maplibre-gl-components 0.22.6 → 0.22.8

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 rO=Object.create;var Vw=Object.defineProperty;var aO=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(!t2(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=ZB(t.name);try{if(KB(n)){if(!this._options.enableAdvancedFormats){this._state.error=`${n2(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 e2(e);if(t==="shapefile"){if(!this._shapefileConverter){this._updateLoading("Loading Shapefile converter...");const{getShapefileConverter:r}=await Promise.resolve().then(()=>require("./ShapefileConverter-Djc69lcP.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-OdEbbaG0.cjs")).then(a=>a.DuckDBConverter_exports);if(this._duckdbConverter=r(),this._options.duckdbBundleUrl){const{DuckDBConverter:a}=await Promise.resolve().then(()=>require("./DuckDBConverter-OdEbbaG0.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")}},j0={fillColor:"#ffff00",fillOpacity:.3,strokeColor:"#ffff00",strokeWidth:3,circleRadius:10,circleStrokeWidth:3},OO={position:"top-right",className:"",visible:!0,enabled:!1,maxFeatures:10,includeLayers:[],excludeLayers:[],highlightStyle:j0,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},UO='<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>',r2=class{_container;_button;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_popup;_highlightSourceId="";_highlightLayerIds=[];_boundClickHandler;constructor(e){this._options={...OO,...e,highlightStyle:{...j0,...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={...j0,...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=UO,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(!t2(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=ZB(t.name);try{if(KB(n)){if(!this._options.enableAdvancedFormats){this._state.error=`${n2(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 e2(e);if(t==="shapefile"){if(!this._shapefileConverter){this._updateLoading("Loading Shapefile converter...");const{getShapefileConverter:r}=await Promise.resolve().then(()=>require("./ShapefileConverter-D2pIfcuN.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-C3OHBGwO.cjs")).then(a=>a.DuckDBConverter_exports);if(this._duckdbConverter=r(),this._options.duckdbBundleUrl){const{DuckDBConverter:a}=await Promise.resolve().then(()=>require("./DuckDBConverter-C3OHBGwO.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")}},j0={fillColor:"#ffff00",fillOpacity:.3,strokeColor:"#ffff00",strokeWidth:3,circleRadius:10,circleStrokeWidth:3},OO={position:"top-right",className:"",visible:!0,enabled:!1,maxFeatures:10,includeLayers:[],excludeLayers:[],highlightStyle:j0,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},UO='<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>',r2=class{_container;_button;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_popup;_highlightSourceId="";_highlightLayerIds=[];_boundClickHandler;constructor(e){this._options={...OO,...e,highlightStyle:{...j0,...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={...j0,...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=UO,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 rO=Object.create;var Vw=Object.defineProperty;var aO=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 o2(e,t){return e&&(Array.isArray(e)?e.map(n=>o2(n,t)):typeof e.clone=="function"?e.clone({opacity:t}):e)}function HO(e,t){return Array.isArray(e)?t(e):e&&Array.isArray(e.renderPipeline)?{...e,renderPipeline:t(e.renderPipeline)}:e}function $O(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 VO(e){const n=new Uint8ClampedArray(1024),i=e.map(s=>({pos:s.position,rgb:$O(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 qO(e){return e?.[0]===1}function cc(e){return typeof e=="number"}function WO(e,t){return Number.isNaN(t)?Number.isNaN(e):e===t}function Xw(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&&!WO(f,n)&&(h=!1)}(c||h)&&(s[o]=0,r=!0)}return r?s:null}function Zw(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 YO(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=VO(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 jO=["none","bone","bwr","cividis","cool","coolwarm","gray","hot","inferno","jet","magma","ocean","plasma","rainbow","RdBu","RdYlBu","RdYlGn","seismic","spectral","terrain","turbo","viridis"],XO={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},ZO='<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>',X0=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={...XO,...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=ZO,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 O of jO){const Q=document.createElement("option");Q.value=O,Q.textContent=O,O===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 O=Number(S.value);this._state.layerOpacity=O/100,R.textContent=`${O}%`,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 U=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||""}),U.appendChild(N),e.appendChild(U);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 O=document.createElement("div");O.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})`,O.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),O.appendChild(W)}e.appendChild(O)}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=>HO(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-H7UXf-4Q.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,U=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=Xw(te,J,cc(K)?K:void 0);if(Zw(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"),O=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:jw,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:U,defaultRenderTile:O})}}}_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:o2(i,Math.max(0,Math.min(1,s)))}}async _createFloatCogLayerProps(e){const{GeoTIFF:t}=await import("@developmentseed/geotiff"),n=await t.fromUrl(e);if(qO(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,U=T.sampleFormat;const N=cc(c)?c:T.nodata;C instanceof Float64Array&&(C=new Float32Array(C),M=Array.from({length:I},()=>32));const D=Xw(C,I,cc(N)?N:void 0);if(Zw(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],U=[3,3,3,3]}const P=i.inferTextureFormat(I,M,U);let O=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=YO(L.mask,D);return H&&(z=b.createTexture({data:H,format:"r8unorm",width:L.width,height:L.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),O+=H.byteLength),{byteLength:O,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:jw,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}},JO={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},KO='<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",eU="maplibre-minimap-viewport-fill",tU="maplibre-minimap-viewport-line",l2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_minimapMap;_handleMove;_handleZoom;_zoomVisible=!0;_isDragging=!1;_dragStartLngLat;_dragCleanup;constructor(e){this._options={...JO,...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=KO,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:eU,type:"fill",source:jf,paint:{"fill-color":this._options.viewportRectColor,"fill-opacity":this._options.viewportRectOpacity}}),this._minimapMap.addLayer({id:tU,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}}},nU={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},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"><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>',eS='<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>',tS='<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>',nS='<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>',iU='<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 sU(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 rU(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 c2=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={...nU,...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=Kw,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 o2(e,t){return e&&(Array.isArray(e)?e.map(n=>o2(n,t)):typeof e.clone=="function"?e.clone({opacity:t}):e)}function HO(e,t){return Array.isArray(e)?t(e):e&&Array.isArray(e.renderPipeline)?{...e,renderPipeline:t(e.renderPipeline)}:e}function $O(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 VO(e){const n=new Uint8ClampedArray(1024),i=e.map(s=>({pos:s.position,rgb:$O(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 qO(e){return e?.[0]===1}function cc(e){return typeof e=="number"}function WO(e,t){return Number.isNaN(t)?Number.isNaN(e):e===t}function Xw(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&&!WO(f,n)&&(h=!1)}(c||h)&&(s[o]=0,r=!0)}return r?s:null}function Zw(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 YO(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=VO(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 jO=["none","bone","bwr","cividis","cool","coolwarm","gray","hot","inferno","jet","magma","ocean","plasma","rainbow","RdBu","RdYlBu","RdYlGn","seismic","spectral","terrain","turbo","viridis"],XO={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},ZO='<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>',X0=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={...XO,...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=ZO,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 O of jO){const Q=document.createElement("option");Q.value=O,Q.textContent=O,O===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 O=Number(S.value);this._state.layerOpacity=O/100,R.textContent=`${O}%`,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 U=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||""}),U.appendChild(N),e.appendChild(U);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 O=document.createElement("div");O.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})`,O.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),O.appendChild(W)}e.appendChild(O)}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=>HO(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-D12xvNnI.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,U=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=Xw(te,J,cc(K)?K:void 0);if(Zw(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"),O=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:jw,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:U,defaultRenderTile:O})}}}_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:o2(i,Math.max(0,Math.min(1,s)))}}async _createFloatCogLayerProps(e){const{GeoTIFF:t}=await import("@developmentseed/geotiff"),n=await t.fromUrl(e);if(qO(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,U=T.sampleFormat;const N=cc(c)?c:T.nodata;C instanceof Float64Array&&(C=new Float32Array(C),M=Array.from({length:I},()=>32));const D=Xw(C,I,cc(N)?N:void 0);if(Zw(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],U=[3,3,3,3]}const P=i.inferTextureFormat(I,M,U);let O=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=YO(L.mask,D);return H&&(z=b.createTexture({data:H,format:"r8unorm",width:L.width,height:L.height,sampler:{magFilter:"nearest",minFilter:"nearest"}}),O+=H.byteLength),{byteLength:O,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:jw,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}},JO={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},KO='<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",eU="maplibre-minimap-viewport-fill",tU="maplibre-minimap-viewport-line",l2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_minimapMap;_handleMove;_handleZoom;_zoomVisible=!0;_isDragging=!1;_dragStartLngLat;_dragCleanup;constructor(e){this._options={...JO,...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=KO,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:eU,type:"fill",source:jf,paint:{"fill-color":this._options.viewportRectColor,"fill-opacity":this._options.viewportRectOpacity}}),this._minimapMap.addLayer({id:tU,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}}},nU={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},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"><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>',eS='<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>',tS='<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>',nS='<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>',iU='<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 sU(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 rU(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 c2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_sourceId;_lineLayerId;_fillLayerId;_resultValueEl;_resultUnitEl;_segmentListEl;_instructionsEl;_measurementsListEl;_boundClickHandler;_boundMoveHandler;_boundDblClickHandler;_boundContextMenuHandler;_boundKeyHandler;_markers=[];constructor(e){this._options={...nU,...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=Kw,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">${nS}</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=`
@@ -128,7 +128,7 @@ var rO=Object.create;var Vw=Object.defineProperty;var aO=Object.getOwnPropertyDe
128
128
  <div class="segment-label">Segments</div>
129
129
  <div class="segment-list"></div>
130
130
  </div>
131
- `,this._resultValueEl=a.querySelector(".result-value"),this._resultUnitEl=a.querySelector(".result-unit"),this._segmentListEl=a.querySelector(".segment-list"),n.appendChild(a),this._instructionsEl=document.createElement("div"),this._instructionsEl.className="measure-instructions",this._instructionsEl.textContent="Click Start, then click the map to add points. Double-click to finish.",n.appendChild(this._instructionsEl),this._measurementsListEl=document.createElement("div"),this._measurementsListEl.className="measurements-list",this._measurementsListEl.style.display="none",n.appendChild(this._measurementsListEl);const o=document.createElement("div");return o.className="measure-actions",o.innerHTML=`
131
+ `,this._resultValueEl=a.querySelector(".result-value"),this._resultUnitEl=a.querySelector(".result-unit"),this._segmentListEl=a.querySelector(".segment-list"),n.appendChild(a),this._instructionsEl=document.createElement("div"),this._instructionsEl.className="measure-instructions",this._instructionsEl.textContent="Click the map to add points. Double-click or right-click to finish.",n.appendChild(this._instructionsEl),this._measurementsListEl=document.createElement("div"),this._measurementsListEl.className="measurements-list",this._measurementsListEl.style.display="none",n.appendChild(this._measurementsListEl);const o=document.createElement("div");return o.className="measure-actions",o.innerHTML=`
132
132
  <button type="button" class="action-btn primary start-btn">
133
133
  ${Kw}
134
134
  <span>Start</span>
@@ -137,7 +137,7 @@ var rO=Object.create;var Vw=Object.defineProperty;var aO=Object.getOwnPropertyDe
137
137
  ${iU}
138
138
  <span>Clear All</span>
139
139
  </button>
140
- `,o.querySelector(".start-btn")?.addEventListener("click",()=>{this._state.isDrawing?this._finishDrawing():this._startDrawing()}),o.querySelector(".clear-btn")?.addEventListener("click",()=>this._clearAll()),n.appendChild(o),e.appendChild(n),e}_updateUnitOptions(e){e.innerHTML="";const t=this._state.mode==="distance"?Xl:th,n=this._state.mode==="distance"?this._state.distanceUnit:this._state.areaUnit;Object.entries(t).forEach(([i,{label:s}])=>{const r=document.createElement("option");r.value=i,r.textContent=s,r.selected=i===n,e.appendChild(r)})}_getCurrentUnitLabel(){return this._state.mode==="distance"?Xl[this._state.distanceUnit].label:th[this._state.areaUnit].label}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._stopDrawing(),this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_setMode(e){if(e===this._state.mode)return;this._stopDrawing(),this._state.mode=e,this._panel?.querySelectorAll(".mode-btn").forEach(i=>{i.classList.toggle("active",i.dataset.mode===e)});const t=this._panel?.querySelector(".measure-unit select");t&&this._updateUnitOptions(t);const n=this._panel?.querySelector(".result-label");n&&(n.textContent=e==="distance"?"Total Distance":"Total Area"),this._emit("modechange")}_setupMapSources(){this._map&&(this._map.addSource(this._sourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this._map.addLayer({id:this._fillLayerId,type:"fill",source:this._sourceId,filter:["==","$type","Polygon"],paint:{"fill-color":this._options.fillColor}}),this._map.addLayer({id:this._lineLayerId,type:"line",source:this._sourceId,paint:{"line-color":this._options.lineColor,"line-width":this._options.lineWidth}}))}_cleanupMapSources(){this._map&&(this._map.getLayer(this._lineLayerId)&&this._map.removeLayer(this._lineLayerId),this._map.getLayer(this._fillLayerId)&&this._map.removeLayer(this._fillLayerId),this._map.getSource(this._sourceId)&&this._map.removeSource(this._sourceId))}_startDrawing(){if(!this._map||this._state.isDrawing)return;this._state.isDrawing=!0,this._state.currentPoints=[],this._state.currentValue=0,this._state.currentSegments=[];const e=this._panel?.querySelector(".start-btn span");e&&(e.textContent="Finish");const t=this._panel?.querySelector(".measure-result");t&&(t.style.display="block"),this._instructionsEl&&(this._instructionsEl.textContent=this._state.mode==="distance"?"Click to add points. Double-click or press Enter to finish.":"Click to add vertices. Double-click or press Enter to close the polygon."),this._boundClickHandler=n=>this._handleClick(n),this._boundMoveHandler=n=>this._handleMouseMove(n),this._boundDblClickHandler=n=>{n.preventDefault(),this._finishDrawing()},this._boundKeyHandler=n=>{n.key==="Enter"?this._finishDrawing():n.key==="Escape"&&this._cancelDrawing()},this._map.on("click",this._boundClickHandler),this._map.on("mousemove",this._boundMoveHandler),this._map.on("dblclick",this._boundDblClickHandler),document.addEventListener("keydown",this._boundKeyHandler),this._map.getCanvas().style.cursor="crosshair",this._emit("drawstart")}_stopDrawing(){if(!this._map)return;this._boundClickHandler&&this._map.off("click",this._boundClickHandler),this._boundMoveHandler&&this._map.off("mousemove",this._boundMoveHandler),this._boundDblClickHandler&&this._map.off("dblclick",this._boundDblClickHandler),this._boundKeyHandler&&document.removeEventListener("keydown",this._boundKeyHandler),this._map.getCanvas().style.cursor="",this._state.isDrawing=!1;const e=this._panel?.querySelector(".start-btn span");e&&(e.textContent="Start")}_handleClick(e){const t={lng:e.lngLat.lng,lat:e.lngLat.lat};this._state.currentPoints.push(t),this._addMarker(t),this._updateMeasurement(),this._updateMapGeometry(),this._emit("drawupdate")}_handleMouseMove(e){if(this._state.currentPoints.length===0)return;const t=[...this._state.currentPoints,{lng:e.lngLat.lng,lat:e.lngLat.lat}];this._updateMapGeometry(t)}_finishDrawing(){if(this._state.currentPoints.length<2){this._cancelDrawing();return}if(this._state.mode==="area"&&this._state.currentPoints.length<3){this._cancelDrawing();return}const e={id:Qa("measurement"),mode:this._state.mode,points:[...this._state.currentPoints],segments:[...this._state.currentSegments]};this._state.mode==="distance"?e.distance=this._state.currentValue:e.area=this._state.currentValue,this._state.measurements.push(e),this._stopDrawing(),this._updateMapGeometry(),this._updateMeasurementsList();const t=this._panel?.querySelector(".clear-btn");t&&(t.disabled=!1),this._emit("drawend",{measurement:e}),this._emit("measurementadd",{measurement:e})}_cancelDrawing(){this._stopDrawing(),this._clearMarkers(),this._state.currentPoints=[],this._state.currentValue=0,this._state.currentSegments=[],this._updateMapGeometry();const e=this._panel?.querySelector(".measure-result");e&&(e.style.display="none"),this._instructionsEl&&(this._instructionsEl.textContent="Click Start, then click the map to add points. Double-click to finish.")}_updateMeasurement(){const e=this._state.currentPoints;if(this._state.mode==="distance"){let t=0;const n=[];for(let i=1;i<e.length;i++){const s=sU(e[i-1],e[i]);n.push(s),t+=s}this._state.currentValue=t,this._state.currentSegments=n}else this._state.currentValue=rU(e);this._updateResult()}_updateResult(){if(!this._resultValueEl||!this._resultUnitEl)return;let e,t;if(this._state.mode==="distance"){const n=Xl[this._state.distanceUnit].factor;e=this._state.currentValue*n,t=Xl[this._state.distanceUnit].label}else{const n=th[this._state.areaUnit].factor;e=this._state.currentValue*n,t=th[this._state.areaUnit].label}if(this._resultValueEl.textContent=e.toFixed(this._options.precision),this._resultUnitEl.textContent=t,this._segmentListEl&&this._state.mode==="distance"&&this._options.showSegments){const n=this._segmentListEl.parentElement;if(this._state.currentSegments.length>0){n.style.display="block";const i=Xl[this._state.distanceUnit].factor;this._segmentListEl.innerHTML=this._state.currentSegments.map((s,r)=>`<span class="segment-item">${r+1}: ${(s*i).toFixed(2)}</span>`).join("")}else n.style.display="none"}}_updateMapGeometry(e){if(!this._map)return;const t=this._map.getSource(this._sourceId);if(!t)return;const n=[];for(const s of this._state.measurements)if(s.mode==="distance")n.push({type:"Feature",properties:{id:s.id,mode:s.mode},geometry:{type:"LineString",coordinates:s.points.map(r=>[r.lng,r.lat])}});else{const r=s.points.map(a=>[a.lng,a.lat]);r.push(r[0]),n.push({type:"Feature",properties:{id:s.id,mode:s.mode},geometry:{type:"Polygon",coordinates:[r]}})}const i=e||this._state.currentPoints;if(i.length>=2)if(this._state.mode==="distance")n.push({type:"Feature",properties:{current:!0},geometry:{type:"LineString",coordinates:i.map(s=>[s.lng,s.lat])}});else if(i.length>=3){const s=i.map(r=>[r.lng,r.lat]);s.push(s[0]),n.push({type:"Feature",properties:{current:!0},geometry:{type:"Polygon",coordinates:[s]}})}else n.push({type:"Feature",properties:{current:!0},geometry:{type:"LineString",coordinates:i.map(s=>[s.lng,s.lat])}});t.setData({type:"FeatureCollection",features:n})}_addMarker(e){if(!this._map)return;const t=window.maplibregl;import("maplibre-gl").then(n=>{const i=n.Marker||t?.Marker;if(!i||!this._map)return;const s=document.createElement("div");s.className="maplibre-gl-measure-vertex",s.style.width=`${this._options.pointRadius*2}px`,s.style.height=`${this._options.pointRadius*2}px`,s.style.borderRadius="50%",s.style.backgroundColor=this._options.pointColor,s.style.border="2px solid white",s.style.boxShadow="0 1px 4px rgba(0,0,0,0.3)",s.style.cursor="pointer";const r=new i({element:s}).setLngLat([e.lng,e.lat]).addTo(this._map);this._markers.push(r)})}_clearMarkers(){this._markers.forEach(e=>e.remove()),this._markers=[]}_updateMeasurementsList(){if(this._measurementsListEl){if(this._state.measurements.length===0){this._measurementsListEl.style.display="none";return}this._measurementsListEl.style.display="block",this._measurementsListEl.innerHTML=this._state.measurements.map(e=>{let t,n;if(e.mode==="distance"){const i=Xl[this._state.distanceUnit].factor;t=`${((e.distance||0)*i).toFixed(2)} ${Xl[this._state.distanceUnit].label}`,n=eS}else{const i=th[this._state.areaUnit].factor;t=`${((e.area||0)*i).toFixed(2)} ${th[this._state.areaUnit].label}`,n=tS}return`
140
+ `,o.querySelector(".start-btn")?.addEventListener("click",()=>{this._state.isDrawing?this._finishDrawing():this._startDrawing()}),o.querySelector(".clear-btn")?.addEventListener("click",()=>this._clearAll()),n.appendChild(o),e.appendChild(n),e}_updateUnitOptions(e){e.innerHTML="";const t=this._state.mode==="distance"?Xl:th,n=this._state.mode==="distance"?this._state.distanceUnit:this._state.areaUnit;Object.entries(t).forEach(([i,{label:s}])=>{const r=document.createElement("option");r.value=i,r.textContent=s,r.selected=i===n,e.appendChild(r)})}_getCurrentUnitLabel(){return this._state.mode==="distance"?Xl[this._state.distanceUnit].label:th[this._state.areaUnit].label}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"),this._state.isDrawing||this._startDrawing()}_hidePanel(){this._stopDrawing(),this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_setMode(e){const t=e!==this._state.mode;this._state.mode=e,this._panel?.querySelectorAll(".mode-btn").forEach(s=>{s.classList.toggle("active",s.dataset.mode===e)});const n=this._panel?.querySelector(".measure-unit select");n&&this._updateUnitOptions(n);const i=this._panel?.querySelector(".result-label");i&&(i.textContent=e==="distance"?"Total Distance":"Total Area"),t&&this._emit("modechange"),this._panel&&(this._state.isDrawing?(this._updateMeasurement(),this._updateMapGeometry()):this._startDrawing())}_setupMapSources(){this._map&&(this._map.addSource(this._sourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this._map.addLayer({id:this._fillLayerId,type:"fill",source:this._sourceId,filter:["==","$type","Polygon"],paint:{"fill-color":this._options.fillColor}}),this._map.addLayer({id:this._lineLayerId,type:"line",source:this._sourceId,paint:{"line-color":this._options.lineColor,"line-width":this._options.lineWidth}}))}_cleanupMapSources(){this._map&&(this._map.getLayer(this._lineLayerId)&&this._map.removeLayer(this._lineLayerId),this._map.getLayer(this._fillLayerId)&&this._map.removeLayer(this._fillLayerId),this._map.getSource(this._sourceId)&&this._map.removeSource(this._sourceId))}_startDrawing(){if(!this._map||this._state.isDrawing)return;this._state.isDrawing=!0,this._state.currentPoints=[],this._state.currentValue=0,this._state.currentSegments=[];const e=this._panel?.querySelector(".start-btn span");e&&(e.textContent="Finish");const t=this._panel?.querySelector(".measure-result");t&&(t.style.display="block"),this._updateResult(),this._instructionsEl&&(this._instructionsEl.textContent=this._state.mode==="distance"?"Click to add points. Double-click, right-click, or Enter to finish.":"Click to add vertices. Double-click, right-click, or Enter to close the polygon."),this._boundClickHandler=n=>this._handleClick(n),this._boundMoveHandler=n=>this._handleMouseMove(n),this._boundDblClickHandler=n=>{n.preventDefault(),this._finishOnDoubleClick()},this._boundContextMenuHandler=n=>{n.preventDefault(),this._finishDrawing()},this._boundKeyHandler=n=>{n.key==="Enter"?this._finishDrawing():n.key==="Escape"&&this._cancelDrawing()},this._map.on("click",this._boundClickHandler),this._map.on("mousemove",this._boundMoveHandler),this._map.on("dblclick",this._boundDblClickHandler),this._map.on("contextmenu",this._boundContextMenuHandler),document.addEventListener("keydown",this._boundKeyHandler),this._map.getCanvas().style.cursor="crosshair",this._emit("drawstart")}_stopDrawing(){if(!this._map)return;this._boundClickHandler&&this._map.off("click",this._boundClickHandler),this._boundMoveHandler&&this._map.off("mousemove",this._boundMoveHandler),this._boundDblClickHandler&&this._map.off("dblclick",this._boundDblClickHandler),this._boundContextMenuHandler&&this._map.off("contextmenu",this._boundContextMenuHandler),this._boundKeyHandler&&document.removeEventListener("keydown",this._boundKeyHandler),this._map.getCanvas().style.cursor="",this._state.isDrawing=!1;const e=this._panel?.querySelector(".start-btn span");e&&(e.textContent="Start")}_handleClick(e){const t={lng:e.lngLat.lng,lat:e.lngLat.lat};this._state.currentPoints.push(t),this._addMarker(t),this._updateMeasurement(),this._updateMapGeometry(),this._emit("drawupdate")}_handleMouseMove(e){if(this._state.currentPoints.length===0)return;const t=[...this._state.currentPoints,{lng:e.lngLat.lng,lat:e.lngLat.lat}];this._updateMapGeometry(t)}_finishDrawing(){const e=this._state.mode==="area"?3:2;if(this._state.currentPoints.length<e)return;const t={id:Qa("measurement"),mode:this._state.mode,points:[...this._state.currentPoints],segments:[...this._state.currentSegments]};this._state.mode==="distance"?t.distance=this._state.currentValue:t.area=this._state.currentValue,this._state.measurements.push(t),this._stopDrawing(),this._updateMapGeometry(),this._updateMeasurementsList();const n=this._panel?.querySelector(".clear-btn");n&&(n.disabled=!1),this._emit("drawend",{measurement:t}),this._emit("measurementadd",{measurement:t}),this._panel&&this._startDrawing()}_finishOnDoubleClick(){const e=this._state.currentPoints;if(this._map&&e.length>=2){const t=e[e.length-1],n=e[e.length-2],i=this._map.project([t.lng,t.lat]),s=this._map.project([n.lng,n.lat]);Math.hypot(i.x-s.x,i.y-s.y)<6&&(e.pop(),this._updateMeasurement())}this._finishDrawing()}_cancelDrawing(){this._stopDrawing(),this._clearMarkers(),this._state.currentPoints=[],this._state.currentValue=0,this._state.currentSegments=[],this._updateMapGeometry();const e=this._panel?.querySelector(".measure-result");e&&(e.style.display="none"),this._instructionsEl&&(this._instructionsEl.textContent="Click the map to add points. Double-click or right-click to finish.")}_updateMeasurement(){const e=this._state.currentPoints;if(this._state.mode==="distance"){let t=0;const n=[];for(let i=1;i<e.length;i++){const s=sU(e[i-1],e[i]);n.push(s),t+=s}this._state.currentValue=t,this._state.currentSegments=n}else this._state.currentValue=rU(e);this._updateResult()}_updateResult(){if(!this._resultValueEl||!this._resultUnitEl)return;let e,t;if(this._state.mode==="distance"){const n=Xl[this._state.distanceUnit].factor;e=this._state.currentValue*n,t=Xl[this._state.distanceUnit].label}else{const n=th[this._state.areaUnit].factor;e=this._state.currentValue*n,t=th[this._state.areaUnit].label}if(this._resultValueEl.textContent=e.toFixed(this._options.precision),this._resultUnitEl.textContent=t,this._segmentListEl&&this._state.mode==="distance"&&this._options.showSegments){const n=this._segmentListEl.parentElement;if(this._state.currentSegments.length>0){n.style.display="block";const i=Xl[this._state.distanceUnit].factor;this._segmentListEl.innerHTML=this._state.currentSegments.map((s,r)=>`<span class="segment-item">${r+1}: ${(s*i).toFixed(2)}</span>`).join("")}else n.style.display="none"}}_updateMapGeometry(e){if(!this._map)return;const t=this._map.getSource(this._sourceId);if(!t)return;const n=[];for(const s of this._state.measurements)if(s.mode==="distance")n.push({type:"Feature",properties:{id:s.id,mode:s.mode},geometry:{type:"LineString",coordinates:s.points.map(r=>[r.lng,r.lat])}});else{const r=s.points.map(a=>[a.lng,a.lat]);r.push(r[0]),n.push({type:"Feature",properties:{id:s.id,mode:s.mode},geometry:{type:"Polygon",coordinates:[r]}})}const i=e||this._state.currentPoints;if(i.length>=2)if(this._state.mode==="distance")n.push({type:"Feature",properties:{current:!0},geometry:{type:"LineString",coordinates:i.map(s=>[s.lng,s.lat])}});else if(i.length>=3){const s=i.map(r=>[r.lng,r.lat]);s.push(s[0]),n.push({type:"Feature",properties:{current:!0},geometry:{type:"Polygon",coordinates:[s]}})}else n.push({type:"Feature",properties:{current:!0},geometry:{type:"LineString",coordinates:i.map(s=>[s.lng,s.lat])}});t.setData({type:"FeatureCollection",features:n})}_addMarker(e){if(!this._map)return;const t=window.maplibregl;import("maplibre-gl").then(n=>{const i=n.Marker||t?.Marker;if(!i||!this._map)return;const s=document.createElement("div");s.className="maplibre-gl-measure-vertex",s.style.width=`${this._options.pointRadius*2}px`,s.style.height=`${this._options.pointRadius*2}px`,s.style.borderRadius="50%",s.style.backgroundColor=this._options.pointColor,s.style.border="2px solid white",s.style.boxShadow="0 1px 4px rgba(0,0,0,0.3)",s.style.cursor="pointer";const r=new i({element:s}).setLngLat([e.lng,e.lat]).addTo(this._map);this._markers.push(r)})}_clearMarkers(){this._markers.forEach(e=>e.remove()),this._markers=[]}_updateMeasurementsList(){if(this._measurementsListEl){if(this._state.measurements.length===0){this._measurementsListEl.style.display="none";return}this._measurementsListEl.style.display="block",this._measurementsListEl.innerHTML=this._state.measurements.map(e=>{let t,n;if(e.mode==="distance"){const i=Xl[this._state.distanceUnit].factor;t=`${((e.distance||0)*i).toFixed(2)} ${Xl[this._state.distanceUnit].label}`,n=eS}else{const i=th[this._state.areaUnit].factor;t=`${((e.area||0)*i).toFixed(2)} ${th[this._state.areaUnit].label}`,n=tS}return`
141
141
  <div class="measurement-item" data-id="${e.id}">
142
142
  <div class="measurement-info">
143
143
  <span class="measurement-icon">${n}</span>
@@ -230,7 +230,7 @@ var rO=Object.create;var Vw=Object.defineProperty;var aO=Object.getOwnPropertyDe
230
230
  </div>
231
231
  <div><strong>Date:</strong> ${this._state.stacItem.properties?.datetime||"N/A"}</div>
232
232
  <div><strong>Assets:</strong> ${this._state.assets.length} available</div>
233
- `,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-H7UXf-4Q.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:U,pool:N,device:D}=M,P=I.getWidth(),O=I.getHeight();let Q=v[0],z=b[0];for(const fe of v)if(fe.getWidth()===P&&fe.getHeight()===O){Q=fe;break}for(const fe of b)if(fe.getWidth()===P&&fe.getHeight()===O){z=fe;break}const H={window:U,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,U,N]=this._state.stacItem.bbox;this._map.fitBounds([[I,M],[U,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:f2(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-H7UXf-4Q.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,U=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=U-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=PU(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,O=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:kU,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=NU(nr(W));O=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:O}})}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}}},UU=[{name:"Element84 Earth Search",url:"https://earth-search.aws.element84.com/v1"},{name:"Microsoft Planetary Computer",url:"https://planetarycomputer.microsoft.com/api/stac/v1"}],zU=["viridis","plasma","inferno","magma","cividis","coolwarm","bwr","seismic","RdBu","RdYlBu","RdYlGn","spectral","jet","rainbow","turbo","terrain","ocean","hot","cool","gray","bone"],QU={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:UU,maxItems:20,defaultRescaleMin:0,defaultRescaleMax:1e4,defaultColormap:"viridis",defaultRgbMode:!0,showFootprints:!0,minzoom:0,maxzoom:24},GU=`<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">
233
+ `,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-D12xvNnI.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:U,pool:N,device:D}=M,P=I.getWidth(),O=I.getHeight();let Q=v[0],z=b[0];for(const fe of v)if(fe.getWidth()===P&&fe.getHeight()===O){Q=fe;break}for(const fe of b)if(fe.getWidth()===P&&fe.getHeight()===O){z=fe;break}const H={window:U,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,U,N]=this._state.stacItem.bbox;this._map.fitBounds([[I,M],[U,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:f2(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-D12xvNnI.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,U=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=U-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=PU(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,O=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:kU,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=NU(nr(W));O=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:O}})}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}}},UU=[{name:"Element84 Earth Search",url:"https://earth-search.aws.element84.com/v1"},{name:"Microsoft Planetary Computer",url:"https://planetarycomputer.microsoft.com/api/stac/v1"}],zU=["viridis","plasma","inferno","magma","cividis","coolwarm","bwr","seismic","RdBu","RdYlBu","RdYlGn","spectral","jet","rainbow","turbo","terrain","ocean","hot","cool","gray","bone"],QU={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:UU,maxItems:20,defaultRescaleMin:0,defaultRescaleMax:1e4,defaultColormap:"viridis",defaultRgbMode:!0,showFootprints:!0,minzoom:0,maxzoom:24},GU=`<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">
234
234
  <circle cx="11" cy="11" r="8"/>
235
235
  <path d="m21 21-4.3-4.3"/>
236
236
  <path d="M11 8v6"/>
@@ -243,7 +243,7 @@ var rO=Object.create;var Vw=Object.defineProperty;var aO=Object.getOwnPropertyDe
243
243
  {
244
244
  "type": "FeatureCollection",
245
245
  "features": [...]
246
- }`,P.value=this._state.geojsonText,P.rows=6,P.addEventListener("input",()=>{this._state.geojsonText=P.value}),D.appendChild(P);const O=document.createElement("div");O.className="maplibre-gl-add-vector-format-hint",O.textContent="Paste a valid GeoJSON FeatureCollection, Feature, or Geometry",D.appendChild(O),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 O of P.layerIds)this._setLayerOpacityDirect(O,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 U=document.createElement("div");U.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()),U.appendChild(N),e.appendChild(U),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[O,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 ${VU(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(O),this._render()}),z.appendChild(J),D.appendChild(z)}e.appendChild(D)}IE({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=yv(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-OdEbbaG0.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-OdEbbaG0.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=FB(()=>{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-OdEbbaG0.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-OdEbbaG0.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-OdEbbaG0.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")}}},qU=`<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">
246
+ }`,P.value=this._state.geojsonText,P.rows=6,P.addEventListener("input",()=>{this._state.geojsonText=P.value}),D.appendChild(P);const O=document.createElement("div");O.className="maplibre-gl-add-vector-format-hint",O.textContent="Paste a valid GeoJSON FeatureCollection, Feature, or Geometry",D.appendChild(O),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 O of P.layerIds)this._setLayerOpacityDirect(O,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 U=document.createElement("div");U.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()),U.appendChild(N),e.appendChild(U),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[O,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 ${VU(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(O),this._render()}),z.appendChild(J),D.appendChild(z)}e.appendChild(D)}IE({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=yv(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-C3OHBGwO.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-C3OHBGwO.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=FB(()=>{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-C3OHBGwO.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-C3OHBGwO.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-C3OHBGwO.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")}}},qU=`<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">
247
247
  <path d="M3 3h7v7H3z" fill="#4292c6" fill-opacity="0.7" stroke="#2171b5"/>
248
248
  <path d="M10 3h7v7h-7z" fill="#9ecae1" fill-opacity="0.7" stroke="#6baed6"/>
249
249
  <path d="M17 3h4v7h-4z" fill="#08519c" fill-opacity="0.7" stroke="#08306b"/>
@@ -253,26 +253,26 @@ var rO=Object.create;var Vw=Object.defineProperty;var aO=Object.getOwnPropertyDe
253
253
  <path d="M3 17h7v4H3z" fill="#2171b5" fill-opacity="0.7" stroke="#08519c"/>
254
254
  <path d="M10 17h7v4h-7z" fill="#08306b" fill-opacity="0.7" stroke="#08306b"/>
255
255
  <path d="M17 17h4v4h-4z" fill="#4292c6" fill-opacity="0.7" stroke="#2171b5"/>
256
- </svg>`,WU=[{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"}],YU={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 jU(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 XU(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=ZU(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 ZU(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(UB(n,r))}return i}var _2=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={...YU,...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=qU,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 WU){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 U=document.createElement("span");U.className="maplibre-gl-choropleth-slider-value",U.textContent=`${Math.round(this._state.opacity*100)}%`,M.addEventListener("input",()=>{const q=Number(M.value);this._state.opacity=q/100,U.textContent=`${q}%`}),I.appendChild(M),I.appendChild(U),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 O=document.createElement("span");O.textContent="Show Outline",D.appendChild(O),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=jU(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}=XU(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 O=0;O<h.length;O++){const Q=Math.min(O,m.length-1);N.push(h[O],m[Q]),D.push(h[O],h[O]/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 O=P.features[0].properties||{},Q=Object.entries(O).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 U={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,U),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-OdEbbaG0.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 lE({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")}}},KU={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},ez='<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>',tz='<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>',A2=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={...KU,...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=ez,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=`
256
+ </svg>`,WU=[{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"}],YU={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 jU(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 XU(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=ZU(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 ZU(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(UB(n,r))}return i}var _2=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={...YU,...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=qU,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 WU){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 U=document.createElement("span");U.className="maplibre-gl-choropleth-slider-value",U.textContent=`${Math.round(this._state.opacity*100)}%`,M.addEventListener("input",()=>{const q=Number(M.value);this._state.opacity=q/100,U.textContent=`${q}%`}),I.appendChild(M),I.appendChild(U),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 O=document.createElement("span");O.textContent="Show Outline",D.appendChild(O),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=jU(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}=XU(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 O=0;O<h.length;O++){const Q=Math.min(O,m.length-1);N.push(h[O],m[Q]),D.push(h[O],h[O]/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 O=P.features[0].properties||{},Q=Object.entries(O).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 U={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,U),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-C3OHBGwO.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 lE({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")}}},KU={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},ez='<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>',tz='<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>',A2=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={...KU,...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=ez,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=`
257
257
  <span>Colorbar</span>
258
258
  <button type="button" class="colorbar-gui-close" title="Close">${tz}</button>
259
259
  `,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
260
260
  or #440154, #21918c, #fde725`,this._customColorsTextarea.addEventListener("input",()=>{this._state.customColors=this._customColorsTextarea.value,this._updatePreview()}),c.appendChild(this._customColorsTextarea),this._customSection.appendChild(c),n.appendChild(this._customSection),this._namedSection.style.display=this._state.mode==="named"?"":"none",this._customSection.style.display=this._state.mode==="custom"?"":"none",this._previewEl=document.createElement("div"),this._previewEl.className="colorbar-gui-preview",n.appendChild(this._previewEl),this._updatePreview();const h=document.createElement("div");h.className="colorbar-gui-row";const d=this._createField("Min Value");this._vminInput=document.createElement("input"),this._vminInput.type="number",this._vminInput.className="colorbar-gui-input",this._vminInput.value=String(this._state.vmin),this._vminInput.addEventListener("input",()=>{this._state.vmin=parseFloat(this._vminInput.value)||0}),d.appendChild(this._vminInput),h.appendChild(d);const f=this._createField("Max Value");this._vmaxInput=document.createElement("input"),this._vmaxInput.type="number",this._vmaxInput.className="colorbar-gui-input",this._vmaxInput.value=String(this._state.vmax),this._vmaxInput.addEventListener("input",()=>{this._state.vmax=parseFloat(this._vmaxInput.value)||1}),f.appendChild(this._vmaxInput),h.appendChild(f),n.appendChild(h);const m=this._createField("Label");this._labelInput=document.createElement("input"),this._labelInput.type="text",this._labelInput.className="colorbar-gui-input",this._labelInput.placeholder="e.g., Temperature",this._labelInput.value=this._state.label,this._labelInput.addEventListener("input",()=>{this._state.label=this._labelInput.value}),m.appendChild(this._labelInput),n.appendChild(m);const A=this._createField("Units");this._unitsInput=document.createElement("input"),this._unitsInput.type="text",this._unitsInput.className="colorbar-gui-input",this._unitsInput.placeholder="e.g., °C",this._unitsInput.value=this._state.units,this._unitsInput.addEventListener("input",()=>{this._state.units=this._unitsInput.value}),A.appendChild(this._unitsInput),n.appendChild(A);const y=document.createElement("div");y.className="colorbar-gui-row";const x=this._createField("Orientation");this._orientationSelect=document.createElement("select"),this._orientationSelect.className="colorbar-gui-select",["horizontal","vertical"].forEach(w=>{const S=document.createElement("option");S.value=w,S.textContent=w.charAt(0).toUpperCase()+w.slice(1),S.selected=w===this._state.orientation,this._orientationSelect.appendChild(S)}),this._orientationSelect.addEventListener("change",()=>{this._state.orientation=this._orientationSelect.value}),x.appendChild(this._orientationSelect),y.appendChild(x);const v=this._createField("Position");this._positionSelect=document.createElement("select"),this._positionSelect.className="colorbar-gui-select",[{value:"top-left",label:"Top Left"},{value:"top-right",label:"Top Right"},{value:"bottom-left",label:"Bottom Left"},{value:"bottom-right",label:"Bottom Right"}].forEach(w=>{const S=document.createElement("option");S.value=w.value,S.textContent=w.label,S.selected=w.value===this._state.colorbarPosition,this._positionSelect.appendChild(S)}),this._positionSelect.addEventListener("change",()=>{this._state.colorbarPosition=this._positionSelect.value}),v.appendChild(this._positionSelect),y.appendChild(v),n.appendChild(y),this._addBtn=document.createElement("button"),this._addBtn.type="button",this._addBtn.className="colorbar-gui-add-btn",this._addBtn.textContent="Add Colorbar",this._addBtn.addEventListener("click",()=>this._addColorbar()),n.appendChild(this._addBtn);const b=document.createElement("button");return b.type="button",b.className="colorbar-gui-add-btn",b.textContent="Update Selected Colorbar",b.style.display=this._state.hasColorbar?"":"none",b.addEventListener("click",()=>this._updateColorbar()),n.appendChild(b),this._updateBtn=b,this._removeBtn=document.createElement("button"),this._removeBtn.type="button",this._removeBtn.className="colorbar-gui-remove-btn",this._removeBtn.textContent="Remove Colorbar",this._removeBtn.style.display=this._state.hasColorbar?"":"none",this._removeBtn.addEventListener("click",()=>this._removeColorbar()),n.appendChild(this._removeBtn),e.appendChild(n),e}_createField(e){const t=document.createElement("div");t.className="colorbar-gui-field";const n=document.createElement("label");return n.textContent=e,t.appendChild(n),t}_setMode(e){this._state.mode=e,this._namedSection&&(this._namedSection.style.display=e==="named"?"":"none"),this._customSection&&(this._customSection.style.display=e==="custom"?"":"none"),this._updatePreview()}_parseCustomColors(){return this._state.customColors.split(/[,\n]+/).map(e=>e.trim()).filter(e=>e.length>0)}_updatePreview(){if(this._previewEl)if(this._state.mode==="custom"){const e=this._parseCustomColors();if(e.length===0){this._previewEl.style.background="#e5e7eb";return}if(e.length===1){this._previewEl.style.background=e[0];return}const t=100/(e.length-1),n=e.map((i,s)=>`${i} ${(s*t).toFixed(1)}%`).join(", ");this._previewEl.style.background=`linear-gradient(to right, ${n})`}else{const e=this._state.colormap,t=nr(e).map(n=>`${n.color} ${n.position*100}%`).join(", ");this._previewEl.style.background=`linear-gradient(to right, ${t})`}}_getFormEntry(){return{mode:this._state.mode,colormap:this._state.colormap,customColors:this._state.customColors,vmin:this._state.vmin,vmax:this._state.vmax,label:this._state.label,units:this._state.units,orientation:this._state.orientation,colorbarPosition:this._state.colorbarPosition}}_applyEntryToForm(e){this._state.mode=e.mode,this._state.colormap=e.colormap,this._state.customColors=e.customColors,this._state.vmin=e.vmin,this._state.vmax=e.vmax,this._state.label=e.label,this._state.units=e.units,this._state.orientation=e.orientation,this._state.colorbarPosition=e.colorbarPosition,this._modeNamedRadio&&(this._modeNamedRadio.checked=e.mode==="named"),this._modeCustomRadio&&(this._modeCustomRadio.checked=e.mode==="custom"),this._namedSection&&(this._namedSection.style.display=e.mode==="named"?"":"none"),this._customSection&&(this._customSection.style.display=e.mode==="custom"?"":"none"),this._colormapSelect&&(this._colormapSelect.value=e.colormap),this._customColorsTextarea&&(this._customColorsTextarea.value=e.customColors),this._vminInput&&(this._vminInput.value=String(e.vmin)),this._vmaxInput&&(this._vmaxInput.value=String(e.vmax)),this._labelInput&&(this._labelInput.value=e.label),this._unitsInput&&(this._unitsInput.value=e.units),this._orientationSelect&&(this._orientationSelect.value=e.orientation),this._positionSelect&&(this._positionSelect.value=e.colorbarPosition),this._updatePreview()}_createColorbar(e){const t=e.mode==="custom"?e.customColors.split(/[,\n]+/).map(n=>n.trim()).filter(n=>n.length>0):e.colormap;return new HB({colormap:Array.isArray(t)&&t.length===0?["#440154","#21918c","#fde725"]:t,vmin:e.vmin,vmax:e.vmax,label:e.label,units:e.units,orientation:e.orientation,position:e.colorbarPosition})}_selectColorbar(e){if(e<0){this._state.selectedColorbarIndex=-1,this._colorbar=void 0,this._updateButtonStates();return}e>=this._colorbarEntries.length||(this._state.selectedColorbarIndex=e,this._colorbar=this._colorbars[e],this._applyEntryToForm(this._colorbarEntries[e]),this._updateButtonStates())}_renderColorbarSelect(){if(!this._colorbarSelect)return;this._colorbarSelect.innerHTML="";const e=document.createElement("option");e.value="-1",e.textContent="New colorbar",this._colorbarSelect.appendChild(e),this._colorbarEntries.forEach((t,n)=>{const i=document.createElement("option");i.value=String(n),i.textContent=t.label||`Colorbar ${n+1}`,this._colorbarSelect.appendChild(i)}),this._colorbarSelect.value=this._state.selectedColorbarIndex>=0?String(this._state.selectedColorbarIndex):"-1"}_addColorbar(){if(!this._map)return;const e=this._getFormEntry(),t=this._createColorbar(e);this._map.addControl(t,e.colorbarPosition),this._colorbars.push(t),this._colorbarEntries.push(e),this._colorbar=t,this._state.hasColorbar=!0,this._state.selectedColorbarIndex=this._colorbars.length-1,this._state.colorbars=this._colorbarEntries.map(n=>({...n})),this._updateButtonStates(),this._emit("colorbaradd")}_updateColorbar(){if(!this._map)return;const e=this._state.selectedColorbarIndex;if(e<0||e>=this._colorbars.length){this._addColorbar();return}const t=this._getFormEntry();this._map.removeControl(this._colorbars[e]);const n=this._createColorbar(t);this._map.addControl(n,t.colorbarPosition),this._colorbars[e]=n,this._colorbarEntries[e]=t,this._colorbar=n,this._state.colorbars=this._colorbarEntries.map(i=>({...i})),this._emit("colorbarupdate"),this._updateButtonStates()}_removeColorbar(){if(!this._map)return;const e=this._state.selectedColorbarIndex;e<0||e>=this._colorbars.length||(this._map.removeControl(this._colorbars[e]),this._colorbars.splice(e,1),this._colorbarEntries.splice(e,1),this._state.hasColorbar=this._colorbars.length>0,this._state.selectedColorbarIndex=this._state.hasColorbar?Math.min(e,this._colorbars.length-1):-1,this._colorbar=this._state.selectedColorbarIndex>=0?this._colorbars[this._state.selectedColorbarIndex]:void 0,this._state.colorbars=this._colorbarEntries.map(t=>({...t})),this._state.selectedColorbarIndex>=0&&this._applyEntryToForm(this._colorbarEntries[this._state.selectedColorbarIndex]),this._updateButtonStates(),this._emit("colorbarremove"))}_removeAllColorbars(){this._map&&(this._colorbars.forEach(e=>{this._map.removeControl(e)}),this._colorbars=[],this._colorbarEntries=[],this._colorbar=void 0,this._state.hasColorbar=!1,this._state.selectedColorbarIndex=-1,this._state.colorbars=[],this._updateButtonStates())}_updateButtonStates(){this._addBtn&&(this._addBtn.textContent="Add Colorbar");const e=this._state.selectedColorbarIndex>=0;this._updateBtn&&(this._updateBtn.style.display=e?"":"none"),this._removeBtn&&(this._removeBtn.style.display=e?"":"none"),this._renderColorbarSelect()}_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"),this._updatePanelHeight(),this._handleResize||(this._handleResize=()=>this._updatePanelHeight(),window.addEventListener("resize",this._handleResize))}_hidePanel(){this._handleResize&&(window.removeEventListener("resize",this._handleResize),this._handleResize=void 0),this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_updatePanelHeight(){if(!this._panel)return;const e=16,t=200,n=this._panel.getBoundingClientRect().top,i=Math.max(t,window.innerHeight-n-e),s=this._options.maxHeight>0?Math.min(this._options.maxHeight,i):i;this._panel.style.maxHeight=`${s}px`}_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())}getColorbar(){return this._colorbar}},nz={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},iz='<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="5" height="5" rx="1" fill="#555" stroke="#555"/><line x1="12" y1="5.5" x2="21" y2="5.5"/><rect x="3" y="10" width="5" height="5" rx="1" fill="#999" stroke="#999"/><line x1="12" y1="12.5" x2="21" y2="12.5"/><rect x="3" y="17" width="5" height="5" rx="1" fill="#ccc" stroke="#ccc"/><line x1="12" y1="19.5" x2="21" y2="19.5"/></svg>',sz='<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>',rz='<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="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>',az='<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>',v2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_handleResize;_zoomVisible=!0;_legend;_legends=[];_legendEntries=[];_legendSelect;_titleInput;_positionSelect;_itemsContainer;_dictTextarea;_dictErrorEl;_addBtn;_updateBtn;_removeBtn;constructor(e){this._options={...nz,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,title:"Legend",items:[{label:"Category A",color:"#ff6b6b",shape:"square"},{label:"Category B",color:"#4ecdc4",shape:"square"},{label:"Category C",color:"#95a5a6",shape:"square"}],legendPosition:"bottom-left",hasLegend:!1,selectedLegendIndex:-1,legends:[]}}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._removeAllLegends(),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,items:[...this._state.items]}};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,items:[...this._state.items],legends:this._legendEntries.map(e=>({...e,items:[...e.items]}))}}setState(e){this._map&&this._legends.forEach(s=>{this._map.removeControl(s)});const t=(e.legends??[]).map(s=>({...s,items:s.items.map(r=>({...r}))}));this._legends=[],this._legendEntries=t,this._map&&t.forEach(s=>{const r=this._createLegend(s);this._map.addControl(r,s.legendPosition),this._legends.push(r)});const n=typeof e.selectedLegendIndex=="number"&&e.selectedLegendIndex>=0&&e.selectedLegendIndex<t.length?e.selectedLegendIndex:t.length>0?t.length-1:-1,i=n>=0?t[n]:{title:e.title??this._state.title,items:(e.items??this._state.items).map(s=>({...s})),legendPosition:e.legendPosition??this._state.legendPosition};return this._state={...this._state,...i,items:i.items.map(s=>({...s})),visible:e.visible??this._state.visible,collapsed:e.collapsed??this._state.collapsed,hasLegend:t.length>0,selectedLegendIndex:n,legends:t.map(s=>({...s,items:s.items.map(r=>({...r}))}))},this._legend=n>=0?this._legends[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("legendupdate"),this}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-legend-gui-control ${this._options.className}`,this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="legend-gui-button",this._button.title="Legend",this._button.innerHTML=iz,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`legend-gui-panel ${this._options.position.includes("left")?"right":"left"}`,e.style.minWidth=`${this._options.panelWidth}px`,e.style.width="auto",e.style.maxWidth="400px",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="legend-gui-header",t.innerHTML=`
261
261
  <span>Legend</span>
262
262
  <button type="button" class="legend-gui-close" title="Close">${sz}</button>
263
- `,t.querySelector(".legend-gui-close")?.addEventListener("click",()=>this._togglePanel()),e.appendChild(t);const n=document.createElement("div");n.className="legend-gui-content";const i=this._createField("Legend");this._legendSelect=document.createElement("select"),this._legendSelect.className="legend-gui-select",this._legendSelect.addEventListener("change",()=>{this._selectLegend(parseInt(this._legendSelect.value,10))}),i.appendChild(this._legendSelect),n.appendChild(i),this._renderLegendSelect();const s=this._createField("Title");this._titleInput=document.createElement("input"),this._titleInput.type="text",this._titleInput.className="legend-gui-input",this._titleInput.placeholder="Legend title",this._titleInput.value=this._state.title,this._titleInput.addEventListener("input",()=>{this._state.title=this._titleInput.value}),s.appendChild(this._titleInput),n.appendChild(s);const r=this._createField("Position");this._positionSelect=document.createElement("select"),this._positionSelect.className="legend-gui-select",[{value:"top-left",label:"Top Left"},{value:"top-right",label:"Top Right"},{value:"bottom-left",label:"Bottom Left"},{value:"bottom-right",label:"Bottom Right"}].forEach(f=>{const m=document.createElement("option");m.value=f.value,m.textContent=f.label,m.selected=f.value===this._state.legendPosition,this._positionSelect.appendChild(m)}),this._positionSelect.addEventListener("change",()=>{this._state.legendPosition=this._positionSelect.value}),r.appendChild(this._positionSelect),n.appendChild(r);const a=document.createElement("div");a.className="legend-gui-field";const o=document.createElement("div");o.className="legend-gui-items-header";const l=document.createElement("label");l.textContent="Items";const c=document.createElement("button");c.type="button",c.className="legend-gui-add-item-btn",c.innerHTML=rz,c.title="Add item",c.addEventListener("click",()=>this._addItem()),o.appendChild(l),o.appendChild(c),a.appendChild(o),n.appendChild(a),this._itemsContainer=document.createElement("div"),this._itemsContainer.className="legend-gui-items",this._renderItems(),n.appendChild(this._itemsContainer);const h=this._createField("Import from Dictionary");this._dictTextarea=document.createElement("textarea"),this._dictTextarea.className="legend-gui-textarea",this._dictTextarea.rows=4,this._dictTextarea.placeholder='{"Label A": "#ff6b6b", "Label B": "#4ecdc4"}',h.appendChild(this._dictTextarea);const d=document.createElement("button");return d.type="button",d.className="legend-gui-import-btn",d.textContent="Import Items from Dictionary",d.addEventListener("click",()=>this._importFromDict()),h.appendChild(d),this._dictErrorEl=document.createElement("div"),this._dictErrorEl.className="legend-gui-import-error",this._dictErrorEl.style.display="none",h.appendChild(this._dictErrorEl),n.appendChild(h),this._addBtn=document.createElement("button"),this._addBtn.type="button",this._addBtn.className="legend-gui-add-btn",this._addBtn.textContent="Add Legend",this._addBtn.addEventListener("click",()=>this._addLegend()),n.appendChild(this._addBtn),this._updateBtn=document.createElement("button"),this._updateBtn.type="button",this._updateBtn.className="legend-gui-add-btn",this._updateBtn.textContent="Update Selected Legend",this._updateBtn.style.display=this._state.hasLegend?"":"none",this._updateBtn.addEventListener("click",()=>this._updateLegend()),n.appendChild(this._updateBtn),this._removeBtn=document.createElement("button"),this._removeBtn.type="button",this._removeBtn.className="legend-gui-remove-btn",this._removeBtn.textContent="Remove Legend",this._removeBtn.style.display=this._state.hasLegend?"":"none",this._removeBtn.addEventListener("click",()=>this._removeLegend()),n.appendChild(this._removeBtn),e.appendChild(n),e}_createField(e){const t=document.createElement("div");t.className="legend-gui-field";const n=document.createElement("label");return n.textContent=e,t.appendChild(n),t}_renderItems(){this._itemsContainer&&(this._itemsContainer.innerHTML="",this._state.items.forEach((e,t)=>{const n=document.createElement("div");n.className="legend-gui-item-row";const i=document.createElement("input");i.type="color",i.className="legend-gui-color-input",i.value=e.color,i.addEventListener("input",()=>{this._state.items[t].color=i.value});const s=document.createElement("input");s.type="text",s.className="legend-gui-input legend-gui-item-label",s.value=e.label,s.placeholder="Label",s.addEventListener("input",()=>{this._state.items[t].label=s.value});const r=document.createElement("select");r.className="legend-gui-select legend-gui-item-shape",["square","circle","line"].forEach(o=>{const l=document.createElement("option");l.value=o,l.textContent=o,l.selected=o===(e.shape||"square"),r.appendChild(l)}),r.addEventListener("change",()=>{this._state.items[t].shape=r.value});const a=document.createElement("button");a.type="button",a.className="legend-gui-delete-item-btn",a.innerHTML=az,a.title="Remove item",a.addEventListener("click",()=>{this._state.items.splice(t,1),this._renderItems()}),n.appendChild(i),n.appendChild(s),n.appendChild(r),n.appendChild(a),this._itemsContainer.appendChild(n)}))}_addItem(){const e=["#ff6b6b","#4ecdc4","#95a5a6","#f39c12","#9b59b6","#3498db","#2ecc71","#e74c3c"],t=e[this._state.items.length%e.length];this._state.items.push({label:`Item ${this._state.items.length+1}`,color:t,shape:"square"}),this._renderItems()}_importFromDict(){if(!this._dictTextarea||!this._dictErrorEl)return;const e=this._dictTextarea.value.trim();if(!e){this._dictErrorEl.textContent="Please paste a JSON dictionary.",this._dictErrorEl.style.display="";return}try{const t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new Error('Expected a JSON object like {"label": "color"}');const n=Object.entries(t);if(n.length===0)throw new Error("Dictionary is empty.");const i=[];for(const[s,r]of n){if(typeof r!="string")throw new Error(`Value for "${s}" must be a color string.`);i.push({label:s,color:r,shape:"square"})}this._state.items=i,this._renderItems(),this._dictErrorEl.style.display="none",this._dictTextarea.value=""}catch(t){const n=t instanceof Error?t.message:"Invalid JSON";this._dictErrorEl.textContent=n,this._dictErrorEl.style.display=""}}_getFormEntry(){return{title:this._state.title,items:this._state.items.map(e=>({...e})),legendPosition:this._state.legendPosition}}_applyEntryToForm(e){this._state.title=e.title,this._state.items=e.items.map(t=>({...t})),this._state.legendPosition=e.legendPosition,this._titleInput&&(this._titleInput.value=e.title),this._positionSelect&&(this._positionSelect.value=e.legendPosition),this._renderItems()}_createLegend(e){return new lE({title:e.title,items:e.items.map(t=>({...t})),collapsible:!0,collapsed:!1})}_selectLegend(e){if(e<0){this._state.selectedLegendIndex=-1,this._legend=void 0,this._updateButtonStates();return}e>=this._legendEntries.length||(this._state.selectedLegendIndex=e,this._legend=this._legends[e],this._applyEntryToForm(this._legendEntries[e]),this._updateButtonStates())}_renderLegendSelect(){if(!this._legendSelect)return;this._legendSelect.innerHTML="";const e=document.createElement("option");e.value="-1",e.textContent="New legend",this._legendSelect.appendChild(e),this._legendEntries.forEach((t,n)=>{const i=document.createElement("option");i.value=String(n),i.textContent=t.title||`Legend ${n+1}`,this._legendSelect.appendChild(i)}),this._legendSelect.value=this._state.selectedLegendIndex>=0?String(this._state.selectedLegendIndex):"-1"}_addLegend(){if(!this._map)return;const e=this._getFormEntry(),t=this._createLegend(e);this._map.addControl(t,e.legendPosition),this._legends.push(t),this._legendEntries.push(e),this._legend=t,this._state.hasLegend=!0,this._state.selectedLegendIndex=this._legends.length-1,this._state.legends=this._legendEntries.map(n=>({...n,items:[...n.items]})),this._updateButtonStates(),this._emit("legendadd")}_updateLegend(){if(!this._map)return;const e=this._state.selectedLegendIndex;if(e<0||e>=this._legends.length){this._addLegend();return}const t=this._getFormEntry();this._map.removeControl(this._legends[e]);const n=this._createLegend(t);this._map.addControl(n,t.legendPosition),this._legends[e]=n,this._legendEntries[e]=t,this._legend=n,this._state.legends=this._legendEntries.map(i=>({...i,items:[...i.items]})),this._emit("legendupdate"),this._updateButtonStates()}_removeLegend(){if(!this._map)return;const e=this._state.selectedLegendIndex;e<0||e>=this._legends.length||(this._map.removeControl(this._legends[e]),this._legends.splice(e,1),this._legendEntries.splice(e,1),this._state.hasLegend=this._legends.length>0,this._state.selectedLegendIndex=this._state.hasLegend?Math.min(e,this._legends.length-1):-1,this._legend=this._state.selectedLegendIndex>=0?this._legends[this._state.selectedLegendIndex]:void 0,this._state.legends=this._legendEntries.map(t=>({...t,items:[...t.items]})),this._state.selectedLegendIndex>=0&&this._applyEntryToForm(this._legendEntries[this._state.selectedLegendIndex]),this._updateButtonStates(),this._emit("legendremove"))}_updateButtonStates(){this._addBtn&&(this._addBtn.textContent="Add Legend");const e=this._state.selectedLegendIndex>=0;this._updateBtn&&(this._updateBtn.style.display=e?"":"none"),this._removeBtn&&(this._removeBtn.style.display=e?"":"none"),this._renderLegendSelect()}_removeAllLegends(){this._map&&(this._legends.forEach(e=>{this._map.removeControl(e)}),this._legends=[],this._legendEntries=[],this._legend=void 0,this._state.hasLegend=!1,this._state.selectedLegendIndex=-1,this._state.legends=[],this._updateButtonStates())}_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"),this._updatePanelHeight(),this._handleResize||(this._handleResize=()=>this._updatePanelHeight(),window.addEventListener("resize",this._handleResize))}_hidePanel(){this._handleResize&&(window.removeEventListener("resize",this._handleResize),this._handleResize=void 0),this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_updatePanelHeight(){if(!this._panel)return;const e=16,t=200,n=this._panel.getBoundingClientRect().top,i=Math.max(t,window.innerHeight-n-e),s=this._options.maxHeight>0?Math.min(this._options.maxHeight,i):i;this._panel.style.maxHeight=`${s}px`}_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())}getLegend(){return this._legend}},oz={position:"top-right",className:"",visible:!0,collapsed:!0,panelWidth:280,maxHeight:500,backgroundColor:"rgba(255, 255, 255, 0.95)",borderRadius:4,opacity:1,fontSize:12,fontColor:"#333",minzoom:0,maxzoom:24},lz='<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="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>',cz='<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>',y2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_zoomVisible=!0;_htmlControl;_htmlControls=[];_htmlEntries=[];_htmlSelect;_titleInput;_htmlTextarea;_positionSelect;_collapsibleCheckbox;_addBtn;_updateBtn;_removeBtn;_previewEl;constructor(e){this._options={...oz,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,title:"Info",html:`<div style="padding: 4px;">
263
+ `,t.querySelector(".legend-gui-close")?.addEventListener("click",()=>this._togglePanel()),e.appendChild(t);const n=document.createElement("div");n.className="legend-gui-content";const i=this._createField("Legend");this._legendSelect=document.createElement("select"),this._legendSelect.className="legend-gui-select",this._legendSelect.addEventListener("change",()=>{this._selectLegend(parseInt(this._legendSelect.value,10))}),i.appendChild(this._legendSelect),n.appendChild(i),this._renderLegendSelect();const s=this._createField("Title");this._titleInput=document.createElement("input"),this._titleInput.type="text",this._titleInput.className="legend-gui-input",this._titleInput.placeholder="Legend title",this._titleInput.value=this._state.title,this._titleInput.addEventListener("input",()=>{this._state.title=this._titleInput.value}),s.appendChild(this._titleInput),n.appendChild(s);const r=this._createField("Position");this._positionSelect=document.createElement("select"),this._positionSelect.className="legend-gui-select",[{value:"top-left",label:"Top Left"},{value:"top-right",label:"Top Right"},{value:"bottom-left",label:"Bottom Left"},{value:"bottom-right",label:"Bottom Right"}].forEach(f=>{const m=document.createElement("option");m.value=f.value,m.textContent=f.label,m.selected=f.value===this._state.legendPosition,this._positionSelect.appendChild(m)}),this._positionSelect.addEventListener("change",()=>{this._state.legendPosition=this._positionSelect.value}),r.appendChild(this._positionSelect),n.appendChild(r);const a=document.createElement("div");a.className="legend-gui-field";const o=document.createElement("div");o.className="legend-gui-items-header";const l=document.createElement("label");l.textContent="Items";const c=document.createElement("button");c.type="button",c.className="legend-gui-add-item-btn",c.innerHTML=rz,c.title="Add item",c.addEventListener("click",()=>this._addItem()),o.appendChild(l),o.appendChild(c),a.appendChild(o),n.appendChild(a),this._itemsContainer=document.createElement("div"),this._itemsContainer.className="legend-gui-items",this._renderItems(),n.appendChild(this._itemsContainer);const h=this._createField("Import from Dictionary");this._dictTextarea=document.createElement("textarea"),this._dictTextarea.className="legend-gui-textarea",this._dictTextarea.rows=4,this._dictTextarea.placeholder='{"Label A": "#ff6b6b", "Label B": "#4ecdc4"}',h.appendChild(this._dictTextarea);const d=document.createElement("button");return d.type="button",d.className="legend-gui-import-btn",d.textContent="Import Items from Dictionary",d.addEventListener("click",()=>this._importFromDict()),h.appendChild(d),this._dictErrorEl=document.createElement("div"),this._dictErrorEl.className="legend-gui-import-error",this._dictErrorEl.style.display="none",h.appendChild(this._dictErrorEl),n.appendChild(h),this._addBtn=document.createElement("button"),this._addBtn.type="button",this._addBtn.className="legend-gui-add-btn",this._addBtn.textContent="Add Legend",this._addBtn.addEventListener("click",()=>this._addLegend()),n.appendChild(this._addBtn),this._updateBtn=document.createElement("button"),this._updateBtn.type="button",this._updateBtn.className="legend-gui-add-btn",this._updateBtn.textContent="Update Selected Legend",this._updateBtn.style.display=this._state.hasLegend?"":"none",this._updateBtn.addEventListener("click",()=>this._updateLegend()),n.appendChild(this._updateBtn),this._removeBtn=document.createElement("button"),this._removeBtn.type="button",this._removeBtn.className="legend-gui-remove-btn",this._removeBtn.textContent="Remove Legend",this._removeBtn.style.display=this._state.hasLegend?"":"none",this._removeBtn.addEventListener("click",()=>this._removeLegend()),n.appendChild(this._removeBtn),e.appendChild(n),e}_createField(e){const t=document.createElement("div");t.className="legend-gui-field";const n=document.createElement("label");return n.textContent=e,t.appendChild(n),t}_renderItems(){this._itemsContainer&&(this._itemsContainer.innerHTML="",this._state.items.forEach((e,t)=>{const n=document.createElement("div");n.className="legend-gui-item-row";const i=document.createElement("input");i.type="color",i.className="legend-gui-color-input",i.value=e.color,i.addEventListener("input",()=>{this._state.items[t].color=i.value});const s=document.createElement("input");s.type="text",s.className="legend-gui-input legend-gui-item-label",s.value=e.label,s.placeholder="Label",s.addEventListener("input",()=>{this._state.items[t].label=s.value});const r=document.createElement("select");r.className="legend-gui-select legend-gui-item-shape",["square","circle","line"].forEach(o=>{const l=document.createElement("option");l.value=o,l.textContent=o,l.selected=o===(e.shape||"square"),r.appendChild(l)}),r.addEventListener("change",()=>{this._state.items[t].shape=r.value});const a=document.createElement("button");a.type="button",a.className="legend-gui-delete-item-btn",a.innerHTML=az,a.title="Remove item",a.addEventListener("click",()=>{this._state.items.splice(t,1),this._renderItems()}),n.appendChild(i),n.appendChild(s),n.appendChild(r),n.appendChild(a),this._itemsContainer.appendChild(n)}))}_addItem(){const e=["#ff6b6b","#4ecdc4","#95a5a6","#f39c12","#9b59b6","#3498db","#2ecc71","#e74c3c"],t=e[this._state.items.length%e.length];this._state.items.push({label:`Item ${this._state.items.length+1}`,color:t,shape:"square"}),this._renderItems()}_importFromDict(){if(!this._dictTextarea||!this._dictErrorEl)return;const e=this._dictTextarea.value.trim();if(!e){this._dictErrorEl.textContent="Please paste a JSON dictionary.",this._dictErrorEl.style.display="";return}try{const t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new Error('Expected a JSON object like {"label": "color"}');const n=Object.entries(t);if(n.length===0)throw new Error("Dictionary is empty.");const i=[];for(const[s,r]of n){if(typeof r!="string")throw new Error(`Value for "${s}" must be a color string.`);i.push({label:s,color:r,shape:"square"})}this._state.items=i,this._renderItems(),this._dictErrorEl.style.display="none",this._dictTextarea.value=""}catch(t){const n=t instanceof Error?t.message:"Invalid JSON";this._dictErrorEl.textContent=n,this._dictErrorEl.style.display=""}}_getFormEntry(){return{title:this._state.title,items:this._state.items.map(e=>({...e})),legendPosition:this._state.legendPosition}}_applyEntryToForm(e){this._state.title=e.title,this._state.items=e.items.map(t=>({...t})),this._state.legendPosition=e.legendPosition,this._titleInput&&(this._titleInput.value=e.title),this._positionSelect&&(this._positionSelect.value=e.legendPosition),this._renderItems()}_createLegend(e){return new lE({title:e.title,items:e.items.map(t=>({...t})),collapsible:!0,collapsed:!1})}_selectLegend(e){if(e<0){this._state.selectedLegendIndex=-1,this._legend=void 0,this._updateButtonStates();return}e>=this._legendEntries.length||(this._state.selectedLegendIndex=e,this._legend=this._legends[e],this._applyEntryToForm(this._legendEntries[e]),this._updateButtonStates())}_renderLegendSelect(){if(!this._legendSelect)return;this._legendSelect.innerHTML="";const e=document.createElement("option");e.value="-1",e.textContent="New legend",this._legendSelect.appendChild(e),this._legendEntries.forEach((t,n)=>{const i=document.createElement("option");i.value=String(n),i.textContent=t.title||`Legend ${n+1}`,this._legendSelect.appendChild(i)}),this._legendSelect.value=this._state.selectedLegendIndex>=0?String(this._state.selectedLegendIndex):"-1"}_addLegend(){if(!this._map)return;const e=this._getFormEntry(),t=this._createLegend(e);this._map.addControl(t,e.legendPosition),this._legends.push(t),this._legendEntries.push(e),this._legend=t,this._state.hasLegend=!0,this._state.selectedLegendIndex=this._legends.length-1,this._state.legends=this._legendEntries.map(n=>({...n,items:[...n.items]})),this._updateButtonStates(),this._emit("legendadd")}_updateLegend(){if(!this._map)return;const e=this._state.selectedLegendIndex;if(e<0||e>=this._legends.length){this._addLegend();return}const t=this._getFormEntry();this._map.removeControl(this._legends[e]);const n=this._createLegend(t);this._map.addControl(n,t.legendPosition),this._legends[e]=n,this._legendEntries[e]=t,this._legend=n,this._state.legends=this._legendEntries.map(i=>({...i,items:[...i.items]})),this._emit("legendupdate"),this._updateButtonStates()}_removeLegend(){if(!this._map)return;const e=this._state.selectedLegendIndex;e<0||e>=this._legends.length||(this._map.removeControl(this._legends[e]),this._legends.splice(e,1),this._legendEntries.splice(e,1),this._state.hasLegend=this._legends.length>0,this._state.selectedLegendIndex=this._state.hasLegend?Math.min(e,this._legends.length-1):-1,this._legend=this._state.selectedLegendIndex>=0?this._legends[this._state.selectedLegendIndex]:void 0,this._state.legends=this._legendEntries.map(t=>({...t,items:[...t.items]})),this._state.selectedLegendIndex>=0&&this._applyEntryToForm(this._legendEntries[this._state.selectedLegendIndex]),this._updateButtonStates(),this._emit("legendremove"))}_updateButtonStates(){this._addBtn&&(this._addBtn.textContent="Add Legend");const e=this._state.selectedLegendIndex>=0;this._updateBtn&&(this._updateBtn.style.display=e?"":"none"),this._removeBtn&&(this._removeBtn.style.display=e?"":"none"),this._renderLegendSelect()}_removeAllLegends(){this._map&&(this._legends.forEach(e=>{this._map.removeControl(e)}),this._legends=[],this._legendEntries=[],this._legend=void 0,this._state.hasLegend=!1,this._state.selectedLegendIndex=-1,this._state.legends=[],this._updateButtonStates())}_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"),this._updatePanelHeight(),this._handleResize||(this._handleResize=()=>this._updatePanelHeight(),window.addEventListener("resize",this._handleResize))}_hidePanel(){this._handleResize&&(window.removeEventListener("resize",this._handleResize),this._handleResize=void 0),this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_updatePanelHeight(){if(!this._panel)return;const e=16,t=200,n=this._panel.getBoundingClientRect().top,i=Math.max(t,window.innerHeight-n-e),s=this._options.maxHeight>0?Math.min(this._options.maxHeight,i):i;this._panel.style.maxHeight=`${s}px`}_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())}getLegend(){return this._legend}},oz={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},lz='<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="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>',cz='<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>',y2=class{_container;_button;_panel;_options;_state;_eventHandlers=new Map;_map;_handleZoom;_handleResize;_zoomVisible=!0;_htmlControl;_htmlControls=[];_htmlEntries=[];_htmlSelect;_titleInput;_htmlTextarea;_positionSelect;_collapsibleCheckbox;_addBtn;_updateBtn;_removeBtn;_previewEl;constructor(e){this._options={...oz,...e},this._state={visible:this._options.visible,collapsed:this._options.collapsed,title:"Info",html:`<div style="padding: 4px;">
264
264
  <h4 style="margin: 0 0 8px 0;">Welcome</h4>
265
265
  <p style="margin: 0; color: #666;">This is a custom HTML control.</p>
266
- </div>`,htmlPosition:"top-left",collapsible:!0,hasHtmlControl:!1,selectedHtmlIndex:-1,htmls:[]}}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._removeAllHtmlControls(),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,htmls:this._htmlEntries.map(e=>({...e}))}}setState(e){this._map&&this._htmlControls.forEach(s=>{this._map.removeControl(s)});const t=(e.htmls??[]).map(s=>({...s}));this._htmlControls=[],this._htmlEntries=t,this._map&&t.forEach(s=>{const r=this._createHtmlControl(s);this._map.addControl(r,s.htmlPosition),this._htmlControls.push(r)});const n=typeof e.selectedHtmlIndex=="number"&&e.selectedHtmlIndex>=0&&e.selectedHtmlIndex<t.length?e.selectedHtmlIndex:t.length>0?t.length-1:-1,i=n>=0?t[n]:{title:e.title??this._state.title,html:e.html??this._state.html,htmlPosition:e.htmlPosition??this._state.htmlPosition,collapsible:e.collapsible??this._state.collapsible};return this._state={...this._state,...i,visible:e.visible??this._state.visible,collapsed:e.collapsed??this._state.collapsed,hasHtmlControl:t.length>0,selectedHtmlIndex:n,htmls:t.map(s=>({...s}))},this._htmlControl=n>=0?this._htmlControls[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("htmlupdate"),this}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-html-gui-control ${this._options.className}`,this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="html-gui-button",this._button.title="HTML Control",this._button.innerHTML=lz,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`html-gui-panel ${this._options.position.includes("left")?"right":"left"}`,e.style.width=`${this._options.panelWidth}px`,this._options.maxHeight>0&&(e.style.maxHeight=`${this._options.maxHeight}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="html-gui-header",t.innerHTML=`
266
+ </div>`,htmlPosition:"top-left",collapsible:!0,hasHtmlControl:!1,selectedHtmlIndex:-1,htmls:[]}}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._removeAllHtmlControls(),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,htmls:this._htmlEntries.map(e=>({...e}))}}setState(e){this._map&&this._htmlControls.forEach(s=>{this._map.removeControl(s)});const t=(e.htmls??[]).map(s=>({...s}));this._htmlControls=[],this._htmlEntries=t,this._map&&t.forEach(s=>{const r=this._createHtmlControl(s);this._map.addControl(r,s.htmlPosition),this._htmlControls.push(r)});const n=typeof e.selectedHtmlIndex=="number"&&e.selectedHtmlIndex>=0&&e.selectedHtmlIndex<t.length?e.selectedHtmlIndex:t.length>0?t.length-1:-1,i=n>=0?t[n]:{title:e.title??this._state.title,html:e.html??this._state.html,htmlPosition:e.htmlPosition??this._state.htmlPosition,collapsible:e.collapsible??this._state.collapsible};return this._state={...this._state,...i,visible:e.visible??this._state.visible,collapsed:e.collapsed??this._state.collapsed,hasHtmlControl:t.length>0,selectedHtmlIndex:n,htmls:t.map(s=>({...s}))},this._htmlControl=n>=0?this._htmlControls[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("htmlupdate"),this}_createContainer(){const e=document.createElement("div");return e.className=`maplibregl-ctrl maplibre-gl-html-gui-control ${this._options.className}`,this._state.visible||(e.style.display="none"),this._button=document.createElement("button"),this._button.type="button",this._button.className="html-gui-button",this._button.title="HTML Control",this._button.innerHTML=lz,this._button.addEventListener("click",()=>this._togglePanel()),e.appendChild(this._button),e}_createPanel(){const e=document.createElement("div");e.className=`html-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="html-gui-header",t.innerHTML=`
267
267
  <span>HTML Control</span>
268
268
  <button type="button" class="html-gui-close" title="Close">${cz}</button>
269
- `,t.querySelector(".html-gui-close")?.addEventListener("click",()=>this._togglePanel()),e.appendChild(t);const n=document.createElement("div");n.className="html-gui-content";const i=this._createField("HTML Control");this._htmlSelect=document.createElement("select"),this._htmlSelect.className="html-gui-select",this._htmlSelect.addEventListener("change",()=>{this._selectHtmlControl(parseInt(this._htmlSelect.value,10))}),i.appendChild(this._htmlSelect),n.appendChild(i),this._renderHtmlSelect();const s=this._createField("Title");this._titleInput=document.createElement("input"),this._titleInput.type="text",this._titleInput.className="html-gui-input",this._titleInput.placeholder="Control title",this._titleInput.value=this._state.title,this._titleInput.addEventListener("input",()=>{this._state.title=this._titleInput.value}),s.appendChild(this._titleInput),n.appendChild(s);const r=this._createField("HTML Content");this._htmlTextarea=document.createElement("textarea"),this._htmlTextarea.className="html-gui-textarea",this._htmlTextarea.rows=6,this._htmlTextarea.value=this._state.html,this._htmlTextarea.placeholder="<div>Your HTML here...</div>",this._htmlTextarea.addEventListener("input",()=>{this._state.html=this._htmlTextarea.value,this._updatePreviewContent()}),r.appendChild(this._htmlTextarea),n.appendChild(r);const a=this._createField("Preview");this._previewEl=document.createElement("div"),this._previewEl.className="html-gui-preview",this._updatePreviewContent(),a.appendChild(this._previewEl),n.appendChild(a);const o=document.createElement("div");o.className="html-gui-row";const l=this._createField("Position");this._positionSelect=document.createElement("select"),this._positionSelect.className="html-gui-select",[{value:"top-left",label:"Top Left"},{value:"top-right",label:"Top Right"},{value:"bottom-left",label:"Bottom Left"},{value:"bottom-right",label:"Bottom Right"}].forEach(d=>{const f=document.createElement("option");f.value=d.value,f.textContent=d.label,f.selected=d.value===this._state.htmlPosition,this._positionSelect.appendChild(f)}),this._positionSelect.addEventListener("change",()=>{this._state.htmlPosition=this._positionSelect.value}),l.appendChild(this._positionSelect),o.appendChild(l);const c=this._createField("Options"),h=document.createElement("label");return h.className="html-gui-checkbox-label",this._collapsibleCheckbox=document.createElement("input"),this._collapsibleCheckbox.type="checkbox",this._collapsibleCheckbox.checked=this._state.collapsible,this._collapsibleCheckbox.addEventListener("change",()=>{this._state.collapsible=!!this._collapsibleCheckbox?.checked}),h.appendChild(this._collapsibleCheckbox),h.appendChild(document.createTextNode(" Collapsible")),c.appendChild(h),o.appendChild(c),n.appendChild(o),this._addBtn=document.createElement("button"),this._addBtn.type="button",this._addBtn.className="html-gui-add-btn",this._addBtn.textContent="Add HTML Control",this._addBtn.addEventListener("click",()=>this._addHtmlControl()),n.appendChild(this._addBtn),this._updateBtn=document.createElement("button"),this._updateBtn.type="button",this._updateBtn.className="html-gui-add-btn",this._updateBtn.textContent="Update Selected Control",this._updateBtn.style.display=this._state.hasHtmlControl?"":"none",this._updateBtn.addEventListener("click",()=>this._updateHtmlControl()),n.appendChild(this._updateBtn),this._removeBtn=document.createElement("button"),this._removeBtn.type="button",this._removeBtn.className="html-gui-remove-btn",this._removeBtn.textContent="Remove Control",this._removeBtn.style.display=this._state.hasHtmlControl?"":"none",this._removeBtn.addEventListener("click",()=>this._removeHtmlControl()),n.appendChild(this._removeBtn),e.appendChild(n),e}_createField(e){const t=document.createElement("div");t.className="html-gui-field";const n=document.createElement("label");return n.textContent=e,t.appendChild(n),t}_updatePreviewContent(){this._previewEl&&(this._previewEl.innerHTML=this._state.html)}_getFormEntry(){return{title:this._state.title,html:this._state.html,htmlPosition:this._state.htmlPosition,collapsible:this._state.collapsible}}_applyEntryToForm(e){this._state.title=e.title,this._state.html=e.html,this._state.htmlPosition=e.htmlPosition,this._state.collapsible=e.collapsible,this._titleInput&&(this._titleInput.value=e.title),this._htmlTextarea&&(this._htmlTextarea.value=e.html),this._positionSelect&&(this._positionSelect.value=e.htmlPosition),this._collapsibleCheckbox&&(this._collapsibleCheckbox.checked=e.collapsible),this._updatePreviewContent()}_createHtmlControl(e){return new $B({title:e.title,html:e.html,collapsible:e.collapsible,collapsed:!1})}_selectHtmlControl(e){if(e<0){this._state.selectedHtmlIndex=-1,this._htmlControl=void 0,this._updateButtonStates();return}e>=this._htmlEntries.length||(this._state.selectedHtmlIndex=e,this._htmlControl=this._htmlControls[e],this._applyEntryToForm(this._htmlEntries[e]),this._updateButtonStates())}_renderHtmlSelect(){if(!this._htmlSelect)return;this._htmlSelect.innerHTML="";const e=document.createElement("option");e.value="-1",e.textContent="New HTML control",this._htmlSelect.appendChild(e),this._htmlEntries.forEach((t,n)=>{const i=document.createElement("option");i.value=String(n),i.textContent=t.title||`HTML ${n+1}`,this._htmlSelect.appendChild(i)}),this._htmlSelect.value=this._state.selectedHtmlIndex>=0?String(this._state.selectedHtmlIndex):"-1"}_addHtmlControl(){if(!this._map)return;const e=this._getFormEntry(),t=this._createHtmlControl(e);this._map.addControl(t,e.htmlPosition),this._htmlControls.push(t),this._htmlEntries.push(e),this._htmlControl=t,this._state.hasHtmlControl=!0,this._state.selectedHtmlIndex=this._htmlControls.length-1,this._state.htmls=this._htmlEntries.map(n=>({...n})),this._updateButtonStates(),this._emit("htmladd")}_updateHtmlControl(){if(!this._map)return;const e=this._state.selectedHtmlIndex;if(e<0||e>=this._htmlControls.length){this._addHtmlControl();return}const t=this._getFormEntry();this._map.removeControl(this._htmlControls[e]);const n=this._createHtmlControl(t);this._map.addControl(n,t.htmlPosition),this._htmlControls[e]=n,this._htmlEntries[e]=t,this._htmlControl=n,this._state.htmls=this._htmlEntries.map(i=>({...i})),this._emit("htmlupdate"),this._updateButtonStates()}_removeHtmlControl(){if(!this._map)return;const e=this._state.selectedHtmlIndex;e<0||e>=this._htmlControls.length||(this._map.removeControl(this._htmlControls[e]),this._htmlControls.splice(e,1),this._htmlEntries.splice(e,1),this._state.hasHtmlControl=this._htmlControls.length>0,this._state.selectedHtmlIndex=this._state.hasHtmlControl?Math.min(e,this._htmlControls.length-1):-1,this._htmlControl=this._state.selectedHtmlIndex>=0?this._htmlControls[this._state.selectedHtmlIndex]:void 0,this._state.htmls=this._htmlEntries.map(t=>({...t})),this._state.selectedHtmlIndex>=0&&this._applyEntryToForm(this._htmlEntries[this._state.selectedHtmlIndex]),this._updateButtonStates(),this._emit("htmlremove"))}_updateButtonStates(){this._addBtn&&(this._addBtn.textContent="Add HTML Control");const e=this._state.selectedHtmlIndex>=0;this._updateBtn&&(this._updateBtn.style.display=e?"":"none"),this._removeBtn&&(this._removeBtn.style.display=e?"":"none"),this._renderHtmlSelect()}_removeAllHtmlControls(){this._map&&(this._htmlControls.forEach(e=>{this._map.removeControl(e)}),this._htmlControls=[],this._htmlEntries=[],this._htmlControl=void 0,this._state.hasHtmlControl=!1,this._state.selectedHtmlIndex=-1,this._state.htmls=[],this._updateButtonStates())}_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")}_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())}getHtmlControl(){return this._htmlControl}},hz={speed:10,spinOnLoad:!1,pauseOnInteraction:!0,collapsed:!0},sS=["dragstart","zoomstart","rotatestart","pitchstart","boxzoomstart","touchstart"],uz='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.636-6.364"/><polyline points="21 3 21 9 15 9"/></svg>',b2=class{_map;_container;_button;_panel;_options;_spinning=!1;_collapsed;_animationId;_lastTime;_eventHandlers=new Map;_speedInput;_speedValueEl;_toggleBtn;_onInteractionStart;_onDoubleClick;_wheelTarget;_doubleClickTimeoutId;constructor(e){this._options={...hz,...e},this._collapsed=this._options.collapsed}onAdd(e){if(this._map=e,this._container=document.createElement("div"),this._container.className="maplibregl-ctrl maplibregl-ctrl-group maplibre-gl-spin-globe-control",this._button=document.createElement("button"),this._button.type="button",this._button.title="Spin globe",this._button.setAttribute("aria-label","Spin globe"),this._button.setAttribute("aria-pressed","false"),this._button.innerHTML=uz,this._button.style.cssText="display:flex;align-items:center;justify-content:center;width:29px;height:29px;cursor:pointer;",this._button.addEventListener("click",()=>this._togglePanel()),this._container.appendChild(this._button),this._onDoubleClick=()=>this._startSpinAfterDoubleClick(),e.on("dblclick",this._onDoubleClick),this._options.pauseOnInteraction){this._onInteractionStart=()=>this._stopSpinForInteraction(),sS.forEach(n=>{e.on(n,this._onInteractionStart)});const t=e.getCanvas?.();t?.addEventListener&&(this._wheelTarget=t,t.addEventListener("wheel",this._onInteractionStart,{passive:!0}))}return this._options.spinOnLoad&&(e.isStyleLoaded()?this.startSpin():e.once("load",()=>this.startSpin())),this._collapsed||this._showPanel(),this._container}onRemove(){this.stopSpin(),this._doubleClickTimeoutId!==void 0&&(clearTimeout(this._doubleClickTimeoutId),this._doubleClickTimeoutId=void 0),this._map&&(this._onInteractionStart&&sS.forEach(e=>{this._map.off(e,this._onInteractionStart)}),this._onDoubleClick&&this._map.off("dblclick",this._onDoubleClick)),this._wheelTarget&&this._onInteractionStart&&this._wheelTarget.removeEventListener("wheel",this._onInteractionStart),this._container?.parentNode?.removeChild(this._container),this._map=void 0,this._container=void 0,this._button=void 0,this._panel=void 0,this._speedInput=void 0,this._speedValueEl=void 0,this._toggleBtn=void 0,this._onInteractionStart=void 0,this._onDoubleClick=void 0,this._wheelTarget=void 0,this._eventHandlers.clear()}startSpin(){this._spinning||(this._spinning=!0,this._lastTime=void 0,this._animationId=requestAnimationFrame(e=>this._animate(e)),this._updateButton(),this._updateToggleBtn(),this._emit("spinstart"))}stopSpin(){this._spinning&&(this._spinning=!1,this._animationId!==void 0&&(cancelAnimationFrame(this._animationId),this._animationId=void 0),this._lastTime=void 0,this._updateButton(),this._updateToggleBtn(),this._emit("spinstop"))}toggleSpin(){this._spinning?this.stopSpin():this.startSpin()}isSpinning(){return this._spinning}getState(){return{spinning:this._spinning,collapsed:this._collapsed}}update(e){this._options={...this._options,...e},e.speed!==void 0&&this._speedInput&&(this._speedInput.value=String(e.speed),this._speedValueEl&&(this._speedValueEl.textContent=`${e.speed}`))}expand(){this._collapsed&&(this._collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._collapsed||(this._collapsed=!0,this._hidePanel(),this._emit("collapse"))}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)}_togglePanel(){this._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._speedInput=void 0,this._speedValueEl=void 0,this._toggleBtn=void 0,this._button?.classList.remove("active")}_createPanel(){const e=document.createElement("div");e.className="spin-globe-panel",e.style.cssText="position:absolute;top:0;right:calc(100% + 0px);background:#fff;color:#000;border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.15);padding:12px;z-index:1;white-space:nowrap;min-width:180px;";const t=document.createElement("div");t.style.cssText="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;font-weight:600;font-size:13px;color:#000;",t.textContent="Spin Globe";const n=document.createElement("button");n.type="button",n.title="Close",n.setAttribute("aria-label","Close"),n.textContent="×",n.style.cssText="background:none;border:none;font-size:18px;cursor:pointer;color:#000;padding:0 0 0 8px;line-height:1;",n.addEventListener("click",()=>this.collapse()),t.appendChild(n),e.appendChild(t);const i=document.createElement("div");i.style.cssText="display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:12px;color:#000;";const s=document.createElement("label");s.textContent="Speed",s.style.cssText="flex-shrink:0;font-weight:500;",this._speedInput=document.createElement("input"),this._speedInput.type="range",this._speedInput.min="1",this._speedInput.max="60",this._speedInput.step="1",this._speedInput.value=String(this._options.speed),this._speedInput.style.cssText="flex:1;min-width:80px;cursor:pointer;accent-color:#2563eb;",this._speedValueEl=document.createElement("span"),this._speedValueEl.textContent=`${this._options.speed}`,this._speedValueEl.style.cssText="min-width:20px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums;";const r=document.createElement("span");return r.textContent="°/s",r.style.cssText="flex-shrink:0;color:#000;",this._speedInput.addEventListener("input",()=>{const a=Number(this._speedInput.value);this._options.speed=a,this._speedValueEl&&(this._speedValueEl.textContent=`${a}`)}),i.appendChild(s),i.appendChild(this._speedInput),i.appendChild(this._speedValueEl),i.appendChild(r),e.appendChild(i),this._toggleBtn=document.createElement("button"),this._toggleBtn.type="button",this._updateToggleBtn(),this._toggleBtn.style.cssText="width:100%;padding:6px 0;border:1px solid #333;border-radius:4px;background:#fff;font-size:12px;font-weight:500;color:#000;cursor:pointer;",this._toggleBtn.addEventListener("mouseenter",()=>{this._toggleBtn&&(this._toggleBtn.style.backgroundColor="#f0f0f0")}),this._toggleBtn.addEventListener("mouseleave",()=>{this._toggleBtn&&(this._toggleBtn.style.backgroundColor="#fff")}),this._toggleBtn.addEventListener("click",()=>this.toggleSpin()),e.appendChild(this._toggleBtn),e}_updateToggleBtn(){this._toggleBtn&&(this._toggleBtn.textContent=this._spinning?"Stop":"Start")}_animate(e){if(!(!this._spinning||!this._map)){if(this._lastTime!==void 0){const t=(e-this._lastTime)/1e3,n=this._map.getCenter();n.lng-=this._options.speed*t,this._map.jumpTo({center:n})}this._lastTime=e,this._animationId=requestAnimationFrame(t=>this._animate(t))}}_stopSpinForInteraction(){this._spinning&&this.stopSpin()}_startSpinAfterDoubleClick(){this._doubleClickTimeoutId!==void 0&&clearTimeout(this._doubleClickTimeoutId),this._doubleClickTimeoutId=setTimeout(()=>{this._doubleClickTimeoutId=void 0,this._map&&this.startSpin()},0)}_updateButton(){this._button&&(this._spinning?(this._button.style.backgroundColor="rgba(0, 120, 215, 0.15)",this._button.title="Stop globe spin",this._button.setAttribute("aria-label","Stop globe spin"),this._button.setAttribute("aria-pressed","true")):(this._button.style.backgroundColor="",this._button.title="Spin globe",this._button.setAttribute("aria-label","Spin globe"),this._button.setAttribute("aria-pressed","false")))}_emit(e){const t=this._eventHandlers.get(e);if(!t)return;const n={type:e,state:this.getState()};t.forEach(i=>i(n))}},dz={collapsed:!0,defaultType:"xyz",defaultUrl:"",defaultWmsUrl:"https://services.terrascope.be/wms/v2",defaultName:"",defaultWmsLayers:"",defaultOpacity:.8,tileSize:256,attribution:""},pz='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4 2 9l10 5 10-5-10-5z"/><path d="M2 15l10 5 10-5"/></svg>',fz='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',mz='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>',x2=class{_map;_container;_button;_panel;_options;_collapsed;_layers=[];_layerCounter=0;_eventHandlers=new Map;_typeSelect;_urlInput;_nameInput;_wmsLayersSelect;_wmsLayersRow;_wmsStatusEl;_opacityInput;_opacityValueEl;_layerListEl;_fetchDebounceTimer;_fetchController;constructor(e){this._options={...dz,...e},this._collapsed=this._options.collapsed}onAdd(e){return this._map=e,this._container=document.createElement("div"),this._container.className="maplibregl-ctrl maplibregl-ctrl-group maplibre-gl-tile-layer-control",this._button=document.createElement("button"),this._button.type="button",this._button.title="Tile Layer",this._button.setAttribute("aria-label","Tile Layer"),this._button.innerHTML=pz,this._button.style.cssText="display:flex;align-items:center;justify-content:center;width:29px;height:29px;cursor:pointer;",this._button.addEventListener("click",()=>this._togglePanel()),this._container.appendChild(this._button),this._collapsed||this._showPanel(),this._container}onRemove(){if(this._map)for(const e of[...this._layers])try{this._map.getLayer(e.id)&&this._map.removeLayer(e.id),this._map.getSource(e.id)&&this._map.removeSource(e.id)}catch{}this._layers=[],this._fetchController?.abort(),clearTimeout(this._fetchDebounceTimer),this._container?.parentNode?.removeChild(this._container),this._map=void 0,this._container=void 0,this._button=void 0,this._panel=void 0,this._typeSelect=void 0,this._urlInput=void 0,this._nameInput=void 0,this._wmsLayersSelect=void 0,this._wmsLayersRow=void 0,this._wmsStatusEl=void 0,this._opacityInput=void 0,this._opacityValueEl=void 0,this._layerListEl=void 0,this._eventHandlers.clear()}addTileLayer(e,t){if(!this._map||!e.trim())return null;++this._layerCounter;const n=t?.type??this._options.defaultType,i=t?.opacity??this._options.defaultOpacity,s=t?.name||`Tile Layer ${this._layerCounter}`;let r=s;(this._map.getSource(r)||this._layers.some(l=>l.id===r))&&(r=`${s}-${this._layerCounter}`);let a=e;n==="wms"&&(a=this._buildWmsUrl(e,t?.wmsLayers));const o={id:r,name:s,url:e,type:n,opacity:i,visible:!0,wmsLayers:t?.wmsLayers};try{this._map.addSource(r,{type:"raster",tiles:[a],tileSize:this._options.tileSize,...this._options.attribution?{attribution:this._options.attribution}:{}}),this._map.addLayer({id:r,type:"raster",source:r,paint:{"raster-opacity":i}})}catch(l){return console.error("Failed to add tile layer:",l),null}return this._layers.push(o),this._updateLayerList(),this._emit("layeradd",o),o}removeTileLayer(e){const t=this._layers.findIndex(i=>i.id===e);if(t===-1||!this._map)return;const n=this._layers[t];try{this._map.getLayer(e)&&this._map.removeLayer(e),this._map.getSource(e)&&this._map.removeSource(e)}catch{}this._layers.splice(t,1),this._updateLayerList(),this._emit("layerremove",n)}setLayerVisibility(e,t){const n=this._layers.find(i=>i.id===e);!n||!this._map||(n.visible=t,this._map.setLayoutProperty(e,"visibility",t?"visible":"none"),this._updateLayerList(),this._emit("layervisibility",n))}setLayerOpacity(e,t){const n=this._layers.find(i=>i.id===e);!n||!this._map||(n.opacity=t,this._map.setPaintProperty(e,"raster-opacity",t),this._emit("layeropacity",n))}getLayers(){return[...this._layers]}getState(){return{collapsed:this._collapsed,layers:[...this._layers]}}expand(){this._collapsed&&(this._collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._collapsed||(this._collapsed=!0,this._hidePanel(),this._emit("collapse"))}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)}_togglePanel(){this._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._fetchController?.abort(),clearTimeout(this._fetchDebounceTimer),this._panel?.remove(),this._panel=void 0,this._typeSelect=void 0,this._urlInput=void 0,this._nameInput=void 0,this._wmsLayersSelect=void 0,this._wmsLayersRow=void 0,this._wmsStatusEl=void 0,this._opacityInput=void 0,this._opacityValueEl=void 0,this._layerListEl=void 0,this._button?.classList.remove("active")}_createPanel(){const e=document.createElement("div");e.className="tile-layer-panel",e.style.cssText="position:absolute;top:0;right:calc(100% + 0px);background:#fff;color:#000;border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.15);padding:12px;z-index:1;white-space:nowrap;min-width:280px;";const t=document.createElement("div");t.style.cssText="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;font-weight:600;font-size:13px;color:#000;",t.textContent="Tile Layer";const n=document.createElement("button");n.type="button",n.title="Close",n.setAttribute("aria-label","Close"),n.textContent="×",n.style.cssText="background:none;border:none;font-size:18px;cursor:pointer;color:#000;padding:0 0 0 8px;line-height:1;",n.addEventListener("click",()=>this.collapse()),t.appendChild(n),e.appendChild(t);const i="display:flex;align-items:center;gap:8px;margin-bottom:8px;font-size:12px;color:#000;",s="flex-shrink:0;font-weight:500;min-width:70px;",r="flex:1;min-width:0;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px;color:#000;background:#fff;",a=document.createElement("div");a.style.cssText=i;const o=document.createElement("label");o.textContent="Type",o.style.cssText=s,this._typeSelect=document.createElement("select"),this._typeSelect.style.cssText="flex:1;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px;color:#000;background:#fff;cursor:pointer;";const l=document.createElement("option");l.value="xyz",l.textContent="XYZ";const c=document.createElement("option");c.value="wms",c.textContent="WMS",this._typeSelect.appendChild(l),this._typeSelect.appendChild(c),this._typeSelect.value=this._options.defaultType,this._typeSelect.addEventListener("change",()=>{const S=this._typeSelect.value==="wms";this._wmsLayersRow&&(this._wmsLayersRow.style.display=S?"flex":"none"),this._urlInput&&(this._urlInput.placeholder=S?"https://example.com/wms":"https://.../{z}/{x}/{y}.png",S&&!this._urlInput.value.trim()?this._urlInput.value=this._options.defaultWmsUrl:S&&this._urlInput.value===this._options.defaultUrl?this._urlInput.value=this._options.defaultWmsUrl:!S&&this._urlInput.value===this._options.defaultWmsUrl&&(this._urlInput.value=this._options.defaultUrl)),S&&this._onWmsUrlChange()}),a.appendChild(o),a.appendChild(this._typeSelect),e.appendChild(a);const h=document.createElement("div");h.style.cssText=i;const d=document.createElement("label");d.textContent="URL",d.style.cssText=s,this._urlInput=document.createElement("input"),this._urlInput.type="text",this._urlInput.placeholder=this._options.defaultType==="wms"?"https://example.com/wms":"https://.../{z}/{x}/{y}.png",this._urlInput.value=this._options.defaultUrl,this._urlInput.style.cssText=r,this._urlInput.addEventListener("input",()=>this._onWmsUrlChange()),this._urlInput.addEventListener("change",()=>this._onWmsUrlChange()),h.appendChild(d),h.appendChild(this._urlInput),e.appendChild(h);const f=document.createElement("div");f.style.cssText=i;const m=document.createElement("label");m.textContent="Name",m.style.cssText=s,this._nameInput=document.createElement("input"),this._nameInput.type="text",this._nameInput.placeholder="Layer name (optional)",this._nameInput.value=this._options.defaultName,this._nameInput.style.cssText=r,f.appendChild(m),f.appendChild(this._nameInput),e.appendChild(f),this._wmsLayersRow=document.createElement("div"),this._wmsLayersRow.style.cssText="display:flex;flex-direction:column;gap:4px;margin-bottom:8px;font-size:12px;color:#000;",this._wmsLayersRow.style.display=this._options.defaultType==="wms"?"flex":"none";const A=document.createElement("div");A.style.cssText="display:flex;align-items:center;gap:8px;";const y=document.createElement("label");y.textContent="Layer",y.style.cssText=s,this._wmsLayersSelect=document.createElement("select"),this._wmsLayersSelect.style.cssText="flex:1;min-width:0;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px;color:#000;background:#fff;cursor:pointer;";const x=document.createElement("option");if(x.value="",x.textContent="Enter WMS URL first...",x.disabled=!0,x.selected=!0,this._wmsLayersSelect.appendChild(x),this._options.defaultWmsLayers){const S=document.createElement("option");S.value=this._options.defaultWmsLayers,S.textContent=this._options.defaultWmsLayers,this._wmsLayersSelect.appendChild(S),this._wmsLayersSelect.value=this._options.defaultWmsLayers}this._wmsLayersSelect.addEventListener("change",()=>{if(this._nameInput){const S=this._wmsLayersSelect.options[this._wmsLayersSelect.selectedIndex];S?.textContent&&(this._nameInput.value=S.textContent)}}),A.appendChild(y),A.appendChild(this._wmsLayersSelect),this._wmsLayersRow.appendChild(A),this._wmsStatusEl=document.createElement("div"),this._wmsStatusEl.style.cssText="font-size:11px;color:#888;padding-left:78px;display:none;",this._wmsLayersRow.appendChild(this._wmsStatusEl),e.appendChild(this._wmsLayersRow),this._options.defaultType==="wms"&&this._options.defaultUrl&&this._onWmsUrlChange();const v=document.createElement("div");v.style.cssText=i;const b=document.createElement("label");b.textContent="Opacity",b.style.cssText=s,this._opacityInput=document.createElement("input"),this._opacityInput.type="range",this._opacityInput.min="0",this._opacityInput.max="1",this._opacityInput.step="0.05",this._opacityInput.value=String(this._options.defaultOpacity),this._opacityInput.style.cssText="flex:1;min-width:80px;cursor:pointer;accent-color:#2563eb;",this._opacityValueEl=document.createElement("span"),this._opacityValueEl.textContent=`${this._options.defaultOpacity}`,this._opacityValueEl.style.cssText="min-width:28px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums;",this._opacityInput.addEventListener("input",()=>{this._opacityValueEl&&(this._opacityValueEl.textContent=`${this._opacityInput.value}`)}),v.appendChild(b),v.appendChild(this._opacityInput),v.appendChild(this._opacityValueEl),e.appendChild(v);const w=document.createElement("button");return w.type="button",w.textContent="Add Layer",w.style.cssText="width:100%;padding:6px 0;border:1px solid #333;border-radius:4px;background:#fff;font-size:12px;font-weight:500;color:#000;cursor:pointer;margin-bottom:8px;",w.addEventListener("mouseenter",()=>{w.style.backgroundColor="#f0f0f0"}),w.addEventListener("mouseleave",()=>{w.style.backgroundColor="#fff"}),w.addEventListener("click",()=>this._addLayerFromForm()),e.appendChild(w),this._layerListEl=document.createElement("div"),this._layerListEl.style.cssText="max-height:200px;overflow-y:auto;",this._updateLayerList(),e.appendChild(this._layerListEl),e}_addLayerFromForm(){const e=this._urlInput?.value.trim();if(!e){this._urlInput&&(this._urlInput.style.borderColor="#e74c3c",setTimeout(()=>{this._urlInput&&(this._urlInput.style.borderColor="#ccc")},2e3));return}const t=this._typeSelect?.value??"xyz",n=this._nameInput?.value.trim()||void 0,i=this._wmsLayersSelect?.value.trim()||void 0,s=Number(this._opacityInput?.value??.8);this.addTileLayer(e,{name:n,type:t,wmsLayers:i,opacity:s})}_updateLayerList(){if(!this._layerListEl||(this._layerListEl.innerHTML="",this._layers.length===0))return;const e=document.createElement("div");e.style.cssText="font-size:11px;font-weight:600;color:#666;margin-bottom:4px;padding-top:4px;border-top:1px solid #eee;",e.textContent="Added Layers",this._layerListEl.appendChild(e);for(const t of this._layers){const n=document.createElement("div");n.style.cssText="display:flex;align-items:center;gap:4px;margin-bottom:4px;font-size:11px;color:#000;";const i=document.createElement("button");i.type="button",i.title=t.visible?"Hide layer":"Show layer",i.innerHTML=t.visible?fz:mz,i.style.cssText="background:none;border:none;cursor:pointer;padding:2px;display:flex;align-items:center;flex-shrink:0;color:#000;",t.visible||(i.style.opacity="0.4"),i.addEventListener("click",()=>{this.setLayerVisibility(t.id,!t.visible)}),n.appendChild(i);const s=document.createElement("span");s.textContent=t.name,s.title=t.url,s.style.cssText="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;",n.appendChild(s);const r=document.createElement("input");r.type="range",r.min="0",r.max="1",r.step="0.05",r.value=String(t.opacity),r.style.cssText="width:50px;cursor:pointer;accent-color:#2563eb;flex-shrink:0;",r.addEventListener("input",()=>{this.setLayerOpacity(t.id,Number(r.value))}),n.appendChild(r);const a=document.createElement("button");a.type="button",a.title="Remove layer",a.textContent="×",a.style.cssText="background:none;border:none;font-size:14px;cursor:pointer;color:#999;padding:0 2px;line-height:1;flex-shrink:0;",a.addEventListener("mouseenter",()=>{a.style.color="#e74c3c"}),a.addEventListener("mouseleave",()=>{a.style.color="#999"}),a.addEventListener("click",()=>{this.removeTileLayer(t.id)}),n.appendChild(a),this._layerListEl.appendChild(n)}}_onWmsUrlChange(){this._typeSelect?.value==="wms"&&(clearTimeout(this._fetchDebounceTimer),this._fetchDebounceTimer=setTimeout(()=>{const e=this._urlInput?.value.trim();e&&this._fetchWmsLayers(e)},600))}async _fetchWmsLayers(e){this._fetchController?.abort(),this._fetchController=new AbortController,this._wmsStatusEl&&(this._wmsStatusEl.style.display="block",this._wmsStatusEl.textContent="Fetching layers...",this._wmsStatusEl.style.color="#888");try{const t=new URL(e);t.searchParams.set("service","WMS"),t.searchParams.set("request","GetCapabilities");const n=await fetch(t.toString(),{signal:this._fetchController.signal});if(!n.ok)throw new Error(`HTTP ${n.status}`);const i=await n.text(),s=new DOMParser().parseFromString(i,"text/xml"),r=[],a=s.querySelectorAll("Layer");for(const l of a){const c=l.querySelector(":scope > Name"),h=l.querySelector(":scope > Title");c?.textContent&&r.push({name:c.textContent,title:h?.textContent||c.textContent})}if(!this._wmsLayersSelect)return;if(this._wmsLayersSelect.innerHTML="",r.length===0){const l=document.createElement("option");l.value="",l.textContent="No layers found",l.disabled=!0,l.selected=!0,this._wmsLayersSelect.appendChild(l),this._wmsStatusEl&&(this._wmsStatusEl.textContent="No layers found",this._wmsStatusEl.style.color="#e74c3c");return}const o=document.createElement("option");o.value="",o.textContent=`Select a layer (${r.length} available)`,o.disabled=!0,o.selected=!0,this._wmsLayersSelect.appendChild(o);for(const l of r){const c=document.createElement("option");c.value=l.name,c.textContent=l.title!==l.name?`${l.title} (${l.name})`:l.name,this._wmsLayersSelect.appendChild(c)}if(this._options.defaultWmsLayers){const l=r.find(c=>c.name===this._options.defaultWmsLayers);l&&(this._wmsLayersSelect.value=l.name)}this._wmsStatusEl&&(this._wmsStatusEl.textContent=`${r.length} layers available`,this._wmsStatusEl.style.color="#22c55e",setTimeout(()=>{this._wmsStatusEl&&(this._wmsStatusEl.style.display="none")},3e3))}catch(t){if(t.name==="AbortError")return;this._wmsStatusEl&&(this._wmsStatusEl.textContent="Failed to fetch layers",this._wmsStatusEl.style.color="#e74c3c")}}_buildWmsUrl(e,t){if(e.includes("{bbox-epsg-3857}"))return e;const n=new URL(e),i=n.searchParams;return i.has("service")||i.set("service","WMS"),i.has("request")||i.set("request","GetMap"),i.has("version")||i.set("version","1.1.1"),t&&!i.has("layers")&&i.set("layers",t),i.has("styles")||i.set("styles",""),i.has("format")||i.set("format","image/png"),i.has("transparent")||i.set("transparent","true"),i.has("width")||i.set("width","256"),i.has("height")||i.set("height","256"),i.has("srs")||i.set("srs","EPSG:3857"),`${n.toString()}&bbox={bbox-epsg-3857}`}_emit(e,t){const n=this._eventHandlers.get(e);if(!n)return;const i={type:e,state:this.getState(),layer:t};n.forEach(s=>s(i))}},E2=class{type="cog";cogControl;layerInfoMap=new Map;changeCallbacks=[];constructor(e){this.cogControl=e,this.cogControl.on("layeradd",t=>{const n=t.layerId;if(n){const i=t.state?.layers?.find(r=>r.id===n);let s=i?.name||n;if(!i?.name&&t.url)try{s=new URL(t.url).pathname.split("/").pop()||n}catch{s=t.url}this.layerInfoMap.set(n,{id:n,name:s,visible:!0,opacity:t.state?.layerOpacity??1}),this.notifyLayerAdded(n)}}),this.cogControl.on("layerremove",t=>{const n=t.layerId;n&&(this.layerInfoMap.delete(n),this.notifyLayerRemoved(n))}),this.syncFromControlState()}syncFromControlState(){const e=this.cogControl.getState();if(e.layers&&Array.isArray(e.layers))for(const t of e.layers){let n=t.name||t.id;if(!t.name&&t.url)try{n=new URL(t.url).pathname.split("/").pop()||t.id}catch{n=t.url}this.layerInfoMap.set(t.id,{id:t.id,name:n,visible:!0,opacity:t.opacity??1})}}getLayerIds(){return Array.from(this.layerInfoMap.keys())}getLayerState(e){const t=this.layerInfoMap.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}setVisibility(e,t){const n=this.layerInfoMap.get(e);n&&(n.visible=t,this.cogControl.setLayerVisibility(e,t,n.opacity))}setOpacity(e,t){const n=this.layerInfoMap.get(e);n&&(n.opacity=t,n.visible&&this.cogControl.setLayerOpacity(e,t))}getName(e){return this.layerInfoMap.get(e)?.name??e}getSymbolType(e){return"raster"}getBounds(e){return this.layerInfoMap.get(e)?.bounds??null}removeLayer(e){this.cogControl.removeLayer(e)}notifyLayerAdded(e){this.changeCallbacks.forEach(t=>t("add",e))}notifyLayerRemoved(e){this.changeCallbacks.forEach(t=>t("remove",e))}onLayerChange(e){return this.changeCallbacks.push(e),()=>{const t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}}},C2=class{type="zarr";zarrControl;layerInfoMap=new Map;changeCallbacks=[];constructor(e){this.zarrControl=e,this.zarrControl.on("layeradd",t=>{const n=t.layerId;if(n){const i=this.zarrControl.getState().layers.find(r=>r.id===n);let s=i?.name||n;if(!i?.name&&t.url)try{const r=new URL(t.url).pathname.split("/").pop()||"",a=i?.variable||"";s=a?`${r} / ${a}`:r}catch{s=t.url}this.layerInfoMap.set(n,{id:n,name:s,visible:!0,opacity:t.state?.layerOpacity??1}),this.notifyLayerAdded(n)}}),this.zarrControl.on("layerremove",t=>{const n=t.layerId;n&&(this.layerInfoMap.delete(n),this.notifyLayerRemoved(n))}),this.syncFromControlState()}syncFromControlState(){const e=this.zarrControl.getState();if(e.layers&&Array.isArray(e.layers))for(const t of e.layers){let n=t.name||t.id;if(!t.name&&t.url)try{const i=new URL(t.url).pathname.split("/").pop()||"";n=t.variable?`${i} / ${t.variable}`:i}catch{n=t.url}this.layerInfoMap.set(t.id,{id:t.id,name:n,visible:!0,opacity:t.opacity??1})}}getLayerIds(){return Array.from(this.layerInfoMap.keys())}getLayerState(e){const t=this.layerInfoMap.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}setVisibility(e,t){const n=this.layerInfoMap.get(e);n&&(n.visible=t,this.zarrControl.setLayerVisibility(e,t,n.opacity))}setOpacity(e,t){const n=this.layerInfoMap.get(e);n&&(n.opacity=t,n.visible&&this.zarrControl.setLayerOpacity(e,t))}getName(e){return this.layerInfoMap.get(e)?.name??e}getSymbolType(e){return"raster"}removeLayer(e){this.zarrControl.removeLayer(e)}notifyLayerAdded(e){this.changeCallbacks.forEach(t=>t("add",e))}notifyLayerRemoved(e){this.changeCallbacks.forEach(t=>t("remove",e))}onLayerChange(e){return this.changeCallbacks.push(e),()=>{const t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}}},w2=class{type="pmtiles";_control;_groups=new Map;_changeCallbacks=[];constructor(e){this._control=e,this._control.on("layeradd",()=>{setTimeout(()=>this._rebuildGroups(),50)}),this._control.on("layerremove",()=>{setTimeout(()=>this._rebuildGroups(),50)})}_rebuildGroups(){const e=new Set(this._groups.keys()),t=new Map;for(const n of this._control.getState().layers){const i=n.id;if(n.sourceLayers&&n.sourceLayers.length>0)for(const s of n.sourceLayers){const r=`${i}-${s}`,a=`${i}-${s}-`,o=n.layerIds.filter(l=>l.startsWith(a));o.length>0&&t.set(r,{name:s.charAt(0).toUpperCase()+s.slice(1),sublayers:o,visible:!0,opacity:n.opacity})}else{const s=n.name||this._extractFilename(n.url);t.set(i,{name:s,sublayers:[...n.layerIds],visible:!0,opacity:n.opacity})}}for(const n of t.keys())e.has(n)||this._changeCallbacks.forEach(i=>i("add",n));for(const n of e)t.has(n)||this._changeCallbacks.forEach(i=>i("remove",n));this._groups=t}_extractFilename(e){try{return new URL(e).pathname.split("/").pop()||e}catch{return e}}getLayerIds(){return Array.from(this._groups.keys())}getLayerState(e){const t=this._groups.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}getName(e){return this._groups.get(e)?.name??e}getSymbolType(e){return"fill"}setVisibility(e,t){const n=this._groups.get(e);if(n){n.visible=t;for(const i of n.sublayers)this._control.setLayerVisibility(i,t)}}setOpacity(e,t){const n=this._groups.get(e);if(n){n.opacity=t;for(const i of n.sublayers)this._control.setLayerOpacity(i,t)}}getNativeLayerIds(e){const t=this._groups.get(e);return t?[...t.sublayers]:[]}removeLayer(e){}onLayerChange(e){return this._changeCallbacks.push(e),()=>{const t=this._changeCallbacks.indexOf(e);t>=0&&this._changeCallbacks.splice(t,1)}}hasLayers(){return this._control.getState().hasLayer}},S2=class{type="addvector";_control;_options;_changeCallbacks=[];constructor(e,t){this._control=e,this._options=t||{},this._control.on("layeradd",n=>{n.layerId&&this._changeCallbacks.forEach(i=>i("add",n.layerId))}),this._control.on("layerremove",n=>{n.layerId&&this._changeCallbacks.forEach(i=>i("remove",n.layerId))})}getControl(){return this._control}getLayerIds(){return this._control.getLayerIds()}getLayerState(e){const t=this._control.getLayerVisibility(e),n=this._control.getLayerOpacity(e);return n===null?null:{visible:t,opacity:n,name:this.getName(e)}}getName(e){const t=e.split("-");if(t.length>=3){const n=t[t.length-1];return`${this._options.name||"Vector"} (${n})`}return this._options.name||e}setVisibility(e,t){this._control.setLayerVisibility(e,t)}setOpacity(e,t){this._control.setLayerOpacity(e,t)}onLayerChange(e){return this._changeCallbacks.push(e),()=>{const t=this._changeCallbacks.indexOf(e);t>=0&&this._changeCallbacks.splice(t,1)}}hasLayers(){return this._control.getState().hasLayer}getMetadata(){const e=this._control.getState();return{layerCount:e.layerCount,layers:e.layers.map(t=>({id:t.id,url:t.url,format:t.format,featureCount:t.featureCount,geometryTypes:t.geometryTypes}))}}},I2=class{type="stac";stacControl;layerInfoMap=new Map;changeCallbacks=[];constructor(e){this.stacControl=e,this.stacControl.on("layeradd",t=>{const n=t.layerId;if(n){let i=t.layerName||n;if(!t.layerName){if(t.assetKey)i=`STAC: ${t.assetKey}`;else if(t.url)try{i=new URL(t.url).pathname.split("/").pop()||n}catch{i=t.url}}this.layerInfoMap.set(n,{id:n,name:i,visible:!0,opacity:t.state?.layerOpacity??1}),this.notifyLayerAdded(n)}}),this.stacControl.on("layerremove",t=>{const n=t.layerId;n&&(this.layerInfoMap.delete(n),this.notifyLayerRemoved(n))}),this.syncFromControlState()}syncFromControlState(){const e=this.stacControl.getLayerIds();for(const t of e){const n=this.stacControl.getLayerOpacity(t);this.layerInfoMap.set(t,{id:t,name:t,visible:n!==null&&n>0,opacity:n??1})}}getLayerIds(){return Array.from(this.layerInfoMap.keys())}getLayerState(e){const t=this.layerInfoMap.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}setVisibility(e,t){const n=this.layerInfoMap.get(e);n&&(n.visible=t,this.stacControl.setLayerVisibility(e,t,n.opacity))}setOpacity(e,t){const n=this.layerInfoMap.get(e);n&&(n.opacity=t,n.visible&&this.stacControl.setLayerOpacity(e,t))}getName(e){return this.layerInfoMap.get(e)?.name??e}getSymbolType(e){return"raster"}removeLayer(e){this.stacControl.removeLayer(e)}notifyLayerAdded(e){this.changeCallbacks.forEach(t=>t("add",e))}notifyLayerRemoved(e){this.changeCallbacks.forEach(t=>t("remove",e))}onLayerChange(e){return this.changeCallbacks.push(e),()=>{const t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}}},$i=63710088e-1,M2={centimeters:$i*100,centimetres:$i*100,degrees:360/(2*Math.PI),feet:$i*3.28084,inches:$i*39.37,kilometers:$i/1e3,kilometres:$i/1e3,meters:$i,metres:$i,miles:$i/1609.344,millimeters:$i*1e3,millimetres:$i*1e3,nauticalmiles:$i/1852,radians:1,yards:$i*1.0936};function or(e,t,n={}){const i={type:"Feature"};return(n.id===0||n.id)&&(i.id=n.id),n.bbox&&(i.bbox=n.bbox),i.properties=t||{},i.geometry=e,i}function wi(e,t,n={}){if(!e)throw new Error("coordinates is required");if(!Array.isArray(e))throw new Error("coordinates must be an Array");if(e.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!rS(e[0])||!rS(e[1]))throw new Error("coordinates must contain numbers");return or({type:"Point",coordinates:e},t,n)}function Hr(e,t,n={}){for(const i of e){if(i.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(i[i.length-1].length!==i[0].length)throw new Error("First and last Position are not equivalent.");for(let s=0;s<i[i.length-1].length;s++)if(i[i.length-1][s]!==i[0][s])throw new Error("First and last Position are not equivalent.")}return or({type:"Polygon",coordinates:e},t,n)}function xs(e,t,n={}){if(e.length<2)throw new Error("coordinates must be an array of two or more positions");return or({type:"LineString",coordinates:e},t,n)}function Kt(e,t={}){const n={type:"FeatureCollection"};return t.id&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.features=e,n}function T2(e,t,n={}){return or({type:"MultiLineString",coordinates:e},t,n)}function mA(e,t,n={}){return or({type:"MultiPolygon",coordinates:e},t,n)}function TE(e,t="kilometers"){const n=M2[t];if(!n)throw new Error(t+" units is invalid");return e*n}function L2(e,t="kilometers"){const n=M2[t];if(!n)throw new Error(t+" units is invalid");return e/n}function A_(e){return e%(2*Math.PI)*180/Math.PI}function Qs(e){return e%360*Math.PI/180}function B2(e,t="kilometers",n="kilometers"){if(!(e>=0))throw new Error("length must be a positive number");return TE(L2(e,t),n)}function rS(e){return!isNaN(e)&&e!==null&&!Array.isArray(e)}function bf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Si(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if(e.type==="Feature"&&e.geometry!==null&&e.geometry.type==="Point")return[...e.geometry.coordinates];if(e.type==="Point")return[...e.coordinates]}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return[...e];throw new Error("coord must be GeoJSON Point or an Array of numbers")}function as(e){if(Array.isArray(e))return e;if(e.type==="Feature"){if(e.geometry!==null)return e.geometry.coordinates}else if(e.coordinates)return e.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $r(e){return e.type==="Feature"?e.geometry:e}function v_(e,t){return e.type==="FeatureCollection"?"FeatureCollection":e.type==="GeometryCollection"?"GeometryCollection":e.type==="Feature"&&e.geometry!==null?e.geometry.type:e.type}function R2(e,t,n={}){if(n.final===!0)return gz(e,t);const i=Si(e),s=Si(t),r=Qs(i[0]),a=Qs(s[0]),o=Qs(i[1]),l=Qs(s[1]),c=Math.sin(a-r)*Math.cos(l),h=Math.cos(o)*Math.sin(l)-Math.sin(o)*Math.cos(l)*Math.cos(a-r);return A_(Math.atan2(c,h))}function gz(e,t){let n=R2(t,e);return n=(n+180)%360,n}function dp(e,t,n={}){var i=Si(e),s=Si(t),r=Qs(s[1]-i[1]),a=Qs(s[0]-i[0]),o=Qs(i[1]),l=Qs(s[1]),c=Math.pow(Math.sin(r/2),2)+Math.pow(Math.sin(a/2),2)*Math.cos(o)*Math.cos(l);return TE(2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c)),n.units)}function _z(e,t,n={}){let i;return n.final?i=aS(Si(t),Si(e)):i=aS(Si(e),Si(t)),i>180?-(360-i):i}function aS(e,t){const n=Qs(e[1]),i=Qs(t[1]);let s=Qs(t[0]-e[0]);s>Math.PI&&(s-=2*Math.PI),s<-Math.PI&&(s+=2*Math.PI);const r=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(A_(Math.atan2(s,r))+360)%360}function Ql(e,t,n){if(e!==null)for(var i,s,r,a,o,l,c,h=0,d=0,f,m=e.type,A=m==="FeatureCollection",y=m==="Feature",x=A?e.features.length:1,v=0;v<x;v++){c=A?e.features[v].geometry:y?e.geometry:e,f=c?c.type==="GeometryCollection":!1,o=f?c.geometries.length:1;for(var b=0;b<o;b++){var w=0,S=0;if(a=f?c.geometries[b]:c,a!==null){l=a.coordinates;var R=a.type;switch(h=n&&(R==="Polygon"||R==="MultiPolygon")?1:0,R){case null:break;case"Point":if(t(l,d,v,w,S)===!1)return!1;d++,w++;break;case"LineString":case"MultiPoint":for(i=0;i<l.length;i++){if(t(l[i],d,v,w,S)===!1)return!1;d++,R==="MultiPoint"&&w++}R==="LineString"&&w++;break;case"Polygon":case"MultiLineString":for(i=0;i<l.length;i++){for(s=0;s<l[i].length-h;s++){if(t(l[i][s],d,v,w,S)===!1)return!1;d++}R==="MultiLineString"&&w++,R==="Polygon"&&S++}R==="Polygon"&&w++;break;case"MultiPolygon":for(i=0;i<l.length;i++){for(S=0,s=0;s<l[i].length;s++){for(r=0;r<l[i][s].length-h;r++){if(t(l[i][s][r],d,v,w,S)===!1)return!1;d++}S++}w++}break;case"GeometryCollection":for(i=0;i<a.geometries.length;i++)if(Ql(a.geometries[i],t,n)===!1)return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function Po(e,t){if(e.type==="Feature")t(e,0);else if(e.type==="FeatureCollection")for(var n=0;n<e.features.length&&t(e.features[n],n)!==!1;n++);}function Az(e,t,n){var i=n;return Po(e,function(s,r){r===0&&n===void 0?i=s:i=t(i,s,r)}),i}function vz(e){var t=[];return Ql(e,function(n){t.push(n)}),t}function Gl(e,t){var n,i,s,r,a,o,l,c,h,d,f=0,m=e.type==="FeatureCollection",A=e.type==="Feature",y=m?e.features.length:1;for(n=0;n<y;n++){for(o=m?e.features[n].geometry:A?e.geometry:e,c=m?e.features[n].properties:A?e.properties:{},h=m?e.features[n].bbox:A?e.bbox:void 0,d=m?e.features[n].id:A?e.id:void 0,l=o?o.type==="GeometryCollection":!1,a=l?o.geometries.length:1,s=0;s<a;s++){if(r=l?o.geometries[s]:o,r===null){if(t(null,f,c,h,d)===!1)return!1;continue}switch(r.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(t(r,f,c,h,d)===!1)return!1;break;case"GeometryCollection":for(i=0;i<r.geometries.length;i++)if(t(r.geometries[i],f,c,h,d)===!1)return!1;break;default:throw new Error("Unknown Geometry Type")}}f++}}function yz(e,t,n){var i=n;return Gl(e,function(s,r,a,o,l){i=t(i,s,r,a,o,l)}),i}function Do(e,t){Gl(e,function(n,i,s,r,a){var o=n===null?null:n.type;switch(o){case null:case"Point":case"LineString":case"Polygon":return t(or(n,s,{bbox:r,id:a}),i,0)===!1?!1:void 0}var l;switch(o){case"MultiPoint":l="Point";break;case"MultiLineString":l="LineString";break;case"MultiPolygon":l="Polygon";break}for(var c=0;c<n.coordinates.length;c++){var h=n.coordinates[c];if(t(or({type:l,coordinates:h},s),i,c)===!1)return!1}})}function Qd(e,t){Do(e,function(n,i,s){var r=0;if(n.geometry){var a=n.geometry.type;if(!(a==="Point"||a==="MultiPoint")){var o,l=0,c=0,h=0;if(Ql(n,function(d,f,m,A,y){if(o===void 0||i>l||A>c||y>h){o=d,l=i,c=A,h=y,r=0;return}if(t(xs([o,d],n.properties),i,s,y,r)===!1)return!1;r++,o=d})===!1)return!1}}})}function y_(e){return yz(e,(t,n)=>t+bz(n),0)}function bz(e){let t=0,n;switch(e.type){case"Polygon":return oS(e.coordinates);case"MultiPolygon":for(n=0;n<e.coordinates.length;n++)t+=oS(e.coordinates[n]);return t;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0}return 0}function oS(e){let t=0;if(e&&e.length>0){t+=Math.abs(lS(e[0]));for(let n=1;n<e.length;n++)t-=Math.abs(lS(e[n]))}return t}var xz=$i*$i/2,bv=Math.PI/180;function lS(e){const t=e.length-1;if(t<=2)return 0;let n=0,i=0;for(;i<t;){const s=e[i],r=e[i+1===t?0:i+1],a=e[i+2>=t?(i+2)%t:i+2],o=s[0]*bv,l=r[1]*bv,c=a[0]*bv;n+=(c-o)*Math.sin(l),i++}return n*xz}function si(e,t={}){if(e.bbox!=null&&t.recompute!==!0)return e.bbox;const n=[1/0,1/0,-1/0,-1/0];return Ql(e,i=>{n[0]>i[0]&&(n[0]=i[0]),n[1]>i[1]&&(n[1]=i[1]),n[2]<i[0]&&(n[2]=i[0]),n[3]<i[1]&&(n[3]=i[1])}),n}function Ez(e,t,n){var i=e.length,s=ru(e[0],t),r=[],a,o,l;let c,h;for(n||(n=[]),a=1;a<i;a++){for(c=e[a-1],h=e[a],o=l=ru(h,t);;)if(s|o){if(s&o)break;s?(c=nb(c,h,s,t),s=ru(c,t)):(h=nb(c,h,o,t),o=ru(h,t))}else{r.push(c),o!==l?(r.push(h),a<i-1&&(n.push(r),r=[])):a===i-1&&r.push(h);break}s=l}return r.length&&n.push(r),n}function Cz(e,t){var n,i,s,r,a,o,l;for(i=1;i<=8;i*=2){for(n=[],s=e[e.length-1],r=!(ru(s,t)&i),a=0;a<e.length;a++)o=e[a],l=!(ru(o,t)&i),l!==r&&n.push(nb(s,o,i,t)),l&&n.push(o),s=o,r=l;if(e=n,!e.length)break}return n}function nb(e,t,n,i){return n&8?[e[0]+(t[0]-e[0])*(i[3]-e[1])/(t[1]-e[1]),i[3]]:n&4?[e[0]+(t[0]-e[0])*(i[1]-e[1])/(t[1]-e[1]),i[1]]:n&2?[i[2],e[1]+(t[1]-e[1])*(i[2]-e[0])/(t[0]-e[0])]:n&1?[i[0],e[1]+(t[1]-e[1])*(i[0]-e[0])/(t[0]-e[0])]:null}function ru(e,t){var n=0;return e[0]<t[0]?n|=1:e[0]>t[2]&&(n|=2),e[1]<t[1]?n|=4:e[1]>t[3]&&(n|=8),n}function wz(e,t){const n=$r(e),i=n.type,s=e.type==="Feature"?e.properties:{};let r=n.coordinates;switch(i){case"LineString":case"MultiLineString":{const a=[];return i==="LineString"&&(r=[r]),r.forEach(o=>{Ez(o,t,a)}),a.length===1?xs(a[0],s):T2(a,s)}case"Polygon":return Hr(cS(r,t),s);case"MultiPolygon":return mA(r.map(a=>cS(a,t)),s);default:throw new Error("geometry "+i+" not supported")}}function cS(e,t){const n=[];for(const i of e){const s=Cz(i,t);s.length>0&&((s[0][0]!==s[s.length-1][0]||s[0][1]!==s[s.length-1][1])&&s.push(s[0]),s.length>=4&&n.push(s))}return n}var Np=11102230246251565e-32,fs=134217729,Sz=3.000000000000001*Np;function xv(e,t,n,i,s){let r,a,o,l,c=t[0],h=i[0],d=0,f=0;h>c==h>-c?(r=c,c=t[++d]):(r=h,h=i[++f]);let m=0;if(d<e&&f<n)for(h>c==h>-c?(a=c+r,o=r-(a-c),c=t[++d]):(a=h+r,o=r-(a-h),h=i[++f]),r=a,o!==0&&(s[m++]=o);d<e&&f<n;)h>c==h>-c?(a=r+c,l=a-r,o=r-(a-l)+(c-l),c=t[++d]):(a=r+h,l=a-r,o=r-(a-l)+(h-l),h=i[++f]),r=a,o!==0&&(s[m++]=o);for(;d<e;)a=r+c,l=a-r,o=r-(a-l)+(c-l),c=t[++d],r=a,o!==0&&(s[m++]=o);for(;f<n;)a=r+h,l=a-r,o=r-(a-l)+(h-l),h=i[++f],r=a,o!==0&&(s[m++]=o);return(r!==0||m===0)&&(s[m++]=r),m}function Iz(e,t){let n=t[0];for(let i=1;i<e;i++)n+=t[i];return n}function xf(e){return new Float64Array(e)}var Mz=3.0000000000000018*Np,Tz=2.0000000000000013*Np,Lz=9.000000000000007*Np*Np,nh=xf(4),hS=xf(8),uS=xf(12),dS=xf(16),Ls=xf(4);function Bz(e,t,n,i,s,r,a){let o,l,c,h,d,f,m,A,y,x,v,b,w,S,R,k,L,T;const C=e-s,I=n-s,M=t-r,U=i-r;S=C*U,f=fs*C,m=f-(f-C),A=C-m,f=fs*U,y=f-(f-U),x=U-y,R=A*x-(S-m*y-A*y-m*x),k=M*I,f=fs*M,m=f-(f-M),A=M-m,f=fs*I,y=f-(f-I),x=I-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,nh[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,nh[1]=w-(v+d)+(d-k),T=b+v,d=T-b,nh[2]=b-(T-d)+(v-d),nh[3]=T;let N=Iz(4,nh),D=Tz*a;if(N>=D||-N>=D||(d=e-C,o=e-(C+d)+(d-s),d=n-I,c=n-(I+d)+(d-s),d=t-M,l=t-(M+d)+(d-r),d=i-U,h=i-(U+d)+(d-r),o===0&&l===0&&c===0&&h===0)||(D=Lz*a+Sz*Math.abs(N),N+=C*h+U*o-(M*c+I*l),N>=D||-N>=D))return N;S=o*U,f=fs*o,m=f-(f-o),A=o-m,f=fs*U,y=f-(f-U),x=U-y,R=A*x-(S-m*y-A*y-m*x),k=l*I,f=fs*l,m=f-(f-l),A=l-m,f=fs*I,y=f-(f-I),x=I-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,Ls[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,Ls[1]=w-(v+d)+(d-k),T=b+v,d=T-b,Ls[2]=b-(T-d)+(v-d),Ls[3]=T;const P=xv(4,nh,4,Ls,hS);S=C*h,f=fs*C,m=f-(f-C),A=C-m,f=fs*h,y=f-(f-h),x=h-y,R=A*x-(S-m*y-A*y-m*x),k=M*c,f=fs*M,m=f-(f-M),A=M-m,f=fs*c,y=f-(f-c),x=c-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,Ls[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,Ls[1]=w-(v+d)+(d-k),T=b+v,d=T-b,Ls[2]=b-(T-d)+(v-d),Ls[3]=T;const O=xv(P,hS,4,Ls,uS);return S=o*h,f=fs*o,m=f-(f-o),A=o-m,f=fs*h,y=f-(f-h),x=h-y,R=A*x-(S-m*y-A*y-m*x),k=l*c,f=fs*l,m=f-(f-l),A=l-m,f=fs*c,y=f-(f-c),x=c-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,Ls[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,Ls[1]=w-(v+d)+(d-k),T=b+v,d=T-b,Ls[2]=b-(T-d)+(v-d),Ls[3]=T,dS[xv(O,uS,4,Ls,dS)-1]}function Rz(e,t,n,i,s,r){const a=(t-r)*(n-s),o=(e-s)*(i-r),l=a-o,c=Math.abs(a+o);return Math.abs(l)>=Mz*c?l:-Bz(e,t,n,i,s,r,c)}function kz(e,t){var n,i,s=0,r,a,o,l,c,h,d,f=e[0],m=e[1],A=t.length;for(n=0;n<A;n++){i=0;var y=t[n],x=y.length-1;if(h=y[0],h[0]!==y[x][0]&&h[1]!==y[x][1])throw new Error("First and last coordinates in a ring must be the same");for(a=h[0]-f,o=h[1]-m;i<x;i++){if(d=y[i+1],l=d[0]-f,c=d[1]-m,o===0&&c===0){if(l<=0&&a>=0||a<=0&&l>=0)return 0}else if(c>=0&&o<=0||c<=0&&o>=0){if(r=Rz(a,l,o,c,0,0),r===0)return 0;(r>0&&c>0&&o<=0||r<0&&c<=0&&o>0)&&s++}h=d,o=c,a=l}}return s%2!==0}function Ii(e,t,n={}){if(!e)throw new Error("point is required");if(!t)throw new Error("polygon is required");const i=Si(e),s=$r(t),r=s.type,a=t.bbox;let o=s.coordinates;if(a&&Nz(i,a)===!1)return!1;r==="Polygon"&&(o=[o]);let l=!1;for(var c=0;c<o.length;++c){const h=kz(i,o[c]);if(h===0)return!n.ignoreBoundary;h&&(l=!0)}return l}function Nz(e,t){return t[0]<=e[0]&&t[1]<=e[1]&&t[2]>=e[0]&&t[3]>=e[1]}function Gs(e,t,n={}){const i=Si(e),s=as(t);for(let r=0;r<s.length-1;r++){let a=!1;if(n.ignoreEndVertices&&(r===0&&(a="start"),r===s.length-2&&(a="end"),r===0&&r+1===s.length-1&&(a="both")),Pz(s[r],s[r+1],i,a,typeof n.epsilon>"u"?null:n.epsilon))return!0}return!1}function Pz(e,t,n,i,s){const r=n[0],a=n[1],o=e[0],l=e[1],c=t[0],h=t[1],d=n[0]-o,f=n[1]-l,m=c-o,A=h-l,y=d*A-f*m;if(s!==null){if(Math.abs(y)>s)return!1}else if(y!==0)return!1;if(Math.abs(m)===Math.abs(A)&&Math.abs(m)===0)return i?!1:n[0]===e[0]&&n[1]===e[1];if(i){if(i==="start")return Math.abs(m)>=Math.abs(A)?m>0?o<r&&r<=c:c<=r&&r<o:A>0?l<a&&a<=h:h<=a&&a<l;if(i==="end")return Math.abs(m)>=Math.abs(A)?m>0?o<=r&&r<c:c<r&&r<=o:A>0?l<=a&&a<h:h<a&&a<=l;if(i==="both")return Math.abs(m)>=Math.abs(A)?m>0?o<r&&r<c:c<r&&r<o:A>0?l<a&&a<h:h<a&&a<l}else return Math.abs(m)>=Math.abs(A)?m>0?o<=r&&r<=c:c<=r&&r<=o:A>0?l<=a&&a<=h:h<=a&&a<=l;return!1}function Dz(e,t,n,i,s){k2(e,t,n||0,i||e.length-1,s||Fz)}function k2(e,t,n,i,s){for(;i>n;){if(i-n>600){var r=i-n+1,a=t-n+1,o=Math.log(r),l=.5*Math.exp(2*o/3),c=.5*Math.sqrt(o*l*(r-l)/r)*(a-r/2<0?-1:1);k2(e,t,Math.max(n,Math.floor(t-a*l/r+c)),Math.min(i,Math.floor(t+(r-a)*l/r+c)),s)}var h=e[t],d=n,f=i;for(dd(e,n,t),s(e[i],h)>0&&dd(e,n,i);d<f;){for(dd(e,d,f),d++,f--;s(e[d],h)<0;)d++;for(;s(e[f],h)>0;)f--}s(e[n],h)===0?dd(e,n,f):(f++,dd(e,f,i)),f<=t&&(n=f+1),t<=f&&(i=f-1)}}function dd(e,t,n){var i=e[t];e[t]=e[n],e[n]=i}function Fz(e,t){return e<t?-1:e>t?1:0}var LE=class{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(t){let n=this.data;const i=[];if(!Zf(t,n))return i;const s=this.toBBox,r=[];for(;n;){for(let a=0;a<n.children.length;a++){const o=n.children[a],l=n.leaf?s(o):o;Zf(t,l)&&(n.leaf?i.push(o):Cv(t,l)?this._all(o,i):r.push(o))}n=r.pop()}return i}collides(t){let n=this.data;if(!Zf(t,n))return!1;const i=[];for(;n;){for(let s=0;s<n.children.length;s++){const r=n.children[s],a=n.leaf?this.toBBox(r):r;if(Zf(t,a)){if(n.leaf||Cv(t,a))return!0;i.push(r)}}n=i.pop()}return!1}load(t){if(!(t&&t.length))return this;if(t.length<this._minEntries){for(let i=0;i<t.length;i++)this.insert(t[i]);return this}let n=this._build(t.slice(),0,t.length-1,0);if(!this.data.children.length)this.data=n;else if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const i=this.data;this.data=n,n=i}this._insert(n,this.data.height-n.height-1,!0)}return this}insert(t){return t&&this._insert(t,this.data.height-1),this}clear(){return this.data=Xh([]),this}remove(t,n){if(!t)return this;let i=this.data;const s=this.toBBox(t),r=[],a=[];let o,l,c;for(;i||r.length;){if(i||(i=r.pop(),l=r[r.length-1],o=a.pop(),c=!0),i.leaf){const h=Oz(t,i.children,n);if(h!==-1)return i.children.splice(h,1),r.push(i),this._condense(r),this}!c&&!i.leaf&&Cv(i,s)?(r.push(i),a.push(o),o=0,l=i,i=i.children[0]):l?(o++,i=l.children[o],c=!1):i=null}return this}toBBox(t){return t}compareMinX(t,n){return t.minX-n.minX}compareMinY(t,n){return t.minY-n.minY}toJSON(){return this.data}fromJSON(t){return this.data=t,this}_all(t,n){const i=[];for(;t;)t.leaf?n.push(...t.children):i.push(...t.children),t=i.pop();return n}_build(t,n,i,s){const r=i-n+1;let a=this._maxEntries,o;if(r<=a)return o=Xh(t.slice(n,i+1)),ih(o,this.toBBox),o;s||(s=Math.ceil(Math.log(r)/Math.log(a)),a=Math.ceil(r/Math.pow(a,s-1))),o=Xh([]),o.leaf=!1,o.height=s;const l=Math.ceil(r/a),c=l*Math.ceil(Math.sqrt(a));pS(t,n,i,c,this.compareMinX);for(let h=n;h<=i;h+=c){const d=Math.min(h+c-1,i);pS(t,h,d,l,this.compareMinY);for(let f=h;f<=d;f+=l){const m=Math.min(f+l-1,d);o.children.push(this._build(t,f,m,s-1))}}return ih(o,this.toBBox),o}_chooseSubtree(t,n,i,s){for(;s.push(n),!(n.leaf||s.length-1===i);){let r=1/0,a=1/0,o;for(let l=0;l<n.children.length;l++){const c=n.children[l],h=Ev(c),d=Qz(t,c)-h;d<a?(a=d,r=h<r?h:r,o=c):d===a&&h<r&&(r=h,o=c)}n=o||n.children[0]}return n}_insert(t,n,i){const s=i?t:this.toBBox(t),r=[],a=this._chooseSubtree(s,this.data,n,r);for(a.children.push(t),Hd(a,s);n>=0&&r[n].children.length>this._maxEntries;)this._split(r,n),n--;this._adjustParentBBoxes(s,r,n)}_split(t,n){const i=t[n],s=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,s);const a=this._chooseSplitIndex(i,r,s),o=Xh(i.children.splice(a,i.children.length-a));o.height=i.height,o.leaf=i.leaf,ih(i,this.toBBox),ih(o,this.toBBox),n?t[n-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,n){this.data=Xh([t,n]),this.data.height=t.height+1,this.data.leaf=!1,ih(this.data,this.toBBox)}_chooseSplitIndex(t,n,i){let s,r=1/0,a=1/0;for(let o=n;o<=i-n;o++){const l=Gd(t,0,o,this.toBBox),c=Gd(t,o,i,this.toBBox),h=Gz(l,c),d=Ev(l)+Ev(c);h<r?(r=h,s=o,a=d<a?d:a):h===r&&d<a&&(a=d,s=o)}return s||i-n}_chooseSplitAxis(t,n,i){const s=t.leaf?this.compareMinX:Uz,r=t.leaf?this.compareMinY:zz;this._allDistMargin(t,n,i,s)<this._allDistMargin(t,n,i,r)&&t.children.sort(s)}_allDistMargin(t,n,i,s){t.children.sort(s);const r=this.toBBox,a=Gd(t,0,n,r),o=Gd(t,i-n,i,r);let l=Xf(a)+Xf(o);for(let c=n;c<i-n;c++){const h=t.children[c];Hd(a,t.leaf?r(h):h),l+=Xf(a)}for(let c=i-n-1;c>=n;c--){const h=t.children[c];Hd(o,t.leaf?r(h):h),l+=Xf(o)}return l}_adjustParentBBoxes(t,n,i){for(let s=i;s>=0;s--)Hd(n[s],t)}_condense(t){for(let n=t.length-1,i;n>=0;n--)t[n].children.length===0?n>0?(i=t[n-1].children,i.splice(i.indexOf(t[n]),1)):this.clear():ih(t[n],this.toBBox)}};function Oz(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function ih(e,t){Gd(e,0,e.children.length,t,e)}function Gd(e,t,n,i,s){s||(s=Xh(null)),s.minX=1/0,s.minY=1/0,s.maxX=-1/0,s.maxY=-1/0;for(let r=t;r<n;r++){const a=e.children[r];Hd(s,e.leaf?i(a):a)}return s}function Hd(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Uz(e,t){return e.minX-t.minX}function zz(e,t){return e.minY-t.minY}function Ev(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function Xf(e){return e.maxX-e.minX+(e.maxY-e.minY)}function Qz(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function Gz(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),s=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return Math.max(0,s-n)*Math.max(0,r-i)}function Cv(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Zf(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Xh(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function pS(e,t,n,i,s){const r=[t,n];for(;r.length;){if(n=r.pop(),t=r.pop(),n-t<=i)continue;const a=t+Math.ceil((n-t)/i/2)*i;Dz(e,a,t,n,s),r.push(t,a,a,n)}}function wv(e){var t;if(e.bbox)t=e.bbox;else if(Array.isArray(e)&&e.length===4)t=e;else if(Array.isArray(e)&&e.length===6)t=[e[0],e[1],e[3],e[4]];else if(e.type==="Feature")t=si(e);else if(e.type==="FeatureCollection")t=si(e);else throw new Error("invalid geojson");return{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}}var Hz=class{constructor(e=9){this.tree=new LE(e),this.tree.toBBox=wv}insert(e){if(e.type!=="Feature")throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:si(e),this.tree.insert(e),this}load(e){var t=[];return Array.isArray(e)?e.forEach(function(n){if(n.type!=="Feature")throw new Error("invalid features");n.bbox=n.bbox?n.bbox:si(n),t.push(n)}):Po(e,function(n){if(n.type!=="Feature")throw new Error("invalid features");n.bbox=n.bbox?n.bbox:si(n),t.push(n)}),this.tree.load(t),this}remove(e,t){if(e.type!=="Feature")throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:si(e),this.tree.remove(e,t),this}clear(){return this.tree.clear(),this}search(e){return Kt(this.tree.search(wv(e)))}collides(e){return this.tree.collides(wv(e))}all(){return Kt(this.tree.all())}toJSON(){return this.tree.toJSON()}fromJSON(e){return this.tree.fromJSON(e),this}};function BE(e){return new Hz(e)}function $z(e,t){if(t=t??{},!bf(t))throw new Error("options is invalid");var n=t.precision,i=t.coordinates,s=t.mutate;if(n=n==null||isNaN(n)?6:n,i=i==null||isNaN(i)?3:i,!e)throw new Error("<geojson> is required");if(typeof n!="number")throw new Error("<precision> must be a number");if(typeof i!="number")throw new Error("<coordinates> must be a number");(s===!1||s===void 0)&&(e=JSON.parse(JSON.stringify(e)));var r=Math.pow(10,n);return Ql(e,function(a){Vz(a,r,i)}),e}function Vz(e,t,n){e.length>n&&e.splice(n,e.length);for(var i=0;i<e.length;i++)e[i]=Math.round(e[i]*t)/t;return e}function N2(e){if(!e)throw new Error("geojson is required");const t=[];return Do(e,n=>{qz(n,t)}),Kt(t)}function qz(e,t){let n=[];const i=e.geometry;if(i!==null){switch(i.type){case"Polygon":n=as(i);break;case"LineString":n=[as(i)]}n.forEach(s=>{Wz(s,e.properties).forEach(r=>{r.id=t.length,t.push(r)})})}}function Wz(e,t){const n=[];return e.reduce((i,s)=>{const r=xs([i,s],t);return r.bbox=Yz(i,s),n.push(r),s}),n}function Yz(e,t){const n=e[0],i=e[1],s=t[0],r=t[1];return[n<s?n:s,i<r?i:r,n>s?n:s,i>r?i:r]}var P2=class{constructor(e=[],t=jz){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this.length++,this._up(this.length-1)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return this.length--,this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,i=t[e];for(;e>0;){const s=e-1>>1,r=t[s];if(n(i,r)>=0)break;t[e]=r,e=s}t[e]=i}_down(e){const{data:t,compare:n}=this,i=this.length>>1,s=t[e];for(;e<i;){let r=(e<<1)+1,a=t[r];const o=r+1;if(o<this.length&&n(t[o],a)<0&&(r=o,a=t[o]),n(a,s)>=0)break;t[e]=a,e=r}t[e]=s}};function jz(e,t){return e<t?-1:e>t?1:0}function D2(e,t){return e.p.x>t.p.x?1:e.p.x<t.p.x?-1:e.p.y!==t.p.y?e.p.y>t.p.y?1:-1:1}function Xz(e,t){return e.rightSweepEvent.p.x>t.rightSweepEvent.p.x?1:e.rightSweepEvent.p.x<t.rightSweepEvent.p.x?-1:e.rightSweepEvent.p.y!==t.rightSweepEvent.p.y?e.rightSweepEvent.p.y<t.rightSweepEvent.p.y?1:-1:1}var fS=class{constructor(e,t,n,i){this.p={x:e[0],y:e[1]},this.featureId=t,this.ringId=n,this.eventId=i,this.otherEvent=null,this.isLeftEndpoint=null}isSamePoint(e){return this.p.x===e.p.x&&this.p.y===e.p.y}};function Zz(e,t){if(e.type==="FeatureCollection"){const n=e.features;for(let i=0;i<n.length;i++)mS(n[i],t)}else mS(e,t)}var Jf=0,Kf=0,em=0;function mS(e,t){const n=e.type==="Feature"?e.geometry:e;let i=n.coordinates;(n.type==="Polygon"||n.type==="MultiLineString")&&(i=[i]),n.type==="LineString"&&(i=[[i]]);for(let s=0;s<i.length;s++)for(let r=0;r<i[s].length;r++){let a=i[s][r][0],o=null;Kf=Kf+1;for(let l=0;l<i[s][r].length-1;l++){o=i[s][r][l+1];const c=new fS(a,Jf,Kf,em),h=new fS(o,Jf,Kf,em+1);c.otherEvent=h,h.otherEvent=c,D2(c,h)>0?(h.isLeftEndpoint=!0,c.isLeftEndpoint=!1):(c.isLeftEndpoint=!0,h.isLeftEndpoint=!1),t.push(c),t.push(h),a=o,em=em+1}}Jf=Jf+1}var Jz=class{constructor(t){this.leftSweepEvent=t,this.rightSweepEvent=t.otherEvent}};function Kz(e,t){if(e===null||t===null||e.leftSweepEvent.ringId===t.leftSweepEvent.ringId&&(e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.rightSweepEvent)||e.leftSweepEvent.isSamePoint(t.leftSweepEvent)||e.leftSweepEvent.isSamePoint(t.rightSweepEvent)))return!1;const n=e.leftSweepEvent.p.x,i=e.leftSweepEvent.p.y,s=e.rightSweepEvent.p.x,r=e.rightSweepEvent.p.y,a=t.leftSweepEvent.p.x,o=t.leftSweepEvent.p.y,l=t.rightSweepEvent.p.x,c=t.rightSweepEvent.p.y,h=(c-o)*(s-n)-(l-a)*(r-i),d=(l-a)*(i-o)-(c-o)*(n-a),f=(s-n)*(i-o)-(r-i)*(n-a);if(h===0)return!1;const m=d/h,A=f/h;return m>=0&&m<=1&&A>=0&&A<=1?[n+m*(s-n),i+m*(r-i)]:!1}function eQ(e,t){t=t||!1;const n=[],i=new P2([],Xz);for(;e.length;){const s=e.pop();if(s.isLeftEndpoint){const r=new Jz(s);for(let a=0;a<i.data.length;a++){const o=i.data[a];if(t&&o.leftSweepEvent.featureId===s.featureId)continue;const l=Kz(r,o);l!==!1&&n.push(l)}i.push(r)}else s.isLeftEndpoint===!1&&i.pop()}return n}function tQ(e,t){const n=new P2([],D2);return Zz(e,n),eQ(n,t)}var nQ=tQ;function ju(e,t,n={}){const{removeDuplicates:i=!0,ignoreSelfIntersections:s=!0}=n;let r=[];e.type==="FeatureCollection"?r=r.concat(e.features):e.type==="Feature"?r.push(e):(e.type==="LineString"||e.type==="Polygon"||e.type==="MultiLineString"||e.type==="MultiPolygon")&&r.push(or(e)),t.type==="FeatureCollection"?r=r.concat(t.features):t.type==="Feature"?r.push(t):(t.type==="LineString"||t.type==="Polygon"||t.type==="MultiLineString"||t.type==="MultiPolygon")&&r.push(or(t));const a=nQ(Kt(r),s);let o=[];if(i){const l={};a.forEach(c=>{const h=c.join(",");l[h]||(l[h]=!0,o.push(c))})}else o=a;return Kt(o.map(l=>wi(l)))}var iQ=Object.defineProperty,sQ=Object.defineProperties,rQ=Object.getOwnPropertyDescriptors,gS=Object.getOwnPropertySymbols,aQ=Object.prototype.hasOwnProperty,oQ=Object.prototype.propertyIsEnumerable,_S=(e,t,n)=>t in e?iQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lQ=(e,t)=>{for(var n in t||(t={}))aQ.call(t,n)&&_S(e,n,t[n]);if(gS)for(var n of gS(t))oQ.call(t,n)&&_S(e,n,t[n]);return e},cQ=(e,t)=>sQ(e,rQ(t));function au(e,t,n={}){if(!e||!t)throw new Error("lines and inputPoint are required arguments");const i=Si(t);let s=wi([1/0,1/0],{lineStringIndex:-1,segmentIndex:-1,totalDistance:-1,lineDistance:-1,segmentDistance:-1,pointDistance:1/0,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),r=0,a=0,o=-1;return Do(e,function(l,c,h){o!==h&&(o=h,a=0);const d=as(l);for(let f=0;f<d.length-1;f++){const m=wi(d[f]),A=Si(m),y=wi(d[f+1]),x=Si(y),v=dp(m,y,n);let b,w;x[0]===i[0]&&x[1]===i[1]?[b,w]=[x,!0]:A[0]===i[0]&&A[1]===i[1]?[b,w]=[A,!1]:[b,w]=dQ(A,x,i);const S=dp(t,b,n);if(S<s.properties.pointDistance){const R=dp(m,b,n);s=wi(b,{lineStringIndex:h,segmentIndex:w?f+1:f,totalDistance:r+R,lineDistance:a+R,segmentDistance:R,pointDistance:S,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),s.properties=cQ(lQ({},s.properties),{multiFeatureIndex:s.properties.lineStringIndex,index:s.properties.segmentIndex,location:s.properties.totalDistance,dist:s.properties.pointDistance})}r+=v,a+=v}}),s}function Zl(e,t){const[n,i,s]=e,[r,a,o]=t;return n*r+i*a+s*o}function pd(e,t){const[n,i,s]=e,[r,a,o]=t;return[i*o-s*a,s*r-n*o,n*a-i*r]}function hQ(e){return Math.sqrt(Math.pow(e[0],2)+Math.pow(e[1],2)+Math.pow(e[2],2))}function AS(e){const t=hQ(e);return[e[0]/t,e[1]/t,e[2]/t]}function Sv(e){const t=Qs(e[1]),n=Qs(e[0]);return[Math.cos(t)*Math.cos(n),Math.cos(t)*Math.sin(n),Math.sin(t)]}function uQ(e){const[t,n,i]=e,s=A_(Math.asin(Math.min(Math.max(i,-1),1)));return[A_(Math.atan2(n,t)),s]}function dQ(e,t,n){const i=Sv(e),s=Sv(t),r=Sv(n),a=pd(i,s);if(a[0]===0&&a[1]===0&&a[2]===0)return Zl(i,s)>0?[[...t],!0]:[[...n],!1];const o=pd(a,r);if(o[0]===0&&o[1]===0&&o[2]===0)return[[...t],!0];const l=AS(pd(o,a)),c=[-l[0],-l[1],-l[2]],h=Zl(r,l)>Zl(r,c)?l:c,d=AS(a),f=Zl(pd(i,h),d),m=Zl(pd(h,s),d);return f>=0&&m>=0?[uQ(h),!1]:Zl(i,r)>Zl(s,r)?[[...e],!1]:[[...t],!0]}function RE(e,t){if(!e)throw new Error("line is required");if(!t)throw new Error("splitter is required");const n=v_(e),i=v_(t);if(n!=="LineString")throw new Error("line must be LineString");if(i==="FeatureCollection")throw new Error("splitter cannot be a FeatureCollection");if(i==="GeometryCollection")throw new Error("splitter cannot be a GeometryCollection");var s=$z(t,{precision:7});switch(e.type!=="Feature"&&(e=or(e)),i){case"Point":return ib(e,s);case"MultiPoint":return vS(e,s);case"LineString":case"MultiLineString":case"Polygon":case"MultiPolygon":return vS(e,ju(e,s,{ignoreSelfIntersections:!0}))}}function vS(e,t){var n=[],i=BE();return Do(t,function(s){if(n.forEach(function(o,l){o.id=l}),!n.length)n=ib(e,s).features,i.load(Kt(n));else{var r=i.search(s);if(r.features.length){var a=F2(s,r);n=n.filter(function(o){return o.id!==a.id}),i.remove(a),Po(ib(a,s),function(o){n.push(o),i.insert(o)})}}}),Kt(n)}function ib(e,t){var n=[],i=as(e)[0],s=as(e)[e.geometry.coordinates.length-1];if(Iv(i,Si(t))||Iv(s,Si(t)))return Kt([e]);var r=BE(),a=N2(e);r.load(a);var o=r.search(t);if(!o.features.length)return Kt([e]);var l=F2(t,o),c=Az(a,function(h,d,f){var m=as(d)[1],A=Si(t);return f===l.id?(h.push(A),n.push(xs(h)),Iv(A,m)?[A]:[A,m]):(h.push(m),h)},[i]);return c.length>1&&n.push(xs(c)),Kt(n)}function F2(e,t){if(!t.features.length)throw new Error("lines must contain features");if(t.features.length===1)return t.features[0];var n,i=1/0;return Po(t,function(s){var r=au(s,e).properties.dist;r<i&&(n=s,i=r)}),n}function Iv(e,t){return e[0]===t[0]&&e[1]===t[1]}function yS(e,t){const n=$r(e),i=$r(t),s=n.type,r=i.type,a=n.coordinates,o=i.coordinates;switch(s){case"Point":if(r==="Point")return NE(a,o);throw new Error("feature2 "+r+" geometry not supported");case"MultiPoint":switch(r){case"Point":return mQ(n,i);case"MultiPoint":return gQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"LineString":switch(r){case"Point":return Gs(i,n,{ignoreEndVertices:!0});case"LineString":return vQ(n,i);case"MultiPoint":return _Q(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"Polygon":switch(r){case"Point":return Ii(i,n,{ignoreBoundary:!0});case"LineString":return bQ(n,i);case"Polygon":return kE(n,i);case"MultiPoint":return AQ(n,i);case"MultiPolygon":return fQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"MultiPolygon":if(r==="Polygon")return pQ(n,i);throw new Error("feature2 "+r+" geometry not supported");default:throw new Error("feature1 "+s+" geometry not supported")}}function pQ(e,t){return e.coordinates.some(n=>kE({type:"Polygon",coordinates:n},t))}function fQ(e,t){return t.coordinates.every(n=>kE(e,{type:"Polygon",coordinates:n}))}function mQ(e,t){let n,i=!1;for(n=0;n<e.coordinates.length;n++)if(NE(e.coordinates[n],t.coordinates)){i=!0;break}return i}function gQ(e,t){for(const n of t.coordinates){let i=!1;for(const s of e.coordinates)if(NE(n,s)){i=!0;break}if(!i)return!1}return!0}function _Q(e,t){let n=!1;for(const i of t.coordinates)if(Gs(i,e,{ignoreEndVertices:!0})&&(n=!0),!Gs(i,e))return!1;return!!n}function AQ(e,t){for(const n of t.coordinates)if(!Ii(n,e,{ignoreBoundary:!0}))return!1;return!0}function vQ(e,t){let n=!1;for(const i of t.coordinates)if(Gs({type:"Point",coordinates:i},e,{ignoreEndVertices:!0})&&(n=!0),!Gs({type:"Point",coordinates:i},e,{ignoreEndVertices:!1}))return!1;return n}function yQ(e,t){const n=e.coordinates,i=[];for(let s=0;s<n.length-1;s++){const r=xs([n[s],n[s+1]]),a=RE(r,or(t));a.features.length===0?i.push(r):i.push(...a.features)}return Kt(i)}function bQ(e,t){if(!O2(si(e),si(t)))return!1;for(const s of t.coordinates)if(!Ii(s,e))return!1;let n=!1;const i=yQ(t,e);for(const s of i.features){const r=xQ(s.geometry.coordinates[0],s.geometry.coordinates[1]);if(!Ii(r,e))return!1;!n&&Ii(r,e,{ignoreBoundary:!0})&&(n=!0)}return n}function kE(e,t){if(e.type==="Feature"&&e.geometry===null||t.type==="Feature"&&t.geometry===null||!O2(si(e),si(t)))return!1;const n=$r(t).coordinates;for(const i of n)for(const s of i)if(!Ii(s,e))return!1;return!0}function O2(e,t){return!(e[0]>t[0]||e[2]<t[2]||e[1]>t[1]||e[3]<t[3])}function NE(e,t){return e[0]===t[0]&&e[1]===t[1]}function xQ(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function b_(e,t={}){const n=$r(e);switch(!t.properties&&e.type==="Feature"&&(t.properties=e.properties),n.type){case"Polygon":return EQ(n,t);case"MultiPolygon":return CQ(n,t);default:throw new Error("invalid poly")}}function EQ(e,t={}){const n=$r(e).coordinates;return U2(n,t.properties?t.properties:e.type==="Feature"?e.properties:{})}function CQ(e,t={}){const n=$r(e).coordinates,i=t.properties?t.properties:e.type==="Feature"?e.properties:{},s=[];return n.forEach(r=>{s.push(U2(r,i))}),Kt(s)}function U2(e,t){return e.length>1?T2(e,t):xs(e[0],t)}var wQ=Object.defineProperty,Xu=(e,t)=>wQ(e,"name",{value:t,configurable:!0}),z2=class{constructor(t){this.direction=!1,this.compareProperties=!0;var n,i,s;this.precision=10**-((n=t?.precision)!=null?n:17),this.direction=(i=t?.direction)!=null?i:!1,this.compareProperties=(s=t?.compareProperties)!=null?s:!0}compare(t,n){if(t.type!==n.type||!$d(t,n))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,n.coordinates);case"LineString":return this.compareLine(t.coordinates,n.coordinates);case"Polygon":return this.comparePolygon(t,n);case"GeometryCollection":return this.compareGeometryCollection(t,n);case"Feature":return this.compareFeature(t,n);case"FeatureCollection":return this.compareFeatureCollection(t,n);default:if(t.type.startsWith("Multi")){const i=sb(t),s=sb(n);return i.every(r=>s.some(a=>this.compare(r,a)))}}return!1}compareCoord(t,n){return t.length===n.length&&t.every((i,s)=>Math.abs(i-n[s])<this.precision)}compareLine(t,n,i=0,s=!1){if(!$d(t,n))return!1;const r=t;let a=n;if(s&&!this.compareCoord(r[0],a[0])){const l=this.fixStartIndex(a,r);if(l)a=l;else return!1}const o=this.compareCoord(r[i],a[i]);return this.direction||o?this.comparePath(r,a):this.compareCoord(r[i],a[a.length-(1+i)])?this.comparePath(r.slice().reverse(),a):!1}fixStartIndex(t,n){let i,s=-1;for(let r=0;r<t.length;r++)if(this.compareCoord(t[r],n[0])){s=r;break}return s>=0&&(i=[].concat(t.slice(s,t.length),t.slice(1,s+1))),i}comparePath(t,n){return t.every((i,s)=>this.compareCoord(i,n[s]))}comparePolygon(t,n){if(this.compareLine(t.coordinates[0],n.coordinates[0],1,!0)){const i=t.coordinates.slice(1,t.coordinates.length),s=n.coordinates.slice(1,n.coordinates.length);return i.every(r=>s.some(a=>this.compareLine(r,a,1,!0)))}return!1}compareGeometryCollection(t,n){return $d(t.geometries,n.geometries)&&this.compareBBox(t,n)&&t.geometries.every((i,s)=>this.compare(i,n.geometries[s]))}compareFeature(t,n){return t.id===n.id&&(this.compareProperties?PE(t.properties,n.properties):!0)&&this.compareBBox(t,n)&&this.compare(t.geometry,n.geometry)}compareFeatureCollection(t,n){return $d(t.features,n.features)&&this.compareBBox(t,n)&&t.features.every((i,s)=>this.compare(i,n.features[s]))}compareBBox(t,n){return!t.bbox&&!n.bbox||(t.bbox&&n.bbox?this.compareCoord(t.bbox,n.bbox):!1)}};Xu(z2,"GeojsonEquality");var SQ=z2;function $d(e,t){return e.coordinates?e.coordinates.length===t.coordinates.length:e.length===t.length}Xu($d,"sameLength");function sb(e){return e.coordinates.map(t=>({type:e.type.replace("Multi",""),coordinates:t}))}Xu(sb,"explode");function Q2(e,t,n){return new SQ(n).compare(e,t)}Xu(Q2,"geojsonEquality");function PE(e,t){if(e===null&&t===null)return!0;if(e===null||t===null)return!1;const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(var s of n){const r=e[s],a=t[s],o=bS(r)&&bS(a);if(o&&!PE(r,a)||!o&&r!==a)return!1}return!0}Xu(PE,"equal");var bS=Xu(e=>e!=null&&typeof e=="object","isObject");function G2(e,t={}){var n=typeof t=="object"?t.mutate:t;if(!e)throw new Error("geojson is required");var i=v_(e),s=[];switch(i){case"LineString":s=Mv(e,i);break;case"MultiLineString":case"Polygon":as(e).forEach(function(a){s.push(Mv(a,i))});break;case"MultiPolygon":as(e).forEach(function(a){var o=[];a.forEach(function(l){o.push(Mv(l,i))}),s.push(o)});break;case"Point":return e;case"MultiPoint":var r={};as(e).forEach(function(a){var o=a.join("-");Object.prototype.hasOwnProperty.call(r,o)||(s.push(a),r[o]=!0)});break;default:throw new Error(i+" geometry not supported")}return e.coordinates?n===!0?(e.coordinates=s,e):{type:i,coordinates:s}:n===!0?(e.geometry.coordinates=s,e):or({type:i,coordinates:s},e.properties,{bbox:e.bbox,id:e.id})}function Mv(e,t){const n=as(e);if(n.length===2&&!xS(n[0],n[1]))return n;const i=[];let s=0,r=1,a=2;for(i.push(n[s]);a<n.length;)Gs(n[r],xs([n[s],n[a]]))?r=a:(i.push(n[r]),s=r,r++,a=r),a++;if(i.push(n[r]),t==="Polygon"||t==="MultiPolygon"){if(Gs(i[0],xs([i[1],i[i.length-2]]))&&(i.shift(),i.pop(),i.push(i[0])),i.length<4)throw new Error("invalid polygon, fewer than 4 points");if(!xS(i[0],i[i.length-1]))throw new Error("invalid polygon, first and last points not equal")}return i}function xS(e,t){return e[0]===t[0]&&e[1]===t[1]}function IQ(e,t,{ignoreSelfIntersections:n=!0}={ignoreSelfIntersections:!0}){let i=!0;return Do(e,s=>{Do(t,r=>{if(i===!1)return!1;i=MQ(s.geometry,r.geometry,n)})}),i}function MQ(e,t,n){switch(e.type){case"Point":switch(t.type){case"Point":return!RQ(e.coordinates,t.coordinates);case"LineString":return!ES(t,e);case"Polygon":return!Ii(e,t)}break;case"LineString":switch(t.type){case"Point":return!ES(e,t);case"LineString":return!TQ(e,t,n);case"Polygon":return!CS(t,e,n)}break;case"Polygon":switch(t.type){case"Point":return!Ii(t,e);case"LineString":return!CS(e,t,n);case"Polygon":return!LQ(t,e,n)}}return!1}function ES(e,t){for(let n=0;n<e.coordinates.length-1;n++)if(BQ(e.coordinates[n],e.coordinates[n+1],t.coordinates))return!0;return!1}function TQ(e,t,n){return ju(e,t,{ignoreSelfIntersections:n}).features.length>0}function CS(e,t,n){for(const i of t.coordinates)if(Ii(i,e))return!0;return ju(t,b_(e),{ignoreSelfIntersections:n}).features.length>0}function LQ(e,t,n){for(const i of e.coordinates[0])if(Ii(i,t))return!0;for(const i of t.coordinates[0])if(Ii(i,e))return!0;return ju(b_(e),b_(t),{ignoreSelfIntersections:n}).features.length>0}function BQ(e,t,n){const i=n[0]-e[0],s=n[1]-e[1],r=t[0]-e[0],a=t[1]-e[1];return i*a-s*r!==0?!1:Math.abs(r)>=Math.abs(a)?r>0?e[0]<=n[0]&&n[0]<=t[0]:t[0]<=n[0]&&n[0]<=e[0]:a>0?e[1]<=n[1]&&n[1]<=t[1]:t[1]<=n[1]&&n[1]<=e[1]}function RQ(e,t){return e[0]===t[0]&&e[1]===t[1]}function DE(e,t,{ignoreSelfIntersections:n=!0}={}){let i=!1;return Do(e,s=>{Do(t,r=>{if(i===!0)return!0;i=!IQ(s.geometry,r.geometry,{ignoreSelfIntersections:n})})}),i}function H2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tv,wS;function kQ(){return wS||(wS=1,Tv=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var i,s,r;if(Array.isArray(t)){if(i=t.length,i!=n.length)return!1;for(s=i;s--!==0;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(r=Object.keys(t),i=r.length,i!==Object.keys(n).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,r[s]))return!1;for(s=i;s--!==0;){var a=r[s];if(!e(t[a],n[a]))return!1}return!0}return t!==t&&n!==n}),Tv}var Vd=H2(kQ());function NQ(e,t,n={}){if(n=n||{},!bf(n))throw new Error("options is invalid");var i=n.tolerance||0,s=[],r=BE();const a=N2(e);r.load(a);var o;let l=[];return Qd(t,function(c){var h=!1;c&&(Po(r.search(c),function(d){if(h===!1){var f=as(c).sort(),m=as(d).sort();if(Vd(f,m))h=!0,o?o=Lv(o,c)||o:o=c;else if(i===0?Gs(f[0],d)&&Gs(f[1],d):au(d,f[0]).properties.dist<=i&&au(d,f[1]).properties.dist<=i)h=!0,o?o=Lv(o,c)||o:o=c;else if(i===0?Gs(m[0],c)&&Gs(m[1],c):au(c,m[0]).properties.dist<=i&&au(c,m[1]).properties.dist<=i)if(o){const A=Lv(o,d);A?o=A:l.push(d)}else o=d}}),h===!1&&o&&(s.push(o),l.length&&(s=s.concat(l),l=[]),o=void 0))}),o&&s.push(o),Kt(s)}function Lv(e,t){var n=as(t),i=as(e),s=i[0],r=i[i.length-1],a=e.geometry.coordinates;if(Vd(n[0],s))a.unshift(n[1]);else if(Vd(n[0],r))a.push(n[1]);else if(Vd(n[1],s))a.unshift(n[0]);else if(Vd(n[1],r))a.push(n[0]);else return;return e}function $2(e,t){const n=$r(e),i=$r(t),s=n.type,r=i.type;if(s==="MultiPoint"&&r!=="MultiPoint"||(s==="LineString"||s==="MultiLineString")&&r!=="LineString"&&r!=="MultiLineString"||(s==="Polygon"||s==="MultiPolygon")&&r!=="Polygon"&&r!=="MultiPolygon")throw new Error("features must be of the same type");if(s==="Point")throw new Error("Point geometry not supported");if(Q2(e,t,{precision:6}))return!1;let a=0;switch(s){case"MultiPoint":for(var o=0;o<n.coordinates.length;o++)for(var l=0;l<i.coordinates.length;l++){var c=n.coordinates[o],h=i.coordinates[l];if(c[0]===h[0]&&c[1]===h[1])return!0}return!1;case"LineString":case"MultiLineString":Qd(e,d=>{Qd(t,f=>{NQ(d,f).features.length&&a++})});break;case"Polygon":case"MultiPolygon":Qd(e,d=>{Qd(t,f=>{ju(d,f).features.length&&a++})});break}return a>0}function PQ(e,t){var n=$r(e),i=$r(t),s=n.type,r=i.type;switch(s){case"Point":switch(r){case"MultiPoint":return DQ(n,i);case"LineString":return Gs(n,i,{ignoreEndVertices:!0});case"Polygon":case"MultiPolygon":return Ii(n,i,{ignoreBoundary:!0});default:throw new Error("feature2 "+r+" geometry not supported")}case"MultiPoint":switch(r){case"MultiPoint":return FQ(n,i);case"LineString":return OQ(n,i);case"Polygon":case"MultiPolygon":return UQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"LineString":switch(r){case"LineString":return zQ(n,i);case"Polygon":case"MultiPolygon":return GQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"Polygon":switch(r){case"Polygon":case"MultiPolygon":return HQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}default:throw new Error("feature1 "+s+" geometry not supported")}}function DQ(e,t){var n,i=!1;for(n=0;n<t.coordinates.length;n++)if(q2(t.coordinates[n],e.coordinates)){i=!0;break}return i}function FQ(e,t){for(var n=0;n<e.coordinates.length;n++){for(var i=!1,s=0;s<t.coordinates.length;s++)q2(e.coordinates[n],t.coordinates[s])&&(i=!0);if(!i)return!1}return!0}function OQ(e,t){for(var n=!1,i=0;i<e.coordinates.length;i++){if(!Gs(e.coordinates[i],t))return!1;n||(n=Gs(e.coordinates[i],t,{ignoreEndVertices:!0}))}return n}function UQ(e,t){for(var n=!0,i=!1,s=0;s<e.coordinates.length;s++){if(i=Ii(e.coordinates[s],t),!i){n=!1;break}i=Ii(e.coordinates[s],t,{ignoreBoundary:!0})}return n&&i}function zQ(e,t){for(var n=0;n<e.coordinates.length;n++)if(!Gs(e.coordinates[n],t))return!1;return!0}function QQ(e,t){const n=e.coordinates,i=[];for(let s=0;s<n.length-1;s++){const r=xs([n[s],n[s+1]]),a=RE(r,or(t));a.features.length===0?i.push(r):i.push(...a.features)}return Kt(i)}function GQ(e,t){if(!V2(si(t),si(e)))return!1;for(const s of e.coordinates)if(!Ii(s,t))return!1;let n=!1;const i=QQ(e,t);for(const s of i.features){const r=$Q(s.geometry.coordinates[0],s.geometry.coordinates[1]);if(!Ii(r,t))return!1;!n&&Ii(r,t,{ignoreBoundary:!0})&&(n=!0)}return n}function HQ(e,t){var n=si(e);if(!V2(si(t),n))return!1;for(var i=0;i<e.coordinates[0].length;i++)if(!Ii(e.coordinates[0][i],t))return!1;return!0}function V2(e,t){return!(e[0]>t[0]||e[2]<t[2]||e[1]>t[1]||e[3]<t[3])}function q2(e,t){return e[0]===t[0]&&e[1]===t[1]}function $Q(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function W2(e,t={}){const n=si(e);return wi([(n[0]+n[2])/2,(n[1]+n[3])/2],t.properties,t)}var zg={exports:{}},VQ=zg.exports,SS;function qQ(){return SS||(SS=1,(function(e,t){(function(n,i){e.exports=i()})(VQ,(function(){function n(_,u){(u==null||u>_.length)&&(u=_.length);for(var p=0,g=Array(u);p<u;p++)g[p]=_[p];return g}function i(_,u,p){return u=h(u),(function(g,E){if(E&&(typeof E=="object"||typeof E=="function"))return E;if(E!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return(function(B){if(B===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return B})(g)})(_,f()?Reflect.construct(u,p||[],h(_).constructor):u.apply(_,p))}function s(_,u){if(!(_ instanceof u))throw new TypeError("Cannot call a class as a function")}function r(_,u,p){if(f())return Reflect.construct.apply(null,arguments);var g=[null];g.push.apply(g,u);var E=new(_.bind.apply(_,g));return p&&m(E,p.prototype),E}function a(_,u){for(var p=0;p<u.length;p++){var g=u[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(_,x(g.key),g)}}function o(_,u,p){return u&&a(_.prototype,u),p&&a(_,p),Object.defineProperty(_,"prototype",{writable:!1}),_}function l(_,u){var p=typeof Symbol<"u"&&_[Symbol.iterator]||_["@@iterator"];if(!p){if(Array.isArray(_)||(p=v(_))||u){p&&(_=p);var g=0,E=function(){};return{s:E,n:function(){return g>=_.length?{done:!0}:{done:!1,value:_[g++]}},e:function(Y){throw Y},f:E}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
269
+ `,t.querySelector(".html-gui-close")?.addEventListener("click",()=>this._togglePanel()),e.appendChild(t);const n=document.createElement("div");n.className="html-gui-content";const i=this._createField("HTML Control");this._htmlSelect=document.createElement("select"),this._htmlSelect.className="html-gui-select",this._htmlSelect.addEventListener("change",()=>{this._selectHtmlControl(parseInt(this._htmlSelect.value,10))}),i.appendChild(this._htmlSelect),n.appendChild(i),this._renderHtmlSelect();const s=this._createField("Title");this._titleInput=document.createElement("input"),this._titleInput.type="text",this._titleInput.className="html-gui-input",this._titleInput.placeholder="Control title",this._titleInput.value=this._state.title,this._titleInput.addEventListener("input",()=>{this._state.title=this._titleInput.value}),s.appendChild(this._titleInput),n.appendChild(s);const r=this._createField("HTML Content");this._htmlTextarea=document.createElement("textarea"),this._htmlTextarea.className="html-gui-textarea",this._htmlTextarea.rows=6,this._htmlTextarea.value=this._state.html,this._htmlTextarea.placeholder="<div>Your HTML here...</div>",this._htmlTextarea.addEventListener("input",()=>{this._state.html=this._htmlTextarea.value,this._updatePreviewContent()}),r.appendChild(this._htmlTextarea),n.appendChild(r);const a=this._createField("Preview");this._previewEl=document.createElement("div"),this._previewEl.className="html-gui-preview",this._updatePreviewContent(),a.appendChild(this._previewEl),n.appendChild(a);const o=document.createElement("div");o.className="html-gui-row";const l=this._createField("Position");this._positionSelect=document.createElement("select"),this._positionSelect.className="html-gui-select",[{value:"top-left",label:"Top Left"},{value:"top-right",label:"Top Right"},{value:"bottom-left",label:"Bottom Left"},{value:"bottom-right",label:"Bottom Right"}].forEach(d=>{const f=document.createElement("option");f.value=d.value,f.textContent=d.label,f.selected=d.value===this._state.htmlPosition,this._positionSelect.appendChild(f)}),this._positionSelect.addEventListener("change",()=>{this._state.htmlPosition=this._positionSelect.value}),l.appendChild(this._positionSelect),o.appendChild(l);const c=this._createField("Options"),h=document.createElement("label");return h.className="html-gui-checkbox-label",this._collapsibleCheckbox=document.createElement("input"),this._collapsibleCheckbox.type="checkbox",this._collapsibleCheckbox.checked=this._state.collapsible,this._collapsibleCheckbox.addEventListener("change",()=>{this._state.collapsible=!!this._collapsibleCheckbox?.checked}),h.appendChild(this._collapsibleCheckbox),h.appendChild(document.createTextNode(" Collapsible")),c.appendChild(h),o.appendChild(c),n.appendChild(o),this._addBtn=document.createElement("button"),this._addBtn.type="button",this._addBtn.className="html-gui-add-btn",this._addBtn.textContent="Add HTML Control",this._addBtn.addEventListener("click",()=>this._addHtmlControl()),n.appendChild(this._addBtn),this._updateBtn=document.createElement("button"),this._updateBtn.type="button",this._updateBtn.className="html-gui-add-btn",this._updateBtn.textContent="Update Selected Control",this._updateBtn.style.display=this._state.hasHtmlControl?"":"none",this._updateBtn.addEventListener("click",()=>this._updateHtmlControl()),n.appendChild(this._updateBtn),this._removeBtn=document.createElement("button"),this._removeBtn.type="button",this._removeBtn.className="html-gui-remove-btn",this._removeBtn.textContent="Remove Control",this._removeBtn.style.display=this._state.hasHtmlControl?"":"none",this._removeBtn.addEventListener("click",()=>this._removeHtmlControl()),n.appendChild(this._removeBtn),e.appendChild(n),e}_createField(e){const t=document.createElement("div");t.className="html-gui-field";const n=document.createElement("label");return n.textContent=e,t.appendChild(n),t}_updatePreviewContent(){this._previewEl&&(this._previewEl.innerHTML=this._state.html)}_getFormEntry(){return{title:this._state.title,html:this._state.html,htmlPosition:this._state.htmlPosition,collapsible:this._state.collapsible}}_applyEntryToForm(e){this._state.title=e.title,this._state.html=e.html,this._state.htmlPosition=e.htmlPosition,this._state.collapsible=e.collapsible,this._titleInput&&(this._titleInput.value=e.title),this._htmlTextarea&&(this._htmlTextarea.value=e.html),this._positionSelect&&(this._positionSelect.value=e.htmlPosition),this._collapsibleCheckbox&&(this._collapsibleCheckbox.checked=e.collapsible),this._updatePreviewContent()}_createHtmlControl(e){return new $B({title:e.title,html:e.html,collapsible:e.collapsible,collapsed:!1})}_selectHtmlControl(e){if(e<0){this._state.selectedHtmlIndex=-1,this._htmlControl=void 0,this._updateButtonStates();return}e>=this._htmlEntries.length||(this._state.selectedHtmlIndex=e,this._htmlControl=this._htmlControls[e],this._applyEntryToForm(this._htmlEntries[e]),this._updateButtonStates())}_renderHtmlSelect(){if(!this._htmlSelect)return;this._htmlSelect.innerHTML="";const e=document.createElement("option");e.value="-1",e.textContent="New HTML control",this._htmlSelect.appendChild(e),this._htmlEntries.forEach((t,n)=>{const i=document.createElement("option");i.value=String(n),i.textContent=t.title||`HTML ${n+1}`,this._htmlSelect.appendChild(i)}),this._htmlSelect.value=this._state.selectedHtmlIndex>=0?String(this._state.selectedHtmlIndex):"-1"}_addHtmlControl(){if(!this._map)return;const e=this._getFormEntry(),t=this._createHtmlControl(e);this._map.addControl(t,e.htmlPosition),this._htmlControls.push(t),this._htmlEntries.push(e),this._htmlControl=t,this._state.hasHtmlControl=!0,this._state.selectedHtmlIndex=this._htmlControls.length-1,this._state.htmls=this._htmlEntries.map(n=>({...n})),this._updateButtonStates(),this._emit("htmladd")}_updateHtmlControl(){if(!this._map)return;const e=this._state.selectedHtmlIndex;if(e<0||e>=this._htmlControls.length){this._addHtmlControl();return}const t=this._getFormEntry();this._map.removeControl(this._htmlControls[e]);const n=this._createHtmlControl(t);this._map.addControl(n,t.htmlPosition),this._htmlControls[e]=n,this._htmlEntries[e]=t,this._htmlControl=n,this._state.htmls=this._htmlEntries.map(i=>({...i})),this._emit("htmlupdate"),this._updateButtonStates()}_removeHtmlControl(){if(!this._map)return;const e=this._state.selectedHtmlIndex;e<0||e>=this._htmlControls.length||(this._map.removeControl(this._htmlControls[e]),this._htmlControls.splice(e,1),this._htmlEntries.splice(e,1),this._state.hasHtmlControl=this._htmlControls.length>0,this._state.selectedHtmlIndex=this._state.hasHtmlControl?Math.min(e,this._htmlControls.length-1):-1,this._htmlControl=this._state.selectedHtmlIndex>=0?this._htmlControls[this._state.selectedHtmlIndex]:void 0,this._state.htmls=this._htmlEntries.map(t=>({...t})),this._state.selectedHtmlIndex>=0&&this._applyEntryToForm(this._htmlEntries[this._state.selectedHtmlIndex]),this._updateButtonStates(),this._emit("htmlremove"))}_updateButtonStates(){this._addBtn&&(this._addBtn.textContent="Add HTML Control");const e=this._state.selectedHtmlIndex>=0;this._updateBtn&&(this._updateBtn.style.display=e?"":"none"),this._removeBtn&&(this._removeBtn.style.display=e?"":"none"),this._renderHtmlSelect()}_removeAllHtmlControls(){this._map&&(this._htmlControls.forEach(e=>{this._map.removeControl(e)}),this._htmlControls=[],this._htmlEntries=[],this._htmlControl=void 0,this._state.hasHtmlControl=!1,this._state.selectedHtmlIndex=-1,this._state.htmls=[],this._updateButtonStates())}_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"),this._updatePanelHeight(),this._handleResize||(this._handleResize=()=>this._updatePanelHeight(),window.addEventListener("resize",this._handleResize))}_hidePanel(){this._handleResize&&(window.removeEventListener("resize",this._handleResize),this._handleResize=void 0),this._panel?.remove(),this._panel=void 0,this._button?.classList.remove("active")}_updatePanelHeight(){if(!this._panel)return;const e=16,t=200,n=this._panel.getBoundingClientRect().top,i=Math.max(t,window.innerHeight-n-e),s=this._options.maxHeight>0?Math.min(this._options.maxHeight,i):i;this._panel.style.maxHeight=`${s}px`}_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())}getHtmlControl(){return this._htmlControl}},hz={speed:10,spinOnLoad:!1,pauseOnInteraction:!0,collapsed:!0},sS=["dragstart","zoomstart","rotatestart","pitchstart","boxzoomstart","touchstart"],uz='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.636-6.364"/><polyline points="21 3 21 9 15 9"/></svg>',b2=class{_map;_container;_button;_panel;_options;_spinning=!1;_collapsed;_animationId;_lastTime;_eventHandlers=new Map;_speedInput;_speedValueEl;_toggleBtn;_onInteractionStart;_onDoubleClick;_wheelTarget;_doubleClickTimeoutId;constructor(e){this._options={...hz,...e},this._collapsed=this._options.collapsed}onAdd(e){if(this._map=e,this._container=document.createElement("div"),this._container.className="maplibregl-ctrl maplibregl-ctrl-group maplibre-gl-spin-globe-control",this._button=document.createElement("button"),this._button.type="button",this._button.title="Spin globe",this._button.setAttribute("aria-label","Spin globe"),this._button.setAttribute("aria-pressed","false"),this._button.innerHTML=uz,this._button.style.cssText="display:flex;align-items:center;justify-content:center;width:29px;height:29px;cursor:pointer;",this._button.addEventListener("click",()=>this._togglePanel()),this._container.appendChild(this._button),this._onDoubleClick=()=>this._startSpinAfterDoubleClick(),e.on("dblclick",this._onDoubleClick),this._options.pauseOnInteraction){this._onInteractionStart=()=>this._stopSpinForInteraction(),sS.forEach(n=>{e.on(n,this._onInteractionStart)});const t=e.getCanvas?.();t?.addEventListener&&(this._wheelTarget=t,t.addEventListener("wheel",this._onInteractionStart,{passive:!0}))}return this._options.spinOnLoad&&(e.isStyleLoaded()?this.startSpin():e.once("load",()=>this.startSpin())),this._collapsed||this._showPanel(),this._container}onRemove(){this.stopSpin(),this._doubleClickTimeoutId!==void 0&&(clearTimeout(this._doubleClickTimeoutId),this._doubleClickTimeoutId=void 0),this._map&&(this._onInteractionStart&&sS.forEach(e=>{this._map.off(e,this._onInteractionStart)}),this._onDoubleClick&&this._map.off("dblclick",this._onDoubleClick)),this._wheelTarget&&this._onInteractionStart&&this._wheelTarget.removeEventListener("wheel",this._onInteractionStart),this._container?.parentNode?.removeChild(this._container),this._map=void 0,this._container=void 0,this._button=void 0,this._panel=void 0,this._speedInput=void 0,this._speedValueEl=void 0,this._toggleBtn=void 0,this._onInteractionStart=void 0,this._onDoubleClick=void 0,this._wheelTarget=void 0,this._eventHandlers.clear()}startSpin(){this._spinning||(this._spinning=!0,this._lastTime=void 0,this._animationId=requestAnimationFrame(e=>this._animate(e)),this._updateButton(),this._updateToggleBtn(),this._emit("spinstart"))}stopSpin(){this._spinning&&(this._spinning=!1,this._animationId!==void 0&&(cancelAnimationFrame(this._animationId),this._animationId=void 0),this._lastTime=void 0,this._updateButton(),this._updateToggleBtn(),this._emit("spinstop"))}toggleSpin(){this._spinning?this.stopSpin():this.startSpin()}isSpinning(){return this._spinning}getState(){return{spinning:this._spinning,collapsed:this._collapsed}}update(e){this._options={...this._options,...e},e.speed!==void 0&&this._speedInput&&(this._speedInput.value=String(e.speed),this._speedValueEl&&(this._speedValueEl.textContent=`${e.speed}`))}expand(){this._collapsed&&(this._collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._collapsed||(this._collapsed=!0,this._hidePanel(),this._emit("collapse"))}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)}_togglePanel(){this._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._speedInput=void 0,this._speedValueEl=void 0,this._toggleBtn=void 0,this._button?.classList.remove("active")}_createPanel(){const e=document.createElement("div");e.className="spin-globe-panel",e.style.cssText="position:absolute;top:0;right:calc(100% + 0px);background:#fff;color:#000;border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.15);padding:12px;z-index:1;white-space:nowrap;min-width:180px;";const t=document.createElement("div");t.style.cssText="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;font-weight:600;font-size:13px;color:#000;",t.textContent="Spin Globe";const n=document.createElement("button");n.type="button",n.title="Close",n.setAttribute("aria-label","Close"),n.textContent="×",n.style.cssText="background:none;border:none;font-size:18px;cursor:pointer;color:#000;padding:0 0 0 8px;line-height:1;",n.addEventListener("click",()=>this.collapse()),t.appendChild(n),e.appendChild(t);const i=document.createElement("div");i.style.cssText="display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:12px;color:#000;";const s=document.createElement("label");s.textContent="Speed",s.style.cssText="flex-shrink:0;font-weight:500;",this._speedInput=document.createElement("input"),this._speedInput.type="range",this._speedInput.min="1",this._speedInput.max="60",this._speedInput.step="1",this._speedInput.value=String(this._options.speed),this._speedInput.style.cssText="flex:1;min-width:80px;cursor:pointer;accent-color:#2563eb;",this._speedValueEl=document.createElement("span"),this._speedValueEl.textContent=`${this._options.speed}`,this._speedValueEl.style.cssText="min-width:20px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums;";const r=document.createElement("span");return r.textContent="°/s",r.style.cssText="flex-shrink:0;color:#000;",this._speedInput.addEventListener("input",()=>{const a=Number(this._speedInput.value);this._options.speed=a,this._speedValueEl&&(this._speedValueEl.textContent=`${a}`)}),i.appendChild(s),i.appendChild(this._speedInput),i.appendChild(this._speedValueEl),i.appendChild(r),e.appendChild(i),this._toggleBtn=document.createElement("button"),this._toggleBtn.type="button",this._updateToggleBtn(),this._toggleBtn.style.cssText="width:100%;padding:6px 0;border:1px solid #333;border-radius:4px;background:#fff;font-size:12px;font-weight:500;color:#000;cursor:pointer;",this._toggleBtn.addEventListener("mouseenter",()=>{this._toggleBtn&&(this._toggleBtn.style.backgroundColor="#f0f0f0")}),this._toggleBtn.addEventListener("mouseleave",()=>{this._toggleBtn&&(this._toggleBtn.style.backgroundColor="#fff")}),this._toggleBtn.addEventListener("click",()=>this.toggleSpin()),e.appendChild(this._toggleBtn),e}_updateToggleBtn(){this._toggleBtn&&(this._toggleBtn.textContent=this._spinning?"Stop":"Start")}_animate(e){if(!(!this._spinning||!this._map)){if(this._lastTime!==void 0){const t=(e-this._lastTime)/1e3,n=this._map.getCenter();n.lng-=this._options.speed*t,this._map.jumpTo({center:n})}this._lastTime=e,this._animationId=requestAnimationFrame(t=>this._animate(t))}}_stopSpinForInteraction(){this._spinning&&this.stopSpin()}_startSpinAfterDoubleClick(){this._doubleClickTimeoutId!==void 0&&clearTimeout(this._doubleClickTimeoutId),this._doubleClickTimeoutId=setTimeout(()=>{this._doubleClickTimeoutId=void 0,this._map&&this.startSpin()},0)}_updateButton(){this._button&&(this._spinning?(this._button.style.backgroundColor="rgba(0, 120, 215, 0.15)",this._button.title="Stop globe spin",this._button.setAttribute("aria-label","Stop globe spin"),this._button.setAttribute("aria-pressed","true")):(this._button.style.backgroundColor="",this._button.title="Spin globe",this._button.setAttribute("aria-label","Spin globe"),this._button.setAttribute("aria-pressed","false")))}_emit(e){const t=this._eventHandlers.get(e);if(!t)return;const n={type:e,state:this.getState()};t.forEach(i=>i(n))}},dz={collapsed:!0,defaultType:"xyz",defaultUrl:"",defaultWmsUrl:"https://services.terrascope.be/wms/v2",defaultName:"",defaultWmsLayers:"",defaultOpacity:.8,tileSize:256,attribution:""},pz='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4 2 9l10 5 10-5-10-5z"/><path d="M2 15l10 5 10-5"/></svg>',fz='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',mz='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>',x2=class{_map;_container;_button;_panel;_options;_collapsed;_layers=[];_layerCounter=0;_eventHandlers=new Map;_typeSelect;_urlInput;_nameInput;_wmsLayersSelect;_wmsLayersRow;_wmsStatusEl;_opacityInput;_opacityValueEl;_layerListEl;_fetchDebounceTimer;_fetchController;constructor(e){this._options={...dz,...e},this._collapsed=this._options.collapsed}onAdd(e){return this._map=e,this._container=document.createElement("div"),this._container.className="maplibregl-ctrl maplibregl-ctrl-group maplibre-gl-tile-layer-control",this._button=document.createElement("button"),this._button.type="button",this._button.title="Tile Layer",this._button.setAttribute("aria-label","Tile Layer"),this._button.innerHTML=pz,this._button.style.cssText="display:flex;align-items:center;justify-content:center;width:29px;height:29px;cursor:pointer;",this._button.addEventListener("click",()=>this._togglePanel()),this._container.appendChild(this._button),this._collapsed||this._showPanel(),this._container}onRemove(){if(this._map)for(const e of[...this._layers])try{this._map.getLayer(e.id)&&this._map.removeLayer(e.id),this._map.getSource(e.id)&&this._map.removeSource(e.id)}catch{}this._layers=[],this._fetchController?.abort(),clearTimeout(this._fetchDebounceTimer),this._container?.parentNode?.removeChild(this._container),this._map=void 0,this._container=void 0,this._button=void 0,this._panel=void 0,this._typeSelect=void 0,this._urlInput=void 0,this._nameInput=void 0,this._wmsLayersSelect=void 0,this._wmsLayersRow=void 0,this._wmsStatusEl=void 0,this._opacityInput=void 0,this._opacityValueEl=void 0,this._layerListEl=void 0,this._eventHandlers.clear()}addTileLayer(e,t){if(!this._map||!e.trim())return null;++this._layerCounter;const n=t?.type??this._options.defaultType,i=t?.opacity??this._options.defaultOpacity,s=t?.name||`Tile Layer ${this._layerCounter}`;let r=s;(this._map.getSource(r)||this._layers.some(l=>l.id===r))&&(r=`${s}-${this._layerCounter}`);let a=e;n==="wms"&&(a=this._buildWmsUrl(e,t?.wmsLayers));const o={id:r,name:s,url:e,type:n,opacity:i,visible:!0,wmsLayers:t?.wmsLayers};try{this._map.addSource(r,{type:"raster",tiles:[a],tileSize:this._options.tileSize,...this._options.attribution?{attribution:this._options.attribution}:{}}),this._map.addLayer({id:r,type:"raster",source:r,paint:{"raster-opacity":i}})}catch(l){return console.error("Failed to add tile layer:",l),null}return this._layers.push(o),this._updateLayerList(),this._emit("layeradd",o),o}removeTileLayer(e){const t=this._layers.findIndex(i=>i.id===e);if(t===-1||!this._map)return;const n=this._layers[t];try{this._map.getLayer(e)&&this._map.removeLayer(e),this._map.getSource(e)&&this._map.removeSource(e)}catch{}this._layers.splice(t,1),this._updateLayerList(),this._emit("layerremove",n)}setLayerVisibility(e,t){const n=this._layers.find(i=>i.id===e);!n||!this._map||(n.visible=t,this._map.setLayoutProperty(e,"visibility",t?"visible":"none"),this._updateLayerList(),this._emit("layervisibility",n))}setLayerOpacity(e,t){const n=this._layers.find(i=>i.id===e);!n||!this._map||(n.opacity=t,this._map.setPaintProperty(e,"raster-opacity",t),this._emit("layeropacity",n))}getLayers(){return[...this._layers]}getState(){return{collapsed:this._collapsed,layers:[...this._layers]}}expand(){this._collapsed&&(this._collapsed=!1,this._showPanel(),this._emit("expand"))}collapse(){this._collapsed||(this._collapsed=!0,this._hidePanel(),this._emit("collapse"))}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)}_togglePanel(){this._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._fetchController?.abort(),clearTimeout(this._fetchDebounceTimer),this._panel?.remove(),this._panel=void 0,this._typeSelect=void 0,this._urlInput=void 0,this._nameInput=void 0,this._wmsLayersSelect=void 0,this._wmsLayersRow=void 0,this._wmsStatusEl=void 0,this._opacityInput=void 0,this._opacityValueEl=void 0,this._layerListEl=void 0,this._button?.classList.remove("active")}_createPanel(){const e=document.createElement("div");e.className="tile-layer-panel",e.style.cssText="position:absolute;top:0;right:calc(100% + 0px);background:#fff;color:#000;border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.15);padding:12px;z-index:1;white-space:nowrap;min-width:280px;";const t=document.createElement("div");t.style.cssText="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;font-weight:600;font-size:13px;color:#000;",t.textContent="Tile Layer";const n=document.createElement("button");n.type="button",n.title="Close",n.setAttribute("aria-label","Close"),n.textContent="×",n.style.cssText="background:none;border:none;font-size:18px;cursor:pointer;color:#000;padding:0 0 0 8px;line-height:1;",n.addEventListener("click",()=>this.collapse()),t.appendChild(n),e.appendChild(t);const i="display:flex;align-items:center;gap:8px;margin-bottom:8px;font-size:12px;color:#000;",s="flex-shrink:0;font-weight:500;min-width:70px;",r="flex:1;min-width:0;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px;color:#000;background:#fff;",a=document.createElement("div");a.style.cssText=i;const o=document.createElement("label");o.textContent="Type",o.style.cssText=s,this._typeSelect=document.createElement("select"),this._typeSelect.style.cssText="flex:1;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px;color:#000;background:#fff;cursor:pointer;";const l=document.createElement("option");l.value="xyz",l.textContent="XYZ";const c=document.createElement("option");c.value="wms",c.textContent="WMS",this._typeSelect.appendChild(l),this._typeSelect.appendChild(c),this._typeSelect.value=this._options.defaultType,this._typeSelect.addEventListener("change",()=>{const S=this._typeSelect.value==="wms";this._wmsLayersRow&&(this._wmsLayersRow.style.display=S?"flex":"none"),this._urlInput&&(this._urlInput.placeholder=S?"https://example.com/wms":"https://.../{z}/{x}/{y}.png",S&&!this._urlInput.value.trim()?this._urlInput.value=this._options.defaultWmsUrl:S&&this._urlInput.value===this._options.defaultUrl?this._urlInput.value=this._options.defaultWmsUrl:!S&&this._urlInput.value===this._options.defaultWmsUrl&&(this._urlInput.value=this._options.defaultUrl)),S&&this._onWmsUrlChange()}),a.appendChild(o),a.appendChild(this._typeSelect),e.appendChild(a);const h=document.createElement("div");h.style.cssText=i;const d=document.createElement("label");d.textContent="URL",d.style.cssText=s,this._urlInput=document.createElement("input"),this._urlInput.type="text",this._urlInput.placeholder=this._options.defaultType==="wms"?"https://example.com/wms":"https://.../{z}/{x}/{y}.png",this._urlInput.value=this._options.defaultUrl,this._urlInput.style.cssText=r,this._urlInput.addEventListener("input",()=>this._onWmsUrlChange()),this._urlInput.addEventListener("change",()=>this._onWmsUrlChange()),h.appendChild(d),h.appendChild(this._urlInput),e.appendChild(h);const f=document.createElement("div");f.style.cssText=i;const m=document.createElement("label");m.textContent="Name",m.style.cssText=s,this._nameInput=document.createElement("input"),this._nameInput.type="text",this._nameInput.placeholder="Layer name (optional)",this._nameInput.value=this._options.defaultName,this._nameInput.style.cssText=r,f.appendChild(m),f.appendChild(this._nameInput),e.appendChild(f),this._wmsLayersRow=document.createElement("div"),this._wmsLayersRow.style.cssText="display:flex;flex-direction:column;gap:4px;margin-bottom:8px;font-size:12px;color:#000;",this._wmsLayersRow.style.display=this._options.defaultType==="wms"?"flex":"none";const A=document.createElement("div");A.style.cssText="display:flex;align-items:center;gap:8px;";const y=document.createElement("label");y.textContent="Layer",y.style.cssText=s,this._wmsLayersSelect=document.createElement("select"),this._wmsLayersSelect.style.cssText="flex:1;min-width:0;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px;color:#000;background:#fff;cursor:pointer;";const x=document.createElement("option");if(x.value="",x.textContent="Enter WMS URL first...",x.disabled=!0,x.selected=!0,this._wmsLayersSelect.appendChild(x),this._options.defaultWmsLayers){const S=document.createElement("option");S.value=this._options.defaultWmsLayers,S.textContent=this._options.defaultWmsLayers,this._wmsLayersSelect.appendChild(S),this._wmsLayersSelect.value=this._options.defaultWmsLayers}this._wmsLayersSelect.addEventListener("change",()=>{if(this._nameInput){const S=this._wmsLayersSelect.options[this._wmsLayersSelect.selectedIndex];S?.textContent&&(this._nameInput.value=S.textContent)}}),A.appendChild(y),A.appendChild(this._wmsLayersSelect),this._wmsLayersRow.appendChild(A),this._wmsStatusEl=document.createElement("div"),this._wmsStatusEl.style.cssText="font-size:11px;color:#888;padding-left:78px;display:none;",this._wmsLayersRow.appendChild(this._wmsStatusEl),e.appendChild(this._wmsLayersRow),this._options.defaultType==="wms"&&this._options.defaultUrl&&this._onWmsUrlChange();const v=document.createElement("div");v.style.cssText=i;const b=document.createElement("label");b.textContent="Opacity",b.style.cssText=s,this._opacityInput=document.createElement("input"),this._opacityInput.type="range",this._opacityInput.min="0",this._opacityInput.max="1",this._opacityInput.step="0.05",this._opacityInput.value=String(this._options.defaultOpacity),this._opacityInput.style.cssText="flex:1;min-width:80px;cursor:pointer;accent-color:#2563eb;",this._opacityValueEl=document.createElement("span"),this._opacityValueEl.textContent=`${this._options.defaultOpacity}`,this._opacityValueEl.style.cssText="min-width:28px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums;",this._opacityInput.addEventListener("input",()=>{this._opacityValueEl&&(this._opacityValueEl.textContent=`${this._opacityInput.value}`)}),v.appendChild(b),v.appendChild(this._opacityInput),v.appendChild(this._opacityValueEl),e.appendChild(v);const w=document.createElement("button");return w.type="button",w.textContent="Add Layer",w.style.cssText="width:100%;padding:6px 0;border:1px solid #333;border-radius:4px;background:#fff;font-size:12px;font-weight:500;color:#000;cursor:pointer;margin-bottom:8px;",w.addEventListener("mouseenter",()=>{w.style.backgroundColor="#f0f0f0"}),w.addEventListener("mouseleave",()=>{w.style.backgroundColor="#fff"}),w.addEventListener("click",()=>this._addLayerFromForm()),e.appendChild(w),this._layerListEl=document.createElement("div"),this._layerListEl.style.cssText="max-height:200px;overflow-y:auto;",this._updateLayerList(),e.appendChild(this._layerListEl),e}_addLayerFromForm(){const e=this._urlInput?.value.trim();if(!e){this._urlInput&&(this._urlInput.style.borderColor="#e74c3c",setTimeout(()=>{this._urlInput&&(this._urlInput.style.borderColor="#ccc")},2e3));return}const t=this._typeSelect?.value??"xyz",n=this._nameInput?.value.trim()||void 0,i=this._wmsLayersSelect?.value.trim()||void 0,s=Number(this._opacityInput?.value??.8);this.addTileLayer(e,{name:n,type:t,wmsLayers:i,opacity:s})}_updateLayerList(){if(!this._layerListEl||(this._layerListEl.innerHTML="",this._layers.length===0))return;const e=document.createElement("div");e.style.cssText="font-size:11px;font-weight:600;color:#666;margin-bottom:4px;padding-top:4px;border-top:1px solid #eee;",e.textContent="Added Layers",this._layerListEl.appendChild(e);for(const t of this._layers){const n=document.createElement("div");n.style.cssText="display:flex;align-items:center;gap:4px;margin-bottom:4px;font-size:11px;color:#000;";const i=document.createElement("button");i.type="button",i.title=t.visible?"Hide layer":"Show layer",i.innerHTML=t.visible?fz:mz,i.style.cssText="background:none;border:none;cursor:pointer;padding:2px;display:flex;align-items:center;flex-shrink:0;color:#000;",t.visible||(i.style.opacity="0.4"),i.addEventListener("click",()=>{this.setLayerVisibility(t.id,!t.visible)}),n.appendChild(i);const s=document.createElement("span");s.textContent=t.name,s.title=t.url,s.style.cssText="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;",n.appendChild(s);const r=document.createElement("input");r.type="range",r.min="0",r.max="1",r.step="0.05",r.value=String(t.opacity),r.style.cssText="width:50px;cursor:pointer;accent-color:#2563eb;flex-shrink:0;",r.addEventListener("input",()=>{this.setLayerOpacity(t.id,Number(r.value))}),n.appendChild(r);const a=document.createElement("button");a.type="button",a.title="Remove layer",a.textContent="×",a.style.cssText="background:none;border:none;font-size:14px;cursor:pointer;color:#999;padding:0 2px;line-height:1;flex-shrink:0;",a.addEventListener("mouseenter",()=>{a.style.color="#e74c3c"}),a.addEventListener("mouseleave",()=>{a.style.color="#999"}),a.addEventListener("click",()=>{this.removeTileLayer(t.id)}),n.appendChild(a),this._layerListEl.appendChild(n)}}_onWmsUrlChange(){this._typeSelect?.value==="wms"&&(clearTimeout(this._fetchDebounceTimer),this._fetchDebounceTimer=setTimeout(()=>{const e=this._urlInput?.value.trim();e&&this._fetchWmsLayers(e)},600))}async _fetchWmsLayers(e){this._fetchController?.abort(),this._fetchController=new AbortController,this._wmsStatusEl&&(this._wmsStatusEl.style.display="block",this._wmsStatusEl.textContent="Fetching layers...",this._wmsStatusEl.style.color="#888");try{const t=new URL(e);t.searchParams.set("service","WMS"),t.searchParams.set("request","GetCapabilities");const n=await fetch(t.toString(),{signal:this._fetchController.signal});if(!n.ok)throw new Error(`HTTP ${n.status}`);const i=await n.text(),s=new DOMParser().parseFromString(i,"text/xml"),r=[],a=s.querySelectorAll("Layer");for(const l of a){const c=l.querySelector(":scope > Name"),h=l.querySelector(":scope > Title");c?.textContent&&r.push({name:c.textContent,title:h?.textContent||c.textContent})}if(!this._wmsLayersSelect)return;if(this._wmsLayersSelect.innerHTML="",r.length===0){const l=document.createElement("option");l.value="",l.textContent="No layers found",l.disabled=!0,l.selected=!0,this._wmsLayersSelect.appendChild(l),this._wmsStatusEl&&(this._wmsStatusEl.textContent="No layers found",this._wmsStatusEl.style.color="#e74c3c");return}const o=document.createElement("option");o.value="",o.textContent=`Select a layer (${r.length} available)`,o.disabled=!0,o.selected=!0,this._wmsLayersSelect.appendChild(o);for(const l of r){const c=document.createElement("option");c.value=l.name,c.textContent=l.title!==l.name?`${l.title} (${l.name})`:l.name,this._wmsLayersSelect.appendChild(c)}if(this._options.defaultWmsLayers){const l=r.find(c=>c.name===this._options.defaultWmsLayers);l&&(this._wmsLayersSelect.value=l.name)}this._wmsStatusEl&&(this._wmsStatusEl.textContent=`${r.length} layers available`,this._wmsStatusEl.style.color="#22c55e",setTimeout(()=>{this._wmsStatusEl&&(this._wmsStatusEl.style.display="none")},3e3))}catch(t){if(t.name==="AbortError")return;this._wmsStatusEl&&(this._wmsStatusEl.textContent="Failed to fetch layers",this._wmsStatusEl.style.color="#e74c3c")}}_buildWmsUrl(e,t){if(e.includes("{bbox-epsg-3857}"))return e;const n=new URL(e),i=n.searchParams;return i.has("service")||i.set("service","WMS"),i.has("request")||i.set("request","GetMap"),i.has("version")||i.set("version","1.1.1"),t&&!i.has("layers")&&i.set("layers",t),i.has("styles")||i.set("styles",""),i.has("format")||i.set("format","image/png"),i.has("transparent")||i.set("transparent","true"),i.has("width")||i.set("width","256"),i.has("height")||i.set("height","256"),i.has("srs")||i.set("srs","EPSG:3857"),`${n.toString()}&bbox={bbox-epsg-3857}`}_emit(e,t){const n=this._eventHandlers.get(e);if(!n)return;const i={type:e,state:this.getState(),layer:t};n.forEach(s=>s(i))}},E2=class{type="cog";cogControl;layerInfoMap=new Map;changeCallbacks=[];constructor(e){this.cogControl=e,this.cogControl.on("layeradd",t=>{const n=t.layerId;if(n){const i=t.state?.layers?.find(r=>r.id===n);let s=i?.name||n;if(!i?.name&&t.url)try{s=new URL(t.url).pathname.split("/").pop()||n}catch{s=t.url}this.layerInfoMap.set(n,{id:n,name:s,visible:!0,opacity:t.state?.layerOpacity??1}),this.notifyLayerAdded(n)}}),this.cogControl.on("layerremove",t=>{const n=t.layerId;n&&(this.layerInfoMap.delete(n),this.notifyLayerRemoved(n))}),this.syncFromControlState()}syncFromControlState(){const e=this.cogControl.getState();if(e.layers&&Array.isArray(e.layers))for(const t of e.layers){let n=t.name||t.id;if(!t.name&&t.url)try{n=new URL(t.url).pathname.split("/").pop()||t.id}catch{n=t.url}this.layerInfoMap.set(t.id,{id:t.id,name:n,visible:!0,opacity:t.opacity??1})}}getLayerIds(){return Array.from(this.layerInfoMap.keys())}getLayerState(e){const t=this.layerInfoMap.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}setVisibility(e,t){const n=this.layerInfoMap.get(e);n&&(n.visible=t,this.cogControl.setLayerVisibility(e,t,n.opacity))}setOpacity(e,t){const n=this.layerInfoMap.get(e);n&&(n.opacity=t,n.visible&&this.cogControl.setLayerOpacity(e,t))}getName(e){return this.layerInfoMap.get(e)?.name??e}getSymbolType(e){return"raster"}getBounds(e){return this.layerInfoMap.get(e)?.bounds??null}removeLayer(e){this.cogControl.removeLayer(e)}notifyLayerAdded(e){this.changeCallbacks.forEach(t=>t("add",e))}notifyLayerRemoved(e){this.changeCallbacks.forEach(t=>t("remove",e))}onLayerChange(e){return this.changeCallbacks.push(e),()=>{const t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}}},C2=class{type="zarr";zarrControl;layerInfoMap=new Map;changeCallbacks=[];constructor(e){this.zarrControl=e,this.zarrControl.on("layeradd",t=>{const n=t.layerId;if(n){const i=this.zarrControl.getState().layers.find(r=>r.id===n);let s=i?.name||n;if(!i?.name&&t.url)try{const r=new URL(t.url).pathname.split("/").pop()||"",a=i?.variable||"";s=a?`${r} / ${a}`:r}catch{s=t.url}this.layerInfoMap.set(n,{id:n,name:s,visible:!0,opacity:t.state?.layerOpacity??1}),this.notifyLayerAdded(n)}}),this.zarrControl.on("layerremove",t=>{const n=t.layerId;n&&(this.layerInfoMap.delete(n),this.notifyLayerRemoved(n))}),this.syncFromControlState()}syncFromControlState(){const e=this.zarrControl.getState();if(e.layers&&Array.isArray(e.layers))for(const t of e.layers){let n=t.name||t.id;if(!t.name&&t.url)try{const i=new URL(t.url).pathname.split("/").pop()||"";n=t.variable?`${i} / ${t.variable}`:i}catch{n=t.url}this.layerInfoMap.set(t.id,{id:t.id,name:n,visible:!0,opacity:t.opacity??1})}}getLayerIds(){return Array.from(this.layerInfoMap.keys())}getLayerState(e){const t=this.layerInfoMap.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}setVisibility(e,t){const n=this.layerInfoMap.get(e);n&&(n.visible=t,this.zarrControl.setLayerVisibility(e,t,n.opacity))}setOpacity(e,t){const n=this.layerInfoMap.get(e);n&&(n.opacity=t,n.visible&&this.zarrControl.setLayerOpacity(e,t))}getName(e){return this.layerInfoMap.get(e)?.name??e}getSymbolType(e){return"raster"}removeLayer(e){this.zarrControl.removeLayer(e)}notifyLayerAdded(e){this.changeCallbacks.forEach(t=>t("add",e))}notifyLayerRemoved(e){this.changeCallbacks.forEach(t=>t("remove",e))}onLayerChange(e){return this.changeCallbacks.push(e),()=>{const t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}}},w2=class{type="pmtiles";_control;_groups=new Map;_changeCallbacks=[];constructor(e){this._control=e,this._control.on("layeradd",()=>{setTimeout(()=>this._rebuildGroups(),50)}),this._control.on("layerremove",()=>{setTimeout(()=>this._rebuildGroups(),50)})}_rebuildGroups(){const e=new Set(this._groups.keys()),t=new Map;for(const n of this._control.getState().layers){const i=n.id;if(n.sourceLayers&&n.sourceLayers.length>0)for(const s of n.sourceLayers){const r=`${i}-${s}`,a=`${i}-${s}-`,o=n.layerIds.filter(l=>l.startsWith(a));o.length>0&&t.set(r,{name:s.charAt(0).toUpperCase()+s.slice(1),sublayers:o,visible:!0,opacity:n.opacity})}else{const s=n.name||this._extractFilename(n.url);t.set(i,{name:s,sublayers:[...n.layerIds],visible:!0,opacity:n.opacity})}}for(const n of t.keys())e.has(n)||this._changeCallbacks.forEach(i=>i("add",n));for(const n of e)t.has(n)||this._changeCallbacks.forEach(i=>i("remove",n));this._groups=t}_extractFilename(e){try{return new URL(e).pathname.split("/").pop()||e}catch{return e}}getLayerIds(){return Array.from(this._groups.keys())}getLayerState(e){const t=this._groups.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}getName(e){return this._groups.get(e)?.name??e}getSymbolType(e){return"fill"}setVisibility(e,t){const n=this._groups.get(e);if(n){n.visible=t;for(const i of n.sublayers)this._control.setLayerVisibility(i,t)}}setOpacity(e,t){const n=this._groups.get(e);if(n){n.opacity=t;for(const i of n.sublayers)this._control.setLayerOpacity(i,t)}}getNativeLayerIds(e){const t=this._groups.get(e);return t?[...t.sublayers]:[]}removeLayer(e){}onLayerChange(e){return this._changeCallbacks.push(e),()=>{const t=this._changeCallbacks.indexOf(e);t>=0&&this._changeCallbacks.splice(t,1)}}hasLayers(){return this._control.getState().hasLayer}},S2=class{type="addvector";_control;_options;_changeCallbacks=[];constructor(e,t){this._control=e,this._options=t||{},this._control.on("layeradd",n=>{n.layerId&&this._changeCallbacks.forEach(i=>i("add",n.layerId))}),this._control.on("layerremove",n=>{n.layerId&&this._changeCallbacks.forEach(i=>i("remove",n.layerId))})}getControl(){return this._control}getLayerIds(){return this._control.getLayerIds()}getLayerState(e){const t=this._control.getLayerVisibility(e),n=this._control.getLayerOpacity(e);return n===null?null:{visible:t,opacity:n,name:this.getName(e)}}getName(e){const t=e.split("-");if(t.length>=3){const n=t[t.length-1];return`${this._options.name||"Vector"} (${n})`}return this._options.name||e}setVisibility(e,t){this._control.setLayerVisibility(e,t)}setOpacity(e,t){this._control.setLayerOpacity(e,t)}onLayerChange(e){return this._changeCallbacks.push(e),()=>{const t=this._changeCallbacks.indexOf(e);t>=0&&this._changeCallbacks.splice(t,1)}}hasLayers(){return this._control.getState().hasLayer}getMetadata(){const e=this._control.getState();return{layerCount:e.layerCount,layers:e.layers.map(t=>({id:t.id,url:t.url,format:t.format,featureCount:t.featureCount,geometryTypes:t.geometryTypes}))}}},I2=class{type="stac";stacControl;layerInfoMap=new Map;changeCallbacks=[];constructor(e){this.stacControl=e,this.stacControl.on("layeradd",t=>{const n=t.layerId;if(n){let i=t.layerName||n;if(!t.layerName){if(t.assetKey)i=`STAC: ${t.assetKey}`;else if(t.url)try{i=new URL(t.url).pathname.split("/").pop()||n}catch{i=t.url}}this.layerInfoMap.set(n,{id:n,name:i,visible:!0,opacity:t.state?.layerOpacity??1}),this.notifyLayerAdded(n)}}),this.stacControl.on("layerremove",t=>{const n=t.layerId;n&&(this.layerInfoMap.delete(n),this.notifyLayerRemoved(n))}),this.syncFromControlState()}syncFromControlState(){const e=this.stacControl.getLayerIds();for(const t of e){const n=this.stacControl.getLayerOpacity(t);this.layerInfoMap.set(t,{id:t,name:t,visible:n!==null&&n>0,opacity:n??1})}}getLayerIds(){return Array.from(this.layerInfoMap.keys())}getLayerState(e){const t=this.layerInfoMap.get(e);return t?{visible:t.visible,opacity:t.opacity,name:t.name}:null}setVisibility(e,t){const n=this.layerInfoMap.get(e);n&&(n.visible=t,this.stacControl.setLayerVisibility(e,t,n.opacity))}setOpacity(e,t){const n=this.layerInfoMap.get(e);n&&(n.opacity=t,n.visible&&this.stacControl.setLayerOpacity(e,t))}getName(e){return this.layerInfoMap.get(e)?.name??e}getSymbolType(e){return"raster"}removeLayer(e){this.stacControl.removeLayer(e)}notifyLayerAdded(e){this.changeCallbacks.forEach(t=>t("add",e))}notifyLayerRemoved(e){this.changeCallbacks.forEach(t=>t("remove",e))}onLayerChange(e){return this.changeCallbacks.push(e),()=>{const t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}}},$i=63710088e-1,M2={centimeters:$i*100,centimetres:$i*100,degrees:360/(2*Math.PI),feet:$i*3.28084,inches:$i*39.37,kilometers:$i/1e3,kilometres:$i/1e3,meters:$i,metres:$i,miles:$i/1609.344,millimeters:$i*1e3,millimetres:$i*1e3,nauticalmiles:$i/1852,radians:1,yards:$i*1.0936};function or(e,t,n={}){const i={type:"Feature"};return(n.id===0||n.id)&&(i.id=n.id),n.bbox&&(i.bbox=n.bbox),i.properties=t||{},i.geometry=e,i}function wi(e,t,n={}){if(!e)throw new Error("coordinates is required");if(!Array.isArray(e))throw new Error("coordinates must be an Array");if(e.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!rS(e[0])||!rS(e[1]))throw new Error("coordinates must contain numbers");return or({type:"Point",coordinates:e},t,n)}function Hr(e,t,n={}){for(const i of e){if(i.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(i[i.length-1].length!==i[0].length)throw new Error("First and last Position are not equivalent.");for(let s=0;s<i[i.length-1].length;s++)if(i[i.length-1][s]!==i[0][s])throw new Error("First and last Position are not equivalent.")}return or({type:"Polygon",coordinates:e},t,n)}function xs(e,t,n={}){if(e.length<2)throw new Error("coordinates must be an array of two or more positions");return or({type:"LineString",coordinates:e},t,n)}function Kt(e,t={}){const n={type:"FeatureCollection"};return t.id&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.features=e,n}function T2(e,t,n={}){return or({type:"MultiLineString",coordinates:e},t,n)}function mA(e,t,n={}){return or({type:"MultiPolygon",coordinates:e},t,n)}function TE(e,t="kilometers"){const n=M2[t];if(!n)throw new Error(t+" units is invalid");return e*n}function L2(e,t="kilometers"){const n=M2[t];if(!n)throw new Error(t+" units is invalid");return e/n}function A_(e){return e%(2*Math.PI)*180/Math.PI}function Qs(e){return e%360*Math.PI/180}function B2(e,t="kilometers",n="kilometers"){if(!(e>=0))throw new Error("length must be a positive number");return TE(L2(e,t),n)}function rS(e){return!isNaN(e)&&e!==null&&!Array.isArray(e)}function bf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Si(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if(e.type==="Feature"&&e.geometry!==null&&e.geometry.type==="Point")return[...e.geometry.coordinates];if(e.type==="Point")return[...e.coordinates]}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return[...e];throw new Error("coord must be GeoJSON Point or an Array of numbers")}function as(e){if(Array.isArray(e))return e;if(e.type==="Feature"){if(e.geometry!==null)return e.geometry.coordinates}else if(e.coordinates)return e.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $r(e){return e.type==="Feature"?e.geometry:e}function v_(e,t){return e.type==="FeatureCollection"?"FeatureCollection":e.type==="GeometryCollection"?"GeometryCollection":e.type==="Feature"&&e.geometry!==null?e.geometry.type:e.type}function R2(e,t,n={}){if(n.final===!0)return gz(e,t);const i=Si(e),s=Si(t),r=Qs(i[0]),a=Qs(s[0]),o=Qs(i[1]),l=Qs(s[1]),c=Math.sin(a-r)*Math.cos(l),h=Math.cos(o)*Math.sin(l)-Math.sin(o)*Math.cos(l)*Math.cos(a-r);return A_(Math.atan2(c,h))}function gz(e,t){let n=R2(t,e);return n=(n+180)%360,n}function dp(e,t,n={}){var i=Si(e),s=Si(t),r=Qs(s[1]-i[1]),a=Qs(s[0]-i[0]),o=Qs(i[1]),l=Qs(s[1]),c=Math.pow(Math.sin(r/2),2)+Math.pow(Math.sin(a/2),2)*Math.cos(o)*Math.cos(l);return TE(2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c)),n.units)}function _z(e,t,n={}){let i;return n.final?i=aS(Si(t),Si(e)):i=aS(Si(e),Si(t)),i>180?-(360-i):i}function aS(e,t){const n=Qs(e[1]),i=Qs(t[1]);let s=Qs(t[0]-e[0]);s>Math.PI&&(s-=2*Math.PI),s<-Math.PI&&(s+=2*Math.PI);const r=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(A_(Math.atan2(s,r))+360)%360}function Ql(e,t,n){if(e!==null)for(var i,s,r,a,o,l,c,h=0,d=0,f,m=e.type,A=m==="FeatureCollection",y=m==="Feature",x=A?e.features.length:1,v=0;v<x;v++){c=A?e.features[v].geometry:y?e.geometry:e,f=c?c.type==="GeometryCollection":!1,o=f?c.geometries.length:1;for(var b=0;b<o;b++){var w=0,S=0;if(a=f?c.geometries[b]:c,a!==null){l=a.coordinates;var R=a.type;switch(h=n&&(R==="Polygon"||R==="MultiPolygon")?1:0,R){case null:break;case"Point":if(t(l,d,v,w,S)===!1)return!1;d++,w++;break;case"LineString":case"MultiPoint":for(i=0;i<l.length;i++){if(t(l[i],d,v,w,S)===!1)return!1;d++,R==="MultiPoint"&&w++}R==="LineString"&&w++;break;case"Polygon":case"MultiLineString":for(i=0;i<l.length;i++){for(s=0;s<l[i].length-h;s++){if(t(l[i][s],d,v,w,S)===!1)return!1;d++}R==="MultiLineString"&&w++,R==="Polygon"&&S++}R==="Polygon"&&w++;break;case"MultiPolygon":for(i=0;i<l.length;i++){for(S=0,s=0;s<l[i].length;s++){for(r=0;r<l[i][s].length-h;r++){if(t(l[i][s][r],d,v,w,S)===!1)return!1;d++}S++}w++}break;case"GeometryCollection":for(i=0;i<a.geometries.length;i++)if(Ql(a.geometries[i],t,n)===!1)return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function Po(e,t){if(e.type==="Feature")t(e,0);else if(e.type==="FeatureCollection")for(var n=0;n<e.features.length&&t(e.features[n],n)!==!1;n++);}function Az(e,t,n){var i=n;return Po(e,function(s,r){r===0&&n===void 0?i=s:i=t(i,s,r)}),i}function vz(e){var t=[];return Ql(e,function(n){t.push(n)}),t}function Gl(e,t){var n,i,s,r,a,o,l,c,h,d,f=0,m=e.type==="FeatureCollection",A=e.type==="Feature",y=m?e.features.length:1;for(n=0;n<y;n++){for(o=m?e.features[n].geometry:A?e.geometry:e,c=m?e.features[n].properties:A?e.properties:{},h=m?e.features[n].bbox:A?e.bbox:void 0,d=m?e.features[n].id:A?e.id:void 0,l=o?o.type==="GeometryCollection":!1,a=l?o.geometries.length:1,s=0;s<a;s++){if(r=l?o.geometries[s]:o,r===null){if(t(null,f,c,h,d)===!1)return!1;continue}switch(r.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(t(r,f,c,h,d)===!1)return!1;break;case"GeometryCollection":for(i=0;i<r.geometries.length;i++)if(t(r.geometries[i],f,c,h,d)===!1)return!1;break;default:throw new Error("Unknown Geometry Type")}}f++}}function yz(e,t,n){var i=n;return Gl(e,function(s,r,a,o,l){i=t(i,s,r,a,o,l)}),i}function Do(e,t){Gl(e,function(n,i,s,r,a){var o=n===null?null:n.type;switch(o){case null:case"Point":case"LineString":case"Polygon":return t(or(n,s,{bbox:r,id:a}),i,0)===!1?!1:void 0}var l;switch(o){case"MultiPoint":l="Point";break;case"MultiLineString":l="LineString";break;case"MultiPolygon":l="Polygon";break}for(var c=0;c<n.coordinates.length;c++){var h=n.coordinates[c];if(t(or({type:l,coordinates:h},s),i,c)===!1)return!1}})}function Qd(e,t){Do(e,function(n,i,s){var r=0;if(n.geometry){var a=n.geometry.type;if(!(a==="Point"||a==="MultiPoint")){var o,l=0,c=0,h=0;if(Ql(n,function(d,f,m,A,y){if(o===void 0||i>l||A>c||y>h){o=d,l=i,c=A,h=y,r=0;return}if(t(xs([o,d],n.properties),i,s,y,r)===!1)return!1;r++,o=d})===!1)return!1}}})}function y_(e){return yz(e,(t,n)=>t+bz(n),0)}function bz(e){let t=0,n;switch(e.type){case"Polygon":return oS(e.coordinates);case"MultiPolygon":for(n=0;n<e.coordinates.length;n++)t+=oS(e.coordinates[n]);return t;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0}return 0}function oS(e){let t=0;if(e&&e.length>0){t+=Math.abs(lS(e[0]));for(let n=1;n<e.length;n++)t-=Math.abs(lS(e[n]))}return t}var xz=$i*$i/2,bv=Math.PI/180;function lS(e){const t=e.length-1;if(t<=2)return 0;let n=0,i=0;for(;i<t;){const s=e[i],r=e[i+1===t?0:i+1],a=e[i+2>=t?(i+2)%t:i+2],o=s[0]*bv,l=r[1]*bv,c=a[0]*bv;n+=(c-o)*Math.sin(l),i++}return n*xz}function si(e,t={}){if(e.bbox!=null&&t.recompute!==!0)return e.bbox;const n=[1/0,1/0,-1/0,-1/0];return Ql(e,i=>{n[0]>i[0]&&(n[0]=i[0]),n[1]>i[1]&&(n[1]=i[1]),n[2]<i[0]&&(n[2]=i[0]),n[3]<i[1]&&(n[3]=i[1])}),n}function Ez(e,t,n){var i=e.length,s=ru(e[0],t),r=[],a,o,l;let c,h;for(n||(n=[]),a=1;a<i;a++){for(c=e[a-1],h=e[a],o=l=ru(h,t);;)if(s|o){if(s&o)break;s?(c=nb(c,h,s,t),s=ru(c,t)):(h=nb(c,h,o,t),o=ru(h,t))}else{r.push(c),o!==l?(r.push(h),a<i-1&&(n.push(r),r=[])):a===i-1&&r.push(h);break}s=l}return r.length&&n.push(r),n}function Cz(e,t){var n,i,s,r,a,o,l;for(i=1;i<=8;i*=2){for(n=[],s=e[e.length-1],r=!(ru(s,t)&i),a=0;a<e.length;a++)o=e[a],l=!(ru(o,t)&i),l!==r&&n.push(nb(s,o,i,t)),l&&n.push(o),s=o,r=l;if(e=n,!e.length)break}return n}function nb(e,t,n,i){return n&8?[e[0]+(t[0]-e[0])*(i[3]-e[1])/(t[1]-e[1]),i[3]]:n&4?[e[0]+(t[0]-e[0])*(i[1]-e[1])/(t[1]-e[1]),i[1]]:n&2?[i[2],e[1]+(t[1]-e[1])*(i[2]-e[0])/(t[0]-e[0])]:n&1?[i[0],e[1]+(t[1]-e[1])*(i[0]-e[0])/(t[0]-e[0])]:null}function ru(e,t){var n=0;return e[0]<t[0]?n|=1:e[0]>t[2]&&(n|=2),e[1]<t[1]?n|=4:e[1]>t[3]&&(n|=8),n}function wz(e,t){const n=$r(e),i=n.type,s=e.type==="Feature"?e.properties:{};let r=n.coordinates;switch(i){case"LineString":case"MultiLineString":{const a=[];return i==="LineString"&&(r=[r]),r.forEach(o=>{Ez(o,t,a)}),a.length===1?xs(a[0],s):T2(a,s)}case"Polygon":return Hr(cS(r,t),s);case"MultiPolygon":return mA(r.map(a=>cS(a,t)),s);default:throw new Error("geometry "+i+" not supported")}}function cS(e,t){const n=[];for(const i of e){const s=Cz(i,t);s.length>0&&((s[0][0]!==s[s.length-1][0]||s[0][1]!==s[s.length-1][1])&&s.push(s[0]),s.length>=4&&n.push(s))}return n}var Np=11102230246251565e-32,fs=134217729,Sz=3.000000000000001*Np;function xv(e,t,n,i,s){let r,a,o,l,c=t[0],h=i[0],d=0,f=0;h>c==h>-c?(r=c,c=t[++d]):(r=h,h=i[++f]);let m=0;if(d<e&&f<n)for(h>c==h>-c?(a=c+r,o=r-(a-c),c=t[++d]):(a=h+r,o=r-(a-h),h=i[++f]),r=a,o!==0&&(s[m++]=o);d<e&&f<n;)h>c==h>-c?(a=r+c,l=a-r,o=r-(a-l)+(c-l),c=t[++d]):(a=r+h,l=a-r,o=r-(a-l)+(h-l),h=i[++f]),r=a,o!==0&&(s[m++]=o);for(;d<e;)a=r+c,l=a-r,o=r-(a-l)+(c-l),c=t[++d],r=a,o!==0&&(s[m++]=o);for(;f<n;)a=r+h,l=a-r,o=r-(a-l)+(h-l),h=i[++f],r=a,o!==0&&(s[m++]=o);return(r!==0||m===0)&&(s[m++]=r),m}function Iz(e,t){let n=t[0];for(let i=1;i<e;i++)n+=t[i];return n}function xf(e){return new Float64Array(e)}var Mz=3.0000000000000018*Np,Tz=2.0000000000000013*Np,Lz=9.000000000000007*Np*Np,nh=xf(4),hS=xf(8),uS=xf(12),dS=xf(16),Ls=xf(4);function Bz(e,t,n,i,s,r,a){let o,l,c,h,d,f,m,A,y,x,v,b,w,S,R,k,L,T;const C=e-s,I=n-s,M=t-r,U=i-r;S=C*U,f=fs*C,m=f-(f-C),A=C-m,f=fs*U,y=f-(f-U),x=U-y,R=A*x-(S-m*y-A*y-m*x),k=M*I,f=fs*M,m=f-(f-M),A=M-m,f=fs*I,y=f-(f-I),x=I-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,nh[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,nh[1]=w-(v+d)+(d-k),T=b+v,d=T-b,nh[2]=b-(T-d)+(v-d),nh[3]=T;let N=Iz(4,nh),D=Tz*a;if(N>=D||-N>=D||(d=e-C,o=e-(C+d)+(d-s),d=n-I,c=n-(I+d)+(d-s),d=t-M,l=t-(M+d)+(d-r),d=i-U,h=i-(U+d)+(d-r),o===0&&l===0&&c===0&&h===0)||(D=Lz*a+Sz*Math.abs(N),N+=C*h+U*o-(M*c+I*l),N>=D||-N>=D))return N;S=o*U,f=fs*o,m=f-(f-o),A=o-m,f=fs*U,y=f-(f-U),x=U-y,R=A*x-(S-m*y-A*y-m*x),k=l*I,f=fs*l,m=f-(f-l),A=l-m,f=fs*I,y=f-(f-I),x=I-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,Ls[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,Ls[1]=w-(v+d)+(d-k),T=b+v,d=T-b,Ls[2]=b-(T-d)+(v-d),Ls[3]=T;const P=xv(4,nh,4,Ls,hS);S=C*h,f=fs*C,m=f-(f-C),A=C-m,f=fs*h,y=f-(f-h),x=h-y,R=A*x-(S-m*y-A*y-m*x),k=M*c,f=fs*M,m=f-(f-M),A=M-m,f=fs*c,y=f-(f-c),x=c-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,Ls[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,Ls[1]=w-(v+d)+(d-k),T=b+v,d=T-b,Ls[2]=b-(T-d)+(v-d),Ls[3]=T;const O=xv(P,hS,4,Ls,uS);return S=o*h,f=fs*o,m=f-(f-o),A=o-m,f=fs*h,y=f-(f-h),x=h-y,R=A*x-(S-m*y-A*y-m*x),k=l*c,f=fs*l,m=f-(f-l),A=l-m,f=fs*c,y=f-(f-c),x=c-y,L=A*x-(k-m*y-A*y-m*x),v=R-L,d=R-v,Ls[0]=R-(v+d)+(d-L),b=S+v,d=b-S,w=S-(b-d)+(v-d),v=w-k,d=w-v,Ls[1]=w-(v+d)+(d-k),T=b+v,d=T-b,Ls[2]=b-(T-d)+(v-d),Ls[3]=T,dS[xv(O,uS,4,Ls,dS)-1]}function Rz(e,t,n,i,s,r){const a=(t-r)*(n-s),o=(e-s)*(i-r),l=a-o,c=Math.abs(a+o);return Math.abs(l)>=Mz*c?l:-Bz(e,t,n,i,s,r,c)}function kz(e,t){var n,i,s=0,r,a,o,l,c,h,d,f=e[0],m=e[1],A=t.length;for(n=0;n<A;n++){i=0;var y=t[n],x=y.length-1;if(h=y[0],h[0]!==y[x][0]&&h[1]!==y[x][1])throw new Error("First and last coordinates in a ring must be the same");for(a=h[0]-f,o=h[1]-m;i<x;i++){if(d=y[i+1],l=d[0]-f,c=d[1]-m,o===0&&c===0){if(l<=0&&a>=0||a<=0&&l>=0)return 0}else if(c>=0&&o<=0||c<=0&&o>=0){if(r=Rz(a,l,o,c,0,0),r===0)return 0;(r>0&&c>0&&o<=0||r<0&&c<=0&&o>0)&&s++}h=d,o=c,a=l}}return s%2!==0}function Ii(e,t,n={}){if(!e)throw new Error("point is required");if(!t)throw new Error("polygon is required");const i=Si(e),s=$r(t),r=s.type,a=t.bbox;let o=s.coordinates;if(a&&Nz(i,a)===!1)return!1;r==="Polygon"&&(o=[o]);let l=!1;for(var c=0;c<o.length;++c){const h=kz(i,o[c]);if(h===0)return!n.ignoreBoundary;h&&(l=!0)}return l}function Nz(e,t){return t[0]<=e[0]&&t[1]<=e[1]&&t[2]>=e[0]&&t[3]>=e[1]}function Gs(e,t,n={}){const i=Si(e),s=as(t);for(let r=0;r<s.length-1;r++){let a=!1;if(n.ignoreEndVertices&&(r===0&&(a="start"),r===s.length-2&&(a="end"),r===0&&r+1===s.length-1&&(a="both")),Pz(s[r],s[r+1],i,a,typeof n.epsilon>"u"?null:n.epsilon))return!0}return!1}function Pz(e,t,n,i,s){const r=n[0],a=n[1],o=e[0],l=e[1],c=t[0],h=t[1],d=n[0]-o,f=n[1]-l,m=c-o,A=h-l,y=d*A-f*m;if(s!==null){if(Math.abs(y)>s)return!1}else if(y!==0)return!1;if(Math.abs(m)===Math.abs(A)&&Math.abs(m)===0)return i?!1:n[0]===e[0]&&n[1]===e[1];if(i){if(i==="start")return Math.abs(m)>=Math.abs(A)?m>0?o<r&&r<=c:c<=r&&r<o:A>0?l<a&&a<=h:h<=a&&a<l;if(i==="end")return Math.abs(m)>=Math.abs(A)?m>0?o<=r&&r<c:c<r&&r<=o:A>0?l<=a&&a<h:h<a&&a<=l;if(i==="both")return Math.abs(m)>=Math.abs(A)?m>0?o<r&&r<c:c<r&&r<o:A>0?l<a&&a<h:h<a&&a<l}else return Math.abs(m)>=Math.abs(A)?m>0?o<=r&&r<=c:c<=r&&r<=o:A>0?l<=a&&a<=h:h<=a&&a<=l;return!1}function Dz(e,t,n,i,s){k2(e,t,n||0,i||e.length-1,s||Fz)}function k2(e,t,n,i,s){for(;i>n;){if(i-n>600){var r=i-n+1,a=t-n+1,o=Math.log(r),l=.5*Math.exp(2*o/3),c=.5*Math.sqrt(o*l*(r-l)/r)*(a-r/2<0?-1:1);k2(e,t,Math.max(n,Math.floor(t-a*l/r+c)),Math.min(i,Math.floor(t+(r-a)*l/r+c)),s)}var h=e[t],d=n,f=i;for(dd(e,n,t),s(e[i],h)>0&&dd(e,n,i);d<f;){for(dd(e,d,f),d++,f--;s(e[d],h)<0;)d++;for(;s(e[f],h)>0;)f--}s(e[n],h)===0?dd(e,n,f):(f++,dd(e,f,i)),f<=t&&(n=f+1),t<=f&&(i=f-1)}}function dd(e,t,n){var i=e[t];e[t]=e[n],e[n]=i}function Fz(e,t){return e<t?-1:e>t?1:0}var LE=class{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(t){let n=this.data;const i=[];if(!Zf(t,n))return i;const s=this.toBBox,r=[];for(;n;){for(let a=0;a<n.children.length;a++){const o=n.children[a],l=n.leaf?s(o):o;Zf(t,l)&&(n.leaf?i.push(o):Cv(t,l)?this._all(o,i):r.push(o))}n=r.pop()}return i}collides(t){let n=this.data;if(!Zf(t,n))return!1;const i=[];for(;n;){for(let s=0;s<n.children.length;s++){const r=n.children[s],a=n.leaf?this.toBBox(r):r;if(Zf(t,a)){if(n.leaf||Cv(t,a))return!0;i.push(r)}}n=i.pop()}return!1}load(t){if(!(t&&t.length))return this;if(t.length<this._minEntries){for(let i=0;i<t.length;i++)this.insert(t[i]);return this}let n=this._build(t.slice(),0,t.length-1,0);if(!this.data.children.length)this.data=n;else if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const i=this.data;this.data=n,n=i}this._insert(n,this.data.height-n.height-1,!0)}return this}insert(t){return t&&this._insert(t,this.data.height-1),this}clear(){return this.data=Xh([]),this}remove(t,n){if(!t)return this;let i=this.data;const s=this.toBBox(t),r=[],a=[];let o,l,c;for(;i||r.length;){if(i||(i=r.pop(),l=r[r.length-1],o=a.pop(),c=!0),i.leaf){const h=Oz(t,i.children,n);if(h!==-1)return i.children.splice(h,1),r.push(i),this._condense(r),this}!c&&!i.leaf&&Cv(i,s)?(r.push(i),a.push(o),o=0,l=i,i=i.children[0]):l?(o++,i=l.children[o],c=!1):i=null}return this}toBBox(t){return t}compareMinX(t,n){return t.minX-n.minX}compareMinY(t,n){return t.minY-n.minY}toJSON(){return this.data}fromJSON(t){return this.data=t,this}_all(t,n){const i=[];for(;t;)t.leaf?n.push(...t.children):i.push(...t.children),t=i.pop();return n}_build(t,n,i,s){const r=i-n+1;let a=this._maxEntries,o;if(r<=a)return o=Xh(t.slice(n,i+1)),ih(o,this.toBBox),o;s||(s=Math.ceil(Math.log(r)/Math.log(a)),a=Math.ceil(r/Math.pow(a,s-1))),o=Xh([]),o.leaf=!1,o.height=s;const l=Math.ceil(r/a),c=l*Math.ceil(Math.sqrt(a));pS(t,n,i,c,this.compareMinX);for(let h=n;h<=i;h+=c){const d=Math.min(h+c-1,i);pS(t,h,d,l,this.compareMinY);for(let f=h;f<=d;f+=l){const m=Math.min(f+l-1,d);o.children.push(this._build(t,f,m,s-1))}}return ih(o,this.toBBox),o}_chooseSubtree(t,n,i,s){for(;s.push(n),!(n.leaf||s.length-1===i);){let r=1/0,a=1/0,o;for(let l=0;l<n.children.length;l++){const c=n.children[l],h=Ev(c),d=Qz(t,c)-h;d<a?(a=d,r=h<r?h:r,o=c):d===a&&h<r&&(r=h,o=c)}n=o||n.children[0]}return n}_insert(t,n,i){const s=i?t:this.toBBox(t),r=[],a=this._chooseSubtree(s,this.data,n,r);for(a.children.push(t),Hd(a,s);n>=0&&r[n].children.length>this._maxEntries;)this._split(r,n),n--;this._adjustParentBBoxes(s,r,n)}_split(t,n){const i=t[n],s=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,s);const a=this._chooseSplitIndex(i,r,s),o=Xh(i.children.splice(a,i.children.length-a));o.height=i.height,o.leaf=i.leaf,ih(i,this.toBBox),ih(o,this.toBBox),n?t[n-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,n){this.data=Xh([t,n]),this.data.height=t.height+1,this.data.leaf=!1,ih(this.data,this.toBBox)}_chooseSplitIndex(t,n,i){let s,r=1/0,a=1/0;for(let o=n;o<=i-n;o++){const l=Gd(t,0,o,this.toBBox),c=Gd(t,o,i,this.toBBox),h=Gz(l,c),d=Ev(l)+Ev(c);h<r?(r=h,s=o,a=d<a?d:a):h===r&&d<a&&(a=d,s=o)}return s||i-n}_chooseSplitAxis(t,n,i){const s=t.leaf?this.compareMinX:Uz,r=t.leaf?this.compareMinY:zz;this._allDistMargin(t,n,i,s)<this._allDistMargin(t,n,i,r)&&t.children.sort(s)}_allDistMargin(t,n,i,s){t.children.sort(s);const r=this.toBBox,a=Gd(t,0,n,r),o=Gd(t,i-n,i,r);let l=Xf(a)+Xf(o);for(let c=n;c<i-n;c++){const h=t.children[c];Hd(a,t.leaf?r(h):h),l+=Xf(a)}for(let c=i-n-1;c>=n;c--){const h=t.children[c];Hd(o,t.leaf?r(h):h),l+=Xf(o)}return l}_adjustParentBBoxes(t,n,i){for(let s=i;s>=0;s--)Hd(n[s],t)}_condense(t){for(let n=t.length-1,i;n>=0;n--)t[n].children.length===0?n>0?(i=t[n-1].children,i.splice(i.indexOf(t[n]),1)):this.clear():ih(t[n],this.toBBox)}};function Oz(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function ih(e,t){Gd(e,0,e.children.length,t,e)}function Gd(e,t,n,i,s){s||(s=Xh(null)),s.minX=1/0,s.minY=1/0,s.maxX=-1/0,s.maxY=-1/0;for(let r=t;r<n;r++){const a=e.children[r];Hd(s,e.leaf?i(a):a)}return s}function Hd(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Uz(e,t){return e.minX-t.minX}function zz(e,t){return e.minY-t.minY}function Ev(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function Xf(e){return e.maxX-e.minX+(e.maxY-e.minY)}function Qz(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function Gz(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),s=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return Math.max(0,s-n)*Math.max(0,r-i)}function Cv(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Zf(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Xh(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function pS(e,t,n,i,s){const r=[t,n];for(;r.length;){if(n=r.pop(),t=r.pop(),n-t<=i)continue;const a=t+Math.ceil((n-t)/i/2)*i;Dz(e,a,t,n,s),r.push(t,a,a,n)}}function wv(e){var t;if(e.bbox)t=e.bbox;else if(Array.isArray(e)&&e.length===4)t=e;else if(Array.isArray(e)&&e.length===6)t=[e[0],e[1],e[3],e[4]];else if(e.type==="Feature")t=si(e);else if(e.type==="FeatureCollection")t=si(e);else throw new Error("invalid geojson");return{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}}var Hz=class{constructor(e=9){this.tree=new LE(e),this.tree.toBBox=wv}insert(e){if(e.type!=="Feature")throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:si(e),this.tree.insert(e),this}load(e){var t=[];return Array.isArray(e)?e.forEach(function(n){if(n.type!=="Feature")throw new Error("invalid features");n.bbox=n.bbox?n.bbox:si(n),t.push(n)}):Po(e,function(n){if(n.type!=="Feature")throw new Error("invalid features");n.bbox=n.bbox?n.bbox:si(n),t.push(n)}),this.tree.load(t),this}remove(e,t){if(e.type!=="Feature")throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:si(e),this.tree.remove(e,t),this}clear(){return this.tree.clear(),this}search(e){return Kt(this.tree.search(wv(e)))}collides(e){return this.tree.collides(wv(e))}all(){return Kt(this.tree.all())}toJSON(){return this.tree.toJSON()}fromJSON(e){return this.tree.fromJSON(e),this}};function BE(e){return new Hz(e)}function $z(e,t){if(t=t??{},!bf(t))throw new Error("options is invalid");var n=t.precision,i=t.coordinates,s=t.mutate;if(n=n==null||isNaN(n)?6:n,i=i==null||isNaN(i)?3:i,!e)throw new Error("<geojson> is required");if(typeof n!="number")throw new Error("<precision> must be a number");if(typeof i!="number")throw new Error("<coordinates> must be a number");(s===!1||s===void 0)&&(e=JSON.parse(JSON.stringify(e)));var r=Math.pow(10,n);return Ql(e,function(a){Vz(a,r,i)}),e}function Vz(e,t,n){e.length>n&&e.splice(n,e.length);for(var i=0;i<e.length;i++)e[i]=Math.round(e[i]*t)/t;return e}function N2(e){if(!e)throw new Error("geojson is required");const t=[];return Do(e,n=>{qz(n,t)}),Kt(t)}function qz(e,t){let n=[];const i=e.geometry;if(i!==null){switch(i.type){case"Polygon":n=as(i);break;case"LineString":n=[as(i)]}n.forEach(s=>{Wz(s,e.properties).forEach(r=>{r.id=t.length,t.push(r)})})}}function Wz(e,t){const n=[];return e.reduce((i,s)=>{const r=xs([i,s],t);return r.bbox=Yz(i,s),n.push(r),s}),n}function Yz(e,t){const n=e[0],i=e[1],s=t[0],r=t[1];return[n<s?n:s,i<r?i:r,n>s?n:s,i>r?i:r]}var P2=class{constructor(e=[],t=jz){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this.length++,this._up(this.length-1)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return this.length--,this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,i=t[e];for(;e>0;){const s=e-1>>1,r=t[s];if(n(i,r)>=0)break;t[e]=r,e=s}t[e]=i}_down(e){const{data:t,compare:n}=this,i=this.length>>1,s=t[e];for(;e<i;){let r=(e<<1)+1,a=t[r];const o=r+1;if(o<this.length&&n(t[o],a)<0&&(r=o,a=t[o]),n(a,s)>=0)break;t[e]=a,e=r}t[e]=s}};function jz(e,t){return e<t?-1:e>t?1:0}function D2(e,t){return e.p.x>t.p.x?1:e.p.x<t.p.x?-1:e.p.y!==t.p.y?e.p.y>t.p.y?1:-1:1}function Xz(e,t){return e.rightSweepEvent.p.x>t.rightSweepEvent.p.x?1:e.rightSweepEvent.p.x<t.rightSweepEvent.p.x?-1:e.rightSweepEvent.p.y!==t.rightSweepEvent.p.y?e.rightSweepEvent.p.y<t.rightSweepEvent.p.y?1:-1:1}var fS=class{constructor(e,t,n,i){this.p={x:e[0],y:e[1]},this.featureId=t,this.ringId=n,this.eventId=i,this.otherEvent=null,this.isLeftEndpoint=null}isSamePoint(e){return this.p.x===e.p.x&&this.p.y===e.p.y}};function Zz(e,t){if(e.type==="FeatureCollection"){const n=e.features;for(let i=0;i<n.length;i++)mS(n[i],t)}else mS(e,t)}var Jf=0,Kf=0,em=0;function mS(e,t){const n=e.type==="Feature"?e.geometry:e;let i=n.coordinates;(n.type==="Polygon"||n.type==="MultiLineString")&&(i=[i]),n.type==="LineString"&&(i=[[i]]);for(let s=0;s<i.length;s++)for(let r=0;r<i[s].length;r++){let a=i[s][r][0],o=null;Kf=Kf+1;for(let l=0;l<i[s][r].length-1;l++){o=i[s][r][l+1];const c=new fS(a,Jf,Kf,em),h=new fS(o,Jf,Kf,em+1);c.otherEvent=h,h.otherEvent=c,D2(c,h)>0?(h.isLeftEndpoint=!0,c.isLeftEndpoint=!1):(c.isLeftEndpoint=!0,h.isLeftEndpoint=!1),t.push(c),t.push(h),a=o,em=em+1}}Jf=Jf+1}var Jz=class{constructor(t){this.leftSweepEvent=t,this.rightSweepEvent=t.otherEvent}};function Kz(e,t){if(e===null||t===null||e.leftSweepEvent.ringId===t.leftSweepEvent.ringId&&(e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.rightSweepEvent)||e.leftSweepEvent.isSamePoint(t.leftSweepEvent)||e.leftSweepEvent.isSamePoint(t.rightSweepEvent)))return!1;const n=e.leftSweepEvent.p.x,i=e.leftSweepEvent.p.y,s=e.rightSweepEvent.p.x,r=e.rightSweepEvent.p.y,a=t.leftSweepEvent.p.x,o=t.leftSweepEvent.p.y,l=t.rightSweepEvent.p.x,c=t.rightSweepEvent.p.y,h=(c-o)*(s-n)-(l-a)*(r-i),d=(l-a)*(i-o)-(c-o)*(n-a),f=(s-n)*(i-o)-(r-i)*(n-a);if(h===0)return!1;const m=d/h,A=f/h;return m>=0&&m<=1&&A>=0&&A<=1?[n+m*(s-n),i+m*(r-i)]:!1}function eQ(e,t){t=t||!1;const n=[],i=new P2([],Xz);for(;e.length;){const s=e.pop();if(s.isLeftEndpoint){const r=new Jz(s);for(let a=0;a<i.data.length;a++){const o=i.data[a];if(t&&o.leftSweepEvent.featureId===s.featureId)continue;const l=Kz(r,o);l!==!1&&n.push(l)}i.push(r)}else s.isLeftEndpoint===!1&&i.pop()}return n}function tQ(e,t){const n=new P2([],D2);return Zz(e,n),eQ(n,t)}var nQ=tQ;function ju(e,t,n={}){const{removeDuplicates:i=!0,ignoreSelfIntersections:s=!0}=n;let r=[];e.type==="FeatureCollection"?r=r.concat(e.features):e.type==="Feature"?r.push(e):(e.type==="LineString"||e.type==="Polygon"||e.type==="MultiLineString"||e.type==="MultiPolygon")&&r.push(or(e)),t.type==="FeatureCollection"?r=r.concat(t.features):t.type==="Feature"?r.push(t):(t.type==="LineString"||t.type==="Polygon"||t.type==="MultiLineString"||t.type==="MultiPolygon")&&r.push(or(t));const a=nQ(Kt(r),s);let o=[];if(i){const l={};a.forEach(c=>{const h=c.join(",");l[h]||(l[h]=!0,o.push(c))})}else o=a;return Kt(o.map(l=>wi(l)))}var iQ=Object.defineProperty,sQ=Object.defineProperties,rQ=Object.getOwnPropertyDescriptors,gS=Object.getOwnPropertySymbols,aQ=Object.prototype.hasOwnProperty,oQ=Object.prototype.propertyIsEnumerable,_S=(e,t,n)=>t in e?iQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lQ=(e,t)=>{for(var n in t||(t={}))aQ.call(t,n)&&_S(e,n,t[n]);if(gS)for(var n of gS(t))oQ.call(t,n)&&_S(e,n,t[n]);return e},cQ=(e,t)=>sQ(e,rQ(t));function au(e,t,n={}){if(!e||!t)throw new Error("lines and inputPoint are required arguments");const i=Si(t);let s=wi([1/0,1/0],{lineStringIndex:-1,segmentIndex:-1,totalDistance:-1,lineDistance:-1,segmentDistance:-1,pointDistance:1/0,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),r=0,a=0,o=-1;return Do(e,function(l,c,h){o!==h&&(o=h,a=0);const d=as(l);for(let f=0;f<d.length-1;f++){const m=wi(d[f]),A=Si(m),y=wi(d[f+1]),x=Si(y),v=dp(m,y,n);let b,w;x[0]===i[0]&&x[1]===i[1]?[b,w]=[x,!0]:A[0]===i[0]&&A[1]===i[1]?[b,w]=[A,!1]:[b,w]=dQ(A,x,i);const S=dp(t,b,n);if(S<s.properties.pointDistance){const R=dp(m,b,n);s=wi(b,{lineStringIndex:h,segmentIndex:w?f+1:f,totalDistance:r+R,lineDistance:a+R,segmentDistance:R,pointDistance:S,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),s.properties=cQ(lQ({},s.properties),{multiFeatureIndex:s.properties.lineStringIndex,index:s.properties.segmentIndex,location:s.properties.totalDistance,dist:s.properties.pointDistance})}r+=v,a+=v}}),s}function Zl(e,t){const[n,i,s]=e,[r,a,o]=t;return n*r+i*a+s*o}function pd(e,t){const[n,i,s]=e,[r,a,o]=t;return[i*o-s*a,s*r-n*o,n*a-i*r]}function hQ(e){return Math.sqrt(Math.pow(e[0],2)+Math.pow(e[1],2)+Math.pow(e[2],2))}function AS(e){const t=hQ(e);return[e[0]/t,e[1]/t,e[2]/t]}function Sv(e){const t=Qs(e[1]),n=Qs(e[0]);return[Math.cos(t)*Math.cos(n),Math.cos(t)*Math.sin(n),Math.sin(t)]}function uQ(e){const[t,n,i]=e,s=A_(Math.asin(Math.min(Math.max(i,-1),1)));return[A_(Math.atan2(n,t)),s]}function dQ(e,t,n){const i=Sv(e),s=Sv(t),r=Sv(n),a=pd(i,s);if(a[0]===0&&a[1]===0&&a[2]===0)return Zl(i,s)>0?[[...t],!0]:[[...n],!1];const o=pd(a,r);if(o[0]===0&&o[1]===0&&o[2]===0)return[[...t],!0];const l=AS(pd(o,a)),c=[-l[0],-l[1],-l[2]],h=Zl(r,l)>Zl(r,c)?l:c,d=AS(a),f=Zl(pd(i,h),d),m=Zl(pd(h,s),d);return f>=0&&m>=0?[uQ(h),!1]:Zl(i,r)>Zl(s,r)?[[...e],!1]:[[...t],!0]}function RE(e,t){if(!e)throw new Error("line is required");if(!t)throw new Error("splitter is required");const n=v_(e),i=v_(t);if(n!=="LineString")throw new Error("line must be LineString");if(i==="FeatureCollection")throw new Error("splitter cannot be a FeatureCollection");if(i==="GeometryCollection")throw new Error("splitter cannot be a GeometryCollection");var s=$z(t,{precision:7});switch(e.type!=="Feature"&&(e=or(e)),i){case"Point":return ib(e,s);case"MultiPoint":return vS(e,s);case"LineString":case"MultiLineString":case"Polygon":case"MultiPolygon":return vS(e,ju(e,s,{ignoreSelfIntersections:!0}))}}function vS(e,t){var n=[],i=BE();return Do(t,function(s){if(n.forEach(function(o,l){o.id=l}),!n.length)n=ib(e,s).features,i.load(Kt(n));else{var r=i.search(s);if(r.features.length){var a=F2(s,r);n=n.filter(function(o){return o.id!==a.id}),i.remove(a),Po(ib(a,s),function(o){n.push(o),i.insert(o)})}}}),Kt(n)}function ib(e,t){var n=[],i=as(e)[0],s=as(e)[e.geometry.coordinates.length-1];if(Iv(i,Si(t))||Iv(s,Si(t)))return Kt([e]);var r=BE(),a=N2(e);r.load(a);var o=r.search(t);if(!o.features.length)return Kt([e]);var l=F2(t,o),c=Az(a,function(h,d,f){var m=as(d)[1],A=Si(t);return f===l.id?(h.push(A),n.push(xs(h)),Iv(A,m)?[A]:[A,m]):(h.push(m),h)},[i]);return c.length>1&&n.push(xs(c)),Kt(n)}function F2(e,t){if(!t.features.length)throw new Error("lines must contain features");if(t.features.length===1)return t.features[0];var n,i=1/0;return Po(t,function(s){var r=au(s,e).properties.dist;r<i&&(n=s,i=r)}),n}function Iv(e,t){return e[0]===t[0]&&e[1]===t[1]}function yS(e,t){const n=$r(e),i=$r(t),s=n.type,r=i.type,a=n.coordinates,o=i.coordinates;switch(s){case"Point":if(r==="Point")return NE(a,o);throw new Error("feature2 "+r+" geometry not supported");case"MultiPoint":switch(r){case"Point":return mQ(n,i);case"MultiPoint":return gQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"LineString":switch(r){case"Point":return Gs(i,n,{ignoreEndVertices:!0});case"LineString":return vQ(n,i);case"MultiPoint":return _Q(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"Polygon":switch(r){case"Point":return Ii(i,n,{ignoreBoundary:!0});case"LineString":return bQ(n,i);case"Polygon":return kE(n,i);case"MultiPoint":return AQ(n,i);case"MultiPolygon":return fQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"MultiPolygon":if(r==="Polygon")return pQ(n,i);throw new Error("feature2 "+r+" geometry not supported");default:throw new Error("feature1 "+s+" geometry not supported")}}function pQ(e,t){return e.coordinates.some(n=>kE({type:"Polygon",coordinates:n},t))}function fQ(e,t){return t.coordinates.every(n=>kE(e,{type:"Polygon",coordinates:n}))}function mQ(e,t){let n,i=!1;for(n=0;n<e.coordinates.length;n++)if(NE(e.coordinates[n],t.coordinates)){i=!0;break}return i}function gQ(e,t){for(const n of t.coordinates){let i=!1;for(const s of e.coordinates)if(NE(n,s)){i=!0;break}if(!i)return!1}return!0}function _Q(e,t){let n=!1;for(const i of t.coordinates)if(Gs(i,e,{ignoreEndVertices:!0})&&(n=!0),!Gs(i,e))return!1;return!!n}function AQ(e,t){for(const n of t.coordinates)if(!Ii(n,e,{ignoreBoundary:!0}))return!1;return!0}function vQ(e,t){let n=!1;for(const i of t.coordinates)if(Gs({type:"Point",coordinates:i},e,{ignoreEndVertices:!0})&&(n=!0),!Gs({type:"Point",coordinates:i},e,{ignoreEndVertices:!1}))return!1;return n}function yQ(e,t){const n=e.coordinates,i=[];for(let s=0;s<n.length-1;s++){const r=xs([n[s],n[s+1]]),a=RE(r,or(t));a.features.length===0?i.push(r):i.push(...a.features)}return Kt(i)}function bQ(e,t){if(!O2(si(e),si(t)))return!1;for(const s of t.coordinates)if(!Ii(s,e))return!1;let n=!1;const i=yQ(t,e);for(const s of i.features){const r=xQ(s.geometry.coordinates[0],s.geometry.coordinates[1]);if(!Ii(r,e))return!1;!n&&Ii(r,e,{ignoreBoundary:!0})&&(n=!0)}return n}function kE(e,t){if(e.type==="Feature"&&e.geometry===null||t.type==="Feature"&&t.geometry===null||!O2(si(e),si(t)))return!1;const n=$r(t).coordinates;for(const i of n)for(const s of i)if(!Ii(s,e))return!1;return!0}function O2(e,t){return!(e[0]>t[0]||e[2]<t[2]||e[1]>t[1]||e[3]<t[3])}function NE(e,t){return e[0]===t[0]&&e[1]===t[1]}function xQ(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function b_(e,t={}){const n=$r(e);switch(!t.properties&&e.type==="Feature"&&(t.properties=e.properties),n.type){case"Polygon":return EQ(n,t);case"MultiPolygon":return CQ(n,t);default:throw new Error("invalid poly")}}function EQ(e,t={}){const n=$r(e).coordinates;return U2(n,t.properties?t.properties:e.type==="Feature"?e.properties:{})}function CQ(e,t={}){const n=$r(e).coordinates,i=t.properties?t.properties:e.type==="Feature"?e.properties:{},s=[];return n.forEach(r=>{s.push(U2(r,i))}),Kt(s)}function U2(e,t){return e.length>1?T2(e,t):xs(e[0],t)}var wQ=Object.defineProperty,Xu=(e,t)=>wQ(e,"name",{value:t,configurable:!0}),z2=class{constructor(t){this.direction=!1,this.compareProperties=!0;var n,i,s;this.precision=10**-((n=t?.precision)!=null?n:17),this.direction=(i=t?.direction)!=null?i:!1,this.compareProperties=(s=t?.compareProperties)!=null?s:!0}compare(t,n){if(t.type!==n.type||!$d(t,n))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,n.coordinates);case"LineString":return this.compareLine(t.coordinates,n.coordinates);case"Polygon":return this.comparePolygon(t,n);case"GeometryCollection":return this.compareGeometryCollection(t,n);case"Feature":return this.compareFeature(t,n);case"FeatureCollection":return this.compareFeatureCollection(t,n);default:if(t.type.startsWith("Multi")){const i=sb(t),s=sb(n);return i.every(r=>s.some(a=>this.compare(r,a)))}}return!1}compareCoord(t,n){return t.length===n.length&&t.every((i,s)=>Math.abs(i-n[s])<this.precision)}compareLine(t,n,i=0,s=!1){if(!$d(t,n))return!1;const r=t;let a=n;if(s&&!this.compareCoord(r[0],a[0])){const l=this.fixStartIndex(a,r);if(l)a=l;else return!1}const o=this.compareCoord(r[i],a[i]);return this.direction||o?this.comparePath(r,a):this.compareCoord(r[i],a[a.length-(1+i)])?this.comparePath(r.slice().reverse(),a):!1}fixStartIndex(t,n){let i,s=-1;for(let r=0;r<t.length;r++)if(this.compareCoord(t[r],n[0])){s=r;break}return s>=0&&(i=[].concat(t.slice(s,t.length),t.slice(1,s+1))),i}comparePath(t,n){return t.every((i,s)=>this.compareCoord(i,n[s]))}comparePolygon(t,n){if(this.compareLine(t.coordinates[0],n.coordinates[0],1,!0)){const i=t.coordinates.slice(1,t.coordinates.length),s=n.coordinates.slice(1,n.coordinates.length);return i.every(r=>s.some(a=>this.compareLine(r,a,1,!0)))}return!1}compareGeometryCollection(t,n){return $d(t.geometries,n.geometries)&&this.compareBBox(t,n)&&t.geometries.every((i,s)=>this.compare(i,n.geometries[s]))}compareFeature(t,n){return t.id===n.id&&(this.compareProperties?PE(t.properties,n.properties):!0)&&this.compareBBox(t,n)&&this.compare(t.geometry,n.geometry)}compareFeatureCollection(t,n){return $d(t.features,n.features)&&this.compareBBox(t,n)&&t.features.every((i,s)=>this.compare(i,n.features[s]))}compareBBox(t,n){return!t.bbox&&!n.bbox||(t.bbox&&n.bbox?this.compareCoord(t.bbox,n.bbox):!1)}};Xu(z2,"GeojsonEquality");var SQ=z2;function $d(e,t){return e.coordinates?e.coordinates.length===t.coordinates.length:e.length===t.length}Xu($d,"sameLength");function sb(e){return e.coordinates.map(t=>({type:e.type.replace("Multi",""),coordinates:t}))}Xu(sb,"explode");function Q2(e,t,n){return new SQ(n).compare(e,t)}Xu(Q2,"geojsonEquality");function PE(e,t){if(e===null&&t===null)return!0;if(e===null||t===null)return!1;const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(var s of n){const r=e[s],a=t[s],o=bS(r)&&bS(a);if(o&&!PE(r,a)||!o&&r!==a)return!1}return!0}Xu(PE,"equal");var bS=Xu(e=>e!=null&&typeof e=="object","isObject");function G2(e,t={}){var n=typeof t=="object"?t.mutate:t;if(!e)throw new Error("geojson is required");var i=v_(e),s=[];switch(i){case"LineString":s=Mv(e,i);break;case"MultiLineString":case"Polygon":as(e).forEach(function(a){s.push(Mv(a,i))});break;case"MultiPolygon":as(e).forEach(function(a){var o=[];a.forEach(function(l){o.push(Mv(l,i))}),s.push(o)});break;case"Point":return e;case"MultiPoint":var r={};as(e).forEach(function(a){var o=a.join("-");Object.prototype.hasOwnProperty.call(r,o)||(s.push(a),r[o]=!0)});break;default:throw new Error(i+" geometry not supported")}return e.coordinates?n===!0?(e.coordinates=s,e):{type:i,coordinates:s}:n===!0?(e.geometry.coordinates=s,e):or({type:i,coordinates:s},e.properties,{bbox:e.bbox,id:e.id})}function Mv(e,t){const n=as(e);if(n.length===2&&!xS(n[0],n[1]))return n;const i=[];let s=0,r=1,a=2;for(i.push(n[s]);a<n.length;)Gs(n[r],xs([n[s],n[a]]))?r=a:(i.push(n[r]),s=r,r++,a=r),a++;if(i.push(n[r]),t==="Polygon"||t==="MultiPolygon"){if(Gs(i[0],xs([i[1],i[i.length-2]]))&&(i.shift(),i.pop(),i.push(i[0])),i.length<4)throw new Error("invalid polygon, fewer than 4 points");if(!xS(i[0],i[i.length-1]))throw new Error("invalid polygon, first and last points not equal")}return i}function xS(e,t){return e[0]===t[0]&&e[1]===t[1]}function IQ(e,t,{ignoreSelfIntersections:n=!0}={ignoreSelfIntersections:!0}){let i=!0;return Do(e,s=>{Do(t,r=>{if(i===!1)return!1;i=MQ(s.geometry,r.geometry,n)})}),i}function MQ(e,t,n){switch(e.type){case"Point":switch(t.type){case"Point":return!RQ(e.coordinates,t.coordinates);case"LineString":return!ES(t,e);case"Polygon":return!Ii(e,t)}break;case"LineString":switch(t.type){case"Point":return!ES(e,t);case"LineString":return!TQ(e,t,n);case"Polygon":return!CS(t,e,n)}break;case"Polygon":switch(t.type){case"Point":return!Ii(t,e);case"LineString":return!CS(e,t,n);case"Polygon":return!LQ(t,e,n)}}return!1}function ES(e,t){for(let n=0;n<e.coordinates.length-1;n++)if(BQ(e.coordinates[n],e.coordinates[n+1],t.coordinates))return!0;return!1}function TQ(e,t,n){return ju(e,t,{ignoreSelfIntersections:n}).features.length>0}function CS(e,t,n){for(const i of t.coordinates)if(Ii(i,e))return!0;return ju(t,b_(e),{ignoreSelfIntersections:n}).features.length>0}function LQ(e,t,n){for(const i of e.coordinates[0])if(Ii(i,t))return!0;for(const i of t.coordinates[0])if(Ii(i,e))return!0;return ju(b_(e),b_(t),{ignoreSelfIntersections:n}).features.length>0}function BQ(e,t,n){const i=n[0]-e[0],s=n[1]-e[1],r=t[0]-e[0],a=t[1]-e[1];return i*a-s*r!==0?!1:Math.abs(r)>=Math.abs(a)?r>0?e[0]<=n[0]&&n[0]<=t[0]:t[0]<=n[0]&&n[0]<=e[0]:a>0?e[1]<=n[1]&&n[1]<=t[1]:t[1]<=n[1]&&n[1]<=e[1]}function RQ(e,t){return e[0]===t[0]&&e[1]===t[1]}function DE(e,t,{ignoreSelfIntersections:n=!0}={}){let i=!1;return Do(e,s=>{Do(t,r=>{if(i===!0)return!0;i=!IQ(s.geometry,r.geometry,{ignoreSelfIntersections:n})})}),i}function H2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tv,wS;function kQ(){return wS||(wS=1,Tv=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var i,s,r;if(Array.isArray(t)){if(i=t.length,i!=n.length)return!1;for(s=i;s--!==0;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(r=Object.keys(t),i=r.length,i!==Object.keys(n).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,r[s]))return!1;for(s=i;s--!==0;){var a=r[s];if(!e(t[a],n[a]))return!1}return!0}return t!==t&&n!==n}),Tv}var Vd=H2(kQ());function NQ(e,t,n={}){if(n=n||{},!bf(n))throw new Error("options is invalid");var i=n.tolerance||0,s=[],r=BE();const a=N2(e);r.load(a);var o;let l=[];return Qd(t,function(c){var h=!1;c&&(Po(r.search(c),function(d){if(h===!1){var f=as(c).sort(),m=as(d).sort();if(Vd(f,m))h=!0,o?o=Lv(o,c)||o:o=c;else if(i===0?Gs(f[0],d)&&Gs(f[1],d):au(d,f[0]).properties.dist<=i&&au(d,f[1]).properties.dist<=i)h=!0,o?o=Lv(o,c)||o:o=c;else if(i===0?Gs(m[0],c)&&Gs(m[1],c):au(c,m[0]).properties.dist<=i&&au(c,m[1]).properties.dist<=i)if(o){const A=Lv(o,d);A?o=A:l.push(d)}else o=d}}),h===!1&&o&&(s.push(o),l.length&&(s=s.concat(l),l=[]),o=void 0))}),o&&s.push(o),Kt(s)}function Lv(e,t){var n=as(t),i=as(e),s=i[0],r=i[i.length-1],a=e.geometry.coordinates;if(Vd(n[0],s))a.unshift(n[1]);else if(Vd(n[0],r))a.push(n[1]);else if(Vd(n[1],s))a.unshift(n[0]);else if(Vd(n[1],r))a.push(n[0]);else return;return e}function $2(e,t){const n=$r(e),i=$r(t),s=n.type,r=i.type;if(s==="MultiPoint"&&r!=="MultiPoint"||(s==="LineString"||s==="MultiLineString")&&r!=="LineString"&&r!=="MultiLineString"||(s==="Polygon"||s==="MultiPolygon")&&r!=="Polygon"&&r!=="MultiPolygon")throw new Error("features must be of the same type");if(s==="Point")throw new Error("Point geometry not supported");if(Q2(e,t,{precision:6}))return!1;let a=0;switch(s){case"MultiPoint":for(var o=0;o<n.coordinates.length;o++)for(var l=0;l<i.coordinates.length;l++){var c=n.coordinates[o],h=i.coordinates[l];if(c[0]===h[0]&&c[1]===h[1])return!0}return!1;case"LineString":case"MultiLineString":Qd(e,d=>{Qd(t,f=>{NQ(d,f).features.length&&a++})});break;case"Polygon":case"MultiPolygon":Qd(e,d=>{Qd(t,f=>{ju(d,f).features.length&&a++})});break}return a>0}function PQ(e,t){var n=$r(e),i=$r(t),s=n.type,r=i.type;switch(s){case"Point":switch(r){case"MultiPoint":return DQ(n,i);case"LineString":return Gs(n,i,{ignoreEndVertices:!0});case"Polygon":case"MultiPolygon":return Ii(n,i,{ignoreBoundary:!0});default:throw new Error("feature2 "+r+" geometry not supported")}case"MultiPoint":switch(r){case"MultiPoint":return FQ(n,i);case"LineString":return OQ(n,i);case"Polygon":case"MultiPolygon":return UQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"LineString":switch(r){case"LineString":return zQ(n,i);case"Polygon":case"MultiPolygon":return GQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}case"Polygon":switch(r){case"Polygon":case"MultiPolygon":return HQ(n,i);default:throw new Error("feature2 "+r+" geometry not supported")}default:throw new Error("feature1 "+s+" geometry not supported")}}function DQ(e,t){var n,i=!1;for(n=0;n<t.coordinates.length;n++)if(q2(t.coordinates[n],e.coordinates)){i=!0;break}return i}function FQ(e,t){for(var n=0;n<e.coordinates.length;n++){for(var i=!1,s=0;s<t.coordinates.length;s++)q2(e.coordinates[n],t.coordinates[s])&&(i=!0);if(!i)return!1}return!0}function OQ(e,t){for(var n=!1,i=0;i<e.coordinates.length;i++){if(!Gs(e.coordinates[i],t))return!1;n||(n=Gs(e.coordinates[i],t,{ignoreEndVertices:!0}))}return n}function UQ(e,t){for(var n=!0,i=!1,s=0;s<e.coordinates.length;s++){if(i=Ii(e.coordinates[s],t),!i){n=!1;break}i=Ii(e.coordinates[s],t,{ignoreBoundary:!0})}return n&&i}function zQ(e,t){for(var n=0;n<e.coordinates.length;n++)if(!Gs(e.coordinates[n],t))return!1;return!0}function QQ(e,t){const n=e.coordinates,i=[];for(let s=0;s<n.length-1;s++){const r=xs([n[s],n[s+1]]),a=RE(r,or(t));a.features.length===0?i.push(r):i.push(...a.features)}return Kt(i)}function GQ(e,t){if(!V2(si(t),si(e)))return!1;for(const s of e.coordinates)if(!Ii(s,t))return!1;let n=!1;const i=QQ(e,t);for(const s of i.features){const r=$Q(s.geometry.coordinates[0],s.geometry.coordinates[1]);if(!Ii(r,t))return!1;!n&&Ii(r,t,{ignoreBoundary:!0})&&(n=!0)}return n}function HQ(e,t){var n=si(e);if(!V2(si(t),n))return!1;for(var i=0;i<e.coordinates[0].length;i++)if(!Ii(e.coordinates[0][i],t))return!1;return!0}function V2(e,t){return!(e[0]>t[0]||e[2]<t[2]||e[1]>t[1]||e[3]<t[3])}function q2(e,t){return e[0]===t[0]&&e[1]===t[1]}function $Q(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function W2(e,t={}){const n=si(e);return wi([(n[0]+n[2])/2,(n[1]+n[3])/2],t.properties,t)}var zg={exports:{}},VQ=zg.exports,SS;function qQ(){return SS||(SS=1,(function(e,t){(function(n,i){e.exports=i()})(VQ,(function(){function n(_,u){(u==null||u>_.length)&&(u=_.length);for(var p=0,g=Array(u);p<u;p++)g[p]=_[p];return g}function i(_,u,p){return u=h(u),(function(g,E){if(E&&(typeof E=="object"||typeof E=="function"))return E;if(E!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return(function(B){if(B===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return B})(g)})(_,f()?Reflect.construct(u,p||[],h(_).constructor):u.apply(_,p))}function s(_,u){if(!(_ instanceof u))throw new TypeError("Cannot call a class as a function")}function r(_,u,p){if(f())return Reflect.construct.apply(null,arguments);var g=[null];g.push.apply(g,u);var E=new(_.bind.apply(_,g));return p&&m(E,p.prototype),E}function a(_,u){for(var p=0;p<u.length;p++){var g=u[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(_,x(g.key),g)}}function o(_,u,p){return u&&a(_.prototype,u),p&&a(_,p),Object.defineProperty(_,"prototype",{writable:!1}),_}function l(_,u){var p=typeof Symbol<"u"&&_[Symbol.iterator]||_["@@iterator"];if(!p){if(Array.isArray(_)||(p=v(_))||u){p&&(_=p);var g=0,E=function(){};return{s:E,n:function(){return g>=_.length?{done:!0}:{done:!1,value:_[g++]}},e:function(Y){throw Y},f:E}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
270
270
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var B,F=!0,G=!1;return{s:function(){p=p.call(_)},n:function(){var Y=p.next();return F=Y.done,Y},e:function(Y){G=!0,B=Y},f:function(){try{F||p.return==null||p.return()}finally{if(G)throw B}}}}function c(){return c=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(_,u,p){var g=(function(B,F){for(;!{}.hasOwnProperty.call(B,F)&&(B=h(B))!==null;);return B})(_,u);if(g){var E=Object.getOwnPropertyDescriptor(g,u);return E.get?E.get.call(arguments.length<3?_:p):E.value}},c.apply(null,arguments)}function h(_){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(u){return u.__proto__||Object.getPrototypeOf(u)},h(_)}function d(_,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function");_.prototype=Object.create(u&&u.prototype,{constructor:{value:_,writable:!0,configurable:!0}}),Object.defineProperty(_,"prototype",{writable:!1}),u&&m(_,u)}function f(){try{var _=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(f=function(){return!!_})()}function m(_,u){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(p,g){return p.__proto__=g,p},m(_,u)}function A(_,u,p,g){var E=c(h(1&g?_.prototype:_),u,p);return 2&g&&typeof E=="function"?function(B){return E.apply(p,B)}:E}function y(_){return(function(u){if(Array.isArray(u))return n(u)})(_)||(function(u){if(typeof Symbol<"u"&&u[Symbol.iterator]!=null||u["@@iterator"]!=null)return Array.from(u)})(_)||v(_)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
271
271
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function x(_){var u=(function(p,g){if(typeof p!="object"||!p)return p;var E=p[Symbol.toPrimitive];if(E!==void 0){var B=E.call(p,g);if(typeof B!="object")return B;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(p)})(_,"string");return typeof u=="symbol"?u:u+""}function v(_,u){if(_){if(typeof _=="string")return n(_,u);var p={}.toString.call(_).slice(8,-1);return p==="Object"&&_.constructor&&(p=_.constructor.name),p==="Map"||p==="Set"?Array.from(_):p==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(p)?n(_,u):void 0}}function b(_){var u=typeof Map=="function"?new Map:void 0;return b=function(p){if(p===null||!(function(E){try{return Function.toString.call(E).indexOf("[native code]")!==-1}catch{return typeof E=="function"}})(p))return p;if(typeof p!="function")throw new TypeError("Super expression must either be null or a function");if(u!==void 0){if(u.has(p))return u.get(p);u.set(p,g)}function g(){return r(p,arguments,h(this).constructor)}return g.prototype=Object.create(p.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m(g,p)},b(_)}var w=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(u){this._quadrantSegments=u,this._quadrantSegments===0&&(this._joinStyle=_.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=_.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),u<=0&&(this._quadrantSegments=1),this._joinStyle!==_.JOIN_ROUND&&(this._quadrantSegments=_.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(u){this._joinStyle=u}},{key:"setSimplifyFactor",value:function(u){this._simplifyFactor=u<0?0:u}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(u){this._endCapStyle=u}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(u){this._mitreLimit=u}},{key:"setSingleSided",value:function(u){this._isSingleSided=u}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=_.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=_.CAP_ROUND,this._joinStyle=_.JOIN_ROUND,this._mitreLimit=_.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=_.DEFAULT_SIMPLIFY_FACTOR,arguments.length!==0){if(arguments.length===1){var u=arguments[0];this.setQuadrantSegments(u)}else if(arguments.length===2){var p=arguments[0],g=arguments[1];this.setQuadrantSegments(p),this.setEndCapStyle(g)}else if(arguments.length===4){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3];this.setQuadrantSegments(E),this.setEndCapStyle(B),this.setJoinStyle(F),this.setMitreLimit(G)}}}},{key:"bufferDistanceError",value:function(u){var p=Math.PI/2/u;return 1-Math.cos(p/2)}}])})();w.CAP_ROUND=1,w.CAP_FLAT=2,w.CAP_SQUARE=3,w.JOIN_ROUND=1,w.JOIN_MITRE=2,w.JOIN_BEVEL=3,w.DEFAULT_QUADRANT_SEGMENTS=8,w.DEFAULT_MITRE_LIMIT=5,w.DEFAULT_SIMPLIFY_FACTOR=.01;var S=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({Exception:u})[0],g}return d(u,_),o(u,[{key:"toString",value:function(){return this.message}}])})(b(Error)),R=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({IllegalArgumentException:u})[0],g}return d(u,_),o(u)})(S),k=(function(){return o((function _(){s(this,_)}),[{key:"filter",value:function(_){}}])})();function L(){}function T(){}function C(){}var I,M,U,N,D,P,O,Q,z=(function(){return o((function _(){s(this,_)}),null,[{key:"equalsWithTolerance",value:function(_,u,p){return Math.abs(_-u)<=p}}])})(),H=(function(){return o((function _(u,p){s(this,_),this.low=p||0,this.high=u||0}),null,[{key:"toBinaryString",value:function(_){var u,p="";for(u=2147483648;u>0;u>>>=1)p+=(_.high&u)===u?"1":"0";for(u=2147483648;u>0;u>>>=1)p+=(_.low&u)===u?"1":"0";return p}}])})();function W(){}function te(){}W.NaN=NaN,W.isNaN=function(_){return Number.isNaN(_)},W.isInfinite=function(_){return!Number.isFinite(_)},W.MAX_VALUE=Number.MAX_VALUE,W.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,W.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,typeof Float64Array=="function"&&typeof Int32Array=="function"?(P=2146435072,O=new Float64Array(1),Q=new Int32Array(O.buffer),W.doubleToLongBits=function(_){O[0]=_;var u=0|Q[0],p=0|Q[1];return(p&P)===P&&1048575&p&&u!==0&&(u=0,p=2146959360),new H(p,u)},W.longBitsToDouble=function(_){return Q[0]=_.low,Q[1]=_.high,O[0]}):(I=1023,M=Math.log2,U=Math.floor,N=Math.pow,D=(function(){for(var _=53;_>0;_--){var u=N(2,_)-1;if(U(M(u))+1===_)return u}return 0})(),W.doubleToLongBits=function(_){var u,p,g,E,B,F,G,Y,ae;if(_<0||1/_===Number.NEGATIVE_INFINITY?(F=1<<31,_=-_):F=0,_===0)return new H(Y=F,ae=0);if(_===1/0)return new H(Y=2146435072|F,ae=0);if(_!=_)return new H(Y=2146959360,ae=0);if(E=0,ae=0,(u=U(_))>1)if(u<=D)(E=U(M(u)))<=20?(ae=0,Y=u<<20-E&1048575):(ae=u%(p=N(2,g=E-20))<<32-g,Y=u/p&1048575);else for(g=u,ae=0;(g=U(p=g/2))!==0;)E++,ae>>>=1,ae|=(1&Y)<<31,Y>>>=1,p!==g&&(Y|=524288);if(G=E+I,B=u===0,u=_-u,E<52&&u!==0)for(g=0;;){if((p=2*u)>=1?(u=p-1,B?(G--,B=!1):(g<<=1,g|=1,E++)):(u=p,B?--G==0&&(E++,B=!1):(g<<=1,E++)),E===20)Y|=g,g=0;else if(E===52){ae|=g;break}if(p===1){E<20?Y|=g<<20-E:E<52&&(ae|=g<<52-E);break}}return Y|=G<<20,new H(Y|=F,ae)},W.longBitsToDouble=function(_){var u,p,g,E,B=_.high,F=_.low,G=B&1<<31?-1:1;for(g=((2146435072&B)>>20)-I,E=0,p=1<<19,u=1;u<=20;u++)B&p&&(E+=N(2,-u)),p>>>=1;for(p=1<<31,u=21;u<=52;u++)F&p&&(E+=N(2,-u)),p>>>=1;if(g===-1023){if(E===0)return 0*G;g=-1022}else{if(g===1024)return E===0?G/0:NaN;E+=1}return G*E*N(2,g)});var J=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({RuntimeException:u})[0],g}return d(u,_),o(u)})(S),K=(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(){if(arguments.length===0)J.constructor_.call(this);else if(arguments.length===1){var p=arguments[0];J.constructor_.call(this,p)}}}])})(J),re=(function(){function _(){s(this,_)}return o(_,null,[{key:"shouldNeverReachHere",value:function(){if(arguments.length===0)_.shouldNeverReachHere(null);else if(arguments.length===1){var u=arguments[0];throw new K("Should never reach here"+(u!==null?": "+u:""))}}},{key:"isTrue",value:function(){if(arguments.length===1){var u=arguments[0];_.isTrue(u,null)}else if(arguments.length===2){var p=arguments[1];if(!arguments[0])throw p===null?new K:new K(p)}}},{key:"equals",value:function(){if(arguments.length===2){var u=arguments[0],p=arguments[1];_.equals(u,p,null)}else if(arguments.length===3){var g=arguments[0],E=arguments[1],B=arguments[2];if(!E.equals(g))throw new K("Expected "+g+" but encountered "+E+(B!==null?": "+B:""))}}}])})(),ce=new ArrayBuffer(8),oe=new Float64Array(ce),ge=new Int32Array(ce),ie=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getM",value:function(){return W.NaN}},{key:"setOrdinate",value:function(u,p){switch(u){case _.X:this.x=p;break;case _.Y:this.y=p;break;case _.Z:this.setZ(p);break;default:throw new R("Invalid ordinate index: "+u)}}},{key:"equals2D",value:function(){if(arguments.length===1){var u=arguments[0];return this.x===u.x&&this.y===u.y}if(arguments.length===2){var p=arguments[0],g=arguments[1];return!!z.equalsWithTolerance(this.x,p.x,g)&&!!z.equalsWithTolerance(this.y,p.y,g)}}},{key:"setM",value:function(u){throw new R("Invalid ordinate index: "+_.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(u){switch(u){case _.X:return this.x;case _.Y:return this.y;case _.Z:return this.getZ()}throw new R("Invalid ordinate index: "+u)}},{key:"equals3D",value:function(u){return this.x===u.x&&this.y===u.y&&(this.getZ()===u.getZ()||W.isNaN(this.getZ())&&W.isNaN(u.getZ()))}},{key:"equals",value:function(u){return u instanceof _&&this.equals2D(u)}},{key:"equalInZ",value:function(u,p){return z.equalsWithTolerance(this.getZ(),u.getZ(),p)}},{key:"setX",value:function(u){this.x=u}},{key:"compareTo",value:function(u){var p=u;return this.x<p.x?-1:this.x>p.x?1:this.y<p.y?-1:this.y>p.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(u){this.z=u}},{key:"clone",value:function(){try{return null}catch(u){if(u instanceof CloneNotSupportedException)return re.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw u}}},{key:"copy",value:function(){return new _(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(u){var p=this.x-u.x,g=this.y-u.y,E=this.getZ()-u.getZ();return Math.sqrt(p*p+g*g+E*E)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(u){this.y=u}},{key:"distance",value:function(u){var p=this.x-u.x,g=this.y-u.y;return Math.sqrt(p*p+g*g)}},{key:"hashCode",value:function(){var u=17;return u=37*(u=37*u+_.hashCode(this.x))+_.hashCode(this.y)}},{key:"setCoordinate",value:function(u){this.x=u.x,this.y=u.y,this.z=u.getZ()}},{key:"interfaces_",get:function(){return[L,T,C]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,arguments.length===0)_.constructor_.call(this,0,0);else if(arguments.length===1){var u=arguments[0];_.constructor_.call(this,u.x,u.y,u.getZ())}else if(arguments.length===2){var p=arguments[0],g=arguments[1];_.constructor_.call(this,p,g,_.NULL_ORDINATE)}else if(arguments.length===3){var E=arguments[0],B=arguments[1],F=arguments[2];this.x=E,this.y=B,this.z=F}}},{key:"hashCode",value:function(u){return oe[0]=u,ge[0]^ge[1]}}])})();ie.DimensionalComparator=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"compare",value:function(u,p){var g=_.compare(u.x,p.x);if(g!==0)return g;var E=_.compare(u.y,p.y);return E!==0?E:this._dimensionsToTest<=2?0:_.compare(u.getZ(),p.getZ())}},{key:"interfaces_",get:function(){return[te]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,arguments.length===0)_.constructor_.call(this,2);else if(arguments.length===1){var u=arguments[0];if(u!==2&&u!==3)throw new R("only 2 or 3 dimensions may be specified");this._dimensionsToTest=u}}},{key:"compare",value:function(u,p){return u<p?-1:u>p?1:W.isNaN(u)?W.isNaN(p)?0:-1:W.isNaN(p)?1:0}}])})(),ie.NULL_ORDINATE=W.NaN,ie.X=0,ie.Y=1,ie.Z=2,ie.M=3;var fe=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(u){if(!(u instanceof _))return!1;var p=u;return this.isNull()?p.isNull():this._maxx===p.getMaxX()&&this._maxy===p.getMaxY()&&this._minx===p.getMinX()&&this._miny===p.getMinY()}},{key:"intersection",value:function(u){if(this.isNull()||u.isNull()||!this.intersects(u))return new _;var p=this._minx>u._minx?this._minx:u._minx,g=this._miny>u._miny?this._miny:u._miny;return new _(p,this._maxx<u._maxx?this._maxx:u._maxx,g,this._maxy<u._maxy?this._maxy:u._maxy)}},{key:"isNull",value:function(){return this._maxx<this._minx}},{key:"getMaxX",value:function(){return this._maxx}},{key:"covers",value:function(){if(arguments.length===1){if(arguments[0]instanceof ie){var u=arguments[0];return this.covers(u.x,u.y)}if(arguments[0]instanceof _){var p=arguments[0];return!this.isNull()&&!p.isNull()&&p.getMinX()>=this._minx&&p.getMaxX()<=this._maxx&&p.getMinY()>=this._miny&&p.getMaxY()<=this._maxy}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];return!this.isNull()&&g>=this._minx&&g<=this._maxx&&E>=this._miny&&E<=this._maxy}}},{key:"intersects",value:function(){if(arguments.length===1){if(arguments[0]instanceof _){var u=arguments[0];return!this.isNull()&&!u.isNull()&&!(u._minx>this._maxx||u._maxx<this._minx||u._miny>this._maxy||u._maxy<this._miny)}if(arguments[0]instanceof ie){var p=arguments[0];return this.intersects(p.x,p.y)}}else if(arguments.length===2){if(arguments[0]instanceof ie&&arguments[1]instanceof ie){var g=arguments[0],E=arguments[1];return!this.isNull()&&!((g.x<E.x?g.x:E.x)>this._maxx)&&!((g.x>E.x?g.x:E.x)<this._minx)&&!((g.y<E.y?g.y:E.y)>this._maxy)&&!((g.y>E.y?g.y:E.y)<this._miny)}if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var B=arguments[0],F=arguments[1];return!this.isNull()&&!(B>this._maxx||B<this._minx||F>this._maxy||F<this._miny)}}}},{key:"getMinY",value:function(){return this._miny}},{key:"getDiameter",value:function(){if(this.isNull())return 0;var u=this.getWidth(),p=this.getHeight();return Math.sqrt(u*u+p*p)}},{key:"getMinX",value:function(){return this._minx}},{key:"expandToInclude",value:function(){if(arguments.length===1){if(arguments[0]instanceof ie){var u=arguments[0];this.expandToInclude(u.x,u.y)}else if(arguments[0]instanceof _){var p=arguments[0];if(p.isNull())return null;this.isNull()?(this._minx=p.getMinX(),this._maxx=p.getMaxX(),this._miny=p.getMinY(),this._maxy=p.getMaxY()):(p._minx<this._minx&&(this._minx=p._minx),p._maxx>this._maxx&&(this._maxx=p._maxx),p._miny<this._miny&&(this._miny=p._miny),p._maxy>this._maxy&&(this._maxy=p._maxy))}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.isNull()?(this._minx=g,this._maxx=g,this._miny=E,this._maxy=E):(g<this._minx&&(this._minx=g),g>this._maxx&&(this._maxx=g),E<this._miny&&(this._miny=E),E>this._maxy&&(this._maxy=E))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var u=this.getWidth(),p=this.getHeight();return u<p?u:p}},{key:"getWidth",value:function(){return this.isNull()?0:this._maxx-this._minx}},{key:"compareTo",value:function(u){var p=u;return this.isNull()?p.isNull()?0:-1:p.isNull()?1:this._minx<p._minx?-1:this._minx>p._minx?1:this._miny<p._miny?-1:this._miny>p._miny?1:this._maxx<p._maxx?-1:this._maxx>p._maxx?1:this._maxy<p._maxy?-1:this._maxy>p._maxy?1:0}},{key:"translate",value:function(u,p){if(this.isNull())return null;this.init(this.getMinX()+u,this.getMaxX()+u,this.getMinY()+p,this.getMaxY()+p)}},{key:"copy",value:function(){return new _(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(u){return!(!this.isNull()&&!u.isNull())||u._minx>this._maxx||u._maxx<this._minx||u._miny>this._maxy||u._maxy<this._miny}},{key:"getHeight",value:function(){return this.isNull()?0:this._maxy-this._miny}},{key:"maxExtent",value:function(){if(this.isNull())return 0;var u=this.getWidth(),p=this.getHeight();return u>p?u:p}},{key:"expandBy",value:function(){if(arguments.length===1){var u=arguments[0];this.expandBy(u,u)}else if(arguments.length===2){var p=arguments[0],g=arguments[1];if(this.isNull())return null;this._minx-=p,this._maxx+=p,this._miny-=g,this._maxy+=g,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(arguments.length===1){if(arguments[0]instanceof _){var u=arguments[0];return this.covers(u)}if(arguments[0]instanceof ie){var p=arguments[0];return this.covers(p)}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];return this.covers(g,E)}}},{key:"centre",value:function(){return this.isNull()?null:new ie((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(arguments.length===0)this.setToNull();else if(arguments.length===1){if(arguments[0]instanceof ie){var u=arguments[0];this.init(u.x,u.x,u.y,u.y)}else if(arguments[0]instanceof _){var p=arguments[0];this._minx=p._minx,this._maxx=p._maxx,this._miny=p._miny,this._maxy=p._maxy}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.init(g.x,E.x,g.y,E.y)}else if(arguments.length===4){var B=arguments[0],F=arguments[1],G=arguments[2],Y=arguments[3];B<F?(this._minx=B,this._maxx=F):(this._minx=F,this._maxx=B),G<Y?(this._miny=G,this._maxy=Y):(this._miny=Y,this._maxy=G)}}},{key:"getMaxY",value:function(){return this._maxy}},{key:"distance",value:function(u){if(this.intersects(u))return 0;var p=0;this._maxx<u._minx?p=u._minx-this._maxx:this._minx>u._maxx&&(p=this._minx-u._maxx);var g=0;return this._maxy<u._miny?g=u._miny-this._maxy:this._miny>u._maxy&&(g=this._miny-u._maxy),p===0?g:g===0?p:Math.sqrt(p*p+g*g)}},{key:"hashCode",value:function(){var u=17;return u=37*(u=37*(u=37*(u=37*u+ie.hashCode(this._minx))+ie.hashCode(this._maxx))+ie.hashCode(this._miny))+ie.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[L,C]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,arguments.length===0)this.init();else if(arguments.length===1){if(arguments[0]instanceof ie){var u=arguments[0];this.init(u.x,u.x,u.y,u.y)}else if(arguments[0]instanceof _){var p=arguments[0];this.init(p)}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this.init(g.x,E.x,g.y,E.y)}else if(arguments.length===4){var B=arguments[0],F=arguments[1],G=arguments[2],Y=arguments[3];this.init(B,F,G,Y)}}},{key:"intersects",value:function(){if(arguments.length===3){var u=arguments[0],p=arguments[1],g=arguments[2];return g.x>=(u.x<p.x?u.x:p.x)&&g.x<=(u.x>p.x?u.x:p.x)&&g.y>=(u.y<p.y?u.y:p.y)&&g.y<=(u.y>p.y?u.y:p.y)}if(arguments.length===4){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3],Y=Math.min(F.x,G.x),ae=Math.max(F.x,G.x),xe=Math.min(E.x,B.x),Ie=Math.max(E.x,B.x);return!(xe>ae)&&!(Ie<Y)&&(Y=Math.min(F.y,G.y),ae=Math.max(F.y,G.y),xe=Math.min(E.y,B.y),Ie=Math.max(E.y,B.y),!(xe>ae)&&!(Ie<Y))}}}])})(),ye=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"isGeometryCollection",value:function(){return this.getTypeCode()===_.TYPECODE_GEOMETRYCOLLECTION}},{key:"getFactory",value:function(){return this._factory}},{key:"getGeometryN",value:function(u){return this}},{key:"getArea",value:function(){return 0}},{key:"isRectangle",value:function(){return!1}},{key:"equalsExact",value:function(u){return this===u||this.equalsExact(u,0)}},{key:"geometryChanged",value:function(){this.apply(_.geometryChangedFilter)}},{key:"geometryChangedAction",value:function(){this._envelope=null}},{key:"equalsNorm",value:function(u){return u!==null&&this.norm().equalsExact(u.norm())}},{key:"getLength",value:function(){return 0}},{key:"getNumGeometries",value:function(){return 1}},{key:"compareTo",value:function(){var u;if(arguments.length===1){var p=arguments[0];return u=p,this.getTypeCode()!==u.getTypeCode()?this.getTypeCode()-u.getTypeCode():this.isEmpty()&&u.isEmpty()?0:this.isEmpty()?-1:u.isEmpty()?1:this.compareToSameClass(p)}if(arguments.length===2){var g=arguments[0],E=arguments[1];return u=g,this.getTypeCode()!==u.getTypeCode()?this.getTypeCode()-u.getTypeCode():this.isEmpty()&&u.isEmpty()?0:this.isEmpty()?-1:u.isEmpty()?1:this.compareToSameClass(g,E)}}},{key:"getUserData",value:function(){return this._userData}},{key:"getSRID",value:function(){return this._SRID}},{key:"getEnvelope",value:function(){return this.getFactory().toGeometry(this.getEnvelopeInternal())}},{key:"checkNotGeometryCollection",value:function(u){if(u.getTypeCode()===_.TYPECODE_GEOMETRYCOLLECTION)throw new R("This method does not support GeometryCollection arguments")}},{key:"equal",value:function(u,p,g){return g===0?u.equals(p):u.distance(p)<=g}},{key:"norm",value:function(){var u=this.copy();return u.normalize(),u}},{key:"reverse",value:function(){var u=this.reverseInternal();return this.envelope!=null&&(u.envelope=this.envelope.copy()),u.setSRID(this.getSRID()),u}},{key:"copy",value:function(){var u=this.copyInternal();return u.envelope=this._envelope==null?null:this._envelope.copy(),u._SRID=this._SRID,u._userData=this._userData,u}},{key:"getPrecisionModel",value:function(){return this._factory.getPrecisionModel()}},{key:"getEnvelopeInternal",value:function(){return this._envelope===null&&(this._envelope=this.computeEnvelopeInternal()),new fe(this._envelope)}},{key:"setSRID",value:function(u){this._SRID=u}},{key:"setUserData",value:function(u){this._userData=u}},{key:"compare",value:function(u,p){for(var g=u.iterator(),E=p.iterator();g.hasNext()&&E.hasNext();){var B=g.next(),F=E.next(),G=B.compareTo(F);if(G!==0)return G}return g.hasNext()?1:E.hasNext()?-1:0}},{key:"hashCode",value:function(){return this.getEnvelopeInternal().hashCode()}},{key:"isEquivalentClass",value:function(u){return this.getClass()===u.getClass()}},{key:"isGeometryCollectionOrDerived",value:function(){return this.getTypeCode()===_.TYPECODE_GEOMETRYCOLLECTION||this.getTypeCode()===_.TYPECODE_MULTIPOINT||this.getTypeCode()===_.TYPECODE_MULTILINESTRING||this.getTypeCode()===_.TYPECODE_MULTIPOLYGON}},{key:"interfaces_",get:function(){return[T,L,C]}},{key:"getClass",value:function(){return _}}],[{key:"hasNonEmptyElements",value:function(u){for(var p=0;p<u.length;p++)if(!u[p].isEmpty())return!0;return!1}},{key:"hasNullElements",value:function(u){for(var p=0;p<u.length;p++)if(u[p]===null)return!0;return!1}}])})();ye.constructor_=function(_){_&&(this._envelope=null,this._userData=null,this._factory=_,this._SRID=_.getSRID())},ye.TYPECODE_POINT=0,ye.TYPECODE_MULTIPOINT=1,ye.TYPECODE_LINESTRING=2,ye.TYPECODE_LINEARRING=3,ye.TYPECODE_MULTILINESTRING=4,ye.TYPECODE_POLYGON=5,ye.TYPECODE_MULTIPOLYGON=6,ye.TYPECODE_GEOMETRYCOLLECTION=7,ye.TYPENAME_POINT="Point",ye.TYPENAME_MULTIPOINT="MultiPoint",ye.TYPENAME_LINESTRING="LineString",ye.TYPENAME_LINEARRING="LinearRing",ye.TYPENAME_MULTILINESTRING="MultiLineString",ye.TYPENAME_POLYGON="Polygon",ye.TYPENAME_MULTIPOLYGON="MultiPolygon",ye.TYPENAME_GEOMETRYCOLLECTION="GeometryCollection",ye.geometryChangedFilter={get interfaces_(){return[k]},filter:function(_){_.geometryChangedAction()}};var $=(function(){function _(){s(this,_)}return o(_,null,[{key:"toLocationSymbol",value:function(u){switch(u){case _.EXTERIOR:return"e";case _.BOUNDARY:return"b";case _.INTERIOR:return"i";case _.NONE:return"-"}throw new R("Unknown location value: "+u)}}])})();$.INTERIOR=0,$.BOUNDARY=1,$.EXTERIOR=2,$.NONE=-1;var Se=(function(){return o((function _(){s(this,_)}),[{key:"add",value:function(){}},{key:"addAll",value:function(){}},{key:"isEmpty",value:function(){}},{key:"iterator",value:function(){}},{key:"size",value:function(){}},{key:"toArray",value:function(){}},{key:"remove",value:function(){}}])})(),Z=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({NoSuchElementException:u})[0],g}return d(u,_),o(u)})(S),Qe=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({UnsupportedOperationException:u})[0],g}return d(u,_),o(u)})(S),Le=(function(_){function u(){return s(this,u),i(this,u,arguments)}return d(u,_),o(u,[{key:"contains",value:function(){}}])})(Se),et=(function(_){function u(p){var g;return s(this,u),(g=i(this,u)).map=new Map,p instanceof Se&&g.addAll(p),g}return d(u,_),o(u,[{key:"contains",value:function(p){var g=p.hashCode?p.hashCode():p;return!!this.map.has(g)}},{key:"add",value:function(p){var g=p.hashCode?p.hashCode():p;return!this.map.has(g)&&!!this.map.set(g,p)}},{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.map.size}},{key:"isEmpty",value:function(){return this.map.size===0}},{key:"toArray",value:function(){return Array.from(this.map.values())}},{key:"iterator",value:function(){return new ne(this.map)}},{key:Symbol.iterator,value:function(){return this.map}}])})(Le),ne=(function(){return o((function _(u){s(this,_),this.iterator=u.values();var p=this.iterator.next(),g=p.done,E=p.value;this.done=g,this.value=E}),[{key:"next",value:function(){if(this.done)throw new Z;var _=this.value,u=this.iterator.next(),p=u.done,g=u.value;return this.done=p,this.value=g,_}},{key:"hasNext",value:function(){return!this.done}},{key:"remove",value:function(){throw new Qe}}])})(),q=(function(){function _(){s(this,_)}return o(_,null,[{key:"opposite",value:function(u){return u===_.LEFT?_.RIGHT:u===_.RIGHT?_.LEFT:u}}])})();q.ON=0,q.LEFT=1,q.RIGHT=2;var pe=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({EmptyStackException:u})[0],g}return d(u,_),o(u)})(S),Be=(function(_){function u(p){var g;return s(this,u),(g=i(this,u,[p])).name=Object.keys({IndexOutOfBoundsException:u})[0],g}return d(u,_),o(u)})(S),We=(function(_){function u(){return s(this,u),i(this,u,arguments)}return d(u,_),o(u,[{key:"get",value:function(){}},{key:"set",value:function(){}},{key:"isEmpty",value:function(){}}])})(Se),st=(function(_){function u(){var p;return s(this,u),(p=i(this,u)).array=[],p}return d(u,_),o(u,[{key:"add",value:function(p){return this.array.push(p),!0}},{key:"get",value:function(p){if(p<0||p>=this.size())throw new Be;return this.array[p]}},{key:"push",value:function(p){return this.array.push(p),p}},{key:"pop",value:function(){if(this.array.length===0)throw new pe;return this.array.pop()}},{key:"peek",value:function(){if(this.array.length===0)throw new pe;return this.array[this.array.length-1]}},{key:"empty",value:function(){return this.array.length===0}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(p){return this.array.indexOf(p)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}])})(We);function X(_,u){return _.interfaces_&&_.interfaces_.indexOf(u)>-1}var V=(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}}])})(),de=(function(){function _(u){s(this,_),this.value=u}return o(_,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(u){return this.value<u?-1:this.value>u?1:0}}],[{key:"compare",value:function(u,p){return u<p?-1:u>p?1:0}},{key:"isNan",value:function(u){return Number.isNaN(u)}},{key:"valueOf",value:function(u){return new _(u)}}])})(),Ce=(function(){return o((function _(){s(this,_)}),null,[{key:"isWhitespace",value:function(_){return _<=32&&_>=0||_===127}},{key:"toUpperCase",value:function(_){return _.toUpperCase()}}])})(),ee=(function(){function _(){s(this,_),_.constructor_.apply(this,arguments)}return o(_,[{key:"le",value:function(u){return this._hi<u._hi||this._hi===u._hi&&this._lo<=u._lo}},{key:"extractSignificantDigits",value:function(u,p){var g=this.abs(),E=_.magnitude(g._hi),B=_.TEN.pow(E);(g=g.divide(B)).gt(_.TEN)?(g=g.divide(_.TEN),E+=1):g.lt(_.ONE)&&(g=g.multiply(_.TEN),E-=1);for(var F=E+1,G=new V,Y=_.MAX_PRINT_DIGITS-1,ae=0;ae<=Y;ae++){u&&ae===F&&G.append(".");var xe=Math.trunc(g._hi);if(xe<0)break;var Ie=!1,Ge=0;xe>9?(Ie=!0,Ge="9"):Ge="0"+xe,G.append(Ge),g=g.subtract(_.valueOf(xe)).multiply(_.TEN),Ie&&g.selfAdd(_.TEN);var ut=!0,Rt=_.magnitude(g._hi);if(Rt<0&&Math.abs(Rt)>=Y-ae&&(ut=!1),!ut)break}return p[0]=E,G.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof _){var u=arguments[0];return this.add(u.negate())}if(typeof arguments[0]=="number"){var p=arguments[0];return this.add(-p)}}},{key:"equals",value:function(){if(arguments.length===1&&arguments[0]instanceof _){var u=arguments[0];return this._hi===u._hi&&this._lo===u._lo}}},{key:"isZero",value:function(){return this._hi===0&&this._lo===0}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof _){var u=arguments[0];return this.isNaN()?this:this.selfAdd(-u._hi,-u._lo)}if(typeof arguments[0]=="number"){var p=arguments[0];return this.isNaN()?this:this.selfAdd(-p,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(u){return this.le(u)?this:u}},{key:"selfDivide",value:function(){if(arguments.length===1){if(arguments[0]instanceof _){var u=arguments[0];return this.selfDivide(u._hi,u._lo)}if(typeof arguments[0]=="number"){var p=arguments[0];return this.selfDivide(p,0)}}else if(arguments.length===2){var g,E,B,F,G=arguments[0],Y=arguments[1],ae=null,xe=null,Ie=null,Ge=null;return B=this._hi/G,Ge=(ae=(Ie=_.SPLIT*B)-(ae=Ie-B))*(xe=(Ge=_.SPLIT*G)-(xe=Ge-G))-(F=B*G)+ae*(E=G-xe)+(g=B-ae)*xe+g*E,Ge=B+(Ie=(this._hi-F-Ge+this._lo-B*Y)/G),this._hi=Ge,this._lo=B-Ge+Ie,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof _){var u,p,g,E,B=arguments[0],F=null,G=null,Y=null,ae=null;return u=(g=this._hi/B._hi)-(F=(Y=_.SPLIT*g)-(F=Y-g)),ae=F*(G=(ae=_.SPLIT*B._hi)-(G=ae-B._hi))-(E=g*B._hi)+F*(p=B._hi-G)+u*G+u*p,new _(ae=g+(Y=(this._hi-E-ae+this._lo-g*B._lo)/B._hi),g-ae+Y)}if(typeof arguments[0]=="number"){var xe=arguments[0];return W.isNaN(xe)?_.createNaN():_.copy(this).selfDivide(xe,0)}}},{key:"ge",value:function(u){return this._hi>u._hi||this._hi===u._hi&&this._lo>=u._lo}},{key:"pow",value:function(u){if(u===0)return _.valueOf(1);var p=new _(this),g=_.valueOf(1),E=Math.abs(u);if(E>1)for(;E>0;)E%2==1&&g.selfMultiply(p),(E/=2)>0&&(p=p.sqr());else g=p;return u<0?g.reciprocal():g}},{key:"ceil",value:function(){if(this.isNaN())return _.NaN;var u=Math.ceil(this._hi),p=0;return u===this._hi&&(p=Math.ceil(this._lo)),new _(u,p)}},{key:"compareTo",value:function(u){var p=u;return this._hi<p._hi?-1:this._hi>p._hi?1:this._lo<p._lo?-1:this._lo>p._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof _){var u=arguments[0];return this.init(u),this}if(typeof arguments[0]=="number"){var p=arguments[0];return this.init(p),this}}},{key:"max",value:function(u){return this.ge(u)?this:u}},{key:"sqrt",value:function(){if(this.isZero())return _.valueOf(0);if(this.isNegative())return _.NaN;var u=1/Math.sqrt(this._hi),p=this._hi*u,g=_.valueOf(p),E=this.subtract(g.sqr())._hi*(.5*u);return g.add(E)}},{key:"selfAdd",value:function(){if(arguments.length===1){if(arguments[0]instanceof _){var u=arguments[0];return this.selfAdd(u._hi,u._lo)}if(typeof arguments[0]=="number"){var p,g,E,B,F,G=arguments[0],Y=null;return Y=(E=this._hi+G)-(B=E-this._hi),g=(F=(Y=G-B+(this._hi-Y))+this._lo)+(E-(p=E+F)),this._hi=p+g,this._lo=g+(p-this._hi),this}}else if(arguments.length===2){var ae,xe,Ie,Ge,ut=arguments[0],Rt=arguments[1],Ft=null,vn=null,pn=null;Ie=this._hi+ut,xe=this._lo+Rt,vn=Ie-(pn=Ie-this._hi),Ft=xe-(Ge=xe-this._lo);var Dn=(ae=Ie+(pn=(vn=ut-pn+(this._hi-vn))+xe))+(pn=(Ft=Rt-Ge+(this._lo-Ft))+(pn+(Ie-ae))),Ki=pn+(ae-Dn);return this._hi=Dn,this._lo=Ki,this}}},{key:"selfMultiply",value:function(){if(arguments.length===1){if(arguments[0]instanceof _){var u=arguments[0];return this.selfMultiply(u._hi,u._lo)}if(typeof arguments[0]=="number"){var p=arguments[0];return this.selfMultiply(p,0)}}else if(arguments.length===2){var g,E,B=arguments[0],F=arguments[1],G=null,Y=null,ae=null,xe=null;G=(ae=_.SPLIT*this._hi)-this._hi,xe=_.SPLIT*B,G=ae-G,g=this._hi-G,Y=xe-B;var Ie=(ae=this._hi*B)+(xe=G*(Y=xe-Y)-ae+G*(E=B-Y)+g*Y+g*E+(this._hi*F+this._lo*B)),Ge=xe+(G=ae-Ie);return this._hi=Ie,this._lo=Ge,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return _.NaN;var u=Math.floor(this._hi),p=0;return u===this._hi&&(p=Math.floor(this._lo)),new _(u,p)}},{key:"negate",value:function(){return this.isNaN()?this:new _(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(u){if(u instanceof CloneNotSupportedException)return null;throw u}}},{key:"multiply",value:function(){if(arguments[0]instanceof _){var u=arguments[0];return u.isNaN()?_.createNaN():_.copy(this).selfMultiply(u)}if(typeof arguments[0]=="number"){var p=arguments[0];return W.isNaN(p)?_.createNaN():_.copy(this).selfMultiply(p,0)}}},{key:"isNaN",value:function(){return W.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var u=_.magnitude(this._hi);return u>=-3&&u<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var u=this.getSpecialNumberString();if(u!==null)return u;var p=new Array(1).fill(null),g=this.extractSignificantDigits(!0,p),E=p[0]+1,B=g;if(g.charAt(0)===".")B="0"+g;else if(E<0)B="0."+_.stringOfChar("0",-E)+g;else if(g.indexOf(".")===-1){var F=E-g.length;B=g+_.stringOfChar("0",F)+".0"}return this.isNegative()?"-"+B:B}},{key:"reciprocal",value:function(){var u,p,g,E,B=null,F=null,G=null,Y=null;u=(g=1/this._hi)-(B=(G=_.SPLIT*g)-(B=G-g)),F=(Y=_.SPLIT*this._hi)-this._hi;var ae=g+(G=(1-(E=g*this._hi)-(Y=B*(F=Y-F)-E+B*(p=this._hi-F)+u*F+u*p)-g*this._lo)/this._hi);return new _(ae,g-ae+G)}},{key:"toSciNotation",value:function(){if(this.isZero())return _.SCI_NOT_ZERO;var u=this.getSpecialNumberString();if(u!==null)return u;var p=new Array(1).fill(null),g=this.extractSignificantDigits(!1,p),E=_.SCI_NOT_EXPONENT_CHAR+p[0];if(g.charAt(0)==="0")throw new IllegalStateException("Found leading zero: "+g);var B="";g.length>1&&(B=g.substring(1));var F=g.charAt(0)+"."+B;return this.isNegative()?"-"+F+E:F+E}},{key:"abs",value:function(){return this.isNaN()?_.NaN:this.isNegative()?this.negate():new _(this)}},{key:"isPositive",value:function(){return this._hi>0||this._hi===0&&this._lo>0}},{key:"lt",value:function(u){return this._hi<u._hi||this._hi===u._hi&&this._lo<u._lo}},{key:"add",value:function(){if(arguments[0]instanceof _){var u=arguments[0];return _.copy(this).selfAdd(u)}if(typeof arguments[0]=="number"){var p=arguments[0];return _.copy(this).selfAdd(p)}}},{key:"init",value:function(){if(arguments.length===1){if(typeof arguments[0]=="number"){var u=arguments[0];this._hi=u,this._lo=0}else if(arguments[0]instanceof _){var p=arguments[0];this._hi=p._hi,this._lo=p._lo}}else if(arguments.length===2){var g=arguments[0],E=arguments[1];this._hi=g,this._lo=E}}},{key:"gt",value:function(u){return this._hi>u._hi||this._hi===u._hi&&this._lo>u._lo}},{key:"isNegative",value:function(){return this._hi<0||this._hi===0&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?_.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[C,L,T]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,arguments.length===0)this.init(0);else if(arguments.length===1){if(typeof arguments[0]=="number"){var u=arguments[0];this.init(u)}else if(arguments[0]instanceof _){var p=arguments[0];this.init(p)}else if(typeof arguments[0]=="string"){var g=arguments[0];_.constructor_.call(this,_.parse(g))}}else if(arguments.length===2){var E=arguments[0],B=arguments[1];this.init(E,B)}}},{key:"determinant",value:function(){if(typeof arguments[3]=="number"&&typeof arguments[2]=="number"&&typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var u=arguments[0],p=arguments[1],g=arguments[2],E=arguments[3];return _.determinant(_.valueOf(u),_.valueOf(p),_.valueOf(g),_.valueOf(E))}if(arguments[3]instanceof _&&arguments[2]instanceof _&&arguments[0]instanceof _&&arguments[1]instanceof _){var B=arguments[1],F=arguments[2],G=arguments[3];return arguments[0].multiply(G).selfSubtract(B.multiply(F))}}},{key:"sqr",value:function(u){return _.valueOf(u).selfMultiply(u)}},{key:"valueOf",value:function(){if(typeof arguments[0]=="string"){var u=arguments[0];return _.parse(u)}if(typeof arguments[0]=="number")return new _(arguments[0])}},{key:"sqrt",value:function(u){return _.valueOf(u).sqrt()}},{key:"parse",value:function(u){for(var p=0,g=u.length;Ce.isWhitespace(u.charAt(p));)p++;var E=!1;if(p<g){var B=u.charAt(p);B!=="-"&&B!=="+"||(p++,B==="-"&&(E=!0))}for(var F=new _,G=0,Y=0,ae=0,xe=!1;!(p>=g);){var Ie=u.charAt(p);if(p++,Ce.isDigit(Ie)){var Ge=Ie-"0";F.selfMultiply(_.TEN),F.selfAdd(Ge),G++}else{if(Ie!=="."){if(Ie==="e"||Ie==="E"){var ut=u.substring(p);try{ae=de.parseInt(ut)}catch(Dn){throw Dn instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+ut+" in string "+u):Dn}break}throw new NumberFormatException("Unexpected character '"+Ie+"' at position "+p+" in string "+u)}Y=G,xe=!0}}var Rt=F;xe||(Y=G);var Ft=G-Y-ae;if(Ft===0)Rt=F;else if(Ft>0){var vn=_.TEN.pow(Ft);Rt=F.divide(vn)}else if(Ft<0){var pn=_.TEN.pow(-Ft);Rt=F.multiply(pn)}return E?Rt.negate():Rt}},{key:"createNaN",value:function(){return new _(W.NaN,W.NaN)}},{key:"copy",value:function(u){return new _(u)}},{key:"magnitude",value:function(u){var p=Math.abs(u),g=Math.log(p)/Math.log(10),E=Math.trunc(Math.floor(g));return 10*Math.pow(10,E)<=p&&(E+=1),E}},{key:"stringOfChar",value:function(u,p){for(var g=new V,E=0;E<p;E++)g.append(u);return g.toString()}}])})();ee.PI=new ee(3.141592653589793,12246467991473532e-32),ee.TWO_PI=new ee(6.283185307179586,24492935982947064e-32),ee.PI_2=new ee(1.5707963267948966,6123233995736766e-32),ee.E=new ee(2.718281828459045,14456468917292502e-32),ee.NaN=new ee(W.NaN,W.NaN),ee.EPS=123259516440783e-46,ee.SPLIT=134217729,ee.MAX_PRINT_DIGITS=32,ee.TEN=ee.valueOf(10),ee.ONE=ee.valueOf(1),ee.SCI_NOT_EXPONENT_CHAR="E",ee.SCI_NOT_ZERO="0.0E0";var Ae=(function(){function _(){s(this,_)}return o(_,null,[{key:"orientationIndex",value:function(u,p,g){var E=_.orientationIndexFilter(u,p,g);if(E<=1)return E;var B=ee.valueOf(p.x).selfAdd(-u.x),F=ee.valueOf(p.y).selfAdd(-u.y),G=ee.valueOf(g.x).selfAdd(-p.x),Y=ee.valueOf(g.y).selfAdd(-p.y);return B.selfMultiply(Y).selfSubtract(F.selfMultiply(G)).signum()}},{key:"signOfDet2x2",value:function(){if(arguments[3]instanceof ee&&arguments[2]instanceof ee&&arguments[0]instanceof ee&&arguments[1]instanceof ee){var u=arguments[1],p=arguments[2],g=arguments[3];return arguments[0].multiply(g).selfSubtract(u.multiply(p)).signum()}if(typeof arguments[3]=="number"&&typeof arguments[2]=="number"&&typeof arguments[0]=="number"&&typeof arguments[1]=="number"){var E=arguments[0],B=arguments[1],F=arguments[2],G=arguments[3],Y=ee.valueOf(E),ae=ee.valueOf(B),xe=ee.valueOf(F),Ie=ee.valueOf(G);return Y.multiply(Ie).selfSubtract(ae.multiply(xe)).signum()}}},{key:"intersection",value:function(u,p,g,E){var B=new ee(u.y).selfSubtract(p.y),F=new ee(p.x).selfSubtract(u.x),G=new ee(u.x).selfMultiply(p.y).selfSubtract(new ee(p.x).selfMultiply(u.y)),Y=new ee(g.y).selfSubtract(E.y),ae=new ee(E.x).selfSubtract(g.x),xe=new ee(g.x).selfMultiply(E.y).selfSubtract(new ee(E.x).selfMultiply(g.y)),Ie=F.multiply(xe).selfSubtract(ae.multiply(G)),Ge=Y.multiply(G).selfSubtract(B.multiply(xe)),ut=B.multiply(ae).selfSubtract(Y.multiply(F)),Rt=Ie.selfDivide(ut).doubleValue(),Ft=Ge.selfDivide(ut).doubleValue();return W.isNaN(Rt)||W.isInfinite(Rt)||W.isNaN(Ft)||W.isInfinite(Ft)?null:new ie(Rt,Ft)}},{key:"orientationIndexFilter",value:function(u,p,g){var E=null,B=(u.x-g.x)*(p.y-g.y),F=(u.y-g.y)*(p.x-g.x),G=B-F;if(B>0){if(F<=0)return _.signum(G);E=B+F}else{if(!(B<0)||F>=0)return _.signum(G);E=-B-F}var Y=_.DP_SAFE_EPSILON*E;return G>=Y||-G>=Y?_.signum(G):2}},{key:"signum",value:function(u){return u>0?1:u<0?-1:0}}])})();Ae.DP_SAFE_EPSILON=1e-15;var _e=(function(){return o((function _(){s(this,_)}),[{key:"getM",value:function(_){if(this.hasM()){var u=this.getDimension()-this.getMeasures();return this.getOrdinate(_,u)}return W.NaN}},{key:"setOrdinate",value:function(_,u,p){}},{key:"getZ",value:function(_){return this.hasZ()?this.getOrdinate(_,2):W.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(_,u){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(_){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(_){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(_){}},{key:"copy",value:function(){}},{key:"getY",value:function(_){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[T]}}])})();_e.X=0,_e.Y=1,_e.Z=2,_e.M=3;var be=(function(){function _(){s(this,_)}return o(_,null,[{key:"index",value:function(u,p,g){return Ae.orientationIndex(u,p,g)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var u=arguments[0],p=u.length-1;if(p<3)throw new R("Ring has fewer than 4 points, so orientation cannot be determined");for(var g=u[0],E=0,B=1;B<=p;B++){var F=u[B];F.y>g.y&&(g=F,E=B)}var G=E;do(G-=1)<0&&(G=p);while(u[G].equals2D(g)&&G!==E);var Y=E;do Y=(Y+1)%p;while(u[Y].equals2D(g)&&Y!==E);var ae=u[G],xe=u[Y];if(ae.equals2D(g)||xe.equals2D(g)||ae.equals2D(xe))return!1;var Ie=_.index(ae,g,xe);return Ie===0?ae.x>xe.x:Ie>0}if(X(arguments[0],_e)){var Ge=arguments[0],ut=Ge.size()-1;if(ut<3)throw new R("Ring has fewer than 4 points, so orientation cannot be determined");for(var Rt=Ge.getCoordinate(0),Ft=0,vn=1;vn<=ut;vn++){var pn=Ge.getCoordinate(vn);pn.y>Rt.y&&(Rt=pn,Ft=vn)}var Dn=null,Ki=Ft;do(Ki-=1)<0&&(Ki=ut),Dn=Ge.getCoordinate(Ki);while(Dn.equals2D(Rt)&&Ki!==Ft);var ps=null,Yl=Ft;do Yl=(Yl+1)%ut,ps=Ge.getCoordinate(Yl);while(ps.equals2D(Rt)&&Yl!==Ft);if(Dn.equals2D(Rt)||ps.equals2D(Rt)||Dn.equals2D(ps))return!1;var ud=_.index(Dn,Rt,ps);return ud===0?Dn.x>ps.x:ud>0}}}])})();be.CLOCKWISE=-1,be.RIGHT=be.CLOCKWISE,be.COUNTERCLOCKWISE=1,be.LEFT=be.COUNTERCLOCKWISE,be.COLLINEAR=0,be.STRAIGHT=be.COLLINEAR;var Oe=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(_,u){var p=this.getRightmostSideOfSegment(_,u);return p<0&&(p=this.getRightmostSideOfSegment(_,u-1)),p<0&&(this._minCoord=null,this.checkForRightmostCoordinate(_)),p}},{key:"findRightmostEdgeAtVertex",value:function(){var _=this._minDe.getEdge().getCoordinates();re.isTrue(this._minIndex>0&&this._minIndex<_.length,"rightmost point expected to be interior vertex of edge");var u=_[this._minIndex-1],p=_[this._minIndex+1],g=be.index(this._minCoord,p,u),E=!1;(u.y<this._minCoord.y&&p.y<this._minCoord.y&&g===be.COUNTERCLOCKWISE||u.y>this._minCoord.y&&p.y>this._minCoord.y&&g===be.CLOCKWISE)&&(E=!0),E&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(_,u){var p=_.getEdge().getCoordinates();if(u<0||u+1>=p.length||p[u].y===p[u+1].y)return-1;var g=q.LEFT;return p[u].y<p[u+1].y&&(g=q.RIGHT),g}},{key:"getEdge",value:function(){return this._orientedDe}},{key:"checkForRightmostCoordinate",value:function(_){for(var u=_.getEdge().getCoordinates(),p=0;p<u.length-1;p++)(this._minCoord===null||u[p].x>this._minCoord.x)&&(this._minDe=_,this._minIndex=p,this._minCoord=u[p])}},{key:"findRightmostEdgeAtNode",value:function(){var _=this._minDe.getNode().getEdges();this._minDe=_.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(_){for(var u=_.iterator();u.hasNext();){var p=u.next();p.isForward()&&this.checkForRightmostCoordinate(p)}re.isTrue(this._minIndex!==0||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),this._minIndex===0?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===q.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}])})(),Ye=(function(_){function u(p,g){var E;return s(this,u),(E=i(this,u,[g?p+" [ "+g+" ]":p])).pt=g?new ie(g):void 0,E.name=Object.keys({TopologyException:u})[0],E}return d(u,_),o(u,[{key:"getCoordinate",value:function(){return this.pt}}])})(J),$e=(function(){return o((function _(){s(this,_),this.array=[]}),[{key:"addLast",value:function(_){this.array.push(_)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return this.array.length===0}}])})(),Pe=(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:"interfaces_",get:function(){return[We,Se]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(p){return arguments.length===1?this.array.push(p):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(p){var g,E=l(p);try{for(E.s();!(g=E.n()).done;){var B=g.value;this.array.push(B)}}catch(F){E.e(F)}finally{E.f()}}},{key:"set",value:function(p,g){var E=this.array[p];return this.array[p]=g,E}},{key:"iterator",value:function(){return new Bt(this)}},{key:"get",value:function(p){if(p<0||p>=this.size())throw new Be;return this.array[p]}},{key:"isEmpty",value:function(){return this.array.length===0}},{key:"sort",value:function(p){p?this.array.sort((function(g,E){return p.compare(g,E)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(p){for(var g=0,E=this.array.length;g<E;g++)if(this.array[g]===p)return!!this.array.splice(g,1);return!1}},{key:Symbol.iterator,value:function(){return this.array.values()}}])})(We),Bt=(function(){return o((function _(u){s(this,_),this.arrayList=u,this.position=0}),[{key:"next",value:function(){if(this.position===this.arrayList.size())throw new Z;return this.arrayList.get(this.position++)}},{key:"hasNext",value:function(){return this.position<this.arrayList.size()}},{key:"set",value:function(_){return this.arrayList.set(this.position-1,_)}},{key:"remove",value:function(){this.arrayList.remove(this.arrayList.get(this.position))}}])})(),at=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"clearVisitedEdges",value:function(){for(var _=this._dirEdgeList.iterator();_.hasNext();)_.next().setVisited(!1)}},{key:"getRightmostCoordinate",value:function(){return this._rightMostCoord}},{key:"computeNodeDepth",value:function(_){for(var u=null,p=_.getEdges().iterator();p.hasNext();){var g=p.next();if(g.isVisited()||g.getSym().isVisited()){u=g;break}}if(u===null)throw new Ye("unable to find edge to compute depths at "+_.getCoordinate());_.getEdges().computeDepths(u);for(var E=_.getEdges().iterator();E.hasNext();){var B=E.next();B.setVisited(!0),this.copySymDepths(B)}}},{key:"computeDepth",value:function(_){this.clearVisitedEdges();var u=this._finder.getEdge();u.getNode(),u.getLabel(),u.setEdgeDepths(q.RIGHT,_),this.copySymDepths(u),this.computeDepths(u)}},{key:"create",value:function(_){this.addReachable(_),this._finder.findEdge(this._dirEdgeList),this._rightMostCoord=this._finder.getCoordinate()}},{key:"findResultEdges",value:function(){for(var _=this._dirEdgeList.iterator();_.hasNext();){var u=_.next();u.getDepth(q.RIGHT)>=1&&u.getDepth(q.LEFT)<=0&&!u.isInteriorAreaEdge()&&u.setInResult(!0)}}},{key:"computeDepths",value:function(_){var u=new et,p=new $e,g=_.getNode();for(p.addLast(g),u.add(g),_.setVisited(!0);!p.isEmpty();){var E=p.removeFirst();u.add(E),this.computeNodeDepth(E);for(var B=E.getEdges().iterator();B.hasNext();){var F=B.next().getSym();if(!F.isVisited()){var G=F.getNode();u.contains(G)||(p.addLast(G),u.add(G))}}}}},{key:"compareTo",value:function(_){var u=_;return this._rightMostCoord.x<u._rightMostCoord.x?-1:this._rightMostCoord.x>u._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(this._env===null){for(var _=new fe,u=this._dirEdgeList.iterator();u.hasNext();)for(var p=u.next().getEdge().getCoordinates(),g=0;g<p.length-1;g++)_.expandToInclude(p[g]);this._env=_}return this._env}},{key:"addReachable",value:function(_){var u=new st;for(u.add(_);!u.empty();){var p=u.pop();this.add(p,u)}}},{key:"copySymDepths",value:function(_){var u=_.getSym();u.setDepth(q.LEFT,_.getDepth(q.RIGHT)),u.setDepth(q.RIGHT,_.getDepth(q.LEFT))}},{key:"add",value:function(_,u){_.setVisited(!0),this._nodes.add(_);for(var p=_.getEdges().iterator();p.hasNext();){var g=p.next();this._dirEdgeList.add(g);var E=g.getSym().getNode();E.isVisited()||u.push(E)}}},{key:"getNodes",value:function(){return this._nodes}},{key:"getDirectedEdges",value:function(){return this._dirEdgeList}},{key:"interfaces_",get:function(){return[L]}}],[{key:"constructor_",value:function(){this._finder=null,this._dirEdgeList=new Pe,this._nodes=new Pe,this._rightMostCoord=null,this._env=null,this._finder=new Oe}}])})(),it=(function(){return o((function _(){s(this,_)}),null,[{key:"intersection",value:function(_,u,p,g){var E=_.x<u.x?_.x:u.x,B=_.y<u.y?_.y:u.y,F=_.x>u.x?_.x:u.x,G=_.y>u.y?_.y:u.y,Y=p.x<g.x?p.x:g.x,ae=p.y<g.y?p.y:g.y,xe=p.x>g.x?p.x:g.x,Ie=p.y>g.y?p.y:g.y,Ge=((E>Y?E:Y)+(F<xe?F:xe))/2,ut=((B>ae?B:ae)+(G<Ie?G:Ie))/2,Rt=_.x-Ge,Ft=_.y-ut,vn=u.x-Ge,pn=u.y-ut,Dn=p.x-Ge,Ki=p.y-ut,ps=g.x-Ge,Yl=g.y-ut,ud=Ft-pn,Uw=vn-Rt,zw=Rt*pn-vn*Ft,Qw=Ki-Yl,Gw=ps-Dn,Hw=Dn*Yl-ps*Ki,$w=ud*Gw-Qw*Uw,dv=(Uw*Hw-Gw*zw)/$w,pv=(Qw*zw-ud*Hw)/$w;return W.isNaN(dv)||W.isInfinite(dv)||W.isNaN(pv)||W.isInfinite(pv)?null:new ie(dv+Ge,pv+ut)}}])})(),xt=(function(){return o((function _(){s(this,_)}),null,[{key:"arraycopy",value:function(_,u,p,g,E){for(var B=0,F=u;F<u+E;F++)p[g+B]=_[F],B++}},{key:"getProperty",value:function(_){return{"line.separator":`
272
272
  `}[_]}}])})(),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"||_==`
273
273
  `}},{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(dw(_.getGeometryN(p)));return u.join(", ")}};function dw(_){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 yF=(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 dw(_)}}])})(),sv=(function(){return o((function _(u){s(this,_),this.parser=new yF(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),bF=(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 bF.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()}}}}])})(),xF=(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),EF=(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 xF(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),pw=(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)}}])})(pw),CF=(function(_){function u(){return s(this,u),i(this,u,arguments)}return d(u,_),o(u)})(lt);function fw(_){return _==null?0:_.color}function An(_){return _==null?null:_.parent}function xa(_,u){_!==null&&(_.color=u)}function av(_){return _==null?null:_.left}function mw(_){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)))?fw(g=mw(An(An(p))))===1?(xa(An(p),0),xa(g,0),xa(An(An(p)),1),p=An(An(p))):(p===mw(An(p))&&(p=An(p),this.rotateLeft(p)),xa(An(p),0),xa(An(An(p)),1),this.rotateRight(An(An(p)))):fw(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}}])})(CF),gw=(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 _w=(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(_w.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}}])})(_w),Aw=(function(){return o((function _(){s(this,_)}),[{key:"createNode",value:function(_){return new Vf(_,null)}}])})(),vw=(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 gw(new Aw);else if(arguments.length===1){var _=arguments[0];this._nodes=new gw(_)}}},{key:"linkResultDirectedEdges",value:function(_){for(var u=_.iterator();u.hasNext();)u.next().getEdges().linkResultDirectedEdges()}}])})(),wF=(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 EF(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];vw.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}}])})(),yw=(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[yw,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)}}])})(),SF=(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[yw,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}},IF=(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 IF.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}}])})(),bw=(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],bw)&&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 MF=(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 xw(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],MF)){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[SF,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),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:"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=xw,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 TF=(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}}])})(),LF=(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?TF.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))}}])})(),BF=(function(){return o((function _(){s(this,_)}),[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}])})(),RF=(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 LF(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=_}}])})(),kF=(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)}}}])})(),NF=(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(){}}])})(),PF=(function(){return o((function _(){s(this,_)}),[{key:"addIntersection",value:function(_,u){}},{key:"interfaces_",get:function(){return[NF]}}])})(),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:kF.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[PF]}}],[{key:"constructor_",value:function(){this._nodeList=new RF(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)}}])})(),DF=(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}}])})(),Ew=(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}}])})(),FF=(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 Ew(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(){}}])})(),Cw=(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=FF.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 ww(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];Cw.constructor_.call(this,p)}}}}])})(Cw),ww=(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}}])})(DF);cv.SegmentOverlapAction=ww;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 Sw=(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}}])})();Sw.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 Sw,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 OF=(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}}])})(),Iw=(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 Mw(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=_}}])})(),Mw=(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}}])})();Iw.DepthSegment=Mw;var Tw=(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 Tw;return u}},{key:"getX",value:function(){var u=this.x/this.w;if(W.isNaN(u)||W.isInfinite(u))throw new Tw;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}}}])})(),UF=(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)}}])})(),zF=(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 UF(_[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}}])})(),QF=(function(){return o((function _(){s(this,_)}),[{key:"locate",value:function(_){}}])})(),GF=(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[BF]}}],[{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)}}])})(),HF=(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[QF]}}],[{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 GF(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}}])})(),$F=(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[_]=HF.locate(u,p[_].getGeometry())),this._ptInAreaLocation[_]}},{key:"toString",value:function(){var _=new V;_.append("EdgeEndStar: "+this.getCoordinate()),_.append(`
274
274
  `);for(var u=this.iterator();u.hasNext();){var p=u.next();_.append(p),_.append(`
275
- `)}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]}}])})()),VF=(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 $F)}}])})(Aw),Lw=(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}}}])})(),qF=(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 Lw(_.getCoordinates());return this._ocaMap.get(u)}},{key:"add",value:function(_){this._edges.add(_);var u=new Lw(_.getCoordinates());this._ocaMap.put(u,_)}}],[{key:"constructor_",value:function(){this._edges=new Pe,this._ocaMap=new cd}}])})(),Bw=(function(){return o((function _(){s(this,_)}),[{key:"processIntersections",value:function(_,u,p,g){}},{key:"isDone",value:function(){}}])})(),WF=(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[Bw]}}],[{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}}])})(),YF=(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}}])})(),jF=(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 kw(B,new Sr(this.edge._label))}},{key:"add",value:function(_,u,p){var g=new YF(_,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=_}}])})(),XF=(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}}])})(),ZF=(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)}}}])})(),JF=(function(){function _(){s(this,_)}return o(_,[{key:"getChainStartIndices",value:function(u){var p=0,g=new ZF(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}}])})(),KF=(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 JF;this.startIndex=u.getChainStartIndices(this.pts)}}])})(),Rw=(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}}])})();Rw.NULL_VALUE=-1;var kw=(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 KF(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 jF(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new Rw,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 XF&&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))}}])})(pw),Nw=(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 Iw(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 WF(g)),p}},{key:"buffer",value:function(u,p){var g=this._workingPrecisionModel;g===null&&(g=u.getPrecisionModel()),this._geomFact=u.getFactory();var E=new zF(u,p,new OF(g,this._bufParams)).getCurves();if(E.size()<=0)return this.createEmptyResultGeometry();this.computeNodedEdges(E,g),this._graph=new vw(new VF),this._graph.addEdges(this._edgeList.getEdges());var B=this.createSubgraphs(this._graph),F=new wF(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 kw(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 qF;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)}}])})(),eO=(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()}}}])})(),Pw=(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}}])})();Pw.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 tO=(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}}])})(),Dw=(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 Fw(u,p,g);return this._index.query(E,new((function(){return o((function F(){s(this,F)}),[{key:"interfaces_",get:function(){return[bw]}},{key:"visitItem",value:function(F){F.select(E,B)}}])})())),B.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var _=arguments[0];this._index=_}}])})(),Fw=(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 Ew))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}}])})(tO);Dw.HotPixelSnapAction=Fw;var nO=(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[Bw]}}],[{key:"constructor_",value:function(){this._li=null,this._interiorIntersections=null;var _=arguments[0];this._li=_,this._interiorIntersections=new Pe}}])})(),iO=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"checkCorrectness",value:function(_){var u=new Pw(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 nO(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 Dw(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 eO(new iO(new ct(1)),u.getScale()),g=new Nw(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 Nw(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 sO=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],Ow=(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 sO.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 Ow(u||new Pt)}),[{key:"read",value:function(_){return this.parser.read(_)}}])})(),GeoJSONWriter:(function(){return o((function _(){s(this,_),this.parser=new Ow(this.geometryFactory)}),[{key:"write",value:function(_){return this.parser.write(_)}}])})()}}))})(zg)),zg.exports}var WQ=H2(qQ());function Hl(){return new x_}function x_(){this.reset()}x_.prototype={constructor:x_,reset:function(){this.s=this.t=0},add:function(e){IS(tm,e,this.t),IS(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 IS(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,MS=gn/4,Ga=gn*2,Yo=180/gn,Pr=gn/180,Yi=Math.abs,YQ=Math.atan,Iu=Math.atan2,hi=Math.cos,ui=Math.sin,Zu=Math.sqrt;function Y2(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&&LS.hasOwnProperty(e.type)&&LS[e.type](e,t)}var TS={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)}},LS={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){rb(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)rb(n[i],t,0)},Polygon:function(e,t){BS(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)BS(n[i],t)},GeometryCollection:function(e,t){for(var n=e.geometries,i=-1,s=n.length;++i<s;)E_(n[i],t)}};function rb(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 BS(e,t){var n=-1,i=e.length;for(t.polygonStart();++n<i;)rb(e[n],t,1);t.polygonEnd()}function jQ(e,t){e&&TS.hasOwnProperty(e.type)?TS[e.type](e,t):E_(e,t)}Hl();Hl();function ab(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 Bv(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 ob(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 j2(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 lb(e,t){return[e>gn?e-Ga:e<-gn?e+Ga:e,t]}lb.invert=lb;function XQ(e,t,n){return(e%=Ga)?t||n?j2(kS(e),NS(t,n)):kS(e):t||n?NS(t,n):lb}function RS(e){return function(t,n){return t+=e,[t>gn?t-Ga:t<-gn?t+Ga:t,n]}}function kS(e){var t=RS(e);return t.invert=RS(-e),t}function NS(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 ZQ(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=PS(a,s),r=PS(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=ab([a,-o*hi(h),-o*ui(h)]),e.point(c[0],c[1])}}function PS(e,t){t=Mu(t),t[0]-=e,ob(t);var n=Y2(-t[1]);return((-t[2]<0?-n:n)+Ga-Wn)%Ga}function X2(){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 Z2(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),DS(r),DS(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 DS(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 J2(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function KQ(e){return e.length===1&&(e=e4(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 e4(e){return function(t,n){return J2(e(t),n)}}KQ(J2);function K2(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 t4(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=X2(),f,m,A,y,x,v,b,w,S,R,k,L={point:T,lineStart:U,lineEnd:N,polygonStart:I,polygonEnd:M};function T(P,O){s(P,O)&&h.point(P,O)}function C(){for(var P=0,O=0,Q=m.length;O<Q;++O)for(var z=m[O],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(),O=k&&P,Q=(f=K2(f)).length;(O||Q)&&(c.polygonStart(),O&&(c.lineStart(),r(null,null,1,c),c.lineEnd()),Q&&Z2(f,o,P,r,c),c.polygonEnd()),h=c,f=m=A=null}function U(){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,O){var Q=s(P,O);if(m&&A.push([P,O]),R)y=P,x=O,v=Q,R=!1,Q&&(h.lineStart(),h.point(P,O));else if(Q&&S)h.point(P,O);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)),O=Math.max(rm,Math.min(Wd,O))];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,O),k=!1)}b=P,w=O,S=Q}return L}}var Rv=Hl();function n4(e,t){var n=t[0],i=t[1],s=[ui(n),-hi(n),0],r=0,a=0;Rv.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+MS,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+MS,S=ui(w),R=hi(w),k=b-f,L=k>=0?1:-1,T=L*k,C=T>gn,I=A*S;if(Rv.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));ob(M);var U=C_(s,M);ob(U);var N=(C^k>=0?-1:1)*Rc(U[2]);(i>N||i===N&&(M[0]||M[1]))&&(a+=C^k>=0?1:-1)}}return(r<-Wn||r<Wn&&Rv<-Wn)^a&1}Hl();function FS(e){return e}Hl();Hl();var Tu=1/0,w_=Tu,Pp=-Tu,S_=Pp,OS={point:i4,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 i4(e,t){e<Tu&&(Tu=e),e>Pp&&(Pp=e),t<w_&&(w_=t),t>S_&&(S_=t)}Hl();function eR(e,t,n,i){return function(s,r){var a=t(r),o=s.invert(i[0],i[1]),l=X2(),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=K2(f);var k=n4(d,o);f.length?(h||(r.polygonStart(),h=!0),Z2(f,r4,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,U;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((U=M[T])[0],U[1]);r.lineEnd()}return}C>1&&k&2&&L.push(L.pop().concat(L.shift())),f.push(L.filter(s4))}}return A}}function s4(e){return e.length>1}function r4(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 US=eR(function(){return!0},a4,l4,[-gn,-Pa]);function a4(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=o4(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 o4(e,t,n,i){var s,r,a=ui(e-n);return Yi(a)>Wn?YQ((ui(t)*(r=hi(i))*ui(n)-ui(i)*(s=hi(t))*ui(e))/(s*r*a)):(t+i)/2}function l4(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 c4(e,t){var n=hi(e),i=n>0,s=Yi(n)>Wn;function r(h,d,f,m){ZQ(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);Bv(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 U=Zu(M),N=im(T,(-C-U)/I);if(Bv(N,L),N=ab(N),!f)return N;var D=h[0],P=d[0],O=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<O&&(z=O,O=Q,Q=z),te?W?O+Q>0^N[1]<(Yi(N[0]-D)<Wn?O:Q):O<=N[1]&&N[1]<=Q:H>gn^(D<=N[0]&&N[0]<=P)){var J=im(T,(-C+U)/I);return Bv(J,L),[N,ab(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 eR(a,o,r,i?[0,-e]:[-gn,e-gn])}function tR(e){return function(t){var n=new cb;for(var i in e)n[i]=e[i];return n.stream=t,n}}function cb(){}cb.prototype={constructor:cb,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 nR(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),jQ(n,e.stream(OS));var a=OS.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 h4(e,t,n){return nR(e,[[0,0],t],n)}var zS=16,u4=hi(30*Pr);function QS(e,t){return+t?p4(e,t):d4(e)}function d4(e){return tR({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function p4(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],U=I[1],N=M-i,D=U-s,P=b*N-v*D;(P*P/w>t||Yi((v*N+b*D)/w-.5)>.3||a*f+o*m+l*A<u4)&&(n(i,s,r,a,o,l,M,U,C,S/=L,R/=L,k,y,x),x.point(M,U),n(M,U,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],zS,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,zS,i),x.lineEnd=S,S()}return x}}var f4=tR({point:function(e,t){this.stream.point(e*Pr,t*Pr)}});function m4(e){return g4(function(){return e})()}function g4(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=US,x=null,v,b,w,S=FS,R=.5,k=QS(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=f4(y(f,k(S(T=D))))},C.clipAngle=function(D){return arguments.length?(y=+D?c4(A=D*Pr,6*Pr):(A=null,US),N()):A*Yo},C.clipExtent=function(D){return arguments.length?(S=D==null?(x=v=b=w=null,FS):t4(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,U()):n},C.translate=function(D){return arguments.length?(i=+D[0],s=+D[1],U()):[i,s]},C.center=function(D){return arguments.length?(o=D[0]%360*Pr,l=D[1]%360*Pr,U()):[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,U()):[c*Yo,h*Yo,d*Yo]},C.precision=function(D){return arguments.length?(k=QS(M,R=D*D),N()):Zu(R)},C.fitExtent=function(D,P){return nR(C,D,P)},C.fitSize=function(D,P){return h4(C,D,P)};function U(){m=j2(f=XQ(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,U()}}function iR(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 sR(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 _4=iR(function(e){return Zu(2/(1+e))});_4.invert=sR(function(e){return 2*Rc(e/2)});var rR=iR(function(e){return(e=Y2(e))&&e/ui(e)});rR.invert=sR(function(e){return e});function A4(){return m4(rR).scale(79.4188).clipAngle(179.999)}function GS(e,t){return[e,t]}GS.invert=GS;var{BufferOp:v4,GeoJSONReader:y4,GeoJSONWriter:b4}=WQ;function x4(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=E4(r),l={type:r.type,coordinates:oR(r.coordinates,o)},c=new y4().read(l),h=TE(L2(t,n),"meters"),d=v4.bufferOp(c,h,i);if(d=new b4().write(d),!aR(d.coordinates))return or({type:d.type,coordinates:lR(d.coordinates,o)},s)}function aR(e){return Array.isArray(e[0])?aR(e[0]):isNaN(e[0])}function oR(e,t){return typeof e[0]!="object"?t(e):e.map(function(n){return oR(n,t)})}function lR(e,t){return typeof e[0]!="object"?t.invert(e):e.map(function(n){return lR(n,t)})}function E4(e){var t=W2(e).geometry.coordinates,n=[-t[0],-t[1]];return A4().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 cR(e);case"FeatureCollection":return C4(e);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return FE(e);default:throw new Error("unknown GeoJSON type")}}function cR(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=hR(e.properties),e.geometry==null?t.geometry=null:t.geometry=FE(e.geometry),t}function hR(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]=hR(i):t[n]=i}),t}function C4(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=>cR(n)),t}function FE(e){const t={type:e.type};return e.bbox&&(t.bbox=e.bbox),e.type==="GeometryCollection"?(t.geometries=e.geometries.map(n=>FE(n)),t):(t.coordinates=uR(e.coordinates),t)}function uR(e){const t=e;return typeof t[0]!="object"?t.slice():t.map(n=>uR(n))}var w4=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,kv=Math.ceil,Rr=Math.floor,Zs="[BigNumber Error] ",HS=Zs+"Number primitive has more than 15 significant digits: ",Xr=1e14,Gt=14,Nv=9007199254740991,Pv=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Qi=1e9;function dR(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,U,N,D,P,O,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(!w4.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(HS+T)}else z.s=Q.charCodeAt(0)===45?(Q=Q.slice(1),-1):1;for(I=x.slice(0,C),N=D=0,O=Q.length;D<O;D++)if(I.indexOf(M=Q.charAt(D))<0){if(M=="."){if(D>N){N=O;continue}}else if(!U&&(Q==Q.toUpperCase()&&(Q=Q.toLowerCase())||Q==Q.toLowerCase()&&(Q=Q.toUpperCase()))){U=!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(O=Q.length;Q.charCodeAt(--O)===48;);if(Q=Q.slice(D,++O)){if(O-=D,P&&b.DEBUG&&O>15&&(T>Nv||T!==Rr(T)))throw Error(HS+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<O){for(D&&z.c.push(+Q.slice(0,D)),O-=Gt;D<O;)z.c.push(+Q.slice(D,D+=Gt));D=Gt-(Q=Q.slice(D)).length}else D-=O;for(;D--;Q+="0");z.c.push(+Q)}}else z.c=[z.e=0]}b.clone=dR,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,U=T.e,N=T.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&U>=-Qi&&U<=Qi&&U===Rr(U)){if(M[0]===0){if(U===0&&M.length===1)return!0;break e}if(C=(U+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&&U===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,U,N,D,P,O=0,Q=[],z=new b(r);if(I==null?I=a:ri(I,0,Qi),D=kv(I/Gt),f)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(D*=2));O<D;)P=M[O]*131072+(M[O+1]>>>11),P>=9e15?(U=crypto.getRandomValues(new Uint32Array(2)),M[O]=U[0],M[O+1]=U[1]):(Q.push(P%1e14),O+=2);O=D/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(D*=7);O<D;)P=(M[O]&31)*281474976710656+M[O+1]*1099511627776+M[O+2]*4294967296+M[O+3]*16777216+(M[O+4]<<16)+(M[O+5]<<8)+M[O+6],P>=9e15?crypto.randomBytes(7).copy(M,O):(Q.push(P%1e14),O+=7);O=D/7}else throw f=!1,Error(Zs+"crypto unavailable");if(!f)for(;O<D;)P=C(),P<9e15&&(Q[O++]=P%1e14);for(D=Q[--O],I%=Gt,D&&I&&(P=Pv[Gt-I],Q[O]=Rr(D/P)*P);Q[O]===0;Q.pop(),O--);if(O<0)Q=[N=0];else{for(N=-1;Q[0]===0;Q.splice(0,1),N-=Gt);for(O=1,P=Q[0];P>=10;P/=10,O++);O<Gt&&(N-=Gt-O)}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,U,N){for(var D,P=[0],O,Q=0,z=I.length;Q<z;){for(O=P.length;O--;P[O]*=M);for(P[0]+=N.indexOf(I.charAt(Q++)),D=0;D<P.length;D++)P[D]>U-1&&(P[D+1]==null&&(P[D+1]=0),P[D+1]+=P[D]/U|0,P[D]%=U)}return P.reverse()}return function(I,M,U,N,D){var P,O,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,U,T),J.e=J.c.length),te=C(I,M,U,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,U),te=W.c,H=W.r,Q=W.e),O=Q+re+1,K=te[O],z=U/2,H=H||O<0||te[O+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[O-1]&1||ce==(W.s<0?8:7)),O<1||!te[0])I=H?io(P.charAt(1),-re,P.charAt(0)):P.charAt(0);else{if(te.length=O,H)for(--U;++te[--O]>U;)te[O]=0,O||(++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,U,N){var D,P,O,Q,z=0,H=M.length,W=U%jo,te=U/jo|0;for(M=M.slice();H--;)O=M[H]%jo,Q=M[H]/jo|0,D=te*O+Q*W,P=W*O+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,U,N,D){var P,O;if(N!=D)O=N>D?1:-1;else for(P=O=0;P<N;P++)if(M[P]!=U[P]){O=M[P]>U[P]?1:-1;break}return O}function I(M,U,N,D){for(var P=0;N--;)M[N]-=P,P=M[N]<U[N]?1:0,M[N]=P*D+M[N]-U[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,U,N,D,P){var O,Q,z,H,W,te,J,K,re,ce,oe,ge,ie,fe,ye,$,Se,Z=M.s==U.s?1:-1,Qe=M.c,Le=U.c;if(!Qe||!Qe[0]||!Le||!Le[0])return new b(!M.s||!U.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-U.e,Z=N+Q+1,P||(P=Xr,Q=kr(M.e/Gt)-kr(U.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,O=C(Le,ce,$,oe),O<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,O=1;else W==0&&(O=W=1),te=Le.slice(),J=te.length;if(J<oe&&(te=[0].concat(te)),I(ce,te,oe,P),oe=ce.length,O==-1)for(;C(Le,ce,$,oe)<1;)W++,I(ce,$<oe?Se:Le,oe,P),oe=ce.length}else O===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 U,N,D,P,O;if(I==null?I=o:ri(I,0,8),!T.c)return T.toString();if(U=T.c[0],D=T.e,C==null)O=Tr(T.c),O=M==1||M==2&&(D<=l||D>=c)?om(O,D):io(O,D,"0");else if(T=k(new b(T),C,I),N=T.e,O=Tr(T.c),P=O.length,M==1||M==2&&(C<=N||N<=l)){for(;P<C;O+="0",P++);O=om(O,N)}else if(C-=D+(M===2&&N>D),O=io(O,N,"0"),N+1>P){if(--C>0)for(O+=".";C--;O+="0");}else if(C+=N-P,C>0)for(N+1==P&&(O+=".");C--;O+="0");return T.s<0&&U?"-"+O:O}function S(T,C){for(var I,M,U=1,N=new b(T[0]);U<T.length;U++)M=new b(T[U]),(!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,U=C.length;!C[--U];C.pop());for(U=C[0];U>=10;U/=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)$/,U=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,D,P,O){var Q,z=P?D:D.replace(U,"");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,!O||O==Q?W:H}),O&&(Q=O,z=z.replace(C,"$1").replace(I,"0.$1")),D!=z))return new b(z,Q);if(b.DEBUG)throw Error(Zs+"Not a"+(O?" base "+O:"")+" number: "+D);N.s=null}N.c=N.e=null}})();function k(T,C,I,M){var U,N,D,P,O,Q,z,H=T.c,W=Pv;if(H){e:{for(U=1,P=H[0];P>=10;P/=10,U++);if(N=C-U,N<0)N+=Gt,D=C,O=H[Q=0],z=Rr(O/W[U-D-1]%10);else if(Q=kv((N+1)/Gt),Q>=H.length)if(M){for(;H.length<=Q;H.push(0));O=z=0,U=1,N%=Gt,D=N-Gt+1}else break e;else{for(O=P=H[Q],U=1;P>=10;P/=10,U++);N%=Gt,D=N-Gt+U,z=D<0?0:Rr(O/W[U-D-1]%10)}if(M=M||C<0||H[Q+1]!=null||(D<0?O:O%W[U-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?O/W[U-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(O/W[U-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,U,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=((U=I.length-1)-kr(this.e/Gt))*Gt,U=I[U])for(;U%10==0;U/=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,U,N,D,P,O,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(O=T.s<0,C){if(C.c?!C.c[0]:!C.s)return new b(NaN);M=!O&&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(O?1/N:N);A&&(N=kv(A/Gt+2))}for(P?(I=new b(.5),O&&(T.s=1),Q=am(T)):(U=Math.abs(+L(T)),Q=U%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(U){if(U=Rr(U/2),U===0)break;Q=U%2}else if(T=T.times(I),k(T,T.e+1,1),T.e>14)Q=am(T);else{if(U=+L(T),U===0)break;Q=U%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(C))}return M?z:(O&&(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,U,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 O=D.e/Gt,Q=T.e/Gt,z=D.c,H=T.c;if(!O||!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(O=kr(O),Q=kr(Q),z=z.slice(),P=O-Q){for((N=P<0)?(P=-P,U=z):(Q=O,U=H),U.reverse(),C=P;C--;U.push(0));U.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&&(U=z,z=H,H=U,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,U=this;return T=new b(T,C),!U.c||!T.s||T.c&&!T.c[0]?new b(NaN):!T.c||U.c&&!U.c[0]?new b(U):(m==9?(M=T.s,T.s=1,I=t(U,T,0,3),T.s=M,I.s*=M):I=t(U,T,0,m),T=U.minus(I.times(T)),!T.c[0]&&m==1&&(T.s=U.s),T)},s.multipliedBy=s.times=function(T,C){var I,M,U,N,D,P,O,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,O=oe.length,H=ge.length,O<H&&(J=oe,oe=ge,ge=J,U=O,O=H,H=U),U=O+H,J=[];U--;J.push(0));for(K=Xr,re=jo,U=H;--U>=0;){for(I=0,W=ge[U]%re,te=ge[U]/re|0,D=O,N=U+D;N>U;)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,U=M.s;if(T=new b(T,C),C=T.s,!U||!C)return new b(NaN);if(U!=C)return T.s=-C,M.minus(T);var N=M.e/Gt,D=T.e/Gt,P=M.c,O=T.c;if(!N||!D){if(!P||!O)return new b(U/0);if(!P[0]||!O[0])return O[0]?T:new b(P[0]?M:U*0)}if(N=kr(N),D=kr(D),P=P.slice(),U=N-D){for(U>0?(D=N,I=O):(U=-U,I=P),I.reverse();U--;I.push(0));I.reverse()}for(U=P.length,C=O.length,U-C<0&&(I=O,O=P,P=I,C=U),U=0;C;)U=(P[--C]=P[C]+O[C]+U)/Xr|0,P[C]=Xr===P[C]?0:P[C]%Xr;return U&&(P=[U].concat(P),++D),R(T,P,D)},s.precision=s.sd=function(T,C){var I,M,U,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(U=I.length-1,M=U*Gt+1,U=I[U]){for(;U%10==0;U/=10,M--);for(U=I[0];U>=10;U/=10,M++);}return T&&N.e+1>M&&(M=N.e+1),M},s.shiftedBy=function(T){return ri(T,-Nv,Nv),this.times("1e"+T)},s.squareRoot=s.sqrt=function(){var T,C,I,M,U,N=this,D=N.c,P=N.s,O=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+O)%2==0&&(C+="0"),P=Math.sqrt(+C),O=kr((O+1)/2)-(O<0||O%2),P==1/0?C="5e"+O:(C=P.toExponential(),C=C.slice(0,C.indexOf("e")+1)+O),I=new b(C)):I=new b(P+""),I.c[0]){for(O=I.e,P=O+Q,P<3&&(P=0);;)if(U=I,I=z.times(U.plus(t(N,U,Q,1))),Tr(U.c).slice(0,P)===(C=Tr(I.c)).slice(0,P))if(I.e<O&&--P,C=C.slice(P-3,P+1),C=="9999"||!M&&C=="4999"){if(!M&&(k(U,U.e+a+2,0),U.times(U).eq(N))){I=U;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,U=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=U.toFixed(T,C),U.c){var N,D=M.split("."),P=+I.groupSize,O=+I.secondaryGroupSize,Q=I.groupSeparator||"",z=D[0],H=D[1],W=U.s<0,te=W?z.slice(1):z,J=te.length;if(O&&(N=P,P=O,O=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);O>0&&(z+=Q+te.slice(N)),W&&(z="-"+z)}M=H?z+(I.decimalSeparator||"")+((O=+I.fractionGroupSize)?H.replace(new RegExp("\\d{"+O+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):H):z}return(I.prefix||"")+M+(I.suffix||"")},s.toFraction=function(T){var C,I,M,U,N,D,P,O,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=O=new b(r),W=Tr(J),N=C.e=W.length-te.e-1,C.c[0]=Pv[(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),O.c[0]=0;z=t(P,C,0,1),U=I.plus(z.times(M)),U.comparedTo(T)!=1;)I=M,M=U,Q=O.plus(z.times(U=Q)),O=U,C=P.minus(z.times(U=C)),P=U;return U=t(T.minus(I),M,0,1),O=O.plus(U.times(Q)),I=I.plus(U.times(M)),O.s=Q.s=te.s,N=N*2,H=t(Q,M,N,o).minus(te).abs().comparedTo(t(O,I,N,o).minus(te).abs())<1?[Q,M]:[O,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,U=I.e;return U===null?M?(C="Infinity",M<0&&(C="-"+C)):C="NaN":(T==null?C=U<=l||U>=c?om(Tr(I.c),U):io(Tr(I.c),U,"0"):T===10&&v?(I=k(new b(I),a+U+1,o),C=io(Tr(I.c),I.e,"0")):(ri(T,2,x.length,"Base"),C=n(io(Tr(I.c),U,"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=dR(),S4=class{key;left=null;right=null;constructor(e){this.key=e}},fd=class extends S4{constructor(e){super(e)}},I4=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 I4{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 T4(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new M4(this.wrap())}[Symbol.toStringTag]="[object Set]"},pR=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}},M4=class extends pR{getValue(e){return e.key}},T4=class extends pR{getValue(e){return[e.key,e.key]}},fR=e=>()=>e,hb=e=>{const t=e?(n,i)=>i.minus(n).abs().isLessThanOrEqualTo(e):fR(!1);return(n,i)=>t(n,i)?0:n.comparedTo(i)};function L4(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)):fR(!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 B4=e=>e,R4=e=>{if(e){const t=new I_(hb(e)),n=new I_(hb(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 B4},ub=e=>({set:t=>{Fo=ub(t)},reset:()=>ub(e),compare:hb(e),snap:R4(e),orient:L4(e)}),Fo=ub(),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),db=(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)),mR=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),M_=e=>mR(e,e).sqrt(),k4=(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))},N4=(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 mR(s,i).div(M_(s)).div(M_(i))},$S=(e,t,n)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(n.minus(e.y))),y:n},VS=(e,t,n)=>t.x.isZero()?null:{x:n,y:e.y.plus(t.y.div(t.x).times(n.minus(e.x)))},P4=(e,t,n,i)=>{if(t.x.isZero())return VS(n,i,e.x);if(i.x.isZero())return VS(e,t,n.x);if(t.y.isZero())return $S(n,i,e.y);if(i.y.isZero())return $S(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 gR{point;isLeft;segment;otherSE;consumedBy;static compare(t,n){const i=gR.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:k4(this.point,t.point,r.point),cosine:N4(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}}},D4=class pb{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 pb(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 pb(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}}},qS=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}},F4=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 qS(s));else{const r=s.enclosingRing();r?.poly||t.push(new qS(r)),r?.poly?.addInterior(s)}}return t}},O4=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}},U4=class{type;numMultiPolys;run(e,t,n){jd.type=e;const i=[new YS(t,!0)];for(let o=0,l=n.length;o<l;o++)i.push(new YS(n[o],!1));if(jd.numMultiPolys=i.length,jd.type==="difference"){const o=i[0];let l=1;for(;l<i.length;)db(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(db(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 O4(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 F4(D4.factory(r.segments)).getGeom()}},jd=new U4,Fp=jd,z4=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=++z4,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=db(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=P4(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}},WS=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}},Q4=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 WS(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 WS(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}},YS=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 Q4(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}},G4=(e,...t)=>Fp.run("union",e,t),H4=(e,...t)=>Fp.run("intersection",e,t),$4=(e,...t)=>Fp.run("difference",e,t);Fo.set;function _R(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=$4(t[0],...t.slice(1));return i.length===0?null:i.length===1?Hr(i[0],n):mA(i,n)}function V4(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,B2(q4(i,s),"meters",n.units)}function q4(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 AR(e,t,n,i={}){const s=t<0;let r=B2(Math.abs(t),i.units,"meters");s&&(r=-Math.abs(r));const a=Si(e),o=W4(a,r,n);return o[0]+=o[0]-a[0]>180?-360:a[0]-o[0]>180?360:0,wi(o,i.properties)}function W4(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 Y4(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=H4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function j4(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]=jS(a,t,i)}),e):jS(e,t,i)}function jS(e,t,n){const i=v_(e)==="Point",s=X4(e,n);return t===1||i||(Ql(e,function(r){const a=V4(s,r),o=_z(s,r),l=as(AR(s,a*t,o));r[0]=l[0],r[1]=l[1],r.length===3&&(r[2]*=t)}),delete e.bbox),e}function X4(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 W2(e);case void 0:case null:case"centroid":return Dp(e);default:throw new Error("invalid origin")}}function Z4(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 K4(e,t){for(var n=e[0],i=[n],s,r=1,a=e.length;r<a;r++)s=e[r],Z4(s,n)>t&&(i.push(s),n=s);return n!==s&&i.push(s),i}function fb(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&&fb(e,t,a,i,s),s.push(e[a]),n-a>1&&fb(e,a,n,i,s))}function eG(e,t){var n=e.length-1,i=[e[0]];return fb(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:K4(e,i),e=eG(e,i),e}function mb(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){tG(l,r,a)}),e}function tG(e,t,n){const i=e.type;if(i==="Point"||i==="MultiPoint")return e;if(G2(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=XS(e.coordinates,t,n);break;case"MultiPolygon":e.coordinates=e.coordinates.map(s=>XS(s,t,n))}return e}function XS(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(;!ZS(r)&&s>=Number.EPSILON;)s-=s*.01,r=L_(i,s,n);return ZS(r)?((r[r.length-1][0]!==r[0][0]||r[r.length-1][1]!==r[0][1])&&r.push(r[0]),r):i})}function ZS(e){return e.length<3?!1:!(e.length===3&&e[2][0]===e[0][0]&&e[2][1]===e[0][1])}function gb(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(AR(o,t,n,{units:s}));o[0]=l[0],o[1]=l[1],r&&o.length===3&&(o[2]+=r)}),e}function nG(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=G4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function iG(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 LE;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=sG(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 sG(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 rG(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(!oG(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=iG(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:aG(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 KS(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 KS(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 LE;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,U=[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);){U.push(c[P].coord);for(var O=void 0,v=0;v<x.length;v++)if(x[v].isect==P){O=v;break}if(O!=null&&x.splice(O,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}}U.push(c[P].coord),k.push(Hr([U],{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}},KS=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 aG(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 oG(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 lG(e){var t=[];return Do(e,function(n){n.geometry.type==="Polygon"&&Po(rG(n),function(i){t.push(Hr(i.geometry.coordinates,n.properties))})}),Kt(t)}var cG=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())}},e1=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}},hG=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}},t1=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}},uG=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}},dG=["polygon","line","rectangle","circle","marker"],pG=["select","drag","change","rotate","cut","delete","scale","copy","split","union","difference","simplify","lasso"],Dv=["select","scale","copy","split","union","difference","simplify","lasso"],fG=["snapping","measurements"],mG=["open","save"],gG={position:"top-left",collapsed:!1,drawModes:dG,editModes:pG,helperModes:fG,fileModes:mG,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},Fv={tolerance:.001,highQuality:!1,mutate:!1},n1={offset:[5e-4,5e-4],generateNewIds:!0};function Oo(){return`feature_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function vR(e){return e.geometry.type==="Polygon"||e.geometry.type==="MultiPolygon"}function _G(e){return e.geometry.type==="LineString"||e.geometry.type==="MultiLineString"}function i1(e,t,n){return Math.min(Math.max(e,t),n)}function gd(e){return vz(e).length}var AG=class{options;constructor(e={}){this.options={offset:e.offset??n1.offset,generateNewIds:e.generateNewIds??n1.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?gb(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})),gb(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}},vG=class{defaultOptions;constructor(e){this.defaultOptions={tolerance:e?.tolerance??Fv.tolerance,highQuality:e?.highQuality??Fv.highQuality,mutate:e?.mutate??Fv.mutate}}simplify(e,t){return mb(e,{...this.defaultOptions,...t})}simplifyWithStats(e,t){const n={...this.defaultOptions,...t},i=gd(e),s=mb(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}},yG=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=nG(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($2(e[t],e[n])||DE(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}},bG=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=_R(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 $2(e,t)||yS(e,t)||DE(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=Y4(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 yS(e,t)?this.difference(e,[t]).result:(console.warn("Hole must be completely inside the polygon"),null)}catch{return null}}},xG=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=j4(e,i1(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=i1(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}},EG=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"?PQ(n,e):DE(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}},CG=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=RE(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=x4(t,1e-5,{units:"degrees"});if(!n)return[];const i=_R(Kt([e,n]));if(!i)return[];if(i.geometry.type==="MultiPolygon")return i.geometry.coordinates.map(r=>Hr(r));const s=lG(i);return s.features.length>1?s.features:[i]}catch{return[]}}clipLineToBbox(e,t){try{return wz(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}},wG=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=mb(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 G2(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(vR)}var _b=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={...gG,...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 AG,this.simplifyFeature=new vG({tolerance:this.options.simplifyTolerance}),this.unionFeature=new yG,this.differenceFeature=new bG,this.scaleFeature=new xG,this.lassoFeature=new EG,this.splitFeature=new CG,this.freehandFeature=new wG,this.options.enableHistory!==!1&&(this.historyManager=new cG(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-BiSZ4hUw.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=R2(wi(t),wi(n)),r=[];this.multiDragOriginalFeatures.forEach((a,o)=>{const l=gb(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(),Dv.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(!vR(t)&&!_G(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=>!Dv.includes(r));if(n.length>0){const r=this.createToolGroup("Edit",n,"edit");t.appendChild(r)}const i=this.options.editModes.filter(r=>Dv.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 e1(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 hG(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 t1(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 t1(a,i));for(const a of t)s.push(new e1(a,i));const r=new uG(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}},Ov="geo-editor-features",yR=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",Ov))):!t&&this._hasFeatures&&(this._hasFeatures=!1,this._changeCallbacks.forEach(n=>n("remove",Ov))),t?[Ov]:[]}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=[]}},SG=Object.defineProperty,IG=(e,t,n)=>t in e?SG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oi=(e,t,n)=>IG(e,typeof t!="symbol"?t+"":t,n),MG="https://planetarycomputer.microsoft.com/api/stac/v1",TG=class{constructor(e=MG){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}}},LG="https://planetarycomputer.microsoft.com/api/data/v1",BG=class{constructor(e=LG){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("&")}},RG="https://planetarycomputer.microsoft.com/api/sas/v1/token",kG=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(`${RG}/${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)}},NG=[{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"}}],PG=[{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"}}],DG=[{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"}}],s1=[{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"}}],FG=[{collectionId:"sentinel-2-l2a",defaultPreset:"true-color",presets:NG},{collectionId:"landsat-c2-l2",defaultPreset:"true-color",presets:PG},{collectionId:"naip",defaultPreset:"rgb",presets:DG},{collectionId:"cop-dem-glo-30",defaultPreset:"elevation",presets:s1},{collectionId:"cop-dem-glo-90",defaultPreset:"elevation",presets:s1}];function bR(e){return FG.find(t=>t.collectionId===e)}function r1(e){const t=bR(e);return t?.presets??[]}function a1(e){const t=bR(e);if(t)return t.presets.find(n=>n.name===t.defaultPreset)}function o1(e=""){const t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return e?`${e}-${t}-${n}`:`${t}-${n}`}function l1(e){if(!e)return"Unknown";try{return new Date(e).toLocaleDateString()}catch{return e}}function c1(e){return e.datetime||e.start_datetime||e.end_datetime||null}function OG(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function UG(e){const[t,n,i,s]=e;return`${t.toFixed(2)}, ${n.toFixed(2)}, ${i.toFixed(2)}, ${s.toFixed(2)}`}var zG=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)}-${o1().slice(-6)}`,i=`${n}-source`,s=e.collection||"";let r=t?.renderParams||{},a=t?.presetName;if(!t?.renderParams&&!t?.assets&&s){const h=a1(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)}-${o1().slice(-6)}`,i=`${n}-source`;let s=t?.renderParams||{},r=t?.presetName;if(!t?.renderParams&&!t?.assets){const h=a1(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]]}},QG={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},Ab=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={...QG,...e},this._state=this._getInitialState(),this._stacClient=new TG(this._options.stacApiUrl),this._tilerClient=new BG(this._options.tilerApiUrl),this._sasManager=new kG}onAdd(e){return this._map=e,this._mapContainer=e.getContainer(),this._layerManager=new zG(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=`
275
+ `)}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]}}])})()),VF=(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 $F)}}])})(Aw),Lw=(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}}}])})(),qF=(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 Lw(_.getCoordinates());return this._ocaMap.get(u)}},{key:"add",value:function(_){this._edges.add(_);var u=new Lw(_.getCoordinates());this._ocaMap.put(u,_)}}],[{key:"constructor_",value:function(){this._edges=new Pe,this._ocaMap=new cd}}])})(),Bw=(function(){return o((function _(){s(this,_)}),[{key:"processIntersections",value:function(_,u,p,g){}},{key:"isDone",value:function(){}}])})(),WF=(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[Bw]}}],[{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}}])})(),YF=(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}}])})(),jF=(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 kw(B,new Sr(this.edge._label))}},{key:"add",value:function(_,u,p){var g=new YF(_,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=_}}])})(),XF=(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}}])})(),ZF=(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)}}}])})(),JF=(function(){function _(){s(this,_)}return o(_,[{key:"getChainStartIndices",value:function(u){var p=0,g=new ZF(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}}])})(),KF=(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 JF;this.startIndex=u.getChainStartIndices(this.pts)}}])})(),Rw=(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}}])})();Rw.NULL_VALUE=-1;var kw=(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 KF(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 jF(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new Rw,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 XF&&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))}}])})(pw),Nw=(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 Iw(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 WF(g)),p}},{key:"buffer",value:function(u,p){var g=this._workingPrecisionModel;g===null&&(g=u.getPrecisionModel()),this._geomFact=u.getFactory();var E=new zF(u,p,new OF(g,this._bufParams)).getCurves();if(E.size()<=0)return this.createEmptyResultGeometry();this.computeNodedEdges(E,g),this._graph=new vw(new VF),this._graph.addEdges(this._edgeList.getEdges());var B=this.createSubgraphs(this._graph),F=new wF(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 kw(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 qF;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)}}])})(),eO=(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()}}}])})(),Pw=(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}}])})();Pw.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 tO=(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}}])})(),Dw=(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 Fw(u,p,g);return this._index.query(E,new((function(){return o((function F(){s(this,F)}),[{key:"interfaces_",get:function(){return[bw]}},{key:"visitItem",value:function(F){F.select(E,B)}}])})())),B.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var _=arguments[0];this._index=_}}])})(),Fw=(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 Ew))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}}])})(tO);Dw.HotPixelSnapAction=Fw;var nO=(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[Bw]}}],[{key:"constructor_",value:function(){this._li=null,this._interiorIntersections=null;var _=arguments[0];this._li=_,this._interiorIntersections=new Pe}}])})(),iO=(function(){return o((function _(){s(this,_),_.constructor_.apply(this,arguments)}),[{key:"checkCorrectness",value:function(_){var u=new Pw(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 nO(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 Dw(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 eO(new iO(new ct(1)),u.getScale()),g=new Nw(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 Nw(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 sO=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],Ow=(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 sO.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 Ow(u||new Pt)}),[{key:"read",value:function(_){return this.parser.read(_)}}])})(),GeoJSONWriter:(function(){return o((function _(){s(this,_),this.parser=new Ow(this.geometryFactory)}),[{key:"write",value:function(_){return this.parser.write(_)}}])})()}}))})(zg)),zg.exports}var WQ=H2(qQ());function Hl(){return new x_}function x_(){this.reset()}x_.prototype={constructor:x_,reset:function(){this.s=this.t=0},add:function(e){IS(tm,e,this.t),IS(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 IS(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,MS=gn/4,Ga=gn*2,Yo=180/gn,Pr=gn/180,Yi=Math.abs,YQ=Math.atan,Iu=Math.atan2,hi=Math.cos,ui=Math.sin,Zu=Math.sqrt;function Y2(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&&LS.hasOwnProperty(e.type)&&LS[e.type](e,t)}var TS={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)}},LS={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){rb(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)rb(n[i],t,0)},Polygon:function(e,t){BS(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,i=-1,s=n.length;++i<s;)BS(n[i],t)},GeometryCollection:function(e,t){for(var n=e.geometries,i=-1,s=n.length;++i<s;)E_(n[i],t)}};function rb(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 BS(e,t){var n=-1,i=e.length;for(t.polygonStart();++n<i;)rb(e[n],t,1);t.polygonEnd()}function jQ(e,t){e&&TS.hasOwnProperty(e.type)?TS[e.type](e,t):E_(e,t)}Hl();Hl();function ab(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 Bv(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 ob(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 j2(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 lb(e,t){return[e>gn?e-Ga:e<-gn?e+Ga:e,t]}lb.invert=lb;function XQ(e,t,n){return(e%=Ga)?t||n?j2(kS(e),NS(t,n)):kS(e):t||n?NS(t,n):lb}function RS(e){return function(t,n){return t+=e,[t>gn?t-Ga:t<-gn?t+Ga:t,n]}}function kS(e){var t=RS(e);return t.invert=RS(-e),t}function NS(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 ZQ(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=PS(a,s),r=PS(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=ab([a,-o*hi(h),-o*ui(h)]),e.point(c[0],c[1])}}function PS(e,t){t=Mu(t),t[0]-=e,ob(t);var n=Y2(-t[1]);return((-t[2]<0?-n:n)+Ga-Wn)%Ga}function X2(){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 Z2(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),DS(r),DS(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 DS(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 J2(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function KQ(e){return e.length===1&&(e=e4(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 e4(e){return function(t,n){return J2(e(t),n)}}KQ(J2);function K2(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 t4(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=X2(),f,m,A,y,x,v,b,w,S,R,k,L={point:T,lineStart:U,lineEnd:N,polygonStart:I,polygonEnd:M};function T(P,O){s(P,O)&&h.point(P,O)}function C(){for(var P=0,O=0,Q=m.length;O<Q;++O)for(var z=m[O],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(),O=k&&P,Q=(f=K2(f)).length;(O||Q)&&(c.polygonStart(),O&&(c.lineStart(),r(null,null,1,c),c.lineEnd()),Q&&Z2(f,o,P,r,c),c.polygonEnd()),h=c,f=m=A=null}function U(){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,O){var Q=s(P,O);if(m&&A.push([P,O]),R)y=P,x=O,v=Q,R=!1,Q&&(h.lineStart(),h.point(P,O));else if(Q&&S)h.point(P,O);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)),O=Math.max(rm,Math.min(Wd,O))];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,O),k=!1)}b=P,w=O,S=Q}return L}}var Rv=Hl();function n4(e,t){var n=t[0],i=t[1],s=[ui(n),-hi(n),0],r=0,a=0;Rv.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+MS,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+MS,S=ui(w),R=hi(w),k=b-f,L=k>=0?1:-1,T=L*k,C=T>gn,I=A*S;if(Rv.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));ob(M);var U=C_(s,M);ob(U);var N=(C^k>=0?-1:1)*Rc(U[2]);(i>N||i===N&&(M[0]||M[1]))&&(a+=C^k>=0?1:-1)}}return(r<-Wn||r<Wn&&Rv<-Wn)^a&1}Hl();function FS(e){return e}Hl();Hl();var Tu=1/0,w_=Tu,Pp=-Tu,S_=Pp,OS={point:i4,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 i4(e,t){e<Tu&&(Tu=e),e>Pp&&(Pp=e),t<w_&&(w_=t),t>S_&&(S_=t)}Hl();function eR(e,t,n,i){return function(s,r){var a=t(r),o=s.invert(i[0],i[1]),l=X2(),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=K2(f);var k=n4(d,o);f.length?(h||(r.polygonStart(),h=!0),Z2(f,r4,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,U;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((U=M[T])[0],U[1]);r.lineEnd()}return}C>1&&k&2&&L.push(L.pop().concat(L.shift())),f.push(L.filter(s4))}}return A}}function s4(e){return e.length>1}function r4(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 US=eR(function(){return!0},a4,l4,[-gn,-Pa]);function a4(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=o4(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 o4(e,t,n,i){var s,r,a=ui(e-n);return Yi(a)>Wn?YQ((ui(t)*(r=hi(i))*ui(n)-ui(i)*(s=hi(t))*ui(e))/(s*r*a)):(t+i)/2}function l4(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 c4(e,t){var n=hi(e),i=n>0,s=Yi(n)>Wn;function r(h,d,f,m){ZQ(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);Bv(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 U=Zu(M),N=im(T,(-C-U)/I);if(Bv(N,L),N=ab(N),!f)return N;var D=h[0],P=d[0],O=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<O&&(z=O,O=Q,Q=z),te?W?O+Q>0^N[1]<(Yi(N[0]-D)<Wn?O:Q):O<=N[1]&&N[1]<=Q:H>gn^(D<=N[0]&&N[0]<=P)){var J=im(T,(-C+U)/I);return Bv(J,L),[N,ab(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 eR(a,o,r,i?[0,-e]:[-gn,e-gn])}function tR(e){return function(t){var n=new cb;for(var i in e)n[i]=e[i];return n.stream=t,n}}function cb(){}cb.prototype={constructor:cb,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 nR(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),jQ(n,e.stream(OS));var a=OS.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 h4(e,t,n){return nR(e,[[0,0],t],n)}var zS=16,u4=hi(30*Pr);function QS(e,t){return+t?p4(e,t):d4(e)}function d4(e){return tR({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function p4(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],U=I[1],N=M-i,D=U-s,P=b*N-v*D;(P*P/w>t||Yi((v*N+b*D)/w-.5)>.3||a*f+o*m+l*A<u4)&&(n(i,s,r,a,o,l,M,U,C,S/=L,R/=L,k,y,x),x.point(M,U),n(M,U,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],zS,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,zS,i),x.lineEnd=S,S()}return x}}var f4=tR({point:function(e,t){this.stream.point(e*Pr,t*Pr)}});function m4(e){return g4(function(){return e})()}function g4(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=US,x=null,v,b,w,S=FS,R=.5,k=QS(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=f4(y(f,k(S(T=D))))},C.clipAngle=function(D){return arguments.length?(y=+D?c4(A=D*Pr,6*Pr):(A=null,US),N()):A*Yo},C.clipExtent=function(D){return arguments.length?(S=D==null?(x=v=b=w=null,FS):t4(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,U()):n},C.translate=function(D){return arguments.length?(i=+D[0],s=+D[1],U()):[i,s]},C.center=function(D){return arguments.length?(o=D[0]%360*Pr,l=D[1]%360*Pr,U()):[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,U()):[c*Yo,h*Yo,d*Yo]},C.precision=function(D){return arguments.length?(k=QS(M,R=D*D),N()):Zu(R)},C.fitExtent=function(D,P){return nR(C,D,P)},C.fitSize=function(D,P){return h4(C,D,P)};function U(){m=j2(f=XQ(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,U()}}function iR(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 sR(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 _4=iR(function(e){return Zu(2/(1+e))});_4.invert=sR(function(e){return 2*Rc(e/2)});var rR=iR(function(e){return(e=Y2(e))&&e/ui(e)});rR.invert=sR(function(e){return e});function A4(){return m4(rR).scale(79.4188).clipAngle(179.999)}function GS(e,t){return[e,t]}GS.invert=GS;var{BufferOp:v4,GeoJSONReader:y4,GeoJSONWriter:b4}=WQ;function x4(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=E4(r),l={type:r.type,coordinates:oR(r.coordinates,o)},c=new y4().read(l),h=TE(L2(t,n),"meters"),d=v4.bufferOp(c,h,i);if(d=new b4().write(d),!aR(d.coordinates))return or({type:d.type,coordinates:lR(d.coordinates,o)},s)}function aR(e){return Array.isArray(e[0])?aR(e[0]):isNaN(e[0])}function oR(e,t){return typeof e[0]!="object"?t(e):e.map(function(n){return oR(n,t)})}function lR(e,t){return typeof e[0]!="object"?t.invert(e):e.map(function(n){return lR(n,t)})}function E4(e){var t=W2(e).geometry.coordinates,n=[-t[0],-t[1]];return A4().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 cR(e);case"FeatureCollection":return C4(e);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return FE(e);default:throw new Error("unknown GeoJSON type")}}function cR(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=hR(e.properties),e.geometry==null?t.geometry=null:t.geometry=FE(e.geometry),t}function hR(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]=hR(i):t[n]=i}),t}function C4(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=>cR(n)),t}function FE(e){const t={type:e.type};return e.bbox&&(t.bbox=e.bbox),e.type==="GeometryCollection"?(t.geometries=e.geometries.map(n=>FE(n)),t):(t.coordinates=uR(e.coordinates),t)}function uR(e){const t=e;return typeof t[0]!="object"?t.slice():t.map(n=>uR(n))}var w4=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,kv=Math.ceil,Rr=Math.floor,Zs="[BigNumber Error] ",HS=Zs+"Number primitive has more than 15 significant digits: ",Xr=1e14,Gt=14,Nv=9007199254740991,Pv=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Qi=1e9;function dR(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,U,N,D,P,O,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(!w4.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(HS+T)}else z.s=Q.charCodeAt(0)===45?(Q=Q.slice(1),-1):1;for(I=x.slice(0,C),N=D=0,O=Q.length;D<O;D++)if(I.indexOf(M=Q.charAt(D))<0){if(M=="."){if(D>N){N=O;continue}}else if(!U&&(Q==Q.toUpperCase()&&(Q=Q.toLowerCase())||Q==Q.toLowerCase()&&(Q=Q.toUpperCase()))){U=!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(O=Q.length;Q.charCodeAt(--O)===48;);if(Q=Q.slice(D,++O)){if(O-=D,P&&b.DEBUG&&O>15&&(T>Nv||T!==Rr(T)))throw Error(HS+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<O){for(D&&z.c.push(+Q.slice(0,D)),O-=Gt;D<O;)z.c.push(+Q.slice(D,D+=Gt));D=Gt-(Q=Q.slice(D)).length}else D-=O;for(;D--;Q+="0");z.c.push(+Q)}}else z.c=[z.e=0]}b.clone=dR,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,U=T.e,N=T.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&U>=-Qi&&U<=Qi&&U===Rr(U)){if(M[0]===0){if(U===0&&M.length===1)return!0;break e}if(C=(U+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&&U===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,U,N,D,P,O=0,Q=[],z=new b(r);if(I==null?I=a:ri(I,0,Qi),D=kv(I/Gt),f)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(D*=2));O<D;)P=M[O]*131072+(M[O+1]>>>11),P>=9e15?(U=crypto.getRandomValues(new Uint32Array(2)),M[O]=U[0],M[O+1]=U[1]):(Q.push(P%1e14),O+=2);O=D/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(D*=7);O<D;)P=(M[O]&31)*281474976710656+M[O+1]*1099511627776+M[O+2]*4294967296+M[O+3]*16777216+(M[O+4]<<16)+(M[O+5]<<8)+M[O+6],P>=9e15?crypto.randomBytes(7).copy(M,O):(Q.push(P%1e14),O+=7);O=D/7}else throw f=!1,Error(Zs+"crypto unavailable");if(!f)for(;O<D;)P=C(),P<9e15&&(Q[O++]=P%1e14);for(D=Q[--O],I%=Gt,D&&I&&(P=Pv[Gt-I],Q[O]=Rr(D/P)*P);Q[O]===0;Q.pop(),O--);if(O<0)Q=[N=0];else{for(N=-1;Q[0]===0;Q.splice(0,1),N-=Gt);for(O=1,P=Q[0];P>=10;P/=10,O++);O<Gt&&(N-=Gt-O)}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,U,N){for(var D,P=[0],O,Q=0,z=I.length;Q<z;){for(O=P.length;O--;P[O]*=M);for(P[0]+=N.indexOf(I.charAt(Q++)),D=0;D<P.length;D++)P[D]>U-1&&(P[D+1]==null&&(P[D+1]=0),P[D+1]+=P[D]/U|0,P[D]%=U)}return P.reverse()}return function(I,M,U,N,D){var P,O,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,U,T),J.e=J.c.length),te=C(I,M,U,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,U),te=W.c,H=W.r,Q=W.e),O=Q+re+1,K=te[O],z=U/2,H=H||O<0||te[O+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[O-1]&1||ce==(W.s<0?8:7)),O<1||!te[0])I=H?io(P.charAt(1),-re,P.charAt(0)):P.charAt(0);else{if(te.length=O,H)for(--U;++te[--O]>U;)te[O]=0,O||(++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,U,N){var D,P,O,Q,z=0,H=M.length,W=U%jo,te=U/jo|0;for(M=M.slice();H--;)O=M[H]%jo,Q=M[H]/jo|0,D=te*O+Q*W,P=W*O+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,U,N,D){var P,O;if(N!=D)O=N>D?1:-1;else for(P=O=0;P<N;P++)if(M[P]!=U[P]){O=M[P]>U[P]?1:-1;break}return O}function I(M,U,N,D){for(var P=0;N--;)M[N]-=P,P=M[N]<U[N]?1:0,M[N]=P*D+M[N]-U[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,U,N,D,P){var O,Q,z,H,W,te,J,K,re,ce,oe,ge,ie,fe,ye,$,Se,Z=M.s==U.s?1:-1,Qe=M.c,Le=U.c;if(!Qe||!Qe[0]||!Le||!Le[0])return new b(!M.s||!U.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-U.e,Z=N+Q+1,P||(P=Xr,Q=kr(M.e/Gt)-kr(U.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,O=C(Le,ce,$,oe),O<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,O=1;else W==0&&(O=W=1),te=Le.slice(),J=te.length;if(J<oe&&(te=[0].concat(te)),I(ce,te,oe,P),oe=ce.length,O==-1)for(;C(Le,ce,$,oe)<1;)W++,I(ce,$<oe?Se:Le,oe,P),oe=ce.length}else O===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 U,N,D,P,O;if(I==null?I=o:ri(I,0,8),!T.c)return T.toString();if(U=T.c[0],D=T.e,C==null)O=Tr(T.c),O=M==1||M==2&&(D<=l||D>=c)?om(O,D):io(O,D,"0");else if(T=k(new b(T),C,I),N=T.e,O=Tr(T.c),P=O.length,M==1||M==2&&(C<=N||N<=l)){for(;P<C;O+="0",P++);O=om(O,N)}else if(C-=D+(M===2&&N>D),O=io(O,N,"0"),N+1>P){if(--C>0)for(O+=".";C--;O+="0");}else if(C+=N-P,C>0)for(N+1==P&&(O+=".");C--;O+="0");return T.s<0&&U?"-"+O:O}function S(T,C){for(var I,M,U=1,N=new b(T[0]);U<T.length;U++)M=new b(T[U]),(!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,U=C.length;!C[--U];C.pop());for(U=C[0];U>=10;U/=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)$/,U=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,D,P,O){var Q,z=P?D:D.replace(U,"");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,!O||O==Q?W:H}),O&&(Q=O,z=z.replace(C,"$1").replace(I,"0.$1")),D!=z))return new b(z,Q);if(b.DEBUG)throw Error(Zs+"Not a"+(O?" base "+O:"")+" number: "+D);N.s=null}N.c=N.e=null}})();function k(T,C,I,M){var U,N,D,P,O,Q,z,H=T.c,W=Pv;if(H){e:{for(U=1,P=H[0];P>=10;P/=10,U++);if(N=C-U,N<0)N+=Gt,D=C,O=H[Q=0],z=Rr(O/W[U-D-1]%10);else if(Q=kv((N+1)/Gt),Q>=H.length)if(M){for(;H.length<=Q;H.push(0));O=z=0,U=1,N%=Gt,D=N-Gt+1}else break e;else{for(O=P=H[Q],U=1;P>=10;P/=10,U++);N%=Gt,D=N-Gt+U,z=D<0?0:Rr(O/W[U-D-1]%10)}if(M=M||C<0||H[Q+1]!=null||(D<0?O:O%W[U-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?O/W[U-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(O/W[U-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,U,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=((U=I.length-1)-kr(this.e/Gt))*Gt,U=I[U])for(;U%10==0;U/=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,U,N,D,P,O,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(O=T.s<0,C){if(C.c?!C.c[0]:!C.s)return new b(NaN);M=!O&&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(O?1/N:N);A&&(N=kv(A/Gt+2))}for(P?(I=new b(.5),O&&(T.s=1),Q=am(T)):(U=Math.abs(+L(T)),Q=U%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(U){if(U=Rr(U/2),U===0)break;Q=U%2}else if(T=T.times(I),k(T,T.e+1,1),T.e>14)Q=am(T);else{if(U=+L(T),U===0)break;Q=U%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(C))}return M?z:(O&&(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,U,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 O=D.e/Gt,Q=T.e/Gt,z=D.c,H=T.c;if(!O||!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(O=kr(O),Q=kr(Q),z=z.slice(),P=O-Q){for((N=P<0)?(P=-P,U=z):(Q=O,U=H),U.reverse(),C=P;C--;U.push(0));U.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&&(U=z,z=H,H=U,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,U=this;return T=new b(T,C),!U.c||!T.s||T.c&&!T.c[0]?new b(NaN):!T.c||U.c&&!U.c[0]?new b(U):(m==9?(M=T.s,T.s=1,I=t(U,T,0,3),T.s=M,I.s*=M):I=t(U,T,0,m),T=U.minus(I.times(T)),!T.c[0]&&m==1&&(T.s=U.s),T)},s.multipliedBy=s.times=function(T,C){var I,M,U,N,D,P,O,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,O=oe.length,H=ge.length,O<H&&(J=oe,oe=ge,ge=J,U=O,O=H,H=U),U=O+H,J=[];U--;J.push(0));for(K=Xr,re=jo,U=H;--U>=0;){for(I=0,W=ge[U]%re,te=ge[U]/re|0,D=O,N=U+D;N>U;)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,U=M.s;if(T=new b(T,C),C=T.s,!U||!C)return new b(NaN);if(U!=C)return T.s=-C,M.minus(T);var N=M.e/Gt,D=T.e/Gt,P=M.c,O=T.c;if(!N||!D){if(!P||!O)return new b(U/0);if(!P[0]||!O[0])return O[0]?T:new b(P[0]?M:U*0)}if(N=kr(N),D=kr(D),P=P.slice(),U=N-D){for(U>0?(D=N,I=O):(U=-U,I=P),I.reverse();U--;I.push(0));I.reverse()}for(U=P.length,C=O.length,U-C<0&&(I=O,O=P,P=I,C=U),U=0;C;)U=(P[--C]=P[C]+O[C]+U)/Xr|0,P[C]=Xr===P[C]?0:P[C]%Xr;return U&&(P=[U].concat(P),++D),R(T,P,D)},s.precision=s.sd=function(T,C){var I,M,U,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(U=I.length-1,M=U*Gt+1,U=I[U]){for(;U%10==0;U/=10,M--);for(U=I[0];U>=10;U/=10,M++);}return T&&N.e+1>M&&(M=N.e+1),M},s.shiftedBy=function(T){return ri(T,-Nv,Nv),this.times("1e"+T)},s.squareRoot=s.sqrt=function(){var T,C,I,M,U,N=this,D=N.c,P=N.s,O=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+O)%2==0&&(C+="0"),P=Math.sqrt(+C),O=kr((O+1)/2)-(O<0||O%2),P==1/0?C="5e"+O:(C=P.toExponential(),C=C.slice(0,C.indexOf("e")+1)+O),I=new b(C)):I=new b(P+""),I.c[0]){for(O=I.e,P=O+Q,P<3&&(P=0);;)if(U=I,I=z.times(U.plus(t(N,U,Q,1))),Tr(U.c).slice(0,P)===(C=Tr(I.c)).slice(0,P))if(I.e<O&&--P,C=C.slice(P-3,P+1),C=="9999"||!M&&C=="4999"){if(!M&&(k(U,U.e+a+2,0),U.times(U).eq(N))){I=U;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,U=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=U.toFixed(T,C),U.c){var N,D=M.split("."),P=+I.groupSize,O=+I.secondaryGroupSize,Q=I.groupSeparator||"",z=D[0],H=D[1],W=U.s<0,te=W?z.slice(1):z,J=te.length;if(O&&(N=P,P=O,O=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);O>0&&(z+=Q+te.slice(N)),W&&(z="-"+z)}M=H?z+(I.decimalSeparator||"")+((O=+I.fractionGroupSize)?H.replace(new RegExp("\\d{"+O+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):H):z}return(I.prefix||"")+M+(I.suffix||"")},s.toFraction=function(T){var C,I,M,U,N,D,P,O,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=O=new b(r),W=Tr(J),N=C.e=W.length-te.e-1,C.c[0]=Pv[(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),O.c[0]=0;z=t(P,C,0,1),U=I.plus(z.times(M)),U.comparedTo(T)!=1;)I=M,M=U,Q=O.plus(z.times(U=Q)),O=U,C=P.minus(z.times(U=C)),P=U;return U=t(T.minus(I),M,0,1),O=O.plus(U.times(Q)),I=I.plus(U.times(M)),O.s=Q.s=te.s,N=N*2,H=t(Q,M,N,o).minus(te).abs().comparedTo(t(O,I,N,o).minus(te).abs())<1?[Q,M]:[O,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,U=I.e;return U===null?M?(C="Infinity",M<0&&(C="-"+C)):C="NaN":(T==null?C=U<=l||U>=c?om(Tr(I.c),U):io(Tr(I.c),U,"0"):T===10&&v?(I=k(new b(I),a+U+1,o),C=io(Tr(I.c),I.e,"0")):(ri(T,2,x.length,"Base"),C=n(io(Tr(I.c),U,"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=dR(),S4=class{key;left=null;right=null;constructor(e){this.key=e}},fd=class extends S4{constructor(e){super(e)}},I4=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 I4{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 T4(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new M4(this.wrap())}[Symbol.toStringTag]="[object Set]"},pR=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}},M4=class extends pR{getValue(e){return e.key}},T4=class extends pR{getValue(e){return[e.key,e.key]}},fR=e=>()=>e,hb=e=>{const t=e?(n,i)=>i.minus(n).abs().isLessThanOrEqualTo(e):fR(!1);return(n,i)=>t(n,i)?0:n.comparedTo(i)};function L4(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)):fR(!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 B4=e=>e,R4=e=>{if(e){const t=new I_(hb(e)),n=new I_(hb(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 B4},ub=e=>({set:t=>{Fo=ub(t)},reset:()=>ub(e),compare:hb(e),snap:R4(e),orient:L4(e)}),Fo=ub(),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),db=(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)),mR=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),M_=e=>mR(e,e).sqrt(),k4=(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))},N4=(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 mR(s,i).div(M_(s)).div(M_(i))},$S=(e,t,n)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(n.minus(e.y))),y:n},VS=(e,t,n)=>t.x.isZero()?null:{x:n,y:e.y.plus(t.y.div(t.x).times(n.minus(e.x)))},P4=(e,t,n,i)=>{if(t.x.isZero())return VS(n,i,e.x);if(i.x.isZero())return VS(e,t,n.x);if(t.y.isZero())return $S(n,i,e.y);if(i.y.isZero())return $S(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 gR{point;isLeft;segment;otherSE;consumedBy;static compare(t,n){const i=gR.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:k4(this.point,t.point,r.point),cosine:N4(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}}},D4=class pb{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 pb(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 pb(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}}},qS=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}},F4=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 qS(s));else{const r=s.enclosingRing();r?.poly||t.push(new qS(r)),r?.poly?.addInterior(s)}}return t}},O4=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}},U4=class{type;numMultiPolys;run(e,t,n){jd.type=e;const i=[new YS(t,!0)];for(let o=0,l=n.length;o<l;o++)i.push(new YS(n[o],!1));if(jd.numMultiPolys=i.length,jd.type==="difference"){const o=i[0];let l=1;for(;l<i.length;)db(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(db(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 O4(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 F4(D4.factory(r.segments)).getGeom()}},jd=new U4,Fp=jd,z4=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=++z4,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=db(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=P4(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}},WS=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}},Q4=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 WS(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 WS(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}},YS=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 Q4(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}},G4=(e,...t)=>Fp.run("union",e,t),H4=(e,...t)=>Fp.run("intersection",e,t),$4=(e,...t)=>Fp.run("difference",e,t);Fo.set;function _R(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=$4(t[0],...t.slice(1));return i.length===0?null:i.length===1?Hr(i[0],n):mA(i,n)}function V4(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,B2(q4(i,s),"meters",n.units)}function q4(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 AR(e,t,n,i={}){const s=t<0;let r=B2(Math.abs(t),i.units,"meters");s&&(r=-Math.abs(r));const a=Si(e),o=W4(a,r,n);return o[0]+=o[0]-a[0]>180?-360:a[0]-o[0]>180?360:0,wi(o,i.properties)}function W4(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 Y4(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=H4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function j4(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]=jS(a,t,i)}),e):jS(e,t,i)}function jS(e,t,n){const i=v_(e)==="Point",s=X4(e,n);return t===1||i||(Ql(e,function(r){const a=V4(s,r),o=_z(s,r),l=as(AR(s,a*t,o));r[0]=l[0],r[1]=l[1],r.length===3&&(r[2]*=t)}),delete e.bbox),e}function X4(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 W2(e);case void 0:case null:case"centroid":return Dp(e);default:throw new Error("invalid origin")}}function Z4(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 K4(e,t){for(var n=e[0],i=[n],s,r=1,a=e.length;r<a;r++)s=e[r],Z4(s,n)>t&&(i.push(s),n=s);return n!==s&&i.push(s),i}function fb(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&&fb(e,t,a,i,s),s.push(e[a]),n-a>1&&fb(e,a,n,i,s))}function eG(e,t){var n=e.length-1,i=[e[0]];return fb(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:K4(e,i),e=eG(e,i),e}function mb(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){tG(l,r,a)}),e}function tG(e,t,n){const i=e.type;if(i==="Point"||i==="MultiPoint")return e;if(G2(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=XS(e.coordinates,t,n);break;case"MultiPolygon":e.coordinates=e.coordinates.map(s=>XS(s,t,n))}return e}function XS(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(;!ZS(r)&&s>=Number.EPSILON;)s-=s*.01,r=L_(i,s,n);return ZS(r)?((r[r.length-1][0]!==r[0][0]||r[r.length-1][1]!==r[0][1])&&r.push(r[0]),r):i})}function ZS(e){return e.length<3?!1:!(e.length===3&&e[2][0]===e[0][0]&&e[2][1]===e[0][1])}function gb(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(AR(o,t,n,{units:s}));o[0]=l[0],o[1]=l[1],r&&o.length===3&&(o[2]+=r)}),e}function nG(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=G4(n[0],...n.slice(1));return i.length===0?null:i.length===1?Hr(i[0],t.properties):mA(i,t.properties)}function iG(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 LE;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=sG(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 sG(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 rG(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(!oG(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=iG(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:aG(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 KS(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 KS(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 LE;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,U=[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);){U.push(c[P].coord);for(var O=void 0,v=0;v<x.length;v++)if(x[v].isect==P){O=v;break}if(O!=null&&x.splice(O,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}}U.push(c[P].coord),k.push(Hr([U],{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}},KS=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 aG(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 oG(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 lG(e){var t=[];return Do(e,function(n){n.geometry.type==="Polygon"&&Po(rG(n),function(i){t.push(Hr(i.geometry.coordinates,n.properties))})}),Kt(t)}var cG=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())}},e1=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}},hG=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}},t1=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}},uG=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}},dG=["polygon","line","rectangle","circle","marker"],pG=["select","drag","change","rotate","cut","delete","scale","copy","split","union","difference","simplify","lasso"],Dv=["select","scale","copy","split","union","difference","simplify","lasso"],fG=["snapping","measurements"],mG=["open","save"],gG={position:"top-left",collapsed:!1,drawModes:dG,editModes:pG,helperModes:fG,fileModes:mG,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},Fv={tolerance:.001,highQuality:!1,mutate:!1},n1={offset:[5e-4,5e-4],generateNewIds:!0};function Oo(){return`feature_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function vR(e){return e.geometry.type==="Polygon"||e.geometry.type==="MultiPolygon"}function _G(e){return e.geometry.type==="LineString"||e.geometry.type==="MultiLineString"}function i1(e,t,n){return Math.min(Math.max(e,t),n)}function gd(e){return vz(e).length}var AG=class{options;constructor(e={}){this.options={offset:e.offset??n1.offset,generateNewIds:e.generateNewIds??n1.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?gb(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})),gb(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}},vG=class{defaultOptions;constructor(e){this.defaultOptions={tolerance:e?.tolerance??Fv.tolerance,highQuality:e?.highQuality??Fv.highQuality,mutate:e?.mutate??Fv.mutate}}simplify(e,t){return mb(e,{...this.defaultOptions,...t})}simplifyWithStats(e,t){const n={...this.defaultOptions,...t},i=gd(e),s=mb(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}},yG=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=nG(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($2(e[t],e[n])||DE(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}},bG=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=_R(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 $2(e,t)||yS(e,t)||DE(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=Y4(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 yS(e,t)?this.difference(e,[t]).result:(console.warn("Hole must be completely inside the polygon"),null)}catch{return null}}},xG=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=j4(e,i1(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=i1(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}},EG=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"?PQ(n,e):DE(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}},CG=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=RE(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=x4(t,1e-5,{units:"degrees"});if(!n)return[];const i=_R(Kt([e,n]));if(!i)return[];if(i.geometry.type==="MultiPolygon")return i.geometry.coordinates.map(r=>Hr(r));const s=lG(i);return s.features.length>1?s.features:[i]}catch{return[]}}clipLineToBbox(e,t){try{return wz(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}},wG=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=mb(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 G2(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(vR)}var _b=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={...gG,...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 AG,this.simplifyFeature=new vG({tolerance:this.options.simplifyTolerance}),this.unionFeature=new yG,this.differenceFeature=new bG,this.scaleFeature=new xG,this.lassoFeature=new EG,this.splitFeature=new CG,this.freehandFeature=new wG,this.options.enableHistory!==!1&&(this.historyManager=new cG(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-DI8MYlr0.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=R2(wi(t),wi(n)),r=[];this.multiDragOriginalFeatures.forEach((a,o)=>{const l=gb(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(),Dv.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(!vR(t)&&!_G(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=>!Dv.includes(r));if(n.length>0){const r=this.createToolGroup("Edit",n,"edit");t.appendChild(r)}const i=this.options.editModes.filter(r=>Dv.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 e1(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 hG(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 t1(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 t1(a,i));for(const a of t)s.push(new e1(a,i));const r=new uG(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}},Ov="geo-editor-features",yR=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",Ov))):!t&&this._hasFeatures&&(this._hasFeatures=!1,this._changeCallbacks.forEach(n=>n("remove",Ov))),t?[Ov]:[]}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=[]}},SG=Object.defineProperty,IG=(e,t,n)=>t in e?SG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oi=(e,t,n)=>IG(e,typeof t!="symbol"?t+"":t,n),MG="https://planetarycomputer.microsoft.com/api/stac/v1",TG=class{constructor(e=MG){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}}},LG="https://planetarycomputer.microsoft.com/api/data/v1",BG=class{constructor(e=LG){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("&")}},RG="https://planetarycomputer.microsoft.com/api/sas/v1/token",kG=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(`${RG}/${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)}},NG=[{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"}}],PG=[{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"}}],DG=[{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"}}],s1=[{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"}}],FG=[{collectionId:"sentinel-2-l2a",defaultPreset:"true-color",presets:NG},{collectionId:"landsat-c2-l2",defaultPreset:"true-color",presets:PG},{collectionId:"naip",defaultPreset:"rgb",presets:DG},{collectionId:"cop-dem-glo-30",defaultPreset:"elevation",presets:s1},{collectionId:"cop-dem-glo-90",defaultPreset:"elevation",presets:s1}];function bR(e){return FG.find(t=>t.collectionId===e)}function r1(e){const t=bR(e);return t?.presets??[]}function a1(e){const t=bR(e);if(t)return t.presets.find(n=>n.name===t.defaultPreset)}function o1(e=""){const t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return e?`${e}-${t}-${n}`:`${t}-${n}`}function l1(e){if(!e)return"Unknown";try{return new Date(e).toLocaleDateString()}catch{return e}}function c1(e){return e.datetime||e.start_datetime||e.end_datetime||null}function OG(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function UG(e){const[t,n,i,s]=e;return`${t.toFixed(2)}, ${n.toFixed(2)}, ${i.toFixed(2)}, ${s.toFixed(2)}`}var zG=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)}-${o1().slice(-6)}`,i=`${n}-source`,s=e.collection||"";let r=t?.renderParams||{},a=t?.presetName;if(!t?.renderParams&&!t?.assets&&s){const h=a1(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)}-${o1().slice(-6)}`,i=`${n}-source`;let s=t?.renderParams||{},r=t?.presetName;if(!t?.renderParams&&!t?.assets){const h=a1(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]]}},QG={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},Ab=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={...QG,...e},this._state=this._getInitialState(),this._stacClient=new TG(this._options.stacApiUrl),this._tilerClient=new BG(this._options.tilerApiUrl),this._sasManager=new kG}onAdd(e){return this._map=e,this._mapContainer=e.getContainer(),this._layerManager=new zG(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=`
276
276
  <span class="pc-control-icon">
277
277
  <svg viewBox="0 0 23 23" width="22" height="22">
278
278
  <rect x="1" y="1" width="10" height="10" fill="#666"/>