@tomtom-org/maps-sdk 0.61.0 → 0.62.0

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.
@@ -1,2 +1,2 @@
1
- import{clamp,clone,isEmpty,isEqual,isNil,isObject,isUndefined,mapValues,omit,omitBy,remove,setWith}from"lodash-es";import{DEFAULT_COMMON_BASE_URL,MILE_IN_METERS,TomTomConfig,areaAnalyticsMetricKeys,bboxCenter,bboxFromCoordsArray,bboxFromGeoJSON,formatDistance,formatDuration,fullTrafficIncidentCategories,generateId,generateTomTomHeaders,getPosition,iconToTrafficIncidentCategory,indexedMagnitudes,isProxyCredentialsMode,mergeFromGlobal,poiCategories,poiCategoriesToID,trafficIncidentToIconCategory}from"@tomtom-org/maps-sdk/core";import{clampRgb,differenceHueNaive,formatHex,formatHsl,interpolate,modeHsl,modeLrgb,modeRgb,parse,round,useMode,wcagLuminance}from"culori/fn";import{bearing,booleanPointInPolygon,difference,featureCollection,hexGrid,mask,squareGrid}from"@turf/turf";import{Map as Map$1,setWorkerCount}from"maplibre-gl";var CombinedEvents=class{constructor(e,t){this.userEventsInstance=e,this.moduleEventsInstance=t}where(e,t){return this.userEventsInstance.where(e,t)}on(e,t){return"config-change"===e?this.moduleEventsInstance.on("config-change",t):"shown-features"===e?this.moduleEventsInstance.on("shown-features",t):this.userEventsInstance.on(e,t)}off(e){"config-change"===e||"shown-features"===e?this.moduleEventsInstance.off(e):this.userEventsInstance.off(e)}},andPredicates=(e,t)=>e?t?(...i)=>e(...i)&&t(...i):e:t,combineEventScopes=(e,t)=>{if(!e)return t;if(!t)return e;const i=andPredicates(e.layerFilter,t.layerFilter),r=andPredicates(e.featureMatches,t.featureMatches);return i||r?{layerFilter:i,featureMatches:r}:void 0},scopedLayerSpecs=(e,t)=>t?.layerFilter?e._layerSpecs.filter(t.layerFilter):e._layerSpecs,reservedScopeNames=["on","off","where"],assertNoReservedScopeNames=(e,t)=>{const i=e.find(e=>reservedScopeNames.includes(e));if(i)throw new Error(`${t} uses the reserved event scope name "${i}". Reserved: ${reservedScopeNames.join(", ")}.`)},isExpressionFilter=e=>{if(!0===e||!1===e)return!0;if(!Array.isArray(e)||0===e.length)return!1;switch(e[0]){case"has":return e.length>=2&&"$id"!==e[1]&&"$type"!==e[1];case"in":return e.length>=3&&("string"!=typeof e[1]||Array.isArray(e[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==e.length||Array.isArray(e[1])||Array.isArray(e[2]);case"any":case"all":for(const t of e.slice(1))if(!isExpressionFilter(t)&&"boolean"!=typeof t)return!1;return!0;default:return!0}},propertyAccessor=e=>"$type"===e?["geometry-type"]:"$id"===e?["id"]:["get",e],convertHas=e=>"$type"===e||("$id"===e?["!=",["id"],null]:["has",e]),convertIn=(e,t)=>!!t.length&&["in",propertyAccessor(e),["literal",t]],convertLegacyFilter=e=>{const t=e[0];if(e.length<=1)return"any"!==t;const i=e[1],r=e.slice(2),o=e.slice(1);switch(t){case"has":return convertHas(i);case"!has":return["!",convertHas(i)];case"==":case"!=":return(null===r[0]?((e,t)=>{if("$id"!==t&&"$type"!==t)return"=="===e?["all",["has",t],["==",["get",t],null]]:["any",["!",["has",t]],["!=",["get",t],null]]})(t,i):void 0)??[t,propertyAccessor(i),r[0]];case">":case">=":case"<":case"<=":return((e,t,i)=>["all",["==",["typeof",propertyAccessor(t)],typeof i],[e,propertyAccessor(t),i]])(t,i,r[0]);case"in":return convertIn(i,r);case"!in":return["!",convertIn(i,r)];case"all":return["all",...o.map(e=>toExpressionFilter(e))];case"any":return["any",...o.map(e=>toExpressionFilter(e))];case"none":return["!",["any",...o.map(e=>toExpressionFilter(e))]];default:return!0}},toExpressionFilter=e=>isExpressionFilter(e)?e:convertLegacyFilter(e),getMergedAnyFilter=e=>e?.length?1===e.length?e[0]:["any",...e]:null,isCompleteValuesFilter=e=>void 0!==e?.show&&void 0!==e.values,buildMappedValuesFilter=(e,t,i)=>{if(1===i.length)return["only"===t?"==":"!=",["get",e],i[0]];const r=["in",["get",e],["literal",i]];return"only"===t?r:["!",r]},buildValuesFilter=(e,t,i)=>buildMappedValuesFilter(e,t.show,i?t.values.map(i):t.values),AbstractLayerComposer=class{constructor(e){this.byLayer=/* @__PURE__ */new Map,this.mapLibreMap=e.mapLibreMap,e.addStyleChangeHandler({onStyleAboutToChange:()=>this.byLayer.clear(),priority:Number.NEGATIVE_INFINITY})}},setOrDelete=(e,t,i)=>{void 0!==i?e.set(t,i):e.delete(t)},composerOfMap=(e,t,i)=>{let r=e.get(t);return r||(r=i(),e.set(t,r)),r},composersByMap$1=/* @__PURE__ */new WeakMap,LayerFilterComposer=class e extends AbstractLayerComposer{constructor(e){super(e)}static for(t){return composerOfMap(composersByMap$1,t,()=>new e(t))}setTransform(e,t,i){this.contribute(e,({transforms:e})=>setOrDelete(e,t,i))}setClause(e,t,i){this.contribute(e,({clauses:e})=>setOrDelete(e,t,i))}contribute(e,t){if(!this.mapLibreMap.getLayer(e))return;let i=this.byLayer.get(e);i||(i={styleFilter:this.mapLibreMap.getFilter(e),transforms:/* @__PURE__ */new Map,clauses:/* @__PURE__ */new Map},this.byLayer.set(e,i)),t(i),this.apply(e,i)}apply(e,t){const i=[...t.transforms.values()].reduce((e,t)=>t(e),t.styleFilter),r=((e,t)=>{if(!t.length)return e;const i=null==e?t:[...t,toExpressionFilter(e)];return 1===i.length?i[0]:["all",...i]})(i,[...t.clauses.values()]);this.mapLibreMap.setFilter(e,r??null,{validate:!1})}},ModuleEvents=class{constructor(e,t){this.configChangeHandlers=e,this.shownFeaturesHandlers=t}on(e,t){if("config-change"===e){const e=t;return this.configChangeHandlers.push(e),()=>{const t=this.configChangeHandlers.indexOf(e);-1!==t&&this.configChangeHandlers.splice(t,1)}}const i=t;return this.shownFeaturesHandlers.push(i),()=>{const e=this.shownFeaturesHandlers.indexOf(i);-1!==e&&this.shownFeaturesHandlers.splice(e,1)}}off(e){"config-change"===e?this.configChangeHandlers.length=0:this.shownFeaturesHandlers.length=0}},notInTheStyle=e=>/* @__PURE__ */new Error(`Trying to ${e} while it is not in the map style. Did you exclude it when loading the map?`),standardStyleIDs=["standardLight","standardDark","drivingLight","drivingDark","monoLight","monoDark","satellite"],styleModules=["trafficIncidents","trafficFlow","hillshade"],standardStyleModulesValues={standardLight:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",hillshade:"hillshade_light"},standardDark:{trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",hillshade:"hillshade_dark"},drivingLight:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",hillshade:"hillshade_light"},drivingDark:{trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",hillshade:"hillshade_dark"},monoLight:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",hillshade:"hillshade_mono-light"},monoDark:{trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",hillshade:"hillshade_mono-dark"},satellite:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",hillshade:"hillshade_satellite"}},mapSuffixes={standardLight:"basic_street-light",standardDark:"basic_street-dark",drivingLight:"basic_street-light-driving",drivingDark:"basic_street-dark-driving",monoLight:"basic_mono-light",monoDark:"basic_mono-dark",satellite:"basic_street-satellite"},buildStandardStyleUrl=(e,t,i)=>{const r=e.id??"standardLight",o=new URL(`${t}/maps/orbis/assets/styles/0.6.0-0/style.json`);o.searchParams.set("apiVersion","1"),i&&o.searchParams.set("key",i),o.searchParams.set("map",mapSuffixes[r]);for(const s of e.include??styleModules)o.searchParams.append(s,standardStyleModulesValues[r][s]);return o.toString()},buildStyleInput=e=>{const t=e.style,i=e.commonBaseURL,r=e.apiKey;if("string"==typeof t)return buildStandardStyleUrl({id:t},i,r);if("standard"===t?.type)return buildStandardStyleUrl(t,i,r);if("custom"===t?.type){if(void 0!==t.url)return((e,t)=>{const i=new URL(e);return i.searchParams.has("key")?console.warn("The style URL is coming with an API key parameter which takes priority. If you want to use the SDK configured API key, remove the key param from the style URL"):t&&i.searchParams.set("key",t),i.toString()})(t.url,r);if(void 0===t.json)/* @__PURE__ */throw new Error("A custom map style takes exactly one of 'url' or 'json', and this one carries neither. Give the URL the style is served from, or the style specification itself.");return t.json}return buildStandardStyleUrl({id:"standardLight"},i,r)},isLegacyFunction=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&Array.isArray(e.stops),scaleNumericValue=(e,t)=>"number"==typeof e?(e=>Math.round(1e3*e)/1e3)(e*t):isLegacyFunction(e)?scaleLegacyStops(e,t):Array.isArray(e)?"interpolate"===e[0]||"step"===e[0]?scaleRampOutputs(e,t):(e=>JSON.stringify(e).includes('"zoom"'))(e)?void 0:["*",t,e]:void 0,scaleLegacyStops=(e,t)=>{const i=[];for(const[r,o]of e.stops){const e=scaleNumericValue(o,t);if(void 0===e)return;i.push([r,e])}return{...e,stops:i}},scaleRampOutputs=(e,t)=>{const i=[...e];for(let r="interpolate"===e[0]?4:2;r<i.length;r+=2){const e=scaleNumericValue(i[r],t);if(void 0===e)return;i[r]=e}return i},shiftZoomOffset=(e,t)=>{let i=!1;const r=e=>Array.isArray(e)?"-"===e[0]&&3===e.length&&Array.isArray(e[1])&&"zoom"===e[1][0]&&"number"==typeof e[2]?(i=!0,["-",["zoom"],e[2]+t]):e.map(r):e;return{filter:r(e),patched:i}},toRgb=useMode(modeRgb),toHslSpace=useMode(modeHsl);useMode(modeLrgb);var toHundredths=round(2),BLACK={mode:"rgb",r:0,g:0,b:0},WHITE={mode:"rgb",r:1,g:1,b:1},STYLE_COLOR_SYNTAX=/^(#|rgba?\(|hsla?\(|[a-z]+$)/,parseColor=e=>{const t=e.trim().toLowerCase(),i=STYLE_COLOR_SYNTAX.test(t)?parse(t):void 0;return i&&clampRgb(i)},parseCssColor=e=>{const t=parseColor(e);if(!t)return;const{r:i,g:r,b:o,alpha:s=1}=toRgb(t);return[i,r,o,s]},toHsl=e=>{const t=parseColor(e);return t&&toHslSpace(toRgb(t))},isColorLiteral=e=>"string"==typeof e&&void 0!==parseColor(e),formatStyleHsl=e=>formatHsl(roundStyleHsl(e)),roundStyleHsl=({h:e=0,s:t,l:i,alpha:r})=>({mode:"hsl",h:(Math.round(e)%360+360)%360,s:toHundredths(t),l:toHundredths(i),alpha:r}),clampUnit=e=>Math.min(Math.max(e,0),1),hslShiftBetween=(e,t)=>{const i=toHsl(e),r=toHsl(t);if(i&&r)return{h:i.s<.01||r.s<.01?0:(r.h??0)-(i.h??0),s:r.s-i.s,l:r.l-i.l,alpha:(r.alpha??1)-(i.alpha??1)}},shiftHsl=(e,t)=>{const i=toHsl(e);if(i)return formatStyleHsl({h:(i.h??0)+t.h,s:void 0===i.h?i.s:i.s+t.s,l:i.l+t.l,alpha:clampUnit((i.alpha??1)+t.alpha)})},relativeLuminance=e=>{const t=parseColor(e);return t&&wcagLuminance(t)},darkenColor=(e,t)=>{const i=parseColor(e);return i&&formatHex(interpolate([i,BLACK])(t))},darkerShadeOf=e=>darkenColor(e,.4),hueDistance=({h:e},{h:t})=>void 0===e||void 0===t?0:Math.abs(differenceHueNaive({h:e},{h:t})),paintedBy={fill:["fill-color","fill-outline-color"],line:["line-color"],"fill-extrusion":["fill-extrusion-color"]},paintLayers=e=>t=>({layers:[{...t,layerTypes:[e]}],properties:[...paintedBy[e]]}),fillLayers=paintLayers("fill"),lineLayers=paintLayers("line"),extrusionLayers=paintLayers("fill-extrusion"),roadLine=(e,t)=>({metadataGroups:["road"],layerTypes:["line"],idIncludes:e,...t&&{idExcludes:t}}),MIXED_CLASS_ROAD_LINES=roadLine(["road line","road outline","under construction","link road"],["tarmac"]),MAJOR_ROAD_LINES=roadLine(["motorway","primary road","major road"]),MINOR_ROAD_LINES=roadLine(["secondary road","tertiary road","street","minor road","restricted","service road"],["outline"]),MINOR_ROAD_OUTLINES=roadLine(["secondary road outline","tertiary road outline","street outline","minor road outline","tarmac outline"]),RAIL_AND_PATH_LINES=roadLine(["railway","subway","track","path","aerialway"]),TEXT_LAYERS={metadataGroups:["places_label","road_label","label","address_point_label","border_label"],layerTypes:["symbol"],idExcludes:["shield","exit","water","river"]},mapColorDefinitions={land:{description:"Map background and other bare-land features, influences admin borders/labels. Also used to derive all map colours if undefined.",anchor:{layers:[{layerTypes:["background"]}],property:"background-color"},targets:[{layers:[{layerTypes:["background"]}],properties:["background-color"]},fillLayers({metadataGroups:["area"],idIncludes:["earth cover","landcover"]}),fillLayers({metadataGroups:["road_area"]}),fillLayers({metadataGroups:["transit_area"]}),lineLayers({metadataGroups:["transit_area"]})]},water:{description:"Waterbodies, waterways and other water features. Also influences glaciers, water labels and ferry lines.",anchor:{layers:[{metadataGroups:["water"],layerTypes:["fill"],idIncludes:["fill"]}],property:"fill-color"},targets:[fillLayers({metadataGroups:["water"]}),lineLayers({metadataGroups:["water"]}),{layers:[{metadataGroups:["label"],layerTypes:["symbol"],idIncludes:["water","river"]}],properties:["text-color","text-halo-color"]},lineLayers({metadataGroups:["road"],idIncludes:["ferry"]})]},vegetation:{description:"Forests and other land cover such as grass and shrubland. Also influences earth cover vegetation at smaller scales.",anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["landcover"]}],property:"fill-color"},targets:[fillLayers({metadataGroups:["area"],idIncludes:["landcover","earth cover"]})]},park:{description:"City parks and sport/recreation grounds. Also influences National Parks and other protected areas at smaller scales.",anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["protected"]}],property:"fill-color"},targets:[fillLayers({metadataGroups:["area"],idIncludes:["protected","outdoor","sport","landuse"]}),lineLayers({metadataGroups:["border"],idIncludes:["overlays"]})]},artificial:{description:"Built-up-areas and man-made features such as landuse grounds and buildings. Also influences railways.",anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["built-up"]}],property:"fill-color",lastStop:!0},targets:[...[fillLayers({metadataGroups:["area"],idIncludes:["built-up","landuse","parking"]}),fillLayers({metadataGroups:["building"]}),lineLayers({metadataGroups:["building"]}),extrusionLayers({metadataGroups:["area_3d","building"]})].map(e=>({...e,recolorsTints:!0})),fillLayers({metadataGroups:["transit_area","road_area"]}),lineLayers({metadataGroups:["transit_area"]}),lineLayers(RAIL_AND_PATH_LINES)]},roadMajor:{description:"Most important road classes, from motorways & trunks to primary roads. Also influences outline and tunnel colours.",anchor:{layers:[roadLine(["motorway & trunk"],["outline"])],property:"line-color",roadClass:"major"},targets:[lineLayers(MAJOR_ROAD_LINES),{layers:[MIXED_CLASS_ROAD_LINES],properties:["line-color"],roadClass:"major"}]},road:{description:"Less important road classes, from secondary/tertiary to streets and service roads. Also influences tunnel colours.",anchor:{layers:[roadLine(["secondary road"],["outline"])],property:"line-color"},targets:[lineLayers(MINOR_ROAD_LINES),{layers:[roadLine(["road line","under construction","link road"],["outline"])],properties:["line-color"],roadClass:"minor"}]},roadOutline:{description:"Road outlines for secondary/tertiary roads and minor classes. Also influences road labels and all other outline colours.",anchor:{layers:[roadLine(["secondary road outline"])],property:"line-color"},targets:[lineLayers(MINOR_ROAD_OUTLINES),{layers:[roadLine(["road outline","link road outline"],["tarmac"])],properties:["line-color"],roadClass:"minor"}]},label:{description:"Labels for capitals and other populated places/admin areas. Also influences border styling and all other label colours.",anchor:{layers:[{metadataGroups:["places_label"],layerTypes:["symbol"],idIncludes:["capital"]}],property:"text-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-color"]},lineLayers({metadataGroups:["border"],idIncludes:["country","state","treaty","disputed"]})]},labelOutline:{description:"Outlines for populated places and admin area labels. Also influences border outlines and all other label halos.",anchor:{layers:[{metadataGroups:["places_label"],layerTypes:["symbol"],idIncludes:["capital"]}],property:"text-halo-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-halo-color"]},lineLayers({metadataGroups:["border"],idIncludes:["background"]})]}},baseMapColorNames=Object.keys(mapColorDefinitions),mapColorNames=[...baseMapColorNames,"accent"],mapColorNameSet=new Set(mapColorNames),isMapColorName=e=>mapColorNameSet.has(e),allButLand=baseMapColorNames.filter(e=>"land"!==e),landDerivedMapColors={monoLight:allButLand,monoDark:allButLand},mapColorDerivationInputs=e=>"roadMajor"===e||"roadOutline"===e?["land","road"]:["land"],themeLuminance=e=>{const t=relativeLuminance(e);return void 0===t?void 0:toHundredths(t)},withLightness=(e,t)=>({...e,l:clampUnit(t)}),lighten=(e,t)=>roundStyleHsl(withLightness(t,t.l*(1+e))),darken=(e,t)=>lighten(-e,t),desaturate=(e,t)=>roundStyleHsl({...t,s:clampUnit(t.s*(1-e))}),lightenBy=(e,t)=>withLightness(t,t.l+e/100),darkenBy=(e,t)=>lightenBy(-e,t),sign=e=>e?1:-1,withDerivedMapColors=(e,t,i)=>{const r=e.land??i,o=t.filter(t=>void 0===e[t]&&mapColorDerivationInputs(t).some(t=>void 0!==e[t])),s=r&&o.length?((e,t)=>{const i=toHsl(e),r=themeLuminance(e);if(!i||void 0===r)return;const o=sign(r<=.95),s=sign(r>.3),a=lightenBy(15*o,lighten(Math.max(r/5,.1),i)),n=t&&toHsl(t)||a;return{water:formatStyleHsl(darkenBy(10*sign(r>.01),darken(Math.max(r/20,.05),i))),vegetation:formatStyleHsl(darken(.05,darkenBy(2,i))),park:formatStyleHsl(darken(.03,darkenBy(1,i))),artificial:formatStyleHsl(darkenBy(4*sign(r>.05),lighten(Math.max(r/15,.02),i))),road:formatStyleHsl(a),roadMajor:formatStyleHsl(n),roadOutline:formatStyleHsl(darkenBy(20*o,n)),label:formatStyleHsl(desaturate(.3,darkenBy(60*s,lighten(Math.max(r/5,.1),i)))),labelOutline:formatStyleHsl(lightenBy(75*s,i))}})(r,e.road):void 0;return s?{...Object.fromEntries(o.map(e=>[e,s[e]])),...e}:e},MAJOR_ROAD_CLASSES=/* @__PURE__ */new Set(["motorway","trunk","primary"]),roadClassOfKeys=e=>(Array.isArray(e)?e:[e]).some(e=>"string"==typeof e&&MAJOR_ROAD_CLASSES.has(e.replace(/_link$/,"")))?"major":"minor",TOP_LEVEL_CONTEXT={roadClass:void 0,keyed:!1},mapColorLiterals=(e,t,i=TOP_LEVEL_CONTEXT)=>{if((e=>{const t="string"==typeof e?parseColor(e):void 0;return void 0!==t&&(t.alpha??1)>0})(e))return t(e,i);if(Array.isArray(e)){if("match"===e[0]){const o="match"===(r=e)[0]&&Array.isArray(r[1])&&"get"===r[1][0]&&("category"===r[1][1]||"road_category"===r[1][1]),s=[e[0],e[1]];for(let r=2;r<e.length-1;r+=2){const a=o?roadClassOfKeys(e[r]):i.roadClass;s.push(e[r],mapColorLiterals(e[r+1],t,{roadClass:a,keyed:!0}))}const a=o?"minor":i.roadClass;return s.push(mapColorLiterals(e.at(-1),t,{...i,roadClass:a})),s}return e.map(e=>mapColorLiterals(e,t,i))}var r;return isLegacyFunction(e)?{...e,stops:e.stops.map(([e,r])=>[e,mapColorLiterals(r,t,i)])}:e},collectColorLiterals=e=>{const t=[];return mapColorLiterals(e,(e,i)=>(t.push({literal:e,...i}),e)),t},tintSaturationScale=e=>{const t=themeLuminance(e);return void 0===t?void 0:Math.max(t,.33)},shadeShift=(e,t,i)=>{const[r,o,s]=[e,t,i].map(toHsl);if(!r||!o||!s)return;const a=r.s<.08||o.s<.08;if(!a&&hueDistance(r,o)>40)return;const n=hslShiftBetween(e,t),l=s.alpha??1;return n&&{...n,h:a?0:n.h,alpha:(o.alpha??1)*l-l}},recolorValue=(e,t)=>{const i=[...t].reverse();return mapColorLiterals(e,(e,{roadClass:t})=>{const r=i.filter(({owns:e})=>!e||e(t));for(const{anchorColor:i,newColor:s}of r){const t=shadeShift(i,e,s);if(t)return shiftHsl(s,t)??e}const o=r.find(e=>e.recolorsTints);return o?((e,t,i)=>{const[r,o,s]=[e,t,i].map(toHsl),[a,n]=[e,i].map(tintSaturationScale);if(!(r&&o&&s&&a&&n))return;const l=o.s*n/a,c=(o.alpha??1)*(s.alpha??1);return formatStyleHsl({h:o.h,s:l,l:s.l+o.l-r.l,alpha:c})})(o.anchorColor,e,o.newColor)??e:e})},FLOW_TAGS=["road_category","road_subcategory","relative_speed","left_hand_traffic","road_closure","absolute_speed","part_of_two_way_road","openlr","display_class"],trafficFlowMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:e.geometry,properties:{roadCategory:t?.road_category,leftHandTraffic:Boolean(t?.left_hand_traffic),roadClosure:Boolean(t?.road_closure),relativeSpeed:t?.relative_speed,...t?.road_subcategory&&{roadSubcategory:t.road_subcategory},...t?.absolute_speed&&{absoluteSpeed:t.absolute_speed},...t?.part_of_two_way_road&&{partOfTwoWayRoad:Boolean(t.part_of_two_way_road)},...t?.openlr&&{openlr:t.openlr},...t?.display_class&&{displayClass:t.display_class}}}},INCIDENT_TAGS=["icon_category","left_hand_traffic","magnitude_of_delay","road_category","road_subcategory","id","description","delay","part_of_two_way_road","start_time","end_time","probability_of_occurrence","number_of_reports","last_report_time","average_speed_kmph","openlr","time_validity","display_class"],trafficIncidentMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:e.geometry,properties:{id:t.id??generateId(),description:t?.description_0??"",category:iconToTrafficIncidentCategory(t?.icon_category_0),magnitudeOfDelay:indexedMagnitudes[t?.magnitude_of_delay],roadCategory:t?.road_category,roadSubcategory:t?.road_subcategory,leftHandTraffic:Boolean(t?.left_hand_traffic),...t?.delay&&{delayInSeconds:t.delay},...t?.part_of_two_way_road&&{partOfTwoWayRoad:Boolean(t.part_of_two_way_road)},...t?.start_time&&{startTime:new Date(t.start_time)},...t?.end_time&&{endTime:new Date(t.end_time)},...t?.probability_of_occurrence&&{probabilityOfOccurrence:t.probability_of_occurrence},...t?.number_of_reports&&{numberOfReports:t.number_of_reports},...t?.last_report_time&&{lastReportTime:new Date(t.last_report_time)},...t?.average_speed_kmph&&{averageSpeedKmph:t.average_speed_kmph},...t?.openlr&&{openlr:t.openlr},...t?.time_validity&&{timeValidity:t.time_validity},...t?.display_class&&{displayClass:t.display_class},...t?.point_type&&{pointType:t.point_type}}}},toPinSpriteImageID=e=>`pinCategories:${e}`,isDOMImageSupported=()=>"undefined"!=typeof document&&"undefined"!=typeof DOMParser&&"undefined"!=typeof btoa,svgToImg=e=>{if(!isDOMImageSupported())return;const t=document.createElement("img");return t.src=`data:image/svg+xml;base64,${btoa((new XMLSerializer).serializeToString(e))}`,t},parseSvg=e=>(new DOMParser).parseFromString(e,"image/svg+xml").documentElement,pinSvg=e=>((e,t)=>(t?.fillColor&&e.querySelector("#background")?.setAttribute("fill",t.fillColor),t?.outlineColor&&e.querySelector("#outline")?.setAttribute("fill",t.outlineColor),void 0!==t?.outlineOpacity&&e.querySelector("#outline")?.setAttribute("fill-opacity",t.outlineOpacity.toString()),e))(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140">\n <path id="background" d="M63.95 137.516c6.556-12.737 19.098-21.09 30.828-29.388C110.046 97.324 120 79.603 120 59.574 120 26.671 93.138 0 60 0S0 26.671 0 59.574c0 20.029 9.954 37.75 25.22 48.55 11.734 8.302 24.274 16.652 30.83 29.388 1.706 3.316 6.194 3.316 7.9 0z"\n fill="#1988cf"/>\n <path id="outline" d="M91.298 103.272C105.052 93.544 114 77.596 114 59.574c0-29.61-24.176-53.617-54-53.617S6 29.964 6 59.574c0 18.022 8.95 33.97 22.7 43.698l2.27 1.601c10.172 7.153 21.922 15.423 29.03 27.416 7.104-11.993 18.858-20.259 29.03-27.416l2.268-1.601zm1.468 6.274c-11.13 7.845-22.632 15.957-28.816 27.966-1.706 3.316-6.194 3.316-7.9 0-6.182-12.009-17.686-20.121-28.816-27.966l-2.016-1.422C9.954 97.324 0 79.603 0 59.574 0 26.671 26.862 0 60 0s60 26.671 60 59.574c0 20.029-9.954 37.75-25.222 48.55l-2.016 1.422z"\n fill-opacity=".3"/>\n</svg>\n'),e),waitUntilMapIsReady=async e=>{e.mapReady||(await e.mapLibreMap.once("styledata"),await waitUntilMapIsReady(e))},VECTOR_TILE_VIEW_PARAMETERS=[[/\/maps\/orbis\/map-display\/tile\/[^/]+\/[^/]+\/[^/]+\.pbf$/,"view"],[/\/maps\/orbis\/display\/vector\/tile\/[^/]+\/[^/]+\/[^/]+$/,"geopoliticalView"]],vectorTileViewParameter=e=>VECTOR_TILE_VIEW_PARAMETERS.find(([t])=>t.test(e.pathname))?.[1],isVectorTileUrl=e=>{try{return void 0!==vectorTileViewParameter(new URL(e))}catch{return!1}},reloadVectorTiles=e=>{for(const t of(e=>Object.entries(e.getStyle()?.sources??{}).filter(([,e])=>"vector"===e.type&&e.tiles?.some(isVectorTileUrl)).map(([e])=>e))(e)){const i=e.style.tileManagers[t];for(const e of i?.getIds()??[]){const t=i.getTileByID(e);t&&(t.etag=void 0)}e.refreshTiles(t)}},gateOnDemosProxySession=e=>{const t=globalThis.__DEMOS_PROXY_ENSURE_SESSION__;return"function"!=typeof t?e:t().then(()=>e,()=>e)},transformRequest=e=>{const t=e.commonBaseURL??DEFAULT_COMMON_BASE_URL,i=t!==DEFAULT_COMMON_BASE_URL,r=isProxyCredentialsMode(e);return(o,s)=>{const a=((e,t,i,r)=>{if(!i)return e;try{const i=new URL(e);return"api.tomtom.com"===(o=i.hostname)||o.endsWith(".api.tomtom.com")?(r&&i.searchParams.delete("key"),t+i.pathname+i.search+i.hash):e}catch{return e}var o})(o,t,i,r),n=i&&a.startsWith(t),l=r&&n;let c=!1;try{const e=new URL(o).hostname;c="tomtom.com"===e||e.endsWith(".tomtom.com")}catch{c=!1}if(!c&&!n)return{url:a};if("Image"===s)return l?gateOnDemosProxySession({url:a,credentials:"include"}):{url:a};const d=new URL(a);(e=>{e.pathname.includes("incidents")?e.searchParams.set("tags",INCIDENT_TAGS.join(",")):e.pathname.includes("flow")&&e.searchParams.set("tags",FLOW_TAGS.join(","))})(d),((e,t)=>{const i=vectorTileViewParameter(e),r=t&&(e=>"AE"===e?"Arabic":"CN"===e||"RU"===e?void 0:e)(t);i&&r&&e.searchParams.set(i,r)})(d,e.geopoliticalView);const p={url:d.toString(),headers:{...generateTomTomHeaders(e)}};return l?(p.credentials="include",gateOnDemosProxySession(p)):p}},changeLayerProps=(e,t,i)=>{const r=e.id;e.maxzoom===t.maxzoom&&e.minzoom===t.minzoom||i.setLayerZoomRange(r,e.minzoom??i.getMinZoom(),e.maxzoom??i.getMaxZoom()),i.setFilter(r,e.filter,{validate:!1});for(const o of Object.keys(t.layout??{}))e.layout?.[o]||i.setLayoutProperty(r,o,void 0,{validate:!1});for(const o of Object.keys(t.paint??{}))e.paint?.[o]||i.setPaintProperty(r,o,void 0,{validate:!1});for(const[o,s]of Object.entries(e.paint??{}))i.setPaintProperty(r,o,s,{validate:!1});for(const[o,s]of Object.entries(e.layout??{}))i.setLayoutProperty(r,o,s,{validate:!1})},updateLayersAndSource=(e,t,i,r)=>{const o=e.reduce((e,t)=>({...e,[t.id]:t}),{}),s=t.reduce((e,t)=>({...e,[t.id]:t}),{}),a=[],n=[],l=[],c=[];Object.keys(o).forEach(e=>{s[e]?(l.push(o[e]),c.push(s[e])):a.push(e)}),Object.keys(s).forEach(e=>{o[e]||n.push(e)});const d=i._layerSpecs;n.forEach(e=>{r.removeLayer(e);for(let t=0;t<d.length;t++)if(d[t].id===e){d.splice(t,1);break}});const p=a.map(e=>({...o[e],source:i.source.id}));p.length&&(d.push(...p),addLayers(p,r)),i._updateSourceAndLayerIDs(),((e,t,i,r)=>{const o=/* @__PURE__ */new Set,s=e=>{if(!r.getLayer(e.id))return;moveLayerBefore(r,e.id,e.beforeID),o.add(e.id);const t=i.find(t=>t.id===e.id);t&&(t.beforeID=e.beforeID)};e.forEach((e,i)=>{e.beforeID!==t[i].beforeID&&s(e)});const a=()=>e.filter(e=>!o.has(e.id)&&void 0!==e.beforeID&&o.has(e.beforeID));for(let n=a();n.length;n=a())n.forEach(s)})(l,c,d,r),((e,t,i)=>{e.forEach((e,r)=>changeLayerProps(e,t[r],i))})(l,c,r)},existingBeforeLayerID=(e,t)=>t&&e.getLayer(t)?t:void 0,moveLayerBefore=(e,t,i)=>{e.moveLayer(t,existingBeforeLayerID(e,i))},applyLayersVisibility=(e,t,i)=>{if(i._removed)return;const r=t?"visible":"none";for(const o of e)"none"!==o.layout?.visibility&&i.getLayer(o.id)&&i.setLayoutProperty(o.id,"visibility",r,{validate:!1})},addLayers=(e,t,i=!1)=>{const r=/* @__PURE__ */new Set,o=e=>{t.getLayer(e.id)?i&&t.moveLayer(e.id,e.beforeID):t.addLayer({...e,layout:{...e.layout,visibility:"none"}},e.beforeID),r.add(e.id)},s={},a=new Set(i?e.map(e=>e.id):[]);for(e.forEach(e=>{var i;e.beforeID?(i=e.beforeID,r.has(i)||!a.has(i)&&t.getLayer(i)?(r.add(e.beforeID),o(e)):s[e.beforeID]?s[e.beforeID].push(e):s[e.beforeID]=[e]):o(e)});Object.keys(s).length>0;){const e=Object.keys(s).filter(e=>r.has(e));if(!e.length)return void console.error(`Some layers cannot be added. Check for non-existing layers, or circular beforeID dependencies for the following: ${JSON.stringify(Object.keys(s))}`);e.forEach(e=>{s[e].forEach(e=>o(e)),delete s[e]})}},updateStyleWithModule=(e,t)=>{switch(typeof e){case"undefined":return{type:"standard",include:[t]};case"string":return{type:"standard",id:e,include:[t]};default:if("standard"===e.type)return e.include?{...e,include:[...e.include,t]}:{...e,include:[t]};throw(e=>/* @__PURE__ */new Error(`The custom map style has no '${e}' part and the SDK cannot add one to it. Style-owned modules work on a custom style only when it already ships the matching source (e.g. built with that part enabled) — or switch to a standard style.`))(t)}},ensureAddedToStyle=async(e,t,i)=>{if(!e.mapLibreMap.getSource(t)){const r=e.mapLibreMap;r.isStyleLoaded()||await r.once("idle"),await e.setStyle(updateStyleWithModule(e.getStyle(),i)),await(async(e,t)=>{e.mapLibreMap.getSource(t)&&e.mapLibreMap.isSourceLoaded(t)||await e.mapLibreMap.once("sourcedata")})(e,t)}},addOrUpdateImage=async(e,t,i,r,o)=>{if(!i)return void console.warn(`addOrUpdateImage called with empty image for ID ${t}`);const s=i=>{const s=r.hasImage(t);s&&"add-or-update"==e?r.updateImage(t,i):s||r.addImage(t,i,o)},a=e=>{e.complete?e.naturalWidth>0?s(e):console.warn(`Failed to load image for ID ${t}`):(e.onload=()=>s(e),e.onerror=()=>console.warn(`Failed to load image for ID ${t}`))};if("string"==typeof i)if(i.includes("<svg"))a(svgToImg(parseSvg(i)));else try{s((await r.loadImage(i)).data)}catch(n){console.warn(`Failed to load image for ID ${t}`,n)}else a(i)},getStyleLightDarkTheme=e=>{const t=getDeclaredLightDarkTheme(e);if(t)return t;const i=standardStyleIdOf(e);return i?(e=>{switch(e){case"standardDark":case"drivingDark":case"monoDark":case"satellite":return"dark";default:return"light"}})(i):"light"},standardStyleIdOf=e=>"string"==typeof e?e:"standard"===e?.type?e.id??"standardLight":void 0,getDeclaredLightDarkTheme=e=>isCustomStyle(e)?e.lightDarkTheme:void 0,isCustomStyle=e=>"object"==typeof e&&"custom"===e?.type,UserEvents=class e{constructor(e){this.options=e,this.sources=e.sourcesWithLayers}where(t,i){return new e({...this.options,config:i??this.options.config,scope:combineEventScopes(this.options.scope,this.resolveScope(t))})}resolveScope(e){if("function"==typeof e){const t=e,i=this.options.mapping;return{featureMatches:i?e=>t(i(e)):e=>t(e)}}const t=this.options.scopeResolver;if(!t)throw new Error("This module supports only feature predicates in events.where().");return t(e)}on(e,t){const{eventProxy:i,config:r,owner:o,scope:s}=this.options,a=this.toRegisteredHandler(t),n=[];for(const l of this.sources)i.addEventHandler(l,a,e,{config:r,owner:o,scope:s}),n.push(l);return()=>{for(const t of n)i.removeHandler(t,e,a)}}toRegisteredHandler(e){const{mapping:t,scope:i}=this.options,r=i?.featureMatches;if(!t&&!r)return e;const o=e=>t?t(e):e;return r?(t,i,s,a)=>{const n=(s.length?s:[t]).filter(e=>r(e));if(!n.length)return;const l=n.map(o);e(l[0],i,l,a)}:(t,i,r,s)=>e(o(t),i,r.map(o),s)}off(e){for(const t of this.sources)this.options.eventProxy.remove(t,e,this.options.owner)}},AbstractMapModule=class e{static{this.instanceCounters=/* @__PURE__ */new WeakMap}constructor(t,i){this._initializing=!0,this.configChangeHandlers=[],this.moduleReady=!1;const r=new.target,o=e.instanceCounters.get(r)??-1;this.instanceIndex=o+1,e.instanceCounters.set(r,this.instanceIndex),this.tomtomMap=t,this.eventsProxy=t._eventsProxy,this.mapLibreMap=t.mapLibreMap,this.filterComposer=LayerFilterComposer.for(t),this.initSourcesWithLayers(i),this.applyConfig(i),this.tomtomMap.addStyleChangeHandler({onStyleAboutToChange:()=>{this.moduleReady=!1},onStyleChanged:({resetState:e})=>e?this.resetOnNewStyle():this.restoreDataAndConfig(),priority:this.styleChangePriority()}),this._initializing=!1}styleChangePriority(){return 0}initSourcesWithLayers(e,t){this.moduleReady=!1,this.sourcesWithLayers=this._initSourcesWithLayers(e,t),this._sourceAndLayerIDs=Object.fromEntries(Object.entries(this.sourcesWithLayers).map(([e,t])=>[e,t.sourceAndLayerIDs])),t&&this.eventsProxy.updateIfRegistered(this.sourcesWithLayers,this),this.tomtomMap.mapReady&&(this.moduleReady=!0)}async waitUntilModuleReady(){await waitUntilMapIsReady(this.tomtomMap),this.moduleReady||await new Promise(e=>{const t=setInterval(()=>{this.tomtomMap.mapReady&&this.moduleReady&&(clearInterval(t),e())},200)})}applyConfig(e){this.config=this._applyConfig(e),this.emitConfigChange()}updateConfig(e){this.applyConfig({...this.config,...e})}emitConfigChange(){if(!this._initializing)for(const e of this.configChangeHandlers)e(this.config)}resetConfig(){this.applyConfig(void 0)}restoreDataAndConfig(){this.moduleReady=!1,this.restoreDataAndConfigImpl()}resetOnNewStyle(){this.moduleReady=!1,this.config=void 0,this.discardShownData(),this.initSourcesWithLayers(void 0,!0),this.config=this._applyConfig(void 0),this.emitConfigChange()}discardShownData(){}restoreDataAndConfigImpl(){this.initSourcesWithLayers(this.config,!0),this._applyConfig(this.config)}getConfig(){return this.config&&{...this.config}}get sourceAndLayerIDs(){return this._sourceAndLayerIDs}userEvents(e,t={}){return new UserEvents({eventProxy:this.eventsProxy,sourcesWithLayers:e.map(e=>this.sourcesWithLayers[e]).filter(e=>!!e),owner:this,config:this.config?.events,mapping:t.mapping,scopeResolver:t.scopeResolver})}lifecycleEvents(){return new ModuleEvents(this.configChangeHandlers,[])}moduleEvents(e,t={}){return new CombinedEvents(this.userEvents(e,t),this.lifecycleEvents())}moduleEventsWithShown(e,t,i={}){return new CombinedEvents(this.userEvents(e,i),new ModuleEvents(this.configChangeHandlers,t))}buildEvents(e,t){return assertNoReservedScopeNames(Object.keys(t),this.constructor.name),Object.assign(e,t)}},AbstractDataOwnedMapModule=class extends AbstractMapModule{setVisible(e){this.config={...this.config,visible:e},this.applyVisibility(this.config),this.emitConfigChange()}isVisible(){return!1!==this.config?.visible}},composersByMap=/* @__PURE__ */new WeakMap,LayerVisibilityComposer=class e extends AbstractLayerComposer{constructor(e){super(e)}static for(t){return composerOfMap(composersByMap,t,()=>new e(t))}setVisible(e,t,i){if(this.mapLibreMap._removed||!this.mapLibreMap.getLayer(e))return;let r=this.byLayer.get(e);if(!r){if(void 0===i)return;r={styleVisibility:this.mapLibreMap.getLayoutProperty(e,"visibility")??"visible",contributions:/* @__PURE__ */new Map},this.byLayer.set(e,r)}setOrDelete(r.contributions,t,i),this.mapLibreMap.setLayoutProperty(e,"visibility",(({styleVisibility:e,contributions:t})=>{const i=new Set(t.values());return i.has(!1)?"none":i.has(!0)?"visible":e})(r),{validate:!1})}},AbstractStyleOwnedMapModule=class extends AbstractMapModule{get visibilityComposer(){return LayerVisibilityComposer.for(this.tomtomMap)}},AbstractEventProxy=class{constructor(){this.interactiveLayerIDs=[],this.handlers={click:{},contextmenu:{},hover:{},"hover-move":{},"long-hover":{}},this.findHandlers=(e,t,i)=>t&&e.flatMap(e=>{const r=this.handlers[e][t]??[];return i?r.filter(e=>!e.scope?.featureMatches||e.scope.featureMatches(i)):r})||[]}ensureInteractiveLayerIDsAdded(e){for(const t of e)this.interactiveLayerIDs.includes(t)||this.interactiveLayerIDs.push(t)}releaseUnusedInteractiveLayerIDs(e){remove(this.interactiveLayerIDs,t=>e.has(t)&&!this.hasHandlerForLayer(t))}indexHandler(e,t){const i=this.handlers[t];for(const r of e.layerIDs)i[r]??=[],i[r].push(e)}unindexHandlers(e,t){const i=this.handlers[t],r=/* @__PURE__ */new Set;for(const o of e)for(const t of o.layerIDs){r.add(t);const o=i[t];o&&(remove(o,t=>e.has(t)),o.length||delete i[t])}return r}dropHandlers(e,t,i){const r=e.source.id,o=/* @__PURE__ */new Set;for(const s of Object.values(this.handlers[t]))for(const e of s)e.sourceWithLayers.source.id===r&&i(e)&&o.add(e);o.size&&this.releaseUnusedInteractiveLayerIDs(this.unindexHandlers(o,t))}addEventHandler(e,t,i,r){const o=new Set(scopedLayerSpecs(e,r.scope).map(e=>e.id));this.ensureInteractiveLayerIDsAdded(o),this.indexHandler({...r,sourceWithLayers:e,layerIDs:o,fn:t},i)}removeHandler(e,t,i){this.dropHandlers(e,t,e=>e.fn===i)}remove(e,t,i){this.dropHandlers(e,t,e=>e.owner===i)}removeAll(){this.interactiveLayerIDs=[],this.handlers={click:{},contextmenu:{},hover:{},"hover-move":{},"long-hover":{}}}hasHandlerForLayer(e){return Object.values(this.handlers).some(t=>!!t[e]?.length)}sourceWithLayersFor(e){if(e)for(const t of Object.values(this.handlers)){const i=t[e];if(i?.length)return i[0].sourceWithLayers}}updateIfRegistered(e,t){const i=new Map(Object.values(e).map(e=>[e.source.id,e]));for(const r of Object.keys(this.handlers)){const e=/* @__PURE__ */new Set;for(const s of Object.values(this.handlers[r]))for(const r of s)r.owner===t&&i.has(r.sourceWithLayers.source.id)&&e.add(r);if(!e.size)continue;const o=this.unindexHandlers(e,r);for(const t of e){const e=i.get(t.sourceWithLayers.source.id);t.sourceWithLayers=e,t.layerIDs=new Set(scopedLayerSpecs(e,t.scope).map(e=>e.id)),this.ensureInteractiveLayerIDsAdded(t.layerIDs),this.indexHandler(t,r)}this.releaseUnusedInteractiveLayerIDs(o)}}},renderedRefId=e=>{const t=e.properties?.id;return"string"==typeof t||"number"==typeof t?t:e.id},findFeatureByRefId=(e,t)=>{if(null!=t)for(let i=0;i<e.length;i++)if(renderedRefId(e[i])===t)return{feature:e[i],index:i}};var sourceProperty,outputProperty,instructionArrowIconImg,asDefined=e=>(function(e){if(isNil(e))throw new Error(`${e} must not be null/undefined. Something went wrong with its initialization.`)}(e),e),TomTomMapSource=class{constructor(e,t,i){this.id=e,this.spec=t,this.runtimeSource=i}ensureAddedToMap(e){this.runtimeSource||(!e.getSource(this.id)&&this.spec&&e.addSource(this.id,this.spec),this.runtimeSource=e.getSource(this.id))}},AbstractSourceWithLayers=class{constructor(e,t,i){this.map=e,this.source=t,this._layerSpecs=i,this._updateSourceAndLayerIDs()}get mapRemoved(){return!0===this.map._removed}isAnyLayerVisible(e){return this.getLayerSpecs(e).some(e=>this.isLayerVisible(e))}areAllLayersVisible(e){return this.getLayerSpecs(e).every(e=>this.isLayerVisible(e))}getLayerSpecs(e){return e?this._layerSpecs.filter(e):this._layerSpecs}_updateSourceAndLayerIDs(){this._sourceAndLayerIDs={sourceID:this.source.id,layerIDs:this._layerSpecs.map(e=>e.id)}}isLayerVisible(e){return!this.mapRemoved&&(!!this.map.getLayer(e.id)&&"none"!==this.map.getLayoutProperty(e.id,"visibility"))}setLayersVisible(e,t){if(!this.mapRemoved)for(const i of this.getLayerSpecs(t))this.map.getLayer(i.id)&&this.map.setLayoutProperty(i.id,"visibility",e?"visible":"none",{validate:!1})}get sourceAndLayerIDs(){return this._sourceAndLayerIDs}},filterLayersBySources=(e,t)=>e.getStyle().layers.filter(e=>t.includes(e?.source)),StyleSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i){let r=filterLayersBySources(e,[t.id]);i&&(r=r.filter(i)),super(e,new TomTomMapSource(t.id,e.getStyle().sources[t.id],t),r)}},AddedSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i,r){super(e,new TomTomMapSource(t,i),r.map(e=>({...e,source:t})))}ensureLayersAddedToMap(){if(!this.mapRemoved)for(const e of this._layerSpecs)this.map.getLayer(e.id)||this.map.addLayer(e,e.beforeID)}ensureAddedToMapWithVisibility(e,t){this.mapRemoved||(this.source.ensureAddedToMap(this.map),t&&(this.ensureLayersAddedToMap(),this.setLayersVisible(e)))}},emptyFeatureCollection={type:"FeatureCollection",features:[]},GeoJSONSourceWithLayers=class extends AddedSourceWithLayers{constructor(e,t,i,r=!0,o){super(e,t,o?.cluster?{type:"geojson",data:emptyFeatureCollection,...o}:{type:"geojson",data:emptyFeatureCollection,promoteId:"id",...o??{}},i),this.shownFeatures=emptyFeatureCollection,this.showListeners=[],this.ensureAddedToMapWithVisibility(!1,r)}show(e,{automaticVisibility:t=!0}={}){if(this.shownFeatures=e,!this.mapRemoved){asDefined(this.source.runtimeSource).setData(e),t&&this.setLayersVisible(!!e.features.length);for(const e of this.showListeners)e()}}onShow(e){this.showListeners.push(e)}findById(e){return findFeatureByRefId(this.shownFeatures.features,e)}clear(){this.show(emptyFeatureCollection)}findFeature(e){return"index"in e?this.shownFeatures.features[e.index]:"id"in e?this.findById(e.id)?.feature:void 0}putEventState(e){if("put"===(e.mode??"put"))for(const i of this.shownFeatures.features)i.properties?.eventState===e.state&&delete i.properties.eventState;const t=this.findFeature(e);t&&(t.properties={...t.properties,eventState:e.state}),!1!==e.show&&this.show(this.shownFeatures,{automaticVisibility:!1})}cleanEventState(e){const t=this.findFeature(e);t?.properties?.eventState&&(delete t?.properties?.eventState,!1!==e?.show&&this.show(this.shownFeatures,{automaticVisibility:!1}))}cleanEventStates(e){let t=!1;for(const i of this.shownFeatures.features)e?.states&&!e.states.includes(i.properties?.eventState)||(delete i.properties?.eventState,t=!0);!1!==e?.show&&t&&this.show(this.shownFeatures,{automaticVisibility:!1})}},isClickEventType=e=>"click"===e||"contextmenu"===e,putEventState=(e,t,i,r="updateInProps")=>{const{feature:o,index:s}=findFeatureByRefId(i,t)||{};if(o&&((e,t)=>{return"recently-hovered"===t?"hover"===(i=e)||"long-hover"===i:!isClickEventType(e)||isClickEventType(t);var i})(o.properties?.eventState,e)){const t={...o,properties:"updateInProps"===r?{...o?.properties,eventState:e}:omit(o?.properties,"eventState")};return i.splice(s,1,t),s}},leaveEventState=(e,t,i,r)=>r?putEventState("recently-hovered",t,i):putEventState(e,t,i,"removeFromProps"),removeEventStateAndShow=(e,t,i,r)=>{const o=[...i.shownFeatures.features],s=leaveEventState(e,renderedRefId(t),o,r);isNil(s)||i.show({...i.shownFeatures,features:o},{automaticVisibility:!1})},updateEventState=(e,t,i,r,o,s=!1)=>{if(t&&r instanceof GeoJSONSourceWithLayers){const l=[...r.shownFeatures.features];return putEventState(e,renderedRefId(t),l),!i||(n=t,(a=i)&&n&&a.id===n.id)||(o===r?leaveEventState(e,renderedRefId(i),l,s):o instanceof GeoJSONSourceWithLayers&&removeEventStateAndShow(e,i,o,s)),void r.show({...r.shownFeatures,features:l},{automaticVisibility:!1})}var a,n;i&&o instanceof GeoJSONSourceWithLayers&&removeEventStateAndShow(e,i,o,s)},noRenderedFeatures=[],interactiveEventTypes=["hover","hover-move","long-hover","click","contextmenu"],eventsProxyDefaultConfig={precisionMode:"box",paddingBoxPx:5,cursorOnHover:"pointer",cursorOnMouseDown:"grabbing",cursorOnMap:"default",longHoverDelayAfterMapMoveMS:800,longHoverDelayOnStillMapMS:300,hoverGracePeriodMS:400},EventsProxy=class extends AbstractEventProxy{constructor(e,t={}){super(),this.enabled=!0,this.recentHoverTimeouts=new globalThis.Map,this.firstDelayedHoverSinceMapMove=!0,this.mouseMoveFrameRequested=!1,this.map=e,this.mapCanvas=e.getCanvas(),this.config={...eventsProxyDefaultConfig,...omitBy(t,isUndefined)},this.mapCanvas.style.cursor=this.config.cursorOnMap,this.lastCursorStyle=this.config.cursorOnMap,this.listenToEvents()}updateConfig(e){this.config={...this.config,...omitBy(e,isUndefined)},this.hoveringFeature||(this.mapCanvas.style.cursor=this.config.cursorOnMap)}listenToEvents(){this.map.on("mousemove",e=>this.onMouseMove(e)),this.map.on("movestart",()=>this.onMouseStart()),this.map.on("mouseout",()=>this.onMouseOut()),this.map.on("mouseover",e=>this.onMouseMove(e)),this.map.on("mousedown",()=>this.onMouseDown()),this.map.on("mouseup",()=>this.onMouseUp()),this.map.on("click",e=>this.onMapClick("click",e)),this.map.on("contextmenu",e=>this.onMapClick("contextmenu",e))}enable(e){this.enabled=e,e||(this.clearLongHoverTimeout(),this.pendingMouseMove=void 0)}toPaddedBounds(e){const t=this.config.paddingBoxPx;return[[e.x-t,e.y+t],[e.x+t,e.y-t]]}isEnabled(){return this.enabled&&!this.map.isMoving()}toCallerFeatures(e,t,i){const r=i?e.filter(e=>i.has(e.layer.id)):e,o=(e=>{const t=/* @__PURE__ */new Set,i=[];for(const r of e){const e=renderedRefId(r);if(void 0===e){i.push(r);continue}const o=`${r.source} ${e}`;t.has(o)||(t.add(o),i.push(r))}return i})((s=r,a=t?.source,a?s.filter(e=>e.source===a):s));var s,a;const n=this.sourceWithLayersFor(t?.layer.id);return n instanceof GeoJSONSourceWithLayers?o.map(e=>n.findById(renderedRefId(e))?.feature??e):o}callerFeaturesFor(e,t,i,r){return e.scope?.layerFilter?this.toCallerFeatures(t,i,e.layerIDs):r}getRenderedFeatures(e){if(!this.interactiveLayerIDs.length)return[];const t={layers:this.interactiveLayerIDs,validate:!1},i=this.config.precisionMode,r="point-then-box"===i||"point"===i?this.map.queryRenderedFeatures(e,t):[];return r.length||"point"===i?r:this.map.queryRenderedFeatures(this.toPaddedBounds(e),t)}clearLongHoverTimeout(){clearTimeout(this.longHoverTimeoutHandlerID)}restartLongHoverTimeout(){this.clearLongHoverTimeout(),this.longHoverTimeoutHandlerID=setTimeout(()=>this.handleLongHoverTimeout(),this.firstDelayedHoverSinceMapMove?this.config.longHoverDelayAfterMapMoveMS:this.config.longHoverDelayOnStillMapMS)}handleLongHoverTimeout(){if(this.firstDelayedHoverSinceMapMove=!1,this.hoveringSourceWithLayers){updateEventState("long-hover",this.hoveringFeature,void 0,this.hoveringSourceWithLayers,void 0);const e=this.findHandlers(["long-hover"],this.hoveringFeature?.layer.id);if(e.length){const t=this.hoveringFeatures??noRenderedFeatures,i=this.hoveringFeature,r=this.toCallerFeatures(t,i);for(const o of e){const e=this.callerFeaturesFor(o,t,i,r);o.fn(e[0],this.hoveringLngLat,e,o.sourceWithLayers)}}}}onMouseStart(){this.firstDelayedHoverSinceMapMove=!0,this.clearLongHoverTimeout()}onMouseOut(){this.clearLongHoverTimeout()}onMouseDown(){this.lastCursorStyle=this.mapCanvas.style.cursor,this.mapCanvas.style.cursor=this.config.cursorOnMouseDown}onMouseUp(){this.mapCanvas.style.cursor=this.lastCursorStyle}onMouseMove(e){this.pendingMouseMove=e,this.mouseMoveFrameRequested||(this.mouseMoveFrameRequested=!0,requestAnimationFrame(()=>{this.mouseMoveFrameRequested=!1;const e=this.pendingMouseMove;this.pendingMouseMove=void 0,e&&this.handleMouseMove(e)}))}handleMouseMove(e){if(!this.isEnabled())return;this.hoveringFeatures=this.getRenderedFeatures(e.point);const[t]=this.hoveringFeatures;if(t&&!this.hasHandlerForLayer(t.layer.id))return;const{hoverChanged:i,mouseInMotionOverHoveredFeature:r}=((e,t,i,r)=>{if(t){if(!r)return{hoverChanged:!0};if(t.id&&t.id!==r.id||t.properties.id&&t.properties.id!==r.properties.id||t.source!==r.source||t.layer.id!==r.layer.id)return{hoverChanged:!0};if(i&&(e.x-i.x!=0||e.y-i.y!=0))return{mouseInMotionOverHoveredFeature:!0}}else if(r)return{hoverChanged:!0};return{}})(e.point,t,this.hoveringPoint,this.hoveringFeature);if(!i&&!r)return;const o=this.hoveringFeature,s=this.hoveringSourceWithLayers;let a;this.hoveringLngLat=e.lngLat,this.hoveringPoint=e.point,this.hoveringFeature=t,this.hoveringSourceWithLayers=this.sourceWithLayersFor(t?.layer.id),i&&(a=this.dispatchHoverEnter(e,o,s)),r&&this.dispatchHoverMove(e,a),this.restartLongHoverTimeout()}dispatchHoverEnter(e,t,i){const r=this.hoveringFeature?.layer.id,o=this.findHandlers(interactiveEventTypes,r,this.hoveringFeature)?.[0];this.updateHoverCursor(o?.config);const s=t?this.hoverGracePeriodFor(t):0;updateEventState("hover",this.hoveringFeature,t,this.hoveringSourceWithLayers,i,s>0),t&&s>0&&this.clearRecentHoverLater(t,s);const a=this.findHandlers(["hover"],r);if(!a.length)return;const n=this.toCallerFeatures(this.hoveringFeatures??noRenderedFeatures,this.hoveringFeature);return this.dispatchToHandlers(a,e,this.hoveringFeature,n),n}dispatchHoverMove(e,t){const i=this.findHandlers(["hover-move"],this.hoveringFeature?.layer.id);if(!i.length)return;const r=this.hoveringFeature,o=t??this.toCallerFeatures(this.hoveringFeatures??noRenderedFeatures,r);this.dispatchToHandlers(i,e,r,o)}dispatchToHandlers(e,t,i,r){for(const o of e){const e=this.callerFeaturesFor(o,this.hoveringFeatures??noRenderedFeatures,i,r);o.fn(e[0],t.lngLat,e,o.sourceWithLayers)}}hoverGracePeriodFor(e){return this.findHandlers(interactiveEventTypes,e.layer.id,e)[0]?.config?.hoverGracePeriodMS??this.config.hoverGracePeriodMS}clearRecentHoverLater(e,t){const i=renderedRefId(e);if(void 0===i)return;const r=`${e.source} ${i}`,o=e.layer.id;clearTimeout(this.recentHoverTimeouts.get(r)),this.recentHoverTimeouts.set(r,setTimeout(()=>{this.recentHoverTimeouts.delete(r);const e=this.sourceWithLayersFor(o);e instanceof GeoJSONSourceWithLayers&&((e,t)=>{const i=e.findById(t);"recently-hovered"===i?.feature.properties?.eventState&&e.cleanEventState({index:i.index})})(e,i)},t))}updateHoverCursor(e){this.hoveringFeature?this.mapCanvas.style.cursor=e?.cursorOnHover??this.config.cursorOnHover:this.mapCanvas.style.cursor=this.config.cursorOnMap}onMapClick(e,t){if(!this.isEnabled())return;const i=this.getRenderedFeatures(t.point),r=this.lastClickedFeature;this.lastClickedFeature=i[0];const o=this.lastClickedSourceWithLayers,s=this.findHandlers([e],this.lastClickedFeature?.layer.id);if(this.lastClickedSourceWithLayers=s[0]?.sourceWithLayers,updateEventState(e,this.lastClickedFeature,r,this.lastClickedSourceWithLayers,o),s.length){const e=this.lastClickedFeature,r=this.toCallerFeatures(i,e);for(const o of s){const s=this.callerFeaturesFor(o,i,e,r);o.fn(s[0],t.lngLat,s,o.sourceWithLayers)}}}},describe=e=>"string"==typeof e?`'${e}'`:Array.isArray(e)?`[${e.map(describe).join(", ")}]`:String(e),expected=(e,t)=>`expects ${e}; got ${describe(t)}`,isFiniteNumber=e=>"number"==typeof e&&Number.isFinite(e),isWithin=(e,{min:t,max:i,bounds:r})=>"soft"===r||e>=t&&("hard-min"===r||e<=i),boundsText=({min:e,max:t,bounds:i})=>"hard"===i?` between ${e} and ${t}`:"hard-min"===i?` of at least ${e}`:"",listProblem=(e,t,i)=>{if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))return expected(e,t);const r=t.filter(e=>!i(e));return r.length?`expects ${e}; ${r.map(describe).join(", ")} ${1===r.length?"is":"are"} not`:void 0},validateKnobValue=(e,t)=>{const i=((e,t)=>{switch(e.kind){case"toggle":return"boolean"==typeof t?void 0:expected("true or false",t);case"factor":case"number":return isFiniteNumber(t)&&isWithin(t,e.range)?void 0:expected(`a number${boundsText(e.range)}`,t);case"offset":return Array.isArray(t)&&2===t.length&&t.every(t=>isFiniteNumber(t)&&isWithin(t,e.range))?void 0:expected(`an [x, y] pair of numbers${boundsText(e.range)}`,t);case"color":return isColorLiteral(t)?void 0:expected("a CSS colour (#rrggbb, hsl(), rgb() or a named colour)",t);case"enum":return"string"==typeof t&&e.options.includes(t)?void 0:expected(`one of ${e.options.join(", ")}`,t);case"enums":return listProblem("a list of its options",t,t=>e.options.includes(t));case"colors":return listProblem(e.options?"a list of CSS colours or of its options":"a list of CSS colours",t,t=>isColorLiteral(t)||Boolean(e.options?.includes(t)));default:return"string"==typeof t?void 0:expected("a string",t)}})(e,t);if(i)throw new RangeError(`Knob '${e.id}' ${i}.`)},copyOf=e=>isObject(e)?clone(e):void 0,setKnob=(e,t,i,r)=>{const o=t.find(e=>e.id===i);if(!o)throw new Error(`Unknown knob '${i}'; its catalogue lists every id.`);validateKnobValue(o,r),e.applyConfig(setWith(e.getConfig()??{},i,r,copyOf))},MAP_BOLD_FONT="Noto-Bold",MAP_REGULAR_FONT="Noto-Regular",MAP_MEDIUM_FONT="Noto-Medium",MAP_ITALIC_FONT="NotoSans-MediumItalic",DEFAULT_TEXT_SIZE=["interpolate",["linear"],["zoom"],10,14,18,16],mapFonts=["Noto-Regular","NotoSans-MediumItalic","Noto-Bold","Noto-Medium"],PIN_ICON_SIZE=["interpolate",["linear"],["zoom"],8,.6,22,.8],SELECTED_PIN_ICON_SIZE=["interpolate",["linear"],["zoom"],8,.8,22,1],mapStyleLayerIDs={country:"Places - Country name",lowestPlaceLabel:"Places - Village / Hamlet",poi:"POI",lowestLabel:"Borders - Treaty label",lowestRoadLine:"Tunnel - Railway outline",lowestBuilding:"Buildings - Underground"},POI_SOURCE_ID="vectorTiles",HILLSHADE_SOURCE_ID="hillshade",TERRAIN_SOURCE_ID="hillshade-terrain",BASE_MAP_SOURCE_ID="vectorTiles",TRAFFIC_INCIDENTS_SOURCE_ID="vectorTilesIncidents",TRAFFIC_FLOW_SOURCE_ID="vectorTilesFlow",instancesByMap=/* @__PURE__ */new WeakMap,builtByMap=/* @__PURE__ */new WeakMap,entriesOf=(e,t)=>{let i=e.get(t);return i||(i=/* @__PURE__ */new Map,e.set(t,i)),i},sharedInstanceIfCreated=(e,t)=>builtByMap.get(e)?.get(t),sharedInstance=async(e,t,i,r)=>{const o=entriesOf(instancesByMap,e),s=o.get(t);if(s){const e=await s;return r?.(e),e}const a=Promise.resolve().then(i);o.set(t,a);try{const i=await a;return entriesOf(builtByMap,e).set(t,i),i}catch(n){throw o.delete(t),n}},filterShowModes=["only","all-except"],clampFactor=(e,t,i=1)=>void 0!==e&&Number.isFinite(e)?clamp(e,t.min,t.max):i,everyOf=()=>e=>e,withIds=e=>Object.keys(e).map(t=>({id:t,...e[t]})),defaultOf=e=>void 0===e?{}:{default:e},OPACITY_RANGE={min:0,max:1,step:.05,bounds:"hard"},ZOOM_RANGE={min:0,max:22,step:1,bounds:"hard"},poiCategoryGroups={FOOD_DRINKS_GROUP:["RESTAURANT","FAST_FOOD","CAFE_PUB","PUB","WINERY","SOUL_FOOD","DELICATESSEN"],SHOPPING_GROUP:["SHOP_OR_STORE","MALL","CLOTHING_SHOP","MARKETPLACE","FOOD_MARKET","SUPERMARKET","DEPARTMENT_STORE","CONVENIENCE_STORE","GROCERY_STORE","HARDWARE_STORE","ELECTRICAL_APPLIANCES_SHOP"],TRANSPORTATION_GROUP:["AIRPORT","FERRY_TERMINAL","HELIPORT_OR_HELIPAD","PUBLIC_TRANSPORT_STOP","RAILWAY_STATION","BUS_STOP","TAXI_STAND"],HEALTH_GROUP:["DOCTOR","EMERGENCY_MEDICAL_SERVICE","EMERGENCY_ROOM","HEALTHCARE_SERVICE","HOSPITAL","PHARMACY","DENTIST","WELFARE_ORGANIZATION"],PARKING_GROUP:["PARKING_GARAGE","OPEN_CAR_PARKING_AREA"],HOLIDAY_TOURISM_GROUP:["AMUSEMENT_PARK","BEACH","HOLIDAY_RENTAL","NATURAL_FEATURE","TOURIST_ATTRACTION","LEISURE_CENTER","MOUNTAIN_PASS","MOUNTAIN_PEAK","MUSEUM","VIEWPOINT","TOURIST_INFORMATION"],EV_CHARGING_STATIONS_GROUP:["CHARGING_LOCATION"],GAS_STATIONS_GROUP:["FUEL_STATION"],ACCOMMODATION_GROUP:["CAMPING_GROUND","HOTEL_OR_MOTEL","HOLIDAY_RENTAL"],ENTERTAINMENT_GROUP:["CINEMA","THEATER","MOVIE_THEATER","NIGHTLIFE","CONCERT_HALL","ENTERTAINMENT","CLUB_AND_ASSOCIATION","CASINO_AND_GAMBLING"],SPORTS_LEISURE_GROUP:["SPORTS_CENTER","WATER_SPORT","SWIMMING_POOL","GOLF_COURSE","STADIUM","BEACH","ICE_RINK","LEISURE_CENTER","MOUNTAIN_PASS","MOUNTAIN_PEAK"],EDUCATION_GROUP:["SCHOOL","COLLEGE_OR_UNIVERSITY","PUBLIC_LIBRARY","CULTURAL_CENTER"],GOVERNMENT_GROUP:["GOVERNMENT_OFFICE","COURTHOUSE","EMBASSY","FIRE_STATION","POLICE_STATION"]},poisKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"The POIs the map style draws.",default:!0},"filters.categories.show":{kind:"enum",description:"`only` draws just the `filters.categories.values` categories, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.categories.values":{kind:"enums",description:"The categories and category groups `filters.categories.show` draws alone or hides; a group stands for each of its categories. Groups come first in the options.",options:[...Object.keys(poiCategoryGroups),...poiCategories]}}))(),poisKnobCatalogue=/* @__PURE__ */withIds(poisKnobDefinitions),poisKnobIds=/* @__PURE__ */poisKnobCatalogue.map(({id:e})=>e),poiLayerIDs=["POI","POI - Micro"],mapDisplayPoiCategoryMappings={ABORIGINAL_LAND:"aboriginal_land",AIRPORT:"airport",AMUSEMENT_PARK:"amusement_park",ATM:"atm",BANK:"bank",BAR:"bar",BEACH:"beach_resort",TRANSPORT_ACCESS:"border_control",BORDER_CONTROL:"border_control",BUS_STOP:"bus_station",CAFE:"cafe",CAFE_PUB:"cafe",CAMPING_GROUND:"camping_ground",CAR_RENTAL:"car_rental",CASINO_AND_GAMBLING:"casino_and_gambling",CEMETERY:"cemetery",CHARGING_LOCATION:"charging_location",CINEMA:"cinema",MOVIE_THEATER:"cinema",HEALTHCARE_SERVICE:"clinic",CLOTHING_SHOP:"clothing_shop",COFFEE_SHOP:"coffee_shop",COLLEGE_OR_UNIVERSITY:"college_or_university",AGRICULTURE:"commercial_area",BUSINESS_PARK:"commercial_area",COMMERCIAL_BUILDING:"commercial_area",COMPANY:"commercial_area",RESIDENTIAL_ACCOMMODATION:"commercial_area",RESIDENTIAL_ENTRANCE:"commercial_area",EXHIBITION_CONVENTION_CENTER:"conference_center",CLUB_AND_ASSOCIATION:"consumer_service",PUBLIC_AMENITY:"consumer_service",PEDESTRIAN_SUBWAY:"consumer_service",WELFARE_ORGANIZATION:"consumer_service",COURTHOUSE:"courthouse",COMMUNITY_CENTER:"cultural_center",CULTURAL_CENTER:"cultural_center",DENTIST:"dentist",DEPARTMENT_STORE:"department_store",DOCTOR:"doctor",EMERGENCY_MEDICAL_SERVICE:"emergency_ward_entrance",EMERGENCY_ROOM:"emergency_ward_entrance",FAST_FOOD:"fast_food",FERRY_TERMINAL:"ferry_terminal",FIRE_STATION:"fire_station",FITNESS_CLUB_AND_CENTER:"fitness_center",WINERY:"food_and_drinks_shop",FOREIGN_EXCHANGE:"foreign_exchange",EXCHANGE:"foreign_exchange",FUEL_STATION:"fuel_station",GOLD_EXCHANGE:"gold_exchange",GOLF_COURSE:"golf_course",EMBASSY:"government_office",GOVERNMENT_OFFICE:"government_office",HELIPORT_OR_HELIPAD:"heliport_or_helipad",HISTORIC_SITE:"historic_site",HOLIDAY_RENTAL:"holiday_home",GENERAL_HOSPITAL_AND_POLYCLINIC:"hospital",HOSPITAL:"hospital",HOTEL_OR_MOTEL:"hotel_or_motel",ICE_RINK:"ice_rink",INDUSTRIAL_BUILDING:"industrial_area",PORT_WAREHOUSE_FACILITY:"industrial_area",PRIMARY_RESOURCE_UTILITY:"industrial_area",NATURAL_FEATURE:"landmark",MALL:"mall",MANUFACTURING_FACILITY:"manufacturing_facility",MARINA:"marina",MARKETPLACE:"marketplace",MEDIA_FACILITY:"media_facility",MOUNTAIN_PASS:"mountain_pass",MUSEUM:"museum",NON_GOVERNMENTAL_ORGANIZATION:"ngo_office",CONCERT_HALL:"nightlife",ENTERTAINMENT:"nightlife",NIGHTLIFE:"nightlife",PARK_AND_RECREATION_AREA:"park_and_recreation_area",TRAIL_SYSTEM:"park_and_recreation_area",LEISURE_CENTER:"park_and_recreation_facility",FLYING_CLUB:"park_and_recreation_facility",WATER_SPORT:"park_and_recreation_facility",PARKING_GARAGE:"parking_facility",PHARMACY:"pharmacy",POLICE_STATION:"police_station",POST_OFFICE:"post_office",PRISON:"prison",PROTECTED_LAND:"protected_land",PUB:"pub",PUBLIC_LIBRARY:"public_library",PUBLIC_TRANSPORT_STOP:"public_transport_stop",RAILWAY_STATION:"railway_station",CHURCH:"religious_site",GURUDWARA:"religious_site",MOSQUE:"religious_site",PAGODA:"religious_site",RELIGIOUS_SITE:"religious_site",SYNAGOG:"religious_site",TEMPLE:"religious_site",RENTAL_CAR_PARKING:"rental_car_parking",RESEARCH_FACILITY:"research_facility",REST_AREA:"rest_and_service_area",RESTAURANT:"restaurant",RESTAURANT_AREA:"restaurant",SCHOOL:"school_or_kindergarten",SHOP_OR_STORE:"shop_or_store",ADVENTURE_SPORTS_FACILITY:"sport_facility",SPORTS_CENTER:"sport_facility",TENNIS_COURT:"sport_facility",STADIUM:"stadium",SUPERMARKET:"supermarket",SWIMMING_POOL:"swimming_pool",TAXI_STAND:"taxi_stand",OPERA_HOUSE:"theater",THEATER:"theater",TOLL_GATE:"toll_plaza",TOURIST_ATTRACTION:"tourist_attraction",TOURIST_INFORMATION:"tourist_information",TRUCK_STOP:"truck_stop",VEHICLE_DEALER:"vehicle_dealer",MOTORING_ORGANIZATION_OFFICE:"vehicle_inspection",TRAFFIC_CONTROL_DEPARTMENT:"vehicle_inspection",TRANSPORT_AUTHORITY_VEHICLE_REGISTRATION:"vehicle_inspection",VEHICLE_REPAIR:"vehicle_repair",CAR_WASH:"vehicle_wash",VETERINARY:"veterinary",HILL:"viewpoint",MOUNTAIN_PEAK:"viewpoint",VIEWPOINT:"viewpoint",WEIGH_STATION:"weighbridge",AQUATIC_ZOO:"zoo_or_aquarium",ARBORETA_AND_BOTANICAL_GARDENS:"zoo_or_aquarium",ZOOS_ARBORETA_BOTANICAL_GARDEN:"zoo_or_aquarium"},completeMapDisplayPoiCategoryMappings={...mapDisplayPoiCategoryMappings,AIRFIELD:"airport",AIRLINE_ACCESS:"airport",PRIVATE_AIRPORT:"airport",PUBLIC_AIRPORT:"airport",ANIMAL_SHELTER:"animal_shelter",DIVERSIFIED_FINANCIALS:"bank",COCKTAIL_BAR:"bar",BEACH_CLUB:"beach_resort",SECURED_ENTRANCE:"border_control",INTERNET_CAFE:"cafe",CAFETERIA:"cafeteria",CARAVAN_SITE:"camping_ground",RECREATIONAL_CAMPING_GROUND:"camping_ground",REST_CAMP:"camping_ground",MAUSOLEUM_OR_GRAVE:"cemetery",CHILDCARE:"childcare",PRE_SCHOOL:"childcare",DRIVE_IN_MOVIES:"cinema",CHILDREN_S_CLOTHES:"clothing_shop",MEN_S_CLOTHING:"clothing_shop",SPECIALTY_CLOTHING_SHOP:"clothing_shop",WOMEN_S_CLOTHING:"clothing_shop",JUNIOR_COLLEGE_OR_COMMUNITY_COLLEGE:"college_or_university",COMEDY_CLUB:"comedy_club",ADVERTISING_COMPANY:"commercial_area",AGRICULTURAL_TECHNOLOGY:"commercial_area",AIRLINE_COMPANY:"commercial_area",APARTMENT_RENTAL:"commercial_area",AUTOMOBILE_COMPANY:"commercial_area",BUILDING:"commercial_area",BUSINESS_SERVICES:"commercial_area",BUS_CHARTER_COMPANY:"commercial_area",CABLE_AND_TELEPHONE_COMPANY:"commercial_area",CLEANING_SERVICES:"commercial_area",COMPUTER_AND_DATA_SERVICES:"commercial_area",CONSTRUCTION_COMPANY:"commercial_area",DELIVERY_SERVICE:"commercial_area",ELECTRONICS_COMPANY:"commercial_area",EQUIPMENT_RENTAL:"commercial_area",FARM:"commercial_area",FLATS_OR_APARTMENT_COMPLEX:"commercial_area",HORTICULTURE:"commercial_area",IMPORT_OR_EXPORT_AND_DISTRIBUTION:"commercial_area",INSURANCE_COMPANY:"commercial_area",INVESTMENT_ADVISOR:"commercial_area",LEGAL_SERVICES:"commercial_area",MINING_COMPANY:"commercial_area",MOVING_AND_STORAGE_COMPANY:"commercial_area",OIL_AND_NATURAL_GAS:"commercial_area",PHARMACEUTICAL_COMPANY:"commercial_area",PRIMARY_PRODUCER:"commercial_area",PUBLISHING_TECHNOLOGIES:"commercial_area",REAL_ESTATE_AGENT:"commercial_area",REAL_ESTATE_COMPANY:"commercial_area",RETIREMENT_COMMUNITY:"commercial_area",SCHOOL_BUS_COMPANY:"commercial_area",SERVICE_COMPANY:"commercial_area",SOFTWARE_COMPANY:"commercial_area",TAX_SERVICES:"commercial_area",TELECOMMUNICATIONS:"commercial_area",TRANSPORT_COMPANY:"commercial_area",TRAVEL_AGENT:"commercial_area",WEDDING_SERVICES:"commercial_area",PUBLIC_CALL_BOX:"consumer_service",PUBLIC_BATHROOM:"consumer_service",GENERAL_PRACTITIONER:"doctor",SPECIALIST:"doctor",AMBULANCE_UNIT:"emergency_ward_entrance",RESCUE_SERVICE:"emergency_ward_entrance",MICROBREWERY:"food_and_drinks_shop",BATTLEFIELD:"historic_site",MEMORIAL:"historic_site",BUNGALOW_RENTAL:"holiday_home",CHALET_RENTAL:"holiday_home",COTTAGE_RENTAL:"holiday_home",VILLA_RENTAL:"holiday_home",HORSE_RIDING:"horse_riding",BLOOD_BANK:"hospital",HOSPITAL_FOR_WOMEN_AND_CHILDREN:"hospital",HOSPITAL_OF_CHINESE_MEDICINE:"hospital",SPECIAL_HOSPITAL:"hospital",BANDB_OR_GUEST_HOUSE:"hotel_or_motel",CABINS_LODGES:"hotel_or_motel",HOSTEL:"hotel_or_motel",HOTEL:"hotel_or_motel",MOTEL:"hotel_or_motel",RESORT:"hotel_or_motel",ICE_CREAM_PARLOR:"ice_cream_shop",ICE_HOCKEY_ARENA:"ice_rink",CHEMICAL_COMPANY:"industrial_area",MECHANICAL_ENGINEERING:"industrial_area",QUARRY:"industrial_area",JUICE_BAR:"juice_bar",ARCH:"landmark",BAY:"landmark",BRIDGE:"landmark",CAPE:"landmark",COVE:"landmark",DAM:"landmark",DUNE:"landmark",ISLAND:"landmark",LOCALE:"landmark",MARSH:"landmark",MONUMENT:"landmark",OASIS:"landmark",OBSERVATORY:"landmark",PARKWAY:"landmark",PLAIN_OR_FLAT:"landmark",PLATEAU:"landmark",PAN:"landmark",RAPIDS:"landmark",REEF:"landmark",RESERVOIR:"landmark",RIVER_CROSSING:"landmark",ROCKS:"landmark",STATUE:"landmark",TOWER:"landmark",TUNNEL:"landmark",VALLEY:"landmark",WATER_HOLE:"landmark",WELL:"landmark",AUTOMOBILE_MANUFACTURING:"manufacturing_facility",MANUFACTURING_COMPANY:"manufacturing_facility",FARMERS_MARKET:"marketplace",FOOD_MARKET:"marketplace",INFORMAL_MARKET:"marketplace",PUBLIC_MARKET:"marketplace",MILITARY_AIRPORT:"military_airfield",FUNERAL_SERVICE_AND_MORTUARIES:"mourning_facility",AMUSEMENT_PLACE:"nightlife",BETTING_STATION:"nightlife",CABARET_THEATER:"nightlife",DISCO_CLUB:"nightlife",FAIRGROUND:"nightlife",JAZZ_CLUB:"nightlife",KARAOKE_CLUB:"nightlife",MUSIC_CENTER:"nightlife",ADVENTURE_VEHICLE_TRAIL:"park_and_recreation_area",FISHING_AND_HUNTING_AREA:"park_and_recreation_area",FOREST_AREA:"park_and_recreation_area",HIKING_TRAIL:"park_and_recreation_area",HISTORICAL_PARK:"park_and_recreation_area",HORSE_RIDING_TRAIL:"park_and_recreation_area",MOUNTAIN_BIKE_TRAIL:"park_and_recreation_area",PARK:"park_and_recreation_area",PICNIC_AREA:"park_and_recreation_area",RECREATION_AREA:"park_and_recreation_area",ROCK_CLIMBING_TRAIL:"park_and_recreation_area",WILDERNESS_AREA:"park_and_recreation_area",OPEN_CAR_PARKING_AREA:"parking_facility",BEAUTY_SALON:"personal_care_service",HAIRDRESSER:"personal_care_service",NAIL_SALON:"personal_care_service",PERSONAL_CARE_FACILITY:"personal_care_service",PERSONAL_SERVICE:"personal_care_service",SAUNA_SOLARIUM_MASSAGE:"personal_care_service",DRUG_STORE:"pharmacy",CANNABIS_SHOP:"pharmacy",MEDICINAL_AND_RECREATIONAL_DISPENSARY:"pharmacy",MEDICINAL_MARIJUANA_DISPENSARY:"pharmacy",RECREATIONAL_MARIJUANA_DISPENSARY:"pharmacy",PLANETARIUM:"planetarium",COURIER_DROP_BOX:"post_depot",BUS_LINES:"public_transport_stop",PASSENGER_TRANSPORT_TICKET_OFFICE:"public_transport_stop",STREETCAR_STOP:"public_transport_stop",SUBWAY_STATION:"public_transport_stop",SUBWAY_ENTRANCE:"public_transport_stop",INTERNATIONAL_RAILROAD_STATION:"railway_station",NATIONAL_RAILROAD_STATION:"railway_station",STATION_ACCESS:"railway_station",URBAN_STATION:"railway_station",AFGHAN_RESTAURANT:"restaurant",AFRICAN_RESTAURANT:"restaurant",AMERICAN_RESTAURANT:"restaurant",ARABIAN_RESTAURANT:"restaurant",ARMENIAN_RESTAURANT:"restaurant",ASIAN_RESTAURANT:"restaurant",AUSTRALIAN_RESTAURANT:"restaurant",AUSTRIAN_RESTAURANT:"restaurant",BANQUET_ROOMS:"restaurant",BARBECUE_RESTAURANT:"restaurant",BASQUE_RESTAURANT:"restaurant",BELGIAN_RESTAURANT:"restaurant",BISTRO:"restaurant",BOLIVIAN_RESTAURANT:"restaurant",BRAZILIAN_RESTAURANT:"restaurant",BRITISH_RESTAURANT:"restaurant",BUFFET_RESTAURANT:"restaurant",BULGARIAN_RESTAURANT:"restaurant",BURMESE_RESTAURANT:"restaurant",CALIFORNIAN_RESTAURANT:"restaurant",CAMBODIAN_RESTAURANT:"restaurant",CANADIAN_RESTAURANT:"restaurant",CARIBBEAN_RESTAURANT:"restaurant",CATERING_SERVICES:"restaurant",CHICKEN_RESTAURANT:"restaurant",CHILEAN_RESTAURANT:"restaurant",CHINESE_RESTAURANT:"restaurant",COLOMBIAN_RESTAURANT:"restaurant",CORSICAN_RESTAURANT:"restaurant",CREOLE_RESTAURANT:"restaurant",CREPERIE:"restaurant",CUBAN_RESTAURANT:"restaurant",CZECH_RESTAURANT:"restaurant",DANISH_RESTAURANT:"restaurant",DINNER_THEATER:"restaurant",DONGBEI_RESTAURANT:"restaurant",DOUGHNUT_RESTAURANT:"restaurant",DUTCH_RESTAURANT:"restaurant",EGYPTIAN_RESTAURANT:"restaurant",ENGLISH_RESTAURANT:"restaurant",ETHIOPIAN_RESTAURANT:"restaurant",FINNISH_RESTAURANT:"restaurant",FONDUE_RESTAURANT:"restaurant",FRENCH_RESTAURANT:"restaurant",FUSION_RESTAURANT:"restaurant",GERMAN_RESTAURANT:"restaurant",GREEK_RESTAURANT:"restaurant",GRILL_RESTAURANT:"restaurant",HAMBURGER_RESTAURANT:"restaurant",HAWAIIAN_RESTAURANT:"restaurant",HOT_POT_RESTAURANT:"restaurant",HUNAN_RESTAURANT:"restaurant",HUNGARIAN_RESTAURANT:"restaurant",INDIAN_RESTAURANT:"restaurant",INDONESIAN_RESTAURANT:"restaurant",INTERNATIONAL_RESTAURANT:"restaurant",IRANIAN_RESTAURANT:"restaurant",IRISH_RESTAURANT:"restaurant",ISRAELI_RESTAURANT:"restaurant",ITALIAN_RESTAURANT:"restaurant",JAMAICAN_RESTAURANT:"restaurant",JAPANESE_RESTAURANT:"restaurant",JEWISH_RESTAURANT:"restaurant",KOREAN_RESTAURANT:"restaurant",KOSHER_RESTAURANT:"restaurant",LATIN_AMERICAN_RESTAURANT:"restaurant",LEBANESE_RESTAURANT:"restaurant",MEDITERRANEAN_RESTAURANT:"restaurant",MEXICAN_RESTAURANT:"restaurant",MIDDLE_EASTERN_RESTAURANT:"restaurant",MONGOLIAN_RESTAURANT:"restaurant",MOROCCAN_RESTAURANT:"restaurant",NEPALESE_RESTAURANT:"restaurant",NORWEGIAN_RESTAURANT:"restaurant",ORGANIC_FOOD_RESTAURANT:"restaurant",ORIENTAL_RESTAURANT:"restaurant",PAKISTANI_RESTAURANT:"restaurant",PERUVIAN_RESTAURANT:"restaurant",PHILIPPINE_RESTAURANT:"restaurant",PIZZERIA:"restaurant",POLISH_RESTAURANT:"restaurant",PORTUGUESE_RESTAURANT:"restaurant",RUSSIAN_RESTAURANT:"restaurant",SALAD_BAR:"restaurant",SANDWICH_RESTAURANT:"restaurant",SCANDINAVIAN_RESTAURANT:"restaurant",SEAFOOD:"restaurant",SHANDONG_RESTAURANT:"restaurant",SICHUAN_RESTAURANT:"restaurant",SNACKS_RESTAURANT:"restaurant",SOUL_FOOD:"restaurant",SOUP_RESTAURANT:"restaurant",SPANISH_RESTAURANT:"restaurant",STEAK_HOUSE:"restaurant",SUSHI_RESTAURANT:"restaurant",SWEDISH_RESTAURANT:"restaurant",SWISS_RESTAURANT:"restaurant",SYRIAN_RESTAURANT:"restaurant",TAIWANESE_RESTAURANT:"restaurant",TAKEOUT_FOOD:"restaurant",TAPAS_RESTAURANT:"restaurant",TEPPANYAKI_RESTAURANT:"restaurant",THAI_RESTAURANT:"restaurant",TIBETAN_RESTAURANT:"restaurant",TUNISIAN_RESTAURANT:"restaurant",TURKISH_RESTAURANT:"restaurant",VEGETARIAN_RESTAURANT:"restaurant",VENEZUELAN_RESTAURANT:"restaurant",VIETNAMESE_RESTAURANT:"restaurant",WESTERN_RESTAURANT:"restaurant",ART_SCHOOL:"school_or_kindergarten",DANCE_STUDIO_AND_SCHOOL:"school_or_kindergarten",DRIVING_SCHOOL:"school_or_kindergarten",HIGH_SCHOOL:"school_or_kindergarten",LANGUAGE_SCHOOL:"school_or_kindergarten",MIDDLE_SCHOOL:"school_or_kindergarten",PRIMARY_SCHOOL:"school_or_kindergarten",SENIOR_HIGH_SCHOOL:"school_or_kindergarten",VOCATIONAL_SCHOOL:"school_or_kindergarten",AGRICULTURAL_SUPPLIES:"shop_or_store",ANTIQUE_ART_SHOP:"shop_or_store",BAGS_LEATHERWEAR:"shop_or_store",BAKERY:"shop_or_store",BEAUTY_SUPPLIES:"shop_or_store",BOATING_EQUIPMENT_AND_ACCESSORIES:"shop_or_store",BOOK_SHOP:"shop_or_store",BUTCHER:"shop_or_store",CAMERAS_AND_PHOTOGRAPHY:"shop_or_store",CARPET_FLOOR_COVERINGS:"shop_or_store",CHRISTMAS_OR_HOLIDAY_SHOP:"shop_or_store",COMPUTER_AND_COMPUTER_SUPPLIES:"shop_or_store",CONSTRUCTION_MATERIAL_AND_EQUIPMENT:"shop_or_store",CONSUMER_ELECTRONICS:"shop_or_store",CONVENIENCE_STORE:"shop_or_store",CURTAINS_TEXTILES:"shop_or_store",C_DS_DVD_VIDEOS:"shop_or_store",DELICATESSEN:"shop_or_store",DO_IT_YOURSELF_CENTERS:"shop_or_store",DRIVE_THROUGH_BOTTLE_SHOP:"shop_or_store",DRY_CLEANER:"shop_or_store",ELECTRICAL_APPLIANCES_SHOP:"shop_or_store",FACTORY_OUTLET:"shop_or_store",FISHMONGER:"shop_or_store",FLORISTS:"shop_or_store",FOOTWEAR_SHOE_REPAIRS:"shop_or_store",FURNITURE_HOME_FURNISHINGS:"shop_or_store",GARDEN_CENTERS_SERVICES:"shop_or_store",GIFTS_CARDS_NOVELTIES_SOUVENIRS:"shop_or_store",GLASSWARE_CERAMIC_SHOP:"shop_or_store",GLASS_WINDOWS_STORE:"shop_or_store",GREENGROCER:"shop_or_store",GROCERY_STORE:"shop_or_store",HARDWARE_STORE:"shop_or_store",HOBBY_SHOP:"shop_or_store",HOUSE_AND_GARDEN_FURNITURE_AND_FITTINGS:"shop_or_store",JEWELRY_CLOCKS_WATCHES:"shop_or_store",KITCHENS_BATHROOMS:"shop_or_store",LAUNDRY:"shop_or_store",LIGHTING_SHOPS:"shop_or_store",LOCAL_SPECIALITIES_SHOP:"shop_or_store",LOTTERY_SHOP:"shop_or_store",MEDICAL_SUPPLIES_EQUIPMENT:"shop_or_store",MOBILE_PHONE_SHOP:"shop_or_store",MUSIC_INSTRUMENTS_STORE:"shop_or_store",NEWSAGENTS_TOBACCONISTS:"shop_or_store",OFFICE_EQUIPMENT:"shop_or_store",OPTICIAN:"shop_or_store",FOOD_AND_DRINKS_SHOP:"shop_or_store",PAINTING_DECORATING:"shop_or_store",PAWN_SHOP:"shop_or_store",PET_SUPPLIES:"shop_or_store",PHOTOCOPY_SHOP:"shop_or_store",PHOTO_LAB_OR_DEVELOPMENT:"shop_or_store",RECYCLING_SHOP:"shop_or_store",RETAIL_OUTLET:"shop_or_store",SECURITY_PRODUCTS:"shop_or_store",SHOPPING_SERVICE:"shop_or_store",SPECIALTY_FOODS:"shop_or_store",SPORTS_EQUIPMENT_AND_CLOTHING:"shop_or_store",TAILOR_SHOP:"shop_or_store",TOYS_GAMES_SHOP:"shop_or_store",VARIETY_STORE:"shop_or_store",VIDEO_RENTAL_SHOP:"shop_or_store",WHOLESALE_CLUB:"shop_or_store",WINE_SPIRITS:"shop_or_store",ATHLETICS_TRACK:"sport_facility",BASEBALL_PARK:"sport_facility",BASKETBALL_ARENA:"sport_facility",BOWLING_CENTER:"sport_facility",CRICKET_GROUND:"sport_facility",HOCKEY_CLUB:"sport_facility",HORSE_RACING_TRACK:"sport_facility",RACE_TRACK:"sport_facility",RUGBY_GROUND:"sport_facility",SQUASH_COURT:"sport_facility",THEMATIC_SPORT_CENTER:"sport_facility",FOOTBALL_STADIUM:"stadium",MOTOR_RACING_STADIUM:"stadium",MULTI_PURPOSE_STADIUM:"stadium",NETBALL_STADIUM:"stadium",SOCCER_STADIUM:"stadium",STOCK_EXCHANGE:"stock_exchange",TAXI_LIMOUSINE_AND_SHUTTLE_SERVICE:"taxi_stand",TEA_HOUSE:"tea_house",AMPHITHEATER:"theater",CAVE:"tourist_attraction",MINERAL_OR_HOT_SPRINGS:"tourist_attraction",NATURAL_TOURIST_ATTRACTION:"tourist_attraction",BOAT_LAUNCHING_RAMP:"transport_access",HARBOR:"transport_access",YACHT_BASIN:"transport_access",ATV_DEALER:"vehicle_dealer",BOAT_DEALER:"vehicle_dealer",BUS_DEALER:"vehicle_dealer",CAR_DEALER:"vehicle_dealer",MOTORCYCLE_DEALER:"vehicle_dealer",RECREATIONAL_VEHICLE_DEALER:"vehicle_dealer",TRUCK_DEALER:"vehicle_dealer",VAN_DEALER:"vehicle_dealer",BODYSHOP:"vehicle_repair",CAR_GLASS_REPLACEMENT_SHOP:"vehicle_repair",CAR_REPAIR_AND_SERVICE:"vehicle_repair",HOME_APPLIANCE_REPAIR:"vehicle_repair",MOTORCYCLE_REPAIR:"vehicle_repair",TIRE_SERVICE:"vehicle_repair",TRUCK_REPAIR_AND_SERVICE:"vehicle_repair",ANIMAL_SERVICE:"veterinary",RIDGE:"viewpoint",SKI_RESORT:"winter_sports",WILDLIFE_PARK:"zoo_or_aquarium",ZOO:"zoo_or_aquarium"},toBaseMapPOICategory=e=>completeMapDisplayPoiCategoryMappings[e],baseMapPOICategoryValues=Array.from(new Set(Object.values(completeMapDisplayPoiCategoryMappings))),baseMapCategoryToGroup={bar:"eat_and_drink",cafe:"eat_and_drink",cafeteria:"eat_and_drink",coffee_shop:"eat_and_drink",fast_food:"eat_and_drink",ice_cream_shop:"eat_and_drink",juice_bar:"eat_and_drink",pub:"eat_and_drink",restaurant:"eat_and_drink",tea_house:"eat_and_drink",clothing_shop:"shopping",department_store:"shopping",food_and_drinks_shop:"shopping",mall:"shopping",marketplace:"shopping",shop_or_store:"shopping",supermarket:"shopping",atm:"finance",bank:"finance",foreign_exchange:"finance",gold_exchange:"finance",stock_exchange:"finance",camping_ground:"lodging",holiday_home:"lodging",hotel_or_motel:"lodging",airport:"transport",bus_station:"transport",ferry_terminal:"transport",heliport_or_helipad:"transport",marina:"transport",public_transport_stop:"transport",railway_station:"transport",taxi_stand:"transport",transport_access:"transport",border_control:"driving",car_rental:"driving",charging_location:"driving",fuel_station:"driving",rest_and_service_area:"driving",toll_plaza:"driving",truck_stop:"driving",vehicle_dealer:"driving",vehicle_inspection:"driving",vehicle_repair:"driving",vehicle_wash:"driving",weighbridge:"driving",parking_facility:"parking",rental_car_parking:"parking",clinic:"healthcare",dentist:"healthcare",doctor:"healthcare",emergency_ward_entrance:"healthcare",hospital:"healthcare",pharmacy:"healthcare",veterinary:"healthcare",childcare:"education",college_or_university:"education",research_facility:"education",school_or_kindergarten:"education",cultural_center:"cultural",historic_site:"cultural",museum:"cultural",planetarium:"cultural",theater:"cultural",amusement_park:"leisure",beach_resort:"leisure",casino_and_gambling:"leisure",cinema:"leisure",comedy_club:"leisure",nightlife:"leisure",park_and_recreation_facility:"leisure",tourist_attraction:"leisure",tourist_information:"leisure",zoo_or_aquarium:"leisure",fitness_center:"sport",golf_course:"sport",horse_riding:"sport",ice_rink:"sport",sport_facility:"sport",stadium:"sport",swimming_pool:"sport",winter_sports:"sport",aboriginal_land:"outdoor",landmark:"outdoor",mountain_pass:"outdoor",park_and_recreation_area:"outdoor",viewpoint:"outdoor",protected_land:"protected",cemetery:"public",courthouse:"public",fire_station:"public",government_office:"public",police_station:"public",post_depot:"public",post_office:"public",prison:"public",public_library:"public",military_airfield:"military",religious_site:"religion",animal_shelter:"business",commercial_area:"business",conference_center:"business",consumer_service:"business",industrial_area:"business",manufacturing_facility:"business",media_facility:"business",mourning_facility:"business",ngo_office:"business",personal_care_service:"business"},toBaseMapPOIGroup=e=>{const t=toBaseMapPOICategory(e);return t?baseMapCategoryToGroup[t]:void 0},TITLE="title",pinIconBaseLayout={"icon-image":["get","iconID"],"icon-anchor":"bottom","icon-size":PIN_ICON_SIZE,"icon-allow-overlap":!0,"icon-padding":0},pinIconBasePaint={"icon-translate":[0,5],"icon-translate-anchor":"viewport"},pinTextBaseLayout={"text-optional":!0,"text-font":["Noto-Bold"],"text-field":["get",TITLE],"text-justify":"auto","text-variable-anchor":["top","left","right"],"text-variable-anchor-offset":["top",[0,.7],"left",[1.4,-1.4],"right",[-1.4,-1.4]],"text-size":DEFAULT_TEXT_SIZE,"text-padding":5},pinTextBasePaint={"text-halo-width":["interpolate",["linear"],["zoom"],6,1,10,1.5],"text-translate-anchor":"viewport"},pinLayerBaseSpec={type:"symbol",layout:{...pinIconBaseLayout,...pinTextBaseLayout},paint:{...pinIconBasePaint,...pinTextBasePaint}},isClusterFilter=["has","point_count"],isNotClusterFilter=["!",isClusterFilter],CLUSTER_PROPERTY_BASE_MAP_ICON_IDS="clusterBaseMapIconIDs",isSingleCategoryClusterFilter=["all",isClusterFilter,["==",["index-of",",",["get","clusterBaseMapIconIDs"]],-1]],isMixedCategoryClusterFilter=["all",isClusterFilter,[">=",["index-of",",",["get","clusterBaseMapIconIDs"]],0]],DEFAULT_SINGLE_BADGE_OFFSET=[12,-14],singleBadgeOffset=e=>e?.offset??DEFAULT_SINGLE_BADGE_OFFSET,badgeCirclePaint=(e,t)=>({"circle-radius":t,"circle-color":e?.color??"#000000","circle-stroke-color":e?.strokeColor??"#FFFFFF","circle-stroke-width":e?.strokeWidth??1.5}),countTextLayout=e=>({"text-field":["get","point_count_abbreviated"],"text-font":["Noto-Bold"],"text-size":e?.textSize??12,"text-allow-overlap":!0,"text-ignore-placement":!0}),clusteredPlacesAggregateProperties={[CLUSTER_PROPERTY_BASE_MAP_ICON_IDS]:(sourceProperty="baseMapIconID",outputProperty="clusterBaseMapIconIDs",[["case",["==",["get",outputProperty],null],["accumulated"],["==",["accumulated"],null],["get",outputProperty],[">=",["index-of",["concat",",",["get",outputProperty],","],["concat",",",["accumulated"],","]],0],["accumulated"],["concat",["accumulated"],",",["get",outputProperty]]],["get",sourceProperty]])},buildKnownBaseMapSpriteImageExpr=e=>{const t=["match",e];for(const i of baseMapPOICategoryValues){const e=`poi-${i}`;t.push(e,["image",e])}return t.push(["image","poi-parking-micro"]),t},isClickEventState=["in",["get","eventState"],["literal",["click","contextmenu"]]],hasActiveEventState=["all",["has","eventState"],["!=",["get","eventState"],"recently-hovered"]],suffixNumber=(e,t)=>`${e}-${t}`,prefixLayerID=(e,t)=>t?`${t}-${e}`:e,mergeLayer=(e,t)=>t?{...e,...t,...t.paint&&{paint:{...e.paint,...t.paint}},...t.layout&&{layout:{...e.layout,...t.layout}}}:e,getThemeAdaptiveConnectionColors=(e,t)=>{const i="dark"===e,r=i?"#1a1a1a":"#ffffff";return t?{lineColor:t,labelColor:darkerShadeOf(t)??t,labelHaloColor:r}:{lineColor:i?"#5AB6F0":"#3f9cd9",labelColor:i?"#A9D6F5":"#1a5f8a",labelHaloColor:r}},buildBaseLineSpec$1=e=>({type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":e,"line-width":1.5,"line-dasharray":[2,2],"line-opacity":.9}}),buildBaseLabelSpec=(e,t)=>({type:"symbol",layout:{"symbol-placement":"line-center","text-field":["get","label"],"text-size":12,"text-offset":[0,-1],"text-allow-overlap":!1,"text-ignore-placement":!1,"text-keep-upright":!0},paint:{"text-color":e,"text-halo-color":t,"text-halo-width":1.5}}),isMainEntryPoint=["==",["get","type"],"main"],buildBaseLineSpec=(e,t)=>({type:"line",minzoom:t,filter:["==",["geometry-type"],"LineString"],layout:{"line-cap":"round"},paint:{"line-color":e,"line-width":1.5,"line-dasharray":[1,2],"line-opacity":.8}}),buildBasePointSpec=(e,t,i)=>({type:"circle",minzoom:i,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":e,"circle-radius":["+",["case",isMainEntryPoint,5,3.5],["case",hasActiveEventState,1.5,0]],"circle-stroke-width":1.5,"circle-stroke-color":t}}),buildEntryPointLayerSpecs=(e,t="light",i=0,r)=>{const{color:o,strokeColor:s}=((e,t)=>{const{lineColor:i,labelColor:r,labelHaloColor:o}=getThemeAdaptiveConnectionColors(e,t);return{color:"dark"===e?i:r,strokeColor:o}})(t,r),a=Math.max(e?.minZoom??15,i);return{line:mergeLayer(buildBaseLineSpec(o,a),e?.layers?.line),point:mergeLayer(buildBasePointSpec(o,s,a),e?.layers?.point)}},placesMarkerTypes=["pin","circle-icon","base-map","pin-clustered"],hasChargingAvailability=e=>Boolean(e&&"availability"in e&&e.availability),isEVStationWithAvailability=e=>"CHARGING_LOCATION"===e.properties.poi?.categories?.[0]&&hasChargingAvailability(e.properties.chargingPark),getChargingPointAvailability=e=>{const t=e.properties.chargingPark;if(hasChargingAvailability(t)){const e=t.availability.chargingPointAvailability,i=e.statusCounts.Available??0;return{availableCount:i,totalCount:e.count,ratio:i/e.count}}},defaultFormatAvailabilityText=(e,t)=>`${e}/${t}`,getAvailabilityRatio=e=>getChargingPointAvailability(e)?.ratio??0,getAvailabilityColorExpression=e=>["case",[">=",["get","evAvailabilityRatio"],e?.threshold??.3],"green","red"],toEntryPointID=(e,t)=>`${e}-entry-point-${t}`,isShownFor=(e,t)=>"all"===e||("selected"===e?void 0!==t:isClickEventType(t)),TEXT_SIZE_RANGE={min:8,max:32,step:1,bounds:"hard-min"},STROKE_WIDTH_RANGE={min:0,max:5,step:.5,bounds:"hard-min"},BADGE_RADIUS_RANGE={min:4,max:32,step:1,bounds:"hard-min"},placesKnobDefinitions={markerType:{kind:"enum",description:"The kind of marker every place is drawn with; `icon.categoryIcons` replace its icon under each.",options:placesMarkerTypes,default:"pin"},color:{kind:"color",description:"Colour of the default pin, the hovered or clicked label, connection lines and entry points. Unset: the map's accent if a theme sets one, else the SDK's own colours."},visible:{kind:"toggle",description:"Everything the module draws: places, connections and entry points. `show()` and `clear()` leave it.",default:!0},"icon.default.style.fillColor":{kind:"color",description:"Fill colour of the default pin, in place of `color`."},"icon.default.style.outlineColor":{kind:"color",description:"Outline colour of the default pin."},"icon.default.style.outlineOpacity":{kind:"number",description:"Outline opacity of the default pin.",range:OPACITY_RANGE},"label.size":{kind:"number",description:"Label size, in pixels. Unset: 14 to 16 as the zoom grows, or the style's POI labels under `base-map`.",range:TEXT_SIZE_RANGE},"label.color":{kind:"color",description:"Label colour. Unset: `#333333`, `#FFFFFF` on a dark map, or the style's POI labels under `base-map`."},"label.haloColor":{kind:"color",description:"Colour of the halo around the labels. Unset: `#FFFFFF`, `#333333` on a dark map."},"label.haloWidth":{kind:"number",description:"Width of the label halo, in pixels. Unset: 1 to 1.5 as the zoom grows.",range:STROKE_WIDTH_RANGE},"label.opacity":{kind:"number",description:"Label opacity.",range:OPACITY_RANGE},"label.offset":{kind:"number",description:"Distance of the label from its icon, in ems. Unset: worked out from the icon's size.",range:{min:0,max:5,step:.1,bounds:"hard-min"}},"label.font":{kind:"enums",description:"Label font faces, in order: the first one available wins. Unset: `Noto-Bold`, or the style's POI labels under `base-map`.",options:mapFonts},"cluster.badge.color":{kind:"color",description:"Fill colour of the cluster count badges; `color` does not reach them.",default:"#000000"},"cluster.badge.strokeColor":{kind:"color",description:"Outline colour of the cluster count badges.",default:"#FFFFFF"},"cluster.badge.strokeWidth":{kind:"number",description:"Outline width of the cluster count badges, in pixels.",range:STROKE_WIDTH_RANGE,default:1.5},"cluster.badge.textColor":{kind:"color",description:"Colour of the count on the cluster badges.",default:"#FFFFFF"},"cluster.badge.textSize":{kind:"number",description:"Size of the count on the cluster badges, in pixels.",range:TEXT_SIZE_RANGE,default:12},"cluster.badge.radius.single":{kind:"number",description:"Radius of the badge in a single-category cluster's corner, in pixels.",range:BADGE_RADIUS_RANGE,default:11},"cluster.badge.radius.mixed":{kind:"number",description:"Radius of the centred badge a mixed-category cluster is drawn as, in pixels.",range:BADGE_RADIUS_RANGE,default:15},"cluster.badge.offset":{kind:"offset",description:"Shift of a single-category cluster's badge from its icon, in pixels; mixed-category badges stay centred.",range:{min:-32,max:32,step:1,bounds:"soft"},default:DEFAULT_SINGLE_BADGE_OFFSET},"cluster.source.clusterRadius":{kind:"number",description:"How near places merge into one cluster, in pixels. Changing it recreates the places source.",range:{min:10,max:200,step:10,bounds:"hard-min"},default:60},"cluster.source.clusterMaxZoom":{kind:"number",description:"Last zoom places cluster at; entry points start one zoom above it.",range:{min:0,max:17,step:1,bounds:"hard"},default:17},"cluster.source.clusterMinPoints":{kind:"number",description:"Fewest places a cluster holds. Unset: MapLibre's, 2.",range:{min:2,max:20,step:1,bounds:"hard-min"}},"evAvailability.enabled":{kind:"toggle",description:"Free and total charging points under each EV station's name, from `getPlacesWithEVAvailability` data.",default:!1},"evAvailability.threshold":{kind:"number",description:"Share of free charging points at or above which a station reads as available.",range:{min:0,max:1,step:.05,bounds:"hard"},default:.3},"entryPoints.showFor":{kind:"enum",description:"Which places have their entry points drawn: all, the hovered or clicked, or the clicked.",options:/* @__PURE__ */everyOf()(["all","selected","clicked"]),default:"selected"},"entryPoints.minZoom":{kind:"number",description:"Lowest zoom entry points are drawn at; under `pin-clustered`, never below the first without clusters.",range:ZOOM_RANGE,default:15}},placesKnobCatalogue=/* @__PURE__ */withIds(placesKnobDefinitions),placesKnobIds=/* @__PURE__ */placesKnobCatalogue.map(({id:e})=>e),mapAccentColor=e=>e.mapColors.accent,onAccentColorChange=(e,t)=>{let i=mapAccentColor(e);e._onMapColorsChange(e=>{e.accent!==i&&(i=e.accent,t())})},incidentColorKnobIds={minor:"traffic.incidents.minorColor",moderate:"traffic.incidents.moderateColor",major:"traffic.incidents.majorColor",indefinite:"traffic.incidents.closedColor"},onStylingKnobsApplied=(e,t,i)=>{e._onStylingApplied(r=>{e.mapReady&&t.some(e=>r.has(e))&&i()})},calculateIconScale=(e,t)=>{if(!e)return;const i=(e=>{try{if("string"==typeof e){if(e.includes("<svg")){const t=parseSvg(e),i=t.getAttribute("viewBox");if(i){const e=i.split(/\s+/);if(4===e.length)return{width:Number.parseFloat(e[2]),height:Number.parseFloat(e[3])}}const r=t.getAttribute("width"),o=t.getAttribute("height");if(r&&o)return{width:Number.parseFloat(r),height:Number.parseFloat(o)}}return null}return e.complete&&e.naturalWidth>0?{width:e.naturalWidth,height:e.naturalHeight}:null}catch(t){return console.warn("Failed to extract image dimensions:",t),null}})(e);if(!i)return;const r="base-map"===t||"circle-icon"===t,o=r?54:140,s=r?54:120;return{heightScale:i.height/o,widthScale:i.width/s}},buildIconOffsetExpression=e=>{const t=["case"];for(const[i,r]of e)0===r.x&&0===r.y||t.push(["==",["get","iconID"],i],["literal",[r.x,r.y]]);if(1!==t.length)return t.push(["literal",[0,0]]),t},labelLayoutProperties=e=>({...void 0!==e?.size&&{"text-size":e.size},...void 0!==e?.font&&{"text-font":e.font}}),labelPaintProperties=e=>({...void 0!==e?.color&&{"text-color":e.color},...void 0!==e?.haloColor&&{"text-halo-color":e.haloColor},...void 0!==e?.haloWidth&&{"text-halo-width":e.haloWidth},...void 0!==e?.opacity&&{"text-opacity":e.opacity}}),round4=e=>Math.round(1e4*e)/1e4,buildAnchorOffsets=(e,t,i,r)=>{const o=void 0!==r;return{top:o?[0,r]:[0,round4(e)],left:o?[r,round4(i)]:[round4(t),round4(i)],right:o?[-r,round4(i)]:[-round4(t),round4(i)]}},getTextOffset=(e,t,i,r)=>{const o=(e=>{if(!e)return.8;if("number"==typeof e)return e;if(Array.isArray(e)){const t=e.at(-1);if("number"==typeof t)return t}if("object"==typeof e&&"stops"in e){const t=e.stops;if(Array.isArray(t)&&t.length>0){const e=t.at(-1);if(Array.isArray(e)&&"number"==typeof e[1])return e[1]}}return.8})(e)/.8,s="base-map"===i||"circle-icon"===i;if(s&&void 0!==r)return{"text-offset":[r,r]};const a=1.4*o,n=buildAnchorOffsets(.7*o,a,s?0:-a,r),l=["top",n.top,"left",n.left,"right",n.right];if(0===t.size)return{"text-variable-anchor-offset":l};const c=["case"];for(const[d,p]of t.entries()){const e=(s?1.4:.7)*p.heightScale*o,t=1.4*p.widthScale*o,i=buildAnchorOffsets(e,t,s?0:-t,r);c.push(["==",["get","iconID"],d],["literal",["top",i.top,"left",i.left,"right",i.right]])}return c.push(["literal",l]),{"text-variable-anchor-offset":c}},buildLayoutConfig=(e,t,i,r,o)=>{const s=t?.label,a=t?.layers?.[i],n=o&&o.size>0,l={...e.layout},c=n||void 0!==s?.offset||"circle-icon"===t?.markerType;c&&(delete l["text-offset"],delete l["text-variable-anchor-offset"],delete l["text-radial-offset"]);const d={...l,...labelLayoutProperties(s),...void 0!==r&&{"text-field":r},...a?.layout};if(c){const e={...d,...getTextOffset(d["icon-size"],o??/* @__PURE__ */new Map,t?.markerType,s?.offset)},r="micro"!==i&&o&&buildIconOffsetExpression([...o].map(([e,{offset:t}])=>[e,t]));return r?{...e,"icon-offset":r}:e}return d},buildPaintConfig=(e,t,i,r)=>{const o=t?.layers?.[i],{textColor:s,haloColor:a}=(e=>({textColor:"dark"===e?"#FFFFFF":"#333333",haloColor:"dark"===e?"#333333":"#FFFFFF"}))(r),n=e.paint??{};return{...n,...void 0===n["text-color"]&&{"text-color":s},...void 0===n["text-halo-color"]&&{"text-halo-color":a},...labelPaintProperties(t?.label),...o?.paint}},poiLookKnobIds=["labels.sizeFactor","symbols.sizeFactor","pois.sizeFactor","pois.labelColor","pois.labelOutlineColor"],getTextSizeSpec=e=>JSON.parse(JSON.stringify(e)?.replaceAll("name",TITLE)),findStyleLayer=(e,t)=>e.getStyle().layers.find(e=>e.id===t)??{},buildBaseMapPOILayerFoundation=e=>({filter:["!",isClickEventState],type:"symbol",paint:e.paint,layout:e.layout?omit(e.layout,"visibility"):void 0}),buildBaseMapPOILayerSpec=e=>{const t=buildBaseMapPOILayerFoundation(findStyleLayer(e,"POI")),i=t.layout?.["text-size"];return{...t,layout:{...t.layout,"icon-image":["get","iconID"],"text-field":["get",TITLE],...i&&{"text-size":getTextSizeSpec(i)}}}},buildPOIMicroLikeLayerSpec=e=>{const t=buildBaseMapPOILayerFoundation(findStyleLayer(e,"POI - Micro"));return{...t,minzoom:0,layout:{...t.layout,"icon-allow-overlap":!0,"icon-ignore-placement":!0},paint:{...t.paint,"icon-opacity":1}}},buildCircleBaseLayerSpec=e=>{const t=findStyleLayer(e,"POI").layout??{};return{...pinLayerBaseSpec,layout:{...pinLayerBaseSpec.layout,"icon-anchor":"center",...void 0!==t["icon-size"]&&{"icon-size":t["icon-size"]},...void 0!==t["icon-padding"]&&{"icon-padding":t["icon-padding"]}},paint:{...pinLayerBaseSpec.paint,"icon-translate":[0,0]}}},HIDDEN_LAYER_SPEC={type:"symbol",layout:{visibility:"none"}},HIDDEN_CIRCLE_LAYER_SPEC={type:"circle",layout:{visibility:"none"}},poiLookMarkerTypes=/* @__PURE__ */new Set(["base-map","circle-icon","pin-clustered"]),pinLayerSpec={...pinLayerBaseSpec,filter:["!",hasActiveEventState]},selectedPinLayerSpec=(e="#3f9cd9")=>({...pinLayerBaseSpec,filter:hasActiveEventState,layout:{...pinLayerBaseSpec.layout,"icon-size":SELECTED_PIN_ICON_SIZE,"text-allow-overlap":!0},paint:{...pinLayerBaseSpec.paint,"text-color":e}}),toSelectedPOILikeSpec=(e,t)=>({...e,filter:hasActiveEventState,layout:{...e.layout,"text-allow-overlap":!0},paint:{...e.paint,"text-color":t}}),withConfig=(e,t,i,r,o)=>{const s=t?.label,a=t?.layers?.[i],n=!0===t?.evAvailability?.enabled,l=s?.title&&"function"!=typeof s?.title?s.title:n?((e,t)=>t?["case",["has","evAvailabilityText"],["format",["get",TITLE],{},"\n",{},["get","evAvailabilityText"],{"font-scale":1.1,"text-color":getAvailabilityColorExpression(e?.evAvailability)}],["get",TITLE]]:["get",TITLE])(t,n):void 0;return{...e,...a,layout:buildLayoutConfig(e,t,i,l,o),paint:buildPaintConfig(e,t,i,r)}},buildPlacesLayerSpecs=(e,t,i,r,o="#3f9cd9")=>{const s=((e,t)=>{const i=/* @__PURE__ */new Map,r=e?.icon?.categoryIcons??[];for(const o of r)if(o.image){const r=calculateIconScale(o.image,e?.markerType),s=void 0!==o.offsetX||void 0!==o.offsetY;if(void 0===r&&!s)continue;const a={heightScale:r?.heightScale??1,widthScale:r?.widthScale??1,offset:{x:o.offsetX??0,y:o.offsetY??0}},n=suffixNumber(o.id,t);if(i.set(n,a),o.availabilityLevel){const e=suffixNumber(`${o.id}-${o.availabilityLevel}`,t);i.set(e,a)}}return i})(e,r);let a,n,l=HIDDEN_LAYER_SPEC,c=HIDDEN_LAYER_SPEC,d=HIDDEN_CIRCLE_LAYER_SPEC,p=HIDDEN_LAYER_SPEC,u=HIDDEN_CIRCLE_LAYER_SPEC,h=HIDDEN_LAYER_SPEC;if("base-map"===e?.markerType)a={...buildBaseMapPOILayerSpec(t),minzoom:10},l=buildPOIMicroLikeLayerSpec(t),n=((e,t)=>toSelectedPOILikeSpec(buildBaseMapPOILayerSpec(e),t))(t,o);else if("circle-icon"===e?.markerType)a=(e=>({...buildCircleBaseLayerSpec(e),filter:["!",hasActiveEventState]}))(t),n=((e,t)=>toSelectedPOILikeSpec(buildCircleBaseLayerSpec(e),t))(t,o);else if("pin-clustered"===e?.markerType){a={...pinLayerSpec,filter:["all",isNotClusterFilter,["!",hasActiveEventState]]},n={...selectedPinLayerSpec(o),filter:["all",isNotClusterFilter,hasActiveEventState]};const i=buildPOIMicroLikeLayerSpec(t);l={...i,filter:i.filter?["all",isNotClusterFilter,i.filter]:isNotClusterFilter};const r=e?.cluster?.badge;c={type:"symbol",filter:isSingleCategoryClusterFilter,layout:{"icon-image":buildKnownBaseMapSpriteImageExpr(["get","clusterBaseMapIconIDs"]),"icon-size":1,"icon-allow-overlap":!0,"icon-ignore-placement":!0}},d=(e=>({type:"circle",filter:isSingleCategoryClusterFilter,paint:{...badgeCirclePaint(e,e?.radius?.single??11),"circle-translate":singleBadgeOffset(e),"circle-translate-anchor":"viewport"}}))(r),p=(e=>({type:"symbol",filter:isSingleCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":e?.textColor??"#FFFFFF","text-translate":singleBadgeOffset(e),"text-translate-anchor":"viewport"}}))(r),u=(e=>({type:"circle",filter:isMixedCategoryClusterFilter,paint:badgeCirclePaint(e,e?.radius?.mixed??15)}))(r),h=(e=>({type:"symbol",filter:isMixedCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":e?.textColor??"#FFFFFF"}}))(r)}else a=pinLayerSpec,n=selectedPinLayerSpec(o);return{micro:{...withConfig(l,e,"micro",i,s),beforeID:mapStyleLayerIDs.lowestPlaceLabel},main:{...withConfig(a,e,"main",i,s),beforeID:"selected"},selected:withConfig(n,e,"selected",i,s),cluster:{...mergeLayer(c,e?.layers?.cluster),beforeID:"clusterBadge"},clusterBadge:{...mergeLayer(d,e?.layers?.clusterBadge),beforeID:"clusterCount"},clusterCount:{...mergeLayer(p,e?.layers?.clusterCount),beforeID:"clusterMixedBadge"},clusterMixedBadge:{...mergeLayer(u,e?.layers?.clusterMixedBadge),beforeID:"clusterMixedCount"},clusterMixedCount:mergeLayer(h,e?.layers?.clusterMixedCount),...e?.layers?.additional}},resolveEndpoint=(e,t)=>"string"!=typeof e?e:t.features.find(t=>t.id===e),supportedPinSubcategories=/* @__PURE__ */new Set([7339002,8099002,7369004,7321003,7376006,9362003,9362004,9160004,9376007,7315015,9376006,9376002,7315078,7315149,9376005,7372003,9352045,9352032,9361048,9902003,9378005,7383004,9910004,7320002,9362016,7320003,9362025,9942002,9942003,7380005,9663003,9361021,9379009,9379004,7315147,9376003,9160002,9160003,9352008,9361006,7389004,9910006]),pinImageSubstitutes=new Map([["ADVENTURE_SPORTS_FACILITY","SPORTS_CENTER"],["COMMUNITY_CENTER","CULTURAL_CENTER"],["EMBASSY","GOVERNMENT_OFFICE"],["EMERGENCY_MEDICAL_SERVICE","EMERGENCY_ROOM"],["ENTERTAINMENT","NIGHTLIFE"],["RESIDENTIAL_ENTRANCE","RESIDENTIAL_ACCOMMODATION"]].map(([e,t])=>[poiCategoriesToID[e],poiCategoriesToID[t]])),buildPlaceTitle=e=>e.properties.poi?.name??e.properties.address.freeformAddress,toImageID=(e,t,i)=>{if("pin"===t||"pin-clustered"===t)return(e=>{if(!e)return;const t=supportedPinSubcategories.has(e)?e:Number(e.toString().substring(0,4));return toPinSpriteImageID(String(pinImageSubstitutes.get(t)??t))})(poiCategoriesToID[e])??i;{const t=toBaseMapPOICategory(e);return t?`poi-${t}`:i}},getIconIDForPlace=(e,t,i={})=>{const r=i.markerType??"pin",o=((e,t)=>e.icon?.default||"base-map"!==(e.markerType??"pin")?suffixNumber("default_place",t):"poi-parking-micro")(i,t),s=i.icon?.mapping;if(s)return"imageID"===s.to?s.fn(e):toImageID(s.fn(e),r,o);const a=e.properties.poi?.categories?.[0],n=((e,t,i,r,o)=>{if(!r.evAvailability?.enabled||!isEVStationWithAvailability(e))return;const s=getAvailabilityRatio(e)>=(r.evAvailability.threshold??.3)?"available":"occupied",a=r.icon?.categoryIcons&&r.icon.categoryIcons.length>0,n=r.icon?.categoryIcons?.find(e=>e.id===t&&e.availabilityLevel===s);return n?suffixNumber(`${n.id}-${s}`,i):a||"pin"!==o?void 0:toPinSpriteImageID(`7309-${s}`)})(e,a,t,i,r);if(n)return n;const l=i.icon?.categoryIcons?.find(e=>e.id===a);return l?suffixNumber(l.id,t):toImageID(a,r,o)},getEffectivePOICategory=(e,t)=>{const i=t?.icon?.mapping;return"poiCategory"===i?.to?i.fn(e):e.properties.poi?.categories?.[0]},getPOILayerCategoryForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&toBaseMapPOICategory(i)},getPOIGroupForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&toBaseMapPOIGroup(i)},toPlaces=e=>Array.isArray(e)?{type:"FeatureCollection",features:e}:"Feature"===e.type?{type:"FeatureCollection",features:[e]}:e,mergeEVAvailabilityProps=(e,t,i)=>{if(!0!==t?.enabled)return e;let r=!1,o=!1;for(const s of i.features)if("CHARGING_LOCATION"===s.properties.poi?.categories?.[0]&&(r=!0,isEVStationWithAvailability(s))){o=!0;break}return r&&!o&&console.warn("PlacesModule: evAvailability is enabled but no availability data found. Did you call getPlacesWithEVAvailability()?"),{...e,evAvailabilityText:e=>isEVStationWithAvailability(e)?((e,t)=>{const i=getChargingPointAvailability(e);return i?(t?.formatText??defaultFormatAvailabilityText)(i.availableCount,i.totalCount):""})(e,t):"",evAvailabilityRatio:e=>isEVStationWithAvailability(e)?getAvailabilityRatio(e):0}},getBaseMapIconIDForPlace=(e,t)=>{const i=getPOILayerCategoryForPlace(e,t);return i?`poi-${i}`:"poi-parking-micro"},preparePlacesForInstance=(e,t,i={})=>{const r=toPlaces(e),o=!0===i.evAvailability?.enabled?mergeEVAvailabilityProps(i.extraFeatureProps,i.evAvailability,r):i.extraFeatureProps;return{...r,features:r.features.map(e=>{const r="function"==typeof i?.label?.title?i?.label?.title(e):buildPlaceTitle(e),s=o?Object.fromEntries(Object.entries(o).map(([t,i])=>[t,"function"==typeof i?i(e):i])):{},a=e.id??generateId();return{...e,id:a,geometry:{...e.geometry,bbox:e.bbox},properties:{...e.properties,id:a,title:r,iconID:getIconIDForPlace(e,t,i),...("base-map"===i?.markerType||"pin-clustered"===i?.markerType)&&{category:getPOILayerCategoryForPlace(e,i),group:getPOIGroupForPlace(e,i)},..."pin-clustered"===i?.markerType&&{baseMapIconID:getBaseMapIconIDForPlace(e,i)},...s}}})}},preparePlacesForDisplay=(e,t={})=>preparePlacesForInstance(e,0,t),PlacesModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t),this.refreshingEntryPoints=!1,this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&this.updateLayersAndData(this.config)}),onStylingKnobsApplied(e,poiLookKnobIds,()=>{this.config?.markerType&&poiLookMarkerTypes.has(this.config.markerType)&&this.updatePlacesLayers(this.config)})}colorOf(e){return e?.color??mapAccentColor(this.tomtomMap)}_initSourcesWithLayers(e,t){t||(this.sourceID=`places-${this.instanceIndex}`,this.unclusteredSourceID=`places-${this.instanceIndex}-unclustered`,this.connectionSourceID=`places-connections-${this.instanceIndex}`,this.entryPointSourceID=`places-entry-points-${this.instanceIndex}`,this.layerIDPrefix=this.sourceID,this.defaultPlaceIconID=suffixNumber("default_place",this.instanceIndex),this.shownConnections=[]),this.layerSpecs=this.buildLayerSpecs(e);const i=this.buildClusterOptions(e);this.currentClusterOptions=i;const r=this.partitionSpecsForSources(this.layerSpecs),o=new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,r.clusteredSpecs,!1,i);let s;r.unclusteredSpecs.length>0&&(s=new GeoJSONSourceWithLayers(this.mapLibreMap,this.unclusteredSourceID,r.unclusteredSpecs,!1)),addLayers([...o._layerSpecs,...s?._layerSpecs??[]],this.mapLibreMap),this.connectionLayerSpecs=this.buildConnectionLayerSpecs(e);const a=this.addOverlaySource(this.connectionSourceID,this.connectionLayerSpecs);this.entryPointLayerSpecs=this.buildEntryPointLayerSpecs(e);const n=this.addOverlaySource(this.entryPointSourceID,this.entryPointLayerSpecs),l=()=>{(this.config?.entryPoints||n.shownFeatures.features.length)&&this.updateEntryPointsData(this.config)};return o.onShow(l),n.onShow(l),s?{places:o,placesUnclustered:s,connections:a,entryPoints:n}:{places:o,connections:a,entryPoints:n}}addOverlaySource(e,t){const i=new GeoJSONSourceWithLayers(this.mapLibreMap,e,Object.values(t),!1);return addLayers(i._layerSpecs,this.mapLibreMap),i}replaceLayerSpecs(e,t,i){return updateLayersAndSource(Object.values(e),Object.values(t),i,this.mapLibreMap),e}partitionSpecsForSources(e){if(!this.currentClusterOptions)return{clusteredSpecs:Object.values(e),unclusteredSpecs:[]};const t=[],i=[];for(const[r,o]of Object.entries(e))"micro"===r?t.push(o):i.push(o);return{clusteredSpecs:i,unclusteredSpecs:t}}buildLayerSpecs(e){const t=buildPlacesLayerSpecs(e,this.tomtomMap.mapLibreMap,this.tomtomMap.styleLightDarkTheme,this.instanceIndex,this.colorOf(e)),i=new Set(Object.keys(t));return Object.fromEntries(Object.entries(t).map(([e,t])=>{const r=t.beforeID;return[e,{...t,id:`${this.layerIDPrefix}-${e}`,...r&&i.has(r)?{beforeID:`${this.layerIDPrefix}-${r}`}:{}}]}))}buildClusterOptions(e){if("pin-clustered"!==e?.markerType)return;const t=e.cluster?.source;return{clusterRadius:60,clusterMaxZoom:17,...t,cluster:!0,clusterProperties:{...t?.clusterProperties,...clusteredPlacesAggregateProperties}}}buildConnectionLayerSpecs(e){const t=((e,t,i="light")=>{const{lineColor:r,labelColor:o,labelHaloColor:s}=getThemeAdaptiveConnectionColors(i,t);return{line:mergeLayer(buildBaseLineSpec$1(r),e?.layers?.line),label:mergeLayer(buildBaseLabelSpec(o,s),e?.layers?.label)}})(e?.connections,this.colorOf(e),this.tomtomMap.styleLightDarkTheme),i=`${this.layerIDPrefix}-connection-line`,r=`${this.layerIDPrefix}-connection-label`,o=mapStyleLayerIDs.lowestLabel;return{line:{...t.line,id:i,beforeID:o},label:{...t.label,id:r,beforeID:o}}}buildEntryPointLayerSpecs(e){const t=this.buildClusterOptions(e),i=t?(t.clusterMaxZoom??17)+1:0,r=buildEntryPointLayerSpecs(e?.entryPoints,this.tomtomMap.styleLightDarkTheme,i,this.colorOf(e));return{line:{...r.line,id:`${this.layerIDPrefix}-entry-point-line`,beforeID:this.layerSpecs.main.id},point:{...r.point,id:`${this.layerIDPrefix}-entry-point`,beforeID:this.layerSpecs.cluster.id}}}_applyConfig(e){return this.updateLayersAndData(e),e}discardShownData(){this.shownConnections=[]}restoreDataAndConfigImpl(){const e=this.sourcesWithLayers.places.shownFeatures,t=this.shownConnections;this.initSourcesWithLayers(this.config,!0),this.config&&this._applyConfig(this.config),this.show(e),t.length&&this.showConnections(t)}applyMarkerType(e){this.applyConfigPart({markerType:e})}applyIconConfig(e){this.applyConfigPart({icon:e})}applyLabelConfig(e){this.applyConfigPart({label:e})}applyConfigPart(e){const t={...this.config,...e};this.updateLayersAndData(t),this.config=t,this.emitConfigChange()}applyExtraFeatureProps(e){const t={...this.config,extraFeatureProps:e};this.updateData(t),this.config=t,this.emitConfigChange()}applyVisibility(e){this.applyPlacesVisibility(e),this.applyVisibilityTo(Object.values(this.connectionLayerSpecs),!!this.sourcesWithLayers.connections.shownFeatures.features.length,e),this.applyVisibilityTo(Object.values(this.entryPointLayerSpecs),!!this.sourcesWithLayers.entryPoints.shownFeatures.features.length,e)}updateLayersAndData(e){this.setupImages(e),isEqual(this.buildClusterOptions(e),this.currentClusterOptions)?(this.updatePlacesLayers(e),this.applyPlacesVisibility(e),this.updateData(e),this.connectionLayerSpecs=this.replaceLayerSpecs(this.buildConnectionLayerSpecs(e),this.connectionLayerSpecs,this.sourcesWithLayers.connections),this.updateConnectionsData(e),this.entryPointLayerSpecs=this.replaceLayerSpecs(this.buildEntryPointLayerSpecs(e),this.entryPointLayerSpecs,this.sourcesWithLayers.entryPoints),this.updateEntryPointsData(e)):this.rebuildSourcesAndLayers(e)}updatePlacesLayers(e){const t=this.buildLayerSpecs(e),i=this.currentClusterOptions?this.partitionSpecsForSources(t):{clusteredSpecs:Object.values(t),unclusteredSpecs:[]},r=this.currentClusterOptions?this.partitionSpecsForSources(this.layerSpecs):{clusteredSpecs:Object.values(this.layerSpecs),unclusteredSpecs:[]};updateLayersAndSource(i.clusteredSpecs,r.clusteredSpecs,this.sourcesWithLayers.places,this.mapLibreMap),this.sourcesWithLayers.placesUnclustered&&i.unclusteredSpecs.length>0&&updateLayersAndSource(i.unclusteredSpecs,r.unclusteredSpecs,this.sourcesWithLayers.placesUnclustered,this.mapLibreMap),this.layerSpecs=t}rebuildSourcesAndLayers(e){const t=this.sourcesWithLayers.places.shownFeatures,i=this.shownConnections,r=this.mapLibreMap;for(const s of[...Object.values(this.layerSpecs),...Object.values(this.connectionLayerSpecs),...Object.values(this.entryPointLayerSpecs)])r.getLayer(s.id)&&r.removeLayer(s.id);for(const s of[this.sourceID,this.unclusteredSourceID,this.connectionSourceID,this.entryPointSourceID])r.getSource(s)&&r.removeSource(s);this.initSourcesWithLayers(e,!0),this.setupImages(e);const o=preparePlacesForInstance(t,this.instanceIndex,e);this.sourcesWithLayers.places.show(o,{automaticVisibility:!1}),this.sourcesWithLayers.placesUnclustered?.show(o,{automaticVisibility:!1}),this.applyPlacesVisibility(e),i.length&&(this.shownConnections=[...i],this.updateConnectionsData(e)),this.updateEntryPointsData(e)}updateConnectionsData(e){const t=this.sourcesWithLayers.places.shownFeatures,i=((e,t,i={})=>{const r=i.connections?.label,o=[];for(const s of e){const e=resolveEndpoint(s.from,t),i=resolveEndpoint(s.to,t);if(!e||!i)continue;const a=s.id??generateId(),n=r?r(s):"";o.push({type:"Feature",id:a,geometry:{type:"LineString",coordinates:[e.geometry.coordinates,i.geometry.coordinates]},properties:{id:a,fromId:"string"==typeof s.from?s.from:e.id,toId:"string"==typeof s.to?s.to:i.id,label:n}})}return{type:"FeatureCollection",features:o}})(this.shownConnections,t,e);this.sourcesWithLayers.connections.show(i,{automaticVisibility:!1}),this.applyVisibilityTo(Object.values(this.connectionLayerSpecs),!!i.features.length,e)}updateEntryPointsData(e){if(!this.refreshingEntryPoints){this.refreshingEntryPoints=!0;try{const t=this.sourcesWithLayers.entryPoints,i=((e,t,i)=>{const r=[];if(!i)return{type:"FeatureCollection",features:r};const o=i.showFor??"selected",s=/* @__PURE__ */new Map;for(const a of t.features)a.properties.eventState&&s.set(a.properties.id,a.properties.eventState);for(const a of e.features){const e=a.properties.id,t=a.properties.entryPoints??[],i=t.map((t,i)=>toEntryPointID(e,i));if(isShownFor(o,a.properties.eventState)||i.some(e=>isShownFor(o,s.get(e))))for(const[o,{position:n,...l}]of t.entries()){const t=i[o],c=s.get(t),d={...l,id:t,placeID:e,entryPointIndex:o};r.push({type:"Feature",id:t,geometry:{type:"Point",coordinates:n},properties:c?{...d,eventState:c}:d},{type:"Feature",id:t,geometry:{type:"LineString",coordinates:[a.geometry.coordinates,n]},properties:d})}}return{type:"FeatureCollection",features:r}})(this.sourcesWithLayers.places.shownFeatures,t.shownFeatures,e?.entryPoints);t.show(i,{automaticVisibility:!1}),this.applyVisibilityTo(Object.values(this.entryPointLayerSpecs),!!i.features.length,e)}finally{this.refreshingEntryPoints=!1}}}applyVisibilityTo(e,t,i){applyLayersVisibility(e,t&&!1!==i?.visible,this.mapLibreMap)}applyPlacesVisibility(e){this.applyVisibilityTo(Object.values(this.layerSpecs),!!this.sourcesWithLayers.places.shownFeatures.features.length,e)}setupImages(e){this.addCategoryIcons(e?.icon?.categoryIcons??[]),this.addDefaultIcon(e?.icon?.default,this.colorOf(e))}addCategoryIcons(e){for(const{id:t,availabilityLevel:i,image:r,pixelRatio:o=2}of e){if(!r)continue;addOrUpdateImage("if-not-in-sprite",suffixNumber(i?`${t}-${i}`:t,this.instanceIndex),r,this.mapLibreMap,{pixelRatio:o})}}addDefaultIcon(e,t){const i=e?.image;if(i?.image)return this.paintedPinStyle=void 0,void addOrUpdateImage("if-not-in-sprite",this.defaultPlaceIconID,i.image,this.mapLibreMap,{pixelRatio:i.pixelRatio??2});const r={fillColor:t,...e?.style};this.mapLibreMap.hasImage(this.defaultPlaceIconID)&&isEqual(r,this.paintedPinStyle)||(this.paintedPinStyle=r,addOrUpdateImage("add-or-update",this.defaultPlaceIconID,(e=>{if(isDOMImageSupported())return svgToImg(pinSvg(e))})(r),this.mapLibreMap,{pixelRatio:2}))}updateData(e){const t=preparePlacesForInstance(this.sourcesWithLayers.places.shownFeatures,this.instanceIndex,e);this.sourcesWithLayers.places.source.runtimeSource?.setData(t),this.sourcesWithLayers.placesUnclustered?.source.runtimeSource?.setData(t)}async show(e){await this.waitUntilModuleReady(),this.clearConnectionsSync(),this.sourcesWithLayers.entryPoints.clear();const t=preparePlacesForInstance(e,this.instanceIndex,this.config);this.sourcesWithLayers.places.show(t,{automaticVisibility:!1}),this.sourcesWithLayers.placesUnclustered?.show(t,{automaticVisibility:!1}),this.applyPlacesVisibility(this.config);for(const i of this.shownFeaturesHandlers)i({places:e})}async clear(){await this.waitUntilModuleReady(),this.clearConnectionsSync(),this.sourcesWithLayers.places.clear(),this.sourcesWithLayers.placesUnclustered?.clear()}async showConnections(e){await this.waitUntilModuleReady(),this.shownConnections=[...e],this.updateConnectionsData(this.config);for(const t of this.shownFeaturesHandlers)t({connections:e})}async clearConnections(){await this.waitUntilModuleReady(),this.clearConnectionsSync()}clearConnectionsSync(){this.shownConnections=[],this.sourcesWithLayers.connections?.clear()}getShown(){return{places:this.sourcesWithLayers.places.shownFeatures,connections:[...this.shownConnections]}}putEventState(e){this.sourcesWithLayers.places.putEventState(e)}cleanEventState(e){this.sourcesWithLayers.places.cleanEventState(e)}cleanEventStates(e){this.sourcesWithLayers.places.cleanEventStates(e)}get events(){const e=["places","placesUnclustered"];return this.buildEvents(this.moduleEventsWithShown([...e,"connections","entryPoints"],this.shownFeaturesHandlers),{places:this.userEvents(e),connections:this.userEvents(["connections"]),entryPoints:this.userEvents(["entryPoints"],{mapping:e=>((e,t)=>{const i=e.properties;return{type:"Feature",id:i.id,geometry:{type:"Point",coordinates:(r=e.geometry,"Point"===r.type?r.coordinates:r.coordinates[1])},properties:{...i,place:findFeatureByRefId(t.features,i.placeID)?.feature}};var r})(e,this.sourcesWithLayers.places.shownFeatures)})})}},poisMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:e.geometry,properties:{id:String(t?.id),name:t?.name,category:t?.category,group:t?.group,priority:t?.priority}}},getStyleCategories=e=>{const t=e.flatMap(e=>(e=>e in poiCategoryGroups)(e)?poiCategoryGroups[e].map(toBaseMapPOICategory):[toBaseMapPOICategory(e)]);return[...new Set(t.filter(e=>!isNil(e)))]},POIsModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTiles");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTiles`);return{poi:new StyleSourceWithLayers(this.mapLibreMap,t,e=>poiLayerIDs.includes(e.id))}}_applyConfig(e){return e&&!isNil(e.visible)?this._setVisible(e.visible,!1):this._initializing||this.isVisible()||this._setVisible(!0,!1),this._filterCategories(e?.filters?.categories,!1),e}isVisible(){return this.config?.visible??this.sourcesWithLayers.poi.isAnyLayerVisible()}setVisible(e){this._setVisible(e)}_setVisible(e,t=!0){if(this.tomtomMap.mapReady)for(const i of this.sourcesWithLayers.poi.sourceAndLayerIDs.layerIDs)this.visibilityComposer.setVisible(i,"pois.visible",e);t&&(this.config={...this.config,visible:e},this.emitConfigChange())}filterCategories(e){this._filterCategories(e)}_filterCategories(e,t=!0){if(e){if(this.tomtomMap.mapReady){const t=isCompleteValuesFilter(e)?buildMappedValuesFilter("category",e.show,getStyleCategories(e.values)):void 0;this.filterComposer.setClause(mapStyleLayerIDs.poi,"pois.categories",t)}t&&(this.config={...this.config,filters:{categories:e}})}else this.categoriesFilter&&(t&&(this.config={...this.config,filters:{categories:{show:"all-except",values:[]}}}),this.tomtomMap.mapReady&&this.filterComposer.setClause(mapStyleLayerIDs.poi,"pois.categories",void 0));this.categoriesFilter=e,t&&this.emitConfigChange()}getShown(){return{poi:this.mapLibreMap.queryRenderedFeatures({layers:this.sourcesWithLayers.poi.sourceAndLayerIDs.layerIDs,validate:!1}).map(poisMapping)}}get events(){return this.moduleEvents(["poi"],{mapping:poisMapping})}},sourceOf=e=>"source"in e&&"string"==typeof e.source?e.source:void 0,matchesOneOf=(e,t)=>!e||void 0!==t&&e.includes(t),matchesLayerSelector=(e,t,i)=>matchesOneOf(e.metadataGroups,(e=>{const t=e.metadata;if(t&&"object"==typeof t&&"group"in t){const e=t.group;return"string"==typeof e?e:void 0}})(t))&&matchesOneOf(e.layerTypes,t.type)&&matchesOneOf(e.sources,sourceOf(t))&&matchesOneOf(e.sourceTypes,((e,t)=>{const i=sourceOf(e);return void 0===i?void 0:t?.[i]?.type})(t,i))&&matchesOneOf(e.sourceLayers,(e=>"source-layer"in e&&"string"==typeof e["source-layer"]?e["source-layer"]:void 0)(t))&&((e,t)=>{const i=t.id.toLowerCase(),r=e=>i.includes(e.toLowerCase());return!(e.idIncludes&&!e.idIncludes.some(r)||e.idExcludes?.some(r))})(e,t),matchesAnyLayerSelector=(e,t,i)=>e.some(e=>matchesLayerSelector(e,t,i)),baseMapLayerGroupNames=["land","water","buildings2D","roads","railways","ferries","borders","buildings3D","natureLabels","roadLabels","roadShields","houseNumbers","smallerTownLabels","stateLabels","cityLabels","allPlaceLabels","capitalLabels","countryLabels"],layerGroupMappings={land:{metadataGroups:["area","background"]},water:{metadataGroups:["water"]},natureLabels:{metadataGroups:["label"]},roads:{metadataGroups:["road","road_area","transit_area"],idExcludes:["railway","subway","aerialway","ferry"]},railways:{metadataGroups:["road"],layerTypes:["line"],idIncludes:["railway","subway","aerialway"]},ferries:{metadataGroups:["road"],layerTypes:["line"],idIncludes:["ferry"]},buildings2D:{metadataGroups:["building"],layerTypes:["fill","line"]},buildings3D:{metadataGroups:["area_3d","building"],layerTypes:["fill-extrusion"]},borders:{metadataGroups:["border","border_label"]},roadLabels:{metadataGroups:["road_label"],idExcludes:["shield"]},roadShields:{metadataGroups:["road_label"],idIncludes:["shield"]},houseNumbers:{metadataGroups:["address_point_label"]},allPlaceLabels:{metadataGroups:["places_label"]},smallerTownLabels:{metadataGroups:["places_label"],idIncludes:["neighbourhood","village","hamlet","town"]},cityLabels:{metadataGroups:["places_label"],idIncludes:["city"]},capitalLabels:{metadataGroups:["places_label"],idIncludes:["capital"]},stateLabels:{metadataGroups:["places_label"],idIncludes:["state"]},countryLabels:{metadataGroups:["places_label"],idIncludes:["country"]}},isMatching=(e,t)=>matchesLayerSelector(layerGroupMappings[e],t),baseMapLayerGroupSelector=e=>layerGroupMappings[e],buildLayerGroupFilter=e=>{const t=e.mode,i=e.names;return"include"===t?e=>i.some(t=>isMatching(t,e)):"exclude"===t?e=>!i.some(t=>isMatching(t,e)):(console.error("Unrecognized layer group mode:",t),()=>!0)},baseMapLayerFilter=e=>!poiLayerIDs.includes(e.id),groupNames=new Set(baseMapLayerGroupNames),isGroupName=e=>groupNames.has(e),groupsVisible=(e,t)=>Object.fromEntries(e.map(e=>[e,{visible:t}])),groupEntries=e=>Object.keys(e??{}).filter(isGroupName).flatMap(t=>{const i=e?.[t];return i?[[t,i.visible]]:[]}),containsAll=(e,t)=>t.every(t=>e.includes(t)),groupsAsRecorded=(e,t,i)=>{const r=t.flatMap(e=>i[e]),o=/* @__PURE__ */new Map,s=(e,t)=>{o.delete(e),o.set(e,t)};for(const a of t)s(a,e?.visible);for(const[a,n]of groupEntries(e?.groups)){const e=containsAll(r,i[a])?[a]:t.filter(e=>containsAll(i[a],i[e]));for(const t of e)s(t,n)}return Object.fromEntries([...o].map(([e,t])=>[e,void 0===t?{}:{visible:t}]))},BaseMapModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t),this.takeoverListeners=[]}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTiles");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTiles`);const i=new StyleSourceWithLayers(this.mapLibreMap,t,baseMapLayerFilter);return this.layersByGroup=void 0,this.knobVisibility=/* @__PURE__ */new Map,{vectorTiles:i}}_applyConfig(e){return!e&&this._initializing||this.writeVisibility(e),e}isVisible(e){const t=this.layerSettings(this.config,e?.layerGroups&&buildLayerGroupFilter(e.layerGroups));return[...t.values()].includes(!0)||this.sourcesWithLayers.vectorTiles.isAnyLayerVisible(e=>t.has(e.id)&&void 0===t.get(e.id))}setVisible(e,t){const i=t?.layerGroups,r=(e=>e?"include"===e.mode?e.names:baseMapLayerGroupNames.filter(t=>!e.names.includes(t)):baseMapLayerGroupNames)(i);for(const o of r)this.knobVisibility.delete(o);this.applyConfig(i?((e,{mode:t,names:i},r,o)=>"exclude"===t?{...e,visible:r,groups:groupsAsRecorded(e,i,o)}:{...e,groups:{...omit(e?.groups,i),...groupsVisible(i,r)}})(this.config,i,e,this.groupedLayers()):{...omit(this.config,"groups"),visible:e});for(const o of this.takeoverListeners)o(r)}_applyKnobVisibility(e,t){this.knobVisibility.delete(e),void 0!==t&&this.knobVisibility.set(e,t),this.writeVisibility(this.config,buildLayerGroupFilter({mode:"include",names:[e]}))}_onGroupsTakenOver(e){this.takeoverListeners.push(e)}writeVisibility(e,t){if(this.tomtomMap.mapReady)for(const[i,r]of this.layerSettings(e,t))this.visibilityComposer.setVisible(i,"baseMap.visible",r)}layerSettings(e,t){const i=this.groupedLayers(),r=/* @__PURE__ */new Map;for(const[s,a]of[...groupEntries(e?.groups),...this.knobVisibility])for(const e of i[s])r.set(e,a);const o=/* @__PURE__ */new Map;for(const s of this.sourcesWithLayers.vectorTiles._layerSpecs)t&&!t(s)||o.set(s.id,r.has(s.id)?r.get(s.id):e?.visible);return o}getLayers(){return mapValues(this.groupedLayers(),e=>[...e])}getLayerIds(e){return[...this.groupedLayers()[e]]}groupedLayers(){return this.layersByGroup??=(e=>{const t=Object.fromEntries(baseMapLayerGroupNames.map(e=>[e,[]]));for(const i of e)for(const e of baseMapLayerGroupNames)isMatching(e,i)&&t[e].push(i.id);return t})(this.sourcesWithLayers.vectorTiles._layerSpecs),this.layersByGroup}get events(){return this.moduleEvents(["vectorTiles"],{scopeResolver:resolveBaseMapEventScope})}},resolveBaseMapEventScope=e=>({layerFilter:buildLayerGroupFilter(e.layerGroups),featureMatches:e.features}),layerGroupContents={land:"land use and land cover areas, and the map background",water:"oceans, lakes and rivers",buildings2D:"2D building footprints",roads:"road lines, their arrows, and road and transit surface areas",railways:"railways and aerial cableways",ferries:"ferry connections",borders:"administrative boundaries, military and protected overlays, and their labels",buildings3D:"3D building models",natureLabels:"labels of peaks, islands, rivers and water areas",roadLabels:"road name labels",roadShields:"highway shields",houseNumbers:"house number labels",smallerTownLabels:"neighbourhood, village, hamlet and town labels",stateLabels:"state and province labels",cityLabels:"city labels",allPlaceLabels:"every place label, the other place-label groups included",capitalLabels:"capital city labels",countryLabels:"country name labels"},describeLayerGroup=e=>`The \`${e}\` layer group: ${layerGroupContents[e]}.`,buildCatalogue$2=()=>[{id:"visible",kind:"toggle",description:"Every base-map layer, beneath what the `groups` entries set."},...baseMapLayerGroupNames.map(e=>({id:`groups.${e}.visible`,kind:"toggle",description:describeLayerGroup(e)}))],baseMapKnobCatalogue=/* @__PURE__ */buildCatalogue$2(),baseMapKnobIds=/* @__PURE__ */baseMapKnobCatalogue.map(({id:e})=>e),CustomGeoJSONModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),validateConfig(i),new e(t,i)}constructor(e,t){super(e,t),this.shownFeaturesHandlers=[]}_initSourcesWithLayers(e,t){const i=e??this.initialConfig;t||(this.lastShown={}),this.resolveIDs(i),this.registerImages(i);const r={};for(const o of Object.keys(i.sources)){const e=this.resolvedSourceIDs[o],t=this.resolvedLayerSpecs[o],s=i.sources[o].cluster;r[o]=new GeoJSONSourceWithLayers(this.mapLibreMap,e,t,!0,s)}return r}registerImages(e){if(e.images)for(const[t,i]of Object.entries(e.images))this.mapLibreMap.hasImage(t)||this.mapLibreMap.addImage(t,i.image,i.options)}resolveIDs(e){const t={},i={};for(const r of Object.keys(e.sources)){const o=e.sources[r],s=o.sourceID??`custom-geojson-${this.instanceIndex}-${String(r)}`;t[r]=s,i[r]=o.layers.map((e,t)=>({...e,id:e.id??`${s}-layer-${t}`}))}this.resolvedSourceIDs=t,this.resolvedLayerSpecs=i}_applyConfig(e){if(!e)return this._applyConfig(this.initialConfig);this.initialConfig??=e;const t=this.config,i=t?this.resolvedLayerSpecs:void 0;return this.resolveIDs(e),this.registerImages(e),t&&i&&this.updateLayersForExistingSources(i),this.applyVisibility(e),e}updateLayersForExistingSources(e){for(const t of Object.keys(this.resolvedLayerSpecs)){const i=e[t],r=this.resolvedLayerSpecs[t],o=this.sourcesWithLayers[t];if(!i||!o)continue;updateLayersAndSource(r,i,o,this.mapLibreMap);const s=[];for(const e of o._layerSpecs)this.mapLibreMap.getLayer(e.id)||s.push(e);s.length>0&&addLayers(s,this.mapLibreMap)}}applyVisibility(e){const t=!1!==e?.visible;for(const i of Object.values(this.sourcesWithLayers))i.setLayersVisible(t&&!!i.shownFeatures.features.length)}discardShownData(){this.lastShown={}}restoreDataAndConfigImpl(){const e=Object.keys(this.lastShown);this.initSourcesWithLayers(this.config,!0),this.config&&this._applyConfig(this.config);for(const t of e){const e=this.lastShown[t];e&&this.showOnSource(t,e)}}async show(e,t){if(await this.waitUntilModuleReady(),void 0!==t)this.showOnSource(t,e);else for(const i of Object.keys(this.sourcesWithLayers))this.showOnSource(i,e)}showOnSource(e,t){const i=ensureFeatureIDs(t);this.lastShown[e]=i,this.sourcesWithLayers[e].show(i,{automaticVisibility:this.isVisible()});for(const r of this.shownFeaturesHandlers)r({sourceName:e,data:i})}async clear(e){if(await this.waitUntilModuleReady(),void 0!==e)return this.sourcesWithLayers[e].clear(),void delete this.lastShown[e];for(const t of Object.keys(this.sourcesWithLayers))this.sourcesWithLayers[t].clear(),delete this.lastShown[t]}getShown(){const e={};for(const t of Object.keys(this.sourcesWithLayers))e[t]=this.sourcesWithLayers[t].shownFeatures;return e}get events(){const e=Object.keys(this.sourcesWithLayers),t={};for(const i of e)t[i]=this.userEvents([i]);return this.buildEvents(this.moduleEventsWithShown(e,this.shownFeaturesHandlers),t)}},validateConfig=e=>{if(!e.sources||0===Object.keys(e.sources).length)throw new Error("CustomGeoJSONModule requires at least one source in config.sources.");assertNoReservedScopeNames(Object.keys(e.sources),"CustomGeoJSONModule source");for(const[t,i]of Object.entries(e.sources))if(!i.layers||0===i.layers.length)throw new Error(`CustomGeoJSONModule source "${t}" requires at least one layer.`)},ensureFeatureIDs=e=>{let t=!1;for(const i of e.features)if(null==i.id||i.properties?.id!==i.id){t=!0;break}return t?{...e,features:e.features.map((e,t)=>{const i=e.id??e.properties?.id??t;return{...e,id:i,properties:{...e.properties,id:i}}})}:e},customGeoJSONKnobDefinitions={visible:{kind:"toggle",description:"Every layer of every source.",default:!0}},customGeoJSONKnobCatalogue=/* @__PURE__ */withIds(customGeoJSONKnobDefinitions),customGeoJSONKnobIds=/* @__PURE__ */customGeoJSONKnobCatalogue.map(({id:e})=>e),beforeLayerTargetOf=(e,t)=>"string"==typeof e?e:e?.[t]??e?.all,beforeLayerIDOf=(e,t)=>"top"===e?t:mapStyleLayerIDs[e],BORDER_LABEL_OFFSET=[0,1],getThemeAdaptiveGeometryColors=e=>({defaultColor:"dark"===e?"#5FA8D8":"#0A3653",textColor:"dark"===e?"#FFFFFF":"#333333",haloColor:"dark"===e?"#333333":"#FFFFFF"}),buildGeometryLayerSpecs=(e,t,i,r="#0A3653")=>{const o=i?.fill,s=i?.line,a=(Array.isArray(o?.color)?o.color:void 0)??i?.color,n=((e="#0A3653")=>({type:"fill",paint:{"fill-color":["coalesce",["get","color"],e],"fill-opacity":["case",["==",["get","fillStyle"],"outline"],0,.15],"fill-antialias":!1}}))(a??r),l=((e="#0A3653",t="#555555")=>({type:"line",paint:{"line-color":["case",["==",["get","fillStyle"],"outline"],["coalesce",["get","color"],t],["coalesce",["get","color"],e]],"line-opacity":["case",["==",["get","fillStyle"],"outline"],.9,1],"line-width":["case",["==",["get","fillStyle"],"outline"],5,2]}}))(a??r,a),c={...n,id:e,paint:{...n.paint,...!isNil(o?.opacity)&&{"fill-opacity":o?.opacity}}},d=s?.layer;return[c,{...l,...d,id:t,...d?.layout&&{layout:{...l.layout,...d.layout}},paint:{...l.paint,...d?.paint,...!isNil(s?.color)&&{"line-color":s?.color},...!isNil(s?.width)&&{"line-width":s?.width},...!isNil(s?.opacity)&&{"line-opacity":s?.opacity}}}]},buildGeometryTitleLayerSpec=(e,t,i="light")=>{const r=t?.label,{textColor:o,haloColor:s}=getThemeAdaptiveGeometryColors(i);return{type:"symbol",id:e,layout:{"text-field":r?.text??["get","title"],"text-padding":5,"text-size":15,"text-font":["Noto-Bold"],...labelLayoutProperties(r),"symbol-placement":"point"},paint:{"text-color":o,"text-halo-color":s,"text-halo-width":["interpolate",["linear"],["zoom"],6,1,10,1.5],...labelPaintProperties(r),"text-translate-anchor":"viewport"}}},buildGeometryLineLabelLayerSpec=(e,t,i="light")=>{const r=t?.lineLabel,{textColor:o,haloColor:s}=getThemeAdaptiveGeometryColors(i);return{type:"symbol",id:e,minzoom:r?.minZoom??3,layout:{"text-field":r?.text??["get","title"],"symbol-placement":"line","text-size":15,"text-font":["Noto-Bold"],...labelLayoutProperties(r),"symbol-spacing":r?.symbolSpacing??200,"text-keep-upright":!0,"text-offset":r?.offset??BORDER_LABEL_OFFSET},paint:{"text-color":o,"text-halo-color":s,"text-halo-width":2,...labelPaintProperties(r)}}},colorPalettes={warm:["#793F0D","#AC703D","#C38E63","#E49969","#E5AE86","#EEC5A9","#6E7649","#9D9754","#C7C397","#B4A851","#DFD27C","#E7E3B5","#846D74","#B7A6AD","#D3C9CE"],browns:["#edc4b3","#e6b8a2","#deab90","#d69f7e","#cd9777","#c38e70","#b07d62","#9d6b53","#8a5a44","#774936"],cold:["#344464","#548ca4","#549cac","#2c445c","#a4ccd4","#acbccc","#b4c4d4","#acd4cc","#5c8ca4"],fadedBlues:["#152033","#1d2d44","#2e455d","#3e5c76","#4c6884","#597491","#67809e","#6e86a5","#7b91ad","#879bb4"],blues:["#03045e","#023e8a","#0077b6","#0096c7","#00b4d8","#48cae4","#90e0ef","#ade8f4","#caf0f8"],greens:["#004b23","#006400","#007200","#008000","#38b000","#70e000","#9ef01a","#ccff33"],fadedGreenToBlue:["#d9ed92","#b5e48c","#99d98c","#76c893","#52b69a","#34a0a4","#168aad","#1a759f","#1e6091","#184e77"],blueToRed:["#033270","#1368aa","#4091c9","#9dcee2","#fedfd4","#f29479","#f26a4f","#ef3c2d","#cb1b16","#65010c"],greenToYellow:["#007f5f","#2b9348","#55a630","#80b918","#aacc00","#bfd200","#d4d700","#dddf00","#eeef20","#ffff3f"],pastel:["#fec5bb","#fcd5ce","#fae1dd","#f8edeb","#e8e8e4","#d8e2dc","#ece4db","#ffe5d9","#ffd7ba","#fec89a"],retro:["#f94144","#f3722c","#f8961e","#f9844a","#f9c74f","#90be6d","#43aa8b","#4d908e","#577590","#277da1"],contrastRetro:["#001219","#005f73","#0a9396","#94d2bd","#e9d8a6","#ee9b00","#ca6702","#bb3e03","#ae2012","#9b2226"],fadedRainbow:["#ffadad","#ffd6a5","#fdffb6","#caffbf","#9bf6ff","#a0c4ff","#bdb2ff","#ffc6ff","#fffffc"],pastelRainbow:["#54478c","#2c699a","#048ba8","#0db39e","#16db93","#83e377","#b9e769","#efea5a","#f1c453","#f29e4c"]},colorPaletteIDs=Object.keys(colorPalettes),adaptPaletteForTheme=(e,t)=>"light"===t?e:e.map(e=>{const t=(e=>{const t=parseCssColor(e);return t?.299*t[0]+.587*t[1]+.114*t[2]:.5})(e);return t>.6?darkenColor(e,.3)??e:t<.22?((e,t)=>{const i=parseColor(e);return i&&formatHex(interpolate([i,WHITE])(t))})(e,.4)??e:e}),prepareGeometryForDisplay=(e,t={},i="light")=>({...e,features:e.features.map((e,r)=>{const o=(e.properties??{}).fillStyle??t.fillStyle,s="inverted"===o?(e=>{const t=mask(e);return{...e,geometry:t.geometry}})(e):e,a=s.properties??{},n=a.title??((e,t)=>{const i=t.label?.text;return"string"==typeof i&&i?i:e.properties?.address?.freeformAddress})(s,t),l=a.color??((e,t,i)=>{const{color:r,palette:o}=e.fill??{};if(void 0!==r)return"string"==typeof r?r:void 0;if(!o)return;const s=adaptPaletteForTheme(colorPalettes[o],i);return s[t%s.length]})(t,r,i);return{...s,properties:{...s.properties,...o&&{fillStyle:o},...n&&{title:n},...l&&{color:l},id:a.id??generateId()}}})}),geometryParts=["fill","line"],GeometriesModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t),this.lastRawInput=null,this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{const e=this.config??{};void 0===(e.color??e.fill?.color??e.fill?.palette)&&(this.updateLayers(e),this.applyVisibility(e))})}get lightDark(){return this.tomtomMap.styleLightDarkTheme}get defaultColor(){return mapAccentColor(this.tomtomMap)??getThemeAdaptiveGeometryColors(this.lightDark).defaultColor}_initSourcesWithLayers(e,t){if(!t){this.sourceID=`geometry-${this.instanceIndex}`,this.titleSourceID=`geometryTitle-${this.instanceIndex}`;const e=`geometry-${this.instanceIndex}`;this.fillLayerID=`${e}_Fill`,this.outlineLayerID=`${e}_Outline`,this.lineLabelLayerID=`${e}_LineLabel`,this.titleLayerID=`${e}_Title`}const[i,r]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,e,this.defaultColor),o=buildGeometryTitleLayerSpec(this.titleLayerID,e,this.lightDark);this.titleLayerSpecs=o,this.geometryFillLayerSpecs=i,this.geometryOutlineLayerSpecs=r;const s=void 0===e?.lineLabel?null:buildGeometryLineLabelLayerSpec(this.lineLabelLayerID,e,this.lightDark);return this.lineLabelLayerSpecs=s,{geometry:new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,[{...i},{...r},...s?[s]:[]]),geometryLabel:new GeoJSONSourceWithLayers(this.mapLibreMap,this.titleSourceID,[o])}}_applyConfig(e){if(this.updateLayers(e),this.lastRawInput){const t=this.sourcesWithLayers.geometry.shownFeatures;this.display(((e,t)=>e.features.length!==t.features.length?e:{...e,features:e.features.map((e,i)=>{const r=t.features[i].properties,o=r?.eventState;return{...e,properties:{...e.properties,id:r?.id,...o&&{eventState:o}}}})})(this.prepare(this.lastRawInput,e),t))}return(e?.beforeLayerConfig||this.config?.beforeLayerConfig)&&this.applyBeforeLayerConfig(e?.beforeLayerConfig,"top"),this.applyVisibility(e),e}applyVisibility(e){const{geometry:t,geometryLabel:i}=this.sourcesWithLayers,r=!1!==e?.visible;applyLayersVisibility([this.geometryFillLayerSpecs,this.geometryOutlineLayerSpecs,...this.lineLabelLayerSpecs?[this.lineLabelLayerSpecs]:[]],r&&!!t.shownFeatures.features.length,this.mapLibreMap),applyLayersVisibility([this.titleLayerSpecs],r&&!!i.shownFeatures.features.length,this.mapLibreMap)}get partLayerIDs(){return{fill:[this.fillLayerID],line:this.lineLabelLayerSpecs?[this.outlineLayerID,this.lineLabelLayerID]:[this.outlineLayerID]}}moveBeforeLayer(e){this.config={...this.config,beforeLayerConfig:e},this.applyBeforeLayerConfig(e),this.emitConfigChange()}applyBeforeLayerConfig(e,t){const i=this.partLayerIDs;for(const r of geometryParts){const o=beforeLayerTargetOf(e,r)??t;if(void 0!==o)for(const e of i[r])moveLayerBefore(this.mapLibreMap,e,beforeLayerIDOf(o,this.titleLayerID))}}applyLabelConfig(e){this.updateConfig({label:e})}updateLayers(e){const[t,i]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,e,this.defaultColor),r=buildGeometryTitleLayerSpec(this.titleLayerID,e,this.lightDark);if(changeLayerProps(t,this.geometryFillLayerSpecs,this.mapLibreMap),changeLayerProps(i,this.geometryOutlineLayerSpecs,this.mapLibreMap),changeLayerProps(r,this.titleLayerSpecs,this.mapLibreMap),this.geometryFillLayerSpecs=t,this.geometryOutlineLayerSpecs=i,this.titleLayerSpecs=r,this.lineLabelLayerSpecs){const t=buildGeometryLineLabelLayerSpec(this.lineLabelLayerID,e,this.lightDark);changeLayerProps(t,this.lineLabelLayerSpecs,this.mapLibreMap),this.lineLabelLayerSpecs=t}}discardShownData(){this.lastRawInput=null}prepare(e,t){const{transformFeaturesForDisplay:i}=t??{},r=i?i(e):e;return prepareGeometryForDisplay(r,t,this.lightDark)}display(e){const t=this.sourcesWithLayers.geometry;t.show(e,{automaticVisibility:!1}),this.sourcesWithLayers.geometryLabel.show((e=>{const t=e.features.map(e=>{let t;if(e.properties?.placeCoordinates)t=e.properties?.placeCoordinates;else if("MultiPolygon"===e.geometry.type){const i=(e=>e.flat().reduce((e,t)=>t.length>e.length?t:e,[]))(e.geometry.coordinates),r=bboxFromCoordsArray(i);t=r&&bboxCenter(r)||null}else t=e.geometry.coordinates.flat();const i=e.id??e.properties?.id??generateId();return{type:"Feature",id:i,geometry:{type:"Point",coordinates:t},properties:{...e.properties,id:i}}});return{type:"FeatureCollection",bbox:e.bbox,features:t}})(t.shownFeatures),{automaticVisibility:!1})}async show(e){await this.waitUntilModuleReady(),this.lastRawInput=e,this.display(this.prepare(e,this.config)),this.applyVisibility(this.config);for(const t of this.shownFeaturesHandlers)t(e)}async clear(){await this.waitUntilModuleReady(),this.lastRawInput=null,this.sourcesWithLayers.geometry.clear(),this.sourcesWithLayers.geometryLabel.clear()}getShown(){return{geometry:this.sourcesWithLayers.geometry.shownFeatures,geometryLabel:this.sourcesWithLayers.geometryLabel.shownFeatures}}get events(){return this.buildEvents(this.moduleEventsWithShown(["geometry","geometryLabel"],this.shownFeaturesHandlers),{geometry:this.userEvents(["geometry"]),geometryLabel:this.userEvents(["geometryLabel"])})}},BUDGET_UNITS={timeMinutes:"min",distanceKM:"km",remainingChargePCT:"% remaining",spentChargePCT:"% spent",spentFuelLiters:"L"},buildReachableRangeFeatures=(e,t,i="filled")=>{const r=e.map((e,r)=>({...e,properties:{...e.properties,title:t[r],fillStyle:i}}));return"inverted"===i?(e=>[...e.map((t,i)=>{const r=0===i?mask(t):difference(featureCollection([e[i-1],t])),{title:o,fillStyle:s,...a}=t.properties??{};return{...t,geometry:r?.geometry??t.geometry,properties:a}}),...e.map(e=>({...e,id:void 0,properties:{...e.properties,fillStyle:"filled"}}))])(r):r},prepareReachableRangesForDisplay=(e,{fillStyle:t="filled",title:i}={})=>{const r=e.features,o=r.map((e,t)=>{if(i)return i(e,t);const r=e.properties?.budget;return void 0!==r?.value&&r?.type?`${r.value} ${BUDGET_UNITS[r.type]??r.type}`:String(t+1)});return{type:"FeatureCollection",...e.bbox&&{bbox:e.bbox},features:buildReachableRangeFeatures(r,o,t)}},fillStyledGeometryConfig=({palette:e="fadedRainbow",beforeLayerConfig:t="lowestLabel"}={})=>({beforeLayerConfig:t,line:{width:["case",["==",["get","fillStyle"],"outline"],5,1],color:["case",["==",["get","fillStyle"],"outline"],["coalesce",["get","color"],"#555555"],"grey"],opacity:["case",["==",["get","fillStyle"],"outline"],.9,1]},fill:{palette:e,opacity:["case",["==",["get","fillStyle"],"outline"],0,.6]},lineLabel:{}}),reachableRangeGeometryConfig=({palette:e,beforeLayerConfig:t,fillStyle:i,title:r}={})=>{const o=fillStyledGeometryConfig({palette:e,beforeLayerConfig:t}),s=e=>prepareReachableRangesForDisplay(e,{fillStyle:i,title:r});return"inverted"!==i?{...o,transformFeaturesForDisplay:s}:{...o,line:{...o.line,opacity:["case",["==",["get","fillStyle"],"filled"],1,0]},fill:{...o.fill,opacity:["case",["==",["get","fillStyle"],"filled"],0,.6]},lineLabel:{opacity:["case",["==",["get","fillStyle"],"filled"],1,0],offset:["case",["==",["get","fillStyle"],"filled"],["literal",[0,-1]],["literal",[0,1]]]},transformFeaturesForDisplay:s}},geometryFillStyles=["filled","outline","inverted"],LABEL_SIZE_RANGE={min:6,max:48,step:1,bounds:"hard-min"},HALO_WIDTH_RANGE={min:0,max:10,step:.5,bounds:"hard-min"},moduleKnobDefinitions={color:{kind:"color",description:"Base colour of the fill and the border. Unset: the map's accent if a theme sets one, else a navy that follows the light/dark theme."},visible:{kind:"toggle",description:"Everything the module draws: fills, borders, center labels and border labels.",default:!0},fillStyle:{kind:"enum",description:"`filled` shades the polygon, `outline` draws only a thick border, `inverted` shades the outside.",options:/* @__PURE__ */everyOf()(geometryFillStyles),default:"filled"},"fill.color":{kind:"color",description:"Fill colour, over `fill.palette` and `color`; a border without its own `line.color` follows it."},"fill.palette":{kind:"enum",description:"Named palette giving each feature the next fill colour in turn, over `color`.",options:colorPaletteIDs},"fill.opacity":{kind:"number",description:"Fill opacity. Unset: 0.15, or 0 with the `outline` fill style.",range:OPACITY_RANGE},"line.color":{kind:"color",description:"Border colour, over a feature's own `color` and every fill colour."},"line.opacity":{kind:"number",description:"Border opacity. Unset: 1, or 0.9 with the `outline` fill style.",range:OPACITY_RANGE},"line.width":{kind:"number",description:"Border width in pixels. Unset: 2, or 5 with the `outline` fill style.",range:{min:0,max:20,step:.5,bounds:"hard-min"}},"lineLabel.minZoom":{kind:"number",description:"Lowest zoom the border labels are drawn at; setting any `lineLabel` knob draws them.",range:ZOOM_RANGE,default:3},"lineLabel.symbolSpacing":{kind:"number",description:"Distance between repeated border labels, in pixels.",range:{min:50,max:1e3,step:10,bounds:"hard-min"},default:200},"lineLabel.offset":{kind:"offset",description:"Shift of the border labels off the line, in ems: x along it, y across it.",range:{min:-5,max:5,step:.1,bounds:"soft"},default:BORDER_LABEL_OFFSET}},labelNames={label:"center labels",lineLabel:"border labels"},labelKnobDefinitions={size:e=>({kind:"number",description:`Text size of the ${labelNames[e]}, in pixels.`,range:LABEL_SIZE_RANGE,default:15}),color:e=>({kind:"color",description:`Text colour of the ${labelNames[e]}. Unset follows the map's light/dark theme.`}),haloColor:e=>({kind:"color",description:`Halo colour of the ${labelNames[e]}. Unset follows the map's light/dark theme.`}),haloWidth:e=>({kind:"number",description:`Halo width of the ${labelNames[e]}, in pixels.`,range:HALO_WIDTH_RANGE,...defaultOf("lineLabel"===e?2:void 0)}),opacity:e=>({kind:"number",description:`Text opacity of the ${labelNames[e]}.`,range:OPACITY_RANGE,default:1}),font:e=>({kind:"enums",description:`Font faces of the ${labelNames[e]}, in order: the first one available wins.`,options:mapFonts,default:["Noto-Bold"]})},geometriesKnobCatalogue=/* @__PURE__ */(()=>{const e=withIds(moduleKnobDefinitions),t=({id:e})=>e.startsWith("lineLabel."),i=e=>Object.keys(labelKnobDefinitions).map(t=>({id:`${e}.${t}`,...labelKnobDefinitions[t](e)}));return[...e.filter(e=>!t(e)),...i("label"),...i("lineLabel"),...e.filter(t)]})(),geometriesKnobIds=/* @__PURE__ */geometriesKnobCatalogue.map(({id:e})=>e),resolveCountryCrossingColors=(e,t)=>{const i=e?.color??("dark"===t?"#F1F3F5":"#1A2024"),r=relativeLuminance(i),o=void 0!==r&&r>.4?"#1A2024":"#F1F3F5";return{plaque:i,text:e?.textColor??o}},generatedSectionTypes=["carpool","carTrain","importantRoadStretch","lowEmissionZone","motorway","pedestrian","speedLimit","tollVignette","unpaved","urban"],bespokeSectionTypes=["ferry","tollRoad","traffic","tunnel","vehicleRestricted"],drawnSectionTypes=[...generatedSectionTypes,...bespokeSectionTypes],ALL_SECTION_KNOBS=["visible","color","opacity","width","widthFactor","style","pattern","icon"],SECTION_REGISTRY={carpool:{sourceKey:"carpoolSections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},carTrain:{sourceKey:"carTrainSections",visible:!0,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},importantRoadStretch:{sourceKey:"importantRoadStretchSections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},lowEmissionZone:{sourceKey:"lowEmissionZoneSections",visible:!0,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},motorway:{sourceKey:"motorwaySections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},pedestrian:{sourceKey:"pedestrianSections",visible:!1,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},speedLimit:{sourceKey:"speedLimitSections",visible:!0,knobs:["visible","sign"]},tollVignette:{sourceKey:"tollVignetteSections",visible:!0,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},unpaved:{sourceKey:"unpavedSections",visible:!1,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},urban:{sourceKey:"urbanSections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},ferry:{sourceKey:"ferries",visible:!0,style:"inline",pattern:"solid",knobs:ALL_SECTION_KNOBS},tollRoad:{sourceKey:"tollRoads",visible:!0,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},traffic:{sourceKey:"incidents",visible:!0,style:"inline",pattern:"solid",knobs:["visible","opacity","width","widthFactor","style"]},tunnel:{sourceKey:"tunnels",visible:!0,style:"inline",pattern:"solid",knobs:ALL_SECTION_KNOBS},vehicleRestricted:{sourceKey:"vehicleRestricted",visible:!0,style:"inline",pattern:"dotted",knobs:ALL_SECTION_KNOBS}},sectionSupportsKnob=(e,t)=>SECTION_REGISTRY[e].knobs.includes(t),sectionEntry=e=>SECTION_REGISTRY[e],isGeneratedSectionType=e=>generatedSectionTypes.includes(e),sectionDrawsByDefault=e=>SECTION_REGISTRY[e].visible,postsSign=e=>sectionSupportsKnob(e,"sign"),sectionSourceKey=(generatedSectionTypes.filter(e=>!postsSign(e)),e=>SECTION_REGISTRY[e].sourceKey),mapLayerSpecs=(e={},t)=>Object.entries(e).map(([e,i])=>({...i,id:prefixLayerID(e,t)})),routeDisplayUnits=e=>e?.displayUnits??TomTomConfig.instance.get().displayUnits,ROUTE_LINE_FOREGROUND_COLOR="#36A8F0",ROUTE_LINE_OUTLINE_COLOR="#105287",DESELECTED_FOREGROUND_COLOR="#ABAFB3",DESELECTED_OUTLINE_COLOR="#3C4956",DESELECTED_SECONDARY_COLOR="#727C85",ROUTE_LINE_FOREGROUND_WIDTH=["interpolate",["linear"],["zoom"],1,3,5,4,10,7,18,10],SELECTED_ROUTE_FILTER=["==",["get","routeState"],"selected"],DESELECTED_ROUTE_FILTER=["==",["get","routeState"],"deselected"],ROUTE_LINE_OUTLINE_WIDTH=["interpolate",["linear"],["zoom"],1,5,5,6,10,10,18,14],ROUTE_WIDTH_FACTOR_RANGE={min:.5,max:2,step:.1,bounds:"hard"},ROUTE_WAYPOINT_SIZE_FACTOR_RANGE={min:.5,max:2,step:.1,bounds:"hard"},SECTION_ICON_SIZE_FACTOR_RANGE={min:.25,max:2,step:.05,bounds:"hard"},isExpression=e=>Array.isArray(e),scaleRamp=(e,t)=>{if(1===t)return e;const i=scaleNumericValue(e,t);return isExpression(i)?i:e},getSectionIconSize=(e,t)=>{const i=e??1,r=scaleNumericValue(i,clampFactor(t,SECTION_ICON_SIZE_FACTOR_RANGE));return"number"==typeof r||isExpression(r)?r:i},scaledWidth=(e,t)=>scaleRamp(e[t?.width??"m"],clampFactor(t?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),LINE_FOREGROUND_WIDTHS={s:["interpolate",["linear"],["zoom"],1,2,5,3,10,5,18,7],m:ROUTE_LINE_FOREGROUND_WIDTH,l:["interpolate",["linear"],["zoom"],1,5,5,6,10,11,18,15]},LINE_OUTLINE_WIDTHS={s:["interpolate",["linear"],["zoom"],1,4,5,5,10,8,18,11],m:ROUTE_LINE_OUTLINE_WIDTH,l:["interpolate",["linear"],["zoom"],1,7,5,9,10,14,18,19]},WAYPOINT_ICON_SIZE=["interpolate",["linear"],["zoom"],8,.6,22,.8],WAYPOINT_INDEX_TEXT_SIZE=["interpolate",["linear"],["zoom"],13,14,18,16],WAYPOINT_SIZE_PRESET_FACTORS={s:.75,m:1,l:1.25},getLineForegroundWidth=e=>scaledWidth(LINE_FOREGROUND_WIDTHS,e),getLineOutlineWidth=e=>scaledWidth(LINE_OUTLINE_WIDTHS,e),waypointScale=(e,t)=>WAYPOINT_SIZE_PRESET_FACTORS[e??"m"]*clampFactor(t,ROUTE_WAYPOINT_SIZE_FACTOR_RANGE),getWaypointIconSize=(e,t)=>scaleRamp(WAYPOINT_ICON_SIZE,waypointScale(e,t)),getWaypointIndexTextSize=(e,t)=>scaleRamp(WAYPOINT_INDEX_TEXT_SIZE,waypointScale(e,t)),SECTION_HALO_WIDTHS={s:["interpolate",["linear"],["zoom"],1,8,5,9,10,12,18,15],m:["interpolate",["linear"],["zoom"],1,9,5,11,10,15,18,20],l:["interpolate",["linear"],["zoom"],1,12,5,14,10,19,18,24]},getSectionHaloWidth=e=>scaledWidth(SECTION_HALO_WIDTHS,e),INSTRUCTION_LINE_WIDTHS={s:["interpolate",["linear"],["zoom"],16,8,22,12],m:["interpolate",["linear"],["zoom"],16,12,22,17],l:["interpolate",["linear"],["zoom"],16,17,22,24]},INSTRUCTION_OUTLINE_WIDTHS={s:["interpolate",["linear"],["zoom"],16,10,22,14],m:["interpolate",["linear"],["zoom"],16,14,22,20],l:["interpolate",["linear"],["zoom"],16,20,22,28]},getInstructionLineWidth=e=>scaledWidth(INSTRUCTION_LINE_WIDTHS,e),getInstructionOutlineWidth=e=>scaledWidth(INSTRUCTION_OUTLINE_WIDTHS,e),INSTRUCTION_ARROW_SIZE=["interpolate",["linear"],["zoom"],16,1,22,2],getInstructionArrowSize=e=>scaleRamp(INSTRUCTION_ARROW_SIZE,clampFactor(e?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),MAJOR_DELAY_COLOR="#AD0000",MODERATE_DELAY_COLOR="#FB2D09",MINOR_DELAY_COLOR="#FFC105",MINOR_DELAY_LABEL_COLOR="#f58240",UNKNOWN_DELAY_COLOR="#000000",UNKNOWN_DELAY_BG_COLOR="#C7D2D8",UNKNOWN_DELAY_DASH_COLOR="rgba(190, 39, 27, 1)",INDEFINITE_DELAY_DASH_COLOR="rgba(137, 150, 168, 1)",DEFAULT_CROSSING_COLORS=resolveCountryCrossingColors(void 0,"light"),COUNTRY_CROSSING_LAYER_ID="routeCountryCrossing",CROSSING_TEXT_SIZE=["interpolate",["linear"],["zoom"],5,11,12,13],CROSSING_ROUTE_ROTATION=["case",[">",["get","bearing"],180],["-",["get","bearing"],270],["-",["get","bearing"],90]],countryCrossingSymbol=(e,t,i)=>{const r=void 0!==e?suffixNumber("route-country-crossing-plaque",e):"route-country-crossing-plaque",o="route"===t?.alignment;return{type:"symbol",filter:SELECTED_ROUTE_FILTER,minzoom:t?.minZoom??4,layout:{"symbol-placement":"point","icon-image":r,"icon-text-fit":"both","icon-text-fit-padding":[4,8,4,8],"icon-rotation-alignment":o?"map":"viewport","text-rotation-alignment":o?"map":"viewport",...o&&{"icon-rotate":CROSSING_ROUTE_ROTATION,"text-rotate":CROSSING_ROUTE_ROTATION},"text-field":["get","label"],"text-font":["Noto-Bold"],"text-size":CROSSING_TEXT_SIZE,"text-allow-overlap":!0,"icon-allow-overlap":!0,...!1===t?.visible&&{visibility:"none"}},paint:{"text-color":i?.text??DEFAULT_CROSSING_COLORS.text}}},GENERATED_SECTION_PAINT={carpool:{color:"#6D4AC7",opacity:.55},carTrain:{color:"#8A5A2B",opacity:.6},importantRoadStretch:{color:"#C7761F",opacity:.6},lowEmissionZone:{color:"#2E8B57",opacity:.5},motorway:{color:"#1F6FB2",opacity:.4},pedestrian:{color:"#B23F86",opacity:.6},tollVignette:{color:"#8C6B1F",opacity:.55},unpaved:{color:"#7A6A54",opacity:.6},urban:{color:"#7E8C8E",opacity:.3}},DASH_ARRAYS={solid:void 0,dashed:[2,1.5],dotted:[0,1.5]},isSectionVisible=(e,t)=>t?.visible??SECTION_REGISTRY[e].visible,sectionDrawStyle=(e,t)=>sectionSupportsKnob(e,"style")&&t?.style||sectionEntry(e).style,SECTION_STYLE_ANCHOR={halo:"routeDeselectedOutline",inline:"routeLineArrows"},sectionStyleAnchor=(e,t)=>{const i=sectionDrawStyle(e,t);return i&&SECTION_STYLE_ANCHOR[i]},withSectionLineKnobs=(e,t,i,r,o="principal")=>{const s={width:i?.width??r?.width,widthFactor:i?.widthFactor??r?.widthFactor},a={...t.paint,"line-width":"halo"===sectionDrawStyle(e,i)?getSectionHaloWidth(s):getLineForegroundWidth(s)};if(i?.color&&sectionSupportsKnob(e,"color")){const e="outline"===o?darkerShadeOf(i.color):i.color;e&&(a["line-color"]=e)}return void 0!==i?.opacity&&sectionSupportsKnob(e,"opacity")&&(a["line-opacity"]=i.opacity),"principal"===o&&sectionSupportsKnob(e,"pattern")&&((e,t,i)=>{const r=i?.pattern??sectionEntry(e).pattern,o=r&&DASH_ARRAYS[r];o?t["line-dasharray"]=o:delete t["line-dasharray"]})(e,a,i),{...t,layout:{...t.layout,...!isSectionVisible(e,i)&&{visibility:"none"}},paint:a}},withSectionSymbolKnobs=(e,t,i)=>{const r=sectionSupportsKnob(e,"icon")?i?.icon:void 0;return{...t,layout:{...t.layout,...r&&{"icon-image":r.image,...void 0!==r.sizeFactor&&{"icon-size":getSectionIconSize(t.layout?.["icon-size"],r.sizeFactor)},...r.placement&&{"symbol-placement":"along"===r.placement?"line":"line-center"}},...!isSectionVisible(e,i)&&{visibility:"none"}}}},sectionLine=(e,t,i)=>withSectionLineKnobs(e,{filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":GENERATED_SECTION_PAINT[e].color,"line-opacity":GENERATED_SECTION_PAINT[e].opacity}},t,i),SIGN_ICON_SIZE=["interpolate",["linear"],["zoom"],10,.5,16,.7],SIGN_TEXT_SIZE=["interpolate",["linear"],["zoom"],10,9,16,13],SIGN_SORT_KEY=["-",["get","startPointIndex"],["get","endPointIndex"]],SIGN_TEXT_OFFSET=["case",["==",["get","signFace"],"plaque"],["literal",[0,.55]],["literal",[0,0]]],signPlacement=e=>e?.sign?.placement??"atChange",sectionSign=(e,t)=>{return{filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:t?.sign?.minZoom??10,layout:{...(i=signPlacement(t),"atChange"===i?{"symbol-placement":"point"}:{"symbol-placement":"line","symbol-spacing":260}),"icon-image":["get","signImageID"],"icon-size":SIGN_ICON_SIZE,"icon-rotation-alignment":"viewport","text-field":["get","signLabel"],"text-font":["Noto-Bold"],"text-size":SIGN_TEXT_SIZE,"text-offset":SIGN_TEXT_OFFSET,"text-rotation-alignment":"viewport","symbol-sort-key":SIGN_SORT_KEY,...!isSectionVisible(e,t)&&{visibility:"none"}},paint:{"text-color":["get","signNumeralsColor"]}};var i},SECTION_START_SIGN_IMAGE_IDS={tunnel:"route-tunnel-sign",vehicleRestricted:"route-vehicle-restricted-sign"},sectionStartSign=(e,t)=>({filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:10,layout:{"symbol-placement":"point","icon-image":void 0===t?SECTION_START_SIGN_IMAGE_IDS[e]:suffixNumber(SECTION_START_SIGN_IMAGE_IDS[e],t),"icon-size":SIGN_ICON_SIZE,"icon-rotation-alignment":"viewport"}}),sectionLayerID=(e,t)=>`routeSection${e.charAt(0).toUpperCase()+e.slice(1)}${t}`,sectionSignLayerID=e=>sectionLayerID(e,"Sign"),routeWidths=/* @__PURE__ */everyOf()(["s","m","l"]),routeKnobDefinitions={visible:{kind:"toggle",description:"Everything the module draws; hiding it keeps the shown routes and waypoints.",default:!0},color:{kind:"color",description:"Colour of the route line, its darker outline and the waypoint pins. Unset: the map's accent if a theme sets one, else the SDK's blue."},width:{kind:"enum",description:"Thickness preset of the route line, which the section and instruction lines follow.",options:routeWidths,default:"m"},widthFactor:{kind:"factor",description:"Multiplier over the width preset; the instruction arrows and sections without their own follow it.",range:ROUTE_WIDTH_FACTOR_RANGE,default:1},waypointSize:{kind:"enum",description:"Size preset of the waypoint pins and their stop numbers: `s` is 0.75 × `m`, `l` 1.25 × `m`.",options:/* @__PURE__ */everyOf()(["s","m","l"]),default:"m"},waypointSizeFactor:{kind:"factor",description:"Multiplier over the waypoint size preset.",range:ROUTE_WAYPOINT_SIZE_FACTOR_RANGE,default:1},"waypoints.icon.style.fillColor":{kind:"color",description:"Fill colour of the waypoint pins, in place of the route's."},"waypoints.icon.style.outlineColor":{kind:"color",description:"Outline colour of the waypoint pins."},"waypoints.icon.style.outlineOpacity":{kind:"number",description:"Outline opacity of the waypoint pins.",range:OPACITY_RANGE},"waypoints.entryPoints":{kind:"enum",description:"Draw each waypoint at its place's main entry point when it has one, or at its own coordinates.",options:/* @__PURE__ */everyOf()(["main-when-available","ignore"]),default:"ignore"},"displayUnits.distance.type":{kind:"enum",description:"Unit system of the summary bubble distances, and of the speed limit signs on a route without `country` sections. Unset follows the global config.",options:/* @__PURE__ */everyOf()(["metric","imperial_us","imperial_uk"])},"displayUnits.distance.kilometers":{kind:"text",description:"Label after a distance in kilometres. Unset follows the global config, else `km`."},"displayUnits.distance.meters":{kind:"text",description:"Label after a distance in metres. Unset follows the global config, else `m`."},"displayUnits.distance.miles":{kind:"text",description:"Label after a distance in miles. Unset follows the global config, else `mi`."},"displayUnits.distance.feet":{kind:"text",description:"Label after a distance in feet. Unset follows the global config, else `ft`."},"displayUnits.distance.yards":{kind:"text",description:"Label after a distance in yards. Unset follows the global config, else `yd`."},"displayUnits.time.hours":{kind:"text",description:"Label after the hours of a duration. Unset follows the global config, else `hr`."},"displayUnits.time.minutes":{kind:"text",description:"Label after the minutes of a duration. Unset follows the global config, else `min`."},"chargingStops.visible":{kind:"toggle",description:"The charging stop icons and labels along an EV route.",default:!0},"chargingStops.label.visible":{kind:"toggle",description:"The labels beside the charging stop icons.",default:!0},"summaryBubbles.visible":{kind:"toggle",description:"The bubbles giving each route's distance, duration and traffic delay.",default:!0},"countryCrossings.visible":{kind:"toggle",description:"The plaques naming both countries at each border crossing; needs `country` sections.",default:!0},"countryCrossings.minZoom":{kind:"number",description:"Lowest zoom a border crossing plaque is drawn at.",range:ZOOM_RANGE,default:4},"countryCrossings.color":{kind:"color",description:"Colour of the border crossing plaques. Unset follows the map's light/dark theme."},"countryCrossings.textColor":{kind:"color",description:"Label colour of the border crossing plaques. Unset: near-black or near-white, whichever reads."},"countryCrossings.alignment":{kind:"enum",description:"Whether a crossing plaque stays level with the screen or turns to the route's bearing.",options:/* @__PURE__ */everyOf()(["viewport","route"]),default:"viewport"}},sectionKnobDefinitions={visible:e=>({kind:"toggle",description:`The \`${e}\` sections.`,default:sectionEntry(e).visible}),color:e=>({kind:"color",description:`Line colour of the \`${e}\` sections.`}),opacity:e=>({kind:"number",description:`Line opacity of the \`${e}\` sections.`,range:OPACITY_RANGE}),width:e=>({kind:"enum",description:`Line width preset of the \`${e}\` sections; unset follows the route's.`,options:routeWidths}),widthFactor:e=>({kind:"factor",description:`Multiplier over the \`${e}\` sections' width preset; unset follows the route's.`,range:ROUTE_WIDTH_FACTOR_RANGE}),style:e=>({kind:"enum",description:`\`halo\` bands the route along the \`${e}\` sections; \`inline\` replaces its line.`,options:/* @__PURE__ */everyOf()(["halo","inline"]),...defaultOf(sectionEntry(e).style)}),pattern:e=>({kind:"enum",description:`Line pattern of the \`${e}\` sections.`,options:/* @__PURE__ */everyOf()(["solid","dashed","dotted"]),...defaultOf(sectionEntry(e).pattern)}),"icon.image":e=>({kind:"image",description:`Sprite image id of the \`${e}\` sections' icon; an id the sprite lacks draws nothing.`}),"icon.placement":e=>({kind:"enum",description:`Whether the \`${e}\` icon sits once mid-section or repeats along it; set with \`icon.image\`.`,options:/* @__PURE__ */everyOf()(["center","along"]),...defaultOf(isGeneratedSectionType(e)?"center":void 0)}),"icon.sizeFactor":e=>({kind:"factor",description:`Multiplier over the \`${e}\` icon's size; set with \`icon.image\`.`,range:SECTION_ICON_SIZE_FACTOR_RANGE,default:1}),"sign.placement":e=>({kind:"enum",description:`Whether a \`${e}\` sign stands only where the value changes or repeats along the stretch.`,options:/* @__PURE__ */everyOf()(["atChange","along"]),default:"atChange"}),"sign.minZoom":e=>({kind:"number",description:`Lowest zoom the \`${e}\` signs are drawn at.`,range:ZOOM_RANGE,default:10}),"sign.priority":e=>({kind:"enum",description:`What the \`${e}\` signs give way to in a symbol collision; unset follows the placement.`,options:/* @__PURE__ */everyOf()(["belowMapLabels","belowRouteIcons","aboveRouteIcons"])}),"sign.unit":e=>({kind:"enum",description:`Unit every \`${e}\` sign reads in; unset, each follows its country, or the display units without \`country\` sections.`,options:/* @__PURE__ */everyOf()(["km/h","mph"])})},sectionKnobId=(e,t)=>`sections.${e}.${t}`,routingKnobCatalogue=/* @__PURE__ */(()=>{const e=Object.keys(sectionKnobDefinitions),t=t=>e.filter(e=>e===t||e.startsWith(`${t}.`));return[...withIds(routeKnobDefinitions),...drawnSectionTypes.flatMap(e=>sectionEntry(e).knobs.flatMap(t).map(t=>({id:sectionKnobId(e,t),...sectionKnobDefinitions[t](e)})))]})(),routingKnobIds=/* @__PURE__ */routingKnobCatalogue.map(({id:e})=>e),stopDurationLabelSection=[["coalesce",["get","stopDuration"],""],{"text-color":"#727C85","text-font":["literal",["Noto-Regular"]]}],hasStopDuration=["has","stopDuration"],chargingStopTextField=e=>!1===e?.visible?"":e?.title??["format",["get","title"],{},"\n",{},["get","chargingPower"],{}," • ",{},...stopDurationLabelSection],chargingStopSymbol=e=>{const t=buildIconOffsetExpression(((e=[])=>{const t=/* @__PURE__ */new Map;for(const i of e){if(!i.image)continue;const e={x:i.offsetX??0,y:i.offsetY??0};0===e.x&&0===e.y||t.set(i.id,e)}return t})(e?.icon?.customIcons));return{...pinLayerBaseSpec,filter:SELECTED_ROUTE_FILTER,minzoom:4,layout:{...pinLayerBaseSpec.layout,"text-field":chargingStopTextField(e?.label),...t&&{"icon-offset":t}},paint:{...pinLayerBaseSpec.paint}}},commonProps={filter:SELECTED_ROUTE_FILTER,minzoom:16},commonLineLayout={"line-cap":"round"},instructionOutline=e=>({...commonProps,type:"line",layout:commonLineLayout,paint:{"line-width":getInstructionOutlineWidth(e),"line-color":"grey"}}),instructionLine=e=>({...commonProps,type:"line",layout:commonLineLayout,paint:{"line-width":getInstructionLineWidth(e),"line-color":"white"}}),routeFerriesLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round"},paint:{"line-color":"#6dc4ed"}},routeFerriesSymbol={filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:6,maxzoom:16.5,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-image":"poi-ferry_terminal","icon-size":["interpolate",["linear"],["zoom"],6,.8,16.5,1],"icon-ignore-placement":!0}},routeLineBaseTemplate={type:"line",layout:{"line-join":"round","line-cap":"round","line-sort-key":["get","index"]}},routeDeselectedOutline=e=>({...routeLineBaseTemplate,filter:DESELECTED_ROUTE_FILTER,paint:{"line-color":"#3C4956","line-width":getLineOutlineWidth(e)}}),routeDeselectedLine=e=>({...routeLineBaseTemplate,filter:DESELECTED_ROUTE_FILTER,paint:{"line-color":"#ABAFB3","line-width":getLineForegroundWidth(e)}}),routeOutline=(e,t)=>({...routeLineBaseTemplate,filter:SELECTED_ROUTE_FILTER,paint:{"line-color":t??"#105287","line-width":getLineOutlineWidth(e)}}),routeMainLine=(e,t)=>({...routeLineBaseTemplate,filter:SELECTED_ROUTE_FILTER,paint:{"line-color":t??"#36A8F0","line-width":getLineForegroundWidth(e)}}),routeLineArrows={type:"symbol",layout:{"symbol-placement":"line","icon-image":"roads-arrow-white","icon-rotate":180}},routeTollRoadsOutline={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":"#BEBFFA"}},routeTollRoadsSymbol={filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:4,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-image":"poi-toll_plaza","icon-size":["interpolate",["linear"],["zoom"],4,.8,16.5,1]}},trafficDelayColorKnobIds=[incidentColorKnobIds.minor,incidentColorKnobIds.moderate,incidentColorKnobIds.major],trafficDelayColors=(e={})=>({minor:e[incidentColorKnobIds.minor]??"#FFC105",moderate:e[incidentColorKnobIds.moderate]??"#FB2D09",major:e[incidentColorKnobIds.major]??"#AD0000"}),magnitudeOfDelayTextColor=["match",["get","magnitudeOfDelay"],"minor","#f58240","moderate","#FB2D09","major","#AD0000","indefinite","#666666","#000000"],routeIncidentsDashedLine={type:"line",filter:["in",["get","magnitudeOfDelay"],["literal",["unknown","indefinite"]]],layout:{"line-join":"round"},paint:{"line-color":["match",["get","magnitudeOfDelay"],"unknown","rgba(190, 39, 27, 1)","rgba(137, 150, 168, 1)"],"line-dasharray":[1.5,1]}},routeIncidentsSymbolBase={filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:6,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-ignore-placement":!0}},routeIncidentsJamSymbol={...routeIncidentsSymbolBase,filter:["all",["has","jamIconID"],routeIncidentsSymbolBase.filter],layout:{...routeIncidentsSymbolBase.layout,"icon-image":["get","jamIconID"],"icon-anchor":"bottom-left","text-anchor":"bottom-left","text-field":["get","title"],"text-font":["Noto-Bold"],"text-offset":[3.9,-1.4],"text-size":13},paint:{...routeIncidentsSymbolBase.paint,"text-color":magnitudeOfDelayTextColor,"text-halo-color":"#FFFFFF","text-halo-width":1}},routeIncidentsCauseSymbol={...routeIncidentsSymbolBase,filter:["all",["has","causeIconID"],routeIncidentsSymbolBase.filter],layout:{...routeIncidentsSymbolBase.layout,"icon-image":["get","causeIconID"],"icon-anchor":"bottom-right"},paint:{...routeIncidentsSymbolBase.paint}},routeTunnelsLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round"},paint:{"line-color":"#000000","line-opacity":.3}},routeVehicleRestrictedBackgroundLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round"},paint:{"line-color":"#105287"}},routeVehicleRestrictedDottedLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":"#36A8F0"}},hasFormattedTraffic=["has","formattedTraffic"],buildSummaryBubbleSymbolPoint=e=>{const t=void 0!==e?suffixNumber("selected-route-summary-popup",e):"selected-route-summary-popup",i=void 0!==e?suffixNumber("deselected-route-summary-popup",e):"deselected-route-summary-popup",r=void 0!==e?suffixNumber("traffic-clear",e):"traffic-clear",o=void 0!==e?suffixNumber("traffic-major",e):"traffic-major",s=void 0!==e?suffixNumber("traffic-moderate",e):"traffic-moderate",a=void 0!==e?suffixNumber("traffic-minor",e):"traffic-minor";return{type:"symbol",layout:{"icon-image":["case",SELECTED_ROUTE_FILTER,t,i],"symbol-placement":"point","icon-rotation-alignment":"viewport","text-rotation-alignment":"viewport","symbol-sort-key":["case",SELECTED_ROUTE_FILTER,0,1],"icon-text-fit":"both","icon-text-fit-padding":[10,5,5,10],"text-font":["Noto-Medium"],"text-size":13,"icon-padding":0,"text-justify":"left","text-line-height":1.5,"text-field":["format",["get","formattedDuration"],{"text-font":["literal",["Noto-Bold"]],"text-color":["case",SELECTED_ROUTE_FILTER,"black","#727C85"]},["concat","\t\t",["get","formattedDistance"]],{"text-color":"#727C85"},["case",hasFormattedTraffic,"\n",""],{},["image",["case",hasFormattedTraffic,["match",["get","magnitudeOfDelay"],"major",o,"moderate",s,"minor",a,r],""]],{},["case",hasFormattedTraffic,["concat"," ",["get","formattedTraffic"]],""],{"text-font":["literal",["Noto-Bold"]],"text-color":magnitudeOfDelayTextColor}]},paint:{"icon-translate":[0,-35],"text-translate":[0,-35]}}},summaryBubbleSymbolPoint=buildSummaryBubbleSymbolPoint(),START_INDEX="start",MIDDLE_INDEX="middle",FINISH_INDEX="finish",STOP_DISPLAY_INDEX="stopDisplayIndex",waypointLabelTextField=["format",["coalesce",["get",TITLE],""],{},["case",["all",["has",TITLE],hasStopDuration],"\n",""],{},...stopDurationLabelSection],pinIndexLabelLayout={"text-field":["get","stopDisplayIndex"],"text-font":["Noto-Bold"],"text-size":getWaypointIndexTextSize(),"text-offset":[0,-1.6],"icon-anchor":"bottom","text-allow-overlap":!0},waypointSymbols={type:"symbol",paint:{...pinIconBasePaint,"text-color":"#ffffff"},layout:{...pinIconBaseLayout,...pinIndexLabelLayout,"symbol-sort-key":["abs",["-",["get","index"],1e3]]}},waypointLabels={type:"symbol",paint:{...pinTextBasePaint,"text-color":"black","text-halo-width":1.5,"text-halo-color":"#ffffff"},layout:{...pinTextBaseLayout,"text-field":waypointLabelTextField,"text-anchor":"top","text-offset":[0,.4]}},prefixBeforeID=(e,t)=>e&&t&&(e.startsWith("route")||e.startsWith("waypoint"))?`${t}-${e}`:e,prefixBeforeIDs=(e,t)=>e&&t?Object.fromEntries(Object.entries(e).map(([e,i])=>[e,i?.beforeID?{...i,beforeID:prefixBeforeID(i.beforeID,t)}:i])):e,buildRoutingLayers=(e={},t,i,r="light",o=e=>e,s=trafficDelayColors())=>{const a=(t,i)=>{const r=beforeLayerTargetOf(e.beforeLayerConfig,t);return void 0===r?i:o(beforeLayerIDOf(r))},n=a("mainLines",mapStyleLayerIDs.lowestLabel),l=a("instructionLines",mapStyleLayerIDs.lowestLabel),c=a("icons",mapStyleLayerIDs.lowestLabel),d=a("icons",void 0),p=e.layers,u=p?.sections,h=e.color,y=h?darkerShadeOf(h):void 0,f={width:e.width,widthFactor:e.widthFactor},m=getWaypointIconSize(e.waypointSize,e.waypointSizeFactor),g=getWaypointIndexTextSize(e.waypointSize,e.waypointSizeFactor),S=(L=f,{...commonProps,type:"symbol",layout:{"icon-allow-overlap":!0,"icon-image":"instruction-arrow","icon-rotation-alignment":"map","icon-rotate":["get","lastPointBearingDegrees"],"icon-size":getInstructionArrowSize(L)}});var L;const b=e.sections,_=(e,i,r)=>({...withSectionLineKnobs(e,i,b?.[e],f,r?.role),beforeID:prefixBeforeID(r?.beforeID??sectionStyleAnchor(e,b?.[e]),t)}),I=(e,i,r)=>({...withSectionSymbolKnobs(e,i,b?.[e]),beforeID:prefixBeforeID(r,t)}),E=Object.fromEntries(generatedSectionTypes.map(e=>{const i=b?.[e],r=(e=>sectionLayerID(e,"Line"))(e),o=(e=>sectionLayerID(e,"Symbol"))(e),s=u?.[e];if(postsSign(e)){const r=sectionSignLayerID(e);return[e,{[r]:mergeLayer(sectionSign(e,i),s?.[r]),...prefixBeforeIDs(s?.additional,t)}]}const a=i&&((e,t)=>{if(t.icon&&sectionSupportsKnob(e,"icon"))return withSectionSymbolKnobs(e,{filter:SELECTED_ROUTE_FILTER,type:"symbol",layout:{"symbol-placement":"line-center","icon-allow-overlap":!0,"icon-rotation-alignment":"viewport"}},t)})(e,i);return[e,{[r]:mergeLayer({...sectionLine(e,i,f),beforeID:prefixBeforeID(sectionStyleAnchor(e,i),t)},s?.[r]),...a&&{[o]:mergeLayer({...a,beforeID:c},s?.[o])},...prefixBeforeIDs(s?.additional,t)}]}));return{mainLines:{routeLineArrows:mergeLayer({...routeLineArrows,beforeID:n},p?.mainLines?.routeLineArrows),routeLine:mergeLayer({...routeMainLine(f,h),beforeID:prefixBeforeID("routeIncidentBackgroundLine",t)},p?.mainLines?.routeLine),routeOutline:mergeLayer({...routeOutline(f,y),beforeID:prefixBeforeID("routeLine",t)},p?.mainLines?.routeOutline),routeDeselectedLine:mergeLayer({...routeDeselectedLine(f),beforeID:prefixBeforeID("routeOutline",t)},p?.mainLines?.routeDeselectedLine),routeDeselectedOutline:mergeLayer({...routeDeselectedOutline(f),beforeID:prefixBeforeID("routeDeselectedLine",t)},p?.mainLines?.routeDeselectedOutline),...prefixBeforeIDs(p?.mainLines?.additional,t)},waypoints:{routeWaypointSymbol:mergeLayer({...waypointSymbols,layout:{...waypointSymbols.layout,"icon-size":m,"text-size":g},beforeID:prefixBeforeID("routeSummaryBubbleSymbol",t)},p?.waypoints?.routeWaypointSymbol),routeWaypointLabel:mergeLayer({...waypointLabels,beforeID:prefixBeforeID("routeWaypointSymbol",t)},p?.waypoints?.routeWaypointLabel),...prefixBeforeIDs(p?.waypoints?.additional,t)},chargingStops:{routeChargingStopSymbol:mergeLayer({...chargingStopSymbol(e.chargingStops),beforeID:prefixBeforeID("routeWaypointSymbol",t)},p?.chargingStops?.routeChargingStopSymbol),...prefixBeforeIDs(p?.chargingStops?.additional,t)},sections:{...E,traffic:{routeIncidentJamSymbol:mergeLayer(I("traffic",routeIncidentsJamSymbol,"routeChargingStopSymbol"),u?.traffic?.routeIncidentJamSymbol),routeIncidentCauseSymbol:mergeLayer(I("traffic",routeIncidentsCauseSymbol,"routeChargingStopSymbol"),u?.traffic?.routeIncidentCauseSymbol),routeIncidentBackgroundLine:mergeLayer(_("traffic",(T=s,{type:"line",layout:{"line-cap":"round"},paint:{"line-color":["match",["get","magnitudeOfDelay"],"minor",T.minor,"moderate",T.moderate,"major",T.major,"#C7D2D8"]}}),{beforeID:"routeIncidentDashedLine"}),u?.traffic?.routeIncidentBackgroundLine),routeIncidentDashedLine:mergeLayer(_("traffic",routeIncidentsDashedLine),u?.traffic?.routeIncidentDashedLine),...prefixBeforeIDs(u?.traffic?.additional,t)},ferry:{routeFerryLine:mergeLayer(_("ferry",routeFerriesLine),u?.ferry?.routeFerryLine),routeFerrySymbol:mergeLayer(I("ferry",routeFerriesSymbol,"routeIncidentJamSymbol"),u?.ferry?.routeFerrySymbol),...prefixBeforeIDs(u?.ferry?.additional,t)},tollRoad:{routeTollRoadOutline:mergeLayer(_("tollRoad",routeTollRoadsOutline),u?.tollRoad?.routeTollRoadOutline),routeTollRoadSymbol:mergeLayer(I("tollRoad",routeTollRoadsSymbol,"routeChargingStopSymbol"),u?.tollRoad?.routeTollRoadSymbol),...prefixBeforeIDs(u?.tollRoad?.additional,t)},tunnel:{routeTunnelLine:mergeLayer(_("tunnel",routeTunnelsLine),u?.tunnel?.routeTunnelLine),routeTunnelSymbol:mergeLayer(I("tunnel",sectionStartSign("tunnel",i),c),u?.tunnel?.routeTunnelSymbol),...prefixBeforeIDs(u?.tunnel?.additional,t)},vehicleRestricted:{routeVehicleRestrictedBackgroundLine:mergeLayer(_("vehicleRestricted",routeVehicleRestrictedBackgroundLine,{beforeID:"routeVehicleRestrictedForegroundLine",role:"outline"}),u?.vehicleRestricted?.routeVehicleRestrictedBackgroundLine),routeVehicleRestrictedForegroundLine:mergeLayer(_("vehicleRestricted",routeVehicleRestrictedDottedLine),u?.vehicleRestricted?.routeVehicleRestrictedForegroundLine),routeVehicleRestrictedSymbol:mergeLayer(I("vehicleRestricted",sectionStartSign("vehicleRestricted",i),"routeIncidentJamSymbol"),u?.vehicleRestricted?.routeVehicleRestrictedSymbol),...prefixBeforeIDs(u?.vehicleRestricted?.additional,t)}},instructionLines:{routeInstructionLine:mergeLayer({...instructionLine(f),beforeID:l},p?.instructionLines?.routeInstructionLine),routeInstructionOutline:mergeLayer({...instructionOutline(f),beforeID:prefixBeforeID("routeInstructionLine",t)},p?.instructionLines?.routeInstructionOutline),...prefixBeforeIDs(p?.instructionLines?.additional,t)},instructionArrows:{routeInstructionArrowSymbol:mergeLayer({...S,beforeID:prefixBeforeID("routeInstructionLine",t),...void 0!==i&&{layout:{...S.layout,"icon-image":suffixNumber("instruction-arrow",i)}}},p?.instructionArrows?.routeInstructionArrowSymbol),...prefixBeforeIDs(p?.instructionArrows?.additional,t)},summaryBubbles:{routeSummaryBubbleSymbol:mergeLayer({...void 0===i?summaryBubbleSymbolPoint:buildSummaryBubbleSymbolPoint(i),...d&&{beforeID:d}},p?.summaryBubbles?.routeSummaryBubbleSymbol),...prefixBeforeIDs(p?.summaryBubbles?.additional,t)},countryCrossings:{[COUNTRY_CROSSING_LAYER_ID]:mergeLayer({...countryCrossingSymbol(i,e.countryCrossings,resolveCountryCrossingColors(e.countryCrossings,r)),beforeID:prefixBeforeID("routeWaypointSymbol",t)},p?.countryCrossings?.routeCountryCrossing),...prefixBeforeIDs(p?.countryCrossings?.additional,t)}};var T},defaultRoutingLayers=buildRoutingLayers();isDOMImageSupported()&&(instructionArrowIconImg=svgToImg(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">\n <path d="M1.562 40.569L25 1.562l23.438 39.007L25 27.566 1.562 40.569z" fill="#fff"/>\n <path d="M25.369.107c.782.429.506.167.917.682l23.438 39.007c.79 1.316-.671 2.829-2.014 2.085L25 29.281l-22.71 12.6c-1.343.744-2.804-.769-2.014-2.085L23.714.789c.461-.694.9-.682 1.656-.682zM25 1.562L1.562 40.569 25 27.566l23.438 13.003L25 1.562z"\n fill="gray"/>\n</svg>\n')));var cachedImg,summaryMapBubbleImg=e=>{if(!isDOMImageSupported())return;const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="65">\n <g filter="url(#A)">\n <rect id="pin" x="81.899" y="47" width="10" height="10" rx="2" transform="rotate(45 81.899 47)"/>\n <rect id="bubble" x="10" y="10" width="140" height="45" rx="12"/>\n </g>\n <defs>\n <filter id="A">\n <feDropShadow dx="0" dy="2" stdDeviation="4" flood-opacity=".3"/>\n </filter>\n </defs>\n</svg>\n');return t.querySelector("#bubble")?.setAttribute("fill",e),t.querySelector("#pin")?.setAttribute("fill",e),svgToImg(t)},summaryBubbleImageOptions={pixelRatio:2,stretchX:[[20,45],[100,130]],stretchY:[[20,35]],content:[10,10,130,45]},countryCrossingPlaqueImageOptions={pixelRatio:2,stretchX:[[30,110]],stretchY:[[25,35]],content:[10,10,130,50]},countryCrossingPlaqueImg=e=>{if(!isDOMImageSupported())return;const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="140" height="60">\n <g filter="url(#shadow)">\n <rect id="plaque" x="10" y="10" width="120" height="40" rx="8"/>\n </g>\n <defs>\n <filter id="shadow">\n <feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity=".35"/>\n </filter>\n </defs>\n</svg>\n');return t.querySelector("#plaque")?.setAttribute("fill",e),svgToImg(t)},roundSignSvg=(e,t,i)=>`<svg xmlns="http://www.w3.org/2000/svg" width="92" height="92" viewBox="0 0 46 46"><circle cx="23" cy="23" r="${22-i/2}" fill="${e}" stroke="${t}" stroke-width="${i}"/></svg>`,WHITE_DISC_SVG=roundSignSvg("#fff","#D0021B",5),SPEED_LIMIT_SIGN_SVGS={whiteDisc:WHITE_DISC_SVG,yellowDisc:roundSignSvg("#FFCE00","#D0021B",5),plaque:'<svg xmlns="http://www.w3.org/2000/svg" width="92" height="92" viewBox="0 0 46 46"><rect x="7" y="3" width="32" height="40" rx="2" fill="#fff" stroke="#1A2024" stroke-width="2"/><text x="23" y="13" fill="#1A2024" font-family="sans-serif" font-size="7" font-weight="bold" text-anchor="middle">SPEED</text><text x="23" y="21" fill="#1A2024" font-family="sans-serif" font-size="7" font-weight="bold" text-anchor="middle">LIMIT</text></svg>\n'},SECTION_START_SIGN_SVGS={tunnel:'<svg xmlns="http://www.w3.org/2000/svg" width="92" height="92" viewBox="0 0 46 46"><rect x="2.5" y="2.5" width="41" height="41" rx="8" fill="#1F5FAD" stroke="#fff" stroke-width="3"/><path fill="#fff" d="M10 36V24a13 13 0 0 1 26 0v12h-6V24.5a7 7 0 0 0-14 0V36z"/></svg>\n',vehicleRestricted:WHITE_DISC_SVG},signImg=e=>{if(isDOMImageSupported())return svgToImg(parseSvg(e))},sectionStartSignImg=e=>signImg(SECTION_START_SIGN_SVGS[e]),speedLimitSignImg=e=>signImg(SPEED_LIMIT_SIGN_SVGS[e]),trafficImg=e=>{if(!isDOMImageSupported())return;const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32">\n <g id="main">\n <path fill-rule="evenodd"\n d="M11.389 4H9.025a.86.86 0 0 0-.517.173l-.001-.001a.5.5 0 0 1-.464.059l-.028-.011a.5.5 0 0 1-.129-.83A1.86 1.86 0 0 1 9.025 3h2.364a2 2 0 0 1 1.789 1.106l1.02 2.04c.471.176.802.63.802 1.156v.803c0 .543 0 .815-.071 1.038a1.5 1.5 0 0 1-.914.953c-.219.08-.491.092-1.034.114l-1.481.062v-.166-.803a2.23 2.23 0 0 0-1.055-1.897l-.74-1.479 2.326.033h.955l-.703-1.406A1 1 0 0 0 11.389 4zM12 8.4a1 1 0 1 1 2 0 .5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5z"/>\n <path d="M11.833 11.115c0-.109.089-.198.198-.198h1.979c.109 0 .198.089.198.198 0 .328-.266.594-.594.594h-1.187c-.328 0-.594-.266-.594-.594z"/>\n <path fill-rule="evenodd"\n d="M1.802 8.146C1.331 8.321 1 8.776 1 9.302v.803c0 .543 0 .815.071 1.038a1.5 1.5 0 0 0 .914.953c.219.08.491.092 1.034.114l2.731.114 2.731-.114c.543-.023.814-.034 1.034-.114a1.5 1.5 0 0 0 .914-.953c.071-.223.071-.494.071-1.038v-.803c0-.526-.331-.98-.802-1.156l-1.02-2.04A2 2 0 0 0 6.889 5H4.611a2 2 0 0 0-1.789 1.106l-1.02 2.04zM6.889 6H4.611a1 1 0 0 0-.894.553l-.703 1.406h.955 3.563.955l-.703-1.406A1 1 0 0 0 6.889 6zM2 10.4a1 1 0 1 1 2 0 .5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm6.5-1a1 1 0 0 0-1 1 .5.5 0 0 0 .5.5h1a.5.5 0 0 0 .5-.5 1 1 0 0 0-1-1z"/>\n <path d="M1.792 13.115c0-.109.089-.198.198-.198h1.979c.109 0 .198.089.198.198 0 .328-.266.594-.594.594H2.385c-.328 0-.594-.266-.594-.594zm5.739-.198c-.109 0-.198.089-.198.198 0 .328.266.594.594.594h1.188c.328 0 .594-.266.594-.594 0-.109-.089-.198-.198-.198h-1.98z"/>\n </g>\n</svg>\n'),i=t.querySelector("#main");return i.setAttribute("transform","scale(2)"),i.setAttribute("fill",e),svgToImg(t)},waypointIcon=(e,t)=>{if(!isDOMImageSupported())return;const i=pinSvg(t);return e&&i.appendChild(e),svgToImg(i)},waypointStartIcon=e=>{if(isDOMImageSupported())return waypointIcon(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140">\n <path d="M63.734 86.383c-1.404.026-2.78-.393-3.93-1.197s-2.01-1.949-2.46-3.271l-3.15-9.339c-1.093-3.403-3.748-6.089-7.154-7.238L37.5 62.21c-2.742-.902-4.567-3.477-4.5-6.345-.058-2.874 1.761-5.457 4.5-6.388l36-11.886c2.461-.88 5.213-.27 7.062 1.567s2.466 4.571 1.578 7.015L70.17 81.918c-.938 2.719-3.54 4.526-6.436 4.469h0z"\n fill="#f4f5f6"/>\n</svg>\n'),e)},waypointFinishIcon=e=>{if(isDOMImageSupported())return waypointIcon(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140">\n <path d="M33 83.404a2.99 2.99 0 0 1-3-2.978V44.681a2.99 2.99 0 1 1 6 0v35.745a2.99 2.99 0 0 1-3 2.978zm48-38.723H39v17.872h42V44.681zm3.878 37.851a3.02 3.02 0 0 0 4.244 0c.561-.559.878-1.317.878-2.106V44.681a2.99 2.99 0 1 0-6 0v35.745c0 .789.317 1.547.878 2.106z"\n fill="#f4f5f6"/>\n</svg>\n'),e)},bearingAtCrossing=(e,t)=>{const i=e[t-1]??e[t],r=e[t+1]??e[t];return i===r?0:(bearing(i,r)+360)%360},toCrossingFeature=(e,t,i,r)=>{const o=generateId();return{type:"Feature",id:o,geometry:{type:"Point",coordinates:i[t.startPointIndex]},properties:{id:o,fromCountryCode:e.countryCodeISO2,toCountryCode:t.countryCodeISO2,label:`${e.countryCodeISO2} → ${t.countryCodeISO2}`,bearing:bearingAtCrossing(i,t.startPointIndex),fromSectionStartPointIndex:e.startPointIndex,toSectionStartPointIndex:t.startPointIndex,routeState:r.routeState,routeIndex:r.index}}},crossingsOfRoute=e=>{const t=e.properties.sections.country;if(!t?.length)return[];const i=[...t].sort((e,t)=>e.startPointIndex-t.startPointIndex),r=e.geometry.coordinates;return i.slice(1).flatMap((t,o)=>r[t.startPointIndex]?[toCrossingFeature(i[o],t,r,e.properties)]:[])},toDisplayCountryCrossings=e=>({type:"FeatureCollection",features:e.features.flatMap(crossingsOfRoute)}),getIconID=(e,t)=>{const i=t?.chargingStops?.icon;if(i?.mapping){const t=i.mapping;switch(t.basedOn){case"chargingSpeed":if(e.properties.chargingConnectionInfo?.chargingSpeed)return t.value[e.properties.chargingConnectionInfo?.chargingSpeed];break;case"custom":return t.fn(e)}}return toPinSpriteImageID("7309")},formatTitle=e=>{const t=e.properties;return t.chargingParkName??t.chargingParkOperatorName},hasJam=e=>e.categories.includes("jam"),toDisplayTrafficSectionProps=e=>{const t=(e=>{if(hasJam(e))return formatDuration(e.delayInSeconds)})(e),i=((e,t)=>hasJam(e)?`traffic-jam-${e.magnitudeOfDelay??"unknown"}-${(e=>e?.length?e.length<6?"small":e.length<8?"medium":"large":"collapsed")(t)}`:null)(e,t),r=(e=>{const t=e.categories.find(e=>"jam"!==e);return t?(e=>{switch(e){case"accident":return"traffic-incidents-accident";case"roadworks":return"traffic-incidents-roadworks";case"road-closed":return"traffic-incidents-road_closed";case"lane-closed":case"narrow-lanes":return"traffic-incidents-lane_closed";case"danger":case"animals-on-road":return"traffic-incidents-danger";case"broken-down-vehicle":return"traffic-incidents-broken_down_vehicle";case"wind":return"traffic-incidents-wind";case"fog":return"traffic-incidents-fog";case"rain":return"traffic-incidents-rain";case"frost":return"traffic-incidents-frost";case"flooding":return"traffic-incidents-flooding";default:return null}})(t):null})(e);return{...e,...i&&{jamIconID:i},...r&&{causeIconID:r},...t&&{title:t}}},getImageIDForWaypoint=(e,t,i)=>{let r;switch(t){case"start":r="waypointStart";break;case"finish":r="waypointFinish";break;default:r="waypointStop"}return void 0!==i?suffixNumber(r,i):r},toDisplayWaypoints=(e,t,i,r)=>({type:"FeatureCollection",features:e.map((o,s)=>{if(!o)return null;const a=(e=>{return Array.isArray(e)?{type:"Feature",geometry:{type:"Point",coordinates:e},properties:{}}:"Point"===e.type?{type:"Feature",geometry:t=e,properties:{},...t.bbox&&{bbox:t.bbox}}:e;var t})(o),n=((e,t)=>0===e?"start":e<t-1?"middle":"finish")(s,e.length),l=(e=>{const t=e?.properties;return t?.poi?.name??t?.address?.freeformAddress??void 0})(a),c=a.id??generateId(),d=formatDuration(a.properties.pauseDurationSeconds,r);return{...a,..."main-when-available"===t?.entryPoints&&{geometry:{type:"Point",coordinates:getPosition(a,{useEntryPoint:"main-when-available"})}},id:c,properties:{...a.properties,id:c,index:s,indexType:n,...l&&{title:l},...d&&{stopDuration:d},iconID:getImageIDForWaypoint(0,n,i),..."middle"===n&&{stopDisplayIndex:s}}}}).filter(e=>e)}),toDisplayRouteSections=(e,t,i)=>({type:"FeatureCollection",features:e.features.flatMap(e=>((e,t,i)=>e.properties.sections[t]?.map(t=>{const r=t.id??generateId();return{type:"Feature",id:r,geometry:{type:"LineString",coordinates:e.geometry.coordinates.slice(t.startPointIndex,t.endPointIndex+1)},properties:{...i?i(t,e.properties):t,routeState:e.properties.routeState,routeIndex:e.properties.index,id:r}}})||[])(e,t,i))}),showFeaturesWithRouteSelection=(e,t)=>t.show(((e,t)=>({...t,features:t.features.map(t=>({...t,properties:{...t.properties,routeState:e.features[t.properties.routeIndex||0].properties.routeState}}))}))(e,t.shownFeatures)),toDisplayRoutes=(e,t=0)=>{const i="features"in e?e:{type:"FeatureCollection",features:[e]};return{...i,features:i.features.map((e,i)=>{const r=e.id??generateId();return{...e,id:r,properties:{...e.properties,id:r,routeState:i===t?"selected":"deselected"}}})}},hasMagnitude=(e,t)=>e.some(e=>e.magnitudeOfDelay===t),toDisplayRouteSummaries=(e,t)=>({type:"FeatureCollection",features:e.features.map(e=>{const i=e.properties.summary,r=e.geometry.coordinates,o=formatDuration(i.trafficDelayInSeconds,t?.time),s=(e=>{const t=e.properties.sections.traffic;if(t?.length)return hasMagnitude(t,"major")?"major":hasMagnitude(t,"moderate")?"moderate":hasMagnitude(t,"minor")?"minor":void 0})(e),a=e.id??generateId();return{type:"Feature",id:a,geometry:{type:"Point",coordinates:r[Math.round(r.length/2)]},properties:{id:a,routeIndex:e.properties.index,routeState:e.properties.routeState,formattedDistance:formatDistance(i.lengthInMeters,t?.distance),...s&&{magnitudeOfDelay:s},...o&&{formattedTraffic:o},formattedDuration:formatDuration(i.travelTimeInSeconds,t?.time)}}})}),SIGN_BY_COUNTRY={GBR:{unit:"mph"},LBR:{unit:"mph"},MMR:{unit:"mph"},USA:{face:"plaque",unit:"mph"},SWE:{face:"yellowDisc"},FIN:{face:"yellowDisc"},ISL:{face:"yellowDisc"},JPN:{numerals:"#0B5FA5"}},SIGN_BY_DISPLAY_UNITS={metric:{},imperial_uk:{unit:"mph"},imperial_us:{face:"plaque",unit:"mph"}},SPEED_LIMIT_IMAGE_ID_BY_FACE={whiteDisc:"routeSpeedLimitWhiteDisc",yellowDisc:"routeSpeedLimitYellowDisc",plaque:"routeSpeedLimitPlaque"},postedSpeedLimit=(e,t)=>"mph"===t?5*Math.round(1e3*e/MILE_IN_METERS/5):e,RoutingModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t),this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&(this.config=this._applyConfig(this.config))}),onStylingKnobsApplied(e,trafficDelayColorKnobIds,()=>this.repaintTrafficSections())}repaintTrafficSections(){const{incidents:e}=this.buildLayersSpecs(this.config);isEqual(e,this.layersSpecs.incidents)||(updateLayersAndSource(e,this.layersSpecs.incidents,this.sourcesWithLayers.incidents,this.mapLibreMap),this.layersSpecs={...this.layersSpecs,incidents:e})}routeColorOf(e){return e?.color??mapAccentColor(this.tomtomMap)}buildLayersSpecs(e){return((e={},t)=>({...Object.fromEntries(generatedSectionTypes.map(i=>[sectionSourceKey(i),mapLayerSpecs(e.sections?.[i],t)])),mainLines:mapLayerSpecs(e.mainLines,t),waypoints:mapLayerSpecs(e.waypoints,t),chargingStops:mapLayerSpecs(e?.chargingStops,t),ferries:mapLayerSpecs(e.sections?.ferry,t),incidents:mapLayerSpecs(e.sections?.traffic,t),tollRoads:mapLayerSpecs(e.sections?.tollRoad,t),tunnels:mapLayerSpecs(e.sections?.tunnel,t),vehicleRestricted:mapLayerSpecs(e.sections?.vehicleRestricted,t),instructionLines:mapLayerSpecs(e.instructionLines,t),instructionArrows:mapLayerSpecs(e.instructionArrows,t),summaryBubbles:mapLayerSpecs(e.summaryBubbles,t),countryCrossings:mapLayerSpecs(e.countryCrossings,t)}))(buildRoutingLayers({...e,color:this.routeColorOf(e)},this.layerIDPrefix,this.instanceIndex,this.tomtomMap.styleLightDarkTheme,e=>existingBeforeLayerID(this.mapLibreMap,e),trafficDelayColors(this.tomtomMap._stylingSettings)),this.layerIDPrefix)}createSourcesWithLayers(e){const t=suffixNumber("routes",this.instanceIndex);return{...Object.fromEntries(generatedSectionTypes.map(i=>{const r=sectionSourceKey(i);return[r,new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-${r}`,e[r],!1)]})),mainLines:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-mainLines`,e.mainLines,!1),waypoints:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-waypoints`,e.waypoints,!1),incidents:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-incidents`,e.incidents,!1),ferries:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-ferries`,e.ferries,!1),chargingStops:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-chargingStops`,e.chargingStops,!1),tollRoads:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-tollRoads`,e.tollRoads,!1),tunnels:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-tunnels`,e.tunnels,!1),vehicleRestricted:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-vehicleRestricted`,e.vehicleRestricted,!1),instructionLines:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-instructionLines`,e.instructionLines,!1),instructionArrows:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-instructionArrows`,e.instructionArrows,!1),summaryBubbles:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-summaryBubbles`,e.summaryBubbles,!1),countryCrossings:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-countryCrossings`,e.countryCrossings,!1)}}_initSourcesWithLayers(e,t){t||(this.layerIDPrefix=suffixNumber("routes",this.instanceIndex));const i=this.routeColorOf(e);this.layersSpecs=this.buildLayersSpecs(e);const r=this.createSourcesWithLayers(this.layersSpecs);addLayers(Object.values(r).flatMap(e=>e._layerSpecs),this.mapLibreMap),this.appliedRouteColor=i;const o={fillColor:i,...e?.waypoints?.icon?.style},s={pixelRatio:2},a=suffixNumber("waypointStart",this.instanceIndex),n=suffixNumber("waypointStop",this.instanceIndex),l=suffixNumber("waypointFinish",this.instanceIndex),c=suffixNumber("instruction-arrow",this.instanceIndex),d=suffixNumber("selected-route-summary-popup",this.instanceIndex),p=suffixNumber("deselected-route-summary-popup",this.instanceIndex),u=suffixNumber("traffic-clear",this.instanceIndex),h=suffixNumber("traffic-major",this.instanceIndex),y=suffixNumber("traffic-moderate",this.instanceIndex),f=suffixNumber("traffic-minor",this.instanceIndex);this.addImageIfNotExisting(a,waypointStartIcon(o),s),this.addImageIfNotExisting(n,waypointIcon(void 0,o),s),this.addImageIfNotExisting(l,waypointFinishIcon(o),s),this.addImageIfNotExisting(c,instructionArrowIconImg,s),this.addImageIfNotExisting(d,summaryMapBubbleImg("white"),summaryBubbleImageOptions),this.addImageIfNotExisting(p,summaryMapBubbleImg("#EEEEEE"),summaryBubbleImageOptions);for(const[m,g]of Object.entries(SPEED_LIMIT_IMAGE_ID_BY_FACE))this.addImageIfNotExisting(suffixNumber(g,this.instanceIndex),speedLimitSignImg(m),s);for(const[m,g]of Object.entries(SECTION_START_SIGN_IMAGE_IDS))this.addImageIfNotExisting(suffixNumber(g,this.instanceIndex),sectionStartSignImg(m),s);this.appliedCrossingColors=void 0,this.addImageIfNotExisting(suffixNumber("route-country-crossing-plaque",this.instanceIndex),countryCrossingPlaqueImg(this.crossingColors(this.config).plaque),{...s,...countryCrossingPlaqueImageOptions}),this.addImageIfNotExisting(u,trafficImg("#000000"),s),this.addImageIfNotExisting(h,trafficImg("#AD0000"),s),this.addImageIfNotExisting(y,trafficImg("#FB2D09"),s),this.addImageIfNotExisting(f,trafficImg("#f58240"),s);for(const m of e?.chargingStops?.icon?.customIcons??[])this.addImageIfNotExisting(m.id,m.image,{pixelRatio:m.pixelRatio??2});return r}_applyConfig(e){const t=routeDisplayUnits(e),i=!isEqual(this.appliedDisplayUnits,t);this.appliedDisplayUnits=t;const r=this.routeColorOf(e);if(!this._initializing){const t=this.buildLayersSpecs(e);Object.keys(t).forEach(e=>{const i=e;updateLayersAndSource(t[i],this.layersSpecs[i],this.sourcesWithLayers[i],this.mapLibreMap)});const r=Object.values(this.sourcesWithLayers);addLayers(r.flatMap(e=>e._layerSpecs),this.mapLibreMap,!isEqual(this.config?.beforeLayerConfig,e?.beforeLayerConfig)),this.reshowSpeedLimitSigns(e,i),this.applySignPriority(e),this.layersSpecs=t}const o=r!==this.appliedRouteColor;if(this.appliedRouteColor=r,o){const t={fillColor:r,...e?.waypoints?.icon?.style},i={pixelRatio:2};addOrUpdateImage("add-or-update",suffixNumber("waypointStart",this.instanceIndex),waypointStartIcon(t),this.mapLibreMap,i),addOrUpdateImage("add-or-update",suffixNumber("waypointStop",this.instanceIndex),waypointIcon(void 0,t),this.mapLibreMap,i),addOrUpdateImage("add-or-update",suffixNumber("waypointFinish",this.instanceIndex),waypointFinishIcon(t),this.mapLibreMap,i)}const s=!1!==e?.summaryBubbles?.visible,a=!isEqual(this.config?.summaryBubbles?.visible,e?.summaryBubbles?.visible),n=this.sourcesWithLayers.summaryBubbles.shownFeatures.features.length>0,l=this.sourcesWithLayers.mainLines.shownFeatures.features.length>0;return!s&&a?this.sourcesWithLayers.summaryBubbles.clear():s&&(a&&l||i&&n)&&this.sourcesWithLayers.summaryBubbles.show(toDisplayRouteSummaries(this.sourcesWithLayers.mainLines.shownFeatures,t)),this.applyCountryCrossingConfig(e),this.applyVisibility(e),e}showSpeedLimitSections(e,t){var i,r;this.sourcesWithLayers.speedLimitSections.show(toDisplayRouteSections(e,"speedLimit",(i=this.instanceIndex,r={unit:t?.sections?.speedLimit?.sign?.unit,displayUnits:routeDisplayUnits(t)},(e,t)=>{const o=(s=e.startPointIndex,a=t?.sections.country,a?.find(e=>s>=e.startPointIndex&&s<=e.endPointIndex)?.countryCodeISO3);var s,a;const n=o?SIGN_BY_COUNTRY[o]??{}:SIGN_BY_DISPLAY_UNITS[r?.displayUnits?.distance?.type??TomTomConfig.instance.get().displayUnits?.distance?.type??"metric"],l=n.face??"whiteDisc",c=r?.unit??n.unit??"km/h";return{...e,signImageID:suffixNumber(SPEED_LIMIT_IMAGE_ID_BY_FACE[l],i),signLabel:String(postedSpeedLimit(e.maxSpeedLimitInKmh,c)),signFace:l,signNumeralsColor:n.numerals??"#1A2024"}})))}crossingColors(e){return resolveCountryCrossingColors(e?.countryCrossings,this.tomtomMap.styleLightDarkTheme)}applyCountryCrossingConfig(e){const t=!1!==e?.countryCrossings?.visible,i=!isEqual(this.config?.countryCrossings?.visible,e?.countryCrossings?.visible);!t&&i?this.sourcesWithLayers.countryCrossings.clear():t&&i&&this.sourcesWithLayers.countryCrossings.show(toDisplayCountryCrossings(this.sourcesWithLayers.mainLines.shownFeatures));const r=this.crossingColors(e);if(isEqual(this.appliedCrossingColors,r))return;this.appliedCrossingColors=r,addOrUpdateImage("add-or-update",suffixNumber("route-country-crossing-plaque",this.instanceIndex),countryCrossingPlaqueImg(r.plaque),this.mapLibreMap,countryCrossingPlaqueImageOptions);const o=prefixLayerID("routeCountryCrossing",this.layerIDPrefix);this.mapLibreMap.getLayer(o)&&this.mapLibreMap.setPaintProperty(o,"text-color",r.text,{validate:!1})}reshowSpeedLimitSigns(e,t){isEqual(this.config?.sections?.speedLimit?.sign?.unit,e?.sections?.speedLimit?.sign?.unit)&&!t||this.sourcesWithLayers.speedLimitSections.shownFeatures.features.length&&this.showSpeedLimitSections(this.sourcesWithLayers.mainLines.shownFeatures,e)}applyVisibility(e){const t=!1!==e?.visible;for(const i of Object.values(this.sourcesWithLayers))i.setLayersVisible(t&&!!i.shownFeatures.features.length);for(const i of drawnSectionTypes)isSectionVisible(i,e?.sections?.[i])||this.sourcesWithLayers[sectionSourceKey(i)].setLayersVisible(!1)}signLayerID(e){if(postsSign(e))return prefixLayerID(sectionSignLayerID(e),this.layerIDPrefix)}applySignPriority(e){for(const t of generatedSectionTypes){const i=this.signLayerID(t);if(!i||!this.mapLibreMap.getLayer(i))continue;const r=e?.sections?.[t];this.mapLibreMap.moveLayer(i,this.signAnchorLayerID(i,r))}}signAnchorLayerID(e,t){const i=(e=>e?.sign?.priority??("atChange"===signPlacement(e)?"belowRouteIcons":"belowMapLabels"))(t);if("aboveRouteIcons"===i)return;const r=this.mapLibreMap.getStyle().layers;if("belowMapLabels"===i)return mapStyleLayerIDs.lowestLabel;const o=r.findIndex(e=>e.id===mapStyleLayerIDs.lowestLabel),s=new Set(["routeLineArrows","routeInstructionArrowSymbol"].map(e=>prefixLayerID(e,this.layerIDPrefix)));return r.find((t,i)=>"symbol"===t.type&&t.id!==e&&!s.has(t.id)&&i>o&&(!this.layerIDPrefix||t.id.startsWith(this.layerIDPrefix)))?.id}discardShownData(){}restoreDataAndConfigImpl(){const e=Object.fromEntries(Object.entries(this.sourcesWithLayers).map(([e,t])=>[e,t.shownFeatures]));this.initSourcesWithLayers(this.config,!0),this._applyConfig(this.config);for(const t of Object.keys(e))this.sourcesWithLayers[t].show(e[t]);this.applyVisibility(this.config)}addImageIfNotExisting(e,t,i){addOrUpdateImage("if-not-in-sprite",e,t,this.mapLibreMap,i)}async showRoutes(e,t){const i=toDisplayRoutes(e,t?.selectedIndex);await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.show(i),this.sourcesWithLayers.vehicleRestricted.show(toDisplayRouteSections(i,"vehicleRestricted")),this.sourcesWithLayers.incidents.show(toDisplayRouteSections(i,"traffic",toDisplayTrafficSectionProps)),this.sourcesWithLayers.chargingStops.show(((e,t)=>{const i=[];if(!1!==t?.chargingStops?.visible)for(const r of e.features)for(const e of r.properties.sections.leg){const o=e.summary.chargingInformationAtEndOfLeg;if(o){const s=o.properties,a=formatDuration(e.summary.stopTimeInSeconds??s.chargingTimeInSeconds,t?.displayUnits?.time);i.push({...o,properties:{...o.properties,id:o.properties.chargingParkId??generateId(),iconID:getIconID(o,t),title:formatTitle(o),chargingPower:`${s.chargingConnectionInfo?.chargingPowerInkW} kW`,chargingDuration:formatDuration(s.chargingTimeInSeconds,t?.displayUnits?.time),...a&&{stopDuration:a},routeState:r.properties.routeState,routeIndex:r.properties.index}})}}return{type:"FeatureCollection",features:i}})(i,this.config)),this.sourcesWithLayers.ferries.show(toDisplayRouteSections(i,"ferry")),this.sourcesWithLayers.tunnels.show(toDisplayRouteSections(i,"tunnel")),this.sourcesWithLayers.tollRoads.show(toDisplayRouteSections(i,"tollRoad"));for(const r of generatedSectionTypes)postsSign(r)||this.sourcesWithLayers[sectionSourceKey(r)].show(toDisplayRouteSections(i,r));this.showSpeedLimitSections(i,this.config),this.applySignPriority(this.config),this.sourcesWithLayers.instructionLines.show((e=>({type:"FeatureCollection",features:e.features.flatMap((e,t)=>e.properties.guidance?.instructions?.filter(e=>e.routePath?.length).map(i=>({type:"Feature",geometry:{type:"LineString",coordinates:i.routePath.map(e=>e.point)},properties:{...i,id:generateId(),routeIndex:t,routeState:e.properties.routeState}}))||[])}))(i)),this.sourcesWithLayers.instructionArrows.show((e=>({type:"FeatureCollection",features:e.features.flatMap((e,t)=>e.properties.guidance?.instructions?.filter(e=>e.routePath?.length&&e.routePath.length>1).map(i=>{const r=[i.routePath[i.routePath.length-2]?.point,i.routePath[i.routePath.length-1]?.point];return{type:"Feature",geometry:{type:"Point",coordinates:r[1]},properties:{...i,id:generateId(),routeIndex:t,routeState:e.properties.routeState,lastPointBearingDegrees:bearing(r[0],r[1])}}})||[])}))(i)),!1!==this.config?.countryCrossings?.visible?this.sourcesWithLayers.countryCrossings.show(toDisplayCountryCrossings(i)):this.sourcesWithLayers.countryCrossings.clear(),!1!==this.config?.summaryBubbles?.visible?this.sourcesWithLayers.summaryBubbles.show(toDisplayRouteSummaries(i,routeDisplayUnits(this.config))):this.sourcesWithLayers.summaryBubbles.clear(),this.applyVisibility(this.config);for(const r of this.shownFeaturesHandlers)r({routes:e})}async clearRoutes(){await this.waitUntilModuleReady();for(const e of Object.keys(this.sourcesWithLayers))"waypoints"!==e&&this.sourcesWithLayers[e].clear()}async selectRoute(e){const t=toDisplayRoutes(this.sourcesWithLayers.mainLines.shownFeatures,e);await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.show(t),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.chargingStops),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.vehicleRestricted),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.incidents),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.ferries),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.tollRoads);for(const i of generatedSectionTypes)showFeaturesWithRouteSelection(t,this.sourcesWithLayers[sectionSourceKey(i)]);showFeaturesWithRouteSelection(t,this.sourcesWithLayers.tunnels),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionLines),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionArrows),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.summaryBubbles),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.countryCrossings),this.applyVisibility(this.config)}async showWaypoints(e){const t=routeDisplayUnits(this.config)?.time,i=Array.isArray(e)?toDisplayWaypoints(e,this.config?.waypoints,this.instanceIndex,t):toDisplayWaypoints(e.features,this.config?.waypoints,this.instanceIndex,t);await this.waitUntilModuleReady(),this.sourcesWithLayers.waypoints.show(i),this.applyVisibility(this.config),this.applySignPriority(this.config);for(const r of this.shownFeaturesHandlers)r({waypoints:e})}async clearWaypoints(){await this.waitUntilModuleReady(),this.sourcesWithLayers.waypoints.clear()}getShown(){return{mainLines:this.sourcesWithLayers.mainLines.shownFeatures,waypoints:this.sourcesWithLayers.waypoints.shownFeatures,incidents:this.sourcesWithLayers.incidents.shownFeatures,ferries:this.sourcesWithLayers.ferries.shownFeatures,chargingStops:this.sourcesWithLayers.chargingStops.shownFeatures,tollRoads:this.sourcesWithLayers.tollRoads.shownFeatures,...Object.fromEntries(generatedSectionTypes.map(e=>[sectionSourceKey(e),this.sourcesWithLayers[sectionSourceKey(e)].shownFeatures])),tunnels:this.sourcesWithLayers.tunnels.shownFeatures,vehicleRestricted:this.sourcesWithLayers.vehicleRestricted.shownFeatures,instructionLines:this.sourcesWithLayers.instructionLines.shownFeatures,instructionArrows:this.sourcesWithLayers.instructionArrows.shownFeatures,summaryBubbles:this.sourcesWithLayers.summaryBubbles.shownFeatures,countryCrossings:this.sourcesWithLayers.countryCrossings.shownFeatures}}get events(){const e=Object.fromEntries(generatedSectionTypes.map(e=>[sectionSourceKey(e),this.userEvents([sectionSourceKey(e)])]));return this.buildEvents(this.moduleEventsWithShown(["mainLines","waypoints","chargingStops","summaryBubbles","countryCrossings","incidents","vehicleRestricted","ferries","tollRoads","tunnels","instructionLines",...generatedSectionTypes.map(sectionSourceKey)],this.shownFeaturesHandlers),{...e,mainLines:this.userEvents(["mainLines"]),waypoints:this.userEvents(["waypoints"]),chargingStops:this.userEvents(["chargingStops"]),summaryBubbles:this.userEvents(["summaryBubbles"]),countryCrossings:this.userEvents(["countryCrossings"],{mapping:e=>((e,t)=>{const i=e.properties,r=t.features[i.routeIndex]?.properties.sections.country??[],o=e=>r.find(t=>t.startPointIndex===e);return{type:"Feature",id:e.id,geometry:e.geometry,properties:{...i,fromSection:o(i.fromSectionStartPointIndex),toSection:o(i.toSectionStartPointIndex)}}})(e,this.sourcesWithLayers.mainLines.shownFeatures)}),incidents:this.userEvents(["incidents"]),vehicleRestricted:this.userEvents(["vehicleRestricted"]),ferries:this.userEvents(["ferries"]),tollRoads:this.userEvents(["tollRoads"]),tunnels:this.userEvents(["tunnels"]),instructionLines:this.userEvents(["instructionLines"])})}getLayerToRenderLinesUnder(){const e=prefixLayerID("routeLineArrows",this.layerIDPrefix);return this.layersSpecs.mainLines.find(t=>t.id===e)?.beforeID}},FACTOR_RANGE={min:.5,max:1.5,step:.1,bounds:"hard"},WIDE_FACTOR_RANGE={min:.5,max:2,step:.1,bounds:"hard"},baseMapSymbols={sourceTypes:["vector"],layerTypes:["symbol"]},poiLayers={sources:["vectorTiles"],sourceLayers:["poi"],layerTypes:["symbol"]},roadLines={...baseMapLayerGroupSelector("roads"),layerTypes:["line"]},trafficLayers=e=>(t,i)=>({sources:[e],layerTypes:["line"],idIncludes:[i?`${t} outline`:t],...i?{}:{idExcludes:["outline"]}}),flowLayers=trafficLayers("vectorTilesFlow"),incidentLayers=trafficLayers("vectorTilesIncidents"),factor=(e,t,i=FACTOR_RANGE)=>({kind:"factor",description:e,range:i,appliesTo:"any-style",mechanisms:t}),toggle=(e,t)=>({kind:"toggle",description:e,appliesTo:"tomtom-styles",mechanisms:[{type:"visibility",layers:t}]}),groupToggle=(e,t)=>({kind:"toggle",description:e,appliesTo:"tomtom-styles",mechanisms:[{type:"baseMapGroup",group:t}]}),color=(e,t,i,r)=>({kind:"color",description:e,appliesTo:"tomtom-styles",mechanisms:[{type:"color",property:t,layers:i,shades:r}]}),hillshadeLayers={layerTypes:["hillshade"]},groupsWithOwnKnob=/* @__PURE__ */new Set(["buildings2D","buildings3D","roadShields"]),basemapToggles=/* @__PURE__ */(()=>Object.fromEntries(baseMapLayerGroupNames.filter(e=>!(e=>groupsWithOwnKnob.has(e))(e)).map(e=>[`basemap.${e}`,groupToggle(`${describeLayerGroup(e)} The same state as BaseMapModule's \`groups.${e}.visible\`.`,e)])))(),mapColor=e=>({kind:"color",description:mapColorDefinitions[e].description,appliesTo:"tomtom-styles",mechanisms:[{type:"mapColor",color:e}]}),trafficColor=e=>(t,i)=>color(t,"line-color",[e(i,!1)],[e(i,!0)]),flowColor=trafficColor(flowLayers),incidentColor=trafficColor(incidentLayers),knobDefinitions=/* @__PURE__ */(()=>({"labels.sizeFactor":factor("Size of every base-map text label (places, roads, POIs, house numbers).",[{type:"scale",property:"text-size",layers:[baseMapSymbols]}]),"symbols.sizeFactor":factor("Size of every base-map icon (POI icons, route shields, road arrows).",[{type:"scale",property:"icon-size",layers:[baseMapSymbols]}]),"roads.widthFactor":factor("Width of all road lines, keeping the hierarchy motorway → path.",[{type:"scale",property:"line-width",layers:[roadLines]}]),"pois.sizeFactor":factor("Size of the base-map POI icons and their labels.",[{type:"scale",property:"icon-size",layers:[poiLayers]},{type:"scale",property:"text-size",layers:[poiLayers]}]),"pois.minZoom":{kind:"number",description:"Zoom level from which base-map POIs appear (the style default is 6).",range:{min:3,max:18,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"minZoom",layers:[{...poiLayers,idExcludes:["micro"]}]}]},"pois.zoomShift":{kind:"number",description:"Shifts the zoom at which each POI appears: positive = later and sparser, negative = earlier and denser.",range:{min:-3,max:3,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"zoomOffset",layers:[poiLayers]}]},"pois.labelColor":color("Text colour of base-map POI labels (replaces the per-category colours).","text-color",[poiLayers]),"pois.labelOutlineColor":color("Halo colour of base-map POI labels.","text-halo-color",[poiLayers]),"pois.microMarkers":toggle("The small dot markers for low-priority POIs at high zoom.",[{...poiLayers,idIncludes:["micro"]}]),"roads.exitNumbers":toggle("Motorway exit number badges.",[{metadataGroups:["road_label"],layerTypes:["symbol"],idIncludes:["exit"]}]),"roads.shields":groupToggle("Route shields along roads.","roadShields"),"roads.arrows":toggle("One-way arrows drawn on roads.",[{metadataGroups:["road"],layerTypes:["symbol"],idIncludes:["arrow"]}]),"roads.restricted":toggle("Dashed marking of roads with restricted access.",[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["restricted"]}]),"roads.underConstruction":toggle("Roads under construction.",[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["construction"]}]),"buildings.footprints":groupToggle("2D building footprints, shadows and outlines.","buildings2D"),"buildings.3d":groupToggle("Extruded 3D buildings (hidden by default in the standard styles).","buildings3D"),"traffic.flow.freeColor":flowColor("Traffic flow colour for free-flowing roads.","free flow"),"traffic.flow.slowColor":flowColor("Traffic flow colour for slow traffic.","slow flow"),"traffic.flow.queueingColor":flowColor("Traffic flow colour for queueing traffic.","queueing flow"),"traffic.flow.stationaryColor":flowColor("Traffic flow colour for stationary traffic.","stationary flow"),"traffic.flow.closedColor":color("Traffic flow colour for closed roads.","line-color",[flowLayers("closed road",!0)]),"traffic.flow.widthFactor":factor("Width of the traffic flow tubes.",[{type:"scale",property:"line-width",layers:[{sources:["vectorTilesFlow"],layerTypes:["line"]}]}],WIDE_FACTOR_RANGE),"traffic.incidents.minorColor":incidentColor("Traffic incident tube colour for minor delays.","minor jam"),"traffic.incidents.moderateColor":incidentColor("Traffic incident tube colour for moderate delays.","moderate jam"),"traffic.incidents.majorColor":incidentColor("Traffic incident tube colour for major delays.","major jam"),"traffic.incidents.closedColor":color("Traffic incident tube colour for closed roads.","line-color",[incidentLayers("closed road",!0)]),"traffic.incidents.widthFactor":factor("Width of the traffic incident tubes.",[{type:"scale",property:"line-width",layers:[{sources:["vectorTilesIncidents"],layerTypes:["line"]}]}],WIDE_FACTOR_RANGE),"colors.land":mapColor("land"),"colors.water":mapColor("water"),"colors.vegetation":mapColor("vegetation"),"colors.park":mapColor("park"),"colors.artificial":mapColor("artificial"),"colors.roadMajor":mapColor("roadMajor"),"colors.road":mapColor("road"),"colors.roadOutline":mapColor("roadOutline"),"colors.label":mapColor("label"),"colors.labelOutline":mapColor("labelOutline"),"colors.accent":{kind:"color",description:"The colour for what is drawn on top of the map — routes, geometries, places. Not a base-map layer: the modules that draw their own layers default to it when a theme sets it.",appliesTo:"any-style",mechanisms:[{type:"published"}]},...basemapToggles,"hillshade.method":{kind:"enum",description:"How the relief is shaded: standard (one light), basic, igor (softer), combined, or multidirectional (four lights).",options:["standard","basic","igor","combined","multidirectional"],appliesTo:"tomtom-styles",mechanisms:[{type:"paintLiteral",property:"hillshade-method",layers:[hillshadeLayers]}]},"hillshade.lightDirection":{kind:"number",description:"Direction the light comes from, in degrees clockwise from north (335 is the cartographic default).",range:{min:0,max:359,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"paintLiteral",property:"hillshade-illumination-direction",layers:[hillshadeLayers]}]},"hillshade.exaggeration":{kind:"number",description:"Strength of the shading (0 = flat), not the 3D surface height (TerrainModule elevationExaggeration). The standard styles ramp it to zero by zoom 13; setting it replaces the ramp with a constant.",range:{min:0,max:1,step:.05,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"paintLiteral",property:"hillshade-exaggeration",layers:[hillshadeLayers]}]},"hillshade.maxZoom":{kind:"number",description:"Zoom level up to which the shading is drawn (the standard styles stop at 13; 22 keeps it at every zoom).",range:{min:10,max:22,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"maxZoom",layers:[hillshadeLayers]}]},"hillshade.shadowColor":color("Colour of the shaded slopes.","hillshade-shadow-color",[hillshadeLayers]),"hillshade.highlightColor":color("Colour of the lit slopes.","hillshade-highlight-color",[hillshadeLayers]),"hillshade.accentColor":color("Colour accentuating the steepest terrain.","hillshade-accent-color",[hillshadeLayers]),"view.projection":{kind:"enum",description:"How the map is drawn: flat Mercator or a globe. The globe flattens to Mercator between zoom 11 and 12 by design.",options:["mercator","globe"],appliesTo:"any-style",mechanisms:[{type:"projection"}]},"view.sky":{kind:"toggle",description:"A sky with atmosphere behind the globe and above a tilted flat map. Without it MapLibre draws a fully transparent sky, so a globe arrives with no atmosphere.",appliesTo:"any-style",mechanisms:[{type:"sky"}]},"view.skyColor":{kind:"color",description:"Colour of the sky (and of the atmosphere halo around the globe). Defaults to a daylit blue on a light style and a night blue on a dark one.",appliesTo:"any-style",mechanisms:[{type:"sky"}]},"view.horizonColor":{kind:"color",description:"Colour of the sky at the horizon. Defaults with the style theme, so a dark map gets a dim horizon rather than a white one.",appliesTo:"any-style",mechanisms:[{type:"sky"}]},"view.spaceColor":{kind:"color",description:"Colour behind the map, which a globe leaves visible around the planet. The map canvas is transparent, so without this the page background shows through. Defaults with the style theme: white on a light style, near-black on a dark one.",appliesTo:"any-style",mechanisms:[{type:"space"}]}}))(),stylingKnobIds=/* @__PURE__ */Object.keys(knobDefinitions),stylingKnobCatalogue=/* @__PURE__ */stylingKnobIds.map(e=>{const{mechanisms:t,...i}=knobDefinitions[e];return{id:e,...i}}),stylingColorKnobIds=/* @__PURE__ */stylingKnobIds.filter(e=>"color"===knobDefinitions[e].kind),LayerSelection=class{constructor(e,t){this.registry=e,this.query=t}get layerIds(){return this.registry.resolve(this.query)}setPaint(e){for(const[t,i]of Object.entries(e))this.registry.override(this.query,{kind:"paint",property:t,value:i});return this}setLayout(e){for(const[t,i]of Object.entries(e))this.registry.override(this.query,{kind:"layout",property:t,value:i});return this}setFilter(e){return this.registry.overrideFilter(this.query,e),this}setVisible(e){return this.setLayout({visibility:e?"visible":"none"})}reset(){return this.registry.reset(this.query),this}},LayerOverrides=class{constructor(e,t,i){this.mapLibreMap=e,this.filterComposer=t,this.warn=i,this.layers=[],this.sources={},this.properties=/* @__PURE__ */new Map,this.filters=/* @__PURE__ */new Map}index(e,t){this.layers=e,this.sources=t}clear(){this.properties.clear(),this.filters.clear()}resolve(e){const t=selectorsOf(e),i=this.layers.filter(e=>t.every(t=>matchesLayerSelector(t,e,this.sources))).map(e=>e.id);return 0===i.length&&this.warn(`query:${JSON.stringify(e)}`,`layers.query(${JSON.stringify(e)}) matches no layer in the loaded style; the edit will have no effect.`),i}override(e,t){const i=`${t.kind}:${t.property}`;for(const r of this.resolve(e)){const e=this.properties.get(r)??/* @__PURE__ */new Map,o=e.get(i);e.set(i,{override:t,before:o?o.before:this.read(r,t)}),this.properties.set(r,e),this.write(r,t)}}overrideFilter(e,t){for(const i of this.resolve(e))this.filters.set(i,t),this.filterComposer.setTransform(i,"styling.layers",()=>t)}reset(e){for(const t of this.resolve(e)){for(const{override:e,before:i}of this.properties.get(t)?.values()??[])this.write(t,{...e,value:i});this.properties.delete(t),this.filters.delete(t)&&this.filterComposer.setTransform(t,"styling.layers",void 0)}}reapply(){for(const[e,t]of this.properties)if(this.mapLibreMap.getLayer(e))for(const i of t.values()){const t=this.read(e,i.override);isEqual(t,i.override.value)||(i.before=t),this.write(e,i.override)}for(const[e,t]of this.filters)this.filterComposer.setTransform(e,"styling.layers",()=>t)}read(e,{kind:t,property:i}){const r=this.mapLibreMap;return"paint"===t?r.getPaintProperty(e,i):r.getLayoutProperty(e,i)}write(e,{kind:t,property:i,value:r}){if(!this.mapLibreMap.getLayer(e))return;const o=this.mapLibreMap,s={validate:!1};"paint"===t?o.setPaintProperty(e,i,r,s):o.setLayoutProperty(e,i,r,s)}},selectorsOf=({group:e,...t})=>[t,...e?[baseMapLayerGroupSelector(e)]:[]],stylingPresets={"data-viz":{name:"Data visualisation",description:"A quiet base for your own data on top: fewer labels and markers, thinner roads, no badges competing with the overlay.",settings:{"labels.sizeFactor":.9,"symbols.sizeFactor":.9,"roads.widthFactor":.8,"roads.exitNumbers":!1,"roads.shields":!1,"roads.arrows":!1,"pois.microMarkers":!1,"pois.minZoom":14,"buildings.3d":!1}},"night-driving":{name:"Night driving",description:"Bigger labels and shields, wider roads and traffic tubes, POIs out of the way until close up.",settings:{"labels.sizeFactor":1.2,"symbols.sizeFactor":1.2,"roads.widthFactor":1.2,"roads.exitNumbers":!0,"roads.shields":!0,"roads.arrows":!0,"pois.minZoom":13,"pois.microMarkers":!1,"traffic.flow.widthFactor":1.3,"buildings.3d":!1}},minimal:{name:"Minimal",description:"The bare map: land, water, roads and the main place names. Everything decorative off.",settings:{"labels.sizeFactor":.9,"roads.exitNumbers":!1,"roads.shields":!1,"roads.arrows":!1,"roads.restricted":!1,"roads.underConstruction":!1,"buildings.footprints":!1,"buildings.3d":!1,"pois.microMarkers":!1,"pois.minZoom":16}},globe:{name:"Globe",description:"A globe with an atmosphere for the zoomed-out view; flattens to Mercator as you zoom in.",settings:{"view.projection":"globe","view.sky":!0}}},stylingPresetIds=/* @__PURE__ */Object.keys(stylingPresets),stylingPresetCatalogue=/* @__PURE__ */stylingPresetIds.map(e=>({id:e,...stylingPresets[e],settings:{...stylingPresets[e].settings}})),ZOOM_BOUNDS={minZoom:"minzoom",maxZoom:"maxzoom"},LAYOUT_PROPERTIES=/* @__PURE__ */new Set(["text-size","icon-size"]),PAINT_PROPERTIES=/* @__PURE__ */new Set(["line-width","fill-color","fill-outline-color","line-color","text-color","text-halo-color","fill-extrusion-color","background-color","hillshade-shadow-color","hillshade-highlight-color","hillshade-accent-color","hillshade-method","hillshade-illumination-direction","hillshade-exaggeration"]),SPEC_DEFAULTS={"text-size":16,"icon-size":1,"line-width":1,visibility:"visible",minzoom:0,maxzoom:24,"hillshade-method":"standard","hillshade-illumination-direction":335,"hillshade-exaggeration":.5,"hillshade-shadow-color":"#000000","hillshade-highlight-color":"#FFFFFF","hillshade-accent-color":"#000000"},targetKey=(e,t)=>`${e}|${t}`,SKY_DEFAULTS={light:{"sky-color":"#88c6fc","horizon-color":"#ffffff","sky-horizon-blend":.8,"atmosphere-blend":.8,"fog-color":"#ffffff","fog-ground-blend":.5,"horizon-fog-blend":.8},dark:{"sky-color":"#0a1626","horizon-color":"#2b4a72","sky-horizon-blend":.8,"atmosphere-blend":.8,"fog-color":"#0a1626","fog-ground-blend":.5,"horizon-fog-blend":.8}},SPACE_COLOR_DEFAULTS={light:"#ffffff",dark:"#0a1626"},UNPAINTED_BACKGROUNDS=/* @__PURE__ */new Set(["","transparent","rgba(0, 0, 0, 0)"]),CLEAR_SKY={"sky-color":"transparent","horizon-color":"transparent","fog-color":"transparent","fog-ground-blend":1,"atmosphere-blend":0},StylingModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await BaseMapModule.get(t).catch(()=>{}),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.updateConfig(i)))}constructor(e,t){super(e,t),this.baseMap()?._onGroupsTakenOver(e=>this.dropGroupToggles(e))}dropGroupToggles(e){const t=knobIdsIn(this.config).filter(t=>{const i=baseMapGroupOf(t);return void 0!==i&&e.includes(i)});t.length&&this.applyConfig(omit(this.config,t))}styleChangePriority(){return 100}_initSourcesWithLayers(){return this.indexStyle(this.mapLibreMap.getStyle()),this.refreshSpace(this.config??{}),{}}_applyConfig(e){const t=withoutUndefined(e),i=/* @__PURE__ */new Set([...knobIdsIn(this.config),...knobIdsIn(t)]),r=this.reindexed?i:[...i].filter(e=>this.config?.[e]!==t[e]);this.reindexed=!1;for(const o of r)this.refreshKnob(o,t);return this.tomtomMap.mapReady&&this.layerOverrides.reapply(),this.publish(t,r),Object.keys(t).length?t:void 0}discardShownData(){this.layerOverrides.clear()}get layers(){return{query:e=>new LayerSelection(this.layerOverrides,e)}}applyPreset(e,t={}){const i=stylingPresets[e];if(!i)throw new Error(`Unknown styling preset '${e}'. Known presets: ${stylingPresetIds.join(", ")}.`);t.merge?this.updateConfig(i.settings):this.applyConfig({...i.settings})}get(e){return this.assertKnob(e),this.liveBaseMapGroupVisibility(e)??this.config?.[e]??this.derivedMapColorOf(e)??this.defaultOf(e)}set(e,t){this.assertKnob(e),validate(e,t),this.config={...this.config,[e]:t},this.refreshKnob(e,this.config),this.publish(this.config,[e]),this.emitConfigChange()}reset(e){if(void 0===e)return void this.resetConfig();this.assertKnob(e);const{[e]:t,...i}=this.config??{};this.config=Object.keys(i).length?i:void 0,this.refreshKnob(e,this.config??{}),this.publish(this.config??{},[e]),this.emitConfigChange()}publish(e,t){this.publishMapColors(e);const i=this.tomtomMap._stylingSettings,r=new Set(t);for(const o of knobIdsIn(i))i[o]!==e[o]&&r.add(o);this.tomtomMap._setStylingSettings(e,r)}publishMapColors(e){const t=this.mapColorsOf(e);for(const i of mapColorNames){if(void 0!==t[i])continue;const e=this.defaultOf(mapColorKnobId(i));"string"==typeof e&&(t[i]=e)}this.tomtomMap._setMapColors(t)}setMapColors(e){const t={};for(const[i,r]of Object.entries(e)){if(!isMapColorName(i))throw new Error(`Unknown map colour '${i}'. Known colours: ${mapColorNames.join(", ")}.`);if(void 0===r)continue;const e=mapColorKnobId(i);validate(e,r),t[e]=r}this.updateConfig(t)}exportStyle(){return structuredClone(this.mapLibreMap.getStyle())}get events(){return this.moduleEvents([])}indexStyle(e){const t=e?.layers??[];this.originalValues=/* @__PURE__ */new Map,this.styleSources=e?.sources??{},this.resolved=/* @__PURE__ */new Map,this.scaleKnobsByTarget=/* @__PURE__ */new Map,this.mapColorTargetsByKey=/* @__PURE__ */new Map,this.mapColorTargetsByKnob=/* @__PURE__ */new Map,this.mapColorAnchors=/* @__PURE__ */new Map;const i=standardStyleIdOf(this.tomtomMap.getStyle());this.landDerivedColors=(i&&landDerivedMapColors[i])??[],this.warned=/* @__PURE__ */new Set,this.reindexed=!0,this.layerOverrides??=new LayerOverrides(this.mapLibreMap,this.filterComposer,(e,t)=>this.warnOnce(e,t)),this.layerOverrides.index(t,this.styleSources),this.mapLevelState={projection:e?.projection?.type??"mercator",sky:e?.sky};for(const r of stylingKnobIds){const e=knobDefinitions[r],i=e.mechanisms.map(e=>this.resolveMechanism(r,e,t)),o=new Set(i.flatMap(e=>e.layerIds)).size;this.resolved.set(r,{definition:e,mechanisms:i,targets:o}),0===o&&this.warnOnce(r,`knob '${r}' matches no layer in the loaded style (curated for style version 0.6.0-0); it will have no effect.`)}}resolveMechanism(e,t,i){if("mapColor"===t.type)return{mechanism:t,layerIds:this.resolveMapColor(t.color,i),shadeLayerIds:[]};if("baseMapGroup"===t.type){const e=new Set(this.baseMap()?.getLayerIds(t.group));return{mechanism:t,layerIds:i.filter(t=>e.has(t.id)&&this.capture(t,"visibility")).map(e=>e.id),shadeLayerIds:[]}}if(!("layers"in t))return{mechanism:t,layerIds:["\0map"],shadeLayerIds:[]};const r=i.filter(e=>matchesAnyLayerSelector(t.layers,e,this.styleSources));let o,s=[];switch(t.type){case"scale":o=r.filter(e=>this.capture(e,t.property)).map(e=>e.id);for(const i of o){const r=targetKey(i,t.property);this.scaleKnobsByTarget.set(r,[...this.scaleKnobsByTarget.get(r)??[],e])}break;case"color":{o=r.filter(e=>this.capture(e,t.property)).map(e=>e.id);const e=t.shades??[];s=i.filter(t=>matchesAnyLayerSelector(e,t,this.styleSources)).filter(e=>this.capture(e,t.property)).map(e=>e.id);break}case"visibility":o=r.filter(e=>this.capture(e,"visibility")).map(e=>e.id);break;case"minZoom":case"maxZoom":o=r.map(e=>e.id);for(const e of r)this.capture(e,"minzoom"),this.capture(e,"maxzoom");break;case"paintLiteral":o=r.map(e=>e.id);for(const e of r)this.capture(e,t.property);break;case"zoomOffset":o=r.filter(e=>shiftZoomOffset(layerFilterOf(e),0).patched).map(e=>e.id)}return{mechanism:t,layerIds:o,shadeLayerIds:s}}capture(e,t){const i=styleValueOf(e,t);return void 0!==i&&(this.originalValues.set(targetKey(e.id,t),i),!0)}originalValueOf(e,t){return this.originalValues.get(targetKey(e,t))}resolveMapColor(e,t){const i=mapColorKnobId(e),r=mapColorDefinitions[e],o=[];for(const l of r.targets)for(const i of t.filter(e=>matchesAnyLayerSelector(l.layers,e,this.styleSources)))for(const t of l.properties){if(!this.capture(i,t))continue;const r={color:e,layerId:i.id,property:t,owns:ownershipOf(l),recolorsTints:l.recolorsTints};o.push(r);const s=targetKey(i.id,t);this.mapColorTargetsByKey.set(s,[...this.mapColorTargetsByKey.get(s)??[],r])}this.mapColorTargetsByKnob.set(i,o);const{anchor:s}=r,a=t.find(e=>matchesAnyLayerSelector(s.layers,e,this.styleSources)&&void 0!==styleValueOf(e,s.property)),n=a&&((e,t=()=>!0,i=!1)=>{let r;for(const{literal:o,roadClass:s,keyed:a}of collectColorLiterals(e)){if(!t(s))continue;const e=Math.round(100*(toHsl(o)?.s??0)),n=r?.saturation===e;r&&!(i?r.keyed||!a:e>r.saturation||n&&r.keyed&&!a)||(r={literal:o,saturation:e,keyed:a})}return r?.literal})(styleValueOf(a,s.property),ownershipOf({roadClass:s.roadClass}),s.lastStop);return n&&this.mapColorAnchors.set(i,n),n?[...new Set(o.map(e=>e.layerId))]:[]}refreshKnob(e,t){const i=this.resolved.get(e);if(i&&this.tomtomMap.mapReady)for(const r of i.mechanisms)this.refreshMechanism(e,r,t)}refreshMechanism(e,{mechanism:t,layerIds:i,shadeLayerIds:r},o){switch(t.type){case"color":this.refreshColor(t.property,i,r,o[e]);break;case"projection":this.refreshProjection(o);break;case"sky":this.refreshSky(o);break;case"space":this.refreshSpace(o);break;case"mapColor":this.refreshMapColor(t.color,o);break;case"baseMapGroup":this.baseMap()?._applyKnobVisibility(t.group,o[e]);break;case"visibility":for(const t of i)this.visibilityComposer.setVisible(t,`styling.${e}`,o[e]);break;case"published":break;default:for(const r of i)this.refreshLayer(t,r,o[e],o)}}refreshLayer(e,t,i,r){switch(e.type){case"scale":this.refreshScaledProperty(t,e.property,r);break;case"minZoom":case"maxZoom":this.refreshZoomBound(t,ZOOM_BOUNDS[e.type],i);break;case"paintLiteral":this.setProperty(t,e.property,i??this.originalValueOf(t,e.property));break;case"zoomOffset":this.refreshZoomOffset(t,i)}}refreshSpace(e){const t=this.mapLibreMap.getContainer();this.originalSpaceColor??=paintedBackgroundOf(t),t.style.backgroundColor=e["view.spaceColor"]??this.defaultSpaceColor()}defaultSpaceColor(){return this.originalSpaceColor||SPACE_COLOR_DEFAULTS[this.tomtomMap.styleLightDarkTheme]}refreshMapColor(e,t){const i=this.mapColorsOf(t),r=[e,...this.landDerivedColors.filter(t=>mapColorDerivationInputs(t).includes(e))],o=new Map(r.flatMap(e=>this.mapColorTargetsByKnob.get(mapColorKnobId(e))??[]).map(e=>[targetKey(e.layerId,e.property),e]));for(const{layerId:s,property:a}of o.values())this.refreshMapColorProperty(s,a,i)}derivedMapColorOf(e){const[t]=this.resolved.get(e)?.mechanisms??[];if("mapColor"===t?.mechanism.type&&this.mapColorAnchors.has(e))return this.mapColorsOf(this.config??{})[t.mechanism.color]}mapColorsOf(e){const t={};for(const i of mapColorNames){const r=e[mapColorKnobId(i)];"string"==typeof r&&(t[i]=r)}return withDerivedMapColors(t,this.landDerivedColors,this.mapColorAnchors.get(mapColorKnobId("land")))}refreshMapColorProperty(e,t,i){const r=this.originalValueOf(e,t),o=[],s=this.mapColorTargetsByKey.get(targetKey(e,t))??[];for(const{color:a,owns:n,recolorsTints:l}of s){const e=i[a],t=this.mapColorAnchors.get(mapColorKnobId(a));e&&t&&o.push({anchorColor:t,newColor:e,owns:n,recolorsTints:l})}this.setProperty(e,t,o.length?recolorValue(r,o):r)}refreshProjection(e){const t=e["view.projection"];this.mapLibreMap.setProjection({type:t??this.mapLevelState.projection})}refreshSky(e){const t=this.mapLevelState.sky,i=e["view.sky"]??this.defaultOf("view.sky"),r=SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme],o=i?{...r,...t,"sky-color":e["view.skyColor"]??t?.["sky-color"]??r["sky-color"],"horizon-color":e["view.horizonColor"]??t?.["horizon-color"]??r["horizon-color"]}:CLEAR_SKY;this.mapLibreMap.setSky(o,{validate:!1})}baseMap(){return sharedInstanceIfCreated(this.tomtomMap,BaseMapModule)}liveBaseMapGroupVisibility(e){const[t]=this.resolved.get(e)?.mechanisms??[];if("baseMapGroup"===t?.mechanism.type&&t.layerIds.length)return this.baseMap()?.isVisible({layerGroups:{mode:"include",names:[t.mechanism.group]}})}refreshZoomBound(e,t,i){if(!this.mapLibreMap.getLayer(e))return;const r={minzoom:this.styleZoomBound(e,"minzoom"),maxzoom:this.styleZoomBound(e,"maxzoom")};r[t]=i??r[t],this.mapLibreMap.setLayerZoomRange(e,r.minzoom,r.maxzoom)}styleZoomBound(e,t){return this.originalValueOf(e,t)??SPEC_DEFAULTS[t]}refreshZoomOffset(e,t){this.filterComposer.setTransform(e,"styling.zoomShift",void 0===t?void 0:e=>shiftZoomOffset(e,t).filter)}refreshScaledProperty(e,t,i){const r=this.originalValueOf(e,t),o=(this.scaleKnobsByTarget.get(targetKey(e,t))??[]).reduce((e,t)=>e*(i[t]??1),1);if(1===o)return void this.setProperty(e,t,r);const s=scaleNumericValue(r,o);void 0!==s?this.setProperty(e,t,s):this.warnOnce(`scale:${e}:${t}`,`cannot scale '${t}' of layer '${e}': the style gives it a value this knob cannot scale (a non-numeric value, or an expression holding a nested zoom term); leaving it as the style defines it.`)}refreshColor(e,t,i,r){for(const s of t)this.setProperty(s,e,r??this.originalValueOf(s,e));const o=t.map(t=>this.originalValueOf(t,e)).find(isColorLiteral);for(const s of i){const t=this.originalValueOf(s,e);let i=t;if(void 0!==r){const e=isColorLiteral(t)&&o&&hslShiftBetween(o,t);i=(e&&shiftHsl(r,e))??r}this.setProperty(s,e,i)}}setProperty(e,t,i){if(!this.mapLibreMap.getLayer(e))return;const r=this.mapLibreMap;LAYOUT_PROPERTIES.has(t)?r.setLayoutProperty(e,t,i,{validate:!1}):PAINT_PROPERTIES.has(t)&&r.setPaintProperty(e,t,i,{validate:!1})}defaultOf(e){const t=this.resolved.get(e);if(!t)return;const{definition:i,mechanisms:r}=t;if("factor"===i.kind)return 1;const[o]=r,[s]=o?.layerIds??[];if(void 0!==s){if("mapColor"===o.mechanism.type){const t=this.mapColorAnchors.get(e);return t&&(e=>{const t=toHsl(e);return t&&(t.alpha??1)<1?formatStyleHsl({...t,alpha:void 0}):e})(t)}if("baseMapGroup"===o.mechanism.type)return o.layerIds.some(e=>"none"!==this.originalValueOf(e,"visibility"));if(!("layers"in o.mechanism))return this.mapLevelDefaultOf(e);switch(o.mechanism.type){case"visibility":return"none"!==this.originalValueOf(s,"visibility");case"color":{const e=this.originalValueOf(s,o.mechanism.property);return isColorLiteral(e)?e:void 0}case"minZoom":case"maxZoom":return this.styleZoomBound(s,ZOOM_BOUNDS[o.mechanism.type]);case"paintLiteral":{const e=this.originalValueOf(s,o.mechanism.property);return"string"==typeof e||"number"==typeof e?e:void 0}case"zoomOffset":return 0;default:return}}}mapLevelDefaultOf(e){const{projection:t,sky:i}=this.mapLevelState;switch(e){case"view.projection":return"string"==typeof t?t:void 0;case"view.sky":return void 0!==i&&0!==i["atmosphere-blend"]&&"transparent"!==i["sky-color"];case"view.skyColor":return isColorLiteral(i?.["sky-color"])?i["sky-color"]:SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme]["sky-color"];case"view.horizonColor":return isColorLiteral(i?.["horizon-color"])?i["horizon-color"]:SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme]["horizon-color"];case"view.spaceColor":return this.defaultSpaceColor();default:return}}assertKnob(e){if(!(e in knobDefinitions))throw new Error(`Unknown styling knob '${e}'. stylingKnobIds lists every knob id.`)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[StylingModule] ${t}`))}},mapColorKnobId=e=>`colors.${e}`,ownershipOf=e=>"major"===e.roadClass?e=>"major"===e:"minor"===e.roadClass?e=>"major"!==e:()=>!0,validate=(e,t)=>validateKnobValue({id:e,...knobDefinitions[e]},t),knobIdsIn=e=>Object.keys(e??{}).filter(e=>e in knobDefinitions),withoutUndefined=e=>Object.fromEntries(Object.entries(e??{}).filter(([,e])=>void 0!==e)),baseMapGroupOf=e=>{const[t]=knobDefinitions[e].mechanisms;return"baseMapGroup"===t?.type?t.group:void 0},paintedBackgroundOf=e=>{const t=getComputedStyle(e).backgroundColor;return UNPAINTED_BACKGROUNDS.has(t)?"":t},layerFilterOf=e=>"filter"in e?e.filter:void 0,styleValueOf=(e,t)=>{const i="layout"in e?e.layout:void 0,r="paint"in e?e.paint:void 0;switch(t){case"text-size":return"symbol"===e.type&&void 0!==i?.["text-field"]?i["text-size"]??SPEC_DEFAULTS["text-size"]:void 0;case"icon-size":return"symbol"===e.type&&void 0!==i?.["icon-image"]?i["icon-size"]??SPEC_DEFAULTS["icon-size"]:void 0;case"line-width":return"line"===e.type?r?.["line-width"]??SPEC_DEFAULTS["line-width"]:void 0;case"visibility":return i?.visibility??SPEC_DEFAULTS.visibility;case"minzoom":return e.minzoom;case"maxzoom":return e.maxzoom;default:return paintValueOf(e,t,r)}},paintValueOf=(e,t,i)=>i?.[t]??("hillshade"===e.type&&(e=>e in SPEC_DEFAULTS)(t)?SPEC_DEFAULTS[t]:void 0),stylingKnobKinds=["factor","number","toggle","color","enum"],stylingKnobAppliesTo=["any-style","tomtom-styles"],isLoading=!1,ensureMapLibreCSS=()=>{isLoading||"undefined"==typeof document||(()=>{const e=document.createElement("div");e.className="maplibregl-ctrl-top-left",document.documentElement.append(e);const t="none"===getComputedStyle(e).pointerEvents;return e.remove(),t})()||(isLoading=!0,import("./chunks/maplibre-gl-DJlOK9hg.js").then(({default:e})=>(e=>{const t=`@layer maplibre-gl{${e}}`;if(Reflect.has(document,"adoptedStyleSheets")){const e=new CSSStyleSheet;e.replaceSync(t),document.adoptedStyleSheets=[...document.adoptedStyleSheets,e]}else{const e=document.createElement("style");e.textContent=t,document.head.append(e)}})(e)).finally(()=>{isLoading=!1}).catch(e=>console.error("Could not apply the MapLibre CSS",e)))},TomTomMap=class{get styleLightDarkTheme(){return this._styleLightDarkTheme}get mapColors(){return this._mapColors}_setMapColors(e){if(!isEqual(e,this._mapColors)){this._mapColors=e;for(const e of this.mapColorsHandlers)e(this._mapColors)}}_onMapColorsChange(e){this.mapColorsHandlers.push(e)}get _stylingSettings(){return this.stylingSettings}_setStylingSettings(e,t){if(this.stylingSettings=e,t.size)for(const i of this.stylingAppliedHandlers)i(t)}_onStylingApplied(e){this.stylingAppliedHandlers.push(e)}constructor(e){var t;this.mapReady=!1,this._mapColors={},this.mapColorsHandlers=[],this.stylingSettings={},this.stylingAppliedHandlers=[],this.styleChangeHandlers=[],this.styleRequestSequence=0,this.setStyle=(e,t={})=>{const i={resetState:t.resetState??!1};this.mapReady=!1;const r=++this.styleRequestSequence,o=i.resetState?e:((e,t)=>t&&"object"==typeof t&&"standard"===t.type&&t.include&&("string"==typeof e||"standard"===e.type&&!e.include)?{type:"standard",id:"string"==typeof e?e:e.id,include:t.include}:e)(e,this._params.style);return this._params={...this._params,style:o},this._styleLightDarkTheme=getStyleLightDarkTheme(o),this.applyStyle(i,r)},this.getStyle=()=>this._params.style,this._params=mergeFromGlobal(e),void 0===this._params.style&&(this._params={...this._params,style:"standardLight"}),this._styleLightDarkTheme=getStyleLightDarkTheme(this._params.style),ensureMapLibreCSS(),setWorkerCount(4),this.styleGivenToMapLibre=buildStyleInput(this._params),this.mapLibreMap=new Map$1({validateStyle:!1,maxTileCacheZoomLevels:22,cancelPendingTileRequestsWhileZooming:!1,...(t=this._params).mapLibre,style:buildStyleInput(t),attributionControl:{compact:!1},transformRequest:transformRequest(t)}),this.mapLibreMap.once("style.load",()=>{this.handleStyleData()}),this._eventsProxy=new EventsProxy(this.mapLibreMap,this._params?.events)}async applyStyle(e,t){if(await this.notifyHandlers("onStyleAboutToChange",e),this.isSuperseded(t))return;if(await(this.styleLoadInFlight?.catch(()=>{})),this.isSuperseded(t))return;const i=this.loadIntoMapLibre();this.styleLoadInFlight=i;try{await i}finally{this.styleLoadInFlight===i&&(this.styleLoadInFlight=void 0)}if(!this.isSuperseded(t))try{await this.handleStyleData(e)}catch(r){console.error(r)}}async loadIntoMapLibre(){const e=buildStyleInput(this._params);if(isEqual(e,this.styleGivenToMapLibre))return;const t=this.styleGivenToMapLibre;this.styleGivenToMapLibre=e,await new Promise((i,r)=>{const o=()=>{this.mapLibreMap.off("error",s),i()},s=e=>{"sourceId"in e||(this.mapLibreMap.off("style.load",o),this.mapLibreMap.off("error",s),this.styleGivenToMapLibre=t,r(e.error instanceof Error?e.error:new Error(e.error.message)))};this.mapLibreMap.once("style.load",o),this.mapLibreMap.on("error",s),this.mapLibreMap.setStyle(e,{validate:!1})})}isSuperseded(e){return e!==this.styleRequestSequence}async notifyHandlers(e,t){const i=[...this.styleChangeHandlers].sort((e,t)=>(e.priority??0)-(t.priority??0));for(const o of i)try{await(o[e]?.(t))}catch(r){console.error(r)}}_setTomTomUserAgent(e){this._params={...this._params,"tomtom-user-agent":e},this.mapLibreMap.setTransformRequest(transformRequest(this._params))}_setLanguage(e){this._params={...this._params,language:e};const t=e?.includes("-")?e.split("-")[0]:e;this.mapLibreMap.getStyle().layers.forEach(e=>{if("symbol"===e.type&&(e=>{const t=e.layout?.["text-field"]??"";return!!t&&("{name}"===t||2===t.length&&"name"===t[1]||3===t.length&&Array.isArray(t[1])&&"string"==typeof t[1][1]&&t[1][1].includes("name_")&&Array.isArray(t[2])&&t[2].includes("name"))})(e)){const i=t?["coalesce",["get",`name_${t}`],["get","name"]]:["get","name"];this.mapLibreMap.setLayoutProperty(e.id,"text-field",i,{validate:!1})}})}setLanguage(e){this.mapReady?this._setLanguage(e):this.mapLibreMap.once("styledata",()=>this.setLanguage(e))}setGeopoliticalView(e){this._params={...this._params,geopoliticalView:e},this.mapLibreMap.setTransformRequest(transformRequest(this._params)),this.mapReady&&reloadVectorTiles(this.mapLibreMap)}updateEventsConfig(e){this._eventsProxy.updateConfig(e)}getBBox(){return this.mapLibreMap.getBounds().toArray().flat()}async handleStyleData(e){for(const t of filterLayersBySources(this.mapLibreMap,["vectorTilesIncidents","vectorTilesFlow","hillshade"]))this.mapLibreMap.setLayoutProperty(t.id,"visibility","none",{validate:!1});isCustomStyle(this._params.style)&&!getDeclaredLightDarkTheme(this._params.style)&&(this._styleLightDarkTheme=(e=>{const t=e?.layers?.find(e=>"background"===e?.type);if(!t)return;const[i]=collectColorLiterals(t.paint?.["background-color"]),r=i&&relativeLuminance(i.literal);return void 0!==r?r<.35?"dark":"light":void 0})(this.mapLibreMap.getStyle())??this._styleLightDarkTheme),(async(e,t,i)=>{if(i.getSprite().some(e=>"pinCategories"===e.id))return;const r=new URLSearchParams;e.apiKey&&r.set("key",e.apiKey),r.set("poi",`poi_${t}`),r.set("apiVersion","1"),r.set("apiChannel","preview"),i.addSprite("pinCategories",`${e.commonBaseURL}/maps/orbis/assets/sprites/2.*/sprite?${r}`,{validate:!1})})(this._params,this._styleLightDarkTheme,this.mapLibreMap),this._params.language&&this._setLanguage(this._params.language),this.mapReady=!0,e&&await this.notifyHandlers("onStyleChanged",e)}addStyleChangeHandler(e){this.styleChangeHandlers.push(e);let t=!1;return()=>{if(t)return;t=!0;const i=this.styleChangeHandlers.indexOf(e);-1!==i&&this.styleChangeHandlers.splice(i,1)}}},terrainKnobCatalogue=/* @__PURE__ */withIds({hillshade:{kind:"toggle",description:"The hillshade: light and shadow on the map surface that reveal the relief at any pitch. Its look is the `hillshade.*` styling knobs.",default:!1},elevation:{kind:"toggle",description:"The 3D surface, raised to the elevation data or flattened. Unset: the map's own terrain, if its style or MapLibre code raised one; flat on TomTom styles."},elevationExaggeration:{kind:"number",description:"Vertical scale of the 3D surface, `1` being true elevation; kept while `elevation` is off.",range:{min:.5,max:3,step:.1,bounds:"hard-min"},default:1}}),terrainKnobIds=/* @__PURE__ */terrainKnobCatalogue.map(({id:e})=>e),TerrainModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await ensureAddedToStyle(t,"hillshade","hillshade"),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("hillshade");if(!t)throw notInTheStyle(`init ${e.name} with source ID hillshade`);const i=this.mapLibreMap.getTerrain();return"hillshade-terrain"!==i?.source&&(this.mapTerrain=i),{hillshade:new StyleSourceWithLayers(this.mapLibreMap,t)}}_applyConfig(e){return this.showHillshade(e?.hillshade??!1),this.showElevation(e?.elevation,e?.elevationExaggeration??1),e}setHillshadeVisible(e){this.showHillshade(e),this.storeConfig({hillshade:e})}isHillshadeVisible(){return this.config?.hillshade??!1}setElevationEnabled(e){this.showElevation(e,this.config?.elevationExaggeration??1),this.storeConfig({elevation:e})}isElevationEnabled(){return this.config?.elevation??null!==this.mapLibreMap.getTerrain()}setElevationExaggeration(e){this.showElevation(this.config?.elevation,e),this.storeConfig({elevationExaggeration:e})}get events(){return this.lifecycleEvents()}showHillshade(e){this.tomtomMap.mapReady&&this.sourcesWithLayers.hillshade.setLayersVisible(e)}showElevation(e,t){this.tomtomMap.mapReady&&(void 0===e?this.overridesMapTerrain&&this.mapLibreMap.setTerrain(this.mapTerrain):e?(new TomTomMapSource("hillshade-terrain",this.sourcesWithLayers.hillshade.source.spec).ensureAddedToMap(this.mapLibreMap),this.mapLibreMap.setTerrain({source:"hillshade-terrain",exaggeration:t})):this.mapLibreMap.setTerrain(null),this.overridesMapTerrain=void 0!==e)}storeConfig(e){this.config={...this.config,...e},this.emitConfigChange()}},TRAFFIC_LIGHT_COLORS_good="#2dc653",TRAFFIC_LIGHT_COLORS_moderate="#f5a623",TRAFFIC_LIGHT_COLORS_bad="#e03030",higherIsWorseStops=()=>[{value:0,color:TRAFFIC_LIGHT_COLORS_good},{value:50,color:TRAFFIC_LIGHT_COLORS_moderate},{value:100,color:TRAFFIC_LIGHT_COLORS_bad}],higherIsBetterStops=()=>[{value:0,color:TRAFFIC_LIGHT_COLORS_bad},{value:50,color:TRAFFIC_LIGHT_COLORS_moderate},{value:100,color:TRAFFIC_LIGHT_COLORS_good}],AREA_ANALYTICS_DEFAULTS={visible:!0,displayMode:"hexgrid-3d",activeMetric:"congestionLevel",metricConfig:{congestionLevel:{color:{valueType:"raw",stops:higherIsWorseStops()},height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},speed:{color:{valueType:"relativeToPredefinedRangePCT",stops:higherIsBetterStops()},height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},travelTime:{color:{valueType:"relativeToPredefinedRangePCT",stops:higherIsWorseStops()},height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},freeFlowSpeed:{color:{valueType:"relativeToPredefinedRangePCT",stops:higherIsBetterStops()},height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},networkLength:{color:{valueType:"relativeToActualRangePCT",stops:higherIsWorseStops()},height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"currentRange"}}},regionPolygon:{fillOpacity:0,outlineOpacity:.5,outlineWidth:2,inverted:!1}},getThemeAdaptiveRegionPolygonColor=e=>"dark"===e?"#FFFFFF":"#000000",COLOR_THEMES={trafficLight:[TRAFFIC_LIGHT_COLORS_good,TRAFFIC_LIGHT_COLORS_moderate,TRAFFIC_LIGHT_COLORS_bad],heat:["#2196F3","#FF9800","#F44336"],monochrome:["#e0e0e0","#888888","#1a1a1a"],viridis:["#fde725","#35b779","#31688e","#440154"],plasma:["#f0f921","#ed7953","#9c179e","#0d0887"]},DEFAULT_METRIC_RANGES={congestionLevel:{min:0,max:100},speed:{min:0,max:120},travelTime:{min:0,max:20},freeFlowSpeed:{min:0,max:120},networkLength:{min:0,max:5e3}},isSpeedMetric=e=>"speed"===e||"freeFlowSpeed"===e,getActiveMetric=e=>e?.activeMetric??AREA_ANALYTICS_DEFAULTS.activeMetric,getDisplayMode=e=>e?.displayMode??AREA_ANALYTICS_DEFAULTS.displayMode,resolveColorStops=e=>{return"string"==typeof e?(t=COLOR_THEMES[e]).map((e,i)=>({value:1===t.length?0:i/(t.length-1),color:e})):e.stops;var t},DEFAULT_BEFORE_LAYER$1={heatmap:"lowestLabel","hexgrid-2d":"lowestLabel","hexgrid-3d":"lowestPlaceLabel","square-2d":"lowestLabel","square-3d":"lowestPlaceLabel"},beforeIDOf=(e,t)=>beforeLayerIDOf(beforeLayerTargetOf(e?.beforeLayerConfig,t)??DEFAULT_BEFORE_LAYER$1[t]),buildColorExpression=(e,t,i)=>{const r=t??AREA_ANALYTICS_DEFAULTS.metricConfig[e].color??"trafficLight",o=resolveColorStops(r);let s;if("string"==typeof r){const{min:t,max:i}=DEFAULT_METRIC_RANGES[e],r=isSpeedMetric(e)?[...o].reverse().map(e=>e.color):o.map(e=>e.color);s=o.map(({value:e},o)=>[t+e*(i-t),r[o]])}else if("relativeToPredefinedRangePCT"===r.valueType){const{min:t,max:i}=DEFAULT_METRIC_RANGES[e];s=o.map(({value:e,color:r})=>[t+e/100*(i-t),r])}else if("relativeToActualRangePCT"===r.valueType){const{min:t,max:r}=i??DEFAULT_METRIC_RANGES[e];s=o.map(({value:e,color:i})=>[t+e/100*(r-t),i])}else s=o.map(({value:e,color:t})=>[e,t]);return["interpolate",["linear"],["get",e],...s.flatMap(([e,t])=>[e,t])]},buildHeatmapColorExpression=(e,t)=>{const i=t??AREA_ANALYTICS_DEFAULTS.metricConfig[e].color??"trafficLight",r=resolveColorStops(i);let o;if("string"==typeof i){const t=isSpeedMetric(e)?[...r].reverse().map(e=>e.color):r.map(e=>e.color);o=r.flatMap(({value:e},i)=>[.3+.7*e,t[i]])}else if("relativeToPredefinedRangePCT"===i.valueType||"relativeToActualRangePCT"===i.valueType)o=r.flatMap(({value:e,color:t})=>[.3+e/100*.7,t]);else{const e=Math.min(...r.map(e=>e.value)),t=Math.max(...r.map(e=>e.value))-e||1;o=r.flatMap(({value:i,color:r})=>[.3+(i-e)/t*.7,r])}return["interpolate",["linear"],["heatmap-density"],0,"rgba(0,0,0,0)",...o]},buildHeightExpression=(e,t,i)=>{const r=AREA_ANALYTICS_DEFAULTS.metricConfig[e].height,o=t?.minHeightMeters??r.minHeightMeters??0;if("raw"===t?.scaleMode){const i=t.scaleFactor??1;if("speed"===e){const{max:t}=DEFAULT_METRIC_RANGES[e];return["max",o,["*",["-",t,["coalesce",["get","speed"],0]],i]]}return["max",o,["*",["coalesce",["get",e],0],i]]}const s=t?.maxHeightMeters??r.maxHeightMeters??1e3,{min:a,max:n}="currentRange"===(t?.scaleMode??r.scaleMode)?i??DEFAULT_METRIC_RANGES[e]:DEFAULT_METRIC_RANGES[e],l=n-a||1;return"speed"===e?["max",o,["*",["/",["-",n,["coalesce",["get","speed"],0]],l],s]]:["max",o,["*",["/",["-",["coalesce",["get",e],0],a],l],s]]},buildHeatmapLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r],{min:s,max:a}=i??DEFAULT_METRIC_RANGES[r];return{id:e,type:"heatmap",beforeID:beforeIDOf(t,"heatmap"),paint:{"heatmap-weight":["interpolate",["linear"],["get",r],s,0,a,1],"heatmap-intensity":["interpolate",["linear"],["zoom"],10,.5,14,2,16,4],"heatmap-color":buildHeatmapColorExpression(r,o?.color),"heatmap-radius":["interpolate",["linear"],["zoom"],4,1,8,3,12,35,14,80,16,100],"heatmap-opacity":["interpolate",["linear"],["zoom"],4,.8,13,.8,17,0]}}},buildHexFillLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill",beforeID:beforeIDOf(t,"hexgrid-2d"),paint:{"fill-color":buildColorExpression(r,o?.color,i),"fill-opacity":.6}}},buildHexExtrusionLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill-extrusion",beforeID:beforeIDOf(t,"hexgrid-3d"),paint:{"fill-extrusion-color":buildColorExpression(r,o?.color,i),"fill-extrusion-height":buildHeightExpression(r,o?.height,i),"fill-extrusion-base":0,"fill-extrusion-opacity":.75}}},buildSquareFillLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill",beforeID:beforeIDOf(t,"square-2d"),paint:{"fill-color":buildColorExpression(r,o?.color,i),"fill-opacity":.6}}},buildSquareExtrusionLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill-extrusion",beforeID:beforeIDOf(t,"square-3d"),paint:{"fill-extrusion-color":buildColorExpression(r,o?.color,i),"fill-extrusion-height":buildHeightExpression(r,o?.height,i),"fill-extrusion-base":0,"fill-extrusion-opacity":.75}}},resolveRegionConfig=e=>({...AREA_ANALYTICS_DEFAULTS.regionPolygon,...e}),buildRegionFillLayerSpec=(e,t,i)=>{const{color:r,fillOpacity:o}=resolveRegionConfig(t?.regionPolygon);return{id:e,type:"fill",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"fill-color":r??getThemeAdaptiveRegionPolygonColor(i),"fill-opacity":o}}},buildRegionLineLayerSpec=(e,t,i)=>{const{color:r,outlineOpacity:o,outlineWidth:s}=resolveRegionConfig(t?.regionPolygon);return{id:e,type:"line",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"line-color":r??getThemeAdaptiveRegionPolygonColor(i),"line-opacity":o,"line-width":s}}},buildPolygonOutlineLayerSpec=(e,t)=>({id:e,type:"line",beforeID:t,filter:hasActiveEventState,paint:{"line-color":"#ffffff","line-width":["case",isClickEventState,3,2],"line-opacity":["case",isClickEventState,1,.8]}}),buildExtrusionHighlightLayerSpec=e=>({...e,filter:hasActiveEventState,paint:{...e.paint,"fill-extrusion-color":["case",isClickEventState,"#ffffff","#ffffff"],"fill-extrusion-height":["+",e.paint?.["fill-extrusion-height"],.5],"fill-extrusion-opacity":.6}}),buildHexExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildHexExtrusionLayerSpec(e,t,i)),buildSquareExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildSquareExtrusionLayerSpec(e,t,i)),INCIDENT_FOCUS_WIDTH_FACTOR_RANGE={min:1,max:1.8,step:.1,bounds:"hard"},svgMarkup='<svg xmlns="http://www.w3.org/2000/svg" width="48" height="18" viewBox="0 0 48 18">\n<path d="M 18 4 L 30 9 L 18 14" fill="none" stroke="rgba(20, 30, 50, 0.5)" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M 18 4 L 30 9 L 18 14" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',INNER_WIDTH=["interpolate",["exponential",1.5],["zoom"],5,0,9,.96,13,2.1,19,10.8],OUTLINE_WIDTH=["interpolate",["exponential",1.5],["zoom"],5,.75,9,1.96,13,3.6,19,13.8],buildColorExpr=e=>["match",["get","magnitudeOfDelay"],"unknown",e.unknown,"minor",e.minor,"moderate",e.moderate,"major",e.major,"indefinite",e.indefinite,e.major],INNER_PATTERN=["match",["get","magnitudeOfDelay"],"unknown","traffic-incidents-no_delay-pattern","indefinite","traffic-incidents-road_closed-pattern",""],getThemeAdaptiveFocusOutlineColor=e=>"dark"===e?"#FFF":"#000",HALO_WIDTH=["interpolate",["exponential",1.5],["zoom"],5,2.2,9,4.6,13,8.3,19,26],haloOpacity=["case",["==",["feature-state","focused"],!0],1,0],focusWidth=(e,t)=>{if(null===t)return e;const[i,r,o,...s]=e;return[i,r,o,...s.map((e,i)=>i%2==1?["case",["==",["feature-state","focused"],!0],e*t,e]:e)]},SOLID_FILTER=["in",["get","magnitudeOfDelay"],["literal",["minor","moderate","major"]]],PATTERN_FILTER=["in",["get","magnitudeOfDelay"],["literal",["unknown","indefinite"]]],buildCanonicalIncidentLineLayers=(e,t,i,r)=>{const o=r?.widthFactor??null,s=[];return null!==r&&s.push({id:`${e}-focus-halo`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":r.outlineColor,"line-width":HALO_WIDTH,"line-blur":0,"line-opacity":haloOpacity},beforeID:t}),s.push({id:`${e}-outline`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpr(i.outline),"line-width":focusWidth(OUTLINE_WIDTH,o)},beforeID:t},{id:`${e}-inner-solid`,type:"line",minzoom:6,filter:SOLID_FILTER,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpr(i.inner),"line-width":focusWidth(INNER_WIDTH,o)},beforeID:t},{id:`${e}-inner-chevron`,type:"line",minzoom:12,filter:SOLID_FILTER,layout:{"line-cap":"butt","line-join":"round"},paint:{"line-pattern":"tt-traffic-incident-direction-chevron","line-width":focusWidth(INNER_WIDTH,o)},beforeID:t},{id:`${e}-inner-pattern`,type:"line",minzoom:6,filter:PATTERN_FILTER,layout:{"line-cap":"round","line-join":"round"},paint:{"line-pattern":INNER_PATTERN,"line-width":focusWidth(INNER_WIDTH,o)},beforeID:t}),s},ICON_SIZE=["step",["zoom"],.7,14,.8,16,.9,18,1],JAM_TEXT_SIZE=["step",["zoom"],12.6,14,14.4,16,16.2,18,18],INCIDENT_MARKER_ICON=["match",["get","category"],"other","traffic-incidents-info","accident","traffic-incidents-accident","fog","traffic-incidents-fog","danger","traffic-incidents-roadworks","rain","traffic-incidents-rain","frost","traffic-incidents-frost","lane-closed","traffic-incidents-lane_closed","roadworks","traffic-incidents-roadworks","wind","traffic-incidents-wind","flooding","traffic-incidents-flooding","broken-down-vehicle","traffic-incidents-broken_down_vehicle",""],INCIDENT_MARKER_FILTER=["all",["!=",["get","magnitudeOfDelay"],"indefinite"],["any",["!",["has","delayInSeconds"]],["step",["zoom"],[">",["get","delayInSeconds"],900],14,[">",["get","delayInSeconds"],600],15,[">",["get","delayInSeconds"],300],16,!0]]],JAM_MARKER_FILTER=["all",["==",["get","category"],"jam"],["!=",["get","magnitudeOfDelay"],"unknown"],["!=",["get","magnitudeOfDelay"],"indefinite"],["step",["zoom"],[">",["get","delayInSeconds"],900],13,[">",["get","delayInSeconds"],600],14,[">",["get","delayInSeconds"],300],15,!0]],CLOSED_ROAD_FILTER=["==",["get","magnitudeOfDelay"],"indefinite"],JAM_ICON=["concat","traffic-jam-",["get","magnitudeOfDelay"],["case",["<",["get","delayInSeconds"],600],"-small",["<",["get","delayInSeconds"],3600],"-medium","-large"]],JAM_TEXT=["case",["<=",["get","delayInSeconds"],60],"1 min",[">=",["get","delayInSeconds"],3600],["concat",["to-string",["floor",["/",["to-number",["get","delayInSeconds"]],3600]]]," hr ",["case",["==",["%",["round",["/",["to-number",["get","delayInSeconds"]],60]],60],0],"",["concat",["to-string",["round",["%",["/",["to-number",["get","delayInSeconds"]],60],60]]]," min"]]],["concat",["round",["/",["get","delayInSeconds"],60]]," min"]],SORT_KEY=["case",["has","delayInSeconds"],["*",-1,["get","delayInSeconds"]],0],buildCanonicalIncidentSymbolLayers=(e,t)=>[{id:`${e}-incident-marker`,type:"symbol",minzoom:13,filter:INCIDENT_MARKER_FILTER,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-anchor":"bottom-right","icon-offset":[-1,3],"icon-image":INCIDENT_MARKER_ICON,"icon-size":ICON_SIZE,"symbol-sort-key":SORT_KEY},beforeID:t},{id:`${e}-jam-marker`,type:"symbol",minzoom:12,filter:JAM_MARKER_FILTER,layout:{"symbol-placement":"point","icon-anchor":"bottom-left","icon-offset":[2,3],"icon-image":JAM_ICON,"icon-size":ICON_SIZE,"icon-padding":0,"text-anchor":"bottom-left","text-field":JAM_TEXT,"text-font":["NotoSans-CondensedBold"],"text-offset":[2.7,-.75],"text-size":JAM_TEXT_SIZE,"symbol-sort-key":SORT_KEY},paint:{"text-color":"hsl(210, 30%, 14%)"},beforeID:t},{id:`${e}-closed-road-marker`,type:"symbol",minzoom:12,filter:CLOSED_ROAD_FILTER,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-anchor":"bottom-right","icon-offset":[-1,3],"icon-image":"traffic-incidents-road_closed","icon-size":ICON_SIZE},beforeID:t}],roadCategories=["motorway","motorway_link","trunk","trunk_link","primary","primary_link","secondary","secondary_link","tertiary","tertiary_link","street","service","track"],streetRoadSubCategories=["unclassified","residential","living_street"],serviceRoadSubCategories=["parking","driveway","alley"],HEIGHT_METERS_RANGE={min:0,max:5e3,step:50,bounds:"hard-min"},RAW_HEIGHT_SCALE_FACTOR_RANGE={min:0,max:100,step:.1,bounds:"hard-min"},OUTLINE_WIDTH_RANGE={min:0,max:10,step:.5,bounds:"hard-min"},roadFilterKnobDefinitions={"filters.any.0.roadCategories.show":{kind:"enum",description:"`only` keeps just the `filters.any.0.roadCategories.values` road categories, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.roadCategories.values":{kind:"enums",description:"The road categories `filters.any.0.roadCategories.show` keeps alone or drops.",options:roadCategories},"filters.any.0.roadSubCategories.show":{kind:"enum",description:"`only` keeps just the `filters.any.0.roadSubCategories.values` street and service roads, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.roadSubCategories.values":{kind:"enums",description:"The street and service road kinds `filters.any.0.roadSubCategories.show` keeps alone or drops.",options:[...streetRoadSubCategories,...serviceRoadSubCategories]}},flowKnobDefinitions={visible:{kind:"toggle",description:"The traffic flow lines; hidden until shown.",default:!1},...roadFilterKnobDefinitions,"filters.any.0.showRoadClosures":{kind:"enum",description:"`only` draws just the closed roads, `all-except` the flow on every road but them.",options:filterShowModes}},incidentsKnobDefinitions={visible:{kind:"toggle",description:"The traffic incident lines and their icons; hidden until shown.",default:!1},"icons.visible":{kind:"toggle",description:"The incident icons, apart from the lines. Unset follows `visible`."},...roadFilterKnobDefinitions,"filters.any.0.incidentCategories.show":{kind:"enum",description:"`only` keeps just the `filters.any.0.incidentCategories.values` incidents, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.incidentCategories.values":{kind:"enums",description:"The incident categories `filters.any.0.incidentCategories.show` keeps alone or drops.",options:fullTrafficIncidentCategories},"filters.any.0.magnitudes.show":{kind:"enum",description:"`only` keeps just the incidents of the `filters.any.0.magnitudes.values` delay magnitudes, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.magnitudes.values":{kind:"enums",description:"The delay magnitudes `filters.any.0.magnitudes.show` keeps alone or drops.",options:/* @__PURE__ */everyOf()(["unknown","minor","moderate","major","indefinite"])},"filters.any.0.delays.mustHaveDelay":{kind:"toggle",description:"Drop the incidents that report no delay.",default:!1},"filters.any.0.delays.minDelayMinutes":{kind:"number",description:"Drop the incidents delaying traffic by less than this many minutes; those that report no delay stay unless `filters.any.0.delays.mustHaveDelay`.",range:{min:0,max:120,step:5,bounds:"hard-min"}}},overlayKnobDefinitions={visible:{kind:"toggle",description:"The incident layers; hiding them keeps the shown incidents.",default:!0},"focus.outlineColor":{kind:"color",description:"Colour of the outline beneath the focused incidents. Unset: black on light styles, white on dark."},"focus.widthFactor":{kind:"factor",description:"Multiplier on the line width of the focused incidents; `1` keeps the outline alone.",range:INCIDENT_FOCUS_WIDTH_FACTOR_RANGE,default:1.6}},areaAnalyticsKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"The analytics layers, region boundary included.",default:AREA_ANALYTICS_DEFAULTS.visible},displayMode:{kind:"enum",description:"How the cells are drawn: hexagons or squares, flat or raised by the metric, or a heatmap.",options:/* @__PURE__ */everyOf()(["hexgrid-3d","hexgrid-2d","square-3d","square-2d","heatmap"]),default:AREA_ANALYTICS_DEFAULTS.displayMode},activeMetric:{kind:"enum",description:"The metric that colours the cells and raises them in the 3D modes.",options:areaAnalyticsMetricKeys,default:AREA_ANALYTICS_DEFAULTS.activeMetric},"regionPolygon.color":{kind:"color",description:"Fill and outline colour of the region boundary. Unset: black on light styles, white on dark."},"regionPolygon.fillOpacity":{kind:"number",description:"Fill opacity of the region boundary.",range:OPACITY_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.fillOpacity},"regionPolygon.outlineOpacity":{kind:"number",description:"Outline opacity of the region boundary.",range:OPACITY_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.outlineOpacity},"regionPolygon.outlineWidth":{kind:"number",description:"Outline width of the region boundary, in pixels.",range:OUTLINE_WIDTH_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.outlineWidth},"regionPolygon.inverted":{kind:"toggle",description:"Fill the world outside the region rather than the region itself.",default:AREA_ANALYTICS_DEFAULTS.regionPolygon.inverted}}))(),metricKnobDefinitions={color:e=>({kind:"enum",description:`Colour theme of the \`${e}\` cells; custom stops are set in the config. Unset: traffic-light colours, red where traffic is worst.`,options:/* @__PURE__ */everyOf()(["trafficLight","heat","monochrome","viridis","plasma"])}),"height.scaleMode":e=>({kind:"enum",description:`What the \`${e}\` cells' height scales against: the SDK's range for the metric, the loaded data's range, or the raw value.`,options:/* @__PURE__ */everyOf()(["predefinedRange","currentRange","raw"]),default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].height.scaleMode}),"height.maxHeightMeters":e=>({kind:"number",description:`Height of the tallest \`${e}\` cell, in metres, under the \`predefinedRange\` and \`currentRange\` scale modes.`,range:HEIGHT_METERS_RANGE,default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].height.maxHeightMeters}),"height.minHeightMeters":e=>({kind:"number",description:`Height of the lowest \`${e}\` cells, in metres.`,range:HEIGHT_METERS_RANGE,default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].height.minHeightMeters}),"height.scaleFactor":e=>({kind:"number",description:`Metres of height per unit of \`${e}\`, under the \`raw\` scale mode.`,range:RAW_HEIGHT_SCALE_FACTOR_RANGE,default:1}),"filters.min":e=>({kind:"number",description:`Hide the cells whose \`${e}\` is below this value, while \`${e}\` is the active metric.`,range:{...DEFAULT_METRIC_RANGES[e],bounds:"hard-min"}}),"filters.max":e=>({kind:"number",description:`Hide the cells whose \`${e}\` is above this value, while \`${e}\` is the active metric.`,range:{...DEFAULT_METRIC_RANGES[e],bounds:"hard-min"}})},buildAreaAnalyticsCatalogue=()=>{const e=Object.keys(metricKnobDefinitions);return[...withIds(areaAnalyticsKnobDefinitions),...areaAnalyticsMetricKeys.flatMap(t=>e.map(e=>({id:`metricConfig.${t}.${e}`,...metricKnobDefinitions[e](t)})))]},trafficFlowKnobCatalogue=/* @__PURE__ */withIds(flowKnobDefinitions),trafficFlowKnobIds=/* @__PURE__ */trafficFlowKnobCatalogue.map(({id:e})=>e),trafficIncidentsKnobCatalogue=/* @__PURE__ */withIds(incidentsKnobDefinitions),trafficIncidentsKnobIds=/* @__PURE__ */trafficIncidentsKnobCatalogue.map(({id:e})=>e),trafficIncidentOverlayKnobCatalogue=/* @__PURE__ */withIds(overlayKnobDefinitions),trafficIncidentOverlayKnobIds=/* @__PURE__ */trafficIncidentOverlayKnobCatalogue.map(({id:e})=>e),trafficAreaAnalyticsKnobCatalogue=/* @__PURE__ */buildAreaAnalyticsCatalogue(),trafficAreaAnalyticsKnobIds=/* @__PURE__ */trafficAreaAnalyticsKnobCatalogue.map(({id:e})=>e),aggregateTilesIntoCells=(e,t,i)=>((e,t,i)=>{const r=[];for(let o=0;o<e.length;o++){const s=e[o];if(!s)continue;const{congestionSum:a,speedSum:n,freeFlowSum:l,travelTimeSum:c,networkLengthSum:d,count:p}=s,u=`${i}-${o}`;r.push({type:"Feature",id:u,geometry:t.features[o].geometry,properties:{id:u,congestionLevel:Math.round(a/p),speed:Math.round(n/p),freeFlowSpeed:Math.round(l/p),travelTime:Math.round(c/p*10)/10,networkLength:Math.round(d/p)}})}return r})(((e,t)=>{const i=[];for(const r of e)for(let e=0;e<t.features.length;e++)if(booleanPointInPolygon(r.tileCentre,t.features[e])){let t=i[e];void 0===t&&(t={congestionSum:0,speedSum:0,freeFlowSum:0,travelTimeSum:0,networkLengthSum:0,count:0},i[e]=t),t.congestionSum+=r.congestionLevel??0,t.speedSum+=r.speed??0,t.freeFlowSum+=r.freeFlowSpeed??0,t.travelTimeSum+=r.travelTime??0,t.networkLengthSum+=r.networkLength??0,t.count++;break}return i})(e,t),t,i),tilesToGridFeatures=(e,t,i,r)=>{const o=[];for(let s=0;s<e.features.length;s++){const a=e.features[s],n=a.properties?.tiledData?.tiles??[];if(0===n.length)continue;const l=bboxFromGeoJSON(a);if(!l)continue;const c=i([l[0]-.005,l[1]-.005,l[2]+.005,l[3]+.005],t);o.push(...aggregateTilesIntoCells(n,c,`${r}-${s}`))}return{type:"FeatureCollection",features:o}},TrafficAreaAnalyticsModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i??{})}constructor(e,t){super(e,t),this.lastAnalytics=null,this.shownFeaturesHandlers=[]}_initSourcesWithLayers(e,t){const i=this.instanceIndex,r=`area-analytics-heatmap-${i}`,o=`area-analytics-hexgrid-${i}`,s=`area-analytics-square-${i}`,a=`area-analytics-region-${i}`,n=`${r}-layer`,l=`${o}-fill`,c=`${o}-extrusion`,d=`${o}-outline`,p=`${o}-extrusion-highlight`,u=`${s}-fill`,h=`${s}-extrusion`,y=`${s}-outline`,f=`${s}-extrusion-highlight`,m=`${a}-fill`,g=`${a}-line`,S=this.lightDark;this.heatmapLayerSpec=buildHeatmapLayerSpec(n,e),this.hexFillLayerSpec=buildHexFillLayerSpec(l,e),this.hexExtrusionLayerSpec=buildHexExtrusionLayerSpec(c,e),this.squareFillLayerSpec=buildSquareFillLayerSpec(u,e),this.squareExtrusionLayerSpec=buildSquareExtrusionLayerSpec(h,e),this.regionFillLayerSpec=buildRegionFillLayerSpec(m,e,S),this.regionLineLayerSpec=buildRegionLineLayerSpec(g,e,S),this.hexOutlineLayerSpec=((e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"hexgrid-2d")))(d,e),this.hexExtrusionHighlightLayerSpec=buildHexExtrusionHighlightLayerSpec(p,e),this.squareOutlineLayerSpec=((e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"square-2d")))(y,e),this.squareExtrusionHighlightLayerSpec=buildSquareExtrusionHighlightLayerSpec(f,e);const L={heatmap:new GeoJSONSourceWithLayers(this.mapLibreMap,r,[this.heatmapLayerSpec]),hexgrid:new GeoJSONSourceWithLayers(this.mapLibreMap,o,[this.hexFillLayerSpec,this.hexExtrusionLayerSpec]),square:new GeoJSONSourceWithLayers(this.mapLibreMap,s,[this.squareFillLayerSpec,this.squareExtrusionLayerSpec]),region:new GeoJSONSourceWithLayers(this.mapLibreMap,a,[this.regionFillLayerSpec,this.regionLineLayerSpec])};return this.addHighlightLayersToMap(o,s),L}_applyConfig(e){const t=this.config,i=e??{},r=Object.keys(AREA_ANALYTICS_DEFAULTS.metricConfig),o=Object.fromEntries(r.map(e=>[e,{...AREA_ANALYTICS_DEFAULTS.metricConfig[e],...i.metricConfig?.[e]}])),s={activeMetric:AREA_ANALYTICS_DEFAULTS.activeMetric,displayMode:AREA_ANALYTICS_DEFAULTS.displayMode,...i,metricConfig:o};return this.config=s,this.applyLayerConfig(s),(s.regionPolygon||t?.regionPolygon)&&this.applyRegionConfig(s),(s.beforeLayerConfig||t?.beforeLayerConfig)&&this.moveLayersToSpecPositions(),this.applyVisibility(s),s}get modeLayerSpecs(){return[["heatmap",this.heatmapLayerSpec],["hexgrid-2d",this.hexFillLayerSpec],["hexgrid-3d",this.hexExtrusionLayerSpec],["square-2d",this.squareFillLayerSpec],["square-3d",this.squareExtrusionLayerSpec]]}moveLayersToSpecPositions(){for(const[,e]of this.modeLayerSpecs)moveLayerBefore(this.mapLibreMap,e.id,e.beforeID)}discardShownData(){this.lastAnalytics=null}restoreDataAndConfigImpl(){const e=this.lastAnalytics;this.initSourcesWithLayers(this.config,!0),e?(this.isVisible()||this.hideAllDataLayers(),this.show(e)):this.config&&this._applyConfig(this.config)}async show(e){await this.waitUntilModuleReady(),this.lastAnalytics=e,this.sourcesWithLayers.heatmap.show((e=>({type:"FeatureCollection",features:e.features.flatMap(e=>e.properties?.tiledData?.tiles??[]).map((e,t)=>{const[i,r]=e.tileCentre,o=`tile-${t}-${i}-${r}`;return{type:"Feature",id:o,geometry:{type:"Point",coordinates:[i,r]},properties:{id:o,speed:e.speed??0,freeFlowSpeed:e.freeFlowSpeed??0,congestionLevel:e.congestionLevel??0,travelTime:e.travelTime??0,networkLength:e.networkLength??0}}})}))(e),{automaticVisibility:!1}),this.sourcesWithLayers.hexgrid.show(((e,t=.25)=>tilesToGridFeatures(e,t,(e,t)=>hexGrid(e,t,{units:"kilometers"}),"hex"))(e),{automaticVisibility:!1}),this.sourcesWithLayers.square.show(((e,t=.5)=>tilesToGridFeatures(e,t,(e,t)=>squareGrid(e,t,{units:"kilometers"}),"square"))(e),{automaticVisibility:!1});const t=this.config?.regionPolygon?.inverted??AREA_ANALYTICS_DEFAULTS.regionPolygon.inverted;this.sourcesWithLayers.region.show(this.buildRegionFC(e.features,t)),this.applyLayerConfig(this.config),this.applyVisibility(this.config);for(const i of this.shownFeaturesHandlers)i(e)}async clear(){await this.waitUntilModuleReady(),this.lastAnalytics=null,this.sourcesWithLayers.heatmap.clear(),this.sourcesWithLayers.hexgrid.clear(),this.sourcesWithLayers.square.clear(),this.sourcesWithLayers.region.clear()}setMode(e){e!==this.mode&&(this.config={...this.config,displayMode:e},this.applyVisibility(this.config),this.emitConfigChange())}setMetric(e){e!==this.activeMetric&&(this.config={...this.config,activeMetric:e},this.applyLayerConfig(this.config),this.emitConfigChange())}setColor(e,t){const i=Object.keys(AREA_ANALYTICS_DEFAULTS.metricConfig),r=t??i,o={...this.config?.metricConfig};if(void 0===e)for(const s of r){const{color:e,...t}=o[s]??{};o[s]=t}else if("string"==typeof e){const t=(e=>{const t=resolveColorStops(e),i=e=>{const{min:i,max:r}=DEFAULT_METRIC_RANGES[e],o=isSpeedMetric(e)?[...t].reverse().map(e=>e.color):t.map(e=>e.color);return{valueType:"raw",stops:t.map(({value:e},t)=>({value:i+e*(r-i),color:o[t]}))}};return{congestionLevel:{color:i("congestionLevel")},speed:{color:i("speed")},travelTime:{color:i("travelTime")},freeFlowSpeed:{color:i("freeFlowSpeed")},networkLength:{color:i("networkLength")}}})(e);for(const e of r)o[e]={...o[e],...t[e]}}else for(const s of r)o[s]={...o[s],color:e};this.config={...this.config,metricConfig:o},this.applyLayerConfig(this.config),this.emitConfigChange()}setHeight(e,t){const i=Object.keys(AREA_ANALYTICS_DEFAULTS.metricConfig),r=t??i,o={...this.config?.metricConfig};for(const s of r)o[s]={...o[s],height:e};this.config={...this.config,metricConfig:o},this.applyLayerConfig(this.config),this.emitConfigChange()}filter(e,t){const i=Object.keys(AREA_ANALYTICS_DEFAULTS.metricConfig),r=t??i,o={...this.config?.metricConfig};for(const s of r)o[s]={...o[s],filters:e};this.config={...this.config,metricConfig:o},this.applyFiltersToLayers(),this.emitConfigChange()}clearFilter(e){this.filter(void 0,e)}getShown(){return{heatmap:this.sourcesWithLayers.heatmap.shownFeatures,hexgrid:this.sourcesWithLayers.hexgrid.shownFeatures,square:this.sourcesWithLayers.square.shownFeatures}}moveBeforeLayer(e){for(const[t,i]of this.modeLayerSpecs){const r=beforeLayerTargetOf(e,t);void 0!==r&&moveLayerBefore(this.mapLibreMap,i.id,beforeLayerIDOf(r))}this.config={...this.config,beforeLayerConfig:e},this.emitConfigChange()}get events(){return this.moduleEventsWithShown(["hexgrid","square","heatmap"],this.shownFeaturesHandlers)}get mode(){return getDisplayMode(this.config)}get activeMetric(){return getActiveMetric(this.config)}get lightDark(){return this.tomtomMap.styleLightDarkTheme}applyVisibility(e){if(!1===e?.visible)return void this.hideAllDataLayers();const t=getDisplayMode(e),i=this.sourcesWithLayers.heatmap.shownFeatures.features.length>0,r=this.sourcesWithLayers.hexgrid.shownFeatures.features.length>0,o=this.sourcesWithLayers.square.shownFeatures.features.length>0,s=this.sourcesWithLayers.region.shownFeatures.features.length>0;this.sourcesWithLayers.heatmap.setLayersVisible("heatmap"===t&&i),this.sourcesWithLayers.hexgrid.setLayersVisible("hexgrid-3d"===t&&r,e=>e.id===this.hexExtrusionLayerSpec.id),this.sourcesWithLayers.hexgrid.setLayersVisible("hexgrid-2d"===t&&r,e=>e.id===this.hexFillLayerSpec.id),this.sourcesWithLayers.square.setLayersVisible("square-3d"===t&&o,e=>e.id===this.squareExtrusionLayerSpec.id),this.sourcesWithLayers.square.setLayersVisible("square-2d"===t&&o,e=>e.id===this.squareFillLayerSpec.id),this.sourcesWithLayers.region.setLayersVisible(s),this.setHighlightLayerVisible(this.hexOutlineLayerSpec.id,"hexgrid-2d"===t&&r),this.setHighlightLayerVisible(this.hexExtrusionHighlightLayerSpec.id,"hexgrid-3d"===t&&r),this.setHighlightLayerVisible(this.squareOutlineLayerSpec.id,"square-2d"===t&&o),this.setHighlightLayerVisible(this.squareExtrusionHighlightLayerSpec.id,"square-3d"===t&&o)}hideAllDataLayers(){this.sourcesWithLayers.heatmap.setLayersVisible(!1),this.sourcesWithLayers.hexgrid.setLayersVisible(!1),this.sourcesWithLayers.square.setLayersVisible(!1),this.sourcesWithLayers.region.setLayersVisible(!1),this.setHighlightLayerVisible(this.hexOutlineLayerSpec.id,!1),this.setHighlightLayerVisible(this.hexExtrusionHighlightLayerSpec.id,!1),this.setHighlightLayerVisible(this.squareOutlineLayerSpec.id,!1),this.setHighlightLayerVisible(this.squareExtrusionHighlightLayerSpec.id,!1)}addHighlightLayersToMap(e,t){const i=(e,t)=>{this.mapLibreMap.getLayer(e.id)||this.mapLibreMap.addLayer({...e,source:t},existingBeforeLayerID(this.mapLibreMap,e.beforeID)),this.mapLibreMap.setLayoutProperty(e.id,"visibility","none")};i(this.hexOutlineLayerSpec,e),i(this.hexExtrusionHighlightLayerSpec,e),i(this.squareOutlineLayerSpec,t),i(this.squareExtrusionHighlightLayerSpec,t)}setHighlightLayerVisible(e,t){this.mapLibreMap.getLayer(e)&&this.mapLibreMap.setLayoutProperty(e,"visibility",t?"visible":"none")}applyLayerConfig(e){const t=this.lastAnalytics?.properties.ranges?.[this.activeMetric],i=buildHeatmapLayerSpec(this.heatmapLayerSpec.id,e,t),r=buildHexFillLayerSpec(this.hexFillLayerSpec.id,e,t),o=buildHexExtrusionLayerSpec(this.hexExtrusionLayerSpec.id,e,t),s=buildHexExtrusionHighlightLayerSpec(this.hexExtrusionHighlightLayerSpec.id,e,t),a=buildSquareFillLayerSpec(this.squareFillLayerSpec.id,e,t),n=buildSquareExtrusionLayerSpec(this.squareExtrusionLayerSpec.id,e,t),l=buildSquareExtrusionHighlightLayerSpec(this.squareExtrusionHighlightLayerSpec.id,e,t);changeLayerProps(i,this.heatmapLayerSpec,this.mapLibreMap),changeLayerProps(r,this.hexFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.hexExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(s,this.hexExtrusionHighlightLayerSpec,this.mapLibreMap),changeLayerProps(a,this.squareFillLayerSpec,this.mapLibreMap),changeLayerProps(n,this.squareExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(l,this.squareExtrusionHighlightLayerSpec,this.mapLibreMap),this.heatmapLayerSpec=i,this.hexFillLayerSpec=r,this.hexExtrusionLayerSpec=o,this.hexExtrusionHighlightLayerSpec=s,this.squareFillLayerSpec=a,this.squareExtrusionLayerSpec=n,this.squareExtrusionHighlightLayerSpec=l,this.applyFiltersToLayers()}applyRegionConfig(e){const t=this.lightDark,i=buildRegionFillLayerSpec(this.regionFillLayerSpec.id,e,t),r=buildRegionLineLayerSpec(this.regionLineLayerSpec.id,e,t);if(changeLayerProps(i,this.regionFillLayerSpec,this.mapLibreMap),changeLayerProps(r,this.regionLineLayerSpec,this.mapLibreMap),this.regionFillLayerSpec=i,this.regionLineLayerSpec=r,this.lastAnalytics){const t=e?.regionPolygon?.inverted??AREA_ANALYTICS_DEFAULTS.regionPolygon.inverted;this.sourcesWithLayers.region.show(this.buildRegionFC(this.lastAnalytics.features,t))}}applyFiltersToLayers(){const e=this.activeMetric,t=this.config?.metricConfig?.[e]?.filters,i=[this.hexFillLayerSpec.id,this.hexExtrusionLayerSpec.id,this.squareFillLayerSpec.id,this.squareExtrusionLayerSpec.id];if(!t||void 0===t.min&&void 0===t.max){for(const e of i)this.mapLibreMap.setFilter(e,null);return}const r=[];void 0!==t.min&&r.push([">=",["get",e],t.min]),void 0!==t.max&&r.push(["<=",["get",e],t.max]);const o=1===r.length?r[0]:["any",...r];for(const s of i)this.mapLibreMap.setFilter(s,o)}buildRegionFC(e,t){return{type:"FeatureCollection",features:e.map((e,i)=>{const r=`traffic-area-analytics-region-${i}`,o=t?mask(e).geometry:e.geometry;return{...e,id:r,geometry:o,properties:{id:r}}})}}},toAllFilter=e=>e.length?1===e.length?e[0]:["all",...e]:null,addFilter=(e,t)=>{e&&t.push(e)},addValuesFilter=(e,t,i)=>{isCompleteValuesFilter(e)&&addFilter(buildValuesFilter(t,e),i)},addCommonFilterExpressions=(e,t)=>{addValuesFilter(e.roadCategories,"road_category",t),addValuesFilter(e.roadSubCategories,"road_subcategory",t)},buildMapLibreIncidentsFilter=e=>{const t=[];if(addCommonFilterExpressions(e,t),isCompleteValuesFilter(e.incidentCategories)){const i=buildValuesFilter("icon_category_0",e.incidentCategories,trafficIncidentToIconCategory);addFilter(i,t)}if(isCompleteValuesFilter(e.magnitudes)){const i=buildValuesFilter("magnitude_of_delay",e.magnitudes,e=>indexedMagnitudes.indexOf(e));addFilter(i,t)}return e.delays&&addFilter((e=>{const t=[];if(e.mustHaveDelay&&e.minDelayMinutes){const i=60*e.minDelayMinutes;t.push([">=",["get","delay"],i])}else if(e.mustHaveDelay)t.push([">",["get","delay"],0]);else if(e.minDelayMinutes){const i=60*e.minDelayMinutes;t.push(["any",["!",["has","delay"]],["==",["get","delay"],0],[">=",["get","delay"],i]])}return toAllFilter(t)})(e.delays),t),toAllFilter(t)},buildMapLibreFlowFilter=e=>{const t=[];if(addCommonFilterExpressions(e,t),e.showRoadClosures){const i="only"===e.showRoadClosures?"==":"!=";t.push([i,["get","road_closure"],!0])}return toAllFilter(t)},applyFilter=(e,t,i,r)=>{for(const o of t)i.setClause(o.id,r,e)},TrafficFlowModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await ensureAddedToStyle(t,"vectorTilesFlow","trafficFlow"),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTilesFlow");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTilesFlow`);return{trafficFlow:new StyleSourceWithLayers(this.mapLibreMap,t)}}_applyConfig(e){return this._setVisible(e?.visible??!1,!1),this._filter(e?.filters,!1),e}getLayers(){return filterLayersBySources(this.tomtomMap.mapLibreMap,["vectorTilesFlow"])}filter(e){this._filter(e)}_filter(e,t=!0){if(this.tomtomMap.mapReady)if(e?.any?.length){const t=(e=>{if(!e?.any?.length)return null;const t=e.any.map(buildMapLibreFlowFilter).filter(e=>!isNil(e));return getMergedAnyFilter(t)})(e);t&&applyFilter(t,this.getLayers(),this.filterComposer,"traffic.flow")}else this.config?.filters?.any?.length&&applyFilter(void 0,this.getLayers(),this.filterComposer,"traffic.flow");t&&(this.config=omitBy({...this.config,filters:e},isNil),this.emitConfigChange())}setVisible(e){this._setVisible(e)}_setVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficFlow.setLayersVisible(e),t&&(this.config={...this.config,visible:e},this.emitConfigChange())}isVisible(){return this.config?.visible??!1}getShown(){return{trafficFlow:this.mapLibreMap.queryRenderedFeatures({layers:this.sourcesWithLayers.trafficFlow.sourceAndLayerIDs.layerIDs,validate:!1}).map(trafficFlowMapping)}}get events(){return this.moduleEvents(["trafficFlow"],{mapping:trafficFlowMapping})}},LAYER_IDS={unknown:{outline:"TrafficIncidents - No delay outline",inner:"TrafficIncidents - No delay pattern"},minor:{outline:"TrafficIncidents - Minor jam outline",inner:"TrafficIncidents - Minor jam"},moderate:{outline:"TrafficIncidents - Moderate jam outline",inner:"TrafficIncidents - Moderate jam"},major:{outline:"TrafficIncidents - Major jam outline",inner:"TrafficIncidents - Major jam"},indefinite:{outline:"TrafficIncidents - Closed road outline",inner:"TrafficIncidents - Closed road pattern"}},FALLBACK_INCIDENT_PALETTE_outline={unknown:"hsl(198, 20%, 54%)",minor:"hsl(45, 85%, 36%)",moderate:"hsl(9, 87%, 31%)",major:"hsl(0, 100%, 17%)",indefinite:"hsl(0, 100%, 34%)"},FALLBACK_INCIDENT_PALETTE_inner={unknown:"hsl(198, 20%, 90%)",minor:"hsl(45, 100%, 51%)",moderate:"hsl(9, 97%, 51%)",major:"hsl(0, 100%, 34%)",indefinite:"hsl(197, 28%, 95%)"},readIncidentPalette=e=>{const t=e.getStyle()?.layers??[],i=/* @__PURE__ */new Map;for(const s of t)i.set(s.id.trim(),s);const r={outline:{...FALLBACK_INCIDENT_PALETTE_outline},inner:{...FALLBACK_INCIDENT_PALETTE_inner}},o=[];for(const s of indexedMagnitudes){const e=LAYER_IDS[s],t=readLineColor(i.get(e.outline),e.outline,o),a=readLineColor(i.get(e.inner),e.inner,o);t&&(r.outline[s]=t),a&&(r.inner[s]=a)}return o.length>0&&console.warn("[TrafficIncidentOverlayModule] style layers have non-literal `line-color` (match/case/etc.); falling back to default colour for: "+o.join(", ")),r},readLineColor=(e,t,i)=>{if(!e||"object"!=typeof e)return;const r=e.paint;if(!r||"object"!=typeof r)return;const o=r["line-color"];if("string"==typeof o)return o;void 0!==o&&i.push(t)},TrafficIncidentOverlayModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i??{})}constructor(e,t){super(e,t),this.lastResult=null,this.lastFeatureIds=[],this.lastFocusIds=null,this.shownFeaturesHandlers=[],onStylingKnobsApplied(e,Object.values(incidentColorKnobIds),()=>this.updateLayers(this.config))}buildLayerSpecs(e,t){const i=beforeLayerIDOf(t?.beforeLayerConfig??"lowestLabel"),r=((e,t)=>!1===e?null:{outlineColor:e?.outlineColor??getThemeAdaptiveFocusOutlineColor(t),widthFactor:clampFactor(e?.widthFactor,INCIDENT_FOCUS_WIDTH_FACTOR_RANGE,1.6)})(t?.focus,this.tomtomMap.styleLightDarkTheme);return[...buildCanonicalIncidentLineLayers(e,i,readIncidentPalette(this.mapLibreMap),r),...buildCanonicalIncidentSymbolLayers(e,i)]}updateLayers(e){const{incidents:t}=this.sourcesWithLayers,i=this.buildLayerSpecs(t.sourceAndLayerIDs.sourceID,e);updateLayersAndSource(i,t._layerSpecs,t,this.mapLibreMap);const r=i.map(({id:e})=>e);t._layerSpecs.sort((e,t)=>r.indexOf(e.id)-r.indexOf(t.id)),t._updateSourceAndLayerIDs()}_initSourcesWithLayers(e,t){const i=`traffic-incident-overlay-${this.instanceIndex}`,r=(()=>{if(isDOMImageSupported())return cachedImg||(cachedImg=svgToImg(parseSvg(svgMarkup))),cachedImg})();return r&&addOrUpdateImage("if-not-in-sprite","tt-traffic-incident-direction-chevron",r,this.mapLibreMap),{incidents:new GeoJSONSourceWithLayers(this.mapLibreMap,i,this.buildLayerSpecs(i,e))}}_applyConfig(e){return this.updateLayers(e),this.applyVisibility(e),this.applyBeforeLayer(e?.beforeLayerConfig),e}applyVisibility(e){this.sourcesWithLayers.incidents.setLayersVisible(!1!==e?.visible)}applyBeforeLayer(e){const t=beforeLayerIDOf(e??"lowestLabel");for(const i of this.sourcesWithLayers.incidents.sourceAndLayerIDs.layerIDs)moveLayerBefore(this.mapLibreMap,i,t)}discardShownData(){this.lastResult=null,this.lastFeatureIds=[],this.lastFocusIds=null}restoreDataAndConfigImpl(){this.initSourcesWithLayers(this.config,!0),this.lastResult&&this.sourcesWithLayers.incidents.show(this.lastResult),this._applyConfig(this.config),null!==this.lastFocusIds&&this.lastFocusIds.length>0&&this.setFocus(this.lastFocusIds)}async show(e){await this.waitUntilModuleReady(),this.clearFeatureState(),this.lastFocusIds=null,this.lastResult=e,this.lastFeatureIds=e.features.map(e=>e.properties.id).filter(e=>"string"==typeof e),this.sourcesWithLayers.incidents.show(e,{automaticVisibility:!1}),this.sourcesWithLayers.incidents.setLayersVisible(this.isVisible());for(const t of this.shownFeaturesHandlers)t(e)}async clear(){await this.waitUntilModuleReady(),this.clearFeatureState(),this.lastResult=null,this.lastFeatureIds=[],this.lastFocusIds=null,this.sourcesWithLayers.incidents.clear()}moveBeforeLayer(e){this.config={...this.config,beforeLayerConfig:e},this.applyBeforeLayer(e),this.emitConfigChange()}getShown(){return{incidents:this.sourcesWithLayers.incidents.shownFeatures}}get events(){return this.moduleEventsWithShown(["incidents"],this.shownFeaturesHandlers)}setFocus(e){if(null===e||0===e.length)return this.lastFocusIds=null,void this.clearFeatureState();if(0===this.lastFeatureIds.length)return;this.lastFocusIds=e;const t=new Set(e),i=this.sourcesWithLayers.incidents.sourceAndLayerIDs.sourceID;for(const r of this.lastFeatureIds)this.mapLibreMap.setFeatureState({source:i,id:r},{focused:t.has(r)})}clearFeatureState(){if(0===this.lastFeatureIds.length)return;const e=this.sourcesWithLayers.incidents.sourceAndLayerIDs.sourceID;for(const t of this.lastFeatureIds)this.mapLibreMap.removeFeatureState({source:e,id:t})}},TrafficIncidentsModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await ensureAddedToStyle(t,"vectorTilesIncidents","trafficIncidents"),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTilesIncidents");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTilesIncidents`);return{trafficIncidents:new StyleSourceWithLayers(this.mapLibreMap,t)}}_applyConfig(e){return this._setVisible(e?.visible??!1,{updateConfig:!1}),isNil(e?.icons?.visible)||this._setIconsVisible(e.icons.visible,!1),this._filter(e?.filters,!1),e}filter(e){this._filter(e)}_filter(e,t=!0){if(this.tomtomMap.mapReady)if(e?.any?.length){const t=(e=>{if(!e?.any?.length)return null;const t=e.any.map(buildMapLibreIncidentsFilter).filter(e=>!isNil(e));return getMergedAnyFilter(t)})(e);t&&applyFilter(t,this.getLayers(),this.filterComposer,"traffic.incidents")}else this.config?.filters?.any?.length&&applyFilter(void 0,this.getLayers(),this.filterComposer,"traffic.incidents");t&&(this.config=omitBy({...this.config,filters:e},isNil),this.emitConfigChange())}getLayers(){return filterLayersBySources(this.tomtomMap.mapLibreMap,["vectorTilesIncidents"])}setIconsVisible(e){this._setIconsVisible(e)}_setIconsVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisible(e,e=>"symbol"===e.type),t&&(this.config={...this.config,icons:{...this.config?.icons,visible:e}},this.emitConfigChange())}setVisible(e){this._setVisible(e)}_setVisible(e,t){(t?.updateConfig??1)&&(delete this.config?.icons?.visible,this.config={...omitBy({...this.config},isEmpty),visible:e},this.emitConfigChange()),this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisible(e)}isVisible(){return this.config?.visible??!1}anyIconLayersVisible(){return this.sourcesWithLayers.trafficIncidents?.isAnyLayerVisible(e=>"symbol"===e.type)}getShown(){return{trafficIncidents:this.mapLibreMap.queryRenderedFeatures({layers:this.sourcesWithLayers.trafficIncidents.sourceAndLayerIDs.layerIDs,validate:!1}).map(trafficIncidentMapping)}}get events(){return this.moduleEvents(["trafficIncidents"],{mapping:trafficIncidentMapping})}},getRelativeElementBounds=(e,t)=>({left:e.left-t.left,top:e.top-t.top,right:e.right-t.left,bottom:e.bottom-t.top}),isElementOutsideContainer=(e,t,i)=>e.right<=0||e.left>=t||e.bottom<=0||e.top>=i,adjustForHorizontalBar=(e,t,i,r)=>{e.top<=i-e.bottom?t.top=Math.max(t.top,e.bottom+r):t.bottom=Math.min(t.bottom,e.top-r)},adjustForVerticalBar=(e,t,i,r)=>{e.left<=i-e.right?t.left=Math.max(t.left,e.right+r):t.right=Math.min(t.right,e.left-r)},adjustVisibleBoundsForElement=(e,t,i,r,o)=>{const s=((e,t,i)=>({left:Math.max(0,e.left),top:Math.max(0,e.top),right:Math.min(t,e.right),bottom:Math.min(i,e.bottom)}))(e,i,r),a=e.left<=0&&e.right>=i,n=e.top<=0&&e.bottom>=r;if(a&&!n)return void adjustForHorizontalBar(s,t,r,o);if(n&&!a)return void adjustForVerticalBar(s,t,i,o);const l=e.left<=0,c=e.right>=i,d=e.top<=0,p=e.bottom>=r;!l&&!c||d||p?!d&&!p||l||c?((e,t,i,r,o)=>{const s=e.left,a=i-e.right,n=e.top,l=r-e.bottom,c=Math.min(s,a,n,l);c===s?t.left=Math.max(t.left,e.right+o):c===a?t.right=Math.min(t.right,e.left-o):c===n?t.top=Math.max(t.top,e.bottom+o):t.bottom=Math.min(t.bottom,e.top-o)})(s,t,i,r,o):adjustForVerticalBar(s,t,i,o):adjustForHorizontalBar(s,t,r,o)},toElement=e=>"string"==typeof e?document.querySelector(e):e,getMapLibreMap=e=>"mapLibreMap"in e?e.mapLibreMap:e,calculateVisibleAreaBounds=(e,t,i)=>{const r=getMapLibreMap(e).getContainer().getBoundingClientRect(),{width:o,height:s}=r,a={left:i,top:i,right:o-i,bottom:s-i};for(const n of t){const e=toElement(n);if(!e)continue;const t=e.getBoundingClientRect(),l=getRelativeElementBounds(t,r);isElementOutsideContainer(l,o,s)||adjustVisibleBoundsForElement(l,a,o,s,i)}return a.left>=a.right||a.top>=a.bottom?null:{visibleAreaBounds:a,mapWidthPX:o,mapHeightPX:s}},calculatePaddedBBox=e=>{const{map:t,surroundingElements:i,paddingPX:r=0}=e,o=calculateVisibleAreaBounds(t,i,r);if(!o)return null;const{visibleAreaBounds:s}=o,a=getMapLibreMap(t),n=a.unproject([s.left,s.bottom]),l=a.unproject([s.right,s.top]);return[n.lng,n.lat,l.lng,l.lat]},calculatePaddedCenter=e=>{const{map:t,surroundingElements:i}=e,r=calculatePaddedBBox({map:t,surroundingElements:i});if(!r)return null;const[o,s,a,n]=r;return[(o+a)/2,(s+n)/2]},calculateFittingBBox=e=>{const{map:t,toBeContainedBBox:i,surroundingElements:r,paddingPX:o=0}=e,s=calculateVisibleAreaBounds(t,r,o);if(!s)return null;const{visibleAreaBounds:a,mapWidthPX:n,mapHeightPX:l}=s,c=a.left/n,d=a.right/n,p=a.top/l,u=d-c,h=a.bottom/l-p,[y,f,m,g]=i,S=(m-y)/u,L=(g-f)/h,b=y-c*S,_=g+p*L;return[b,_-L,b+S,_]};export{AbstractDataOwnedMapModule,AbstractMapModule,AbstractSourceWithLayers,AbstractStyleOwnedMapModule,AddedSourceWithLayers,BASE_MAP_SOURCE_ID,BaseMapModule,CombinedEvents,CustomGeoJSONModule,DEFAULT_TEXT_SIZE,DESELECTED_FOREGROUND_COLOR,DESELECTED_OUTLINE_COLOR,DESELECTED_ROUTE_FILTER,DESELECTED_SECONDARY_COLOR,EventsProxy,FINISH_INDEX,GeoJSONSourceWithLayers,GeometriesModule,HILLSHADE_SOURCE_ID,INCIDENT_FOCUS_WIDTH_FACTOR_RANGE,INDEFINITE_DELAY_DASH_COLOR,LayerFilterComposer,LayerSelection,MAJOR_DELAY_COLOR,MAP_BOLD_FONT,MAP_ITALIC_FONT,MAP_MEDIUM_FONT,MAP_REGULAR_FONT,MIDDLE_INDEX,MINOR_DELAY_COLOR,MINOR_DELAY_LABEL_COLOR,MODERATE_DELAY_COLOR,ModuleEvents,POI_SOURCE_ID,POIsModule,PlacesModule,ROUTE_LINE_FOREGROUND_COLOR,ROUTE_LINE_FOREGROUND_WIDTH,ROUTE_LINE_OUTLINE_COLOR,ROUTE_LINE_OUTLINE_WIDTH,ROUTE_WAYPOINT_SIZE_FACTOR_RANGE,ROUTE_WIDTH_FACTOR_RANGE,RoutingModule,SECTION_ICON_SIZE_FACTOR_RANGE,SELECTED_ROUTE_FILTER,START_INDEX,STOP_DISPLAY_INDEX,StyleSourceWithLayers,StylingModule,TERRAIN_SOURCE_ID,TRAFFIC_FLOW_SOURCE_ID,TRAFFIC_INCIDENTS_SOURCE_ID,TerrainModule,TomTomMap,TomTomMapSource,TrafficAreaAnalyticsModule,TrafficFlowModule,TrafficIncidentOverlayModule,TrafficIncidentsModule,UNKNOWN_DELAY_BG_COLOR,UNKNOWN_DELAY_COLOR,UNKNOWN_DELAY_DASH_COLOR,UserEvents,adaptPaletteForTheme,assertNoReservedScopeNames,baseMapColorNames,baseMapKnobCatalogue,baseMapKnobIds,baseMapLayerGroupNames,baseMapPOICategoryValues,bespokeSectionTypes,buildPlaceTitle,buildReachableRangeFeatures,buildRoutingLayers,calculateFittingBBox,calculatePaddedBBox,calculatePaddedCenter,colorPaletteIDs,colorPalettes,combineEventScopes,customGeoJSONKnobCatalogue,customGeoJSONKnobIds,defaultRoutingLayers,drawnSectionTypes,fillStyledGeometryConfig,filterLayersBySources,filterShowModes,findFeatureByRefId,formatStyleHsl,generatedSectionTypes,geometriesKnobCatalogue,geometriesKnobIds,geometryFillStyles,getIconIDForPlace,getInstructionArrowSize,getInstructionLineWidth,getInstructionOutlineWidth,getLineForegroundWidth,getLineOutlineWidth,getPOIGroupForPlace,getPOILayerCategoryForPlace,getSectionHaloWidth,getSectionIconSize,getStyleCategories,getWaypointIconSize,getWaypointIndexTextSize,hueDistance,mapColorNames,mapDisplayPoiCategoryMappings,mapFonts,mapStyleLayerIDs,parseCssColor,placesKnobCatalogue,placesKnobIds,placesMarkerTypes,poiCategoryGroups,poiLayerIDs,poisKnobCatalogue,poisKnobIds,preparePlacesForDisplay,prepareReachableRangesForDisplay,reachableRangeGeometryConfig,renderedRefId,reservedScopeNames,resolveColorStops,roadCategories,routingKnobCatalogue,routingKnobIds,scopedLayerSpecs,sectionDrawsByDefault,sectionSourceKey,sectionSupportsKnob,serviceRoadSubCategories,setKnob,sharedInstance,sharedInstanceIfCreated,standardStyleIDs,streetRoadSubCategories,styleModules,stylingColorKnobIds,stylingKnobAppliesTo,stylingKnobCatalogue,stylingKnobIds,stylingKnobKinds,stylingPresetCatalogue,stylingPresetIds,terrainKnobCatalogue,terrainKnobIds,toBaseMapPOICategory,toBaseMapPOIGroup,toHsl,toPlaces,trafficAreaAnalyticsKnobCatalogue,trafficAreaAnalyticsKnobIds,trafficFlowKnobCatalogue,trafficFlowKnobIds,trafficIncidentOverlayKnobCatalogue,trafficIncidentOverlayKnobIds,trafficIncidentsKnobCatalogue,trafficIncidentsKnobIds,validateKnobValue};
1
+ import{clamp,clone,groupBy,isEmpty,isEqual,isNil,isObject,isUndefined,keyBy,mapValues,omit,omitBy,pick,remove,setWith,sortBy}from"lodash-es";import{DEFAULT_COMMON_BASE_URL,MILE_IN_METERS,TomTomConfig,areaAnalyticsMetricKeys,bboxCenter,bboxFromCoordsArray,bboxFromGeoJSON,budgetUnits,formatDistance,formatDuration,fullTrafficIncidentCategories,generateId,generateTomTomHeaders,getPosition,iconToTrafficIncidentCategory,indexedMagnitudes,isProxyCredentialsMode,mergeFromGlobal,poiCategories,poiCategoriesToID,trafficIncidentToIconCategory}from"@tomtom-org/maps-sdk/core";import{clampRgb,differenceHueNaive,formatHex,formatHsl,interpolate,modeHsl,modeLrgb,modeRgb,parse,round,useMode,wcagLuminance}from"culori/fn";import{area,bearing,booleanPointInPolygon,difference,featureCollection,hexGrid,mask,squareGrid,union}from"@turf/turf";import{Map as Map$1,setWorkerCount}from"maplibre-gl";var CombinedEvents=class{constructor(e,t){this.userEventsInstance=e,this.moduleEventsInstance=t}where(e,t){return this.userEventsInstance.where(e,t)}on(e,t){return"config-change"===e?this.moduleEventsInstance.on("config-change",t):"shown-features"===e?this.moduleEventsInstance.on("shown-features",t):this.userEventsInstance.on(e,t)}off(e){"config-change"===e||"shown-features"===e?this.moduleEventsInstance.off(e):this.userEventsInstance.off(e)}},andPredicates=(e,t)=>e?t?(...i)=>e(...i)&&t(...i):e:t,combineEventScopes=(e,t)=>{if(!e)return t;if(!t)return e;const i=andPredicates(e.layerFilter,t.layerFilter),r=andPredicates(e.featureMatches,t.featureMatches);return i||r?{layerFilter:i,featureMatches:r}:void 0},scopedLayerSpecs=(e,t)=>t?.layerFilter?e._layerSpecs.filter(t.layerFilter):e._layerSpecs,reservedScopeNames=["on","off","where"],assertNoReservedScopeNames=(e,t)=>{const i=e.find(e=>reservedScopeNames.includes(e));if(i)throw new Error(`${t} uses the reserved event scope name "${i}". Reserved: ${reservedScopeNames.join(", ")}.`)},isExpressionFilter=e=>{if(!0===e||!1===e)return!0;if(!Array.isArray(e)||0===e.length)return!1;switch(e[0]){case"has":return e.length>=2&&"$id"!==e[1]&&"$type"!==e[1];case"in":return e.length>=3&&("string"!=typeof e[1]||Array.isArray(e[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==e.length||Array.isArray(e[1])||Array.isArray(e[2]);case"any":case"all":for(const t of e.slice(1))if(!isExpressionFilter(t)&&"boolean"!=typeof t)return!1;return!0;default:return!0}},propertyAccessor=e=>"$type"===e?["geometry-type"]:"$id"===e?["id"]:["get",e],convertHas=e=>"$type"===e||("$id"===e?["!=",["id"],null]:["has",e]),convertIn=(e,t)=>!!t.length&&["in",propertyAccessor(e),["literal",t]],convertLegacyFilter=e=>{const t=e[0];if(e.length<=1)return"any"!==t;const i=e[1],r=e.slice(2),o=e.slice(1);switch(t){case"has":return convertHas(i);case"!has":return["!",convertHas(i)];case"==":case"!=":return(null===r[0]?((e,t)=>{if("$id"!==t&&"$type"!==t)return"=="===e?["all",["has",t],["==",["get",t],null]]:["any",["!",["has",t]],["!=",["get",t],null]]})(t,i):void 0)??[t,propertyAccessor(i),r[0]];case">":case">=":case"<":case"<=":return((e,t,i)=>["all",["==",["typeof",propertyAccessor(t)],typeof i],[e,propertyAccessor(t),i]])(t,i,r[0]);case"in":return convertIn(i,r);case"!in":return["!",convertIn(i,r)];case"all":return["all",...o.map(e=>toExpressionFilter(e))];case"any":return["any",...o.map(e=>toExpressionFilter(e))];case"none":return["!",["any",...o.map(e=>toExpressionFilter(e))]];default:return!0}},toExpressionFilter=e=>isExpressionFilter(e)?e:convertLegacyFilter(e),getMergedFilter=(e,t)=>t?.length?1===t.length?t[0]:[e,...t]:null,isCompleteValuesFilter=e=>void 0!==e?.show&&void 0!==e.values,getMergedAnyFilter=e=>getMergedFilter("any",e),buildMappedValuesFilter=(e,t,i)=>{if(1===i.length)return["only"===t?"==":"!=",["get",e],i[0]];const r=["in",["get",e],["literal",i]];return"only"===t?r:["!",r]},buildValuesFilter=(e,t,i)=>buildMappedValuesFilter(e,t.show,i?t.values.map(i):t.values),AbstractLayerComposer=class{constructor(e){this.byLayer=/* @__PURE__ */new Map,this.mapLibreMap=e.mapLibreMap,e.addStyleChangeHandler({onStyleAboutToChange:()=>this.byLayer.clear(),priority:Number.NEGATIVE_INFINITY})}},setOrDelete=(e,t,i)=>{void 0!==i?e.set(t,i):e.delete(t)},composerOfMap=(e,t,i)=>{let r=e.get(t);return r||(r=i(),e.set(t,r)),r},composersByMap$1=/* @__PURE__ */new WeakMap,LayerFilterComposer=class e extends AbstractLayerComposer{constructor(e){super(e)}static for(t){return composerOfMap(composersByMap$1,t,()=>new e(t))}setTransform(e,t,i){this.contribute(e,({transforms:e})=>setOrDelete(e,t,i))}setClause(e,t,i){this.contribute(e,({clauses:e})=>setOrDelete(e,t,i))}contribute(e,t){if(!this.mapLibreMap.getLayer(e))return;let i=this.byLayer.get(e);i||(i={styleFilter:this.mapLibreMap.getFilter(e),transforms:/* @__PURE__ */new Map,clauses:/* @__PURE__ */new Map},this.byLayer.set(e,i)),t(i),this.apply(e,i)}apply(e,t){const i=[...t.transforms.values()].reduce((e,t)=>t(e),t.styleFilter),r=((e,t)=>{if(!t.length)return e;const i=null==e?t:[...t,toExpressionFilter(e)];return 1===i.length?i[0]:["all",...i]})(i,[...t.clauses.values()]);this.mapLibreMap.setFilter(e,r??null,{validate:!1})}},ModuleEvents=class{constructor(e,t){this.configChangeHandlers=e,this.shownFeaturesHandlers=t}on(e,t){if("config-change"===e){const e=t;return this.configChangeHandlers.push(e),()=>{const t=this.configChangeHandlers.indexOf(e);-1!==t&&this.configChangeHandlers.splice(t,1)}}const i=t;return this.shownFeaturesHandlers.push(i),()=>{const e=this.shownFeaturesHandlers.indexOf(i);-1!==e&&this.shownFeaturesHandlers.splice(e,1)}}off(e){"config-change"===e?this.configChangeHandlers.length=0:this.shownFeaturesHandlers.length=0}},notInTheStyle=e=>/* @__PURE__ */new Error(`Trying to ${e} while it is not in the map style. Did you exclude it when loading the map?`),standardStyleIDs=["standardLight","standardDark","drivingLight","drivingDark","monoLight","monoDark","satellite"],styleParts=["trafficIncidents","trafficFlow","terrain"],stylePartURLParams={trafficIncidents:"trafficIncidents",trafficFlow:"trafficFlow",terrain:"hillshade"},standardStylePartValues={standardLight:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",terrain:"hillshade_light"},standardDark:{trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",terrain:"hillshade_dark"},drivingLight:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",terrain:"hillshade_light"},drivingDark:{trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",terrain:"hillshade_dark"},monoLight:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",terrain:"hillshade_mono-light"},monoDark:{trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",terrain:"hillshade_mono-dark"},satellite:{trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",terrain:"hillshade_satellite"}},mapSuffixes={standardLight:"basic_street-light",standardDark:"basic_street-dark",drivingLight:"basic_street-light-driving",drivingDark:"basic_street-dark-driving",monoLight:"basic_mono-light",monoDark:"basic_mono-dark",satellite:"basic_street-satellite"},buildStandardStyleUrl=(e,t,i)=>{const r=e.id??"standardLight",o=new URL(`${t}/maps/orbis/assets/styles/0.6.0-0/style.json`);o.searchParams.set("apiVersion","1"),i&&o.searchParams.set("key",i),o.searchParams.set("map",mapSuffixes[r]);for(const s of e.include??styleParts)o.searchParams.append(stylePartURLParams[s],standardStylePartValues[r][s]);return o.toString()},buildStyleInput=e=>{const t=e.style,i=e.commonBaseURL,r=e.apiKey;if("string"==typeof t)return buildStandardStyleUrl({id:t},i,r);if("standard"===t?.type)return buildStandardStyleUrl(t,i,r);if("custom"===t?.type){if(void 0!==t.url)return((e,t)=>{const i=new URL(e);return i.searchParams.has("key")?console.warn("The style URL is coming with an API key parameter which takes priority. If you want to use the SDK configured API key, remove the key param from the style URL"):t&&i.searchParams.set("key",t),i.toString()})(t.url,r);if(void 0===t.json)/* @__PURE__ */throw new Error("A custom map style takes exactly one of 'url' or 'json', and this one carries neither. Give the URL the style is served from, or the style specification itself.");return t.json}return buildStandardStyleUrl({id:"standardLight"},i,r)},isLegacyFunction=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&Array.isArray(e.stops),scaleNumericValue=(e,t)=>"number"==typeof e?(e=>Math.round(1e3*e)/1e3)(e*t):isLegacyFunction(e)?scaleLegacyStops(e,t):Array.isArray(e)?"interpolate"===e[0]||"step"===e[0]?scaleRampOutputs(e,t):(e=>JSON.stringify(e).includes('"zoom"'))(e)?void 0:["*",t,e]:void 0,scaleLegacyStops=(e,t)=>{const i=[];for(const[r,o]of e.stops){const e=scaleNumericValue(o,t);if(void 0===e)return;i.push([r,e])}return{...e,stops:i}},scaleRampOutputs=(e,t)=>{const i=[...e];for(let r="interpolate"===e[0]?4:2;r<i.length;r+=2){const e=scaleNumericValue(i[r],t);if(void 0===e)return;i[r]=e}return i},branchOn=(e,t,i,r)=>{const o=scaleNumericValue(t,i);if(void 0!==o)return void 0===r?["case",e,o,t]:["case",e,"number"==typeof o?Math.min(r,o):["min",r,o],t]},scaledWhen=(e,t,i,r)=>{if(1===i)return t;if(!Array.isArray(t)||"interpolate"!==t[0]&&"step"!==t[0])return branchOn(e,t,i,r)??t;const o=[...t];for(let s="interpolate"===t[0]?4:2;s<o.length;s+=2){const a=branchOn(e,o[s],i,r);if(void 0===a)return t;o[s]=a}return o},shiftZoomOffset=(e,t)=>{let i=!1;const r=e=>Array.isArray(e)?"-"===e[0]&&3===e.length&&Array.isArray(e[1])&&"zoom"===e[1][0]&&"number"==typeof e[2]?(i=!0,["-",["zoom"],e[2]+t]):e.map(r):e;return{filter:r(e),patched:i}},toRgb=useMode(modeRgb),toHslSpace=useMode(modeHsl);useMode(modeLrgb);var toHundredths=round(2),STYLE_COLOR_SYNTAX=/^(#|rgba?\(|hsla?\(|[a-z]+$)/,parseColor=e=>{const t=e.trim().toLowerCase(),i=STYLE_COLOR_SYNTAX.test(t)?parse(t):void 0;return i&&clampRgb(i)},parseCssColor=e=>{const t=parseColor(e);if(!t)return;const{r:i,g:r,b:o,alpha:s=1}=toRgb(t);return[i,r,o,s]},toHsl=e=>{const t=parseColor(e);return t&&toHslSpace(toRgb(t))},isColorLiteral=e=>"string"==typeof e&&void 0!==parseColor(e),formatStyleHsl=e=>formatHsl(roundStyleHsl(e)),roundStyleHsl=({h:e=0,s:t,l:i,alpha:r})=>({mode:"hsl",h:(Math.round(e)%360+360)%360,s:toHundredths(t),l:toHundredths(i),alpha:r}),clampUnit=e=>clamp(e,0,1),hslShiftBetween=(e,t)=>{const i=toHsl(e),r=toHsl(t);if(i&&r)return{h:i.s<.01||r.s<.01?0:(r.h??0)-(i.h??0),s:r.s-i.s,l:r.l-i.l,alpha:(r.alpha??1)-(i.alpha??1)}},shiftHsl=(e,t)=>{const i=toHsl(e);if(i)return formatStyleHsl({h:(i.h??0)+t.h,s:void 0===i.h?i.s:i.s+t.s,l:i.l+t.l,alpha:clampUnit((i.alpha??1)+t.alpha)})},relativeLuminance=e=>{const t=parseColor(e);return t&&wcagLuminance(t)},mixColor=(e,t,i)=>{const r=parseColor(e),o=parseColor(t);return r&&o&&formatHex(interpolate([r,o])(i))},darkerShadeOf=e=>((e,t)=>mixColor(e,"#000000",t))(e,.4),lighterShadeOf=e=>((e,t)=>mixColor(e,"#ffffff",t))(e,.4),hueDistance=({h:e},{h:t})=>void 0===e||void 0===t?0:Math.abs(differenceHueNaive({h:e},{h:t})),paintedBy={fill:["fill-color","fill-outline-color"],line:["line-color"],"fill-extrusion":["fill-extrusion-color"]},paintLayers=e=>t=>({layers:[{...t,layerTypes:[e]}],properties:[...paintedBy[e]]}),fillLayers=paintLayers("fill"),lineLayers=paintLayers("line"),extrusionLayers=paintLayers("fill-extrusion"),roadLine=(e,t)=>({metadataGroups:["road"],layerTypes:["line"],idIncludes:e,...t&&{idExcludes:t}}),MIXED_CLASS_ROAD_LINES=roadLine(["road line","road outline","under construction","link road"],["tarmac"]),MAJOR_ROAD_LINES=roadLine(["motorway","primary road","major road"]),MINOR_ROAD_LINES=roadLine(["secondary road","tertiary road","street","minor road","restricted","service road"],["outline"]),MINOR_ROAD_OUTLINES=roadLine(["secondary road outline","tertiary road outline","street outline","minor road outline","tarmac outline"]),RAIL_AND_PATH_LINES=roadLine(["railway","subway","track","path","aerialway"]),TEXT_LAYERS={metadataGroups:["places_label","road_label","label","address_point_label","border_label"],layerTypes:["symbol"],idExcludes:["shield","exit","water","river"]},mapColorDefinitions={land:{description:"Map background and other bare-land features, influences admin borders/labels. Also used to derive all map colours if undefined.",anchor:{layers:[{layerTypes:["background"]}],property:"background-color"},targets:[{layers:[{layerTypes:["background"]}],properties:["background-color"]},fillLayers({metadataGroups:["area"],idIncludes:["earth cover","landcover"]}),fillLayers({metadataGroups:["road_area"]}),fillLayers({metadataGroups:["transit_area"]}),lineLayers({metadataGroups:["transit_area"]})]},water:{description:"Waterbodies, waterways and other water features. Also influences glaciers, water labels and ferry lines.",anchor:{layers:[{metadataGroups:["water"],layerTypes:["fill"],idIncludes:["fill"]}],property:"fill-color"},targets:[fillLayers({metadataGroups:["water"]}),lineLayers({metadataGroups:["water"]}),{layers:[{metadataGroups:["label"],layerTypes:["symbol"],idIncludes:["water","river"]}],properties:["text-color","text-halo-color"]},lineLayers({metadataGroups:["road"],idIncludes:["ferry"]})]},vegetation:{description:"Forests and other land cover such as grass and shrubland. Also influences earth cover vegetation at smaller scales.",anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["landcover"]}],property:"fill-color"},targets:[fillLayers({metadataGroups:["area"],idIncludes:["landcover","earth cover"]})]},park:{description:"City parks and sport/recreation grounds. Also influences National Parks and other protected areas at smaller scales.",anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["protected"]}],property:"fill-color"},targets:[fillLayers({metadataGroups:["area"],idIncludes:["protected","outdoor","sport","landuse"]}),lineLayers({metadataGroups:["border"],idIncludes:["overlays"]})]},artificial:{description:"Built-up-areas and man-made features such as landuse grounds and buildings. Also influences railways.",anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["built-up"]}],property:"fill-color",lastStop:!0},targets:[...[fillLayers({metadataGroups:["area"],idIncludes:["built-up","landuse","parking"]}),fillLayers({metadataGroups:["building"]}),lineLayers({metadataGroups:["building"]}),extrusionLayers({metadataGroups:["area_3d","building"]})].map(e=>({...e,recolorsTints:!0})),fillLayers({metadataGroups:["transit_area","road_area"]}),lineLayers({metadataGroups:["transit_area"]}),lineLayers(RAIL_AND_PATH_LINES)]},roadMajor:{description:"Most important road classes, from motorways & trunks to primary roads. Also influences outline and tunnel colours.",anchor:{layers:[roadLine(["motorway & trunk"],["outline"])],property:"line-color",roadClass:"major"},targets:[lineLayers(MAJOR_ROAD_LINES),{layers:[MIXED_CLASS_ROAD_LINES],properties:["line-color"],roadClass:"major"}]},road:{description:"Less important road classes, from secondary/tertiary to streets and service roads. Also influences tunnel colours.",anchor:{layers:[roadLine(["secondary road"],["outline"])],property:"line-color"},targets:[lineLayers(MINOR_ROAD_LINES),{layers:[roadLine(["road line","under construction","link road"],["outline"])],properties:["line-color"],roadClass:"minor"}]},roadOutline:{description:"Road outlines for secondary/tertiary roads and minor classes. Also influences road labels and all other outline colours.",anchor:{layers:[roadLine(["secondary road outline"])],property:"line-color"},targets:[lineLayers(MINOR_ROAD_OUTLINES),{layers:[roadLine(["road outline","link road outline"],["tarmac"])],properties:["line-color"],roadClass:"minor"}]},label:{description:"Labels for capitals and other populated places/admin areas. Also influences border styling and all other label colours.",anchor:{layers:[{metadataGroups:["places_label"],layerTypes:["symbol"],idIncludes:["capital"]}],property:"text-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-color"]},lineLayers({metadataGroups:["border"],idIncludes:["country","state","treaty","disputed"]})]},labelOutline:{description:"Outlines for populated places and admin area labels. Also influences border outlines and all other label halos.",anchor:{layers:[{metadataGroups:["places_label"],layerTypes:["symbol"],idIncludes:["capital"]}],property:"text-halo-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-halo-color"]},lineLayers({metadataGroups:["border"],idIncludes:["background"]})]}},baseMapColorNames=Object.keys(mapColorDefinitions),mapColorNames=[...baseMapColorNames,"accent"],mapColorNameSet=new Set(mapColorNames),isMapColorName=e=>mapColorNameSet.has(e),allButLand=baseMapColorNames.filter(e=>"land"!==e),landDerivedMapColors={monoLight:allButLand,monoDark:allButLand},mapColorDerivationInputs=e=>"roadMajor"===e||"roadOutline"===e?["land","road"]:["land"],themeLuminance=e=>{const t=relativeLuminance(e);return void 0===t?void 0:toHundredths(t)},withLightness=(e,t)=>({...e,l:clampUnit(t)}),lighten=(e,t)=>roundStyleHsl(withLightness(t,t.l*(1+e))),darken=(e,t)=>lighten(-e,t),desaturate=(e,t)=>roundStyleHsl({...t,s:clampUnit(t.s*(1-e))}),lightenBy=(e,t)=>withLightness(t,t.l+e/100),darkenBy=(e,t)=>lightenBy(-e,t),sign=e=>e?1:-1,withDerivedMapColors=(e,t,i)=>{const r=e.land??i,o=t.filter(t=>void 0===e[t]&&mapColorDerivationInputs(t).some(t=>void 0!==e[t])),s=r&&o.length?((e,t)=>{const i=toHsl(e),r=themeLuminance(e);if(!i||void 0===r)return;const o=sign(r<=.95),s=sign(r>.3),a=lightenBy(15*o,lighten(Math.max(r/5,.1),i)),n=t&&toHsl(t)||a;return{water:formatStyleHsl(darkenBy(10*sign(r>.01),darken(Math.max(r/20,.05),i))),vegetation:formatStyleHsl(darken(.05,darkenBy(2,i))),park:formatStyleHsl(darken(.03,darkenBy(1,i))),artificial:formatStyleHsl(darkenBy(4*sign(r>.05),lighten(Math.max(r/15,.02),i))),road:formatStyleHsl(a),roadMajor:formatStyleHsl(n),roadOutline:formatStyleHsl(darkenBy(20*o,n)),label:formatStyleHsl(desaturate(.3,darkenBy(60*s,lighten(Math.max(r/5,.1),i)))),labelOutline:formatStyleHsl(lightenBy(75*s,i))}})(r,e.road):void 0;return s?{...Object.fromEntries(o.map(e=>[e,s[e]])),...e}:e},MAJOR_ROAD_CLASSES=/* @__PURE__ */new Set(["motorway","trunk","primary"]),roadClassOfKeys=e=>(Array.isArray(e)?e:[e]).some(e=>"string"==typeof e&&MAJOR_ROAD_CLASSES.has(e.replace(/_link$/,"")))?"major":"minor",TOP_LEVEL_CONTEXT={roadClass:void 0,keyed:!1},mapColorLiterals=(e,t,i=TOP_LEVEL_CONTEXT)=>{if((e=>{const t="string"==typeof e?parseColor(e):void 0;return void 0!==t&&(t.alpha??1)>0})(e))return t(e,i);if(Array.isArray(e)){if("match"===e[0]){const o="match"===(r=e)[0]&&Array.isArray(r[1])&&"get"===r[1][0]&&("category"===r[1][1]||"road_category"===r[1][1]),s=[e[0],e[1]];for(let r=2;r<e.length-1;r+=2){const a=o?roadClassOfKeys(e[r]):i.roadClass;s.push(e[r],mapColorLiterals(e[r+1],t,{roadClass:a,keyed:!0}))}const a=o?"minor":i.roadClass;return s.push(mapColorLiterals(e.at(-1),t,{...i,roadClass:a})),s}return e.map(e=>mapColorLiterals(e,t,i))}var r;return isLegacyFunction(e)?{...e,stops:e.stops.map(([e,r])=>[e,mapColorLiterals(r,t,i)])}:e},collectColorLiterals=e=>{const t=[];return mapColorLiterals(e,(e,i)=>(t.push({literal:e,...i}),e)),t},tintSaturationScale=e=>{const t=themeLuminance(e);return void 0===t?void 0:Math.max(t,.33)},shadeShift=(e,t,i)=>{const[r,o,s]=[e,t,i].map(toHsl);if(!r||!o||!s)return;const a=r.s<.08||o.s<.08;if(!a&&hueDistance(r,o)>40)return;const n=hslShiftBetween(e,t),l=s.alpha??1;return n&&{...n,h:a?0:n.h,alpha:(o.alpha??1)*l-l}},recolorValue=(e,t)=>{const i=[...t].reverse();return mapColorLiterals(e,(e,{roadClass:t})=>{const r=i.filter(({owns:e})=>!e||e(t));for(const{anchorColor:i,newColor:s}of r){const t=shadeShift(i,e,s);if(t)return shiftHsl(s,t)??e}const o=r.find(e=>e.recolorsTints);return o?((e,t,i)=>{const[r,o,s]=[e,t,i].map(toHsl),[a,n]=[e,i].map(tintSaturationScale);if(!(r&&o&&s&&a&&n))return;const l=o.s*n/a,c=(o.alpha??1)*(s.alpha??1);return formatStyleHsl({h:o.h,s:l,l:s.l+o.l-r.l,alpha:c})})(o.anchorColor,e,o.newColor)??e:e})},FLOW_TAGS=["road_category","road_subcategory","relative_speed","left_hand_traffic","road_closure","absolute_speed","part_of_two_way_road","openlr","display_class"],trafficFlowMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:e.geometry,properties:{roadCategory:t?.road_category,leftHandTraffic:Boolean(t?.left_hand_traffic),roadClosure:Boolean(t?.road_closure),relativeSpeed:t?.relative_speed,...t?.road_subcategory&&{roadSubcategory:t.road_subcategory},...t?.absolute_speed&&{absoluteSpeed:t.absolute_speed},...t?.part_of_two_way_road&&{partOfTwoWayRoad:Boolean(t.part_of_two_way_road)},...t?.openlr&&{openlr:t.openlr},...t?.display_class&&{displayClass:t.display_class}}}},INCIDENT_TAGS=["icon_category","left_hand_traffic","magnitude_of_delay","road_category","road_subcategory","id","description","delay","part_of_two_way_road","start_time","end_time","probability_of_occurrence","number_of_reports","last_report_time","average_speed_kmph","openlr","time_validity","display_class"],trafficIncidentMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:e.geometry,properties:{id:t.id??generateId(),description:t?.description_0??"",category:iconToTrafficIncidentCategory(t?.icon_category_0),magnitudeOfDelay:indexedMagnitudes[t?.magnitude_of_delay],roadCategory:t?.road_category,roadSubcategory:t?.road_subcategory,leftHandTraffic:Boolean(t?.left_hand_traffic),...t?.delay&&{delayInSeconds:t.delay},...t?.part_of_two_way_road&&{partOfTwoWayRoad:Boolean(t.part_of_two_way_road)},...t?.start_time&&{startTime:new Date(t.start_time)},...t?.end_time&&{endTime:new Date(t.end_time)},...t?.probability_of_occurrence&&{probabilityOfOccurrence:t.probability_of_occurrence},...t?.number_of_reports&&{numberOfReports:t.number_of_reports},...t?.last_report_time&&{lastReportTime:new Date(t.last_report_time)},...t?.average_speed_kmph&&{averageSpeedKmph:t.average_speed_kmph},...t?.openlr&&{openlr:t.openlr},...t?.time_validity&&{timeValidity:t.time_validity},...t?.display_class&&{displayClass:t.display_class},...t?.point_type&&{pointType:t.point_type}}}},toPinSpriteImageID=e=>`pinCategories:${e}`,isDOMImageSupported=()=>"undefined"!=typeof document&&"undefined"!=typeof DOMParser&&"undefined"!=typeof btoa,urlToImg=e=>{if(!isDOMImageSupported())return;const t=document.createElement("img");return t.src=e,t},svgToImg=e=>{if(isDOMImageSupported())return urlToImg(`data:image/svg+xml;base64,${btoa((new XMLSerializer).serializeToString(e))}`)},parseSvg=e=>(new DOMParser).parseFromString(e,"image/svg+xml").documentElement,pinSvg=e=>((e,t)=>(t?.fillColor&&e.querySelector("#background")?.setAttribute("fill",t.fillColor),t?.outlineColor&&e.querySelector("#outline")?.setAttribute("fill",t.outlineColor),void 0!==t?.outlineOpacity&&e.querySelector("#outline")?.setAttribute("fill-opacity",t.outlineOpacity.toString()),e))(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140">\n <path id="background" d="M63.95 137.516c6.556-12.737 19.098-21.09 30.828-29.388C110.046 97.324 120 79.603 120 59.574 120 26.671 93.138 0 60 0S0 26.671 0 59.574c0 20.029 9.954 37.75 25.22 48.55 11.734 8.302 24.274 16.652 30.83 29.388 1.706 3.316 6.194 3.316 7.9 0z"\n fill="#1988cf"/>\n <path id="outline" d="M91.298 103.272C105.052 93.544 114 77.596 114 59.574c0-29.61-24.176-53.617-54-53.617S6 29.964 6 59.574c0 18.022 8.95 33.97 22.7 43.698l2.27 1.601c10.172 7.153 21.922 15.423 29.03 27.416 7.104-11.993 18.858-20.259 29.03-27.416l2.268-1.601zm1.468 6.274c-11.13 7.845-22.632 15.957-28.816 27.966-1.706 3.316-6.194 3.316-7.9 0-6.182-12.009-17.686-20.121-28.816-27.966l-2.016-1.422C9.954 97.324 0 79.603 0 59.574 0 26.671 26.862 0 60 0s60 26.671 60 59.574c0 20.029-9.954 37.75-25.222 48.55l-2.016 1.422z"\n fill-opacity=".3"/>\n</svg>\n'),e),waitUntilMapIsReady=async e=>{e.mapReady||(await e.mapLibreMap.once("styledata"),await waitUntilMapIsReady(e))},VECTOR_TILE_VIEW_PARAMETERS=[[/\/maps\/orbis\/map-display\/tile\/[^/]+\/[^/]+\/[^/]+\.pbf$/,"view"],[/\/maps\/orbis\/display\/vector\/tile\/[^/]+\/[^/]+\/[^/]+$/,"geopoliticalView"]],vectorTileViewParameter=e=>VECTOR_TILE_VIEW_PARAMETERS.find(([t])=>t.test(e.pathname))?.[1],isVectorTileUrl=e=>{try{return void 0!==vectorTileViewParameter(new URL(e))}catch{return!1}},reloadVectorTiles=e=>{for(const t of(e=>Object.entries(e.getStyle()?.sources??{}).filter(([,e])=>"vector"===e.type&&e.tiles?.some(isVectorTileUrl)).map(([e])=>e))(e)){const i=e.style.tileManagers[t];for(const e of i?.getIds()??[]){const t=i.getTileByID(e);t&&(t.etag=void 0)}e.refreshTiles(t)}},gateOnDemosProxySession=e=>{const t=globalThis.__DEMOS_PROXY_ENSURE_SESSION__;return"function"!=typeof t?e:t().then(()=>e,()=>e)},transformRequest=e=>{const t=e.commonBaseURL??DEFAULT_COMMON_BASE_URL,i=t!==DEFAULT_COMMON_BASE_URL,r=isProxyCredentialsMode(e);return(o,s)=>{const a=((e,t,i,r)=>{if(!i)return e;try{const i=new URL(e);return"api.tomtom.com"===(o=i.hostname)||o.endsWith(".api.tomtom.com")?(r&&i.searchParams.delete("key"),t+i.pathname+i.search+i.hash):e}catch{return e}var o})(o,t,i,r),n=i&&a.startsWith(t),l=r&&n;let c=!1;try{const e=new URL(o).hostname;c="tomtom.com"===e||e.endsWith(".tomtom.com")}catch{c=!1}if(!c&&!n)return{url:a};if("Image"===s)return l?gateOnDemosProxySession({url:a,credentials:"include"}):{url:a};const d=new URL(a);(e=>{e.pathname.includes("incidents")?e.searchParams.set("tags",INCIDENT_TAGS.join(",")):e.pathname.includes("flow")&&e.searchParams.set("tags",FLOW_TAGS.join(","))})(d),((e,t)=>{const i=vectorTileViewParameter(e),r=t&&(e=>"AE"===e?"Arabic":"CN"===e||"RU"===e?void 0:e)(t);i&&r&&e.searchParams.set(i,r)})(d,e.geopoliticalView);const u={url:d.toString(),headers:{...generateTomTomHeaders(e)}};return l?(u.credentials="include",gateOnDemosProxySession(u)):u}},changeLayerProps=(e,t,i)=>{const r=e.id;e.maxzoom===t.maxzoom&&e.minzoom===t.minzoom||i.setLayerZoomRange(r,e.minzoom??i.getMinZoom(),e.maxzoom??i.getMaxZoom()),i.setFilter(r,e.filter,{validate:!1});for(const o of Object.keys(t.layout??{}))e.layout?.[o]||i.setLayoutProperty(r,o,void 0,{validate:!1});for(const o of Object.keys(t.paint??{}))e.paint?.[o]||i.setPaintProperty(r,o,void 0,{validate:!1});for(const[o,s]of Object.entries(e.paint??{}))i.setPaintProperty(r,o,s,{validate:!1});for(const[o,s]of Object.entries(e.layout??{}))i.setLayoutProperty(r,o,s,{validate:!1})},updateLayersAndSource=(e,t,i,r)=>{const o=keyBy(e,"id"),s=keyBy(t,"id"),a=[],n=[],l=[],c=[];Object.keys(o).forEach(e=>{s[e]?(l.push(o[e]),c.push(s[e])):a.push(e)}),Object.keys(s).forEach(e=>{o[e]||n.push(e)});const d=i._layerSpecs;n.forEach(e=>{r.removeLayer(e);for(let t=0;t<d.length;t++)if(d[t].id===e){d.splice(t,1);break}});const u=a.map(e=>({...o[e],source:i.source.id}));u.length&&(d.push(...u),addLayers(u,r)),i._updateSourceAndLayerIDs(),((e,t,i,r)=>{const o=/* @__PURE__ */new Set,s=e=>{if(!r.getLayer(e.id))return;moveLayerBefore(r,e.id,e.beforeID),o.add(e.id);const t=i.find(t=>t.id===e.id);t&&(t.beforeID=e.beforeID)};e.forEach((e,i)=>{e.beforeID!==t[i].beforeID&&s(e)});const a=()=>e.filter(e=>!o.has(e.id)&&void 0!==e.beforeID&&o.has(e.beforeID));for(let n=a();n.length;n=a())n.forEach(s)})(l,c,d,r),((e,t,i)=>{e.forEach((e,r)=>changeLayerProps(e,t[r],i))})(l,c,r)},existingBeforeLayerID=(e,t)=>t&&e.getLayer(t)?t:void 0,moveLayerBefore=(e,t,i)=>{e.moveLayer(t,existingBeforeLayerID(e,i))},applyLayersVisibility=(e,t,i)=>{if(i._removed)return;const r=t?"visible":"none";for(const o of e)"none"!==o.layout?.visibility&&i.getLayer(o.id)&&i.setLayoutProperty(o.id,"visibility",r,{validate:!1})},addLayers=(e,t,i=!1)=>{const r=/* @__PURE__ */new Set,o=e=>{t.getLayer(e.id)?i&&t.moveLayer(e.id,e.beforeID):t.addLayer({...e,layout:{...e.layout,visibility:"none"}},e.beforeID),r.add(e.id)},s={},a=new Set(i?e.map(e=>e.id):[]);for(e.forEach(e=>{var i;e.beforeID?(i=e.beforeID,r.has(i)||!a.has(i)&&t.getLayer(i)?(r.add(e.beforeID),o(e)):s[e.beforeID]?s[e.beforeID].push(e):s[e.beforeID]=[e]):o(e)});Object.keys(s).length>0;){const e=Object.keys(s).filter(e=>r.has(e));if(!e.length)return void console.error(`Some layers cannot be added. Check for non-existing layers, or circular beforeID dependencies for the following: ${JSON.stringify(Object.keys(s))}`);e.forEach(e=>{s[e].forEach(e=>o(e)),delete s[e]})}},updateStyleWithPart=(e,t)=>{switch(typeof e){case"undefined":return{type:"standard",include:[t]};case"string":return{type:"standard",id:e,include:[t]};default:if("standard"===e.type)return e.include?{...e,include:[...e.include,t]}:{...e,include:[t]};throw(e=>/* @__PURE__ */new Error(`The custom map style has no '${e}' part and the SDK cannot add one to it. Style-owned modules work on a custom style only when it already ships the matching source (e.g. built with that part enabled) — or switch to a standard style.`))(t)}},ensureAddedToStyle=async(e,t,i)=>{if(!e.mapLibreMap.getSource(t)){const r=e.mapLibreMap;r.isStyleLoaded()||await r.once("idle"),await e.setStyle(updateStyleWithPart(e.getStyleInput(),i)),await(async(e,t)=>{e.mapLibreMap.getSource(t)&&e.mapLibreMap.isSourceLoaded(t)||await e.mapLibreMap.once("sourcedata")})(e,t)}},addOrUpdateImage=async(e,t,i,r,o)=>{if(!i)return void console.warn(`addOrUpdateImage called with empty image for ID ${t}`);const s=i=>{const s=r.hasImage(t);s&&"add-or-update"==e?r.updateImage(t,i):s||r.addImage(t,i,o)},a=e=>{e.complete?e.naturalWidth>0?s(e):console.warn(`Failed to load image for ID ${t}`):(e.onload=()=>s(e),e.onerror=()=>console.warn(`Failed to load image for ID ${t}`))};if("string"==typeof i)if(/^data:image\/svg\+xml[;,]/i.test(i))a(urlToImg(i));else if(i.includes("<svg"))a(svgToImg(parseSvg(i)));else try{s((await r.loadImage(i)).data)}catch(n){console.warn(`Failed to load image for ID ${t}`,n)}else a(i)},getStyleLightDarkTheme=e=>{const t=getDeclaredLightDarkTheme(e);if(t)return t;const i=standardStyleIdOf(e);return i?(e=>{switch(e){case"standardDark":case"drivingDark":case"monoDark":case"satellite":return"dark";default:return"light"}})(i):"light"},standardStyleIdOf=e=>"string"==typeof e?e:"standard"===e?.type?e.id??"standardLight":void 0,getDeclaredLightDarkTheme=e=>isCustomStyle(e)?e.lightDarkTheme:void 0,isCustomStyle=e=>"object"==typeof e&&"custom"===e?.type,UserEvents=class e{constructor(e){this.options=e,this.sources=e.sourcesWithLayers}where(t,i){return new e({...this.options,config:i??this.options.config,scope:combineEventScopes(this.options.scope,this.resolveScope(t))})}resolveScope(e){if("function"==typeof e){const t=e,i=this.options.mapping;return{featureMatches:i?e=>t(i(e)):e=>t(e)}}const t=this.options.scopeResolver;if(!t)throw new Error("This module supports only feature predicates in events.where().");return t(e)}on(e,t){const{eventProxy:i,config:r,owner:o,scope:s}=this.options,a=this.toRegisteredHandler(t),n=[];for(const l of this.sources)i.addEventHandler(l,a,e,{config:r,owner:o,scope:s}),n.push(l);return()=>{for(const t of n)i.removeHandler(t,e,a)}}toRegisteredHandler(e){const{mapping:t,scope:i}=this.options,r=i?.featureMatches;if(!t&&!r)return e;const o=e=>t?t(e):e;return r?(t,i,s,a)=>{const n=(s.length?s:[t]).filter(e=>r(e));if(!n.length)return;const l=n.map(o);e(l[0],i,l,a)}:(t,i,r,s)=>e(o(t),i,r.map(o),s)}off(e){for(const t of this.sources)this.options.eventProxy.remove(t,e,this.options.owner)}},AbstractMapModule=class e{static{this.instanceCounters=/* @__PURE__ */new WeakMap}constructor(t,i){this._initializing=!0,this.configChangeHandlers=[],this.moduleReady=!1;const r=new.target,o=e.instanceCounters.get(r)??-1;this.instanceIndex=o+1,e.instanceCounters.set(r,this.instanceIndex),this.tomtomMap=t,this.eventsProxy=t._eventsProxy,this.mapLibreMap=t.mapLibreMap,this.filterComposer=LayerFilterComposer.for(t),this.initSourcesWithLayers(i),this.applyConfig(i),this.tomtomMap.addStyleChangeHandler({onStyleAboutToChange:()=>{this.moduleReady=!1},onStyleChanged:({resetState:e})=>e?this.resetOnNewStyle():this.restoreDataAndConfig(),priority:this.styleChangePriority()}),this._initializing=!1}styleChangePriority(){return 0}initSourcesWithLayers(e,t){this.moduleReady=!1,this.sourcesWithLayers=this._initSourcesWithLayers(e,t),this._sourceAndLayerIDs=Object.fromEntries(Object.entries(this.sourcesWithLayers).map(([e,t])=>[e,t.sourceAndLayerIDs])),t&&this.eventsProxy.updateIfRegistered(this.sourcesWithLayers,this),this.tomtomMap.mapReady&&(this.moduleReady=!0)}async waitUntilModuleReady(){await waitUntilMapIsReady(this.tomtomMap),this.moduleReady||await new Promise(e=>{const t=setInterval(()=>{this.tomtomMap.mapReady&&this.moduleReady&&(clearInterval(t),e())},200)})}applyConfig(e){this.config=this._applyConfig(e),this.emitConfigChange()}updateConfig(e){this.applyConfig({...this.config,...e})}emitConfigChange(){if(!this._initializing)for(const e of this.configChangeHandlers)e(this.config)}resetConfig(){this.applyConfig(void 0)}restoreDataAndConfig(){this.moduleReady=!1,this.restoreDataAndConfigImpl()}resetOnNewStyle(){this.moduleReady=!1,this.config=void 0,this.discardShownData(),this.initSourcesWithLayers(void 0,!0),this.config=this._applyConfig(void 0),this.emitConfigChange()}discardShownData(){}restoreDataAndConfigImpl(){this.initSourcesWithLayers(this.config,!0),this._applyConfig(this.config)}getConfig(){return this.config&&{...this.config}}get sourceAndLayerIDs(){return this._sourceAndLayerIDs}userEvents(e,t={}){return new UserEvents(this.userEventsOptions(e,t))}userEventsOptions(e,t){return{eventProxy:this.eventsProxy,sourcesWithLayers:this.sourcesNamed(e),owner:this,config:this.config?.events,mapping:t.mapping,scopeResolver:t.scopeResolver}}sourcesNamed(e){return e.map(e=>this.sourcesWithLayers[e]).filter(e=>!!e)}lifecycleEvents(){return new ModuleEvents(this.configChangeHandlers,[])}moduleEvents(e,t={}){return new CombinedEvents(this.userEvents(e,t),this.lifecycleEvents())}moduleEventsWithShown(e,t,i={}){return new CombinedEvents(this.userEvents(e,i),new ModuleEvents(this.configChangeHandlers,t))}buildEvents(e,t){return assertNoReservedScopeNames(Object.keys(t),this.constructor.name),Object.assign(e,t)}},EventStates=class{constructor(e){this.sources=e}put(e){for(const t of this.sources())t.putEventState(e)}clean(e){for(const t of this.sources())t.cleanEventState(e)}cleanAll(e){for(const t of this.sources())t.cleanEventStates(e)}get(){const e={};for(const t of this.sources())t.getEventStates(e);return e}},UserEventsWithStates=class extends UserEvents{constructor(e,t){super(e),this.eventStates=new EventStates(t)}putEventState(e){this.eventStates.put(e)}cleanEventState(e){this.eventStates.clean(e)}cleanEventStates(e){this.eventStates.cleanAll(e)}getEventStates(){return this.eventStates.get()}},AbstractDataOwnedMapModule=class extends AbstractMapModule{constructor(...e){super(...e),this.eventStates=new EventStates(()=>this.sourcesNamed(this.eventStateSources()))}setVisible(e){this.config={...this.config,visible:e},this.applyVisibility(this.config),this.emitConfigChange()}isVisible(){return!1!==this.config?.visible}userEventsWithStates(e,t={}){return new UserEventsWithStates(this.userEventsOptions(e,t),()=>this.sourcesNamed(e))}putEventState(e){this.eventStates.put(e)}cleanEventState(e){this.eventStates.clean(e)}cleanEventStates(e){this.eventStates.cleanAll(e)}getEventStates(){return this.eventStates.get()}},composersByMap=/* @__PURE__ */new WeakMap,LayerVisibilityComposer=class e extends AbstractLayerComposer{constructor(e){super(e)}static for(t){return composerOfMap(composersByMap,t,()=>new e(t))}setVisible(e,t,i){if(this.mapLibreMap._removed||!this.mapLibreMap.getLayer(e))return;let r=this.byLayer.get(e);if(!r){if(void 0===i)return;r={styleVisibility:this.mapLibreMap.getLayoutProperty(e,"visibility")??"visible",contributions:/* @__PURE__ */new Map},this.byLayer.set(e,r)}setOrDelete(r.contributions,t,i),this.mapLibreMap.setLayoutProperty(e,"visibility",(({styleVisibility:e,contributions:t})=>{const i=new Set(t.values());return i.has(!1)?"none":i.has(!0)?"visible":e})(r),{validate:!1})}},AbstractStyleOwnedMapModule=class extends AbstractMapModule{get visibilityComposer(){return LayerVisibilityComposer.for(this.tomtomMap)}},AbstractEventProxy=class{constructor(){this.interactiveLayerIDs=[],this.handlers={click:{},contextmenu:{},hover:{},"hover-move":{},"long-hover":{}},this.findHandlers=(e,t,i)=>t&&e.flatMap(e=>{const r=this.handlers[e][t]??[];return i?r.filter(e=>!e.scope?.featureMatches||e.scope.featureMatches(i)):r})||[]}ensureInteractiveLayerIDsAdded(e){for(const t of e)this.interactiveLayerIDs.includes(t)||this.interactiveLayerIDs.push(t)}releaseUnusedInteractiveLayerIDs(e){remove(this.interactiveLayerIDs,t=>e.has(t)&&!this.hasHandlerForLayer(t))}indexHandler(e,t){const i=this.handlers[t];for(const r of e.layerIDs)i[r]??=[],i[r].push(e)}unindexHandlers(e,t){const i=this.handlers[t],r=/* @__PURE__ */new Set;for(const o of e)for(const t of o.layerIDs){r.add(t);const o=i[t];o&&(remove(o,t=>e.has(t)),o.length||delete i[t])}return r}dropHandlers(e,t,i){const r=e.source.id,o=/* @__PURE__ */new Set;for(const s of Object.values(this.handlers[t]))for(const e of s)e.sourceWithLayers.source.id===r&&i(e)&&o.add(e);o.size&&this.releaseUnusedInteractiveLayerIDs(this.unindexHandlers(o,t))}addEventHandler(e,t,i,r){const o=new Set(scopedLayerSpecs(e,r.scope).map(e=>e.id));this.ensureInteractiveLayerIDsAdded(o),this.indexHandler({...r,sourceWithLayers:e,layerIDs:o,fn:t},i)}removeHandler(e,t,i){this.dropHandlers(e,t,e=>e.fn===i)}remove(e,t,i){this.dropHandlers(e,t,e=>e.owner===i)}removeAll(){this.interactiveLayerIDs=[],this.handlers={click:{},contextmenu:{},hover:{},"hover-move":{},"long-hover":{}}}hasHandlerForLayer(e){return Object.values(this.handlers).some(t=>!!t[e]?.length)}sourceWithLayersFor(e){if(e)for(const t of Object.values(this.handlers)){const i=t[e];if(i?.length)return i[0].sourceWithLayers}}updateIfRegistered(e,t){const i=new Map(Object.values(e).map(e=>[e.source.id,e]));for(const r of Object.keys(this.handlers)){const e=/* @__PURE__ */new Set;for(const s of Object.values(this.handlers[r]))for(const r of s)r.owner===t&&i.has(r.sourceWithLayers.source.id)&&e.add(r);if(!e.size)continue;const o=this.unindexHandlers(e,r);for(const t of e){const e=i.get(t.sourceWithLayers.source.id);t.sourceWithLayers=e,t.layerIDs=new Set(scopedLayerSpecs(e,t.scope).map(e=>e.id)),this.ensureInteractiveLayerIDsAdded(t.layerIDs),this.indexHandler(t,r)}this.releaseUnusedInteractiveLayerIDs(o)}}},renderedRefId=e=>{const t=e.properties?.id;return"string"==typeof t||"number"==typeof t?t:e.id},findFeatureByRefId=(e,t)=>{if(null!=t)for(let i=0;i<e.length;i++)if(renderedRefId(e[i])===t)return{feature:e[i],index:i}};var sourceProperty,outputProperty,instructionArrowIconImg,asDefined=e=>(function(e){if(isNil(e))throw new Error(`${e} must not be null/undefined. Something went wrong with its initialization.`)}(e),e),TomTomMapSource=class{constructor(e,t,i){this.id=e,this.spec=t,this.runtimeSource=i}ensureAddedToMap(e){this.runtimeSource||(!e.getSource(this.id)&&this.spec&&e.addSource(this.id,this.spec),this.runtimeSource=e.getSource(this.id))}},AbstractSourceWithLayers=class{constructor(e,t,i){this.map=e,this.source=t,this._layerSpecs=i,this._updateSourceAndLayerIDs()}get mapRemoved(){return!0===this.map._removed}isAnyLayerVisible(e){return this.getLayerSpecs(e).some(e=>this.isLayerVisible(e))}areAllLayersVisible(e){return this.getLayerSpecs(e).every(e=>this.isLayerVisible(e))}getLayerSpecs(e){return e?this._layerSpecs.filter(e):this._layerSpecs}_updateSourceAndLayerIDs(){this._sourceAndLayerIDs={sourceID:this.source.id,layerIDs:this._layerSpecs.map(e=>e.id)}}isLayerVisible(e){return!this.mapRemoved&&(!!this.map.getLayer(e.id)&&"none"!==this.map.getLayoutProperty(e.id,"visibility"))}setLayersVisible(e,t){if(!this.mapRemoved)for(const i of this.getLayerSpecs(t))this.map.getLayer(i.id)&&this.map.setLayoutProperty(i.id,"visibility",e?"visible":"none",{validate:!1})}get sourceAndLayerIDs(){return this._sourceAndLayerIDs}},filterLayersBySources=(e,t)=>e.getStyle().layers.filter(e=>t.includes(e?.source)),StyleSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i){let r=filterLayersBySources(e,[t.id]);i&&(r=r.filter(i)),super(e,new TomTomMapSource(t.id,e.getStyle().sources[t.id],t),r)}},AddedSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i,r){super(e,new TomTomMapSource(t,i),r.map(e=>({...e,source:t})))}ensureLayersAddedToMap(){if(!this.mapRemoved)for(const e of this._layerSpecs)this.map.getLayer(e.id)||this.map.addLayer(e,e.beforeID)}ensureAddedToMapWithVisibility(e,t){this.mapRemoved||(this.source.ensureAddedToMap(this.map),t&&(this.ensureLayersAddedToMap(),this.setLayersVisible(e)))}},emptyFeatureCollection={type:"FeatureCollection",features:[]},withEventState=(e,t)=>({...e,properties:t?{...e.properties,eventState:t}:omit(e.properties,"eventState")}),GeoJSONSourceWithLayers=class extends AddedSourceWithLayers{constructor(e,t,i,r=!0,o){super(e,t,o?.cluster?{type:"geojson",data:emptyFeatureCollection,...o}:{type:"geojson",data:emptyFeatureCollection,promoteId:"id",...o??{}},i),this.shownFeatures=emptyFeatureCollection,this.showListeners=[],this.ensureAddedToMapWithVisibility(!1,r)}show(e,{automaticVisibility:t=!0}={}){if(this.shownFeatures=e,!this.mapRemoved){asDefined(this.source.runtimeSource).setData(e),t&&this.setLayersVisible(!!e.features.length);for(const e of this.showListeners)e()}}onShow(e){this.showListeners.push(e)}findById(e){return findFeatureByRefId(this.shownFeatures.features,e)}clear(){this.show(emptyFeatureCollection)}findFeature(e){return"index"in e?this.shownFeatures.features[e.index]:"id"in e?this.findById(e.id)?.feature:void 0}showWithFeatures(e,t=!0){const i={...this.shownFeatures,features:e};t?this.show(i,{automaticVisibility:!1}):this.shownFeatures=i}putEventState(e){const t=e.mode??"put",i=this.findFeature(e);this.showWithFeatures(this.shownFeatures.features.map(r=>r===i?withEventState(r,e.state):"put"===t&&r.properties?.eventState===e.state?withEventState(r,void 0):r),e.show)}cleanEventState(e){const t=this.findFeature(e);t?.properties?.eventState&&this.showWithFeatures(this.shownFeatures.features.map(e=>e===t?withEventState(e,void 0):e),e.show)}cleanEventStates(e){const t=t=>void 0!==t.properties?.eventState&&(!e?.states||e.states.includes(t.properties.eventState));this.shownFeatures.features.some(t)&&this.showWithFeatures(this.shownFeatures.features.map(e=>t(e)?withEventState(e,void 0):e),e?.show)}getEventStates(e={}){for(const t of this.shownFeatures.features){const i=t.properties?.eventState,r=renderedRefId(t);if(!i||void 0===r)continue;const o=e[i]??=[];o.includes(r)||o.push(r)}return e}},isClickEventType=e=>"click"===e||"contextmenu"===e,isHoverEventState=e=>"hover"===e||"hover-move"===e||"long-hover"===e,putEventState=(e,t,i,r="updateInProps")=>{const{feature:o,index:s}=findFeatureByRefId(i,t)||{};if(o&&(a=o.properties?.eventState,"recently-hovered"===(n=e)?isHoverEventState(a):!isClickEventType(a)||isClickEventType(n)))return i.splice(s,1,withEventState(o,"updateInProps"===r?e:void 0)),s;var a,n},leaveEventState=(e,t,i,r)=>r?putEventState("recently-hovered",t,i):putEventState(e,t,i,"removeFromProps"),leaveOtherFeatures=(e,t,i)=>{i.forEach((r,o)=>{renderedRefId(r)!==t&&((e,t)=>isClickEventType(e)&&isClickEventType(t)||isHoverEventState(e)&&isHoverEventState(t))(r.properties?.eventState,e)&&(i[o]=withEventState(r,void 0))})},removeEventStateAndShow=(e,t,i,r)=>{const o=[...i.shownFeatures.features],s=leaveEventState(e,renderedRefId(t),o,r);isNil(s)||i.show({...i.shownFeatures,features:o},{automaticVisibility:!1})},updateEventState=(e,t,i,r,o,s=!1)=>{if(t&&r instanceof GeoJSONSourceWithLayers){const l=[...r.shownFeatures.features];return putEventState(e,renderedRefId(t),l),!i||(n=t,(a=i)&&n&&a.id===n.id)||(o===r?leaveEventState(e,renderedRefId(i),l,s):o instanceof GeoJSONSourceWithLayers&&removeEventStateAndShow(e,i,o,s)),leaveOtherFeatures(e,renderedRefId(t),l),void r.show({...r.shownFeatures,features:l},{automaticVisibility:!1})}var a,n;i&&o instanceof GeoJSONSourceWithLayers&&removeEventStateAndShow(e,i,o,s)},noRenderedFeatures=[],interactiveEventTypes=["hover","hover-move","long-hover","click","contextmenu"],eventsProxyDefaultConfig={precisionMode:"box",paddingBoxPx:5,cursorOnHover:"pointer",cursorOnMouseDown:"grabbing",cursorOnMap:"default",longHoverDelayAfterMapMoveMS:800,longHoverDelayOnStillMapMS:300,hoverGracePeriodMS:400},EventsProxy=class extends AbstractEventProxy{constructor(e,t={}){super(),this.enabled=!0,this.recentHoverTimeouts=new globalThis.Map,this.firstDelayedHoverSinceMapMove=!0,this.mouseMoveFrameRequested=!1,this.map=e,this.mapCanvas=e.getCanvas(),this.config={...eventsProxyDefaultConfig,...omitBy(t,isUndefined)},this.mapCanvas.style.cursor=this.config.cursorOnMap,this.lastCursorStyle=this.config.cursorOnMap,this.listenToEvents()}updateConfig(e){this.config={...this.config,...omitBy(e,isUndefined)},this.hoveringFeature||(this.mapCanvas.style.cursor=this.config.cursorOnMap)}listenToEvents(){this.map.on("mousemove",e=>this.onMouseMove(e)),this.map.on("movestart",()=>this.onMouseStart()),this.map.on("mouseout",()=>this.onMouseOut()),this.map.on("mouseover",e=>this.onMouseMove(e)),this.map.on("mousedown",()=>this.onMouseDown()),this.map.on("mouseup",()=>this.onMouseUp()),this.map.on("click",e=>this.onMapClick("click",e)),this.map.on("contextmenu",e=>this.onMapClick("contextmenu",e))}enable(e){this.enabled=e,e||(this.clearLongHoverTimeout(),this.pendingMouseMove=void 0)}toPaddedBounds(e){const t=this.config.paddingBoxPx;return[[e.x-t,e.y+t],[e.x+t,e.y-t]]}isEnabled(){return this.enabled&&!this.map.isMoving()}toCallerFeatures(e,t,i){const r=i?e.filter(e=>i.has(e.layer.id)):e,o=(e=>{const t=/* @__PURE__ */new Set,i=[];for(const r of e){const e=renderedRefId(r);if(void 0===e){i.push(r);continue}const o=`${r.source} ${e}`;t.has(o)||(t.add(o),i.push(r))}return i})((s=r,a=t?.source,a?s.filter(e=>e.source===a):s));var s,a;const n=this.sourceWithLayersFor(t?.layer.id);return n instanceof GeoJSONSourceWithLayers?o.map(e=>n.findById(renderedRefId(e))?.feature??e):o}callerFeaturesFor(e,t,i,r){return e.scope?.layerFilter?this.toCallerFeatures(t,i,e.layerIDs):r}getRenderedFeatures(e){if(!this.interactiveLayerIDs.length)return[];const t={layers:this.interactiveLayerIDs,validate:!1},i=this.config.precisionMode,r="point-then-box"===i||"point"===i?this.map.queryRenderedFeatures(e,t):[];return r.length||"point"===i?r:this.map.queryRenderedFeatures(this.toPaddedBounds(e),t)}clearLongHoverTimeout(){clearTimeout(this.longHoverTimeoutHandlerID)}restartLongHoverTimeout(){this.clearLongHoverTimeout(),this.longHoverTimeoutHandlerID=setTimeout(()=>this.handleLongHoverTimeout(),this.firstDelayedHoverSinceMapMove?this.config.longHoverDelayAfterMapMoveMS:this.config.longHoverDelayOnStillMapMS)}handleLongHoverTimeout(){if(this.firstDelayedHoverSinceMapMove=!1,this.hoveringSourceWithLayers){updateEventState("long-hover",this.hoveringFeature,void 0,this.hoveringSourceWithLayers,void 0);const e=this.findHandlers(["long-hover"],this.hoveringFeature?.layer.id);if(e.length){const t=this.hoveringFeatures??noRenderedFeatures,i=this.hoveringFeature,r=this.toCallerFeatures(t,i);for(const o of e){const e=this.callerFeaturesFor(o,t,i,r);o.fn(e[0],this.hoveringLngLat,e,o.sourceWithLayers)}}}}onMouseStart(){this.firstDelayedHoverSinceMapMove=!0,this.clearLongHoverTimeout()}onMouseOut(){this.clearLongHoverTimeout()}onMouseDown(){this.lastCursorStyle=this.mapCanvas.style.cursor,this.mapCanvas.style.cursor=this.config.cursorOnMouseDown}onMouseUp(){this.mapCanvas.style.cursor=this.lastCursorStyle}onMouseMove(e){this.pendingMouseMove=e,this.mouseMoveFrameRequested||(this.mouseMoveFrameRequested=!0,requestAnimationFrame(()=>{this.mouseMoveFrameRequested=!1;const e=this.pendingMouseMove;this.pendingMouseMove=void 0,e&&this.handleMouseMove(e)}))}handleMouseMove(e){if(!this.isEnabled())return;this.hoveringFeatures=this.getRenderedFeatures(e.point);const[t]=this.hoveringFeatures;if(t&&!this.hasHandlerForLayer(t.layer.id))return;const{hoverChanged:i,mouseInMotionOverHoveredFeature:r}=((e,t,i,r)=>{if(t){if(!r)return{hoverChanged:!0};if(t.id&&t.id!==r.id||t.properties.id&&t.properties.id!==r.properties.id||t.source!==r.source||t.layer.id!==r.layer.id)return{hoverChanged:!0};if(i&&(e.x-i.x!=0||e.y-i.y!=0))return{mouseInMotionOverHoveredFeature:!0}}else if(r)return{hoverChanged:!0};return{}})(e.point,t,this.hoveringPoint,this.hoveringFeature);if(!i&&!r)return;const o=this.hoveringFeature,s=this.hoveringSourceWithLayers;let a;this.hoveringLngLat=e.lngLat,this.hoveringPoint=e.point,this.hoveringFeature=t,this.hoveringSourceWithLayers=this.sourceWithLayersFor(t?.layer.id),i&&(a=this.dispatchHoverEnter(e,o,s)),r&&this.dispatchHoverMove(e,a),this.restartLongHoverTimeout()}dispatchHoverEnter(e,t,i){const r=this.hoveringFeature?.layer.id,o=this.findHandlers(interactiveEventTypes,r,this.hoveringFeature)?.[0];this.updateHoverCursor(o?.config);const s=t?this.hoverGracePeriodFor(t):0;updateEventState("hover",this.hoveringFeature,t,this.hoveringSourceWithLayers,i,s>0),t&&s>0&&this.clearRecentHoverLater(t,s);const a=this.findHandlers(["hover"],r);if(!a.length)return;const n=this.toCallerFeatures(this.hoveringFeatures??noRenderedFeatures,this.hoveringFeature);return this.dispatchToHandlers(a,e,this.hoveringFeature,n),n}dispatchHoverMove(e,t){const i=this.findHandlers(["hover-move"],this.hoveringFeature?.layer.id);if(!i.length)return;const r=this.hoveringFeature,o=t??this.toCallerFeatures(this.hoveringFeatures??noRenderedFeatures,r);this.dispatchToHandlers(i,e,r,o)}dispatchToHandlers(e,t,i,r){for(const o of e){const e=this.callerFeaturesFor(o,this.hoveringFeatures??noRenderedFeatures,i,r);o.fn(e[0],t.lngLat,e,o.sourceWithLayers)}}hoverGracePeriodFor(e){return this.findHandlers(interactiveEventTypes,e.layer.id,e)[0]?.config?.hoverGracePeriodMS??this.config.hoverGracePeriodMS}clearRecentHoverLater(e,t){const i=renderedRefId(e);if(void 0===i)return;const r=`${e.source} ${i}`,o=e.layer.id;clearTimeout(this.recentHoverTimeouts.get(r)),this.recentHoverTimeouts.set(r,setTimeout(()=>{this.recentHoverTimeouts.delete(r);const e=this.sourceWithLayersFor(o);e instanceof GeoJSONSourceWithLayers&&((e,t)=>{const i=e.findById(t);"recently-hovered"===i?.feature.properties?.eventState&&e.cleanEventState({index:i.index})})(e,i)},t))}updateHoverCursor(e){this.hoveringFeature?this.mapCanvas.style.cursor=e?.cursorOnHover??this.config.cursorOnHover:this.mapCanvas.style.cursor=this.config.cursorOnMap}onMapClick(e,t){if(!this.isEnabled())return;const i=this.getRenderedFeatures(t.point),r=this.lastClickedFeature;this.lastClickedFeature=i[0];const o=this.lastClickedSourceWithLayers,s=this.findHandlers([e],this.lastClickedFeature?.layer.id);if(this.lastClickedSourceWithLayers=s[0]?.sourceWithLayers,updateEventState(e,this.lastClickedFeature,r,this.lastClickedSourceWithLayers,o),s.length){const e=this.lastClickedFeature,r=this.toCallerFeatures(i,e);for(const o of s){const s=this.callerFeaturesFor(o,i,e,r);o.fn(s[0],t.lngLat,s,o.sourceWithLayers)}}}},describe=e=>"string"==typeof e?`'${e}'`:Array.isArray(e)?`[${e.map(describe).join(", ")}]`:String(e),expected=(e,t)=>`expects ${e}; got ${describe(t)}`,isFiniteNumber=e=>"number"==typeof e&&Number.isFinite(e),isWithin=(e,{min:t,max:i,bounds:r})=>"soft"===r||e>=t&&("hard-min"===r||e<=i),boundsText=({min:e,max:t,bounds:i})=>"hard"===i?` between ${e} and ${t}`:"hard-min"===i?` of at least ${e}`:"",listProblem=(e,t,i)=>{if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))return expected(e,t);const r=t.filter(e=>!i(e));return r.length?`expects ${e}; ${r.map(describe).join(", ")} ${1===r.length?"is":"are"} not`:void 0},validateKnobValue=(e,t)=>{const i=((e,t)=>{switch(e.kind){case"toggle":return"boolean"==typeof t?void 0:expected("true or false",t);case"factor":case"number":return isFiniteNumber(t)&&isWithin(t,e.range)?void 0:expected(`a number${boundsText(e.range)}`,t);case"offset":return Array.isArray(t)&&2===t.length&&t.every(t=>isFiniteNumber(t)&&isWithin(t,e.range))?void 0:expected(`an [x, y] pair of numbers${boundsText(e.range)}`,t);case"color":return isColorLiteral(t)?void 0:expected("a CSS colour (#rrggbb, hsl(), rgb() or a named colour)",t);case"enum":return"string"==typeof t&&e.options.includes(t)?void 0:expected(`one of ${e.options.join(", ")}`,t);case"enums":return listProblem("a list of its options",t,t=>e.options.includes(t));case"colors":return listProblem(e.options?"a list of CSS colours or of its options":"a list of CSS colours",t,t=>isColorLiteral(t)||Boolean(e.options?.includes(t)));default:return"string"==typeof t?void 0:expected("a string",t)}})(e,t);if(i)throw new RangeError(`Knob '${e.id}' ${i}.`)},copyOf=e=>isObject(e)?clone(e):void 0,setKnob=(e,t,i,r)=>{const o=t.find(e=>e.id===i);if(!o)throw new Error(`Unknown knob '${i}'; its catalogue lists every id.`);validateKnobValue(o,r),e.applyConfig(setWith(e.getConfig()??{},i,r,copyOf))},MAP_BOLD_FONT="Noto-Bold",MAP_REGULAR_FONT="Noto-Regular",MAP_MEDIUM_FONT="Noto-Medium",MAP_ITALIC_FONT="NotoSans-MediumItalic",DEFAULT_TEXT_SIZE=["interpolate",["linear"],["zoom"],10,14,18,16],mapFonts=["Noto-Regular","NotoSans-MediumItalic","Noto-Bold","Noto-Medium"],PIN_ICON_SIZE=["interpolate",["linear"],["zoom"],8,.6,22,.8],SELECTED_PIN_ICON_SIZE=["interpolate",["linear"],["zoom"],8,.8,22,1],mapStyleLayerIDs={country:"Places - Country name",lowestPlaceLabel:"Places - Village / Hamlet",poi:"POI",lowestLabel:"Borders - Treaty label",lowestRoadLine:"Tunnel - Railway outline",lowestBuilding:"Buildings - Underground"},BASE_MAP_SOURCE_ID="vectorTiles",POI_SOURCE_ID="vectorTiles",HILLSHADE_SOURCE_ID="hillshade",TERRAIN_SOURCE_ID="hillshade-terrain",TRAFFIC_INCIDENTS_SOURCE_ID="vectorTilesIncidents",TRAFFIC_FLOW_SOURCE_ID="vectorTilesFlow",instancesByMap=/* @__PURE__ */new WeakMap,builtByMap=/* @__PURE__ */new WeakMap,entriesOf=(e,t)=>{let i=e.get(t);return i||(i=/* @__PURE__ */new Map,e.set(t,i)),i},sharedInstanceIfCreated=(e,t)=>builtByMap.get(e)?.get(t),sharedInstance=async(e,t,i,r)=>{const o=entriesOf(instancesByMap,e),s=o.get(t);if(s){const e=await s;return r?.(e),e}const a=Promise.resolve().then(i);o.set(t,a);try{const i=await a;return entriesOf(builtByMap,e).set(t,i),i}catch(n){throw o.delete(t),n}},filterShowModes=["only","all-except"],clampFactor=(e,t,i=1)=>void 0!==e&&Number.isFinite(e)?clamp(e,t.min,t.max):i,everyOf=()=>e=>e,withIds=e=>Object.keys(e).map(t=>({id:t,...e[t]})),defaultOf=e=>void 0===e?{}:{default:e},OPACITY_RANGE={min:0,max:1,step:.05,bounds:"hard"},ZOOM_RANGE={min:0,max:22,step:1,bounds:"hard"},poiCategoryGroups={FOOD_DRINKS_GROUP:["RESTAURANT","FAST_FOOD","CAFE_PUB","PUB","WINERY","SOUL_FOOD","DELICATESSEN"],SHOPPING_GROUP:["SHOP_OR_STORE","MALL","CLOTHING_SHOP","MARKETPLACE","FOOD_MARKET","SUPERMARKET","DEPARTMENT_STORE","CONVENIENCE_STORE","GROCERY_STORE","HARDWARE_STORE","ELECTRICAL_APPLIANCES_SHOP"],TRANSPORTATION_GROUP:["AIRPORT","FERRY_TERMINAL","HELIPORT_OR_HELIPAD","PUBLIC_TRANSPORT_STOP","RAILWAY_STATION","BUS_STOP","TAXI_STAND"],HEALTH_GROUP:["DOCTOR","EMERGENCY_MEDICAL_SERVICE","EMERGENCY_ROOM","HEALTHCARE_SERVICE","HOSPITAL","PHARMACY","DENTIST","WELFARE_ORGANIZATION"],PARKING_GROUP:["PARKING_GARAGE","OPEN_CAR_PARKING_AREA"],HOLIDAY_TOURISM_GROUP:["AMUSEMENT_PARK","BEACH","HOLIDAY_RENTAL","NATURAL_FEATURE","TOURIST_ATTRACTION","LEISURE_CENTER","MOUNTAIN_PASS","MOUNTAIN_PEAK","MUSEUM","VIEWPOINT","TOURIST_INFORMATION"],EV_CHARGING_STATIONS_GROUP:["CHARGING_LOCATION"],GAS_STATIONS_GROUP:["FUEL_STATION"],ACCOMMODATION_GROUP:["CAMPING_GROUND","HOTEL_OR_MOTEL","HOLIDAY_RENTAL"],ENTERTAINMENT_GROUP:["CINEMA","THEATER","MOVIE_THEATER","NIGHTLIFE","CONCERT_HALL","ENTERTAINMENT","CLUB_AND_ASSOCIATION","CASINO_AND_GAMBLING"],SPORTS_LEISURE_GROUP:["SPORTS_CENTER","WATER_SPORT","SWIMMING_POOL","GOLF_COURSE","STADIUM","BEACH","ICE_RINK","LEISURE_CENTER","MOUNTAIN_PASS","MOUNTAIN_PEAK"],EDUCATION_GROUP:["SCHOOL","COLLEGE_OR_UNIVERSITY","PUBLIC_LIBRARY","CULTURAL_CENTER"],GOVERNMENT_GROUP:["GOVERNMENT_OFFICE","COURTHOUSE","EMBASSY","FIRE_STATION","POLICE_STATION"]},poisKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"The POIs the map style draws.",default:!0},"filters.categories.show":{kind:"enum",description:"`only` draws just the `filters.categories.values` categories, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.categories.values":{kind:"enums",description:"The categories and category groups `filters.categories.show` draws alone or hides; a group stands for each of its categories. Groups come first in the options.",options:[...Object.keys(poiCategoryGroups),...poiCategories]}}))(),poisKnobCatalogue=/* @__PURE__ */withIds(poisKnobDefinitions),poisKnobIds=/* @__PURE__ */poisKnobCatalogue.map(({id:e})=>e),poiLayerIDs=["POI","POI - Micro"],mapDisplayPoiCategoryMappings={ABORIGINAL_LAND:"aboriginal_land",AIRPORT:"airport",AMUSEMENT_PARK:"amusement_park",ATM:"atm",BANK:"bank",BAR:"bar",BEACH:"beach_resort",TRANSPORT_ACCESS:"border_control",BORDER_CONTROL:"border_control",BUS_STOP:"bus_station",CAFE:"cafe",CAFE_PUB:"cafe",CAMPING_GROUND:"camping_ground",CAR_RENTAL:"car_rental",CASINO_AND_GAMBLING:"casino_and_gambling",CEMETERY:"cemetery",CHARGING_LOCATION:"charging_location",CINEMA:"cinema",MOVIE_THEATER:"cinema",HEALTHCARE_SERVICE:"clinic",CLOTHING_SHOP:"clothing_shop",COFFEE_SHOP:"coffee_shop",COLLEGE_OR_UNIVERSITY:"college_or_university",AGRICULTURE:"commercial_area",BUSINESS_PARK:"commercial_area",COMMERCIAL_BUILDING:"commercial_area",COMPANY:"commercial_area",RESIDENTIAL_ACCOMMODATION:"commercial_area",RESIDENTIAL_ENTRANCE:"commercial_area",EXHIBITION_CONVENTION_CENTER:"conference_center",CLUB_AND_ASSOCIATION:"consumer_service",PUBLIC_AMENITY:"consumer_service",PEDESTRIAN_SUBWAY:"consumer_service",WELFARE_ORGANIZATION:"consumer_service",COURTHOUSE:"courthouse",COMMUNITY_CENTER:"cultural_center",CULTURAL_CENTER:"cultural_center",DENTIST:"dentist",DEPARTMENT_STORE:"department_store",DOCTOR:"doctor",EMERGENCY_MEDICAL_SERVICE:"emergency_ward_entrance",EMERGENCY_ROOM:"emergency_ward_entrance",FAST_FOOD:"fast_food",FERRY_TERMINAL:"ferry_terminal",FIRE_STATION:"fire_station",FITNESS_CLUB_AND_CENTER:"fitness_center",WINERY:"food_and_drinks_shop",FOREIGN_EXCHANGE:"foreign_exchange",EXCHANGE:"foreign_exchange",FUEL_STATION:"fuel_station",GOLD_EXCHANGE:"gold_exchange",GOLF_COURSE:"golf_course",EMBASSY:"government_office",GOVERNMENT_OFFICE:"government_office",HELIPORT_OR_HELIPAD:"heliport_or_helipad",HISTORIC_SITE:"historic_site",HOLIDAY_RENTAL:"holiday_home",GENERAL_HOSPITAL_AND_POLYCLINIC:"hospital",HOSPITAL:"hospital",HOTEL_OR_MOTEL:"hotel_or_motel",ICE_RINK:"ice_rink",INDUSTRIAL_BUILDING:"industrial_area",PORT_WAREHOUSE_FACILITY:"industrial_area",PRIMARY_RESOURCE_UTILITY:"industrial_area",NATURAL_FEATURE:"landmark",MALL:"mall",MANUFACTURING_FACILITY:"manufacturing_facility",MARINA:"marina",MARKETPLACE:"marketplace",MEDIA_FACILITY:"media_facility",MOUNTAIN_PASS:"mountain_pass",MUSEUM:"museum",NON_GOVERNMENTAL_ORGANIZATION:"ngo_office",CONCERT_HALL:"nightlife",ENTERTAINMENT:"nightlife",NIGHTLIFE:"nightlife",PARK_AND_RECREATION_AREA:"park_and_recreation_area",TRAIL_SYSTEM:"park_and_recreation_area",LEISURE_CENTER:"park_and_recreation_facility",FLYING_CLUB:"park_and_recreation_facility",WATER_SPORT:"park_and_recreation_facility",PARKING_GARAGE:"parking_facility",PHARMACY:"pharmacy",POLICE_STATION:"police_station",POST_OFFICE:"post_office",PRISON:"prison",PROTECTED_LAND:"protected_land",PUB:"pub",PUBLIC_LIBRARY:"public_library",PUBLIC_TRANSPORT_STOP:"public_transport_stop",RAILWAY_STATION:"railway_station",CHURCH:"religious_site",GURUDWARA:"religious_site",MOSQUE:"religious_site",PAGODA:"religious_site",RELIGIOUS_SITE:"religious_site",SYNAGOG:"religious_site",TEMPLE:"religious_site",RENTAL_CAR_PARKING:"rental_car_parking",RESEARCH_FACILITY:"research_facility",REST_AREA:"rest_and_service_area",RESTAURANT:"restaurant",RESTAURANT_AREA:"restaurant",SCHOOL:"school_or_kindergarten",SHOP_OR_STORE:"shop_or_store",ADVENTURE_SPORTS_FACILITY:"sport_facility",SPORTS_CENTER:"sport_facility",TENNIS_COURT:"sport_facility",STADIUM:"stadium",SUPERMARKET:"supermarket",SWIMMING_POOL:"swimming_pool",TAXI_STAND:"taxi_stand",OPERA_HOUSE:"theater",THEATER:"theater",TOLL_GATE:"toll_plaza",TOURIST_ATTRACTION:"tourist_attraction",TOURIST_INFORMATION:"tourist_information",TRUCK_STOP:"truck_stop",VEHICLE_DEALER:"vehicle_dealer",MOTORING_ORGANIZATION_OFFICE:"vehicle_inspection",TRAFFIC_CONTROL_DEPARTMENT:"vehicle_inspection",TRANSPORT_AUTHORITY_VEHICLE_REGISTRATION:"vehicle_inspection",VEHICLE_REPAIR:"vehicle_repair",CAR_WASH:"vehicle_wash",VETERINARY:"veterinary",HILL:"viewpoint",MOUNTAIN_PEAK:"viewpoint",VIEWPOINT:"viewpoint",WEIGH_STATION:"weighbridge",AQUATIC_ZOO:"zoo_or_aquarium",ARBORETA_AND_BOTANICAL_GARDENS:"zoo_or_aquarium",ZOOS_ARBORETA_BOTANICAL_GARDEN:"zoo_or_aquarium"},completeMapDisplayPoiCategoryMappings={...mapDisplayPoiCategoryMappings,AIRFIELD:"airport",AIRLINE_ACCESS:"airport",PRIVATE_AIRPORT:"airport",PUBLIC_AIRPORT:"airport",ANIMAL_SHELTER:"animal_shelter",DIVERSIFIED_FINANCIALS:"bank",COCKTAIL_BAR:"bar",BEACH_CLUB:"beach_resort",SECURED_ENTRANCE:"border_control",INTERNET_CAFE:"cafe",CAFETERIA:"cafeteria",CARAVAN_SITE:"camping_ground",RECREATIONAL_CAMPING_GROUND:"camping_ground",REST_CAMP:"camping_ground",MAUSOLEUM_OR_GRAVE:"cemetery",CHILDCARE:"childcare",PRE_SCHOOL:"childcare",DRIVE_IN_MOVIES:"cinema",CHILDREN_S_CLOTHES:"clothing_shop",MEN_S_CLOTHING:"clothing_shop",SPECIALTY_CLOTHING_SHOP:"clothing_shop",WOMEN_S_CLOTHING:"clothing_shop",JUNIOR_COLLEGE_OR_COMMUNITY_COLLEGE:"college_or_university",COMEDY_CLUB:"comedy_club",ADVERTISING_COMPANY:"commercial_area",AGRICULTURAL_TECHNOLOGY:"commercial_area",AIRLINE_COMPANY:"commercial_area",APARTMENT_RENTAL:"commercial_area",AUTOMOBILE_COMPANY:"commercial_area",BUILDING:"commercial_area",BUSINESS_SERVICES:"commercial_area",BUS_CHARTER_COMPANY:"commercial_area",CABLE_AND_TELEPHONE_COMPANY:"commercial_area",CLEANING_SERVICES:"commercial_area",COMPUTER_AND_DATA_SERVICES:"commercial_area",CONSTRUCTION_COMPANY:"commercial_area",DELIVERY_SERVICE:"commercial_area",ELECTRONICS_COMPANY:"commercial_area",EQUIPMENT_RENTAL:"commercial_area",FARM:"commercial_area",FLATS_OR_APARTMENT_COMPLEX:"commercial_area",HORTICULTURE:"commercial_area",IMPORT_OR_EXPORT_AND_DISTRIBUTION:"commercial_area",INSURANCE_COMPANY:"commercial_area",INVESTMENT_ADVISOR:"commercial_area",LEGAL_SERVICES:"commercial_area",MINING_COMPANY:"commercial_area",MOVING_AND_STORAGE_COMPANY:"commercial_area",OIL_AND_NATURAL_GAS:"commercial_area",PHARMACEUTICAL_COMPANY:"commercial_area",PRIMARY_PRODUCER:"commercial_area",PUBLISHING_TECHNOLOGIES:"commercial_area",REAL_ESTATE_AGENT:"commercial_area",REAL_ESTATE_COMPANY:"commercial_area",RETIREMENT_COMMUNITY:"commercial_area",SCHOOL_BUS_COMPANY:"commercial_area",SERVICE_COMPANY:"commercial_area",SOFTWARE_COMPANY:"commercial_area",TAX_SERVICES:"commercial_area",TELECOMMUNICATIONS:"commercial_area",TRANSPORT_COMPANY:"commercial_area",TRAVEL_AGENT:"commercial_area",WEDDING_SERVICES:"commercial_area",PUBLIC_CALL_BOX:"consumer_service",PUBLIC_BATHROOM:"consumer_service",GENERAL_PRACTITIONER:"doctor",SPECIALIST:"doctor",AMBULANCE_UNIT:"emergency_ward_entrance",RESCUE_SERVICE:"emergency_ward_entrance",MICROBREWERY:"food_and_drinks_shop",BATTLEFIELD:"historic_site",MEMORIAL:"historic_site",BUNGALOW_RENTAL:"holiday_home",CHALET_RENTAL:"holiday_home",COTTAGE_RENTAL:"holiday_home",VILLA_RENTAL:"holiday_home",HORSE_RIDING:"horse_riding",BLOOD_BANK:"hospital",HOSPITAL_FOR_WOMEN_AND_CHILDREN:"hospital",HOSPITAL_OF_CHINESE_MEDICINE:"hospital",SPECIAL_HOSPITAL:"hospital",BANDB_OR_GUEST_HOUSE:"hotel_or_motel",CABINS_LODGES:"hotel_or_motel",HOSTEL:"hotel_or_motel",HOTEL:"hotel_or_motel",MOTEL:"hotel_or_motel",RESORT:"hotel_or_motel",ICE_CREAM_PARLOR:"ice_cream_shop",ICE_HOCKEY_ARENA:"ice_rink",CHEMICAL_COMPANY:"industrial_area",MECHANICAL_ENGINEERING:"industrial_area",QUARRY:"industrial_area",JUICE_BAR:"juice_bar",ARCH:"landmark",BAY:"landmark",BRIDGE:"landmark",CAPE:"landmark",COVE:"landmark",DAM:"landmark",DUNE:"landmark",ISLAND:"landmark",LOCALE:"landmark",MARSH:"landmark",MONUMENT:"landmark",OASIS:"landmark",OBSERVATORY:"landmark",PARKWAY:"landmark",PLAIN_OR_FLAT:"landmark",PLATEAU:"landmark",PAN:"landmark",RAPIDS:"landmark",REEF:"landmark",RESERVOIR:"landmark",RIVER_CROSSING:"landmark",ROCKS:"landmark",STATUE:"landmark",TOWER:"landmark",TUNNEL:"landmark",VALLEY:"landmark",WATER_HOLE:"landmark",WELL:"landmark",AUTOMOBILE_MANUFACTURING:"manufacturing_facility",MANUFACTURING_COMPANY:"manufacturing_facility",FARMERS_MARKET:"marketplace",FOOD_MARKET:"marketplace",INFORMAL_MARKET:"marketplace",PUBLIC_MARKET:"marketplace",MILITARY_AIRPORT:"military_airfield",FUNERAL_SERVICE_AND_MORTUARIES:"mourning_facility",AMUSEMENT_PLACE:"nightlife",BETTING_STATION:"nightlife",CABARET_THEATER:"nightlife",DISCO_CLUB:"nightlife",FAIRGROUND:"nightlife",JAZZ_CLUB:"nightlife",KARAOKE_CLUB:"nightlife",MUSIC_CENTER:"nightlife",ADVENTURE_VEHICLE_TRAIL:"park_and_recreation_area",FISHING_AND_HUNTING_AREA:"park_and_recreation_area",FOREST_AREA:"park_and_recreation_area",HIKING_TRAIL:"park_and_recreation_area",HISTORICAL_PARK:"park_and_recreation_area",HORSE_RIDING_TRAIL:"park_and_recreation_area",MOUNTAIN_BIKE_TRAIL:"park_and_recreation_area",PARK:"park_and_recreation_area",PICNIC_AREA:"park_and_recreation_area",RECREATION_AREA:"park_and_recreation_area",ROCK_CLIMBING_TRAIL:"park_and_recreation_area",WILDERNESS_AREA:"park_and_recreation_area",OPEN_CAR_PARKING_AREA:"parking_facility",BEAUTY_SALON:"personal_care_service",HAIRDRESSER:"personal_care_service",NAIL_SALON:"personal_care_service",PERSONAL_CARE_FACILITY:"personal_care_service",PERSONAL_SERVICE:"personal_care_service",SAUNA_SOLARIUM_MASSAGE:"personal_care_service",DRUG_STORE:"pharmacy",CANNABIS_SHOP:"pharmacy",MEDICINAL_AND_RECREATIONAL_DISPENSARY:"pharmacy",MEDICINAL_MARIJUANA_DISPENSARY:"pharmacy",RECREATIONAL_MARIJUANA_DISPENSARY:"pharmacy",PLANETARIUM:"planetarium",COURIER_DROP_BOX:"post_depot",BUS_LINES:"public_transport_stop",PASSENGER_TRANSPORT_TICKET_OFFICE:"public_transport_stop",STREETCAR_STOP:"public_transport_stop",SUBWAY_STATION:"public_transport_stop",SUBWAY_ENTRANCE:"public_transport_stop",INTERNATIONAL_RAILROAD_STATION:"railway_station",NATIONAL_RAILROAD_STATION:"railway_station",STATION_ACCESS:"railway_station",URBAN_STATION:"railway_station",AFGHAN_RESTAURANT:"restaurant",AFRICAN_RESTAURANT:"restaurant",AMERICAN_RESTAURANT:"restaurant",ARABIAN_RESTAURANT:"restaurant",ARMENIAN_RESTAURANT:"restaurant",ASIAN_RESTAURANT:"restaurant",AUSTRALIAN_RESTAURANT:"restaurant",AUSTRIAN_RESTAURANT:"restaurant",BANQUET_ROOMS:"restaurant",BARBECUE_RESTAURANT:"restaurant",BASQUE_RESTAURANT:"restaurant",BELGIAN_RESTAURANT:"restaurant",BISTRO:"restaurant",BOLIVIAN_RESTAURANT:"restaurant",BRAZILIAN_RESTAURANT:"restaurant",BRITISH_RESTAURANT:"restaurant",BUFFET_RESTAURANT:"restaurant",BULGARIAN_RESTAURANT:"restaurant",BURMESE_RESTAURANT:"restaurant",CALIFORNIAN_RESTAURANT:"restaurant",CAMBODIAN_RESTAURANT:"restaurant",CANADIAN_RESTAURANT:"restaurant",CARIBBEAN_RESTAURANT:"restaurant",CATERING_SERVICES:"restaurant",CHICKEN_RESTAURANT:"restaurant",CHILEAN_RESTAURANT:"restaurant",CHINESE_RESTAURANT:"restaurant",COLOMBIAN_RESTAURANT:"restaurant",CORSICAN_RESTAURANT:"restaurant",CREOLE_RESTAURANT:"restaurant",CREPERIE:"restaurant",CUBAN_RESTAURANT:"restaurant",CZECH_RESTAURANT:"restaurant",DANISH_RESTAURANT:"restaurant",DINNER_THEATER:"restaurant",DONGBEI_RESTAURANT:"restaurant",DOUGHNUT_RESTAURANT:"restaurant",DUTCH_RESTAURANT:"restaurant",EGYPTIAN_RESTAURANT:"restaurant",ENGLISH_RESTAURANT:"restaurant",ETHIOPIAN_RESTAURANT:"restaurant",FINNISH_RESTAURANT:"restaurant",FONDUE_RESTAURANT:"restaurant",FRENCH_RESTAURANT:"restaurant",FUSION_RESTAURANT:"restaurant",GERMAN_RESTAURANT:"restaurant",GREEK_RESTAURANT:"restaurant",GRILL_RESTAURANT:"restaurant",HAMBURGER_RESTAURANT:"restaurant",HAWAIIAN_RESTAURANT:"restaurant",HOT_POT_RESTAURANT:"restaurant",HUNAN_RESTAURANT:"restaurant",HUNGARIAN_RESTAURANT:"restaurant",INDIAN_RESTAURANT:"restaurant",INDONESIAN_RESTAURANT:"restaurant",INTERNATIONAL_RESTAURANT:"restaurant",IRANIAN_RESTAURANT:"restaurant",IRISH_RESTAURANT:"restaurant",ISRAELI_RESTAURANT:"restaurant",ITALIAN_RESTAURANT:"restaurant",JAMAICAN_RESTAURANT:"restaurant",JAPANESE_RESTAURANT:"restaurant",JEWISH_RESTAURANT:"restaurant",KOREAN_RESTAURANT:"restaurant",KOSHER_RESTAURANT:"restaurant",LATIN_AMERICAN_RESTAURANT:"restaurant",LEBANESE_RESTAURANT:"restaurant",MEDITERRANEAN_RESTAURANT:"restaurant",MEXICAN_RESTAURANT:"restaurant",MIDDLE_EASTERN_RESTAURANT:"restaurant",MONGOLIAN_RESTAURANT:"restaurant",MOROCCAN_RESTAURANT:"restaurant",NEPALESE_RESTAURANT:"restaurant",NORWEGIAN_RESTAURANT:"restaurant",ORGANIC_FOOD_RESTAURANT:"restaurant",ORIENTAL_RESTAURANT:"restaurant",PAKISTANI_RESTAURANT:"restaurant",PERUVIAN_RESTAURANT:"restaurant",PHILIPPINE_RESTAURANT:"restaurant",PIZZERIA:"restaurant",POLISH_RESTAURANT:"restaurant",PORTUGUESE_RESTAURANT:"restaurant",RUSSIAN_RESTAURANT:"restaurant",SALAD_BAR:"restaurant",SANDWICH_RESTAURANT:"restaurant",SCANDINAVIAN_RESTAURANT:"restaurant",SEAFOOD:"restaurant",SHANDONG_RESTAURANT:"restaurant",SICHUAN_RESTAURANT:"restaurant",SNACKS_RESTAURANT:"restaurant",SOUL_FOOD:"restaurant",SOUP_RESTAURANT:"restaurant",SPANISH_RESTAURANT:"restaurant",STEAK_HOUSE:"restaurant",SUSHI_RESTAURANT:"restaurant",SWEDISH_RESTAURANT:"restaurant",SWISS_RESTAURANT:"restaurant",SYRIAN_RESTAURANT:"restaurant",TAIWANESE_RESTAURANT:"restaurant",TAKEOUT_FOOD:"restaurant",TAPAS_RESTAURANT:"restaurant",TEPPANYAKI_RESTAURANT:"restaurant",THAI_RESTAURANT:"restaurant",TIBETAN_RESTAURANT:"restaurant",TUNISIAN_RESTAURANT:"restaurant",TURKISH_RESTAURANT:"restaurant",VEGETARIAN_RESTAURANT:"restaurant",VENEZUELAN_RESTAURANT:"restaurant",VIETNAMESE_RESTAURANT:"restaurant",WESTERN_RESTAURANT:"restaurant",ART_SCHOOL:"school_or_kindergarten",DANCE_STUDIO_AND_SCHOOL:"school_or_kindergarten",DRIVING_SCHOOL:"school_or_kindergarten",HIGH_SCHOOL:"school_or_kindergarten",LANGUAGE_SCHOOL:"school_or_kindergarten",MIDDLE_SCHOOL:"school_or_kindergarten",PRIMARY_SCHOOL:"school_or_kindergarten",SENIOR_HIGH_SCHOOL:"school_or_kindergarten",VOCATIONAL_SCHOOL:"school_or_kindergarten",AGRICULTURAL_SUPPLIES:"shop_or_store",ANTIQUE_ART_SHOP:"shop_or_store",BAGS_LEATHERWEAR:"shop_or_store",BAKERY:"shop_or_store",BEAUTY_SUPPLIES:"shop_or_store",BOATING_EQUIPMENT_AND_ACCESSORIES:"shop_or_store",BOOK_SHOP:"shop_or_store",BUTCHER:"shop_or_store",CAMERAS_AND_PHOTOGRAPHY:"shop_or_store",CARPET_FLOOR_COVERINGS:"shop_or_store",CHRISTMAS_OR_HOLIDAY_SHOP:"shop_or_store",COMPUTER_AND_COMPUTER_SUPPLIES:"shop_or_store",CONSTRUCTION_MATERIAL_AND_EQUIPMENT:"shop_or_store",CONSUMER_ELECTRONICS:"shop_or_store",CONVENIENCE_STORE:"shop_or_store",CURTAINS_TEXTILES:"shop_or_store",C_DS_DVD_VIDEOS:"shop_or_store",DELICATESSEN:"shop_or_store",DO_IT_YOURSELF_CENTERS:"shop_or_store",DRIVE_THROUGH_BOTTLE_SHOP:"shop_or_store",DRY_CLEANER:"shop_or_store",ELECTRICAL_APPLIANCES_SHOP:"shop_or_store",FACTORY_OUTLET:"shop_or_store",FISHMONGER:"shop_or_store",FLORISTS:"shop_or_store",FOOTWEAR_SHOE_REPAIRS:"shop_or_store",FURNITURE_HOME_FURNISHINGS:"shop_or_store",GARDEN_CENTERS_SERVICES:"shop_or_store",GIFTS_CARDS_NOVELTIES_SOUVENIRS:"shop_or_store",GLASSWARE_CERAMIC_SHOP:"shop_or_store",GLASS_WINDOWS_STORE:"shop_or_store",GREENGROCER:"shop_or_store",GROCERY_STORE:"shop_or_store",HARDWARE_STORE:"shop_or_store",HOBBY_SHOP:"shop_or_store",HOUSE_AND_GARDEN_FURNITURE_AND_FITTINGS:"shop_or_store",JEWELRY_CLOCKS_WATCHES:"shop_or_store",KITCHENS_BATHROOMS:"shop_or_store",LAUNDRY:"shop_or_store",LIGHTING_SHOPS:"shop_or_store",LOCAL_SPECIALITIES_SHOP:"shop_or_store",LOTTERY_SHOP:"shop_or_store",MEDICAL_SUPPLIES_EQUIPMENT:"shop_or_store",MOBILE_PHONE_SHOP:"shop_or_store",MUSIC_INSTRUMENTS_STORE:"shop_or_store",NEWSAGENTS_TOBACCONISTS:"shop_or_store",OFFICE_EQUIPMENT:"shop_or_store",OPTICIAN:"shop_or_store",FOOD_AND_DRINKS_SHOP:"shop_or_store",PAINTING_DECORATING:"shop_or_store",PAWN_SHOP:"shop_or_store",PET_SUPPLIES:"shop_or_store",PHOTOCOPY_SHOP:"shop_or_store",PHOTO_LAB_OR_DEVELOPMENT:"shop_or_store",RECYCLING_SHOP:"shop_or_store",RETAIL_OUTLET:"shop_or_store",SECURITY_PRODUCTS:"shop_or_store",SHOPPING_SERVICE:"shop_or_store",SPECIALTY_FOODS:"shop_or_store",SPORTS_EQUIPMENT_AND_CLOTHING:"shop_or_store",TAILOR_SHOP:"shop_or_store",TOYS_GAMES_SHOP:"shop_or_store",VARIETY_STORE:"shop_or_store",VIDEO_RENTAL_SHOP:"shop_or_store",WHOLESALE_CLUB:"shop_or_store",WINE_SPIRITS:"shop_or_store",ATHLETICS_TRACK:"sport_facility",BASEBALL_PARK:"sport_facility",BASKETBALL_ARENA:"sport_facility",BOWLING_CENTER:"sport_facility",CRICKET_GROUND:"sport_facility",HOCKEY_CLUB:"sport_facility",HORSE_RACING_TRACK:"sport_facility",RACE_TRACK:"sport_facility",RUGBY_GROUND:"sport_facility",SQUASH_COURT:"sport_facility",THEMATIC_SPORT_CENTER:"sport_facility",FOOTBALL_STADIUM:"stadium",MOTOR_RACING_STADIUM:"stadium",MULTI_PURPOSE_STADIUM:"stadium",NETBALL_STADIUM:"stadium",SOCCER_STADIUM:"stadium",STOCK_EXCHANGE:"stock_exchange",TAXI_LIMOUSINE_AND_SHUTTLE_SERVICE:"taxi_stand",TEA_HOUSE:"tea_house",AMPHITHEATER:"theater",CAVE:"tourist_attraction",MINERAL_OR_HOT_SPRINGS:"tourist_attraction",NATURAL_TOURIST_ATTRACTION:"tourist_attraction",BOAT_LAUNCHING_RAMP:"transport_access",HARBOR:"transport_access",YACHT_BASIN:"transport_access",ATV_DEALER:"vehicle_dealer",BOAT_DEALER:"vehicle_dealer",BUS_DEALER:"vehicle_dealer",CAR_DEALER:"vehicle_dealer",MOTORCYCLE_DEALER:"vehicle_dealer",RECREATIONAL_VEHICLE_DEALER:"vehicle_dealer",TRUCK_DEALER:"vehicle_dealer",VAN_DEALER:"vehicle_dealer",BODYSHOP:"vehicle_repair",CAR_GLASS_REPLACEMENT_SHOP:"vehicle_repair",CAR_REPAIR_AND_SERVICE:"vehicle_repair",HOME_APPLIANCE_REPAIR:"vehicle_repair",MOTORCYCLE_REPAIR:"vehicle_repair",TIRE_SERVICE:"vehicle_repair",TRUCK_REPAIR_AND_SERVICE:"vehicle_repair",ANIMAL_SERVICE:"veterinary",RIDGE:"viewpoint",SKI_RESORT:"winter_sports",WILDLIFE_PARK:"zoo_or_aquarium",ZOO:"zoo_or_aquarium"},toBaseMapPOICategory=e=>completeMapDisplayPoiCategoryMappings[e],baseMapPOICategoryValues=Array.from(new Set(Object.values(completeMapDisplayPoiCategoryMappings))),baseMapCategoryToGroup={bar:"eat_and_drink",cafe:"eat_and_drink",cafeteria:"eat_and_drink",coffee_shop:"eat_and_drink",fast_food:"eat_and_drink",ice_cream_shop:"eat_and_drink",juice_bar:"eat_and_drink",pub:"eat_and_drink",restaurant:"eat_and_drink",tea_house:"eat_and_drink",clothing_shop:"shopping",department_store:"shopping",food_and_drinks_shop:"shopping",mall:"shopping",marketplace:"shopping",shop_or_store:"shopping",supermarket:"shopping",atm:"finance",bank:"finance",foreign_exchange:"finance",gold_exchange:"finance",stock_exchange:"finance",camping_ground:"lodging",holiday_home:"lodging",hotel_or_motel:"lodging",airport:"transport",bus_station:"transport",ferry_terminal:"transport",heliport_or_helipad:"transport",marina:"transport",public_transport_stop:"transport",railway_station:"transport",taxi_stand:"transport",transport_access:"transport",border_control:"driving",car_rental:"driving",charging_location:"driving",fuel_station:"driving",rest_and_service_area:"driving",toll_plaza:"driving",truck_stop:"driving",vehicle_dealer:"driving",vehicle_inspection:"driving",vehicle_repair:"driving",vehicle_wash:"driving",weighbridge:"driving",parking_facility:"parking",rental_car_parking:"parking",clinic:"healthcare",dentist:"healthcare",doctor:"healthcare",emergency_ward_entrance:"healthcare",hospital:"healthcare",pharmacy:"healthcare",veterinary:"healthcare",childcare:"education",college_or_university:"education",research_facility:"education",school_or_kindergarten:"education",cultural_center:"cultural",historic_site:"cultural",museum:"cultural",planetarium:"cultural",theater:"cultural",amusement_park:"leisure",beach_resort:"leisure",casino_and_gambling:"leisure",cinema:"leisure",comedy_club:"leisure",nightlife:"leisure",park_and_recreation_facility:"leisure",tourist_attraction:"leisure",tourist_information:"leisure",zoo_or_aquarium:"leisure",fitness_center:"sport",golf_course:"sport",horse_riding:"sport",ice_rink:"sport",sport_facility:"sport",stadium:"sport",swimming_pool:"sport",winter_sports:"sport",aboriginal_land:"outdoor",landmark:"outdoor",mountain_pass:"outdoor",park_and_recreation_area:"outdoor",viewpoint:"outdoor",protected_land:"protected",cemetery:"public",courthouse:"public",fire_station:"public",government_office:"public",police_station:"public",post_depot:"public",post_office:"public",prison:"public",public_library:"public",military_airfield:"military",religious_site:"religion",animal_shelter:"business",commercial_area:"business",conference_center:"business",consumer_service:"business",industrial_area:"business",manufacturing_facility:"business",media_facility:"business",mourning_facility:"business",ngo_office:"business",personal_care_service:"business"},toBaseMapPOIGroup=e=>{const t=toBaseMapPOICategory(e);return t?baseMapCategoryToGroup[t]:void 0},TITLE="title",pinIconBaseLayout={"icon-image":["get","iconID"],"icon-anchor":"bottom","icon-size":PIN_ICON_SIZE,"icon-allow-overlap":!0,"icon-padding":0},pinIconBasePaint={"icon-translate":[0,5],"icon-translate-anchor":"viewport"},pinTextBaseLayout={"text-optional":!0,"text-font":["Noto-Bold"],"text-field":["get",TITLE],"text-justify":"auto","text-variable-anchor":["top","left","right"],"text-variable-anchor-offset":["top",[0,.7],"left",[1.4,-1.4],"right",[-1.4,-1.4]],"text-size":DEFAULT_TEXT_SIZE,"text-padding":5},pinTextBasePaint={"text-halo-width":["interpolate",["linear"],["zoom"],6,1,10,1.5],"text-translate-anchor":"viewport"},pinLayerBaseSpec={type:"symbol",layout:{...pinIconBaseLayout,...pinTextBaseLayout},paint:{...pinIconBasePaint,...pinTextBasePaint}},isClusterFilter=["has","point_count"],isNotClusterFilter=["!",isClusterFilter],CLUSTER_PROPERTY_BASE_MAP_ICON_IDS="clusterBaseMapIconIDs",isSingleCategoryClusterFilter=["all",isClusterFilter,["==",["index-of",",",["get","clusterBaseMapIconIDs"]],-1]],isMixedCategoryClusterFilter=["all",isClusterFilter,[">=",["index-of",",",["get","clusterBaseMapIconIDs"]],0]],DEFAULT_SINGLE_BADGE_OFFSET=[12,-14],singleBadgeOffset=e=>e?.offset??DEFAULT_SINGLE_BADGE_OFFSET,badgeCirclePaint=(e,t)=>({"circle-radius":t,"circle-color":e?.color??"#000000","circle-stroke-color":e?.strokeColor??"#FFFFFF","circle-stroke-width":e?.strokeWidth??1.5}),countTextLayout=e=>({"text-field":["get","point_count_abbreviated"],"text-font":["Noto-Bold"],"text-size":e?.textSize??12,"text-allow-overlap":!0,"text-ignore-placement":!0}),clusteredPlacesAggregateProperties={[CLUSTER_PROPERTY_BASE_MAP_ICON_IDS]:(sourceProperty="baseMapIconID",outputProperty="clusterBaseMapIconIDs",[["case",["==",["get",outputProperty],null],["accumulated"],["==",["accumulated"],null],["get",outputProperty],[">=",["index-of",["concat",",",["get",outputProperty],","],["concat",",",["accumulated"],","]],0],["accumulated"],["concat",["accumulated"],",",["get",outputProperty]]],["get",sourceProperty]])},buildKnownBaseMapSpriteImageExpr=e=>{const t=["match",e];for(const i of baseMapPOICategoryValues){const e=`poi-${i}`;t.push(e,["image",e])}return t.push(["image","poi-parking-micro"]),t},isClickEventState=["in",["get","eventState"],["literal",["click","contextmenu"]]],hasActiveEventState=["all",["has","eventState"],["!=",["get","eventState"],"recently-hovered"]],suffixNumber=(e,t)=>`${e}-${t}`,prefixLayerID=(e,t)=>t?`${t}-${e}`:e,mergeLayer=(e,t)=>t?{...e,...t,...t.paint&&{paint:{...e.paint,...t.paint}},...t.layout&&{layout:{...e.layout,...t.layout}}}:e,themeAdaptiveLabelColors=e=>({textColor:"dark"===e?"#FFFFFF":"#333333",haloColor:"dark"===e?"#333333":"#FFFFFF"}),themeAdaptiveLabelShadeOf=(e,t)=>("dark"===t?lighterShadeOf(e):darkerShadeOf(e))??e,labelLayoutProperties=e=>({...void 0!==e?.size&&{"text-size":e.size},...void 0!==e?.font&&{"text-font":e.font}}),labelPaintProperties=e=>({...void 0!==e?.color&&{"text-color":e.color},...void 0!==e?.haloColor&&{"text-halo-color":e.haloColor},...void 0!==e?.haloWidth&&{"text-halo-width":e.haloWidth},...void 0!==e?.opacity&&{"text-opacity":e.opacity}}),getThemeAdaptiveConnectionColors=(e,t)=>{const i="dark"===e,r=themeAdaptiveLabelColors(e).haloColor;return t?{lineColor:t,labelColor:themeAdaptiveLabelShadeOf(t,e),labelHaloColor:r}:{lineColor:i?"#5AB6F0":"#3f9cd9",labelColor:i?"#A9D6F5":"#1a5f8a",labelHaloColor:r}},buildBaseLineSpec$1=e=>({type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":e,"line-width":1.5,"line-dasharray":[2,2],"line-opacity":.9}}),buildBaseLabelSpec=(e,t)=>({type:"symbol",layout:{"symbol-placement":"line-center","text-field":["get","label"],"text-font":["Noto-Regular"],"text-size":12,"text-offset":[0,-1],"text-allow-overlap":!1,"text-ignore-placement":!1,"text-keep-upright":!0},paint:{"text-color":e,"text-halo-color":t,"text-halo-width":1.5}}),isMainEntryPoint=["==",["get","type"],"main"],buildBaseLineSpec=(e,t)=>({type:"line",minzoom:t,filter:["==",["geometry-type"],"LineString"],layout:{"line-cap":"round"},paint:{"line-color":e,"line-width":1.5,"line-dasharray":[1,2],"line-opacity":.8}}),buildBasePointSpec=(e,t,i)=>({type:"circle",minzoom:i,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":e,"circle-radius":["+",["case",isMainEntryPoint,5,3.5],["case",hasActiveEventState,1.5,0]],"circle-stroke-width":1.5,"circle-stroke-color":t}}),buildEntryPointLayerSpecs=(e,t="light",i=0,r)=>{const{color:o,strokeColor:s}=((e,t)=>{const{lineColor:i,labelColor:r,labelHaloColor:o}=getThemeAdaptiveConnectionColors(e,t);return{color:"dark"===e?i:r,strokeColor:o}})(t,r),a=Math.max(e?.minZoom??15,i);return{line:mergeLayer(buildBaseLineSpec(o,a),e?.layers?.line),point:mergeLayer(buildBasePointSpec(o,s,a),e?.layers?.point)}},placesMarkerTypes=["pin","circle-icon","base-map","pin-clustered"],hasChargingAvailability=e=>Boolean(e&&"availability"in e&&e.availability),isEVStationWithAvailability=e=>"CHARGING_LOCATION"===e.properties.poi?.categories?.[0]&&hasChargingAvailability(e.properties.chargingPark),getChargingPointAvailability=e=>{const t=e.properties.chargingPark;if(hasChargingAvailability(t)){const e=t.availability.chargingPointAvailability,i=e.statusCounts.Available??0;return{availableCount:i,totalCount:e.count,ratio:i/e.count}}},defaultFormatAvailabilityText=(e,t)=>`${e}/${t}`,getAvailabilityRatio=e=>getChargingPointAvailability(e)?.ratio??0,getAvailabilityColorExpression=e=>["case",[">=",["get","evAvailabilityRatio"],e?.threshold??.3],"green","red"],toEntryPointID=(e,t)=>`${e}-entry-point-${t}`,isShownFor=(e,t)=>"all"===e||("selected"===e?void 0!==t:isClickEventType(t)),TEXT_SIZE_RANGE={min:8,max:32,step:1,bounds:"hard-min"},STROKE_WIDTH_RANGE={min:0,max:5,step:.5,bounds:"hard-min"},BADGE_RADIUS_RANGE={min:4,max:32,step:1,bounds:"hard-min"},placesKnobDefinitions={markerType:{kind:"enum",description:"The kind of marker every place is drawn with; `icon.categoryIcons` replace its icon under each.",options:placesMarkerTypes,default:"pin"},color:{kind:"color",description:"Colour of the default pin, the hovered or clicked label, connection lines and entry points. Unset: the map's accent if a theme sets one, else the SDK's own colours."},visible:{kind:"toggle",description:"Everything the module draws: places, connections and entry points. `show()` and `clear()` leave it.",default:!0},"icon.default.style.fillColor":{kind:"color",description:"Fill colour of the default pin, in place of `color`."},"icon.default.style.outlineColor":{kind:"color",description:"Outline colour of the default pin."},"icon.default.style.outlineOpacity":{kind:"number",description:"Outline opacity of the default pin.",range:OPACITY_RANGE},"label.size":{kind:"number",description:"Label size, in pixels. Unset: 14 to 16 as the zoom grows, or the style's POI labels under `base-map`.",range:TEXT_SIZE_RANGE},"label.color":{kind:"color",description:"Label colour. Unset: `#333333`, `#FFFFFF` on a dark map, or the style's POI labels under `base-map`."},"label.haloColor":{kind:"color",description:"Colour of the halo around the labels. Unset: `#FFFFFF`, `#333333` on a dark map."},"label.haloWidth":{kind:"number",description:"Width of the label halo, in pixels. Unset: 1 to 1.5 as the zoom grows.",range:STROKE_WIDTH_RANGE},"label.opacity":{kind:"number",description:"Label opacity.",range:OPACITY_RANGE},"label.offset":{kind:"number",description:"Distance of the label from its icon, in ems. Unset: worked out from the icon's size.",range:{min:0,max:5,step:.1,bounds:"hard-min"}},"label.font":{kind:"enums",description:"Label font faces, in order: the first one available wins. Unset: `Noto-Bold`, or the style's POI labels under `base-map`.",options:mapFonts},"cluster.badge.color":{kind:"color",description:"Fill colour of the cluster count badges; `color` does not reach them.",default:"#000000"},"cluster.badge.strokeColor":{kind:"color",description:"Outline colour of the cluster count badges.",default:"#FFFFFF"},"cluster.badge.strokeWidth":{kind:"number",description:"Outline width of the cluster count badges, in pixels.",range:STROKE_WIDTH_RANGE,default:1.5},"cluster.badge.textColor":{kind:"color",description:"Colour of the count on the cluster badges.",default:"#FFFFFF"},"cluster.badge.textSize":{kind:"number",description:"Size of the count on the cluster badges, in pixels.",range:TEXT_SIZE_RANGE,default:12},"cluster.badge.radius.single":{kind:"number",description:"Radius of the badge in a single-category cluster's corner, in pixels.",range:BADGE_RADIUS_RANGE,default:11},"cluster.badge.radius.mixed":{kind:"number",description:"Radius of the centred badge a mixed-category cluster is drawn as, in pixels.",range:BADGE_RADIUS_RANGE,default:15},"cluster.badge.offset":{kind:"offset",description:"Shift of a single-category cluster's badge from its icon, in pixels; mixed-category badges stay centred.",range:{min:-32,max:32,step:1,bounds:"soft"},default:DEFAULT_SINGLE_BADGE_OFFSET},"cluster.source.clusterRadius":{kind:"number",description:"How near places merge into one cluster, in pixels. Changing it recreates the places source.",range:{min:10,max:200,step:10,bounds:"hard-min"},default:60},"cluster.source.clusterMaxZoom":{kind:"number",description:"Last zoom places cluster at; entry points start one zoom above it.",range:{min:0,max:17,step:1,bounds:"hard"},default:17},"cluster.source.clusterMinPoints":{kind:"number",description:"Fewest places a cluster holds. Unset: MapLibre's, 2.",range:{min:2,max:20,step:1,bounds:"hard-min"}},"evAvailability.enabled":{kind:"toggle",description:"Free and total charging points under each EV station's name, from `getPlacesWithEVAvailability` data.",default:!1},"evAvailability.threshold":{kind:"number",description:"Share of free charging points at or above which a station reads as available.",range:{min:0,max:1,step:.05,bounds:"hard"},default:.3},"entryPoints.showFor":{kind:"enum",description:"Which places have their entry points drawn: all, the hovered or clicked, or the clicked.",options:/* @__PURE__ */everyOf()(["all","selected","clicked"]),default:"selected"},"entryPoints.minZoom":{kind:"number",description:"Lowest zoom entry points are drawn at; under `pin-clustered`, never below the first without clusters.",range:ZOOM_RANGE,default:15},"connections.color":{kind:"color",description:"Colour of the connection lines, over `color`. Unset: `color`, else the map's accent, else a blue that follows the light/dark theme."},"connections.textColor":{kind:"color",description:"Colour of the connection labels. Unset: a darker shade of the line colour on a light map, a lighter one on a dark map."},"connections.haloColor":{kind:"color",description:"Colour of the halo around the connection labels. Unset: `#FFFFFF`, `#333333` on a dark map."}},placesKnobCatalogue=/* @__PURE__ */withIds(placesKnobDefinitions),placesKnobIds=/* @__PURE__ */placesKnobCatalogue.map(({id:e})=>e),mapAccentColor=e=>e.mapColors.accent,onMapColorsChange=(e,t,i)=>{let r=pick(e.mapColors,t);e._onMapColorsChange(e=>{const o=pick(e,t);isEqual(o,r)||(r=o,i())})},onAccentColorChange=(e,t)=>onMapColorsChange(e,["accent"],t),beforeLayerTargetOf=(e,t)=>"string"==typeof e?e:e?.[t]??e?.all,beforeLayerIDOf=(e,t)=>"top"===e?t:mapStyleLayerIDs[e],partBeforeLayerIDOf=(e,t,i,r)=>{const o=beforeLayerTargetOf(e,t);return void 0===o?i:r(beforeLayerIDOf(o))},incidentColorKnobIds={minor:"traffic.incidents.minorColor",moderate:"traffic.incidents.moderateColor",major:"traffic.incidents.majorColor",indefinite:"traffic.incidents.closedColor"},onStylingKnobsApplied=(e,t,i)=>{e._onStylingApplied(r=>{e.mapReady&&t.some(e=>r.has(e))&&i()})},calculateIconScale=(e,t)=>{if(!e)return;const i=(e=>{try{if("string"==typeof e){if(e.includes("<svg")){const t=parseSvg(e),i=t.getAttribute("viewBox");if(i){const e=i.split(/\s+/);if(4===e.length)return{width:Number.parseFloat(e[2]),height:Number.parseFloat(e[3])}}const r=t.getAttribute("width"),o=t.getAttribute("height");if(r&&o)return{width:Number.parseFloat(r),height:Number.parseFloat(o)}}return null}return e.complete&&e.naturalWidth>0?{width:e.naturalWidth,height:e.naturalHeight}:null}catch(t){return console.warn("Failed to extract image dimensions:",t),null}})(e);if(!i)return;const r="base-map"===t||"circle-icon"===t,o=r?54:140,s=r?54:120;return{heightScale:i.height/o,widthScale:i.width/s}},buildIconOffsetExpression=e=>{const t=["case"];for(const[i,r]of e)0===r.x&&0===r.y||t.push(["==",["get","iconID"],i],["literal",[r.x,r.y]]);if(1!==t.length)return t.push(["literal",[0,0]]),t},round4=e=>Math.round(1e4*e)/1e4,buildAnchorOffsets=(e,t,i,r)=>{const o=void 0!==r;return{top:o?[0,r]:[0,round4(e)],left:o?[r,round4(i)]:[round4(t),round4(i)],right:o?[-r,round4(i)]:[-round4(t),round4(i)]}},getTextOffset=(e,t,i,r)=>{const o=(e=>{if(!e)return.8;if("number"==typeof e)return e;if(Array.isArray(e)){const t=e.at(-1);if("number"==typeof t)return t}if("object"==typeof e&&"stops"in e){const t=e.stops;if(Array.isArray(t)&&t.length>0){const e=t.at(-1);if(Array.isArray(e)&&"number"==typeof e[1])return e[1]}}return.8})(e)/.8,s="base-map"===i||"circle-icon"===i;if(s&&void 0!==r)return{"text-offset":[r,r]};const a=1.4*o,n=buildAnchorOffsets(.7*o,a,s?0:-a,r),l=["top",n.top,"left",n.left,"right",n.right];if(0===t.size)return{"text-variable-anchor-offset":l};const c=["case"];for(const[d,u]of t.entries()){const e=(s?1.4:.7)*u.heightScale*o,t=1.4*u.widthScale*o,i=buildAnchorOffsets(e,t,s?0:-t,r);c.push(["==",["get","iconID"],d],["literal",["top",i.top,"left",i.left,"right",i.right]])}return c.push(["literal",l]),{"text-variable-anchor-offset":c}},buildLayoutConfig=(e,t,i,r,o)=>{const s=t?.label,a=t?.layers?.[i],n=o&&o.size>0,l={...e.layout},c=n||void 0!==s?.offset||"circle-icon"===t?.markerType;c&&(delete l["text-offset"],delete l["text-variable-anchor-offset"],delete l["text-radial-offset"]);const d={...l,...labelLayoutProperties(s),...void 0!==r&&{"text-field":r},...a?.layout};if(c){const e={...d,...getTextOffset(d["icon-size"],o??/* @__PURE__ */new Map,t?.markerType,s?.offset)},r="micro"!==i&&o&&buildIconOffsetExpression([...o].map(([e,{offset:t}])=>[e,t]));return r?{...e,"icon-offset":r}:e}return d},buildPaintConfig=(e,t,i,r)=>{const o=t?.layers?.[i],{textColor:s,haloColor:a}=themeAdaptiveLabelColors(r),n=e.paint??{};return{...n,...void 0===n["text-color"]&&{"text-color":s},...void 0===n["text-halo-color"]&&{"text-halo-color":a},...labelPaintProperties(t?.label),...o?.paint}},poiLookKnobIds=["labels.sizeFactor","symbols.sizeFactor","pois.sizeFactor","pois.labelColor","pois.labelOutlineColor"],getTextSizeSpec=e=>JSON.parse(JSON.stringify(e)?.replaceAll("name",TITLE)),findStyleLayer=(e,t)=>e.getStyle().layers.find(e=>e.id===t)??{},buildBaseMapPOILayerFoundation=e=>({filter:["!",isClickEventState],type:"symbol",paint:e.paint,layout:e.layout?omit(e.layout,"visibility"):void 0}),buildBaseMapPOILayerSpec=e=>{const t=buildBaseMapPOILayerFoundation(findStyleLayer(e,"POI")),i=t.layout?.["text-size"];return{...t,layout:{...t.layout,"icon-image":["get","iconID"],"text-field":["get",TITLE],...i&&{"text-size":getTextSizeSpec(i)}}}},buildPOIMicroLikeLayerSpec=e=>{const t=buildBaseMapPOILayerFoundation(findStyleLayer(e,"POI - Micro"));return{...t,minzoom:0,layout:{...t.layout,"icon-allow-overlap":!0,"icon-ignore-placement":!0},paint:{...t.paint,"icon-opacity":1}}},buildCircleBaseLayerSpec=e=>{const t=findStyleLayer(e,"POI").layout??{};return{...pinLayerBaseSpec,layout:{...pinLayerBaseSpec.layout,"icon-anchor":"center",...void 0!==t["icon-size"]&&{"icon-size":t["icon-size"]},...void 0!==t["icon-padding"]&&{"icon-padding":t["icon-padding"]}},paint:{...pinLayerBaseSpec.paint,"icon-translate":[0,0]}}},HIDDEN_LAYER_SPEC={type:"symbol",layout:{visibility:"none"}},HIDDEN_CIRCLE_LAYER_SPEC={type:"circle",layout:{visibility:"none"}},poiLookMarkerTypes=/* @__PURE__ */new Set(["base-map","circle-icon","pin-clustered"]),pinLayerSpec={...pinLayerBaseSpec,filter:["!",hasActiveEventState]},selectedPinLayerSpec=(e="#3f9cd9")=>({...pinLayerBaseSpec,filter:hasActiveEventState,layout:{...pinLayerBaseSpec.layout,"icon-size":SELECTED_PIN_ICON_SIZE,"text-allow-overlap":!0},paint:{...pinLayerBaseSpec.paint,"text-color":e}}),toSelectedPOILikeSpec=(e,t)=>({...e,filter:hasActiveEventState,layout:{...e.layout,"text-allow-overlap":!0},paint:{...e.paint,"text-color":t}}),withConfig=(e,t,i,r,o)=>{const s=t?.label,a=t?.layers?.[i],n=!0===t?.evAvailability?.enabled,l=s?.title&&"function"!=typeof s?.title?s.title:n?((e,t)=>t?["case",["has","evAvailabilityText"],["format",["get",TITLE],{},"\n",{},["get","evAvailabilityText"],{"font-scale":1.1,"text-color":getAvailabilityColorExpression(e?.evAvailability)}],["get",TITLE]]:["get",TITLE])(t,n):void 0;return{...e,...a,layout:buildLayoutConfig(e,t,i,l,o),paint:buildPaintConfig(e,t,i,r)}},buildPlacesLayerSpecs=(e,t,i,r,o="#3f9cd9")=>{const s=((e,t)=>{const i=/* @__PURE__ */new Map,r=e?.icon?.categoryIcons??[];for(const o of r)if(o.image){const r=calculateIconScale(o.image,e?.markerType),s=void 0!==o.offsetX||void 0!==o.offsetY;if(void 0===r&&!s)continue;const a={heightScale:r?.heightScale??1,widthScale:r?.widthScale??1,offset:{x:o.offsetX??0,y:o.offsetY??0}},n=suffixNumber(o.id,t);if(i.set(n,a),o.availabilityLevel){const e=suffixNumber(`${o.id}-${o.availabilityLevel}`,t);i.set(e,a)}}return i})(e,r);let a,n,l=HIDDEN_LAYER_SPEC,c=HIDDEN_LAYER_SPEC,d=HIDDEN_CIRCLE_LAYER_SPEC,u=HIDDEN_LAYER_SPEC,p=HIDDEN_CIRCLE_LAYER_SPEC,h=HIDDEN_LAYER_SPEC;if("base-map"===e?.markerType)a={...buildBaseMapPOILayerSpec(t),minzoom:10},l=buildPOIMicroLikeLayerSpec(t),n=((e,t)=>toSelectedPOILikeSpec(buildBaseMapPOILayerSpec(e),t))(t,o);else if("circle-icon"===e?.markerType)a=(e=>({...buildCircleBaseLayerSpec(e),filter:["!",hasActiveEventState]}))(t),n=((e,t)=>toSelectedPOILikeSpec(buildCircleBaseLayerSpec(e),t))(t,o);else if("pin-clustered"===e?.markerType){a={...pinLayerSpec,filter:["all",isNotClusterFilter,["!",hasActiveEventState]]},n={...selectedPinLayerSpec(o),filter:["all",isNotClusterFilter,hasActiveEventState]};const i=buildPOIMicroLikeLayerSpec(t);l={...i,filter:i.filter?["all",isNotClusterFilter,i.filter]:isNotClusterFilter};const r=e?.cluster?.badge;c={type:"symbol",filter:isSingleCategoryClusterFilter,layout:{"icon-image":buildKnownBaseMapSpriteImageExpr(["get","clusterBaseMapIconIDs"]),"icon-size":1,"icon-allow-overlap":!0,"icon-ignore-placement":!0}},d=(e=>({type:"circle",filter:isSingleCategoryClusterFilter,paint:{...badgeCirclePaint(e,e?.radius?.single??11),"circle-translate":singleBadgeOffset(e),"circle-translate-anchor":"viewport"}}))(r),u=(e=>({type:"symbol",filter:isSingleCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":e?.textColor??"#FFFFFF","text-translate":singleBadgeOffset(e),"text-translate-anchor":"viewport"}}))(r),p=(e=>({type:"circle",filter:isMixedCategoryClusterFilter,paint:badgeCirclePaint(e,e?.radius?.mixed??15)}))(r),h=(e=>({type:"symbol",filter:isMixedCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":e?.textColor??"#FFFFFF"}}))(r)}else a=pinLayerSpec,n=selectedPinLayerSpec(o);const{microBeforeID:y,partAnchor:f}=((e,t)=>{const i=partBeforeLayerIDOf(e?.beforeLayerConfig,"places",void 0,e=>existingBeforeLayerID(t,e));return{microBeforeID:void 0===beforeLayerTargetOf(e?.beforeLayerConfig,"places")?mapStyleLayerIDs.lowestPlaceLabel:"main",partAnchor:i?{beforeID:i}:{}}})(e,t);return{micro:{...withConfig(l,e,"micro",i,s),beforeID:y},main:{...withConfig(a,e,"main",i,s),beforeID:"selected"},selected:{...withConfig(n,e,"selected",i,s),...f},cluster:{...mergeLayer(c,e?.layers?.cluster),beforeID:"clusterBadge"},clusterBadge:{...mergeLayer(d,e?.layers?.clusterBadge),beforeID:"clusterCount"},clusterCount:{...mergeLayer(u,e?.layers?.clusterCount),beforeID:"clusterMixedBadge"},clusterMixedBadge:{...mergeLayer(p,e?.layers?.clusterMixedBadge),beforeID:"clusterMixedCount"},clusterMixedCount:{...mergeLayer(h,e?.layers?.clusterMixedCount),...f},...e?.layers?.additional}},resolveEndpoint=(e,t)=>"string"!=typeof e?e:t.features.find(t=>t.id===e),supportedPinSubcategories=/* @__PURE__ */new Set([7339002,8099002,7369004,7321003,7376006,9362003,9362004,9160004,9376007,7315015,9376006,9376002,7315078,7315149,9376005,7372003,9352045,9352032,9361048,9902003,9378005,7383004,9910004,7320002,9362016,7320003,9362025,9942002,9942003,7380005,9663003,9361021,9379009,9379004,7315147,9376003,9160002,9160003,9352008,9361006,7389004,9910006]),pinImageSubstitutes=new Map([["ADVENTURE_SPORTS_FACILITY","SPORTS_CENTER"],["COMMUNITY_CENTER","CULTURAL_CENTER"],["EMBASSY","GOVERNMENT_OFFICE"],["EMERGENCY_MEDICAL_SERVICE","EMERGENCY_ROOM"],["ENTERTAINMENT","NIGHTLIFE"],["RESIDENTIAL_ENTRANCE","RESIDENTIAL_ACCOMMODATION"]].map(([e,t])=>[poiCategoriesToID[e],poiCategoriesToID[t]])),buildPlaceTitle=e=>e.properties.poi?.name??e.properties.address.freeformAddress,toImageID=(e,t,i)=>{if("pin"===t||"pin-clustered"===t)return(e=>{if(!e)return;const t=supportedPinSubcategories.has(e)?e:Number(e.toString().substring(0,4));return toPinSpriteImageID(String(pinImageSubstitutes.get(t)??t))})(poiCategoriesToID[e])??i;{const t=toBaseMapPOICategory(e);return t?`poi-${t}`:i}},getIconIDForPlace=(e,t,i={})=>{const r=i.markerType??"pin",o=((e,t)=>e.icon?.default||"base-map"!==(e.markerType??"pin")?suffixNumber("default_place",t):"poi-parking-micro")(i,t),s=i.icon?.mapping;if(s)return"imageID"===s.to?s.fn(e):toImageID(s.fn(e),r,o);const a=e.properties.poi?.categories?.[0],n=((e,t,i,r,o)=>{if(!r.evAvailability?.enabled||!isEVStationWithAvailability(e))return;const s=getAvailabilityRatio(e)>=(r.evAvailability.threshold??.3)?"available":"occupied",a=r.icon?.categoryIcons&&r.icon.categoryIcons.length>0,n=r.icon?.categoryIcons?.find(e=>e.id===t&&e.availabilityLevel===s);return n?suffixNumber(`${n.id}-${s}`,i):a||"pin"!==o?void 0:toPinSpriteImageID(`7309-${s}`)})(e,a,t,i,r);if(n)return n;const l=i.icon?.categoryIcons?.find(e=>e.id===a);return l?suffixNumber(l.id,t):toImageID(a,r,o)},getEffectivePOICategory=(e,t)=>{const i=t?.icon?.mapping;return"poiCategory"===i?.to?i.fn(e):e.properties.poi?.categories?.[0]},getPOILayerCategoryForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&toBaseMapPOICategory(i)},getPOIGroupForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&toBaseMapPOIGroup(i)},toPlaces=e=>Array.isArray(e)?{type:"FeatureCollection",features:e}:"Feature"===e.type?{type:"FeatureCollection",features:[e]}:e,mergeEVAvailabilityProps=(e,t,i)=>{if(!0!==t?.enabled)return e;let r=!1,o=!1;for(const s of i.features)if("CHARGING_LOCATION"===s.properties.poi?.categories?.[0]&&(r=!0,isEVStationWithAvailability(s))){o=!0;break}return r&&!o&&console.warn("PlacesModule: evAvailability is enabled but no availability data found. Did you call getPlacesWithEVAvailability()?"),{...e,evAvailabilityText:e=>isEVStationWithAvailability(e)?((e,t)=>{const i=getChargingPointAvailability(e);return i?(t?.formatText??defaultFormatAvailabilityText)(i.availableCount,i.totalCount):""})(e,t):"",evAvailabilityRatio:e=>isEVStationWithAvailability(e)?getAvailabilityRatio(e):0}},getBaseMapIconIDForPlace=(e,t)=>{const i=getPOILayerCategoryForPlace(e,t);return i?`poi-${i}`:"poi-parking-micro"},preparePlacesForInstance=(e,t,i={})=>{const r=toPlaces(e),o=!0===i.evAvailability?.enabled?mergeEVAvailabilityProps(i.extraFeatureProps,i.evAvailability,r):i.extraFeatureProps;return{...r,features:r.features.map(e=>{const r="function"==typeof i?.label?.title?i?.label?.title(e):buildPlaceTitle(e),s=o?Object.fromEntries(Object.entries(o).map(([t,i])=>[t,"function"==typeof i?i(e):i])):{},a=e.id??generateId();return{...e,id:a,geometry:{...e.geometry,bbox:e.bbox},properties:{...e.properties,id:a,title:r,iconID:getIconIDForPlace(e,t,i),...("base-map"===i?.markerType||"pin-clustered"===i?.markerType)&&{category:getPOILayerCategoryForPlace(e,i),group:getPOIGroupForPlace(e,i)},..."pin-clustered"===i?.markerType&&{baseMapIconID:getBaseMapIconIDForPlace(e,i)},...s}}})}},preparePlacesForDisplay=(e,t={})=>preparePlacesForInstance(e,0,t),placeSources=["places","placesUnclustered"],PlacesModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t),this.refreshingEntryPoints=!1,this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&this.updateLayersAndData(this.config)}),onStylingKnobsApplied(e,poiLookKnobIds,()=>{this.config?.markerType&&poiLookMarkerTypes.has(this.config.markerType)&&this.updatePlacesLayers(this.config)})}colorOf(e){return e?.color??mapAccentColor(this.tomtomMap)}_initSourcesWithLayers(e,t){t||(this.sourceID=`places-${this.instanceIndex}`,this.unclusteredSourceID=`places-${this.instanceIndex}-unclustered`,this.connectionSourceID=`places-connections-${this.instanceIndex}`,this.entryPointSourceID=`places-entry-points-${this.instanceIndex}`,this.layerIDPrefix=this.sourceID,this.defaultPlaceIconID=suffixNumber("default_place",this.instanceIndex),this.shownConnections=[]),this.layerSpecs=this.buildLayerSpecs(e);const i=this.buildClusterOptions(e);this.currentClusterOptions=i;const r=this.partitionSpecsForSources(this.layerSpecs),o=new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,r.clusteredSpecs,!1,i);let s;r.unclusteredSpecs.length>0&&(s=new GeoJSONSourceWithLayers(this.mapLibreMap,this.unclusteredSourceID,r.unclusteredSpecs,!1)),this.connectionLayerSpecs=this.buildConnectionLayerSpecs(e);const a=this.addOverlaySource(this.connectionSourceID,this.connectionLayerSpecs);addLayers([...o._layerSpecs,...s?._layerSpecs??[]],this.mapLibreMap),this.entryPointLayerSpecs=this.buildEntryPointLayerSpecs(e);const n=this.addOverlaySource(this.entryPointSourceID,this.entryPointLayerSpecs),l=()=>{(this.config?.entryPoints||n.shownFeatures.features.length)&&this.updateEntryPointsData(this.config)};return o.onShow(l),n.onShow(l),s?{places:o,placesUnclustered:s,connections:a,entryPoints:n}:{places:o,connections:a,entryPoints:n}}addOverlaySource(e,t){const i=new GeoJSONSourceWithLayers(this.mapLibreMap,e,Object.values(t),!1);return addLayers(i._layerSpecs,this.mapLibreMap),i}replaceLayerSpecs(e,t,i){return updateLayersAndSource(Object.values(e),Object.values(t),i,this.mapLibreMap),e}partitionSpecsForSources(e){if(!this.currentClusterOptions)return{clusteredSpecs:Object.values(e),unclusteredSpecs:[]};const t=[],i=[];for(const[r,o]of Object.entries(e))"micro"===r?t.push(o):i.push(o);return{clusteredSpecs:i,unclusteredSpecs:t}}buildLayerSpecs(e){const t=buildPlacesLayerSpecs(e,this.tomtomMap.mapLibreMap,this.tomtomMap.styleLightDarkTheme,this.instanceIndex,this.colorOf(e)),i=new Set(Object.keys(t));return Object.fromEntries(Object.entries(t).map(([e,t])=>{const r=t.beforeID;return[e,{...t,id:`${this.layerIDPrefix}-${e}`,...r&&i.has(r)?{beforeID:`${this.layerIDPrefix}-${r}`}:{}}]}))}buildClusterOptions(e){if("pin-clustered"!==e?.markerType)return;const t=e.cluster?.source;return{clusterRadius:60,clusterMaxZoom:17,...t,cluster:!0,clusterProperties:{...t?.clusterProperties,...clusteredPlacesAggregateProperties}}}buildConnectionLayerSpecs(e){const t=((e,t,i="light")=>{const{lineColor:r,labelColor:o,labelHaloColor:s}=getThemeAdaptiveConnectionColors(i,e?.color??t);return{line:mergeLayer(buildBaseLineSpec$1(r),e?.layers?.line),label:mergeLayer(buildBaseLabelSpec(e?.textColor??o,e?.haloColor??s),e?.layers?.label)}})(e?.connections,this.colorOf(e),this.tomtomMap.styleLightDarkTheme),i=`${this.layerIDPrefix}-connection-line`,r=`${this.layerIDPrefix}-connection-label`,o=partBeforeLayerIDOf(e?.beforeLayerConfig,"connections",mapStyleLayerIDs.lowestLabel,e=>existingBeforeLayerID(this.mapLibreMap,e));return{line:{...t.line,id:i,beforeID:o},label:{...t.label,id:r,beforeID:o}}}buildEntryPointLayerSpecs(e){const t=this.buildClusterOptions(e),i=t?(t.clusterMaxZoom??17)+1:0,r=buildEntryPointLayerSpecs(e?.entryPoints,this.tomtomMap.styleLightDarkTheme,i,this.colorOf(e));return{line:{...r.line,id:`${this.layerIDPrefix}-entry-point-line`,beforeID:this.layerSpecs.main.id},point:{...r.point,id:`${this.layerIDPrefix}-entry-point`,beforeID:this.layerSpecs.cluster.id}}}_applyConfig(e){return this.updateLayersAndData(e),e}discardShownData(){this.shownConnections=[]}restoreDataAndConfigImpl(){const e=this.sourcesWithLayers.places.shownFeatures,t=this.shownConnections;this.initSourcesWithLayers(this.config,!0),this.config&&this._applyConfig(this.config),this.show(e),t.length&&this.showConnections(t)}applyConfig(e){super.applyConfig(e)}updateConfig(e){super.updateConfig(e)}applyVisibility(e){this.applyPlacesVisibility(e),this.applyVisibilityTo(Object.values(this.connectionLayerSpecs),!!this.sourcesWithLayers.connections.shownFeatures.features.length,e),this.applyVisibilityTo(Object.values(this.entryPointLayerSpecs),!!this.sourcesWithLayers.entryPoints.shownFeatures.features.length,e)}updateLayersAndData(e){this.setupImages(e),isEqual(this.buildClusterOptions(e),this.currentClusterOptions)?(this.updatePlacesLayers(e),this.applyPlacesVisibility(e),this.updateData(e),this.connectionLayerSpecs=this.replaceLayerSpecs(this.buildConnectionLayerSpecs(e),this.connectionLayerSpecs,this.sourcesWithLayers.connections),this.updateConnectionsData(e),this.entryPointLayerSpecs=this.replaceLayerSpecs(this.buildEntryPointLayerSpecs(e),this.entryPointLayerSpecs,this.sourcesWithLayers.entryPoints),this.updateEntryPointsData(e),this._initializing||isEqual(this.config?.beforeLayerConfig,e?.beforeLayerConfig)||this.restackLayers()):this.rebuildSourcesAndLayers(e)}restackLayers(){const{connections:e,places:t,placesUnclustered:i,entryPoints:r}=this.sourcesWithLayers;addLayers([e,t,i,r].flatMap(e=>e?._layerSpecs??[]),this.mapLibreMap,!0)}updatePlacesLayers(e){const t=this.buildLayerSpecs(e),i=this.currentClusterOptions?this.partitionSpecsForSources(t):{clusteredSpecs:Object.values(t),unclusteredSpecs:[]},r=this.currentClusterOptions?this.partitionSpecsForSources(this.layerSpecs):{clusteredSpecs:Object.values(this.layerSpecs),unclusteredSpecs:[]};updateLayersAndSource(i.clusteredSpecs,r.clusteredSpecs,this.sourcesWithLayers.places,this.mapLibreMap),this.sourcesWithLayers.placesUnclustered&&i.unclusteredSpecs.length>0&&updateLayersAndSource(i.unclusteredSpecs,r.unclusteredSpecs,this.sourcesWithLayers.placesUnclustered,this.mapLibreMap),this.layerSpecs=t}rebuildSourcesAndLayers(e){const t=this.sourcesWithLayers.places.shownFeatures,i=this.shownConnections,r=this.mapLibreMap;for(const s of[...Object.values(this.layerSpecs),...Object.values(this.connectionLayerSpecs),...Object.values(this.entryPointLayerSpecs)])r.getLayer(s.id)&&r.removeLayer(s.id);for(const s of[this.sourceID,this.unclusteredSourceID,this.connectionSourceID,this.entryPointSourceID])r.getSource(s)&&r.removeSource(s);this.initSourcesWithLayers(e,!0),this.setupImages(e);const o=preparePlacesForInstance(t,this.instanceIndex,e);this.sourcesWithLayers.places.show(o,{automaticVisibility:!1}),this.sourcesWithLayers.placesUnclustered?.show(o,{automaticVisibility:!1}),this.applyPlacesVisibility(e),i.length&&(this.shownConnections=[...i],this.updateConnectionsData(e)),this.updateEntryPointsData(e)}updateConnectionsData(e){const t=this.sourcesWithLayers.places.shownFeatures,i=((e,t,i={})=>{const r=i.connections?.label,o=[];for(const s of e){const e=resolveEndpoint(s.from,t),i=resolveEndpoint(s.to,t);if(!e||!i)continue;const a=s.id??generateId(),n=r?r(s):"";o.push({type:"Feature",id:a,geometry:{type:"LineString",coordinates:[e.geometry.coordinates,i.geometry.coordinates]},properties:{id:a,fromId:"string"==typeof s.from?s.from:e.id,toId:"string"==typeof s.to?s.to:i.id,label:n}})}return{type:"FeatureCollection",features:o}})(this.shownConnections,t,e);this.sourcesWithLayers.connections.show(i,{automaticVisibility:!1}),this.applyVisibilityTo(Object.values(this.connectionLayerSpecs),!!i.features.length,e)}updateEntryPointsData(e){if(!this.refreshingEntryPoints){this.refreshingEntryPoints=!0;try{const t=this.sourcesWithLayers.entryPoints,i=((e,t,i)=>{const r=[];if(!i)return{type:"FeatureCollection",features:r};const o=i.showFor??"selected",s=/* @__PURE__ */new Map;for(const a of t.features)a.properties.eventState&&s.set(a.properties.id,a.properties.eventState);for(const a of e.features){const e=a.properties.id,t=a.properties.entryPoints??[],i=t.map((t,i)=>toEntryPointID(e,i));if(isShownFor(o,a.properties.eventState)||i.some(e=>isShownFor(o,s.get(e))))for(const[o,{position:n,...l}]of t.entries()){const t=i[o],c=s.get(t),d={...l,id:t,placeID:e,entryPointIndex:o};r.push({type:"Feature",id:t,geometry:{type:"Point",coordinates:n},properties:c?{...d,eventState:c}:d},{type:"Feature",id:t,geometry:{type:"LineString",coordinates:[a.geometry.coordinates,n]},properties:d})}}return{type:"FeatureCollection",features:r}})(this.sourcesWithLayers.places.shownFeatures,t.shownFeatures,e?.entryPoints);t.show(i,{automaticVisibility:!1}),this.applyVisibilityTo(Object.values(this.entryPointLayerSpecs),!!i.features.length,e)}finally{this.refreshingEntryPoints=!1}}}applyVisibilityTo(e,t,i){applyLayersVisibility(e,t&&!1!==i?.visible,this.mapLibreMap)}applyPlacesVisibility(e){this.applyVisibilityTo(Object.values(this.layerSpecs),!!this.sourcesWithLayers.places.shownFeatures.features.length,e)}setupImages(e){this.addCategoryIcons(e?.icon?.categoryIcons??[]),this.addDefaultIcon(e?.icon?.default,this.colorOf(e))}addCategoryIcons(e){for(const{id:t,availabilityLevel:i,image:r,pixelRatio:o=2}of e){if(!r)continue;addOrUpdateImage("if-not-in-sprite",suffixNumber(i?`${t}-${i}`:t,this.instanceIndex),r,this.mapLibreMap,{pixelRatio:o})}}addDefaultIcon(e,t){const i=e?.image;if(i?.image)return this.paintedPinStyle=void 0,void addOrUpdateImage("if-not-in-sprite",this.defaultPlaceIconID,i.image,this.mapLibreMap,{pixelRatio:i.pixelRatio??2});const r={fillColor:t,...e?.style};this.mapLibreMap.hasImage(this.defaultPlaceIconID)&&isEqual(r,this.paintedPinStyle)||(this.paintedPinStyle=r,addOrUpdateImage("add-or-update",this.defaultPlaceIconID,(e=>{if(isDOMImageSupported())return svgToImg(pinSvg(e))})(r),this.mapLibreMap,{pixelRatio:2}))}updateData(e){const t=preparePlacesForInstance(this.sourcesWithLayers.places.shownFeatures,this.instanceIndex,e);this.sourcesWithLayers.places.show(t,{automaticVisibility:!1}),this.sourcesWithLayers.placesUnclustered?.show(t,{automaticVisibility:!1})}async show(e){await this.waitUntilModuleReady(),this.clearConnectionsSync(),this.sourcesWithLayers.entryPoints.clear();const t=preparePlacesForInstance(e,this.instanceIndex,this.config);this.sourcesWithLayers.places.show(t,{automaticVisibility:!1}),this.sourcesWithLayers.placesUnclustered?.show(t,{automaticVisibility:!1}),this.applyPlacesVisibility(this.config);for(const i of this.shownFeaturesHandlers)i({places:e})}async clear(){await this.waitUntilModuleReady(),this.clearConnectionsSync(),this.sourcesWithLayers.places.clear(),this.sourcesWithLayers.placesUnclustered?.clear()}async showConnections(e){await this.waitUntilModuleReady(),this.shownConnections=[...e],this.updateConnectionsData(this.config);for(const t of this.shownFeaturesHandlers)t({connections:e})}async clearConnections(){await this.waitUntilModuleReady(),this.clearConnectionsSync()}clearConnectionsSync(){this.shownConnections=[],this.sourcesWithLayers.connections?.clear()}getShown(){return{places:this.sourcesWithLayers.places.shownFeatures,connections:[...this.shownConnections]}}eventStateSources(){return placeSources}get events(){return this.buildEvents(this.moduleEventsWithShown([...placeSources,"connections","entryPoints"],this.shownFeaturesHandlers),{places:this.userEventsWithStates(placeSources),connections:this.userEventsWithStates(["connections"]),entryPoints:this.userEventsWithStates(["entryPoints"],{mapping:e=>((e,t)=>{const i=e.properties;return{type:"Feature",id:i.id,geometry:{type:"Point",coordinates:(r=e.geometry,"Point"===r.type?r.coordinates:r.coordinates[1])},properties:{...i,place:findFeatureByRefId(t.features,i.placeID)?.feature}};var r})(e,this.sourcesWithLayers.places.shownFeatures)})})}},poisMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:e.geometry,properties:{id:String(t?.id),name:t?.name,category:t?.category,group:t?.group,priority:t?.priority}}},getStyleCategories=e=>{const t=e.flatMap(e=>(e=>e in poiCategoryGroups)(e)?poiCategoryGroups[e].map(toBaseMapPOICategory):[toBaseMapPOICategory(e)]);return[...new Set(t.filter(e=>!isNil(e)))]},POIsModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTiles");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTiles`);return{pois:new StyleSourceWithLayers(this.mapLibreMap,t,e=>poiLayerIDs.includes(e.id))}}_applyConfig(e){return e&&!isNil(e.visible)?this._setVisible(e.visible,!1):this._initializing||this.isVisible()||this._setVisible(!0,!1),this.applyCategoriesFilter(e?.filters?.categories),e}isVisible(){return this.config?.visible??this.sourcesWithLayers.pois.isAnyLayerVisible()}setVisible(e){this._setVisible(e)}_setVisible(e,t=!0){if(this.tomtomMap.mapReady)for(const i of this.sourcesWithLayers.pois.sourceAndLayerIDs.layerIDs)this.visibilityComposer.setVisible(i,"pois.visible",e);t&&(this.config={...this.config,visible:e},this.emitConfigChange())}applyCategoriesFilter(e){if(this.tomtomMap.mapReady&&(e||this.categoriesFilter)){const t=e&&isCompleteValuesFilter(e)?buildMappedValuesFilter("category",e.show,getStyleCategories(e.values)):void 0;this.filterComposer.setClause(mapStyleLayerIDs.poi,"pois.categories",t)}this.categoriesFilter=e}getShown(){return{pois:this.mapLibreMap.queryRenderedFeatures({layers:this.sourcesWithLayers.pois.sourceAndLayerIDs.layerIDs,validate:!1}).map(poisMapping)}}get events(){return this.moduleEvents(["pois"],{mapping:poisMapping})}},sourceOf=e=>"source"in e&&"string"==typeof e.source?e.source:void 0,matchesOneOf=(e,t)=>!e||void 0!==t&&e.includes(t),matchesLayerSelector=(e,t,i)=>matchesOneOf(e.metadataGroups,(e=>{const t=e.metadata;if(t&&"object"==typeof t&&"group"in t){const e=t.group;return"string"==typeof e?e:void 0}})(t))&&matchesOneOf(e.layerTypes,t.type)&&matchesOneOf(e.sources,sourceOf(t))&&matchesOneOf(e.sourceTypes,((e,t)=>{const i=sourceOf(e);return void 0===i?void 0:t?.[i]?.type})(t,i))&&matchesOneOf(e.sourceLayers,(e=>"source-layer"in e&&"string"==typeof e["source-layer"]?e["source-layer"]:void 0)(t))&&((e,t)=>{const i=t.id.toLowerCase(),r=e=>i.includes(e.toLowerCase());return!(e.idIncludes&&!e.idIncludes.some(r)||e.idExcludes?.some(r))})(e,t),matchesAnyLayerSelector=(e,t,i)=>e.some(e=>matchesLayerSelector(e,t,i)),baseMapLayerGroupNames=["land","water","buildings2D","roads","railways","ferries","borders","buildings3D","natureLabels","roadLabels","roadShields","houseNumbers","smallerTownLabels","stateLabels","cityLabels","allPlaceLabels","capitalLabels","countryLabels"],layerGroupMappings={land:{metadataGroups:["area","background"]},water:{metadataGroups:["water"]},natureLabels:{metadataGroups:["label"]},roads:{metadataGroups:["road","road_area","transit_area"],idExcludes:["railway","subway","aerialway","ferry"]},railways:{metadataGroups:["road"],layerTypes:["line"],idIncludes:["railway","subway","aerialway"]},ferries:{metadataGroups:["road"],layerTypes:["line"],idIncludes:["ferry"]},buildings2D:{metadataGroups:["building"],layerTypes:["fill","line"]},buildings3D:{metadataGroups:["area_3d","building"],layerTypes:["fill-extrusion"]},borders:{metadataGroups:["border","border_label"]},roadLabels:{metadataGroups:["road_label"],idExcludes:["shield"]},roadShields:{metadataGroups:["road_label"],idIncludes:["shield"]},houseNumbers:{metadataGroups:["address_point_label"]},allPlaceLabels:{metadataGroups:["places_label"]},smallerTownLabels:{metadataGroups:["places_label"],idIncludes:["neighbourhood","village","hamlet","town"]},cityLabels:{metadataGroups:["places_label"],idIncludes:["city"]},capitalLabels:{metadataGroups:["places_label"],idIncludes:["capital"]},stateLabels:{metadataGroups:["places_label"],idIncludes:["state"]},countryLabels:{metadataGroups:["places_label"],idIncludes:["country"]}},isMatching=(e,t)=>matchesLayerSelector(layerGroupMappings[e],t),baseMapLayerGroupSelector=e=>layerGroupMappings[e],buildLayerGroupFilter=e=>{const t=e.mode,i=e.names;return"include"===t?e=>i.some(t=>isMatching(t,e)):"exclude"===t?e=>!i.some(t=>isMatching(t,e)):(console.error("Unrecognized layer group mode:",t),()=>!0)},baseMapLayerFilter=e=>!poiLayerIDs.includes(e.id),groupNames=new Set(baseMapLayerGroupNames),isGroupName=e=>groupNames.has(e),groupsVisible=(e,t)=>Object.fromEntries(e.map(e=>[e,{visible:t}])),groupEntries=e=>Object.keys(e??{}).filter(isGroupName).flatMap(t=>{const i=e?.[t];return i?[[t,i.visible]]:[]}),containsAll=(e,t)=>t.every(t=>e.includes(t)),groupsAsRecorded=(e,t,i)=>{const r=t.flatMap(e=>i[e]),o=/* @__PURE__ */new Map,s=(e,t)=>{o.delete(e),o.set(e,t)};for(const a of t)s(a,e?.visible);for(const[a,n]of groupEntries(e?.groups)){const e=containsAll(r,i[a])?[a]:t.filter(e=>containsAll(i[a],i[e]));for(const t of e)s(t,n)}return Object.fromEntries([...o].map(([e,t])=>[e,void 0===t?{}:{visible:t}]))},BaseMapModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t),this.takeoverListeners=[]}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTiles");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTiles`);const i=new StyleSourceWithLayers(this.mapLibreMap,t,baseMapLayerFilter);return this.layersByGroup=void 0,this.knobVisibility=/* @__PURE__ */new Map,{vectorTiles:i}}_applyConfig(e){return!e&&this._initializing||this.writeVisibility(e),e}isVisible(e){const t=this.layerSettings(this.config,e?.layerGroups&&buildLayerGroupFilter(e.layerGroups));return[...t.values()].includes(!0)||this.sourcesWithLayers.vectorTiles.isAnyLayerVisible(e=>t.has(e.id)&&void 0===t.get(e.id))}setVisible(e,t){const i=t?.layerGroups,r=(e=>e?"include"===e.mode?e.names:baseMapLayerGroupNames.filter(t=>!e.names.includes(t)):baseMapLayerGroupNames)(i);for(const o of r)this.knobVisibility.delete(o);this.applyConfig(i?((e,{mode:t,names:i},r,o)=>"exclude"===t?{...e,visible:r,groups:groupsAsRecorded(e,i,o)}:{...e,groups:{...omit(e?.groups,i),...groupsVisible(i,r)}})(this.config,i,e,this.groupedLayers()):{...omit(this.config,"groups"),visible:e});for(const o of this.takeoverListeners)o(r)}_applyKnobVisibility(e,t){this.knobVisibility.delete(e),void 0!==t&&this.knobVisibility.set(e,t),this.writeVisibility(this.config,buildLayerGroupFilter({mode:"include",names:[e]}))}_onGroupsTakenOver(e){this.takeoverListeners.push(e)}writeVisibility(e,t){if(this.tomtomMap.mapReady)for(const[i,r]of this.layerSettings(e,t))this.visibilityComposer.setVisible(i,"baseMap.visible",r)}layerSettings(e,t){const i=this.groupedLayers(),r=/* @__PURE__ */new Map;for(const[s,a]of[...groupEntries(e?.groups),...this.knobVisibility])for(const e of i[s])r.set(e,a);const o=/* @__PURE__ */new Map;for(const s of this.sourcesWithLayers.vectorTiles._layerSpecs)t&&!t(s)||o.set(s.id,r.has(s.id)?r.get(s.id):e?.visible);return o}getLayers(){return mapValues(this.groupedLayers(),e=>[...e])}getLayerIds(e){return[...this.groupedLayers()[e]]}groupedLayers(){return this.layersByGroup??=(e=>{const t=Object.fromEntries(baseMapLayerGroupNames.map(e=>[e,[]]));for(const i of e)for(const e of baseMapLayerGroupNames)isMatching(e,i)&&t[e].push(i.id);return t})(this.sourcesWithLayers.vectorTiles._layerSpecs),this.layersByGroup}get events(){return this.moduleEvents(["vectorTiles"],{scopeResolver:resolveBaseMapEventScope})}},resolveBaseMapEventScope=e=>({layerFilter:buildLayerGroupFilter(e.layerGroups),featureMatches:e.features}),layerGroupContents={land:"land use and land cover areas, and the map background",water:"oceans, lakes and rivers",buildings2D:"2D building footprints",roads:"road lines, their arrows, and road and transit surface areas",railways:"railways and aerial cableways",ferries:"ferry connections",borders:"administrative boundaries, military and protected overlays, and their labels",buildings3D:"3D building models",natureLabels:"labels of peaks, islands, rivers and water areas",roadLabels:"road name labels",roadShields:"highway shields",houseNumbers:"house number labels",smallerTownLabels:"neighbourhood, village, hamlet and town labels",stateLabels:"state and province labels",cityLabels:"city labels",allPlaceLabels:"every place label, the other place-label groups included",capitalLabels:"capital city labels",countryLabels:"country name labels"},describeLayerGroup=e=>`The \`${e}\` layer group: ${layerGroupContents[e]}.`,buildCatalogue$2=()=>[{id:"visible",kind:"toggle",description:"Every base-map layer, beneath what the `groups` entries set."},...baseMapLayerGroupNames.map(e=>({id:`groups.${e}.visible`,kind:"toggle",description:describeLayerGroup(e)}))],baseMapKnobCatalogue=/* @__PURE__ */buildCatalogue$2(),baseMapKnobIds=/* @__PURE__ */baseMapKnobCatalogue.map(({id:e})=>e),CustomGeoJSONModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),validateConfig(i),new e(t,i)}constructor(e,t){super(e,t),this.shownFeaturesHandlers=[]}_initSourcesWithLayers(e,t){const i=e??this.initialConfig;t||(this.shownSourceNames=/* @__PURE__ */new Set),this.resolveIDs(i),this.registerImages(i);const r={};for(const o of Object.keys(i.sources)){const e=this.resolvedSourceIDs[o],t=this.resolvedLayerSpecs[o],s=i.sources[o].cluster;r[o]=new GeoJSONSourceWithLayers(this.mapLibreMap,e,t,!0,s)}return r}registerImages(e){if(e.images)for(const[t,i]of Object.entries(e.images))this.mapLibreMap.hasImage(t)||this.mapLibreMap.addImage(t,i.image,i.options)}resolveIDs(e){const t={},i={};for(const r of Object.keys(e.sources)){const o=e.sources[r],s=o.sourceID??`custom-geojson-${this.instanceIndex}-${String(r)}`;t[r]=s,i[r]=o.layers.map((e,t)=>({...e,id:e.id??`${s}-layer-${t}`}))}this.resolvedSourceIDs=t,this.resolvedLayerSpecs=i}_applyConfig(e){if(!e)return this._applyConfig(this.initialConfig);this.initialConfig??=e;const t=this.config,i=t?this.resolvedLayerSpecs:void 0;return this.resolveIDs(e),this.registerImages(e),t&&i&&this.updateLayersForExistingSources(i),this.applyVisibility(e),e}updateLayersForExistingSources(e){for(const t of Object.keys(this.resolvedLayerSpecs)){const i=e[t],r=this.resolvedLayerSpecs[t],o=this.sourcesWithLayers[t];if(!i||!o)continue;updateLayersAndSource(r,i,o,this.mapLibreMap);const s=[];for(const e of o._layerSpecs)this.mapLibreMap.getLayer(e.id)||s.push(e);s.length>0&&addLayers(s,this.mapLibreMap)}}applyVisibility(e){const t=!1!==e?.visible;for(const i of Object.values(this.sourcesWithLayers))i.setLayersVisible(t&&!!i.shownFeatures.features.length)}discardShownData(){this.shownSourceNames.clear()}restoreDataAndConfigImpl(){const e=[...this.shownSourceNames].map(e=>[e,this.sourcesWithLayers[e].shownFeatures]);this.initSourcesWithLayers(this.config,!0),this.config&&this._applyConfig(this.config);for(const[t,i]of e)this.sourcesWithLayers[t]&&this.showOnSource(t,i)}async show(e,t){if(await this.waitUntilModuleReady(),void 0!==t)this.showOnSource(t,e);else for(const i of Object.keys(this.sourcesWithLayers))this.showOnSource(i,e)}showOnSource(e,t){const i=ensureFeatureIDs(t);this.shownSourceNames.add(e),this.sourcesWithLayers[e].show(i,{automaticVisibility:this.isVisible()});for(const r of this.shownFeaturesHandlers)r({sourceName:e,data:i})}async clear(e){if(await this.waitUntilModuleReady(),void 0!==e)return this.sourcesWithLayers[e].clear(),void this.shownSourceNames.delete(e);for(const t of Object.keys(this.sourcesWithLayers))this.sourcesWithLayers[t].clear();this.shownSourceNames.clear()}getShown(){const e={};for(const t of Object.keys(this.sourcesWithLayers))e[t]=this.sourcesWithLayers[t].shownFeatures;return e}eventStateSources(){return Object.keys(this.sourcesWithLayers)}get events(){const e=Object.keys(this.sourcesWithLayers),t={};for(const i of e)t[i]=this.userEventsWithStates([i]);return this.buildEvents(this.moduleEventsWithShown(e,this.shownFeaturesHandlers),t)}},validateConfig=e=>{if(!e.sources||0===Object.keys(e.sources).length)throw new Error("CustomGeoJSONModule requires at least one source in config.sources.");assertNoReservedScopeNames(Object.keys(e.sources),"CustomGeoJSONModule source");for(const[t,i]of Object.entries(e.sources))if(!i.layers||0===i.layers.length)throw new Error(`CustomGeoJSONModule source "${t}" requires at least one layer.`)},ensureFeatureIDs=e=>{let t=!1;for(const i of e.features)if(null==i.id||i.properties?.id!==i.id){t=!0;break}return t?{...e,features:e.features.map((e,t)=>{const i=e.id??e.properties?.id??t;return{...e,id:i,properties:{...e.properties,id:i}}})}:e},customGeoJSONKnobDefinitions={visible:{kind:"toggle",description:"Every layer of every source.",default:!0}},customGeoJSONKnobCatalogue=/* @__PURE__ */withIds(customGeoJSONKnobDefinitions),customGeoJSONKnobIds=/* @__PURE__ */customGeoJSONKnobCatalogue.map(({id:e})=>e),HIGHLIGHT_FILL_OPACITY_FACTOR_RANGE={min:1,max:4,step:.25,bounds:"hard"},HIGHLIGHT_LINE_WIDTH_FACTOR_RANGE={min:1,max:3,step:.25,bounds:"hard"},BORDER_LABEL_OFFSET=[0,1],getThemeAdaptiveGeometryColors=e=>({defaultColor:"dark"===e?"#5FA8D8":"#0A3653",...themeAdaptiveLabelColors(e)}),fillOpacityByStyle=["case",["==",["get","fillStyle"],"outline"],0,.15],lineWidthByStyle=["case",["==",["get","fillStyle"],"outline"],5,2],highlightedFillOpacity=(e,t)=>scaledWhen(hasActiveEventState,e,clampFactor(t?.fillOpacityFactor,HIGHLIGHT_FILL_OPACITY_FACTOR_RANGE,2),1),buildGeometryLayerSpecs=(e,t,i,r="#0A3653")=>{const o=i?.fill,s=i?.line,a=i?.highlight,n=(Array.isArray(o?.color)?o.color:void 0)??i?.color,l=((e="#0A3653")=>({type:"fill",paint:{"fill-color":["coalesce",["get","color"],e],"fill-opacity":fillOpacityByStyle,"fill-antialias":!1}}))(n??r),c=((e="#0A3653",t="#555555")=>({type:"line",paint:{"line-color":["case",["==",["get","fillStyle"],"outline"],["coalesce",["get","color"],t],["coalesce",["get","color"],e]],"line-opacity":["case",["==",["get","fillStyle"],"outline"],.9,1],"line-width":lineWidthByStyle}}))(n??r,n),d={...l,id:e,paint:{...l.paint,"fill-opacity":highlightedFillOpacity(o?.opacity??fillOpacityByStyle,a)}},u=s?.layer,p=u?.paint?.["line-width"],h=isNil(s?.width)&&!isNil(p)?p:((e,t)=>scaledWhen(hasActiveEventState,e,clampFactor(t?.lineWidthFactor,HIGHLIGHT_LINE_WIDTH_FACTOR_RANGE,1.75)))(s?.width??lineWidthByStyle,a);return[d,{...c,...u,id:t,...u?.layout&&{layout:{...c.layout,...u.layout}},paint:{...c.paint,...u?.paint,...!isNil(s?.color)&&{"line-color":s?.color},"line-width":h,...!isNil(s?.opacity)&&{"line-opacity":s?.opacity}}}]},buildGeometryTitleLayerSpec=(e,t,i="light")=>{const r=t?.label,{textColor:o,haloColor:s}=getThemeAdaptiveGeometryColors(i);return{type:"symbol",id:e,layout:{"text-field":r?.text??["get","title"],"text-padding":5,"text-size":15,"text-font":["Noto-Bold"],...labelLayoutProperties(r),"symbol-placement":"point"},paint:{"text-color":o,"text-halo-color":s,"text-halo-width":["interpolate",["linear"],["zoom"],6,1,10,1.5],...labelPaintProperties(r),"text-translate-anchor":"viewport"}}},buildGeometryLineLabelLayerSpec=(e,t,i="light")=>{const r=t?.lineLabel,{textColor:o,haloColor:s}=getThemeAdaptiveGeometryColors(i);return{type:"symbol",id:e,minzoom:r?.minZoom??3,layout:{"text-field":r?.text??["get","title"],"symbol-placement":"line","text-size":15,"text-font":["Noto-Bold"],...labelLayoutProperties(r),"symbol-spacing":r?.symbolSpacing??200,"text-keep-upright":!0,"text-offset":r?.offset??BORDER_LABEL_OFFSET},paint:{"text-color":o,"text-halo-color":s,"text-halo-width":2,...labelPaintProperties(r)}}},prepareGeometryForDisplay=(e,t={})=>({...e,features:e.features.map((e,i)=>{const r=(e.properties??{}).fillStyle??t.fillStyle,o="inverted"===r?(e=>{const t=mask(e);return{...e,geometry:t.geometry}})(e):e,s=o.properties??{},a=s.title??((e,t)=>{const i=t.label?.text;return"string"==typeof i&&i?i:e.properties?.address?.freeformAddress})(o,t),n=s.color??((e,t)=>{const{color:i,palette:r}=e.fill??{};return void 0!==i?"string"==typeof i?i:void 0:r?.length?r[t%r.length]:void 0})(t,i);return{...o,properties:{...o.properties,...r&&{fillStyle:r},...a&&{title:a},...n&&{color:n},id:s.id??generateId()}}})}),geometryParts=["fill","line"],layerOnlyConfigKeys=["beforeLayerConfig","visible","events","highlight"],AbstractGeometriesModule=class extends AbstractDataOwnedMapModule{constructor(e,t){super(e,t),this.lastRawInput=null,this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{const e=this.displayConfig(this.config)??{};void 0!==e.color||void 0!==e.fill?.color||e.fill?.palette?.length||(this.updateLayers(e),this.applyVisibility(this.config))})}get lightDark(){return this.tomtomMap.styleLightDarkTheme}get defaultColor(){return mapAccentColor(this.tomtomMap)??getThemeAdaptiveGeometryColors(this.lightDark).defaultColor}_initSourcesWithLayers(e,t){if(!t){const e=this.idPrefix;this.sourceID=`${e}-${this.instanceIndex}`,this.titleSourceID=`${e}Title-${this.instanceIndex}`;const t=`${e}-${this.instanceIndex}`;this.fillLayerID=`${t}_Fill`,this.outlineLayerID=`${t}_Outline`,this.lineLabelLayerID=`${t}_LineLabel`,this.titleLayerID=`${t}_Title`}const i=this.displayConfig(e),[r,o]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,i,this.defaultColor),s=buildGeometryTitleLayerSpec(this.titleLayerID,i,this.lightDark);this.titleLayerSpecs=s,this.geometryFillLayerSpecs=r,this.geometryOutlineLayerSpecs=o;const a=buildGeometryLineLabelLayerSpec(this.lineLabelLayerID,i,this.lightDark);return this.lineLabelLayerSpecs=a,{geometry:new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,[{...r},{...o},a]),geometryLabel:new GeoJSONSourceWithLayers(this.mapLibreMap,this.titleSourceID,[s])}}_applyConfig(e){const t=this.displayConfig(e);this.updateLayers(t);const i=this.sourcesWithLayers.geometry.shownFeatures;return i.features.length&&isEqual(omit(e,layerOnlyConfigKeys),omit(this.config,layerOnlyConfigKeys))||this.displayAgain(e,i),(t?.beforeLayerConfig||this.displayConfig(this.config)?.beforeLayerConfig)&&this.applyBeforeLayerConfig(t?.beforeLayerConfig,"top"),this.applyVisibility(e),e}applyVisibility(e){const{geometry:t,geometryLabel:i}=this.sourcesWithLayers,r=!1!==e?.visible&&!!t.shownFeatures.features.length;applyLayersVisibility([this.geometryFillLayerSpecs,this.geometryOutlineLayerSpecs],r,this.mapLibreMap),applyLayersVisibility([this.lineLabelLayerSpecs],r&&void 0!==this.displayConfig(e)?.lineLabel,this.mapLibreMap),applyLayersVisibility([this.titleLayerSpecs],r&&!!i.shownFeatures.features.length,this.mapLibreMap)}get partLayerIDs(){return{fill:[this.fillLayerID],line:[this.outlineLayerID,this.lineLabelLayerID]}}applyBeforeLayerConfig(e,t){const i=this.partLayerIDs;for(const r of geometryParts){const o=beforeLayerTargetOf(e,r)??t;for(const e of i[r])moveLayerBefore(this.mapLibreMap,e,beforeLayerIDOf(o,this.titleLayerID))}}updateLayers(e){const[t,i]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,e,this.defaultColor),r=buildGeometryTitleLayerSpec(this.titleLayerID,e,this.lightDark);changeLayerProps(t,this.geometryFillLayerSpecs,this.mapLibreMap),changeLayerProps(i,this.geometryOutlineLayerSpecs,this.mapLibreMap),changeLayerProps(r,this.titleLayerSpecs,this.mapLibreMap),this.geometryFillLayerSpecs=t,this.geometryOutlineLayerSpecs=i,this.titleLayerSpecs=r;const o=buildGeometryLineLabelLayerSpec(this.lineLabelLayerID,e,this.lightDark);changeLayerProps(o,this.lineLabelLayerSpecs,this.mapLibreMap),this.lineLabelLayerSpecs=o}discardShownData(){this.lastRawInput=null}restoreDataAndConfigImpl(){const e=this.sourcesWithLayers.geometry.shownFeatures;this.initSourcesWithLayers(this.config,!0),this.displayAgain(this.config,e),this._applyConfig(this.config)}displayAgain(e,t){this.lastRawInput&&this.display(((e,t)=>e.features.length!==t.features.length?e:{...e,features:e.features.map((e,i)=>{const r=t.features[i].properties,o=r?.eventState;return{...e,properties:{...e.properties,id:r?.id,...o&&{eventState:o}}}})})(this.prepare(this.lastRawInput,e),t))}prepare(e,t){return prepareGeometryForDisplay(this.prepareShown(e,t),this.displayConfig(t))}display(e){const t=this.sourcesWithLayers.geometry;t.show(e,{automaticVisibility:!1}),this.sourcesWithLayers.geometryLabel.show((e=>{const t=e.features.map(e=>{let t;if(e.properties?.placeCoordinates)t=e.properties?.placeCoordinates;else if("MultiPolygon"===e.geometry.type){const i=(e=>e.flat().reduce((e,t)=>t.length>e.length?t:e,[]))(e.geometry.coordinates),r=bboxFromCoordsArray(i);t=r&&bboxCenter(r)||null}else t=e.geometry.coordinates.flat();const i=e.id??e.properties?.id??generateId();return{type:"Feature",id:i,geometry:{type:"Point",coordinates:t},properties:{...e.properties,id:i}}});return{type:"FeatureCollection",bbox:e.bbox,features:t}})(t.shownFeatures),{automaticVisibility:!1})}async showPolygons(e){await this.waitUntilModuleReady(),this.lastRawInput=e,this.display(this.prepare(e,this.config)),this.applyVisibility(this.config);for(const t of this.shownFeaturesHandlers)t(e)}async clear(){await this.waitUntilModuleReady(),this.lastRawInput=null,this.sourcesWithLayers.geometry.clear(),this.sourcesWithLayers.geometryLabel.clear()}getShown(){return{geometry:this.sourcesWithLayers.geometry.shownFeatures,geometryLabel:this.sourcesWithLayers.geometryLabel.shownFeatures}}eventStateSources(){return["geometry"]}get events(){return this.buildEvents(this.moduleEventsWithShown(["geometry","geometryLabel"],this.shownFeaturesHandlers),{geometry:this.userEventsWithStates(["geometry"]),geometryLabel:this.userEventsWithStates(["geometryLabel"])})}},GeometriesModule=class e extends AbstractGeometriesModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t)}get idPrefix(){return"geometry"}displayConfig(e){return e}prepareShown(e,t){const i=t?.transformFeaturesForDisplay;return i?i(e):e}async show(e){await this.showPolygons(e)}},fillStyledGeometryConfig=({palette:e,beforeLayerConfig:t="lowestLabel"}={})=>({beforeLayerConfig:t,line:{width:["case",["==",["get","fillStyle"],"outline"],5,1],color:["case",["==",["get","fillStyle"],"outline"],["coalesce",["get","color"],"#555555"],"grey"],opacity:["case",["==",["get","fillStyle"],"outline"],.9,1]},fill:{...e&&{palette:e},opacity:["case",["==",["get","fillStyle"],"outline"],0,.6]},lineLabel:{}}),geometryFillStyles=["filled","outline","inverted"],LABEL_SIZE_RANGE={min:6,max:48,step:1,bounds:"hard-min"},HALO_WIDTH_RANGE={min:0,max:10,step:.5,bounds:"hard-min"},highlightKnobDefinitions=e=>({"highlight.fillOpacityFactor":{kind:"factor",description:`Multiplier on the fill opacity of a hovered or clicked ${e}, at most opaque; \`1\` draws it as any other.`,range:HIGHLIGHT_FILL_OPACITY_FACTOR_RANGE,default:2},"highlight.lineWidthFactor":{kind:"factor",description:`Multiplier on the border width of a hovered or clicked ${e}; \`1\` draws it as any other.`,range:HIGHLIGHT_LINE_WIDTH_FACTOR_RANGE,default:1.75}}),fillStyleKnobDefinition=e=>({kind:"enum",description:e,options:/* @__PURE__ */everyOf()(geometryFillStyles),default:"filled"}),moduleKnobDefinitions={color:{kind:"color",description:"Base colour of the fill and the border. Unset: the map's accent if a theme sets one, else a navy on light styles and a light blue on dark ones."},visible:{kind:"toggle",description:"Everything the module draws: fills, borders, center labels and border labels.",default:!0},fillStyle:fillStyleKnobDefinition("`filled` shades the polygon, `outline` draws only a thick border, `inverted` shades the outside."),"fill.color":{kind:"color",description:"Fill colour, over `fill.palette` and `color`; a border without its own `line.color` follows it."},"fill.palette":{kind:"colors",description:"CSS colours giving each feature the next fill colour in turn, over `color`."},"fill.opacity":{kind:"number",description:"Fill opacity, which `highlight.fillOpacityFactor` multiplies while hovered or clicked. Unset: 0.15, or 0 with the `outline` fill style.",range:OPACITY_RANGE},"line.color":{kind:"color",description:"Border colour, over a feature's own `color` and every fill colour."},"line.opacity":{kind:"number",description:"Border opacity. Unset: 1, or 0.9 with the `outline` fill style.",range:OPACITY_RANGE},"line.width":{kind:"number",description:"Border width in pixels, which `highlight.lineWidthFactor` multiplies while hovered or clicked. Unset: 2, or 5 with the `outline` fill style.",range:{min:0,max:20,step:.5,bounds:"hard-min"}},...highlightKnobDefinitions("geometry"),"lineLabel.minZoom":{kind:"number",description:"Lowest zoom the border labels are drawn at; setting any `lineLabel` knob draws them.",range:ZOOM_RANGE,default:3},"lineLabel.symbolSpacing":{kind:"number",description:"Distance between repeated border labels, in pixels.",range:{min:50,max:1e3,step:10,bounds:"hard-min"},default:200},"lineLabel.offset":{kind:"offset",description:"Shift of the border labels off the line, in ems: x along it, y across it.",range:{min:-5,max:5,step:.1,bounds:"soft"},default:BORDER_LABEL_OFFSET}},labelNames={label:"center labels",lineLabel:"border labels"},labelKnobDefinitions={size:e=>({kind:"number",description:`Text size of the ${labelNames[e]}, in pixels.`,range:LABEL_SIZE_RANGE,default:15}),color:e=>({kind:"color",description:`Text colour of the ${labelNames[e]}. Unset follows the map's light/dark theme.`}),haloColor:e=>({kind:"color",description:`Halo colour of the ${labelNames[e]}. Unset follows the map's light/dark theme.`}),haloWidth:e=>({kind:"number",description:`Halo width of the ${labelNames[e]}, in pixels.`,range:HALO_WIDTH_RANGE,...defaultOf("lineLabel"===e?2:void 0)}),opacity:e=>({kind:"number",description:`Text opacity of the ${labelNames[e]}.`,range:OPACITY_RANGE,default:1}),font:e=>({kind:"enums",description:`Font faces of the ${labelNames[e]}, in order: the first one available wins.`,options:mapFonts,default:["Noto-Bold"]})},labelEntries=(e,t)=>Object.keys(labelKnobDefinitions).map(i=>({id:`${t}.${i}`,...labelKnobDefinitions[i](e)})),geometriesKnobCatalogue=/* @__PURE__ */(()=>{const e=withIds(moduleKnobDefinitions),t=({id:e})=>e.startsWith("lineLabel.");return[...e.filter(e=>!t(e)),...labelEntries("label","label"),...labelEntries("lineLabel","lineLabel"),...e.filter(t)]})(),geometriesKnobIds=/* @__PURE__ */geometriesKnobCatalogue.map(({id:e})=>e),rangesModuleKnobDefinitions={visible:{kind:"toggle",description:"Everything the module draws: bands, borders and their labels.",default:!0},fillStyle:fillStyleKnobDefinition("`filled` shades each band, `outline` draws only each range's border, `inverted` shades the outside of each range."),palette:{kind:"colors",description:"CSS colours of the bands, the innermost first, starting over after the last. Empty: a ramp from the map's accent toward its land colour, reversed for `inverted`."},...highlightKnobDefinitions("band")},reachableRangesKnobCatalogue=/* @__PURE__ */(()=>[...withIds(rangesModuleKnobDefinitions),...labelEntries("lineLabel","label")])(),reachableRangesKnobIds=/* @__PURE__ */reachableRangesKnobCatalogue.map(({id:e})=>e),titleOf=(e,t,i)=>{if(i)return i(e,t);const r=e.properties?.budget;return void 0!==r?.value&&r.type?`${r.value} ${budgetUnits[r.type]??r.type}`:String(t+1)},invertedFill=(e,t,i)=>{const{title:r,fillStyle:o,...s}=e.properties??{};return{...e,geometry:t,properties:{...s,color:i}}},layOutRanges=(e,t,i)=>"inverted"===t?((e,t)=>{const i=e.map(e=>e[0].feature),r=i.length>1&&union(featureCollection(i))||i[0],o=Math.max(...e.map(e=>e[0].rank)),s=[invertedFill(i[0],mask(r).geometry,t(o))];for(const n of e)for(const[e,{feature:i,rank:r}]of n.entries()){if(0===e)continue;const o=difference(featureCollection([n[e-1].feature,i]));s.push(invertedFill(i,o?.geometry??i.geometry,t(r)))}const a=e.flat().map(({feature:e,rank:i,title:r})=>{const{id:o,...s}=e.properties??{};return{...e,id:void 0,properties:{...s,title:r,fillStyle:"filled",color:t(i)}}});return[...s,...a]})(e,i):sortBy(e.flat(),({squareMeters:e})=>-e).map(({feature:e,rank:r,title:o})=>({...e,properties:{...e.properties,title:o,fillStyle:t,color:i(r)}})),prepareReachableRanges=(e,{fillStyle:t="filled",title:i},r)=>{const o=((e,t)=>{const i=e.map((e,i)=>({feature:e,squareMeters:area(e),title:titleOf(e,i,t)})),r=groupBy(i,({feature:e})=>JSON.stringify(getPosition(e.properties?.origin)));return Object.values(r).map(e=>sortBy(e,({squareMeters:e})=>-e).map((t,i)=>({...t,rank:e.length-1-i})))})(e.features,i),s=r(Math.max(0,...o.map(e=>e.length))),a=o.length?layOutRanges(o,t,e=>s[e%s.length]):[];return{type:"FeatureCollection",...e.bbox&&{bbox:e.bbox},features:a}},isBorder=["==",["get","fillStyle"],"filled"],ReachableRangesModule=class e extends AbstractGeometriesModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t),onMapColorsChange(e,["accent","land"],()=>{this.config?.palette?.length||this.displayAgain(this.config,this.sourcesWithLayers.geometry.shownFeatures)})}get idPrefix(){return"reachableRange"}displayConfig(e){const t=fillStyledGeometryConfig({beforeLayerConfig:e?.beforeLayerConfig}),i=e?.label;return"inverted"!==e?.fillStyle?{...t,highlight:e?.highlight,lineLabel:{...i}}:{...t,highlight:e.highlight,line:{...t.line,opacity:["case",isBorder,1,0]},fill:{...t.fill,opacity:["case",isBorder,0,.6]},lineLabel:{...i,opacity:["case",isBorder,i?.opacity??1,0],offset:["case",isBorder,["literal",[0,-1]],["literal",[0,1]]]}}}prepareShown(e,t){return prepareReachableRanges(e,t??{},e=>{if(t?.palette?.length)return t.palette;const i=((e,t,i)=>Array.from({length:i},(r,o)=>mixColor(e,t,i>1?.7*o/(i-1):0)??e))(this.defaultColor,this.landColor,e);return"inverted"===t?.fillStyle?i.reverse():i})}get landColor(){return this.tomtomMap.mapColors.land??getThemeAdaptiveGeometryColors(this.lightDark).haloColor}async show(e){await this.showPolygons(e)}},resolveCountryCrossingColors=(e,t)=>{const i=e?.color??("dark"===t?"#F1F3F5":"#1A2024"),r=relativeLuminance(i),o=void 0!==r&&r>.4?"#1A2024":"#F1F3F5";return{plaque:i,text:e?.textColor??o}},generatedSectionTypes=["carpool","carTrain","importantRoadStretch","lowEmissionZone","motorway","pedestrian","speedLimit","tollVignette","unpaved","urban"],bespokeSectionTypes=["ferry","tollRoad","traffic","tunnel","vehicleRestricted"],drawnSectionTypes=[...generatedSectionTypes,...bespokeSectionTypes],ALL_SECTION_KNOBS=["visible","color","opacity","width","widthFactor","style","pattern","icon"],SECTION_REGISTRY={carpool:{sourceKey:"carpoolSections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},carTrain:{sourceKey:"carTrainSections",visible:!0,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},importantRoadStretch:{sourceKey:"importantRoadStretchSections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},lowEmissionZone:{sourceKey:"lowEmissionZoneSections",visible:!0,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},motorway:{sourceKey:"motorwaySections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},pedestrian:{sourceKey:"pedestrianSections",visible:!1,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},speedLimit:{sourceKey:"speedLimitSections",visible:!0,knobs:["visible","sign"]},tollVignette:{sourceKey:"tollVignetteSections",visible:!0,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},unpaved:{sourceKey:"unpavedSections",visible:!1,style:"halo",pattern:"dashed",knobs:ALL_SECTION_KNOBS},urban:{sourceKey:"urbanSections",visible:!1,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},ferry:{sourceKey:"ferries",visible:!0,style:"inline",pattern:"solid",knobs:ALL_SECTION_KNOBS},tollRoad:{sourceKey:"tollRoads",visible:!0,style:"halo",pattern:"solid",knobs:ALL_SECTION_KNOBS},traffic:{sourceKey:"incidents",visible:!0,style:"inline",pattern:"solid",knobs:["visible","opacity","width","widthFactor","style"]},tunnel:{sourceKey:"tunnels",visible:!0,style:"inline",pattern:"solid",knobs:ALL_SECTION_KNOBS},vehicleRestricted:{sourceKey:"vehicleRestricted",visible:!0,style:"inline",pattern:"dotted",knobs:ALL_SECTION_KNOBS}},sectionSupportsKnob=(e,t)=>SECTION_REGISTRY[e].knobs.includes(t),sectionEntry=e=>SECTION_REGISTRY[e],isGeneratedSectionType=e=>generatedSectionTypes.includes(e),sectionDrawsByDefault=e=>SECTION_REGISTRY[e].visible,postsSign=e=>sectionSupportsKnob(e,"sign"),sectionSourceKey=(generatedSectionTypes.filter(e=>!postsSign(e)),e=>SECTION_REGISTRY[e].sourceKey),mapLayerSpecs=(e={},t)=>Object.entries(e).map(([e,i])=>({...i,id:prefixLayerID(e,t)})),routeDisplayUnits=e=>e?.displayUnits??TomTomConfig.instance.get().displayUnits,ROUTE_LINE_FOREGROUND_COLOR="#36A8F0",ROUTE_LINE_OUTLINE_COLOR="#105287",DESELECTED_FOREGROUND_COLOR="#ABAFB3",DESELECTED_OUTLINE_COLOR="#3C4956",DESELECTED_SECONDARY_COLOR="#727C85",ROUTE_LINE_FOREGROUND_WIDTH=["interpolate",["linear"],["zoom"],1,3,5,4,10,7,18,10],SELECTED_ROUTE_FILTER=["==",["get","routeState"],"selected"],DESELECTED_ROUTE_FILTER=["==",["get","routeState"],"deselected"],ROUTE_LINE_OUTLINE_WIDTH=["interpolate",["linear"],["zoom"],1,5,5,6,10,10,18,14],ROUTE_WIDTH_FACTOR_RANGE={min:.5,max:2,step:.1,bounds:"hard"},ROUTE_WAYPOINT_SIZE_FACTOR_RANGE={min:.5,max:2,step:.1,bounds:"hard"},SECTION_ICON_SIZE_FACTOR_RANGE={min:.25,max:2,step:.05,bounds:"hard"},ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE={min:1,max:1.25,step:.05,bounds:"hard"},isExpression=e=>Array.isArray(e),scaleRamp=(e,t)=>{if(1===t)return e;const i=scaleNumericValue(e,t);return isExpression(i)?i:e},getSectionIconSize=(e,t)=>{const i=e??1,r=scaleNumericValue(i,clampFactor(t,SECTION_ICON_SIZE_FACTOR_RANGE));return"number"==typeof r||isExpression(r)?r:i},scaledWidth=(e,t)=>scaleRamp(e[t?.width??"m"],clampFactor(t?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),LINE_FOREGROUND_WIDTHS={s:["interpolate",["linear"],["zoom"],1,2,5,3,10,5,18,7],m:ROUTE_LINE_FOREGROUND_WIDTH,l:["interpolate",["linear"],["zoom"],1,5,5,6,10,11,18,15]},LINE_OUTLINE_WIDTHS={s:["interpolate",["linear"],["zoom"],1,4,5,5,10,8,18,11],m:ROUTE_LINE_OUTLINE_WIDTH,l:["interpolate",["linear"],["zoom"],1,7,5,9,10,14,18,19]},WAYPOINT_ICON_SIZE=["interpolate",["linear"],["zoom"],8,.6,22,.8],WAYPOINT_INDEX_TEXT_SIZE=["interpolate",["linear"],["zoom"],13,14,18,16],WAYPOINT_SIZE_PRESET_FACTORS={s:.75,m:1,l:1.25},getLineForegroundWidth=e=>scaledWidth(LINE_FOREGROUND_WIDTHS,e),getLineOutlineWidth=e=>scaledWidth(LINE_OUTLINE_WIDTHS,e),waypointScale=(e,t)=>WAYPOINT_SIZE_PRESET_FACTORS[e??"m"]*clampFactor(t,ROUTE_WAYPOINT_SIZE_FACTOR_RANGE),getWaypointIconSize=(e,t)=>scaleRamp(WAYPOINT_ICON_SIZE,waypointScale(e,t)),getWaypointIndexTextSize=(e,t)=>scaleRamp(WAYPOINT_INDEX_TEXT_SIZE,waypointScale(e,t)),SECTION_HALO_WIDTHS={s:["interpolate",["linear"],["zoom"],1,8,5,9,10,12,18,15],m:["interpolate",["linear"],["zoom"],1,9,5,11,10,15,18,20],l:["interpolate",["linear"],["zoom"],1,12,5,14,10,19,18,24]},getSectionHaloWidth=e=>scaledWidth(SECTION_HALO_WIDTHS,e),INSTRUCTION_LINE_WIDTHS={s:["interpolate",["linear"],["zoom"],16,8,22,12],m:["interpolate",["linear"],["zoom"],16,12,22,17],l:["interpolate",["linear"],["zoom"],16,17,22,24]},INSTRUCTION_OUTLINE_WIDTHS={s:["interpolate",["linear"],["zoom"],16,10,22,14],m:["interpolate",["linear"],["zoom"],16,14,22,20],l:["interpolate",["linear"],["zoom"],16,20,22,28]},getInstructionLineWidth=e=>scaledWidth(INSTRUCTION_LINE_WIDTHS,e),getInstructionOutlineWidth=e=>scaledWidth(INSTRUCTION_OUTLINE_WIDTHS,e),INSTRUCTION_ARROW_SIZE=["interpolate",["linear"],["zoom"],16,1,22,2],getInstructionArrowSize=e=>scaleRamp(INSTRUCTION_ARROW_SIZE,clampFactor(e?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),MAJOR_DELAY_COLOR="#AD0000",MODERATE_DELAY_COLOR="#FB2D09",MINOR_DELAY_COLOR="#FFC105",MINOR_DELAY_LABEL_COLOR="#f58240",UNKNOWN_DELAY_COLOR="#000000",UNKNOWN_DELAY_BG_COLOR="#C7D2D8",UNKNOWN_DELAY_DASH_COLOR="rgba(190, 39, 27, 1)",INDEFINITE_DELAY_DASH_COLOR="rgba(137, 150, 168, 1)",DEFAULT_CROSSING_COLORS=resolveCountryCrossingColors(void 0,"light"),COUNTRY_CROSSING_LAYER_ID="routeCountryCrossing",CROSSING_TEXT_SIZE=["interpolate",["linear"],["zoom"],5,11,12,13],CROSSING_ROUTE_ROTATION=["case",[">",["get","bearing"],180],["-",["get","bearing"],270],["-",["get","bearing"],90]],countryCrossingSymbol=(e,t,i)=>{const r=void 0!==e?suffixNumber("route-country-crossing-plaque",e):"route-country-crossing-plaque",o="route"===t?.alignment;return{type:"symbol",filter:SELECTED_ROUTE_FILTER,minzoom:t?.minZoom??4,layout:{"symbol-placement":"point","icon-image":r,"icon-text-fit":"both","icon-text-fit-padding":[4,8,4,8],"icon-rotation-alignment":o?"map":"viewport","text-rotation-alignment":o?"map":"viewport",...o&&{"icon-rotate":CROSSING_ROUTE_ROTATION,"text-rotate":CROSSING_ROUTE_ROTATION},"text-field":["get","label"],"text-font":["Noto-Bold"],"text-size":CROSSING_TEXT_SIZE,"text-allow-overlap":!0,"icon-allow-overlap":!0,...!1===t?.visible&&{visibility:"none"}},paint:{"text-color":i?.text??DEFAULT_CROSSING_COLORS.text}}},GENERATED_SECTION_PAINT={carpool:{color:"#6D4AC7",opacity:.55},carTrain:{color:"#8A5A2B",opacity:.6},importantRoadStretch:{color:"#C7761F",opacity:.6},lowEmissionZone:{color:"#2E8B57",opacity:.5},motorway:{color:"#1F6FB2",opacity:.4},pedestrian:{color:"#B23F86",opacity:.6},tollVignette:{color:"#8C6B1F",opacity:.55},unpaved:{color:"#7A6A54",opacity:.6},urban:{color:"#7E8C8E",opacity:.3}},DASH_ARRAYS={solid:void 0,dashed:[2,1.5],dotted:[0,1.5]},isSectionVisible=(e,t)=>t?.visible??SECTION_REGISTRY[e].visible,sectionDrawStyle=(e,t)=>sectionSupportsKnob(e,"style")&&t?.style||sectionEntry(e).style,SECTION_STYLE_ANCHOR={halo:"routeDeselectedOutline",inline:"routeLineArrows"},sectionStyleAnchor=(e,t)=>{const i=sectionDrawStyle(e,t);return i&&SECTION_STYLE_ANCHOR[i]},withSectionLineKnobs=(e,t,i,r,o="principal")=>{const s={width:i?.width??r?.width,widthFactor:i?.widthFactor??r?.widthFactor},a={...t.paint,"line-width":"halo"===sectionDrawStyle(e,i)?getSectionHaloWidth(s):getLineForegroundWidth(s)};if(i?.color&&sectionSupportsKnob(e,"color")){const e="outline"===o?darkerShadeOf(i.color):i.color;e&&(a["line-color"]=e)}return void 0!==i?.opacity&&sectionSupportsKnob(e,"opacity")&&(a["line-opacity"]=i.opacity),"principal"===o&&sectionSupportsKnob(e,"pattern")&&((e,t,i)=>{const r=i?.pattern??sectionEntry(e).pattern,o=r&&DASH_ARRAYS[r];o?t["line-dasharray"]=o:delete t["line-dasharray"]})(e,a,i),{...t,layout:{...t.layout,...!isSectionVisible(e,i)&&{visibility:"none"}},paint:a}},withSectionSymbolKnobs=(e,t,i)=>{const r=sectionSupportsKnob(e,"icon")?i?.icon:void 0;return{...t,layout:{...t.layout,...r&&{"icon-image":r.image,...void 0!==r.sizeFactor&&{"icon-size":getSectionIconSize(t.layout?.["icon-size"],r.sizeFactor)},...r.placement&&{"symbol-placement":"along"===r.placement?"line":"line-center"}},...!isSectionVisible(e,i)&&{visibility:"none"}}}},sectionLine=(e,t,i)=>withSectionLineKnobs(e,{filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":GENERATED_SECTION_PAINT[e].color,"line-opacity":GENERATED_SECTION_PAINT[e].opacity}},t,i),SIGN_ICON_SIZE=["interpolate",["linear"],["zoom"],10,.5,16,.7],SIGN_TEXT_SIZE=["interpolate",["linear"],["zoom"],10,9,16,13],SIGN_SORT_KEY=["-",["get","startPointIndex"],["get","endPointIndex"]],SIGN_TEXT_OFFSET=["case",["==",["get","signFace"],"plaque"],["literal",[0,.55]],["literal",[0,0]]],signPlacement=e=>e?.sign?.placement??"atChange",sectionSign=(e,t)=>{return{filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:t?.sign?.minZoom??10,layout:{...(i=signPlacement(t),"atChange"===i?{"symbol-placement":"point"}:{"symbol-placement":"line","symbol-spacing":260}),"icon-image":["get","signImageID"],"icon-size":SIGN_ICON_SIZE,"icon-rotation-alignment":"viewport","text-field":["get","signLabel"],"text-font":["Noto-Bold"],"text-size":SIGN_TEXT_SIZE,"text-offset":SIGN_TEXT_OFFSET,"text-rotation-alignment":"viewport","symbol-sort-key":SIGN_SORT_KEY,...!isSectionVisible(e,t)&&{visibility:"none"}},paint:{"text-color":["get","signNumeralsColor"]}};var i},SECTION_START_SIGN_IMAGE_IDS={tunnel:"route-tunnel-sign",vehicleRestricted:"route-vehicle-restricted-sign"},sectionStartSign=(e,t)=>({filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:10,layout:{"symbol-placement":"point","icon-image":void 0===t?SECTION_START_SIGN_IMAGE_IDS[e]:suffixNumber(SECTION_START_SIGN_IMAGE_IDS[e],t),"icon-size":SIGN_ICON_SIZE,"icon-rotation-alignment":"viewport"}}),sectionLayerID=(e,t)=>`routeSection${e.charAt(0).toUpperCase()+e.slice(1)}${t}`,sectionSignLayerID=e=>sectionLayerID(e,"Sign"),routeWidths=/* @__PURE__ */everyOf()(["s","m","l"]),routeKnobDefinitions={visible:{kind:"toggle",description:"Everything the module draws; hiding it keeps the shown routes and waypoints.",default:!0},color:{kind:"color",description:"Colour of the route line, its darker outline and the waypoint pins. Unset: the map's accent if a theme sets one, else the SDK's blue."},width:{kind:"enum",description:"Thickness preset of the route line, which the section and instruction lines follow.",options:routeWidths,default:"m"},widthFactor:{kind:"factor",description:"Multiplier over the width preset; the instruction arrows and sections without their own follow it.",range:ROUTE_WIDTH_FACTOR_RANGE,default:1},"highlight.outlineWidthFactor":{kind:"factor",description:"Multiplier on the outline width of a hovered or clicked route, selected or not; `1` draws it as any other.",range:ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE,default:1.2},waypointSize:{kind:"enum",description:"Size preset of the waypoint pins and their stop numbers: `s` is 0.75 × `m`, `l` 1.25 × `m`.",options:/* @__PURE__ */everyOf()(["s","m","l"]),default:"m"},waypointSizeFactor:{kind:"factor",description:"Multiplier over the waypoint size preset.",range:ROUTE_WAYPOINT_SIZE_FACTOR_RANGE,default:1},"waypoints.icon.style.fillColor":{kind:"color",description:"Fill colour of the waypoint pins, in place of the route's."},"waypoints.icon.style.outlineColor":{kind:"color",description:"Outline colour of the waypoint pins."},"waypoints.icon.style.outlineOpacity":{kind:"number",description:"Outline opacity of the waypoint pins.",range:OPACITY_RANGE},"waypoints.label.color":{kind:"color",description:"Colour of the waypoint labels. Unset: `#333333`, `#FFFFFF` on a dark map."},"waypoints.label.haloColor":{kind:"color",description:"Colour of the halo around the waypoint labels. Unset: `#FFFFFF`, `#333333` on a dark map."},"waypoints.entryPoints":{kind:"enum",description:"Draw each waypoint at its place's main entry point when it has one, or at its own coordinates.",options:/* @__PURE__ */everyOf()(["main-when-available","ignore"]),default:"ignore"},"displayUnits.distance.type":{kind:"enum",description:"Unit system of the summary bubble distances, and of the speed limit signs on a route without `country` sections. Unset follows the global config.",options:/* @__PURE__ */everyOf()(["metric","imperial_us","imperial_uk"])},"displayUnits.distance.kilometers":{kind:"text",description:"Label after a distance in kilometres. Unset follows the global config, else `km`."},"displayUnits.distance.meters":{kind:"text",description:"Label after a distance in metres. Unset follows the global config, else `m`."},"displayUnits.distance.miles":{kind:"text",description:"Label after a distance in miles. Unset follows the global config, else `mi`."},"displayUnits.distance.feet":{kind:"text",description:"Label after a distance in feet. Unset follows the global config, else `ft`."},"displayUnits.distance.yards":{kind:"text",description:"Label after a distance in yards. Unset follows the global config, else `yd`."},"displayUnits.time.hours":{kind:"text",description:"Label after the hours of a duration. Unset follows the global config, else `hr`."},"displayUnits.time.minutes":{kind:"text",description:"Label after the minutes of a duration. Unset follows the global config, else `min`."},"chargingStops.visible":{kind:"toggle",description:"The charging stop icons and labels along an EV route.",default:!0},"chargingStops.label.visible":{kind:"toggle",description:"The labels beside the charging stop icons.",default:!0},"summaryBubbles.visible":{kind:"toggle",description:"The bubbles giving each route's distance, duration and traffic delay.",default:!0},"countryCrossings.visible":{kind:"toggle",description:"The plaques naming both countries at each border crossing; needs `country` sections.",default:!0},"countryCrossings.minZoom":{kind:"number",description:"Lowest zoom a border crossing plaque is drawn at.",range:ZOOM_RANGE,default:4},"countryCrossings.color":{kind:"color",description:"Colour of the border crossing plaques. Unset follows the map's light/dark theme."},"countryCrossings.textColor":{kind:"color",description:"Label colour of the border crossing plaques. Unset: near-black or near-white, whichever reads."},"countryCrossings.alignment":{kind:"enum",description:"Whether a crossing plaque stays level with the screen or turns to the route's bearing.",options:/* @__PURE__ */everyOf()(["viewport","route"]),default:"viewport"}},sectionKnobDefinitions={visible:e=>({kind:"toggle",description:`The \`${e}\` sections.`,default:sectionEntry(e).visible}),color:e=>({kind:"color",description:`Line colour of the \`${e}\` sections.`}),opacity:e=>({kind:"number",description:`Line opacity of the \`${e}\` sections.`,range:OPACITY_RANGE}),width:e=>({kind:"enum",description:`Line width preset of the \`${e}\` sections; unset follows the route's.`,options:routeWidths}),widthFactor:e=>({kind:"factor",description:`Multiplier over the \`${e}\` sections' width preset; unset follows the route's.`,range:ROUTE_WIDTH_FACTOR_RANGE}),style:e=>({kind:"enum",description:`\`halo\` bands the route along the \`${e}\` sections; \`inline\` replaces its line.`,options:/* @__PURE__ */everyOf()(["halo","inline"]),...defaultOf(sectionEntry(e).style)}),pattern:e=>({kind:"enum",description:`Line pattern of the \`${e}\` sections.`,options:/* @__PURE__ */everyOf()(["solid","dashed","dotted"]),...defaultOf(sectionEntry(e).pattern)}),"icon.image":e=>({kind:"image",description:`Sprite image id of the \`${e}\` sections' icon; an id the sprite lacks draws nothing.`}),"icon.placement":e=>({kind:"enum",description:`Whether the \`${e}\` icon sits once mid-section or repeats along it; set with \`icon.image\`.`,options:/* @__PURE__ */everyOf()(["center","along"]),...defaultOf(isGeneratedSectionType(e)?"center":void 0)}),"icon.sizeFactor":e=>({kind:"factor",description:`Multiplier over the \`${e}\` icon's size; set with \`icon.image\`.`,range:SECTION_ICON_SIZE_FACTOR_RANGE,default:1}),"sign.placement":e=>({kind:"enum",description:`Whether a \`${e}\` sign stands only where the value changes or repeats along the stretch.`,options:/* @__PURE__ */everyOf()(["atChange","along"]),default:"atChange"}),"sign.minZoom":e=>({kind:"number",description:`Lowest zoom the \`${e}\` signs are drawn at.`,range:ZOOM_RANGE,default:10}),"sign.priority":e=>({kind:"enum",description:`What the \`${e}\` signs give way to in a symbol collision; unset follows the placement.`,options:/* @__PURE__ */everyOf()(["belowMapLabels","belowRouteIcons","aboveRouteIcons"])}),"sign.unit":e=>({kind:"enum",description:`Unit every \`${e}\` sign reads in; unset, each follows its country, or the display units without \`country\` sections.`,options:/* @__PURE__ */everyOf()(["km/h","mph"])})},sectionKnobId=(e,t)=>`sections.${e}.${t}`,routingKnobCatalogue=/* @__PURE__ */(()=>{const e=Object.keys(sectionKnobDefinitions),t=t=>e.filter(e=>e===t||e.startsWith(`${t}.`));return[...withIds(routeKnobDefinitions),...drawnSectionTypes.flatMap(e=>sectionEntry(e).knobs.flatMap(t).map(t=>({id:sectionKnobId(e,t),...sectionKnobDefinitions[t](e)})))]})(),routingKnobIds=/* @__PURE__ */routingKnobCatalogue.map(({id:e})=>e),stopDurationLabelSection=[["coalesce",["get","stopDuration"],""],{"text-color":"#727C85","text-font":["literal",["Noto-Regular"]]}],hasStopDuration=["has","stopDuration"],chargingStopTextField=e=>!1===e?.visible?"":e?.title??["format",["get","title"],{},"\n",{},["get","chargingPower"],{}," • ",{},...stopDurationLabelSection],chargingStopSymbol=e=>{const t=buildIconOffsetExpression(((e=[])=>{const t=/* @__PURE__ */new Map;for(const i of e){if(!i.image)continue;const e={x:i.offsetX??0,y:i.offsetY??0};0===e.x&&0===e.y||t.set(i.id,e)}return t})(e?.icon?.customIcons));return{...pinLayerBaseSpec,filter:SELECTED_ROUTE_FILTER,minzoom:4,layout:{...pinLayerBaseSpec.layout,"text-field":chargingStopTextField(e?.label),...t&&{"icon-offset":t}},paint:{...pinLayerBaseSpec.paint}}},commonProps={filter:SELECTED_ROUTE_FILTER,minzoom:16},commonLineLayout={"line-cap":"round"},instructionOutline=e=>({...commonProps,type:"line",layout:commonLineLayout,paint:{"line-width":getInstructionOutlineWidth(e),"line-color":"grey"}}),instructionLine=e=>({...commonProps,type:"line",layout:commonLineLayout,paint:{"line-width":getInstructionLineWidth(e),"line-color":"white"}}),routeFerriesLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round"},paint:{"line-color":"#6dc4ed"}},routeFerriesSymbol={filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:6,maxzoom:16.5,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-image":"poi-ferry_terminal","icon-size":["interpolate",["linear"],["zoom"],6,.8,16.5,1],"icon-ignore-placement":!0}},outlineWidth=(e,t)=>scaledWhen(hasActiveEventState,getLineOutlineWidth(e),t),routeLineBaseTemplate={type:"line",layout:{"line-join":"round","line-cap":"round","line-sort-key":["get","index"]}},routeDeselectedOutline=(e,t=1.2)=>({...routeLineBaseTemplate,filter:DESELECTED_ROUTE_FILTER,paint:{"line-color":"#3C4956","line-width":outlineWidth(e,t)}}),routeDeselectedLine=e=>({...routeLineBaseTemplate,filter:DESELECTED_ROUTE_FILTER,paint:{"line-color":"#ABAFB3","line-width":getLineForegroundWidth(e)}}),routeOutline=(e,t,i=1.2)=>({...routeLineBaseTemplate,filter:SELECTED_ROUTE_FILTER,paint:{"line-color":t??"#105287","line-width":outlineWidth(e,i)}}),routeMainLine=(e,t)=>({...routeLineBaseTemplate,filter:SELECTED_ROUTE_FILTER,paint:{"line-color":t??"#36A8F0","line-width":getLineForegroundWidth(e)}}),routeLineArrows={type:"symbol",layout:{"symbol-placement":"line","icon-image":"roads-arrow-white","icon-rotate":180}},routeTollRoadsOutline={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":"#BEBFFA"}},routeTollRoadsSymbol={filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:4,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-image":"poi-toll_plaza","icon-size":["interpolate",["linear"],["zoom"],4,.8,16.5,1]}},trafficDelayColorKnobIds=[incidentColorKnobIds.minor,incidentColorKnobIds.moderate,incidentColorKnobIds.major],trafficDelayColors=(e={})=>({minor:e[incidentColorKnobIds.minor]??"#FFC105",moderate:e[incidentColorKnobIds.moderate]??"#FB2D09",major:e[incidentColorKnobIds.major]??"#AD0000"}),magnitudeOfDelayTextColor=["match",["get","magnitudeOfDelay"],"minor","#f58240","moderate","#FB2D09","major","#AD0000","indefinite","#666666","#000000"],routeIncidentsDashedLine={type:"line",filter:["in",["get","magnitudeOfDelay"],["literal",["unknown","indefinite"]]],layout:{"line-join":"round"},paint:{"line-color":["match",["get","magnitudeOfDelay"],"unknown","rgba(190, 39, 27, 1)","rgba(137, 150, 168, 1)"],"line-dasharray":[1.5,1]}},routeIncidentsSymbolBase={filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:6,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-ignore-placement":!0}},routeIncidentsJamSymbol={...routeIncidentsSymbolBase,filter:["all",["has","jamIconID"],routeIncidentsSymbolBase.filter],layout:{...routeIncidentsSymbolBase.layout,"icon-image":["get","jamIconID"],"icon-anchor":"bottom-left","text-anchor":"bottom-left","text-field":["get","title"],"text-font":["Noto-Bold"],"text-offset":[3.9,-1.4],"text-size":13},paint:{...routeIncidentsSymbolBase.paint,"text-color":magnitudeOfDelayTextColor,"text-halo-color":"#FFFFFF","text-halo-width":1}},routeIncidentsCauseSymbol={...routeIncidentsSymbolBase,filter:["all",["has","causeIconID"],routeIncidentsSymbolBase.filter],layout:{...routeIncidentsSymbolBase.layout,"icon-image":["get","causeIconID"],"icon-anchor":"bottom-right"},paint:{...routeIncidentsSymbolBase.paint}},routeTunnelsLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round"},paint:{"line-color":"#000000","line-opacity":.3}},routeVehicleRestrictedBackgroundLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round"},paint:{"line-color":"#105287"}},routeVehicleRestrictedDottedLine={filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":"#36A8F0"}},hasFormattedTraffic=["has","formattedTraffic"],buildSummaryBubbleSymbolPoint=e=>{const t=void 0!==e?suffixNumber("selected-route-summary-popup",e):"selected-route-summary-popup",i=void 0!==e?suffixNumber("deselected-route-summary-popup",e):"deselected-route-summary-popup",r=void 0!==e?suffixNumber("traffic-clear",e):"traffic-clear",o=void 0!==e?suffixNumber("traffic-major",e):"traffic-major",s=void 0!==e?suffixNumber("traffic-moderate",e):"traffic-moderate",a=void 0!==e?suffixNumber("traffic-minor",e):"traffic-minor";return{type:"symbol",layout:{"icon-image":["case",SELECTED_ROUTE_FILTER,t,i],"symbol-placement":"point","icon-rotation-alignment":"viewport","text-rotation-alignment":"viewport","symbol-sort-key":["case",SELECTED_ROUTE_FILTER,0,1],"icon-text-fit":"both","icon-text-fit-padding":[10,5,5,10],"text-font":["Noto-Medium"],"text-size":13,"icon-padding":0,"text-justify":"left","text-line-height":1.5,"text-field":["format",["get","formattedDuration"],{"text-font":["literal",["Noto-Bold"]],"text-color":["case",SELECTED_ROUTE_FILTER,"black","#727C85"]},["concat","\t\t",["get","formattedDistance"]],{"text-color":"#727C85"},["case",hasFormattedTraffic,"\n",""],{},["image",["case",hasFormattedTraffic,["match",["get","magnitudeOfDelay"],"major",o,"moderate",s,"minor",a,r],""]],{},["case",hasFormattedTraffic,["concat"," ",["get","formattedTraffic"]],""],{"text-font":["literal",["Noto-Bold"]],"text-color":magnitudeOfDelayTextColor}]},paint:{"icon-translate":[0,-35],"text-translate":[0,-35]}}},summaryBubbleSymbolPoint=buildSummaryBubbleSymbolPoint(),START_INDEX="start",MIDDLE_INDEX="middle",FINISH_INDEX="finish",STOP_DISPLAY_INDEX="stopDisplayIndex",waypointLabelTextField=["format",["coalesce",["get",TITLE],""],{},["case",["all",["has",TITLE],hasStopDuration],"\n",""],{},...stopDurationLabelSection],pinIndexLabelLayout={"text-field":["get","stopDisplayIndex"],"text-font":["Noto-Bold"],"text-size":getWaypointIndexTextSize(),"text-offset":[0,-1.6],"icon-anchor":"bottom","text-allow-overlap":!0},waypointSymbols={type:"symbol",paint:{...pinIconBasePaint,"text-color":"#ffffff"},layout:{...pinIconBaseLayout,...pinIndexLabelLayout,"symbol-sort-key":["abs",["-",["get","index"],1e3]]}},waypointLabels=(e,t)=>{const{textColor:i,haloColor:r}=themeAdaptiveLabelColors(e);return{type:"symbol",paint:{...pinTextBasePaint,"text-color":i,"text-halo-width":1.5,"text-halo-color":r,...labelPaintProperties(t)},layout:{...pinTextBaseLayout,"text-field":waypointLabelTextField,"text-anchor":"top","text-offset":[0,.4],...labelLayoutProperties(t)}}},prefixBeforeID=(e,t)=>e&&t&&(e.startsWith("route")||e.startsWith("waypoint"))?`${t}-${e}`:e,prefixBeforeIDs=(e,t)=>e&&t?Object.fromEntries(Object.entries(e).map(([e,i])=>[e,i?.beforeID?{...i,beforeID:prefixBeforeID(i.beforeID,t)}:i])):e,buildRoutingLayers=(e={},t,i,r="light",o=e=>e,s=trafficDelayColors())=>{const a=(t,i)=>partBeforeLayerIDOf(e.beforeLayerConfig,t,i,o),n=a("mainLines",mapStyleLayerIDs.lowestLabel),l=a("instructionLines",mapStyleLayerIDs.lowestLabel),c=a("icons",mapStyleLayerIDs.lowestLabel),d=a("icons",void 0),u=e.layers,p=u?.sections,h=e.color,y=h?darkerShadeOf(h):void 0,f={width:e.width,widthFactor:e.widthFactor},m=clampFactor(e.highlight?.outlineWidthFactor,ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE,1.2),g=getWaypointIconSize(e.waypointSize,e.waypointSizeFactor),S=getWaypointIndexTextSize(e.waypointSize,e.waypointSizeFactor),L=(b=f,{...commonProps,type:"symbol",layout:{"icon-allow-overlap":!0,"icon-image":"instruction-arrow","icon-rotation-alignment":"map","icon-rotate":["get","lastPointBearingDegrees"],"icon-size":getInstructionArrowSize(b)}});var b;const _=e.sections,I=(e,i,r)=>({...withSectionLineKnobs(e,i,_?.[e],f,r?.role),beforeID:prefixBeforeID(r?.beforeID??sectionStyleAnchor(e,_?.[e]),t)}),E=(e,i,r)=>({...withSectionSymbolKnobs(e,i,_?.[e]),beforeID:prefixBeforeID(r,t)}),T=Object.fromEntries(generatedSectionTypes.map(e=>{const i=_?.[e],r=(e=>sectionLayerID(e,"Line"))(e),o=(e=>sectionLayerID(e,"Symbol"))(e),s=p?.[e];if(postsSign(e)){const r=sectionSignLayerID(e);return[e,{[r]:mergeLayer(sectionSign(e,i),s?.[r]),...prefixBeforeIDs(s?.additional,t)}]}const a=i&&((e,t)=>{if(t.icon&&sectionSupportsKnob(e,"icon"))return withSectionSymbolKnobs(e,{filter:SELECTED_ROUTE_FILTER,type:"symbol",layout:{"symbol-placement":"line-center","icon-allow-overlap":!0,"icon-rotation-alignment":"viewport"}},t)})(e,i);return[e,{[r]:mergeLayer({...sectionLine(e,i,f),beforeID:prefixBeforeID(sectionStyleAnchor(e,i),t)},s?.[r]),...a&&{[o]:mergeLayer({...a,beforeID:c},s?.[o])},...prefixBeforeIDs(s?.additional,t)}]}));return{mainLines:{routeLineArrows:mergeLayer({...routeLineArrows,beforeID:n},u?.mainLines?.routeLineArrows),routeLine:mergeLayer({...routeMainLine(f,h),beforeID:prefixBeforeID("routeIncidentBackgroundLine",t)},u?.mainLines?.routeLine),routeOutline:mergeLayer({...routeOutline(f,y,m),beforeID:prefixBeforeID("routeLine",t)},u?.mainLines?.routeOutline),routeDeselectedLine:mergeLayer({...routeDeselectedLine(f),beforeID:prefixBeforeID("routeOutline",t)},u?.mainLines?.routeDeselectedLine),routeDeselectedOutline:mergeLayer({...routeDeselectedOutline(f,m),beforeID:prefixBeforeID("routeDeselectedLine",t)},u?.mainLines?.routeDeselectedOutline),...prefixBeforeIDs(u?.mainLines?.additional,t)},waypoints:{routeWaypointSymbol:mergeLayer({...waypointSymbols,layout:{...waypointSymbols.layout,"icon-size":g,"text-size":S},beforeID:prefixBeforeID("routeSummaryBubbleSymbol",t)},u?.waypoints?.routeWaypointSymbol),routeWaypointLabel:mergeLayer({...waypointLabels(r,e.waypoints?.label),beforeID:prefixBeforeID("routeWaypointSymbol",t)},u?.waypoints?.routeWaypointLabel),...prefixBeforeIDs(u?.waypoints?.additional,t)},chargingStops:{routeChargingStopSymbol:mergeLayer({...chargingStopSymbol(e.chargingStops),beforeID:prefixBeforeID("routeWaypointSymbol",t)},u?.chargingStops?.routeChargingStopSymbol),...prefixBeforeIDs(u?.chargingStops?.additional,t)},sections:{...T,traffic:{routeIncidentJamSymbol:mergeLayer(E("traffic",routeIncidentsJamSymbol,"routeChargingStopSymbol"),p?.traffic?.routeIncidentJamSymbol),routeIncidentCauseSymbol:mergeLayer(E("traffic",routeIncidentsCauseSymbol,"routeChargingStopSymbol"),p?.traffic?.routeIncidentCauseSymbol),routeIncidentBackgroundLine:mergeLayer(I("traffic",(A=s,{type:"line",layout:{"line-cap":"round"},paint:{"line-color":["match",["get","magnitudeOfDelay"],"minor",A.minor,"moderate",A.moderate,"major",A.major,"#C7D2D8"]}}),{beforeID:"routeIncidentDashedLine"}),p?.traffic?.routeIncidentBackgroundLine),routeIncidentDashedLine:mergeLayer(I("traffic",routeIncidentsDashedLine),p?.traffic?.routeIncidentDashedLine),...prefixBeforeIDs(p?.traffic?.additional,t)},ferry:{routeFerryLine:mergeLayer(I("ferry",routeFerriesLine),p?.ferry?.routeFerryLine),routeFerrySymbol:mergeLayer(E("ferry",routeFerriesSymbol,"routeIncidentJamSymbol"),p?.ferry?.routeFerrySymbol),...prefixBeforeIDs(p?.ferry?.additional,t)},tollRoad:{routeTollRoadOutline:mergeLayer(I("tollRoad",routeTollRoadsOutline),p?.tollRoad?.routeTollRoadOutline),routeTollRoadSymbol:mergeLayer(E("tollRoad",routeTollRoadsSymbol,"routeChargingStopSymbol"),p?.tollRoad?.routeTollRoadSymbol),...prefixBeforeIDs(p?.tollRoad?.additional,t)},tunnel:{routeTunnelLine:mergeLayer(I("tunnel",routeTunnelsLine),p?.tunnel?.routeTunnelLine),routeTunnelSymbol:mergeLayer(E("tunnel",sectionStartSign("tunnel",i),c),p?.tunnel?.routeTunnelSymbol),...prefixBeforeIDs(p?.tunnel?.additional,t)},vehicleRestricted:{routeVehicleRestrictedBackgroundLine:mergeLayer(I("vehicleRestricted",routeVehicleRestrictedBackgroundLine,{beforeID:"routeVehicleRestrictedForegroundLine",role:"outline"}),p?.vehicleRestricted?.routeVehicleRestrictedBackgroundLine),routeVehicleRestrictedForegroundLine:mergeLayer(I("vehicleRestricted",routeVehicleRestrictedDottedLine),p?.vehicleRestricted?.routeVehicleRestrictedForegroundLine),routeVehicleRestrictedSymbol:mergeLayer(E("vehicleRestricted",sectionStartSign("vehicleRestricted",i),"routeIncidentJamSymbol"),p?.vehicleRestricted?.routeVehicleRestrictedSymbol),...prefixBeforeIDs(p?.vehicleRestricted?.additional,t)}},instructionLines:{routeInstructionLine:mergeLayer({...instructionLine(f),beforeID:l},u?.instructionLines?.routeInstructionLine),routeInstructionOutline:mergeLayer({...instructionOutline(f),beforeID:prefixBeforeID("routeInstructionLine",t)},u?.instructionLines?.routeInstructionOutline),...prefixBeforeIDs(u?.instructionLines?.additional,t)},instructionArrows:{routeInstructionArrowSymbol:mergeLayer({...L,beforeID:prefixBeforeID("routeInstructionLine",t),...void 0!==i&&{layout:{...L.layout,"icon-image":suffixNumber("instruction-arrow",i)}}},u?.instructionArrows?.routeInstructionArrowSymbol),...prefixBeforeIDs(u?.instructionArrows?.additional,t)},summaryBubbles:{routeSummaryBubbleSymbol:mergeLayer({...void 0===i?summaryBubbleSymbolPoint:buildSummaryBubbleSymbolPoint(i),...d&&{beforeID:d}},u?.summaryBubbles?.routeSummaryBubbleSymbol),...prefixBeforeIDs(u?.summaryBubbles?.additional,t)},countryCrossings:{[COUNTRY_CROSSING_LAYER_ID]:mergeLayer({...countryCrossingSymbol(i,e.countryCrossings,resolveCountryCrossingColors(e.countryCrossings,r)),beforeID:prefixBeforeID("routeWaypointSymbol",t)},u?.countryCrossings?.routeCountryCrossing),...prefixBeforeIDs(u?.countryCrossings?.additional,t)}};var A},defaultRoutingLayers=buildRoutingLayers();isDOMImageSupported()&&(instructionArrowIconImg=svgToImg(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">\n <path d="M1.562 40.569L25 1.562l23.438 39.007L25 27.566 1.562 40.569z" fill="#fff"/>\n <path d="M25.369.107c.782.429.506.167.917.682l23.438 39.007c.79 1.316-.671 2.829-2.014 2.085L25 29.281l-22.71 12.6c-1.343.744-2.804-.769-2.014-2.085L23.714.789c.461-.694.9-.682 1.656-.682zM25 1.562L1.562 40.569 25 27.566l23.438 13.003L25 1.562z"\n fill="gray"/>\n</svg>\n')));var cachedImg,summaryMapBubbleImg=e=>{if(!isDOMImageSupported())return;const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="65">\n <g filter="url(#A)">\n <rect id="pin" x="81.899" y="47" width="10" height="10" rx="2" transform="rotate(45 81.899 47)"/>\n <rect id="bubble" x="10" y="10" width="140" height="45" rx="12"/>\n </g>\n <defs>\n <filter id="A">\n <feDropShadow dx="0" dy="2" stdDeviation="4" flood-opacity=".3"/>\n </filter>\n </defs>\n</svg>\n');return t.querySelector("#bubble")?.setAttribute("fill",e),t.querySelector("#pin")?.setAttribute("fill",e),svgToImg(t)},summaryBubbleImageOptions={pixelRatio:2,stretchX:[[20,45],[100,130]],stretchY:[[20,35]],content:[10,10,130,45]},countryCrossingPlaqueImageOptions={pixelRatio:2,stretchX:[[30,110]],stretchY:[[25,35]],content:[10,10,130,50]},countryCrossingPlaqueImg=e=>{if(!isDOMImageSupported())return;const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="140" height="60">\n <g filter="url(#shadow)">\n <rect id="plaque" x="10" y="10" width="120" height="40" rx="8"/>\n </g>\n <defs>\n <filter id="shadow">\n <feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity=".35"/>\n </filter>\n </defs>\n</svg>\n');return t.querySelector("#plaque")?.setAttribute("fill",e),svgToImg(t)},roundSignSvg=(e,t,i)=>`<svg xmlns="http://www.w3.org/2000/svg" width="92" height="92" viewBox="0 0 46 46"><circle cx="23" cy="23" r="${22-i/2}" fill="${e}" stroke="${t}" stroke-width="${i}"/></svg>`,WHITE_DISC_SVG=roundSignSvg("#fff","#D0021B",5),SPEED_LIMIT_SIGN_SVGS={whiteDisc:WHITE_DISC_SVG,yellowDisc:roundSignSvg("#FFCE00","#D0021B",5),plaque:'<svg xmlns="http://www.w3.org/2000/svg" width="92" height="92" viewBox="0 0 46 46"><rect x="7" y="3" width="32" height="40" rx="2" fill="#fff" stroke="#1A2024" stroke-width="2"/><text x="23" y="13" fill="#1A2024" font-family="sans-serif" font-size="7" font-weight="bold" text-anchor="middle">SPEED</text><text x="23" y="21" fill="#1A2024" font-family="sans-serif" font-size="7" font-weight="bold" text-anchor="middle">LIMIT</text></svg>\n'},SECTION_START_SIGN_SVGS={tunnel:'<svg xmlns="http://www.w3.org/2000/svg" width="92" height="92" viewBox="0 0 46 46"><rect x="2.5" y="2.5" width="41" height="41" rx="8" fill="#1F5FAD" stroke="#fff" stroke-width="3"/><path fill="#fff" d="M10 36V24a13 13 0 0 1 26 0v12h-6V24.5a7 7 0 0 0-14 0V36z"/></svg>\n',vehicleRestricted:WHITE_DISC_SVG},signImg=e=>{if(isDOMImageSupported())return svgToImg(parseSvg(e))},sectionStartSignImg=e=>signImg(SECTION_START_SIGN_SVGS[e]),speedLimitSignImg=e=>signImg(SPEED_LIMIT_SIGN_SVGS[e]),trafficImg=e=>{if(!isDOMImageSupported())return;const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32">\n <g id="main">\n <path fill-rule="evenodd"\n d="M11.389 4H9.025a.86.86 0 0 0-.517.173l-.001-.001a.5.5 0 0 1-.464.059l-.028-.011a.5.5 0 0 1-.129-.83A1.86 1.86 0 0 1 9.025 3h2.364a2 2 0 0 1 1.789 1.106l1.02 2.04c.471.176.802.63.802 1.156v.803c0 .543 0 .815-.071 1.038a1.5 1.5 0 0 1-.914.953c-.219.08-.491.092-1.034.114l-1.481.062v-.166-.803a2.23 2.23 0 0 0-1.055-1.897l-.74-1.479 2.326.033h.955l-.703-1.406A1 1 0 0 0 11.389 4zM12 8.4a1 1 0 1 1 2 0 .5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5z"/>\n <path d="M11.833 11.115c0-.109.089-.198.198-.198h1.979c.109 0 .198.089.198.198 0 .328-.266.594-.594.594h-1.187c-.328 0-.594-.266-.594-.594z"/>\n <path fill-rule="evenodd"\n d="M1.802 8.146C1.331 8.321 1 8.776 1 9.302v.803c0 .543 0 .815.071 1.038a1.5 1.5 0 0 0 .914.953c.219.08.491.092 1.034.114l2.731.114 2.731-.114c.543-.023.814-.034 1.034-.114a1.5 1.5 0 0 0 .914-.953c.071-.223.071-.494.071-1.038v-.803c0-.526-.331-.98-.802-1.156l-1.02-2.04A2 2 0 0 0 6.889 5H4.611a2 2 0 0 0-1.789 1.106l-1.02 2.04zM6.889 6H4.611a1 1 0 0 0-.894.553l-.703 1.406h.955 3.563.955l-.703-1.406A1 1 0 0 0 6.889 6zM2 10.4a1 1 0 1 1 2 0 .5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm6.5-1a1 1 0 0 0-1 1 .5.5 0 0 0 .5.5h1a.5.5 0 0 0 .5-.5 1 1 0 0 0-1-1z"/>\n <path d="M1.792 13.115c0-.109.089-.198.198-.198h1.979c.109 0 .198.089.198.198 0 .328-.266.594-.594.594H2.385c-.328 0-.594-.266-.594-.594zm5.739-.198c-.109 0-.198.089-.198.198 0 .328.266.594.594.594h1.188c.328 0 .594-.266.594-.594 0-.109-.089-.198-.198-.198h-1.98z"/>\n </g>\n</svg>\n'),i=t.querySelector("#main");return i.setAttribute("transform","scale(2)"),i.setAttribute("fill",e),svgToImg(t)},waypointIcon=(e,t)=>{if(!isDOMImageSupported())return;const i=pinSvg(t);return e&&i.appendChild(e),svgToImg(i)},waypointStartIcon=e=>{if(isDOMImageSupported())return waypointIcon(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140">\n <path d="M63.734 86.383c-1.404.026-2.78-.393-3.93-1.197s-2.01-1.949-2.46-3.271l-3.15-9.339c-1.093-3.403-3.748-6.089-7.154-7.238L37.5 62.21c-2.742-.902-4.567-3.477-4.5-6.345-.058-2.874 1.761-5.457 4.5-6.388l36-11.886c2.461-.88 5.213-.27 7.062 1.567s2.466 4.571 1.578 7.015L70.17 81.918c-.938 2.719-3.54 4.526-6.436 4.469h0z"\n fill="#f4f5f6"/>\n</svg>\n'),e)},waypointFinishIcon=e=>{if(isDOMImageSupported())return waypointIcon(parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140">\n <path d="M33 83.404a2.99 2.99 0 0 1-3-2.978V44.681a2.99 2.99 0 1 1 6 0v35.745a2.99 2.99 0 0 1-3 2.978zm48-38.723H39v17.872h42V44.681zm3.878 37.851a3.02 3.02 0 0 0 4.244 0c.561-.559.878-1.317.878-2.106V44.681a2.99 2.99 0 1 0-6 0v35.745c0 .789.317 1.547.878 2.106z"\n fill="#f4f5f6"/>\n</svg>\n'),e)},bearingAtCrossing=(e,t)=>{const i=e[t-1]??e[t],r=e[t+1]??e[t];return i===r?0:(bearing(i,r)+360)%360},toCrossingFeature=(e,t,i,r)=>{const o=generateId();return{type:"Feature",id:o,geometry:{type:"Point",coordinates:i[t.startPointIndex]},properties:{id:o,fromCountryCode:e.countryCodeISO2,toCountryCode:t.countryCodeISO2,label:`${e.countryCodeISO2} → ${t.countryCodeISO2}`,bearing:bearingAtCrossing(i,t.startPointIndex),fromSectionStartPointIndex:e.startPointIndex,toSectionStartPointIndex:t.startPointIndex,routeState:r.routeState,routeIndex:r.index}}},crossingsOfRoute=e=>{const t=e.properties.sections.country;if(!t?.length)return[];const i=[...t].sort((e,t)=>e.startPointIndex-t.startPointIndex),r=e.geometry.coordinates;return i.slice(1).flatMap((t,o)=>r[t.startPointIndex]?[toCrossingFeature(i[o],t,r,e.properties)]:[])},toDisplayCountryCrossings=e=>({type:"FeatureCollection",features:e.features.flatMap(crossingsOfRoute)}),getIconID=(e,t)=>{const i=t?.chargingStops?.icon;if(i?.mapping){const t=i.mapping;switch(t.basedOn){case"chargingSpeed":if(e.properties.chargingConnectionInfo?.chargingSpeed)return t.value[e.properties.chargingConnectionInfo?.chargingSpeed];break;case"custom":return t.fn(e)}}return toPinSpriteImageID("7309")},formatTitle=e=>{const t=e.properties;return t.chargingParkName??t.chargingParkOperatorName},hasJam=e=>e.categories.includes("jam"),toDisplayTrafficSectionProps=e=>{const t=(e=>{if(hasJam(e))return formatDuration(e.delayInSeconds)})(e),i=((e,t)=>hasJam(e)?`traffic-jam-${e.magnitudeOfDelay??"unknown"}-${(e=>e?.length?e.length<6?"small":e.length<8?"medium":"large":"collapsed")(t)}`:null)(e,t),r=(e=>{const t=e.categories.find(e=>"jam"!==e);return t?(e=>{switch(e){case"accident":return"traffic-incidents-accident";case"roadworks":return"traffic-incidents-roadworks";case"road-closed":return"traffic-incidents-road_closed";case"lane-closed":case"narrow-lanes":return"traffic-incidents-lane_closed";case"danger":case"animals-on-road":return"traffic-incidents-danger";case"broken-down-vehicle":return"traffic-incidents-broken_down_vehicle";case"wind":return"traffic-incidents-wind";case"fog":return"traffic-incidents-fog";case"rain":return"traffic-incidents-rain";case"frost":return"traffic-incidents-frost";case"flooding":return"traffic-incidents-flooding";default:return null}})(t):null})(e);return{...e,...i&&{jamIconID:i},...r&&{causeIconID:r},...t&&{title:t}}},getImageIDForWaypoint=(e,t,i)=>{let r;switch(t){case"start":r="waypointStart";break;case"finish":r="waypointFinish";break;default:r="waypointStop"}return void 0!==i?suffixNumber(r,i):r},toDisplayWaypoints=(e,t,i,r)=>({type:"FeatureCollection",features:e.map((o,s)=>{if(!o)return null;const a=(e=>{return Array.isArray(e)?{type:"Feature",geometry:{type:"Point",coordinates:e},properties:{}}:"Point"===e.type?{type:"Feature",geometry:t=e,properties:{},...t.bbox&&{bbox:t.bbox}}:e;var t})(o),n=((e,t)=>0===e?"start":e<t-1?"middle":"finish")(s,e.length),l=(e=>{const t=e?.properties;return t?.poi?.name??t?.address?.freeformAddress??void 0})(a),c=a.id??generateId(),d=formatDuration(a.properties.pauseDurationSeconds,r);return{...a,..."main-when-available"===t?.entryPoints&&{geometry:{type:"Point",coordinates:getPosition(a,{useEntryPoint:"main-when-available"})}},id:c,properties:{...a.properties,id:c,index:s,indexType:n,...l&&{title:l},...d&&{stopDuration:d},iconID:getImageIDForWaypoint(0,n,i),..."middle"===n&&{stopDisplayIndex:s}}}}).filter(e=>e)}),toDisplayRouteSections=(e,t,i)=>({type:"FeatureCollection",features:e.features.flatMap(e=>((e,t,i)=>e.properties.sections[t]?.map(t=>{const r=t.id??generateId();return{type:"Feature",id:r,geometry:{type:"LineString",coordinates:e.geometry.coordinates.slice(t.startPointIndex,t.endPointIndex+1)},properties:{...i?i(t,e.properties):t,routeState:e.properties.routeState,routeIndex:e.properties.index,id:r}}})||[])(e,t,i))}),showFeaturesWithRouteSelection=(e,t)=>t.show(((e,t)=>({...t,features:t.features.map(t=>({...t,properties:{...t.properties,routeState:e.features[t.properties.routeIndex||0].properties.routeState}}))}))(e,t.shownFeatures)),toDisplayRoutes=(e,t=0)=>{const i="features"in e?e:{type:"FeatureCollection",features:[e]};return{...i,features:i.features.map((e,i)=>{const r=e.id??generateId();return{...e,id:r,properties:{...e.properties,id:r,routeState:i===t?"selected":"deselected"}}})}},hasMagnitude=(e,t)=>e.some(e=>e.magnitudeOfDelay===t),toDisplayRouteSummaries=(e,t)=>({type:"FeatureCollection",features:e.features.map(e=>{const i=e.properties.summary,r=e.geometry.coordinates,o=formatDuration(i.trafficDelayInSeconds,t?.time),s=(e=>{const t=e.properties.sections.traffic;if(t?.length)return hasMagnitude(t,"major")?"major":hasMagnitude(t,"moderate")?"moderate":hasMagnitude(t,"minor")?"minor":void 0})(e),a=e.id??generateId();return{type:"Feature",id:a,geometry:{type:"Point",coordinates:r[Math.round(r.length/2)]},properties:{id:a,routeIndex:e.properties.index,routeState:e.properties.routeState,formattedDistance:formatDistance(i.lengthInMeters,t?.distance),...s&&{magnitudeOfDelay:s},...o&&{formattedTraffic:o},formattedDuration:formatDuration(i.travelTimeInSeconds,t?.time)}}})}),SIGN_BY_COUNTRY={GBR:{unit:"mph"},LBR:{unit:"mph"},MMR:{unit:"mph"},USA:{face:"plaque",unit:"mph"},SWE:{face:"yellowDisc"},FIN:{face:"yellowDisc"},ISL:{face:"yellowDisc"},JPN:{numerals:"#0B5FA5"}},SIGN_BY_DISPLAY_UNITS={metric:{},imperial_uk:{unit:"mph"},imperial_us:{face:"plaque",unit:"mph"}},SPEED_LIMIT_IMAGE_ID_BY_FACE={whiteDisc:"routeSpeedLimitWhiteDisc",yellowDisc:"routeSpeedLimitYellowDisc",plaque:"routeSpeedLimitPlaque"},postedSpeedLimit=(e,t)=>"mph"===t?5*Math.round(1e3*e/MILE_IN_METERS/5):e,RoutingModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i)}constructor(e,t){super(e,t),this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&(this.config=this._applyConfig(this.config))}),onStylingKnobsApplied(e,trafficDelayColorKnobIds,()=>this.repaintTrafficSections())}repaintTrafficSections(){const{incidents:e}=this.buildLayersSpecs(this.config);isEqual(e,this.layersSpecs.incidents)||(updateLayersAndSource(e,this.layersSpecs.incidents,this.sourcesWithLayers.incidents,this.mapLibreMap),this.layersSpecs={...this.layersSpecs,incidents:e})}routeColorOf(e){return e?.color??mapAccentColor(this.tomtomMap)}buildLayersSpecs(e){return((e={},t)=>({...Object.fromEntries(generatedSectionTypes.map(i=>[sectionSourceKey(i),mapLayerSpecs(e.sections?.[i],t)])),mainLines:mapLayerSpecs(e.mainLines,t),waypoints:mapLayerSpecs(e.waypoints,t),chargingStops:mapLayerSpecs(e?.chargingStops,t),ferries:mapLayerSpecs(e.sections?.ferry,t),incidents:mapLayerSpecs(e.sections?.traffic,t),tollRoads:mapLayerSpecs(e.sections?.tollRoad,t),tunnels:mapLayerSpecs(e.sections?.tunnel,t),vehicleRestricted:mapLayerSpecs(e.sections?.vehicleRestricted,t),instructionLines:mapLayerSpecs(e.instructionLines,t),instructionArrows:mapLayerSpecs(e.instructionArrows,t),summaryBubbles:mapLayerSpecs(e.summaryBubbles,t),countryCrossings:mapLayerSpecs(e.countryCrossings,t)}))(buildRoutingLayers({...e,color:this.routeColorOf(e)},this.layerIDPrefix,this.instanceIndex,this.tomtomMap.styleLightDarkTheme,e=>existingBeforeLayerID(this.mapLibreMap,e),trafficDelayColors(this.tomtomMap._stylingSettings)),this.layerIDPrefix)}createSourcesWithLayers(e){const t=suffixNumber("routes",this.instanceIndex);return{...Object.fromEntries(generatedSectionTypes.map(i=>{const r=sectionSourceKey(i);return[r,new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-${r}`,e[r],!1)]})),mainLines:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-mainLines`,e.mainLines,!1),waypoints:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-waypoints`,e.waypoints,!1),incidents:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-incidents`,e.incidents,!1),ferries:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-ferries`,e.ferries,!1),chargingStops:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-chargingStops`,e.chargingStops,!1),tollRoads:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-tollRoads`,e.tollRoads,!1),tunnels:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-tunnels`,e.tunnels,!1),vehicleRestricted:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-vehicleRestricted`,e.vehicleRestricted,!1),instructionLines:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-instructionLines`,e.instructionLines,!1),instructionArrows:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-instructionArrows`,e.instructionArrows,!1),summaryBubbles:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-summaryBubbles`,e.summaryBubbles,!1),countryCrossings:new GeoJSONSourceWithLayers(this.mapLibreMap,`${t}-countryCrossings`,e.countryCrossings,!1)}}_initSourcesWithLayers(e,t){t||(this.layerIDPrefix=suffixNumber("routes",this.instanceIndex));const i=this.routeColorOf(e);this.layersSpecs=this.buildLayersSpecs(e);const r=this.createSourcesWithLayers(this.layersSpecs);addLayers(Object.values(r).flatMap(e=>e._layerSpecs),this.mapLibreMap),this.appliedRouteColor=i;const o={fillColor:i,...e?.waypoints?.icon?.style},s={pixelRatio:2},a=suffixNumber("waypointStart",this.instanceIndex),n=suffixNumber("waypointStop",this.instanceIndex),l=suffixNumber("waypointFinish",this.instanceIndex),c=suffixNumber("instruction-arrow",this.instanceIndex),d=suffixNumber("selected-route-summary-popup",this.instanceIndex),u=suffixNumber("deselected-route-summary-popup",this.instanceIndex),p=suffixNumber("traffic-clear",this.instanceIndex),h=suffixNumber("traffic-major",this.instanceIndex),y=suffixNumber("traffic-moderate",this.instanceIndex),f=suffixNumber("traffic-minor",this.instanceIndex);this.addImageIfNotExisting(a,waypointStartIcon(o),s),this.addImageIfNotExisting(n,waypointIcon(void 0,o),s),this.addImageIfNotExisting(l,waypointFinishIcon(o),s),this.addImageIfNotExisting(c,instructionArrowIconImg,s),this.addImageIfNotExisting(d,summaryMapBubbleImg("white"),summaryBubbleImageOptions),this.addImageIfNotExisting(u,summaryMapBubbleImg("#EEEEEE"),summaryBubbleImageOptions);for(const[m,g]of Object.entries(SPEED_LIMIT_IMAGE_ID_BY_FACE))this.addImageIfNotExisting(suffixNumber(g,this.instanceIndex),speedLimitSignImg(m),s);for(const[m,g]of Object.entries(SECTION_START_SIGN_IMAGE_IDS))this.addImageIfNotExisting(suffixNumber(g,this.instanceIndex),sectionStartSignImg(m),s);this.appliedCrossingColors=void 0,this.addImageIfNotExisting(suffixNumber("route-country-crossing-plaque",this.instanceIndex),countryCrossingPlaqueImg(this.crossingColors(this.config).plaque),{...s,...countryCrossingPlaqueImageOptions}),this.addImageIfNotExisting(p,trafficImg("#000000"),s),this.addImageIfNotExisting(h,trafficImg("#AD0000"),s),this.addImageIfNotExisting(y,trafficImg("#FB2D09"),s),this.addImageIfNotExisting(f,trafficImg("#f58240"),s);for(const m of e?.chargingStops?.icon?.customIcons??[])this.addImageIfNotExisting(m.id,m.image,{pixelRatio:m.pixelRatio??2});return r}_applyConfig(e){const t=routeDisplayUnits(e),i=!isEqual(this.appliedDisplayUnits,t);this.appliedDisplayUnits=t;const r=this.routeColorOf(e);if(!this._initializing){const t=this.buildLayersSpecs(e);Object.keys(t).forEach(e=>{const i=e;updateLayersAndSource(t[i],this.layersSpecs[i],this.sourcesWithLayers[i],this.mapLibreMap)});const r=Object.values(this.sourcesWithLayers);addLayers(r.flatMap(e=>e._layerSpecs),this.mapLibreMap,!isEqual(this.config?.beforeLayerConfig,e?.beforeLayerConfig)),this.reshowSpeedLimitSigns(e,i),this.applySignPriority(e),this.layersSpecs=t}const o=r!==this.appliedRouteColor;if(this.appliedRouteColor=r,o){const t={fillColor:r,...e?.waypoints?.icon?.style},i={pixelRatio:2};addOrUpdateImage("add-or-update",suffixNumber("waypointStart",this.instanceIndex),waypointStartIcon(t),this.mapLibreMap,i),addOrUpdateImage("add-or-update",suffixNumber("waypointStop",this.instanceIndex),waypointIcon(void 0,t),this.mapLibreMap,i),addOrUpdateImage("add-or-update",suffixNumber("waypointFinish",this.instanceIndex),waypointFinishIcon(t),this.mapLibreMap,i)}const s=!1!==e?.summaryBubbles?.visible,a=!isEqual(this.config?.summaryBubbles?.visible,e?.summaryBubbles?.visible),n=this.sourcesWithLayers.summaryBubbles.shownFeatures.features.length>0,l=this.sourcesWithLayers.mainLines.shownFeatures.features.length>0;return!s&&a?this.sourcesWithLayers.summaryBubbles.clear():s&&(a&&l||i&&n)&&this.sourcesWithLayers.summaryBubbles.show(toDisplayRouteSummaries(this.sourcesWithLayers.mainLines.shownFeatures,t)),this.applyCountryCrossingConfig(e),this.applyVisibility(e),e}showSpeedLimitSections(e,t){var i,r;this.sourcesWithLayers.speedLimitSections.show(toDisplayRouteSections(e,"speedLimit",(i=this.instanceIndex,r={unit:t?.sections?.speedLimit?.sign?.unit,displayUnits:routeDisplayUnits(t)},(e,t)=>{const o=(s=e.startPointIndex,a=t?.sections.country,a?.find(e=>s>=e.startPointIndex&&s<=e.endPointIndex)?.countryCodeISO3);var s,a;const n=o?SIGN_BY_COUNTRY[o]??{}:SIGN_BY_DISPLAY_UNITS[r?.displayUnits?.distance?.type??TomTomConfig.instance.get().displayUnits?.distance?.type??"metric"],l=n.face??"whiteDisc",c=r?.unit??n.unit??"km/h";return{...e,signImageID:suffixNumber(SPEED_LIMIT_IMAGE_ID_BY_FACE[l],i),signLabel:String(postedSpeedLimit(e.maxSpeedLimitInKmh,c)),signFace:l,signNumeralsColor:n.numerals??"#1A2024"}})))}crossingColors(e){return resolveCountryCrossingColors(e?.countryCrossings,this.tomtomMap.styleLightDarkTheme)}applyCountryCrossingConfig(e){const t=!1!==e?.countryCrossings?.visible,i=!isEqual(this.config?.countryCrossings?.visible,e?.countryCrossings?.visible);!t&&i?this.sourcesWithLayers.countryCrossings.clear():t&&i&&this.sourcesWithLayers.countryCrossings.show(toDisplayCountryCrossings(this.sourcesWithLayers.mainLines.shownFeatures));const r=this.crossingColors(e);if(isEqual(this.appliedCrossingColors,r))return;this.appliedCrossingColors=r,addOrUpdateImage("add-or-update",suffixNumber("route-country-crossing-plaque",this.instanceIndex),countryCrossingPlaqueImg(r.plaque),this.mapLibreMap,countryCrossingPlaqueImageOptions);const o=prefixLayerID("routeCountryCrossing",this.layerIDPrefix);this.mapLibreMap.getLayer(o)&&this.mapLibreMap.setPaintProperty(o,"text-color",r.text,{validate:!1})}reshowSpeedLimitSigns(e,t){isEqual(this.config?.sections?.speedLimit?.sign?.unit,e?.sections?.speedLimit?.sign?.unit)&&!t||this.sourcesWithLayers.speedLimitSections.shownFeatures.features.length&&this.showSpeedLimitSections(this.sourcesWithLayers.mainLines.shownFeatures,e)}applyVisibility(e){const t=!1!==e?.visible;for(const i of Object.values(this.sourcesWithLayers))i.setLayersVisible(t&&!!i.shownFeatures.features.length);for(const i of drawnSectionTypes)isSectionVisible(i,e?.sections?.[i])||this.sourcesWithLayers[sectionSourceKey(i)].setLayersVisible(!1)}signLayerID(e){if(postsSign(e))return prefixLayerID(sectionSignLayerID(e),this.layerIDPrefix)}applySignPriority(e){for(const t of generatedSectionTypes){const i=this.signLayerID(t);if(!i||!this.mapLibreMap.getLayer(i))continue;const r=e?.sections?.[t];this.mapLibreMap.moveLayer(i,this.signAnchorLayerID(i,r))}}signAnchorLayerID(e,t){const i=(e=>e?.sign?.priority??("atChange"===signPlacement(e)?"belowRouteIcons":"belowMapLabels"))(t);if("aboveRouteIcons"===i)return;const r=this.mapLibreMap.getStyle().layers;if("belowMapLabels"===i)return mapStyleLayerIDs.lowestLabel;const o=r.findIndex(e=>e.id===mapStyleLayerIDs.lowestLabel),s=new Set(["routeLineArrows","routeInstructionArrowSymbol"].map(e=>prefixLayerID(e,this.layerIDPrefix)));return r.find((t,i)=>"symbol"===t.type&&t.id!==e&&!s.has(t.id)&&i>o&&(!this.layerIDPrefix||t.id.startsWith(this.layerIDPrefix)))?.id}discardShownData(){}restoreDataAndConfigImpl(){const e=Object.fromEntries(Object.entries(this.sourcesWithLayers).map(([e,t])=>[e,t.shownFeatures]));this.initSourcesWithLayers(this.config,!0),this._applyConfig(this.config);for(const t of Object.keys(e))this.sourcesWithLayers[t].show(e[t]);this.applyVisibility(this.config)}addImageIfNotExisting(e,t,i){addOrUpdateImage("if-not-in-sprite",e,t,this.mapLibreMap,i)}async showRoutes(e,t){const i=toDisplayRoutes(e,t?.selectedIndex);await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.show(i),this.sourcesWithLayers.vehicleRestricted.show(toDisplayRouteSections(i,"vehicleRestricted")),this.sourcesWithLayers.incidents.show(toDisplayRouteSections(i,"traffic",toDisplayTrafficSectionProps)),this.sourcesWithLayers.chargingStops.show(((e,t)=>{const i=[];if(!1!==t?.chargingStops?.visible)for(const r of e.features)for(const e of r.properties.sections.leg){const o=e.summary.chargingInformationAtEndOfLeg;if(o){const s=o.properties,a=formatDuration(e.summary.stopTimeInSeconds??s.chargingTimeInSeconds,t?.displayUnits?.time);i.push({...o,properties:{...o.properties,id:o.properties.chargingParkId??generateId(),iconID:getIconID(o,t),title:formatTitle(o),chargingPower:`${s.chargingConnectionInfo?.chargingPowerInkW} kW`,chargingDuration:formatDuration(s.chargingTimeInSeconds,t?.displayUnits?.time),...a&&{stopDuration:a},routeState:r.properties.routeState,routeIndex:r.properties.index}})}}return{type:"FeatureCollection",features:i}})(i,this.config)),this.sourcesWithLayers.ferries.show(toDisplayRouteSections(i,"ferry")),this.sourcesWithLayers.tunnels.show(toDisplayRouteSections(i,"tunnel")),this.sourcesWithLayers.tollRoads.show(toDisplayRouteSections(i,"tollRoad"));for(const r of generatedSectionTypes)postsSign(r)||this.sourcesWithLayers[sectionSourceKey(r)].show(toDisplayRouteSections(i,r));this.showSpeedLimitSections(i,this.config),this.applySignPriority(this.config),this.sourcesWithLayers.instructionLines.show((e=>({type:"FeatureCollection",features:e.features.flatMap((e,t)=>e.properties.guidance?.instructions?.filter(e=>e.routePath?.length).map(i=>({type:"Feature",geometry:{type:"LineString",coordinates:i.routePath.map(e=>e.point)},properties:{...i,id:generateId(),routeIndex:t,routeState:e.properties.routeState}}))||[])}))(i)),this.sourcesWithLayers.instructionArrows.show((e=>({type:"FeatureCollection",features:e.features.flatMap((e,t)=>e.properties.guidance?.instructions?.filter(e=>e.routePath?.length&&e.routePath.length>1).map(i=>{const r=[i.routePath[i.routePath.length-2]?.point,i.routePath[i.routePath.length-1]?.point];return{type:"Feature",geometry:{type:"Point",coordinates:r[1]},properties:{...i,id:generateId(),routeIndex:t,routeState:e.properties.routeState,lastPointBearingDegrees:bearing(r[0],r[1])}}})||[])}))(i)),!1!==this.config?.countryCrossings?.visible?this.sourcesWithLayers.countryCrossings.show(toDisplayCountryCrossings(i)):this.sourcesWithLayers.countryCrossings.clear(),!1!==this.config?.summaryBubbles?.visible?this.sourcesWithLayers.summaryBubbles.show(toDisplayRouteSummaries(i,routeDisplayUnits(this.config))):this.sourcesWithLayers.summaryBubbles.clear(),this.applyVisibility(this.config);for(const r of this.shownFeaturesHandlers)r({routes:e})}async clearRoutes(){await this.waitUntilModuleReady();for(const e of Object.keys(this.sourcesWithLayers))"waypoints"!==e&&this.sourcesWithLayers[e].clear()}async selectRoute(e){const t=toDisplayRoutes(this.sourcesWithLayers.mainLines.shownFeatures,e);await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.show(t),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.chargingStops),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.vehicleRestricted),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.incidents),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.ferries),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.tollRoads);for(const i of generatedSectionTypes)showFeaturesWithRouteSelection(t,this.sourcesWithLayers[sectionSourceKey(i)]);showFeaturesWithRouteSelection(t,this.sourcesWithLayers.tunnels),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionLines),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionArrows),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.summaryBubbles),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.countryCrossings),this.applyVisibility(this.config)}async showWaypoints(e){const t=routeDisplayUnits(this.config)?.time,i=Array.isArray(e)?toDisplayWaypoints(e,this.config?.waypoints,this.instanceIndex,t):toDisplayWaypoints(e.features,this.config?.waypoints,this.instanceIndex,t);await this.waitUntilModuleReady(),this.sourcesWithLayers.waypoints.show(i),this.applyVisibility(this.config),this.applySignPriority(this.config);for(const r of this.shownFeaturesHandlers)r({waypoints:e})}async clearWaypoints(){await this.waitUntilModuleReady(),this.sourcesWithLayers.waypoints.clear()}getShown(){return{mainLines:this.sourcesWithLayers.mainLines.shownFeatures,waypoints:this.sourcesWithLayers.waypoints.shownFeatures,incidents:this.sourcesWithLayers.incidents.shownFeatures,ferries:this.sourcesWithLayers.ferries.shownFeatures,chargingStops:this.sourcesWithLayers.chargingStops.shownFeatures,tollRoads:this.sourcesWithLayers.tollRoads.shownFeatures,...Object.fromEntries(generatedSectionTypes.map(e=>[sectionSourceKey(e),this.sourcesWithLayers[sectionSourceKey(e)].shownFeatures])),tunnels:this.sourcesWithLayers.tunnels.shownFeatures,vehicleRestricted:this.sourcesWithLayers.vehicleRestricted.shownFeatures,instructionLines:this.sourcesWithLayers.instructionLines.shownFeatures,instructionArrows:this.sourcesWithLayers.instructionArrows.shownFeatures,summaryBubbles:this.sourcesWithLayers.summaryBubbles.shownFeatures,countryCrossings:this.sourcesWithLayers.countryCrossings.shownFeatures}}eventStateSources(){return["mainLines"]}get events(){const e=Object.fromEntries(generatedSectionTypes.map(e=>[sectionSourceKey(e),this.userEventsWithStates([sectionSourceKey(e)])]));return this.buildEvents(this.moduleEventsWithShown(["mainLines","waypoints","chargingStops","summaryBubbles","countryCrossings","incidents","vehicleRestricted","ferries","tollRoads","tunnels","instructionLines",...generatedSectionTypes.map(sectionSourceKey)],this.shownFeaturesHandlers),{...e,mainLines:this.userEventsWithStates(["mainLines"]),waypoints:this.userEventsWithStates(["waypoints"]),chargingStops:this.userEventsWithStates(["chargingStops"]),summaryBubbles:this.userEventsWithStates(["summaryBubbles"]),countryCrossings:this.userEventsWithStates(["countryCrossings"],{mapping:e=>((e,t)=>{const i=e.properties,r=t.features[i.routeIndex]?.properties.sections.country??[],o=e=>r.find(t=>t.startPointIndex===e);return{type:"Feature",id:e.id,geometry:e.geometry,properties:{...i,fromSection:o(i.fromSectionStartPointIndex),toSection:o(i.toSectionStartPointIndex)}}})(e,this.sourcesWithLayers.mainLines.shownFeatures)}),incidents:this.userEventsWithStates(["incidents"]),vehicleRestricted:this.userEventsWithStates(["vehicleRestricted"]),ferries:this.userEventsWithStates(["ferries"]),tollRoads:this.userEventsWithStates(["tollRoads"]),tunnels:this.userEventsWithStates(["tunnels"]),instructionLines:this.userEventsWithStates(["instructionLines"])})}getLayerToRenderLinesUnder(){const e=prefixLayerID("routeLineArrows",this.layerIDPrefix);return this.layersSpecs.mainLines.find(t=>t.id===e)?.beforeID}},FACTOR_RANGE={min:.5,max:1.5,step:.1,bounds:"hard"},WIDE_FACTOR_RANGE={min:.5,max:2,step:.1,bounds:"hard"},baseMapSymbols={sourceTypes:["vector"],layerTypes:["symbol"]},poiLayers={sources:["vectorTiles"],sourceLayers:["poi"],layerTypes:["symbol"]},roadLines={...baseMapLayerGroupSelector("roads"),layerTypes:["line"]},trafficLayers=e=>(t,i)=>({sources:[e],layerTypes:["line"],idIncludes:[i?`${t} outline`:t],...i?{}:{idExcludes:["outline"]}}),flowLayers=trafficLayers("vectorTilesFlow"),incidentLayers=trafficLayers("vectorTilesIncidents"),factor=(e,t,i=FACTOR_RANGE)=>({kind:"factor",description:e,range:i,appliesTo:"any-style",mechanisms:t}),toggle=(e,t)=>({kind:"toggle",description:e,appliesTo:"tomtom-styles",mechanisms:[{type:"visibility",layers:t}]}),groupToggle=(e,t)=>({kind:"toggle",description:e,appliesTo:"tomtom-styles",mechanisms:[{type:"baseMapGroup",group:t}]}),color=(e,t,i,r)=>({kind:"color",description:e,appliesTo:"tomtom-styles",mechanisms:[{type:"color",property:t,layers:i,shades:r}]}),hillshadeLayers={layerTypes:["hillshade"]},groupsWithOwnKnob=/* @__PURE__ */new Set(["buildings2D","buildings3D","roadShields"]),basemapToggles=/* @__PURE__ */(()=>Object.fromEntries(baseMapLayerGroupNames.filter(e=>!(e=>groupsWithOwnKnob.has(e))(e)).map(e=>[`basemap.${e}`,groupToggle(`${describeLayerGroup(e)} The same state as BaseMapModule's \`groups.${e}.visible\`.`,e)])))(),mapColor=e=>({kind:"color",description:mapColorDefinitions[e].description,appliesTo:"tomtom-styles",mechanisms:[{type:"mapColor",color:e}]}),trafficColor=e=>(t,i)=>color(t,"line-color",[e(i,!1)],[e(i,!0)]),flowColor=trafficColor(flowLayers),incidentColor=trafficColor(incidentLayers),knobDefinitions=/* @__PURE__ */(()=>({"labels.sizeFactor":factor("Size of every base-map text label (places, roads, POIs, house numbers).",[{type:"scale",property:"text-size",layers:[baseMapSymbols]}]),"symbols.sizeFactor":factor("Size of every base-map icon (POI icons, route shields, road arrows).",[{type:"scale",property:"icon-size",layers:[baseMapSymbols]}]),"roads.widthFactor":factor("Width of all road lines, keeping the hierarchy motorway → path.",[{type:"scale",property:"line-width",layers:[roadLines]}]),"pois.sizeFactor":factor("Size of the base-map POI icons and their labels.",[{type:"scale",property:"icon-size",layers:[poiLayers]},{type:"scale",property:"text-size",layers:[poiLayers]}]),"pois.minZoom":{kind:"number",description:"Zoom level from which base-map POIs appear (the style default is 6).",range:{min:3,max:18,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"minZoom",layers:[{...poiLayers,idExcludes:["micro"]}]}]},"pois.zoomShift":{kind:"number",description:"Shifts the zoom at which each POI appears: positive = later and sparser, negative = earlier and denser.",range:{min:-3,max:3,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"zoomOffset",layers:[poiLayers]}]},"pois.labelColor":color("Text colour of base-map POI labels (replaces the per-category colours).","text-color",[poiLayers]),"pois.labelOutlineColor":color("Halo colour of base-map POI labels.","text-halo-color",[poiLayers]),"pois.microMarkers":toggle("The small dot markers for low-priority POIs at high zoom.",[{...poiLayers,idIncludes:["micro"]}]),"roads.exitNumbers":toggle("Motorway exit number badges.",[{metadataGroups:["road_label"],layerTypes:["symbol"],idIncludes:["exit"]}]),"roads.shields":groupToggle("Route shields along roads.","roadShields"),"roads.arrows":toggle("One-way arrows drawn on roads.",[{metadataGroups:["road"],layerTypes:["symbol"],idIncludes:["arrow"]}]),"roads.restricted":toggle("Dashed marking of roads with restricted access.",[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["restricted"]}]),"roads.underConstruction":toggle("Roads under construction.",[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["construction"]}]),"buildings.footprints":groupToggle("2D building footprints, shadows and outlines.","buildings2D"),"buildings.3d":groupToggle("Extruded 3D buildings (hidden by default in the standard styles).","buildings3D"),"traffic.flow.freeColor":flowColor("Traffic flow colour for free-flowing roads.","free flow"),"traffic.flow.slowColor":flowColor("Traffic flow colour for slow traffic.","slow flow"),"traffic.flow.queueingColor":flowColor("Traffic flow colour for queueing traffic.","queueing flow"),"traffic.flow.stationaryColor":flowColor("Traffic flow colour for stationary traffic.","stationary flow"),"traffic.flow.closedColor":color("Traffic flow colour for closed roads.","line-color",[flowLayers("closed road",!0)]),"traffic.flow.widthFactor":factor("Width of the traffic flow tubes.",[{type:"scale",property:"line-width",layers:[{sources:["vectorTilesFlow"],layerTypes:["line"]}]}],WIDE_FACTOR_RANGE),"traffic.incidents.minorColor":incidentColor("Traffic incident tube colour for minor delays.","minor jam"),"traffic.incidents.moderateColor":incidentColor("Traffic incident tube colour for moderate delays.","moderate jam"),"traffic.incidents.majorColor":incidentColor("Traffic incident tube colour for major delays.","major jam"),"traffic.incidents.closedColor":color("Traffic incident tube colour for closed roads.","line-color",[incidentLayers("closed road",!0)]),"traffic.incidents.widthFactor":factor("Width of the traffic incident tubes.",[{type:"scale",property:"line-width",layers:[{sources:["vectorTilesIncidents"],layerTypes:["line"]}]}],WIDE_FACTOR_RANGE),"colors.land":mapColor("land"),"colors.water":mapColor("water"),"colors.vegetation":mapColor("vegetation"),"colors.park":mapColor("park"),"colors.artificial":mapColor("artificial"),"colors.roadMajor":mapColor("roadMajor"),"colors.road":mapColor("road"),"colors.roadOutline":mapColor("roadOutline"),"colors.label":mapColor("label"),"colors.labelOutline":mapColor("labelOutline"),"colors.accent":{kind:"color",description:"The colour for what is drawn on top of the map — routes, geometries, places. Not a base-map layer: the modules that draw their own layers default to it when a theme sets it.",appliesTo:"any-style",mechanisms:[{type:"published"}]},...basemapToggles,"hillshade.method":{kind:"enum",description:"How the relief is shaded: standard (one light), basic, igor (softer), combined, or multidirectional (four lights).",options:["standard","basic","igor","combined","multidirectional"],appliesTo:"tomtom-styles",mechanisms:[{type:"paintLiteral",property:"hillshade-method",layers:[hillshadeLayers]}]},"hillshade.lightDirection":{kind:"number",description:"Direction the light comes from, in degrees clockwise from north (335 is the cartographic default).",range:{min:0,max:359,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"paintLiteral",property:"hillshade-illumination-direction",layers:[hillshadeLayers]}]},"hillshade.exaggeration":{kind:"number",description:"Strength of the shading (0 = flat), not the 3D surface height (TerrainModule elevationExaggeration). The standard styles ramp it to zero by zoom 13; setting it replaces the ramp with a constant.",range:{min:0,max:1,step:.05,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"paintLiteral",property:"hillshade-exaggeration",layers:[hillshadeLayers]}]},"hillshade.maxZoom":{kind:"number",description:"Zoom level up to which the shading is drawn (the standard styles stop at 13; 22 keeps it at every zoom).",range:{min:10,max:22,step:1,bounds:"hard"},appliesTo:"tomtom-styles",mechanisms:[{type:"maxZoom",layers:[hillshadeLayers]}]},"hillshade.shadowColor":color("Colour of the shaded slopes.","hillshade-shadow-color",[hillshadeLayers]),"hillshade.highlightColor":color("Colour of the lit slopes.","hillshade-highlight-color",[hillshadeLayers]),"hillshade.accentColor":color("Colour accentuating the steepest terrain.","hillshade-accent-color",[hillshadeLayers]),"view.projection":{kind:"enum",description:"How the map is drawn: flat Mercator or a globe. The globe flattens to Mercator between zoom 11 and 12 by design.",options:["mercator","globe"],appliesTo:"any-style",mechanisms:[{type:"projection"}]},"view.sky":{kind:"toggle",description:"A sky with atmosphere behind the globe and above a tilted flat map. Without it MapLibre draws a fully transparent sky, so a globe arrives with no atmosphere.",appliesTo:"any-style",mechanisms:[{type:"sky"}]},"view.skyColor":{kind:"color",description:"Colour of the sky (and of the atmosphere halo around the globe). Defaults to a daylit blue on a light style and a night blue on a dark one.",appliesTo:"any-style",mechanisms:[{type:"sky"}]},"view.horizonColor":{kind:"color",description:"Colour of the sky at the horizon. Defaults with the style theme, so a dark map gets a dim horizon rather than a white one.",appliesTo:"any-style",mechanisms:[{type:"sky"}]},"view.spaceColor":{kind:"color",description:"Colour behind the map, which a globe leaves visible around the planet. The map canvas is transparent, so without this the page background shows through. Defaults with the style theme: white on a light style, near-black on a dark one.",appliesTo:"any-style",mechanisms:[{type:"space"}]}}))(),stylingKnobIds=/* @__PURE__ */Object.keys(knobDefinitions),stylingKnobCatalogue=/* @__PURE__ */stylingKnobIds.map(e=>{const{mechanisms:t,...i}=knobDefinitions[e];return{id:e,...i}}),stylingColorKnobIds=/* @__PURE__ */stylingKnobIds.filter(e=>"color"===knobDefinitions[e].kind),LayerSelection=class{constructor(e,t){this.registry=e,this.query=t}get layerIds(){return this.registry.resolve(this.query)}setPaint(e){for(const[t,i]of Object.entries(e))this.registry.override(this.query,{kind:"paint",property:t,value:i});return this}setLayout(e){for(const[t,i]of Object.entries(e))this.registry.override(this.query,{kind:"layout",property:t,value:i});return this}setFilter(e){return this.registry.overrideFilter(this.query,e),this}setVisible(e){return this.setLayout({visibility:e?"visible":"none"})}reset(){return this.registry.reset(this.query),this}},LayerOverrides=class{constructor(e,t,i){this.mapLibreMap=e,this.filterComposer=t,this.warn=i,this.layers=[],this.sources={},this.properties=/* @__PURE__ */new Map,this.filters=/* @__PURE__ */new Map}index(e,t){this.layers=e,this.sources=t}clear(){this.properties.clear(),this.filters.clear()}resolve(e){const t=selectorsOf(e),i=this.layers.filter(e=>t.every(t=>matchesLayerSelector(t,e,this.sources))).map(e=>e.id);return 0===i.length&&this.warn(`query:${JSON.stringify(e)}`,`layers.query(${JSON.stringify(e)}) matches no layer in the loaded style; the edit will have no effect.`),i}override(e,t){const i=`${t.kind}:${t.property}`;for(const r of this.resolve(e)){const e=this.properties.get(r)??/* @__PURE__ */new Map,o=e.get(i);e.set(i,{override:t,before:o?o.before:this.read(r,t)}),this.properties.set(r,e),this.write(r,t)}}overrideFilter(e,t){for(const i of this.resolve(e))this.filters.set(i,t),this.filterComposer.setTransform(i,"styling.layers",()=>t)}reset(e){for(const t of this.resolve(e)){for(const{override:e,before:i}of this.properties.get(t)?.values()??[])this.write(t,{...e,value:i});this.properties.delete(t),this.filters.delete(t)&&this.filterComposer.setTransform(t,"styling.layers",void 0)}}reapply(){for(const[e,t]of this.properties)if(this.mapLibreMap.getLayer(e))for(const i of t.values()){const t=this.read(e,i.override);isEqual(t,i.override.value)||(i.before=t),this.write(e,i.override)}for(const[e,t]of this.filters)this.filterComposer.setTransform(e,"styling.layers",()=>t)}read(e,{kind:t,property:i}){const r=this.mapLibreMap;return"paint"===t?r.getPaintProperty(e,i):r.getLayoutProperty(e,i)}write(e,{kind:t,property:i,value:r}){if(!this.mapLibreMap.getLayer(e))return;const o=this.mapLibreMap,s={validate:!1};"paint"===t?o.setPaintProperty(e,i,r,s):o.setLayoutProperty(e,i,r,s)}},selectorsOf=({group:e,...t})=>[t,...e?[baseMapLayerGroupSelector(e)]:[]],stylingPresets={"data-viz":{name:"Data visualisation",description:"A quiet base for your own data on top: fewer labels and markers, thinner roads, no badges competing with the overlay.",settings:{"labels.sizeFactor":.9,"symbols.sizeFactor":.9,"roads.widthFactor":.8,"roads.exitNumbers":!1,"roads.shields":!1,"roads.arrows":!1,"pois.microMarkers":!1,"pois.minZoom":14,"buildings.3d":!1}},"night-driving":{name:"Night driving",description:"Bigger labels and shields, wider roads and traffic tubes, POIs out of the way until close up.",settings:{"labels.sizeFactor":1.2,"symbols.sizeFactor":1.2,"roads.widthFactor":1.2,"roads.exitNumbers":!0,"roads.shields":!0,"roads.arrows":!0,"pois.minZoom":13,"pois.microMarkers":!1,"traffic.flow.widthFactor":1.3,"buildings.3d":!1}},minimal:{name:"Minimal",description:"The bare map: land, water, roads and the main place names. Everything decorative off.",settings:{"labels.sizeFactor":.9,"roads.exitNumbers":!1,"roads.shields":!1,"roads.arrows":!1,"roads.restricted":!1,"roads.underConstruction":!1,"buildings.footprints":!1,"buildings.3d":!1,"pois.microMarkers":!1,"pois.minZoom":16}},globe:{name:"Globe",description:"A globe with an atmosphere for the zoomed-out view; flattens to Mercator as you zoom in.",settings:{"view.projection":"globe","view.sky":!0}}},stylingPresetIds=/* @__PURE__ */Object.keys(stylingPresets),stylingPresetCatalogue=/* @__PURE__ */stylingPresetIds.map(e=>({id:e,...stylingPresets[e],settings:{...stylingPresets[e].settings}})),ZOOM_BOUNDS={minZoom:"minzoom",maxZoom:"maxzoom"},LAYOUT_PROPERTIES=/* @__PURE__ */new Set(["text-size","icon-size"]),PAINT_PROPERTIES=/* @__PURE__ */new Set(["line-width","fill-color","fill-outline-color","line-color","text-color","text-halo-color","fill-extrusion-color","background-color","hillshade-shadow-color","hillshade-highlight-color","hillshade-accent-color","hillshade-method","hillshade-illumination-direction","hillshade-exaggeration"]),SPEC_DEFAULTS={"text-size":16,"icon-size":1,"line-width":1,visibility:"visible",minzoom:0,maxzoom:24,"hillshade-method":"standard","hillshade-illumination-direction":335,"hillshade-exaggeration":.5,"hillshade-shadow-color":"#000000","hillshade-highlight-color":"#FFFFFF","hillshade-accent-color":"#000000"},targetKey=(e,t)=>`${e}|${t}`,SKY_DEFAULTS={light:{"sky-color":"#88c6fc","horizon-color":"#ffffff","sky-horizon-blend":.8,"atmosphere-blend":.8,"fog-color":"#ffffff","fog-ground-blend":.5,"horizon-fog-blend":.8},dark:{"sky-color":"#0a1626","horizon-color":"#2b4a72","sky-horizon-blend":.8,"atmosphere-blend":.8,"fog-color":"#0a1626","fog-ground-blend":.5,"horizon-fog-blend":.8}},SPACE_COLOR_DEFAULTS={light:"#ffffff",dark:"#0a1626"},UNPAINTED_BACKGROUNDS=/* @__PURE__ */new Set(["","transparent","rgba(0, 0, 0, 0)"]),CLEAR_SKY={"sky-color":"transparent","horizon-color":"transparent","fog-color":"transparent","fog-ground-blend":1,"atmosphere-blend":0},StylingModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await BaseMapModule.get(t).catch(()=>{}),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.updateConfig(i)))}constructor(e,t){super(e,t),this.baseMap()?._onGroupsTakenOver(e=>this.dropGroupToggles(e))}dropGroupToggles(e){const t=knobIdsIn(this.config).filter(t=>{const i=baseMapGroupOf(t);return void 0!==i&&e.includes(i)});t.length&&this.applyConfig(omit(this.config,t))}styleChangePriority(){return 100}_initSourcesWithLayers(){return this.indexStyle(this.mapLibreMap.getStyle()),this.refreshSpace(this.config??{}),{}}_applyConfig(e){const t=withoutUndefined(e),i=/* @__PURE__ */new Set([...knobIdsIn(this.config),...knobIdsIn(t)]),r=this.reindexed?i:[...i].filter(e=>this.config?.[e]!==t[e]);this.reindexed=!1;for(const o of r)this.refreshKnob(o,t);return this.tomtomMap.mapReady&&this.layerOverrides.reapply(),this.publish(t,r),Object.keys(t).length?t:void 0}discardShownData(){this.layerOverrides.clear()}get layers(){return{query:e=>new LayerSelection(this.layerOverrides,e)}}applyPreset(e,t={}){const i=stylingPresets[e];if(!i)throw new Error(`Unknown styling preset '${e}'. Known presets: ${stylingPresetIds.join(", ")}.`);t.merge?this.updateConfig(i.settings):this.applyConfig({...i.settings})}get(e){return this.assertKnob(e),this.liveBaseMapGroupVisibility(e)??this.config?.[e]??this.derivedMapColorOf(e)??this.defaultOf(e)}set(e,t){this.assertKnob(e),validate(e,t),this.config={...this.config,[e]:t},this.refreshKnob(e,this.config),this.publish(this.config,[e]),this.emitConfigChange()}reset(e){if(void 0===e)return void this.resetConfig();this.assertKnob(e);const{[e]:t,...i}=this.config??{};this.config=Object.keys(i).length?i:void 0,this.refreshKnob(e,this.config??{}),this.publish(this.config??{},[e]),this.emitConfigChange()}publish(e,t){this.publishMapColors(e);const i=this.tomtomMap._stylingSettings,r=new Set(t);for(const o of knobIdsIn(i))i[o]!==e[o]&&r.add(o);this.tomtomMap._setStylingSettings(e,r)}publishMapColors(e){const t=this.mapColorsOf(e);for(const i of mapColorNames){if(void 0!==t[i])continue;const e=this.defaultOf(mapColorKnobId(i));"string"==typeof e&&(t[i]=e)}this.tomtomMap._setMapColors(t)}setMapColors(e){const t={};for(const[i,r]of Object.entries(e)){if(!isMapColorName(i))throw new Error(`Unknown map colour '${i}'. Known colours: ${mapColorNames.join(", ")}.`);if(void 0===r)continue;const e=mapColorKnobId(i);validate(e,r),t[e]=r}this.updateConfig(t)}exportStyle(){return structuredClone(this.mapLibreMap.getStyle())}get events(){return this.moduleEvents([])}indexStyle(e){const t=e?.layers??[];this.originalValues=/* @__PURE__ */new Map,this.styleSources=e?.sources??{},this.resolved=/* @__PURE__ */new Map,this.scaleKnobsByTarget=/* @__PURE__ */new Map,this.mapColorTargetsByKey=/* @__PURE__ */new Map,this.mapColorTargetsByKnob=/* @__PURE__ */new Map,this.mapColorAnchors=/* @__PURE__ */new Map;const i=standardStyleIdOf(this.tomtomMap.getStyleInput());this.landDerivedColors=(i&&landDerivedMapColors[i])??[],this.warned=/* @__PURE__ */new Set,this.reindexed=!0,this.layerOverrides??=new LayerOverrides(this.mapLibreMap,this.filterComposer,(e,t)=>this.warnOnce(e,t)),this.layerOverrides.index(t,this.styleSources),this.mapLevelState={projection:e?.projection?.type??"mercator",sky:e?.sky};for(const r of stylingKnobIds){const e=knobDefinitions[r],i=e.mechanisms.map(e=>this.resolveMechanism(r,e,t)),o=new Set(i.flatMap(e=>e.layerIds)).size;this.resolved.set(r,{definition:e,mechanisms:i,targets:o})}}resolveMechanism(e,t,i){if("mapColor"===t.type)return{mechanism:t,layerIds:this.resolveMapColor(t.color,i),shadeLayerIds:[]};if("baseMapGroup"===t.type){const e=new Set(this.baseMap()?.getLayerIds(t.group));return{mechanism:t,layerIds:i.filter(t=>e.has(t.id)&&this.capture(t,"visibility")).map(e=>e.id),shadeLayerIds:[]}}if(!("layers"in t))return{mechanism:t,layerIds:["\0map"],shadeLayerIds:[]};const r=i.filter(e=>matchesAnyLayerSelector(t.layers,e,this.styleSources));let o,s=[];switch(t.type){case"scale":o=r.filter(e=>this.capture(e,t.property)).map(e=>e.id);for(const i of o){const r=targetKey(i,t.property);this.scaleKnobsByTarget.set(r,[...this.scaleKnobsByTarget.get(r)??[],e])}break;case"color":{o=r.filter(e=>this.capture(e,t.property)).map(e=>e.id);const e=t.shades??[];s=i.filter(t=>matchesAnyLayerSelector(e,t,this.styleSources)).filter(e=>this.capture(e,t.property)).map(e=>e.id);break}case"visibility":o=r.filter(e=>this.capture(e,"visibility")).map(e=>e.id);break;case"minZoom":case"maxZoom":o=r.map(e=>e.id);for(const e of r)this.capture(e,"minzoom"),this.capture(e,"maxzoom");break;case"paintLiteral":o=r.map(e=>e.id);for(const e of r)this.capture(e,t.property);break;case"zoomOffset":o=r.filter(e=>shiftZoomOffset(layerFilterOf(e),0).patched).map(e=>e.id)}return{mechanism:t,layerIds:o,shadeLayerIds:s}}capture(e,t){const i=styleValueOf(e,t);return void 0!==i&&(this.originalValues.set(targetKey(e.id,t),i),!0)}originalValueOf(e,t){return this.originalValues.get(targetKey(e,t))}resolveMapColor(e,t){const i=mapColorKnobId(e),r=mapColorDefinitions[e],o=[];for(const l of r.targets)for(const i of t.filter(e=>matchesAnyLayerSelector(l.layers,e,this.styleSources)))for(const t of l.properties){if(!this.capture(i,t))continue;const r={color:e,layerId:i.id,property:t,owns:ownershipOf(l),recolorsTints:l.recolorsTints};o.push(r);const s=targetKey(i.id,t);this.mapColorTargetsByKey.set(s,[...this.mapColorTargetsByKey.get(s)??[],r])}this.mapColorTargetsByKnob.set(i,o);const{anchor:s}=r,a=t.find(e=>matchesAnyLayerSelector(s.layers,e,this.styleSources)&&void 0!==styleValueOf(e,s.property)),n=a&&((e,t=()=>!0,i=!1)=>{let r;for(const{literal:o,roadClass:s,keyed:a}of collectColorLiterals(e)){if(!t(s))continue;const e=Math.round(100*(toHsl(o)?.s??0)),n=r?.saturation===e;r&&!(i?r.keyed||!a:e>r.saturation||n&&r.keyed&&!a)||(r={literal:o,saturation:e,keyed:a})}return r?.literal})(styleValueOf(a,s.property),ownershipOf({roadClass:s.roadClass}),s.lastStop);return n&&this.mapColorAnchors.set(i,n),n?[...new Set(o.map(e=>e.layerId))]:[]}refreshKnob(e,t){const i=this.resolved.get(e);if(i&&this.tomtomMap.mapReady){0===i.targets&&void 0!==t[e]&&this.warnOnce(e,`knob '${e}' matches no layer in the loaded style (curated for style version 0.6.0-0); it will have no effect.`);for(const r of i.mechanisms)this.refreshMechanism(e,r,t)}}refreshMechanism(e,{mechanism:t,layerIds:i,shadeLayerIds:r},o){switch(t.type){case"color":this.refreshColor(t.property,i,r,o[e]);break;case"projection":this.refreshProjection(o);break;case"sky":this.refreshSky(o);break;case"space":this.refreshSpace(o);break;case"mapColor":this.refreshMapColor(t.color,o);break;case"baseMapGroup":this.baseMap()?._applyKnobVisibility(t.group,o[e]);break;case"visibility":for(const t of i)this.visibilityComposer.setVisible(t,`styling.${e}`,o[e]);break;case"published":break;default:for(const r of i)this.refreshLayer(t,r,o[e],o)}}refreshLayer(e,t,i,r){switch(e.type){case"scale":this.refreshScaledProperty(t,e.property,r);break;case"minZoom":case"maxZoom":this.refreshZoomBound(t,ZOOM_BOUNDS[e.type],i);break;case"paintLiteral":this.setProperty(t,e.property,i??this.originalValueOf(t,e.property));break;case"zoomOffset":this.refreshZoomOffset(t,i)}}refreshSpace(e){const t=this.mapLibreMap.getContainer();this.originalSpaceColor??=paintedBackgroundOf(t),t.style.backgroundColor=e["view.spaceColor"]??this.defaultSpaceColor()}defaultSpaceColor(){return this.originalSpaceColor||SPACE_COLOR_DEFAULTS[this.tomtomMap.styleLightDarkTheme]}refreshMapColor(e,t){const i=this.mapColorsOf(t),r=[e,...this.landDerivedColors.filter(t=>mapColorDerivationInputs(t).includes(e))],o=new Map(r.flatMap(e=>this.mapColorTargetsByKnob.get(mapColorKnobId(e))??[]).map(e=>[targetKey(e.layerId,e.property),e]));for(const{layerId:s,property:a}of o.values())this.refreshMapColorProperty(s,a,i)}derivedMapColorOf(e){const[t]=this.resolved.get(e)?.mechanisms??[];if("mapColor"===t?.mechanism.type&&this.mapColorAnchors.has(e))return this.mapColorsOf(this.config??{})[t.mechanism.color]}mapColorsOf(e){const t={};for(const i of mapColorNames){const r=e[mapColorKnobId(i)];"string"==typeof r&&(t[i]=r)}return withDerivedMapColors(t,this.landDerivedColors,this.mapColorAnchors.get(mapColorKnobId("land")))}refreshMapColorProperty(e,t,i){const r=this.originalValueOf(e,t),o=[],s=this.mapColorTargetsByKey.get(targetKey(e,t))??[];for(const{color:a,owns:n,recolorsTints:l}of s){const e=i[a],t=this.mapColorAnchors.get(mapColorKnobId(a));e&&t&&o.push({anchorColor:t,newColor:e,owns:n,recolorsTints:l})}this.setProperty(e,t,o.length?recolorValue(r,o):r)}refreshProjection(e){const t=e["view.projection"];this.mapLibreMap.setProjection({type:t??this.mapLevelState.projection})}refreshSky(e){const t=this.mapLevelState.sky,i=e["view.sky"]??this.defaultOf("view.sky"),r=SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme],o=i?{...r,...t,"sky-color":e["view.skyColor"]??t?.["sky-color"]??r["sky-color"],"horizon-color":e["view.horizonColor"]??t?.["horizon-color"]??r["horizon-color"]}:CLEAR_SKY;this.mapLibreMap.setSky(o,{validate:!1})}baseMap(){return sharedInstanceIfCreated(this.tomtomMap,BaseMapModule)}liveBaseMapGroupVisibility(e){const[t]=this.resolved.get(e)?.mechanisms??[];if("baseMapGroup"===t?.mechanism.type&&t.layerIds.length)return this.baseMap()?.isVisible({layerGroups:{mode:"include",names:[t.mechanism.group]}})}refreshZoomBound(e,t,i){if(!this.mapLibreMap.getLayer(e))return;const r={minzoom:this.styleZoomBound(e,"minzoom"),maxzoom:this.styleZoomBound(e,"maxzoom")};r[t]=i??r[t],this.mapLibreMap.setLayerZoomRange(e,r.minzoom,r.maxzoom)}styleZoomBound(e,t){return this.originalValueOf(e,t)??SPEC_DEFAULTS[t]}refreshZoomOffset(e,t){this.filterComposer.setTransform(e,"styling.zoomShift",void 0===t?void 0:e=>shiftZoomOffset(e,t).filter)}refreshScaledProperty(e,t,i){const r=this.originalValueOf(e,t),o=(this.scaleKnobsByTarget.get(targetKey(e,t))??[]).reduce((e,t)=>e*(i[t]??1),1);if(1===o)return void this.setProperty(e,t,r);const s=scaleNumericValue(r,o);void 0!==s?this.setProperty(e,t,s):this.warnOnce(`scale:${e}:${t}`,`cannot scale '${t}' of layer '${e}': the style gives it a value this knob cannot scale (a non-numeric value, or an expression holding a nested zoom term); leaving it as the style defines it.`)}refreshColor(e,t,i,r){for(const s of t)this.setProperty(s,e,r??this.originalValueOf(s,e));const o=t.map(t=>this.originalValueOf(t,e)).find(isColorLiteral);for(const s of i){const t=this.originalValueOf(s,e);let i=t;if(void 0!==r){const e=isColorLiteral(t)&&o&&hslShiftBetween(o,t);i=(e&&shiftHsl(r,e))??r}this.setProperty(s,e,i)}}setProperty(e,t,i){if(!this.mapLibreMap.getLayer(e))return;const r=this.mapLibreMap;LAYOUT_PROPERTIES.has(t)?r.setLayoutProperty(e,t,i,{validate:!1}):PAINT_PROPERTIES.has(t)&&r.setPaintProperty(e,t,i,{validate:!1})}defaultOf(e){const t=this.resolved.get(e);if(!t)return;const{definition:i,mechanisms:r}=t;if("factor"===i.kind)return 1;const[o]=r,[s]=o?.layerIds??[];if(void 0!==s){if("mapColor"===o.mechanism.type){const t=this.mapColorAnchors.get(e);return t&&(e=>{const t=toHsl(e);return t&&(t.alpha??1)<1?formatStyleHsl({...t,alpha:void 0}):e})(t)}if("baseMapGroup"===o.mechanism.type)return o.layerIds.some(e=>"none"!==this.originalValueOf(e,"visibility"));if(!("layers"in o.mechanism))return this.mapLevelDefaultOf(e);switch(o.mechanism.type){case"visibility":return"none"!==this.originalValueOf(s,"visibility");case"color":{const e=this.originalValueOf(s,o.mechanism.property);return isColorLiteral(e)?e:void 0}case"minZoom":case"maxZoom":return this.styleZoomBound(s,ZOOM_BOUNDS[o.mechanism.type]);case"paintLiteral":{const e=this.originalValueOf(s,o.mechanism.property);return"string"==typeof e||"number"==typeof e?e:void 0}case"zoomOffset":return 0;default:return}}}mapLevelDefaultOf(e){const{projection:t,sky:i}=this.mapLevelState;switch(e){case"view.projection":return"string"==typeof t?t:void 0;case"view.sky":return void 0!==i&&0!==i["atmosphere-blend"]&&"transparent"!==i["sky-color"];case"view.skyColor":return isColorLiteral(i?.["sky-color"])?i["sky-color"]:SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme]["sky-color"];case"view.horizonColor":return isColorLiteral(i?.["horizon-color"])?i["horizon-color"]:SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme]["horizon-color"];case"view.spaceColor":return this.defaultSpaceColor();default:return}}assertKnob(e){if(!(e in knobDefinitions))throw new Error(`Unknown styling knob '${e}'. stylingKnobIds lists every knob id.`)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[StylingModule] ${t}`))}},mapColorKnobId=e=>`colors.${e}`,ownershipOf=e=>"major"===e.roadClass?e=>"major"===e:"minor"===e.roadClass?e=>"major"!==e:()=>!0,validate=(e,t)=>validateKnobValue({id:e,...knobDefinitions[e]},t),knobIdsIn=e=>Object.keys(e??{}).filter(e=>e in knobDefinitions),withoutUndefined=e=>Object.fromEntries(Object.entries(e??{}).filter(([,e])=>void 0!==e)),baseMapGroupOf=e=>{const[t]=knobDefinitions[e].mechanisms;return"baseMapGroup"===t?.type?t.group:void 0},paintedBackgroundOf=e=>{const t=getComputedStyle(e).backgroundColor;return UNPAINTED_BACKGROUNDS.has(t)?"":t},layerFilterOf=e=>"filter"in e?e.filter:void 0,styleValueOf=(e,t)=>{const i="layout"in e?e.layout:void 0,r="paint"in e?e.paint:void 0;switch(t){case"text-size":return"symbol"===e.type&&void 0!==i?.["text-field"]?i["text-size"]??SPEC_DEFAULTS["text-size"]:void 0;case"icon-size":return"symbol"===e.type&&void 0!==i?.["icon-image"]?i["icon-size"]??SPEC_DEFAULTS["icon-size"]:void 0;case"line-width":return"line"===e.type?r?.["line-width"]??SPEC_DEFAULTS["line-width"]:void 0;case"visibility":return i?.visibility??SPEC_DEFAULTS.visibility;case"minzoom":return e.minzoom;case"maxzoom":return e.maxzoom;default:return paintValueOf(e,t,r)}},paintValueOf=(e,t,i)=>i?.[t]??("hillshade"===e.type&&(e=>e in SPEC_DEFAULTS)(t)?SPEC_DEFAULTS[t]:void 0),stylingKnobKinds=["factor","number","toggle","color","enum"],stylingKnobAppliesTo=["any-style","tomtom-styles"],isLoading=!1,ensureMapLibreCSS=()=>{isLoading||"undefined"==typeof document||(()=>{const e=document.createElement("div");e.className="maplibregl-ctrl-top-left",document.documentElement.append(e);const t="none"===getComputedStyle(e).pointerEvents;return e.remove(),t})()||(isLoading=!0,import("./chunks/maplibre-gl-DJlOK9hg.js").then(({default:e})=>(e=>{const t=`@layer maplibre-gl{${e}}`;if(Reflect.has(document,"adoptedStyleSheets")){const e=new CSSStyleSheet;e.replaceSync(t),document.adoptedStyleSheets=[...document.adoptedStyleSheets,e]}else{const e=document.createElement("style");e.textContent=t,document.head.append(e)}})(e)).finally(()=>{isLoading=!1}).catch(e=>console.error("Could not apply the MapLibre CSS",e)))},TomTomMap=class{get styleLightDarkTheme(){return this._styleLightDarkTheme}get mapColors(){return this._mapColors}_setMapColors(e){if(!isEqual(e,this._mapColors)){this._mapColors=e;for(const e of this.mapColorsHandlers)e(this._mapColors)}}_onMapColorsChange(e){this.mapColorsHandlers.push(e)}get _stylingSettings(){return this.stylingSettings}_setStylingSettings(e,t){if(this.stylingSettings=e,t.size)for(const i of this.stylingAppliedHandlers)i(t)}_onStylingApplied(e){this.stylingAppliedHandlers.push(e)}constructor(e){var t;this.mapReady=!1,this._mapColors={},this.mapColorsHandlers=[],this.stylingSettings={},this.stylingAppliedHandlers=[],this.styleChangeHandlers=[],this.styleRequestSequence=0,this.setStyle=(e,t={})=>{const i={resetState:t.resetState??!1};this.mapReady=!1;const r=++this.styleRequestSequence,o=i.resetState?e:((e,t)=>t&&"object"==typeof t&&"standard"===t.type&&t.include&&("string"==typeof e||"standard"===e.type&&!e.include)?{type:"standard",id:"string"==typeof e?e:e.id,include:t.include}:e)(e,this._params.style);return this._params={...this._params,style:o},this._styleLightDarkTheme=getStyleLightDarkTheme(o),this.applyStyle(i,r)},this.getStyleInput=()=>this._params.style,this._params=mergeFromGlobal(e),void 0===this._params.style&&(this._params={...this._params,style:"standardLight"}),this._styleLightDarkTheme=getStyleLightDarkTheme(this._params.style),ensureMapLibreCSS(),setWorkerCount(4),this.styleGivenToMapLibre=buildStyleInput(this._params),this.mapLibreMap=new Map$1({validateStyle:!1,maxTileCacheZoomLevels:22,cancelPendingTileRequestsWhileZooming:!1,...(t=this._params).mapLibre,style:buildStyleInput(t),attributionControl:{compact:!1},transformRequest:transformRequest(t)}),this.mapLibreMap.once("style.load",()=>{this.handleStyleData()}),this._eventsProxy=new EventsProxy(this.mapLibreMap,this._params?.events)}async applyStyle(e,t){if(await this.notifyHandlers("onStyleAboutToChange",e),this.isSuperseded(t))return;if(await(this.styleLoadInFlight?.catch(()=>{})),this.isSuperseded(t))return;const i=this.loadIntoMapLibre();this.styleLoadInFlight=i;try{await i}finally{this.styleLoadInFlight===i&&(this.styleLoadInFlight=void 0)}if(!this.isSuperseded(t))try{await this.handleStyleData(e)}catch(r){console.error(r)}}async loadIntoMapLibre(){const e=buildStyleInput(this._params);if(isEqual(e,this.styleGivenToMapLibre))return;const t=this.styleGivenToMapLibre;this.styleGivenToMapLibre=e,await new Promise((i,r)=>{const o=()=>{this.mapLibreMap.off("error",s),i()},s=e=>{"sourceId"in e||(this.mapLibreMap.off("style.load",o),this.mapLibreMap.off("error",s),this.styleGivenToMapLibre=t,r(e.error instanceof Error?e.error:new Error(e.error.message)))};this.mapLibreMap.once("style.load",o),this.mapLibreMap.on("error",s),this.mapLibreMap.setStyle(e,{validate:!1})})}isSuperseded(e){return e!==this.styleRequestSequence}async notifyHandlers(e,t){const i=[...this.styleChangeHandlers].sort((e,t)=>(e.priority??0)-(t.priority??0));for(const o of i)try{await(o[e]?.(t))}catch(r){console.error(r)}}_setTomTomUserAgent(e){this._params={...this._params,"tomtom-user-agent":e},this.mapLibreMap.setTransformRequest(transformRequest(this._params))}_setLanguage(e){this._params={...this._params,language:e};const t=e?.includes("-")?e.split("-")[0]:e;this.mapLibreMap.getStyle().layers.forEach(e=>{if("symbol"===e.type&&(e=>{const t=e.layout?.["text-field"]??"";return!!t&&("{name}"===t||2===t.length&&"name"===t[1]||3===t.length&&Array.isArray(t[1])&&"string"==typeof t[1][1]&&t[1][1].includes("name_")&&Array.isArray(t[2])&&t[2].includes("name"))})(e)){const i=t?["coalesce",["get",`name_${t}`],["get","name"]]:["get","name"];this.mapLibreMap.setLayoutProperty(e.id,"text-field",i,{validate:!1})}})}setLanguage(e){this.mapReady?this._setLanguage(e):this.mapLibreMap.once("styledata",()=>this.setLanguage(e))}setGeopoliticalView(e){this._params={...this._params,geopoliticalView:e},this.mapLibreMap.setTransformRequest(transformRequest(this._params)),this.mapReady&&reloadVectorTiles(this.mapLibreMap)}updateEventsConfig(e){this._eventsProxy.updateConfig(e)}getBBox(){return this.mapLibreMap.getBounds().toArray().flat()}async handleStyleData(e){for(const t of filterLayersBySources(this.mapLibreMap,["vectorTilesIncidents","vectorTilesFlow","hillshade"]))this.mapLibreMap.setLayoutProperty(t.id,"visibility","none",{validate:!1});isCustomStyle(this._params.style)&&!getDeclaredLightDarkTheme(this._params.style)&&(this._styleLightDarkTheme=(e=>{const t=e?.layers?.find(e=>"background"===e?.type);if(!t)return;const[i]=collectColorLiterals(t.paint?.["background-color"]),r=i&&relativeLuminance(i.literal);return void 0!==r?r<.35?"dark":"light":void 0})(this.mapLibreMap.getStyle())??this._styleLightDarkTheme),(async(e,t,i)=>{if(i.getSprite().some(e=>"pinCategories"===e.id))return;const r=new URLSearchParams;e.apiKey&&r.set("key",e.apiKey),r.set("poi",`poi_${t}`),r.set("apiVersion","1"),r.set("apiChannel","preview"),i.addSprite("pinCategories",`${e.commonBaseURL}/maps/orbis/assets/sprites/2.*/sprite?${r}`,{validate:!1})})(this._params,this._styleLightDarkTheme,this.mapLibreMap),this._params.language&&this._setLanguage(this._params.language),this.mapReady=!0,e&&await this.notifyHandlers("onStyleChanged",e)}addStyleChangeHandler(e){this.styleChangeHandlers.push(e);let t=!1;return()=>{if(t)return;t=!0;const i=this.styleChangeHandlers.indexOf(e);-1!==i&&this.styleChangeHandlers.splice(i,1)}}},terrainKnobCatalogue=/* @__PURE__ */withIds({hillshade:{kind:"toggle",description:"The hillshade: light and shadow on the map surface that reveal the relief at any pitch. Its look is the `hillshade.*` styling knobs.",default:!1},elevation:{kind:"toggle",description:"The 3D surface, raised to the elevation data or flattened. Unset: the map's own terrain, if its style or MapLibre code raised one; flat on TomTom styles."},elevationExaggeration:{kind:"number",description:"Vertical scale of the 3D surface, `1` being true elevation; kept while `elevation` is off.",range:{min:.5,max:3,step:.1,bounds:"hard-min"},default:1}}),terrainKnobIds=/* @__PURE__ */terrainKnobCatalogue.map(({id:e})=>e),TerrainModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await ensureAddedToStyle(t,"hillshade","terrain"),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("hillshade");if(!t)throw notInTheStyle(`init ${e.name} with source ID hillshade`);const i=this.mapLibreMap.getTerrain();return"hillshade-terrain"!==i?.source&&(this.mapTerrain=i),{hillshade:new StyleSourceWithLayers(this.mapLibreMap,t)}}_applyConfig(e){return this.showHillshade(e?.hillshade??!1),this.showElevation(e?.elevation,e?.elevationExaggeration??1),e}setHillshadeVisible(e){this.showHillshade(e),this.storeConfig({hillshade:e})}isHillshadeVisible(){return this.config?.hillshade??!1}setElevationEnabled(e){this.showElevation(e,this.config?.elevationExaggeration??1),this.storeConfig({elevation:e})}isElevationEnabled(){return this.config?.elevation??null!==this.mapLibreMap.getTerrain()}get events(){return this.lifecycleEvents()}showHillshade(e){this.tomtomMap.mapReady&&this.sourcesWithLayers.hillshade.setLayersVisible(e)}showElevation(e,t){this.tomtomMap.mapReady&&(void 0===e?this.overridesMapTerrain&&this.mapLibreMap.setTerrain(this.mapTerrain):e?(new TomTomMapSource("hillshade-terrain",this.sourcesWithLayers.hillshade.source.spec).ensureAddedToMap(this.mapLibreMap),this.mapLibreMap.setTerrain({source:"hillshade-terrain",exaggeration:t})):this.mapLibreMap.setTerrain(null),this.overridesMapTerrain=void 0!==e)}storeConfig(e){this.config={...this.config,...e},this.emitConfigChange()}},areaAnalyticsPalettes=["trafficLight","heat","monochrome","viridis","plasma"],AREA_ANALYTICS_DEFAULTS={visible:!0,displayMode:"hexgrid-3d",activeMetric:"congestionLevel",metricConfig:{congestionLevel:{palette:"trafficLight",height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},speed:{palette:"trafficLight",height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},travelTime:{palette:"trafficLight",height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},freeFlowSpeed:{palette:"trafficLight",height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"predefinedRange"}},networkLength:{palette:"trafficLight",height:{maxHeightMeters:1e3,minHeightMeters:0,scaleMode:"currentRange"}}},regionPolygon:{fillOpacity:0,outlineOpacity:.5,outlineWidth:2,inverted:!1}},getThemeAdaptiveRegionPolygonColor=e=>"dark"===e?"#FFFFFF":"#000000",PALETTE_COLORS={trafficLight:["#2dc653","#f5a623","#e03030"],heat:["#2196F3","#FF9800","#F44336"],monochrome:["#e0e0e0","#888888","#1a1a1a"],viridis:["#fde725","#35b779","#31688e","#440154"],plasma:["#f0f921","#ed7953","#9c179e","#0d0887"]},DEFAULT_METRIC_RANGES={congestionLevel:{min:0,max:100},speed:{min:0,max:120},travelTime:{min:0,max:20},freeFlowSpeed:{min:0,max:120},networkLength:{min:0,max:5e3}},paletteValueType=e=>"networkLength"===e?"relativeToActualRangePCT":"relativeToPredefinedRangePCT",getActiveMetric=e=>e?.activeMetric??AREA_ANALYTICS_DEFAULTS.activeMetric,resolveColorStops=(e,t)=>{if(t?.colorStops)return t.colorStops;const i=PALETTE_COLORS[t?.palette??"trafficLight"],r=(e=>"speed"===e||"freeFlowSpeed"===e)(e)?[...i].reverse():i;return{valueType:paletteValueType(e),stops:r.map((e,t)=>({value:t/(r.length-1)*100,color:e}))}},DEFAULT_BEFORE_LAYER$1={heatmap:"lowestLabel","hexgrid-2d":"lowestLabel","hexgrid-3d":"lowestPlaceLabel","square-2d":"lowestLabel","square-3d":"lowestPlaceLabel"},beforeIDOf=(e,t)=>beforeLayerIDOf(beforeLayerTargetOf(e?.beforeLayerConfig,t)??DEFAULT_BEFORE_LAYER$1[t]),buildColorExpression=(e,t,i)=>{const{valueType:r,stops:o}=resolveColorStops(e,t);let s;if("relativeToPredefinedRangePCT"===r){const{min:t,max:i}=DEFAULT_METRIC_RANGES[e];s=o.map(({value:e,color:r})=>[t+e/100*(i-t),r])}else if("relativeToActualRangePCT"===r){const{min:t,max:r}=i??DEFAULT_METRIC_RANGES[e];s=o.map(({value:e,color:i})=>[t+e/100*(r-t),i])}else s=o.map(({value:e,color:t})=>[e,t]);return["interpolate",["linear"],["get",e],...s.flatMap(([e,t])=>[e,t])]},buildHeatmapColorExpression=(e,t)=>{const{valueType:i,stops:r}=resolveColorStops(e,t);let o;if("relativeToPredefinedRangePCT"===i||"relativeToActualRangePCT"===i)o=r.flatMap(({value:e,color:t})=>[.3+e/100*.7,t]);else{const e=Math.min(...r.map(e=>e.value)),t=Math.max(...r.map(e=>e.value))-e||1;o=r.flatMap(({value:i,color:r})=>[.3+(i-e)/t*.7,r])}return["interpolate",["linear"],["heatmap-density"],0,"rgba(0,0,0,0)",...o]},buildHeightExpression=(e,t,i)=>{const r=AREA_ANALYTICS_DEFAULTS.metricConfig[e].height,o=t?.minHeightMeters??r.minHeightMeters??0;if("raw"===t?.scaleMode){const i=t.metersPerUnit??1;if("speed"===e){const{max:t}=DEFAULT_METRIC_RANGES[e];return["max",o,["*",["-",t,["coalesce",["get","speed"],0]],i]]}return["max",o,["*",["coalesce",["get",e],0],i]]}const s=t?.maxHeightMeters??r.maxHeightMeters??1e3,{min:a,max:n}="currentRange"===(t?.scaleMode??r.scaleMode)?i??DEFAULT_METRIC_RANGES[e]:DEFAULT_METRIC_RANGES[e],l=n-a||1;return"speed"===e?["max",o,["*",["/",["-",n,["coalesce",["get","speed"],0]],l],s]]:["max",o,["*",["/",["-",["coalesce",["get",e],0],a],l],s]]},buildHeatmapLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r],{min:s,max:a}=i??DEFAULT_METRIC_RANGES[r];return{id:e,type:"heatmap",beforeID:beforeIDOf(t,"heatmap"),paint:{"heatmap-weight":["interpolate",["linear"],["get",r],s,0,a,1],"heatmap-intensity":["interpolate",["linear"],["zoom"],10,.5,14,2,16,4],"heatmap-color":buildHeatmapColorExpression(r,o),"heatmap-radius":["interpolate",["linear"],["zoom"],4,1,8,3,12,35,14,80,16,100],"heatmap-opacity":["interpolate",["linear"],["zoom"],4,.8,13,.8,17,0]}}},buildHexFillLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill",beforeID:beforeIDOf(t,"hexgrid-2d"),paint:{"fill-color":buildColorExpression(r,o,i),"fill-opacity":.6}}},buildHexExtrusionLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill-extrusion",beforeID:beforeIDOf(t,"hexgrid-3d"),paint:{"fill-extrusion-color":buildColorExpression(r,o,i),"fill-extrusion-height":buildHeightExpression(r,o?.height,i),"fill-extrusion-base":0,"fill-extrusion-opacity":.75}}},buildSquareFillLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill",beforeID:beforeIDOf(t,"square-2d"),paint:{"fill-color":buildColorExpression(r,o,i),"fill-opacity":.6}}},buildSquareExtrusionLayerSpec=(e,t,i)=>{const r=getActiveMetric(t),o=t?.metricConfig?.[r];return{id:e,type:"fill-extrusion",beforeID:beforeIDOf(t,"square-3d"),paint:{"fill-extrusion-color":buildColorExpression(r,o,i),"fill-extrusion-height":buildHeightExpression(r,o?.height,i),"fill-extrusion-base":0,"fill-extrusion-opacity":.75}}},resolveRegionConfig=e=>({...AREA_ANALYTICS_DEFAULTS.regionPolygon,...e}),buildRegionFillLayerSpec=(e,t,i)=>{const{color:r,fillOpacity:o}=resolveRegionConfig(t?.regionPolygon);return{id:e,type:"fill",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"fill-color":r??getThemeAdaptiveRegionPolygonColor(i),"fill-opacity":o}}},buildRegionLineLayerSpec=(e,t,i)=>{const{color:r,outlineOpacity:o,outlineWidth:s}=resolveRegionConfig(t?.regionPolygon);return{id:e,type:"line",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"line-color":r??getThemeAdaptiveRegionPolygonColor(i),"line-opacity":o,"line-width":s}}},buildPolygonOutlineLayerSpec=(e,t)=>({id:e,type:"line",beforeID:t,filter:hasActiveEventState,paint:{"line-color":"#ffffff","line-width":["case",isClickEventState,3,2],"line-opacity":["case",isClickEventState,1,.8]}}),buildExtrusionHighlightLayerSpec=e=>({...e,filter:hasActiveEventState,paint:{...e.paint,"fill-extrusion-color":["case",isClickEventState,"#ffffff","#ffffff"],"fill-extrusion-height":["+",e.paint?.["fill-extrusion-height"],.5],"fill-extrusion-opacity":.6}}),buildHexExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildHexExtrusionLayerSpec(e,t,i)),buildSquareExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildSquareExtrusionLayerSpec(e,t,i)),INCIDENT_FOCUS_WIDTH_FACTOR_RANGE={min:1,max:1.8,step:.1,bounds:"hard"},svgMarkup='<svg xmlns="http://www.w3.org/2000/svg" width="48" height="18" viewBox="0 0 48 18">\n<path d="M 18 4 L 30 9 L 18 14" fill="none" stroke="rgba(20, 30, 50, 0.5)" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M 18 4 L 30 9 L 18 14" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',INNER_WIDTH=["interpolate",["exponential",1.5],["zoom"],5,0,9,.96,13,2.1,19,10.8],OUTLINE_WIDTH=["interpolate",["exponential",1.5],["zoom"],5,.75,9,1.96,13,3.6,19,13.8],buildColorExpr=e=>["match",["get","magnitudeOfDelay"],"unknown",e.unknown,"minor",e.minor,"moderate",e.moderate,"major",e.major,"indefinite",e.indefinite,e.major],INNER_PATTERN=["match",["get","magnitudeOfDelay"],"unknown","traffic-incidents-no_delay-pattern","indefinite","traffic-incidents-road_closed-pattern",""],getThemeAdaptiveFocusOutlineColor=e=>"dark"===e?"#FFF":"#000",HALO_WIDTH=["interpolate",["exponential",1.5],["zoom"],5,2.2,9,4.6,13,8.3,19,26],isFocusedOrActive=["any",["==",["feature-state","focused"],!0],hasActiveEventState],haloOpacity=["case",isFocusedOrActive,1,0],focusWidth=(e,t)=>null===t?e:scaledWhen(isFocusedOrActive,e,t),SOLID_FILTER=["in",["get","magnitudeOfDelay"],["literal",["minor","moderate","major"]]],PATTERN_FILTER=["in",["get","magnitudeOfDelay"],["literal",["unknown","indefinite"]]],buildCanonicalIncidentLineLayers=(e,t,i,r)=>{const o=r?.widthFactor??null,s=[];return null!==r&&s.push({id:`${e}-focus-halo`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":r.outlineColor,"line-width":HALO_WIDTH,"line-blur":0,"line-opacity":haloOpacity},beforeID:t}),s.push({id:`${e}-outline`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpr(i.outline),"line-width":focusWidth(OUTLINE_WIDTH,o)},beforeID:t},{id:`${e}-inner-solid`,type:"line",minzoom:6,filter:SOLID_FILTER,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpr(i.inner),"line-width":focusWidth(INNER_WIDTH,o)},beforeID:t},{id:`${e}-inner-chevron`,type:"line",minzoom:12,filter:SOLID_FILTER,layout:{"line-cap":"butt","line-join":"round"},paint:{"line-pattern":"tt-traffic-incident-direction-chevron","line-width":focusWidth(INNER_WIDTH,o)},beforeID:t},{id:`${e}-inner-pattern`,type:"line",minzoom:6,filter:PATTERN_FILTER,layout:{"line-cap":"round","line-join":"round"},paint:{"line-pattern":INNER_PATTERN,"line-width":focusWidth(INNER_WIDTH,o)},beforeID:t}),s},ICON_SIZE=["step",["zoom"],.7,14,.8,16,.9,18,1],JAM_TEXT_SIZE=["step",["zoom"],12.6,14,14.4,16,16.2,18,18],INCIDENT_MARKER_ICON=["match",["get","category"],"other","traffic-incidents-info","accident","traffic-incidents-accident","fog","traffic-incidents-fog","danger","traffic-incidents-roadworks","rain","traffic-incidents-rain","frost","traffic-incidents-frost","lane-closed","traffic-incidents-lane_closed","roadworks","traffic-incidents-roadworks","wind","traffic-incidents-wind","flooding","traffic-incidents-flooding","broken-down-vehicle","traffic-incidents-broken_down_vehicle",""],INCIDENT_MARKER_FILTER=["all",["!=",["get","magnitudeOfDelay"],"indefinite"],["any",["!",["has","delayInSeconds"]],["step",["zoom"],[">",["get","delayInSeconds"],900],14,[">",["get","delayInSeconds"],600],15,[">",["get","delayInSeconds"],300],16,!0]]],JAM_MARKER_FILTER=["all",["==",["get","category"],"jam"],["!=",["get","magnitudeOfDelay"],"unknown"],["!=",["get","magnitudeOfDelay"],"indefinite"],["step",["zoom"],[">",["get","delayInSeconds"],900],13,[">",["get","delayInSeconds"],600],14,[">",["get","delayInSeconds"],300],15,!0]],CLOSED_ROAD_FILTER=["==",["get","magnitudeOfDelay"],"indefinite"],JAM_ICON=["concat","traffic-jam-",["get","magnitudeOfDelay"],["case",["<",["get","delayInSeconds"],600],"-small",["<",["get","delayInSeconds"],3600],"-medium","-large"]],JAM_TEXT=["case",["<=",["get","delayInSeconds"],60],"1 min",[">=",["get","delayInSeconds"],3600],["concat",["to-string",["floor",["/",["to-number",["get","delayInSeconds"]],3600]]]," hr ",["case",["==",["%",["round",["/",["to-number",["get","delayInSeconds"]],60]],60],0],"",["concat",["to-string",["round",["%",["/",["to-number",["get","delayInSeconds"]],60],60]]]," min"]]],["concat",["round",["/",["get","delayInSeconds"],60]]," min"]],SORT_KEY=["case",["has","delayInSeconds"],["*",-1,["get","delayInSeconds"]],0],buildCanonicalIncidentSymbolLayers=(e,t)=>[{id:`${e}-incident-marker`,type:"symbol",minzoom:13,filter:INCIDENT_MARKER_FILTER,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-anchor":"bottom-right","icon-offset":[-1,3],"icon-image":INCIDENT_MARKER_ICON,"icon-size":ICON_SIZE,"symbol-sort-key":SORT_KEY},beforeID:t},{id:`${e}-jam-marker`,type:"symbol",minzoom:12,filter:JAM_MARKER_FILTER,layout:{"symbol-placement":"point","icon-anchor":"bottom-left","icon-offset":[2,3],"icon-image":JAM_ICON,"icon-size":ICON_SIZE,"icon-padding":0,"text-anchor":"bottom-left","text-field":JAM_TEXT,"text-font":["NotoSans-CondensedBold"],"text-offset":[2.7,-.75],"text-size":JAM_TEXT_SIZE,"symbol-sort-key":SORT_KEY},paint:{"text-color":"hsl(210, 30%, 14%)"},beforeID:t},{id:`${e}-closed-road-marker`,type:"symbol",minzoom:12,filter:CLOSED_ROAD_FILTER,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-anchor":"bottom-right","icon-offset":[-1,3],"icon-image":"traffic-incidents-road_closed","icon-size":ICON_SIZE},beforeID:t}],roadCategories=["motorway","motorway_link","trunk","trunk_link","primary","primary_link","secondary","secondary_link","tertiary","tertiary_link","street","service","track"],streetRoadSubCategories=["unclassified","residential","living_street"],serviceRoadSubCategories=["parking","driveway","alley"],HEIGHT_METERS_RANGE={min:0,max:5e3,step:50,bounds:"hard-min"},RAW_HEIGHT_METERS_PER_UNIT_RANGE={min:0,max:100,step:.1,bounds:"hard-min"},OUTLINE_WIDTH_RANGE={min:0,max:10,step:.5,bounds:"hard-min"},roadFilterKnobDefinitions={"filters.any.0.roadCategories.show":{kind:"enum",description:"`only` keeps just the `filters.any.0.roadCategories.values` road categories, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.roadCategories.values":{kind:"enums",description:"The road categories `filters.any.0.roadCategories.show` keeps alone or drops.",options:roadCategories},"filters.any.0.roadSubCategories.show":{kind:"enum",description:"`only` keeps just the `filters.any.0.roadSubCategories.values` street and service roads, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.roadSubCategories.values":{kind:"enums",description:"The street and service road kinds `filters.any.0.roadSubCategories.show` keeps alone or drops.",options:[...streetRoadSubCategories,...serviceRoadSubCategories]}},flowKnobDefinitions={visible:{kind:"toggle",description:"The traffic flow lines; hidden until shown.",default:!1},...roadFilterKnobDefinitions,"filters.any.0.showRoadClosures":{kind:"enum",description:"`only` draws just the closed roads, `all-except` the flow on every road but them.",options:filterShowModes}},incidentsKnobDefinitions={visible:{kind:"toggle",description:"The traffic incident lines and their icons; hidden until shown.",default:!1},"icons.visible":{kind:"toggle",description:"The incident icons, apart from the lines. Unset follows `visible`."},...roadFilterKnobDefinitions,"filters.any.0.incidentCategories.show":{kind:"enum",description:"`only` keeps just the `filters.any.0.incidentCategories.values` incidents, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.incidentCategories.values":{kind:"enums",description:"The incident categories `filters.any.0.incidentCategories.show` keeps alone or drops.",options:fullTrafficIncidentCategories},"filters.any.0.magnitudes.show":{kind:"enum",description:"`only` keeps just the incidents of the `filters.any.0.magnitudes.values` delay magnitudes, `all-except` every one but them; the filter applies once both are set.",options:filterShowModes},"filters.any.0.magnitudes.values":{kind:"enums",description:"The delay magnitudes `filters.any.0.magnitudes.show` keeps alone or drops.",options:/* @__PURE__ */everyOf()(["unknown","minor","moderate","major","indefinite"])},"filters.any.0.delays.mustHaveDelay":{kind:"toggle",description:"Drop the incidents that report no delay.",default:!1},"filters.any.0.delays.minDelayMinutes":{kind:"number",description:"Drop the incidents delaying traffic by less than this many minutes; those that report no delay stay unless `filters.any.0.delays.mustHaveDelay`.",range:{min:0,max:120,step:5,bounds:"hard-min"}}},incidentDetailsKnobDefinitions={visible:{kind:"toggle",description:"The incident layers; hiding them keeps the shown incidents.",default:!0},"focus.outlineColor":{kind:"color",description:"Colour of the outline beneath the focused, hovered or clicked incidents. Unset: black on light styles, white on dark."},"focus.widthFactor":{kind:"factor",description:"Multiplier on the line width of the focused, hovered or clicked incidents; `1` keeps the outline alone.",range:INCIDENT_FOCUS_WIDTH_FACTOR_RANGE,default:1.6}},areaAnalyticsKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"The analytics layers, region boundary included.",default:AREA_ANALYTICS_DEFAULTS.visible},displayMode:{kind:"enum",description:"How the cells are drawn: hexagons or squares, flat or raised by the metric, or a heatmap.",options:/* @__PURE__ */everyOf()(["hexgrid-3d","hexgrid-2d","square-3d","square-2d","heatmap"]),default:AREA_ANALYTICS_DEFAULTS.displayMode},activeMetric:{kind:"enum",description:"The metric that colours the cells and raises them in the 3D modes.",options:areaAnalyticsMetricKeys,default:AREA_ANALYTICS_DEFAULTS.activeMetric},"regionPolygon.color":{kind:"color",description:"Fill and outline colour of the region boundary. Unset: black on light styles, white on dark."},"regionPolygon.fillOpacity":{kind:"number",description:"Fill opacity of the region boundary.",range:OPACITY_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.fillOpacity},"regionPolygon.outlineOpacity":{kind:"number",description:"Outline opacity of the region boundary.",range:OPACITY_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.outlineOpacity},"regionPolygon.outlineWidth":{kind:"number",description:"Outline width of the region boundary, in pixels.",range:OUTLINE_WIDTH_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.outlineWidth},"regionPolygon.inverted":{kind:"toggle",description:"Fill the world outside the region rather than the region itself.",default:AREA_ANALYTICS_DEFAULTS.regionPolygon.inverted}}))(),metricKnobDefinitions={palette:e=>({kind:"enum",description:`Palette of the \`${e}\` cells, its bad end where traffic is worst; \`colorStops\`, set in the config, wins over it.`,options:areaAnalyticsPalettes,default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].palette}),"height.scaleMode":e=>({kind:"enum",description:`What the \`${e}\` cells' height scales against: the SDK's range for the metric, the loaded data's range, or the raw value.`,options:/* @__PURE__ */everyOf()(["predefinedRange","currentRange","raw"]),default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].height.scaleMode}),"height.maxHeightMeters":e=>({kind:"number",description:`Height of the tallest \`${e}\` cell, in metres, under the \`predefinedRange\` and \`currentRange\` scale modes.`,range:HEIGHT_METERS_RANGE,default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].height.maxHeightMeters}),"height.minHeightMeters":e=>({kind:"number",description:`Height of the lowest \`${e}\` cells, in metres.`,range:HEIGHT_METERS_RANGE,default:AREA_ANALYTICS_DEFAULTS.metricConfig[e].height.minHeightMeters}),"height.metersPerUnit":e=>({kind:"number",description:`Metres of height per unit of \`${e}\`, under the \`raw\` scale mode.`,range:RAW_HEIGHT_METERS_PER_UNIT_RANGE,default:1}),"filters.min":e=>({kind:"number",description:`Hide the cells whose \`${e}\` is below this value, while \`${e}\` is the active metric.`,range:{...DEFAULT_METRIC_RANGES[e],bounds:"hard-min"}}),"filters.max":e=>({kind:"number",description:`Hide the cells whose \`${e}\` is above this value, while \`${e}\` is the active metric.`,range:{...DEFAULT_METRIC_RANGES[e],bounds:"hard-min"}})},buildAreaAnalyticsCatalogue=()=>{const e=Object.keys(metricKnobDefinitions);return[...withIds(areaAnalyticsKnobDefinitions),...areaAnalyticsMetricKeys.flatMap(t=>e.map(e=>({id:`metricConfig.${t}.${e}`,...metricKnobDefinitions[e](t)})))]},trafficFlowKnobCatalogue=/* @__PURE__ */withIds(flowKnobDefinitions),trafficFlowKnobIds=/* @__PURE__ */trafficFlowKnobCatalogue.map(({id:e})=>e),trafficIncidentsKnobCatalogue=/* @__PURE__ */withIds(incidentsKnobDefinitions),trafficIncidentsKnobIds=/* @__PURE__ */trafficIncidentsKnobCatalogue.map(({id:e})=>e),trafficIncidentDetailsKnobCatalogue=/* @__PURE__ */withIds(incidentDetailsKnobDefinitions),trafficIncidentDetailsKnobIds=/* @__PURE__ */trafficIncidentDetailsKnobCatalogue.map(({id:e})=>e),trafficAreaAnalyticsKnobCatalogue=/* @__PURE__ */buildAreaAnalyticsCatalogue(),trafficAreaAnalyticsKnobIds=/* @__PURE__ */trafficAreaAnalyticsKnobCatalogue.map(({id:e})=>e),tilesToPointFeatures=e=>({type:"FeatureCollection",features:e.features.flatMap(e=>e.properties?.tiledData?.tiles??[]).map((e,t)=>{const[i,r]=e.tileCentre,o=`tile-${t}-${i}-${r}`;return{type:"Feature",id:o,geometry:{type:"Point",coordinates:[i,r]},properties:{id:o,speed:e.speed??0,freeFlowSpeed:e.freeFlowSpeed??0,congestionLevel:e.congestionLevel??0,travelTime:e.travelTime??0,networkLength:e.networkLength??0}}})}),aggregateTilesIntoCells=(e,t,i)=>((e,t,i)=>{const r=[];for(let o=0;o<e.length;o++){const s=e[o];if(!s)continue;const{congestionSum:a,speedSum:n,freeFlowSum:l,travelTimeSum:c,networkLengthSum:d,count:u}=s,p=`${i}-${o}`;r.push({type:"Feature",id:p,geometry:t.features[o].geometry,properties:{id:p,congestionLevel:Math.round(a/u),speed:Math.round(n/u),freeFlowSpeed:Math.round(l/u),travelTime:Math.round(c/u*10)/10,networkLength:Math.round(d/u)}})}return r})(((e,t)=>{const i=[];for(const r of e)for(let e=0;e<t.features.length;e++)if(booleanPointInPolygon(r.tileCentre,t.features[e])){let t=i[e];void 0===t&&(t={congestionSum:0,speedSum:0,freeFlowSum:0,travelTimeSum:0,networkLengthSum:0,count:0},i[e]=t),t.congestionSum+=r.congestionLevel??0,t.speedSum+=r.speed??0,t.freeFlowSum+=r.freeFlowSpeed??0,t.travelTimeSum+=r.travelTime??0,t.networkLengthSum+=r.networkLength??0,t.count++;break}return i})(e,t),t,i),tilesToGridFeatures=(e,t,i,r)=>{const o=[];for(let s=0;s<e.features.length;s++){const a=e.features[s],n=a.properties?.tiledData?.tiles??[];if(0===n.length)continue;const l=bboxFromGeoJSON(a);if(!l)continue;const c=i([l[0]-.005,l[1]-.005,l[2]+.005,l[3]+.005],t);o.push(...aggregateTilesIntoCells(n,c,`${r}-${s}`))}return{type:"FeatureCollection",features:o}},tilesToHexFeatures=(e,t=.25)=>tilesToGridFeatures(e,t,(e,t)=>hexGrid(e,t,{units:"kilometers"}),"hex"),tilesToSquareFeatures=(e,t=.5)=>tilesToGridFeatures(e,t,(e,t)=>squareGrid(e,t,{units:"kilometers"}),"square"),isRegionInverted=e=>e?.regionPolygon?.inverted??AREA_ANALYTICS_DEFAULTS.regionPolygon.inverted,dataSources=["hexgrid","square","heatmap"],TrafficAreaAnalyticsModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i??{})}constructor(e,t){super(e,t),this.lastAnalytics=null,this.shownFeaturesHandlers=[]}_initSourcesWithLayers(e,t){const i=this.instanceIndex,r=`area-analytics-heatmap-${i}`,o=`area-analytics-hexgrid-${i}`,s=`area-analytics-square-${i}`,a=`area-analytics-region-${i}`,n=`${r}-layer`,l=`${o}-fill`,c=`${o}-extrusion`,d=`${o}-outline`,u=`${o}-extrusion-highlight`,p=`${s}-fill`,h=`${s}-extrusion`,y=`${s}-outline`,f=`${s}-extrusion-highlight`,m=`${a}-fill`,g=`${a}-line`,S=this.lightDark;this.heatmapLayerSpec=buildHeatmapLayerSpec(n,e),this.hexFillLayerSpec=buildHexFillLayerSpec(l,e),this.hexExtrusionLayerSpec=buildHexExtrusionLayerSpec(c,e),this.squareFillLayerSpec=buildSquareFillLayerSpec(p,e),this.squareExtrusionLayerSpec=buildSquareExtrusionLayerSpec(h,e),this.regionFillLayerSpec=buildRegionFillLayerSpec(m,e,S),this.regionLineLayerSpec=buildRegionLineLayerSpec(g,e,S),this.hexOutlineLayerSpec=((e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"hexgrid-2d")))(d,e),this.hexExtrusionHighlightLayerSpec=buildHexExtrusionHighlightLayerSpec(u,e),this.squareOutlineLayerSpec=((e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"square-2d")))(y,e),this.squareExtrusionHighlightLayerSpec=buildSquareExtrusionHighlightLayerSpec(f,e);const L={heatmap:new GeoJSONSourceWithLayers(this.mapLibreMap,r,[this.heatmapLayerSpec]),hexgrid:new GeoJSONSourceWithLayers(this.mapLibreMap,o,[this.hexFillLayerSpec,this.hexExtrusionLayerSpec]),square:new GeoJSONSourceWithLayers(this.mapLibreMap,s,[this.squareFillLayerSpec,this.squareExtrusionLayerSpec]),region:new GeoJSONSourceWithLayers(this.mapLibreMap,a,[this.regionFillLayerSpec,this.regionLineLayerSpec])};return this.addHighlightLayersToMap(o,s),L}_applyConfig(e){const t=this.config,i=e??{},r=Object.keys(AREA_ANALYTICS_DEFAULTS.metricConfig),o=Object.fromEntries(r.map(e=>[e,{...AREA_ANALYTICS_DEFAULTS.metricConfig[e],...i.metricConfig?.[e]}])),s={activeMetric:AREA_ANALYTICS_DEFAULTS.activeMetric,displayMode:AREA_ANALYTICS_DEFAULTS.displayMode,...i,metricConfig:o};return this.config=s,this.applyLayerConfig(s),isEqual(s.regionPolygon,t?.regionPolygon)||this.applyRegionConfig(s,t),(s.beforeLayerConfig||t?.beforeLayerConfig)&&this.moveLayersToSpecPositions(),this.applyVisibility(s),s}moveLayersToSpecPositions(){for(const e of[this.heatmapLayerSpec,this.hexFillLayerSpec,this.hexExtrusionLayerSpec,this.squareFillLayerSpec,this.squareExtrusionLayerSpec])moveLayerBefore(this.mapLibreMap,e.id,e.beforeID)}discardShownData(){this.lastAnalytics=null}restoreDataAndConfigImpl(){const{heatmap:e,hexgrid:t,square:i,region:r}=this.sourcesWithLayers,o={heatmap:e.shownFeatures,hexgrid:t.shownFeatures,square:i.shownFeatures,region:r.shownFeatures};this.initSourcesWithLayers(this.config,!0),this.lastAnalytics?this.display(o):this.config&&this._applyConfig(this.config)}async show(e){await this.waitUntilModuleReady(),this.lastAnalytics=e,this.display({heatmap:tilesToPointFeatures(e),hexgrid:tilesToHexFeatures(e),square:tilesToSquareFeatures(e),region:this.buildRegionFC(e.features,isRegionInverted(this.config))});for(const t of this.shownFeaturesHandlers)t(e)}display(e){this.sourcesWithLayers.heatmap.show(e.heatmap,{automaticVisibility:!1}),this.sourcesWithLayers.hexgrid.show(e.hexgrid,{automaticVisibility:!1}),this.sourcesWithLayers.square.show(e.square,{automaticVisibility:!1}),this.sourcesWithLayers.region.show(e.region,{automaticVisibility:!1}),this.applyLayerConfig(this.config),this.applyVisibility(this.config)}async clear(){await this.waitUntilModuleReady(),this.lastAnalytics=null,this.sourcesWithLayers.heatmap.clear(),this.sourcesWithLayers.hexgrid.clear(),this.sourcesWithLayers.square.clear(),this.sourcesWithLayers.region.clear()}setPalette(e,t){this.setMetricField("palette",e,t),this.applyLayerConfig(this.config),this.emitConfigChange()}setColorStops(e,t){this.setMetricField("colorStops",e,t),this.applyLayerConfig(this.config),this.emitConfigChange()}setHeight(e,t){this.setMetricField("height",e,t),this.applyLayerConfig(this.config),this.emitConfigChange()}setFilters(e,t){this.setMetricField("filters",e,t),this.applyFiltersToLayers(),this.emitConfigChange()}getShown(){return{heatmap:this.sourcesWithLayers.heatmap.shownFeatures,hexgrid:this.sourcesWithLayers.hexgrid.shownFeatures,square:this.sourcesWithLayers.square.shownFeatures}}eventStateSources(){return dataSources}get events(){return this.moduleEventsWithShown(dataSources,this.shownFeaturesHandlers)}setMetricField(e,t,i=areaAnalyticsMetricKeys){const r={...this.config?.metricConfig};for(const o of i){const i={...r[o]};void 0===t?delete i[e]:i[e]=t,r[o]=i}this.config={...this.config,metricConfig:r}}get activeMetric(){return getActiveMetric(this.config)}get lightDark(){return this.tomtomMap.styleLightDarkTheme}applyVisibility(e){if(!1===e?.visible)return void this.hideAllDataLayers();const t=(e=>e?.displayMode??AREA_ANALYTICS_DEFAULTS.displayMode)(e),i=this.sourcesWithLayers.heatmap.shownFeatures.features.length>0,r=this.sourcesWithLayers.hexgrid.shownFeatures.features.length>0,o=this.sourcesWithLayers.square.shownFeatures.features.length>0,s=this.sourcesWithLayers.region.shownFeatures.features.length>0;this.sourcesWithLayers.heatmap.setLayersVisible("heatmap"===t&&i),this.sourcesWithLayers.hexgrid.setLayersVisible("hexgrid-3d"===t&&r,e=>e.id===this.hexExtrusionLayerSpec.id),this.sourcesWithLayers.hexgrid.setLayersVisible("hexgrid-2d"===t&&r,e=>e.id===this.hexFillLayerSpec.id),this.sourcesWithLayers.square.setLayersVisible("square-3d"===t&&o,e=>e.id===this.squareExtrusionLayerSpec.id),this.sourcesWithLayers.square.setLayersVisible("square-2d"===t&&o,e=>e.id===this.squareFillLayerSpec.id),this.sourcesWithLayers.region.setLayersVisible(s),this.setHighlightLayerVisible(this.hexOutlineLayerSpec.id,"hexgrid-2d"===t&&r),this.setHighlightLayerVisible(this.hexExtrusionHighlightLayerSpec.id,"hexgrid-3d"===t&&r),this.setHighlightLayerVisible(this.squareOutlineLayerSpec.id,"square-2d"===t&&o),this.setHighlightLayerVisible(this.squareExtrusionHighlightLayerSpec.id,"square-3d"===t&&o)}hideAllDataLayers(){this.sourcesWithLayers.heatmap.setLayersVisible(!1),this.sourcesWithLayers.hexgrid.setLayersVisible(!1),this.sourcesWithLayers.square.setLayersVisible(!1),this.sourcesWithLayers.region.setLayersVisible(!1),this.setHighlightLayerVisible(this.hexOutlineLayerSpec.id,!1),this.setHighlightLayerVisible(this.hexExtrusionHighlightLayerSpec.id,!1),this.setHighlightLayerVisible(this.squareOutlineLayerSpec.id,!1),this.setHighlightLayerVisible(this.squareExtrusionHighlightLayerSpec.id,!1)}addHighlightLayersToMap(e,t){const i=(e,t)=>{this.mapLibreMap.getLayer(e.id)||this.mapLibreMap.addLayer({...e,source:t},existingBeforeLayerID(this.mapLibreMap,e.beforeID)),this.mapLibreMap.setLayoutProperty(e.id,"visibility","none")};i(this.hexOutlineLayerSpec,e),i(this.hexExtrusionHighlightLayerSpec,e),i(this.squareOutlineLayerSpec,t),i(this.squareExtrusionHighlightLayerSpec,t)}setHighlightLayerVisible(e,t){this.mapLibreMap.getLayer(e)&&this.mapLibreMap.setLayoutProperty(e,"visibility",t?"visible":"none")}applyLayerConfig(e){const t=this.lastAnalytics?.properties.ranges?.[this.activeMetric],i=buildHeatmapLayerSpec(this.heatmapLayerSpec.id,e,t),r=buildHexFillLayerSpec(this.hexFillLayerSpec.id,e,t),o=buildHexExtrusionLayerSpec(this.hexExtrusionLayerSpec.id,e,t),s=buildHexExtrusionHighlightLayerSpec(this.hexExtrusionHighlightLayerSpec.id,e,t),a=buildSquareFillLayerSpec(this.squareFillLayerSpec.id,e,t),n=buildSquareExtrusionLayerSpec(this.squareExtrusionLayerSpec.id,e,t),l=buildSquareExtrusionHighlightLayerSpec(this.squareExtrusionHighlightLayerSpec.id,e,t);changeLayerProps(i,this.heatmapLayerSpec,this.mapLibreMap),changeLayerProps(r,this.hexFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.hexExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(s,this.hexExtrusionHighlightLayerSpec,this.mapLibreMap),changeLayerProps(a,this.squareFillLayerSpec,this.mapLibreMap),changeLayerProps(n,this.squareExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(l,this.squareExtrusionHighlightLayerSpec,this.mapLibreMap),this.heatmapLayerSpec=i,this.hexFillLayerSpec=r,this.hexExtrusionLayerSpec=o,this.hexExtrusionHighlightLayerSpec=s,this.squareFillLayerSpec=a,this.squareExtrusionLayerSpec=n,this.squareExtrusionHighlightLayerSpec=l,this.applyFiltersToLayers()}applyRegionConfig(e,t){const i=this.lightDark,r=buildRegionFillLayerSpec(this.regionFillLayerSpec.id,e,i),o=buildRegionLineLayerSpec(this.regionLineLayerSpec.id,e,i);changeLayerProps(r,this.regionFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.regionLineLayerSpec,this.mapLibreMap),this.regionFillLayerSpec=r,this.regionLineLayerSpec=o;const s=isRegionInverted(e);this.lastAnalytics&&s!==isRegionInverted(t)&&this.sourcesWithLayers.region.show(this.buildRegionFC(this.lastAnalytics.features,s))}applyFiltersToLayers(){const e=this.activeMetric,t=this.config?.metricConfig?.[e]?.filters,i=[this.hexFillLayerSpec.id,this.hexExtrusionLayerSpec.id,this.squareFillLayerSpec.id,this.squareExtrusionLayerSpec.id];if(!t||void 0===t.min&&void 0===t.max){for(const e of i)this.mapLibreMap.setFilter(e,null);return}const r=[];void 0!==t.min&&r.push([">=",["get",e],t.min]),void 0!==t.max&&r.push(["<=",["get",e],t.max]);const o=getMergedAnyFilter(r);for(const s of i)this.mapLibreMap.setFilter(s,o)}buildRegionFC(e,t){return{type:"FeatureCollection",features:e.map((e,i)=>{const r=`traffic-area-analytics-region-${i}`,o=t?mask(e).geometry:e.geometry;return{...e,id:r,geometry:o,properties:{id:r}}})}}},addFilter=(e,t)=>{e&&t.push(e)},addValuesFilter=(e,t,i)=>{isCompleteValuesFilter(e)&&addFilter(buildValuesFilter(t,e),i)},addCommonFilterExpressions=(e,t)=>{addValuesFilter(e.roadCategories,"road_category",t),addValuesFilter(e.roadSubCategories,"road_subcategory",t)},buildMapLibreIncidentsFilter=e=>{const t=[];if(addCommonFilterExpressions(e,t),isCompleteValuesFilter(e.incidentCategories)){const i=buildValuesFilter("icon_category_0",e.incidentCategories,trafficIncidentToIconCategory);addFilter(i,t)}if(isCompleteValuesFilter(e.magnitudes)){const i=buildValuesFilter("magnitude_of_delay",e.magnitudes,e=>indexedMagnitudes.indexOf(e));addFilter(i,t)}return e.delays&&addFilter((e=>{const t=[];if(e.mustHaveDelay&&e.minDelayMinutes){const i=60*e.minDelayMinutes;t.push([">=",["get","delay"],i])}else if(e.mustHaveDelay)t.push([">",["get","delay"],0]);else if(e.minDelayMinutes){const i=60*e.minDelayMinutes;t.push(["any",["!",["has","delay"]],["==",["get","delay"],0],[">=",["get","delay"],i]])}return getMergedFilter("all",t)})(e.delays),t),getMergedFilter("all",t)},buildMapLibreAnyFilters=(e,t)=>e?.any?.length?getMergedAnyFilter(e.any.map(t).filter(e=>!isNil(e))):null,buildMapLibreFlowFilter=e=>{const t=[];if(addCommonFilterExpressions(e,t),e.showRoadClosures){const i="only"===e.showRoadClosures?"==":"!=";t.push([i,["get","road_closure"],!0])}return getMergedFilter("all",t)},applyFilter=(e,t,i,r)=>{for(const o of t)i.setClause(o.id,r,e)},TrafficFlowModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await ensureAddedToStyle(t,"vectorTilesFlow","trafficFlow"),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTilesFlow");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTilesFlow`);return{trafficFlow:new StyleSourceWithLayers(this.mapLibreMap,t)}}_applyConfig(e){return this._setVisible(e?.visible??!1,!1),this.applyFilters(e?.filters),e}getLayers(){return filterLayersBySources(this.tomtomMap.mapLibreMap,["vectorTilesFlow"])}applyFilters(e){if(this.tomtomMap.mapReady)if(e?.any?.length){const t=buildMapLibreAnyFilters(e,buildMapLibreFlowFilter);t&&applyFilter(t,this.getLayers(),this.filterComposer,"traffic.flow")}else this.config?.filters?.any?.length&&applyFilter(void 0,this.getLayers(),this.filterComposer,"traffic.flow")}setVisible(e){this._setVisible(e)}_setVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficFlow.setLayersVisible(e),t&&(this.config={...this.config,visible:e},this.emitConfigChange())}isVisible(){return this.config?.visible??!1}getShown(){return{trafficFlow:this.mapLibreMap.queryRenderedFeatures({layers:this.sourcesWithLayers.trafficFlow.sourceAndLayerIDs.layerIDs,validate:!1}).map(trafficFlowMapping)}}get events(){return this.moduleEvents(["trafficFlow"],{mapping:trafficFlowMapping})}},LAYER_IDS={unknown:{outline:"TrafficIncidents - No delay outline",inner:"TrafficIncidents - No delay pattern"},minor:{outline:"TrafficIncidents - Minor jam outline",inner:"TrafficIncidents - Minor jam"},moderate:{outline:"TrafficIncidents - Moderate jam outline",inner:"TrafficIncidents - Moderate jam"},major:{outline:"TrafficIncidents - Major jam outline",inner:"TrafficIncidents - Major jam"},indefinite:{outline:"TrafficIncidents - Closed road outline",inner:"TrafficIncidents - Closed road pattern"}},FALLBACK_INCIDENT_PALETTE_outline={unknown:"hsl(198, 20%, 54%)",minor:"hsl(45, 85%, 36%)",moderate:"hsl(9, 87%, 31%)",major:"hsl(0, 100%, 17%)",indefinite:"hsl(0, 100%, 34%)"},FALLBACK_INCIDENT_PALETTE_inner={unknown:"hsl(198, 20%, 90%)",minor:"hsl(45, 100%, 51%)",moderate:"hsl(9, 97%, 51%)",major:"hsl(0, 100%, 34%)",indefinite:"hsl(197, 28%, 95%)"},readIncidentPalette=e=>{const t=e.getStyle()?.layers??[],i=/* @__PURE__ */new Map;for(const s of t)i.set(s.id.trim(),s);const r={outline:{...FALLBACK_INCIDENT_PALETTE_outline},inner:{...FALLBACK_INCIDENT_PALETTE_inner}},o=[];for(const s of indexedMagnitudes){const e=LAYER_IDS[s],t=readLineColor(i.get(e.outline),e.outline,o),a=readLineColor(i.get(e.inner),e.inner,o);t&&(r.outline[s]=t),a&&(r.inner[s]=a)}return o.length>0&&console.warn("[TrafficIncidentDetailsModule] style layers have non-literal `line-color` (match/case/etc.); falling back to default colour for: "+o.join(", ")),r},readLineColor=(e,t,i)=>{if(!e||"object"!=typeof e)return;const r=e.paint;if(!r||"object"!=typeof r)return;const o=r["line-color"];if("string"==typeof o)return o;void 0!==o&&i.push(t)},TrafficIncidentDetailsModule=class e extends AbstractDataOwnedMapModule{static async create(t,i){return await waitUntilMapIsReady(t),new e(t,i??{})}constructor(e,t){super(e,t),this.lastFeatureIds=[],this.lastFocusIds=null,this.shownFeaturesHandlers=[],onStylingKnobsApplied(e,Object.values(incidentColorKnobIds),()=>this.updateLayers(this.config))}buildLayerSpecs(e,t){const i=beforeLayerIDOf(t?.beforeLayerConfig??"lowestLabel"),r=((e,t)=>!1===e?null:{outlineColor:e?.outlineColor??getThemeAdaptiveFocusOutlineColor(t),widthFactor:clampFactor(e?.widthFactor,INCIDENT_FOCUS_WIDTH_FACTOR_RANGE,1.6)})(t?.focus,this.tomtomMap.styleLightDarkTheme);return[...buildCanonicalIncidentLineLayers(e,i,readIncidentPalette(this.mapLibreMap),r),...buildCanonicalIncidentSymbolLayers(e,i)]}updateLayers(e){const{incidents:t}=this.sourcesWithLayers,i=this.buildLayerSpecs(t.sourceAndLayerIDs.sourceID,e);updateLayersAndSource(i,t._layerSpecs,t,this.mapLibreMap);const r=i.map(({id:e})=>e);t._layerSpecs.sort((e,t)=>r.indexOf(e.id)-r.indexOf(t.id)),t._updateSourceAndLayerIDs()}_initSourcesWithLayers(e,t){const i=`traffic-incident-details-${this.instanceIndex}`,r=(()=>{if(isDOMImageSupported())return cachedImg||(cachedImg=svgToImg(parseSvg(svgMarkup))),cachedImg})();return r&&addOrUpdateImage("if-not-in-sprite","tt-traffic-incident-direction-chevron",r,this.mapLibreMap),{incidents:new GeoJSONSourceWithLayers(this.mapLibreMap,i,this.buildLayerSpecs(i,e))}}_applyConfig(e){return this.updateLayers(e),this.applyVisibility(e),this.applyBeforeLayer(e?.beforeLayerConfig),e}applyVisibility(e){this.sourcesWithLayers.incidents.setLayersVisible(!1!==e?.visible)}applyBeforeLayer(e){const t=beforeLayerIDOf(e??"lowestLabel");for(const i of this.sourcesWithLayers.incidents.sourceAndLayerIDs.layerIDs)moveLayerBefore(this.mapLibreMap,i,t)}discardShownData(){this.lastFeatureIds=[],this.lastFocusIds=null}restoreDataAndConfigImpl(){const e=this.sourcesWithLayers.incidents.shownFeatures;this.initSourcesWithLayers(this.config,!0),this.sourcesWithLayers.incidents.show(e,{automaticVisibility:!1}),this._applyConfig(this.config),null!==this.lastFocusIds&&this.lastFocusIds.length>0&&this.setFocus(this.lastFocusIds)}async show(e){await this.waitUntilModuleReady(),this.clearFeatureState(),this.lastFocusIds=null,this.lastFeatureIds=e.features.map(e=>e.properties.id).filter(e=>"string"==typeof e),this.sourcesWithLayers.incidents.show(e,{automaticVisibility:!1}),this.sourcesWithLayers.incidents.setLayersVisible(this.isVisible());for(const t of this.shownFeaturesHandlers)t(e)}async clear(){await this.waitUntilModuleReady(),this.clearFeatureState(),this.lastFeatureIds=[],this.lastFocusIds=null,this.sourcesWithLayers.incidents.clear()}getShown(){return{incidents:this.sourcesWithLayers.incidents.shownFeatures}}eventStateSources(){return["incidents"]}get events(){return this.moduleEventsWithShown(["incidents"],this.shownFeaturesHandlers)}setFocus(e){if(null===e||0===e.length)return this.lastFocusIds=null,void this.clearFeatureState();if(0===this.lastFeatureIds.length)return;this.lastFocusIds=e;const t=new Set(e),i=this.sourcesWithLayers.incidents.sourceAndLayerIDs.sourceID;for(const r of this.lastFeatureIds)this.mapLibreMap.setFeatureState({source:i,id:r},{focused:t.has(r)})}clearFeatureState(){if(0===this.lastFeatureIds.length)return;const e=this.sourcesWithLayers.incidents.sourceAndLayerIDs.sourceID;for(const t of this.lastFeatureIds)this.mapLibreMap.removeFeatureState({source:e,id:t})}},TrafficIncidentsModule=class e extends AbstractStyleOwnedMapModule{static async get(t,i){return await waitUntilMapIsReady(t),await ensureAddedToStyle(t,"vectorTilesIncidents","trafficIncidents"),sharedInstance(t,e,()=>new e(t,i),i&&(e=>e.applyConfig(i)))}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const t=this.mapLibreMap.getSource("vectorTilesIncidents");if(!t)throw notInTheStyle(`init ${e.name} with source ID vectorTilesIncidents`);return{trafficIncidents:new StyleSourceWithLayers(this.mapLibreMap,t)}}_applyConfig(e){return this._setVisible(e?.visible??!1,{updateConfig:!1}),isNil(e?.icons?.visible)||this._setIconsVisible(e.icons.visible,!1),this.applyFilters(e?.filters),e}applyFilters(e){if(this.tomtomMap.mapReady)if(e?.any?.length){const t=buildMapLibreAnyFilters(e,buildMapLibreIncidentsFilter);t&&applyFilter(t,this.getLayers(),this.filterComposer,"traffic.incidents")}else this.config?.filters?.any?.length&&applyFilter(void 0,this.getLayers(),this.filterComposer,"traffic.incidents")}getLayers(){return filterLayersBySources(this.tomtomMap.mapLibreMap,["vectorTilesIncidents"])}setIconsVisible(e){this._setIconsVisible(e)}_setIconsVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisible(e,e=>"symbol"===e.type),t&&(this.config={...this.config,icons:{...this.config?.icons,visible:e}},this.emitConfigChange())}setVisible(e){this._setVisible(e)}_setVisible(e,t){if(t?.updateConfig??1){const{icons:t,...i}=this.config??{},r=omit(t,"visible");this.config={...i,...!isEmpty(r)&&{icons:r},visible:e},this.emitConfigChange()}this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisible(e)}isVisible(){return this.config?.visible??!1}isIconsVisible(){return this.config?.icons?.visible??this.isVisible()}getShown(){return{trafficIncidents:this.mapLibreMap.queryRenderedFeatures({layers:this.sourcesWithLayers.trafficIncidents.sourceAndLayerIDs.layerIDs,validate:!1}).map(trafficIncidentMapping)}}get events(){return this.moduleEvents(["trafficIncidents"],{mapping:trafficIncidentMapping})}},getRelativeElementBounds=(e,t)=>({left:e.left-t.left,top:e.top-t.top,right:e.right-t.left,bottom:e.bottom-t.top}),isElementOutsideContainer=(e,t,i)=>e.right<=0||e.left>=t||e.bottom<=0||e.top>=i,adjustForHorizontalBar=(e,t,i,r)=>{e.top<=i-e.bottom?t.top=Math.max(t.top,e.bottom+r):t.bottom=Math.min(t.bottom,e.top-r)},adjustForVerticalBar=(e,t,i,r)=>{e.left<=i-e.right?t.left=Math.max(t.left,e.right+r):t.right=Math.min(t.right,e.left-r)},adjustVisibleBoundsForElement=(e,t,i,r,o)=>{const s=((e,t,i)=>({left:Math.max(0,e.left),top:Math.max(0,e.top),right:Math.min(t,e.right),bottom:Math.min(i,e.bottom)}))(e,i,r),a=e.left<=0&&e.right>=i,n=e.top<=0&&e.bottom>=r;if(a&&!n)return void adjustForHorizontalBar(s,t,r,o);if(n&&!a)return void adjustForVerticalBar(s,t,i,o);const l=e.left<=0,c=e.right>=i,d=e.top<=0,u=e.bottom>=r;!l&&!c||d||u?!d&&!u||l||c?((e,t,i,r,o)=>{const s=e.left,a=i-e.right,n=e.top,l=r-e.bottom,c=Math.min(s,a,n,l);c===s?t.left=Math.max(t.left,e.right+o):c===a?t.right=Math.min(t.right,e.left-o):c===n?t.top=Math.max(t.top,e.bottom+o):t.bottom=Math.min(t.bottom,e.top-o)})(s,t,i,r,o):adjustForVerticalBar(s,t,i,o):adjustForHorizontalBar(s,t,r,o)},toElement=e=>"string"==typeof e?document.querySelector(e):e,getMapLibreMap=e=>"mapLibreMap"in e?e.mapLibreMap:e,calculateVisibleAreaBounds=(e,t,i)=>{const r=getMapLibreMap(e).getContainer().getBoundingClientRect(),{width:o,height:s}=r,a={left:i,top:i,right:o-i,bottom:s-i};for(const n of t){const e=toElement(n);if(!e)continue;const t=e.getBoundingClientRect(),l=getRelativeElementBounds(t,r);isElementOutsideContainer(l,o,s)||adjustVisibleBoundsForElement(l,a,o,s,i)}return a.left>=a.right||a.top>=a.bottom?null:{visibleAreaBounds:a,mapWidthPX:o,mapHeightPX:s}},calculatePaddedBBox=e=>{const{map:t,surroundingElements:i,paddingPX:r=0}=e,o=calculateVisibleAreaBounds(t,i,r);if(!o)return null;const{visibleAreaBounds:s}=o,a=getMapLibreMap(t),n=a.unproject([s.left,s.bottom]),l=a.unproject([s.right,s.top]);return[n.lng,n.lat,l.lng,l.lat]},calculatePaddedCenter=e=>{const{map:t,surroundingElements:i}=e,r=calculatePaddedBBox({map:t,surroundingElements:i});return r?bboxCenter(r):null},calculateFittingBBox=e=>{const{map:t,toBeContainedBBox:i,surroundingElements:r,paddingPX:o=0}=e,s=calculateVisibleAreaBounds(t,r,o);if(!s)return null;const{visibleAreaBounds:a,mapWidthPX:n,mapHeightPX:l}=s,c=a.left/n,d=a.right/n,u=a.top/l,p=d-c,h=a.bottom/l-u,[y,f,m,g]=i,S=(m-y)/p,L=(g-f)/h,b=y-c*S,_=g+u*L;return[b,_-L,b+S,_]};export{AbstractDataOwnedMapModule,AbstractGeometriesModule,AbstractMapModule,AbstractSourceWithLayers,AbstractStyleOwnedMapModule,AddedSourceWithLayers,BASE_MAP_SOURCE_ID,BaseMapModule,CombinedEvents,CustomGeoJSONModule,DEFAULT_TEXT_SIZE,DESELECTED_FOREGROUND_COLOR,DESELECTED_OUTLINE_COLOR,DESELECTED_ROUTE_FILTER,DESELECTED_SECONDARY_COLOR,EventsProxy,FINISH_INDEX,GeoJSONSourceWithLayers,GeometriesModule,HILLSHADE_SOURCE_ID,INCIDENT_FOCUS_WIDTH_FACTOR_RANGE,INDEFINITE_DELAY_DASH_COLOR,LayerFilterComposer,LayerSelection,MAJOR_DELAY_COLOR,MAP_BOLD_FONT,MAP_ITALIC_FONT,MAP_MEDIUM_FONT,MAP_REGULAR_FONT,MIDDLE_INDEX,MINOR_DELAY_COLOR,MINOR_DELAY_LABEL_COLOR,MODERATE_DELAY_COLOR,ModuleEvents,POI_SOURCE_ID,POIsModule,PlacesModule,ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE,ROUTE_LINE_FOREGROUND_COLOR,ROUTE_LINE_FOREGROUND_WIDTH,ROUTE_LINE_OUTLINE_COLOR,ROUTE_LINE_OUTLINE_WIDTH,ROUTE_WAYPOINT_SIZE_FACTOR_RANGE,ROUTE_WIDTH_FACTOR_RANGE,ReachableRangesModule,RoutingModule,SECTION_ICON_SIZE_FACTOR_RANGE,SELECTED_ROUTE_FILTER,START_INDEX,STOP_DISPLAY_INDEX,StyleSourceWithLayers,StylingModule,TERRAIN_SOURCE_ID,TRAFFIC_FLOW_SOURCE_ID,TRAFFIC_INCIDENTS_SOURCE_ID,TerrainModule,TomTomMap,TomTomMapSource,TrafficAreaAnalyticsModule,TrafficFlowModule,TrafficIncidentDetailsModule,TrafficIncidentsModule,UNKNOWN_DELAY_BG_COLOR,UNKNOWN_DELAY_COLOR,UNKNOWN_DELAY_DASH_COLOR,UserEvents,UserEventsWithStates,areaAnalyticsPalettes,assertNoReservedScopeNames,baseMapColorNames,baseMapKnobCatalogue,baseMapKnobIds,baseMapLayerGroupNames,baseMapPOICategoryValues,bespokeSectionTypes,buildPlaceTitle,buildRoutingLayers,calculateFittingBBox,calculatePaddedBBox,calculatePaddedCenter,combineEventScopes,customGeoJSONKnobCatalogue,customGeoJSONKnobIds,defaultRoutingLayers,drawnSectionTypes,fillStyledGeometryConfig,filterLayersBySources,filterShowModes,findFeatureByRefId,formatStyleHsl,generatedSectionTypes,geometriesKnobCatalogue,geometriesKnobIds,geometryFillStyles,getIconIDForPlace,getInstructionArrowSize,getInstructionLineWidth,getInstructionOutlineWidth,getLineForegroundWidth,getLineOutlineWidth,getPOIGroupForPlace,getPOILayerCategoryForPlace,getSectionHaloWidth,getSectionIconSize,getStyleCategories,getWaypointIconSize,getWaypointIndexTextSize,hueDistance,mapColorNames,mapDisplayPoiCategoryMappings,mapFonts,mapStyleLayerIDs,parseCssColor,placesKnobCatalogue,placesKnobIds,placesMarkerTypes,poiCategoryGroups,poiLayerIDs,poisKnobCatalogue,poisKnobIds,preparePlacesForDisplay,reachableRangesKnobCatalogue,reachableRangesKnobIds,renderedRefId,reservedScopeNames,resolveColorStops,roadCategories,routingKnobCatalogue,routingKnobIds,scopedLayerSpecs,sectionDrawsByDefault,sectionSourceKey,sectionSupportsKnob,serviceRoadSubCategories,setKnob,sharedInstance,sharedInstanceIfCreated,standardStyleIDs,streetRoadSubCategories,styleParts,stylingColorKnobIds,stylingKnobAppliesTo,stylingKnobCatalogue,stylingKnobIds,stylingKnobKinds,stylingPresetCatalogue,stylingPresetIds,terrainKnobCatalogue,terrainKnobIds,toBaseMapPOICategory,toBaseMapPOIGroup,toHsl,toPlaces,trafficAreaAnalyticsKnobCatalogue,trafficAreaAnalyticsKnobIds,trafficFlowKnobCatalogue,trafficFlowKnobIds,trafficIncidentDetailsKnobCatalogue,trafficIncidentDetailsKnobIds,trafficIncidentsKnobCatalogue,trafficIncidentsKnobIds,validateKnobValue,withEventState};
2
2
  //# sourceMappingURL=map.es.js.map