@tomtom-org/maps-sdk 1.0.0-rc.4 → 1.0.0-rc.6

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,3 +1,5 @@
1
- import{get,has,isEmpty,isEqual,isNil,isObject,isPlainObject,setWith,toPath,unset}from"lodash-es";import{DEFAULT_COMMON_BASE_URL,MAX_MERCATOR_LATITUDE,MILE_IN_METERS,TomTomConfig,areaAnalyticsMetricKeys,bboxCenter,bboxFromGeoJSON,bboxLongitudeSpan,budgetUnits,canRetrySDKErrorCode,clamp,definedFields,formatDistance,formatDuration,fullTrafficIncidentCategories,generateId,generateTomTomHeaders,getDistinctSections,getPosition,iconToTrafficIncidentCategory,indexedMagnitudes,insecureBaseURLMessage,isProxyCredentialsMode,isSecureBaseURL,latticeCellOf,latticeCellPolygon,mergeFromGlobal,metersAlongLine,pickKeys,poiCategories,poiCategoriesToID,positionBetween,sdkErrorCodeForStatus,segmentAtMeters,servesGeopoliticalView,toPointGeometry,trafficIncidentLanguage,trafficIncidentTimeValidities,trafficIncidentToIconCategory}from"@tomtom-org/maps-sdk/core";import{clampRgb,differenceHueNaive,formatHex,formatHsl,formatRgb,interpolate,modeHsl,modeLrgb,modeOklch,modeRgb,parse,useMode,wcagLuminance}from"culori/fn";import{area,bearing,convertLength,difference,distance,featureCollection,mask,union}from"@turf/turf";import{Map as Map$1,MercatorCoordinate,getWorkerUrl,setWorkerCount,setWorkerUrl}from"maplibre-gl";var colorSpaces,loading,cachedImage,CombinedEvents=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}where(e,t){return this.#e.where(e,t)}on(e,t){return"config-change"===e?this.#t.on("config-change",t):"shown-features"===e?this.#t.on("shown-features",t):this.#e.on(e,t)}off(e){"config-change"===e||"shown-features"===e?this.#t.off(e):this.#e.off(e)}},asDefined=e=>{if(isNil(e))throw new Error(`${e} must not be null/undefined. Something went wrong with its initialization.`);return e},renderedRefId=e=>{const t=e.properties?.id;return"string"==typeof t||"number"==typeof t?t:e.id},isCluster=e=>!0===e.properties?.cluster&&void 0!==e.properties.cluster_id,shownRefId=e=>isCluster(e)?void 0:renderedRefId(e),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}},standardStyleIDs=["streetLight","streetDark","streetLightDriving","streetDarkDriving","monoLight","monoDark","streetSatellite"],styleParts=["trafficIncidents","trafficFlow","terrain"],stylePartURLParams={trafficIncidents:"trafficIncidents",trafficFlow:"trafficFlow",terrain:"hillshade"},lightStylePartValues={trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",terrain:"hillshade_light"},darkStylePartValues={trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",terrain:"hillshade_dark"},standardStylePartValues=/* @__PURE__ */(()=>({streetLight:lightStylePartValues,streetDark:darkStylePartValues,streetLightDriving:lightStylePartValues,streetDarkDriving:darkStylePartValues,monoLight:{...lightStylePartValues,terrain:"hillshade_mono-light"},monoDark:{...darkStylePartValues,terrain:"hillshade_mono-dark"},streetSatellite:{...lightStylePartValues,terrain:"hillshade_satellite"}}))(),mapSuffixes={streetLight:"basic_street-light",streetDark:"basic_street-dark",streetLightDriving:"basic_street-light-driving",streetDarkDriving:"basic_street-dark-driving",monoLight:"basic_mono-light",monoDark:"basic_mono-dark",streetSatellite:"basic_street-satellite"},setApiKeyParameter=(e,t)=>{t&&e.set("key",t)},buildStyleInput=e=>{const t=e.style;return((e,t,i)=>{const s=e.id??"streetLight",o=new URL(`${t}/maps/orbis/assets/styles/0.6.0-0/style.json`);o.searchParams.set("apiVersion","1"),setApiKeyParameter(o.searchParams,i),o.searchParams.set("map",mapSuffixes[s]);for(const r of e.include??styleParts)o.searchParams.append(stylePartURLParams[r],standardStylePartValues[s][r]);return o.toString()})("string"==typeof t?{id:t}:t??{},e.commonBaseURL,e.apiKey)},trafficRoadProperties=e=>({roadCategory:e?.road_category,leftHandTraffic:Boolean(e?.left_hand_traffic),...e?.road_subcategory&&{roadSubcategory:e.road_subcategory},...e?.part_of_two_way_road&&{partOfTwoWayRoad:Boolean(e.part_of_two_way_road)},...e?.openlr&&{openlr:e.openlr},...e?.display_class&&{displayClass:e.display_class}}),FLOW_TAGS=["road_category","road_subcategory","relative_speed","left_hand_traffic","road_closure","absolute_speed","part_of_two_way_road","openlr","display_class"],lineGeometryOf=({geometry:e})=>{if("LineString"===e.type||"MultiLineString"===e.type)return e;throw new Error(`Unexpected ${e.type} traffic flow geometry`)},trafficFlowMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:lineGeometryOf(e),properties:{...trafficRoadProperties(t),roadClosure:Boolean(t?.road_closure),relativeSpeed:t?.relative_speed,...!isNil(t?.absolute_speed)&&{absoluteSpeed:t.absolute_speed}}}},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],...trafficRoadProperties(t),...!isNil(t?.delay)&&{delayInSeconds:t.delay},...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},...!isNil(t?.number_of_reports)&&{numberOfReports:t.number_of_reports},...t?.last_report_time&&{lastReportTime:new Date(t.last_report_time)},...!isNil(t?.average_speed_kmph)&&{averageSpeedKmph:t.average_speed_kmph},...t?.time_validity&&{timeValidity:t.time_validity},...t?.point_type&&{pointType:t.point_type}}}},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),toBaseMapPOIImageID=e=>`poi-${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=>isDOMImageSupported()?urlToImg(`data:image/svg+xml;base64,${btoa((new XMLSerializer).serializeToString(e()))}`):void 0,svgMarkupToImg=e=>svgToImg(()=>parseSvg(e)),mapStyleLayerIDs={country:"Places - Country name",lowestPlaceLabel:"Places - Village / Hamlet",poi:"POI",lowestLabel:"Borders - Treaty label",lowest3D:"3D - Building",lowestRoadLine:"Tunnel - Railway outline",lowestBuilding:"Buildings - Underground"},MAP_BOLD_FONT="Noto-Bold",MAP_REGULAR_FONT="Noto-Regular",MAP_MEDIUM_FONT="Noto-Medium",MAP_ITALIC_FONT="NotoSans-MediumItalic",zoomRamp=(...e)=>["interpolate",["linear"],["zoom"],...e],DEFAULT_TEXT_SIZE=/* @__PURE__ */zoomRamp(10,14,18,16),mapFonts=["Noto-Regular","NotoSans-MediumItalic","Noto-Bold","Noto-Medium","NotoSans-RegularItalic","NotoSans-BoldItalic","NotoSerif-Regular","NotoSerif-Medium","NotoSerif-Bold","NotoSerif-RegularItalic","NotoSerif-MediumItalic","NotoSerif-BoldItalic"],mapTypefaces=["sans","sans-italic","serif","serif-italic"],PIN_ICON_SIZE=/* @__PURE__ */zoomRamp(8,.6,22,.8),SELECTED_PIN_ICON_SIZE=/* @__PURE__ */zoomRamp(8,.8,22,1),incidentColorKnobIds={minor:"traffic.incidents.colors.minor",moderate:"traffic.incidents.colors.moderate",major:"traffic.incidents.colors.major",indefinite:"traffic.incidents.colors.closed"},onStyleKnobsApplied=(e,t,i)=>{e._onStyleKnobsApplied(s=>{e.mapReady&&t.some(e=>s.has(e))&&i()})},FONT_ROLES=["regular","medium","bold","regularItalic","mediumItalic","boldItalic"],SANS={regular:"Noto-Regular",medium:"Noto-Medium",bold:"Noto-Bold",regularItalic:"NotoSans-RegularItalic",mediumItalic:"NotoSans-MediumItalic",boldItalic:"NotoSans-BoldItalic"},SERIF={regular:"NotoSerif-Regular",medium:"NotoSerif-Medium",bold:"NotoSerif-Bold",regularItalic:"NotoSerif-RegularItalic",mediumItalic:"NotoSerif-MediumItalic",boldItalic:"NotoSerif-BoldItalic"},inItalics=e=>({...e,regular:e.regularItalic,medium:e.mediumItalic,bold:e.boldItalic}),upright=e=>({...e,regularItalic:e.regular,mediumItalic:e.medium,boldItalic:e.bold}),FACES_BY_TYPEFACE={"sans-italic":/* @__PURE__ */inItalics(SANS),serif:SERIF,"serif-italic":/* @__PURE__ */inItalics(SERIF)},BACKSTOP=/* @__PURE__ */upright(SANS),builtInTypeface=e=>(e=>"string"==typeof e&&Object.hasOwn(FACES_BY_TYPEFACE,e))(e)?FACES_BY_TYPEFACE[e]:void 0,SDK_NAME="tomtom-sdk-(?:face|role)-[a-zA-Z0-9]+",SDK_NAME_IN_STACK=/* @__PURE__ */(()=>new RegExp(`${SDK_NAME},`,"g"))(),SDK_NAME_IN_JSON_STACK=/* @__PURE__ */(()=>new RegExp(`"${SDK_NAME}",`,"g"))(),withoutCustomFaceDeclarations=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!e.startsWith("tomtom-sdk-face-"))),customTypefaces=/* @__PURE__ */new WeakMap,customTypefaceOf=e=>customTypefaces.get(e),typefaceOf=(e,t)=>customTypefaceOf(e)??builtInTypeface(t),roleByServedFace=/* @__PURE__ */(()=>new Map([...[SANS,SERIF].flatMap(e=>FONT_ROLES.map(t=>[e[t],t])),["NotoSans-Condensed","regular"],["NotoSans-CondensedMedium","medium"],["NotoSans-CondensedBold","bold"]]))(),roleOf=e=>roleByServedFace.get(e)??(e=>{const t=e.startsWith("tomtom-sdk-role-")?e.slice(16):void 0;return FONT_ROLES.find(e=>e===t)})(e),isFace=e=>"string"==typeof e&&(roleByServedFace.has(e)||e.startsWith("tomtom-sdk-")),retypeset=(e,t)=>{const i=Array.isArray(e)&&e.every(isFace)?e.map(roleOf).find(Boolean):void 0;return void 0!==i?((e,t)=>{const i=t[e];return i===BACKSTOP[e]?[i]:i.startsWith("tomtom-sdk-face-")?[i,`tomtom-sdk-role-${e}`,BACKSTOP[e]]:[i,BACKSTOP[e]]})(i,t):Array.isArray(e)?e.map(e=>retypeset(e,t)):(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"text-font"in e)(e)?{...e,"text-font":retypeset(e["text-font"],t)}:e},inTypeface=(e,t)=>void 0===t?e:retypeset(e,t),withMapTypeface=(e,t)=>void 0===e.layout||void 0===t?e:{...e,layout:{...e.layout,...void 0!==e.layout["text-font"]&&{"text-font":inTypeface(e.layout["text-font"],t)},...void 0!==e.layout["text-field"]&&{"text-field":inTypeface(e.layout["text-field"],t)}}},mapTypefaceOf=e=>typefaceOf(e,e._styleKnobSettings["labels.typeface"]),onMapTypefaceChange=(e,t)=>onStyleKnobsApplied(e,["labels.typeface"],t),ofMap=(e,t,i)=>{let s=e.get(t);return void 0===s&&(s=i(),e.set(t,s)),s},waitUntilMapIsReady=e=>{if(e.mapReady)return Promise.resolve();const t=e._styleLoadError;if(t)return Promise.reject(t);const i=e.mapLibreMap;return new Promise((t,s)=>{const o=()=>{i.off("styledata",r),a()},r=()=>{e.mapReady&&(o(),t())},a=e._onStyleLoadFailure(e=>{o(),s(e)});i.on("styledata",r)})},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}},vectorTileSourceIds=e=>Object.entries(e.getStyle()?.sources??{}).filter(([,e])=>"vector"===e.type&&e.tiles?.some(isVectorTileUrl)).map(([e])=>e),reloadTiles=(e,t)=>{for(const i of t){if(!e.getSource(i))continue;const t=e.style.tileManagers[i];for(const e of t?.getIds()??[]){const i=t.getTileByID(e);i&&(i.etag=void 0)}e.refreshTiles(i)}},sdkTransformRequest=e=>{const t=e.commonBaseURL??DEFAULT_COMMON_BASE_URL,i=t!==DEFAULT_COMMON_BASE_URL,s=isProxyCredentialsMode(e);return(o,r)=>{const a="Glyphs"===r?o.replace(SDK_NAME_IN_STACK,""):o,n=((e,t,i,s)=>{if(!i)return e;try{const i=new URL(e);return"api.tomtom.com"===(o=i.hostname)||o.endsWith(".api.tomtom.com")?(s&&i.searchParams.delete("key"),t+i.pathname+i.search+i.hash):e}catch{return e}var o})(a,t,i,s),l=i&&((e,t)=>{try{const i=new URL(e),s=new URL(t),o=s.pathname.replace(/\/$/,"");return i.origin===s.origin&&(i.pathname===o||i.pathname.startsWith(`${o}/`))}catch{return!1}})(n,t),c=s&&l;let d=!1;try{const e=new URL(a).hostname;d="tomtom.com"===e||e.endsWith(".tomtom.com")}catch{d=!1}if(!d&&!l)return{url:n};if("Image"===r)return c?{url:n,credentials:"include"}:{url:n};const u=new URL(n);((e,t)=>{if(e.pathname.includes("incidents")){e.searchParams.set("tags",INCIDENT_TAGS.join(","));const i=trafficIncidentLanguage(t);i&&e.searchParams.set("language",i)}else e.pathname.includes("flow")&&e.searchParams.set("tags",FLOW_TAGS.join(","))})(u,e.language),((e,t)=>{const i=vectorTileViewParameter(e),s=t&&(e=>{if(servesGeopoliticalView(e,"mapTiles"))return"AE"===e?"Arabic":e})(t);i&&s&&e.searchParams.set(i,s)})(u,e.geopoliticalView);const h={url:u.toString(),headers:{...generateTomTomHeaders(e)}};return c&&(h.credentials="include"),h}},transformRequest=e=>{const t=sdkTransformRequest(e),i=e.transformRequest;return i?(e,s)=>i(t(e,s),s):t},changeLayerProps=(e,t,i)=>{const s=e.id;e.maxzoom===t.maxzoom&&e.minzoom===t.minzoom||i.setLayerZoomRange(s,e.minzoom??0,e.maxzoom??24),isEqual(e.filter,t.filter)||i.setFilter(s,e.filter,{validate:!1});for(const o of Object.keys(t.layout??{}))void 0===e.layout?.[o]&&i.setLayoutProperty(s,o,void 0,{validate:!1});for(const o of Object.keys(t.paint??{}))void 0===e.paint?.[o]&&i.setPaintProperty(s,o,void 0,{validate:!1});for(const[o,r]of Object.entries(e.paint??{}))isEqual(r,t.paint?.[o])||i.setPaintProperty(s,o,r,{validate:!1});for(const[o,r]of Object.entries(e.layout??{}))isEqual(r,t.layout?.[o])||i.setLayoutProperty(s,o,r,{validate:!1})},existingAnchorLayerID=(e,t)=>{if(!t)return;if(e.getLayer(t))return t;const i=t===mapStyleLayerIDs.lowest3D?mapStyleLayerIDs.poi:void 0;return i&&e.getLayer(i)?i:void 0},customLayerAnchorsByMap=/* @__PURE__ */new WeakMap,customLayerAnchorsOf=e=>ofMap(customLayerAnchorsByMap,e,()=>new globalThis.Map),existingBeforeLayerID=(e,t)=>{const i=existingAnchorLayerID(e,t);return belowCustomLayersAsking(e,i,e=>e===t||e===i)},belowCustomLayersAsking=(e,t,i)=>{const s=customLayerAnchorsByMap.get(e);if(!s?.size)return t;const o=e.getLayersOrder();let r=t?o.indexOf(t):o.length;for(let a=r-1;a>=0&&s.has(o[a]);a--)i(s.get(o[a]))&&(r=a);return o[r]},moveLayerBefore=(e,t,i)=>{e.moveLayer(t,existingBeforeLayerID(e,i))},applyLayersVisibility=(e,t,i)=>{if(i._removed)return;const s=t?"visible":"none";for(const o of e)"none"!==o.layout?.visibility&&i.getLayer(o.id)&&i.setLayoutProperty(o.id,"visibility",s,{validate:!1})},addLayers=(e,t,i=!1)=>{const s=ModuleSourcesAndLayers.for(t),o=/* @__PURE__ */new Set,r=e=>{!s.addLayer({...e,layout:{...e.layout,visibility:"none"}})&&i&&moveLayerBefore(t,e.id,e.beforeID),o.add(e.id)},a={},n=new Set(e.map(e=>e.id)),l=new Set(e.filter(e=>i||s.isCarried(e.id)).map(e=>e.id));for(e.forEach(e=>{var i;e.beforeID?(i=e.beforeID,o.has(i)||!l.has(i)&&(!n.has(i)||t.getLayer(i))?(o.add(e.beforeID),r(e)):a[e.beforeID]?a[e.beforeID].push(e):a[e.beforeID]=[e]):r(e)});Object.keys(a).length>0;){const e=Object.keys(a).filter(e=>o.has(e));if(!e.length)return void console.error(`Some layers cannot be added. Check for circular beforeID dependencies for the following: ${JSON.stringify(Object.keys(a))}`);e.forEach(e=>{a[e].forEach(e=>r(e)),delete a[e]})}},addOrUpdateImage=async(e,t,i,s,o,r=()=>!0)=>{if(void 0===i)return;if(!i)return void console.warn(`addOrUpdateImage called with empty image for ID ${t}`);const a=i=>{if(!r())return;if(!s.hasImage(t))return void s.addImage(t,i,o);if("if-not-in-sprite"===e)return;const a=s.getImage(t);a.data.width===i.width&&a.data.height===i.height&&a.pixelRatio===(o?.pixelRatio??1)?s.updateImage(t,i):(s.removeImage(t),s.addImage(t,i,o))},n=e=>{e&&(e.complete?e.naturalWidth>0?a(e):console.warn(`Failed to load image for ID ${t}`):(e.addEventListener("load",()=>a(e),{once:!0}),e.addEventListener("error",()=>console.warn(`Failed to load image for ID ${t}`),{once:!0})))};if("string"==typeof i)if(/^data:image\/svg\+xml[;,]/i.test(i))n(urlToImg(i));else if(i.includes("<svg"))n(svgMarkupToImg(i));else try{a((await s.loadImage(i)).data)}catch(l){console.warn(`Failed to load image for ID ${t}`,l)}else n(i)},imageLoadTokens=/* @__PURE__ */new WeakMap,syncImages=(e,t,i)=>{const s=ofMap(imageLoadTokens,e,()=>({}));for(const o of Object.keys(t))o in i||(delete s[o],e.hasImage(o)&&e.removeImage(o));for(const[o,{image:r,pixelRatio:a}]of Object.entries(i)){const i=t[o],n=i?.image===r&&i.pixelRatio===a;n&&s[o]||(s[o]={});const l=s[o];addOrUpdateImage(n?"if-not-in-sprite":"add-or-update",o,r,e,{pixelRatio:a},()=>s[o]===l)}return{...i}},darkStandardStyleIDs=/* @__PURE__ */(()=>new Set(standardStyleIDs.filter(e=>e.includes("Dark")||"streetSatellite"===e)))(),standardStyleIdOf=e=>("string"==typeof e?e:e?.id)??"streetLight",getStyleLightDarkTheme=e=>{return t=standardStyleIdOf(e),darkStandardStyleIDs.has(t)?"dark":"light";var t},pendingPinCategoriesSprites=/* @__PURE__ */new WeakMap,byMap=/* @__PURE__ */new WeakMap,ModuleSourcesAndLayers=class ModuleSourcesAndLayers{constructor(e){this.map=e,this.sourceIds=/* @__PURE__ */new Set,this.layerIds=/* @__PURE__ */new Set,this.carriedSourceIds=/* @__PURE__ */new Set,this.carriedLayerIds=/* @__PURE__ */new Set}static for(e){return ofMap(byMap,e,()=>new ModuleSourcesAndLayers(e))}addSource(e,t){this.sourceIds.add(e),this.carriedSourceIds.delete(e),this.map.getSource(e)||this.map.addSource(e,t)}addLayer(e){this.layerIds.add(e.id);const t=this.map.getLayer(e.id);if(!t)return this.map.addLayer(e,existingBeforeLayerID(this.map,e.beforeID)),!0;if(!this.carriedLayerIds.delete(e.id))return!1;const i=t.serialize();return changeLayerProps({...e,layout:{...e.layout,visibility:i.layout?.visibility}},i,this.map),moveLayerBefore(this.map,e.id,e.beforeID),!0}isCarried(e){return this.carriedLayerIds.has(e)}carryInto(e,t){if(this.carriedSourceIds.clear(),this.carriedLayerIds.clear(),!e)return t;const i={...t.sources},s=new Set(t.layers.map(e=>e.id)),o=/* @__PURE__ */new Map;let r=[];for(const n of e.layers){if(s.has(n.id)){r.length&&o.set(n.id,r),r=[];continue}if(!this.layerIds.has(n.id))continue;const t="source"in n?n.source:void 0;if(t&&!i[t]){if(!this.sourceIds.has(t))continue;i[t]=e.sources[t],this.carriedSourceIds.add(t)}this.carriedLayerIds.add(n.id),r.push(n)}const a=t.layers.flatMap(e=>[...o.get(e.id)??[],e]);return{...t,sources:i,layers:[...a,...r]}}dropUnadopted(){for(const e of this.carriedLayerIds)this.map.getLayer(e)&&this.map.removeLayer(e);for(const e of this.carriedSourceIds)this.map.getSource(e)&&this.map.removeSource(e);this.carriedLayerIds.clear(),this.carriedSourceIds.clear()}},TomTomMapSource=class{constructor(e,t,i){this.id=e,this.spec=t,this.runtimeSource=i}ensureAddedToMap(e){this.runtimeSource||(this.spec&&ModuleSourcesAndLayers.for(e).addSource(this.id,this.spec),this.runtimeSource=e.getSource(this.id))}},withSourceID=(e,t)=>({...e,source:t}),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))}queryRenderedFeatures(){const e=this._layerSpecs.filter(e=>this.isLayerVisible(e)).map(e=>e.id);return e.length?this.map.queryRenderedFeatures({layers:e,validate:!1}):[]}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=>"source"in e&&t.includes(e.source)),StyleSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i){let s=filterLayersBySources(e,[t.id]);i&&(s=s.filter(i)),super(e,new TomTomMapSource(t.id,e.getStyle().sources[t.id],t),s)}setLayersVisibleThrough(e,t,i,s){for(const o of this.getLayerSpecs(s))e.setVisible(o.id,t,i)}},AddedSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i,s){super(e,new TomTomMapSource(t,i),s.map(e=>withSourceID(e,t)))}ensureLayersAddedToMap(){if(this.mapRemoved)return;const e=ModuleSourcesAndLayers.for(this.map);for(const t of this._layerSpecs)e.addLayer(t)}ensureAddedToMapWithVisibility(e,t){this.mapRemoved||(this.source.ensureAddedToMap(this.map),t&&(this.ensureLayersAddedToMap(),this.setLayersVisible(e)))}},emptyFeatureCollection={type:"FeatureCollection",features:[]},propertyBySource=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,i])=>[e,i[t]])),shownFeaturesOf=e=>propertyBySource(e,"shownFeatures"),withEventState=(e,t)=>{if(t)return{...e,properties:{...e.properties,eventState:t}};const{eventState:i,...s}=e.properties??{};return{...e,properties:s}},withShownEventStates=(e,t,i)=>({...t,features:t.features.map(t=>withEventState(t,findFeatureByRefId(e.features,i(t))?.feature.properties?.eventState))}),GeoJSONSourceWithLayers=class extends AddedSourceWithLayers{constructor(e,t,i,s=!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,s)}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 void 0!==e.index?this.shownFeatures.features[e.index]:this.findById(e.id)?.feature}showWithFeatures(e,t=!0){const i={...this.shownFeatures,features:e};t?this.show(i,{automaticVisibility:!1}):this.shownFeatures=i}setEventState(e){const t=e.mode??"put",i=this.findFeature(e);this.showWithFeatures(this.shownFeatures.features.map(s=>s===i?withEventState(s,e.state):"put"===t&&s.properties?.eventState===e.state?withEventState(s,void 0):s),e.show)}clearEventState(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)}clearEventStates(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,s=renderedRefId(t);if(!i||void 0===s)continue;const o=e[i]??=[];o.includes(s)||o.push(s)}return e}},CustomLayerSourceWithLayers=class{constructor(e,t,i){this.map=e,this.layerId=t,this.callbacks=i,this.hits=/* @__PURE__ */new WeakMap,this.eventStates=new globalThis.Map,this.detached=!1,this.source={id:t},this._layerSpecs=[{id:t}]}hitFeatures(e){return this.map._removed||!this.map.getLayer(this.layerId)||"none"===this.map.getLayoutProperty(this.layerId,"visibility")?[]:this.callbacks.hitTest(e).map(e=>{const t={type:"Feature",id:e.id,properties:{...e.properties,id:e.id},layer:{id:this.layerId,type:"custom"},source:this.layerId,state:{}};return this.hits.set(t,e),t})}hitOf(e){return asDefined(this.hits.get(e))}eventStateOf(e){return this.eventStates.get(e)}idsWithEventState(){return[...this.eventStates.keys()]}putEventState(e,t){this.detached||this.eventStates.get(e)===t||(t?this.eventStates.set(e,t):this.eventStates.delete(e),this.callbacks.setState?.(e,t))}detach(){this.detached=!0,this.eventStates.clear()}},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),s=andPredicates(e.featureMatches,t.featureMatches);return i||s?{layerFilter:i,featureMatches:s}:void 0},scopedLayerIDs=(e,t)=>e instanceof CustomLayerSourceWithLayers?[e.layerId]:(t?.layerFilter?e._layerSpecs.filter(t.layerFilter):e._layerSpecs).map(e=>e.id),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(", ")}.`)},roundToDecimals=(e,t)=>{const i=10**t;return Math.round(e*i)/i},isLegacyFunction=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&Array.isArray(e.stops),scaleNumericValue=(e,t)=>mapNumericValue(e,e=>e*t,e=>["*",t,e]),mapNumericValue=(e,t,i)=>{if("number"==typeof e)return roundToDecimals(t(e),3);const s=e=>mapNumericValue(e,t,i);return isLegacyFunction(e)?mapLegacyStops(e,s):Array.isArray(e)?"interpolate"===e[0]||"step"===e[0]?mapRampOutputs(e,s):(e=>JSON.stringify(e).includes('"zoom"'))(e)?void 0:i(e):void 0},mapLegacyStops=(e,t)=>{const i=[];for(const[s,o]of e.stops){const e=t(o);if(void 0===e)return;i.push([s,e])}return{...e,stops:i}},mapRampOutputs=(e,t)=>{const i=[...e];for(let s="interpolate"===e[0]?4:2;s<i.length;s+=2){const e=t(i[s]);if(void 0===e)return;i[s]=e}return i},branchOn=(e,t,i,s)=>{const o=scaleNumericValue(t,i);if(void 0!==o)return void 0===s?["case",e,o,t]:["case",e,"number"==typeof o?Math.min(s,o):["min",s,o],t]},scaledWhen=(e,t,i,s)=>1===i||isLegacyFunction(t)?t:!Array.isArray(t)||"interpolate"!==t[0]&&"step"!==t[0]?branchOn(e,t,i,s)??t:mapRampOutputs(t,t=>branchOn(e,t,i,s))??t,shiftZoomOffset=(e,t)=>{let i=!1;const s=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(s):e;return{filter:s(e),patched:i}},registeredColorSpaces=()=>(colorSpaces??=(()=>{const e={toRgb:useMode(modeRgb),toHslSpace:useMode(modeHsl)};return useMode(modeLrgb),e})(),colorSpaces),themeContrastColor=e=>"dark"===e?"#FFF":"#000",toHundredths=e=>roundToDecimals(e,2),STYLE_COLOR_SYNTAX=/^(#|rgba?\(|hsla?\(|[a-z]+$)/,parseColor=e=>{registeredColorSpaces();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:s,b:o,alpha:r=1}=registeredColorSpaces().toRgb(t);return[i,s,o,r]},toHsl=e=>{const t=parseColor(e),{toRgb:i,toHslSpace:s}=registeredColorSpaces();return t&&s(i(t))},isColorLiteral=e=>"string"==typeof e&&void 0!==parseColor(e),formatStyleHsl=e=>formatHsl(roundStyleHsl(e)),roundStyleHsl=({h:e=0,s:t,l:i,alpha:s})=>({mode:"hsl",h:(Math.round(e)%360+360)%360,s:toHundredths(t),l:toHundredths(i),alpha:s}),opaqueColor=e=>{const t=toHsl(e);return t&&(t.alpha??1)<1?formatStyleHsl({...t,alpha:void 0}):e},clampUnit=e=>clamp(e,0,1),hslShiftBetween=(e,t)=>{const i=toHsl(e),s=toHsl(t);if(i&&s)return{h:i.s<.01||s.s<.01?0:(s.h??0)-(i.h??0),s:s.s-i.s,l:s.l-i.l,alpha:(s.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=>{registeredColorSpaces();const t=parseColor(e);return t&&wcagLuminance(t)},needsDarkText=e=>(relativeLuminance(e)??0)>.4,mixColor=(e,t,i)=>{registeredColorSpaces();const s=parseColor(e),o=parseColor(t);return s&&o&&formatHex(interpolate([s,o])(i))},oklchRegistered=!1,colorRamp=(e,t,{space:i="rgb",reach:s=1}={})=>{registeredColorSpaces(),"oklch"!==i||oklchRegistered||(useMode(modeOklch),oklchRegistered=!0);const o=e.map(parseColor);if(!o.length||o.some(e=>!e))return;const r=interpolate(o,i);return Array.from({length:t},(e,i)=>{const o=clampRgb(r(t>1?s*i/(t-1):0));return(o.alpha??1)<1?formatRgb(o):formatHex(o)})},darkerShadeOf=e=>mixColor(e,"#000000",.4),hueDistance=({h:e},{h:t})=>void 0===e||void 0===t?0:Math.abs(differenceHueNaive({h:e},{h:t})),filterShowModes=["only","all-except"],clampFactor=(e,t,i=1)=>void 0!==e&&Number.isFinite(e)?clamp(e,t.min,t.max):i,shallowCopy=e=>Array.isArray(e)?[...e]:{...e},copyOf=e=>isObject(e)?shallowCopy(e):void 0,configWith=(e,t,i)=>setWith(shallowCopy(e),t,i,copyOf),everyOf=()=>e=>e,valuesFilterKnobs=(e,t,i,s="")=>({show:{kind:"enum",description:`\`only\` keeps just the \`${e}.values\` ${t}, \`all-except\` every one but them; the filter applies once both are set.`,options:filterShowModes},values:{kind:"enums",description:`The ${t} \`${e}.show\` keeps alone or drops.${s}`,options:i}}),labelTypefaceKnob=(e,t,i=!0)=>({kind:"enum",description:`Typeface of the ${t}, each keeping its weight. Unset: the map's \`labels.customTypeface\`, otherwise its \`labels.typeface\`. A \`${e}.customTypeface\` of your own font files${i?`, or a \`${e}.font\`,`:""} wins over it.`,options:mapTypefaces}),withIds=e=>Object.keys(e).map(t=>({id:t,...e[t]})),defaultOf=e=>void 0===e?{}:{default:e},FACTOR_RANGE={min:.5,max:1.5,step:.1,bounds:"hard"},WIDE_FACTOR_RANGE=/* @__PURE__ */(()=>({...FACTOR_RANGE,max:2}))(),OPACITY_RANGE={min:0,max:1,step:.05,bounds:"hard"},LABEL_SIZE_RANGE={min:6,max:48,step:1,bounds:"hard-min"},LABEL_HALO_WIDTH_RANGE={min:0,max:10,step:.5,bounds:"hard-min"},ZOOM_RANGE={min:0,max:22,step:1,bounds:"hard"},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:s})=>"soft"===s||e>=t&&("hard-min"===s||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 s=t.filter(e=>!i(e));return s.length?`expects ${e}; ${s.map(describe).join(", ")} ${1===s.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}.`)},knobValueIn=(e,t)=>get(e,t),configWithKnobs=(e,t)=>Object.entries(t).reduce((e,[t,i])=>configWith(e,t,i),e),configWithoutKnob=(e,t)=>((e,t)=>{if(!has(e,t))return e;const i=configWith(e,t,void 0),s=toPath(t);unset(i,s);for(let o=s.length-1;o>0&&isEmpty(get(i,s.slice(0,o)));o--)unset(i,s.slice(0,o));return i})(e,t),knobEntryOf=(e,t)=>{const i=e.find(e=>e.id===t);if(!i)throw new Error(`Unknown knob '${t}'; its catalogue lists every id.`);return i},setKnob=(e,t,i,s)=>{validateKnobValue(knobEntryOf(t,i),s),e._setKnobValues({[i]:s})},setKnobs=(e,t,i)=>{const s=Object.entries(i);for(const[o,r]of s)validateKnobValue(knobEntryOf(t,o),r);s.length&&e._setKnobValues(i)},getKnob=(e,t,i)=>{const s=knobEntryOf(t,i).default;return e._knobValue(i)??s},resetKnob=(e,t,i)=>{knobEntryOf(t,i),e._resetKnobValue(i)},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]],toExpressionFilter=e=>isExpressionFilter(e)?e:(e=>{const t=e[0];if(e.length<=1)return"any"!==t;const i=e[1],s=e.slice(2),o=e.slice(1);switch(t){case"has":return convertHas(i);case"!has":return["!",convertHas(i)];case"==":case"!=":return(null===s[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),s[0]];case">":case">=":case"<":case"<=":return((e,t,i)=>["all",["==",["typeof",propertyAccessor(t)],typeof i],[e,propertyAccessor(t),i]])(t,i,s[0]);case"in":return convertIn(i,s);case"!in":return["!",convertIn(i,s)];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}})(e),getMergedFilter=(e,t)=>t?.length?1===t.length?t[0]:[e,...t]:null,isCompleteValuesFilter=e=>void 0!==e?.show&&void 0!==e.values,buildMappedValuesFilter=(e,t,i)=>{const s="string"==typeof e?["get",e]:e;if(1===i.length)return["only"===t?"==":"!=",s,i[0]];const o=["in",s,["literal",i]];return"only"===t?o:["!",o]},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)},composersByMap$1=/* @__PURE__ */new WeakMap,LayerFilterComposer=class LayerFilterComposer extends AbstractLayerComposer{constructor(e){super(e)}static for(e){return ofMap(composersByMap$1,e,()=>new LayerFilterComposer(e))}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;const i=ofMap(this.byLayer,e,()=>({styleFilter:this.mapLibreMap.getFilter(e),transforms:/* @__PURE__ */new Map,clauses:/* @__PURE__ */new Map}));t(i),this.apply(e,i)}apply(e,t){const i=[...t.transforms.values()].reduce((e,t)=>t(e),t.styleFilter),s=((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,s??null,{validate:!1})}},ModuleEvents=class{constructor(e,t){this.configChangeHandlers=e,this.shownFeaturesHandlers=t}on(e,t){return((e,t)=>(e.push(t),()=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)}))("config-change"===e?this.configChangeHandlers:this.shownFeaturesHandlers,t)}off(e){"config-change"===e?this.configChangeHandlers.length=0:this.shownFeaturesHandlers.length=0}},UserEvents=class UserEvents{constructor(e){this.options=e}where(e,t){return new UserEvents({...this.options,config:t?()=>t:this.options.config,scope:combineEventScopes(this.options.scope,this.resolveScope(e))})}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:s,owner:o,scope:r}=this.options,a=this.toRegisteredHandler(t),n=this.options.sourcesWithLayers();for(const l of n)i.addEventHandler(l,a,e,{config:s,owner:o,scope:r});return()=>{for(const t of n)i.removeHandler(t,e,a)}}toRegisteredHandler(e){const{mapping:t,scope:i}=this.options,s=i?.featureMatches,o=e=>t?t(e):e;return s||t?s?(t,i,r,a)=>{const n=r.length?r:[t];if(!s(n[0]))return;const l=n.filter(e=>s(e)).map(o);e(l[0],i,l,a)}:(t,i,s,r)=>e(o(t),i,s.map(o),r):(t,i,s,o)=>e(t,i,s,o)}off(e){for(const t of this.options.sourcesWithLayers())this.options.eventProxy.remove(t,e,this.options.owner)}},instanceCounters=/* @__PURE__ */new WeakMap,AbstractMapModule=class{constructor(e,t){this._initializing=!0,this.configChangeHandlers=[],this.moduleReady=!1;const i=new.target,s=instanceCounters.get(i)??-1;this.instanceIndex=s+1,instanceCounters.set(i,this.instanceIndex),this.tomtomMap=e,this.eventsProxy=e._eventsProxy,this.mapLibreMap=e.mapLibreMap,this.filterComposer=LayerFilterComposer.for(e),this.initSourcesWithLayers(t),this.applyConfig(t),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),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,t)=>{const i=setInterval(()=>{const s=this.tomtomMap._styleLoadError;this.mapLibreMap._removed?clearInterval(i):s?(clearInterval(i),t(s)):this.tomtomMap.mapReady&&this.moduleReady&&(clearInterval(i),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.slice())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}}_knobValue(e){return knobValueIn(this.config,e)}_setKnobValues(e){this.applyConfig(configWithKnobs(this.config??{},e))}_resetKnobValue(e){if(!this.config)return;const t=configWithoutKnob(this.config,e);this.applyConfig(isEmpty(t)?void 0:t)}get sourceAndLayerIDs(){return propertyBySource(this.sourcesWithLayers,"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,scope:t.scope}}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}set(e){for(const t of this.sources())t.setEventState(e)}clear(e){for(const t of this.sources())t.clearEventState(e)}clearAll(e){for(const t of this.sources())t.clearEventStates(e)}get(){const e={};for(const t of this.sources())t.getEventStates(e);return e}},UserEventsWithStates=class extends UserEvents{constructor(e){super(e),this.eventStates=new EventStates(e.sourcesWithLayers)}setEventState(e){this.eventStates.set(e)}clearEventState(e){this.eventStates.clear(e)}clearEventStates(e){this.eventStates.clearAll(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))}setEventState(e){this.eventStates.set(e)}clearEventState(e){this.eventStates.clear(e)}clearEventStates(e){this.eventStates.clearAll(e)}getEventStates(){return this.eventStates.get()}replaceSourceLayers(e,t,i){((e,t,i,s)=>{const o=Object.fromEntries(e.map(e=>[e.id,e])),r=Object.fromEntries(t.map(e=>[e.id,e])),a=[],n=[],l=[],c=[];Object.keys(o).forEach(e=>{r[e]?(l.push(o[e]),c.push(r[e])):a.push(e)}),Object.keys(r).forEach(e=>{o[e]||n.push(e)});const d=i._layerSpecs;n.forEach(e=>{s.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=>withSourceID(o[e],i.source.id));u.length&&(d.push(...u),addLayers(u,s)),i._updateSourceAndLayerIDs(),((e,t,i,s)=>{const o=/* @__PURE__ */new Set,r=e=>{s.getLayer(e.id)&&(moveLayerBefore(s,e.id,e.beforeID),o.add(e.id))};e.forEach((e,i)=>{e.beforeID!==t[i].beforeID&&r(e)});const a=()=>[...e,...i].filter(e=>!o.has(e.id)&&void 0!==e.beforeID&&o.has(e.beforeID));for(let n=a();n.length;n=a())n.forEach(r)})(l,c,u,s),((e,t,i)=>{e.forEach((e,s)=>changeLayerProps(e,t[s],i))})(l,c,s);for(const h of l){const e=d.findIndex(e=>e.id===h.id);-1!==e&&(d[e]=withSourceID(h,i.source.id))}})(e,t,i,this.mapLibreMap),this.eventsProxy.updateIfRegistered(this.sourcesWithLayers,this)}},composersByMap=/* @__PURE__ */new WeakMap,LayerVisibilityComposer=class LayerVisibilityComposer extends AbstractLayerComposer{constructor(e){super(e)}static for(e){return ofMap(composersByMap,e,()=>new LayerVisibilityComposer(e))}setVisible(e,t,i){if(this.mapLibreMap._removed||!this.mapLibreMap.getLayer(e))return;let s=this.byLayer.get(e);if(!s){if(void 0===i)return;s={styleVisibility:this.mapLibreMap.getLayoutProperty(e,"visibility")??"visible",contributions:/* @__PURE__ */new Map},this.byLayer.set(e,s)}setOrDelete(s.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})(s),{validate:!1})}},AbstractStyleOwnedMapModule=class extends AbstractMapModule{get visibilityComposer(){return LayerVisibilityComposer.for(this.tomtomMap)}},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",linePatterns=["solid","dashed","dotted"],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))&&matchesOneOf(e.ids,t.id)&&((e,t)=>{const i=t.id.toLowerCase(),s=e=>i.includes(e.toLowerCase());return!(e.idIncludes&&!e.idIncludes.some(s)||e.idExcludes?.some(s))})(e,t),matchesAnyLayerSelector=(e,t,i)=>e.some(e=>matchesLayerSelector(e,t,i)),LayerPartToggles=class{constructor(e,t){this.contributor=e,this.selectors=t,this.layerIds=/* @__PURE__ */new Map,this.styleVisibility=/* @__PURE__ */new Map}index(e){this.layerIds=/* @__PURE__ */new Map,this.styleVisibility=/* @__PURE__ */new Map;for(const[t,i]of Object.entries(this.selectors)){const s=e.filter(e=>matchesAnyLayerSelector(i,e));this.layerIds.set(t,s.map(e=>e.id)),s.length&&this.styleVisibility.set(t,"none"!==s[0].layout?.visibility)}}apply(e,t){for(const[i,s]of this.layerIds){const o=get(t,i);for(const t of s)e.setVisible(t,`${this.contributor}.${i}`,o)}}valueOf(e){return this.styleVisibility.get(e)}},instancesByMap=/* @__PURE__ */new WeakMap,sharedInstance=async(e,t,i,s)=>{const o=ofMap(instancesByMap,e,()=>/* @__PURE__ */new Map),r=o.get(t);if(r){const e=await r;return s?.(e),e}const a=Promise.resolve().then(i);o.set(t,a);try{return await a}catch(n){throw o.delete(t),n}},getStyleOwnedModule=async(e,t,i,s,o)=>(await waitUntilMapIsReady(e),o&&await(async(e,t,i)=>{if(!e.mapLibreMap.getSource(t)){const s=e.mapLibreMap;s.isStyleLoaded()||await s.once("idle"),await e.setStyle(((e,t)=>{switch(typeof e){case"undefined":return{type:"standard",include:[t]};case"string":return{type:"standard",id:e,include:[t]};default:return e.include?e.include.includes(t)?e:{...e,include:[...e.include,t]}:{...e,include:[t]}}})(e.getStyleInput(),i)),await(async(e,t)=>{e.mapLibreMap.getSource(t)&&e.mapLibreMap.isSourceLoaded(t)||await e.mapLibreMap.once("sourcedata")})(e,t)}})(e,o.sourceId,o.part),sharedInstance(e,t,i,s?e=>e.applyConfig(s):void 0)),styleSourceWithLayers=(e,t,i,s)=>{const o=e.getSource(t);if(!o)/* @__PURE__ */throw new Error(`Trying to init ${i} with source ID ${t} while it is not in the map style. Did you exclude it when loading the map?`);return new StyleSourceWithLayers(e,o,s)},POI_MICRO_LAYER_ID=/* @__PURE__ */(()=>`${mapStyleLayerIDs.poi} - Micro`)(),poiLayerIDs=/* @__PURE__ */(()=>[mapStyleLayerIDs.poi,POI_MICRO_LAYER_ID])(),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=({show:e,values:t})=>{const i=e=>t.some(t=>isMatching(t,e));return"only"===e?i:e=>!i(e)},baseMapLayerFilter=e=>!poiLayerIDs.includes(e.id),roadPartSelectors={"roads.exitNumbers.visible":[{metadataGroups:["road_label"],layerTypes:["symbol"],idIncludes:["exit"]}],"roads.arrows.visible":[{metadataGroups:["road"],layerTypes:["symbol"],idIncludes:["arrow"]}],"roads.restricted.visible":[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["restricted"]}],"roads.underConstruction.visible":[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["construction"]}]},isGroupName=e=>baseMapLayerGroupNames.includes(e),groupsVisible=(e,t)=>Object.fromEntries(e.map(e=>[e,{visible:t}])),groupsWithout=(e,t)=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>!(isGroupName(e)&&t.includes(e)))),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 s=t.flatMap(e=>i[e]),o=/* @__PURE__ */new Map,r=(e,t)=>{o.delete(e),o.set(e,t)};for(const a of t)r(a,e?.visible);for(const[a,n]of groupEntries(e?.groups)){const e=i[a],o=t.includes(a)||e.length&&containsAll(s,e)?[a]:t.filter(t=>i[t].length&&containsAll(e,i[t]));for(const t of o)r(t,n)}return Object.fromEntries([...o].map(([e,t])=>[e,void 0===t?{}:{visible:t}]))},BaseMapModule=class BaseMapModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,BaseMapModule,()=>new BaseMapModule(e,t),t)}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const e=styleSourceWithLayers(this.mapLibreMap,"vectorTiles",BaseMapModule.name,baseMapLayerFilter);return this.layersByGroup=void 0,this.roadParts=new LayerPartToggles("baseMap",roadPartSelectors),this.roadParts.index(e._layerSpecs),{vectorTiles:e}}_applyConfig(e){return!e&&this._initializing||this.writeVisibility(e),e}_knobValue(e){return super._knobValue(e)??this.roadParts.valueOf(e)}_setKnobValues(e){const t=this.config??{},i=Object.keys(e).map(e=>e.split(".")).flatMap(([e,t])=>"groups"===e&&isGroupName(t)?[t]:[]),s=t.groups&&groupsWithout(t.groups,i);this.applyConfig(configWithKnobs(s?{...t,groups:s}:t,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,{groups:s,...o}=this.config??{};this.applyConfig(i?((e,{show:t,values:i},s,o)=>"all-except"===t?{...e,visible:s,groups:groupsAsRecorded(e,i,o)}:{...e,groups:{...groupsWithout(e?.groups,i),...groupsVisible(i,s)}})(this.config,i,e,this.groupedLayers()):{...o,visible:e})}writeVisibility(e){if(this.tomtomMap.mapReady){for(const[t,i]of this.layerSettings(e))this.visibilityComposer.setVisible(t,"baseMap.visible",i);this.roadParts.apply(this.visibilityComposer,e)}}layerSettings(e,t){const i=this.groupedLayers(),s=/* @__PURE__ */new Map;for(const[r,a]of groupEntries(e?.groups))for(const e of i[r])s.set(e,a);const o=/* @__PURE__ */new Map;for(const r of this.sourcesWithLayers.vectorTiles._layerSpecs)t&&!t(r)||o.set(r.id,s.has(r.id)?s.get(r.id):e?.visible);return o}getLayers(){return Object.fromEntries(Object.entries(this.groupedLayers()).map(([e,t])=>[e,[...t]]))}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"},roadPartContents={exitNumbers:"Motorway exit number badges",arrows:"One-way arrows drawn on roads",restricted:"Dashed marking of roads with restricted access",underConstruction:"Roads under construction"},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)})),...Object.keys(roadPartContents).map(e=>({id:`roads.${e}.visible`,kind:"toggle",description:`${roadPartContents[e]}; never shown while its layer group is hidden.`}))],baseMapKnobCatalogue=/* @__PURE__ */buildCatalogue$2(),baseMapKnobIds=/* @__PURE__ */baseMapKnobCatalogue.map(({id:e})=>e),beforeLayerTargetOf=(e,t)=>"string"==typeof e?e:e?.[t]??e?.all,beforeLayerIDOf=(e,t)=>"top"===e?t:mapStyleLayerIDs[e],partBeforeLayerIDOf=(e,t,i)=>{const s=beforeLayerTargetOf(e,t);return void 0===s?i:beforeLayerIDOf(s)},CustomGeoJSONModule=class CustomGeoJSONModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),validateConfig(t),new CustomGeoJSONModule(e,t)}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 s={};for(const o of Object.keys(i.sources)){const e=this.resolvedSourceIDs[o],t=this.resolvedLayerSpecs[o],r=i.sources[o].cluster;s[o]=new GeoJSONSourceWithLayers(this.mapLibreMap,e,t,!1,r)}return addLayers(Object.values(s).flatMap(e=>e._layerSpecs),this.mapLibreMap),s}registerImages(e){if(this.addedImages??=/* @__PURE__ */new Map,e.images)for(const[t,i]of Object.entries(e.images)){if(this.mapLibreMap.hasImage(t)){const e=this.addedImages.get(t);if(!e||e.image===i.image&&isEqual(e.options,i.options))continue;this.mapLibreMap.removeImage(t)}this.mapLibreMap.addImage(t,i.image,i.options),this.addedImages.set(t,i)}}sourceIDOf(e,t){return t.sources[e].sourceID??`custom-geojson-${this.instanceIndex}-${String(e)}`}assertSameSources(e){const t=Object.keys(e.sources);if(t.length!==Object.keys(this.resolvedSourceIDs).length||!t.every(t=>this.resolvedSourceIDs[t]===this.sourceIDOf(t,e)))throw new Error("CustomGeoJSONModule keeps the source names and sourceIDs it was created with. Recreate the module to change them.")}resolveIDs(e){const t={},i={};for(const s of Object.keys(e.sources)){const o=e.sources[s],r=this.sourceIDOf(s,e);t[s]=r,i[s]=o.layers.map(({beforeLayerConfig:t=e.beforeLayerConfig??"top",...i},s)=>({...i,id:i.id??`${r}-layer-${s}`,beforeID:beforeLayerIDOfCustom(t)}))}this.resolvedSourceIDs=t,this.resolvedLayerSpecs=i}_applyConfig(e){if(!e)return this._applyConfig(this.initialConfig);this.initialConfig??=e;const t=this.config;t&&this.assertSameSources(e);const 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 s of Object.keys(this.resolvedLayerSpecs)){const t=e[s],i=this.resolvedLayerSpecs[s],o=this.sourcesWithLayers[s];t&&o&&this.replaceSourceLayers(i,t,o)}const t=Object.values(this.sourcesWithLayers).flatMap(e=>e._layerSpecs),i=new Set(t.map(e=>e.id));addLayers(t.filter(e=>e.beforeID&&i.has(e.beforeID)),this.mapLibreMap,!0)}applyVisibility(e){const t=!1!==e?.visible;for(const i of Object.keys(this.sourcesWithLayers))this.applySourceVisibility(i,t)}applySourceVisibility(e,t){const i=!!this.sourcesWithLayers[e].shownFeatures.features.length;applyLayersVisibility(this.resolvedLayerSpecs[e],t&&i,this.mapLibreMap)}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.drawOnSource(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=this.drawOnSource(e,t);for(const s of this.shownFeaturesHandlers)s({sourceName:e,data:i})}drawOnSource(e,t){const i=ensureFeatureIDs(t);return this.shownSourceNames.add(e),this.sourcesWithLayers[e].show(i,{automaticVisibility:!1}),this.applySourceVisibility(e,this.isVisible()),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(){return shownFeaturesOf(this.sourcesWithLayers)}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)}},beforeLayerIDOfCustom=e=>"string"==typeof e?beforeLayerIDOf(e):e.layerID,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 s of e.features)if(null==s.id||s.properties?.id!==s.id){t=!0;break}if(!t)return e;const i=new Set(e.features.map(e=>e.id??e.properties?.id));return{...e,features:e.features.map((e,t)=>{const s=e.id??e.properties?.id??(e=>{let t=e;for(;i.has(t);)t++;return i.add(t),t})(t);return{...e,id:s,properties:{...e.properties,id:s}}})}},CustomLayer=class{constructor(e,t,i){this.removed=!1;const s=customLayerAnchorsOf(e.mapLibreMap);if(s.has(t.id)||e.mapLibreMap.getLayer(t.id))throw new Error(`The map already has a layer with the id '${t.id}'.`);this.map=e,this.layer=t,this.options=i,this.id=t.id;const o=e._eventsProxy,r=i.hitTest?new CustomLayerSourceWithLayers(e.mapLibreMap,t.id,i):void 0;this.hitSource=r,r&&o.addCustomLayer(r),this.events=new UserEvents({eventProxy:o,sourcesWithLayers:()=>r&&!this.removed?[r]:[],owner:this,config:()=>i.events,mapping:r&&(e=>r.hitOf(e))}),s.set(this.id,this.anchorLayerID()),this.stopRestoring=e.addStyleChangeHandler({priority:-1,onStyleChanged:()=>this.place()}),this.placeOnceReady()}remove(){if(this.removed)return;this.removed=!0,this.stopRestoring(),this.hitSource&&this.map._eventsProxy.removeCustomLayer(this.hitSource);const e=this.map.mapLibreMap;customLayerAnchorsOf(e).delete(this.id),!e._removed&&e.getLayer(this.id)&&e.removeLayer(this.id)}placeOnceReady(){this.map.mapReady?this.place():waitUntilMapIsReady(this.map).then(()=>this.place(),()=>{})}place(){if(this.removed)return;const e=this.map.mapLibreMap,t=((e,t)=>{const i=existingAnchorLayerID(e,t);return i===t?i:belowCustomLayersAsking(e,i,e=>e===i)})(e,this.anchorLayerID());e.getLayer(this.id)?e.moveLayer(this.id,t):e.addLayer(this.layer,t)}anchorLayerID(){return beforeLayerIDOf(this.options.beforeLayerConfig??"top")}},customGeoJSONKnobDefinitions={visible:{kind:"toggle",description:"Every layer of every source.",default:!0}},customGeoJSONKnobCatalogue=/* @__PURE__ */withIds(customGeoJSONKnobDefinitions),customGeoJSONKnobIds=/* @__PURE__ */customGeoJSONKnobCatalogue.map(({id:e})=>e),mapAccentColor=e=>e.mapColors.accent,onMapColorsChange=(e,t,i)=>{let s=pickKeys(e.mapColors,t);e._onMapColorsChange(e=>{const o=pickKeys(e,t);isEqual(o,s)||(s=o,i())})},onAccentColorChange=(e,t)=>onMapColorsChange(e,["accent"],t),NEAREST_FIRST={regular:["regular","medium","bold"],medium:["medium","regular","bold"],bold:["bold","medium","regular"]},LATIN=["U+0000-00FF","U+0131","U+0152-0153","U+02BB-02BC","U+02C6","U+02DA","U+02DC","U+0304","U+0308","U+0329","U+2000-206F","U+20AC","U+2122","U+2191","U+2193","U+2212","U+2215","U+FEFF","U+FFFD"],nearest=(e,t)=>NEAREST_FIRST[t].map(t=>e[t]).find(e=>void 0!==e),declaredTypefaces=/* @__PURE__ */new WeakMap,declareCustomTypeface=e=>ofMap(declaredTypefaces,e,()=>(e=>{const t={regular:e.regular,medium:e.medium,bold:e.bold},i={regular:e.regularItalic,medium:e.mediumItalic,bold:e.boldItalic},s=e.unicodeRange??LATIN,o={},r=(r,a)=>{const n=(a?nearest(i,r):void 0)??nearest(t,r)??e.regular,l=("string"==typeof n?[{url:n,unicodeRange:s}]:n).map(e=>({url:e.url,"unicode-range":[...e.unicodeRange]})),c=`tomtom-sdk-face-${(e=>{let t=0;for(const i of e)t=Math.imul(31,t)+(i.codePointAt(0)??0);return(t>>>0).toString(36)})(JSON.stringify(l))}`;return o[c]=l,c};return{typeface:{regular:r("regular",!1),medium:r("medium",!1),bold:r("bold",!1),regularItalic:r("regular",!0),mediumItalic:r("medium",!0),boldItalic:r("bold",!0)},fontFaces:o}})(e)),labelTypefaceOf=(e,t)=>{return(e?.customTypeface&&declareCustomTypeface(e.customTypeface).typeface)??(i=e?.typeface,"sans"===i?SANS:builtInTypeface(i))??t;var i},customFacesOf=e=>Object.assign({},...e.map(e=>e?.customTypeface&&declareCustomTypeface(e.customTypeface).fontFaces)),declarations=/* @__PURE__ */new WeakMap,fontFacesToSet=(e,{faces:t})=>{const i=e.mapLibreMap.getFontFaces()??{},s=Object.assign(withoutCustomFaceDeclarations(i),...t.values());return isEqual(i,s)?void 0:s},runWaiting=({waiting:e})=>{const t=[...e.values()];e.clear();for(const i of t)i()},syncFontFaces=(e,t)=>{const i=e.mapLibreMap;if(!fontFacesToSet(e,t))return runWaiting(t),!1;const s=()=>{const s=fontFacesToSet(e,t);s&&i.setFontFaces(isEmpty(s)?null:s),runWaiting(t)},o=()=>{i.loaded()&&(i.off("render",o),s())};return isEmpty(i.getFontFaces())||i.loaded()?s():i.on("render",o),!0},declareFontFaces=(e,t,i)=>{const s=isEmpty(i)?void 0:i,o=declarations.get(e);if(o?.waiting.delete(t),!s&&!o?.faces.has(t))return!1;const r=(e=>ofMap(declarations,e,()=>{const t={faces:/* @__PURE__ */new Map,waiting:/* @__PURE__ */new Map};return e.addStyleChangeHandler({onStyleChanged:()=>{syncFontFaces(e,t)}}),t}))(e);return s?r.faces.set(t,s):r.faces.delete(t),e.mapReady&&syncFontFaces(e,r)},themeAdaptiveLabelColors=e=>({textColor:"dark"===e?"#FFFFFF":"#333333",haloColor:"dark"===e?"#333333":"#FFFFFF"}),themeAdaptiveLabelShadeOf=(e,t)=>("dark"===t?(e=>mixColor(e,"#ffffff",.4))(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}}),featureTitle=(e,t,i)=>"function"==typeof t?t(e):i(e),titleTextField=(e,t)=>void 0!==e&&"function"!=typeof e?e:t,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"},byOutlineFillStyle=(e,t)=>["case",["==",["get","fillStyle"],"outline"],e,t],BORDER_LABEL_OFFSET=[0,1],getThemeAdaptiveGeometryColors=e=>({defaultColor:"dark"===e?"#5FA8D8":"#0A3653",...themeAdaptiveLabelColors(e)}),isClickEventState=["in",["get","eventState"],["literal",["click","contextmenu"]]],hasActiveEventState=["all",["has","eventState"],["!=",["get","eventState"],"recently-hovered"]],DASH_ARRAYS={solid:void 0,dashed:[2,1.5],dotted:[0,1.5]},linePatternDashArray=e=>e&&DASH_ARRAYS[e],linePatternLayout=e=>"dotted"===e?{"line-cap":"round"}:void 0,pinIconBaseLayout={"icon-image":["get","iconID"],"icon-anchor":"bottom","icon-size":PIN_ICON_SIZE,"icon-allow-overlap":!0,"icon-padding":0},PIN_TRANSLATE=[0,5],pinIconBasePaint={"icon-translate":PIN_TRANSLATE,"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":/* @__PURE__ */zoomRamp(6,1,10,1.5),"text-translate-anchor":"viewport"},pinLayerBaseSpec=/* @__PURE__ */(()=>({type:"symbol",layout:{...pinIconBaseLayout,...pinTextBaseLayout},paint:{...pinIconBasePaint,...pinTextBasePaint}}))(),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,mergeLayerOverride=(e,t)=>{if(!t)return e;const{beforeID:i,...s}=t;return mergeLayer(e,s)},fillOpacityByStyle=/* @__PURE__ */byOutlineFillStyle(0,.15),lineWidthByStyle=/* @__PURE__ */byOutlineFillStyle(5,2),highlightedFillOpacity=(e,t)=>scaledWhen(hasActiveEventState,e,clampFactor(t?.fill?.opacityFactor,HIGHLIGHT_FILL_OPACITY_FACTOR_RANGE,2),1),highlightedLineWidth=(e,t)=>scaledWhen(hasActiveEventState,e,clampFactor(t?.line?.widthFactor,HIGHLIGHT_LINE_WIDTH_FACTOR_RANGE,1.75)),buildGeometryLayerSpecs=(e,t,i,s="#0A3653")=>{const o=i?.fill,r=i?.line,a=i?.highlight,n=(Array.isArray(o?.color)?o.color:void 0)??i?.color,l=(e=>({type:"fill",paint:{"fill-color":["coalesce",["get","color"],e],"fill-opacity":fillOpacityByStyle,"fill-antialias":!1}}))(n??s),c=((e,t="#555555")=>({type:"line",paint:{"line-color":/* @__PURE__ */byOutlineFillStyle(["coalesce",["get","color"],t],["coalesce",["get","color"],e]),"line-opacity":/* @__PURE__ */byOutlineFillStyle(.9,1),"line-width":lineWidthByStyle}}))(n??s,n),d=linePatternDashArray(r?.pattern),u=linePatternLayout(r?.pattern),h={...l,id:e,paint:{...l.paint,"fill-opacity":highlightedFillOpacity(o?.opacity??fillOpacityByStyle,a)}},p={...c,id:t,...u&&{layout:u},paint:{...c.paint,...!isNil(r?.color)&&{"line-color":r?.color},"line-width":highlightedLineWidth(r?.width??lineWidthByStyle,a),...!isNil(r?.opacity)&&{"line-opacity":r?.opacity},...d&&{"line-dasharray":d}}};return[mergeLayerOverride(h,i?.layers?.fill),mergeLayerOverride(p,i?.layers?.line)]},buildGeometryTitleLayerSpec=(e,t,i="light",s)=>{const o=t?.label,{textColor:r,haloColor:a}=getThemeAdaptiveGeometryColors(i);return mergeLayerOverride({type:"symbol",id:e,layout:{"text-field":o?.title??["get","title"],"text-padding":5,"text-size":15,"text-font":inTypeface(["Noto-Bold"],labelTypefaceOf(o,s)),...labelLayoutProperties(o),"symbol-placement":"point"},paint:{"text-color":r,"text-halo-color":a,...pinTextBasePaint,...labelPaintProperties(o)}},t?.layers?.label)},buildGeometryLineLabelLayerSpec=(e,t,i="light",s)=>{const o=t?.lineLabel,{textColor:r,haloColor:a}=getThemeAdaptiveGeometryColors(i);return mergeLayerOverride({type:"symbol",id:e,minzoom:o?.minZoom??3,layout:{"text-field":o?.title??["get","title"],"symbol-placement":"line","text-size":15,"text-font":inTypeface(["Noto-Bold"],labelTypefaceOf(o,s)),...labelLayoutProperties(o),"symbol-spacing":o?.symbolSpacing??200,"text-keep-upright":!0,"text-offset":o?.offset??BORDER_LABEL_OFFSET},paint:{"text-color":r,"text-halo-color":a,"text-halo-width":2,...labelPaintProperties(o)}},t?.layers?.lineLabel)},paletteColors=(e,t,i)=>"ramp"===t&&colorRamp(e,i,{space:"oklch"})||Array.from({length:i},(t,i)=>e[i%e.length]),geometryParts=["fill","line"],layerOnlyConfigKeys=["beforeLayerConfig","visible","events","highlight","layers","line","color"],withoutLayerOnlyKeys=e=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>!layerOnlyConfigKeys.includes(e))),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))}),onMapTypefaceChange(e,()=>this.updateLayers(this.displayConfig(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),[s,o]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,i,this.defaultColor),{titleLayerSpec:r,lineLabelSpec:a}=this.labelLayerSpecs(i);return this.titleLayerSpecs=r,this.geometryFillLayerSpecs=s,this.geometryOutlineLayerSpecs=o,this.lineLabelLayerSpecs=a,{geometry:new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,[s,o,a]),geometryLabel:new GeoJSONSourceWithLayers(this.mapLibreMap,this.titleSourceID,[r])}}_applyConfig(e){const t=this.displayConfig(e);declareFontFaces(this.tomtomMap,this,customFacesOf([t?.label,t?.lineLabel])),this.updateLayers(t);const i=this.getShown();return i.geometry.features.length&&isEqual(withoutLayerOnlyKeys(e),withoutLayerOnlyKeys(this.config))||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,s=!1!==e?.visible&&!!t.shownFeatures.features.length;applyLayersVisibility([this.geometryFillLayerSpecs,this.geometryOutlineLayerSpecs],s,this.mapLibreMap),applyLayersVisibility([this.lineLabelLayerSpecs],s&&void 0!==this.displayConfig(e)?.lineLabel,this.mapLibreMap),applyLayersVisibility([this.titleLayerSpecs],s&&!!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 s of geometryParts){const o=beforeLayerTargetOf(e,s)??t;for(const e of i[s])moveLayerBefore(this.mapLibreMap,e,beforeLayerIDOf(o,this.titleLayerID))}}labelLayerSpecs(e){const t=mapTypefaceOf(this.tomtomMap);return{titleLayerSpec:buildGeometryTitleLayerSpec(this.titleLayerID,e,this.lightDark,t),lineLabelSpec:buildGeometryLineLabelLayerSpec(this.lineLabelLayerID,e,this.lightDark,t)}}updateLayers(e){const[t,i]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,e,this.defaultColor),{titleLayerSpec:s,lineLabelSpec:o}=this.labelLayerSpecs(e);changeLayerProps(t,this.geometryFillLayerSpecs,this.mapLibreMap),changeLayerProps(i,this.geometryOutlineLayerSpecs,this.mapLibreMap),changeLayerProps(s,this.titleLayerSpecs,this.mapLibreMap),changeLayerProps(o,this.lineLabelLayerSpecs,this.mapLibreMap),this.geometryFillLayerSpecs=t,this.geometryOutlineLayerSpecs=i,this.titleLayerSpecs=s,this.lineLabelLayerSpecs=o}discardShownData(){this.lastRawInput=null}restoreDataAndConfigImpl(){const e=this.getShown();this.initSourcesWithLayers(this.config,!0),this.displayAgain(this.config,e),this._applyConfig(this.config)}displayAgain(e,t){this.lastRawInput&&this.display(this.prepare(this.lastRawInput,e,t.geometry),t.geometryLabel)}prepare(e,t,i){const s=this.prepareShown(e,t);return((e,t={})=>{const i=((e,t)=>{const{color:i,palette:s,paletteMode:o}=e.fill??{};return void 0!==i?Array.from({length:t},()=>"string"==typeof i?i:void 0):s?.length?paletteColors(s,o,t):[]})(t,e.features.length);return{...e,features:e.features.map((e,s)=>{const o=(e.properties??{}).fillStyle??t.fill?.style,r="inverted"===o?(e=>{const t=mask(e);return{...e,geometry:t.geometry}})(e):e,a=r.properties??{},n=a.title??((e,t)=>{const i=t.label?.title;return"string"==typeof i&&i?i:e.properties?.address?.freeformAddress})(r,t),l=a.color??i[s];return{...r,properties:{...r.properties,...o&&{fillStyle:o},...n&&{title:n},...l&&{color:l},id:a.id??generateId()}}})}})(i?((e,t)=>{const i=new Set(e.features.map(({properties:e})=>e?.id).filter(e=>void 0!==e)),s=t.features.filter(({properties:e})=>!i.has(e?.id)),o=e.features.filter(({properties:e})=>void 0===e?.id).length===s.length;let r=0;return{...e,features:e.features.map(e=>{const i=e.properties?.id;if(void 0!==i)return withEventState(e,findFeatureByRefId(t.features,i)?.feature.properties?.eventState);if(!o)return e;const a=s[r++].properties;return withEventState({...e,properties:{...e.properties,id:a?.id}},a?.eventState)})}})(s,i):s,this.displayConfig(t))}display(e,t){const i=this.sourcesWithLayers.geometry;i.show(e,{automaticVisibility:!1});const s=(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),s=bboxFromGeoJSON({type:"Polygon",coordinates:[i]});t=s&&bboxCenter(s)||null}else t=e.geometry.coordinates.flat();const i=e.properties?.id??e.id??generateId(),{eventState:s,...o}=e.properties??{};return{type:"Feature",id:i,geometry:{type:"Point",coordinates:t},properties:{...o,id:i}}});return{type:"FeatureCollection",bbox:e.bbox,features:t}})(i.shownFeatures);this.sourcesWithLayers.geometryLabel.show(t?withShownEventStates(t,s,renderedRefId):s,{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 GeometriesModule extends AbstractGeometriesModule{static async create(e,t){return await waitUntilMapIsReady(e),new GeometriesModule(e,t)}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:/* @__PURE__ */byOutlineFillStyle(5,1),color:/* @__PURE__ */byOutlineFillStyle(["coalesce",["get","color"],"#555555"],"grey"),opacity:/* @__PURE__ */byOutlineFillStyle(.9,1)},fill:{...e&&{palette:e},opacity:/* @__PURE__ */byOutlineFillStyle(0,.6)},lineLabel:{}}),geometryFillStyles=["filled","outline","inverted"],geometryPaletteModes=["cycle","ramp"],LINE_WIDTH_RANGE={min:0,max:20,step:.5,bounds:"hard-min"},SYMBOL_SPACING_RANGE={min:50,max:1e3,step:10,bounds:"hard-min"},LINE_LABEL_OFFSET_RANGE={min:-5,max:5,step:.1,bounds:"soft"},highlightKnobDefinitions=e=>({"highlight.fill.opacityFactor":{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.line.widthFactor":{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__ */(()=>/* @__PURE__ */everyOf()(geometryFillStyles))(),default:"filled"}),paletteModeKnobDefinition=e=>({kind:"enum",description:`How \`fill.palette\` colours the ${e}: \`cycle\` gives each the next colour in turn, \`ramp\` blends evenly from its first colour to its last.`,options:geometryPaletteModes,default:"cycle"}),linePatternKnobDefinition=e=>({kind:"enum",description:`Whether ${e} is drawn unbroken, in dashes or in dots, which scale with its width.`,options:linePatterns,default:"solid"}),moduleKnobDefinitions=/* @__PURE__ */(()=>({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},"fill.style":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 its fill colour, in turn or blended as `fill.paletteMode` sets, over `color`."},"fill.paletteMode":paletteModeKnobDefinition("features"),"fill.opacity":{kind:"number",description:"Fill opacity, which `highlight.fill.opacityFactor` 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.line.widthFactor` multiplies while hovered or clicked. Unset: 2, or 5 with the `outline` fill style.",range:LINE_WIDTH_RANGE},"line.pattern":linePatternKnobDefinition("the border"),...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:SYMBOL_SPACING_RANGE,default:200},"lineLabel.offset":{kind:"offset",description:"Shift of the border labels off the line, in ems: x along it, y across it.",range:LINE_LABEL_OFFSET_RANGE,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:LABEL_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. Unset: \`Noto-Bold\` in the labels' typeface.`,options:mapFonts}),typeface:e=>/* @__PURE__ */labelTypefaceKnob(e,labelNames[e])},labelEntries=e=>Object.keys(labelKnobDefinitions).map(t=>({id:`${e}.${t}`,...labelKnobDefinitions[t](e)})),buildCatalogue$1=()=>{const e=withIds(moduleKnobDefinitions),t=({id:e})=>e.startsWith("lineLabel.");return[...e.filter(e=>!t(e)),...labelEntries("label"),...labelEntries("lineLabel"),...e.filter(t)]},geometriesKnobCatalogue=/* @__PURE__ */buildCatalogue$1(),geometriesKnobIds=/* @__PURE__ */geometriesKnobCatalogue.map(({id:e})=>e),rangesModuleKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"Everything the module draws: bands, borders and their labels.",default:!0},"fill.style":fillStyleKnobDefinition("`filled` shades each band, `outline` draws only each range's border, `inverted` shades the outside of each range."),"fill.palette":{kind:"colors",description:"CSS colours of the bands, the innermost first, in turn or blended as `fill.paletteMode` sets. Empty: a ramp from the map's accent toward its land colour, reversed for `inverted`."},"fill.paletteMode":paletteModeKnobDefinition("bands"),"fill.outermostOpacityFactor":{kind:"factor",description:"Multiplier on the outermost band's fill opacity; the bands between step evenly from the innermost, at full opacity. With `inverted`, the world beyond the largest range is the outermost.",range:OPACITY_RANGE,default:1},"line.pattern":linePatternKnobDefinition("each range's border"),...highlightKnobDefinitions("band")}))(),buildRangesCatalogue=()=>[...withIds(rangesModuleKnobDefinitions),...labelEntries("lineLabel")],reachableRangesKnobCatalogue=/* @__PURE__ */buildRangesCatalogue(),reachableRangesKnobIds=/* @__PURE__ */reachableRangesKnobCatalogue.map(({id:e})=>e),titleOf=(e,t,i)=>{if(i)return i(e,t);const s=e.properties?.budget;return void 0!==s?.value&&s.type?`${s.value} ${budgetUnits[s.type]??s.type}`:String(t+1)},largestFirst=e=>[...e].sort((e,t)=>t.squareMeters-e.squareMeters),invertedFill=(e,t,i)=>{const{title:s,fillStyle:o,...r}=e.properties??{};return{...e,geometry:t,properties:{...r,...i}}},bandOpacityFactor=(e,t,i)=>t>1?roundToDecimals(1-(1-i)*e/(t-1),3):i,prepareReachableRanges=(e,{fill:t,lineLabel:i},s)=>{const o=((e,t)=>{const i=e.map((e,i)=>({feature:e,squareMeters:area(e),title:titleOf(e,i,t)})),s=/* @__PURE__ */new Map;for(const o of i)ofMap(s,JSON.stringify(getPosition(o.feature.properties?.origin)),()=>[]).push(o);return[...s.values()].map(e=>largestFirst(e).map((t,i)=>({...t,rank:e.length-1-i})))})(e.features,i?.title),r=Math.max(0,...o.map(e=>e.length)),a=s(r),n=clampFactor(t?.outermostOpacityFactor,OPACITY_RANGE),l=o.length?((e,t,i)=>"inverted"===t?((e,t)=>{const i=e.map(e=>e[0].feature),s=i.length>1&&union(featureCollection(i))||i[0],o=Math.max(...e.map(e=>e[0].rank)),r=[invertedFill(i[0],mask(s).geometry,t(o))];for(const n of e)for(const[e,{feature:i,rank:s}]of n.entries()){if(0===e)continue;const o=difference(featureCollection([n[e-1].feature,i]));o&&r.push(invertedFill(i,o.geometry,t(s)))}const a=e.flat().map(({feature:e,rank:i,title:s})=>{const{id:o,...r}=e.properties??{};return{...e,id:void 0,properties:{...r,title:s,fillStyle:"filled",...t(i)}}});return[...r,...a]})(e,i):largestFirst(e.flat()).map(({feature:e,rank:s,title:o})=>({...e,properties:{...e.properties,title:o,fillStyle:t,...i(s)}})))(o,t?.style??"filled",e=>({color:a[e%a.length],...n<1&&{opacityFactor:bandOpacityFactor(e,r,n)}})):[];return{type:"FeatureCollection",...e.bbox&&{bbox:e.bbox},features:l}},isBorder=["==",["get","fillStyle"],"filled"],byBand=(e,t)=>clampFactor(t?.fill?.outermostOpacityFactor,OPACITY_RANGE)<1?["*",e,["coalesce",["get","opacityFactor"],1]]:e,ReachableRangesModule=class ReachableRangesModule extends AbstractGeometriesModule{static async create(e,t){return await waitUntilMapIsReady(e),new ReachableRangesModule(e,t)}constructor(e,t){super(e,t),onMapColorsChange(e,["accent","land"],()=>{this.config?.fill?.palette?.length||this.displayAgain(this.config,this.getShown())})}get idPrefix(){return"reachableRange"}displayConfig(e){const t=fillStyledGeometryConfig({beforeLayerConfig:e?.beforeLayerConfig}),{title:i,...s}=e?.lineLabel??{},o={...t,highlight:e?.highlight,layers:e?.layers,line:{...t.line,pattern:e?.line?.pattern}};return"inverted"!==e?.fill?.style?{...o,fill:{...t.fill,opacity:byBand(/* @__PURE__ */byOutlineFillStyle(0,.6),e)},lineLabel:s}:{...o,line:{...o.line,opacity:["case",isBorder,1,0]},fill:{...t.fill,opacity:byBand(["case",isBorder,0,.6],e)},lineLabel:{...s,opacity:scaledWhen(["!",isBorder],s.opacity??1,0),offset:["case",isBorder,["literal",[0,-1]],["literal",[0,1]]]}}}prepareShown(e,t){return prepareReachableRanges(e,t??{},e=>{if(t?.fill?.palette?.length)return paletteColors(t.fill.palette,t.fill.paletteMode,e);const i=((e,t,i)=>colorRamp([e,t],i,{reach:.7})??Array.from({length:i},()=>e))(this.defaultColor,this.landColor,e);return"inverted"===t?.fill?.style?i.reverse():i})}get landColor(){return this.tomtomMap.mapColors.land??getThemeAdaptiveGeometryColors(this.lightDark).haloColor}async show(e){await this.showPolygons(e)}},directCategories={aboriginal_land:["ABORIGINAL_LAND"],airport:["AIRPORT"],amusement_park:["AMUSEMENT_PARK","AMUSEMENT_PARK_GENERIC"],animal_shelter:["ANIMAL_SHELTER"],atm:["ATM"],bank:["BANK"],bar:["BAR"],beach_resort:["BEACH"],border_control:["TRANSPORT_ACCESS","BORDER_CONTROL"],bus_station:["BUS_STOP"],cafe:["CAFE","CAFE_PUB"],cafeteria:["CAFETERIA"],camping_ground:["CAMPING_GROUND"],car_rental:["CAR_RENTAL"],casino_and_gambling:["CASINO_AND_GAMBLING"],cemetery:["CEMETERY"],charging_location:["CHARGING_LOCATION"],childcare:["CHILDCARE"],cinema:["CINEMA","MOVIE_THEATER"],clinic:["HEALTHCARE_SERVICE"],clothing_shop:["CLOTHING_SHOP"],coffee_shop:["COFFEE_SHOP"],college_or_university:["COLLEGE_OR_UNIVERSITY","COLLEGE_OR_UNIVERSITY_GENERIC"],comedy_club:["COMEDY_CLUB"],commercial_area:["AGRICULTURE","BUSINESS_PARK","COMMERCIAL_BUILDING","COMPANY","RESIDENTIAL_ACCOMMODATION","RESIDENTIAL_ENTRANCE"],conference_center:["EXHIBITION_CONVENTION_CENTER"],consumer_service:["CLUB_AND_ASSOCIATION","PUBLIC_AMENITY","PEDESTRIAN_SUBWAY","WELFARE_ORGANIZATION"],courthouse:["COURTHOUSE"],cultural_center:["COMMUNITY_CENTER","CULTURAL_CENTER"],dentist:["DENTIST"],department_store:["DEPARTMENT_STORE"],doctor:["DOCTOR"],emergency_ward_entrance:["EMERGENCY_MEDICAL_SERVICE","EMERGENCY_ROOM"],fast_food:["FAST_FOOD"],ferry_terminal:["FERRY_TERMINAL"],fire_station:["FIRE_STATION"],fitness_center:["FITNESS_CLUB_AND_CENTER"],food_and_drinks_shop:["WINERY"],foreign_exchange:["FOREIGN_EXCHANGE","EXCHANGE"],fuel_station:["FUEL_STATION"],gold_exchange:["GOLD_EXCHANGE"],golf_course:["GOLF_COURSE"],government_office:["EMBASSY","GOVERNMENT_OFFICE"],heliport_or_helipad:["HELIPORT_OR_HELIPAD"],historic_site:["HISTORIC_SITE"],holiday_home:["HOLIDAY_RENTAL"],horse_riding:["HORSE_RIDING"],hospital:["GENERAL_HOSPITAL_AND_POLYCLINIC","HOSPITAL"],hotel_or_motel:["HOTEL_OR_MOTEL"],ice_rink:["ICE_RINK"],industrial_area:["INDUSTRIAL_BUILDING","PORT_WAREHOUSE_FACILITY","PRIMARY_RESOURCE_UTILITY"],juice_bar:["JUICE_BAR"],landmark:["NATURAL_FEATURE"],mall:["MALL"],manufacturing_facility:["MANUFACTURING_FACILITY"],marina:["MARINA","MARINA_GENERIC"],marketplace:["MARKETPLACE"],media_facility:["MEDIA_FACILITY"],mountain_pass:["MOUNTAIN_PASS"],museum:["MUSEUM"],ngo_office:["NON_GOVERNMENTAL_ORGANIZATION"],nightlife:["CONCERT_HALL","ENTERTAINMENT","NIGHTLIFE"],park_and_recreation_area:["PARK_AND_RECREATION_AREA","TRAIL_SYSTEM"],park_and_recreation_facility:["LEISURE_CENTER","FLYING_CLUB","WATER_SPORT"],parking_facility:["PARKING_GARAGE"],pharmacy:["PHARMACY"],planetarium:["PLANETARIUM"],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"],religious_site:["CHURCH","GURUDWARA","MOSQUE","PAGODA","RELIGIOUS_SITE","SYNAGOG","TEMPLE"],rental_car_parking:["RENTAL_CAR_PARKING"],research_facility:["RESEARCH_FACILITY"],rest_and_service_area:["REST_AREA"],restaurant:["RESTAURANT","RESTAURANT_AREA"],school_or_kindergarten:["SCHOOL","SCHOOL_GENERIC"],shop_or_store:["SHOP_OR_STORE"],sport_facility:["ADVENTURE_SPORTS_FACILITY","SPORTS_CENTER","SPORTS_CENTER_GENERIC","TENNIS_COURT"],stadium:["STADIUM"],stock_exchange:["STOCK_EXCHANGE"],supermarket:["SUPERMARKET"],swimming_pool:["SWIMMING_POOL"],taxi_stand:["TAXI_STAND"],tea_house:["TEA_HOUSE"],theater:["OPERA_HOUSE","THEATER","THEATER_GENERIC"],toll_plaza:["TOLL_GATE"],tourist_attraction:["TOURIST_ATTRACTION"],tourist_information:["TOURIST_INFORMATION"],truck_stop:["TRUCK_STOP"],vehicle_dealer:["VEHICLE_DEALER"],vehicle_inspection:["MOTORING_ORGANIZATION_OFFICE","TRAFFIC_CONTROL_DEPARTMENT","TRAFFIC_CONTROL_DEPARTMENT_GENERIC","TRANSPORT_AUTHORITY_VEHICLE_REGISTRATION"],vehicle_repair:["VEHICLE_REPAIR"],vehicle_wash:["CAR_WASH","CAR_WASH_GENERIC"],veterinary:["VETERINARY"],viewpoint:["HILL","MOUNTAIN_PEAK","VIEWPOINT"],weighbridge:["WEIGH_STATION","WEIGH_STATION_GENERIC"],zoo_or_aquarium:["AQUATIC_ZOO","ARBORETA_AND_BOTANICAL_GARDENS","ZOOS_ARBORETA_BOTANICAL_GARDEN"]},closestCategories={airport:["AIRFIELD","AIRLINE_ACCESS","PRIVATE_AIRPORT","PUBLIC_AIRPORT"],bank:["DIVERSIFIED_FINANCIALS"],bar:["COCKTAIL_BAR"],beach_resort:["BEACH_CLUB"],border_control:["SECURED_ENTRANCE"],cafe:["INTERNET_CAFE"],camping_ground:["CARAVAN_SITE","RECREATIONAL_CAMPING_GROUND","REST_CAMP"],cemetery:["MAUSOLEUM_OR_GRAVE"],childcare:["PRE_SCHOOL"],cinema:["DRIVE_IN_MOVIES"],clothing_shop:["CHILDREN_S_CLOTHES","MEN_S_CLOTHING","SPECIALTY_CLOTHING_SHOP","WOMEN_S_CLOTHING"],college_or_university:["JUNIOR_COLLEGE_OR_COMMUNITY_COLLEGE"],commercial_area:["ADVERTISING_COMPANY","AGRICULTURAL_TECHNOLOGY","AIRLINE_COMPANY","APARTMENT_RENTAL","AUTOMOBILE_COMPANY","BUILDING","BUSINESS_SERVICES","BUS_CHARTER_COMPANY","CABLE_AND_TELEPHONE_COMPANY","CLEANING_SERVICES","COMPUTER_AND_DATA_SERVICES","CONSTRUCTION_COMPANY","DELIVERY_SERVICE","ELECTRONICS_COMPANY","EQUIPMENT_RENTAL","FARM","FLATS_OR_APARTMENT_COMPLEX","HORTICULTURE","IMPORT_OR_EXPORT_AND_DISTRIBUTION","INSURANCE_COMPANY","INVESTMENT_ADVISOR","LEGAL_SERVICES","MINING_COMPANY","MOVING_AND_STORAGE_COMPANY","OIL_AND_NATURAL_GAS","PHARMACEUTICAL_COMPANY","PRIMARY_PRODUCER","PUBLISHING_TECHNOLOGIES","REAL_ESTATE_AGENT","REAL_ESTATE_COMPANY","RETIREMENT_COMMUNITY","SCHOOL_BUS_COMPANY","SERVICE_COMPANY","SOFTWARE_COMPANY","TAX_SERVICES","TELECOMMUNICATIONS","TRANSPORT_COMPANY","TRAVEL_AGENT","WEDDING_SERVICES"],consumer_service:["PUBLIC_CALL_BOX","PUBLIC_BATHROOM"],doctor:["GENERAL_PRACTITIONER","SPECIALIST"],emergency_ward_entrance:["AMBULANCE_UNIT","RESCUE_SERVICE"],food_and_drinks_shop:["MICROBREWERY"],historic_site:["BATTLEFIELD","MEMORIAL"],holiday_home:["BUNGALOW_RENTAL","CHALET_RENTAL","COTTAGE_RENTAL","VILLA_RENTAL"],hospital:["BLOOD_BANK","HOSPITAL_FOR_WOMEN_AND_CHILDREN","HOSPITAL_OF_CHINESE_MEDICINE","SPECIAL_HOSPITAL"],hotel_or_motel:["BANDB_OR_GUEST_HOUSE","CABINS_LODGES","HOSTEL","HOTEL","MOTEL","RESORT"],ice_cream_shop:["ICE_CREAM_PARLOR"],ice_rink:["ICE_HOCKEY_ARENA"],industrial_area:["CHEMICAL_COMPANY","MECHANICAL_ENGINEERING","QUARRY"],landmark:["ARCH","BAY","BRIDGE","CAPE","COVE","DAM","DUNE","ISLAND","LOCALE","MARSH","MONUMENT","OASIS","OBSERVATORY","PARKWAY","PLAIN_OR_FLAT","PLATEAU","PAN","RAPIDS","REEF","RESERVOIR","RIVER_CROSSING","ROCKS","STATUE","TOWER","TUNNEL","VALLEY","WATER_HOLE","WELL"],manufacturing_facility:["AUTOMOBILE_MANUFACTURING","MANUFACTURING_COMPANY"],marketplace:["FARMERS_MARKET","FOOD_MARKET","INFORMAL_MARKET","PUBLIC_MARKET"],military_airfield:["MILITARY_AIRPORT"],mourning_facility:["FUNERAL_SERVICE_AND_MORTUARIES"],nightlife:["AMUSEMENT_PLACE","BETTING_STATION","CABARET_THEATER","DISCO_CLUB","FAIRGROUND","JAZZ_CLUB","KARAOKE_CLUB","MUSIC_CENTER"],park_and_recreation_area:["ADVENTURE_VEHICLE_TRAIL","FISHING_AND_HUNTING_AREA","FOREST_AREA","HIKING_TRAIL","HISTORICAL_PARK","HORSE_RIDING_TRAIL","MOUNTAIN_BIKE_TRAIL","PARK","PICNIC_AREA","RECREATION_AREA","ROCK_CLIMBING_TRAIL","WILDERNESS_AREA"],parking_facility:["OPEN_CAR_PARKING_AREA","OPEN_CAR_PARKING_AREA_GENERIC"],personal_care_service:["BEAUTY_SALON","HAIRDRESSER","NAIL_SALON","PERSONAL_CARE_FACILITY","PERSONAL_SERVICE","SAUNA_SOLARIUM_MASSAGE"],pharmacy:["DRUG_STORE","CANNABIS_SHOP","MEDICINAL_AND_RECREATIONAL_DISPENSARY","MEDICINAL_MARIJUANA_DISPENSARY","RECREATIONAL_MARIJUANA_DISPENSARY"],post_depot:["COURIER_DROP_BOX"],public_transport_stop:["BUS_LINES","PASSENGER_TRANSPORT_TICKET_OFFICE","STREETCAR_STOP","SUBWAY_STATION","SUBWAY_ENTRANCE"],railway_station:["INTERNATIONAL_RAILROAD_STATION","NATIONAL_RAILROAD_STATION","STATION_ACCESS","URBAN_STATION"],restaurant:["AFGHAN_RESTAURANT","AFRICAN_RESTAURANT","AMERICAN_RESTAURANT","ARABIAN_RESTAURANT","ARMENIAN_RESTAURANT","ASIAN_RESTAURANT","AUSTRALIAN_RESTAURANT","AUSTRIAN_RESTAURANT","BANQUET_ROOMS","BARBECUE_RESTAURANT","BASQUE_RESTAURANT","BELGIAN_RESTAURANT","BISTRO","BOLIVIAN_RESTAURANT","BRAZILIAN_RESTAURANT","BRITISH_RESTAURANT","BUFFET_RESTAURANT","BULGARIAN_RESTAURANT","BURMESE_RESTAURANT","CALIFORNIAN_RESTAURANT","CAMBODIAN_RESTAURANT","CANADIAN_RESTAURANT","CARIBBEAN_RESTAURANT","CATERING_SERVICES","CHICKEN_RESTAURANT","CHILEAN_RESTAURANT","CHINESE_RESTAURANT","COLOMBIAN_RESTAURANT","CORSICAN_RESTAURANT","CREOLE_RESTAURANT","CREPERIE","CUBAN_RESTAURANT","CZECH_RESTAURANT","DANISH_RESTAURANT","DINNER_THEATER","DONGBEI_RESTAURANT","DOUGHNUT_RESTAURANT","DUTCH_RESTAURANT","EGYPTIAN_RESTAURANT","ENGLISH_RESTAURANT","ETHIOPIAN_RESTAURANT","FINNISH_RESTAURANT","FONDUE_RESTAURANT","FRENCH_RESTAURANT","FUSION_RESTAURANT","GERMAN_RESTAURANT","GREEK_RESTAURANT","GRILL_RESTAURANT","HAMBURGER_RESTAURANT","HAWAIIAN_RESTAURANT","HOT_POT_RESTAURANT","HUNAN_RESTAURANT","HUNGARIAN_RESTAURANT","INDIAN_RESTAURANT","INDONESIAN_RESTAURANT","INTERNATIONAL_RESTAURANT","IRANIAN_RESTAURANT","IRISH_RESTAURANT","ISRAELI_RESTAURANT","ITALIAN_RESTAURANT","JAMAICAN_RESTAURANT","JAPANESE_RESTAURANT","JEWISH_RESTAURANT","KOREAN_RESTAURANT","KOSHER_RESTAURANT","LATIN_AMERICAN_RESTAURANT","LEBANESE_RESTAURANT","MEDITERRANEAN_RESTAURANT","MEXICAN_RESTAURANT","MIDDLE_EASTERN_RESTAURANT","MONGOLIAN_RESTAURANT","MOROCCAN_RESTAURANT","NEPALESE_RESTAURANT","NORWEGIAN_RESTAURANT","ORGANIC_FOOD_RESTAURANT","ORIENTAL_RESTAURANT","PAKISTANI_RESTAURANT","PERUVIAN_RESTAURANT","PHILIPPINE_RESTAURANT","PIZZERIA","POLISH_RESTAURANT","PORTUGUESE_RESTAURANT","RUSSIAN_RESTAURANT","SALAD_BAR","SANDWICH_RESTAURANT","SCANDINAVIAN_RESTAURANT","SEAFOOD","SHANDONG_RESTAURANT","SICHUAN_RESTAURANT","SNACKS_RESTAURANT","SOUL_FOOD","SOUP_RESTAURANT","SPANISH_RESTAURANT","STEAK_HOUSE","SUSHI_RESTAURANT","SWEDISH_RESTAURANT","SWISS_RESTAURANT","SYRIAN_RESTAURANT","TAIWANESE_RESTAURANT","TAKEOUT_FOOD","TAPAS_RESTAURANT","TEPPANYAKI_RESTAURANT","THAI_RESTAURANT","TIBETAN_RESTAURANT","TUNISIAN_RESTAURANT","TURKISH_RESTAURANT","VEGETARIAN_RESTAURANT","VENEZUELAN_RESTAURANT","VIETNAMESE_RESTAURANT","WESTERN_RESTAURANT"],school_or_kindergarten:["ART_SCHOOL","DANCE_STUDIO_AND_SCHOOL","DRIVING_SCHOOL","HIGH_SCHOOL","LANGUAGE_SCHOOL","MIDDLE_SCHOOL","PRIMARY_SCHOOL","SENIOR_HIGH_SCHOOL","VOCATIONAL_SCHOOL"],shop_or_store:["AGRICULTURAL_SUPPLIES","ANTIQUE_ART_SHOP","BAGS_LEATHERWEAR","BAKERY","BEAUTY_SUPPLIES","BOATING_EQUIPMENT_AND_ACCESSORIES","BOOK_SHOP","BUTCHER","CAMERAS_AND_PHOTOGRAPHY","CARPET_FLOOR_COVERINGS","CHRISTMAS_OR_HOLIDAY_SHOP","COMPUTER_AND_COMPUTER_SUPPLIES","CONSTRUCTION_MATERIAL_AND_EQUIPMENT","CONSUMER_ELECTRONICS","CONVENIENCE_STORE","CURTAINS_TEXTILES","C_DS_DVD_VIDEOS","DELICATESSEN","DO_IT_YOURSELF_CENTERS","DRIVE_THROUGH_BOTTLE_SHOP","DRY_CLEANER","ELECTRICAL_APPLIANCES_SHOP","FACTORY_OUTLET","FISHMONGER","FLORISTS","FOOTWEAR_SHOE_REPAIRS","FURNITURE_HOME_FURNISHINGS","GARDEN_CENTERS_SERVICES","GIFTS_CARDS_NOVELTIES_SOUVENIRS","GLASSWARE_CERAMIC_SHOP","GLASS_WINDOWS_STORE","GREENGROCER","GROCERY_STORE","HARDWARE_STORE","HOBBY_SHOP","HOUSE_AND_GARDEN_FURNITURE_AND_FITTINGS","JEWELRY_CLOCKS_WATCHES","KITCHENS_BATHROOMS","LAUNDRY","LIGHTING_SHOPS","LOCAL_SPECIALITIES_SHOP","LOTTERY_SHOP","MEDICAL_SUPPLIES_EQUIPMENT","MOBILE_PHONE_SHOP","MUSIC_INSTRUMENTS_STORE","NEWSAGENTS_TOBACCONISTS","OFFICE_EQUIPMENT","OPTICIAN","FOOD_AND_DRINKS_SHOP","PAINTING_DECORATING","PAWN_SHOP","PET_SUPPLIES","PHOTOCOPY_SHOP","PHOTO_LAB_OR_DEVELOPMENT","RECYCLING_SHOP","RETAIL_OUTLET","SECURITY_PRODUCTS","SHOPPING_SERVICE","SPECIALTY_FOODS","SPORTS_EQUIPMENT_AND_CLOTHING","TAILOR_SHOP","TOYS_GAMES_SHOP","VARIETY_STORE","VIDEO_RENTAL_SHOP","WHOLESALE_CLUB","WINE_SPIRITS"],sport_facility:["ATHLETICS_TRACK","BASEBALL_PARK","BASKETBALL_ARENA","BOWLING_CENTER","CRICKET_GROUND","HOCKEY_CLUB","HORSE_RACING_TRACK","RACE_TRACK","RUGBY_GROUND","SQUASH_COURT","THEMATIC_SPORT_CENTER"],stadium:["FOOTBALL_STADIUM","MOTOR_RACING_STADIUM","MULTI_PURPOSE_STADIUM","NETBALL_STADIUM","SOCCER_STADIUM"],taxi_stand:["TAXI_LIMOUSINE_AND_SHUTTLE_SERVICE"],theater:["AMPHITHEATER"],tourist_attraction:["CAVE","MINERAL_OR_HOT_SPRINGS","NATURAL_TOURIST_ATTRACTION"],transport_access:["BOAT_LAUNCHING_RAMP","HARBOR","YACHT_BASIN"],vehicle_dealer:["ATV_DEALER","BOAT_DEALER","BUS_DEALER","CAR_DEALER","MOTORCYCLE_DEALER","RECREATIONAL_VEHICLE_DEALER","TRUCK_DEALER","VAN_DEALER"],vehicle_repair:["BODYSHOP","CAR_GLASS_REPLACEMENT_SHOP","CAR_REPAIR_AND_SERVICE","HOME_APPLIANCE_REPAIR","MOTORCYCLE_REPAIR","TIRE_SERVICE","TRUCK_REPAIR_AND_SERVICE"],veterinary:["ANIMAL_SERVICE"],viewpoint:["RIDGE"],winter_sports:["SKI_RESORT"],zoo_or_aquarium:["WILDLIFE_PARK","ZOO"]},baseMapPOICategoryValues=/* @__PURE__ */(()=>[.../* @__PURE__ */new Set([...Object.keys(directCategories),...Object.keys(closestCategories)])])(),baseMapCategories=/* @__PURE__ */(()=>Object.fromEntries([directCategories,closestCategories].flatMap(e=>baseMapPOICategoryValues.flatMap(t=>(e[t]??[]).map(e=>[e,t])))))(),toBaseMapPOICategory=e=>Object.hasOwn(baseMapCategories,e)?baseMapCategories[e]:void 0,groupCategories={eat_and_drink:["bar","cafe","cafeteria","coffee_shop","fast_food","ice_cream_shop","juice_bar","pub","restaurant","tea_house"],shopping:["clothing_shop","department_store","food_and_drinks_shop","mall","marketplace","shop_or_store","supermarket"],finance:["atm","bank","foreign_exchange","gold_exchange","stock_exchange"],lodging:["camping_ground","holiday_home","hotel_or_motel"],transport:["airport","bus_station","ferry_terminal","heliport_or_helipad","marina","public_transport_stop","railway_station","taxi_stand","transport_access"],driving:["border_control","car_rental","charging_location","fuel_station","rest_and_service_area","toll_plaza","truck_stop","vehicle_dealer","vehicle_inspection","vehicle_repair","vehicle_wash","weighbridge"],parking:["parking_facility","rental_car_parking"],healthcare:["clinic","dentist","doctor","emergency_ward_entrance","hospital","pharmacy","veterinary"],education:["childcare","college_or_university","research_facility","school_or_kindergarten"],cultural:["cultural_center","historic_site","museum","planetarium","theater"],leisure:["amusement_park","beach_resort","casino_and_gambling","cinema","comedy_club","nightlife","park_and_recreation_facility","tourist_attraction","tourist_information","zoo_or_aquarium"],sport:["fitness_center","golf_course","horse_riding","ice_rink","sport_facility","stadium","swimming_pool","winter_sports"],outdoor:["aboriginal_land","landmark","mountain_pass","park_and_recreation_area","viewpoint"],protected:["protected_land"],public:["cemetery","courthouse","fire_station","government_office","police_station","post_depot","post_office","prison","public_library"],military:["military_airfield"],religion:["religious_site"],business:["animal_shelter","commercial_area","conference_center","consumer_service","industrial_area","manufacturing_facility","media_facility","mourning_facility","ngo_office","personal_care_service"]},baseMapCategoryGroups=/* @__PURE__ */(()=>Object.fromEntries(Object.keys(groupCategories).flatMap(e=>groupCategories[e].map(t=>[t,e]))))(),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?.outlineColor??"#FFFFFF","circle-stroke-width":e?.outlineWidth??1.5}),countTextLayout=e=>({"text-field":["get","point_count_abbreviated"],"text-font":["Noto-Bold"],"text-size":e?.label?.size??12,"text-allow-overlap":!0,"text-ignore-placement":!0}),clusteredPlacesAggregateProperties=/* @__PURE__ */(()=>{return{[CLUSTER_PROPERTY_BASE_MAP_ICON_IDS]:(e="clusterBaseMapIconIDs",[["case",["==",["get",e],null],["accumulated"],["==",["accumulated"],null],["get",e],[">=",["index-of",["concat",",",["get",e],","],["concat",",",["accumulated"],","]],0],["accumulated"],["concat",["accumulated"],",",["get",e]]],["get","baseMapIconID"]])};var e})(),buildKnownBaseMapSpriteImageExpr=e=>{const t=["match",e];for(const i of baseMapPOICategoryValues){const e=toBaseMapPOIImageID(i);t.push(e,["image",e])}return t.push(["image","poi-parking-micro"]),t},buildCustomIconOffsets=(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},buildIconOffsetExpression=(e,t="iconID",i=[0,0])=>{const s=["case"];for(const[o,r]of e)0===r.x&&0===r.y||s.push(["==",["get",t],o],["literal",[r.x,r.y]]);if(1!==s.length)return s.push(Array.isArray(i)&&"number"==typeof i[0]?["literal",i]:i),s},isCenteredMarkerType=e=>"base-map"===e||"circle-icon"===e,absoluteSvgLength=e=>{const t=e?.trim().match(/^(\d+(?:\.\d+)?|\.\d+)\s*(?:px)?$/);return t?Number.parseFloat(t[1]):void 0},calculateIconScale=(e,t,i=2)=>{if(!e)return;const s=(e=>{try{return"string"==typeof e?e.includes("<svg")?(e=>{const t=parseSvg(e),i=absoluteSvgLength(t.getAttribute("width")),s=absoluteSvgLength(t.getAttribute("height"));if(void 0!==i&&void 0!==s)return{width:i,height:s};const o=(e=>{const t=e?.trim().split(/[\s,]+/);return 4===t?.length?{width:Number.parseFloat(t[2]),height:Number.parseFloat(t[3])}:void 0})(t.getAttribute("viewBox"));return o?void 0!==i?{width:i,height:i*o.height/o.width}:void 0!==s?{width:s*o.width/o.height,height:s}:o:null})(e):null: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(!s)return;const o=isCenteredMarkerType(t),r=o?54:140,a=o?54:120,n=2/i;return{heightScale:s.height*n/r,widthScale:s.width*n/a}},round4=e=>roundToDecimals(e,4),buildAnchorOffsets=(e,t,i,s)=>{const o=void 0!==s;return{top:o?[0,s]:[0,round4(e)],left:o?[s,round4(i)]:[round4(t),round4(i)],right:o?[-s,round4(i)]:[-round4(t),round4(i)]}},getTextOffset=(e,t,i,s)=>{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(isLegacyFunction(e)){const t=e.stops.at(-1);if(Array.isArray(t)&&"number"==typeof t[1])return t[1]}return.8})(e)/.8,r=isCenteredMarkerType(i);if(r&&void 0!==s)return{"text-offset":[s,s]};const a=1.4*o,n=buildAnchorOffsets(.7*o,a,r?0:-a,s),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=(r?1.4:.7)*u.heightScale*o,t=1.4*u.widthScale*o,i=buildAnchorOffsets(e,t,r?0:-t,s);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,s,o)=>{const r=t?.label,a=t?.layers?.[i],n=o&&o.size>0,l={...e.layout},c=n||void 0!==r?.distance||"circle-icon"===t?.markerType;c&&(delete l["text-offset"],delete l["text-variable-anchor-offset"],delete l["text-radial-offset"]);const d={...l,...labelLayoutProperties(r),...void 0!==s&&{"text-field":s},...a?.layout};if(c){const e=[...o??[]],s=new Map(e.flatMap(([e,{scales:t}])=>t?[[e,t]]:[])),n="micro"!==i&&buildIconOffsetExpression(e.flatMap(([e,{offset:t}])=>t?[[e,t]]:[]),void 0,l["icon-offset"]);return{...d,...getTextOffset(d["icon-size"],s,t?.markerType,r?.distance),...n&&{"icon-offset":n},...a?.layout}}return d},buildPaintConfig=(e,t,i,s)=>{const o=t?.layers?.[i],{textColor:r,haloColor:a}=themeAdaptiveLabelColors(s),n=e.paint??{};return{...n,...void 0===n["text-color"]&&{"text-color":r},...void 0===n["text-halo-color"]&&{"text-halo-color":a},...labelPaintProperties(t?.label),...void 0!==t?.icon?.opacity&&"selected"!==i&&{"icon-opacity":t.icon.opacity},...o?.paint}},writtenIconLayouts=/* @__PURE__ */new WeakMap,styleIconLayout=(e,t)=>{const i=writtenIconLayouts.get(e),s=e=>i&&isEqual(t?.[e],i.written[e])?i.over[e]:t?.[e];return{"icon-image":s("icon-image"),"icon-offset":s("icon-offset")}},poiLookKnobIds=["labels.sizeFactor","labels.typeface","symbols.sizeFactor","pois.sizeFactor","pois.label.color","pois.label.haloColor"],getTextSizeSpec=e=>JSON.parse(JSON.stringify(e).replaceAll("name","title")),findStyleLayer=(e,t)=>{const i=e.getStyle().layers.find(e=>e.id===t);return"symbol"===i?.type?i:void 0},buildBaseMapPOILayerFoundation=e=>{const{visibility:t,...i}=e?.layout??{};return{filter:["!",isClickEventState],type:"symbol",paint:e?.paint,layout:e?.layout?i:void 0}},buildBaseMapPOILayerSpec=e=>{const t=findStyleLayer(e,mapStyleLayerIDs.poi),i=buildBaseMapPOILayerFoundation(t),s=i.layout?.["text-size"],{"icon-offset":o}=styleIconLayout(e,t?.layout),{"icon-offset":r,...a}=i.layout??{};return{...i,layout:{...a,...void 0!==o&&{"icon-offset":o},"icon-image":["get","iconID"],"text-field":["get","title"],...s&&{"text-size":getTextSizeSpec(s)}}}},buildPOIMicroLikeLayerSpec=e=>{const t=buildBaseMapPOILayerFoundation(findStyleLayer(e,POI_MICRO_LAYER_ID));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,mapStyleLayerIDs.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"}},hasNoActiveEventState=["!",hasActiveEventState],poiLookMarkerTypes=/* @__PURE__ */new Set(["base-map","circle-icon","pin-clustered"]),pinLayerSpec=/* @__PURE__ */(()=>({...pinLayerBaseSpec,filter:hasNoActiveEventState}))(),toSelectedSpec=(e,t)=>({...e,filter:hasActiveEventState,layout:{...e.layout,"text-allow-overlap":!0},paint:{...e.paint,"text-color":t}}),selectedPinLayerSpec=(e="#3f9cd9")=>toSelectedSpec({...pinLayerBaseSpec,layout:{...pinLayerBaseSpec.layout,"icon-size":SELECTED_PIN_ICON_SIZE}},e),getThemeAdaptiveConnectionColors=(e,t)=>{const i="dark"===e,s=themeAdaptiveLabelColors(e).haloColor;return t?{lineColor:t,labelColor:themeAdaptiveLabelShadeOf(t,e),labelHaloColor:s}:{lineColor:i?"#5AB6F0":"#3f9cd9",labelColor:i?"#A9D6F5":"#1a5f8a",labelHaloColor:s}},dashedLineSpec=(e,t,i)=>({type:"line",layout:{"line-cap":"round"},paint:{"line-color":e,"line-width":1.5,"line-dasharray":t,"line-opacity":i}}),buildBaseLineSpec$1=e=>{const t=dashedLineSpec(e,[2,2],.9);return{...t,layout:{"line-join":"round",...t.layout}}},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)=>({...dashedLineSpec(e,[1,2],.8),minzoom:t,filter:["==",["geometry-type"],"LineString"]}),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}}),placesMarkerTypes=["pin","circle-icon","base-map","pin-clustered"],isClickEventType=e=>"click"===e||"contextmenu"===e,isHoverEventState=e=>"hover"===e||"hover-move"===e||"long-hover"===e,isSameEventFamily=(e,t)=>isClickEventType(e)&&isClickEventType(t)||isHoverEventState(e)&&isHoverEventState(t),canReplaceEventState=(e,t)=>"recently-hovered"===t?isHoverEventState(e):!isClickEventType(e)||isClickEventType(t),setEventState=(e,t,i,s="updateInProps")=>{const o=findFeatureByRefId(i,t);if(o&&canReplaceEventState(o.feature.properties?.eventState,e))return i.splice(o.index,1,withEventState(o.feature,"updateInProps"===s?e:void 0)),o.index},leaveEventState=(e,t,i,s)=>s?setEventState("recently-hovered",t,i):setEventState(e,t,i,"removeFromProps"),isSameRenderedFeature=(e,t)=>e.source===t.source&&renderedRefId(e)===renderedRefId(t),putCustomLayerState=(e,t,i,s="updateInProps")=>{void 0!==i&&canReplaceEventState(e.eventStateOf(i),t)&&e.putEventState(i,"updateInProps"===s?t:void 0)},leaveEventStateOf=(e,t,i,s)=>{if(i instanceof GeoJSONSourceWithLayers)((e,t,i,s)=>{const o=[...i.shownFeatures.features],r=leaveEventState(e,shownRefId(t),o,s);isNil(r)||i.show({...i.shownFeatures,features:o},{automaticVisibility:!1})})(e,t,i,s);else if(i instanceof CustomLayerSourceWithLayers){const o=renderedRefId(t);s?putCustomLayerState(i,"recently-hovered",o):putCustomLayerState(i,e,o,"removeFromProps")}},updateEventState=(e,t,i,s,o,r=!1)=>{if(t&&s instanceof GeoJSONSourceWithLayers){const a=[...s.shownFeatures.features];return setEventState(e,shownRefId(t),a),i&&!isSameRenderedFeature(i,t)&&(o===s?leaveEventState(e,shownRefId(i),a,r):leaveEventStateOf(e,i,o,r)),((e,t,i)=>{i.forEach((s,o)=>{renderedRefId(s)!==t&&isSameEventFamily(s.properties?.eventState,e)&&(i[o]=withEventState(s,void 0))})})(e,shownRefId(t),a),void s.show({...s.shownFeatures,features:a},{automaticVisibility:!1})}if(!(t&&s instanceof CustomLayerSourceWithLayers))return void(i&&leaveEventStateOf(e,i,o,r));i&&!isSameRenderedFeature(i,t)&&leaveEventStateOf(e,i,o,r);const a=renderedRefId(t);for(const n of s.idsWithEventState())n!==a&&isSameEventFamily(s.eventStateOf(n),e)&&s.putEventState(n,void 0);putCustomLayerState(s,e,a)},eventStatesById=e=>{const t=/* @__PURE__ */new Map;for(const i of e.features)i.properties.eventState&&t.set(i.properties.id,i.properties.eventState);return t},toEntryPointID=(e,t)=>`${e}-entry-point-${t}`,isShownFor=(e,t)=>"all"===e||("selected"===e?void 0!==t:isClickEventType(t)),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},"icon.opacity":{kind:"number",description:"Opacity of the place icons, whichever marker type draws them; the cluster badges and a highlighted or selected place stay opaque.",range:OPACITY_RANGE,default:1},"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:LABEL_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, or the style's POI labels under `base-map`."},"label.haloWidth":{kind:"number",description:"Width of the label halo, in pixels. Unset: 1 to 1.5 as the zoom grows, or the style's POI labels under `base-map`.",range:LABEL_HALO_WIDTH_RANGE},"label.opacity":{kind:"number",description:"Label opacity.",range:OPACITY_RANGE},"label.distance":{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`, in the labels' typeface.",options:mapFonts},"label.typeface":/* @__PURE__ */labelTypefaceKnob("label","labels"),"cluster.badge.color":{kind:"color",description:"Fill colour of the cluster count badges; `color` does not reach them.",default:"#000000"},"cluster.badge.outlineColor":{kind:"color",description:"Outline colour of the cluster count badges.",default:"#FFFFFF"},"cluster.badge.outlineWidth":{kind:"number",description:"Outline width of the cluster count badges, in pixels.",range:{min:0,max:5,step:.5,bounds:"hard-min"},default:1.5},"cluster.badge.label.color":{kind:"color",description:"Colour of the count on the cluster badges.",default:"#FFFFFF"},"cluster.badge.label.size":{kind:"number",description:"Size of the count on the cluster badges, in pixels.",range:LABEL_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.radius":{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.maxZoom":{kind:"number",description:"Last zoom places cluster at; entry points start one zoom above it. Changing it recreates the places source.",range:{min:0,max:17,step:1,bounds:"hard"},default:17},"cluster.source.minPoints":{kind:"number",description:"Fewest places a cluster holds. Changing it recreates the places source.",range:{min:2,max:20,step:1,bounds:"hard-min"},default:2},"entryPoints.showFor":{kind:"enum",description:"Which places have their entry points drawn: all, the hovered or clicked, or the clicked.",options:/* @__PURE__ */(()=>/* @__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.label.color":{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.label.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),paintPin=(e,t,i,s,o,r)=>{const a=((e,t)=>e?.image?.image?{image:e.image.image,pixelRatio:e.image.pixelRatio??2}:{style:{...t,...e?.style}})(i,s);if(r&&e.hasImage(t)&&((e,t)=>"image"in e?"image"in t&&e.image===t.image&&e.pixelRatio===t.pixelRatio:"style"in t&&isEqual(e.style,t.style))(a,r))return r;const n="image"in a?a.image:o(a.style),l="image"in a?a.pixelRatio:2;return addOrUpdateImage("add-or-update",t,n,e,{pixelRatio:l}),a},customImagesByID=(e,t=e=>e.id)=>{const i={};for(const s of e??[])s.image&&(i[t(s)]={image:s.image,pixelRatio:s.pixelRatio??2});return i},defaultPin=e=>svgToImg(()=>pinSvg(e)),resolveEndpoint=(e,t)=>"string"!=typeof e?e:t.features.find(t=>t.id===e),isMapCategoryIcon=e=>!!e.image,iconsByMapCategory=(e=[])=>{const t=/* @__PURE__ */new Map;for(const i of e){const e=toBaseMapPOICategory(i.id);e&&!t.has(e)&&isMapCategoryIcon(i)&&t.set(e,i)}return t},supportedPinSubcategories=/* @__PURE__ */new Set([7339002,8099002,7369004,7321003,7376006,9362003,9362004,9160004,9376007,7315015,9376006,9376002,7315078,7315149,9376005,7372003,9352045,9352032,9361048,9378005,7383004,9910004,7320002,9362016,7320003,9362025,9942002,9942003,7380005,9663003,9361021,9379009,9379004,7315147,9376003,9160002,9160003,9352008,9361006,7389004,9910006]),pinImageSubstitutes=/* @__PURE__ */(()=>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]])))(),toPinImageID=e=>{if(!e)return;const t=supportedPinSubcategories.has(e)?e:Number(e.toString().substring(0,4));return`pinCategories:${String(pinImageSubstitutes.get(t)??t)}`},buildPlaceTitle=e=>e.properties.poi?.name??e.properties.address.freeformAddress,getEffectivePOICategory=(e,t)=>{const i=t?.icon?.mapping;return("poiCategory"===i?.to?i.fn(e):void 0)??e.properties.poi?.categories?.[0]},getIconIDForPlace=(e,t,i={})=>{const s=i.icon?.mapping,o="imageID"===s?.to?s.fn(e):void 0;if(o)return o;const r=getEffectivePOICategory(e,i),a=((e,t=[])=>{const i=e&&toBaseMapPOICategory(e),s=e?.endsWith("_GENERIC")?e.slice(0,-8):void 0;return t.find(t=>t.id===e)??(s?t.find(e=>e.id===s):void 0)??(i?iconsByMapCategory(t).get(i):void 0)})(r,i.icon?.categoryIcons);return a?a.image?suffixNumber(a.id,t):a.id:((e,t,i)=>{if(!e)return i;if("pin"===t||"pin-clustered"===t)return toPinImageID(poiCategoriesToID[e])??i;{const t=toBaseMapPOICategory(e);return t?toBaseMapPOIImageID(t):i}})(r,i.markerType??"pin",((e,t)=>e.icon?.default||"base-map"!==(e.markerType??"pin")?suffixNumber("default_place",t):"poi-parking-micro")(i,t))},getPOILayerCategoryForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&toBaseMapPOICategory(i)},getPOIGroupForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&(e=>{const t=toBaseMapPOICategory(e);return t?baseMapCategoryGroups[t]:void 0})(i)},toPlaces=e=>Array.isArray(e)?{type:"FeatureCollection",features:e}:"Feature"===e.type?{type:"FeatureCollection",features:[e]}:e,getBaseMapIconIDForPlace=(e,t)=>{const i=getPOILayerCategoryForPlace(e,t);return i?toBaseMapPOIImageID(i):"poi-parking-micro"},configWrites=/* @__PURE__ */new WeakMap,preparePlacesForInstance=(e,t,i={})=>{const s=toPlaces(e);return{...s,features:s.features.map(e=>{const s=(e=>{const t=configWrites.get(e.geometry);if(!t)return e;const i={...e.properties};for(const s of t.keys)Reflect.deleteProperty(i,s);return{...e,properties:{...i,...t.replaced}}})(e),o=s.id??generateId(),r=((e,t)=>({...("base-map"===t.markerType||"pin-clustered"===t.markerType)&&{category:getPOILayerCategoryForPlace(e,t),group:getPOIGroupForPlace(e,t)},..."pin-clustered"===t.markerType&&{baseMapIconID:getBaseMapIconIDForPlace(e,t)},...Object.fromEntries(Object.entries(t.extraFeatureProps??{}).map(([t,i])=>[t,"function"==typeof i?i(e):i]))}))(s,i),a=Object.keys(r),n={...s.geometry,bbox:s.bbox};return configWrites.set(n,{keys:a,replaced:Object.fromEntries(Object.entries(s.properties).filter(([e])=>a.includes(e)))}),{...s,id:o,geometry:n,properties:{...s.properties,id:o,title:featureTitle(s,i.label?.title,buildPlaceTitle),iconID:getIconIDForPlace(s,t,i),...r}}})}},preparePlacesForDisplay=(e,t={})=>preparePlacesForInstance(e,0,t),placeSources=["places","placesUnclustered"],PlacesModule=class PlacesModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new PlacesModule(e,t)}constructor(e,t){super(e,t),this.refreshingEntryPoints=!1,this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&this.updateLayersAndData(this.config)});const i=()=>this.config?.markerType&&poiLookMarkerTypes.has(this.config.markerType);onStyleKnobsApplied(e,poiLookKnobIds,()=>{i()&&this.updatePlacesLayers(this.config)}),onMapTypefaceChange(e,()=>{i()||this.updatePlacesLayers(this.config),this.connectionLayerSpecs=this.replaceLayerSpecs(this.buildConnectionLayerSpecs(this.config),this.connectionLayerSpecs,this.sourcesWithLayers.connections)})}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.addedCategoryIcons={}),this.layerSpecs=this.buildLayerSpecs(e);const i=this.buildClusterOptions(e);this.currentClusterOptions=i;const s=this.partitionSpecsForSources(this.layerSpecs),o=new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,s.clusteredSpecs,!1,i);let r;s.unclusteredSpecs.length>0&&(r=new GeoJSONSourceWithLayers(this.mapLibreMap,this.unclusteredSourceID,s.unclusteredSpecs,!1)),this.connectionLayerSpecs=this.buildConnectionLayerSpecs(e);const a=this.addOverlaySource(this.connectionSourceID,this.connectionLayerSpecs);addLayers([...o._layerSpecs,...r?._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),r?{places:o,placesUnclustered:r,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 this.replaceSourceLayers(Object.values(e),Object.values(t),i),e}partitionSpecsForSources(e){if(!this.currentClusterOptions)return{clusteredSpecs:Object.values(e),unclusteredSpecs:[]};const t=[],i=[];for(const[s,o]of Object.entries(e))"micro"===s?t.push(o):i.push(o);return{clusteredSpecs:i,unclusteredSpecs:t}}buildLayerSpecs(e){const t=((e,t,i,s,o="#3f9cd9",r)=>{const a=((e,t)=>{const i=/* @__PURE__ */new Map,s=e?.icon?.categoryIcons??[],o=buildCustomIconOffsets(s);for(const r of s){const s=calculateIconScale(r.image,e?.markerType,r.pixelRatio),a=o.get(r.id);(s||a)&&i.set(suffixNumber(r.id,t),{scales:s,offset:a})}return i})(e,s);let n,l,c=HIDDEN_LAYER_SPEC,d=HIDDEN_LAYER_SPEC,u=HIDDEN_CIRCLE_LAYER_SPEC,h=HIDDEN_LAYER_SPEC,p=HIDDEN_CIRCLE_LAYER_SPEC,y=HIDDEN_LAYER_SPEC;if("base-map"===e?.markerType)n={...buildBaseMapPOILayerSpec(t),minzoom:10},c=buildPOIMicroLikeLayerSpec(t),l=((e,t)=>toSelectedSpec(buildBaseMapPOILayerSpec(e),t))(t,o);else if("circle-icon"===e?.markerType)n=(e=>({...buildCircleBaseLayerSpec(e),filter:hasNoActiveEventState}))(t),l=((e,t)=>toSelectedSpec(buildCircleBaseLayerSpec(e),t))(t,o);else if("pin-clustered"===e?.markerType){n={...pinLayerSpec,filter:["all",isNotClusterFilter,hasNoActiveEventState]},l={...selectedPinLayerSpec(o),filter:["all",isNotClusterFilter,hasActiveEventState]},c=buildPOIMicroLikeLayerSpec(t);const i=e?.cluster?.badge;f=e.icon?.opacity,d={type:"symbol",filter:isSingleCategoryClusterFilter,layout:{"icon-image":buildKnownBaseMapSpriteImageExpr(["get","clusterBaseMapIconIDs"]),"icon-size":1,"icon-allow-overlap":!0,"icon-ignore-placement":!0},...void 0!==f&&{paint:{"icon-opacity":f}}},u=(e=>({type:"circle",filter:isSingleCategoryClusterFilter,paint:{...badgeCirclePaint(e,e?.radius?.single??11),"circle-translate":singleBadgeOffset(e),"circle-translate-anchor":"viewport"}}))(i),h=(e=>({type:"symbol",filter:isSingleCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":e?.label?.color??"#FFFFFF","text-translate":singleBadgeOffset(e),"text-translate-anchor":"viewport"}}))(i),p=(e=>({type:"circle",filter:isMixedCategoryClusterFilter,paint:badgeCirclePaint(e,e?.radius?.mixed??15)}))(i),y=(e=>({type:"symbol",filter:isMixedCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":e?.label?.color??"#FFFFFF"}}))(i)}else n=pinLayerSpec,l=selectedPinLayerSpec(o);var f;const{microBeforeID:m,partAnchor:g}=(e=>{const t=partBeforeLayerIDOf(e?.beforeLayerConfig,"places",void 0);return{microBeforeID:void 0===beforeLayerTargetOf(e?.beforeLayerConfig,"places")?mapStyleLayerIDs.lowestPlaceLabel:"main",partAnchor:t?{beforeID:t}:{}}})(e),S=labelTypefaceOf(e?.label,r),b=(t,s)=>((e,t,i,s,o)=>{const r=t?.label,a=t?.layers?.[i],n=titleTextField(r?.title,void 0);return{...e,...a,layout:buildLayoutConfig(e,t,i,n,o),paint:buildPaintConfig(e,t,i,s)}})(withMapTypeface(t,S),e,s,i,a);return{micro:{...b(c,"micro"),beforeID:m},main:{...b(n,"main"),beforeID:"selected"},selected:{...b(l,"selected"),...g},cluster:{...mergeLayer(d,e?.layers?.cluster),beforeID:"clusterBadge"},clusterBadge:{...mergeLayer(u,e?.layers?.clusterBadge),beforeID:"clusterCount"},clusterCount:{...mergeLayer(withMapTypeface(h,r),e?.layers?.clusterCount),beforeID:"clusterMixedBadge"},clusterMixedBadge:{...mergeLayer(p,e?.layers?.clusterMixedBadge),beforeID:"clusterMixedCount"},clusterMixedCount:{...mergeLayer(withMapTypeface(y,r),e?.layers?.clusterMixedCount),...g},...e?.layers?.additional}})(e,this.tomtomMap.mapLibreMap,this.tomtomMap.styleLightDarkTheme,this.instanceIndex,this.colorOf(e),mapTypefaceOf(this.tomtomMap)),i=new Set(Object.keys(t));return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,{...t,id:prefixLayerID(e,this.layerIDPrefix),...t.beforeID&&i.has(t.beforeID)?{beforeID:prefixLayerID(t.beforeID,this.layerIDPrefix)}:{}}]))}buildClusterOptions(e){if("pin-clustered"!==e?.markerType)return;const t=e.cluster?.source;return{cluster:!0,clusterRadius:t?.radius??60,clusterMaxZoom:t?.maxZoom??17,...void 0!==t?.minPoints&&{clusterMinPoints:t.minPoints},clusterProperties:{...t?.properties,...clusteredPlacesAggregateProperties}}}buildConnectionLayerSpecs(e){const t=((e,t,i="light",s)=>{const{lineColor:o,labelColor:r,labelHaloColor:a}=getThemeAdaptiveConnectionColors(i,e?.color??t);return{line:mergeLayer(buildBaseLineSpec$1(o),e?.layers?.line),label:mergeLayer(withMapTypeface(buildBaseLabelSpec(e?.label?.color??r,e?.label?.haloColor??a),s),e?.layers?.label)}})(e?.connections,this.colorOf(e),this.tomtomMap.styleLightDarkTheme,mapTypefaceOf(this.tomtomMap)),i=prefixLayerID("connection-line",this.layerIDPrefix),s=prefixLayerID("connection-label",this.layerIDPrefix),o=partBeforeLayerIDOf(e?.beforeLayerConfig,"connections",mapStyleLayerIDs.lowestLabel);return{line:{...t.line,id:i,beforeID:o},label:{...t.label,id:s,beforeID:o}}}buildEntryPointLayerSpecs(e){const t=this.buildClusterOptions(e),i=t?(t.clusterMaxZoom??17)+1:0,s=((e,t="light",i=0,s)=>{const{color:o,strokeColor:r}=((e,t)=>{const{lineColor:i,labelColor:s,labelHaloColor:o}=getThemeAdaptiveConnectionColors(e,t);return{color:"dark"===e?i:s,strokeColor:o}})(t,s),a=Math.max(e?.minZoom??15,i);return{line:mergeLayer(buildBaseLineSpec(o,a),e?.layers?.line),point:mergeLayer(buildBasePointSpec(o,r,a),e?.layers?.point)}})(e?.entryPoints,this.tomtomMap.styleLightDarkTheme,i,this.colorOf(e));return{line:{...s.line,id:prefixLayerID("entry-point-line",this.layerIDPrefix),beforeID:this.layerSpecs.main.id},point:{...s.point,id:prefixLayerID("entry-point",this.layerIDPrefix),beforeID:this.layerSpecs.cluster.id}}}_applyConfig(e){return declareFontFaces(this.tomtomMap,this,customFacesOf([e?.label])),this.updateLayersAndData(e),e}discardShownData(){this.shownConnections=[]}restoreDataAndConfigImpl(){const e=this.drawnFeatures();this.initSourcesWithLayers(this.config,!0),this.showAgain(e,this.config),this._applyConfig(this.config)}drawnFeatures(){const{places:e,placesUnclustered:t,connections:i,entryPoints:s}=this.sourcesWithLayers;return{places:e.shownFeatures,placesUnclustered:t?.shownFeatures,connections:i.shownFeatures,entryPoints:s.shownFeatures}}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:s}=this.sourcesWithLayers;addLayers([e,t,i,s].flatMap(e=>e?._layerSpecs??[]),this.mapLibreMap,!0)}updatePlacesLayers(e){const t=this.buildLayerSpecs(e),i=this.partitionSpecsForSources(t),s=this.partitionSpecsForSources(this.layerSpecs);this.replaceSourceLayers(i.clusteredSpecs,s.clusteredSpecs,this.sourcesWithLayers.places),this.sourcesWithLayers.placesUnclustered&&i.unclusteredSpecs.length>0&&this.replaceSourceLayers(i.unclusteredSpecs,s.unclusteredSpecs,this.sourcesWithLayers.placesUnclustered),this.layerSpecs=t}rebuildSourcesAndLayers(e){const t=this.drawnFeatures(),i=this.mapLibreMap;for(const s of[...Object.values(this.layerSpecs),...Object.values(this.connectionLayerSpecs),...Object.values(this.entryPointLayerSpecs)])i.getLayer(s.id)&&i.removeLayer(s.id);for(const s of[this.sourceID,this.unclusteredSourceID,this.connectionSourceID,this.entryPointSourceID])i.getSource(s)&&i.removeSource(s);this.initSourcesWithLayers(e,!0),this.showAgain(t,e)}showAgain(e,t){this.showPlaces(t,e.places,e.placesUnclustered),this.applyPlacesVisibility(t),this.updateConnectionsData(t,e.connections),this.updateEntryPointsData(t,e.entryPoints)}showPlaces(e,t,i=t){const s=preparePlacesForInstance(t,this.instanceIndex,e);this.sourcesWithLayers.places.show(s,{automaticVisibility:!1}),this.sourcesWithLayers.placesUnclustered?.show(i===t?s:preparePlacesForInstance(i,this.instanceIndex,e),{automaticVisibility:!1})}updateConnectionsData(e,t=this.sourcesWithLayers.connections.shownFeatures){const i=this.sourcesWithLayers.places.shownFeatures,s=((e,t,i,s={})=>{const o=s.connections?.label?.title,r=eventStatesById(i),a=[];for(const{connection:n,id:l}of e){const e=resolveEndpoint(n.from,t),i=resolveEndpoint(n.to,t);if(!e||!i)continue;const s=o?o(n):"",c=r.get(l);a.push({type:"Feature",id:l,geometry:{type:"LineString",coordinates:[e.geometry.coordinates,i.geometry.coordinates]},properties:{id:l,fromId:"string"==typeof n.from?n.from:e.id,toId:"string"==typeof n.to?n.to:i.id,label:s,...c&&{eventState:c}}})}return{type:"FeatureCollection",features:a}})(this.shownConnections,i,t,e);this.sourcesWithLayers.connections.show(s,{automaticVisibility:!1}),this.applyVisibilityTo(Object.values(this.connectionLayerSpecs),!!s.features.length,e)}updateEntryPointsData(e,t=this.sourcesWithLayers.entryPoints.shownFeatures){if(!this.refreshingEntryPoints){this.refreshingEntryPoints=!0;try{const i=this.sourcesWithLayers.entryPoints,s=((e,t,i)=>{const s=[];if(!i)return{type:"FeatureCollection",features:s};const o=i.showFor??"selected",r=eventStatesById(t);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,r.get(e))))for(const[o,{position:n,...l}]of t.entries()){const t=i[o],c=r.get(t),d={...l,id:t,placeID:e,entryPointIndex:o};s.push({type:"Feature",id:t,geometry:toPointGeometry(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:s}})(this.sourcesWithLayers.places.shownFeatures,t,e?.entryPoints);i.show(s,{automaticVisibility:!1}),this.applyVisibilityTo(Object.values(this.entryPointLayerSpecs),!!s.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.addedCategoryIcons=syncImages(this.mapLibreMap,this.addedCategoryIcons,customImagesByID(e?.icon?.categoryIcons,({id:e})=>suffixNumber(e,this.instanceIndex))),this.paintedPin=paintPin(this.mapLibreMap,this.defaultPlaceIconID,e?.icon?.default,{fillColor:this.colorOf(e)},defaultPin,this.paintedPin)}updateData(e){const{places:t,placesUnclustered:i}=this.sourcesWithLayers;this.showPlaces(e,t.shownFeatures,i?.shownFeatures)}async show(e){await this.waitUntilModuleReady(),this.clearConnectionsSync(),this.sourcesWithLayers.entryPoints.clear(),this.showPlaces(this.config,e),this.applyPlacesVisibility(this.config);for(const t of this.shownFeaturesHandlers)t({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.map(e=>({connection:e,id:e.id??generateId()})),this.updateConnectionsData(this.config,{type:"FeatureCollection",features:[]});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.map(({connection:e})=>e)}}eventStateSources(){return placeSources}get events(){return this.buildEvents(this.moduleEventsWithShown([...placeSources,"connections","entryPoints"],this.shownFeaturesHandlers),{places:this.userEventsWithStates(placeSources,{scope:{featureMatches:e=>!isCluster(e)}}),connections:this.userEventsWithStates(["connections"]),entryPoints:this.userEventsWithStates(["entryPoints"],{mapping:e=>((e,t)=>{const i=e.properties,s=findFeatureByRefId(t.features,i.placeID)?.feature,{position:o,...r}=s?.properties.entryPoints?.[i.entryPointIndex]??{...i,position:(a=e.geometry,"Point"===a.type?a.coordinates:a.coordinates[1])};var a;return{type:"Feature",id:i.id,geometry:toPointGeometry(o),properties:{...i,...r,place:s}}})(e,this.sourcesWithLayers.places.shownFeatures)})})}},poiCategoryGroups={FOOD_DRINKS_GROUP:["RESTAURANT","FAST_FOOD","CAFE_PUB","PUB","WINERY","SOUL_FOOD"],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"],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","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__ */(()=>{const e=/* @__PURE__ */valuesFilterKnobs("filters.categories","categories and category groups",[...Object.keys(poiCategoryGroups),...poiCategories]," A group stands for each of its categories; groups come first in the options.");return{visible:{kind:"toggle",description:"The POIs the map style draws.",default:!0},"filters.categories.show":e.show,"filters.categories.values":e.values,sizeFactor:{kind:"factor",description:"Size of the POI icons and their labels.",range:FACTOR_RANGE,default:1},minZoom:{kind:"number",description:"Zoom level from which POIs appear (the style default is 6).",range:{min:3,max:18,step:1,bounds:"hard"}},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"},default:0},"label.color":{kind:"color",description:"Text colour of the POI labels (replaces the per-category colours)."},"label.haloColor":{kind:"color",description:"Halo colour of the POI labels."},"microMarkers.visible":{kind:"toggle",description:"The small dot markers for low-priority POIs at high zoom; never shown while the POIs are hidden."}}})(),poisKnobCatalogue=/* @__PURE__ */withIds(poisKnobDefinitions),poisKnobIds=/* @__PURE__ */poisKnobCatalogue.map(({id:e})=>e),styleModuleLayerGroupNames=["pois","trafficFlow","trafficIncidents","hillshade"],styleModuleLayerGroupSelectors={pois:{sources:["vectorTiles"],sourceLayers:["poi"],layerTypes:["symbol"]},trafficFlow:{sources:["vectorTilesFlow"]},trafficIncidents:{sources:["vectorTilesIncidents"]},hillshade:{layerTypes:["hillshade"]}},styleModuleLayerGroupSelector=e=>styleModuleLayerGroupSelectors[e],styleLayerGroupSelector=e=>(e=>e in styleModuleLayerGroupSelectors)(e)?styleModuleLayerGroupSelector(e):baseMapLayerGroupSelector(e),writeLayerProperty=(e,t,i,s,o)=>{if(!e.getLayer(t))return;const r=e,a={validate:!1};"paint"===i?r.setPaintProperty(t,s,o,a):r.setLayoutProperty(t,s,o,a)},isDerivation=e=>"function"==typeof e,toOverrides=(e,t)=>Object.entries(t).map(([t,i])=>({kind:e,property:t,valueOf:isDerivation(i)?i:()=>i})),LayerSelection=class{constructor(e,t){this.registry=e,this.query=t}get layerIds(){return this.registry.resolve(this.query)}setPaint(e){for(const t of toOverrides("paint",e))this.registry.override(this.query,t);return this}setLayout({visibility:e,...t}){for(const i of toOverrides("layout",t))this.registry.override(this.query,i);return void 0!==e&&this.setVisible("none"!==e),this}setFilter(e){return this.registry.overrideFilter(this.query,e),this}addFilterClause(e){return this.registry.addFilterClause(this.query,e),this}removeFilterClause(e){return this.registry.removeFilterClause(this.query,e),this}setVisible(e){return this.registry.overrideVisibility(this.query,e),this}reset(){return this.registry.reset(this.query),this}},LayerOverrides=class{constructor(e,t,i,s){this.mapLibreMap=e,this.filterComposer=t,this.visibilityComposer=i,this.warn=s,this.layers=[],this.sources={},this.properties=/* @__PURE__ */new Map,this.filters=/* @__PURE__ */new Map,this.clauses=/* @__PURE__ */new Map,this.visibility=/* @__PURE__ */new Map}index(e,t,i){if(this.layers=e,this.sources=t,i)for(const s of this.properties.values())for(const e of s.values())e.restyled=!0}clear(){this.properties.clear(),this.filters.clear(),this.clauses.clear(),this.visibility.clear()}resolve(e){const t=selectorsOf(e);return this.layers.filter(e=>t.every(t=>matchesLayerSelector(t,e,this.sources))).map(e=>e.id)}override(e,t){const i=`${t.kind}:${t.property}`;for(const s of this.resolveToEdit(e)){const e=ofMap(this.properties,s,()=>/* @__PURE__ */new Map),o=e.get(i),r={override:t,before:o&&!o.restyled?o.before:this.read(s,t),written:void 0};e.set(i,r),this.land(s,r)}}addFilterClause(e,t){for(const i of this.resolveToEdit(e)){const e=ofMap(this.clauses,i,()=>[]);e.some(e=>isEqual(e,t))||e.push(t),this.contributeClauses(i)}}removeFilterClause(e,t){for(const i of this.resolveToEdit(e)){const e=(this.clauses.get(i)??[]).filter(e=>!isEqual(e,t));e.length?this.clauses.set(i,e):this.clauses.delete(i),this.contributeClauses(i)}}overrideFilter(e,t){for(const i of this.resolveToEdit(e))this.filters.set(i,t),this.filterComposer.setTransform(i,"styling.layers",()=>t)}overrideVisibility(e,t){for(const i of this.resolveToEdit(e))this.visibility.set(i,t),this.visibilityComposer.setVisible(i,"styling.layers",t)}reset(e){for(const t of this.resolveToEdit(e)){for(const{override:e,before:i}of this.properties.get(t)?.values()??[])this.write(t,e,i);this.properties.delete(t),this.filters.delete(t)&&this.filterComposer.setTransform(t,"styling.layers",void 0),this.clauses.delete(t)&&this.contributeClauses(t),this.visibility.delete(t)&&this.visibilityComposer.setVisible(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);!i.restyled&&isEqual(t,i.written)||(i.before=t),i.restyled=!1,this.land(e,i)}for(const[e,t]of this.filters)this.filterComposer.setTransform(e,"styling.layers",()=>t);for(const e of this.clauses.keys())this.contributeClauses(e);for(const[e,t]of this.visibility)this.visibilityComposer.setVisible(e,"styling.layers",t)}resolveToEdit(e){const t=this.resolve(e);return 0===t.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.`),t}read(e,{kind:t,property:i}){const s=this.mapLibreMap;return"paint"===t?s.getPaintProperty(e,i):s.getLayoutProperty(e,i)}land(e,t){t.written=t.override.valueOf(t.before,e),this.write(e,t.override,t.written)}write(e,{kind:t,property:i},s){writeLayerProperty(this.mapLibreMap,e,t,i,s)}contributeClauses(e){const t=getMergedFilter("all",this.clauses.get(e)??[])??void 0;this.filterComposer.setClause(e,"styling.layers",t)}},selectorsOf=({group:e,...t})=>[t,...e?[styleLayerGroupSelector(e)]:[]],ZOOM_BOUNDS={minZoom:"minzoom",maxZoom:"maxzoom"},LAYOUT_PROPERTIES=/* @__PURE__ */new Set(["text-size","icon-size","text-font","fill-extrusion-rounded-corner-distance"]),SPEC_DEFAULTS={"text-size":16,"icon-size":1,"line-width":1,"line-opacity":1,minzoom:0,maxzoom:24,"hillshade-method":"standard","hillshade-illumination-direction":335,"hillshade-illumination-altitude":45,"hillshade-illumination-anchor":"viewport","hillshade-exaggeration":.5,"hillshade-shadow-color":"#000000","hillshade-highlight-color":"#FFFFFF","hillshade-accent-color":"#000000","fill-extrusion-rounded-corner-distance":0},isLayerMechanism=e=>"layers"in e,targetKey=(e,t)=>`${e}|${t}`,NO_TRANSITION={duration:0,delay:0},enginesByMap=/* @__PURE__ */new WeakMap,StyleKnobs=class StyleKnobs{constructor(e){this.settings={},this.stale=!1,this.registered=/* @__PURE__ */new Map,this.dependents=/* @__PURE__ */new Map,this.style={layers:[],sources:{}},this.originalValues=/* @__PURE__ */new Map,this.resolved=/* @__PURE__ */new Map,this.scaleKnobsByTarget=/* @__PURE__ */new Map,this.warned=/* @__PURE__ */new Set,this.tomtomMap=e,this.filterComposer=LayerFilterComposer.for(e),this.indexStyle(),e.addStyleChangeHandler({onStyleAboutToChange:()=>{this.stale=!0},onStyleChanged:({resetState:e})=>this.restore(e),priority:90})}static for(e){return ofMap(enginesByMap,e,()=>new StyleKnobs(e))}register(e,t,i){i&&!this.extension&&(this.extension=i,this.stale||i.index());for(const[s,o]of Object.entries(t))this.registered.has(s)||(this.registered.set(s,{owner:e,definition:o}),this.trackDependencies(s,o),this.stale||this.resolveKnob(s))}trackDependencies(e,t){for(const i of t.mechanisms)if("literal"===i.type)for(const t of i.expansion?.dependsOn??[])ofMap(this.dependents,t,()=>[]).push(e)}get values(){return this.settings}get indexedStyle(){return this.style}update(e){const t={...this.settings},i=[];for(const s of Object.keys(e)){const o=e[s];t[s]!==o&&(void 0===o?delete t[s]:t[s]=o,i.push(s))}if(this.settings=t,!this.stale&&i.length){for(const e of this.withDependents(i))this.refreshKnob(e);this.publish(i)}}reapply(e){if(!this.stale){for(const t of this.withDependents(e))this.refreshKnob(t);this.publish(e)}}valueOf(e){return this.settings[e]??this.derivedValueOf(e)??this.defaultOf(e)}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))}setProperty(e,t,i){const s=LAYOUT_PROPERTIES.has(t)?"layout":"paint";writeLayerProperty(this.tomtomMap.mapLibreMap,e,s,t,i)}restore(e){e&&(this.settings={}),this.stale=!1,this.indexStyle();const t=new Set(Object.keys(this.settings));customTypefaceOf(this.tomtomMap)&&t.add("labels.typeface"),this.reapply([...t])}withDependents(e){return new Set(e.flatMap(e=>[e,...this.dependents.get(e)??[]]))}publish(e){const t=this.tomtomMap._styleKnobSettings,i=new Set(e);for(const s of Object.keys(t))t[s]!==this.settings[s]&&i.add(s);this.tomtomMap._setStyleKnobSettings(this.settings,i)}indexStyle(){const e=this.tomtomMap.mapLibreMap.getStyle();this.style={layers:(e?.layers??[]).filter(e=>this.tomtomMap._isStyleLayer(e.id)),sources:e?.sources??{},projection:e?.projection,sky:e?.sky,light:e?.light},this.originalValues=/* @__PURE__ */new Map,this.resolved=/* @__PURE__ */new Map,this.scaleKnobsByTarget=/* @__PURE__ */new Map,this.warned=/* @__PURE__ */new Set,this.holdTransitionsUntilFirstFrame(),this.extension?.index();for(const t of this.registered.keys())this.resolveKnob(t)}holdTransitionsUntilFirstFrame(){const e=this.tomtomMap.mapLibreMap,t=e.style?.stylesheet;if(!t||t.transition===NO_TRANSITION)return;const i=t.transition;t.transition=NO_TRANSITION,e.once("render",()=>{t.transition=i})}resolveKnob(e){const t=this.registered.get(e);if(!t)return;const{definition:i}=t,s=i.mechanisms.map(t=>this.resolveMechanism(e,t)),o=new Set(s.flatMap(e=>e.layerIds)).size;this.resolved.set(e,{definition:i,mechanisms:s,targets:o})}resolveMechanism(e,t){if(!isLayerMechanism(t))return{mechanism:t,layerIds:this.extension?.resolve(e,t)??[],shadeLayerIds:[]};const{layers:i,sources:s}=this.style,o=i.filter(e=>matchesAnyLayerSelector(t.layers,e,s));let r,a=[];switch(t.type){case"scale":r=this.captureAll(o,t.property);for(const i of r){const s=targetKey(i,t.property);ofMap(this.scaleKnobsByTarget,s,()=>[]).push(e)}break;case"color":{r=this.captureAll(o,t.property);const e=t.shades??[],n=i.filter(t=>matchesAnyLayerSelector(e,t,s));a=this.captureAll(n,t.property);break}case"minZoom":case"maxZoom":r=o.map(e=>e.id);for(const e of o)this.capture(e,"minzoom"),this.capture(e,"maxzoom");break;case"literal":r=o.map(e=>e.id);for(const e of o)this.capture(e,t.property);break;case"zoomOffset":r=o.filter(e=>shiftZoomOffset(layerFilterOf(e),0).patched).map(e=>e.id);break;case"typeface":r=this.captureAll(o,"text-font")}return{mechanism:t,layerIds:r,shadeLayerIds:a}}captureAll(e,t){return e.filter(e=>this.capture(e,t)).map(e=>e.id)}refreshKnob(e){const t=this.resolved.get(e);if(t&&this.tomtomMap.mapReady){0===t.targets&&void 0!==this.settings[e]&&this.warnOnce(e,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 i of t.mechanisms)this.refreshMechanism(e,i)}}refreshMechanism(e,{mechanism:t,layerIds:i,shadeLayerIds:s}){if(isLayerMechanism(t))if("color"!==t.type)for(const o of i)this.refreshLayer(e,t,o);else this.refreshColor(t.property,i,s,this.settings[e]);else this.extension?.refresh(e,t)}refreshLayer(e,t,i){const s=this.settings[e];switch(t.type){case"scale":this.refreshScaledProperty(e,i,t.property);break;case"minZoom":case"maxZoom":this.refreshZoomBound(i,ZOOM_BOUNDS[t.type],s);break;case"literal":{const e=s??this.originalValueOf(i,t.property),{expansion:o}=t;this.setProperty(i,t.property,o?o.expand(e,e=>this.valueOf(e)):e);break}case"zoomOffset":this.refreshZoomOffset(i,s);break;case"typeface":this.setProperty(i,"text-font",inTypeface(this.originalValueOf(i,"text-font"),typefaceOf(this.tomtomMap,s)))}}refreshZoomBound(e,t,i){const s=this.tomtomMap.mapLibreMap;if(!s.getLayer(e))return;const o={minzoom:this.styleZoomBound(e,"minzoom"),maxzoom:this.styleZoomBound(e,"maxzoom")};o[t]=i??o[t],s.setLayerZoomRange(e,o.minzoom,o.maxzoom)}styleZoomBound(e,t){return this.originalValueOf(e,t)??SPEC_DEFAULTS[t]}refreshZoomOffset(e,t){this.filterComposer.setTransform(e,"styleKnobs.zoomShift",void 0===t?void 0:e=>shiftZoomOffset(e,t).filter)}refreshScaledProperty(e,t,i){const s=this.originalValueOf(t,i),o=(this.scaleKnobsByTarget.get(targetKey(t,i))??[]).reduce((e,t)=>e*(this.settings[t]??1),1);if(1===o)return void this.setProperty(t,i,s);const r=scaleNumericValue(s,o);void 0!==r?this.setProperty(t,i,r):this.warnOnce(e,`scale:${t}:${i}`,`cannot scale '${i}' of layer '${t}': 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,s){for(const r of t)this.setProperty(r,e,s??this.originalValueOf(r,e));const o=t.map(t=>this.originalValueOf(t,e)).find(isColorLiteral);for(const r of i){const t=this.originalValueOf(r,e);let i=t;if(void 0!==s){const e=isColorLiteral(t)&&o&&hslShiftBetween(o,t);i=(e&&shiftHsl(s,e))??s}this.setProperty(r,e,i)}}derivedValueOf(e){const[t]=this.resolved.get(e)?.definition.mechanisms??[];return t&&!isLayerMechanism(t)?this.extension?.derivedValueOf(e,t):void 0}defaultOf(e){const t=this.resolved.get(e);if(!t)return;const{definition:i,mechanisms:s}=t;if("factor"===i.kind)return 1;const[o]=s,[r]=o?.layerIds??[];if(void 0===r)return;const{mechanism:a}=o;if(!isLayerMechanism(a))return this.extension?.defaultOf(e,a);switch(a.type){case"color":{const e=this.originalValueOf(r,a.property);return isColorLiteral(e)?e:void 0}case"minZoom":case"maxZoom":return this.styleZoomBound(r,ZOOM_BOUNDS[a.type]);case"literal":{const e=this.originalValueOf(r,a.property);return"string"==typeof e||"number"==typeof e?e:void 0}case"zoomOffset":return 0;case"typeface":return"sans";default:return}}warnOnce(e,t,i){this.warned.has(t)||(this.warned.add(t),console.warn(`[${this.registered.get(e)?.owner??StyleKnobs.name}] ${i}`))}},StyleKnobScope=class{constructor(e,t,i,s){this.owner=e,this.prefix=t,this.definitions=i,this.extension=s}get knobIds(){return this.knobIdsByLocalId??=new Map(Object.keys(this.definitions).map(e=>[e.slice(this.prefix.length),e])),this.knobIdsByLocalId}has(e){return e in this.definitions}get colorKnobIds(){return Object.keys(this.definitions).filter(e=>"color"===this.definitions[e].kind&&this.definitions[e].mechanisms.some(e=>"light"!==e.type))}engineOf(e){const t=StyleKnobs.for(e);return t.register(this.owner,this.definitions,this.extension?.(e)),t}apply(e,t){const i={};for(const[s,o]of this.knobIds)i[o]=knobValueIn(t,s);this.engineOf(e).update(i)}valueOf(e,t){const i=this.knobIds.get(t);return void 0===i?void 0:this.engineOf(e).valueOf(i)}},styleKnobScope=(e,t,i,s)=>new StyleKnobScope(e,t,i,s),layerFilterOf=e=>"filter"in e?e.filter:void 0,styleValueOf=(e,t)=>{const i=(e=>"layout"in e?e.layout:void 0)(e),s=(e=>"paint"in e?e.paint:void 0)(e),o="symbol"===e.type&&void 0!==i?.["text-field"];switch(t){case"text-size":return o?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":case"line-opacity":return"line"===e.type?s?.[t]??SPEC_DEFAULTS[t]:void 0;case"text-font":return o?i?.["text-font"]:void 0;case"minzoom":return e.minzoom;case"maxzoom":return e.maxzoom;default:return(LAYOUT_PROPERTIES.has(t)?i:s)?.[t]??((e,t)=>"hillshade"!==e.type&&"fill-extrusion"!==e.type||!(e=>e in SPEC_DEFAULTS)(t)?void 0:SPEC_DEFAULTS[t])(e,t)}},scaleKnob=(e,t)=>({kind:"factor",mechanisms:[{type:"scale",property:e,layers:[t]}]}),colorKnob=(e,t,i)=>({kind:"color",mechanisms:[{type:"color",property:e,layers:[t],shades:i&&[i]}]}),poisStyleKnobs=/* @__PURE__ */(()=>{const e=styleModuleLayerGroupSelector("pois");return{"pois.sizeFactor":{kind:"factor",mechanisms:[{type:"scale",property:"icon-size",layers:[e]},{type:"scale",property:"text-size",layers:[e]}]},"pois.minZoom":{kind:"number",mechanisms:[{type:"minZoom",layers:[{...e,idExcludes:["micro"]}]}]},"pois.zoomShift":{kind:"number",mechanisms:[{type:"zoomOffset",layers:[e]}]},"pois.label.color":colorKnob("text-color",e),"pois.label.haloColor":colorKnob("text-halo-color",e)}})(),poisLook=/* @__PURE__ */styleKnobScope("POIsModule","pois.",poisStyleKnobs),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}}},POI_ID=["to-string",["get","id"]],microMarkerSelectors=[{idIncludes:["micro"]}],iconLayoutProperties=["icon-image","icon-offset"],iconImageExpression=(e,t)=>{const i="string"==typeof t&&t.includes("{")?(e=>{const t=[];for(const[i,s]of e.split(/[{}]/).entries())i%2?t.push(["get",s]):s&&t.push(s);return["concat",...t]})(t):t??"",s=["match",["get","category"],...[...e].flat()];return s.push(i),s},toIconImageID=e=>`pois-${e}`,POIsModule=class POIsModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,POIsModule,()=>new POIsModule(e,t),t)}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const e=styleSourceWithLayers(this.mapLibreMap,"vectorTiles",POIsModule.name,e=>poiLayerIDs.includes(e.id));return this.addedIcons??={},this.microMarkers=new LayerPartToggles("pois",{"microMarkers.visible":microMarkerSelectors}),this.microMarkers.index(e._layerSpecs),{pois:e}}_applyConfig(e){return e&&!isNil(e.visible)?this._setVisible(e.visible,!1):this._initializing||this.isVisible()||this._setVisible(!0,!1),this.categoriesFilter=this.applyValuesFilter("pois.categories",this.categoriesFilter,e?.filters?.categories,({show:e,values:t})=>buildMappedValuesFilter("category",e,(e=>{const t=e.flatMap(e=>(e=>Object.hasOwn(poiCategoryGroups,e))(e)?poiCategoryGroups[e].map(toBaseMapPOICategory):[toBaseMapPOICategory(e)]);return[...new Set(t.filter(e=>!isNil(e)))]})(t))),this.idsFilter=this.applyValuesFilter("pois.ids",this.idsFilter,e?.filters?.ids,({show:e,values:t})=>buildMappedValuesFilter(POI_ID,e,t)),this.applyCategoryIcons(e?.icon?.categoryIcons),poisLook.apply(this.tomtomMap,e),this.tomtomMap.mapReady&&this.microMarkers.apply(this.visibilityComposer,e),e}_knobValue(e){return super._knobValue(e)??poisLook.valueOf(this.tomtomMap,e)??this.microMarkers.valueOf(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._layerSpecs){const t=matchesAnyLayerSelector(microMarkerSelectors,i);this.visibilityComposer.setVisible(i.id,"pois.visible",e&&t?void 0:e)}t&&(this.config={...this.config,visible:e},this.emitConfigChange())}applyValuesFilter(e,t,i,s){if(this.tomtomMap.mapReady&&(i||t)){const t=i&&isCompleteValuesFilter(i)?s(i):void 0;for(const i of this.sourcesWithLayers.pois.sourceAndLayerIDs.layerIDs)this.filterComposer.setClause(i,e,t)}return i}applyCategoryIcons(e){if(!this.tomtomMap.mapReady||!this.mapLibreMap.getLayer(mapStyleLayerIDs.poi))return;const t=iconsByMapCategory(e),i=/* @__PURE__ */new Map,s=/* @__PURE__ */new Map;for(const[h,p]of t)i.set(h,toIconImageID(p.id)),s.set(h,{x:p.offsetX??0,y:p.offsetY??0});if(!i.size&&!Object.keys(this.addedIcons).length)return;const o=styleIconLayout(this.mapLibreMap,{"icon-image":this.mapLibreMap.getLayoutProperty(mapStyleLayerIDs.poi,"icon-image"),"icon-offset":this.mapLibreMap.getLayoutProperty(mapStyleLayerIDs.poi,"icon-offset")}),{"icon-image":r,"icon-offset":a}=o,n={"icon-image":i.size?iconImageExpression(i,r):r,"icon-offset":buildIconOffsetExpression(s,"category",a)??a};for(const h of iconLayoutProperties)this.mapLibreMap.setLayoutProperty(mapStyleLayerIDs.poi,h,n[h]);var l,c,d;l=this.mapLibreMap,c=n,d=o,writtenIconLayouts.set(l,{written:c,over:d});const u=customImagesByID([...t.values()],e=>toIconImageID(e.id));this.addedIcons=syncImages(this.mapLibreMap,this.addedIcons,u)}getRenderedFeatures(){return{pois:this.sourcesWithLayers.pois.queryRenderedFeatures().map(poisMapping)}}get events(){return this.moduleEvents(["pois"],{mapping:poisMapping})}},generatedSectionTypes=["carpool","carTrain","curvyStretch","curve","importantRoadStretch","lowEmissionZone","motorway","pedestrian","speedLimit","tollVignette","unpaved","urban"],bespokeSectionTypes=["ferry","tollRoad","traffic","tunnel","vehicleRestricted"],drawnSectionTypes=/* @__PURE__ */(()=>[...generatedSectionTypes,...bespokeSectionTypes])(),ALL_SECTION_KNOBS=["visible","color","opacity","widthPreset","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},curve:{sourceKey:"curveSections",visible:!1,style:"halo",rampsBy:"severity",knobs:["visible","color","opacity","widthPreset","widthFactor","style","icon","kerb"]},curvyStretch:{sourceKey:"curvyStretchSections",visible:!1,style:"halo",pattern:"solid",drawsUnder:"curve",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","widthPreset","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"),bandedSectionTypes=/* @__PURE__ */generatedSectionTypes.filter(e=>!postsSign(e)),sectionSourceKey=e=>SECTION_REGISTRY[e].sourceKey,SUMMARY_BUBBLE_DEFAULT_FIELDS=["duration","distance","trafficDelay"],mapLayerSpecs=(e={},t)=>Object.entries(e).map(([e,i])=>({...i,id:prefixLayerID(e,t)})),routeDisplayUnits=e=>{const t=TomTomConfig.instance.get().displayUnits;return{distance:{...t?.distance,...e?.displayUnits?.distance},time:{...t?.time,...e?.displayUnits?.time}}},SELECTED_ROUTE_FILTER=["==",["get","routeState"],"selected"],DESELECTED_ROUTE_FILTER=["==",["get","routeState"],"deselected"],selectedRouteLine=(e,t)=>({filter:SELECTED_ROUTE_FILTER,type:"line",layout:{"line-join":"round",...t},paint:e}),selectedRoutePOISymbol=(e,t)=>({filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:t,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-image":e,"icon-size":/* @__PURE__ */zoomRamp(t,.8,16.5,1)}}),instanceImageID=(e,t)=>void 0===t?e:suffixNumber(e,t),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"},ROUTE_WAYPOINT_HIGHLIGHT_SIZE_FACTOR_RANGE={min:1,max:1.5,step:.05,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"},SECTION_FOCUS_OUTLINE_WIDTH_FACTOR_RANGE={min:.5,max:2,step:.1,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,s=scaleNumericValue(i,clampFactor(t,SECTION_ICON_SIZE_FACTOR_RANGE));return"number"==typeof s||isExpression(s)?s:i},scaledWidth=(e,t)=>scaleRamp(e[t?.widthPreset??"m"],clampFactor(t?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),LINE_FOREGROUND_WIDTHS={s:/* @__PURE__ */zoomRamp(1,2,5,3,10,5,18,7),m:/* @__PURE__ */zoomRamp(1,3,5,4,10,7,18,10),l:/* @__PURE__ */zoomRamp(1,5,5,6,10,11,18,15)},LINE_OUTLINE_WIDTHS={s:/* @__PURE__ */zoomRamp(1,4,5,5,10,8,18,11),m:/* @__PURE__ */zoomRamp(1,5,5,6,10,10,18,14),l:/* @__PURE__ */zoomRamp(1,7,5,9,10,14,18,19)},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),SECTION_FOCUS_OUTLINE_WIDTH=/* @__PURE__ */zoomRamp(5,2,10,3,18,4),rampStops=e=>e.slice(3).filter(e=>"number"==typeof e),widestRamp=e=>{const[t,...i]=e.map(rampStops);/* @__PURE__ */
2
- return zoomRamp(...t.map((e,t)=>t%2==0?e:Math.max(e,...i.map(e=>e[t]))))},getSectionFocusGapWidth=(e,t,i=[])=>widestRamp([scaleRamp(getLineOutlineWidth(e),t),...i]),getSectionFocusOutlineWidth=e=>scaleRamp(SECTION_FOCUS_OUTLINE_WIDTH,clampFactor(e,SECTION_FOCUS_OUTLINE_WIDTH_FACTOR_RANGE)),waypointScale=(e,t)=>WAYPOINT_SIZE_PRESET_FACTORS[e??"m"]*clampFactor(t,ROUTE_WAYPOINT_SIZE_FACTOR_RANGE),getWaypointIndexTextSize=(e,t)=>scaleRamp(PIN_ICON_SIZE,21*waypointScale(e,t)),STOP_MARK_TEXT_OFFSET=/* @__PURE__ */(()=>[0,-40.2/21])(),SECTION_HALO_WIDTHS={s:/* @__PURE__ */zoomRamp(1,8,5,9,10,12,18,15),m:/* @__PURE__ */zoomRamp(1,9,5,11,10,15,18,20),l:/* @__PURE__ */zoomRamp(1,12,5,14,10,19,18,24)},SECTION_HALO_MIN_OUTLINE_RATIO=/* @__PURE__ */(()=>ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE.max+.01)(),INSTRUCTION_LINE_WIDTHS={s:/* @__PURE__ */zoomRamp(16,8,22,12),m:/* @__PURE__ */zoomRamp(16,12,22,17),l:/* @__PURE__ */zoomRamp(16,17,22,24)},INSTRUCTION_OUTLINE_WIDTHS={s:/* @__PURE__ */zoomRamp(16,10,22,14),m:/* @__PURE__ */zoomRamp(16,14,22,20),l:/* @__PURE__ */zoomRamp(16,20,22,28)},getInstructionLineWidth=e=>scaledWidth(INSTRUCTION_LINE_WIDTHS,e),getInstructionOutlineWidth=e=>scaledWidth(INSTRUCTION_OUTLINE_WIDTHS,e),INSTRUCTION_ARROW_SIZE=/* @__PURE__ */zoomRamp(16,1,22,2),getInstructionArrowSize=e=>scaleRamp(INSTRUCTION_ARROW_SIZE,clampFactor(e?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),summaryBubbleColorKnobIds=["colors.label","colors.labelHalo"],summaryBubbleMapColors=(e={})=>({label:e["colors.label"],labelHalo:e["colors.labelHalo"]}),DARK_TEXT={text:"black",mutedText:"#727C85",majorDelay:"#AD0000",unknownDelay:"#000000"},LIGHT_TEXT={text:"#FFFFFF",mutedText:"#A7B0B8",majorDelay:"#FF6F61",unknownDelay:"#FFFFFF"},LIGHT_MAP_FILLS={selectedFill:"#FFFFFF",deselectedFill:"#EEEEEE"},DARK_MAP_FILLS={selectedFill:"#3A4148",deselectedFill:"#2A3036"},resolveSummaryBubbleColors=(e,t,i={})=>{const s=e?.color??(i.labelHalo&&(o=i.labelHalo,mixColor(o,"#FFFFFF",needsDarkText(o)?.6:.12)??o));var o;const r=s?{selectedFill:s,deselectedFill:mixColor(s,"#000000",.1)??s}:"dark"===t?DARK_MAP_FILLS:LIGHT_MAP_FILLS,a=needsDarkText(r.selectedFill)?DARK_TEXT:LIGHT_TEXT,n=e?.color?void 0:i.label;return{...r,...a,text:e?.label?.color??n??a.text}},resolveCountryCrossingColors=(e,t,i)=>{const{selectedFill:s,text:o}=resolveSummaryBubbleColors(e,t,i);return{selectedFill:s,text:o}},incidentIconID=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}},severityDashedFilter=["in",["get","magnitudeOfDelay"],["literal",["unknown","indefinite"]]],severitySolidFilter=["in",["get","magnitudeOfDelay"],["literal",["minor","moderate","major"]]],matchMagnitudeOfDelay=({fallback:e,...t})=>["match",["get","magnitudeOfDelay"],...indexedMagnitudes.flatMap(e=>{const i=t[e];return void 0===i?[]:[e,i]}),e],severityLineDashColor=/* @__PURE__ */matchMagnitudeOfDelay({unknown:"rgba(190, 39, 27, 1)",fallback:"rgba(137, 150, 168, 1)"}),summaryMapBubbleImg=e=>svgToImg(()=>{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),t}),SUMMARY_BUBBLE_CONTENT=[10,10,130,45],summaryBubbleImageOptions={pixelRatio:2,stretchX:[[20,45],[100,130]],stretchY:[[20,35]],content:SUMMARY_BUBBLE_CONTENT},summaryBubbleOverhang=/* @__PURE__ */(()=>({right:(150-SUMMARY_BUBBLE_CONTENT[2])/2,bottom:(55-SUMMARY_BUBBLE_CONTENT[3])/2,tail:3}))(),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=/* @__PURE__ */roundSignSvg("#fff","#D0021B",5),SPEED_LIMIT_SIGN_SVGS={whiteDisc:WHITE_DISC_SVG,yellowDisc:/* @__PURE__ */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},sectionStartSignImg=e=>svgMarkupToImg(SECTION_START_SIGN_SVGS[e]),speedLimitSignImg=e=>svgMarkupToImg(SPEED_LIMIT_SIGN_SVGS[e]),trafficImg=e=>svgToImg(()=>{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),t}),waypointGlyphs={start:'<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',middle:void 0,finish:'<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'},hasFormattedTraffic=["has","formattedTraffic"],HEADLINE_PROPERTY={duration:"formattedDuration",distance:"formattedDistance",durationDifference:"formattedDurationDifference"},HAS_FIELD={durationDifference:["has","formattedDurationDifference"],trafficDelay:hasFormattedTraffic},anyFieldOf=e=>{const t=e.map(e=>HAS_FIELD[e]).filter(e=>void 0!==e);return t.length<e.length||getMergedFilter("any",t)||!0},when=(e,t,i="")=>!0===e?t:["case",e,t,i],ROUTES_FILTER={all:void 0,selected:SELECTED_ROUTE_FILTER,alternatives:DESELECTED_ROUTE_FILTER},BOLD_FONT=["literal",["Noto-Bold"]],MEDIUM_FONT=["literal",["Noto-Medium"]],headlineSections=(e,t)=>{const i=["case",SELECTED_ROUTE_FILTER,t.text,t.mutedText];return e.flatMap((s,o)=>{const r=["get",HEADLINE_PROPERTY[s]],a=HAS_FIELD[s]??!0;if(0===o)return[when(a,r),{"text-font":BOLD_FONT,"text-color":i}];const n=anyFieldOf(e.slice(0,o));return[when(a,["concat",when(n,"\t\t"),r]),{"text-font":when(n,MEDIUM_FONT,BOLD_FONT),"text-color":when(n,t.mutedText,i)}]})},newlineAfter=e=>{if(!e.length)return[];const t=anyFieldOf(e);return[when(!0===t?hasFormattedTraffic:["all",hasFormattedTraffic,t],"\n"),{}]},trafficDelaySections=(e,t,i)=>[...newlineAfter(e),["image",["case",hasFormattedTraffic,
3
- /* @__PURE__ */matchMagnitudeOfDelay({minor:i("traffic-minor"),moderate:i("traffic-moderate"),major:i("traffic-major"),fallback:i("traffic-clear")}),""]],{},["case",hasFormattedTraffic,["concat"," ",["get","formattedTraffic"]],""],{"text-font":BOLD_FONT,"text-color":/* @__PURE__ */matchMagnitudeOfDelay({minor:"#f58240",moderate:"#FB2D09",major:t.majorDelay,fallback:t.unknownDelay})}],summaryBubbleSymbol=(e,t,i,s)=>{const o=t=>instanceImageID(t,e),r=t?.label,a=labelTypefaceOf(r,s),{textField:n,filter:l}=((e,t,i,s)=>{const o=e?.label?.title;if("function"==typeof o)return{textField:["get","title"],filter:["has","title"]};if(void 0!==o)return{textField:o};const r=((e,t,i)=>{const s=e.filter(e=>"trafficDelay"!==e),o=e.includes("trafficDelay");if(!s.length&&!o)return{textField:"",filter:["boolean",!1]};const r=["format",...headlineSections(s,t),...o?trafficDelaySections(s,t,i):[]],a=anyFieldOf(e);return!0===a?{textField:r}:{textField:r,filter:a}})(e?.fields??SUMMARY_BUBBLE_DEFAULT_FIELDS,t,i);return{...r,textField:inTypeface(r.textField,s)}})(t,i,o,a),c=getMergedFilter("all",[ROUTES_FILTER[t?.routes??"all"],l].filter(e=>void 0!==e));return{type:"symbol",...c&&{filter:c},...void 0!==t?.minZoom&&{minzoom:t.minZoom},...void 0!==t?.maxZoom&&{maxzoom:t.maxZoom},layout:{"icon-image":["case",SELECTED_ROUTE_FILTER,o("selected-route-summary-popup"),o("deselected-route-summary-popup")],"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":inTypeface(["Noto-Medium"],a),"text-size":r?.size??13,"icon-padding":0,"text-justify":"left","text-line-height":1.5,"text-field":n},paint:{"text-color":["case",SELECTED_ROUTE_FILTER,i.text,i.mutedText],...void 0!==r?.opacity&&{"text-opacity":r.opacity},"icon-translate":[0,-35],"text-translate":[0,-35]}}},DEFAULT_CROSSING_COLORS=/* @__PURE__ */resolveCountryCrossingColors(void 0,"light"),COUNTRY_CROSSING_LAYER_ID="routeCountryCrossing",CROSSING_TEXT_SIZE=/* @__PURE__ */zoomRamp(5,11,12,13),countryCrossingSymbol=(e,t,i)=>{const s=(e=>{const t=[0,-(4+summaryBubbleOverhang.tail)];return{layout:{"icon-image":e,"icon-text-fit":"both","icon-text-fit-padding":[4,8-summaryBubbleOverhang.right,4-summaryBubbleOverhang.bottom,8],"text-anchor":"bottom","icon-rotation-alignment":"viewport","text-rotation-alignment":"viewport"},paint:{"icon-translate":t,"text-translate":t,"icon-translate-anchor":"viewport","text-translate-anchor":"viewport"}}})(instanceImageID("route-country-crossing-bubble",e));return{type:"symbol",filter:SELECTED_ROUTE_FILTER,minzoom:t?.minZoom??4,layout:{"symbol-placement":"point",...s.layout,"text-field":["get","label"],"text-font":["Noto-Bold"],"text-size":CROSSING_TEXT_SIZE,...!1===t?.visible&&{visibility:"none"}},paint:{...s.paint,"text-color":i?.text??DEFAULT_CROSSING_COLORS.text}}},GENERATED_SECTION_PAINT={carpool:{color:"#6D4AC7",opacity:.55},carTrain:{color:"#8A5A2B",opacity:.6},curvyStretch:{color:"#D6336C",opacity:.35},curve:{color:"#D6336C",opacity:.8},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}},FADE_TOWARD={light:"#FFFFFF",dark:"#1A2024"},kerbDefaultColor=(e,t)=>mixColor(e,FADE_TOWARD[t],.95)??e,rampedColor=(e,t,i)=>["interpolate",["linear"],["coalesce",["get",e],1],0,mixColor(t,FADE_TOWARD[i],.45)??t,1,t],KERB_DASH_ARRAY=[.3,.3],isKerbStriped=(e,t)=>sectionSupportsKnob(e,"kerb")&&(t?.kerb?.visible??!0),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]},getSectionLineWidth=(e,t,i)=>{const s={widthPreset:t?.widthPreset??i?.widthPreset,widthFactor:t?.widthFactor??i?.widthFactor};return"halo"===sectionDrawStyle(e,t)?((e,t=e??{})=>widestRamp([scaledWidth(SECTION_HALO_WIDTHS,e),scaleRamp(getLineOutlineWidth(t),SECTION_HALO_MIN_OUTLINE_RATIO)]))(s,i??{}):getLineForegroundWidth(s)},drawnSectionLineWidths=(e,t)=>drawnSectionTypes.filter(t=>sectionDrawStyle(t,e?.[t])&&isSectionVisible(t,e?.[t])).map(i=>{const s=getSectionLineWidth(i,e?.[i],t);return isKerbStriped(i,e?.[i])?scaleRamp(s,1.1):s}),withSectionLineKnobs=(e,t,i,s,o="principal")=>{const r=getSectionLineWidth(e,i,s),a={...t.paint,"line-width":"kerb"===o?scaleRamp(r,1.1):r};if(i?.color&&sectionSupportsKnob(e,"color")&&"kerb"!==o){const e="outline"===o?darkerShadeOf(i.color):i.color;e&&(a["line-color"]=e)}void 0!==i?.opacity&&sectionSupportsKnob(e,"opacity")&&(a["line-opacity"]=i.opacity);const n="principal"===o&&sectionSupportsKnob(e,"pattern"),l=n?i?.pattern??sectionEntry(e).pattern:void 0;return n&&((e,t)=>{const i=linePatternDashArray(e);i?t["line-dasharray"]=i:delete t["line-dasharray"]})(l,a),{...t,layout:{...t.layout,...linePatternLayout(l),...!isSectionVisible(e,i)&&{visibility:"none"}},paint:a}},withSectionSymbolKnobs=(e,t,i)=>{const s=sectionSupportsKnob(e,"icon")?i?.icon:void 0;return{...t,layout:{...t.layout,...s&&{"icon-image":s.image,...void 0!==s.sizeFactor&&{"icon-size":getSectionIconSize(t.layout?.["icon-size"],s.sizeFactor)},...s.placement&&{"symbol-placement":"along"===s.placement?"line":"line-center"}},...!isSectionVisible(e,i)&&{visibility:"none"}}}},sectionLine=(e,t,i,s="light")=>{const o=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),{rampsBy:r}=sectionEntry(e);if(!r)return o;const a=t?.color??GENERATED_SECTION_PAINT[e].color;return{...o,paint:{...o.paint,"line-color":rampedColor(r,a,s)}}},SIGN_ICON_SIZE=/* @__PURE__ */zoomRamp(10,.5,16,.7),POSTED_SIGN_ICON_SIZE=/* @__PURE__ */zoomRamp(10,.45,16,.63),POSTED_SIGN_TEXT_SIZE=/* @__PURE__ */zoomRamp(10,8,16,11.5),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??12.5,layout:{...(i=signPlacement(t),"atChange"===i?{"symbol-placement":"point"}:{"symbol-placement":"line","symbol-spacing":260}),"icon-image":["get","signImageID"],"icon-size":POSTED_SIGN_ICON_SIZE,"icon-rotation-alignment":"viewport","text-field":["get","signLabel"],"text-font":["Noto-Bold"],"text-size":POSTED_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":instanceImageID(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}`,sectionLineLayerID=e=>sectionLayerID(e,"Line"),sectionSignLayerID=e=>sectionLayerID(e,"Sign"),START_INDEX="start",MIDDLE_INDEX="middle",FINISH_INDEX="finish",routeWidths=/* @__PURE__ */(()=>/* @__PURE__ */everyOf()(["s","m","l"]))(),routeKnobDefinitions=/* @__PURE__ */(()=>({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."},widthPreset:{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},opacity:{kind:"number",description:"Opacity of the route lines and their outlines, selected and deselected; sections keep their own.",range:OPACITY_RANGE,default:1},"highlight.outline.widthFactor":{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},"highlight.section.outline.color":{kind:"color",description:"Colour of the ring around the sections `setSectionFocus` marks. Unset: black on light styles, white on dark."},"highlight.section.outline.widthFactor":{kind:"factor",description:"Multiplier on the width of the ring around the focused sections, 2 to 4 pixels as the zoom grows.",range:SECTION_FOCUS_OUTLINE_WIDTH_FACTOR_RANGE,default:1},"waypoints.sizePreset":{kind:"enum",description:"Size preset of the waypoint pins and their stop marks: `s` is 0.75 × `m`, `l` 1.25 × `m`.",options:/* @__PURE__ */everyOf()(["s","m","l"]),default:"m"},"waypoints.sizeFactor":{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.stopNumbering":{kind:"enum",description:"How the stop pins are marked: `1, 2, 3…`, `A, B, C…`, or left empty.",options:/* @__PURE__ */everyOf()(["numbers","letters","none"]),default:"numbers"},"waypoints.highlight.sizeFactor":{kind:"factor",description:"Multiplier on the pin size of a hovered or clicked waypoint; `1` draws it as any other.",range:ROUTE_WAYPOINT_HIGHLIGHT_SIZE_FACTOR_RANGE,default:1.2},"waypoints.label.visible":{kind:"toggle",description:"Whether the waypoint labels show: the place name, and the stop duration under it.",default:!0},"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.label.size":{kind:"number",description:"Text size of the waypoint labels, in pixels. Unset: 14 to 16 as the zoom grows.",range:LABEL_SIZE_RANGE},"waypoints.label.haloWidth":{kind:"number",description:"Width of the halo around the waypoint labels, in pixels.",range:LABEL_HALO_WIDTH_RANGE,default:1.5},"waypoints.label.opacity":{kind:"number",description:"Opacity of the waypoint labels.",range:OPACITY_RANGE,default:1},"waypoints.label.font":{kind:"enums",description:"Font faces of the waypoint labels, in order: the first one available wins. Unset: `Noto-Bold` in the labels' typeface.",options:mapFonts},"waypoints.label.typeface":/* @__PURE__ */labelTypefaceKnob("waypoints.label","waypoint labels"),"waypoints.entryPoints":{kind:"enum",description:"Draw each waypoint at its place's main entry point, otherwise its first untyped one, as reverse geocoding returns them, otherwise 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`."},"summaryBubbles.visible":{kind:"toggle",description:"The bubbles giving each route's duration, distance and traffic delay.",default:!0},"summaryBubbles.routes":{kind:"enum",description:"Which routes get a bubble: `all`, the `selected` one alone, or the `alternatives` to it, for an app that tells the selected trip in a panel of its own.",options:/* @__PURE__ */everyOf()(["all","selected","alternatives"]),default:"all"},"summaryBubbles.fields":{kind:"enums",description:"What each bubble says, in order: the first field the route carries in bold, `durationDifference` against the selected route on the other routes, `trafficDelay` on its own line on a route with a delay. A bubble with nothing to say is not drawn.",options:/* @__PURE__ */everyOf()(["duration","distance","durationDifference","trafficDelay"]),default:SUMMARY_BUBBLE_DEFAULT_FIELDS},"summaryBubbles.minZoom":{kind:"number",description:"Lowest zoom the summary bubbles are drawn at. Unset: every zoom.",range:ZOOM_RANGE},"summaryBubbles.maxZoom":{kind:"number",description:"Zoom from which the summary bubbles stop being drawn. Unset: every zoom.",range:ZOOM_RANGE},"summaryBubbles.color":{kind:"color",description:"Colour of the selected route's bubble; the others take a darker shade, and the text whichever of black and white reads. Unset: the map's `colors.labelHalo` lightened, when a theme sets it; otherwise white, or dark grey on a dark style."},"summaryBubbles.label.color":{kind:"color",description:"Text colour on the selected route's bubble; the others keep their muted text. Unset: the map's `colors.label` when a theme sets it and the bubble has no `summaryBubbles.color`; otherwise black or white, whichever reads on the bubble."},"summaryBubbles.label.size":{kind:"number",description:"Text size of the summary bubbles, in pixels; the bubble grows with it.",range:LABEL_SIZE_RANGE,default:13},"summaryBubbles.label.opacity":{kind:"number",description:"Opacity of the summary bubble text; the bubble stays opaque.",range:OPACITY_RANGE,default:1},"summaryBubbles.label.typeface":/* @__PURE__ */labelTypefaceKnob("summaryBubbles.label","summary bubbles",!1),"countryCrossings.visible":{kind:"toggle",description:"The labels naming both countries at each border crossing; needs `country` sections.",default:!0},"countryCrossings.minZoom":{kind:"number",description:"Lowest zoom a border crossing label is drawn at.",range:ZOOM_RANGE,default:4},"countryCrossings.color":{kind:"color",description:"Colour of the border crossing bubbles. Unset: the map's `colors.labelHalo` lightened, when a theme sets it; otherwise white, or dark grey on a dark style."},"countryCrossings.label.color":{kind:"color",description:"Label colour of the border crossings. Unset: the map's `colors.label` when a theme sets it and the bubble has no `countryCrossings.color`; otherwise black or white, whichever reads on the bubble."}}))(),HALO_FLOOR=/* @__PURE__ */(()=>`A halo stays at least ${SECTION_HALO_MIN_OUTLINE_RATIO}× the route's outline.`)(),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}),widthPreset:e=>({kind:"enum",description:`Line width preset of the \`${e}\` sections; unset follows the route's. ${HALO_FLOOR}`,options:routeWidths}),widthFactor:e=>({kind:"factor",description:`Multiplier over the \`${e}\` sections' width preset; unset follows the route's. ${HALO_FLOOR}`,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:linePatterns,...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,step:.5},default:12.5}),"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"])}),"kerb.visible":e=>({kind:"toggle",description:`Kerb stripes over the tight \`${e}\` sections, 60 m of radius or less, from zoom 12, alternating \`kerb.color\` with \`color\`; off draws one plain line.`,default:!0}),"kerb.color":e=>({kind:"color",description:`Colour of the \`${e}\` kerb stripes. Unset: \`color\` faded toward the map, white on light styles and near-black on dark.`})},waypointPinNames={start:"origin pin",middle:"stop pins",finish:"destination pin"},waypointPinStyleKnobDefinitions={fillColor:e=>({kind:"color",description:`Fill colour of the ${e}, over the shared pin style.`}),outlineColor:e=>({kind:"color",description:`Outline colour of the ${e}, over the shared pin style.`}),outlineOpacity:e=>({kind:"number",description:`Outline opacity of the ${e}, over the shared pin style.`,range:OPACITY_RANGE})},sectionKnobId=(e,t)=>`sections.${e}.${t}`,buildCatalogue=()=>{const e=Object.keys(sectionKnobDefinitions),t=t=>e.filter(e=>e===t||e.startsWith(`${t}.`));return[...withIds(routeKnobDefinitions).flatMap(e=>"waypoints.icon.style.outlineOpacity"===e.id?[e,...[START_INDEX,MIDDLE_INDEX,FINISH_INDEX].flatMap(e=>Object.keys(waypointPinStyleKnobDefinitions).map(t=>({id:`waypoints.icon.${e}.style.${t}`,...waypointPinStyleKnobDefinitions[t](waypointPinNames[e])})))]:[e]),...drawnSectionTypes.flatMap(e=>sectionEntry(e).knobs.flatMap(t).map(t=>({id:sectionKnobId(e,t),...sectionKnobDefinitions[t](e)})))]},routingKnobCatalogue=/* @__PURE__ */buildCatalogue(),routingKnobIds=/* @__PURE__ */routingKnobCatalogue.map(({id:e})=>e),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"}}),instructionArrow=(e,t)=>({...commonProps,type:"symbol",layout:{"icon-allow-overlap":!0,"icon-image":instanceImageID("instruction-arrow",t),"icon-rotation-alignment":"map","icon-rotate":["get","lastPointBearingDegrees"],"icon-size":getInstructionArrowSize(e)}}),routeFerriesLine=/* @__PURE__ */selectedRouteLine({"line-color":"#6dc4ed"}),ferryTerminalSymbol=/* @__PURE__ */selectedRoutePOISymbol("poi-ferry_terminal",6),routeFerriesSymbol=/* @__PURE__ */(()=>({...ferryTerminalSymbol,maxzoom:16.5,layout:{...ferryTerminalSymbol.layout,"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)}}),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}},routeSectionFocusOutline=(e,t,i,s)=>({filter:e,type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":i,"line-width":getSectionFocusOutlineWidth(s),"line-gap-width":t}}),routeTollRoadsOutline=/* @__PURE__ */selectedRouteLine({"line-color":"#BEBFFA"},{"line-cap":"round"}),routeTollRoadsSymbol=/* @__PURE__ */selectedRoutePOISymbol("poi-toll_plaza",4),trafficDelayColorKnobIds=/* @__PURE__ */(()=>[incidentColorKnobIds.minor,incidentColorKnobIds.moderate,incidentColorKnobIds.major])(),trafficDelayColors=(e={})=>({minor:e[incidentColorKnobIds.minor]??"#FFC105",moderate:e[incidentColorKnobIds.moderate]??"#FB2D09",major:e[incidentColorKnobIds.major]??"#AD0000"}),magnitudeOfDelayTextColor=/* @__PURE__ */matchMagnitudeOfDelay({minor:"#f58240",moderate:"#FB2D09",major:"#AD0000",indefinite:"#666666",fallback:"#000000"}),routeIncidentsDashedLine={type:"line",filter:severityDashedFilter,layout:{"line-join":"round"},paint:{"line-color":severityLineDashColor,"line-dasharray":[1.5,1]}},routeIncidentsSymbol=(e,t,i={})=>({filter:["all",["has",e],SELECTED_ROUTE_FILTER],type:"symbol",minzoom:6,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-ignore-placement":!0,"icon-image":["get",e],...t},paint:i}),routeIncidentsJamSymbol=/* @__PURE__ */routeIncidentsSymbol("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},{"text-color":magnitudeOfDelayTextColor,"text-halo-color":"#FFFFFF","text-halo-width":1}),routeIncidentsCauseSymbol=/* @__PURE__ */routeIncidentsSymbol("causeIconID",{"icon-anchor":"bottom-right"}),routeTunnelsLine=/* @__PURE__ */selectedRouteLine({"line-color":"#000000","line-opacity":.3}),routeVehicleRestrictedBackgroundLine=/* @__PURE__ */selectedRouteLine({"line-color":"#105287"}),routeVehicleRestrictedDottedLine=/* @__PURE__ */selectedRouteLine({"line-color":"#36A8F0"},{"line-cap":"round"}),stopDurationLabelSection=[["coalesce",["get","stopDuration"],""],{"text-color":"#727C85","text-font":["literal",["Noto-Regular"]]}],hasStopDuration=["has","stopDuration"],waypointLabelTextField=/* @__PURE__ */(()=>["format",["coalesce",["get","title"],""],{},["case",["all",["has","title"],hasStopDuration],"\n",""],{},...stopDurationLabelSection])(),waypointSymbols=e=>{const t=clampFactor(e.waypoints?.highlight?.sizeFactor,ROUTE_WAYPOINT_HIGHLIGHT_SIZE_FACTOR_RANGE,1.2),i=buildIconOffsetExpression(buildCustomIconOffsets(e.waypoints?.icon?.customIcons));return{type:"symbol",paint:{...pinIconBasePaint,"text-color":"#ffffff","text-translate":PIN_TRANSLATE,"text-translate-anchor":"viewport"},layout:{...pinIconBaseLayout,"icon-size":scaledWhen(hasActiveEventState,(s=e.waypoints?.sizePreset,o=e.waypoints?.sizeFactor,scaleRamp(PIN_ICON_SIZE,waypointScale(s,o))),t),...i&&{"icon-offset":i},"text-field":["get","stopDisplayLabel"],"text-font":["Noto-Bold"],"text-size":scaledWhen(hasActiveEventState,getWaypointIndexTextSize(e.waypoints?.sizePreset,e.waypoints?.sizeFactor),t),"text-offset":STOP_MARK_TEXT_OFFSET,"text-allow-overlap":!0,"symbol-sort-key":["abs",["-",["get","index"],1e3]]}};var s,o},waypointLabels=(e,t,i)=>{const{textColor:s,haloColor:o}=themeAdaptiveLabelColors(e),r=labelTypefaceOf(t,i);return{type:"symbol",paint:{...pinTextBasePaint,"text-color":s,"text-halo-width":1.5,"text-halo-color":o,...labelPaintProperties(t)},layout:{...pinTextBaseLayout,"text-font":inTypeface(pinTextBaseLayout?.["text-font"],r),"text-field":!1===t?.visible?"":titleTextField(t?.title,inTypeface(waypointLabelTextField,r)),"text-anchor":"top","text-offset":[0,.4],...labelLayoutProperties(t)}}},prefixBeforeID=(e,t)=>e&&t?e.startsWith(`${t}-`)?e:e.startsWith("route")||e.startsWith("waypoint")?prefixLayerID(e,t):e:e,prefixLayerBeforeID=(e,t)=>e.beforeID?{...e,beforeID:prefixBeforeID(e.beforeID,t)}:e,prefixBeforeIDs=(e,t)=>e&&t?Object.fromEntries(Object.entries(e).map(([e,i])=>[e,prefixLayerBeforeID(i,t)])):e,buildRoutingLayers=(e={},t,i,s="light",o=trafficDelayColors(),r,a)=>{const n=(t,i)=>partBeforeLayerIDOf(e.beforeLayerConfig,t,i),l=n("mainLines",mapStyleLayerIDs.lowestLabel),c=n("instructionLines",mapStyleLayerIDs.lowestLabel),d=n("icons",void 0),u=(e,i)=>mergeLayer(e,i&&prefixLayerBeforeID(i,t)),h=e.layers,p=h?.sections,y=e.color,f=y?darkerShadeOf(y):void 0,m={widthPreset:e.widthPreset,widthFactor:e.widthFactor},g=clampFactor(e.highlight?.outline?.widthFactor,ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE,1.2),S=e.highlight?.section?.outline,b=S?.color??themeContrastColor(s),L=e.sections,I=e.opacity,E=e=>void 0===I?e:{...e,paint:{...e.paint,"line-opacity":I}},_=u({...withMapTypeface(waypointSymbols(e),r),beforeID:prefixBeforeID("routeSummaryBubbleSymbol",t)},h?.waypoints?.routeWaypointSymbol),T=(e=>{const t="string"==typeof e?e:"center",i=e=>"center"===t||e?10:2;return[i(t.startsWith("bottom")),i(t.endsWith("left")),i(t.startsWith("top")),i(t.endsWith("right"))]})(_.layout?.["icon-anchor"]),A=e=>({...e,layout:{...e.layout,"icon-padding":T}}),C=(e,i,s)=>({...withSectionLineKnobs(e,i,L?.[e],m,s?.role),beforeID:prefixBeforeID(s?.beforeID??sectionStyleAnchor(e,L?.[e]),t)}),v=(e,i,s)=>({...withSectionSymbolKnobs(e,A(withMapTypeface(i,r)),L?.[e]),beforeID:prefixBeforeID(s,t)}),R=Object.fromEntries(generatedSectionTypes.map(e=>{const i=L?.[e],o=sectionLineLayerID(e),a=(e=>sectionLayerID(e,"Symbol"))(e),n=p?.[e];if(postsSign(e)){const s=sectionSignLayerID(e);return[e,{[s]:u(A(withMapTypeface(sectionSign(e,i),r)),n?.[s]),...prefixBeforeIDs(n?.additional,t)}]}const l=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),c=((e,t,i,s="light")=>isKerbStriped(e,t)?withSectionLineKnobs(e,{filter:["all",SELECTED_ROUTE_FILTER,["<=",["get","radiusInMeters"],60]],type:"line",minzoom:12,layout:{"line-cap":"butt","line-join":"round"},paint:{"line-color":t?.kerb?.color??kerbDefaultColor(t?.color??GENERATED_SECTION_PAINT[e].color,s),"line-opacity":GENERATED_SECTION_PAINT[e].opacity,"line-dasharray":KERB_DASH_ARRAY}},t,i,"kerb"):void 0)(e,i,m,s),d=(e=>sectionLayerID(e,"Kerb"))(e),h=((e,t)=>{const i=sectionEntry(e).drawsUnder,s=sectionDrawStyle(e,t?.[e]);return i&&s===sectionDrawStyle(i,t?.[i])?sectionLineLayerID(i):sectionStyleAnchor(e,t?.[e])})(e,L);return[e,{[o]:u({...sectionLine(e,i,m,s),beforeID:prefixBeforeID(c?d:h,t)},n?.[o]),...c&&{[d]:u({...c,beforeID:prefixBeforeID(h,t)},n?.[d])},...l&&{[a]:u({...l,beforeID:prefixBeforeID("routeTunnelSymbol",t)},n?.[a])},...prefixBeforeIDs(n?.additional,t)}]}));return{mainLines:{routeLineArrows:u({...routeLineArrows,beforeID:l},h?.mainLines?.routeLineArrows),routeLine:u({...E(routeMainLine(m,y)),beforeID:prefixBeforeID("halo"===sectionDrawStyle("traffic",L?.traffic)?"routeLineArrows":"routeIncidentBackgroundLine",t)},h?.mainLines?.routeLine),routeOutline:u({...E(routeOutline(m,f,g)),beforeID:prefixBeforeID("routeLine",t)},h?.mainLines?.routeOutline),routeDeselectedLine:u({...E((w=m,{...routeLineBaseTemplate,filter:DESELECTED_ROUTE_FILTER,paint:{"line-color":"#ABAFB3","line-width":getLineForegroundWidth(w)}})),beforeID:prefixBeforeID("routeOutline",t)},h?.mainLines?.routeDeselectedLine),routeDeselectedOutline:u({...E(routeDeselectedOutline(m,g)),beforeID:prefixBeforeID("routeDeselectedLine",t)},h?.mainLines?.routeDeselectedOutline),...prefixBeforeIDs(h?.mainLines?.additional,t)},waypoints:{routeWaypointSymbol:_,routeWaypointLabel:u({...waypointLabels(s,e.waypoints?.label,r),beforeID:prefixBeforeID("routeWaypointSymbol",t)},h?.waypoints?.routeWaypointLabel),...prefixBeforeIDs(h?.waypoints?.additional,t)},sections:{...R,traffic:{routeIncidentJamSymbol:u(v("traffic",routeIncidentsJamSymbol,"routeCountryCrossing"),p?.traffic?.routeIncidentJamSymbol),routeIncidentCauseSymbol:u(v("traffic",routeIncidentsCauseSymbol,"routeCountryCrossing"),p?.traffic?.routeIncidentCauseSymbol),routeIncidentBackgroundLine:u(C("traffic",(O=o,{type:"line",layout:{"line-cap":"round"},paint:{"line-color":/* @__PURE__ */matchMagnitudeOfDelay({...O,fallback:"#C7D2D8"})}}),{beforeID:"routeIncidentDashedLine"}),p?.traffic?.routeIncidentBackgroundLine),routeIncidentDashedLine:u(C("traffic",routeIncidentsDashedLine),p?.traffic?.routeIncidentDashedLine),...prefixBeforeIDs(p?.traffic?.additional,t)},ferry:{routeFerryLine:u(C("ferry",routeFerriesLine),p?.ferry?.routeFerryLine),routeFerrySymbol:u(v("ferry",routeFerriesSymbol,"routeIncidentJamSymbol"),p?.ferry?.routeFerrySymbol),...prefixBeforeIDs(p?.ferry?.additional,t)},tollRoad:{routeTollRoadOutline:u(C("tollRoad",routeTollRoadsOutline),p?.tollRoad?.routeTollRoadOutline),routeTollRoadSymbol:u(v("tollRoad",routeTollRoadsSymbol,"routeCountryCrossing"),p?.tollRoad?.routeTollRoadSymbol),...prefixBeforeIDs(p?.tollRoad?.additional,t)},tunnel:{routeTunnelLine:u(C("tunnel",routeTunnelsLine),p?.tunnel?.routeTunnelLine),routeTunnelSymbol:u(v("tunnel",sectionStartSign("tunnel",i),"routeFerrySymbol"),p?.tunnel?.routeTunnelSymbol),...prefixBeforeIDs(p?.tunnel?.additional,t)},vehicleRestricted:{routeVehicleRestrictedBackgroundLine:u(C("vehicleRestricted",routeVehicleRestrictedBackgroundLine,{beforeID:"routeVehicleRestrictedForegroundLine",role:"outline"}),p?.vehicleRestricted?.routeVehicleRestrictedBackgroundLine),routeVehicleRestrictedForegroundLine:u(C("vehicleRestricted",routeVehicleRestrictedDottedLine),p?.vehicleRestricted?.routeVehicleRestrictedForegroundLine),routeVehicleRestrictedSymbol:u(v("vehicleRestricted",sectionStartSign("vehicleRestricted",i),"routeIncidentJamSymbol"),p?.vehicleRestricted?.routeVehicleRestrictedSymbol),...prefixBeforeIDs(p?.vehicleRestricted?.additional,t)}},instructionLines:{routeInstructionLine:u({...instructionLine(m),beforeID:c},h?.instructionLines?.routeInstructionLine),routeInstructionOutline:u({...instructionOutline(m),beforeID:prefixBeforeID("routeInstructionLine",t)},h?.instructionLines?.routeInstructionOutline),...prefixBeforeIDs(h?.instructionLines?.additional,t)},instructionArrows:{routeInstructionArrowSymbol:u({...instructionArrow(m,i),beforeID:prefixBeforeID("routeInstructionLine",t)},h?.instructionArrows?.routeInstructionArrowSymbol),...prefixBeforeIDs(h?.instructionArrows?.additional,t)},summaryBubbles:{routeSummaryBubbleSymbol:u({...summaryBubbleSymbol(i,e.summaryBubbles,resolveSummaryBubbleColors(e.summaryBubbles,s,a),r),...d&&{beforeID:d}},h?.summaryBubbles?.routeSummaryBubbleSymbol),...prefixBeforeIDs(h?.summaryBubbles?.additional,t)},countryCrossings:{[COUNTRY_CROSSING_LAYER_ID]:u({...withMapTypeface(countryCrossingSymbol(i,e.countryCrossings,resolveCountryCrossingColors(e.countryCrossings,s,a)),r),beforeID:prefixBeforeID("routeWaypointSymbol",t)},h?.countryCrossings?.routeCountryCrossing),...prefixBeforeIDs(h?.countryCrossings?.additional,t)},sectionFocus:{routeSectionFocusOutline:u({...routeSectionFocusOutline(SELECTED_ROUTE_FILTER,getSectionFocusGapWidth(m,g,drawnSectionLineWidths(L,m)),b,S?.widthFactor),beforeID:prefixBeforeID("routeLineArrows",t)},h?.sectionFocus?.routeSectionFocusOutline),routeDeselectedSectionFocusOutline:u({...routeSectionFocusOutline(DESELECTED_ROUTE_FILTER,getSectionFocusGapWidth(m,g),b,S?.widthFactor),beforeID:prefixBeforeID("routeOutline",t)},h?.sectionFocus?.routeDeselectedSectionFocusOutline),...prefixBeforeIDs(h?.sectionFocus?.additional,t)}};var O,w},defaultRoutingLayers=/* @__PURE__ */buildRoutingLayers(),toCrossingFeature=(e,t,i,s,o)=>{const r=generateId();return{type:"Feature",id:r,geometry:toPointGeometry(i[t.startPointIndex]),properties:{id:r,fromCountryCode:e.countryCodeISO2,toCountryCode:t.countryCodeISO2,label:`${e.countryCodeISO2} → ${t.countryCodeISO2}`,fromSectionStartPointIndex:e.startPointIndex,toSectionStartPointIndex:t.startPointIndex,routeState:s.routeState,routeIndex:o}}},hasJam=e=>e.categories.includes("jam"),buildWaypointTitle=e=>{const t=e?.properties;return t?.poi?.name??t?.address?.freeformAddress??void 0},WAYPOINT_IMAGE_IDS={start:"waypointStart",middle:"waypointStop",finish:"waypointFinish"},getImageIDForWaypoint=(e,t)=>instanceImageID(WAYPOINT_IMAGE_IDS[e],t),asWaypoint=e=>{return Array.isArray(e)?{type:"Feature",geometry:toPointGeometry(e),properties:{}}:"Point"===e.type?{type:"Feature",geometry:t=e,properties:{},...t.bbox&&{bbox:t.bbox}}:{...e,properties:e.properties??{}};var t},toDisplayWaypoints=(e,t,i,s)=>({type:"FeatureCollection",features:e.flatMap((o,r)=>{if(!o)return[];const a=asWaypoint(o),n=((e,t)=>0===e?START_INDEX:e<t-1?MIDDLE_INDEX:FINISH_INDEX)(r,e.length),l=a.id??generateId(),c=formatDuration(a.properties.pauseDurationSeconds,s),d={...a,..."main-when-available"===t?.entryPoints&&{geometry:{type:"Point",coordinates:getPosition(a,{useEntryPoint:"main-when-available"})}},id:l,properties:{...a.properties,id:l,index:r,indexType:n,...c&&{stopDuration:c},iconID:getImageIDForWaypoint(n,i),..."middle"===n&&{stopDisplayIndex:r}}},u=featureTitle(d,t?.label?.title,buildWaypointTitle);u&&(d.properties.title=u);const h=((e,t)=>{if("imageID"===t?.to)return t.fn(e);if("poiCategory"!==t?.to)return;const i=t.fn(e);return i&&toPinImageID(poiCategoriesToID[i])})(d,t?.icon?.mapping);if(h)d.properties.iconID=h;else if("middle"===n&&!t?.icon?.middle?.image?.image){const e=((e,t="numbers")=>{if("none"!==t)return"letters"===t?(e=>{let t="";for(let i=e;i>0;i=Math.floor((i-1)/26))t=String.fromCodePoint(65+(i-1)%26)+t;return t})(e):String(e)})(r,t?.stopNumbering);e&&(d.properties.stopDisplayLabel=e)}return[d]})}),drawableInstructions=e=>e.features.flatMap((e,t)=>e.properties.guidance?.instructions?.filter(e=>(e.routePath?.length??0)>1).map(i=>({instruction:i,routeIndex:t,routeState:e.properties.routeState}))||[]),toRouteSection=(e,t,i,s)=>{const o=i.id??generateId();return{type:"Feature",id:o,geometry:{type:"LineString",coordinates:e.geometry.coordinates.slice(i.startPointIndex,i.endPointIndex+1)},properties:{...s?s(i,e.properties):i,routeState:e.properties.routeState,routeIndex:t,id:o}}},toDisplayRouteSections=(e,t,i)=>({type:"FeatureCollection",features:e.features.flatMap((e,s)=>(e.properties.sections[t]??[]).map(t=>toRouteSection(e,s,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 s=e.id??generateId();return{...e,id:s,properties:{...e.properties,id:s,routeState:i===t?"selected":"deselected"}}})}},BUBBLE_FRACTIONS=[.5,.25,.75],wholeMinutesOf=e=>Math.round(e/60),toDisplayRouteSummaries=(e,t,i,s)=>{const o=e.features.filter(e=>e.geometry.coordinates.length),r=o.find(e=>"selected"===e.properties.routeState),a=(s&&((e,t)=>{const i=new Map(t.features.map(({id:e,geometry:t})=>[e,t.coordinates])),s=e.map(e=>void 0===e.id?void 0:i.get(e.id));return s.every(e=>void 0!==e)?s:void 0})(o,s))??(e=>{const t=(e=>{if(e.length<2)return e.map(()=>[]);const t=e.map(e=>e.properties.sections.distinct);return t.every(e=>void 0!==e)?t:getDistinctSections(e)})(e),i=[];return e.map(({geometry:{coordinates:e}},s)=>{const o=metersAlongLine(e),r=t[s].reduce((e,t)=>{const i=t.lengthInMeters;return null==i||Number.isNaN(i)?e:!e||i>e.lengthInMeters?t:e},void 0),a=r&&r.lengthInMeters>.05*(o.at(-1)??0)?r:{startPointIndex:0,endPointIndex:e.length-1},n=o[a.startPointIndex],l=o[a.endPointIndex]-n,c=e=>Math.min(...i.map(t=>distance(e,t))),[d,...u]=BUBBLE_FRACTIONS.map(t=>((e,t,{startPointIndex:i,endPointIndex:s},o)=>{if(s<=i)return e[i];const{pathIndex:r,share:a}=segmentAtMeters(t,o,i,s);return positionBetween(e[r],e[r+1],a)})(e,o,a,n+l*t)),h=u.reduce((e,t)=>c(t)>c(e)?t:e,d);return i.push(h),h})})(o);return{type:"FeatureCollection",features:o.map((s,o)=>{const n=s.properties.summary,l=formatDuration(n.trafficDelayInSeconds,t?.time),c=((e,t,i)=>{if(!t||"selected"===e.properties.routeState)return;const s=wholeMinutesOf(e.properties.summary.travelTimeInSeconds)-wholeMinutesOf(t.properties.summary.travelTimeInSeconds),o=formatDuration(60*Math.abs(s),i?.time);return o&&`${s>0?"+":"-"}${o}`})(s,r,t),d=(e=>{const t=e.properties.sections.traffic??[];return["major","moderate","minor"].find(e=>t.some(t=>t.magnitudeOfDelay===e))})(s),u=s.id??generateId(),h={type:"Feature",id:u,geometry:toPointGeometry(a[o]),properties:{id:u,routeIndex:e.features.indexOf(s),routeState:s.properties.routeState,formattedDistance:formatDistance(n.lengthInMeters,t?.distance),...d&&{magnitudeOfDelay:d},...l&&{formattedTraffic:l},...c&&{formattedDurationDifference:c},formattedDuration:formatDuration(n.travelTimeInSeconds,t?.time)}},p=featureTitle(h,i,()=>{});return p&&(h.properties.title=p),h})}},SIGN_BY_COUNTRY={GBR:{unit:"mph"},JEY:{unit:"mph"},GGY:{unit:"mph"},IMN:{unit:"mph"},AIA:{unit:"mph"},CYM:{unit:"mph"},FLK:{unit:"mph"},MSR:{unit:"mph"},SHN:{unit:"mph"},TCA:{unit:"mph"},VGB:{unit:"mph"},ATG:{unit:"mph"},BHS:{unit:"mph"},BLZ:{unit:"mph"},DMA:{unit:"mph"},GRD:{unit:"mph"},KNA:{unit:"mph"},LCA:{unit:"mph"},VCT:{unit:"mph"},WSM:{unit:"mph"},LBR:{unit:"mph"},MMR:{unit:"mph"},USA:{face:"plaque",unit:"mph"},PRI:{face:"plaque",unit:"mph"},GUM:{face:"plaque",unit:"mph"},VIR:{face:"plaque",unit:"mph"},ASM:{face:"plaque",unit:"mph"},MNP:{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,featureIdOf=e=>e.id,showOrClearCountryCrossings=(e,t,i)=>{!1!==i?.countryCrossings?.visible?e.show((e=>({type:"FeatureCollection",features:e.features.flatMap((e,t)=>((e,t)=>{const i=e.properties.sections.country;if(!i?.length)return[];const s=[...i].sort((e,t)=>e.startPointIndex-t.startPointIndex),o=e.geometry.coordinates;return s.slice(1).flatMap((i,r)=>o[i.startPointIndex]?[toCrossingFeature(s[r],i,o,e.properties,t)]:[])})(e,t))}))(t)):e.clear()},RoutingModule=class RoutingModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new RoutingModule(e,t)}constructor(e,t){super(e,t),this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&(this.config=this._applyConfig(this.config))}),onStyleKnobsApplied(e,trafficDelayColorKnobIds,()=>this.repaintTrafficSections()),onStyleKnobsApplied(e,summaryBubbleColorKnobIds,()=>{this.config=this._applyConfig(this.config)}),onMapTypefaceChange(e,()=>{this.config=this._applyConfig(this.config)})}repaintTrafficSections(){const{incidents:e}=this.buildLayersSpecs(this.config);isEqual(e,this.layersSpecs.incidents)||(this.replaceSourceLayers(e,this.layersSpecs.incidents,this.sourcesWithLayers.incidents),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),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),sectionFocus:mapLayerSpecs(e.sectionFocus,t)}))(buildRoutingLayers({...e,color:this.routeColorOf(e)},this.layerIDPrefix,this.instanceIndex,this.tomtomMap.styleLightDarkTheme,trafficDelayColors(this.tomtomMap._styleKnobSettings),mapTypefaceOf(this.tomtomMap),summaryBubbleMapColors(this.tomtomMap._styleKnobSettings)),this.layerIDPrefix)}createSourcesWithLayers(e){const t=t=>new GeoJSONSourceWithLayers(this.mapLibreMap,`${this.layerIDPrefix}-${t}`,e[t],!1);return{...Object.fromEntries(generatedSectionTypes.map(e=>{const i=sectionSourceKey(e);return[i,t(i)]})),mainLines:t("mainLines"),waypoints:t("waypoints"),incidents:t("incidents"),ferries:t("ferries"),tollRoads:t("tollRoads"),tunnels:t("tunnels"),vehicleRestricted:t("vehicleRestricted"),instructionLines:t("instructionLines"),instructionArrows:t("instructionArrows"),summaryBubbles:t("summaryBubbles"),countryCrossings:t("countryCrossings"),sectionFocus:t("sectionFocus")}}_initSourcesWithLayers(e,t){t||(this.layerIDPrefix=suffixNumber("routes",this.instanceIndex)),this.layersSpecs=this.buildLayersSpecs(e);const i=this.createSourcesWithLayers(this.layersSpecs);addLayers(Object.values(i).flatMap(e=>e._layerSpecs),this.mapLibreMap);const s={pixelRatio:2},o=instanceImageID("instruction-arrow",this.instanceIndex),r=instanceImageID("traffic-moderate",this.instanceIndex),a=instanceImageID("traffic-minor",this.instanceIndex);this.addImageIfNotExisting(o,svgMarkupToImg('<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'),s);for(const[n,l]of Object.entries(SPEED_LIMIT_IMAGE_ID_BY_FACE))this.addImageIfNotExisting(instanceImageID(l,this.instanceIndex),speedLimitSignImg(n),s);for(const[n,l]of Object.entries(SECTION_START_SIGN_IMAGE_IDS))this.addImageIfNotExisting(instanceImageID(l,this.instanceIndex),sectionStartSignImg(n),s);return this.appliedCrossingColors=void 0,this.appliedSummaryBubbleColors=void 0,this.addImageIfNotExisting(r,trafficImg("#FB2D09"),s),this.addImageIfNotExisting(a,trafficImg("#f58240"),s),i}_applyConfig(e){const t=routeDisplayUnits(e),i=!isEqual(this.appliedDisplayUnits,t);if(this.appliedDisplayUnits=t,this.addConfiguredImages(e),this.applySummaryBubbleColors(e),declareFontFaces(this.tomtomMap,this,customFacesOf([e?.waypoints?.label,e?.summaryBubbles?.label])),!this._initializing){const t=this.buildLayersSpecs(e);Object.keys(t).forEach(e=>{const i=e;this.replaceSourceLayers(t[i],this.layersSpecs[i],this.sourcesWithLayers[i])});const s=Object.values(this.sourcesWithLayers),o=e=>Object.values(e).flatMap(e=>e.map(e=>e.beforeID));addLayers(s.flatMap(e=>e._layerSpecs),this.mapLibreMap,!isEqual(o(this.layersSpecs),o(t))),this.reshowSpeedLimitSigns(e,i);const{incidents:r,mainLines:a}=this.sourcesWithLayers;i&&r.shownFeatures.features.length&&this.reshowKeepingEventStates(r,this.trafficSectionsOf(a.shownFeatures,e)),this.applySignPriority(e),this.layersSpecs=t}return this.reshowWaypoints(e,i),this.reshowSummaryBubbles(e,i),this.applyCountryCrossingConfig(e),this.applyVisibility(e),e}addConfiguredImages(e){const t=e?.waypoints?.icon,i={fillColor:this.routeColorOf(e),...t?.style},s=e=>paintPin(this.mapLibreMap,getImageIDForWaypoint(e,this.instanceIndex),t?.[e],i,t=>((e,t)=>svgToImg(()=>{const i=pinSvg(t),s=waypointGlyphs[e];return s&&i.appendChild(parseSvg(s)),i}))(e,t),this.paintedWaypointPins?.[e]);this.paintedWaypointPins={start:s(START_INDEX),middle:s(MIDDLE_INDEX),finish:s(FINISH_INDEX)},((e,t)=>{for(const[i,{image:s,pixelRatio:o}]of Object.entries(customImagesByID(t)))addOrUpdateImage("if-not-in-sprite",i,s,e,{pixelRatio:o})})(this.mapLibreMap,t?.customIcons)}reshowWaypoints(e,t){this.shownWaypoints&&!this._initializing&&(!t&&isEqual(this.config?.waypoints,e?.waypoints)||this.reshowKeepingEventStates(this.sourcesWithLayers.waypoints,this.displayWaypointsOf(this.shownWaypoints,e)))}displayWaypointsOf(e,t){return toDisplayWaypoints(e,t?.waypoints,this.instanceIndex,routeDisplayUnits(t).time)}speedLimitSectionsOf(e,t){return toDisplayRouteSections(e,"speedLimit",(i=this.instanceIndex,s={unit:t?.sections?.speedLimit?.sign?.unit,displayUnits:routeDisplayUnits(t)},(e,t)=>{const o=(r=e.startPointIndex,a=t?.sections.country,a?.find(e=>r>=e.startPointIndex&&r<e.endPointIndex)?.countryCodeISO3);var r,a;const n=o?SIGN_BY_COUNTRY[o]??{}:SIGN_BY_DISPLAY_UNITS[s?.displayUnits?.distance?.type??"metric"],l=n.face??"whiteDisc",c=s?.unit??n.unit??"km/h";return{...e,signImageID:instanceImageID(SPEED_LIMIT_IMAGE_ID_BY_FACE[l],i),signLabel:String(postedSpeedLimit(e.maxSpeedLimitInKmh,c)),signFace:l,signNumeralsColor:n.numerals??"#1A2024"}}));var i,s}trafficSectionsOf(e,t){return toDisplayRouteSections(e,"traffic",(i=routeDisplayUnits(t).time,e=>{const t=((e,t)=>hasJam(e)?formatDuration(e.delayInSeconds,t):void 0)(e,i),s=((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),o=(e=>e.categories.filter(e=>"jam"!==e).map(incidentIconID).find(e=>null!==e)??null)(e);return{...e,...s&&{jamIconID:s},...o&&{causeIconID:o},...t&&{title:t}}}));var i}displaySummariesOf(e,t,i){const{summaryBubbles:s}=this.sourcesWithLayers,o=toDisplayRouteSummaries(e,routeDisplayUnits(t),t?.summaryBubbles?.label?.title,i?s.shownFeatures:void 0);return i?withShownEventStates(s.shownFeatures,o,featureIdOf):o}reshowSummaryBubbles(e,t){const i=this.sourcesWithLayers.summaryBubbles,s=!1!==e?.summaryBubbles?.visible,o=!isEqual(this.config?.summaryBubbles?.visible,e?.summaryBubbles?.visible);if(!s)return void(o&&i.clear());const r=this.config?.summaryBubbles?.label?.title!==e?.summaryBubbles?.label?.title,a=this.sourcesWithLayers.mainLines.shownFeatures.features.length>0,n=i.shownFeatures.features.length>0;(o&&a||(t||r)&&n)&&i.show(this.displaySummariesOf(this.sourcesWithLayers.mainLines.shownFeatures,e,!0))}applySummaryBubbleColors(e){const t=resolveSummaryBubbleColors(e?.summaryBubbles,this.tomtomMap.styleLightDarkTheme,summaryBubbleMapColors(this.tomtomMap._styleKnobSettings));isEqual(this.appliedSummaryBubbleColors,t)||(this.appliedSummaryBubbleColors=t,this.paintImage("selected-route-summary-popup",summaryMapBubbleImg(t.selectedFill),summaryBubbleImageOptions),this.paintImage("deselected-route-summary-popup",summaryMapBubbleImg(t.deselectedFill),summaryBubbleImageOptions),this.paintImage("traffic-major",trafficImg(t.majorDelay),{pixelRatio:2}),this.paintImage("traffic-clear",trafficImg(t.unknownDelay),{pixelRatio:2}))}crossingColors(e){return resolveCountryCrossingColors(e?.countryCrossings,this.tomtomMap.styleLightDarkTheme,summaryBubbleMapColors(this.tomtomMap._styleKnobSettings))}applyCountryCrossingConfig(e){if(!1!==e?.countryCrossings?.visible!=(!1!==this.config?.countryCrossings?.visible)){const{countryCrossings:t,mainLines:i}=this.sourcesWithLayers;showOrClearCountryCrossings(t,i.shownFeatures,e)}const t=this.crossingColors(e);if(isEqual(this.appliedCrossingColors,t))return;this.appliedCrossingColors=t,this.paintImage("route-country-crossing-bubble",summaryMapBubbleImg(t.selectedFill),summaryBubbleImageOptions);const i=prefixLayerID("routeCountryCrossing",this.layerIDPrefix);this.mapLibreMap.getLayer(i)&&this.mapLibreMap.setPaintProperty(i,"text-color",t.text,{validate:!1})}reshowSpeedLimitSigns(e,t){if(isEqual(this.config?.sections?.speedLimit?.sign?.unit,e?.sections?.speedLimit?.sign?.unit)&&!t)return;const{speedLimitSections:i,mainLines:s}=this.sourcesWithLayers;i.shownFeatures.features.length&&this.reshowKeepingEventStates(i,this.speedLimitSectionsOf(s.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 s=e?.sections?.[t];moveLayerBefore(this.mapLibreMap,i,this.signAnchorLayerID(i,s))}}signAnchorLayerID(e,t){const i=(e=>e?.sign?.priority??("atChange"===signPlacement(e)?"belowRouteIcons":"belowMapLabels"))(t);if("aboveRouteIcons"===i)return;if("belowMapLabels"===i)return mapStyleLayerIDs.lowestLabel;const s=new Set(["routeLineArrows","routeInstructionArrowSymbol"].map(e=>prefixLayerID(e,this.layerIDPrefix)));return this.mapLibreMap.getStyle().layers.find(t=>"symbol"===t.type&&t.id!==e&&!s.has(t.id)&&(!this.layerIDPrefix||t.id.startsWith(`${this.layerIDPrefix}-`)))?.id}discardShownData(){this.shownWaypoints=void 0}restoreDataAndConfigImpl(){const e=shownFeaturesOf(this.sourcesWithLayers),t=this.appliedDisplayUnits;this.initSourcesWithLayers(this.config,!0),this._applyConfig(this.config);for(const i of Object.keys(e))this.sourcesWithLayers[i].show(e[i]);this.appliedDisplayUnits=t,this.applyVisibility(this.config)}addImageIfNotExisting(e,t,i){addOrUpdateImage("if-not-in-sprite",e,t,this.mapLibreMap,i)}paintImage(e,t,i){addOrUpdateImage("add-or-update",instanceImageID(e,this.instanceIndex),t,this.mapLibreMap,i)}reshowKeepingEventStates(e,t){e.show(withShownEventStates(e.shownFeatures,t,featureIdOf))}async showRoutes(e,t){const i=toDisplayRoutes(e,t?.selectedIndex);await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.show(i),this.sourcesWithLayers.incidents.show(this.trafficSectionsOf(i,this.config));for(const s of["vehicleRestricted","ferry","tunnel","tollRoad",...bandedSectionTypes])this.sourcesWithLayers[sectionSourceKey(s)].show(toDisplayRouteSections(i,s));this.sourcesWithLayers.speedLimitSections.show(this.speedLimitSectionsOf(i,this.config)),this.applySignPriority(this.config),this.sourcesWithLayers.instructionLines.show((e=>({type:"FeatureCollection",features:drawableInstructions(e).map(({instruction:e,routeIndex:t,routeState:i})=>({type:"Feature",geometry:{type:"LineString",coordinates:e.routePath.map(e=>e.point)},properties:{...e,id:generateId(),routeIndex:t,routeState:i}}))}))(i)),this.sourcesWithLayers.instructionArrows.show((e=>({type:"FeatureCollection",features:drawableInstructions(e).map(({instruction:e,routeIndex:t,routeState:i})=>{const s=[e.routePath[e.routePath.length-2]?.point,e.routePath[e.routePath.length-1]?.point];return{type:"Feature",geometry:toPointGeometry(s[1]),properties:{...e,id:generateId(),routeIndex:t,routeState:i,lastPointBearingDegrees:bearing(s[0],s[1])}}})}))(i)),showOrClearCountryCrossings(this.sourcesWithLayers.countryCrossings,i,this.config),!1!==this.config?.summaryBubbles?.visible?this.sourcesWithLayers.summaryBubbles.show(this.displaySummariesOf(i,this.config,!1)):this.sourcesWithLayers.summaryBubbles.clear(),this.sourcesWithLayers.sectionFocus.clear(),this.applyVisibility(this.config);for(const s of this.shownFeaturesHandlers)s({routes:e})}async setSectionFocus(e){await this.waitUntilModuleReady(),this.sourcesWithLayers.sectionFocus.show(((e,t)=>{const i=new Set(t);return{type:"FeatureCollection",features:e.features.flatMap((e,t)=>Object.values(e.properties.sections).flat().filter(e=>void 0!==e&&i.has(e.id)&&void 0!==e.startPointIndex&&void 0!==e.endPointIndex).map(i=>toRouteSection(e,t,i)))}})(this.sourcesWithLayers.mainLines.shownFeatures,e??[])),this.applyVisibility(this.config)}async clearRoutes(){await this.waitUntilModuleReady();for(const e of Object.keys(this.sourcesWithLayers))"waypoints"!==e&&this.sourcesWithLayers[e].clear()}async selectRoute(e){await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.clearEventStates({states:["click"],show:!1}),this.sourcesWithLayers.summaryBubbles.clearEventStates({states:["click"],show:!1});const t=toDisplayRoutes(this.sourcesWithLayers.mainLines.shownFeatures,e);this.sourcesWithLayers.mainLines.show(t);for(const i of drawnSectionTypes)showFeaturesWithRouteSelection(t,this.sourcesWithLayers[sectionSourceKey(i)]);showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionLines),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionArrows),this.sourcesWithLayers.summaryBubbles.shownFeatures.features.length&&this.sourcesWithLayers.summaryBubbles.show(this.displaySummariesOf(t,this.config,!0)),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.countryCrossings),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.sectionFocus),this.applyVisibility(this.config)}async showWaypoints(e){const t=(e=>e.map(e=>{if(!e)return e;const t=asWaypoint(e);return{...t,id:t.id??generateId()}}))(Array.isArray(e)?e:e.features);await this.waitUntilModuleReady(),this.shownWaypoints=t,this.sourcesWithLayers.waypoints.show(this.displayWaypointsOf(t,this.config)),this.applyVisibility(this.config);for(const i of this.shownFeaturesHandlers)i({waypoints:e})}async clearWaypoints(){await this.waitUntilModuleReady(),this.shownWaypoints=void 0,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,tollRoads:this.sourcesWithLayers.tollRoads.shownFeatures,...Object.fromEntries(generatedSectionTypes.map(e=>[sectionSourceKey(e),this.sourcesWithLayers[sectionSourceKey(e)].shownFeatures])),speedLimitSections:this.sourcesWithLayers.speedLimitSections.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,sectionFocus:this.sourcesWithLayers.sectionFocus.shownFeatures}}eventStateSources(){return["mainLines"]}get events(){const e=Object.fromEntries(bandedSectionTypes.map(e=>[sectionSourceKey(e),this.userEventsWithStates([sectionSourceKey(e)])]));return this.buildEvents(this.moduleEventsWithShown(["mainLines","waypoints","summaryBubbles","countryCrossings","incidents","vehicleRestricted","ferries","tollRoads","tunnels","instructionLines",...generatedSectionTypes.map(sectionSourceKey)],this.shownFeaturesHandlers),{...e,speedLimitSections:this.userEventsWithStates(["speedLimitSections"]),mainLines:this.userEventsWithStates(["mainLines"]),waypoints:this.userEventsWithStates(["waypoints"]),summaryBubbles:this.userEventsWithStates(["summaryBubbles"]),countryCrossings:this.userEventsWithStates(["countryCrossings"],{mapping:e=>((e,t)=>{const i=e.properties,s=t.features[i.routeIndex]?.properties.sections.country??[],o=e=>s.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 existingAnchorLayerID(this.mapLibreMap,this.layersSpecs.mainLines.find(t=>t.id===e)?.beforeID)}},hillshadeMethods=["standard","basic","igor","combined","multidirectional"],hillshadeLightAlignments=["viewport","map"],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]]}),roadLine=(e,t)=>({metadataGroups:["road"],layerTypes:["line"],idIncludes:e,...t&&{idExcludes:t}}),TEXT_LAYERS={metadataGroups:["places_label","road_label","label","address_point_label","border_label"],layerTypes:["symbol"],idExcludes:["shield","exit","water","river"]},WATER_TEXT_LAYERS={metadataGroups:["label"],layerTypes:["symbol"],idIncludes:["water","river"]},mapColorDescriptions={land:"Map background and other bare-land features. On the mono styles, every map colour left unset derives from it, borders and labels included.",water:"Waterbodies, waterways and other water features. Also influences glaciers, water labels and ferry lines.",vegetation:"Forests and other land cover such as grass and shrubland. Also influences earth cover vegetation at smaller scales.",park:"City parks and sport/recreation grounds. Also influences National Parks and other protected areas at smaller scales.",artificial:"Built-up-areas and man-made features such as landuse grounds and buildings. Also influences railways.",roadMajor:"Most important road classes, from motorways & trunks to primary roads. Also influences outline and tunnel colours.",road:"Less important road classes, from secondary/tertiary to streets and service roads. Also influences tunnel colours.",roadOutline:"Road outlines for secondary/tertiary roads and minor classes, on tunnels, bridges and link roads too. Major road outlines follow `roadMajor`.",label:"Labels for capitals and other populated places/admin areas. Also influences border styling and all other label colours.",labelHalo:"Halos of populated places and admin area labels. Also influences border outlines and all other label halos."},mapColorDefinitions=/* @__PURE__ */(()=>{const e=paintLayers("fill"),t=paintLayers("line"),i=paintLayers("fill-extrusion"),s=baseMapLayerGroupSelector("water"),o=roadLine(["road line","road outline","under construction","link road"],["tarmac"]),r=roadLine(["motorway","primary road","major road"]),a=roadLine(["secondary road","tertiary road","street","minor road","restricted","service road"],["outline"]),n=roadLine(["secondary road outline","tertiary road outline","street outline","minor road outline","tarmac outline"]),l=roadLine(["railway","subway","track","path","aerialway"]),c={...baseMapLayerGroupSelector("capitalLabels"),layerTypes:["symbol"]};return{land:{anchor:{layers:[{layerTypes:["background"]}],property:"background-color"},targets:[{layers:[{layerTypes:["background"]}],properties:["background-color"]},e({metadataGroups:["area"],idIncludes:["earth cover","landcover"]}),e({metadataGroups:["road_area"]}),e({metadataGroups:["transit_area"]}),t({metadataGroups:["transit_area"]})]},water:{anchor:{layers:[{...s,layerTypes:["fill"],idIncludes:["fill"]}],property:"fill-color"},targets:[e(s),t(s),{layers:[WATER_TEXT_LAYERS],properties:["text-color","text-halo-color"]},t(baseMapLayerGroupSelector("ferries"))]},vegetation:{anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["landcover"]}],property:"fill-color"},targets:[e({metadataGroups:["area"],idIncludes:["landcover","earth cover"]})]},park:{anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["protected"]}],property:"fill-color"},targets:[e({metadataGroups:["area"],idIncludes:["protected","outdoor","sport"]}),{...e({metadataGroups:["area"],idIncludes:["landuse"]}),claimedMatchKeys:["outdoor","sport"]},t({metadataGroups:["border"],idIncludes:["overlays"]})]},artificial:{anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["built-up"]}],property:"fill-color",lastStop:!0},targets:[...[e({metadataGroups:["area"],idIncludes:["built-up","landuse","parking"]}),e(baseMapLayerGroupSelector("buildings2D")),t(baseMapLayerGroupSelector("buildings2D")),i(baseMapLayerGroupSelector("buildings3D"))].map(e=>({...e,recolorsTints:!0})),e({metadataGroups:["transit_area","road_area"]}),t({metadataGroups:["transit_area"]}),t(l)]},roadMajor:{anchor:{layers:[roadLine(["motorway & trunk"],["outline"])],property:"line-color",roadClass:"major"},targets:[t(r),{layers:[o],properties:["line-color"],roadClass:"major"}]},road:{anchor:{layers:[roadLine(["secondary road"],["outline"])],property:"line-color"},targets:[t(a),{layers:[roadLine(["road line","under construction","link road"],["outline"])],properties:["line-color"],roadClass:"minor"}]},roadOutline:{anchor:{layers:[roadLine(["secondary road outline"])],property:"line-color"},targets:[t(n),{layers:[roadLine(["road outline","link road outline"],["tarmac"])],properties:["line-color"],roadClass:"minor"}]},label:{anchor:{layers:[c],property:"text-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-color"]},t({metadataGroups:["border"],idIncludes:["country","state","treaty","disputed"]})]},labelHalo:{anchor:{layers:[c],property:"text-halo-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-halo-color"]},t({metadataGroups:["border"],idIncludes:["background"]})]}}})(),baseMapColorNames=/* @__PURE__ */(()=>/* @__PURE__ */everyOf()(["land","water","vegetation","park","artificial","roadMajor","road","roadOutline","label","labelHalo"]))(),mapColorNames=/* @__PURE__ */(()=>[...baseMapColorNames,"accent"])(),isMapColorName=e=>mapColorNames.some(t=>t===e),mapColorKnobId=e=>`colors.${e}`,baseMapColorKnobs=e=>Object.fromEntries(baseMapColorNames.map(t=>[mapColorKnobId(t),e(t)])),factor=e=>({kind:"factor",description:e,range:FACTOR_RANGE,appliesTo:"any-style"}),mapColor$1=e=>({kind:"color",description:mapColorDescriptions[e],appliesTo:"tomtom-styles"}),knobDefinitions=/* @__PURE__ */(()=>({"labels.sizeFactor":factor("Size of every base-map text label (places, roads, POIs, house numbers)."),"symbols.sizeFactor":factor("Size of every base-map icon (POI icons, route shields, road arrows)."),"roads.widthFactor":factor("Width of all road lines, keeping the hierarchy motorway → path."),"labels.typeface":{kind:"enum",description:"Typeface of every map label, each keeping its weight. The SDK's own labels follow it unless their module sets a typeface or a `font` of its own. The serif and italic faces lack some scripts, which the style's own face draws instead. A `labels.customTypeface` of your own font files, set through the module's config, wins over it.",options:mapTypefaces,appliesTo:"tomtom-styles"},...baseMapColorKnobs(mapColor$1),"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"},"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"},"view.sky.visible":{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"},"view.sky.color":{kind:"color",description:"Colour of the sky (and of the atmosphere halo around the globe). Defaults to the style's own sky where it draws one, otherwise to a daylit blue on a light style and a night blue on a dark one.",appliesTo:"any-style"},"view.sky.horizonColor":{kind:"color",description:"Colour of the sky at the horizon. Defaults to the style's own sky where it draws one, otherwise follows the style theme, so a dark map gets a dim horizon rather than a white one.",appliesTo:"any-style"},"view.space.color":{kind:"color",description:"Colour behind the map, which a globe leaves visible around the planet. The map canvas is transparent there. Defaults to a background the page already gives the map container, otherwise follows the style theme: white on a light style, the night blue #0a1626 on a dark one.",appliesTo:"any-style"},"view.light.direction":{kind:"number",description:"Direction the light on the 3D buildings comes from, in degrees clockwise from the top of the screen, or from north with `view.light.alignment` at `map`. Defaults to the style's own light, otherwise 210.",range:{min:0,max:359,step:1,bounds:"hard"},appliesTo:"any-style"},"view.light.altitude":{kind:"number",description:"Height of the light above the horizon, in degrees (0 = sunset, 90 = noon). Defaults to the style's own light, otherwise 60.",range:{min:0,max:90,step:1,bounds:"hard"},appliesTo:"any-style"},"view.light.alignment":{kind:"enum",description:"What `view.light.direction` is measured from: viewport (the top of the screen, turning with the camera) or map (north, staying on the same sides of the buildings as the map rotates). Defaults to the style's own light, otherwise viewport.",options:hillshadeLightAlignments,appliesTo:"any-style"},"view.light.color":{kind:"color",description:"Colour of the light on the 3D buildings. Defaults to the style's own light, otherwise white.",appliesTo:"any-style"},"view.light.intensity":{kind:"number",description:"Strength of the light, 0 to 1: higher sets the lit sides further apart from the shaded ones. Defaults to the style's own light, otherwise 0.5.",range:{min:0,max:1,step:.05,bounds:"hard"},appliesTo:"any-style"},"buildings3D.roundedCornerDistanceMeters":{kind:"number",description:"How far along each wall the corners of the 3D buildings are rounded, in metres. 0 keeps them sharp. Defaults to the style's own rounding, otherwise 1, which softens the edges.",range:{min:0,max:10,step:.5,bounds:"hard-min"},appliesTo:"tomtom-styles"}}))(),stylingFoundationsKnobCatalogue=/* @__PURE__ */withIds(knobDefinitions),stylingFoundationsKnobIds=/* @__PURE__ */stylingFoundationsKnobCatalogue.map(({id:e})=>e),allButLand=/* @__PURE__ */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,MAJOR_ROAD_CLASSES=/* @__PURE__ */new Set(["motorway","trunk","primary"]),isMatchKey=e=>"string"==typeof e||"number"==typeof e,matchLabelKeys=e=>(Array.isArray(e)?e:[e]).filter(isMatchKey),roadClassOfKeys=e=>e.some(e=>"string"==typeof e&&MAJOR_ROAD_CLASSES.has(e.replace(/_link$/,"")))?"major":"minor",TOP_LEVEL_CONTEXT={roadClass:void 0,matchKeys:[]},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"===(s=e)[0]&&Array.isArray(s[1])&&"get"===s[1][0]&&("category"===s[1][1]||"road_category"===s[1][1]),r=[e[0],e[1]];for(let s=2;s<e.length-1;s+=2){const a=matchLabelKeys(e[s]),n=o?roadClassOfKeys(a):i.roadClass,l=[...i.matchKeys,...a];r.push(e[s],mapColorLiterals(e[s+1],t,{roadClass:n,matchKeys:l}))}const a=o?"minor":i.roadClass;return r.push(mapColorLiterals(e.at(-1),t,{...i,roadClass:a})),r}return e.map(e=>mapColorLiterals(e,t,i))}var s;return isLegacyFunction(e)?{...e,stops:e.stops.map(([e,s])=>[e,mapColorLiterals(s,t,i)])}:e},tintSaturationScale=e=>{const t=themeLuminance(e);return void 0===t?void 0:Math.max(t,.33)},shadeShift=(e,t,i)=>{const[s,o,r]=[e,t,i].map(toHsl);if(!s||!o||!r)return;const a=s.s<.08||o.s<.08;if(!a&&hueDistance(s,o)>40)return;const n=hslShiftBetween(e,t),l=r.alpha??1;return n&&{...n,h:a?0:n.h,alpha:(o.alpha??1)*l-l}},SKY_DEFAULTS=/* @__PURE__ */(()=>{const e={"sky-horizon-blend":.8,"atmosphere-blend":.8,"fog-ground-blend":.5,"horizon-fog-blend":.8};return{light:{...e,"sky-color":"#88c6fc","horizon-color":"#ffffff","fog-color":"#ffffff"},dark:{...e,"sky-color":"#0a1626","horizon-color":"#2b4a72","fog-color":"#0a1626"}}})(),SPACE_COLOR_DEFAULTS={light:"#ffffff",dark:"#0a1626"},styleSkyColor=(e,t)=>void 0===e?t:isColorLiteral(e)?e:void 0,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},DEFAULT_LIGHT={anchor:"viewport",position:[1.15,210,30],color:"#ffffff",intensity:.5},isLightPosition=e=>Array.isArray(e)&&3===e.length&&e.every(e=>"number"==typeof e),extensionsByMap=/* @__PURE__ */new WeakMap,MapLookKnobs=class MapLookKnobs{constructor(e){this.engine=e,this.mapColorTargetsByKey=/* @__PURE__ */new Map,this.mapColorTargetsByKnob=/* @__PURE__ */new Map,this.mapColorAnchors=/* @__PURE__ */new Map,this.landDerivedColors=[],this.lightWritten=!1}static for(e){return ofMap(extensionsByMap,e,()=>new MapLookKnobs(StyleKnobs.for(e)))}get tomtomMap(){return this.engine.tomtomMap}index(){this.mapColorTargetsByKey=/* @__PURE__ */new Map,this.mapColorTargetsByKnob=/* @__PURE__ */new Map,this.mapColorAnchors=/* @__PURE__ */new Map,this.landDerivedColors=landDerivedMapColors[standardStyleIdOf(this.tomtomMap.getStyleInput())]??[]}resolve(e,t){return"mapColor"===t.type?this.resolveMapColor(t.color):["\0map"]}refresh(e,t){switch(t.type){case"projection":this.refreshProjection();break;case"sky":this.refreshSky();break;case"space":this.refreshSpace();break;case"light":this.refreshLight();break;case"mapColor":this.refreshMapColor(t.color)}}defaultOf(e,t){if("mapColor"===t.type){const t=this.mapColorAnchors.get(e);return t&&opaqueColor(t)}return this.mapLevelDefaultOf(e)}derivedValueOf(e,t){if("mapColor"===t.type&&this.mapColorAnchors.has(e))return this.mapColorsOf()[t.color]}mapColorsInForce(){const e=this.mapColorsOf();for(const t of mapColorNames){const i=this.mapColorAnchors.get(mapColorKnobId(t));void 0===e[t]&&i&&(e[t]=opaqueColor(i))}return e}refreshSpace(){const e=this.tomtomMap.mapLibreMap.getContainer();this.originalSpaceColor??=paintedBackgroundOf(e),e.style.backgroundColor=this.engine.values["view.space.color"]??this.defaultSpaceColor()}restoreLight(){this.lightWritten&&this.refreshLight()}resolveMapColor(e){const{layers:t,sources:i}=this.engine.indexedStyle,s=mapColorKnobId(e),o=mapColorDefinitions[e],r=[];for(const c of o.targets)for(const s of t.filter(e=>matchesAnyLayerSelector(c.layers,e,i)))for(const t of c.properties){if(!this.engine.capture(s,t))continue;const i={color:e,layerId:s.id,property:t,owns:ownershipOf(c),recolorsTints:c.recolorsTints,claimedMatchKeys:c.claimedMatchKeys};r.push(i);const o=targetKey(s.id,t);ofMap(this.mapColorTargetsByKey,o,()=>[]).push(i)}this.mapColorTargetsByKnob.set(s,r);const{anchor:a}=o,n=t.find(e=>matchesAnyLayerSelector(a.layers,e,i)&&void 0!==styleValueOf(e,a.property)),l=n&&((e,t=()=>!0,i=!1)=>{let s;for(const{literal:o,...r}of(e=>{const t=[];return mapColorLiterals(e,(e,i)=>(t.push({literal:e,...i}),e)),t})(e)){if(!t(r))continue;const e=r.matchKeys.length>0,a=Math.round(100*(toHsl(o)?.s??0)),n=s?.saturation===a;s&&!(i?s.keyed||!e:a>s.saturation||n&&s.keyed&&!e)||(s={literal:o,saturation:a,keyed:e})}return s?.literal})(styleValueOf(n,a.property),ownershipOf({roadClass:a.roadClass}),a.lastStop);return l&&this.mapColorAnchors.set(s,l),l?[...new Set(r.map(e=>e.layerId))]:[]}refreshMapColor(e){const t=this.mapColorsOf(),i=[e,...this.landDerivedColors.filter(t=>mapColorDerivationInputs(t).includes(e))],s=new Map(i.flatMap(e=>this.mapColorTargetsByKnob.get(mapColorKnobId(e))??[]).map(e=>[targetKey(e.layerId,e.property),e]));for(const{layerId:o,property:r}of s.values())this.refreshMapColorProperty(o,r,t)}mapColorsOf(){const e=this.engine.values,t={};for(const i of mapColorNames){const s=e[mapColorKnobId(i)];"string"==typeof s&&(t[i]=s)}return((e,t,i)=>{const s=e.land??i,o=t.filter(t=>void 0===e[t]&&mapColorDerivationInputs(t).some(t=>void 0!==e[t])),r=s&&o.length?((e,t)=>{const i=toHsl(e),s=themeLuminance(e);if(!i||void 0===s)return;const o=sign(s<=.95),r=sign(s>.3),a=lightenBy(15*o,lighten(Math.max(s/5,.1),i)),n=t&&toHsl(t)||a;return{water:formatStyleHsl(darkenBy(10*sign(s>.01),darken(Math.max(s/20,.05),i))),vegetation:formatStyleHsl(darken(.05,darkenBy(2,i))),park:formatStyleHsl(darken(.03,darkenBy(1,i))),artificial:formatStyleHsl(darkenBy(4*sign(s>.05),lighten(Math.max(s/15,.02),i))),road:formatStyleHsl(a),roadMajor:formatStyleHsl(n),roadOutline:formatStyleHsl(darkenBy(20*o,n)),label:formatStyleHsl(desaturate(.3,darkenBy(60*r,lighten(Math.max(s/5,.1),i)))),labelHalo:formatStyleHsl(lightenBy(75*r,i))}})(s,e.road):void 0;return r?{...Object.fromEntries(o.map(e=>[e,r[e]])),...e}:e})(t,this.landDerivedColors,this.mapColorAnchors.get(mapColorKnobId("land")))}refreshMapColorProperty(e,t,i){const s=this.engine.originalValueOf(e,t),o=[],r=(e=>{const t=new Set(e.flatMap(({claimedMatchKeys:e=[]})=>e));return t.size?e.map(e=>{const i=new Set(e.claimedMatchKeys);return{...e,owns:s=>e.owns(s)&&s.matchKeys.every(e=>i.has(e)||!t.has(e))}}):e})(this.mapColorTargetsByKey.get(targetKey(e,t))??[]);for(const{color:a,owns:n,recolorsTints:l}of r){const e=i[a],t=this.mapColorAnchors.get(mapColorKnobId(a));e&&t&&o.push({anchorColor:t,newColor:e,owns:n,recolorsTints:l})}this.engine.setProperty(e,t,o.length?((e,t)=>{const i=[...t].reverse();return mapColorLiterals(e,(e,t)=>{const s=i.filter(({owns:e})=>!e||e(t));for(const{anchorColor:i,newColor:r}of s){const t=shadeShift(i,e,r);if(t)return shiftHsl(r,t)??e}const o=s.find(e=>e.recolorsTints);return o?((e,t,i)=>{const[s,o,r]=[e,t,i].map(toHsl),[a,n]=[e,i].map(tintSaturationScale);if(!(s&&o&&r&&a&&n))return;const l=o.s*n/a,c=(o.alpha??1)*(r.alpha??1);return formatStyleHsl({h:o.h,s:l,l:r.l+o.l-s.l,alpha:c})})(o.anchorColor,e,o.newColor)??e:e})})(s,o):s)}refreshProjection(){this.tomtomMap.mapLibreMap.setProjection({type:this.engine.values["view.projection"]??this.styleProjection()})}styleProjection(){return this.engine.indexedStyle.projection?.type??"mercator"}refreshSky(){const e=this.engine.values,t=this.shownStyleSky(),i=e["view.sky.visible"]??this.mapLevelDefaultOf("view.sky.visible"),s=SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme],o=i?{...s,...t,"sky-color":e["view.sky.color"]??t?.["sky-color"]??s["sky-color"],"horizon-color":e["view.sky.horizonColor"]??t?.["horizon-color"]??s["horizon-color"]}:CLEAR_SKY;this.tomtomMap.mapLibreMap.setSky(o,{validate:!1})}refreshLight(){const e=this.engine.values,t=this.styleLight(),i=e["view.light.direction"],s=e["view.light.altitude"],o=e["view.light.alignment"],[r,a,n]=isLightPosition(t.position)?t.position:DEFAULT_LIGHT.position;this.tomtomMap.mapLibreMap.setLight({anchor:"map"===o||"viewport"===o?o:t.anchor,position:void 0===i&&void 0===s?t.position:[r,i??a,void 0===s?n:90-s],color:e["view.light.color"]??t.color,intensity:e["view.light.intensity"]??t.intensity},{validate:!1}),this.lightWritten=!0}styleLight(){return{...DEFAULT_LIGHT,...this.engine.indexedStyle.light}}defaultSpaceColor(){return this.originalSpaceColor||SPACE_COLOR_DEFAULTS[this.tomtomMap.styleLightDarkTheme]}shownStyleSky(){const e=this.engine.indexedStyle.sky,t=0===e?.["atmosphere-blend"]&&"transparent"===e["sky-color"]&&"transparent"===e["horizon-color"];return e&&!t?e:void 0}mapLevelDefaultOf(e){const t=this.shownStyleSky(),i=SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme],s=this.styleLight();switch(e){case"view.projection":{const e=this.styleProjection();return"string"==typeof e?e:void 0}case"view.sky.visible":return void 0!==t;case"view.sky.color":return styleSkyColor(t?.["sky-color"],i["sky-color"]);case"view.sky.horizonColor":return styleSkyColor(t?.["horizon-color"],i["horizon-color"]);case"view.space.color":return this.defaultSpaceColor();case"view.light.direction":return isLightPosition(s.position)?s.position[1]:void 0;case"view.light.altitude":return isLightPosition(s.position)?90-s.position[2]:void 0;case"view.light.alignment":return"string"==typeof s.anchor?s.anchor:void 0;case"view.light.color":return isColorLiteral(s.color)?s.color:void 0;case"view.light.intensity":return"number"==typeof s.intensity?s.intensity:void 0;default:return}}},ownershipOf=e=>"major"===e.roadClass?({roadClass:e})=>"major"===e:"minor"===e.roadClass?({roadClass:e})=>"major"!==e:()=>!0,paintedBackgroundOf=e=>{const t=getComputedStyle(e).backgroundColor;return UNPAINTED_BACKGROUNDS.has(t)?"":t},mapColor=e=>({kind:"color",mechanisms:[{type:"mapColor",color:e}]}),stylingFoundationsLook=/* @__PURE__ */styleKnobScope("StylingFoundationsModule","",/* @__PURE__ */(()=>{const e={sourceTypes:["vector"],layerTypes:["symbol"]},t={...baseMapLayerGroupSelector("roads"),layerTypes:["line"]},i={kind:"color",mechanisms:[{type:"sky"}]},s={kind:"number",mechanisms:[{type:"light"}]};return{"labels.sizeFactor":scaleKnob("text-size",e),"symbols.sizeFactor":scaleKnob("icon-size",e),"roads.widthFactor":scaleKnob("line-width",t),"labels.typeface":{kind:"enum",mechanisms:[{type:"typeface",layers:[e]}]},...baseMapColorKnobs(mapColor),"colors.accent":{kind:"color",mechanisms:[{type:"published"}]},"view.projection":{kind:"enum",mechanisms:[{type:"projection"}]},"view.sky.visible":{kind:"toggle",mechanisms:[{type:"sky"}]},"view.sky.color":i,"view.sky.horizonColor":i,"view.space.color":{kind:"color",mechanisms:[{type:"space"}]},"view.light.direction":s,"view.light.altitude":s,"view.light.alignment":{kind:"enum",mechanisms:[{type:"light"}]},"view.light.color":{kind:"color",mechanisms:[{type:"light"}]},"view.light.intensity":s,"buildings3D.roundedCornerDistanceMeters":{kind:"number",mechanisms:[{type:"literal",property:"fill-extrusion-rounded-corner-distance",layers:[baseMapLayerGroupSelector("buildings3D")]}]}}})(),e=>MapLookKnobs.for(e)),StylingFoundationsModule=class StylingFoundationsModule extends AbstractStyleOwnedMapModule{static async get(e,t){return await waitUntilMapIsReady(e),sharedInstance(e,StylingFoundationsModule,()=>new StylingFoundationsModule(e,t),t&&(e=>e.updateConfig(t)))}constructor(e,t){super(e,t),e._onStyleKnobsApplied(()=>{e.mapReady&&this.styleKnobs.indexedStyle===this.overriddenStyle&&this.layerOverrides.reapply()})}get styleKnobs(){return stylingFoundationsLook.engineOf(this.tomtomMap)}styleChangePriority(){return 100}_initSourcesWithLayers(){this.warned=/* @__PURE__ */new Set,this.layerOverrides??=new LayerOverrides(this.mapLibreMap,this.filterComposer,this.visibilityComposer,(e,t)=>this.warnOnce(e,t)),this.overriddenStyle=this.styleKnobs.indexedStyle;const e=this.tomtomMap._styleLoads;this.layerOverrides.index(this.overriddenStyle.layers,this.overriddenStyle.sources,e!==this.indexedStyleLoads),this.indexedStyleLoads=e;const t=MapLookKnobs.for(this.tomtomMap);return t.refreshSpace(),t.restoreLight(),{}}_applyConfig(e){const t=withoutUndefined(e??{});return stylingFoundationsLook.apply(this.tomtomMap,t),((e,t,i)=>{if(!e.mapReady||!t&&!customTypefaceOf(e))return;const s=t&&declareCustomTypeface(t);!declareFontFaces(e,i,s?.fontFaces)&&isEqual(customTypefaceOf(e),s?.typeface)||((e,t,i)=>{const s=declarations.get(e);s&&e.mapReady&&fontFacesToSet(e,s)?s.waiting.set(t,i):i()})(e,i,()=>{((e,t)=>{t?customTypefaces.set(e,t):customTypefaces.delete(e)})(e,s?.typeface),i.reapply(["labels.typeface"])})})(this.tomtomMap,t.labels?.customTypeface,this.styleKnobs),this.tomtomMap._setMapColors(MapLookKnobs.for(this.tomtomMap).mapColorsInForce()),this.tomtomMap.mapReady&&this.layerOverrides.reapply(),isEmpty(t)?void 0:t}discardShownData(){this.layerOverrides.clear()}get layers(){return{query:e=>new LayerSelection(this.layerOverrides,e)}}_knobValue(e){return super._knobValue(e)??stylingFoundationsLook.valueOf(this.tomtomMap,e)}setMapColors(e){const t={};for(const[i,s]of Object.entries(e)){if(!isMapColorName(i))throw new Error(`Unknown map colour '${i}'. Known colours: ${mapColorNames.join(", ")}.`);void 0!==s&&(t[mapColorKnobId(i)]=s)}setKnobs(this,stylingFoundationsKnobCatalogue,t)}exportStyle(){const e=this.mapLibreMap.getStyle(),t=this.mapLibreMap.getLight();return(e=>{const{"font-faces":t,...i}=JSON.parse(JSON.stringify(e).replace(SDK_NAME_IN_JSON_STACK,"")),s=t&&withoutCustomFaceDeclarations(t);return isEmpty(s)?i:{...i,"font-faces":s}})(Object.keys(t).length?{...e,light:t}:e)}get events(){return this.moduleEvents([])}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[StylingFoundationsModule] ${t}`))}},withoutUndefined=e=>Object.fromEntries(Object.entries(e).flatMap(([e,t])=>{const i=isPlainObject(t)?withoutUndefined(t):t;return void 0===i||isPlainObject(i)&&isEmpty(i)?[]:[[e,i]]})),mapPresets={"data-viz":{name:"Data visualisation",description:"A quiet base for your own data on top: smaller labels, fewer markers, thinner roads, no badges competing with the overlay.",settings:{stylingFoundations:{"labels.sizeFactor":.9,"symbols.sizeFactor":.9,"roads.widthFactor":.8},baseMap:{"roads.exitNumbers.visible":!1,"roads.arrows.visible":!1},pois:{"microMarkers.visible":!1,minZoom:14}}},"night-driving":{name:"Night driving",description:"Bigger labels and shields, wider roads, POIs out of the way until close up.",settings:{stylingFoundations:{"labels.sizeFactor":1.2,"symbols.sizeFactor":1.2,"roads.widthFactor":1.2},baseMap:{"roads.exitNumbers.visible":!0,"roads.arrows.visible":!0},pois:{"microMarkers.visible":!1,minZoom:13}}},minimal:{name:"Minimal",description:"The bare map: smaller labels, no road markings, exit badges or POI dots until close up. Hide buildings and shields with BaseMapModule.",settings:{stylingFoundations:{"labels.sizeFactor":.9},baseMap:{"roads.exitNumbers.visible":!1,"roads.arrows.visible":!1,"roads.restricted.visible":!1,"roads.underConstruction.visible":!1},pois:{"microMarkers.visible":!1,minZoom:16}}},globe:{name:"Globe",description:"A globe with an atmosphere for the zoomed-out view; flattens to Mercator as you zoom in.",settings:{stylingFoundations:{"view.projection":"globe","view.sky.visible":!0}}}},mapPresetIds=/* @__PURE__ */Object.keys(mapPresets),mapPresetCatalogue=/* @__PURE__ */mapPresetIds.map(e=>({id:e,...structuredClone(mapPresets[e])})),applyPresetPart=(e,t,i,s={})=>{for(const[a,n]of Object.entries(s))validateKnobValue(knobEntryOf(t,a),n);const o=e.getConfig()??{},r=configWithKnobs(i.reduce((e,t)=>configWithoutKnob(e,t),o),s);isEqual(r,o)||e.applyConfig(isEmpty(r)?void 0:r)},applyMapPreset=async(e,t,i={})=>{if(!Object.hasOwn(mapPresets,t))throw new Error(`Unknown map preset '${t}'. Known presets: ${mapPresetIds.join(", ")}.`);const s=mapPresets[t].settings,[o,r,a]=await Promise.all([StylingFoundationsModule.get(e),BaseMapModule.get(e),POIsModule.get(e)]),n=e=>i.merge?[]:(e=>[...new Set(Object.values(mapPresets).flatMap(({settings:t})=>Object.keys(t[e]??{})))])(e);applyPresetPart(o,stylingFoundationsKnobCatalogue,n("stylingFoundations"),s.stylingFoundations),applyPresetPart(r,baseMapKnobCatalogue,n("baseMap"),s.baseMap),applyPresetPart(a,poisKnobCatalogue,n("pois"),s.pois)},MULTIDIRECTIONAL_LIGHT_OFFSETS=[-67.5,-22.5,22.5,67.5],multidirectionalLights={dependsOn:["terrain.hillshade.method"],expand:(e,t)=>"multidirectional"===t("terrain.hillshade.method")&&"number"==typeof e?MULTIDIRECTIONAL_LIGHT_OFFSETS.map(t=>((e+t)%360+360)%360):e},hillshadeLook=/* @__PURE__ */styleKnobScope("TerrainModule","terrain.",/* @__PURE__ */(()=>{const e=styleModuleLayerGroupSelector("hillshade"),t=(t,i,s)=>({kind:t,mechanisms:[{type:"literal",property:i,layers:[e],expansion:s}]});return{"terrain.hillshade.method":t("enum","hillshade-method"),"terrain.hillshade.light.direction":t("number","hillshade-illumination-direction",multidirectionalLights),"terrain.hillshade.light.altitude":t("number","hillshade-illumination-altitude"),"terrain.hillshade.light.alignment":t("enum","hillshade-illumination-anchor"),"terrain.hillshade.intensity":t("number","hillshade-exaggeration"),"terrain.hillshade.maxZoom":{kind:"number",mechanisms:[{type:"maxZoom",layers:[e]}]},"terrain.hillshade.colors.shaded":colorKnob("hillshade-shadow-color",e),"terrain.hillshade.colors.lit":colorKnob("hillshade-highlight-color",e),"terrain.hillshade.colors.steep":colorKnob("hillshade-accent-color",e)}})()),trafficLook=e=>{const t={...styleModuleLayerGroupSelector(e),layerTypes:["line"]},i=(e,i)=>({...t,idIncludes:[i?`${e} outline`:e],...i?{}:{idExcludes:["outline"]}});return{levelColor:e=>colorKnob("line-color",i(e,!1),i(e,!0)),closedColor:()=>colorKnob("line-color",i("closed road",!0)),widthFactor:()=>scaleKnob("line-width",t),opacityFactor:()=>scaleKnob("line-opacity",t)}},trafficFlowStyleKnobs=/* @__PURE__ */(()=>{const e=trafficLook("trafficFlow");return{"traffic.flow.colors.free":e.levelColor("free flow"),"traffic.flow.colors.slow":e.levelColor("slow flow"),"traffic.flow.colors.queueing":e.levelColor("queueing flow"),"traffic.flow.colors.stationary":e.levelColor("stationary flow"),"traffic.flow.colors.closed":e.closedColor(),"traffic.flow.widthFactor":e.widthFactor(),"traffic.flow.opacityFactor":e.opacityFactor()}})(),trafficIncidentsStyleKnobs=/* @__PURE__ */(()=>{const e=trafficLook("trafficIncidents");return{[incidentColorKnobIds.minor]:e.levelColor("minor jam"),[incidentColorKnobIds.moderate]:e.levelColor("moderate jam"),[incidentColorKnobIds.major]:e.levelColor("major jam"),[incidentColorKnobIds.indefinite]:e.closedColor(),"traffic.incidents.widthFactor":e.widthFactor(),"traffic.incidents.opacityFactor":e.opacityFactor()}})(),trafficFlowLook=/* @__PURE__ */styleKnobScope("TrafficFlowModule","traffic.flow.",trafficFlowStyleKnobs),trafficIncidentsLook=/* @__PURE__ */styleKnobScope("TrafficIncidentsModule","traffic.incidents.",trafficIncidentsStyleKnobs),styleKnobScopes=[stylingFoundationsLook,poisLook,trafficFlowLook,trafficIncidentsLook,hillshadeLook],styleColorKnobIds=/* @__PURE__ */(()=>/* @__PURE__ */everyOf()(["colors.land","colors.water","colors.vegetation","colors.park","colors.artificial","colors.roadMajor","colors.road","colors.roadOutline","colors.label","colors.labelHalo","colors.accent","view.sky.color","view.sky.horizonColor","view.space.color","pois.label.color","pois.label.haloColor","traffic.flow.colors.free","traffic.flow.colors.slow","traffic.flow.colors.queueing","traffic.flow.colors.stationary","traffic.flow.colors.closed","traffic.incidents.colors.minor","traffic.incidents.colors.moderate","traffic.incidents.colors.major","traffic.incidents.colors.closed","terrain.hillshade.colors.shaded","terrain.hillshade.colors.lit","terrain.hillshade.colors.steep"]))(),getStyleColor=(e,t)=>{const i=styleKnobScopes.find(e=>e.has(t))?.engineOf(e).valueOf(t);return"string"==typeof i?i:void 0},stylingFoundationsKnobKinds=["factor","number","toggle","color","enum"],stylingFoundationsKnobAppliesTo=["any-style","tomtom-styles"],shownOriginalOf=(e,t)=>t instanceof GeoJSONSourceWithLayers?t.findById(shownRefId(e))?.feature??e:e,emptyRegistry=()=>({click:/* @__PURE__ */new Set,contextmenu:/* @__PURE__ */new Set,hover:/* @__PURE__ */new Set,"hover-move":/* @__PURE__ */new Set,"long-hover":/* @__PURE__ */new Set,dragstart:/* @__PURE__ */new Set,drag:/* @__PURE__ */new Set,dragend:/* @__PURE__ */new Set}),removeWhere=(e,t)=>{for(let i=e.length-1;i>=0;i--)t(e[i])&&e.splice(i,1)},AbstractEventProxy=class{constructor(){this.interactiveLayerIDs=[],this.handlers={click:{},contextmenu:{},hover:{},"hover-move":{},"long-hover":{},dragstart:{},drag:{},dragend:{}},this.registered=emptyRegistry(),this.findHandlers=(e,t,i)=>t&&e.flatMap(e=>{const s=this.handlers[e][t]??[];return i?s.filter(e=>!e.scope?.featureMatches||e.scope.featureMatches(shownOriginalOf(i,e.sourceWithLayers))):s})||[]}ensureInteractiveLayerIDsAdded(e){for(const t of e)this.interactiveLayerIDs.includes(t)||this.interactiveLayerIDs.push(t)}releaseUnusedInteractiveLayerIDs(e){removeWhere(this.interactiveLayerIDs,t=>e.has(t)&&!this.hasHandlerForLayer(t))}indexHandler(e,t){const i=this.handlers[t];for(const s of e.layerIDs)i[s]??=[],i[s].push(e)}unindexHandlers(e,t){const i=this.handlers[t],s=/* @__PURE__ */new Set;for(const o of e)for(const t of o.layerIDs){s.add(t);const o=i[t];o&&(removeWhere(o,t=>e.has(t)),o.length||delete i[t])}return s}dropHandlers(e,t,i){const s=e.source.id,o=/* @__PURE__ */new Set;for(const r of this.registered[t])r.sourceWithLayers.source.id===s&&i(r)&&o.add(r);if(o.size){for(const e of o)this.registered[t].delete(e);this.releaseUnusedInteractiveLayerIDs(this.unindexHandlers(o,t))}}addEventHandler(e,t,i,s){const o=new Set(scopedLayerIDs(e,s.scope)),r={...s,sourceWithLayers:e,layerIDs:o,handler:t};this.registered[i].add(r),this.ensureInteractiveLayerIDsAdded(o),this.indexHandler(r,i)}removeHandler(e,t,i){this.dropHandlers(e,t,e=>e.handler===i)}remove(e,t,i){this.dropHandlers(e,t,e=>e.owner===i)}removeSource(e){for(const t of Object.keys(this.registered))this.dropHandlers(e,t,()=>!0)}removeAll(){this.interactiveLayerIDs=[],this.handlers={click:{},contextmenu:{},hover:{},"hover-move":{},"long-hover":{},dragstart:{},drag:{},dragend:{}},this.registered=emptyRegistry()}hasHandlerForLayer(e){return Object.values(this.handlers).some(t=>!!t[e]?.length)}hasHandlersOf(e){return e.some(e=>this.registered[e].size>0)}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])),s=/* @__PURE__ */new Map;for(const o of Object.keys(this.registered)){const e=/* @__PURE__ */new Map;for(const s of this.registered[o]){const o=s.owner===t?i.get(s.sourceWithLayers.source.id):void 0;o&&e.set(s,o)}if(!e.size)continue;const r=this.unindexHandlers(new Set(e.keys()),o);for(const[t,i]of e)s.set(t.sourceWithLayers,i),t.sourceWithLayers=i,t.layerIDs=new Set(scopedLayerIDs(i,t.scope)),this.ensureInteractiveLayerIDsAdded(t.layerIDs),this.indexHandler(t,o);this.releaseUnusedInteractiveLayerIDs(r)}return s}},noRenderedFeatures=[],dragEventTypes=["dragstart","drag","dragend"],interactiveEventTypes=["hover","hover-move","long-hover","click","contextmenu",...dragEventTypes],eventsProxyDefaultConfig={precisionMode:"box",paddingBoxPx:5,cursorOnHover:"pointer",cursorOnDraggable:"grab",cursorOnMouseDown:"grabbing",cursorOnMap:"default",longHoverDelayAfterMapMoveMS:800,longHoverDelayOnStillMapMS:300,hoverGracePeriodMS:400},EventsProxy=class extends AbstractEventProxy{constructor(e,t={}){super(),this.enabled=!0,this.recentHovers=new globalThis.Map,this.firstDelayedHoverSinceMapMove=!0,this.mouseMoveFrameRequested=!1,this.dragJustEnded=!1,this.hoverStaleAfterDrag=!1,this.customLayers=new globalThis.Map,this.sameClaim=(e,t)=>this.claimingHandler(e)===this.claimingHandler(t),this.onReleaseOutside=()=>{this.onMouseUp(),this.onPressEnd()},this.map=e,this.mapCanvas=e.getCanvas(),this.config={...eventsProxyDefaultConfig,...definedFields(t)},this.mapCanvas.style.cursor=this.config.cursorOnMap,this.lastCursorStyle=this.config.cursorOnMap,this.listenToEvents()}updateConfig(e){this.config={...this.config,...definedFields(e)},this.hoveringSourceWithLayers||(this.mapCanvas.style.cursor=this.config.cursorOnMap)}updateIfRegistered(e,t){const i=super.updateIfRegistered(e,t),s=new globalThis.Map(Object.values(e).filter(e=>e instanceof GeoJSONSourceWithLayers).map(e=>[e.source.id,e])),o=e=>e?i.get(e)??(e instanceof GeoJSONSourceWithLayers?s.get(e.source.id):void 0)??e:e;this.hoveringSourceWithLayers=o(this.hoveringSourceWithLayers),this.lastClickedSourceWithLayers=o(this.lastClickedSourceWithLayers);for(const r of this.recentHovers.values())r.sourceWithLayers=o(r.sourceWithLayers);return i}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",e=>{this.onMouseDown(),0===e.originalEvent.button&&this.onPressStart(e)&&this.mapCanvas.ownerDocument.addEventListener("mouseup",this.onReleaseOutside,{once:!0})}),this.map.on("mouseup",e=>{this.onMouseUp(),this.onPressEnd(e.lngLat)}),this.map.on("touchstart",e=>{1===e.points.length?this.onPressStart(e):this.onPressEnd()}),this.map.on("touchmove",e=>this.onPressMove(e)),this.map.on("touchend",e=>this.onPressEnd(e.lngLat)),this.map.on("touchcancel",()=>this.onPressEnd()),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,this.onPressEnd())}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 s=this.sourceWithLayersFor(t?.layer.id);return(e=>{const t=/* @__PURE__ */new Set,i=[];for(const s of e){const e=renderedRefId(s);if(void 0===e){i.push(s);continue}const o=`${s.source} ${e}`;t.has(o)||(t.add(o),i.push(s))}return i})(e.filter(e=>i?i.has(e.layer.id):s?._layerSpecs.some(t=>t.id===e.layer.id))).map(e=>shownOriginalOf(e,s))}callerFeaturesFor(e,t,i,s){return e.scope?.layerFilter?this.toCallerFeatures(t,i,e.layerIDs):s}addCustomLayer(e){this.customLayers.set(e.layerId,e)}removeCustomLayer(e){this.removeSource(e),this.customLayers.delete(e.layerId),this.hoveringFeature?.layer.id===e.layerId&&(this.clearLongHoverTimeout(),this.hoveringFeature=void 0,this.hoveringFeatures=void 0,this.hoveringSourceWithLayers=void 0,this.updateHoverCursor(void 0,void 0)),this.lastClickedFeature?.layer.id===e.layerId&&(this.lastClickedFeature=void 0,this.lastClickedSourceWithLayers=void 0),e.detach()}getRenderedFeatures(e){const t=this.queryRenderedFeatures(e);return this.customLayers.size?this.withCustomLayerHits(e,t):t}withCustomLayerHits(e,t){let i;for(const n of this.customLayers.values()){if(!this.hasHandlerForLayer(n.layerId))continue;const t=n.hitFeatures(e);t.length&&(i??=[],i.push({layerId:n.layerId,hits:t}))}if(!i)return t;const s=new globalThis.Map(this.map.getLayersOrder().map((e,t)=>[e,t])),o=e=>s.get(e)??-1;i.sort((e,t)=>o(t.layerId)-o(e.layerId));const r=[];let a=0;for(const{layerId:n,hits:l}of i){for(;a<t.length&&o(t[a].layer.id)>o(n);)r.push(t[a++]);r.push(...l)}return r.concat(t.slice(a))}queryRenderedFeatures(e){const t=this.customLayers.size?this.interactiveLayerIDs.filter(e=>!this.customLayers.has(e)):this.interactiveLayerIDs;if(!t.length)return[];const i={layers:t,validate:!1},s=this.config.precisionMode,o="point-then-box"===s||"point"===s?this.map.queryRenderedFeatures(e,i):[];return o.length||"point"===s?o:this.map.queryRenderedFeatures(this.toPaddedBounds(e),i)}clearLongHoverTimeout(){clearTimeout(this.longHoverTimeoutHandlerID)}restartLongHoverTimeout(){this.clearLongHoverTimeout(),this.longHoverTimeoutHandlerID=setTimeout(()=>this.handleLongHoverTimeout(),this.firstDelayedHoverSinceMapMove?this.config.longHoverDelayAfterMapMoveMS:this.config.longHoverDelayOnStillMapMS)}handleLongHoverTimeout(){this.firstDelayedHoverSinceMapMove=!1;const e=this.lastHandledMouseMove;if(e&&this.isEnabled()){const t=this.getRenderedFeatures(e.point);if(!this.claimsHover(t[0]))return void this.rehover(e,t)}if(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,s=this.toCallerFeatures(t,i);for(const o of e){const e=this.callerFeaturesFor(o,t,i,s);o.handler(e[0],this.hoveringLngLat,e,o.sourceWithLayers)}}}}claimsHover(e){const t=this.hoveringFeature;if(!e||!t)return e===t;const i=renderedRefId(e);return e.source===t.source&&(void 0===i?e.layer.id===t.layer.id:i===renderedRefId(t))&&this.claimingHandler(e)?.sourceWithLayers===this.hoveringSourceWithLayers}claimingHandler(e){return this.findHandlers(interactiveEventTypes,e.layer.id,e)[0]}rehover(e,t){const i=this.hoveringFeature,s=this.hoveringSourceWithLayers;this.hoveringFeatures=t,this.hoveringFeature=t[0],this.dispatchHoverEnter(e,i,s),this.restartLongHoverTimeout()}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}onPressStart(e){if(this.onPressEnd(),this.dragJustEnded=!1,!this.isEnabled()||!this.hasHandlersOf(dragEventTypes))return!1;const t=this.getRenderedFeatures(e.point),[i]=t;return!(!i||!this.findHandlers(dragEventTypes,i.layer.id,i).length||(e.preventDefault(),this.press={feature:i,rendered:t,startPoint:e.point,lngLat:e.lngLat},0))}onPressMove(e){const t=this.press;if(!t)return;t.lngLat=e.lngLat;let{callerFeatures:i}=t;if(!i){const{x:s,y:o}=t.startPoint;if(Math.hypot(e.point.x-s,e.point.y-o)<3)return;this.clearLongHoverTimeout(),i=this.toCallerFeatures(t.rendered,t.feature),t.callerFeatures=i,this.dispatchDrag("dragstart",t,i)}this.dispatchDrag("drag",t,i)}onPressEnd(e){const t=this.press;t&&(this.press=void 0,this.mapCanvas.ownerDocument.removeEventListener("mouseup",this.onReleaseOutside),t.callerFeatures&&(this.dragJustEnded=!0,this.hoverStaleAfterDrag=!0,t.lngLat=e??t.lngLat,this.dispatchDrag("dragend",t,t.callerFeatures)))}dispatchDrag(e,t,i){for(const s of this.findHandlers([e],t.feature.layer.id)){const e=this.callerFeaturesFor(s,t.rendered,t.feature,i);s.handler(e[0],t.lngLat,e,s.sourceWithLayers)}}onMouseMove(e){this.onPressMove(e),this.press?.callerFeatures||(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()||this.press?.callerFeatures)return;this.lastHandledMouseMove=e,this.hoveringFeatures=this.getRenderedFeatures(e.point);const[t]=this.hoveringFeatures;if(t&&!this.hasHandlerForLayer(t.layer.id))return;const i=((e,t,i,s,o)=>{if(t){if(!s)return{hoverChanged:!0};if(!isSameRenderedFeature(t,s)||t.layer.id!==s.layer.id&&(void 0===renderedRefId(t)||!o?.(t,s)))return{hoverChanged:!0};if(i&&(e.x-i.x!=0||e.y-i.y!=0))return{mouseInMotionOverHoveredFeature:!0}}else if(s)return{hoverChanged:!0};return{}})(e.point,t,this.hoveringPoint,this.hoveringFeature,this.sameClaim),s=i.hoverChanged||this.hoverStaleAfterDrag,{mouseInMotionOverHoveredFeature:o}=i;if(this.hoverStaleAfterDrag=!1,!s&&!o)return;const r=!s&&!this.claimsHover(t),a=this.hoveringFeature,n=this.hoveringSourceWithLayers;let l;this.hoveringLngLat=e.lngLat,this.hoveringPoint=e.point,this.hoveringFeature=t,(s||r)&&(l=this.dispatchHoverEnter(e,a,n)),o&&this.dispatchHoverMove(e,l),this.restartLongHoverTimeout()}dispatchHoverEnter(e,t,i){const s=this.hoveringFeature?.layer.id,o=this.findHandlers(interactiveEventTypes,s,this.hoveringFeature)?.[0];this.hoveringSourceWithLayers=o?.sourceWithLayers,this.updateHoverCursor(o,this.hoveringFeature);const r=t?this.hoverGracePeriodFor(t):0;updateEventState("hover",this.hoveringFeature,t,this.hoveringSourceWithLayers,i,r>0),t&&r>0&&this.clearRecentHoverLater(t,i,r);const a=this.findHandlers(["hover"],s);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 s=this.hoveringFeature,o=t??this.toCallerFeatures(this.hoveringFeatures??noRenderedFeatures,s);this.dispatchToHandlers(i,e,s,o)}dispatchToHandlers(e,t,i,s){for(const o of e){const e=this.callerFeaturesFor(o,this.hoveringFeatures??noRenderedFeatures,i,s);o.handler(e[0],t.lngLat,e,o.sourceWithLayers)}}hoverGracePeriodFor(e){return this.claimingHandler(e)?.config?.()?.hoverGracePeriodMS??this.config.hoverGracePeriodMS}clearRecentHoverLater(e,t,i){const s=shownRefId(e);if(void 0===s)return;const o=`${e.source} ${s}`,r=e.layer.id;clearTimeout(this.recentHovers.get(o)?.timeout);const a=setTimeout(()=>{const e=this.recentHovers.get(o)?.sourceWithLayers;this.recentHovers.delete(o);const t=this.sourceWithLayersFor(r)??e;t&&((e,t)=>{if(e instanceof CustomLayerSourceWithLayers)return void("recently-hovered"===e.eventStateOf(t)&&e.putEventState(t,void 0));if(!(e instanceof GeoJSONSourceWithLayers))return;const i=e.findById(t);"recently-hovered"===i?.feature.properties?.eventState&&e.clearEventState({index:i.index})})(t,s)},i);this.recentHovers.set(o,{timeout:a,sourceWithLayers:t})}updateHoverCursor(e,t){if(!e||!t)return void(this.mapCanvas.style.cursor=this.config.cursorOnMap);const i=this.findHandlers(dragEventTypes,t.layer.id,t)[0];this.mapCanvas.style.cursor=i?i.config?.()?.cursorOnDraggable??this.config.cursorOnDraggable:e.config?.()?.cursorOnHover??this.config.cursorOnHover}onMapClick(e,t){if("click"===e&&this.dragJustEnded)return void(this.dragJustEnded=!1);if(!this.isEnabled())return;const i=this.getRenderedFeatures(t.point),s=this.lastClickedFeature;this.lastClickedFeature=i[0];const o=this.lastClickedSourceWithLayers,r=this.findHandlers([e],this.lastClickedFeature?.layer.id);if(this.lastClickedSourceWithLayers=this.findHandlers([e],this.lastClickedFeature?.layer.id,this.lastClickedFeature)[0]?.sourceWithLayers,updateEventState(e,this.lastClickedFeature,s,this.lastClickedSourceWithLayers,o),r.length){const e=this.lastClickedFeature,s=this.toCallerFeatures(i,e);for(const o of r){const r=this.callerFeaturesFor(o,i,e,s);o.handler(r[0],t.lngLat,r,o.sourceWithLayers)}}}},labelFields={ngt:"name","ngt-Latn":"name_ngt-Latn",ar:"name_ar","eu-ES":"name_eu","bg-BG":"name_bg","ca-ES":"name_ca","zh-Hant":"name_zh-Hant","zh-Hans":"name_zh-Hans","hr-HR":"name_hr","cs-CZ":"name_cs","da-DK":"name_da","nl-NL":"name_nl","en-AU":"name_en","en-CA":"name_en","en-GB":"name_en","en-NZ":"name_en","en-US":"name_en","et-EE":"name_et","fi-FI":"name_fi","fr-FR":"name_fr","gl-ES":"name_gl","de-DE":"name_de","el-GR":"name_el","he-IL":"name_he","hi-IN":"name_hi","hu-HU":"name_hu","id-ID":"name_id","it-IT":"name_it","ja-JP":"name_ja","kk-KZ":"name_kk","ko-KR":"name_ko","ko-Latn-KR":"name_ko-Latn","lv-LV":"name_lv","lt-LT":"name_lt","ms-MY":"name_ms","nb-NO":"name_no","pl-PL":"name_pl","pt-BR":"name_pt","pt-PT":"name_pt","ro-RO":"name_ro","ru-RU":"name_ru","ru-Latn-RU":"name_ru-Latn","ru-Cyrl-RU":"name_ru","sr-RS":"name_sr","sk-SK":"name_sk","sl-SI":"name_sl","es-ES":"name_es","es-MX":"name_es","sv-SE":"name_sv","th-TH":"name_th","tr-TR":"name_tr","uk-UA":"name_uk"},TomTomMapError=class extends Error{constructor(e,t){super(e,"cause"in t?{cause:t.cause}:void 0),this.sdkVersion="1.0.0-rc.4",this.name="TomTomMapError",this.code=t.code,this.canRetry=canRetrySDKErrorCode(t.code),this.status=t.status,this.sourceId=t.sourceId}},FETCH_FAILURE_MESSAGES=/^(Failed to fetch|NetworkError when attempting to fetch resource\.|Load failed)$/,addHandler=(e,t)=>{e.push(t);let i=!1;return()=>{if(i)return;i=!0;const s=e.indexOf(t);-1!==s&&e.splice(s,1)}},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 _styleKnobSettings(){return this.styleKnobSettings}_setStyleKnobSettings(e,t){if(this.styleKnobSettings=e,t.size)for(const i of this.styleKnobsAppliedHandlers)i(t)}_onStyleKnobsApplied(e){this.styleKnobsAppliedHandlers.push(e)}constructor(e){if(this.mapReady=!1,this._mapColors={},this.mapColorsHandlers=[],this.styleKnobSettings={},this.styleKnobsAppliedHandlers=[],this.styleChangeHandlers=[],this.errorHandlers=[],this.styleLoadFailureHandlers=[],this.vectorTilesReloadPending=!1,this.incidentTilesReloadPending=!1,this.styleRequestSequence=0,this.styleLayerIds=/* @__PURE__ */new Set,this.styleLoads=0,this.firstStyleUnfinished=!1,this.setStyle=(e,t={})=>{const i={resetState:t.resetState??!1};this.mapReady=!1,this.styleLoadError=void 0;const s=++this.styleRequestSequence,o=i.resetState?e:((e,t)=>{const i="object"==typeof t?t.include:void 0;return i?"string"==typeof e?{type:"standard",id:e,include:i}:e.include?e:{...e,include:i}:e})(e,this._params.style);return this._params={...this._params,style:o},this._styleLightDarkTheme=getStyleLightDarkTheme(o),this.applyStyle(i,s)},this.getStyleInput=()=>this._params.style??"streetLight",this._params=mergeFromGlobal(e),!isSecureBaseURL(this._params.commonBaseURL))throw new TomTomMapError(insecureBaseURLMessage(this._params.commonBaseURL),{code:"INSECURE_BASE_URL"});void 0===this._params.style&&(this._params={...this._params,style:"streetLight"}),this._styleLightDarkTheme=getStyleLightDarkTheme(this._params.style);const t=loading||"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})()?loading:loading=import("./chunks/maplibre-gl-DudBHU-O.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)).catch(e=>console.error("Could not apply the MapLibre CSS",e)).finally(()=>{loading=void 0});!1!==this._params.registerMapLibreWorker&&(()=>{if("undefined"==typeof Worker||getWorkerUrl())return;const e=(()=>{try{const e=(()=>{const e=globalThis.Worker;let t;globalThis.Worker=new Proxy(e,{construct:(e,[i,s])=>(t={url:String(i),type:s?.type},{})});try{new Worker(new URL("./chunks/maplibre-gl-worker.js",import.meta.url),{type:"module"})}finally{globalThis.Worker=e}return t})(),t=import.meta.url;return"module"===e?.type&&e.url!==new URL("./chunks/maplibre-gl-worker.js",t).href?e.url:void 0}catch{return}})();e&&setWorkerUrl(e)})(),setWorkerCount(4),this.styleGivenToMapLibre=buildStyleInput(this._params);try{this.mapLibreMap=new Map$1({validateStyle:!1,maxTileCacheZoomLevels:22,cancelPendingTileRequestsWhileZooming:!1,...(i=this._params).mapLibre,style:buildStyleInput(i),attributionControl:{compact:!1,customAttribution:i.attribution?.credits?.slice()},transformRequest:transformRequest(i)})}catch(s){throw s instanceof Error&&"GPUInitializationError"===s.name?new TomTomMapError(s.message,{code:"WEBGL_UNSUPPORTED",cause:s}):s}var i;t?.then(()=>this.fitCanvasToContainer()),this.mapLibreMap.on("error",e=>{const t=!this.mapReady&&!("sourceId"in e),i=((e,t)=>{const i=e.error,s="status"in i&&"number"==typeof i.status?i.status:void 0,o=s||void 0,r="sourceId"in e&&"string"==typeof e.sourceId?e.sourceId:void 0;let a=t;return o?a=sdkErrorCodeForStatus(o):(0===s||FETCH_FAILURE_MESSAGES.test(i.message))&&(a="NETWORK_NOT_AVAILABLE"),new TomTomMapError(i.message,{code:a,status:o,sourceId:r,cause:i})})(e,t?"STYLE_LOAD_FAILED":"INTERNAL");this.notifyErrorHandlers(i),t&&this.failStyleLoadInFlight?.(i)}),this.mapLibreMap.on("webglcontextlost",e=>this.notifyErrorHandlers(new TomTomMapError("The browser lost the WebGL context the map draws with.",{code:"WEBGL_CONTEXT_LOST",cause:e.originalEvent}))),this.moduleSourcesAndLayers=ModuleSourcesAndLayers.for(this.mapLibreMap),this.styleLoadInFlight=this.initialStyleLoad(),this._eventsProxy=new EventsProxy(this.mapLibreMap,this._params?.events)}initialStyleLoad(){return new Promise(e=>this.onStyleLoadSettled(()=>{this.styleRequestSequence?this.firstStyleUnfinished=!0:this.handleStyleData(),e()},t=>{this.styleGivenToMapLibre=void 0,this.styleRequestSequence||this.failStyleLoad(t),e()}))}onStyleLoadSettled(e,t){const i=()=>{this.failStyleLoadInFlight=void 0,this.recordStyleLayers(),e()};this.failStyleLoadInFlight=e=>{this.failStyleLoadInFlight=void 0,this.mapLibreMap.off("style.load",i),t(e)},this.mapLibreMap.once("style.load",i)}failStyleLoad(e){this.styleLoadError=e;for(const t of this.styleLoadFailureHandlers.slice())t(e)}get _styleLoadError(){return this.styleLoadError}_onStyleLoadFailure(e){return addHandler(this.styleLoadFailureHandlers,e)}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(!e.resetState);this.styleLoadInFlight=i;try{await i}catch(s){if(!this.isSuperseded(t))throw this.firstStyleUnfinished?await this.handleStyleData():s instanceof TomTomMapError&&this.failStyleLoad(s),s}finally{this.styleLoadInFlight===i&&(this.styleLoadInFlight=void 0)}if(!this.isSuperseded(t)){try{await this.handleStyleData(e)}catch(s){console.error(s)}this.isSuperseded(t)||this.moduleSourcesAndLayers.dropUnadopted()}}async loadIntoMapLibre(e){const t=buildStyleInput(this._params);if(t===this.styleGivenToMapLibre)return;const i=this.styleGivenToMapLibre;this.styleGivenToMapLibre=t,await new Promise((s,o)=>{this.onStyleLoadSettled(s,e=>{this.styleGivenToMapLibre=i,o(e)}),this.mapLibreMap.setStyle(t,void 0===i?{validate:!1,diff:!1}:{validate:!1,transformStyle:(t,i)=>this.moduleSourcesAndLayers.carryInto(e?t:void 0,i)})})}isSuperseded(e){return e!==this.styleRequestSequence}fitCanvasToContainer(){if(this.mapLibreMap._removed)return;const e=this.mapLibreMap.getCanvas(),t=this.mapLibreMap.getContainer();e.clientWidth===t.clientWidth&&e.clientHeight===t.clientHeight||this.mapLibreMap.resize()}recordStyleLayers(){this.styleLoads++,this.styleLayerIds=new Set(this.mapLibreMap.getStyle().layers.map(e=>e.id).filter(e=>!this.moduleSourcesAndLayers.isCarried(e)))}_isStyleLayer(e){return this.styleLayerIds.has(e)}get _styleLoads(){return this.styleLoads}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(s){console.error(s)}}_setTomTomUserAgent(e){this._updateRequestParams({"tomtom-user-agent":e})}_updateRequestParams(e){this._params={...this._params,...e},this.mapLibreMap.setTransformRequest(transformRequest(this._params))}_setLanguage(e){const t=(e=>{const t=labelFields[e]??`name_${e.split("-")[0]}`;return"name"===t?["get","name"]:["coalesce",["get",t],["get","name"]]})(e);this.mapLibreMap.getStyle().layers.forEach(e=>{"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)&&this.mapLibreMap.setLayoutProperty(e.id,"text-field",t,{validate:!1})})}setLanguage(e){const t=trafficIncidentLanguage(this._params.language)!==trafficIncidentLanguage(e);this._updateRequestParams({language:e}),this.applyLanguage(t)}applyLanguage(e){this.mapReady?(this._params.language&&this._setLanguage(this._params.language),e&&reloadTiles(this.mapLibreMap,["vectorTilesIncidents"])):this.incidentTilesReloadPending||=e}setGeopoliticalView(e){this._updateRequestParams({geopoliticalView:e}),this.reloadVectorTiles()}reloadVectorTiles(){this.mapReady?reloadTiles(this.mapLibreMap,vectorTileSourceIds(this.mapLibreMap)):this.vectorTilesReloadPending=!0}updateEventsConfig(e){this._eventsProxy.updateConfig(e)}getBBox(){const[[e,t],[i,s]]=this.mapLibreMap.getBounds().toArray();return[e,t,i,s]}async handleStyleData(e){this.firstStyleUnfinished=!1;for(const t of filterLayersBySources(this.mapLibreMap,["vectorTilesIncidents","vectorTilesFlow","hillshade"]))this.mapLibreMap.setLayoutProperty(t.id,"visibility","none",{validate:!1});(e=>{const t=baseMapLayerGroupSelector("buildings3D");for(const i of e.getStyle().layers)"fill-extrusion"===i.type&&matchesLayerSelector(t,i)&&void 0===i.layout?.["fill-extrusion-rounded-corner-distance"]&&e.setLayoutProperty(i.id,"fill-extrusion-rounded-corner-distance",1,{validate:!1})})(this.mapLibreMap),((e,t,i)=>{const s=pendingPinCategoriesSprites.get(i);if(s&&(i.off("styledata",s),pendingPinCategoriesSprites.delete(i)),i.getSprite().some(e=>"pinCategories"===e.id))return;const o=new URLSearchParams;setApiKeyParameter(o,e.apiKey),o.set("poi",`poi_${t}`),o.set("apiVersion","1"),o.set("apiChannel","preview");const r=()=>i.addSprite("pinCategories",`${e.commonBaseURL}/maps/orbis/assets/sprites/2.*/sprite?${o}`,{validate:!1});if(i.style.imageManager.isLoaded())return void r();const a=()=>{i.style.imageManager.isLoaded()&&(i.off("styledata",a),pendingPinCategoriesSprites.delete(i),r())};pendingPinCategoriesSprites.set(i,a),i.on("styledata",a)})(this._params,this._styleLightDarkTheme,this.mapLibreMap),this._params.language&&this._setLanguage(this._params.language),this.mapReady=!0,this.runPendingTileReloads(),e&&await this.notifyHandlers("onStyleChanged",e)}runPendingTileReloads(){const e=[...this.vectorTilesReloadPending?vectorTileSourceIds(this.mapLibreMap):[],...this.incidentTilesReloadPending?["vectorTilesIncidents"]:[]];this.vectorTilesReloadPending=!1,this.incidentTilesReloadPending=!1,reloadTiles(this.mapLibreMap,e)}addStyleChangeHandler(e){return addHandler(this.styleChangeHandlers,e)}addCustomLayer(e,t={}){return new CustomLayer(this,e,t)}addErrorHandler(e){return addHandler(this.errorHandlers,e)}notifyErrorHandlers(e){if(this.errorHandlers.length)for(const t of this.errorHandlers.slice())t(e);else console.error(e)}},terrainKnobCatalogue=/* @__PURE__ */withIds({"hillshade.visible":{kind:"toggle",description:"The hillshade: light and shadow on the map surface that reveal the relief at any pitch.",default:!1},"hillshade.method":{kind:"enum",description:"How the relief is shaded: standard (one light), basic, igor (softer), combined, or multidirectional (four lights fanned over 135° around `hillshade.light.direction`).",options:hillshadeMethods},"hillshade.light.direction":{kind:"number",description:"Direction the light comes from, in degrees clockwise from the top of the screen, or from north with `hillshade.light.alignment` at `map` (335 is the cartographic default).",range:{min:0,max:359,step:1,bounds:"hard"}},"hillshade.light.altitude":{kind:"number",description:"Height of the light above the horizon, in degrees (0 = sunset, 90 = noon); lower casts longer shadows. Used by the basic, combined and multidirectional methods.",range:{min:0,max:90,step:1,bounds:"hard"}},"hillshade.light.alignment":{kind:"enum",description:"What `hillshade.light.direction` is measured from: viewport (the top of the screen, turning with the camera) or map (north, staying on the same slopes as the map rotates).",options:hillshadeLightAlignments},"hillshade.intensity":{kind:"number",description:"Strength of the shading (0 = flat); it raises nothing. 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"}},"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"}},"hillshade.colors.shaded":{kind:"color",description:"Colour of the slopes facing away from the light."},"hillshade.colors.lit":{kind:"color",description:"Colour of the slopes facing the light."},"hillshade.colors.steep":{kind:"color",description:"Colour accentuating the steepest terrain."},"elevation.visible":{kind:"toggle",description:"The 3D surface, raised to the elevation data or flattened. Unset: flat, unless MapLibre code raised a terrain of its own."},"elevation.exaggeration":{kind:"number",description:"Vertical scale of the 3D surface, `1` being true elevation; kept while `elevation.visible` is off.",range:{min:.5,max:3,step:.1,bounds:"hard-min"},default:1}}),terrainKnobIds=/* @__PURE__ */terrainKnobCatalogue.map(({id:e})=>e),TerrainModule=class TerrainModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,TerrainModule,()=>new TerrainModule(e,t),t,{sourceId:"hillshade",part:"terrain"})}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const e=styleSourceWithLayers(this.mapLibreMap,"hillshade",TerrainModule.name),t=this.mapLibreMap.getTerrain();return"hillshade-terrain"!==t?.source&&(this.mapTerrain=t),{hillshade:e}}_applyConfig(e){return this.showHillshade(e?.hillshade?.visible??!1),hillshadeLook.apply(this.tomtomMap,e),this.showElevation(e?.elevation?.visible,e?.elevation?.exaggeration??1),e}_knobValue(e){return super._knobValue(e)??hillshadeLook.valueOf(this.tomtomMap,e)}setHillshadeVisible(e){this.showHillshade(e),this.storeConfig({hillshade:{...this.config?.hillshade,visible:e}})}isHillshadeVisible(){return this.config?.hillshade?.visible??!1}setElevationVisible(e){this.showElevation(e,this.config?.elevation?.exaggeration??1),this.storeConfig({elevation:{...this.config?.elevation,visible:e}})}isElevationVisible(){return this.config?.elevation?.visible??null!==this.mapLibreMap.getTerrain()}get events(){return this.lifecycleEvents()}showHillshade(e){this.tomtomMap.mapReady&&this.sourcesWithLayers.hillshade.setLayersVisibleThrough(this.visibilityComposer,"terrain.hillshade.visible",e)}showElevation(e,t){this.tomtomMap.mapReady&&(void 0===e?this.overridesMapTerrain&&this.setMapTerrain(this.mapTerrain):e?(new TomTomMapSource("hillshade-terrain",this.sourcesWithLayers.hillshade.source.spec).ensureAddedToMap(this.mapLibreMap),this.setMapTerrain({source:"hillshade-terrain",exaggeration:t})):this.setMapTerrain(null),this.overridesMapTerrain=void 0!==e)}setMapTerrain(e){isEqual(this.mapLibreMap.getTerrain(),e)||this.mapLibreMap.setTerrain(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",metrics:{congestionLevel:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},speed:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},travelTime:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},freeFlowSpeed:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},networkLength:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"currentRange"}}},regionPolygon:{fill:{style:"filled",opacity:0},line:{opacity:.5,width:2}}},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}},paletteScaleMode=e=>"networkLength"===e?"currentRange":"predefinedRange",getActiveMetric=e=>e?.activeMetric??AREA_ANALYTICS_DEFAULTS.activeMetric,resolveColorStops=(e,t)=>{if(t?.colorStops?.stops.length)return t.colorStops;const i=PALETTE_COLORS[t?.palette??"trafficLight"],s=(e=>"speed"===e||"freeFlowSpeed"===e)(e)?[...i].reverse():i;return{scaleMode:paletteScaleMode(e),stops:s.map((e,t)=>({value:t/(s.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]),interpolationStops=e=>[...e].sort(([e],[t])=>e-t).filter(([e],t,i)=>i[t+1]?.[0]!==e).flat(),metricRange=(e,t,i)=>"currentRange"===t?i??DEFAULT_METRIC_RANGES[e]:DEFAULT_METRIC_RANGES[e],buildColorExpression$1=(e,t,i)=>{const{scaleMode:s,stops:o}=resolveColorStops(e,t);let r;if("predefinedRange"===s||"currentRange"===s){const{min:t,max:a}=metricRange(e,s,i);r=o.map(({value:e,color:i})=>[t+e/100*(a-t),i])}else r=o.map(({value:e,color:t})=>[e,t]);return["interpolate",["linear"],["get",e],...interpolationStops(r)]},buildHeatmapColorExpression=(e,t)=>{const{scaleMode:i,stops:s}=resolveColorStops(e,t);let o;if("predefinedRange"===i||"currentRange"===i)o=s.map(({value:e,color:t})=>[.3+e/100*.7,t]);else{const e=Math.min(...s.map(e=>e.value)),t=Math.max(...s.map(e=>e.value))-e||1;o=s.map(({value:i,color:s})=>[.3+(i-e)/t*.7,s])}return["interpolate",["linear"],["heatmap-density"],0,"rgba(0,0,0,0)",...interpolationStops(o)]},buildHeightExpression=(e,t,i)=>{const s=AREA_ANALYTICS_DEFAULTS.metrics[e].height,o=t?.minMeters??s.minMeters,r=["coalesce",["get",e],0];if("raw"===t?.scaleMode){const i=t.metersPerUnit??1;return["max",o,["*","speed"===e?["-",DEFAULT_METRIC_RANGES.speed.max,r]:r,i]]}const a=t?.maxMeters??s.maxMeters,n=t?.scaleMode??s.scaleMode,{min:l,max:c}=metricRange(e,n,i);return["max",o,["min",a,["*",["/","speed"===e?["-",c,r]:["-",r,l],c-l||1],a]]]},buildHeatmapLayerSpec=(e,t,i)=>{const s=getActiveMetric(t),o=t?.metrics?.[s],{min:r,max:a}=i??DEFAULT_METRIC_RANGES[s],n=r+(a-r||1);return mergeLayerOverride({id:e,type:"heatmap",beforeID:beforeIDOf(t,"heatmap"),paint:{"heatmap-weight":["interpolate",["linear"],["get",s],r,0,n,1],"heatmap-intensity":/* @__PURE__ */zoomRamp(10,.5,14,2,16,4),"heatmap-color":buildHeatmapColorExpression(s,o),"heatmap-radius":/* @__PURE__ */zoomRamp(4,1,8,3,12,35,14,80,16,100),"heatmap-opacity":/* @__PURE__ */zoomRamp(4,.8,13,.8,17,0)}},t?.layers?.heatmap)},buildCellFillLayerSpec=(e,t,i,s,o)=>{const r=getActiveMetric(t);return mergeLayerOverride({id:e,type:"fill",beforeID:beforeIDOf(t,s),paint:{"fill-color":buildColorExpression$1(r,t?.metrics?.[r],i),"fill-opacity":.6}},o)},buildCellExtrusionLayerSpec=(e,t,i,s,o)=>{const r=getActiveMetric(t),a=t?.metrics?.[r];return mergeLayerOverride({id:e,type:"fill-extrusion",beforeID:beforeIDOf(t,s),paint:{"fill-extrusion-color":buildColorExpression$1(r,a,i),"fill-extrusion-height":buildHeightExpression(r,a?.height,i),"fill-extrusion-base":0,"fill-extrusion-opacity":.75}},o)},buildHexFillLayerSpec=(e,t,i)=>buildCellFillLayerSpec(e,t,i,"hexgrid-2d",t?.layers?.hexgridFill),buildHexExtrusionLayerSpec=(e,t,i)=>buildCellExtrusionLayerSpec(e,t,i,"hexgrid-3d",t?.layers?.hexgridExtrusion),buildSquareFillLayerSpec=(e,t,i)=>buildCellFillLayerSpec(e,t,i,"square-2d",t?.layers?.squareFill),buildSquareExtrusionLayerSpec=(e,t,i)=>buildCellExtrusionLayerSpec(e,t,i,"square-3d",t?.layers?.squareExtrusion),resolveRegionConfig=e=>{const t=AREA_ANALYTICS_DEFAULTS.regionPolygon;return{color:e?.color,fill:{opacity:e?.fill?.opacity??t.fill.opacity},line:{opacity:e?.line?.opacity??t.line.opacity,width:e?.line?.width??t.line.width}}},buildRegionFillLayerSpec=(e,t,i)=>{const{color:s,fill:o}=resolveRegionConfig(t?.regionPolygon);return mergeLayerOverride({id:e,type:"fill",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"fill-color":s??themeContrastColor(i),"fill-opacity":o.opacity}},t?.layers?.regionFill)},buildRegionLineLayerSpec=(e,t,i)=>{const{color:s,line:o}=resolveRegionConfig(t?.regionPolygon);return mergeLayerOverride({id:e,type:"line",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"line-color":s??themeContrastColor(i),"line-opacity":o.opacity,"line-width":o.width}},t?.layers?.regionLine)},activeEventStateWithin=e=>e?["all",toExpressionFilter(e),hasActiveEventState]:hasActiveEventState,buildPolygonOutlineLayerSpec=(e,t,i,s)=>mergeLayerOverride({id:e,type:"line",beforeID:t,filter:activeEventStateWithin(i),paint:{"line-color":"#ffffff","line-width":["case",isClickEventState,3,2],"line-opacity":["case",isClickEventState,1,.8]}},s),buildHexOutlineLayerSpec=(e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"hexgrid-2d"),t?.layers?.hexgridFill?.filter,t?.layers?.hexgridOutline),buildSquareOutlineLayerSpec=(e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"square-2d"),t?.layers?.squareFill?.filter,t?.layers?.squareOutline),buildExtrusionHighlightLayerSpec=(e,t)=>{const i=e.paint?.["fill-extrusion-height"];return mergeLayerOverride({...e,filter:activeEventStateWithin(e.filter),paint:{...e.paint,"fill-extrusion-color":"#ffffff","fill-extrusion-height":(s=i,mapNumericValue(s,e=>e+.5,e=>["+",e,.5])??i),"fill-extrusion-opacity":.6}},t);var s},buildHexExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildHexExtrusionLayerSpec(e,t,i),t?.layers?.hexgridExtrusionHighlight),buildSquareExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildSquareExtrusionLayerSpec(e,t,i),t?.layers?.squareExtrusionHighlight),INCIDENT_HIGHLIGHT_WIDTH_FACTOR_RANGE={min:1,max:1.8,step:.1,bounds:"hard"},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],buildColorExpression=e=>/* @__PURE__ */matchMagnitudeOfDelay({...e,fallback:e.major}),INNER_PATTERN=["match",["get","magnitudeOfDelay"],"unknown","traffic-incidents-no_delay-pattern","indefinite","traffic-incidents-road_closed-pattern",""],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],isUnfocused=["all",["==",["feature-state","focused"],!1],["!",hasActiveEventState]],haloOpacity=["case",isFocusedOrActive,1,0],highlightWidth=(e,t)=>null===t?e:scaledWhen(isFocusedOrActive,e,t),unfocusedScaled=(e,t)=>scaledWhen(isUnfocused,e,t),buildCanonicalIncidentLineLayers=(e,t,i,s,o,r)=>{const a=s?.widthFactor??null,n=s?.unfocusedOpacityFactor??1,l=(void 0!==r?.opacity||1!==n)&&{"line-opacity":unfocusedScaled(r?.opacity??1,n)},c=[];return null!==s&&c.push(mergeLayerOverride({id:`${e}-highlight-halo`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":s.outlineColor,"line-width":HALO_WIDTH,"line-blur":0,"line-opacity":haloOpacity},beforeID:t},o?.highlightHalo)),c.push(mergeLayerOverride({id:`${e}-outline`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpression(i.outline),"line-width":highlightWidth(OUTLINE_WIDTH,a),...l},beforeID:t},o?.outline),mergeLayerOverride({id:`${e}-inner-solid`,type:"line",minzoom:6,filter:severitySolidFilter,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpression(i.inner),"line-width":highlightWidth(INNER_WIDTH,a),...l},beforeID:t},o?.innerSolid),mergeLayerOverride({id:`${e}-inner-chevron`,type:"line",minzoom:12,filter:severitySolidFilter,layout:{"line-cap":"butt","line-join":"round"},paint:{"line-pattern":"tt-traffic-incident-direction-chevron","line-width":highlightWidth(INNER_WIDTH,a),...l},beforeID:t},o?.innerChevron),mergeLayerOverride({id:`${e}-inner-pattern`,type:"line",minzoom:6,filter:severityDashedFilter,layout:{"line-cap":"round","line-join":"round"},paint:{"line-pattern":INNER_PATTERN,"line-width":highlightWidth(INNER_WIDTH,a),...l},beforeID:t},o?.innerPattern)),c},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"],["!=",["get","delayInSeconds"],0],["step",["zoom"],[">",["get","delayInSeconds"],900],13,[">",["get","delayInSeconds"],600],14,[">",["get","delayInSeconds"],300],15,!0]],CLOSED_ROAD_FILTER=["==",["get","magnitudeOfDelay"],"indefinite"],DELAY_MINUTES=["round",["/",["to-number",["get","delayInSeconds"]],60]],JAM_ICON=["concat","traffic-jam-",["get","magnitudeOfDelay"],["case",["any",["<",DELAY_MINUTES,10],["==",["%",DELAY_MINUTES,60],0]],"-small",["<",DELAY_MINUTES,60],"-medium","-large"]],JAM_TEXT=["case",["<=",["get","delayInSeconds"],60],"1 min",[">=",DELAY_MINUTES,60],["concat",["to-string",["floor",["/",DELAY_MINUTES,60]]]," hr",["case",["==",["%",DELAY_MINUTES,60],0],"",["concat"," ",["to-string",["%",DELAY_MINUTES,60]]," min"]]],["concat",["to-string",DELAY_MINUTES]," min"]],SORT_KEY=["case",["has","delayInSeconds"],["*",-1,["get","delayInSeconds"]],0],buildCanonicalIncidentSymbolLayers=(e,t,i,s,o=1)=>{const r=unfocusedScaled(1,o),a=1!==o&&{"icon-opacity":r},n=1!==o&&{"text-opacity":r};return[mergeLayerOverride({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},...a&&{paint:a},beforeID:t},i?.incidentMarker),mergeLayerOverride({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":inTypeface(["NotoSans-CondensedBold"],s),"text-offset":[2.7,-.75],"text-size":JAM_TEXT_SIZE,"symbol-sort-key":SORT_KEY},paint:{"text-color":"hsl(210, 30%, 14%)",...a,...n},beforeID:t},i?.jamMarker),mergeLayerOverride({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},...a&&{paint:a},beforeID:t},i?.closedRoadMarker)]},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"},DELAY_MINUTES_RANGE={min:0,max:120,step:5,bounds:"hard-min"},roadCategoriesFilter=/* @__PURE__ */valuesFilterKnobs("filters.roadCategories","road categories",roadCategories),roadSubCategoriesFilter=/* @__PURE__ */(()=>/* @__PURE__ */valuesFilterKnobs("filters.roadSubCategories","street and service road kinds",[...streetRoadSubCategories,...serviceRoadSubCategories]))(),roadFilterKnobDefinitions=/* @__PURE__ */(()=>({"filters.roadCategories.show":roadCategoriesFilter.show,"filters.roadCategories.values":roadCategoriesFilter.values,"filters.roadSubCategories.show":roadSubCategoriesFilter.show,"filters.roadSubCategories.values":roadSubCategoriesFilter.values}))(),incidentCategoriesFilter=/* @__PURE__ */valuesFilterKnobs("filters.incidentCategories","incident categories",fullTrafficIncidentCategories),magnitudesFilter=/* @__PURE__ */(()=>/* @__PURE__ */valuesFilterKnobs("filters.magnitudes","delay magnitudes",/* @__PURE__ */everyOf()(["unknown","minor","moderate","major","indefinite"])))(),flowKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"The traffic flow lines; hidden until shown.",default:!1},...roadFilterKnobDefinitions,"filters.roadClosures":{kind:"enum",description:"`only` draws just the closed roads, `all-except` the flow on every road but them.",options:filterShowModes},"colors.free":{kind:"color",description:"Flow colour of free-flowing roads; its outline follows."},"colors.slow":{kind:"color",description:"Flow colour of slow traffic; its outline follows."},"colors.queueing":{kind:"color",description:"Flow colour of queueing traffic; its outline follows."},"colors.stationary":{kind:"color",description:"Flow colour of stationary traffic; its outline follows."},"colors.closed":{kind:"color",description:"Outline colour of closed roads."},widthFactor:{kind:"factor",description:"Width of the flow lines.",range:WIDE_FACTOR_RANGE,default:1},opacityFactor:{kind:"factor",description:"Opacity of the flow lines and their outlines, over the style's own.",range:OPACITY_RANGE,default:1}}))(),incidentsKnobDefinitions=/* @__PURE__ */(()=>({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`."},timeValidity:{kind:"enums",description:"Which incidents the tiles bring: `present` ones under way, `future` ones planned. A change reloads the incident tiles.",options:trafficIncidentTimeValidities,default:["present"]},...roadFilterKnobDefinitions,"filters.incidentCategories.show":incidentCategoriesFilter.show,"filters.incidentCategories.values":incidentCategoriesFilter.values,"filters.magnitudes.show":magnitudesFilter.show,"filters.magnitudes.values":magnitudesFilter.values,"filters.delays.required":{kind:"toggle",description:"Drop the incidents that report no delay.",default:!1},"filters.delays.minMinutes":{kind:"number",description:"Drop the incidents delaying traffic by less than this many minutes; those that report no delay stay unless `filters.delays.required`.",range:DELAY_MINUTES_RANGE},"colors.minor":{kind:"color",description:"Incident line colour for minor delays; its outline follows."},"colors.moderate":{kind:"color",description:"Incident line colour for moderate delays; its outline follows."},"colors.major":{kind:"color",description:"Incident line colour for major delays; its outline follows."},"colors.closed":{kind:"color",description:"Incident outline colour for closed roads."},widthFactor:{kind:"factor",description:"Width of the incident lines.",range:WIDE_FACTOR_RANGE,default:1},opacityFactor:{kind:"factor",description:"Opacity of the incident lines and their outlines, over the style's own; the icons stay opaque.",range:OPACITY_RANGE,default:1}}))(),incidentDetailsKnobDefinitions={visible:{kind:"toggle",description:"The incident layers; hiding them keeps the shown incidents.",default:!0},"highlight.outline.color":{kind:"color",description:"Colour of the outline beneath the focused, hovered or clicked incidents. Unset: black on light styles, white on dark."},"highlight.line.widthFactor":{kind:"factor",description:"Multiplier on the line width of the focused, hovered or clicked incidents; `1` keeps the outline alone.",range:INCIDENT_HIGHLIGHT_WIDTH_FACTOR_RANGE,default:1.6},"highlight.unfocusedOpacityFactor":{kind:"factor",description:"Multiplier on the opacity of the incidents outside the focus set while a focus is active, lines, icons and text alike; `1` keeps them as they are.",range:OPACITY_RANGE,default:1},"line.opacity":{kind:"number",description:"Opacity of the incident lines; the markers and the outline of a highlighted incident stay opaque.",range:OPACITY_RANGE,default:1}},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 line colour of the region boundary. Unset: black on light styles, white on dark."},"regionPolygon.fill.style":{kind:"enum",description:"`filled` fills the region; `inverted` fills the world outside it instead.",options:/* @__PURE__ */everyOf()(["filled","inverted"]),default:AREA_ANALYTICS_DEFAULTS.regionPolygon.fill.style},"regionPolygon.fill.opacity":{kind:"number",description:"Fill opacity of the region.",range:OPACITY_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.fill.opacity},"regionPolygon.line.opacity":{kind:"number",description:"Opacity of the region boundary line.",range:OPACITY_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.line.opacity},"regionPolygon.line.width":{kind:"number",description:"Width of the region boundary line, in pixels.",range:OUTLINE_WIDTH_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.line.width}}))(),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.metrics[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.metrics[e].height.scaleMode}),"height.maxMeters":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.metrics[e].height.maxMeters}),"height.minMeters":e=>({kind:"number",description:`Height of the lowest \`${e}\` cells, in metres.`,range:HEIGHT_METERS_RANGE,default:AREA_ANALYTICS_DEFAULTS.metrics[e].height.minMeters}),"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:`metrics.${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),metricValuesOf=e=>Object.fromEntries(areaAnalyticsMetricKeys.map(t=>[t,e[t]??0])),tilesToPointFeatures=e=>({type:"FeatureCollection",features:e.features.flatMap(e=>e.properties?.tiledData?.tiles??[]).map((e,t)=>{const[i,s]=e.tileCentre,o=`tile-${t}-${i}-${s}`;return{type:"Feature",id:o,geometry:toPointGeometry([i,s]),properties:{id:o,...metricValuesOf(e)}}})}),averageOf=(e,t,i)=>roundToDecimals(t/i,"travelTime"===e?1:0),turfHexLayout=(e,t)=>{const[i,s,o,r]=e,[a,n]=bboxCenter(e),l=bboxLongitudeSpan(e),c=2*t/distance([i,n],[o,n])*l,d=2*t/distance([a,s],[a,r])*(r-s),u=c/2,h=Math.sqrt(3)/2*d,p=3/4*c,y=Math.floor((l-c)/(c-u/2)),f=(y*p-u/2-l)/2-u/2+p/2,m=Math.floor((r-s-h)/h),g={shape:"hex",origin:[i-f,s+(r-s-m*h)/2],width:c,height:d};return{lattice:g,cellOf:e=>latticeCellOf(g,e),turfIndexOf:({column:e,row:t})=>e>=0&&e<=y&&t>=(1&e)&&t<=m?e*(m+1)-Math.floor(e/2)+t-(1&e):void 0}},turfSquareLayout=(e,t)=>{const[i,s,,o]=e,r=bboxLongitudeSpan(e),a=convertLength(t,"kilometers","degrees"),n=Math.floor(r/a),l=Math.floor((o-s)/a),c={shape:"square",origin:[i+(r-n*a)/2+a/2,s+(o-s-l*a)/2+a/2],width:a,height:a};return{lattice:c,cellOf:([e,t])=>latticeCellOf(c,[e-1e-9,t-1e-9]),turfIndexOf:({column:e,row:t})=>e>=0&&e<n&&t>=0&&t<l?e*l+t:void 0}},aggregateTilesIntoCells=(e,{lattice:t,cellOf:i,turfIndexOf:s},o)=>{const r=/* @__PURE__ */new Map;for(const a of e){const e=i(a.tileCentre),t=s(e);if(void 0===t)continue;const o=metricValuesOf(a),n=r.get(t);if(n){for(const e of areaAnalyticsMetricKeys)n.sums[e]+=o[e];n.count++}else r.set(t,{cell:e,sums:o,count:1})}return[...r.entries()].sort(([e],[t])=>e-t).map(([e,{cell:i,sums:s,count:r}])=>{const a=`${o}-${e}`,n=Object.fromEntries(areaAnalyticsMetricKeys.map(e=>[e,averageOf(e,s[e],r)]));return{type:"Feature",id:a,geometry:latticeCellPolygon(t,i),properties:{id:a,...n}}})},tilesToGridFeatures=(e,t,i,s)=>{const o=[];for(let r=0;r<e.features.length;r++){const a=e.features[r],n=a.properties?.tiledData?.tiles??[];if(0===n.length)continue;const l=bboxFromGeoJSON(a);if(!l)continue;const c=[l[0]-.005,l[1]-.005,l[2]+.005,l[3]+.005];o.push(...aggregateTilesIntoCells(n,i(c,t),`${s}-${r}`))}return{type:"FeatureCollection",features:o}},tilesToHexFeatures=(e,t=.25)=>tilesToGridFeatures(e,t,turfHexLayout,"hex"),tilesToSquareFeatures=(e,t=.5)=>tilesToGridFeatures(e,t,turfSquareLayout,"square"),isRegionInverted=e=>"inverted"===(e?.regionPolygon?.fill?.style??AREA_ANALYTICS_DEFAULTS.regionPolygon.fill.style),dataSources=["hexgrid","square","heatmap"],TrafficAreaAnalyticsModule=class TrafficAreaAnalyticsModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new TrafficAreaAnalyticsModule(e,t)}constructor(e,t){super(e,t),this.lastAnalytics=null,this.shownFeaturesHandlers=[]}_initSourcesWithLayers(e,t){const i=this.instanceIndex,s=`area-analytics-heatmap-${i}`,o=`area-analytics-hexgrid-${i}`,r=`area-analytics-square-${i}`,a=`area-analytics-region-${i}`,n=`${s}-layer`,l=`${o}-fill`,c=`${o}-extrusion`,d=`${o}-outline`,u=`${o}-extrusion-highlight`,h=`${r}-fill`,p=`${r}-extrusion`,y=`${r}-outline`,f=`${r}-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(h,e),this.squareExtrusionLayerSpec=buildSquareExtrusionLayerSpec(p,e),this.regionFillLayerSpec=buildRegionFillLayerSpec(m,e,S),this.regionLineLayerSpec=buildRegionLineLayerSpec(g,e,S),this.hexOutlineLayerSpec=buildHexOutlineLayerSpec(d,e),this.hexExtrusionHighlightLayerSpec=buildHexExtrusionHighlightLayerSpec(u,e),this.squareOutlineLayerSpec=buildSquareOutlineLayerSpec(y,e),this.squareExtrusionHighlightLayerSpec=buildSquareExtrusionHighlightLayerSpec(f,e);const b={heatmap:new GeoJSONSourceWithLayers(this.mapLibreMap,s,[this.heatmapLayerSpec]),hexgrid:new GeoJSONSourceWithLayers(this.mapLibreMap,o,[this.hexFillLayerSpec,this.hexExtrusionLayerSpec]),square:new GeoJSONSourceWithLayers(this.mapLibreMap,r,[this.squareFillLayerSpec,this.squareExtrusionLayerSpec]),region:new GeoJSONSourceWithLayers(this.mapLibreMap,a,[this.regionFillLayerSpec,this.regionLineLayerSpec])};return this.addHighlightLayersToMap(o,r),b}_applyConfig(e){const t=this.config,i=e??{},s=Object.fromEntries(areaAnalyticsMetricKeys.map(e=>[e,{...AREA_ANALYTICS_DEFAULTS.metrics[e],...i.metrics?.[e]}])),o={activeMetric:AREA_ANALYTICS_DEFAULTS.activeMetric,displayMode:AREA_ANALYTICS_DEFAULTS.displayMode,...i,metrics:s};return this.config=o,this.applyLayerConfig(o),isEqual(o.regionPolygon,t?.regionPolygon)&&isEqual(o.layers?.regionFill,t?.layers?.regionFill)&&isEqual(o.layers?.regionLine,t?.layers?.regionLine)||this.applyRegionConfig(o,t),(o.beforeLayerConfig||t?.beforeLayerConfig)&&this.moveLayersToSpecPositions(),this.applyVisibility(o),o}moveLayersToSpecPositions(){for(const e of[this.heatmapLayerSpec,this.hexFillLayerSpec,this.hexOutlineLayerSpec,this.hexExtrusionLayerSpec,this.hexExtrusionHighlightLayerSpec,this.squareFillLayerSpec,this.squareOutlineLayerSpec,this.squareExtrusionLayerSpec,this.squareExtrusionHighlightLayerSpec])moveLayerBefore(this.mapLibreMap,e.id,e.beforeID)}discardShownData(){this.lastAnalytics=null}restoreDataAndConfigImpl(){const e=shownFeaturesOf(this.sourcesWithLayers);this.initSourcesWithLayers(this.config,!0),this.lastAnalytics?this.display(e):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.buildRegionFeatureCollection(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 s={...this.config?.metrics};for(const o of i){const i={...s[o]};void 0===t?delete i[e]:i[e]=t,s[o]=i}this.config={...this.config,metrics:s}}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,s=this.sourcesWithLayers.hexgrid.shownFeatures.features.length>0,o=this.sourcesWithLayers.square.shownFeatures.features.length>0,r=this.sourcesWithLayers.region.shownFeatures.features.length>0;this.setLayersVisible([this.heatmapLayerSpec],"heatmap"===t&&i),this.setLayersVisible([this.hexExtrusionLayerSpec,this.hexExtrusionHighlightLayerSpec],"hexgrid-3d"===t&&s),this.setLayersVisible([this.hexFillLayerSpec,this.hexOutlineLayerSpec],"hexgrid-2d"===t&&s),this.setLayersVisible([this.squareExtrusionLayerSpec,this.squareExtrusionHighlightLayerSpec],"square-3d"===t&&o),this.setLayersVisible([this.squareFillLayerSpec,this.squareOutlineLayerSpec],"square-2d"===t&&o),this.setLayersVisible([this.regionFillLayerSpec,this.regionLineLayerSpec],r)}hideAllDataLayers(){this.setLayersVisible([this.heatmapLayerSpec,this.hexFillLayerSpec,this.hexExtrusionLayerSpec,this.hexOutlineLayerSpec,this.hexExtrusionHighlightLayerSpec,this.squareFillLayerSpec,this.squareExtrusionLayerSpec,this.squareOutlineLayerSpec,this.squareExtrusionHighlightLayerSpec,this.regionFillLayerSpec,this.regionLineLayerSpec],!1)}setLayersVisible(e,t){applyLayersVisibility(e,t,this.mapLibreMap)}addHighlightLayersToMap(e,t){const i=(e,t)=>({...e,source:t});addLayers([i(this.hexOutlineLayerSpec,e),i(this.hexExtrusionHighlightLayerSpec,e),i(this.squareOutlineLayerSpec,t),i(this.squareExtrusionHighlightLayerSpec,t)],this.mapLibreMap)}applyLayerConfig(e){const t=this.lastAnalytics?.properties.ranges?.[this.activeMetric],i=buildHeatmapLayerSpec(this.heatmapLayerSpec.id,e,t),s=buildHexFillLayerSpec(this.hexFillLayerSpec.id,e,t),o=buildHexExtrusionLayerSpec(this.hexExtrusionLayerSpec.id,e,t),r=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),c=buildHexOutlineLayerSpec(this.hexOutlineLayerSpec.id,e),d=buildSquareOutlineLayerSpec(this.squareOutlineLayerSpec.id,e);changeLayerProps(i,this.heatmapLayerSpec,this.mapLibreMap),changeLayerProps(s,this.hexFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.hexExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(r,this.hexExtrusionHighlightLayerSpec,this.mapLibreMap),changeLayerProps(c,this.hexOutlineLayerSpec,this.mapLibreMap),changeLayerProps(a,this.squareFillLayerSpec,this.mapLibreMap),changeLayerProps(n,this.squareExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(l,this.squareExtrusionHighlightLayerSpec,this.mapLibreMap),changeLayerProps(d,this.squareOutlineLayerSpec,this.mapLibreMap),this.heatmapLayerSpec=i,this.hexFillLayerSpec=s,this.hexExtrusionLayerSpec=o,this.hexExtrusionHighlightLayerSpec=r,this.hexOutlineLayerSpec=c,this.squareFillLayerSpec=a,this.squareExtrusionLayerSpec=n,this.squareExtrusionHighlightLayerSpec=l,this.squareOutlineLayerSpec=d,this.applyFiltersToLayers()}applyRegionConfig(e,t){const i=this.lightDark,s=buildRegionFillLayerSpec(this.regionFillLayerSpec.id,e,i),o=buildRegionLineLayerSpec(this.regionLineLayerSpec.id,e,i);changeLayerProps(s,this.regionFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.regionLineLayerSpec,this.mapLibreMap),this.regionFillLayerSpec=s,this.regionLineLayerSpec=o;const r=isRegionInverted(e);this.lastAnalytics&&r!==isRegionInverted(t)&&this.sourcesWithLayers.region.show(this.buildRegionFeatureCollection(this.lastAnalytics.features,r))}applyFiltersToLayers(){const e=this.activeMetric,t=this.config?.metrics?.[e]?.filters,i=[];void 0!==t?.min&&i.push([">=",["get",e],t.min]),void 0!==t?.max&&i.push(["<=",["get",e],t.max]);for(const s of[this.hexFillLayerSpec,this.hexExtrusionLayerSpec,this.hexOutlineLayerSpec,this.hexExtrusionHighlightLayerSpec,this.squareFillLayerSpec,this.squareExtrusionLayerSpec,this.squareOutlineLayerSpec,this.squareExtrusionHighlightLayerSpec]){const e=s.filter?[toExpressionFilter(s.filter)]:[];this.mapLibreMap.setFilter(s.id,getMergedFilter("all",[...e,...i]),{validate:!1})}}buildRegionFeatureCollection(e,t){if(t&&e.length){const t="traffic-area-analytics-region-0";return{type:"FeatureCollection",features:[{...mask(featureCollection(e)),id:t,properties:{id:t}}]}}return{type:"FeatureCollection",features:e.map((e,t)=>{const i=`traffic-area-analytics-region-${t}`;return{...e,id:i,properties:{id:i}}})}}},addValuesFilter=(e,t,i,s)=>{isCompleteValuesFilter(e)&&i.push(((e,t,i)=>buildMappedValuesFilter(e,t.show,i?t.values.map(i):t.values))(t,e,s))},addCommonFilterExpressions=(e,t)=>{addValuesFilter(e.roadCategories,"road_category",t),addValuesFilter(e.roadSubCategories,"road_subcategory",t)},buildMapLibreIncidentsFilter=e=>{const t=[];addCommonFilterExpressions(e,t),addValuesFilter(e.incidentCategories,"icon_category_0",t,trafficIncidentToIconCategory),addValuesFilter(e.magnitudes,"magnitude_of_delay",t,e=>indexedMagnitudes.indexOf(e));const i=e.delays&&(({required:e,minMinutes:t})=>{if(t){const i=[">=",["get","delay"],60*t];return e?i:["any",["!",["has","delay"]],["==",["get","delay"],0],i]}return e?[">",["get","delay"],0]:null})(e.delays);return i&&t.push(i),getMergedFilter("all",t)},buildMapLibreAnyFilters=({any:e,...t},i)=>getMergedFilter("any",[t,...e??[]].map(i).filter(e=>!isNil(e))),buildMapLibreFlowFilter=e=>{const t=[];if(addCommonFilterExpressions(e,t),e.roadClosures){const i="only"===e.roadClosures?"==":"!=";t.push([i,["get","road_closure"],!0])}return getMergedFilter("all",t)},applyTrafficFilters=(e,{sourceId:t,contributor:i,build:s},o,r)=>{if(!e.mapReady)return;const a=o&&s(o);(a||r)&&((e,t,i,s)=>{for(const o of t)i.setClause(o.id,s,e)})(a??void 0,filterLayersBySources(e.mapLibreMap,[t]),LayerFilterComposer.for(e),i)},FLOW_FILTERS={sourceId:"vectorTilesFlow",contributor:"traffic.flow",build:e=>buildMapLibreAnyFilters(e,buildMapLibreFlowFilter)},TrafficFlowModule=class TrafficFlowModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,TrafficFlowModule,()=>new TrafficFlowModule(e,t),t,{sourceId:"vectorTilesFlow",part:"trafficFlow"})}constructor(e,t){super(e,t)}_initSourcesWithLayers(){return{trafficFlow:styleSourceWithLayers(this.mapLibreMap,"vectorTilesFlow",TrafficFlowModule.name)}}_applyConfig(e){return this._setVisible(e?.visible??!1,!1),applyTrafficFilters(this.tomtomMap,FLOW_FILTERS,e?.filters,this.config?.filters),trafficFlowLook.apply(this.tomtomMap,e),e}_knobValue(e){return super._knobValue(e)??trafficFlowLook.valueOf(this.tomtomMap,e)}setVisible(e){this._setVisible(e)}_setVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficFlow.setLayersVisibleThrough(this.visibilityComposer,"trafficFlow.visible",e),t&&(this.config={...this.config,visible:e},this.emitConfigChange())}isVisible(){return this.config?.visible??!1}getRenderedFeatures(){return{trafficFlow:this.sourcesWithLayers.trafficFlow.queryRenderedFeatures().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 r of t)i.set(r.id.trim(),r);const s={outline:{...FALLBACK_INCIDENT_PALETTE_outline},inner:{...FALLBACK_INCIDENT_PALETTE_inner}},o=[];for(const r of indexedMagnitudes){const e=LAYER_IDS[r],t=readLineColor(i.get(e.outline),e.outline,o),a=readLineColor(i.get(e.inner),e.inner,o);t&&(s.outline[r]=t),a&&(s.inner[r]=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(", ")),s},readLineColor=(e,t,i)=>{if(!e||"object"!=typeof e)return;const s=e.paint;if(!s||"object"!=typeof s)return;const o=s["line-color"];if("string"==typeof o)return o;void 0!==o&&i.push(t)},TrafficIncidentDetailsModule=class TrafficIncidentDetailsModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new TrafficIncidentDetailsModule(e,t??{})}constructor(e,t){super(e,t),this.lastFeatureIds=[],this.lastFocusIds=null,this.shownFeaturesHandlers=[],onStyleKnobsApplied(e,Object.values(incidentColorKnobIds),()=>this.updateLayers(this.config)),onMapTypefaceChange(e,()=>this.updateLayers(this.config))}buildLayerSpecs(e,t){const i=beforeLayerIDOf(t?.beforeLayerConfig??"lowestLabel"),s=((e,t)=>!1===e?null:{outlineColor:e?.outline?.color??themeContrastColor(t),widthFactor:clampFactor(e?.line?.widthFactor,INCIDENT_HIGHLIGHT_WIDTH_FACTOR_RANGE,1.6),unfocusedOpacityFactor:clampFactor(e?.unfocusedOpacityFactor,OPACITY_RANGE)})(t?.highlight,this.tomtomMap.styleLightDarkTheme);return[...buildCanonicalIncidentLineLayers(e,i,readIncidentPalette(this.mapLibreMap),s,t?.layers,t?.line),...buildCanonicalIncidentSymbolLayers(e,i,t?.layers,mapTypefaceOf(this.tomtomMap),s?.unfocusedOpacityFactor)]}updateLayers(e){const{incidents:t}=this.sourcesWithLayers,i=this.buildLayerSpecs(t.sourceAndLayerIDs.sourceID,e);this.replaceSourceLayers(i,t._layerSpecs,t);const s=i.map(({id:e})=>e);t._layerSpecs.sort((e,t)=>s.indexOf(e.id)-s.indexOf(t.id)),t._updateSourceAndLayerIDs()}_initSourcesWithLayers(e,t){const i=`traffic-incident-details-${this.instanceIndex}`;return addOrUpdateImage("if-not-in-sprite","tt-traffic-incident-direction-chevron",(cachedImage??=svgMarkupToImg('<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>'),cachedImage),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){applyLayersVisibility(this.sourcesWithLayers.incidents._layerSpecs,!1!==e?.visible,this.mapLibreMap)}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.applyVisibility(this.config);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 s of this.lastFeatureIds)this.mapLibreMap.setFeatureState({source:i,id:s},{focused:t.has(s)})}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})}},INCIDENTS_FILTERS={sourceId:"vectorTilesIncidents",contributor:"traffic.incidents",build:e=>buildMapLibreAnyFilters(e,buildMapLibreIncidentsFilter)},TrafficIncidentsModule=class TrafficIncidentsModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,TrafficIncidentsModule,()=>new TrafficIncidentsModule(e,t),t,{sourceId:"vectorTilesIncidents",part:"trafficIncidents"})}constructor(e,t){super(e,t)}_initSourcesWithLayers(){return{trafficIncidents:styleSourceWithLayers(this.mapLibreMap,"vectorTilesIncidents",TrafficIncidentsModule.name)}}_applyConfig(e){return this._setVisible(e?.visible??!1,!1),isNil(e?.icons?.visible)||this._setIconsVisible(e.icons.visible,!1),this._applyTimeValidity(e?.timeValidity),applyTrafficFilters(this.tomtomMap,INCIDENTS_FILTERS,e?.filters,this.config?.filters),trafficIncidentsLook.apply(this.tomtomMap,e),e}_applyTimeValidity(e){const t=this.mapLibreMap.getSource("vectorTilesIncidents"),i=t?.serialize().tiles;if(!i)return;const s=i.map(t=>((e,t)=>{const[i,s=""]=e.split("?"),o=new URLSearchParams(s),r=trafficIncidentTimeValidities.filter(e=>t?.includes(e)),a=r.some(e=>"present"!==e)?r.join(","):null;if(o.get("timeValidityFilter")===a)return e;a?o.set("timeValidityFilter",a):o.delete("timeValidityFilter");const n=o.toString();return n?`${i}?${n}`:i})(t,e));isEqual(s,i)||t.setTiles(s)}_knobValue(e){return super._knobValue(e)??trafficIncidentsLook.valueOf(this.tomtomMap,e)}setIconsVisible(e){this._setIconsVisible(e)}_setIconsVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisibleThrough(this.visibilityComposer,"trafficIncidents.visible",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=!0){if(t){const{icons:t,...i}=this.config??{},{visible:s,...o}=t??{};this.config={...i,...!isEmpty(o)&&{icons:o},visible:e},this.emitConfigChange()}this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisibleThrough(this.visibilityComposer,"trafficIncidents.visible",e)}isVisible(){return this.config?.visible??!1}isIconsVisible(){return this.config?.icons?.visible??this.isVisible()}getRenderedFeatures(){return{trafficIncidents:this.sourcesWithLayers.trafficIncidents.queryRenderedFeatures().map(trafficIncidentMapping)}}get events(){return this.moduleEvents(["trafficIncidents"],{mapping:trafficIncidentMapping})}},MERCATOR_UNITS_PER_EPSG3857_METER=1/(2*Math.PI*6378137),mercatorUnitsPerMeterAt=e=>MERCATOR_UNITS_PER_EPSG3857_METER/Math.cos(e*Math.PI/180),localFrameMatrix=(e,t,i={})=>{const{altitude:s=0,units:o}=i,[,r]=t,a=MercatorCoordinate.fromLngLat(t),n="mercatorMeters"===o?MERCATOR_UNITS_PER_EPSG3857_METER:mercatorUnitsPerMeterAt(r),l=mercatorUnitsPerMeterAt(i.centerLatitude??r),c=[n,-n,l],d=[a.x,a.y,s*l],u=/* @__PURE__ */new Float64Array(16);for(let h=0;h<4;h++){u[12+h]=e[12+h];for(let t=0;t<3;t++)u[4*t+h]=e[4*t+h]*c[t],u[12+h]+=e[4*t+h]*d[t]}return u},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,adjustVisibleBoundsForElement=(e,t,i,s,o)=>{const r=((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,s),a=e.left<=0&&e.right>=i,n=e.top<=0&&e.bottom>=s;!a||n?!n||a?((e,t,i,s,o)=>{const r=e.left,a=i-e.right,n=e.top,l=s-e.bottom,c=Math.min(r,a,n,l);c===r?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)})(r,t,i,s,o):((e,t,i,s)=>{e.left<=i-e.right?t.left=Math.max(t.left,e.right+s):t.right=Math.min(t.right,e.left-s)})(r,t,i,o):((e,t,i,s)=>{e.top<=i-e.bottom?t.top=Math.max(t.top,e.bottom+s):t.bottom=Math.min(t.bottom,e.top-s)})(r,t,s,o)},toElement=e=>"string"==typeof e?document.querySelector(e):e,getMapLibreMap=e=>"mapLibreMap"in e?e.mapLibreMap:e,calculateVisibleAreaBounds=(e,t,i)=>{const s=getMapLibreMap(e).getContainer().getBoundingClientRect(),{width:o,height:r}=s,a={left:i,top:i,right:o-i,bottom:r-i};for(const n of t){const e=toElement(n);if(!e)continue;const t=e.getBoundingClientRect(),l=getRelativeElementBounds(t,s);isElementOutsideContainer(l,o,r)||adjustVisibleBoundsForElement(l,a,o,r,i)}return a.left>=a.right||a.top>=a.bottom?null:{visibleAreaBounds:a,mapWidthPX:o,mapHeightPX:r}},calculatePaddedBBox=e=>{const{map:t,surroundingElements:i,paddingPX:s=0}=e,o=calculateVisibleAreaBounds(t,i,s);if(!o)return null;const{left:r,top:a,right:n,bottom:l}=o.visibleAreaBounds,c=getMapLibreMap(t),d=[[r,l],[r,a],[n,a],[n,l]].map(([e,t])=>{const{lng:i,lat:s}=c.unproject([e,t]);return[i,s]});return bboxFromGeoJSON({type:"LineString",coordinates:d})??null},calculatePaddedCenter=e=>{const{map:t,surroundingElements:i}=e,s=calculatePaddedBBox({map:t,surroundingElements:i});return s?bboxCenter(s):null},clampLatitude=e=>clamp(e,-MAX_MERCATOR_LATITUDE,MAX_MERCATOR_LATITUDE),calculateFittingBBox=e=>{const{map:t,toBeContainedBBox:i,surroundingElements:s,paddingPX:o=0}=e,r=calculateVisibleAreaBounds(t,s,o);if(!r)return null;const{visibleAreaBounds:a,mapWidthPX:n,mapHeightPX:l}=r,c=a.left/n,d=a.right/n,u=a.top/l,h=d-c,p=a.bottom/l-u,[y,f,,m]=i,g=bboxLongitudeSpan(i)/h,S=(m-f)/p,b=y-c*g,L=b+g,I=m+u*S;return[b,clampLatitude(I-S),L,clampLatitude(I)]};export{AREA_ANALYTICS_DEFAULTS,AbstractDataOwnedMapModule,AbstractGeometriesModule,AbstractMapModule,AbstractSourceWithLayers,AbstractStyleOwnedMapModule,AddedSourceWithLayers,BASE_MAP_SOURCE_ID,BaseMapModule,CombinedEvents,CustomGeoJSONModule,CustomLayer,CustomLayerSourceWithLayers,DEFAULT_TEXT_SIZE,DESELECTED_ROUTE_FILTER,FINISH_INDEX,GeoJSONSourceWithLayers,GeometriesModule,HILLSHADE_SOURCE_ID,LayerFilterComposer,LayerSelection,MAP_BOLD_FONT,MAP_ITALIC_FONT,MAP_MEDIUM_FONT,MAP_REGULAR_FONT,MERCATOR_UNITS_PER_EPSG3857_METER,MIDDLE_INDEX,ModuleEvents,POI_SOURCE_ID,POIsModule,PlacesModule,ReachableRangesModule,RoutingModule,SELECTED_ROUTE_FILTER,START_INDEX,StyleSourceWithLayers,StylingFoundationsModule,TERRAIN_SOURCE_ID,TRAFFIC_FLOW_SOURCE_ID,TRAFFIC_INCIDENTS_SOURCE_ID,TerrainModule,TomTomMap,TomTomMapError,TrafficAreaAnalyticsModule,TrafficFlowModule,TrafficIncidentDetailsModule,TrafficIncidentsModule,UserEvents,UserEventsWithStates,applyMapPreset,areaAnalyticsPalettes,baseMapColorNames,baseMapKnobCatalogue,baseMapKnobIds,baseMapLayerGroupNames,bespokeSectionTypes,buildPlaceTitle,buildWaypointTitle,calculateFittingBBox,calculatePaddedBBox,calculatePaddedCenter,configWithKnobs,configWithoutKnob,customGeoJSONKnobCatalogue,customGeoJSONKnobIds,defaultRoutingLayers,drawnSectionTypes,fillStyledGeometryConfig,filterShowModes,formatStyleHsl,generatedSectionTypes,geometriesKnobCatalogue,geometriesKnobIds,geometryFillStyles,geometryPaletteModes,getKnob,getStyleColor,hillshadeLightAlignments,hillshadeMethods,hueDistance,knobEntryOf,knobValueIn,linePatterns,localFrameMatrix,mapColorNames,mapFonts,mapPresetCatalogue,mapPresetIds,mapStyleLayerIDs,mapTypefaces,parseCssColor,placesKnobCatalogue,placesKnobIds,placesMarkerTypes,poiCategoryGroups,poisKnobCatalogue,poisKnobIds,preparePlacesForDisplay,reachableRangesKnobCatalogue,reachableRangesKnobIds,resetKnob,resolveColorStops,roadCategories,routingKnobCatalogue,routingKnobIds,sectionDrawsByDefault,sectionSourceKey,sectionSupportsKnob,serviceRoadSubCategories,setKnob,setKnobs,standardStyleIDs,streetRoadSubCategories,styleColorKnobIds,styleModuleLayerGroupNames,styleParts,stylingFoundationsKnobAppliesTo,stylingFoundationsKnobCatalogue,stylingFoundationsKnobIds,stylingFoundationsKnobKinds,terrainKnobCatalogue,terrainKnobIds,toHsl,toPlaces,trafficAreaAnalyticsKnobCatalogue,trafficAreaAnalyticsKnobIds,trafficFlowKnobCatalogue,trafficFlowKnobIds,trafficIncidentDetailsKnobCatalogue,trafficIncidentDetailsKnobIds,trafficIncidentsKnobCatalogue,trafficIncidentsKnobIds,validateKnobValue};
1
+ import{DEFAULT_COMMON_BASE_URL,MILE_IN_METERS,RADIANS_PER_DEGREE,TomTomConfig,apiErrorCodeIn,apiErrorMessageIn,areaAnalyticsMetricKeys,bboxCenter,bboxFromGeoJSON,bboxLongitudeSpan,budgetUnits,canRetrySDKErrorCode,clamp,clampLatitude,definedFields,describeAPIError,distinctBy,formatDistance,formatDuration,fullTrafficIncidentCategories,generateId,generateTomTomHeaders,getDistinctSections,getPosition,getPositionEntryPointOptions,getPositionStrict,iconToTrafficIncidentCategory,indexedMagnitudes,insecureBaseURLMessage,isProxyCredentialsMode,isSecureBaseURL,latticeCellOf,latticeCellPolygon,mergeFromGlobal,metersAlongLine,pickKeys,poiCategories,poiCategoriesToID,pointInsidePolygon,polygonFromBBox,positionBetween,sdkErrorCodeForStatus,segmentAtMeters,servesGeopoliticalView,setApiKeyParameter,toPointGeometry,trafficIncidentLanguage,trafficIncidentTimeValidities,trafficIncidentToIconCategory,withNearestLongitude,wrapDegrees,wrapLongitude}from"@tomtom-org/maps-sdk/core";import{get,has,isEmpty,isEqual,isNil,isObject,isPlainObject,minBy,setWith,toPath,unset}from"lodash-es";import{clampRgb,converter,differenceHueNaive,formatHex,formatHsl,formatRgb,interpolate,modeHsl,modeLrgb,modeOklch,modeRgb,parse,useMode,wcagLuminance}from"culori/fn";import{area,bbox,bearing,booleanPointInPolygon,convertLength,difference,distance,featureCollection,mask,union}from"@turf/turf";import{Map as Map$1,MercatorCoordinate,getWorkerUrl,setWorkerCount,setWorkerUrl}from"maplibre-gl";var loading,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),glyphsSvg=(e,t,i)=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${e}"><path d="${i.map(([e,t,i])=>`M${e} ${t}${i}`).join("")}" fill="#000" stroke="#fff" stroke-width="2" stroke-linejoin="${t}" paint-order="stroke"/></svg>`,TOM_T="l-1.23-2.14h-1.46c-.68 0-1.28-.5-1.33-1.12l-.02-.29v-3.23h2.8l1.1-1.94h-3.9v-3.52l-2.13 1.48v1.93h-1.35v2.15h1.35v3.27a3.5 3.5 0 0 0 3.3 3.41h2.87Z",TOM_O="a4.49 4.49 0 0 0 0 8.98 4.49 4.49 0 0 0 0-8.98Zm0 6.84a2.35 2.35 0 0 1 0-4.7 2.35 2.35 0 0 1 0 4.7Z",TOM_M="h2.13v-5.46a4 4 0 0 0-.12-.97 3.56 3.56 0 0 0-5.74-1.71l-.08.07-.09-.07a3.56 3.56 0 0 0-5.86 2.68v5.46h2.14v-5.37c0-.76.61-1.38 1.37-1.38s1.36.62 1.37 1.37v5.38h2.13v-5.38c.01-.75.63-1.37 1.38-1.37s1.37.62 1.37 1.38v5.37Z",OSM_P="q2.2 0 2.3 3.3-.2 3.3-2.4 3.4a2 2 0 0 1-1.7-.9v3.7h-1.6v-9.4h1.3l.2.9h.1q.5-1 1.8-1Zm-.5 1.2q-1.4 0-1.3 2v.1q-.1 2.1 1.3 2.2 1.2-.1 1.2-2.2 0-2-1.2-2.1Z",OSM_E="q2.6 0 2.7 3v.7h-4q0 1.8 1.6 1.9 1.1 0 2-.5v1.2q-.7.4-2.1.4c-1.8 0-3.1-1-3.1-3.3q.2-3.4 2.9-3.4Zm0 1q-1.1 0-1.3 1.6h2.5q0-1.4-1.2-1.5Z",OSM_T="q.6 0 1-.3v1.2l-1.4.2q-1.8.2-2-2v-3.5h-.8v-.6l1-.6.4-1.3h1v1.4h1.7v1.1h-1.7v3.4q0 1 .8 1Z",attributionLogos=[{matches:["tomtom","tomtom n.v."],svg:/* @__PURE__ */glyphsSvg("0 0 65.704 14.241","round",[[9.52,13.24,TOM_T],[15,4.26,TOM_O],[30.22,13.24,TOM_M],[40.88,13.24,TOM_T],[46.35,4.26,TOM_O],[61.57,13.24,TOM_M]]),label:"© TomTom",widthPx:65.704,heightPx:14.241},{matches:["openstreetmap"],svg:/* @__PURE__ */glyphsSvg("0.46 0 98 16","miter",[[5.4,6.8,"q-1.2 0-1.3 2 0 1.7 1.3 1.8.6 0 1.2-.3v.8q-.5.3-1.3.3-2.3 0-2.3-2.7 0-2.5 2.3-2.7.8 0 1.5.4l-.4.7q-.5-.3-1-.3Zm-4.4 1.92a4.14 4.4 0 1 0 8.28 0 4.14 4.4 0 1 0-8.28 0Zm.69 0a3.45 3.77 0 1 1 6.9 0 3.45 3.77 0 1 1-6.9 0Z"],[18.1,8.7,"c0 2.6-1.2 4.4-3.8 4.4-2.7 0-3.8-1.8-3.8-4.4q0-4.2 3.8-4.4 3.9.2 3.8 4.4Zm-6 0q0 3 2.2 3.1 2.2-.1 2.1-3.1 0-3-2.1-3.1-2.2 0-2.1 3.1Z"],[23,6.4,OSM_P],[29.3,6.4,OSM_E],[36.8,6.4,"q2 0 2.2 2.4v4.2h-1.6v-4q0-1.5-1-1.4-1.5 0-1.4 2.2v3.2h-1.6v-6.5h1.2l.2.8q.8-1 2-1Z"],[45.7,10.7,"q0 2.3-3 2.4-1.4 0-2.4-.5v-1.4q1.2.5 2.4.6 1.4 0 1.3-1 .1-1-1.6-1.6c-1-.5-2-1-2-2.5q.1-2.3 2.8-2.4 1.4 0 2.4.6l-.5 1.2q-1-.5-2-.5t-1 1q-.1.9 1.6 1.5 1.9.7 2 2.6Z"],[49.5,12,OSM_T],[55,6.4,"h.6l-.1 1.4h-.3c-.8-.1-2 .3-2 1.8v3.4h-1.5v-6.5h1.2l.2 1.1q.7-1.1 1.9-1.2Z"],[59,6.4,OSM_E],[65.7,6.4,OSM_E],[72.3,12,OSM_T],[78,13,"l-2-7v7h-1.4v-8.6h2.2l2 6.8 2.2-6.8h2.2v8.6h-1.5v-7l-2.2 7z"],[87.6,6.4,"q2.5 0 2.5 2.2v4.4h-1.1l-.4-.9q-.6 1-2 1-1.8 0-2-2 0-2 2.8-2l1-.1v-.3q0-1.3-1-1.2-.7 0-1.6.5l-.5-1q1-.6 2.3-.6Zm.2 3.6q-1.6 0-1.5 1.1 0 .9.8.9 1.3 0 1.4-1.5v-.6z"],[95.1,6.4,OSM_P]]),label:"©OpenStreetMap",widthPx:98,heightPx:16}],splitCredits=e=>{const t=[];let i=0,s=!1;for(let o=0;o<e.length;o++){const r=e[o];"<"===r?s=!0:">"===r?s=!1:"|"!==r||s||(t.push(e.slice(i,o)),i=o+1)}return t.push(e.slice(i)),t.map(e=>e.trim()).filter(Boolean)},normalizeAttribution=e=>e.replaceAll(/<[^<>]*>/g," ").replaceAll(/&copy;|&nbsp;|©/gi," ").replaceAll(/&amp;/gi,"&").replaceAll(/\s+/g," ").trim().toLowerCase(),DEFAULT_PADDING={horizontal:12,vertical:8},resolvePadding=e=>"number"==typeof e?{horizontal:e,vertical:e}:{...DEFAULT_PADDING,...e},ATTRIBUTION_LOGOS_CLASS="tomtom-attribution-logos",ATTRIBUTION_LOGO_CLASS="tomtom-attribution-logo",ATTRIBUTION_CREDITS_CLASS="tomtom-attribution-credits",ATTRIBUTION_BACKDROP_CLASS="tomtom-attribution-backdrop",BACKDROP_COLORS={light:"rgba(255, 255, 255, 0.6)",dark:"rgba(0, 0, 0, 0.45)"},BACKDROP_MASK="linear-gradient(90deg,transparent,#000 16px,#000 calc(100% - 16px),transparent),linear-gradient(transparent,#000 8px,#000 calc(100% - 8px),transparent)",AttributionLogosControl=class{constructor(e={},t=()=>"light"){this._styleTheme=t,this._refresh=()=>{if(!this._map||!this._container)return;this._container.style.setProperty("--tomtom-attribution-backdrop",BACKDROP_COLORS[this._styleTheme()]);const e=collectCredits(this._map,this._ownCredits),t=e.map(e=>e.text).join("|");if(t===this._renderedCredits)return;this._renderedCredits=t;const i=buildAttributionElements(e);this._container.replaceChildren(...this._backdrop&&i.length?[buildBackdrop()]:[],...i)},this._refreshOnMetadata=e=>{"metadata"===e.sourceDataType&&this._refresh()};const{position:i,padding:s,credits:o,backdrop:r}=(e=>{const t="object"==typeof e&&null!==e?e:{};return{position:t.position??"bottom-right",padding:resolvePadding(t.padding),credits:t.credits?.slice()??[],backdrop:t.backdrop??!0}})(e);this._position=i,this._margin=((e,t)=>{const i=e.startsWith("top")?t.vertical:0,s=e.startsWith("bottom")?t.vertical:0,o=e.endsWith("left")?t.horizontal:0;return`${i}px ${e.endsWith("right")?t.horizontal:0}px ${s}px ${o}px`})(i,s),this._ownCredits=o,this._backdrop=r}onAdd(e){return this._map=e,this._container=document.createElement("div"),this._container.className="maplibregl-ctrl tomtom-attribution-logos",this._container.style.cssText=`display:flex;align-items:center;gap:8px;pointer-events:none;position:relative;isolation:isolate;margin:${this._margin}`,e.on("styledata",this._refresh),e.on("sourcedata",this._refreshOnMetadata),this._refresh(),this._container}onRemove(){this._map?.off("styledata",this._refresh),this._map?.off("sourcedata",this._refreshOnMetadata),this._container?.remove(),this._map=void 0,this._container=void 0,this._renderedCredits=void 0}getDefaultPosition(){return this._position}},collectCredits=(e,t)=>{const i=Object.values(e.style?.tileManagers??{}).map(e=>e.getSource().attribution??""),s=[],o=/* @__PURE__ */new Set;for(const r of[...i,...t])for(const e of splitCredits(r)){const t=normalizeAttribution(e);t&&!o.has(t)&&(o.add(t),s.push({text:e,normalized:t}))}return s},buildAttributionElements=e=>{const t=[],i=[];for(const o of e){const e=attributionLogos.findIndex(e=>e.matches.includes(o.normalized));-1===e?i.push(o):t[e]??=o}const s=attributionLogos.flatMap((e,i)=>{const s=t[i];return void 0===s?[]:[buildLogoElement(e,s.text)]});return i.length>0&&s.push(buildTextElement(i.map(e=>e.text))),s.flatMap((e,t)=>0===t?[e]:[buildDivider(),e])},buildLogoElement=(e,t)=>{const i=creditLink(t),s=i??document.createElement("span");s.className="tomtom-attribution-logo",i||s.setAttribute("role","img"),s.setAttribute("aria-label",e.label),s.style.cssText=`display:block;flex-shrink:0;width:${e.widthPx}px;height:${e.heightPx}px;pointer-events:${i?"auto":"none"}`;const o=parseSvg(e.svg);return o.setAttribute("aria-hidden","true"),o.style.cssText="display:block;width:100%;height:100%;overflow:visible;pointer-events:none",s.append(o),s},parseCredit=e=>(new DOMParser).parseFromString(e,"text/html").body,creditLink=e=>{const t=parseCredit(e).querySelector("a");return t?safeLink(t):void 0},safeLink=e=>{const t=e.getAttribute("href")??"";if(!/^https?:\/\//i.test(t))return;const i=document.createElement("a");return i.href=t,i.target=e.getAttribute("target")??"_blank",i.rel="noopener nofollow",i},buildBackdrop=()=>{const e=document.createElement("div");return e.className="tomtom-attribution-backdrop",e.style.cssText=`position:absolute;inset:-8px -16px;z-index:-1;pointer-events:none;background:var(--tomtom-attribution-backdrop);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);-webkit-mask-image:${BACKDROP_MASK};mask-image:${BACKDROP_MASK};-webkit-mask-composite:source-in;mask-composite:intersect`,e},buildDivider=()=>{const e=document.createElement("span");return e.setAttribute("aria-hidden","true"),e.style.cssText="flex-shrink:0;width:1px;height:14px;margin:0 1px;background:#000;box-shadow:0 0 0 1px #fff",e},buildTextElement=e=>{const t=document.createElement("span");return t.className="tomtom-attribution-credits",t.style.cssText='font:11px/16px -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:#000;text-shadow:0 0 2px #fff,0 0 2px #fff,0 0 2px #fff;pointer-events:auto',e.forEach((e,i)=>{i>0&&t.append(" | "),t.append(...sanitizedNodes(parseCredit(e).childNodes))}),t},sanitizedNodes=e=>[...e].flatMap(e=>{if(e.nodeType===Node.TEXT_NODE)return[document.createTextNode(e.textContent??"")];if(!(e instanceof Element)||["script","style"].includes(e.localName))return[];const t=sanitizedNodes(e.childNodes),i="a"===e.localName?safeLink(e):void 0;return i?(i.style.color="inherit",i.append(...t),[i]):t}),CombinedEvents=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}where(e,t){return this.#e.where(e,t)}on(e,t){return"config-change"===e?this.#t.on("config-change",t):"shown-features"===e?this.#t.on("shown-features",t):this.#e.on(e,t)}off(e){"config-change"===e||"shown-features"===e?this.#t.off(e):this.#e.off(e)}},renderedRefId=e=>{const t=e.properties?.id;return"string"==typeof t||"number"==typeof t?t:e.id},isCluster=e=>!0===e.properties?.cluster&&void 0!==e.properties.cluster_id,shownRefId=e=>isCluster(e)?void 0:renderedRefId(e),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}},indexByRefId=e=>{const t=/* @__PURE__ */new Map;return e.forEach((e,i)=>{const s=renderedRefId(e);void 0===s||t.has(s)||t.set(s,{feature:e,index:i})}),t},CLICK_EVENT_STATES=["click","contextmenu"],HOVER_EVENT_STATES=["hover","hover-move","long-hover"],CLICK_STATES=/* @__PURE__ */new Set(CLICK_EVENT_STATES),HOVER_STATES=/* @__PURE__ */new Set(HOVER_EVENT_STATES),isClickEventType=e=>CLICK_STATES.has(e),isHoverEventState=e=>HOVER_STATES.has(e),isClickEventState=["in",["get","eventState"],["literal",/* @__PURE__ */CLICK_EVENT_STATES.slice()]],hasActiveEventState=["all",["has","eventState"],["!=",["get","eventState"],"recently-hovered"]],standardStyleIDs=["streetLight","streetDark","streetLightDriving","streetDarkDriving","monoLight","monoDark","streetSatellite"],styleParts=["trafficIncidents","trafficFlow","terrain"],stylePartURLParams={trafficIncidents:"trafficIncidents",trafficFlow:"trafficFlow",terrain:"hillshade"},lightStylePartValues={trafficIncidents:"incidents_light",trafficFlow:"flow_relative-light",terrain:"hillshade_light"},darkStylePartValues={trafficIncidents:"incidents_dark",trafficFlow:"flow_relative-dark",terrain:"hillshade_dark"},standardStylePartValues=/* @__PURE__ */(()=>({streetLight:lightStylePartValues,streetDark:darkStylePartValues,streetLightDriving:lightStylePartValues,streetDarkDriving:darkStylePartValues,monoLight:{...lightStylePartValues,terrain:"hillshade_mono-light"},monoDark:{...darkStylePartValues,terrain:"hillshade_mono-dark"},streetSatellite:{...lightStylePartValues,terrain:"hillshade_satellite"}}))(),buildStyleInput=e=>{const t=e.style;return((e,t,i)=>{const s=e.id??"streetLight",o=new URL(`${t}/maps/orbis/assets/styles/0.6.0-0/style.json`);o.searchParams.set("apiVersion","1"),setApiKeyParameter(o.searchParams,i),o.searchParams.set("map",(e=>`basic_${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`)(s));for(const r of styleParts)e.include&&!e.include.includes(r)||o.searchParams.append(stylePartURLParams[r],standardStylePartValues[s][r]);return o.toString()})("string"==typeof t?{id:t}:t??{},e.commonBaseURL,e.apiKey)},trafficRoadProperties=e=>({roadCategory:e?.road_category,leftHandTraffic:Boolean(e?.left_hand_traffic),...e?.road_subcategory&&{roadSubcategory:e.road_subcategory},...e?.part_of_two_way_road&&{partOfTwoWayRoad:Boolean(e.part_of_two_way_road)},...e?.openlr&&{openlr:e.openlr},...e?.display_class&&{displayClass:e.display_class}}),FLOW_TAGS=["road_category","road_subcategory","relative_speed","left_hand_traffic","road_closure","absolute_speed","part_of_two_way_road","openlr","display_class"],lineGeometryOf=({geometry:e})=>{if("LineString"===e.type||"MultiLineString"===e.type)return e;throw new Error(`Unexpected ${e.type} traffic flow geometry`)},trafficFlowMapping=e=>{const{properties:t}=e;return{id:e.id,type:e.type,geometry:lineGeometryOf(e),properties:{...trafficRoadProperties(t),roadClosure:Boolean(t?.road_closure),relativeSpeed:t?.relative_speed,...!isNil(t?.absolute_speed)&&{absoluteSpeed:t.absolute_speed}}}},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],...trafficRoadProperties(t),...!isNil(t?.delay)&&{delayInSeconds:t.delay},...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},...!isNil(t?.number_of_reports)&&{numberOfReports:t.number_of_reports},...t?.last_report_time&&{lastReportTime:new Date(t.last_report_time)},...!isNil(t?.average_speed_kmph)&&{averageSpeedKmph:t.average_speed_kmph},...t?.time_validity&&{timeValidity:t.time_validity},...t?.point_type&&{pointType:t.point_type}}}},ofMap=(e,t,i)=>{let s=e.get(t);return void 0===s&&(s=i(),e.set(t,s)),s},toBaseMapPOIImageID=e=>`poi-${e}`,isDOMImageSupported=()=>"undefined"!=typeof document&&"undefined"!=typeof DOMParser,urlToImg=e=>{if(!isDOMImageSupported())return;const t=document.createElement("img");return t.crossOrigin="anonymous",t.src=e,t},svgDataUri=e=>`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`,svgToImg=e=>isDOMImageSupported()?urlToImg(svgDataUri((new XMLSerializer).serializeToString(e()))):void 0,svgMarkupToImg=e=>urlToImg(svgDataUri(e)),staticImages=/* @__PURE__ */new Map,staticImg=e=>ofMap(staticImages,e,()=>svgMarkupToImg(e)),mapStyleLayerIDs={country:"Places - Country name",lowestPlaceLabel:"Places - Village / Hamlet",poi:"POI",lowestLabel:"Borders - Treaty label",lowest3D:"3D - Building",lowestRoadLine:"Tunnel - Railway outline",lowestBuilding:"Buildings - Underground"},MAP_BOLD_FONT="Noto-Bold",MAP_REGULAR_FONT="Noto-Regular",MAP_MEDIUM_FONT="Noto-Medium",MAP_ITALIC_FONT="NotoSans-MediumItalic",zoomRamp=(...e)=>["interpolate",["linear"],["zoom"],...e],DEFAULT_TEXT_SIZE=/* @__PURE__ */zoomRamp(10,14,18,16),mapFonts=["Noto-Regular","NotoSans-MediumItalic","Noto-Bold","Noto-Medium","NotoSans-RegularItalic","NotoSans-BoldItalic","NotoSerif-Regular","NotoSerif-Medium","NotoSerif-Bold","NotoSerif-RegularItalic","NotoSerif-MediumItalic","NotoSerif-BoldItalic"],mapTypefaces=["sans","sans-italic","serif","serif-italic"],PIN_ICON_SIZE=/* @__PURE__ */zoomRamp(8,.6,22,.8),SELECTED_PIN_ICON_SIZE=/* @__PURE__ */zoomRamp(8,.8,22,1),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,valuesFilterKnobs=(e,t,i,s="")=>({show:{kind:"enum",description:`\`only\` keeps just the \`${e}.values\` ${t}, \`all-except\` every one but them; the filter applies once both are set.`,options:filterShowModes},values:{kind:"enums",description:`The ${t} \`${e}.show\` keeps alone or drops.${s}`,options:i}}),labelTypefaceKnob=(e,t,i=!0)=>({kind:"enum",description:`Typeface of the ${t}, each keeping its weight. Unset: the map's \`labels.customTypeface\`, otherwise its \`labels.typeface\`. A \`${e}.customTypeface\` of your own font files${i?`, or a \`${e}.font\`,`:""} wins over it.`,options:mapTypefaces}),withIds=e=>Object.keys(e).map(t=>({id:t,...e[t]})),defaultOf=e=>void 0===e?{}:{default:e},FACTOR_RANGE={min:.5,max:1.5,step:.1,bounds:"hard"},WIDE_FACTOR_RANGE=/* @__PURE__ */(()=>({...FACTOR_RANGE,max:2}))(),UNIT_RANGE={min:0,max:1,step:.05,bounds:"hard"},LABEL_SIZE_RANGE={min:6,max:48,step:1,bounds:"hard-min"},LABEL_HALO_WIDTH_RANGE={min:0,max:10,step:.5,bounds:"hard-min"},ZOOM_RANGE={min:0,max:22,step:1,bounds:"hard"},incidentColorKnobIds={minor:"traffic.incidents.colors.minor",moderate:"traffic.incidents.colors.moderate",major:"traffic.incidents.colors.major",indefinite:"traffic.incidents.colors.closed"},onStyleKnobsApplied=(e,t,i)=>{e._onStyleKnobsApplied(s=>{const o="function"==typeof t?t():t;e.mapReady&&o.some(e=>s.has(e))&&i()})},FONT_ROLES=/* @__PURE__ */ /* @__PURE__ */everyOf()(["regular","medium","bold","regularItalic","mediumItalic","boldItalic"]),SANS={regular:"Noto-Regular",medium:"Noto-Medium",bold:"Noto-Bold",regularItalic:"NotoSans-RegularItalic",mediumItalic:"NotoSans-MediumItalic",boldItalic:"NotoSans-BoldItalic"},SERIF={regular:"NotoSerif-Regular",medium:"NotoSerif-Medium",bold:"NotoSerif-Bold",regularItalic:"NotoSerif-RegularItalic",mediumItalic:"NotoSerif-MediumItalic",boldItalic:"NotoSerif-BoldItalic"},inItalics=e=>({...e,regular:e.regularItalic,medium:e.mediumItalic,bold:e.boldItalic}),upright=e=>({...e,regularItalic:e.regular,mediumItalic:e.medium,boldItalic:e.bold}),FACES_BY_TYPEFACE={"sans-italic":/* @__PURE__ */inItalics(SANS),serif:SERIF,"serif-italic":/* @__PURE__ */inItalics(SERIF)},BACKSTOP=/* @__PURE__ */upright(SANS),builtInTypeface=e=>(e=>"string"==typeof e&&Object.hasOwn(FACES_BY_TYPEFACE,e))(e)?FACES_BY_TYPEFACE[e]:void 0,SDK_NAME="(?:tomtom-sdk-face-|tomtom-sdk-role-)[a-zA-Z0-9]+",SDK_NAME_IN_STACK=/* @__PURE__ */(()=>new RegExp(`${SDK_NAME},`,"g"))(),SDK_NAME_IN_JSON_STACK=/* @__PURE__ */(()=>new RegExp(`"${SDK_NAME}",`,"g"))(),withoutCustomFaceDeclarations=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!e.startsWith("tomtom-sdk-face-"))),customTypefaces=/* @__PURE__ */new WeakMap,customTypefaceOf=e=>customTypefaces.get(e),typefaceOf=(e,t)=>customTypefaceOf(e)??builtInTypeface(t),roleByServedFace=/* @__PURE__ */(()=>new Map([...[SANS,SERIF].flatMap(e=>FONT_ROLES.map(t=>[e[t],t])),["NotoSans-Condensed","regular"],["NotoSans-CondensedMedium","medium"],["NotoSans-CondensedBold","bold"]]))(),roleOf=e=>roleByServedFace.get(e)??(e=>{const t=e.startsWith("tomtom-sdk-role-")?e.slice(16):void 0;return FONT_ROLES.find(e=>e===t)})(e),isFace=e=>"string"==typeof e&&(roleByServedFace.has(e)||e.startsWith("tomtom-sdk-")),retypeset=(e,t)=>{const i=Array.isArray(e)&&e.every(isFace)?e.map(roleOf).find(Boolean):void 0;return void 0!==i?((e,t)=>{const i=t[e];return i===BACKSTOP[e]?[i]:i.startsWith("tomtom-sdk-face-")?[i,`tomtom-sdk-role-${e}`,BACKSTOP[e]]:[i,BACKSTOP[e]]})(i,t):Array.isArray(e)?e.map(e=>retypeset(e,t)):(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"text-font"in e)(e)?{...e,"text-font":retypeset(e["text-font"],t)}:e},inTypeface=(e,t)=>void 0===t?e:retypeset(e,t),withMapTypeface=(e,t)=>void 0===e.layout||void 0===t?e:{...e,layout:{...e.layout,...void 0!==e.layout["text-font"]&&{"text-font":inTypeface(e.layout["text-font"],t)},...void 0!==e.layout["text-field"]&&{"text-field":inTypeface(e.layout["text-field"],t)}}},mapTypefaceOf=e=>typefaceOf(e,e._styleKnobSettings["labels.typeface"]),onMapTypefaceChange=(e,t)=>onStyleKnobsApplied(e,["labels.typeface"],t),waitUntilMapIsReady=e=>{if(e.mapReady)return Promise.resolve();const t=e._styleLoadError;if(t)return Promise.reject(t);const i=e.mapLibreMap;return new Promise((t,s)=>{const o=()=>{i.off("styledata",r),a()},r=()=>{e.mapReady&&(o(),t())},a=e._onStyleLoadFailure(e=>{o(),s(e)});i.on("styledata",r)})},runWhenMapIsReady=(e,t)=>{e.mapReady?t():waitUntilMapIsReady(e).then(t,()=>{})},trimmedPath=e=>e.pathname.replace(/\/$/,""),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}},vectorTileSourceIds=e=>Object.entries(e.getStyle()?.sources??{}).filter(([,e])=>"vector"===e.type&&e.tiles?.some(isVectorTileUrl)).map(([e])=>e),reloadTiles=(e,t)=>{for(const i of t){if(!e.getSource(i))continue;const t=e.style.tileManagers[i];for(const e of t?.getIds()??[]){const i=t.getTileByID(e);i&&(i.etag=void 0)}e.refreshTiles(i)}},sdkTransformRequest=e=>{const t=e.commonBaseURL??DEFAULT_COMMON_BASE_URL,i=t!==DEFAULT_COMMON_BASE_URL,s=isProxyCredentialsMode(e),o=i?(e=>{try{return trimmedPath(new URL(e))}catch{return""}})(t).length:0;return(r,a)=>{const n="Glyphs"===a?r.replace(SDK_NAME_IN_STACK,""):r,l=((e,t,i,s)=>{if(!i)return e;try{const i=new URL(e);return"api.tomtom.com"===(o=i.hostname)||o.endsWith(".api.tomtom.com")?(s&&i.searchParams.delete("key"),t+i.pathname+i.search+i.hash):e}catch{return e}var o})(n,t,i,s),c=i&&((e,t)=>{try{const i=new URL(e),s=new URL(t),o=trimmedPath(s);return i.origin===s.origin&&(i.pathname===o||i.pathname.startsWith(`${o}/`))}catch{return!1}})(l,t),d=s&&c;let u=!1;try{const e=new URL(n).hostname;u="tomtom.com"===e||e.endsWith(".tomtom.com")}catch{u=!1}if(!u&&!c)return{url:l};if("Image"===a)return d?{url:l,credentials:"include"}:{url:l};const h=new URL(l);((e,t,i)=>{if(t.includes("incidents")){e.searchParams.set("tags",INCIDENT_TAGS.join(","));const t=trafficIncidentLanguage(i);t&&e.searchParams.set("language",t)}else t.includes("flow")&&e.searchParams.set("tags",FLOW_TAGS.join(","))})(h,h.pathname.slice(c?o:0),e.language),((e,t)=>{const i=vectorTileViewParameter(e),s=t&&(e=>{if(servesGeopoliticalView(e,"mapTiles"))return"AE"===e?"Arabic":e})(t);i&&s&&e.searchParams.set(i,s)})(h,e.geopoliticalView);const p={url:h.toString(),headers:{...generateTomTomHeaders(e)}};return d&&(p.credentials="include"),p}},transformRequest=e=>{const t=sdkTransformRequest(e),i=e.transformRequest;return i?(e,s)=>i(t(e,s),s):t},changeLayerProps=(e,t,i)=>{const s=e.id;e.maxzoom===t.maxzoom&&e.minzoom===t.minzoom||i.setLayerZoomRange(s,e.minzoom??0,e.maxzoom??24),isEqual(e.filter,t.filter)||i.setFilter(s,e.filter,{validate:!1});for(const o of Object.keys(t.layout??{}))void 0===e.layout?.[o]&&i.setLayoutProperty(s,o,void 0,{validate:!1});for(const o of Object.keys(t.paint??{}))void 0===e.paint?.[o]&&i.setPaintProperty(s,o,void 0,{validate:!1});for(const[o,r]of Object.entries(e.paint??{}))isEqual(r,t.paint?.[o])||i.setPaintProperty(s,o,r,{validate:!1});for(const[o,r]of Object.entries(e.layout??{}))isEqual(r,t.layout?.[o])||i.setLayoutProperty(s,o,r,{validate:!1})},existingAnchorLayerID=(e,t)=>{if(!t)return;if(e.getLayer(t))return t;const i=t===mapStyleLayerIDs.lowest3D?mapStyleLayerIDs.poi:void 0;return i&&e.getLayer(i)?i:void 0},customLayerAnchorsByMap=/* @__PURE__ */new WeakMap,customLayerAnchorsOf=e=>ofMap(customLayerAnchorsByMap,e,()=>new globalThis.Map),existingBeforeLayerID=(e,t)=>{const i=existingAnchorLayerID(e,t);return belowCustomLayersAsking(e,i,e=>e===t||e===i)},belowCustomLayersAsking=(e,t,i)=>{const s=customLayerAnchorsByMap.get(e);if(!s?.size)return t;const o=e.getLayersOrder();let r=t?o.indexOf(t):o.length;for(let a=r-1;a>=0&&s.has(o[a]);a--)i(s.get(o[a]))&&(r=a);return o[r]},moveLayerBefore=(e,t,i)=>{e.moveLayer(t,existingBeforeLayerID(e,i))},applyLayersVisibility=(e,t,i)=>{if(i._removed)return;const s=t?"visible":"none";for(const o of e)"none"!==o.layout?.visibility&&i.getLayer(o.id)&&i.setLayoutProperty(o.id,"visibility",s,{validate:!1})},addLayers=(e,t,i=!1)=>{const s=ModuleSourcesAndLayers.for(t),o=/* @__PURE__ */new Set,r=e=>{!s.addLayer({...e,layout:{...e.layout,visibility:"none"}})&&i&&moveLayerBefore(t,e.id,e.beforeID),o.add(e.id)},a={},n=new Set(e.map(e=>e.id)),l=new Set(e.filter(e=>i||s.isCarried(e.id)).map(e=>e.id));for(e.forEach(e=>{var i;e.beforeID?(i=e.beforeID,o.has(i)||!l.has(i)&&(!n.has(i)||t.getLayer(i))?(o.add(e.beforeID),r(e)):a[e.beforeID]?a[e.beforeID].push(e):a[e.beforeID]=[e]):r(e)});Object.keys(a).length>0;){const e=Object.keys(a).filter(e=>o.has(e));if(!e.length)return void console.error(`Some layers cannot be added. Check for circular beforeID dependencies for the following: ${JSON.stringify(Object.keys(a))}`);e.forEach(e=>{a[e].forEach(e=>r(e)),delete a[e]})}},addOrUpdateImage=async(e,t,i,s,o,r=()=>!0)=>{if(void 0===i)return;if(!i)return void console.warn(`addOrUpdateImage called with empty image for ID ${t}`);if("if-not-in-sprite"===e&&s.hasImage(t))return;const a=i=>{if(s._removed||!r())return;if(!s.hasImage(t))return void s.addImage(t,i,o);if("if-not-in-sprite"===e)return;const a=s.getImage(t);a.data.width===i.width&&a.data.height===i.height&&a.pixelRatio===(o?.pixelRatio??1)?s.updateImage(t,i):(s.removeImage(t),s.addImage(t,i,o))},n=()=>console.warn(`Failed to load image for ID ${t}`),l=e=>e.naturalWidth>0?a(e):n(),c=e=>{if(e)if(e.complete)l(e);else{const t=new AbortController,i={once:!0,signal:t.signal};e.addEventListener("load",()=>{t.abort(),l(e)},i),e.addEventListener("error",()=>{t.abort(),n()},i)}};if("string"==typeof i){const e=/^data:image\/svg\+xml[;,]/i.test(i);if(!e&&i.includes("<svg"))c(svgMarkupToImg(i));else if(e||/\.svg(?:[?#]|$)/i.test(i))c(urlToImg(i));else try{a((await s.loadImage(i)).data)}catch(d){console.warn(`Failed to load image for ID ${t}`,d)}}else c(i)},imageLoadTokens=/* @__PURE__ */new WeakMap,imageLoadTokensOf=e=>ofMap(imageLoadTokens,e,()=>({})),latestImageLoad=(e,t,i=!1)=>{const s=imageLoadTokensOf(e);i&&s[t]||(s[t]={});const o=s[t];return()=>s[t]===o},syncImages=(e,t,i)=>{const s=imageLoadTokensOf(e);for(const o of Object.keys(t))o in i||(delete s[o],e.hasImage(o)&&e.removeImage(o));for(const[o,{image:r,pixelRatio:a}]of Object.entries(i)){const i=t[o],s=i?.image===r&&i.pixelRatio===a;addOrUpdateImage(s?"if-not-in-sprite":"add-or-update",o,r,e,{pixelRatio:a},latestImageLoad(e,o,s))}return{...i}},standardStyleIdOf=e=>("string"==typeof e?e:e?.id)??"streetLight",getStyleLightDarkTheme=e=>{return(t=standardStyleIdOf(e)).includes("Dark")||"streetSatellite"===t?"dark":"light";var t},pendingPinCategoriesSprites=/* @__PURE__ */new WeakMap,byMap=/* @__PURE__ */new WeakMap,ModuleSourcesAndLayers=class ModuleSourcesAndLayers{constructor(e){this.map=e,this.sourceIds=/* @__PURE__ */new Set,this.layerIds=/* @__PURE__ */new Set,this.carriedSourceIds=/* @__PURE__ */new Set,this.carriedLayerIds=/* @__PURE__ */new Set}static for(e){return ofMap(byMap,e,()=>new ModuleSourcesAndLayers(e))}addSource(e,t){this.sourceIds.add(e),this.carriedSourceIds.delete(e),this.map.getSource(e)||this.map.addSource(e,t)}addLayer(e){this.layerIds.add(e.id);const t=this.map.getLayer(e.id);if(!t)return this.map.addLayer(e,existingBeforeLayerID(this.map,e.beforeID)),!0;if(!this.carriedLayerIds.delete(e.id))return!1;const i=t.serialize();return changeLayerProps({...e,layout:{...e.layout,visibility:i.layout?.visibility}},i,this.map),moveLayerBefore(this.map,e.id,e.beforeID),!0}isCarried(e){return this.carriedLayerIds.has(e)}carryInto(e,t){if(this.carriedSourceIds.clear(),this.carriedLayerIds.clear(),!e)return t;const i={...t.sources},s=new Set(t.layers.map(e=>e.id)),o=/* @__PURE__ */new Map;let r=[];for(const n of e.layers){if(s.has(n.id)){r.length&&o.set(n.id,r),r=[];continue}if(!this.layerIds.has(n.id))continue;const t="source"in n?n.source:void 0;if(t&&!i[t]){if(!this.sourceIds.has(t))continue;i[t]=e.sources[t],this.carriedSourceIds.add(t)}this.carriedLayerIds.add(n.id),r.push(n)}const a=t.layers.flatMap(e=>[...o.get(e.id)??[],e]);return{...t,sources:i,layers:[...a,...r]}}dropUnadopted(){for(const e of this.carriedLayerIds)this.map.getLayer(e)&&this.map.removeLayer(e);for(const e of this.carriedSourceIds)this.map.getSource(e)&&this.map.removeSource(e);this.carriedLayerIds.clear(),this.carriedSourceIds.clear()}},TomTomMapSource=class{constructor(e,t,i){this.id=e,this.spec=t,this.runtimeSource=i}ensureAddedToMap(e){this.runtimeSource||(this.spec&&ModuleSourcesAndLayers.for(e).addSource(this.id,this.spec),this.runtimeSource=e.getSource(this.id))}},asDefined=e=>{if(null==e)throw new Error("A value must not be null/undefined. Something went wrong with its initialization.");return e},withSourceID=(e,t)=>({...e,source:t}),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))}queryRenderedFeatures(){const e=this._layerSpecs.filter(e=>this.isLayerVisible(e)).map(e=>e.id);return e.length?this.map.queryRenderedFeatures({layers:e,validate:!1}):[]}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}},layersOfSources=(e,t)=>e.filter(e=>"source"in e&&t.includes(e.source)),StyleSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i){const s=e.getStyle();let o=layersOfSources(s.layers,[t.id]);i&&(o=o.filter(i)),super(e,new TomTomMapSource(t.id,s.sources[t.id],t),o),this.eventStates=new globalThis.Map}setLayersVisibleThrough(e,t,i,s){for(const o of this.getLayerSpecs(s))e.setVisible(o.id,t,i)}eventStateKeyOf(e){if(void 0===e.id)return;const t=e.sourceLayer??null;return JSON.stringify([t,this.featureGroups?.groupOf(t,e.id)??e.id])}eventStateOf(e){return this.eventStates.get(e)}keysWithEventState(){return[...this.eventStates.keys()]}putEventState(e,t){t&&this.eventStates.get(e)===t||(t?this.eventStates.set(e,t):this.eventStates.delete(e),this.writeEventState(e,t))}takeEventStatesFrom(e){for(const[t,i]of e.eventStates)this.putEventState(t,i)}clearEventStates(){for(const e of this.eventStates.keys())this.putEventState(e,void 0)}rewriteEventStates(){for(const[e,t]of this.eventStates){const[i,s]=JSON.parse(e),o=JSON.stringify([i,this.featureGroups?.groupOf(i,s)??s]);if(o===e)continue;this.eventStates.delete(e);const r=this.eventStates.get(o);(!r||isClickEventType(t)&&!isClickEventType(r))&&this.eventStates.set(o,t)}for(const[e,t]of this.eventStates)this.writeEventState(e,t)}writeFeatureState(e,t,i){if(this.mapRemoved||!this.map.getSource(this.source.id))return;const s=Object.entries(i),o=Object.fromEntries(s.filter(([,e])=>void 0!==e)),r=s.filter(([,e])=>void 0===e).map(([e])=>e),a=this.featureGroups?.groupOf(e,t)??t;for(const n of this.featureGroups?.membersOf(e,a)??[a]){const t={source:this.source.id,id:n,...null===e?{}:{sourceLayer:e}};for(const e of r)this.map.removeFeatureState(t,e);r.length<s.length&&this.map.setFeatureState(t,o)}}writeEventState(e,t){const[i,s]=JSON.parse(e);this.writeFeatureState(i,s,{eventState:t,...this.eventStateLook?.(i,t)})}},AddedSourceWithLayers=class extends AbstractSourceWithLayers{constructor(e,t,i,s){super(e,new TomTomMapSource(t,i),s.map(e=>withSourceID(e,t)))}ensureLayersAddedToMap(){if(this.mapRemoved)return;const e=ModuleSourcesAndLayers.for(this.map);for(const t of this._layerSpecs)e.addLayer(t)}ensureAddedToMapWithVisibility(e,t){this.mapRemoved||(this.source.ensureAddedToMap(this.map),t&&(this.ensureLayersAddedToMap(),this.setLayersVisible(e)))}},propertyBySource=(e,t)=>Object.fromEntries(Object.entries(e).flatMap(([e,i])=>i?[[e,i[t]]]:[])),shownFeaturesOf=e=>propertyBySource(e,"shownFeatures"),withEventState=(e,t)=>{if(t)return{...e,properties:{...e.properties,eventState:t}};const{eventState:i,...s}=e.properties??{};return{...e,properties:s}},withShownEventStates=(e,t,i)=>{const s=indexByRefId(e.features);return{...t,features:t.features.map(e=>{const t=i(e),o=void 0===t?void 0:s.get(t)?.feature.properties?.eventState;return o||void 0!==e.properties?.eventState?withEventState(e,o):e})}},GeoJSONSourceWithLayers=class extends AddedSourceWithLayers{constructor(e,t,i,s=!0,o){super(e,t,o?.cluster?{type:"geojson",data:{type:"FeatureCollection",features:[]},...o}:{type:"geojson",data:{type:"FeatureCollection",features:[]},promoteId:"id",...o},i),this.shownFeatures={type:"FeatureCollection",features:[]},this.showListeners=[],this.eventStatesUnshown=!1,this.ensureAddedToMapWithVisibility(!1,s)}show(e,{automaticVisibility:t=!0}={}){if(this.shownFeatures=e,this.featuresById=void 0,this.eventStatesUnshown=!1,!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){if(void 0!==e)return this.featuresById??=indexByRefId(this.shownFeatures.features),this.featuresById.get(e)}clear(){this.show({type:"FeatureCollection",features:[]})}isEmpty(){return!this.shownFeatures.features.length}showUnlessStillEmpty(e,t){!e.features.length&&this.isEmpty()||this.show(e,t)}clearUnlessEmpty(){this.isEmpty()||this.clear()}findFeature(e){return void 0!==e.index?this.shownFeatures.features[e.index]:(this.featuresById?.get(e.id)??findFeatureByRefId(this.shownFeatures.features,e.id))?.feature}showWithFeatures(e,t=!0){const i={...this.shownFeatures,features:e};t?this.show(i,{automaticVisibility:!1}):(this.shownFeatures=i,this.featuresById=void 0,this.eventStatesUnshown=!0)}setEventState(e){const t=e.mode??"put",i=this.findFeature(e);let s=!1;const o=this.shownFeatures.features.map(o=>{const r=o.properties?.eventState;return(o===i?r===e.state:"add"===t||r!==e.state)?o:(s=!0,withEventState(o,o===i?e.state:void 0))});s?this.showWithFeatures(o,e.show):this.showUnshownEventStates(e.show)}showUnshownEventStates(e){!1!==e&&this.eventStatesUnshown&&this.showWithFeatures(this.shownFeatures.features)}clearEventState(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):this.showUnshownEventStates(e.show)}clearEventStates(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):this.showUnshownEventStates(e?.show)}getEventStates(e={}){for(const t of this.shownFeatures.features){const i=t.properties?.eventState,s=renderedRefId(t);if(!i||void 0===s)continue;const o=e[i]??=[];o.includes(s)||o.push(s)}return e}},CustomLayerSourceWithLayers=class{constructor(e,t,i){this.map=e,this.layerId=t,this.callbacks=i,this.hits=/* @__PURE__ */new WeakMap,this.eventStates=new globalThis.Map,this.detached=!1,this.source={id:`\0customLayer:${t}`},this._layerSpecs=[{id:t}]}hitFeatures(e){return this.map._removed||!this.map.getLayer(this.layerId)||"none"===this.map.getLayoutProperty(this.layerId,"visibility")?[]:this.callbacks.hitTest(e).map(e=>{const t={type:"Feature",id:e.id,properties:{...e.properties,id:e.id},layer:{id:this.layerId,type:"custom"},source:this.source.id,state:{}};return this.hits.set(t,e),t})}hitOf(e){return asDefined(this.hits.get(e))}eventStateKeyOf(e){return renderedRefId(e)}eventStateOf(e){return this.eventStates.get(e)}keysWithEventState(){return[...this.eventStates.keys()]}putEventState(e,t){this.detached||this.eventStates.get(e)===t||(t?this.eventStates.set(e,t):this.eventStates.delete(e),this.callbacks.setState?.(e,t))}detach(){this.detached=!0,this.eventStates.clear()}},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),s=andPredicates(e.featureMatches,t.featureMatches);return i||s?{layerFilter:i,featureMatches:s}:void 0},scopedLayerIDs=(e,t)=>e instanceof CustomLayerSourceWithLayers?[e.layerId]:(t?.layerFilter?e._layerSpecs.filter(t.layerFilter):e._layerSpecs).map(e=>e.id),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(", ")}.`)},roundToDecimals=(e,t)=>{const i=10**t;return Math.round(e*i)/i},mentionsZoom=e=>JSON.stringify(e).includes('"zoom"'),isLegacyFunction=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&Array.isArray(e.stops),scaleNumericValue=(e,t)=>mapNumericValue(e,e=>e*t,e=>["*",t,e]),wrapZoomFreeParts=(e,t)=>{if(!isLegacyFunction(e)){if(Array.isArray(e)&&("interpolate"===e[0]||"step"===e[0])){const i=e["interpolate"===e[0]?2:1];if(mentionsZoom(i))return mapRampOutputs(e,e=>wrapZoomFreeParts(e,t))}return mentionsZoom(e)?void 0:t(e)}},mapNumericValue=(e,t,i)=>{if("number"==typeof e)return roundToDecimals(t(e),3);const s=e=>mapNumericValue(e,t,i);return isLegacyFunction(e)?mapLegacyStops(e,s):Array.isArray(e)?"interpolate"===e[0]||"step"===e[0]?mapRampOutputs(e,s):mentionsZoom(e)?void 0:i(e):void 0},mapLegacyStops=(e,t)=>{const i=[];for(const[s,o]of e.stops){const e=t(o);if(void 0===e)return;i.push([s,e])}return{...e,stops:i}},mapRampOutputs=(e,t)=>{const i=[...e];for(let s="interpolate"===e[0]?4:2;s<i.length;s+=2){const e=t(i[s]);if(void 0===e)return;i[s]=e}return i},branchOn=(e,t,i,s)=>{const o=scaleNumericValue(t,i);if(void 0!==o)return void 0===s?["case",e,o,t]:["case",e,"number"==typeof o?Math.min(s,o):["min",s,o],t]},scaledWhen=(e,t,i,s)=>1===i||isLegacyFunction(t)?t:!Array.isArray(t)||"interpolate"!==t[0]&&"step"!==t[0]?branchOn(e,t,i,s)??t:mapRampOutputs(t,t=>branchOn(e,t,i,s))??t,shiftZoomOffset=(e,t)=>{let i=!1;const s=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(s):e;return{filter:s(e),patched:i}},registeredModes=/* @__PURE__ */new Set,ensureColorSpace=e=>(registeredModes.has(e.mode)||(useMode(e),registeredModes.add(e.mode)),converter(e.mode)),registeredColorSpaces=()=>({toRgb:ensureColorSpace(modeRgb),toHslSpace:ensureColorSpace(modeHsl)}),themeContrastColor=e=>"dark"===e?"#FFF":"#000",toHundredths=e=>roundToDecimals(e,2),NUMBER=String.raw`[\d.e+-]+`,CHANNEL_SEPARATOR=String.raw`(?:\s+|\s*,\s*)`,ALPHA_AND_CLOSE=String.raw`(?:\s*[,/]\s*${NUMBER}%?)?\s*\)$`,RGB=String.raw`rgba?\(\s*${NUMBER}(%?)${CHANNEL_SEPARATOR}${NUMBER}\1${CHANNEL_SEPARATOR}${NUMBER}\1${ALPHA_AND_CLOSE}`,HSL=String.raw`hsla?\(\s*${NUMBER}(?:deg)?${CHANNEL_SEPARATOR}${NUMBER}%${CHANNEL_SEPARATOR}${NUMBER}%${ALPHA_AND_CLOSE}`,STYLE_COLOR_SYNTAX=/* @__PURE__ */(()=>new RegExp(`^(?:#|[a-z]+$|${RGB}|${HSL})`))(),parseColor=e=>{registeredColorSpaces();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:s,b:o,alpha:r=1}=registeredColorSpaces().toRgb(t);return[i,s,o,r]},toHsl=e=>{const t=parseColor(e),{toRgb:i,toHslSpace:s}=registeredColorSpaces();return t&&s(i(t))},isColorLiteral=e=>"string"==typeof e&&void 0!==parseColor(e),formatStyleHsl=e=>formatHsl(roundStyleHsl(e)),roundStyleHsl=({h:e=0,s:t,l:i,alpha:s})=>({mode:"hsl",h:wrapDegrees(Math.round(e)),s:toHundredths(t),l:toHundredths(i),alpha:s}),opaqueColor=e=>{const t=toHsl(e);return t&&(t.alpha??1)<1?formatStyleHsl({...t,alpha:void 0}):e},clampUnit=e=>clamp(e,0,1),hslShiftBetween=(e,t)=>{const i=toHsl(e),s=toHsl(t);if(i&&s)return{h:i.s<.08||s.s<.08?0:(s.h??0)-(i.h??0),s:s.s-i.s,l:s.l-i.l,alpha:(s.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<.08?i.s:i.s+t.s,l:i.l+t.l,alpha:clampUnit((i.alpha??1)+t.alpha)})},relativeLuminance=e=>{ensureColorSpace(modeLrgb);const t=parseColor(e);return t&&wcagLuminance(t)},needsDarkText=e=>(relativeLuminance(e)??0)>.4,mixColor=(e,t,i)=>{const s=parseColor(e),o=parseColor(t);return s&&o&&formatHex(interpolate([s,o])(i))},colorRamp=(e,t,{space:i="rgb",reach:s=1}={})=>{"oklch"===i&&ensureColorSpace(modeOklch);const o=e.map(parseColor).filter(e=>void 0!==e);if(!o.length||o.length<e.length)return;const r=interpolate(o,i);return Array.from({length:t},(e,i)=>{const o=clampRgb(r(t>1?s*i/(t-1):0));return(o.alpha??1)<1?formatRgb(o):formatHex(o)})},darkerShadeOf=e=>mixColor(e,"#000000",.4),hueDistance=({h:e},{h:t})=>void 0===e||void 0===t?0:Math.abs(differenceHueNaive({h:e},{h:t})),shallowCopy=e=>Array.isArray(e)?[...e]:{...e},copyOf=e=>isObject(e)?shallowCopy(e):void 0,configWith=(e,t,i)=>setWith(shallowCopy(e),t,i,copyOf),describe=e=>"string"==typeof e?`'${e}'`:Array.isArray(e)?`[${e.map(describe).join(", ")}]`:null!==e&&"object"==typeof e?(e=>{try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}})(e):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:s})=>"soft"===s||e>=t&&("hard-min"===s||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 s=t.filter(e=>!i(e));return s.length?`expects ${e}; ${s.map(describe).join(", ")} ${1===s.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}.`)},knobValueIn=(e,t)=>get(e,t),configWithKnobs=(e,t)=>Object.entries(t).reduce((e,[t,i])=>configWith(e,t,i),e),configWithoutKnob=(e,t)=>{if(!has(e,t))return e;const i=configWith(e,t,void 0),s=toPath(t);unset(i,s);for(let o=s.length-1;o>0&&isEmpty(get(i,s.slice(0,o)));o--)unset(i,s.slice(0,o));return i},knobEntryOf=(e,t)=>{const i=e.find(e=>e.id===t);if(!i)throw new Error(`Unknown knob '${t}'; its catalogue lists every id.`);return i},setKnob=(e,t,i,s)=>{validateKnobValue(knobEntryOf(t,i),s),e._setKnobValues({[i]:s})},setKnobs=(e,t,i)=>{const s=Object.entries(i);for(const[o,r]of s)validateKnobValue(knobEntryOf(t,o),r);s.length&&e._setKnobValues(i)},getKnob=(e,t,i)=>{const s=knobEntryOf(t,i).default;return e._knobValue(i)??s},resetKnob=(e,t,i)=>{knobEntryOf(t,i),e._resetKnobValue(i)},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))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]],toExpressionFilter=e=>isExpressionFilter(e)?e:(e=>{const t=e[0];if(e.length<=1)return"any"!==t;const i=e[1],s=e.slice(2),o=e.slice(1);switch(t){case"has":return convertHas(i);case"!has":return["!",convertHas(i)];case"==":case"!=":return(null===s[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),s[0]];case">":case">=":case"<":case"<=":return((e,t,i)=>["all",["==",["typeof",propertyAccessor(t)],typeof i],[e,propertyAccessor(t),i]])(t,i,s[0]);case"in":return convertIn(i,s);case"!in":return["!",convertIn(i,s)];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}})(e),getMergedFilter=(e,t)=>t.length?1===t.length?t[0]:[e,...t]:null,isCompleteValuesFilter=e=>void 0!==e?.show&&void 0!==e.values,buildMappedValuesFilter=(e,t,i)=>{const s="string"==typeof e?["get",e]:e;if(1===i.length)return["only"===t?"==":"!=",s,i[0]];const o=["in",s,["literal",i]];return"only"===t?o:["!",o]},AbstractLayerComposer=class{constructor(e){this.byLayer=/* @__PURE__ */new Map,this.mapLibreMap=e.mapLibreMap;let t=e._styleLoads;e.addStyleChangeHandler({onStyleChanged:()=>{e._styleLoads!==t&&(t=e._styleLoads,this.byLayer.clear())},priority:Number.NEGATIVE_INFINITY})}contribute(e,t,i){const s=this.mapLibreMap;if(s._removed||!s.getLayer(e)||t&&!this.byLayer.has(e))return;const o=ofMap(this.byLayer,e,()=>this.snapshot(e));i(o),this.write(e,o)}},setOrDelete=(e,t,i)=>{void 0!==i?e.set(t,i):e.delete(t)},composersByMap$1=/* @__PURE__ */new WeakMap,LayerFilterComposer=class LayerFilterComposer extends AbstractLayerComposer{constructor(e){super(e)}static for(e){return ofMap(composersByMap$1,e,()=>new LayerFilterComposer(e))}setTransform(e,t,i){this.contribute(e,void 0===i,({transforms:e})=>setOrDelete(e,t,i))}setClause(e,t,i){this.contribute(e,void 0===i,({clauses:e})=>setOrDelete(e,t,i))}snapshot(e){return{styleFilter:this.mapLibreMap.getFilter(e),transforms:/* @__PURE__ */new Map,clauses:/* @__PURE__ */new Map}}write(e,t){const i=[...t.transforms.values()].reduce((e,t)=>t(e),t.styleFilter),s=((e,t)=>{if(!t.length)return e;const i=null==e?t:[...t,toExpressionFilter(e)];return getMergedFilter("all",i)??void 0})(i,[...t.clauses.values()]);this.mapLibreMap.setFilter(e,s??null,{validate:!1})}},ModuleEvents=class{constructor(e,t){this.configChangeHandlers=e,this.shownFeaturesHandlers=t}on(e,t){return((e,t)=>{const i=e=>t(e);return e.push(i),()=>{const t=e.indexOf(i);-1!==t&&e.splice(t,1)}})("config-change"===e?this.configChangeHandlers:this.shownFeaturesHandlers,t)}off(e){"config-change"===e?this.configChangeHandlers.length=0:this.shownFeaturesHandlers.length=0}},UserEvents=class UserEvents{constructor(e){this.options=e}where(e,t){return new UserEvents({...this.options,config:t?()=>t:this.options.config,scope:combineEventScopes(this.options.scope,this.resolveScope(e))})}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:s,owner:o,scope:r}=this.options,a=this.toRegisteredHandler(t),n=[];for(const l of this.options.sourcesWithLayers())i.addEventHandler(l,a,e,{config:s,owner:o,scope:r}),n.push(l.source.id);return()=>{for(const t of n)i.removeHandler(t,e,a)}}toRegisteredHandler(e){const{mapping:t,scope:i}=this.options,s=i?.featureMatches,o=e=>t?t(e):e;return s||t?s?(t,i,r,a)=>{if(!s(r[0]))return;const n=[o(r[0])];for(let e=1;e<r.length;e++)s(r[e])&&n.push(o(r[e]));e(n[0],i,n,a)}:(t,i,s,r)=>{const a=s.map(o);e(a[0],i,a,r)}:(t,i,s,o)=>e(t,i,s,o)}off(e){const{eventProxy:t,owner:i,sourceIds:s,sourcesWithLayers:o}=this.options;for(const r of s?.()??o().map(({source:e})=>e.id))t.remove(r,e,i)}},keepsEventStates=e=>"object"==typeof e&&null!==e&&"takeEventStatesFrom"in e,instanceCounters=/* @__PURE__ */new WeakMap,AbstractMapModule=class{get filterComposer(){return LayerFilterComposer.for(this.tomtomMap)}constructor(e,t){this.sourceIdsByName=new globalThis.Map,this._initializing=!0,this.configChangeHandlers=[],this.moduleReady=!1;const i=new.target,s=instanceCounters.get(i)??-1;this.instanceIndex=s+1,instanceCounters.set(i,this.instanceIndex),this.tomtomMap=e,this.eventsProxy=e._eventsProxy,this.mapLibreMap=e.mapLibreMap,this.initSourcesWithLayers(t),this.applyConfig(t),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;const i=t?this.sourcesWithLayers:void 0;this.sourcesWithLayers=this._initSourcesWithLayers(e,t);for(const s in this.sourcesWithLayers){const e=this.sourcesWithLayers[s];e&&this.sourceIdsByName.set(s,e.source.id);const t=i?.[s];keepsEventStates(e)&&keepsEventStates(t)&&e.takeEventStatesFrom(t)}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,t)=>{const i=setInterval(()=>{const s=this.tomtomMap._styleLoadError;this.mapLibreMap._removed?clearInterval(i):s?(clearInterval(i),t(s)):this.tomtomMap.mapReady&&this.moduleReady&&(clearInterval(i),e())},200)})}applyConfig(e){this.config=this._applyConfig(e),this.emitConfigChange()}updateConfig(e){this.applyConfig({...this.config,...e})}emitConfigChange(){if(this._initializing)return;const e=this.configChangeHandlers.slice();if(!e.length)return;const t=this.getConfig();for(const i of e)i(t)}resetConfig(){this.applyConfig(void 0)}restoreDataAndConfig(){this.moduleReady=!1,this.restoreDataAndConfigImpl()}resetOnNewStyle(){this.moduleReady=!1,this.config=void 0,this.discardShownData();for(const e in this.sourcesWithLayers){const t=this.sourcesWithLayers[e];keepsEventStates(t)&&t.clearEventStates()}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}}_knobValue(e){return knobValueIn(this.config,e)}_setKnobValues(e){this.applyConfig(configWithKnobs(this.config??{},e))}_resetKnobValue(e){if(!this.config)return;const t=configWithoutKnob(this.config,e);t!==this.config&&this.applyConfig(isEmpty(t)?void 0:t)}get sourceAndLayerIDs(){return propertyBySource(this.sourcesWithLayers,"sourceAndLayerIDs")}userEvents(e,t={}){return new UserEvents(this.userEventsOptions(e,t))}userEventsOptions(e,t){return{eventProxy:this.eventsProxy,sourcesWithLayers:()=>this.sourcesNamed(e),sourceIds:()=>e.flatMap(e=>this.sourceIdsByName.get(e)??[]),owner:this,config:()=>this.config?.events,mapping:t.mapping,scopeResolver:t.scopeResolver,scope:t.scope}}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}set(e){for(const t of this.sources())t.setEventState(e)}clear(e){for(const t of this.sources())t.clearEventState(e)}clearAll(e){for(const t of this.sources())t.clearEventStates(e)}get(){const e={};for(const t of this.sources())t.getEventStates(e);return e}},UserEventsWithStates=class extends UserEvents{constructor(e){super(e),this.eventStates=new EventStates(e.sourcesWithLayers)}setEventState(e){this.eventStates.set(e)}clearEventState(e){this.eventStates.clear(e)}clearEventStates(e){this.eventStates.clearAll(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))}setEventState(e){this.eventStates.set(e)}clearEventState(e){this.eventStates.clear(e)}clearEventStates(e){this.eventStates.clearAll(e)}getEventStates(){return this.eventStates.get()}replaceSourceLayers(e,t,i){((e,t,i,s)=>{const o=Object.fromEntries(e.map(e=>[e.id,e])),r=Object.fromEntries(t.map(e=>[e.id,e])),a=[],n=[],l=[],c=[];Object.keys(o).forEach(e=>{r[e]?(l.push(o[e]),c.push(r[e])):a.push(e)}),Object.keys(r).forEach(e=>{o[e]||n.push(e)});const d=i._layerSpecs;n.forEach(e=>{s.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=>withSourceID(o[e],i.source.id));u.length&&(d.push(...u),addLayers(u,s)),i._updateSourceAndLayerIDs(),((e,t,i,s)=>{const o=[...e,...i].filter(e=>s.getLayer(e.id)),r=new Set(e.filter((e,i)=>e.beforeID!==t[i].beforeID&&s.getLayer(e.id)).map(e=>e.id));for(let n=!0;n;){n=!1;for(const e of o)!r.has(e.id)&&void 0!==e.beforeID&&r.has(e.beforeID)&&(r.add(e.id),n=!0)}let a=o.filter(e=>r.has(e.id));for(;a.length;){const e=new Set(a.map(e=>e.id)),t=a.filter(t=>void 0===t.beforeID||!e.has(t.beforeID)),i=t.length?t:a;for(const o of i)moveLayerBefore(s,o.id,o.beforeID);a=a.filter(e=>!i.includes(e))}})(l,c,u,s),((e,t,i)=>{e.forEach((e,s)=>changeLayerProps(e,t[s],i))})(l,c,s);for(const h of l){const e=d.findIndex(e=>e.id===h.id);-1!==e&&(d[e]=withSourceID(h,i.source.id))}})(e,t,i,this.mapLibreMap),this.eventsProxy.updateIfRegistered(this.sourcesWithLayers,this)}},composersByMap=/* @__PURE__ */new WeakMap,LayerVisibilityComposer=class LayerVisibilityComposer extends AbstractLayerComposer{constructor(e){super(e)}static for(e){return ofMap(composersByMap,e,()=>new LayerVisibilityComposer(e))}setVisible(e,t,i){this.contribute(e,void 0===i,({contributions:e})=>setOrDelete(e,t,i))}snapshot(e){return{styleVisibility:this.mapLibreMap.getLayoutProperty(e,"visibility")??"visible",contributions:/* @__PURE__ */new Map}}write(e,t){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})(t),{validate:!1})}},AbstractStyleOwnedMapModule=class extends AbstractMapModule{get visibilityComposer(){return LayerVisibilityComposer.for(this.tomtomMap)}},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",linePatterns=["solid","dashed","dotted"],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))&&matchesOneOf(e.ids,t.id)&&((e,t)=>{const i=t.id.toLowerCase(),s=e=>i.includes(e.toLowerCase());return!(e.idIncludes&&!e.idIncludes.some(s)||e.idExcludes?.some(s))})(e,t),matchesAnyLayerSelector=(e,t,i)=>e.some(e=>matchesLayerSelector(e,t,i)),LayerPartToggles=class{constructor(e,t){this.contributor=e,this.selectors=t,this.layerIds=/* @__PURE__ */new Map,this.styleVisibility=/* @__PURE__ */new Map}index(e){this.layerIds=/* @__PURE__ */new Map,this.styleVisibility=/* @__PURE__ */new Map;for(const[t,i]of Object.entries(this.selectors)){const s=e.filter(e=>matchesAnyLayerSelector(i,e));this.layerIds.set(t,s.map(e=>e.id)),s.length&&this.styleVisibility.set(t,"none"!==s[0].layout?.visibility)}}apply(e,t){for(const[i,s]of this.layerIds){const o=knobValueIn(t,i),r="boolean"==typeof o?o:void 0;for(const t of s)e.setVisible(t,`${this.contributor}.${i}`,r)}}valueOf(e){return this.styleVisibility.get(e)}},instancesByMap=/* @__PURE__ */new WeakMap,sharedInstance=async(e,t,i,s)=>{const o=ofMap(instancesByMap,e,()=>/* @__PURE__ */new Map),r=o.get(t);if(r){const e=await r;return s?.(e),e}const a=Promise.resolve().then(i);o.set(t,a);try{return await a}catch(n){throw o.delete(t),n}},getStyleOwnedModule=async(e,t,i,s,o)=>(await waitUntilMapIsReady(e),o&&await(async(e,t,i)=>{if(!e.mapLibreMap.getSource(t)){const s=e.mapLibreMap;s.isStyleLoaded()||await s.once("idle"),await e.setStyle(((e,t)=>{switch(typeof e){case"undefined":return{type:"standard",include:[t]};case"string":return{type:"standard",id:e,include:[t]};default:return e.include?e.include.includes(t)?e:{...e,include:[...e.include,t]}:{...e,include:[t]}}})(e.getStyleInput(),i)),await waitUntilMapIsReady(e),await(async(e,t)=>{e.mapLibreMap.getSource(t)&&e.mapLibreMap.isSourceLoaded(t)||await e.mapLibreMap.once("sourcedata")})(e,t)}})(e,o.sourceId,o.part),sharedInstance(e,t,i,s?e=>e.applyConfig(s):void 0)),styleSourceWithLayers=(e,t,i,s)=>{const o=e.getSource(t);if(!o)throw new Error(`Trying to init ${i} with source ID ${t} while it is not in the map style. Did you exclude it when loading the map?`);return new StyleSourceWithLayers(e,o,s)},isPolygonalWithId=e=>void 0!==e.id&&("Polygon"===e.geometry.type||"MultiPolygon"===e.geometry.type),outlineAround=(e,{geometry:t})=>{const i=pointInsidePolygon("Polygon"===t.type?t.coordinates:t.coordinates[0]);let s;for(const o of e)(void 0===s||o.area<s.area)&&booleanPointInPolygon(i,o.geometry)&&(s=o);return s},BuildingParts=class{constructor(e,t){this.map=e,this.sourceId=t,this.version=0,this.groups=/* @__PURE__ */new Map,this.members=/* @__PURE__ */new Map,this.groupedVersion=-1,e.on("sourcedata",e=>{e.sourceId===t&&e.tile&&this.version++})}groupOf(e,t){return(e===this.sourceLayer?this.groups.get(t):void 0)??t}membersOf(e,t){return[t,...(e===this.sourceLayer?this.members.get(t):void 0)??[]]}buildingAt(e){const{sourceLayer:t}=this;if(void 0===t)return;const i=this.features(t,["!=",["get","underground"],!0]).filter(({geometry:t})=>booleanPointInPolygon(e,t)),s=minBy(i,({geometry:e})=>area(e));return s&&this.groupOf(t,s.id)}regroup(){const e=/* @__PURE__ */new Set,{sourceLayer:t}=this;if(void 0===t||this.groupedVersion===this.version)return e;this.groupedVersion=this.version;const i=this.features(t,["==",["get","part"],!0]).filter(({id:e})=>!this.groups.has(e));if(!i.length)return e;const s=this.features(t,["==",["get","has_part"],!0]).map(({id:e,geometry:t})=>({id:e,geometry:{...t,bbox:bbox(t)},area:area(t)}));for(const o of i){const t=outlineAround(s,o);t&&(this.groups.set(o.id,t.id),ofMap(this.members,t.id,()=>/* @__PURE__ */new Set).add(o.id),e.add(t.id))}return e}features(e,t){return this.map.querySourceFeatures(this.sourceId,{sourceLayer:e,filter:t}).filter(isPolygonalWithId)}},COLOR="fill-extrusion-color",BUILDING_COLOR_STATE="color",BUILDING_LOOK_STATES_color="eventStateColor",BUILDING_LOOK_STATES_intensity="eventStateIntensity",DEFAULT_BUILDING_STATE_INTENSITIES={hover:.35,click:.7},featureState=e=>["feature-state",e],withBuildingStates=e=>["interpolate",["linear"],["to-number",featureState("eventStateIntensity"),0],0,["to-color",featureState("color"),e],1,["to-color",featureState("eventStateColor"),"rgba(0, 0, 0, 0)"]],isWrapped=e=>JSON.stringify(e).includes("eventStateIntensity"),POI_MICRO_LAYER_ID=/* @__PURE__ */(()=>`${mapStyleLayerIDs.poi} - Micro`)(),poiLayerIDs=/* @__PURE__ */(()=>[mapStyleLayerIDs.poi,POI_MICRO_LAYER_ID])(),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],buildings3DExtrusionLayers=e=>e.filter(e=>"fill-extrusion"===e.type&&matchesLayerSelector(layerGroupMappings.buildings3D,e)),buildLayerGroupFilter=({show:e,values:t})=>{const i=e=>t.some(t=>isMatching(t,e));return"only"===e?i:e=>!i(e)},baseMapLayerFilter=e=>!poiLayerIDs.includes(e.id),roadPartSelectors={"roads.exitNumbers.visible":[{metadataGroups:["road_label"],layerTypes:["symbol"],idIncludes:["exit"]}],"roads.arrows.visible":[{metadataGroups:["road"],layerTypes:["symbol"],idIncludes:["arrow"]}],"roads.restricted.visible":[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["restricted"]}],"roads.underConstruction.visible":[{metadataGroups:["road"],layerTypes:["line"],idIncludes:["construction"]}]},featureIdOf$1=e=>{const t=Number(e);return Number.isSafeInteger(t)?t:e},knownGroupNames=baseMapLayerGroupNames,isGroupName=e=>knownGroupNames.includes(e),groupsVisible=(e,t)=>Object.fromEntries(e.map(e=>[e,{visible:t}])),groupsWithout=(e,t)=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>!(isGroupName(e)&&t.includes(e)))),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 s=t.flatMap(e=>i[e]),o=/* @__PURE__ */new Map,r=(e,t)=>{o.delete(e),o.set(e,t)};for(const a of t)r(a,e?.visible);for(const[a,n]of groupEntries(e?.groups)){const e=i[a],o=t.includes(a)||e.length&&containsAll(s,e)?[a]:t.filter(t=>i[t].length&&containsAll(e,i[t]));for(const t of o)r(t,n)}return Object.fromEntries([...o].map(([e,t])=>[e,void 0===t?{}:{visible:t}]))},BaseMapModule=class BaseMapModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,BaseMapModule,()=>new BaseMapModule(e,t),t)}constructor(e,t){super(e,t),this.buildingColors={},this.writtenBuildingColors={},this.mapLibreMap.on("idle",()=>{const{sourceLayer:e}=this.buildingParts;this.buildingLayerIds.some(e=>"none"!==this.mapLibreMap.getLayoutProperty(e,"visibility"))&&(Object.keys(this.buildingColors).length||this.buildingLayerIds.some(e=>this.eventsProxy.hasHandlerForLayer(e))||this.sourcesWithLayers.vectorTiles.keysWithEventState().some(t=>JSON.parse(t)[0]===e))&&this.regroupBuildings()})}_initSourcesWithLayers(){const e=styleSourceWithLayers(this.mapLibreMap,"vectorTiles",BaseMapModule.name,baseMapLayerFilter);this.layersByGroup=void 0,this.roadParts=new LayerPartToggles("baseMap",roadPartSelectors),this.roadParts.index(e._layerSpecs),this.buildingParts??=new BuildingParts(this.mapLibreMap,"vectorTiles");const t=buildings3DExtrusionLayers(e._layerSpecs);return this.buildingLayerIds=t.map(({id:e})=>e),this.buildingParts.sourceLayer=t[0]?.["source-layer"],e.featureGroups=this.buildingParts,e.eventStateLook=(e,t)=>e===this.buildingParts.sourceLayer?((e,t)=>{const i=(e=>isClickEventType(e)?"click":isHoverEventState(e)?"hover":void 0)(t),s=i&&e?.[i];return{[BUILDING_LOOK_STATES_color]:s?.color,[BUILDING_LOOK_STATES_intensity]:i&&s?.color?s.intensity??DEFAULT_BUILDING_STATE_INTENSITIES[i]:void 0}})(this.buildingLooks,t):{},{vectorTiles:e}}_applyConfig(e){return!e&&this._initializing||(this.writeVisibility(e),this.buildingLooks=e?.buildings3D,this.tomtomMap.mapReady&&this.sourcesWithLayers.vectorTiles.rewriteEventStates()),e}restoreDataAndConfigImpl(){super.restoreDataAndConfigImpl(),this.writeBuildingColors("all")}discardShownData(){this.setBuildingColors({})}_knobValue(e){return super._knobValue(e)??this.roadParts.valueOf(e)}_setKnobValues(e){const t=this.config??{},i=Object.keys(e).map(e=>e.split(".")).flatMap(([e,t])=>"groups"===e&&isGroupName(t)?[t]:[]),s=t.groups&&groupsWithout(t.groups,i);this.applyConfig(configWithKnobs(s?{...t,groups:s}:t,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,{groups:s,...o}=this.config??{};this.applyConfig(i?((e,{show:t,values:i},s,o)=>"all-except"===t?{...e,visible:s,groups:groupsAsRecorded(e,i,o)}:{...e,groups:{...groupsWithout(e?.groups,i),...groupsVisible(i,s)}})(this.config,i,e,this.groupedLayers()):{...o,visible:e})}setBuildingColors(e){this.buildingColors={...e},this.writeBuildingColors()}getBuildingColors(){return{...this.buildingColors}}getBuildingIdAt(e){return this.regroupBuildings(),this.buildingParts.buildingAt(getPositionStrict(e))}regroupBuildings(){const e=this.buildingParts.regroup();e.size&&(this.writeBuildingColors(e),this.sourcesWithLayers.vectorTiles.rewriteEventStates())}writeBuildingColors(e){const{sourceLayer:t}=this.buildingParts;if(!this.tomtomMap.mapReady||void 0===t)return;const i=this.writtenBuildingColors,s=e=>this.buildingParts.groupOf(t,featureIdOf$1(e)),o=(e,i)=>this.sourcesWithLayers.vectorTiles.writeFeatureState(t,featureIdOf$1(e),{[BUILDING_COLOR_STATE]:i}),r=/* @__PURE__ */new Set;for(const a of Object.keys(i))a in this.buildingColors||(o(a),r.add(s(a)));for(const[a,n]of Object.entries(this.buildingColors)){const t=s(a);(i[a]!==n||"all"===e||e?.has(t)||r.has(t))&&o(a,n)}this.writtenBuildingColors=this.buildingColors}writeVisibility(e){if(this.tomtomMap.mapReady){for(const[t,i]of this.layerSettings(e))this.visibilityComposer.setVisible(t,"baseMap.visible",i);this.roadParts.apply(this.visibilityComposer,e)}}layerSettings(e,t){const i=this.groupedLayers(),s=/* @__PURE__ */new Map;for(const[r,a]of groupEntries(e?.groups))for(const e of i[r])s.set(e,a);const o=/* @__PURE__ */new Map;for(const r of this.sourcesWithLayers.vectorTiles._layerSpecs)t&&!t(r)||o.set(r.id,s.has(r.id)?s.get(r.id):e?.visible);return o}getLayers(){return Object.fromEntries(Object.entries(this.groupedLayers()).map(([e,t])=>[e,[...t]]))}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"},roadPartContents={exitNumbers:"Motorway exit number badges",arrows:"One-way arrows drawn on roads",restricted:"Dashed marking of roads with restricted access",underConstruction:"Roads under construction"},buildingStateContents={hover:"the 3D building under the pointer",click:"the clicked 3D building, until the next click lands elsewhere"},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)})),...Object.keys(roadPartContents).map(e=>({id:`roads.${e}.visible`,kind:"toggle",description:`${roadPartContents[e]}; never shown while its layer group is hidden.`})),...Object.keys(buildingStateContents).flatMap(e=>[{id:`buildings3D.${e}.color`,kind:"color",description:`Colour ${buildingStateContents[e]} turns towards, while a handler of the base map's events reaches it. Unset: it stays as drawn.`},{id:`buildings3D.${e}.intensity`,kind:"number",description:`How far ${buildingStateContents[e]} turns towards its colour, 0 (not at all) to 1.`,range:UNIT_RANGE,default:DEFAULT_BUILDING_STATE_INTENSITIES[e]}])],baseMapKnobCatalogue=/* @__PURE__ */buildCatalogue$2(),baseMapKnobIds=/* @__PURE__ */baseMapKnobCatalogue.map(({id:e})=>e),isSameEventFamily=(e,t)=>isClickEventType(e)&&isClickEventType(t)||isHoverEventState(e)&&isHoverEventState(t),canReplaceEventState=(e,t)=>"recently-hovered"===t?isHoverEventState(e):!isClickEventType(e)||isClickEventType(t),setEventState=(e,t,i,s="updateInProps")=>{const o=findFeatureByRefId(i,t),r=o?.feature.properties?.eventState,a="updateInProps"===s?e:void 0;if(o&&r!==a&&canReplaceEventState(r,e))return i.splice(o.index,1,withEventState(o.feature,a)),o.index},leaveEventState=(e,t,i,s)=>s?setEventState("recently-hovered",t,i):setEventState(e,t,i,"removeFromProps"),isSameRenderedFeature=(e,t)=>e.source===t.source&&renderedRefId(e)===renderedRefId(t)&&isCluster(e)===isCluster(t),isSameHoverTarget=(e,t)=>isSameRenderedFeature(e,t)&&(e.layer.id===t.layer.id||void 0!==renderedRefId(e)),keeperOf=e=>e&&"eventStateKeyOf"in e?e:void 0,putKeptEventState=(e,t,i,s="updateInProps")=>{const o=e.eventStateKeyOf(i);void 0!==o&&canReplaceEventState(e.eventStateOf(o),t)&&e.putEventState(o,"updateInProps"===s?t:void 0)},leaveEventStateOf=(e,t,i,s)=>{if(i instanceof GeoJSONSourceWithLayers)return void((e,t,i,s)=>{const o=[...i.shownFeatures.features];void 0!==leaveEventState(e,shownRefId(t),o,s)&&i.show({...i.shownFeatures,features:o},{automaticVisibility:!1})})(e,t,i,s);const o=keeperOf(i);o&&(s?putKeptEventState(o,"recently-hovered",t):putKeptEventState(o,e,t,"removeFromProps"))},updateEventState=(e,t,i,s,o,r=!1)=>{if(t&&s instanceof GeoJSONSourceWithLayers){const a=[...s.shownFeatures.features];let n=void 0!==setEventState(e,shownRefId(t),a);return i&&!isSameRenderedFeature(i,t)&&(o===s?n=void 0!==leaveEventState(e,shownRefId(i),a,r)||n:leaveEventStateOf(e,i,o,r)),n=((e,t,i)=>{let s=!1;return i.forEach((o,r)=>{renderedRefId(o)!==t&&isSameEventFamily(o.properties?.eventState,e)&&(i[r]=withEventState(o,void 0),s=!0)}),s})(e,shownRefId(t),a)||n,void(n&&s.show({...s.shownFeatures,features:a},{automaticVisibility:!1}))}const a=keeperOf(s);if(!t||!a)return void(i&&leaveEventStateOf(e,i,o,r));i&&!isSameRenderedFeature(i,t)&&leaveEventStateOf(e,i,o,r);const n=a.eventStateKeyOf(t);for(const l of a.keysWithEventState())l!==n&&isSameEventFamily(a.eventStateOf(l),e)&&a.putEventState(l,void 0);putKeptEventState(a,e,t)},emitShownFeatures=(e,t)=>{for(const i of e.slice())i(t)},beforeLayerTargetOf=(e,t)=>"string"==typeof e?e:e?.[t]??e?.all,beforeLayerIDOf=(e,t)=>"top"===e?t:mapStyleLayerIDs[e],partBeforeLayerIDOf=(e,t,i)=>{const s=beforeLayerTargetOf(e,t);return void 0===s?i:beforeLayerIDOf(s)},CustomGeoJSONModule=class CustomGeoJSONModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),validateConfig(t),new CustomGeoJSONModule(e,t)}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 s={};for(const o of Object.keys(i.sources)){const e=this.resolvedSourceIDs[o],t=this.resolvedLayerSpecs[o],r=i.sources[o].cluster;s[o]=new GeoJSONSourceWithLayers(this.mapLibreMap,e,t,!1,r)}return addLayers(Object.values(s).flatMap(e=>e._layerSpecs),this.mapLibreMap),s}registerImages(e){this.addedImages??=/* @__PURE__ */new Map;for(const t of this.addedImages.keys())this.mapLibreMap.hasImage(t)||this.addedImages.delete(t);if(e.images)for(const[t,i]of Object.entries(e.images)){if(this.mapLibreMap.hasImage(t)){const e=this.addedImages.get(t);if(!e||e.image===i.image&&isEqual(e.options,i.options))continue;this.mapLibreMap.removeImage(t)}this.mapLibreMap.addImage(t,i.image,i.options),this.addedImages.set(t,i)}}sourceIDOf(e,t){return t.sources[e].sourceID??`custom-geojson-${this.instanceIndex}-${String(e)}`}assertSameSources(e){const t=Object.keys(e.sources);if(t.length!==Object.keys(this.resolvedSourceIDs).length||!t.every(t=>this.resolvedSourceIDs[t]===this.sourceIDOf(t,e)))throw new Error("CustomGeoJSONModule keeps the source names and sourceIDs it was created with. Recreate the module to change them.")}resolveIDs(e){const t={},i={};for(const s of Object.keys(e.sources)){const o=e.sources[s],r=this.sourceIDOf(s,e);t[s]=r,i[s]=o.layers.map(({beforeLayerConfig:t=e.beforeLayerConfig??"top",...i},s)=>({...i,id:i.id??`${r}-layer-${s}`,beforeID:beforeLayerIDOfCustom(t)}))}this.resolvedSourceIDs=t,this.resolvedLayerSpecs=i}_applyConfig(e){if(!e)return this._applyConfig(this.initialConfig);this.initialConfig??=e;const t=this.config;t&&this.assertSameSources(e);const i=t?this.resolvedLayerSpecs:void 0;return this.resolveIDs(e),this.registerImages(e),t&&i&&this.updateLayersForExistingSources(i),this.applyVisibility(e),e}updateLayersForExistingSources(e){const t=Object.keys(this.resolvedLayerSpecs).filter(t=>e[t]&&this.sourcesWithLayers[t]).map(t=>{const i=e[t],s=this.resolvedLayerSpecs[t].filter(e=>i.some(t=>t.id===e.id&&t.type===e.type));return this.replaceSourceLayers(s,i,this.sourcesWithLayers[t]),[t,s]});for(const[o,r]of t){const e=this.resolvedLayerSpecs[o];r.length!==e.length&&(this.replaceSourceLayers(e,r,this.sourcesWithLayers[o]),this.stackAddedInArrayOrder(e,r))}const i=Object.values(this.sourcesWithLayers).flatMap(e=>e._layerSpecs),s=new Set(i.map(e=>e.id));addLayers(i.filter(e=>e.beforeID&&s.has(e.beforeID)),this.mapLibreMap,!0)}stackAddedInArrayOrder(e,t){for(let i=e.length-2;i>=0;i--){const s=e[i];if(t.includes(s))continue;const o=e.find((e,t)=>t>i&&e.beforeID===s.beforeID);o&&moveLayerBefore(this.mapLibreMap,s.id,o.id)}}applyVisibility(e){const t=!1!==e?.visible;for(const i of this.sourceNames())this.applySourceVisibility(i,t)}applySourceVisibility(e,t){const i=!!this.sourcesWithLayers[e].shownFeatures.features.length;applyLayersVisibility(this.resolvedLayerSpecs[e],t&&i,this.mapLibreMap)}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.drawOnSource(t,i)}async show(e,t){await this.waitUntilModuleReady();const i=ensureFeatureIDs(e);if(void 0!==t)this.showOnSource(t,i);else for(const s of this.sourceNames())this.showOnSource(s,i)}showOnSource(e,t){this.drawOnSource(e,t),emitShownFeatures(this.shownFeaturesHandlers,{sourceName:e,data:t})}drawOnSource(e,t){const i=this.sourcesWithLayers[e],s=!i.shownFeatures.features.length;i.show(t,{automaticVisibility:!1}),this.shownSourceNames.add(e),s!==!t.features.length&&this.applySourceVisibility(e,this.isVisible())}async clear(e){if(await this.waitUntilModuleReady(),void 0!==e)return this.sourcesWithLayers[e].clear(),void this.shownSourceNames.delete(e);for(const t of this.sourceNames())this.sourcesWithLayers[t].clear();this.shownSourceNames.clear()}getShown(){return shownFeaturesOf(this.sourcesWithLayers)}eventStateSources(){return this.sourceNames()}sourceNames(){return Object.keys(this.sourcesWithLayers)}get events(){const e=this.sourceNames(),t={};for(const i of e)t[i]=this.userEventsWithStates([i]);return this.buildEvents(this.moduleEventsWithShown(e,this.shownFeaturesHandlers),t)}},beforeLayerIDOfCustom=e=>"string"==typeof e?beforeLayerIDOf(e):e.layerID,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,i=!1;for(const o of e.features)if(null==o.id||o.properties?.id!==o.id){i=!0;break}if(!i)return e;let s=0;return{...e,features:e.features.map((i,o)=>{if(null!=i.id&&i.properties?.id===i.id)return i;const r=i.id??i.properties?.id??(i=>{t??=new Set(e.features.map(e=>e.id??e.properties?.id));let o=Math.max(i,s);for(;t.has(o);)o++;return t.add(o),s=o+1,o})(o);return{...i,id:r,properties:{...i.properties,id:r}}})}},CustomLayer=class{constructor(e,t,i){this.removed=!1;const s=customLayerAnchorsOf(e.mapLibreMap);if(s.has(t.id)||e.mapLibreMap.getLayer(t.id))throw new Error(`The map already has a layer with the id '${t.id}'.`);this.map=e,this.layer=t,this.options=i,this.id=t.id;const o=e._eventsProxy,r=i.hitTest?new CustomLayerSourceWithLayers(e.mapLibreMap,t.id,i):void 0;this.hitSource=r,r&&o.addCustomLayer(r),this.events=new UserEvents({eventProxy:o,sourcesWithLayers:()=>r&&!this.removed?[r]:[],owner:this,config:()=>i.events,mapping:r&&(e=>r.hitOf(e))}),s.set(this.id,this.anchorLayerID()),this.stopRestoring=e.addStyleChangeHandler({priority:-1,onStyleChanged:()=>this.place()}),runWhenMapIsReady(this.map,()=>this.place())}remove(){if(this.removed)return;this.removed=!0,this.stopRestoring(),this.hitSource&&this.map._eventsProxy.removeCustomLayer(this.hitSource);const e=this.map.mapLibreMap;customLayerAnchorsOf(e).delete(this.id),!e._removed&&e.getLayer(this.id)&&e.removeLayer(this.id)}place(){if(this.removed)return;const e=this.map.mapLibreMap,t=((e,t)=>{const i=existingAnchorLayerID(e,t);return i===t?i:belowCustomLayersAsking(e,i,e=>e===i)})(e,this.anchorLayerID());e.getLayer(this.id)?e.moveLayer(this.id,t):e.addLayer(this.layer,t)}anchorLayerID(){return beforeLayerIDOf(this.options.beforeLayerConfig??"top")}},customGeoJSONKnobDefinitions={visible:{kind:"toggle",description:"Every layer of every source.",default:!0}},customGeoJSONKnobCatalogue=/* @__PURE__ */withIds(customGeoJSONKnobDefinitions),customGeoJSONKnobIds=/* @__PURE__ */customGeoJSONKnobCatalogue.map(({id:e})=>e),mapAccentColor=e=>e.mapColors.accent,onMapColorsChange=(e,t,i)=>{let s=pickKeys(e.mapColors,t);e._onMapColorsChange(e=>{const o=pickKeys(e,t);isEqual(o,s)||(s=o,i())})},onAccentColorChange=(e,t)=>onMapColorsChange(e,["accent"],t),NEAREST_FIRST={regular:["regular","medium","bold"],medium:["medium","regular","bold"],bold:["bold","medium","regular"]},LATIN=["U+0000-00FF","U+0131","U+0152-0153","U+02BB-02BC","U+02C6","U+02DA","U+02DC","U+0304","U+0308","U+0329","U+2000-206F","U+20AC","U+2122","U+2191","U+2193","U+2212","U+2215","U+FEFF","U+FFFD"],nearest=(e,t)=>NEAREST_FIRST[t].map(t=>e[t]).find(e=>void 0!==e),declaredTypefaces=/* @__PURE__ */new WeakMap,declareCustomTypeface=e=>ofMap(declaredTypefaces,e,()=>(e=>{const t={regular:e.regular,medium:e.medium,bold:e.bold},i={regular:e.regularItalic,medium:e.mediumItalic,bold:e.boldItalic},s=e.unicodeRange??LATIN,o={},r=(r,a)=>{const n=(a?nearest(i,r):void 0)??nearest(t,r)??e.regular,l=("string"==typeof n?[{url:n,unicodeRange:s}]:n).map(e=>({url:e.url,"unicode-range":[...e.unicodeRange]})),c=`tomtom-sdk-face-${(e=>{let t=0;for(const i of e)t=Math.imul(31,t)+(i.codePointAt(0)??0);return(t>>>0).toString(36)})(JSON.stringify(l))}`;return o[c]=l,c};return{typeface:{regular:r("regular",!1),medium:r("medium",!1),bold:r("bold",!1),regularItalic:r("regular",!0),mediumItalic:r("medium",!0),boldItalic:r("bold",!0)},fontFaces:o}})(e)),labelTypefaceOf=(e,t)=>{return(e?.customTypeface&&declareCustomTypeface(e.customTypeface).typeface)??(i=e?.typeface,"sans"===i?SANS:builtInTypeface(i))??t;var i},customFacesOf=e=>Object.assign({},...e.map(e=>e?.customTypeface&&declareCustomTypeface(e.customTypeface).fontFaces)),declarations=/* @__PURE__ */new WeakMap,fontFacesToSet=(e,{faces:t})=>{const i=e.mapLibreMap.getFontFaces()??{},s=Object.assign(withoutCustomFaceDeclarations(i),...t.values());return isEqual(i,s)?void 0:s},runWaiting=({waiting:e})=>{const t=[...e.values()];e.clear();for(const i of t)i()},syncFontFaces=(e,t)=>{const i=e.mapLibreMap;if(!fontFacesToSet(e,t))return runWaiting(t),!1;const s=()=>{const s=fontFacesToSet(e,t);s&&i.setFontFaces(isEmpty(s)?null:s),runWaiting(t)},o=()=>{i.loaded()&&(i.off("render",o),t.pendingRender=void 0,s())};return isEmpty(i.getFontFaces())||i.loaded()?s():t.pendingRender||(t.pendingRender=o,i.on("render",o)),!0},declareFontFaces=(e,t,i)=>{const s=isEmpty(i)?void 0:i,o=declarations.get(e);if(o?.waiting.delete(t),!s&&!o?.faces.has(t))return!1;const r=(e=>ofMap(declarations,e,()=>{const t={faces:/* @__PURE__ */new Map,waiting:/* @__PURE__ */new Map};return e.addStyleChangeHandler({onStyleChanged:()=>{syncFontFaces(e,t)}}),t}))(e);return s?r.faces.set(t,s):r.faces.delete(t),e.mapReady&&syncFontFaces(e,r)},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"},byOutlineFillStyle=(e,t)=>["case",["==",["get","fillStyle"],"outline"],e,t],BORDER_LABEL_OFFSET=[0,1],themeAdaptiveLabelColors=e=>({textColor:"dark"===e?"#FFFFFF":"#333333",haloColor:"dark"===e?"#333333":"#FFFFFF"}),themeAdaptiveLabelShadeOf=(e,t)=>("dark"===t?(e=>mixColor(e,"#ffffff",.4))(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}}),featureTitle=(e,t,i)=>"function"==typeof t?t(e):i(e),titleTextField=(e,t)=>void 0!==e&&"function"!=typeof e?e:t,DASH_ARRAYS={solid:void 0,dashed:[2,1.5],dotted:[0,1.5]},linePatternDashArray=e=>e&&DASH_ARRAYS[e],linePatternLayout=e=>"dotted"===e?{"line-cap":"round"}:void 0,TITLE="title",pinIconBaseLayout={"icon-image":["get","iconID"],"icon-anchor":"bottom","icon-size":PIN_ICON_SIZE,"icon-allow-overlap":!0,"icon-padding":0},PIN_TRANSLATE=[0,5],pinIconBasePaint={"icon-translate":PIN_TRANSLATE,"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":/* @__PURE__ */zoomRamp(6,1,10,1.5),"text-translate-anchor":"viewport"},pinLayerBaseSpec=/* @__PURE__ */(()=>({type:"symbol",layout:{...pinIconBaseLayout,...pinTextBaseLayout},paint:{...pinIconBasePaint,...pinTextBasePaint}}))(),suffixNumber=(e,t)=>`${e}-${t}`,prefixLayerID=(e,t)=>t?`${t}-${e}`:e,mergeLayer=(e,t)=>{if(!t)return e;const{paint:i,layout:s,...o}=t;return{...e,...o,...i&&{paint:{...e.paint,...i}},...s&&{layout:{...e.layout,...s}}}},mergeLayerOverride=(e,t)=>{if(!t)return e;const{beforeID:i,...s}=t;return mergeLayer(e,s)},fillOpacityByStyle=/* @__PURE__ */byOutlineFillStyle(0,.15),lineWidthByStyle=/* @__PURE__ */byOutlineFillStyle(5,2),lineOpacityByStyle=/* @__PURE__ */byOutlineFillStyle(.9,1),buildGeometryLayerSpecs=(e,t,i,s="#0A3653")=>{const o=i?.fill,r=i?.line,a=i?.highlight,n=Array.isArray(o?.color)?[o.color]:[],l=linePatternDashArray(r?.pattern),c=linePatternLayout(r?.pattern),d={type:"fill",id:e,paint:{"fill-color":["coalesce",["get","color"],...n,i?.color??s],"fill-antialias":!1,"fill-opacity":scaledWhen(hasActiveEventState,o?.opacity??fillOpacityByStyle,clampFactor(a?.fill?.opacityFactor,HIGHLIGHT_FILL_OPACITY_FACTOR_RANGE,2),1)}},u={type:"line",id:t,...c&&{layout:c},paint:{"line-color":r?.color??["coalesce",["get","color"],...n,i?.color??/* @__PURE__ */byOutlineFillStyle("#555555",s)],"line-width":scaledWhen(hasActiveEventState,r?.width??lineWidthByStyle,clampFactor(a?.line?.widthFactor,HIGHLIGHT_LINE_WIDTH_FACTOR_RANGE,1.75)),"line-opacity":r?.opacity??lineOpacityByStyle,...l&&{"line-dasharray":l}}};return[mergeLayerOverride(d,i?.layers?.fill),mergeLayerOverride(u,i?.layers?.line)]},buildGeometryTitleLayerSpec=(e,t,i="light",s)=>{const o=t?.label,{textColor:r,haloColor:a}=themeAdaptiveLabelColors(i);return mergeLayerOverride({type:"symbol",id:e,layout:{"text-field":o?.title??["get","title"],"text-padding":5,"text-size":15,"text-font":inTypeface(["Noto-Bold"],labelTypefaceOf(o,s)),...labelLayoutProperties(o)},paint:{"text-color":r,"text-halo-color":a,...pinTextBasePaint,...labelPaintProperties(o)}},t?.layers?.label)},buildGeometryLineLabelLayerSpec=(e,t,i="light",s)=>{const o=t?.lineLabel,{textColor:r,haloColor:a}=themeAdaptiveLabelColors(i);return mergeLayerOverride({type:"symbol",id:e,minzoom:o?.minZoom??3,layout:{"text-field":o?.title??["get","title"],"symbol-placement":"line","text-size":15,"text-font":inTypeface(["Noto-Bold"],labelTypefaceOf(o,s)),...labelLayoutProperties(o),"symbol-spacing":o?.symbolSpacing??200,"text-offset":o?.offset??BORDER_LABEL_OFFSET},paint:{"text-color":r,"text-halo-color":a,"text-halo-width":2,...labelPaintProperties(o)}},t?.layers?.lineLabel)},paletteColors=(e,t,i)=>"ramp"===t&&colorRamp(e,i,{space:"oklch"})||Array.from({length:i},(t,i)=>e[i%e.length]),invertedGeometry=e=>{return("Polygon"===(t=e.geometry).type?t.coordinates.length>1:t.coordinates.some(e=>e.length>1))&&difference(featureCollection([polygonFromBBox([-180,-90,180,90]),e]))?.geometry||mask(e).geometry;var t},geometryParts=["fill","line"],layerOnlyConfigKeys=["beforeLayerConfig","visible","events","highlight","layers","line","color"],withoutLayerOnlyKeys=e=>Object.fromEntries(Object.entries(e??{}).filter(([e])=>!layerOnlyConfigKeys.includes(e))),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||"string"==typeof e.fill?.color||e.fill?.palette?.length||(this.updateLayers(e),this.applyVisibility(this.config))}),onMapTypefaceChange(e,()=>this.updateLayers(this.displayConfig(this.config)))}get lightDark(){return this.tomtomMap.styleLightDarkTheme}get defaultColor(){return mapAccentColor(this.tomtomMap)??("dark"===this.lightDark?"#5FA8D8":"#0A3653")}_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),[s,o]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,i,this.defaultColor),{titleLayerSpec:r,lineLabelSpec:a}=this.labelLayerSpecs(i);return this.titleLayerSpecs=r,this.geometryFillLayerSpecs=s,this.geometryOutlineLayerSpecs=o,this.lineLabelLayerSpecs=a,{geometry:new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,[s,o,a]),geometryLabel:new GeoJSONSourceWithLayers(this.mapLibreMap,this.titleSourceID,[r])}}_applyConfig(e){const t=this.displayConfig(e);declareFontFaces(this.tomtomMap,this,customFacesOf([t?.label,t?.lineLabel])),this.updateLayers(t);const i=this.getShown();return i.geometry.features.length&&isEqual(withoutLayerOnlyKeys(e),withoutLayerOnlyKeys(this.config))||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,s=!1!==e?.visible&&!!t.shownFeatures.features.length;applyLayersVisibility([this.geometryFillLayerSpecs,this.geometryOutlineLayerSpecs],s,this.mapLibreMap),applyLayersVisibility([this.lineLabelLayerSpecs],s&&void 0!==this.displayConfig(e)?.lineLabel,this.mapLibreMap),applyLayersVisibility([this.titleLayerSpecs],s&&!!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 s of geometryParts){const o=beforeLayerTargetOf(e,s)??t;for(const e of i[s])moveLayerBefore(this.mapLibreMap,e,beforeLayerIDOf(o,this.titleLayerID))}}labelLayerSpecs(e){const t=mapTypefaceOf(this.tomtomMap);return{titleLayerSpec:buildGeometryTitleLayerSpec(this.titleLayerID,e,this.lightDark,t),lineLabelSpec:buildGeometryLineLabelLayerSpec(this.lineLabelLayerID,e,this.lightDark,t)}}updateLayers(e){const[t,i]=buildGeometryLayerSpecs(this.fillLayerID,this.outlineLayerID,e,this.defaultColor),{titleLayerSpec:s,lineLabelSpec:o}=this.labelLayerSpecs(e);changeLayerProps(t,this.geometryFillLayerSpecs,this.mapLibreMap),changeLayerProps(i,this.geometryOutlineLayerSpecs,this.mapLibreMap),changeLayerProps(s,this.titleLayerSpecs,this.mapLibreMap),changeLayerProps(o,this.lineLabelLayerSpecs,this.mapLibreMap),this.geometryFillLayerSpecs=t,this.geometryOutlineLayerSpecs=i,this.titleLayerSpecs=s,this.lineLabelLayerSpecs=o}discardShownData(){this.lastRawInput=null}restoreDataAndConfigImpl(){const e=this.getShown();this.initSourcesWithLayers(this.config,!0),this.displayAgain(this.config,e),this._applyConfig(this.config)}displayAgain(e,t){this.lastRawInput&&this.display(this.prepare(this.lastRawInput,e,t.geometry),t.geometryLabel)}prepare(e,t,i){const s=this.prepareShown(e,t);return((e,t={})=>{const i=((e,t)=>{const{color:i,palette:s,paletteMode:o}=e.fill??{};return void 0!==i?Array.from({length:t},()=>"string"==typeof i?i:void 0):s?.length?paletteColors(s,o,t):[]})(t,e.features.length);return{...e,features:e.features.map((e,s)=>{const o=e.properties??{},r=o.fillStyle??t.fill?.style,a="inverted"===r?(e=>({...e,geometry:invertedGeometry(e)}))(e):e,n=o.title??((e,t)=>{const i=t.label?.title;return"string"==typeof i&&i?i:e.properties?.address?.freeformAddress})(e,t),l=o.color??i[s];return{...a,properties:{...e.properties,...r&&{fillStyle:r},...n&&{title:n},...l&&{color:l},id:o.id??generateId()}}})}})(i?((e,t)=>{const i=new Set(e.features.map(({properties:e})=>e?.id).filter(e=>void 0!==e)),s=t.features.filter(({properties:e})=>!i.has(e?.id)),o=e.features.filter(({properties:e})=>void 0===e?.id).length===s.length;let r=0;return{...e,features:e.features.map(e=>{const i=e.properties?.id;if(void 0!==i)return withEventState(e,findFeatureByRefId(t.features,i)?.feature.properties?.eventState);if(!o)return e;const a=s[r++].properties;return withEventState({...e,properties:{...e.properties,id:a?.id}},a?.eventState)})}})(s,i):s,this.displayConfig(t))}display(e,t){const i=this.sourcesWithLayers.geometry;i.show(e,{automaticVisibility:!1});const s=(e=>{const t=e.features.flatMap(e=>{let t;if(e.properties?.placeCoordinates)t=e.properties?.placeCoordinates;else if("MultiPolygon"===e.geometry.type&&"inverted"!==e.properties?.fillStyle){const i=(e=>e.map(([e])=>e).reduce((e,t)=>t.length>e.length?t:e,[]))(e.geometry.coordinates),s=bboxFromGeoJSON({type:"Polygon",coordinates:[i]});t=s&&bboxCenter(s)}if(!t)return[];const i=e.properties?.id??e.id??generateId(),{eventState:s,...o}=e.properties??{};return[{type:"Feature",id:i,geometry:{type:"Point",coordinates:t},properties:{...o,id:i}}]});return{type:"FeatureCollection",bbox:e.bbox,features:t}})(i.shownFeatures);this.sourcesWithLayers.geometryLabel.show(t?withShownEventStates(t,s,renderedRefId):s,{automaticVisibility:!1})}async showPolygons(e){await this.waitUntilModuleReady(),this.lastRawInput=e,this.display(this.prepare(e,this.config)),this.applyVisibility(this.config),emitShownFeatures(this.shownFeaturesHandlers,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 GeometriesModule extends AbstractGeometriesModule{static async create(e,t){return await waitUntilMapIsReady(e),new GeometriesModule(e,t)}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:/* @__PURE__ */byOutlineFillStyle(5,1),color:/* @__PURE__ */byOutlineFillStyle(["coalesce",["get","color"],"#555555"],"grey"),opacity:/* @__PURE__ */byOutlineFillStyle(.9,1)},fill:{...e&&{palette:e},opacity:/* @__PURE__ */byOutlineFillStyle(0,.6)},lineLabel:{}}),geometryFillStyles=["filled","outline","inverted"],geometryPaletteModes=["cycle","ramp"],LINE_WIDTH_RANGE={min:0,max:20,step:.5,bounds:"hard-min"},SYMBOL_SPACING_RANGE={min:50,max:1e3,step:10,bounds:"hard-min"},LINE_LABEL_OFFSET_RANGE={min:-5,max:5,step:.1,bounds:"soft"},highlightKnobDefinitions=e=>({"highlight.fill.opacityFactor":{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.line.widthFactor":{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:geometryFillStyles,default:"filled"}),paletteModeKnobDefinition=e=>({kind:"enum",description:`How \`fill.palette\` colours the ${e}: \`cycle\` gives each the next colour in turn, \`ramp\` blends evenly from its first colour to its last.`,options:geometryPaletteModes,default:"cycle"}),linePatternKnobDefinition=e=>({kind:"enum",description:`Whether ${e} is drawn unbroken, in dashes or in dots, which scale with its width.`,options:linePatterns,default:"solid"}),moduleKnobDefinitions=/* @__PURE__ */(()=>({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; under the `outline` fill style, the border is grey."},visible:{kind:"toggle",description:"Everything the module draws: fills, borders, center labels and border labels.",default:!0},"fill.style":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 its fill colour, in turn or blended as `fill.paletteMode` sets, over `color`."},"fill.paletteMode":paletteModeKnobDefinition("features"),"fill.opacity":{kind:"number",description:"Fill opacity, which `highlight.fill.opacityFactor` multiplies while hovered or clicked. Unset: 0.15, or 0 with the `outline` fill style.",range:UNIT_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:UNIT_RANGE},"line.width":{kind:"number",description:"Border width in pixels, which `highlight.line.widthFactor` multiplies while hovered or clicked. Unset: 2, or 5 with the `outline` fill style.",range:LINE_WIDTH_RANGE},"line.pattern":linePatternKnobDefinition("the border"),...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:SYMBOL_SPACING_RANGE,default:200},"lineLabel.offset":{kind:"offset",description:"Shift of the border labels off the line, in ems: x along it, y across it.",range:LINE_LABEL_OFFSET_RANGE,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:LABEL_HALO_WIDTH_RANGE,...defaultOf("lineLabel"===e?2:void 0)}),opacity:e=>({kind:"number",description:`Text opacity of the ${labelNames[e]}.`,range:UNIT_RANGE,default:1}),font:e=>({kind:"enums",description:`Font faces of the ${labelNames[e]}, in order: the first one available wins. Unset: \`Noto-Bold\` in the labels' typeface.`,options:mapFonts}),typeface:e=>/* @__PURE__ */labelTypefaceKnob(e,labelNames[e])},labelEntries=e=>Object.keys(labelKnobDefinitions).map(t=>({id:`${e}.${t}`,...labelKnobDefinitions[t](e)})),buildCatalogue$1=()=>{const e=/* @__PURE__ */withIds(moduleKnobDefinitions),t=({id:e})=>e.startsWith("lineLabel.");return[...e.filter(e=>!t(e)),...labelEntries("label"),...labelEntries("lineLabel"),...e.filter(t)]},geometriesKnobCatalogue=/* @__PURE__ */buildCatalogue$1(),geometriesKnobIds=/* @__PURE__ */geometriesKnobCatalogue.map(({id:e})=>e),rangesModuleKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"Everything the module draws: bands, borders and their labels.",default:!0},"fill.style":fillStyleKnobDefinition("`filled` shades each band, `outline` draws only each range's border, `inverted` shades the outside of each range."),"fill.palette":{kind:"colors",description:"CSS colours of the bands, the innermost first, in turn or blended as `fill.paletteMode` sets. Empty: a ramp from the map's accent toward its land colour, reversed for `inverted`."},"fill.paletteMode":paletteModeKnobDefinition("bands"),"fill.outermostOpacityFactor":{kind:"factor",description:"Multiplier on the outermost band's fill opacity; the bands between step evenly from the innermost, at full opacity. With `inverted`, the world beyond the largest range is the outermost.",range:UNIT_RANGE,default:1},"line.pattern":linePatternKnobDefinition("each range's border"),...highlightKnobDefinitions("band")}))(),buildRangesCatalogue=()=>[.../* @__PURE__ */withIds(rangesModuleKnobDefinitions),...labelEntries("lineLabel")],reachableRangesKnobCatalogue=/* @__PURE__ */buildRangesCatalogue(),reachableRangesKnobIds=/* @__PURE__ */reachableRangesKnobCatalogue.map(({id:e})=>e),titleOf=(e,t,i)=>{if(i)return i(e,t);const s=e.properties?.budget;return void 0!==s?.value&&s.type?`${s.value} ${budgetUnits[s.type]??s.type}`:String(t+1)},largestFirst=e=>[...e].sort((e,t)=>t.squareMeters-e.squareMeters),invertedFill=(e,t,i)=>{const{title:s,fillStyle:o,...r}=e.properties??{};return{...e,geometry:t,properties:{...r,...i}}},bandOpacityFactor=(e,t,i)=>t>1?roundToDecimals(1-(1-i)*e/(t-1),3):i,prepareReachableRanges=(e,{fill:t,lineLabel:i},s)=>{const o=((e,t)=>{const i=e.map((e,i)=>({feature:e,squareMeters:area(e),title:titleOf(e,i,t)})),s=/* @__PURE__ */new Map;for(const o of i)ofMap(s,JSON.stringify(getPosition(o.feature.properties?.origin)),()=>[]).push(o);return[...s.values()].map(e=>largestFirst(e).map((t,i)=>({...t,rank:e.length-1-i})))})(e.features,i?.title),r=Math.max(0,...o.map(e=>e.length)),a=s(r),n=clampFactor(t?.outermostOpacityFactor,UNIT_RANGE),l=o.length?((e,t,i)=>"inverted"===t?((e,t)=>{const i=e.map(e=>e[0].feature),s=i.length>1&&union(featureCollection(i))||i[0],o=Math.max(...e.map(e=>e[0].rank)),r=[invertedFill(i[0],invertedGeometry(s),t(o))];for(const n of e)for(const[e,{feature:i,rank:s}]of n.entries()){if(0===e)continue;const o=difference(featureCollection([n[e-1].feature,i]));o&&r.push(invertedFill(i,o.geometry,t(s)))}const a=e.flat().map(({feature:e,rank:i,title:s})=>{const{id:o,...r}=e.properties??{};return{...e,id:void 0,properties:{...r,title:s,fillStyle:"filled",...t(i)}}});return[...r,...a]})(e,i):largestFirst(e.flat()).map(({feature:e,rank:s,title:o})=>({...e,properties:{...e.properties,title:o,fillStyle:t,...i(s)}})))(o,t?.style??"filled",e=>({color:a[e%a.length],...n<1&&{opacityFactor:bandOpacityFactor(e,r,n)}})):[];return{type:"FeatureCollection",...e.bbox&&{bbox:e.bbox},features:l}},isBorder=["==",["get","fillStyle"],"filled"],byBand=(e,t)=>clampFactor(t?.fill?.outermostOpacityFactor,UNIT_RANGE)<1?["*",e,["coalesce",["get","opacityFactor"],1]]:e,ReachableRangesModule=class ReachableRangesModule extends AbstractGeometriesModule{static async create(e,t){return await waitUntilMapIsReady(e),new ReachableRangesModule(e,t)}constructor(e,t){super(e,t),onMapColorsChange(e,["accent","land"],()=>{this.config?.fill?.palette?.length||this.displayAgain(this.config,this.getShown())})}get idPrefix(){return"reachableRange"}displayConfig(e){const t=fillStyledGeometryConfig({beforeLayerConfig:e?.beforeLayerConfig}),{title:i,...s}=e?.lineLabel??{},o={...t,highlight:e?.highlight,layers:e?.layers,line:{...t.line,pattern:e?.line?.pattern}};return"inverted"!==e?.fill?.style?{...o,fill:{...t.fill,opacity:byBand(/* @__PURE__ */byOutlineFillStyle(0,.6),e)},lineLabel:s}:{...o,line:{...o.line,opacity:["case",isBorder,1,0]},fill:{...t.fill,opacity:byBand(["case",isBorder,0,.6],e)},lineLabel:{...s,opacity:scaledWhen(["!",isBorder],s.opacity??1,0),offset:["case",isBorder,["literal",[0,-1]],["literal",[0,1]]]}}}prepareShown(e,t){return prepareReachableRanges(e,t??{},e=>{if(t?.fill?.palette?.length)return paletteColors(t.fill.palette,t.fill.paletteMode,e);const i=((e,t,i)=>colorRamp([e,t],i,{reach:.7})??Array.from({length:i},()=>e))(this.defaultColor,this.landColor,e);return"inverted"===t?.fill?.style?i.reverse():i})}get landColor(){return this.tomtomMap.mapColors.land??themeAdaptiveLabelColors(this.lightDark).haloColor}async show(e){await this.showPolygons(e)}},sameNamedCategories=["aboriginal_land","airport","amusement_park","animal_shelter","atm","bank","bar","border_control","cafe","cafeteria","camping_ground","car_rental","casino_and_gambling","cemetery","charging_location","childcare","cinema","clothing_shop","coffee_shop","college_or_university","comedy_club","courthouse","cultural_center","dentist","department_store","doctor","fast_food","ferry_terminal","fire_station","foreign_exchange","fuel_station","gold_exchange","golf_course","government_office","heliport_or_helipad","historic_site","horse_riding","hospital","hotel_or_motel","ice_rink","juice_bar","mall","manufacturing_facility","marina","marketplace","media_facility","mountain_pass","museum","nightlife","park_and_recreation_area","pharmacy","planetarium","police_station","post_office","prison","protected_land","pub","public_library","public_transport_stop","railway_station","religious_site","rental_car_parking","research_facility","restaurant","shop_or_store","stadium","stock_exchange","supermarket","swimming_pool","taxi_stand","tea_house","theater","tourist_attraction","tourist_information","truck_stop","vehicle_dealer","vehicle_repair","veterinary","viewpoint"],otherCategories={airport:["AIRFIELD","AIRLINE_ACCESS","PRIVATE_AIRPORT","PUBLIC_AIRPORT"],bank:["DIVERSIFIED_FINANCIALS"],bar:["COCKTAIL_BAR"],beach_resort:["BEACH","BEACH_CLUB"],border_control:["SECURED_ENTRANCE","TRANSPORT_ACCESS"],bus_station:["BUS_STOP"],cafe:["CAFE_PUB","INTERNET_CAFE"],camping_ground:["CARAVAN_SITE","RECREATIONAL_CAMPING_GROUND","REST_CAMP"],cemetery:["MAUSOLEUM_OR_GRAVE"],childcare:["PRE_SCHOOL"],cinema:["DRIVE_IN_MOVIES","MOVIE_THEATER"],clinic:["HEALTHCARE_SERVICE"],clothing_shop:["CHILDREN_S_CLOTHES","MEN_S_CLOTHING","SPECIALTY_CLOTHING_SHOP","WOMEN_S_CLOTHING"],college_or_university:["JUNIOR_COLLEGE_OR_COMMUNITY_COLLEGE"],commercial_area:["ADVERTISING_COMPANY","AGRICULTURAL_TECHNOLOGY","AGRICULTURE","AIRLINE_COMPANY","APARTMENT_RENTAL","AUTOMOBILE_COMPANY","BUILDING","BUSINESS_PARK","BUSINESS_SERVICES","BUS_CHARTER_COMPANY","CABLE_AND_TELEPHONE_COMPANY","CLEANING_SERVICES","COMMERCIAL_BUILDING","COMPANY","COMPUTER_AND_DATA_SERVICES","CONSTRUCTION_COMPANY","DELIVERY_SERVICE","ELECTRONICS_COMPANY","EQUIPMENT_RENTAL","FARM","FLATS_OR_APARTMENT_COMPLEX","HORTICULTURE","IMPORT_OR_EXPORT_AND_DISTRIBUTION","INSURANCE_COMPANY","INVESTMENT_ADVISOR","LEGAL_SERVICES","MINING_COMPANY","MOVING_AND_STORAGE_COMPANY","OIL_AND_NATURAL_GAS","PHARMACEUTICAL_COMPANY","PRIMARY_PRODUCER","PUBLISHING_TECHNOLOGIES","REAL_ESTATE_AGENT","REAL_ESTATE_COMPANY","RESIDENTIAL_ACCOMMODATION","RESIDENTIAL_ENTRANCE","RETIREMENT_COMMUNITY","SCHOOL_BUS_COMPANY","SERVICE_COMPANY","SOFTWARE_COMPANY","TAX_SERVICES","TELECOMMUNICATIONS","TRANSPORT_COMPANY","TRAVEL_AGENT","WEDDING_SERVICES"],conference_center:["EXHIBITION_CONVENTION_CENTER"],consumer_service:["CLUB_AND_ASSOCIATION","PEDESTRIAN_SUBWAY","PUBLIC_AMENITY","PUBLIC_BATHROOM","PUBLIC_CALL_BOX","WELFARE_ORGANIZATION"],cultural_center:["COMMUNITY_CENTER"],doctor:["GENERAL_PRACTITIONER","SPECIALIST"],emergency_ward_entrance:["AMBULANCE_UNIT","EMERGENCY_MEDICAL_SERVICE","EMERGENCY_ROOM","RESCUE_SERVICE"],fitness_center:["FITNESS_CLUB_AND_CENTER"],food_and_drinks_shop:["MICROBREWERY","WINERY"],foreign_exchange:["EXCHANGE"],government_office:["EMBASSY"],historic_site:["BATTLEFIELD","MEMORIAL"],holiday_home:["BUNGALOW_RENTAL","CHALET_RENTAL","COTTAGE_RENTAL","HOLIDAY_RENTAL","VILLA_RENTAL"],hospital:["BLOOD_BANK","GENERAL_HOSPITAL_AND_POLYCLINIC","HOSPITAL_FOR_WOMEN_AND_CHILDREN","HOSPITAL_OF_CHINESE_MEDICINE","SPECIAL_HOSPITAL"],hotel_or_motel:["BANDB_OR_GUEST_HOUSE","CABINS_LODGES","HOSTEL","HOTEL","MOTEL","RESORT"],ice_cream_shop:["ICE_CREAM_PARLOR"],ice_rink:["ICE_HOCKEY_ARENA"],industrial_area:["CHEMICAL_COMPANY","INDUSTRIAL_BUILDING","MECHANICAL_ENGINEERING","PORT_WAREHOUSE_FACILITY","PRIMARY_RESOURCE_UTILITY","QUARRY"],landmark:["ARCH","BAY","BRIDGE","CAPE","COVE","DAM","DUNE","ISLAND","LOCALE","MARSH","MONUMENT","NATURAL_FEATURE","OASIS","OBSERVATORY","PAN","PARKWAY","PLAIN_OR_FLAT","PLATEAU","RAPIDS","REEF","RESERVOIR","RIVER_CROSSING","ROCKS","STATUE","TOWER","TUNNEL","VALLEY","WATER_HOLE","WELL"],manufacturing_facility:["AUTOMOBILE_MANUFACTURING","MANUFACTURING_COMPANY"],marketplace:["FARMERS_MARKET","FOOD_MARKET","INFORMAL_MARKET","PUBLIC_MARKET"],military_airfield:["MILITARY_AIRPORT"],mourning_facility:["FUNERAL_SERVICE_AND_MORTUARIES"],ngo_office:["NON_GOVERNMENTAL_ORGANIZATION"],nightlife:["AMUSEMENT_PLACE","BETTING_STATION","CABARET_THEATER","CONCERT_HALL","DISCO_CLUB","ENTERTAINMENT","FAIRGROUND","JAZZ_CLUB","KARAOKE_CLUB","MUSIC_CENTER"],park_and_recreation_area:["ADVENTURE_VEHICLE_TRAIL","FISHING_AND_HUNTING_AREA","FOREST_AREA","HIKING_TRAIL","HISTORICAL_PARK","HORSE_RIDING_TRAIL","MOUNTAIN_BIKE_TRAIL","PARK","PICNIC_AREA","RECREATION_AREA","ROCK_CLIMBING_TRAIL","TRAIL_SYSTEM","WILDERNESS_AREA"],park_and_recreation_facility:["FLYING_CLUB","LEISURE_CENTER","WATER_SPORT"],parking_facility:["OPEN_CAR_PARKING_AREA","PARKING_GARAGE"],personal_care_service:["BEAUTY_SALON","HAIRDRESSER","NAIL_SALON","PERSONAL_CARE_FACILITY","PERSONAL_SERVICE","SAUNA_SOLARIUM_MASSAGE"],pharmacy:["CANNABIS_SHOP","DRUG_STORE","MEDICINAL_AND_RECREATIONAL_DISPENSARY","MEDICINAL_MARIJUANA_DISPENSARY","RECREATIONAL_MARIJUANA_DISPENSARY"],post_depot:["COURIER_DROP_BOX"],public_transport_stop:["BUS_LINES","PASSENGER_TRANSPORT_TICKET_OFFICE","STREETCAR_STOP","SUBWAY_ENTRANCE","SUBWAY_STATION"],railway_station:["INTERNATIONAL_RAILROAD_STATION","NATIONAL_RAILROAD_STATION","STATION_ACCESS","URBAN_STATION"],religious_site:["CHURCH","GURUDWARA","MOSQUE","PAGODA","SYNAGOG","TEMPLE"],rest_and_service_area:["REST_AREA"],restaurant:["BANQUET_ROOMS","BISTRO","CATERING_SERVICES","CREPERIE","DINNER_THEATER","PIZZERIA","RESTAURANT_AREA","SALAD_BAR","SEAFOOD","SOUL_FOOD","STEAK_HOUSE","TAKEOUT_FOOD"],school_or_kindergarten:["ART_SCHOOL","DANCE_STUDIO_AND_SCHOOL","DRIVING_SCHOOL","HIGH_SCHOOL","LANGUAGE_SCHOOL","MIDDLE_SCHOOL","PRIMARY_SCHOOL","SCHOOL","SENIOR_HIGH_SCHOOL","VOCATIONAL_SCHOOL"],shop_or_store:["AGRICULTURAL_SUPPLIES","ANTIQUE_ART_SHOP","BAGS_LEATHERWEAR","BAKERY","BEAUTY_SUPPLIES","BOATING_EQUIPMENT_AND_ACCESSORIES","BOOK_SHOP","BUTCHER","CAMERAS_AND_PHOTOGRAPHY","CARPET_FLOOR_COVERINGS","CHRISTMAS_OR_HOLIDAY_SHOP","COMPUTER_AND_COMPUTER_SUPPLIES","CONSTRUCTION_MATERIAL_AND_EQUIPMENT","CONSUMER_ELECTRONICS","CONVENIENCE_STORE","CURTAINS_TEXTILES","C_DS_DVD_VIDEOS","DELICATESSEN","DO_IT_YOURSELF_CENTERS","DRIVE_THROUGH_BOTTLE_SHOP","DRY_CLEANER","ELECTRICAL_APPLIANCES_SHOP","FACTORY_OUTLET","FISHMONGER","FLORISTS","FOOD_AND_DRINKS_SHOP","FOOTWEAR_SHOE_REPAIRS","FURNITURE_HOME_FURNISHINGS","GARDEN_CENTERS_SERVICES","GIFTS_CARDS_NOVELTIES_SOUVENIRS","GLASSWARE_CERAMIC_SHOP","GLASS_WINDOWS_STORE","GREENGROCER","GROCERY_STORE","HARDWARE_STORE","HOBBY_SHOP","HOUSE_AND_GARDEN_FURNITURE_AND_FITTINGS","JEWELRY_CLOCKS_WATCHES","KITCHENS_BATHROOMS","LAUNDRY","LIGHTING_SHOPS","LOCAL_SPECIALITIES_SHOP","LOTTERY_SHOP","MEDICAL_SUPPLIES_EQUIPMENT","MOBILE_PHONE_SHOP","MUSIC_INSTRUMENTS_STORE","NEWSAGENTS_TOBACCONISTS","OFFICE_EQUIPMENT","OPTICIAN","PAINTING_DECORATING","PAWN_SHOP","PET_SUPPLIES","PHOTOCOPY_SHOP","PHOTO_LAB_OR_DEVELOPMENT","RECYCLING_SHOP","RETAIL_OUTLET","SECURITY_PRODUCTS","SHOPPING_SERVICE","SPECIALTY_FOODS","SPORTS_EQUIPMENT_AND_CLOTHING","TAILOR_SHOP","TOYS_GAMES_SHOP","VARIETY_STORE","VIDEO_RENTAL_SHOP","WHOLESALE_CLUB","WINE_SPIRITS"],sport_facility:["ADVENTURE_SPORTS_FACILITY","ATHLETICS_TRACK","BASEBALL_PARK","BASKETBALL_ARENA","BOWLING_CENTER","CRICKET_GROUND","HOCKEY_CLUB","HORSE_RACING_TRACK","RACE_TRACK","RUGBY_GROUND","SPORTS_CENTER","SQUASH_COURT","TENNIS_COURT","THEMATIC_SPORT_CENTER"],stadium:["FOOTBALL_STADIUM","MOTOR_RACING_STADIUM","MULTI_PURPOSE_STADIUM","NETBALL_STADIUM","SOCCER_STADIUM"],taxi_stand:["TAXI_LIMOUSINE_AND_SHUTTLE_SERVICE"],theater:["AMPHITHEATER","OPERA_HOUSE"],toll_plaza:["TOLL_GATE"],tourist_attraction:["CAVE","MINERAL_OR_HOT_SPRINGS","NATURAL_TOURIST_ATTRACTION"],transport_access:["BOAT_LAUNCHING_RAMP","HARBOR","YACHT_BASIN"],vehicle_dealer:["ATV_DEALER","BOAT_DEALER","BUS_DEALER","CAR_DEALER","MOTORCYCLE_DEALER","RECREATIONAL_VEHICLE_DEALER","TRUCK_DEALER","VAN_DEALER"],vehicle_inspection:["MOTORING_ORGANIZATION_OFFICE","TRAFFIC_CONTROL_DEPARTMENT","TRANSPORT_AUTHORITY_VEHICLE_REGISTRATION"],vehicle_repair:["BODYSHOP","CAR_GLASS_REPLACEMENT_SHOP","CAR_REPAIR_AND_SERVICE","HOME_APPLIANCE_REPAIR","MOTORCYCLE_REPAIR","TIRE_SERVICE","TRUCK_REPAIR_AND_SERVICE"],vehicle_wash:["CAR_WASH"],veterinary:["ANIMAL_SERVICE"],viewpoint:["HILL","MOUNTAIN_PEAK","RIDGE"],weighbridge:["WEIGH_STATION"],winter_sports:["SKI_RESORT"],zoo_or_aquarium:["AQUATIC_ZOO","ARBORETA_AND_BOTANICAL_GARDENS","WILDLIFE_PARK","ZOO","ZOOS_ARBORETA_BOTANICAL_GARDEN"]},baseMapPOICategoryValues=/* @__PURE__ */(()=>[.../* @__PURE__ */new Set([...sameNamedCategories,...Object.keys(otherCategories)])])(),baseMapCategories=/* @__PURE__ */(()=>Object.fromEntries([...sameNamedCategories.map(e=>[e.toUpperCase(),e]),...Object.entries(otherCategories).flatMap(([e,t])=>t.map(t=>[t,e]))]))(),toBaseMapPOICategory=e=>Object.hasOwn(baseMapCategories,e)?baseMapCategories[e]:e.endsWith("_GENERIC")?toBaseMapPOICategory(e.slice(0,-8)):e.endsWith("_RESTAURANT")?"restaurant":void 0,groupCategories={eat_and_drink:["bar","cafe","cafeteria","coffee_shop","fast_food","ice_cream_shop","juice_bar","pub","restaurant","tea_house"],shopping:["clothing_shop","department_store","food_and_drinks_shop","mall","marketplace","shop_or_store","supermarket"],finance:["atm","bank","foreign_exchange","gold_exchange","stock_exchange"],lodging:["camping_ground","holiday_home","hotel_or_motel"],transport:["airport","bus_station","ferry_terminal","heliport_or_helipad","marina","public_transport_stop","railway_station","taxi_stand","transport_access"],driving:["border_control","car_rental","charging_location","fuel_station","rest_and_service_area","toll_plaza","truck_stop","vehicle_dealer","vehicle_inspection","vehicle_repair","vehicle_wash","weighbridge"],parking:["parking_facility","rental_car_parking"],healthcare:["clinic","dentist","doctor","emergency_ward_entrance","hospital","pharmacy","veterinary"],education:["childcare","college_or_university","research_facility","school_or_kindergarten"],cultural:["cultural_center","historic_site","museum","planetarium","theater"],leisure:["amusement_park","beach_resort","casino_and_gambling","cinema","comedy_club","nightlife","park_and_recreation_facility","tourist_attraction","tourist_information","zoo_or_aquarium"],sport:["fitness_center","golf_course","horse_riding","ice_rink","sport_facility","stadium","swimming_pool","winter_sports"],outdoor:["aboriginal_land","landmark","mountain_pass","park_and_recreation_area","viewpoint"],protected:["protected_land"],public:["cemetery","courthouse","fire_station","government_office","police_station","post_depot","post_office","prison","public_library"],military:["military_airfield"],religion:["religious_site"],business:["animal_shelter","commercial_area","conference_center","consumer_service","industrial_area","manufacturing_facility","media_facility","mourning_facility","ngo_office","personal_care_service"]},baseMapCategoryGroups=/* @__PURE__ */(()=>Object.fromEntries(Object.keys(groupCategories).flatMap(e=>groupCategories[e].map(t=>[t,e]))))(),isClusterFilter=["all",["==",["get","cluster"],!0],["has","cluster_id"]],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?.outlineColor??"#FFFFFF","circle-stroke-width":e?.outlineWidth??1.5}),countTextLayout=e=>({"text-field":["get","point_count_abbreviated"],"text-font":["Noto-Bold"],"text-size":e?.label?.size??12,"text-allow-overlap":!0,"text-ignore-placement":!0}),countTextColor=e=>e?.label?.color??"#FFFFFF",clusteredPlacesAggregateProperties=/* @__PURE__ */(()=>{return{[CLUSTER_PROPERTY_BASE_MAP_ICON_IDS]:(e="clusterBaseMapIconIDs",[["case",["==",["get",e],null],["accumulated"],["==",["accumulated"],null],["get",e],[">=",["index-of",["concat",",",["get",e],","],["concat",",",["accumulated"],","]],0],["accumulated"],["concat",["accumulated"],",",["get",e]]],["get","baseMapIconID"]])};var e})(),buildKnownBaseMapSpriteImageExpression=e=>{const t=["match",e];for(const i of baseMapPOICategoryValues){const e=toBaseMapPOIImageID(i);t.push(e,["image",e])}return t.push(["image","poi-parking-micro"]),t},clusterPinIconImage=/* @__PURE__ */buildKnownBaseMapSpriteImageExpression(["get","clusterBaseMapIconIDs"]),buildCustomIconOffsets=(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},buildIconOffsetExpression=(e,t="iconID",i=[0,0])=>{const s=[];for(const[a,n]of e)0===n.x&&0===n.y||s.push(["==",["get",t],a],["literal",[n.x,n.y]]);if(!s.length||isLegacyFunction(i))return;const o=e=>Array.isArray(e)&&"number"==typeof e[0]?["literal",e]:e,r=e=>mentionsZoom(e)?void 0:["case",...s,o(e)];return Array.isArray(i)&&("interpolate"===i[0]||"step"===i[0])&&mentionsZoom(i)?mapRampOutputs(i,r):r(i)},isCenteredMarkerType=e=>"base-map"===e||"circle-icon"===e,absoluteSvgLength=e=>{const t=e?.trim().match(/^(\d+(?:\.\d+)?|\.\d+)\s*(?:px)?$/);return t?Number.parseFloat(t[1]):void 0},calculateIconScale=(e,t,i=2)=>{if(!e)return;const s=(e=>{try{return"string"==typeof e?e.includes("<svg")?(e=>{const t=parseSvg(e),i=absoluteSvgLength(t.getAttribute("width")),s=absoluteSvgLength(t.getAttribute("height"));if(void 0!==i&&void 0!==s)return{width:i,height:s};const o=(e=>{const t=e?.trim().split(/[\s,]+/);if(4!==t?.length)return;const i=Number.parseFloat(t[2]),s=Number.parseFloat(t[3]);return i>0&&s>0&&Number.isFinite(i)&&Number.isFinite(s)?{width:i,height:s}:void 0})(t.getAttribute("viewBox"));return o?void 0!==i?{width:i,height:i*o.height/o.width}:void 0!==s?{width:s*o.width/o.height,height:s}:o:null})(e):null: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(!s)return;const o=isCenteredMarkerType(t),r=o?54:140,a=o?54:120,n=2/i;return{heightScale:s.height*n/r,widthScale:s.width*n/a}},round4=e=>roundToDecimals(e,4),buildAnchorOffsets=(e,t,i,s)=>{const o=s??round4(t),r=round4(i);return["top",[0,s??round4(e)],"left",[o,r],"right",[-o,r]]},getTextOffset=(e,t,i,s)=>{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(isLegacyFunction(e)){const t=e.stops.at(-1);if(Array.isArray(t)&&"number"==typeof t[1])return t[1]}return.8})(e)/.8,r=isCenteredMarkerType(i);if(r&&void 0!==s)return{"text-offset":[s,s]};const a=1.4*o,n=buildAnchorOffsets(.7*o,a,r?0:-a,s);if(0===t.size)return{"text-variable-anchor-offset":n};const l=["case"];for(const[c,d]of t.entries()){const e=(r?1.4:.7)*d.heightScale*o,t=1.4*d.widthScale*o,i=r?0:-t;l.push(["==",["get","iconID"],c],["literal",buildAnchorOffsets(e,t,i,s)])}return l.push(["literal",n]),{"text-variable-anchor-offset":l}},buildLayoutConfig=(e,t,i,s,o)=>{const r=t?.label,a=t?.layers?.[i],n=o&&o.size>0,l={...e.layout},c=n||void 0!==r?.distance||"circle-icon"===t?.markerType;c&&(delete l["text-offset"],delete l["text-variable-anchor-offset"],delete l["text-radial-offset"]);const d={...l,...labelLayoutProperties(r),...void 0!==s&&{"text-field":s},...a?.layout};if(c){const e=[...o??[]],i=new Map(e.flatMap(([e,{scales:t}])=>t?[[e,t]]:[])),s=buildIconOffsetExpression(e.flatMap(([e,{offset:t}])=>t?[[e,t]]:[]),void 0,l["icon-offset"]);return{...d,...getTextOffset(d["icon-size"],i,t?.markerType,r?.distance),...s&&{"icon-offset":s},...a?.layout}}return d},buildPaintConfig=(e,t,i,s)=>{const o=t?.layers?.[i],{textColor:r,haloColor:a}=themeAdaptiveLabelColors(s),n=e.paint??{};return{...n,...void 0===n["text-color"]&&{"text-color":r},...void 0===n["text-halo-color"]&&{"text-halo-color":a},...labelPaintProperties(t?.label),...void 0!==t?.icon?.opacity&&"selected"!==i&&{"icon-opacity":t.icon.opacity},...o?.paint}},writtenIconLayouts=/* @__PURE__ */new WeakMap,styleIconLayout=(e,t)=>{const i=writtenIconLayouts.get(e),s=e=>i&&isEqual(t?.[e],i.written[e])?i.over[e]:t?.[e];return{"icon-image":s("icon-image"),"icon-offset":s("icon-offset")}},poiLookKnobIds=["labels.sizeFactor","labels.typeface","symbols.sizeFactor","pois.sizeFactor","pois.label.color","pois.label.haloColor"],poiIconLookKnobIds=["symbols.sizeFactor","pois.sizeFactor"],getTextSizeSpec=e=>JSON.parse(JSON.stringify(e).replaceAll("name",TITLE)),readPOIStyleLayers=e=>{const t=e.getStyle().layers,i=e=>{const i=t.find(t=>t.id===e);return"symbol"===i?.type?i:void 0};return{poi:i(mapStyleLayerIDs.poi),micro:i(POI_MICRO_LAYER_ID)}},buildBaseMapPOILayerFoundation=e=>{const{visibility:t,...i}=e?.layout??{};return{filter:["!",isClickEventState],type:"symbol",paint:e?.paint,layout:e?.layout?i:void 0}},buildPOIMicroLikeLayerSpec=e=>{const t=buildBaseMapPOILayerFoundation(e);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=e?.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"}},hasNoActiveEventState=["!",hasActiveEventState],pinLayerSpec=/* @__PURE__ */(()=>({...pinLayerBaseSpec,filter:hasNoActiveEventState}))(),toSelectedSpec=(e,t)=>({...e,filter:hasActiveEventState,layout:{...e.layout,"text-allow-overlap":!0},paint:{...e.paint,"text-color":t}}),selectedPinLayerSpec=(e="#3f9cd9")=>toSelectedSpec({...pinLayerBaseSpec,layout:{...pinLayerBaseSpec.layout,"icon-size":SELECTED_PIN_ICON_SIZE}},e),getThemeAdaptiveConnectionColors=(e,t)=>{const i="dark"===e,s=themeAdaptiveLabelColors(e).haloColor;return t?{lineColor:t,labelColor:themeAdaptiveLabelShadeOf(t,e),labelHaloColor:s}:{lineColor:i?"#5AB6F0":"#3f9cd9",labelColor:i?"#A9D6F5":"#1a5f8a",labelHaloColor:s}},dashedLineSpec=(e,t,i)=>({type:"line",layout:{"line-cap":"round"},paint:{"line-color":e,"line-width":1.5,"line-dasharray":t,"line-opacity":i}}),buildBaseLineSpec$1=e=>{const t=dashedLineSpec(e,[2,2],.9);return{...t,layout:{"line-join":"round",...t.layout}}},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)=>({...dashedLineSpec(e,[1,2],.8),minzoom:t,filter:["==",["geometry-type"],"LineString"]}),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}}),placesMarkerTypes=["pin","circle-icon","base-map","pin-clustered"],eventStatesById=e=>{const t=/* @__PURE__ */new Map;for(const i of e.features)i.properties.eventState&&t.set(i.properties.id,i.properties.eventState);return t},toEntryPointID=(e,t)=>`${e}-entry-point-${t}`,isShownFor=(e,t)=>"all"===e||("selected"===e?void 0!==t:isClickEventType(t)),toEntryPointPosition=e=>{if("Point"===e.type)return e.coordinates;const[t,...i]=e.coordinates[1];return[wrapLongitude(t),...i]},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:UNIT_RANGE},"icon.opacity":{kind:"number",description:"Opacity of the place icons, whichever marker type draws them; the cluster badges and a highlighted or selected place stay opaque.",range:UNIT_RANGE,default:1},"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:LABEL_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, or the style's POI labels under `base-map`."},"label.haloWidth":{kind:"number",description:"Width of the label halo, in pixels. Unset: 1 to 1.5 as the zoom grows, or the style's POI labels under `base-map`.",range:LABEL_HALO_WIDTH_RANGE},"label.opacity":{kind:"number",description:"Label opacity.",range:UNIT_RANGE},"label.distance":{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`, in the labels' typeface.",options:mapFonts},"label.typeface":/* @__PURE__ */labelTypefaceKnob("label","labels"),"cluster.badge.color":{kind:"color",description:"Fill colour of the cluster count badges; `color` does not reach them.",default:"#000000"},"cluster.badge.outlineColor":{kind:"color",description:"Outline colour of the cluster count badges.",default:"#FFFFFF"},"cluster.badge.outlineWidth":{kind:"number",description:"Outline width of the cluster count badges, in pixels.",range:{min:0,max:5,step:.5,bounds:"hard-min"},default:1.5},"cluster.badge.label.color":{kind:"color",description:"Colour of the count on the cluster badges.",default:"#FFFFFF"},"cluster.badge.label.size":{kind:"number",description:"Size of the count on the cluster badges, in pixels.",range:LABEL_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.radius":{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.maxZoom":{kind:"number",description:"Last zoom places cluster at; entry points start one zoom above it. Changing it recreates the places source.",range:{min:1,max:17,step:1,bounds:"hard"},default:17},"cluster.source.minPoints":{kind:"number",description:"Fewest places a cluster holds. Changing it recreates the places source.",range:{min:2,max:20,step:1,bounds:"hard-min"},default:2},"entryPoints.showFor":{kind:"enum",description:"Which places have their entry points drawn: all, the hovered or clicked, or the clicked.",options:/* @__PURE__ */(()=>/* @__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.label.color":{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.label.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),paintPin=(e,t,i,s,o,r)=>{const a=((e,t)=>e?.image?.image?{image:e.image.image,pixelRatio:e.image.pixelRatio??2}:{style:{...t,...definedFields(e?.style)}})(i,s);if(r&&e.hasImage(t)&&((e,t)=>"image"in e?"image"in t&&e.image===t.image&&e.pixelRatio===t.pixelRatio:"style"in t&&isEqual(e.style,t.style))(a,r))return r;const n="image"in a?a.image:o(a.style),l="image"in a?a.pixelRatio:2;return addOrUpdateImage("add-or-update",t,n,e,{pixelRatio:l},latestImageLoad(e,t)),a},customImagesByID=(e,t=e=>e.id)=>{const i={};for(const s of e??[])s.image&&(i[t(s)]={image:s.image,pixelRatio:s.pixelRatio??2});return i},defaultPin=e=>svgToImg(()=>pinSvg(e)),resolveEndpoint=(e,t)=>"string"==typeof e?t(e):e,isMapCategoryIcon=e=>!!e.image,iconsByMapCategory=(e=[])=>{const t=/* @__PURE__ */new Map;for(const i of e){const e=toBaseMapPOICategory(i.id);e&&!t.has(e)&&isMapCategoryIcon(i)&&t.set(e,i)}return t},supportedPinSubcategories=/* @__PURE__ */new Set([7339002,8099002,7369004,7321003,7376006,9362003,9362004,9160004,9376007,7315015,9376006,9376002,7315078,7315149,9376005,7372003,9352045,9352032,9361048,9378005,7383004,9910004,7320002,9362016,7320003,9362025,9942002,9942003,7380005,9663003,9361021,9379009,9379004,7315147,9376003,9160002,9160003,9352008,9361006,7389004,9910006]),pinImageSubstitutes=/* @__PURE__ */(()=>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]])))(),toPinImageID=e=>{if(!e)return;const t=supportedPinSubcategories.has(e)?e:Number(e.toString().substring(0,4));return`pinCategories:${String(pinImageSubstitutes.get(t)??t)}`},buildPlaceTitle=e=>e.properties.poi?.name??e.properties.address?.freeformAddress??"",toImageID=(e,t,i)=>{if(!e)return i;if("pin"===t||"pin-clustered"===t)return toPinImageID(poiCategoriesToID[e])??i;{const t=toBaseMapPOICategory(e);return t?toBaseMapPOIImageID(t):i}},getEffectivePOICategory=(e,t)=>{const i=t?.icon?.mapping;return("poiCategory"===i?.to?i.fn(e):void 0)??e.properties.poi?.categories?.[0]},getIconIDForPlace=(e,t,i={})=>{const s=i.icon?.categoryIcons,o=e=>e.image?suffixNumber(e.id,t):e.id,r=i.icon?.mapping,a="imageID"===r?.to?r.fn(e):void 0;if(a){const e=s?.find(({id:e})=>e===a);return e?o(e):a}const n=getEffectivePOICategory(e,i),l=((e,t=[])=>{const i=e&&toBaseMapPOICategory(e),s=e?.endsWith("_GENERIC")?e.slice(0,-8):void 0;return t.find(t=>t.id===e)??(s?t.find(e=>e.id===s):void 0)??(i?iconsByMapCategory(t).get(i):void 0)})(n,s);return l?o(l):toImageID(n,i.markerType??"pin",((e,t)=>e.icon?.default||"base-map"!==(e.markerType??"pin")?suffixNumber("default_place",t):"poi-parking-micro")(i,t))},getPOILayerCategoryForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&toBaseMapPOICategory(i)},getPOIGroupForPlace=(e,t)=>{const i=getEffectivePOICategory(e,t);return i&&(e=>{const t=toBaseMapPOICategory(e);return t?baseMapCategoryGroups[t]:void 0})(i)},toPlaces=e=>Array.isArray(e)?{type:"FeatureCollection",features:e}:"Feature"===e.type?{type:"FeatureCollection",features:[e]}:e,getBaseMapIconIDForPlace=(e,t)=>toImageID(getEffectivePOICategory(e,t),"base-map","poi-parking-micro"),configWrites=/* @__PURE__ */new WeakMap,preparePlaces=(e,t,i,s)=>{const o=toPlaces(e);return{...o,features:o.features.map(e=>{const o=s?((e,t)=>{const i=configWrites.get(e.geometry);if(i?.instanceIndex!==t)return e;const s={...e.properties};for(const o of i.keys)Reflect.deleteProperty(s,o);return{...e,properties:{...s,...i.replaced}}})(e,t):e,r=o.id??generateId(),a=((e,t)=>({...("base-map"===t.markerType||"pin-clustered"===t.markerType)&&{category:getPOILayerCategoryForPlace(e,t),group:getPOIGroupForPlace(e,t)},..."pin-clustered"===t.markerType&&{baseMapIconID:getBaseMapIconIDForPlace(e,t)},...Object.fromEntries(Object.entries(t.extraFeatureProps??{}).map(([t,i])=>[t,"function"==typeof i?i(e):i]))}))(o,i),n=Object.keys(a),l={...o.geometry,bbox:o.bbox};if(s&&n.length){const e=o.properties;configWrites.set(l,{instanceIndex:t,keys:n,replaced:Object.fromEntries(n.filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]]))})}return{...o,id:r,geometry:l,properties:{...o.properties,id:r,title:featureTitle(o,i.label?.title,buildPlaceTitle),iconID:getIconIDForPlace(o,t,i),...a}}})}},preparePlacesForInstance=(e,t,i={})=>preparePlaces(e,t,i,!0),preparePlacesForDisplay=(e,t={})=>preparePlaces(e,0,t,!1),placeSources=["places","placesUnclustered"],placeDataSettings=e=>[e?.markerType,e?.icon?.categoryIcons,e?.icon?.mapping,!!e?.icon?.default,"function"==typeof e?.label?.title?e.label.title:void 0,e?.extraFeatureProps],connectionDataSettings=e=>[e?.connections?.label?.title],entryPointDataSettings=e=>[!!e?.entryPoints,e?.entryPoints?.showFor],PlacesModule=class PlacesModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new PlacesModule(e,t)}constructor(e,t){super(e,t),this.entryPointsRefreshHeld=!1,this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&this.updateLayersAndData(this.config)}),onStyleKnobsApplied(e,()=>{return e=this.config?.markerType,"base-map"===e?poiLookKnobIds:"circle-icon"===e||"pin-clustered"===e?[...poiIconLookKnobIds,"labels.typeface"]:["labels.typeface"];var e},()=>this.updatePlacesLayers(this.config)),onMapTypefaceChange(e,()=>{this.connectionLayerSpecs=this.replaceLayerSpecs(this.buildConnectionLayerSpecs(this.config),this.connectionLayerSpecs,this.sourcesWithLayers.connections)})}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.addedCategoryIcons={}),this.layerSpecs=this.buildLayerSpecs(e);const i=this.buildClusterOptions(e);this.currentClusterOptions=i;const s=this.partitionSpecsForSources(this.layerSpecs),o=new GeoJSONSourceWithLayers(this.mapLibreMap,this.sourceID,s.clusteredSpecs,!1,i);let r;s.unclusteredSpecs.length>0&&(r=new GeoJSONSourceWithLayers(this.mapLibreMap,this.unclusteredSourceID,s.unclusteredSpecs,!1)),this.connectionLayerSpecs=this.buildConnectionLayerSpecs(e);const a=this.addOverlaySource(this.connectionSourceID,this.connectionLayerSpecs);addLayers([...o._layerSpecs,...r?._layerSpecs??[]],this.mapLibreMap),this.entryPointLayerSpecs=this.buildEntryPointLayerSpecs(e);const n=this.addOverlaySource(this.entryPointSourceID,this.entryPointLayerSpecs),l=()=>{!this.config?.entryPoints&&n.isEmpty()||this.updateEntryPointsData(this.config)};return o.onShow(l),n.onShow(l),r?{places:o,placesUnclustered:r,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 isEqual(e,t)?t:(this.replaceSourceLayers(Object.values(e),Object.values(t),i),e)}partitionSpecsForSources(e){if(!this.currentClusterOptions)return{clusteredSpecs:Object.values(e),unclusteredSpecs:[]};const t=[],i=[];for(const[s,o]of Object.entries(e))"micro"===s?t.push(o):i.push(o);return{clusteredSpecs:i,unclusteredSpecs:t}}buildLayerSpecs(e){const t=((e,t,i,s,o="#3f9cd9",r)=>{const a=((e,t)=>{const i=/* @__PURE__ */new Map,s=e?.icon?.categoryIcons??[],o=buildCustomIconOffsets(s);for(const n of s){const s=calculateIconScale(n.image,e?.markerType,n.pixelRatio),r=o.get(n.id);(s||r)&&i.set(suffixNumber(n.id,t),{scales:s,offset:r})}const r=e?.icon?.default?.image,a=calculateIconScale(r?.image,e?.markerType,r?.pixelRatio);return a&&i.set(suffixNumber("default_place",t),{scales:a}),i})(e,s);let n,l,c=HIDDEN_LAYER_SPEC,d=HIDDEN_LAYER_SPEC,u=HIDDEN_CIRCLE_LAYER_SPEC,h=HIDDEN_LAYER_SPEC,p=HIDDEN_CIRCLE_LAYER_SPEC,y=HIDDEN_LAYER_SPEC;if("base-map"===e?.markerType){const{poi:e,micro:i}=readPOIStyleLayers(t),s=((e,t)=>{const i=buildBaseMapPOILayerFoundation(t),s=i.layout?.["text-size"],{"icon-offset":o}=styleIconLayout(e,t?.layout),{"icon-offset":r,...a}=i.layout??{};return{...i,layout:{...a,...void 0!==o&&{"icon-offset":o},"icon-image":["get","iconID"],"text-field":["get",TITLE],...s&&{"text-size":getTextSizeSpec(s)}}}})(t,e);n={...s,minzoom:10,filter:hasNoActiveEventState},c=buildPOIMicroLikeLayerSpec(i),l=toSelectedSpec(s,o)}else if("circle-icon"===e?.markerType){const{poi:e}=readPOIStyleLayers(t);n={...buildCircleBaseLayerSpec(e),filter:hasNoActiveEventState},l=toSelectedSpec(buildCircleBaseLayerSpec(e),o)}else if("pin-clustered"===e?.markerType){n={...pinLayerSpec,filter:["all",isNotClusterFilter,hasNoActiveEventState]},l={...selectedPinLayerSpec(o),filter:["all",isNotClusterFilter,hasActiveEventState]};const{filter:i,...s}=buildPOIMicroLikeLayerSpec(readPOIStyleLayers(t).micro);c=s;const r=e?.cluster?.badge;f=e.icon?.opacity,d={type:"symbol",filter:isSingleCategoryClusterFilter,layout:{"icon-image":clusterPinIconImage,"icon-size":1,"icon-allow-overlap":!0,"icon-ignore-placement":!0},...void 0!==f&&{paint:{"icon-opacity":f}}},u=(e=>({type:"circle",filter:isSingleCategoryClusterFilter,paint:{...badgeCirclePaint(e,e?.radius?.single??11),"circle-translate":singleBadgeOffset(e),"circle-translate-anchor":"viewport"}}))(r),h=(e=>({type:"symbol",filter:isSingleCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":countTextColor(e),"text-translate":singleBadgeOffset(e),"text-translate-anchor":"viewport"}}))(r),p=(e=>({type:"circle",filter:isMixedCategoryClusterFilter,paint:badgeCirclePaint(e,e?.radius?.mixed??15)}))(r),y=(e=>({type:"symbol",filter:isMixedCategoryClusterFilter,layout:countTextLayout(e),paint:{"text-color":countTextColor(e)}}))(r)}else n=pinLayerSpec,l=selectedPinLayerSpec(o);var f;const{microBeforeID:m,partAnchor:g}=(e=>{const t=partBeforeLayerIDOf(e?.beforeLayerConfig,"places",void 0);return{microBeforeID:void 0===beforeLayerTargetOf(e?.beforeLayerConfig,"places")?mapStyleLayerIDs.lowestPlaceLabel:"main",partAnchor:t?{beforeID:t}:{}}})(e),b=labelTypefaceOf(e?.label,r),S=(t,s)=>((e,t,i,s,o)=>{const r=t?.label,a=t?.layers?.[i],n=titleTextField(r?.title,void 0);return{...e,...a,layout:buildLayoutConfig(e,t,i,n,o),paint:buildPaintConfig(e,t,i,s)}})(withMapTypeface(t,b),e,s,i,"micro"===s?void 0:a);return{micro:{...S(c,"micro"),beforeID:m},main:{...S(n,"main"),beforeID:"selected"},selected:{...S(l,"selected"),...g},cluster:{...mergeLayer(d,e?.layers?.cluster),beforeID:"clusterBadge"},clusterBadge:{...mergeLayer(u,e?.layers?.clusterBadge),beforeID:"clusterCount"},clusterCount:{...mergeLayer(withMapTypeface(h,r),e?.layers?.clusterCount),beforeID:"clusterMixedBadge"},clusterMixedBadge:{...mergeLayer(p,e?.layers?.clusterMixedBadge),beforeID:"clusterMixedCount"},clusterMixedCount:{...mergeLayer(withMapTypeface(y,r),e?.layers?.clusterMixedCount),...g},...e?.layers?.additional}})(e,this.tomtomMap.mapLibreMap,this.tomtomMap.styleLightDarkTheme,this.instanceIndex,this.colorOf(e),mapTypefaceOf(this.tomtomMap)),i=new Set(Object.keys(t));return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,{...t,id:prefixLayerID(e,this.layerIDPrefix),...t.beforeID&&i.has(t.beforeID)?{beforeID:prefixLayerID(t.beforeID,this.layerIDPrefix)}:{}}]))}buildClusterOptions(e){if("pin-clustered"!==e?.markerType)return;const t=e.cluster?.source;return{cluster:!0,clusterRadius:t?.radius??60,clusterMaxZoom:t?.maxZoom??17,...void 0!==t?.minPoints&&{clusterMinPoints:t.minPoints},clusterProperties:{...t?.properties,...clusteredPlacesAggregateProperties}}}buildConnectionLayerSpecs(e){const t=((e,t,i="light",s)=>{const{lineColor:o,labelColor:r,labelHaloColor:a}=getThemeAdaptiveConnectionColors(i,e?.color??t);return{line:mergeLayer(buildBaseLineSpec$1(o),e?.layers?.line),label:mergeLayer(withMapTypeface(buildBaseLabelSpec(e?.label?.color??r,e?.label?.haloColor??a),s),e?.layers?.label)}})(e?.connections,this.colorOf(e),this.tomtomMap.styleLightDarkTheme,mapTypefaceOf(this.tomtomMap)),i=prefixLayerID("connection-line",this.layerIDPrefix),s=prefixLayerID("connection-label",this.layerIDPrefix),o=partBeforeLayerIDOf(e?.beforeLayerConfig,"connections",mapStyleLayerIDs.lowestLabel);return{line:{...t.line,id:i,beforeID:o},label:{...t.label,id:s,beforeID:o}}}buildEntryPointLayerSpecs(e){const t=this.buildClusterOptions(e),i=t?(t.clusterMaxZoom||17)+1:0,s=((e,t="light",i=0,s)=>{const{color:o,strokeColor:r}=((e,t)=>{const{lineColor:i,labelColor:s,labelHaloColor:o}=getThemeAdaptiveConnectionColors(e,t);return{color:"dark"===e?i:s,strokeColor:o}})(t,s),a=Math.max(e?.minZoom??15,i);return{line:mergeLayer(buildBaseLineSpec(o,a),e?.layers?.line),point:mergeLayer(buildBasePointSpec(o,r,a),e?.layers?.point)}})(e?.entryPoints,this.tomtomMap.styleLightDarkTheme,i,this.colorOf(e));return{line:{...s.line,id:prefixLayerID("entry-point-line",this.layerIDPrefix),beforeID:this.layerSpecs.main.id},point:{...s.point,id:prefixLayerID("entry-point",this.layerIDPrefix),beforeID:this.layerSpecs.cluster.id}}}_applyConfig(e){return declareFontFaces(this.tomtomMap,this,customFacesOf([e?.label])),this.updateLayersAndData(e),e}discardShownData(){this.shownConnections=[]}restoreDataAndConfigImpl(){const e=this.drawnFeatures();this.initSourcesWithLayers(this.config,!0),this.showAgain(e,this.config),this._applyConfig(this.config)}drawnFeatures(){const{places:e,placesUnclustered:t,connections:i,entryPoints:s}=this.sourcesWithLayers;return{places:e.shownFeatures,placesUnclustered:t?.shownFeatures,connections:i.shownFeatures,entryPoints:s.shownFeatures}}applyConfig(e){super.applyConfig(e)}updateConfig(e){super.updateConfig(e)}applyVisibility(e){this.applyPlacesVisibility(e),this.applyConnectionsVisibility(e),this.applyEntryPointsVisibility(e)}updateLayersAndData(e){if(this.setupImages(e),!isEqual(this.buildClusterOptions(e),this.currentClusterOptions))return void this.rebuildSourcesAndLayers(e);this.updatePlacesLayers(e),this.applyPlacesVisibility(e);const{connections:t,entryPoints:i}=this.sourcesWithLayers,s=!isEqual(placeDataSettings(e),placeDataSettings(this.config));s&&this.withoutEntryPointsRefresh(()=>this.updateData(e)),this.connectionLayerSpecs=this.replaceLayerSpecs(this.buildConnectionLayerSpecs(e),this.connectionLayerSpecs,t),isEqual(connectionDataSettings(e),connectionDataSettings(this.config))?this.applyConnectionsVisibility(e):this.updateConnectionsData(e),this.entryPointLayerSpecs=this.replaceLayerSpecs(this.buildEntryPointLayerSpecs(e),this.entryPointLayerSpecs,i),s||!isEqual(entryPointDataSettings(e),entryPointDataSettings(this.config))?this.updateEntryPointsData(e):this.applyEntryPointsVisibility(e),this._initializing||isEqual(this.config?.beforeLayerConfig,e?.beforeLayerConfig)||this.restackLayers()}restackLayers(){const{connections:e,places:t,placesUnclustered:i,entryPoints:s}=this.sourcesWithLayers;addLayers([e,t,i,s].flatMap(e=>e?._layerSpecs??[]),this.mapLibreMap,!0)}updatePlacesLayers(e){const t=this.buildLayerSpecs(e);if(isEqual(t,this.layerSpecs))return;const i=this.partitionSpecsForSources(t),s=this.partitionSpecsForSources(this.layerSpecs);isEqual(i.clusteredSpecs,s.clusteredSpecs)||this.replaceSourceLayers(i.clusteredSpecs,s.clusteredSpecs,this.sourcesWithLayers.places),this.sourcesWithLayers.placesUnclustered&&i.unclusteredSpecs.length>0&&!isEqual(i.unclusteredSpecs,s.unclusteredSpecs)&&this.replaceSourceLayers(i.unclusteredSpecs,s.unclusteredSpecs,this.sourcesWithLayers.placesUnclustered),this.layerSpecs=t}rebuildSourcesAndLayers(e){const t=this.drawnFeatures(),i=this.mapLibreMap;for(const s of[...Object.values(this.layerSpecs),...Object.values(this.connectionLayerSpecs),...Object.values(this.entryPointLayerSpecs)])i.getLayer(s.id)&&i.removeLayer(s.id);for(const s of[this.sourceID,this.unclusteredSourceID,this.connectionSourceID,this.entryPointSourceID])i.getSource(s)&&i.removeSource(s);this.initSourcesWithLayers(e,!0),this.showAgain(t,e)}showAgain(e,t){this.withoutEntryPointsRefresh(()=>this.showPlaces(t,e.places,e.placesUnclustered)),this.applyPlacesVisibility(t),this.updateConnectionsData(t,e.connections),this.updateEntryPointsData(t,e.entryPoints)}showPlaces(e,t,i=t){const s=preparePlacesForInstance(t,this.instanceIndex,e),{places:o,placesUnclustered:r}=this.sourcesWithLayers;(s.features.length||!o.isEmpty()||r&&!r.isEmpty())&&(o.show(s,{automaticVisibility:!1}),r?.show(i===t?s:preparePlacesForInstance(i,this.instanceIndex,e),{automaticVisibility:!1}))}updateConnectionsData(e,t=this.sourcesWithLayers.connections.shownFeatures){const{places:i,connections:s}=this.sourcesWithLayers,o=((e,t,i,s={})=>{const o=s.connections?.label?.title,r=eventStatesById(i),a=[];for(const{connection:n,id:l}of e){const e=resolveEndpoint(n.from,t),i=resolveEndpoint(n.to,t);if(!e||!i)continue;const s=o?o(n):"",c=r.get(l);a.push({type:"Feature",id:l,geometry:{type:"LineString",coordinates:[e.geometry.coordinates,withNearestLongitude(e.geometry.coordinates,i.geometry.coordinates)]},properties:{id:l,fromId:e.id,toId:i.id,label:s,...c&&{eventState:c}}})}return{type:"FeatureCollection",features:a}})(this.shownConnections,e=>i.findById(e)?.feature,t,e);s.showUnlessStillEmpty(o,{automaticVisibility:!1}),this.applyConnectionsVisibility(e)}updateEntryPointsData(e,t=this.sourcesWithLayers.entryPoints.shownFeatures){this.entryPointsRefreshHeld||this.withoutEntryPointsRefresh(()=>{const i=((e,t,i)=>{const s=[];if(!i)return{type:"FeatureCollection",features:s};const o=i.showFor??"selected",r=eventStatesById(t);for(const a of e.features){const e=a.properties.id,t=a.properties.entryPoints??[];if(t.length&&(isShownFor(o,a.properties.eventState)||r.size>0&&t.some((t,i)=>isShownFor(o,r.get(toEntryPointID(e,i))))))for(const[i,{position:o,...n}]of t.entries()){const t=toEntryPointID(e,i),l=r.get(t),c={...n,id:t,placeID:e,entryPointIndex:i};s.push({type:"Feature",id:t,geometry:toPointGeometry(o),properties:l?{...c,eventState:l}:c},{type:"Feature",id:t,geometry:{type:"LineString",coordinates:[a.geometry.coordinates,withNearestLongitude(a.geometry.coordinates,o)]},properties:c})}}return{type:"FeatureCollection",features:s}})(this.sourcesWithLayers.places.shownFeatures,t,e?.entryPoints),{entryPoints:s}=this.sourcesWithLayers;((e,t)=>e.features.length===t.features.length&&e.features.every((e,i)=>e.id===t.features[i].id&&e.properties.eventState===t.features[i].properties.eventState))(i,s.shownFeatures)||s.show(i,{automaticVisibility:!1}),this.applyEntryPointsVisibility(e)})}withoutEntryPointsRefresh(e){const t=this.entryPointsRefreshHeld;this.entryPointsRefreshHeld=!0;try{e()}finally{this.entryPointsRefreshHeld=t}}applyVisibilityTo(e,t,i){applyLayersVisibility(e,t&&!1!==i?.visible,this.mapLibreMap)}applyPlacesVisibility(e){this.applyVisibilityTo(Object.values(this.layerSpecs),!this.sourcesWithLayers.places.isEmpty(),e)}applyConnectionsVisibility(e){this.applyVisibilityTo(Object.values(this.connectionLayerSpecs),!this.sourcesWithLayers.connections.isEmpty(),e)}applyEntryPointsVisibility(e){this.applyVisibilityTo(Object.values(this.entryPointLayerSpecs),!this.sourcesWithLayers.entryPoints.isEmpty(),e)}setupImages(e){this.addedCategoryIcons=syncImages(this.mapLibreMap,this.addedCategoryIcons,customImagesByID(e?.icon?.categoryIcons,({id:e})=>suffixNumber(e,this.instanceIndex))),this.paintedPin=paintPin(this.mapLibreMap,this.defaultPlaceIconID,e?.icon?.default,{fillColor:this.colorOf(e)},defaultPin,this.paintedPin)}updateData(e){const{places:t,placesUnclustered:i}=this.sourcesWithLayers;this.showPlaces(e,t.shownFeatures,i?.shownFeatures)}async show(e){await this.waitUntilModuleReady(),this.clearConnectionsSync();const{entryPoints:t}=this.sourcesWithLayers;t.isEmpty()||this.withoutEntryPointsRefresh(()=>t.clear()),this.showPlaces(this.config,e),this.applyPlacesVisibility(this.config),emitShownFeatures(this.shownFeaturesHandlers,{places:e})}async clear(){await this.waitUntilModuleReady(),this.clearConnectionsSync();for(const e of[this.sourcesWithLayers.places,this.sourcesWithLayers.placesUnclustered])e?.clearUnlessEmpty()}async showConnections(e){await this.waitUntilModuleReady(),this.shownConnections=e.map(e=>({connection:e,id:e.id??generateId()})),this.updateConnectionsData(this.config,{type:"FeatureCollection",features:[]}),emitShownFeatures(this.shownFeaturesHandlers,{connections:e})}async clearConnections(){await this.waitUntilModuleReady(),this.clearConnectionsSync()}clearConnectionsSync(){this.shownConnections=[];const{connections:e}=this.sourcesWithLayers;e.clearUnlessEmpty()}getShown(){return{places:this.sourcesWithLayers.places.shownFeatures,connections:this.shownConnections.map(({connection:e})=>e)}}eventStateSources(){return placeSources}get events(){return this.buildEvents(this.moduleEventsWithShown([...placeSources,"connections","entryPoints"],this.shownFeaturesHandlers),{places:this.userEventsWithStates(placeSources,{scope:{featureMatches:e=>!isCluster(e)}}),connections:this.userEventsWithStates(["connections"]),entryPoints:this.userEventsWithStates(["entryPoints"],{mapping:e=>((e,t)=>{const i=e.properties,s=findFeatureByRefId(t.features,i.placeID)?.feature,{position:o,...r}=s?.properties.entryPoints?.[i.entryPointIndex]??{...i,position:toEntryPointPosition(e.geometry)};return{type:"Feature",id:i.id,geometry:toPointGeometry(o),properties:{...i,...r,place:s}}})(e,this.sourcesWithLayers.places.shownFeatures)})})}},poiCategoryGroups={FOOD_DRINKS_GROUP:["RESTAURANT","FAST_FOOD","CAFE_PUB","PUB","WINERY","SOUL_FOOD"],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"],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","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__ */(()=>{const e=/* @__PURE__ */valuesFilterKnobs("filters.categories","categories and category groups",[...Object.keys(poiCategoryGroups),...poiCategories]," A group stands for each of its categories; groups come first in the options.");return{visible:{kind:"toggle",description:"The POIs the map style draws.",default:!0},"filters.categories.show":e.show,"filters.categories.values":e.values,sizeFactor:{kind:"factor",description:"Size of the POI icons and their labels.",range:FACTOR_RANGE,default:1},minZoom:{kind:"number",description:"Zoom level from which POIs appear (the style default is 6).",range:{min:3,max:18,step:1,bounds:"hard"}},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"},default:0},"label.color":{kind:"color",description:"Text colour of the POI labels (replaces the per-category colours)."},"label.haloColor":{kind:"color",description:"Halo colour of the POI labels."},"microMarkers.visible":{kind:"toggle",description:"The small dot markers for low-priority POIs at high zoom; never shown while the POIs are hidden."}}})(),poisKnobCatalogue=/* @__PURE__ */withIds(poisKnobDefinitions),poisKnobIds=/* @__PURE__ */poisKnobCatalogue.map(({id:e})=>e),AppliedFilters=class{replace(e,t,i){e.mapReady&&(i(t,this.filters),this.filters=t)}},styleModuleLayerGroupNames=["pois","trafficFlow","trafficIncidents","hillshade"],styleModuleLayerGroupSelectors={pois:{sources:["vectorTiles"],sourceLayers:["poi"],layerTypes:["symbol"]},trafficFlow:{sources:["vectorTilesFlow"]},trafficIncidents:{sources:["vectorTilesIncidents"]},hillshade:{layerTypes:["hillshade"]}},styleModuleLayerGroupSelector=e=>styleModuleLayerGroupSelectors[e],styleLayerGroupSelector=e=>(e=>e in styleModuleLayerGroupSelectors)(e)?styleModuleLayerGroupSelector(e):baseMapLayerGroupSelector(e),writeLayerProperty=(e,t,i,s,o)=>{if(!e.getLayer(t))return;const r=e,a={validate:!1};"paint"===i?r.setPaintProperty(t,s,o,a):r.setLayoutProperty(t,s,o,a)},isDerivation=e=>"function"==typeof e,toOverrides=(e,t)=>Object.entries(t).map(([t,i])=>({kind:e,property:t,valueOf:isDerivation(i)?i:()=>i})),LayerSelection=class{constructor(e,t){this.registry=e,this.query=t}get layerIds(){return this.registry.resolve(this.query)}setPaint(e){return this.registry.override(this.query,toOverrides("paint",e)),this}setLayout({visibility:e,...t}){return this.registry.override(this.query,toOverrides("layout",t)),void 0!==e&&this.setVisible("none"!==e),this}setFilter(e){return this.registry.overrideFilter(this.query,e),this}addFilterClause(e){return this.registry.addFilterClause(this.query,e),this}removeFilterClause(e){return this.registry.removeFilterClause(this.query,e),this}setVisible(e){return this.registry.overrideVisibility(this.query,e),this}reset(){return this.registry.reset(this.query),this}},LayerOverrides=class{constructor(e,t,i,s){this.mapLibreMap=e,this.filterComposer=t,this.visibilityComposer=i,this.warn=s,this.layers=[],this.sources={},this.properties=/* @__PURE__ */new Map,this.filters=/* @__PURE__ */new Map,this.clauses=/* @__PURE__ */new Map,this.visibility=/* @__PURE__ */new Map,this.contributed=!1}index(e,t,i){if(this.layers=e,this.sources=t,this.contributed=!1,i)for(const s of this.properties.values())for(const e of s.values())e.restyled=!0}clear(e){e&&this.withdrawFromKeptLayers(),this.properties.clear(),this.filters.clear(),this.clauses.clear(),this.visibility.clear()}resolve(e){const t=selectorsOf(e);return this.layers.filter(e=>t.every(t=>matchesLayerSelector(t,e,this.sources))).map(e=>e.id)}override(e,t){if(t.length)for(const i of this.resolveToEdit(e)){const e=ofMap(this.properties,i,()=>/* @__PURE__ */new Map),s=!!this.mapLibreMap.getLayer(i);for(const o of t){const t=`${o.kind}:${o.property}`;if(!s){e.set(t,{override:o,before:void 0,written:void 0,restyled:!0});continue}const r=e.get(t),a={override:o,before:r&&!r.restyled?r.before:this.read(i,o),written:void 0};this.land(i,a),e.set(t,a)}}}addFilterClause(e,t){for(const i of this.resolveToEdit(e)){const e=ofMap(this.clauses,i,()=>[]);e.some(e=>isEqual(e,t))||e.push(t),this.contributeClauses(i)}}removeFilterClause(e,t){for(const i of this.resolveToEdit(e)){const e=(this.clauses.get(i)??[]).filter(e=>!isEqual(e,t));e.length?this.clauses.set(i,e):this.clauses.delete(i),this.contributeClauses(i)}}overrideFilter(e,t){for(const i of this.resolveToEdit(e))this.filters.set(i,t),this.filterComposer.setTransform(i,"styling.layers",()=>t)}overrideVisibility(e,t){for(const i of this.resolveToEdit(e))this.visibility.set(i,t),this.visibilityComposer.setVisible(i,"styling.layers",t)}reset(e){for(const t of this.resolveToEdit(e)){for(const{override:e,before:i}of this.properties.get(t)?.values()??[])this.write(t,e,i);this.properties.delete(t),this.filters.delete(t)&&this.filterComposer.setTransform(t,"styling.layers",void 0),this.clauses.delete(t)&&this.contributeClauses(t),this.visibility.delete(t)&&this.visibilityComposer.setVisible(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);!i.restyled&&isEqual(t,i.written)||(i.before=t,i.restyled=!1,this.landOrWarn(e,i,t))}if(!this.contributed){this.contributed=!0;for(const[e,t]of this.filters)this.filterComposer.setTransform(e,"styling.layers",()=>t);for(const e of this.clauses.keys())this.contributeClauses(e);for(const[e,t]of this.visibility)this.visibilityComposer.setVisible(e,"styling.layers",t)}}withdrawFromKeptLayers(){for(const[e,t]of this.properties)if(this.mapLibreMap.getLayer(e))for(const{override:i,before:s,written:o}of t.values())isEqual(this.read(e,i),o)&&this.write(e,i,s);for(const e of this.filters.keys())this.filterComposer.setTransform(e,"styling.layers",void 0);for(const e of this.clauses.keys())this.filterComposer.setClause(e,"styling.layers",void 0);for(const e of this.visibility.keys())this.visibilityComposer.setVisible(e,"styling.layers",void 0)}landOrWarn(e,t,i){try{this.land(e,t)}catch(s){t.written=i;const{kind:o,property:r}=t.override;this.warn(`rejected:${e}:${o}:${r}`,`The ${o} edit of '${r}' on '${e}' failed on this style: ${s}`)}}resolveToEdit(e){const t=this.resolve(e);return 0===t.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.`),t}read(e,{kind:t,property:i}){const s=this.mapLibreMap;return"paint"===t?s.getPaintProperty(e,i):s.getLayoutProperty(e,i)}land(e,t){t.written=t.override.valueOf(t.before,e),this.write(e,t.override,t.written)}write(e,{kind:t,property:i},s){writeLayerProperty(this.mapLibreMap,e,t,i,s)}contributeClauses(e){const t=getMergedFilter("all",this.clauses.get(e)??[])??void 0;this.filterComposer.setClause(e,"styling.layers",t)}},selectorsOf=({group:e,...t})=>[t,...e?[styleLayerGroupSelector(e)]:[]],ZOOM_BOUNDS={minZoom:"minzoom",maxZoom:"maxzoom"},LAYOUT_PROPERTIES=/* @__PURE__ */new Set(["text-size","icon-size","text-font","fill-extrusion-rounded-corner-distance"]),SPEC_DEFAULTS={"text-size":16,"icon-size":1,"line-width":1,"line-opacity":1,minzoom:0,maxzoom:24,"hillshade-method":"standard","hillshade-illumination-direction":335,"hillshade-illumination-altitude":45,"hillshade-illumination-anchor":"viewport","hillshade-exaggeration":.5,"hillshade-shadow-color":"#000000","hillshade-highlight-color":"#FFFFFF","hillshade-accent-color":"#000000","fill-extrusion-rounded-corner-distance":0},isLayerMechanism=e=>"layers"in e,targetKey=(e,t)=>`${e}|${t}`,NO_TRANSITION={duration:0,delay:0},enginesByMap=/* @__PURE__ */new WeakMap,StyleKnobs=class StyleKnobs{constructor(e){this.settings={},this.stale=!1,this.registered=/* @__PURE__ */new Map,this.dependents=/* @__PURE__ */new Map,this.extensionIndexed=!1,this.style={layers:[],sources:{}},this.originalValues=/* @__PURE__ */new Map,this.resolved=/* @__PURE__ */new Map,this.scaleKnobsByTarget=/* @__PURE__ */new Map,this.warned=/* @__PURE__ */new Set,this.tomtomMap=e,this.filterComposer=LayerFilterComposer.for(e),this.indexStyle(),e.addStyleChangeHandler({onStyleAboutToChange:()=>{this.stale=!0},onStyleChanged:({resetState:e})=>this.restore(e),priority:90})}static for(e){return ofMap(enginesByMap,e,()=>new StyleKnobs(e))}register(e,t,i){i&&!this.extension&&(this.extension=i,this.stale||(i.index(),this.extensionIndexed=!0));for(const[s,o]of Object.entries(t))this.registered.has(s)||(this.registered.set(s,{owner:e,definition:o}),this.trackDependencies(s,o),this.stale||this.resolveKnob(s))}trackDependencies(e,t){for(const i of t.mechanisms)if("literal"===i.type)for(const t of i.expansion?.dependsOn??[])ofMap(this.dependents,t,()=>[]).push(e)}get values(){return this.settings}get indexedStyle(){return this.style}update(e){const t={...this.settings},i=[];for(const s of Object.keys(e)){const o=e[s];t[s]!==o&&(void 0===o?delete t[s]:t[s]=o,i.push(s))}if(this.settings=t,!this.stale&&i.length){for(const e of this.withDependents(i))this.refreshKnob(e);this.publish(i)}}reapply(e){if(!this.stale){for(const t of this.withDependents(e))this.refreshKnob(t);this.publish(e)}}valueOf(e){return this.settings[e]??this.derivedValueOf(e)??this.defaultOf(e)}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))}setProperty(e,t,i){const s=LAYOUT_PROPERTIES.has(t)?"layout":"paint";writeLayerProperty(this.tomtomMap.mapLibreMap,e,s,t,i)}restore(e){const t=new Set(Object.keys(this.settings));if(e&&(this.settings={}),this.stale=!1,this.tomtomMap._styleLoads!==this.indexedStyleLoads)this.indexStyle();else{for(const e of Object.keys(this.tomtomMap._styleKnobSettings))t.add(e);this.indexRegisteredWhileStale()}customTypefaceOf(this.tomtomMap)&&t.add("labels.typeface"),this.reapply([...t])}withDependents(e){return new Set(e.flatMap(e=>[e,...this.dependents.get(e)??[]]))}publish(e){const t=this.tomtomMap._styleKnobSettings,i=new Set(e);for(const s of Object.keys(t))t[s]!==this.settings[s]&&i.add(s);this.tomtomMap._setStyleKnobSettings(this.settings,i)}indexStyle(){this.indexedStyleLoads=this.tomtomMap._styleLoads;const e=this.tomtomMap.mapLibreMap.getStyle();this.style={layers:(e?.layers??[]).filter(e=>this.tomtomMap._isStyleLayer(e.id)),sources:e?.sources??{},projection:e?.projection,sky:e?.sky,light:e?.light},this.originalValues=/* @__PURE__ */new Map,this.resolved=/* @__PURE__ */new Map,this.scaleKnobsByTarget=/* @__PURE__ */new Map,this.warned=/* @__PURE__ */new Set,this.holdTransitionsUntilFirstFrame(),this.extension?.index(),this.extensionIndexed=!!this.extension;for(const t of this.registered.keys())this.resolveKnob(t)}indexRegisteredWhileStale(){this.extension&&!this.extensionIndexed&&(this.extension.index(),this.extensionIndexed=!0);for(const e of this.registered.keys())this.resolved.has(e)||this.resolveKnob(e)}holdTransitionsUntilFirstFrame(){const e=this.tomtomMap.mapLibreMap,t=e.style?.stylesheet;if(!t||t.transition===NO_TRANSITION)return;const i=t.transition;this.shippedTransition=i,t.transition=NO_TRANSITION,e.once("render",()=>{t.transition=i})}withShippedTransition(e){if(e.transition!==NO_TRANSITION)return e;const{transition:t,...i}=e;return this.shippedTransition?{...i,transition:this.shippedTransition}:i}resolveKnob(e){const t=this.registered.get(e);if(!t)return;const{definition:i}=t,s=i.mechanisms.map(t=>this.resolveMechanism(e,t)),o=new Set(s.flatMap(e=>e.layerIds)).size;this.resolved.set(e,{definition:i,mechanisms:s,targets:o})}resolveMechanism(e,t){if(!isLayerMechanism(t))return{mechanism:t,layerIds:this.extension?.resolve(e,t)??[],shadeLayerIds:[]};const{layers:i,sources:s}=this.style,o=i.filter(e=>matchesAnyLayerSelector(t.layers,e,s));let r,a=[];switch(t.type){case"scale":r=this.captureAll(o,t.property);for(const i of r){const s=targetKey(i,t.property);ofMap(this.scaleKnobsByTarget,s,()=>[]).push(e)}break;case"color":{r=this.captureAll(o,t.property);const e=t.shades??[],n=i.filter(t=>matchesAnyLayerSelector(e,t,s));a=this.captureAll(n,t.property);break}case"minZoom":case"maxZoom":r=o.map(e=>e.id);for(const e of o)this.capture(e,"minzoom"),this.capture(e,"maxzoom");break;case"literal":r=o.map(e=>e.id);for(const e of o)this.capture(e,t.property);break;case"zoomOffset":r=o.filter(e=>shiftZoomOffset(layerFilterOf(e),0).patched).map(e=>e.id);break;case"typeface":r=this.captureAll(o,"text-font")}return{mechanism:t,layerIds:r,shadeLayerIds:a}}captureAll(e,t){return e.filter(e=>this.capture(e,t)).map(e=>e.id)}refreshKnob(e){const t=this.resolved.get(e);if(t&&this.tomtomMap.mapReady){0===t.targets&&void 0!==this.settings[e]&&this.warnOnce(e,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 i of t.mechanisms)this.refreshMechanism(e,i)}}refreshMechanism(e,{mechanism:t,layerIds:i,shadeLayerIds:s}){if(isLayerMechanism(t)){if("color"===t.type){const o=this.settings[e];return void this.refreshColor(t.property,i,s,"string"==typeof o?o:void 0)}for(const s of i)this.refreshLayer(e,t,s)}else this.extension?.refresh(e,t)}refreshLayer(e,t,i){const s=this.settings[e];switch(t.type){case"scale":this.refreshScaledProperty(e,i,t.property);break;case"minZoom":case"maxZoom":this.refreshZoomBound(i,ZOOM_BOUNDS[t.type],"number"==typeof s?s:void 0);break;case"literal":{const e=s??this.originalValueOf(i,t.property),{expansion:o}=t;this.setProperty(i,t.property,o?o.expand(e,e=>this.valueOf(e)):e);break}case"zoomOffset":this.refreshZoomOffset(i,"number"==typeof s?s:void 0);break;case"typeface":this.setProperty(i,"text-font",inTypeface(this.originalValueOf(i,"text-font"),typefaceOf(this.tomtomMap,s)))}}refreshZoomBound(e,t,i){const s=this.tomtomMap.mapLibreMap;if(!s.getLayer(e))return;const o={minzoom:this.styleZoomBound(e,"minzoom"),maxzoom:this.styleZoomBound(e,"maxzoom")};o[t]=i??o[t],s.setLayerZoomRange(e,o.minzoom,o.maxzoom)}styleZoomBound(e,t){return this.originalValueOf(e,t)??SPEC_DEFAULTS[t]}refreshZoomOffset(e,t){this.filterComposer.setTransform(e,"styleKnobs.zoomShift",void 0===t?void 0:e=>shiftZoomOffset(e,t).filter)}refreshScaledProperty(e,t,i){const s=this.originalValueOf(t,i),o=(this.scaleKnobsByTarget.get(targetKey(t,i))??[]).reduce((e,t)=>{const i=this.settings[t];return e*("number"==typeof i?i:1)},1);if(1===o)return void this.setProperty(t,i,s);const r=scaleNumericValue(s,o);void 0!==r?this.setProperty(t,i,r):this.warnOnce(e,`scale:${t}:${i}`,`cannot scale '${i}' of layer '${t}': 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,s){for(const r of t)this.setProperty(r,e,s??this.originalValueOf(r,e));const o=t.map(t=>this.originalValueOf(t,e)).find(isColorLiteral);for(const r of i){const t=this.originalValueOf(r,e);let i=t;if(void 0!==s){const e=isColorLiteral(t)&&o&&hslShiftBetween(o,t);i=(e?shiftHsl(s,e):void 0)??s}this.setProperty(r,e,i)}}derivedValueOf(e){const[t]=this.resolved.get(e)?.definition.mechanisms??[];return t&&!isLayerMechanism(t)?this.extension?.derivedValueOf(e,t):void 0}defaultOf(e){const t=this.resolved.get(e);if(!t)return;const{definition:i,mechanisms:s}=t;if("factor"===i.kind)return 1;const[o]=s,[r]=o?.layerIds??[];if(void 0===r)return;const{mechanism:a}=o;if(!isLayerMechanism(a))return this.extension?.defaultOf(e,a);switch(a.type){case"color":{const e=this.originalValueOf(r,a.property);return isColorLiteral(e)?e:void 0}case"minZoom":case"maxZoom":return this.styleZoomBound(r,ZOOM_BOUNDS[a.type]);case"literal":{const e=this.originalValueOf(r,a.property);return"string"==typeof e||"number"==typeof e?e:void 0}case"zoomOffset":return 0;case"typeface":return"sans";default:return}}warnOnce(e,t,i){this.warned.has(t)||(this.warned.add(t),console.warn(`[${this.registered.get(e)?.owner??StyleKnobs.name}] ${i}`))}},StyleKnobScope=class{constructor(e,t,i,s){this.owner=e,this.prefix=t,this.definitions=i,this.extension=s}get knobIds(){return this.knobIdsByLocalId??=new Map(Object.keys(this.definitions).map(e=>[e.slice(this.prefix.length),e])),this.knobIdsByLocalId}has(e){return e in this.definitions}engineOf(e){const t=StyleKnobs.for(e);return this.registeredOn??=/* @__PURE__ */new WeakSet,this.registeredOn.has(e)||(t.register(this.owner,this.definitions,this.extension?.(e)),this.registeredOn.add(e)),t}apply(e,t){const i={};for(const[s,o]of this.knobIds)i[o]=knobValueIn(t,s);this.engineOf(e).update(i)}valueOf(e,t){const i=this.knobIds.get(t);return void 0===i?void 0:this.engineOf(e).valueOf(i)}},styleKnobScope=(e,t,i,s)=>new StyleKnobScope(e,t,i,s),layerFilterOf=e=>"filter"in e?e.filter:void 0,styleValueOf=(e,t)=>{const i=(e=>"layout"in e?e.layout:void 0)(e),s=(e=>"paint"in e?e.paint:void 0)(e),o="symbol"===e.type&&void 0!==i?.["text-field"];switch(t){case"text-size":return o?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":case"line-opacity":return"line"===e.type?s?.[t]??SPEC_DEFAULTS[t]:void 0;case"text-font":return o?i?.["text-font"]:void 0;case"minzoom":return e.minzoom;case"maxzoom":return e.maxzoom;default:return(LAYOUT_PROPERTIES.has(t)?i:s)?.[t]??((e,t)=>"hillshade"!==e.type&&"fill-extrusion"!==e.type||!(e=>e in SPEC_DEFAULTS)(t)?void 0:SPEC_DEFAULTS[t])(e,t)}},scaleKnob=(e,t)=>({kind:"factor",mechanisms:[{type:"scale",property:e,layers:[t]}]}),colorKnob=(e,t,i)=>({kind:"color",mechanisms:[{type:"color",property:e,layers:[t],shades:i&&[i]}]}),poisStyleKnobs=/* @__PURE__ */(()=>{const e=styleModuleLayerGroupSelector("pois");return{"pois.sizeFactor":{kind:"factor",mechanisms:[{type:"scale",property:"icon-size",layers:[e]},{type:"scale",property:"text-size",layers:[e]}]},"pois.minZoom":{kind:"number",mechanisms:[{type:"minZoom",layers:[{...e,idExcludes:["micro"]}]}]},"pois.zoomShift":{kind:"number",mechanisms:[{type:"zoomOffset",layers:[e]}]},"pois.label.color":colorKnob("text-color",e),"pois.label.haloColor":colorKnob("text-halo-color",e)}})(),poisLook=/* @__PURE__ */styleKnobScope("POIsModule","pois.",poisStyleKnobs),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}}},POI_ID=["to-string",["get","id"]],microMarkerSelectors=[{idIncludes:["micro"]}],iconLayoutProperties=["icon-image","icon-offset"],iconImageExpression=(e,t)=>{const i="string"==typeof t&&t.includes("{")?(e=>{const t=[];for(const[i,s]of e.split(/[{}]/).entries())i%2?t.push(["get",s]):s&&t.push(s);return["concat",...t]})(t):t??"",s=["match",["get","category"],...[...e].flat()];return s.push(i),s},toIconImageID=e=>`pois-${e}`,POIsModule=class POIsModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,POIsModule,()=>new POIsModule(e,t),t)}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const e=styleSourceWithLayers(this.mapLibreMap,"vectorTiles",POIsModule.name,e=>poiLayerIDs.includes(e.id));return this.addedIcons??={},this.appliedFilters??=new AppliedFilters,this.microMarkers=new LayerPartToggles("pois",{"microMarkers.visible":microMarkerSelectors}),this.microMarkers.index(e._layerSpecs),{pois:e}}_applyConfig(e){return e&&!isNil(e.visible)?this._setVisible(e.visible,!1):this._initializing||this.isVisible()||this._setVisible(!0,!1),this.appliedFilters.replace(this.tomtomMap,e?.filters,(e,t)=>{this.applyValuesFilter("pois.categories",t?.categories,e?.categories,({show:e,values:t})=>buildMappedValuesFilter("category",e,(e=>{const t=e.flatMap(e=>(e=>Object.hasOwn(poiCategoryGroups,e))(e)?poiCategoryGroups[e].map(toBaseMapPOICategory):[toBaseMapPOICategory(e)]);return[...new Set(t.filter(e=>!isNil(e)))]})(t))),this.applyValuesFilter("pois.ids",t?.ids,e?.ids,({show:e,values:t})=>buildMappedValuesFilter(POI_ID,e,t))}),this.applyCategoryIcons(e?.icon?.categoryIcons),poisLook.apply(this.tomtomMap,e),this.tomtomMap.mapReady&&this.microMarkers.apply(this.visibilityComposer,e),e}_knobValue(e){return super._knobValue(e)??("visible"===e?this.isVisible():void 0)??poisLook.valueOf(this.tomtomMap,e)??this.microMarkers.valueOf(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._layerSpecs){const t=matchesAnyLayerSelector(microMarkerSelectors,i);this.visibilityComposer.setVisible(i.id,"pois.visible",e&&t?void 0:e)}t&&(this.config={...this.config,visible:e},this.emitConfigChange())}applyValuesFilter(e,t,i,s){if(!i&&!t)return;const o=i&&isCompleteValuesFilter(i)?s(i):void 0;for(const r of this.sourcesWithLayers.pois.sourceAndLayerIDs.layerIDs)this.filterComposer.setClause(r,e,o)}applyCategoryIcons(e){if(!this.tomtomMap.mapReady||!this.mapLibreMap.getLayer(mapStyleLayerIDs.poi))return;const t=iconsByMapCategory(e),i=/* @__PURE__ */new Map,s=/* @__PURE__ */new Map;for(const[h,p]of t)i.set(h,toIconImageID(p.id)),s.set(h,{x:p.offsetX??0,y:p.offsetY??0});if(!i.size&&!Object.keys(this.addedIcons).length)return;const o=styleIconLayout(this.mapLibreMap,{"icon-image":this.mapLibreMap.getLayoutProperty(mapStyleLayerIDs.poi,"icon-image"),"icon-offset":this.mapLibreMap.getLayoutProperty(mapStyleLayerIDs.poi,"icon-offset")}),{"icon-image":r,"icon-offset":a}=o,n={"icon-image":i.size?iconImageExpression(i,r):r,"icon-offset":buildIconOffsetExpression(s,"category",a)??a};for(const h of iconLayoutProperties)this.mapLibreMap.setLayoutProperty(mapStyleLayerIDs.poi,h,n[h]);var l,c,d;l=this.mapLibreMap,c=n,d=o,writtenIconLayouts.set(l,{written:c,over:d});const u=customImagesByID([...t.values()],e=>toIconImageID(e.id));this.addedIcons=syncImages(this.mapLibreMap,this.addedIcons,u)}getRenderedFeatures(){return{pois:this.sourcesWithLayers.pois.queryRenderedFeatures().map(poisMapping)}}get events(){return this.moduleEvents(["pois"],{mapping:poisMapping})}},generatedSectionTypes=["carpool","carTrain","curvyStretch","curve","importantRoadStretch","lowEmissionZone","motorway","pedestrian","speedLimit","tollVignette","unpaved","urban"],bespokeSectionTypes=["ferry","tollRoad","traffic","tunnel","vehicleRestricted"],drawnSectionTypes=/* @__PURE__ */(()=>[...generatedSectionTypes,...bespokeSectionTypes])(),BAND_SECTION_KNOBS=["visible","color","opacity","widthPreset","widthFactor","style","pattern","icon"],SECTION_REGISTRY={carpool:{sourceKey:"carpoolSections",visible:!1,style:"halo",pattern:"solid",knobs:BAND_SECTION_KNOBS},carTrain:{sourceKey:"carTrainSections",visible:!0,style:"halo",pattern:"dashed",knobs:BAND_SECTION_KNOBS},curve:{sourceKey:"curveSections",visible:!1,style:"halo",rampsBy:"severity",knobs:["visible","color","opacity","widthPreset","widthFactor","style","icon","kerb"]},curvyStretch:{sourceKey:"curvyStretchSections",visible:!1,style:"halo",pattern:"solid",drawsUnder:"curve",knobs:BAND_SECTION_KNOBS},importantRoadStretch:{sourceKey:"importantRoadStretchSections",visible:!1,style:"halo",pattern:"solid",knobs:BAND_SECTION_KNOBS},lowEmissionZone:{sourceKey:"lowEmissionZoneSections",visible:!0,style:"halo",pattern:"solid",knobs:BAND_SECTION_KNOBS},motorway:{sourceKey:"motorwaySections",visible:!1,style:"halo",pattern:"solid",knobs:BAND_SECTION_KNOBS},pedestrian:{sourceKey:"pedestrianSections",visible:!1,style:"halo",pattern:"dashed",knobs:BAND_SECTION_KNOBS},speedLimit:{sourceKey:"speedLimitSections",visible:!0,knobs:["visible","sign"]},tollVignette:{sourceKey:"tollVignetteSections",visible:!0,style:"halo",pattern:"dashed",knobs:BAND_SECTION_KNOBS},unpaved:{sourceKey:"unpavedSections",visible:!1,style:"halo",pattern:"dashed",knobs:BAND_SECTION_KNOBS},urban:{sourceKey:"urbanSections",visible:!1,style:"halo",pattern:"solid",knobs:BAND_SECTION_KNOBS},ferry:{sourceKey:"ferries",visible:!0,style:"inline",pattern:"solid",knobs:BAND_SECTION_KNOBS},tollRoad:{sourceKey:"tollRoads",visible:!0,style:"halo",pattern:"solid",knobs:BAND_SECTION_KNOBS},traffic:{sourceKey:"incidents",visible:!0,style:"inline",knobs:["visible","opacity","widthPreset","widthFactor","style"]},tunnel:{sourceKey:"tunnels",visible:!0,style:"inline",pattern:"solid",knobs:BAND_SECTION_KNOBS},vehicleRestricted:{sourceKey:"vehicleRestricted",visible:!0,style:"inline",pattern:"dotted",knobs:BAND_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"),bandedSectionTypes=/* @__PURE__ */generatedSectionTypes.filter(e=>!postsSign(e)),sectionSourceKey=e=>SECTION_REGISTRY[e].sourceKey,SUMMARY_BUBBLE_DEFAULT_FIELDS=["duration","distance","trafficDelay"],mapLayerSpecs=(e={},t)=>Object.entries(e).map(([e,i])=>({...i,id:prefixLayerID(e,t)})),routeDisplayUnits=e=>{const t=TomTomConfig.instance.get().displayUnits;return{distance:{...t?.distance,...e?.displayUnits?.distance},time:{...t?.time,...e?.displayUnits?.time}}},SELECTED_ROUTE_FILTER=["==",["get","routeState"],"selected"],DESELECTED_ROUTE_FILTER=["==",["get","routeState"],"deselected"],routeStateLine=(e,t,i)=>({filter:e,type:"line",layout:{"line-join":"round",...i},paint:t}),selectedRouteLine=(e,t)=>/* @__PURE__ */routeStateLine(SELECTED_ROUTE_FILTER,e,t),selectedRoutePOISymbol=(e,t)=>({filter:SELECTED_ROUTE_FILTER,type:"symbol",minzoom:t,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-image":e,"icon-size":/* @__PURE__ */zoomRamp(t,.8,16.5,1)}}),instanceImageID=(e,t)=>void 0===t?e:suffixNumber(e,t),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"},ROUTE_WAYPOINT_HIGHLIGHT_SIZE_FACTOR_RANGE={min:1,max:1.5,step:.05,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"},SECTION_FOCUS_OUTLINE_WIDTH_FACTOR_RANGE={min:.5,max:2,step:.1,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,s=scaleNumericValue(i,clampFactor(t,SECTION_ICON_SIZE_FACTOR_RANGE));return"number"==typeof s||isExpression(s)?s:i},scaledWidth=(e,t)=>scaleRamp(e[t?.widthPreset??"m"],clampFactor(t?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),LINE_FOREGROUND_WIDTHS={s:/* @__PURE__ */zoomRamp(1,2,5,3,10,5,18,7),m:/* @__PURE__ */zoomRamp(1,3,5,4,10,7,18,10),l:/* @__PURE__ */zoomRamp(1,5,5,6,10,11,18,15)},LINE_OUTLINE_WIDTHS={s:/* @__PURE__ */zoomRamp(1,4,5,5,10,8,18,11),m:/* @__PURE__ */zoomRamp(1,5,5,6,10,10,18,14),l:/* @__PURE__ */zoomRamp(1,7,5,9,10,14,18,19)},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),SECTION_FOCUS_OUTLINE_WIDTH=/* @__PURE__ */zoomRamp(5,2,10,3,18,4),rampStops=e=>e.slice(3).filter(e=>"number"==typeof e),widestRamp=e=>{const[t,...i]=e.map(rampStops);/* @__PURE__ */
2
+ return zoomRamp(...t.map((e,t)=>t%2==0?e:Math.max(e,...i.map(e=>e[t]))))},getSectionFocusGapWidth=(e,t,i=[])=>widestRamp([scaleRamp(getLineOutlineWidth(e),t),...i]),getSectionFocusOutlineWidth=e=>scaleRamp(SECTION_FOCUS_OUTLINE_WIDTH,clampFactor(e,SECTION_FOCUS_OUTLINE_WIDTH_FACTOR_RANGE)),waypointScale=(e,t)=>WAYPOINT_SIZE_PRESET_FACTORS[e??"m"]*clampFactor(t,ROUTE_WAYPOINT_SIZE_FACTOR_RANGE),getWaypointIndexTextSize=(e,t)=>scaleRamp(PIN_ICON_SIZE,21*waypointScale(e,t)),STOP_MARK_TEXT_OFFSET=[0,-40.2/21],SECTION_HALO_WIDTHS={s:/* @__PURE__ */zoomRamp(1,8,5,9,10,12,18,15),m:/* @__PURE__ */zoomRamp(1,9,5,11,10,15,18,20),l:/* @__PURE__ */zoomRamp(1,12,5,14,10,19,18,24)},SECTION_HALO_MIN_OUTLINE_RATIO=/* @__PURE__ */(()=>ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE.max+.01)(),INSTRUCTION_LINE_WIDTHS={s:/* @__PURE__ */zoomRamp(16,8,22,12),m:/* @__PURE__ */zoomRamp(16,12,22,17),l:/* @__PURE__ */zoomRamp(16,17,22,24)},INSTRUCTION_OUTLINE_WIDTHS={s:/* @__PURE__ */zoomRamp(16,10,22,14),m:/* @__PURE__ */zoomRamp(16,14,22,20),l:/* @__PURE__ */zoomRamp(16,20,22,28)},getInstructionLineWidth=e=>scaledWidth(INSTRUCTION_LINE_WIDTHS,e),getInstructionOutlineWidth=e=>scaledWidth(INSTRUCTION_OUTLINE_WIDTHS,e),INSTRUCTION_ARROW_SIZE=/* @__PURE__ */zoomRamp(16,1,22,2),getInstructionArrowSize=e=>scaleRamp(INSTRUCTION_ARROW_SIZE,clampFactor(e?.widthFactor,ROUTE_WIDTH_FACTOR_RANGE)),incidentIconID=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}},severityDashedFilter=["in",["get","magnitudeOfDelay"],["literal",["unknown","indefinite"]]],severitySolidFilter=["in",["get","magnitudeOfDelay"],["literal",["minor","moderate","major"]]],matchMagnitudeOfDelay=({fallback:e,...t})=>["match",["get","magnitudeOfDelay"],...indexedMagnitudes.flatMap(e=>{const i=t[e];return void 0===i?[]:[e,i]}),e],severityLineDashColor=/* @__PURE__ */matchMagnitudeOfDelay({unknown:"rgba(190, 39, 27, 1)",fallback:"rgba(137, 150, 168, 1)"}),summaryMapBubbleImg=e=>svgToImg(()=>{const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="65"><g filter="url(#A)"><rect id="pin" x="81.899" y="47" width="10" height="10" rx="2" transform="rotate(45 81.899 47)"/><rect id="bubble" x="10" y="10" width="140" height="45" rx="12"/></g><defs><filter id="A"><feDropShadow dx="0" dy="2" stdDeviation="4" flood-opacity=".3"/></filter></defs></svg>\n');return t.querySelector("#bubble")?.setAttribute("fill",e),t.querySelector("#pin")?.setAttribute("fill",e),t}),SUMMARY_BUBBLE_CONTENT=[10,10,130,45],summaryBubbleImageOptions={pixelRatio:2,stretchX:[[20,45],[100,130]],stretchY:[[20,35]],content:SUMMARY_BUBBLE_CONTENT},summaryBubbleOverhang=/* @__PURE__ */(()=>({right:(150-SUMMARY_BUBBLE_CONTENT[2])/2,bottom:(55-SUMMARY_BUBBLE_CONTENT[3])/2,tail:3}))(),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=/* @__PURE__ */roundSignSvg("#fff","#D0021B",5),SPEED_LIMIT_SIGN_SVGS={whiteDisc:WHITE_DISC_SVG,yellowDisc:/* @__PURE__ */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},sectionStartSignImg=e=>staticImg(SECTION_START_SIGN_SVGS[e]),speedLimitSignImg=e=>staticImg(SPEED_LIMIT_SIGN_SVGS[e]),trafficImg=e=>svgToImg(()=>{const t=parseSvg('<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><g id="main"><path fill-rule="evenodd" 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"/><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"/><path fill-rule="evenodd" 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"/><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"/></g></svg>\n'),i=t.querySelector("#main");return i?.setAttribute("transform","scale(2)"),i?.setAttribute("fill",e),t}),waypointGlyphs={start:'<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140"><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" fill="#f4f5f6"/></svg>\n',middle:void 0,finish:'<svg xmlns="http://www.w3.org/2000/svg" width="120" height="140"><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" fill="#f4f5f6"/></svg>\n'},hasFormattedTraffic=["has","formattedTraffic"],HEADLINE_PROPERTY={duration:"formattedDuration",distance:"formattedDistance",durationDifference:"formattedDurationDifference"},HAS_FIELD={durationDifference:["has","formattedDurationDifference"],trafficDelay:hasFormattedTraffic},anyFieldOf=e=>{const t=e.map(e=>HAS_FIELD[e]).filter(e=>void 0!==e);return t.length<e.length||getMergedFilter("any",t)||!0},when=(e,t,i="")=>!0===e?t:["case",e,t,i],ROUTES_FILTER={all:void 0,selected:SELECTED_ROUTE_FILTER,alternatives:DESELECTED_ROUTE_FILTER},BOLD_FONT=["literal",["Noto-Bold"]],MEDIUM_FONT=["literal",["Noto-Medium"]],headlineSections=(e,t)=>{const i=["case",SELECTED_ROUTE_FILTER,t.text,t.mutedText];return e.flatMap((s,o)=>{const r=["get",HEADLINE_PROPERTY[s]],a=HAS_FIELD[s]??!0;if(0===o)return[when(a,r),{"text-font":BOLD_FONT,"text-color":i}];const n=anyFieldOf(e.slice(0,o));return[when(a,["concat",when(n,"\t\t"),r]),{"text-font":when(n,MEDIUM_FONT,BOLD_FONT),"text-color":when(n,t.mutedText,i)}]})},newlineAfter=e=>{if(!e.length)return[];const t=anyFieldOf(e);return[when(!0===t?hasFormattedTraffic:["all",hasFormattedTraffic,t],"\n"),{}]},trafficDelaySections=(e,t,i)=>[...newlineAfter(e),["image",["case",hasFormattedTraffic,
3
+ /* @__PURE__ */matchMagnitudeOfDelay({minor:i("traffic-minor"),moderate:i("traffic-moderate"),major:i("traffic-major"),fallback:i("traffic-clear")}),""]],{},["case",hasFormattedTraffic,["concat"," ",["get","formattedTraffic"]],""],{"text-font":BOLD_FONT,"text-color":/* @__PURE__ */matchMagnitudeOfDelay({minor:"#f58240",moderate:"#FB2D09",major:t.majorDelay,fallback:t.unknownDelay})}],summaryBubbleSymbol=(e,t,i,s)=>{const o=t=>instanceImageID(t,e),r=t?.label,a=labelTypefaceOf(r,s),{textField:n,filter:l}=((e,t,i,s)=>{const o=e?.label?.title;if("function"==typeof o)return{textField:["get",TITLE],filter:["has",TITLE]};if(void 0!==o)return{textField:o};const r=((e,t,i)=>{const s=e.filter(e=>"trafficDelay"!==e),o=e.includes("trafficDelay");if(!s.length&&!o)return{textField:"",filter:["boolean",!1]};const r=["format",...headlineSections(s,t),...o?trafficDelaySections(s,t,i):[]],a=anyFieldOf(e);return!0===a?{textField:r}:{textField:r,filter:a}})(e?.fields??SUMMARY_BUBBLE_DEFAULT_FIELDS,t,i);return{...r,textField:inTypeface(r.textField,s)}})(t,i,o,a),c=getMergedFilter("all",[ROUTES_FILTER[t?.routes??"all"],l].filter(e=>void 0!==e));return{type:"symbol",...c&&{filter:c},...void 0!==t?.minZoom&&{minzoom:t.minZoom},...void 0!==t?.maxZoom&&{maxzoom:t.maxZoom},layout:{"icon-image":["case",SELECTED_ROUTE_FILTER,o("selected-route-summary-popup"),o("deselected-route-summary-popup")],"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":inTypeface(["Noto-Medium"],a),"text-size":r?.size??13,"icon-padding":0,"text-justify":"left","text-line-height":1.5,"text-field":n},paint:{"text-color":["case",SELECTED_ROUTE_FILTER,i.text,i.mutedText],...void 0!==r?.opacity&&{"text-opacity":r.opacity},"icon-translate":[0,-35],"text-translate":[0,-35],"icon-translate-anchor":"viewport","text-translate-anchor":"viewport"}}},COUNTRY_CROSSING_LAYER_ID="routeCountryCrossing",CROSSING_TEXT_SIZE=/* @__PURE__ */zoomRamp(5,11,12,13),countryCrossingSymbol=(e,t,i)=>{const s=(e=>{const t=[0,-(4+summaryBubbleOverhang.tail)];return{layout:{"icon-image":e,"icon-text-fit":"both","icon-text-fit-padding":[4,8-summaryBubbleOverhang.right,4-summaryBubbleOverhang.bottom,8],"text-anchor":"bottom","icon-rotation-alignment":"viewport","text-rotation-alignment":"viewport"},paint:{"icon-translate":t,"text-translate":t,"icon-translate-anchor":"viewport","text-translate-anchor":"viewport"}}})(instanceImageID("route-country-crossing-bubble",e));return{type:"symbol",filter:SELECTED_ROUTE_FILTER,minzoom:t?.minZoom??4,layout:{"symbol-placement":"point",...s.layout,"text-field":["get","label"],"text-font":["Noto-Bold"],"text-size":CROSSING_TEXT_SIZE,...!1===t?.visible&&{visibility:"none"}},paint:{...s.paint,"text-color":i.text}}},GENERATED_SECTION_PAINT={carpool:{color:"#6D4AC7",opacity:.55},carTrain:{color:"#8A5A2B",opacity:.6},curvyStretch:{color:"#D6336C",opacity:.35},curve:{color:"#D6336C",opacity:.8},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}},FADE_TOWARD={light:"#FFFFFF",dark:"#1A2024"},kerbDefaultColor=(e,t)=>mixColor(e,FADE_TOWARD[t],.95)??e,rampedColor=(e,t,i)=>["interpolate",["linear"],["coalesce",["get",e],1],0,mixColor(t,FADE_TOWARD[i],.45)??t,1,t],KERB_DASH_ARRAY=[.3,.3],isKerbStriped=(e,t)=>sectionSupportsKnob(e,"kerb")&&(t?.kerb?.visible??!0),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]},getSectionLineWidth=(e,t,i)=>{const s={widthPreset:t?.widthPreset??i?.widthPreset,widthFactor:t?.widthFactor??i?.widthFactor};return"halo"===sectionDrawStyle(e,t)?((e,t=e??{})=>widestRamp([scaledWidth(SECTION_HALO_WIDTHS,e),scaleRamp(getLineOutlineWidth(t),SECTION_HALO_MIN_OUTLINE_RATIO)]))(s,i??{}):getLineForegroundWidth(s)},drawnSectionLineWidths=(e,t)=>drawnSectionTypes.filter(t=>sectionDrawStyle(t,e?.[t])&&isSectionVisible(t,e?.[t])).map(i=>{const s=getSectionLineWidth(i,e?.[i],t);return isKerbStriped(i,e?.[i])?scaleRamp(s,1.1):s}),withSectionLineKnobs=(e,t,i,s,o="principal")=>{const r=getSectionLineWidth(e,i,s),a={...t.paint,"line-width":"kerb"===o?scaleRamp(r,1.1):r};if(i?.color&&sectionSupportsKnob(e,"color")&&"kerb"!==o){const e="outline"===o?darkerShadeOf(i.color):i.color;e&&(a["line-color"]=e)}void 0!==i?.opacity&&sectionSupportsKnob(e,"opacity")&&(a["line-opacity"]=i.opacity);const n="principal"===o&&sectionSupportsKnob(e,"pattern"),l=n?i?.pattern??sectionEntry(e).pattern:void 0;return n&&((e,t)=>{const i=linePatternDashArray(e);i?t["line-dasharray"]=i:delete t["line-dasharray"]})(l,a),{...t,layout:{...t.layout,...linePatternLayout(l),...!isSectionVisible(e,i)&&{visibility:"none"}},paint:a}},withSectionSymbolKnobs=(e,t,i)=>{const s=sectionSupportsKnob(e,"icon")?i?.icon:void 0;return{...t,layout:{...t.layout,...s&&{...s.image&&{"icon-image":s.image},...void 0!==s.sizeFactor&&{"icon-size":getSectionIconSize(t.layout?.["icon-size"],s.sizeFactor)},...s.placement&&{"symbol-placement":"along"===s.placement?"line":"line-center"}},...!isSectionVisible(e,i)&&{visibility:"none"}}}},sectionLine=(e,t,i,s="light")=>{const o=withSectionLineKnobs(e,/* @__PURE__ */selectedRouteLine({"line-color":GENERATED_SECTION_PAINT[e].color,"line-opacity":GENERATED_SECTION_PAINT[e].opacity},{"line-cap":"round"}),t,i),{rampsBy:r}=sectionEntry(e);if(!r)return o;const a=t?.color??GENERATED_SECTION_PAINT[e].color;return{...o,paint:{...o.paint,"line-color":rampedColor(r,a,s)}}},SIGN_ICON_SIZE=/* @__PURE__ */zoomRamp(10,.5,16,.7),POSTED_SIGN_ICON_SIZE=/* @__PURE__ */scaleRamp(SIGN_ICON_SIZE,.9),POSTED_SIGN_TEXT_SIZE=/* @__PURE__ */zoomRamp(10,8,16,11.5),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??12.5,layout:{...(i=signPlacement(t),"atChange"===i?{"symbol-placement":"point"}:{"symbol-placement":"line","symbol-spacing":260}),"icon-image":["get","signImageID"],"icon-size":POSTED_SIGN_ICON_SIZE,"icon-rotation-alignment":"viewport","text-field":["get","signLabel"],"text-font":["Noto-Bold"],"text-size":POSTED_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":instanceImageID(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}`,sectionLineLayerID=e=>sectionLayerID(e,"Line"),sectionSignLayerID=e=>sectionLayerID(e,"Sign"),START_INDEX="start",MIDDLE_INDEX="middle",FINISH_INDEX="finish",routeWidths=/* @__PURE__ */(()=>/* @__PURE__ */everyOf()(["s","m","l"]))(),routeKnobDefinitions=/* @__PURE__ */(()=>({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."},widthPreset:{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},opacity:{kind:"number",description:"Opacity of the route lines and their outlines, selected and deselected; sections keep their own.",range:UNIT_RANGE,default:1},"highlight.outline.widthFactor":{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},"highlight.section.outline.color":{kind:"color",description:"Colour of the ring around the sections `setSectionFocus` marks. Unset: black on light styles, white on dark."},"highlight.section.outline.widthFactor":{kind:"factor",description:"Multiplier on the width of the ring around the focused sections, 2 to 4 pixels as the zoom grows.",range:SECTION_FOCUS_OUTLINE_WIDTH_FACTOR_RANGE,default:1},"waypoints.sizePreset":{kind:"enum",description:`Size preset of the waypoint pins and their stop marks: \`s\` is ${WAYPOINT_SIZE_PRESET_FACTORS.s} × \`m\`, \`l\` ${WAYPOINT_SIZE_PRESET_FACTORS.l} × \`m\`.`,options:/* @__PURE__ */everyOf()(["s","m","l"]),default:"m"},"waypoints.sizeFactor":{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:UNIT_RANGE},"waypoints.stopNumbering":{kind:"enum",description:"How the stop pins are marked: `1, 2, 3…`, `A, B, C…`, or left empty.",options:/* @__PURE__ */everyOf()(["numbers","letters","none"]),default:"numbers"},"waypoints.highlight.sizeFactor":{kind:"factor",description:"Multiplier on the pin size of a hovered or clicked waypoint; `1` draws it as any other.",range:ROUTE_WAYPOINT_HIGHLIGHT_SIZE_FACTOR_RANGE,default:1.2},"waypoints.label.visible":{kind:"toggle",description:"Whether the waypoint labels show: the place name, and the stop duration under it.",default:!0},"waypoints.label.color":{kind:"color",description:`Colour of the waypoint labels. Unset: \`${themeAdaptiveLabelColors("light").textColor}\`, \`${themeAdaptiveLabelColors("dark").textColor}\` on a dark map.`},"waypoints.label.haloColor":{kind:"color",description:`Colour of the halo around the waypoint labels. Unset: \`${themeAdaptiveLabelColors("light").haloColor}\`, \`${themeAdaptiveLabelColors("dark").haloColor}\` on a dark map.`},"waypoints.label.size":{kind:"number",description:"Text size of the waypoint labels, in pixels. Unset: 14 to 16 as the zoom grows.",range:LABEL_SIZE_RANGE},"waypoints.label.haloWidth":{kind:"number",description:"Width of the halo around the waypoint labels, in pixels.",range:LABEL_HALO_WIDTH_RANGE,default:1.5},"waypoints.label.opacity":{kind:"number",description:"Opacity of the waypoint labels.",range:UNIT_RANGE,default:1},"waypoints.label.font":{kind:"enums",description:"Font faces of the waypoint labels, in order: the first one available wins. Unset: `Noto-Bold` in the labels' typeface.",options:mapFonts},"waypoints.label.typeface":/* @__PURE__ */labelTypefaceKnob("waypoints.label","waypoint labels"),"waypoints.entryPoints":{kind:"enum",description:"Draw each waypoint at its place's main entry point, otherwise its first untyped one, as reverse geocoding returns them, otherwise at its own coordinates.",options:/* @__PURE__ */everyOf()(getPositionEntryPointOptions),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`."},"summaryBubbles.visible":{kind:"toggle",description:"The bubbles giving each route's duration, distance and traffic delay.",default:!0},"summaryBubbles.routes":{kind:"enum",description:"Which routes get a bubble: `all`, the `selected` one alone, or the `alternatives` to it, for an app that tells the selected trip in a panel of its own.",options:/* @__PURE__ */everyOf()(["all","selected","alternatives"]),default:"all"},"summaryBubbles.fields":{kind:"enums",description:"What each bubble says, in order: the first field the route carries in bold, `durationDifference` against the selected route on the other routes, `trafficDelay` on its own line on a route with a delay. A bubble with nothing to say is not drawn.",options:/* @__PURE__ */everyOf()(["duration","distance","durationDifference","trafficDelay"]),default:SUMMARY_BUBBLE_DEFAULT_FIELDS},"summaryBubbles.minZoom":{kind:"number",description:"Lowest zoom the summary bubbles are drawn at. Unset: every zoom.",range:ZOOM_RANGE},"summaryBubbles.maxZoom":{kind:"number",description:"Zoom from which the summary bubbles stop being drawn. Unset: every zoom.",range:ZOOM_RANGE},"summaryBubbles.color":{kind:"color",description:"Colour of the selected route's bubble; the others take a darker shade, and the text whichever of black and white reads. Unset: the map's `colors.labelHalo` lightened, when a theme sets it; otherwise white, or dark grey on a dark style."},"summaryBubbles.label.color":{kind:"color",description:"Text colour on the selected route's bubble; the others keep their muted text. Unset: the map's `colors.label` when a theme sets it and the bubble has no `summaryBubbles.color`; otherwise black or white, whichever reads on the bubble."},"summaryBubbles.label.size":{kind:"number",description:"Text size of the summary bubbles, in pixels; the bubble grows with it.",range:LABEL_SIZE_RANGE,default:13},"summaryBubbles.label.opacity":{kind:"number",description:"Opacity of the summary bubble text; the bubble stays opaque.",range:UNIT_RANGE,default:1},"summaryBubbles.label.typeface":/* @__PURE__ */labelTypefaceKnob("summaryBubbles.label","summary bubbles",!1),"countryCrossings.visible":{kind:"toggle",description:"The labels naming both countries at each border crossing; needs `country` sections.",default:!0},"countryCrossings.minZoom":{kind:"number",description:"Lowest zoom a border crossing label is drawn at.",range:ZOOM_RANGE,default:4},"countryCrossings.color":{kind:"color",description:"Colour of the border crossing bubbles. Unset: the map's `colors.labelHalo` lightened, when a theme sets it; otherwise white, or dark grey on a dark style."},"countryCrossings.label.color":{kind:"color",description:"Label colour of the border crossings. Unset: the map's `colors.label` when a theme sets it and the bubble has no `countryCrossings.color`; otherwise black or white, whichever reads on the bubble."}}))(),HALO_FLOOR=/* @__PURE__ */(()=>`A halo stays at least ${SECTION_HALO_MIN_OUTLINE_RATIO}× the route's outline.`)(),withIconImage=e=>isGeneratedSectionType(e)?"; set with `icon.image`":"",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:UNIT_RANGE}),widthPreset:e=>({kind:"enum",description:`Line width preset of the \`${e}\` sections; unset follows the route's. ${HALO_FLOOR}`,options:routeWidths}),widthFactor:e=>({kind:"factor",description:`Multiplier over the \`${e}\` sections' width preset; unset follows the route's. ${HALO_FLOOR}`,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:linePatterns,...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${withIconImage(e)}.`,options:/* @__PURE__ */everyOf()(["center","along"]),...defaultOf(isGeneratedSectionType(e)?"center":void 0)}),"icon.sizeFactor":e=>({kind:"factor",description:`Multiplier over the \`${e}\` icon's size${withIconImage(e)}.`,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,step:.5},default:12.5}),"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"])}),"kerb.visible":e=>({kind:"toggle",description:`Kerb stripes over the tight \`${e}\` sections, 60 m of radius or less, from zoom 12, alternating \`kerb.color\` with \`color\`; off draws one plain line.`,default:!0}),"kerb.color":e=>({kind:"color",description:`Colour of the \`${e}\` kerb stripes. Unset: \`color\` faded toward the map, white on light styles and near-black on dark.`})},waypointPinNames={start:"origin pin",middle:"stop pins",finish:"destination pin"},waypointPinStyleKnobDefinitions={fillColor:e=>({kind:"color",description:`Fill colour of the ${e}, over the shared pin style.`}),outlineColor:e=>({kind:"color",description:`Outline colour of the ${e}, over the shared pin style.`}),outlineOpacity:e=>({kind:"number",description:`Outline opacity of the ${e}, over the shared pin style.`,range:UNIT_RANGE})},sectionKnobId=(e,t)=>`sections.${e}.${t}`,buildCatalogue=()=>{const e=Object.keys(sectionKnobDefinitions),t=t=>e.filter(e=>e===t||e.startsWith(`${t}.`));return[.../* @__PURE__ */withIds(routeKnobDefinitions).flatMap(e=>"waypoints.icon.style.outlineOpacity"===e.id?[e,...[START_INDEX,MIDDLE_INDEX,FINISH_INDEX].flatMap(e=>Object.keys(waypointPinStyleKnobDefinitions).map(t=>({id:`waypoints.icon.${e}.style.${t}`,...waypointPinStyleKnobDefinitions[t](waypointPinNames[e])})))]:[e]),...drawnSectionTypes.flatMap(e=>sectionEntry(e).knobs.flatMap(t).map(t=>({id:sectionKnobId(e,t),...sectionKnobDefinitions[t](e)})))]},routingKnobCatalogue=/* @__PURE__ */buildCatalogue(),routingKnobIds=/* @__PURE__ */routingKnobCatalogue.map(({id:e})=>e),summaryBubbleColorKnobIds=["colors.label","colors.labelHalo"],summaryBubbleMapColors=(e={})=>({label:e["colors.label"],labelHalo:e["colors.labelHalo"]}),DARK_TEXT={text:"black",mutedText:"#727C85",majorDelay:"#AD0000",unknownDelay:"#000000"},LIGHT_TEXT={text:"#FFFFFF",mutedText:"#A7B0B8",majorDelay:"#FF6F61",unknownDelay:"#FFFFFF"},LIGHT_MAP_FILLS={selectedFill:"#FFFFFF",deselectedFill:"#EEEEEE"},DARK_MAP_FILLS={selectedFill:"#3A4148",deselectedFill:"#2A3036"},resolveSummaryBubbleColors=(e,t,i={})=>{const s=e?.color??(i.labelHalo&&(o=i.labelHalo,mixColor(o,"#FFFFFF",needsDarkText(o)?.6:.12)??o));var o;const r=s?{selectedFill:s,deselectedFill:mixColor(s,"#000000",.1)??s}:"dark"===t?DARK_MAP_FILLS:LIGHT_MAP_FILLS,a=needsDarkText(r.selectedFill)?DARK_TEXT:LIGHT_TEXT,n=e?.color?void 0:i.label;return{...r,...a,text:e?.label?.color??n??a.text}},resolveCountryCrossingColors=(e,t,i)=>{const{selectedFill:s,text:o}=resolveSummaryBubbleColors(e,t,i);return{selectedFill:s,text:o}},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"}}),instructionArrow=(e,t)=>({...commonProps,type:"symbol",layout:{"icon-allow-overlap":!0,"icon-image":instanceImageID("instruction-arrow",t),"icon-rotation-alignment":"map","icon-rotate":["get","lastPointBearingDegrees"],"icon-size":getInstructionArrowSize(e)}}),routeFerriesLine=/* @__PURE__ */selectedRouteLine({"line-color":"#6dc4ed"}),ferryTerminalSymbol=/* @__PURE__ */selectedRoutePOISymbol("poi-ferry_terminal",6),routeFerriesSymbol=/* @__PURE__ */(()=>({...ferryTerminalSymbol,maxzoom:16.5,layout:{...ferryTerminalSymbol.layout,"icon-ignore-placement":!0}}))(),outlineWidth=(e,t)=>scaledWhen(hasActiveEventState,getLineOutlineWidth(e),t),routeLine=(e,t,i)=>/* @__PURE__ */routeStateLine(e,{"line-color":t,"line-width":i},{"line-cap":"round","line-sort-key":["get","index"]}),routeDeselectedOutline=(e,t=1.2)=>routeLine(DESELECTED_ROUTE_FILTER,"#3C4956",outlineWidth(e,t)),routeOutline=(e,t,i=1.2)=>routeLine(SELECTED_ROUTE_FILTER,t??"#105287",outlineWidth(e,i)),routeMainLine=(e,t)=>routeLine(SELECTED_ROUTE_FILTER,t??"#36A8F0",getLineForegroundWidth(e)),routeLineArrows={type:"symbol",layout:{"symbol-placement":"line","icon-image":"roads-arrow-white","icon-rotate":180}},routeSectionFocusOutline=(e,t,i,s)=>({filter:e,type:"line",layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":i,"line-width":getSectionFocusOutlineWidth(s),"line-gap-width":t}}),routeTollRoadsOutline=/* @__PURE__ */selectedRouteLine({"line-color":"#BEBFFA"},{"line-cap":"round"}),routeTollRoadsSymbol=/* @__PURE__ */selectedRoutePOISymbol("poi-toll_plaza",4),trafficDelayColorKnobIds=/* @__PURE__ */(()=>[incidentColorKnobIds.minor,incidentColorKnobIds.moderate,incidentColorKnobIds.major])(),trafficDelayColors=(e={})=>({minor:e[incidentColorKnobIds.minor]??"#FFC105",moderate:e[incidentColorKnobIds.moderate]??"#FB2D09",major:e[incidentColorKnobIds.major]??"#AD0000"}),magnitudeOfDelayTextColor=/* @__PURE__ */matchMagnitudeOfDelay({minor:"#f58240",moderate:"#FB2D09",major:"#AD0000",indefinite:"#666666",fallback:"#000000"}),routeIncidentsDashedLine={type:"line",filter:severityDashedFilter,layout:{"line-join":"round"},paint:{"line-color":severityLineDashColor,"line-dasharray":[1.5,1]}},routeIncidentsSymbol=(e,t,i={})=>({filter:["all",["has",e],SELECTED_ROUTE_FILTER],type:"symbol",minzoom:6,layout:{"symbol-placement":"point","symbol-avoid-edges":!0,"icon-ignore-placement":!0,"icon-image":["get",e],...t},paint:i}),routeIncidentsJamSymbol=/* @__PURE__ */routeIncidentsSymbol("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},{"text-color":magnitudeOfDelayTextColor,"text-halo-color":"#FFFFFF","text-halo-width":1}),routeIncidentsCauseSymbol=/* @__PURE__ */routeIncidentsSymbol("causeIconID",{"icon-anchor":"bottom-right"}),routeTunnelsLine=/* @__PURE__ */selectedRouteLine({"line-color":"#000000","line-opacity":.3}),routeVehicleRestrictedBackgroundLine=/* @__PURE__ */selectedRouteLine({"line-color":"#105287"}),routeVehicleRestrictedForegroundLine=/* @__PURE__ */selectedRouteLine({"line-color":"#36A8F0"},{"line-cap":"round"}),stopDurationLabelSection=[["coalesce",["get","stopDuration"],""],{"text-color":"#727C85","text-font":["literal",["Noto-Regular"]]}],hasStopDuration=["has","stopDuration"],waypointLabelTextField=/* @__PURE__ */(()=>["format",["coalesce",["get",TITLE],""],{},["case",["all",["has",TITLE],hasStopDuration],"\n",""],{},...stopDurationLabelSection])(),waypointSymbols=e=>{const t=clampFactor(e.waypoints?.highlight?.sizeFactor,ROUTE_WAYPOINT_HIGHLIGHT_SIZE_FACTOR_RANGE,1.2),i=buildIconOffsetExpression(buildCustomIconOffsets(e.waypoints?.icon?.customIcons));return{type:"symbol",paint:{...pinIconBasePaint,"text-color":"#ffffff","text-translate":PIN_TRANSLATE,"text-translate-anchor":"viewport"},layout:{...pinIconBaseLayout,"icon-size":scaledWhen(hasActiveEventState,(s=e.waypoints?.sizePreset,o=e.waypoints?.sizeFactor,scaleRamp(PIN_ICON_SIZE,waypointScale(s,o))),t),...i&&{"icon-offset":i},"text-field":["get","stopDisplayLabel"],"text-font":["Noto-Bold"],"text-size":scaledWhen(hasActiveEventState,getWaypointIndexTextSize(e.waypoints?.sizePreset,e.waypoints?.sizeFactor),t),"text-offset":STOP_MARK_TEXT_OFFSET,"text-allow-overlap":!0,"symbol-sort-key":["abs",["-",["get","index"],1e3]]}};var s,o},waypointLabels=(e,t,i)=>{const{textColor:s,haloColor:o}=themeAdaptiveLabelColors(e),r=labelTypefaceOf(t,i);return{type:"symbol",paint:{...pinTextBasePaint,"text-color":s,"text-halo-width":1.5,"text-halo-color":o,...labelPaintProperties(t)},layout:{...pinTextBaseLayout,"text-font":inTypeface(pinTextBaseLayout?.["text-font"],r),"text-field":!1===t?.visible?"":titleTextField(t?.title,inTypeface(waypointLabelTextField,r)),...labelLayoutProperties(t)}}},prefixBeforeID=(e,t)=>e&&t?e.startsWith(`${t}-`)||e.startsWith("routes-")?e:e.startsWith("route")||e.startsWith("waypoint")?prefixLayerID(e,t):e:e,prefixLayerBeforeID=(e,t)=>e.beforeID?{...e,beforeID:prefixBeforeID(e.beforeID,t)}:e,prefixBeforeIDs=(e,t)=>e&&t?Object.fromEntries(Object.entries(e).map(([i,s])=>[i,s.beforeID&&Object.hasOwn(e,s.beforeID)?{...s,beforeID:prefixLayerID(s.beforeID,t)}:prefixLayerBeforeID(s,t)])):e,buildRoutingLayers=(e={},t,i,s="light",o=trafficDelayColors(),r,a)=>{const n=(t,i)=>partBeforeLayerIDOf(e.beforeLayerConfig,t,i),l=n("mainLines",mapStyleLayerIDs.lowestLabel),c=n("instructionLines",mapStyleLayerIDs.lowestLabel),d=n("icons",void 0),u=(e,i)=>mergeLayer(e,i&&prefixLayerBeforeID(i,t)),h=e.layers,p=h?.sections,y=e.color,f=y?darkerShadeOf(y):void 0,m={widthPreset:e.widthPreset,widthFactor:e.widthFactor},g=clampFactor(e.highlight?.outline?.widthFactor,ROUTE_HIGHLIGHT_OUTLINE_WIDTH_FACTOR_RANGE,1.2),b=e.highlight?.section?.outline,S=b?.color??themeContrastColor(s),L=e.sections,I=e.opacity,E=e=>void 0===I?e:{...e,paint:{...e.paint,"line-opacity":I}},_=u({...withMapTypeface(waypointSymbols(e),r),beforeID:prefixBeforeID("routeSummaryBubbleSymbol",t)},h?.waypoints?.routeWaypointSymbol),v=(e=>{const t="string"==typeof e?e:"center",i=e=>"center"===t||e?10:2;return[i(t.startsWith("bottom")),i(t.endsWith("left")),i(t.startsWith("top")),i(t.endsWith("right"))]})(_.layout?.["icon-anchor"]),T=e=>({...e,layout:{...e.layout,"icon-padding":v}}),C=(e,i,s)=>({...withSectionLineKnobs(e,i,L?.[e],m,s?.role),beforeID:prefixBeforeID(s?.beforeID??sectionStyleAnchor(e,L?.[e]),t)}),w=(e,i,s)=>({...withSectionSymbolKnobs(e,T(withMapTypeface(i,r)),L?.[e]),beforeID:prefixBeforeID(s,t)}),O=Object.fromEntries(generatedSectionTypes.map(e=>{const i=L?.[e],o=sectionLineLayerID(e),a=(e=>sectionLayerID(e,"Symbol"))(e),n=p?.[e];if(postsSign(e)){const s=sectionSignLayerID(e);return[e,{[s]:u(T(withMapTypeface(sectionSign(e,i),r)),n?.[s]),...prefixBeforeIDs(n?.additional,t)}]}const l=i&&((e,t)=>{if(t.icon?.image&&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),c=((e,t,i,s="light")=>isKerbStriped(e,t)?withSectionLineKnobs(e,{filter:["all",SELECTED_ROUTE_FILTER,["<=",["get","radiusInMeters"],60]],type:"line",minzoom:12,layout:{"line-cap":"butt","line-join":"round"},paint:{"line-color":t?.kerb?.color??kerbDefaultColor(t?.color??GENERATED_SECTION_PAINT[e].color,s),"line-opacity":GENERATED_SECTION_PAINT[e].opacity,"line-dasharray":KERB_DASH_ARRAY}},t,i,"kerb"):void 0)(e,i,m,s),d=(e=>sectionLayerID(e,"Kerb"))(e),h=((e,t)=>{const i=sectionEntry(e).drawsUnder,s=sectionDrawStyle(e,t?.[e]);return i&&s===sectionDrawStyle(i,t?.[i])?sectionLineLayerID(i):sectionStyleAnchor(e,t?.[e])})(e,L);return[e,{[o]:u({...sectionLine(e,i,m,s),beforeID:prefixBeforeID(c?d:h,t)},n?.[o]),...c&&{[d]:u({...c,beforeID:prefixBeforeID(h,t)},n?.[d])},...l&&{[a]:u({...l,beforeID:prefixBeforeID("routeTunnelSymbol",t)},n?.[a])},...prefixBeforeIDs(n?.additional,t)}]}));return{mainLines:{routeLineArrows:u({...routeLineArrows,beforeID:l},h?.mainLines?.routeLineArrows),routeLine:u({...E(routeMainLine(m,y)),beforeID:prefixBeforeID("halo"===sectionDrawStyle("traffic",L?.traffic)?"routeLineArrows":"routeIncidentBackgroundLine",t)},h?.mainLines?.routeLine),routeOutline:u({...E(routeOutline(m,f,g)),beforeID:prefixBeforeID("routeLine",t)},h?.mainLines?.routeOutline),routeDeselectedLine:u({...E((R=m,routeLine(DESELECTED_ROUTE_FILTER,"#ABAFB3",getLineForegroundWidth(R)))),beforeID:prefixBeforeID("routeOutline",t)},h?.mainLines?.routeDeselectedLine),routeDeselectedOutline:u({...E(routeDeselectedOutline(m,g)),beforeID:prefixBeforeID("routeDeselectedLine",t)},h?.mainLines?.routeDeselectedOutline),...prefixBeforeIDs(h?.mainLines?.additional,t)},waypoints:{routeWaypointSymbol:_,routeWaypointLabel:u({...waypointLabels(s,e.waypoints?.label,r),beforeID:prefixBeforeID("routeWaypointSymbol",t)},h?.waypoints?.routeWaypointLabel),...prefixBeforeIDs(h?.waypoints?.additional,t)},sections:{...O,traffic:{routeIncidentJamSymbol:u(w("traffic",routeIncidentsJamSymbol,"routeCountryCrossing"),p?.traffic?.routeIncidentJamSymbol),routeIncidentCauseSymbol:u(w("traffic",routeIncidentsCauseSymbol,"routeCountryCrossing"),p?.traffic?.routeIncidentCauseSymbol),routeIncidentBackgroundLine:u(C("traffic",(A=o,{type:"line",layout:{"line-cap":"round"},paint:{"line-color":/* @__PURE__ */matchMagnitudeOfDelay({...A,fallback:"#C7D2D8"})}}),{beforeID:"routeIncidentDashedLine"}),p?.traffic?.routeIncidentBackgroundLine),routeIncidentDashedLine:u(C("traffic",routeIncidentsDashedLine),p?.traffic?.routeIncidentDashedLine),...prefixBeforeIDs(p?.traffic?.additional,t)},ferry:{routeFerryLine:u(C("ferry",routeFerriesLine),p?.ferry?.routeFerryLine),routeFerrySymbol:u(w("ferry",routeFerriesSymbol,"routeIncidentJamSymbol"),p?.ferry?.routeFerrySymbol),...prefixBeforeIDs(p?.ferry?.additional,t)},tollRoad:{routeTollRoadOutline:u(C("tollRoad",routeTollRoadsOutline),p?.tollRoad?.routeTollRoadOutline),routeTollRoadSymbol:u(w("tollRoad",routeTollRoadsSymbol,"routeCountryCrossing"),p?.tollRoad?.routeTollRoadSymbol),...prefixBeforeIDs(p?.tollRoad?.additional,t)},tunnel:{routeTunnelLine:u(C("tunnel",routeTunnelsLine),p?.tunnel?.routeTunnelLine),routeTunnelSymbol:u(w("tunnel",sectionStartSign("tunnel",i),"routeFerrySymbol"),p?.tunnel?.routeTunnelSymbol),...prefixBeforeIDs(p?.tunnel?.additional,t)},vehicleRestricted:{routeVehicleRestrictedBackgroundLine:u(C("vehicleRestricted",routeVehicleRestrictedBackgroundLine,{beforeID:"routeVehicleRestrictedForegroundLine",role:"outline"}),p?.vehicleRestricted?.routeVehicleRestrictedBackgroundLine),routeVehicleRestrictedForegroundLine:u(C("vehicleRestricted",routeVehicleRestrictedForegroundLine),p?.vehicleRestricted?.routeVehicleRestrictedForegroundLine),routeVehicleRestrictedSymbol:u(w("vehicleRestricted",sectionStartSign("vehicleRestricted",i),"routeIncidentJamSymbol"),p?.vehicleRestricted?.routeVehicleRestrictedSymbol),...prefixBeforeIDs(p?.vehicleRestricted?.additional,t)}},instructionLines:{routeInstructionLine:u({...instructionLine(m),beforeID:c},h?.instructionLines?.routeInstructionLine),routeInstructionOutline:u({...instructionOutline(m),beforeID:prefixBeforeID("routeInstructionLine",t)},h?.instructionLines?.routeInstructionOutline),...prefixBeforeIDs(h?.instructionLines?.additional,t)},instructionArrows:{routeInstructionArrowSymbol:u({...instructionArrow(m,i),beforeID:prefixBeforeID("routeInstructionLine",t)},h?.instructionArrows?.routeInstructionArrowSymbol),...prefixBeforeIDs(h?.instructionArrows?.additional,t)},summaryBubbles:{routeSummaryBubbleSymbol:u({...summaryBubbleSymbol(i,e.summaryBubbles,resolveSummaryBubbleColors(e.summaryBubbles,s,a),r),...d&&{beforeID:d}},h?.summaryBubbles?.routeSummaryBubbleSymbol),...prefixBeforeIDs(h?.summaryBubbles?.additional,t)},countryCrossings:{[COUNTRY_CROSSING_LAYER_ID]:u({...withMapTypeface(countryCrossingSymbol(i,e.countryCrossings,resolveCountryCrossingColors(e.countryCrossings,s,a)),r),beforeID:prefixBeforeID("routeWaypointLabel",t)},h?.countryCrossings?.routeCountryCrossing),...prefixBeforeIDs(h?.countryCrossings?.additional,t)},sectionFocus:{routeSectionFocusOutline:u({...routeSectionFocusOutline(SELECTED_ROUTE_FILTER,getSectionFocusGapWidth(m,g,drawnSectionLineWidths(L,m)),S,b?.widthFactor),beforeID:prefixBeforeID("routeOutline",t)},h?.sectionFocus?.routeSectionFocusOutline),routeDeselectedSectionFocusOutline:u({...routeSectionFocusOutline(DESELECTED_ROUTE_FILTER,getSectionFocusGapWidth(m,g),S,b?.widthFactor),beforeID:prefixBeforeID("routeDeselectedOutline",t)},h?.sectionFocus?.routeDeselectedSectionFocusOutline),...prefixBeforeIDs(h?.sectionFocus?.additional,t)}};var A,R},defaultRoutingLayers=/* @__PURE__ */buildRoutingLayers(),toCrossingFeature=(e,t,i,s,o)=>{const r=generateId();return{type:"Feature",id:r,geometry:toPointGeometry(i[t.startPointIndex]),properties:{id:r,fromCountryCode:e.countryCodeISO2,toCountryCode:t.countryCodeISO2,label:`${e.countryCodeISO2} → ${t.countryCodeISO2}`,fromSectionStartPointIndex:e.startPointIndex,toSectionStartPointIndex:t.startPointIndex,routeState:s.routeState,routeIndex:o}}},wholeMinutesOf=e=>Math.round(e/60),formatDurationOfAMinuteOrMore=(e,t)=>void 0!==e&&wholeMinutesOf(Math.abs(e))?formatDuration(e,t):void 0,hasJam=e=>e.categories.includes("jam"),buildWaypointTitle=e=>{const t=e?.properties;return t?.poi?.name??t?.address?.freeformAddress??void 0},WAYPOINT_IMAGE_IDS={start:"waypointStart",middle:"waypointStop",finish:"waypointFinish"},getImageIDForWaypoint=(e,t)=>instanceImageID(WAYPOINT_IMAGE_IDS[e],t),asWaypoint=e=>{return Array.isArray(e)?{type:"Feature",geometry:toPointGeometry(e),properties:{}}:"Point"===e.type?{type:"Feature",geometry:t=e,properties:{},...t.bbox&&{bbox:t.bbox}}:{...e,properties:e.properties??{}};var t},waypointFeatureSettings=e=>[e?.entryPoints,"function"==typeof e?.label?.title?e.label.title:void 0,e?.icon?.mapping,!!e?.icon?.middle?.image?.image,e?.stopNumbering],toDisplayWaypoints=(e,t,i,s)=>({type:"FeatureCollection",features:e.flatMap((o,r)=>{if(!o)return[];const a=asWaypoint(o),n=((e,t)=>0===e?START_INDEX:e<t-1?MIDDLE_INDEX:FINISH_INDEX)(r,e.length),l=a.id??generateId(),c=formatDurationOfAMinuteOrMore(a.properties.pauseDurationSeconds,s),{stopDisplayIndex:d,stopDisplayLabel:u,stopDuration:h,...p}=a.properties,y={...a,..."main-when-available"===t?.entryPoints&&{geometry:toPointGeometry(getPosition(a,{useEntryPoint:"main-when-available"})??a.geometry.coordinates)},id:l,properties:{...p,id:l,index:r,indexType:n,...c&&{stopDuration:c},iconID:getImageIDForWaypoint(n,i),..."middle"===n&&{stopDisplayIndex:r}}},f=featureTitle(y,t?.label?.title,buildWaypointTitle);f&&(y.properties.title=f);const m=((e,t)=>{if("imageID"===t?.to)return t.fn(e);if("poiCategory"!==t?.to)return;const i=t.fn(e);return i&&toPinImageID(poiCategoriesToID[i])})(y,t?.icon?.mapping);if(m)y.properties.iconID=m;else if("middle"===n&&!t?.icon?.middle?.image?.image){const e=((e,t="numbers")=>{if("none"!==t)return"letters"===t?(e=>{let t="";for(let i=e;i>0;i=Math.floor((i-1)/26))t=String.fromCodePoint(65+(i-1)%26)+t;return t})(e):String(e)})(r,t?.stopNumbering);e&&(y.properties.stopDisplayLabel=e)}return[y]})}),drawableInstructions=e=>e.features.flatMap((e,t)=>e.properties.guidance?.instructions?.filter(e=>(e.routePath?.length??0)>1).map(i=>({instruction:i,routeIndex:t,routeState:e.properties.routeState}))||[]),toRouteSection=(e,t,i,s)=>{const o=i.id??generateId();return{type:"Feature",id:o,geometry:{type:"LineString",coordinates:e.geometry.coordinates.slice(i.startPointIndex,i.endPointIndex+1)},properties:{...s?s(i,e.properties):i,routeState:e.properties.routeState,routeIndex:t,id:o}}},toDisplayRouteSections=(e,t,i)=>({type:"FeatureCollection",features:e.features.flatMap((e,s)=>(e.properties.sections[t]??[]).map(t=>toRouteSection(e,s,t,i)))}),routeStateOf=(e,t)=>e.features[t.properties.routeIndex||0].properties.routeState,showFeaturesWithRouteSelection=(e,t)=>{const{shownFeatures:i}=t;i.features.every(t=>t.properties.routeState===routeStateOf(e,t))||t.show(((e,t)=>({...t,features:t.features.map(t=>({...t,properties:{...t.properties,routeState:routeStateOf(e,t)}}))}))(e,i),{automaticVisibility:!1})},toDisplayRoutes=(e,t=0)=>{const i="features"in e?e:{type:"FeatureCollection",features:[e]};return{...i,features:i.features.map((e,i)=>{const s=e.id??generateId();return{...e,id:s,properties:{...e.properties,id:s,routeState:i===t?"selected":"deselected"}}})}},BUBBLE_FRACTIONS=[.5,.25,.75],toDisplayRouteSummaries=(e,t,i,s)=>{const o=e.features.filter(e=>e.geometry.coordinates.length),r=o.find(e=>"selected"===e.properties.routeState),a=(s&&((e,t)=>{const i=new Map(t.features.map(({id:e,geometry:t})=>[e,t.coordinates])),s=e.map(e=>void 0===e.id?void 0:i.get(e.id));return s.every(e=>void 0!==e)?s:void 0})(o,s))??(e=>{const t=(e=>{if(e.length<2)return e.map(()=>[]);const t=e.map(e=>e.properties.sections.distinct);return t.every(e=>void 0!==e)?t:getDistinctSections(e)})(e),i=[];return e.map(({geometry:{coordinates:e}},s)=>{const o=metersAlongLine(e),r=t[s].reduce((e,t)=>{const i=t.lengthInMeters;return null==i||Number.isNaN(i)?e:!e||i>e.lengthInMeters?t:e},void 0),a=r&&r.lengthInMeters>.05*(o.at(-1)??0)?r:{startPointIndex:0,endPointIndex:e.length-1},n=o[a.startPointIndex],l=o[a.endPointIndex]-n,c=e=>Math.min(...i.map(t=>distance(e,t))),[d,...u]=BUBBLE_FRACTIONS.map(t=>((e,t,{startPointIndex:i,endPointIndex:s},o)=>{if(s<=i)return e[i];const{pathIndex:r,share:a}=segmentAtMeters(t,o,i,s);return positionBetween(e[r],e[r+1],a)})(e,o,a,n+l*t)),h=u.reduce((e,t)=>c(t)>c(e)?t:e,d);return i.push(h),h})})(o);return{type:"FeatureCollection",features:o.map((s,o)=>{const n=s.properties.summary,l=formatDurationOfAMinuteOrMore(n.trafficDelayInSeconds,t?.time),c=((e,t,i)=>{if(!t||"selected"===e.properties.routeState)return;const s=wholeMinutesOf(e.properties.summary.travelTimeInSeconds)-wholeMinutesOf(t.properties.summary.travelTimeInSeconds),o=formatDurationOfAMinuteOrMore(60*Math.abs(s),i?.time);return o&&`${s>0?"+":"-"}${o}`})(s,r,t),d=(e=>{const t=e.properties.sections.traffic??[];return["major","moderate","minor"].find(e=>t.some(t=>t.magnitudeOfDelay===e))})(s),u=s.id??generateId(),h={type:"Feature",id:u,geometry:toPointGeometry(a[o]),properties:{id:u,routeIndex:e.features.indexOf(s),routeState:s.properties.routeState,formattedDistance:formatDistance(n.lengthInMeters,t?.distance),...d&&{magnitudeOfDelay:d},...l&&{formattedTraffic:l},...c&&{formattedDurationDifference:c},formattedDuration:formatDuration(n.travelTimeInSeconds,t?.time)}},p=featureTitle(h,i,()=>{});return p&&(h.properties.title=p),h})}},MPH_DISC={unit:"mph"},US_PLAQUE={face:"plaque",unit:"mph"},SIGN_BY_COUNTRY={GBR:MPH_DISC,JEY:MPH_DISC,GGY:MPH_DISC,IMN:MPH_DISC,AIA:MPH_DISC,CYM:MPH_DISC,FLK:MPH_DISC,MSR:MPH_DISC,SHN:MPH_DISC,TCA:MPH_DISC,VGB:MPH_DISC,ATG:MPH_DISC,BHS:MPH_DISC,BLZ:MPH_DISC,DMA:MPH_DISC,GRD:MPH_DISC,KNA:MPH_DISC,LCA:MPH_DISC,VCT:MPH_DISC,WSM:MPH_DISC,LBR:MPH_DISC,MMR:MPH_DISC,USA:US_PLAQUE,PRI:US_PLAQUE,GUM:US_PLAQUE,VIR:US_PLAQUE,ASM:US_PLAQUE,MNP:US_PLAQUE,SWE:{face:"yellowDisc"},FIN:{face:"yellowDisc"},ISL:{face:"yellowDisc"},JPN:{numerals:"#0B5FA5"}},SIGN_BY_DISPLAY_UNITS={metric:{},imperial_uk:MPH_DISC,imperial_us:US_PLAQUE},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,featureIdOf=e=>e.id,manualVisibility={automaticVisibility:!1},showOrClearCountryCrossings=(e,t,i)=>{!1!==i?.countryCrossings?.visible?e.showUnlessStillEmpty((e=>({type:"FeatureCollection",features:e.features.flatMap((e,t)=>((e,t)=>{const i=e.properties.sections.country;if(!i?.length)return[];const s=[...i].sort((e,t)=>e.startPointIndex-t.startPointIndex),o=e.geometry.coordinates;return s.slice(1).flatMap((i,r)=>o[i.startPointIndex]?[toCrossingFeature(s[r],i,o,e.properties,t)]:[])})(e,t))}))(t),manualVisibility):e.clearUnlessEmpty()},RoutingModule=class RoutingModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new RoutingModule(e,t)}constructor(e,t){super(e,t),this.shownFeaturesHandlers=[],onAccentColorChange(e,()=>{void 0===this.config?.color&&(this.config=this._applyConfig(this.config))}),onStyleKnobsApplied(e,trafficDelayColorKnobIds,()=>this.repaintTrafficSections()),onStyleKnobsApplied(e,summaryBubbleColorKnobIds,()=>{this.config=this._applyConfig(this.config)}),onMapTypefaceChange(e,()=>{this.config=this._applyConfig(this.config)})}repaintTrafficSections(){const{incidents:e}=this.buildLayersSpecs(this.config);isEqual(e,this.layersSpecs.incidents)||(this.replaceSourceLayers(e,this.layersSpecs.incidents,this.sourcesWithLayers.incidents),this.layersSpecs={...this.layersSpecs,incidents:e})}routeColorOf(e){return e?.color??mapAccentColor(this.tomtomMap)}buildLayersSpecs(e){return((e={},t)=>({...Object.fromEntries(drawnSectionTypes.map(i=>[sectionSourceKey(i),mapLayerSpecs(e.sections?.[i],t)])),mainLines:mapLayerSpecs(e.mainLines,t),waypoints:mapLayerSpecs(e.waypoints,t),instructionLines:mapLayerSpecs(e.instructionLines,t),instructionArrows:mapLayerSpecs(e.instructionArrows,t),summaryBubbles:mapLayerSpecs(e.summaryBubbles,t),countryCrossings:mapLayerSpecs(e.countryCrossings,t),sectionFocus:mapLayerSpecs(e.sectionFocus,t)}))(buildRoutingLayers({...e,color:this.routeColorOf(e)},this.layerIDPrefix,this.instanceIndex,this.tomtomMap.styleLightDarkTheme,trafficDelayColors(this.tomtomMap._styleKnobSettings),mapTypefaceOf(this.tomtomMap),summaryBubbleMapColors(this.tomtomMap._styleKnobSettings)),this.layerIDPrefix)}createSourcesWithLayers(e){const t=t=>new GeoJSONSourceWithLayers(this.mapLibreMap,`${this.layerIDPrefix}-${t}`,e[t],!1);return{...Object.fromEntries(generatedSectionTypes.map(e=>{const i=sectionSourceKey(e);return[i,t(i)]})),mainLines:t("mainLines"),waypoints:t("waypoints"),incidents:t("incidents"),ferries:t("ferries"),tollRoads:t("tollRoads"),tunnels:t("tunnels"),vehicleRestricted:t("vehicleRestricted"),instructionLines:t("instructionLines"),instructionArrows:t("instructionArrows"),summaryBubbles:t("summaryBubbles"),countryCrossings:t("countryCrossings"),sectionFocus:t("sectionFocus")}}_initSourcesWithLayers(e,t){t||(this.layerIDPrefix=suffixNumber("routes",this.instanceIndex)),this.layersSpecs=this.buildLayersSpecs(e);const i=this.createSourcesWithLayers(this.layersSpecs);addLayers(Object.values(i).flatMap(e=>e._layerSpecs),this.mapLibreMap);const s={pixelRatio:2},o=instanceImageID("instruction-arrow",this.instanceIndex),r=instanceImageID("traffic-moderate",this.instanceIndex),a=instanceImageID("traffic-minor",this.instanceIndex);this.addImageIfNotExisting(o,staticImg('<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50"><path d="M1.562 40.569L25 1.562l23.438 39.007L25 27.566 1.562 40.569z" fill="#fff"/><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" fill="gray"/></svg>\n'),s);for(const[n,l]of Object.entries(SPEED_LIMIT_IMAGE_ID_BY_FACE))this.addImageIfNotExisting(instanceImageID(l,this.instanceIndex),speedLimitSignImg(n),s);for(const[n,l]of Object.entries(SECTION_START_SIGN_IMAGE_IDS))this.addImageIfNotExisting(instanceImageID(l,this.instanceIndex),sectionStartSignImg(n),s);return this.appliedCrossingFill=void 0,this.appliedSummaryBubbleColors=void 0,this.addImageIfNotExisting(r,trafficImg("#FB2D09"),s),this.addImageIfNotExisting(a,trafficImg("#f58240"),s),i}_applyConfig(e){const t=routeDisplayUnits(e),i=!isEqual(this.appliedDisplayUnits,t);if(this.appliedDisplayUnits=t,this.addConfiguredImages(e),this.applySummaryBubbleColors(e),declareFontFaces(this.tomtomMap,this,customFacesOf([e?.waypoints?.label,e?.summaryBubbles?.label])),!this._initializing){const t=this.buildLayersSpecs(e);Object.keys(t).forEach(e=>{const i=e;isEqual(t[i],this.layersSpecs[i])||this.replaceSourceLayers(t[i],this.layersSpecs[i],this.sourcesWithLayers[i])});const s=Object.values(this.sourcesWithLayers),o=e=>Object.values(e).flatMap(e=>e.map(e=>e.beforeID));addLayers(s.flatMap(e=>e._layerSpecs),this.mapLibreMap,!isEqual(o(this.layersSpecs),o(t))),this.reshowSpeedLimitSigns(e,i);const{incidents:r,mainLines:a}=this.sourcesWithLayers;i&&r.shownFeatures.features.length&&this.reshowKeepingEventStates(r,this.trafficSectionsOf(a.shownFeatures,e)),this.applySignPriority(e),this.layersSpecs=t}return this.reshowWaypoints(e,i),this.reshowSummaryBubbles(e,i),this.applyCountryCrossingConfig(e),this.applyVisibility(e),e}addConfiguredImages(e){const t=e?.waypoints?.icon,i={fillColor:this.routeColorOf(e),...t?.style},s=e=>paintPin(this.mapLibreMap,getImageIDForWaypoint(e,this.instanceIndex),t?.[e],i,t=>((e,t)=>svgToImg(()=>{const i=pinSvg(t),s=waypointGlyphs[e];return s&&i.appendChild(parseSvg(s)),i}))(e,t),this.paintedWaypointPins?.[e]);this.paintedWaypointPins={start:s(START_INDEX),middle:s(MIDDLE_INDEX),finish:s(FINISH_INDEX)},((e,t)=>{for(const[i,{image:s,pixelRatio:o}]of Object.entries(customImagesByID(t)))addOrUpdateImage("if-not-in-sprite",i,s,e,{pixelRatio:o})})(this.mapLibreMap,t?.customIcons)}reshowWaypoints(e,t){if(!this.shownWaypoints||this._initializing)return;const i=!isEqual(waypointFeatureSettings(this.config?.waypoints),waypointFeatureSettings(e?.waypoints));(t||i)&&this.reshowKeepingEventStates(this.sourcesWithLayers.waypoints,this.displayWaypointsOf(this.shownWaypoints,e))}displayWaypointsOf(e,t){return toDisplayWaypoints(e,t?.waypoints,this.instanceIndex,routeDisplayUnits(t).time)}speedLimitSectionsOf(e,t){return toDisplayRouteSections(e,"speedLimit",(i=this.instanceIndex,s={unit:t?.sections?.speedLimit?.sign?.unit,displayUnits:routeDisplayUnits(t)},(e,t)=>{const o=(r=e.startPointIndex,a=t?.sections.country,a?.find(e=>r>=e.startPointIndex&&r<e.endPointIndex)?.countryCodeISO3);var r,a;const n=o?SIGN_BY_COUNTRY[o]??{}:SIGN_BY_DISPLAY_UNITS[s?.displayUnits?.distance?.type??"metric"],l=n.face??"whiteDisc",c=s?.unit??n.unit??"km/h";return{...e,signImageID:instanceImageID(SPEED_LIMIT_IMAGE_ID_BY_FACE[l],i),signLabel:String(postedSpeedLimit(e.maxSpeedLimitInKmh,c)),signFace:l,signNumeralsColor:n.numerals??"#1A2024"}}));var i,s}trafficSectionsOf(e,t){return toDisplayRouteSections(e,"traffic",(i=routeDisplayUnits(t).time,e=>{const t=((e,t)=>hasJam(e)?formatDurationOfAMinuteOrMore(e.delayInSeconds,t):void 0)(e,i),s=((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),o=(e=>e.categories.filter(e=>"jam"!==e).map(incidentIconID).find(e=>null!==e)??null)(e);return{...e,...s&&{jamIconID:s},...o&&{causeIconID:o},...t&&{title:t}}}));var i}displaySummariesOf(e,t,i){const{summaryBubbles:s}=this.sourcesWithLayers,o=toDisplayRouteSummaries(e,routeDisplayUnits(t),t?.summaryBubbles?.label?.title,i?s.shownFeatures:void 0);return i?withShownEventStates(s.shownFeatures,o,featureIdOf):o}reshowSummaryBubbles(e,t){const i=this.sourcesWithLayers.summaryBubbles,s=!1!==e?.summaryBubbles?.visible,o=s!==(!1!==this.config?.summaryBubbles?.visible);if(!s)return void(o&&i.clear());const r=this.config?.summaryBubbles?.label?.title!==e?.summaryBubbles?.label?.title,a=this.sourcesWithLayers.mainLines.shownFeatures.features.length>0,n=i.shownFeatures.features.length>0;(o&&a||(t||r)&&n)&&i.show(this.displaySummariesOf(this.sourcesWithLayers.mainLines.shownFeatures,e,!0),manualVisibility)}applySummaryBubbleColors(e){const t=resolveSummaryBubbleColors(e?.summaryBubbles,this.tomtomMap.styleLightDarkTheme,summaryBubbleMapColors(this.tomtomMap._styleKnobSettings)),i=this.appliedSummaryBubbleColors;this.appliedSummaryBubbleColors=t;const s=(e,s,o,r)=>{i?.[s]!==t[s]&&this.paintImage(e,o(t[s]),r)};s("selected-route-summary-popup","selectedFill",summaryMapBubbleImg,summaryBubbleImageOptions),s("deselected-route-summary-popup","deselectedFill",summaryMapBubbleImg,summaryBubbleImageOptions),s("traffic-major","majorDelay",trafficImg,{pixelRatio:2}),s("traffic-clear","unknownDelay",trafficImg,{pixelRatio:2})}applyCountryCrossingConfig(e){if(!1!==e?.countryCrossings?.visible!=(!1!==this.config?.countryCrossings?.visible)){const{countryCrossings:t,mainLines:i}=this.sourcesWithLayers;showOrClearCountryCrossings(t,i.shownFeatures,e)}const{selectedFill:t}=resolveCountryCrossingColors(e?.countryCrossings,this.tomtomMap.styleLightDarkTheme,summaryBubbleMapColors(this.tomtomMap._styleKnobSettings));this.appliedCrossingFill!==t&&(this.appliedCrossingFill=t,this.paintImage("route-country-crossing-bubble",summaryMapBubbleImg(t),summaryBubbleImageOptions))}reshowSpeedLimitSigns(e,t){if(isEqual(this.config?.sections?.speedLimit?.sign?.unit,e?.sections?.speedLimit?.sign?.unit)&&!t)return;const{speedLimitSections:i,mainLines:s}=this.sourcesWithLayers;i.shownFeatures.features.length&&this.reshowKeepingEventStates(i,this.speedLimitSectionsOf(s.shownFeatures,e))}applyVisibility(e){this.applySourcesVisibility(e,Object.keys(this.sourcesWithLayers))}applySourcesVisibility(e,t){const i=!1!==e?.visible,s=new Set(drawnSectionTypes.filter(t=>!isSectionVisible(t,e?.sections?.[t])).map(e=>sectionSourceKey(e)));for(const o of t){const e=this.sourcesWithLayers[o];e.setLayersVisible(i&&!s.has(o)&&!!e.shownFeatures.features.length)}}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 s=e?.sections?.[t];moveLayerBefore(this.mapLibreMap,i,this.signAnchorLayerID(i,s))}}signAnchorLayerID(e,t){const i=(e=>e?.sign?.priority??("atChange"===signPlacement(e)?"belowRouteIcons":"belowMapLabels"))(t);if("aboveRouteIcons"===i)return;if("belowMapLabels"===i)return mapStyleLayerIDs.lowestLabel;const s=new Set(["routeLineArrows","routeInstructionArrowSymbol"].map(e=>prefixLayerID(e,this.layerIDPrefix)));return this.mapLibreMap.getLayersOrder().find(t=>t!==e&&!s.has(t)&&t.startsWith(`${this.layerIDPrefix}-`)&&"symbol"===this.mapLibreMap.getLayer(t)?.type)}discardShownData(){this.shownWaypoints=void 0}restoreDataAndConfigImpl(){const e=shownFeaturesOf(this.sourcesWithLayers),t=this.appliedDisplayUnits;this.initSourcesWithLayers(this.config,!0),this._applyConfig(this.config);for(const i of Object.keys(e))this.sourcesWithLayers[i].showUnlessStillEmpty(e[i],manualVisibility);this.appliedDisplayUnits=t,this.applyVisibility(this.config)}addImageIfNotExisting(e,t,i){addOrUpdateImage("if-not-in-sprite",e,t,this.mapLibreMap,i)}paintImage(e,t,i){const s=instanceImageID(e,this.instanceIndex);addOrUpdateImage("add-or-update",s,t,this.mapLibreMap,i,latestImageLoad(this.mapLibreMap,s))}reshowKeepingEventStates(e,t){e.show(withShownEventStates(e.shownFeatures,t,featureIdOf),manualVisibility)}async showRoutes(e,t){const i=toDisplayRoutes(e,t?.selectedIndex);await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.show(i,manualVisibility),this.sourcesWithLayers.incidents.showUnlessStillEmpty(this.trafficSectionsOf(i,this.config),manualVisibility);const s=[...bespokeSectionTypes.filter(e=>"traffic"!==e),...bandedSectionTypes];for(const o of s)this.sourcesWithLayers[sectionSourceKey(o)].showUnlessStillEmpty(toDisplayRouteSections(i,o),manualVisibility);this.sourcesWithLayers.speedLimitSections.showUnlessStillEmpty(this.speedLimitSectionsOf(i,this.config),manualVisibility),this.applySignPriority(this.config),this.sourcesWithLayers.instructionLines.showUnlessStillEmpty((e=>({type:"FeatureCollection",features:drawableInstructions(e).map(({instruction:e,routeIndex:t,routeState:i})=>({type:"Feature",geometry:{type:"LineString",coordinates:e.routePath.map(e=>e.point)},properties:{...e,id:generateId(),routeIndex:t,routeState:i}}))}))(i),manualVisibility),this.sourcesWithLayers.instructionArrows.showUnlessStillEmpty((e=>({type:"FeatureCollection",features:drawableInstructions(e).map(({instruction:e,routeIndex:t,routeState:i})=>{const s=[e.routePath[e.routePath.length-2]?.point,e.routePath[e.routePath.length-1]?.point];return{type:"Feature",geometry:toPointGeometry(s[1]),properties:{...e,id:generateId(),routeIndex:t,routeState:i,lastPointBearingDegrees:bearing(s[0],s[1])}}})}))(i),manualVisibility),showOrClearCountryCrossings(this.sourcesWithLayers.countryCrossings,i,this.config),!1!==this.config?.summaryBubbles?.visible?this.sourcesWithLayers.summaryBubbles.show(this.displaySummariesOf(i,this.config,!1),manualVisibility):this.sourcesWithLayers.summaryBubbles.clearUnlessEmpty(),this.sourcesWithLayers.sectionFocus.clearUnlessEmpty(),this.applyVisibility(this.config),emitShownFeatures(this.shownFeaturesHandlers,{routes:e})}async setSectionFocus(e){await this.waitUntilModuleReady(),this.sourcesWithLayers.sectionFocus.show(((e,t)=>{if(!t.length)return{type:"FeatureCollection",features:[]};const i=new Set(t);return{type:"FeatureCollection",features:e.features.flatMap((e,t)=>Object.values(e.properties.sections).flat().filter(e=>void 0!==e&&i.has(e.id)&&void 0!==e.startPointIndex&&void 0!==e.endPointIndex).map(i=>toRouteSection(e,t,i)))}})(this.sourcesWithLayers.mainLines.shownFeatures,e??[]),manualVisibility),this.applySourcesVisibility(this.config,["sectionFocus"])}async clearRoutes(){await this.waitUntilModuleReady();for(const e of Object.keys(this.sourcesWithLayers))"waypoints"!==e&&this.sourcesWithLayers[e].clearUnlessEmpty()}async selectRoute(e){await this.waitUntilModuleReady(),this.sourcesWithLayers.mainLines.clearEventStates({states:["click"],show:!1}),this.sourcesWithLayers.summaryBubbles.clearEventStates({states:["click"],show:!1});const t=toDisplayRoutes(this.sourcesWithLayers.mainLines.shownFeatures,e);this.sourcesWithLayers.mainLines.show(t,manualVisibility);for(const i of drawnSectionTypes)showFeaturesWithRouteSelection(t,this.sourcesWithLayers[sectionSourceKey(i)]);showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionLines),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.instructionArrows),this.sourcesWithLayers.summaryBubbles.shownFeatures.features.length&&this.sourcesWithLayers.summaryBubbles.show(this.displaySummariesOf(t,this.config,!0),manualVisibility),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.countryCrossings),showFeaturesWithRouteSelection(t,this.sourcesWithLayers.sectionFocus),this.applyVisibility(this.config)}async showWaypoints(e){const t=(e=>e.map(e=>{if(!e)return e;const t=asWaypoint(e);return{...t,id:t.id??generateId()}}))(Array.isArray(e)?e:e.features);await this.waitUntilModuleReady(),this.shownWaypoints=t,this.sourcesWithLayers.waypoints.show(this.displayWaypointsOf(t,this.config),manualVisibility),this.applySourcesVisibility(this.config,["waypoints"]),emitShownFeatures(this.shownFeaturesHandlers,{waypoints:e})}async clearWaypoints(){await this.waitUntilModuleReady(),this.shownWaypoints=void 0,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,tollRoads:this.sourcesWithLayers.tollRoads.shownFeatures,...Object.fromEntries(generatedSectionTypes.map(e=>[sectionSourceKey(e),this.sourcesWithLayers[sectionSourceKey(e)].shownFeatures])),speedLimitSections:this.sourcesWithLayers.speedLimitSections.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,sectionFocus:this.sourcesWithLayers.sectionFocus.shownFeatures}}eventStateSources(){return["mainLines"]}get events(){const e=Object.fromEntries(bandedSectionTypes.map(e=>[sectionSourceKey(e),this.userEventsWithStates([sectionSourceKey(e)])]));return this.buildEvents(this.moduleEventsWithShown(["mainLines","waypoints","summaryBubbles","countryCrossings","incidents","vehicleRestricted","ferries","tollRoads","tunnels","instructionLines",...generatedSectionTypes.map(sectionSourceKey)],this.shownFeaturesHandlers),{...e,speedLimitSections:this.userEventsWithStates(["speedLimitSections"]),mainLines:this.userEventsWithStates(["mainLines"]),waypoints:this.userEventsWithStates(["waypoints"]),summaryBubbles:this.userEventsWithStates(["summaryBubbles"]),countryCrossings:this.userEventsWithStates(["countryCrossings"],{mapping:e=>((e,t)=>{const i=e.properties,s=t.features[i.routeIndex]?.properties.sections.country??[],o=e=>s.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 existingAnchorLayerID(this.mapLibreMap,this.layersSpecs.mainLines.find(t=>t.id===e)?.beforeID)}},hillshadeMethods=["standard","basic","igor","combined","multidirectional"],hillshadeLightAlignments=["viewport","map"],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]]}),roadLine=(e,t)=>({metadataGroups:["road"],layerTypes:["line"],idIncludes:e,...t&&{idExcludes:t}}),TEXT_LAYERS={metadataGroups:["places_label","road_label","label","address_point_label","border_label"],layerTypes:["symbol"],idExcludes:["shield","exit","water","river"]},WATER_TEXT_LAYERS={metadataGroups:["label"],layerTypes:["symbol"],idIncludes:["water","river"]},mapColorDescriptions={land:"Map background and other bare-land features. On the mono styles, every map colour left unset derives from it, borders and labels included, and `roadMajor` and `roadOutline` from a given `road` too.",water:"Waterbodies, waterways and other water features. Also influences glaciers, water labels and ferry lines.",vegetation:"Forests and other land cover such as grass and shrubland. Also influences earth cover vegetation at smaller scales.",park:"City parks and sport/recreation grounds. Also influences National Parks and other protected areas at smaller scales.",artificial:"Built-up-areas and man-made features such as landuse grounds and buildings. Also influences railways.",roadMajor:"Most important road classes, from motorways & trunks to primary roads. Also influences outline and tunnel colours.",road:"Less important road classes, from secondary/tertiary to streets and service roads. Also influences tunnel colours.",roadOutline:"Road outlines for secondary/tertiary roads and minor classes, on tunnels, bridges and link roads too. Major road outlines follow `roadMajor`.",label:"Labels for capitals and other populated places/admin areas. Also influences border styling and all other label colours.",labelHalo:"Halos of populated places and admin area labels. Also influences border outlines and all other label halos."},mapColorDefinitions=/* @__PURE__ */(()=>{const e=paintLayers("fill"),t=paintLayers("line"),i=paintLayers("fill-extrusion"),s=baseMapLayerGroupSelector("water"),o=roadLine(["road line","road outline","under construction","link road"],["tarmac"]),r=roadLine(["motorway","primary road","major road"]),a=roadLine(["secondary road","tertiary road","street","minor road","restricted","service road"],["outline"]),n=roadLine(["secondary road outline","tertiary road outline","street outline","minor road outline","tarmac outline"]),l=roadLine(["railway","subway","track","path","aerialway"]),c={...baseMapLayerGroupSelector("capitalLabels"),layerTypes:["symbol"]};return{land:{anchor:{layers:[{layerTypes:["background"]}],property:"background-color"},targets:[{layers:[{layerTypes:["background"]}],properties:["background-color"]},e({metadataGroups:["area"],idIncludes:["earth cover","landcover"]}),e({metadataGroups:["road_area"]}),e({metadataGroups:["transit_area"]}),t({metadataGroups:["transit_area"]})]},water:{anchor:{layers:[{...s,layerTypes:["fill"],idIncludes:["fill"]}],property:"fill-color"},targets:[e(s),t(s),{layers:[WATER_TEXT_LAYERS],properties:["text-color","text-halo-color"]},t(baseMapLayerGroupSelector("ferries"))]},vegetation:{anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["landcover"]}],property:"fill-color"},targets:[e({metadataGroups:["area"],idIncludes:["landcover","earth cover"]})]},park:{anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["protected"]}],property:"fill-color"},targets:[e({metadataGroups:["area"],idIncludes:["protected","outdoor","sport"]}),{...e({metadataGroups:["area"],idIncludes:["landuse"]}),claimedMatchKeys:["outdoor","sport"]},t({metadataGroups:["border"],idIncludes:["overlays"]})]},artificial:{anchor:{layers:[{metadataGroups:["area"],layerTypes:["fill"],idIncludes:["built-up"]}],property:"fill-color",lastStop:!0},targets:[...[e({metadataGroups:["area"],idIncludes:["built-up","landuse","parking"]}),e(baseMapLayerGroupSelector("buildings2D")),t(baseMapLayerGroupSelector("buildings2D")),i(baseMapLayerGroupSelector("buildings3D"))].map(e=>({...e,recolorsTints:!0})),e({metadataGroups:["transit_area","road_area"]}),t({metadataGroups:["transit_area"]}),t(l)]},roadMajor:{anchor:{layers:[roadLine(["motorway & trunk"],["outline"])],property:"line-color",roadClass:"major"},targets:[t(r),{layers:[o],properties:["line-color"],roadClass:"major"}]},road:{anchor:{layers:[roadLine(["secondary road"],["outline"])],property:"line-color"},targets:[t(a),{layers:[roadLine(["road line","under construction","link road"],["outline"])],properties:["line-color"],roadClass:"minor"}]},roadOutline:{anchor:{layers:[roadLine(["secondary road outline"])],property:"line-color"},targets:[t(n),{layers:[roadLine(["road outline","link road outline"],["tarmac"])],properties:["line-color"],roadClass:"minor"}]},label:{anchor:{layers:[c],property:"text-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-color"]},t({metadataGroups:["border"],idIncludes:["country","state","treaty","disputed"]})]},labelHalo:{anchor:{layers:[c],property:"text-halo-color"},targets:[{layers:[TEXT_LAYERS],properties:["text-halo-color"]},t({metadataGroups:["border"],idIncludes:["background"]})]}}})(),baseMapColorNames=/* @__PURE__ */(()=>/* @__PURE__ */everyOf()(["land","water","vegetation","park","artificial","roadMajor","road","roadOutline","label","labelHalo"]))(),mapColorNames=/* @__PURE__ */(()=>[...baseMapColorNames,"accent"])(),isMapColorName=e=>mapColorNames.some(t=>t===e),mapColorKnobId=e=>`colors.${e}`,baseMapColorKnobs=e=>Object.fromEntries(baseMapColorNames.map(t=>[mapColorKnobId(t),e(t)])),factor=e=>({kind:"factor",description:e,range:FACTOR_RANGE,appliesTo:"any-style"}),mapColor$1=e=>({kind:"color",description:mapColorDescriptions[e],appliesTo:"tomtom-styles"}),knobDefinitions=/* @__PURE__ */(()=>({"labels.sizeFactor":factor("Size of every base-map text label (places, roads, POIs, house numbers)."),"symbols.sizeFactor":factor("Size of every base-map icon (POI icons, route shields, road arrows)."),"roads.widthFactor":factor("Width of all road lines, keeping the hierarchy motorway → path."),"labels.typeface":{kind:"enum",description:"Typeface of every map label, each keeping its weight. The SDK's own labels follow it unless their module sets a typeface or a `font` of its own. The serif and italic faces lack some scripts, which the style's own face draws instead. A `labels.customTypeface` of your own font files, set through the module's config, wins over it.",options:mapTypefaces,appliesTo:"tomtom-styles"},...baseMapColorKnobs(mapColor$1),"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"},"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"},"view.sky.visible":{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"},"view.sky.color":{kind:"color",description:"Colour of the sky (and of the atmosphere halo around the globe). Defaults to the style's own sky where it draws one, otherwise to a daylit blue on a light style and a night blue on a dark one.",appliesTo:"any-style"},"view.sky.horizonColor":{kind:"color",description:"Colour of the sky at the horizon. Defaults to the style's own sky where it draws one, otherwise follows the style theme, so a dark map gets a dim horizon rather than a white one.",appliesTo:"any-style"},"view.space.color":{kind:"color",description:"Colour behind the map, which a globe leaves visible around the planet. The map canvas is transparent there. Defaults to a background the page already gives the map container, otherwise follows the style theme: white on a light style, the night blue #0a1626 on a dark one.",appliesTo:"any-style"},"view.light.direction":{kind:"number",description:"Direction the light on the 3D buildings comes from, in degrees clockwise from the top of the screen, or from north with `view.light.alignment` at `map`. Defaults to the style's own light, otherwise 210.",range:{min:0,max:359,step:1,bounds:"hard"},appliesTo:"any-style"},"view.light.altitude":{kind:"number",description:"Height of the light above the horizon, in degrees (0 = sunset, 90 = noon). Defaults to the style's own light, otherwise 60.",range:{min:0,max:90,step:1,bounds:"hard"},appliesTo:"any-style"},"view.light.alignment":{kind:"enum",description:"What `view.light.direction` is measured from: viewport (the top of the screen, turning with the camera) or map (north, staying on the same sides of the buildings as the map rotates). Defaults to the style's own light, otherwise viewport.",options:hillshadeLightAlignments,appliesTo:"any-style"},"view.light.color":{kind:"color",description:"Colour of the light on the 3D buildings. Defaults to the style's own light, otherwise white.",appliesTo:"any-style"},"view.light.intensity":{kind:"number",description:"Strength of the light, 0 to 1: higher sets the lit sides further apart from the shaded ones. Defaults to the style's own light, otherwise 0.5.",range:UNIT_RANGE,appliesTo:"any-style"},"buildings3D.roundedCornerDistanceMeters":{kind:"number",description:"How far along each wall the corners of the 3D buildings are rounded, in metres. 0 keeps them sharp. Defaults to the style's own rounding, otherwise 1, which softens the edges.",range:{min:0,max:10,step:.5,bounds:"hard-min"},appliesTo:"tomtom-styles"}}))(),stylingFoundationsKnobCatalogue=/* @__PURE__ */withIds(knobDefinitions),stylingFoundationsKnobIds=/* @__PURE__ */stylingFoundationsKnobCatalogue.map(({id:e})=>e),isLightPosition=e=>Array.isArray(e)&&3===e.length&&e.every(e=>"number"==typeof e),getMapLight=e=>{const t=e.mapLibreMap;if(!t.style?.light)return;const{anchor:i,position:s}=t.getLight();if(!isLightPosition(s))return;const[,o,r]=s,a="map"===i?0:t.getBearing();return{direction:wrapDegrees(o+a),altitude:90-r}},allButLand=/* @__PURE__ */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,MAJOR_ROAD_CLASSES=/* @__PURE__ */new Set(["motorway","trunk","primary"]),isMatchKey=e=>"string"==typeof e||"number"==typeof e,matchLabelKeys=e=>(Array.isArray(e)?e:[e]).filter(isMatchKey),roadClassOfKeys=e=>e.some(e=>"string"==typeof e&&MAJOR_ROAD_CLASSES.has(e.replace(/_link$/,"")))?"major":"minor",TOP_LEVEL_CONTEXT={roadClass:void 0,matchKeys:[]},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])return((e,t,i)=>{const s="match"===(o=e)[0]&&Array.isArray(o[1])&&"get"===o[1][0]&&("category"===o[1][1]||"road_category"===o[1][1]);var o;const r=[e[0],e[1]];for(let n=2;n<e.length-1;n+=2){const o=matchLabelKeys(e[n]),a=s?roadClassOfKeys(o):i.roadClass,l=[...i.matchKeys,...o];r.push(e[n],mapColorLiterals(e[n+1],t,{roadClass:a,matchKeys:l}))}const a=s?"minor":i.roadClass;return r.push(mapColorLiterals(e.at(-1),t,{...i,roadClass:a})),r})(e,t,i);if("get"===e[0])return e;const[s,...o]=e;return[s,...o.map(e=>mapColorLiterals(e,t,i))]}return isLegacyFunction(e)?{...e,stops:e.stops.map(([e,s])=>[e,mapColorLiterals(s,t,i)])}:e},tintSaturationScale=e=>{const t=themeLuminance(e);return void 0===t?void 0:Math.max(t,.33)},shadeShift=(e,t,i)=>{const[s,o,r]=[e,t,i].map(toHsl);if(!s||!o||!r)return;const a=s.s<.08||o.s<.08;if(!a&&hueDistance(s,o)>40)return;const n=hslShiftBetween(e,t),l=r.alpha??1;return n&&{...n,h:a?0:n.h,alpha:(o.alpha??1)*l-l}},SKY_DEFAULTS=/* @__PURE__ */(()=>{const e={"sky-horizon-blend":.8,"atmosphere-blend":.8,"fog-ground-blend":.5,"horizon-fog-blend":.8};return{light:{...e,"sky-color":"#88c6fc","horizon-color":"#ffffff","fog-color":"#ffffff"},dark:{...e,"sky-color":"#0a1626","horizon-color":"#2b4a72","fog-color":"#0a1626"}}})(),styleSkyColor=(e,t)=>void 0===e?t:isColorLiteral(e)?e:void 0,CLEAR_SKY={"sky-color":"transparent","horizon-color":"transparent","fog-color":"transparent","fog-ground-blend":1,"atmosphere-blend":0},DEFAULT_LIGHT={anchor:"viewport",position:[1.15,210,30],color:"#ffffff",intensity:.5},extensionsByMap=/* @__PURE__ */new WeakMap,MapLookKnobs=class MapLookKnobs{constructor(e){this.engine=e,this.mapColorTargetsByKey=/* @__PURE__ */new Map,this.mapColorTargetsByKnob=/* @__PURE__ */new Map,this.mapColorAnchors=/* @__PURE__ */new Map,this.landDerivedColors=[],this.lightWritten=!1}static for(e){return ofMap(extensionsByMap,e,()=>new MapLookKnobs(StyleKnobs.for(e)))}get tomtomMap(){return this.engine.tomtomMap}index(){this.mapColorTargetsByKey=/* @__PURE__ */new Map,this.mapColorTargetsByKnob=/* @__PURE__ */new Map,this.mapColorAnchors=/* @__PURE__ */new Map,this.landDerivedColors=landDerivedMapColors[standardStyleIdOf(this.tomtomMap.getStyleInput())]??[]}resolve(e,t){return"mapColor"===t.type?this.resolveMapColor(t.color):["\0map"]}refresh(e,t){switch(t.type){case"projection":this.refreshProjection();break;case"sky":this.refreshSky();break;case"space":this.refreshSpace();break;case"light":this.refreshLight();break;case"mapColor":this.refreshMapColor(t.color)}}defaultOf(e,t){if("mapColor"===t.type){const t=this.mapColorAnchors.get(e);return t&&opaqueColor(t)}return this.mapLevelDefaultOf(e)}derivedValueOf(e,t){if("mapColor"===t.type&&this.mapColorAnchors.has(e))return this.mapColorsOf()[t.color]}mapColorsInForce(){const e=this.mapColorsOf();for(const t of mapColorNames){const i=this.mapColorAnchors.get(mapColorKnobId(t));void 0===e[t]&&i&&(e[t]=opaqueColor(i))}return e}refreshSpace(){const e=this.tomtomMap.mapLibreMap.getContainer();this.originalSpaceColor??=paintedBackgroundOf(e),e.style.backgroundColor=this.engine.values["view.space.color"]??this.defaultSpaceColor()}restoreLight(){this.lightWritten&&this.refreshLight()}resolveMapColor(e){const{layers:t,sources:i}=this.engine.indexedStyle,s=mapColorKnobId(e),o=mapColorDefinitions[e],r=[];for(const c of o.targets)for(const s of t.filter(e=>matchesAnyLayerSelector(c.layers,e,i)))for(const t of c.properties){if(!this.engine.capture(s,t))continue;const i={color:e,layerId:s.id,property:t,owns:ownershipOf(c),recolorsTints:c.recolorsTints,claimedMatchKeys:c.claimedMatchKeys};r.push(i);const o=targetKey(s.id,t);ofMap(this.mapColorTargetsByKey,o,()=>[]).push(i)}this.mapColorTargetsByKnob.set(s,r);const{anchor:a}=o,n=t.find(e=>matchesAnyLayerSelector(a.layers,e,i)&&void 0!==styleValueOf(e,a.property)),l=n&&((e,t=()=>!0,i=!1)=>{let s;for(const{literal:o,...r}of(e=>{const t=[];return mapColorLiterals(e,(e,i)=>(t.push({literal:e,...i}),e)),t})(e)){if(!t(r))continue;const e=r.matchKeys.length>0,a=Math.round(100*(toHsl(o)?.s??0)),n=s?.saturation===a;s&&!(i?s.keyed||!e:a>s.saturation||n&&s.keyed&&!e)||(s={literal:o,saturation:a,keyed:e})}return s?.literal})(styleValueOf(n,a.property),ownershipOf({roadClass:a.roadClass}),a.lastStop);return l&&this.mapColorAnchors.set(s,l),l?[...new Set(r.map(e=>e.layerId))]:[]}refreshMapColor(e){const t=this.mapColorsOf(),i=[e,...this.landDerivedColors.filter(t=>void 0===this.engine.values[mapColorKnobId(t)]&&mapColorDerivationInputs(t).includes(e))],s=new Map(i.flatMap(e=>this.mapColorTargetsByKnob.get(mapColorKnobId(e))??[]).map(e=>[targetKey(e.layerId,e.property),e]));for(const{layerId:o,property:r}of s.values())this.refreshMapColorProperty(o,r,t)}mapColorsOf(){const e=this.engine.values,t={};for(const i of mapColorNames){const s=e[mapColorKnobId(i)];"string"==typeof s&&(t[i]=s)}return((e,t,i)=>{const s=e.land??i,o=t.filter(t=>void 0===e[t]&&mapColorDerivationInputs(t).some(t=>void 0!==e[t])),r=s&&o.length?((e,t)=>{const i=toHsl(e),s=themeLuminance(e);if(!i||void 0===s)return;const o=sign(s<=.95),r=sign(s>.3),a=lightenBy(15*o,lighten(Math.max(s/5,.1),i)),n=t&&toHsl(t)||a;return{water:formatStyleHsl(darkenBy(10*sign(s>.01),darken(Math.max(s/20,.05),i))),vegetation:formatStyleHsl(darken(.05,darkenBy(2,i))),park:formatStyleHsl(darken(.03,darkenBy(1,i))),artificial:formatStyleHsl(darkenBy(4*sign(s>.05),lighten(Math.max(s/15,.02),i))),road:formatStyleHsl(a),roadMajor:formatStyleHsl(n),roadOutline:formatStyleHsl(darkenBy(20*o,n)),label:formatStyleHsl(desaturate(.3,darkenBy(60*r,lighten(Math.max(s/5,.1),i)))),labelHalo:formatStyleHsl(lightenBy(75*r,i))}})(s,e.road):void 0;return r?{...Object.fromEntries(o.map(e=>[e,r[e]])),...e}:e})(t,this.landDerivedColors,this.mapColorAnchors.get(mapColorKnobId("land")))}refreshMapColorProperty(e,t,i){const s=this.engine.originalValueOf(e,t),o=[],r=(e=>{const t=new Set(e.flatMap(({claimedMatchKeys:e=[]})=>e));return t.size?e.map(e=>{const i=new Set(e.claimedMatchKeys);return{...e,owns:s=>e.owns(s)&&s.matchKeys.every(e=>i.has(e)||!t.has(e))}}):e})(this.mapColorTargetsByKey.get(targetKey(e,t))??[]);for(const{color:a,owns:n,recolorsTints:l}of r){const e=i[a],t=this.mapColorAnchors.get(mapColorKnobId(a));e&&t&&o.push({anchorColor:t,newColor:e,owns:n,recolorsTints:l})}this.engine.setProperty(e,t,o.length?((e,t)=>{const i=[...t].reverse();return mapColorLiterals(e,(e,t)=>{const s=i.filter(({owns:e})=>!e||e(t));for(const{anchorColor:i,newColor:r}of s){const t=shadeShift(i,e,r);if(t)return shiftHsl(r,t)??e}const o=s.find(e=>e.recolorsTints);return o?((e,t,i)=>{const[s,o,r]=[e,t,i].map(toHsl),[a,n]=[e,i].map(tintSaturationScale);if(!(s&&o&&r&&a&&n))return;const l=o.s*n/a,c=(o.alpha??1)*(r.alpha??1);return formatStyleHsl({h:o.h,s:l,l:r.l+o.l-s.l,alpha:c})})(o.anchorColor,e,o.newColor)??e:e})})(s,o):s)}refreshProjection(){this.tomtomMap.mapLibreMap.setProjection({type:this.engine.values["view.projection"]??this.styleProjection()})}styleProjection(){return this.engine.indexedStyle.projection?.type??"mercator"}refreshSky(){const e=this.engine.values,t=this.shownStyleSky(),i=e["view.sky.visible"]??this.mapLevelDefaultOf("view.sky.visible"),s=SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme],o=i?{...s,...t,"sky-color":e["view.sky.color"]??t?.["sky-color"]??s["sky-color"],"horizon-color":e["view.sky.horizonColor"]??t?.["horizon-color"]??s["horizon-color"]}:CLEAR_SKY;this.tomtomMap.mapLibreMap.setSky(o,{validate:!1})}refreshLight(){const e=this.engine.values,t=this.styleLight(),i=e["view.light.direction"],s=e["view.light.altitude"],o=e["view.light.alignment"],[r,a,n]=isLightPosition(t.position)?t.position:DEFAULT_LIGHT.position;this.tomtomMap.mapLibreMap.setLight({anchor:"map"===o||"viewport"===o?o:t.anchor,position:void 0===i&&void 0===s?this.engine.indexedStyle.light?.position:[r,i??a,void 0===s?n:90-s],color:e["view.light.color"]??t.color,intensity:e["view.light.intensity"]??t.intensity},{validate:!1}),this.lightWritten=!0}styleLight(){return{...DEFAULT_LIGHT,...this.engine.indexedStyle.light}}defaultSpaceColor(){return(this.originalSpaceColor??paintedBackgroundOf(this.tomtomMap.mapLibreMap.getContainer()))||SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme]["fog-color"]}shownStyleSky(){const e=this.engine.indexedStyle.sky,t=0===e?.["atmosphere-blend"]&&"transparent"===e["sky-color"]&&"transparent"===e["horizon-color"];return e&&!t?e:void 0}mapLevelDefaultOf(e){const t=this.shownStyleSky(),i=SKY_DEFAULTS[this.tomtomMap.styleLightDarkTheme],s=this.styleLight();switch(e){case"view.projection":{const e=this.styleProjection();return"string"==typeof e?e:void 0}case"view.sky.visible":return void 0!==t;case"view.sky.color":return styleSkyColor(t?.["sky-color"],i["sky-color"]);case"view.sky.horizonColor":return styleSkyColor(t?.["horizon-color"],i["horizon-color"]);case"view.space.color":return this.defaultSpaceColor();case"view.light.direction":return isLightPosition(s.position)?s.position[1]:void 0;case"view.light.altitude":return isLightPosition(s.position)?90-s.position[2]:void 0;case"view.light.alignment":return"string"==typeof s.anchor?s.anchor:void 0;case"view.light.color":return isColorLiteral(s.color)?s.color:void 0;case"view.light.intensity":return"number"==typeof s.intensity?s.intensity:void 0;default:return}}},ownershipOf=e=>"major"===e.roadClass?({roadClass:e})=>"major"===e:"minor"===e.roadClass?({roadClass:e})=>"major"!==e:()=>!0,paintedBackgroundOf=e=>{const t=getComputedStyle(e).backgroundColor;return t&&(i=t,registeredColorSpaces(),0!==parse(i.trim().toLowerCase())?.alpha)?t:"";var i},mapColor=e=>({kind:"color",mechanisms:[{type:"mapColor",color:e}]}),stylingFoundationsLook=/* @__PURE__ */styleKnobScope("StylingFoundationsModule","",/* @__PURE__ */(()=>{const e={sourceTypes:["vector"],layerTypes:["symbol"]},t={...baseMapLayerGroupSelector("roads"),layerTypes:["line"]},i={kind:"color",mechanisms:[{type:"sky"}]},s={kind:"number",mechanisms:[{type:"light"}]};return{"labels.sizeFactor":scaleKnob("text-size",e),"symbols.sizeFactor":scaleKnob("icon-size",e),"roads.widthFactor":scaleKnob("line-width",t),"labels.typeface":{kind:"enum",mechanisms:[{type:"typeface",layers:[e]}]},...baseMapColorKnobs(mapColor),"colors.accent":{kind:"color",mechanisms:[{type:"published"}]},"view.projection":{kind:"enum",mechanisms:[{type:"projection"}]},"view.sky.visible":{kind:"toggle",mechanisms:[{type:"sky"}]},"view.sky.color":i,"view.sky.horizonColor":i,"view.space.color":{kind:"color",mechanisms:[{type:"space"}]},"view.light.direction":s,"view.light.altitude":s,"view.light.alignment":{kind:"enum",mechanisms:[{type:"light"}]},"view.light.color":{kind:"color",mechanisms:[{type:"light"}]},"view.light.intensity":s,"buildings3D.roundedCornerDistanceMeters":{kind:"number",mechanisms:[{type:"literal",property:"fill-extrusion-rounded-corner-distance",layers:[baseMapLayerGroupSelector("buildings3D")]}]}}})(),e=>MapLookKnobs.for(e)),StylingFoundationsModule=class StylingFoundationsModule extends AbstractStyleOwnedMapModule{static async get(e,t){return await waitUntilMapIsReady(e),sharedInstance(e,StylingFoundationsModule,()=>new StylingFoundationsModule(e,t),t&&(e=>e.updateConfig(t)))}constructor(e,t){super(e,t),e._onStyleKnobsApplied(()=>{e.mapReady&&this.styleKnobs.indexedStyle===this.overriddenStyle&&this.layerOverrides.reapply()})}get styleKnobs(){return stylingFoundationsLook.engineOf(this.tomtomMap)}styleChangePriority(){return 100}_initSourcesWithLayers(){this.warned=/* @__PURE__ */new Set,this.layerOverrides??=new LayerOverrides(this.mapLibreMap,this.filterComposer,this.visibilityComposer,(e,t)=>this.warnOnce(e,t)),this.overriddenStyle=this.styleKnobs.indexedStyle;const e=this.tomtomMap._styleLoads;this.layerOverrides.index(this.overriddenStyle.layers,this.overriddenStyle.sources,e!==this.indexedStyleLoads),this.indexedStyleLoads=e;const t=MapLookKnobs.for(this.tomtomMap);return t.refreshSpace(),t.restoreLight(),{}}_applyConfig(e){const t=withoutUndefined(e??{});return stylingFoundationsLook.apply(this.tomtomMap,t),((e,t,i)=>{if(!e.mapReady)return;const s=t&&declareCustomTypeface(t);!declareFontFaces(e,i,s?.fontFaces)&&isEqual(customTypefaceOf(e),s?.typeface)||((e,t,i)=>{const s=declarations.get(e);s&&e.mapReady&&fontFacesToSet(e,s)?s.waiting.set(t,i):i()})(e,i,()=>{((e,t)=>{t?customTypefaces.set(e,t):customTypefaces.delete(e)})(e,s?.typeface),i.reapply(["labels.typeface"])})})(this.tomtomMap,t.labels?.customTypeface,this.styleKnobs),this.tomtomMap._setMapColors(MapLookKnobs.for(this.tomtomMap).mapColorsInForce()),this.tomtomMap.mapReady&&this.layerOverrides.reapply(),isEmpty(t)?void 0:t}discardShownData(){this.layerOverrides.clear(this.tomtomMap._styleLoads===this.indexedStyleLoads)}get layers(){return{query:e=>new LayerSelection(this.layerOverrides,e)}}_knobValue(e){return super._knobValue(e)??stylingFoundationsLook.valueOf(this.tomtomMap,e)}setMapColors(e){const t={};for(const[i,s]of Object.entries(e)){if(!isMapColorName(i))throw new Error(`Unknown map colour '${i}'. Known colours: ${mapColorNames.join(", ")}.`);void 0!==s&&(t[mapColorKnobId(i)]=s)}setKnobs(this,stylingFoundationsKnobCatalogue,t)}exportStyle(){const e=this.styleKnobs.withShippedTransition(this.mapLibreMap.getStyle()),t=this.mapLibreMap.getLight();return(e=>{const{"font-faces":t,...i}=JSON.parse(JSON.stringify(e).replace(SDK_NAME_IN_JSON_STACK,"")),s=t&&withoutCustomFaceDeclarations(t);return isEmpty(s)?i:{...i,"font-faces":s}})(Object.keys(t).length?{...e,light:t}:e)}get events(){return this.moduleEvents([])}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[StylingFoundationsModule] ${t}`))}},withoutUndefined=e=>Object.fromEntries(Object.entries(e).flatMap(([e,t])=>{const i=isPlainObject(t)?withoutUndefined(t):t;return void 0===i||isPlainObject(i)&&isEmpty(i)?[]:[[e,i]]})),presetSettings={"data-viz":{stylingFoundations:{"labels.sizeFactor":.9,"symbols.sizeFactor":.9,"roads.widthFactor":.8},baseMap:{"roads.exitNumbers.visible":!1,"roads.arrows.visible":!1},pois:{"microMarkers.visible":!1,minZoom:14}},"night-driving":{stylingFoundations:{"labels.sizeFactor":1.2,"symbols.sizeFactor":1.2,"roads.widthFactor":1.2},baseMap:{"roads.exitNumbers.visible":!0,"roads.arrows.visible":!0},pois:{"microMarkers.visible":!1,minZoom:13}},minimal:{stylingFoundations:{"labels.sizeFactor":.9},baseMap:{"roads.exitNumbers.visible":!1,"roads.arrows.visible":!1,"roads.restricted.visible":!1,"roads.underConstruction.visible":!1},pois:{"microMarkers.visible":!1,minZoom:16}},globe:{stylingFoundations:{"view.projection":"globe","view.sky.visible":!0}}},presetTexts={"data-viz":{name:"Data visualisation",description:"A quiet base for your own data on top: smaller labels, fewer markers, thinner roads, no badges competing with the overlay."},"night-driving":{name:"Night driving",description:"Bigger labels and shields, wider roads, POIs out of the way until close up."},minimal:{name:"Minimal",description:"The bare map: smaller labels, no road markings, roads under construction, exit badges or POI dots until close up. Hide buildings and shields with BaseMapModule."},globe:{name:"Globe",description:"A globe with an atmosphere for the zoomed-out view; flattens to Mercator as you zoom in."}},mapPresetIds=/* @__PURE__ */Object.keys(presetSettings),mapPresetCatalogue=/* @__PURE__ */mapPresetIds.map(e=>({id:e,...presetTexts[e],settings:structuredClone(presetSettings[e])})),applyPresetPart=(e,t,i={})=>{const s=e.getConfig()??{},o=configWithKnobs(t.reduce((e,t)=>configWithoutKnob(e,t),s),i);isEqual(o,s)||e.applyConfig(isEmpty(o)?void 0:o)},applyMapPreset=async(e,t,i={})=>{if(!Object.hasOwn(presetSettings,t))throw new Error(`Unknown map preset '${t}'. Known presets: ${mapPresetIds.join(", ")}.`);const s=presetSettings[t],[o,r,a]=await Promise.all([StylingFoundationsModule.get(e),BaseMapModule.get(e),POIsModule.get(e)]),n=e=>i.merge?[]:(e=>[...new Set(Object.values(presetSettings).flatMap(t=>Object.keys(t[e]??{})))])(e);applyPresetPart(o,n("stylingFoundations"),s.stylingFoundations),applyPresetPart(r,n("baseMap"),s.baseMap),applyPresetPart(a,n("pois"),s.pois)},MULTIDIRECTIONAL_LIGHT_OFFSETS=[-67.5,-22.5,22.5,67.5],multidirectionalLights={dependsOn:["terrain.hillshade.method"],expand:(e,t)=>"multidirectional"===t("terrain.hillshade.method")&&"number"==typeof e?MULTIDIRECTIONAL_LIGHT_OFFSETS.map(t=>wrapDegrees(e+t)):e},hillshadeLook=/* @__PURE__ */styleKnobScope("TerrainModule","terrain.",/* @__PURE__ */(()=>{const e=styleModuleLayerGroupSelector("hillshade"),t=(t,i,s)=>({kind:t,mechanisms:[{type:"literal",property:i,layers:[e],expansion:s}]});return{"terrain.hillshade.method":t("enum","hillshade-method"),"terrain.hillshade.light.direction":t("number","hillshade-illumination-direction",multidirectionalLights),"terrain.hillshade.light.altitude":t("number","hillshade-illumination-altitude"),"terrain.hillshade.light.alignment":t("enum","hillshade-illumination-anchor"),"terrain.hillshade.intensity":t("number","hillshade-exaggeration"),"terrain.hillshade.maxZoom":{kind:"number",mechanisms:[{type:"maxZoom",layers:[e]}]},"terrain.hillshade.colors.shaded":colorKnob("hillshade-shadow-color",e),"terrain.hillshade.colors.lit":colorKnob("hillshade-highlight-color",e),"terrain.hillshade.colors.steep":colorKnob("hillshade-accent-color",e)}})()),trafficLook=e=>{const t={...styleModuleLayerGroupSelector(e),layerTypes:["line"]},i=(e,i)=>({...t,idIncludes:[i?`${e} outline`:e],...i?{}:{idExcludes:["outline"]}});return{levelColor:e=>colorKnob("line-color",i(e,!1),i(e,!0)),closedColor:()=>colorKnob("line-color",i("closed road",!0)),widthFactor:()=>scaleKnob("line-width",t),opacityFactor:()=>scaleKnob("line-opacity",t)}},trafficFlowStyleKnobs=/* @__PURE__ */(()=>{const e=trafficLook("trafficFlow");return{"traffic.flow.colors.free":e.levelColor("free flow"),"traffic.flow.colors.slow":e.levelColor("slow flow"),"traffic.flow.colors.queueing":e.levelColor("queueing flow"),"traffic.flow.colors.stationary":e.levelColor("stationary flow"),"traffic.flow.colors.closed":e.closedColor(),"traffic.flow.widthFactor":e.widthFactor(),"traffic.flow.opacityFactor":e.opacityFactor()}})(),trafficIncidentsStyleKnobs=/* @__PURE__ */(()=>{const e=trafficLook("trafficIncidents");return{[incidentColorKnobIds.minor]:e.levelColor("minor jam"),[incidentColorKnobIds.moderate]:e.levelColor("moderate jam"),[incidentColorKnobIds.major]:e.levelColor("major jam"),[incidentColorKnobIds.indefinite]:e.closedColor(),"traffic.incidents.widthFactor":e.widthFactor(),"traffic.incidents.opacityFactor":e.opacityFactor()}})(),trafficFlowLook=/* @__PURE__ */styleKnobScope("TrafficFlowModule","traffic.flow.",trafficFlowStyleKnobs),trafficIncidentsLook=/* @__PURE__ */styleKnobScope("TrafficIncidentsModule","traffic.incidents.",trafficIncidentsStyleKnobs),styleKnobScopes=[stylingFoundationsLook,poisLook,trafficFlowLook,trafficIncidentsLook,hillshadeLook],styleColorKnobIds=/* @__PURE__ */(()=>/* @__PURE__ */everyOf()(["colors.land","colors.water","colors.vegetation","colors.park","colors.artificial","colors.roadMajor","colors.road","colors.roadOutline","colors.label","colors.labelHalo","colors.accent","view.sky.color","view.sky.horizonColor","view.space.color","pois.label.color","pois.label.haloColor","traffic.flow.colors.free","traffic.flow.colors.slow","traffic.flow.colors.queueing","traffic.flow.colors.stationary","traffic.flow.colors.closed","traffic.incidents.colors.minor","traffic.incidents.colors.moderate","traffic.incidents.colors.major","traffic.incidents.colors.closed","terrain.hillshade.colors.shaded","terrain.hillshade.colors.lit","terrain.hillshade.colors.steep"]))(),getStyleColor=(e,t)=>{if(!e.mapReady)return;const i=styleKnobScopes.find(e=>e.has(t))?.engineOf(e).valueOf(t);return"string"==typeof i?i:void 0},stylingFoundationsKnobKinds=["factor","number","toggle","color","enum"],stylingFoundationsKnobAppliesTo=["any-style","tomtom-styles"],interactiveEventTypes=/* @__PURE__ */Object.keys({hover:!0,"hover-move":!0,"long-hover":!0,click:!0,contextmenu:!0,dragstart:!0,drag:!0,dragend:!0}),shownOriginalOf=(e,t)=>t instanceof GeoJSONSourceWithLayers?t.findById(shownRefId(e))?.feature??e:e,accepts=(e,t)=>!e.scope?.featureMatches||e.scope.featureMatches(shownOriginalOf(t,e.sourceWithLayers)),noHandlers=[],removeWhere=(e,t)=>{for(let i=e.length-1;i>=0;i--)t(e[i])&&e.splice(i,1)},AbstractEventProxy=class{constructor(){this.interactiveLayerIDs=[],this.handlers=Object.fromEntries(interactiveEventTypes.map(e=>[e,{}])),this.registered=Object.fromEntries(interactiveEventTypes.map(e=>[e,/* @__PURE__ */new Set])),this.findHandlers=(e,t)=>t&&e.flatMap(e=>this.handlers[e][t]??noHandlers)||[]}ensureInteractiveLayerIDsAdded(e){for(const t of e)this.interactiveLayerIDs.includes(t)||this.interactiveLayerIDs.push(t)}releaseUnusedInteractiveLayerIDs(e){removeWhere(this.interactiveLayerIDs,t=>e.has(t)&&!this.hasHandlerForLayer(t))}indexHandler(e,t){const i=this.handlers[t];for(const s of e.layerIDs)i[s]??=[],i[s].push(e)}unindexHandlers(e,t){const i=this.handlers[t],s=/* @__PURE__ */new Set;for(const o of e)for(const t of o.layerIDs){s.add(t);const o=i[t];o&&(removeWhere(o,t=>e.has(t)),o.length||delete i[t])}return s}dropHandlers(e,t,i){const s=/* @__PURE__ */new Set;for(const o of this.registered[t])o.sourceWithLayers.source.id===e&&i(o)&&s.add(o);if(s.size){for(const e of s)this.registered[t].delete(e);this.releaseUnusedInteractiveLayerIDs(this.unindexHandlers(s,t))}}addEventHandler(e,t,i,s){const o=new Set(scopedLayerIDs(e,s.scope)),r={...s,sourceWithLayers:e,layerIDs:o,handler:t};this.registered[i].add(r),this.ensureInteractiveLayerIDsAdded(o),this.indexHandler(r,i)}removeHandler(e,t,i){this.dropHandlers(e,t,e=>e.handler===i)}remove(e,t,i){this.dropHandlers(e,t,e=>e.owner===i)}removeSource(e){for(const t of interactiveEventTypes)this.dropHandlers(e.source.id,t,()=>!0)}hasHandlerForLayer(e){for(const t of interactiveEventTypes)if(this.handlers[t][e]?.length)return!0;return!1}hasHandlersOf(e){return e.some(e=>this.registered[e].size>0)}sourceWithLayersFor(e){if(e)for(const t of interactiveEventTypes){const i=this.handlers[t][e];if(i?.length)return i[0].sourceWithLayers}}updateIfRegistered(e,t){const i=new Map(Object.values(e).filter(e=>void 0!==e).map(e=>[e.source.id,e])),s=/* @__PURE__ */new Map;for(const o of interactiveEventTypes){const e=this.handlersToRefile(o,t,i);if(!e.size)continue;const r=this.unindexHandlers(new Set(e.keys()),o);for(const[t,i]of e)i?(s.set(t.sourceWithLayers,i),t.sourceWithLayers=i,t.layerIDs=new Set(scopedLayerIDs(i,t.scope)),this.ensureInteractiveLayerIDsAdded(t.layerIDs),this.indexHandler(t,o)):t.layerIDs=/* @__PURE__ */new Set;this.releaseUnusedInteractiveLayerIDs(r)}return s}handlersToRefile(e,t,i){const s=/* @__PURE__ */new Map;for(const o of this.registered[e]){if(o.owner!==t)continue;const e=i.get(o.sourceWithLayers.source.id);(e||o.layerIDs.size)&&s.set(o,e)}return s}firstHandler(e,t,i){if(t)for(const s of e)for(const e of this.handlers[s][t]??noHandlers)if(!i||accepts(e,i))return e}},noRenderedFeatures=[],dragEventTypes=["dragstart","drag","dragend"],eventsProxyDefaultConfig={precisionMode:"box",paddingBoxPx:5,cursorOnHover:"pointer",cursorOnDraggable:"grab",cursorOnMouseDown:"grabbing",cursorOnMap:"default",longHoverDelayAfterMapMoveMS:800,longHoverDelayOnStillMapMS:300,hoverGracePeriodMS:400},EventsProxy=class extends AbstractEventProxy{constructor(e,t={}){super(),this.enabled=!0,this.recentHovers=new globalThis.Map,this.firstDelayedHoverSinceMapMove=!0,this.mouseButtonDown=!1,this.mouseMoveFrameRequested=!1,this.dragJustEnded=!1,this.hoverStaleAfterDrag=!1,this.customLayers=new globalThis.Map,this.isQueryable=e=>!this.customLayers.has(e)&&!!this.map.getLayer(e),this.handleLongHoverTimeout=()=>{const e=this.lastHandledMouseMove;if(e&&this.isEnabled()){const t=this.getRenderedFeatures(e.point);if(!this.claimsHover(t[0]))return void this.rehover(e,t);this.hoveringFeatures=t}this.hoveringSourceWithLayers&&(this.firstDelayedHoverSinceMapMove=!1,updateEventState("long-hover",this.hoveringFeature,void 0,this.hoveringSourceWithLayers,void 0),this.hoveringLngLat&&this.dispatchToHandlers(this.findHandlers(["long-hover"],this.hoveringFeature?.layer.id),this.hoveringFeatures??noRenderedFeatures,this.hoveringFeature,this.hoveringLngLat))},this.sameClaim=(e,t)=>this.claimingHandler(e)===this.claimingHandler(t),this.onReleaseOutside=()=>{this.onMouseUp(),this.onPressEnd()},this.onMouseMoveFrame=()=>{this.mouseMoveFrameRequested=!1;const e=this.pendingMouseMove;this.pendingMouseMove=void 0,e&&this.handleMouseMove(e)},this.map=e,this.mapCanvas=e.getCanvas(),this.config={...eventsProxyDefaultConfig,...definedFields(t)},this.mapCanvas.style.cursor=this.config.cursorOnMap,this.lastCursorStyle=this.config.cursorOnMap,this.listenToEvents()}updateConfig(e){this.config={...this.config,...definedFields(e)},this.hoveringSourceWithLayers||(this.mapCanvas.style.cursor=this.config.cursorOnMap)}updateIfRegistered(e,t){const i=super.updateIfRegistered(e,t),s=new globalThis.Map(Object.values(e).filter(e=>e instanceof GeoJSONSourceWithLayers).map(e=>[e.source.id,e])),o=e=>e?i.get(e)??(e instanceof GeoJSONSourceWithLayers?s.get(e.source.id):void 0)??e:e;this.hoveringSourceWithLayers=o(this.hoveringSourceWithLayers),this.lastClickedSourceWithLayers=o(this.lastClickedSourceWithLayers);for(const r of this.recentHovers.values())r.sourceWithLayers=o(r.sourceWithLayers);return i}listenToEvents(){this.map.on("mousemove",e=>this.onMouseMove(e)),this.map.on("movestart",()=>this.onMoveStart()),this.map.on("mouseout",()=>this.onMouseOut()),this.map.on("mouseover",e=>this.onMouseMove(e)),this.map.on("mousedown",e=>{this.onMouseDown(),0===e.originalEvent.button&&this.onPressStart(e),this.mapCanvas.ownerDocument.addEventListener("mouseup",this.onReleaseOutside,{once:!0})}),this.map.on("mouseup",e=>{this.mapCanvas.ownerDocument.removeEventListener("mouseup",this.onReleaseOutside),this.onMouseUp(),this.onPressEnd(e.lngLat)}),this.map.on("touchstart",e=>{1===e.points.length?this.onPressStart(e):this.onPressEnd()}),this.map.on("touchmove",e=>this.onPressMove(e)),this.map.on("touchend",e=>this.onPressEnd(e.lngLat)),this.map.on("touchcancel",()=>this.onPressEnd()),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,this.onPressEnd())}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 s=this.sourceWithLayersFor(t?.layer.id);return(o=e.filter(e=>i?i.has(e.layer.id):s?._layerSpecs.some(t=>t.id===e.layer.id)),distinctBy(o,e=>{const t=renderedRefId(e);if(void 0!==t)return`${isCluster(e)?`${e.source} cluster`:e.source} ${t}`})).map(e=>shownOriginalOf(e,s));var o}addCustomLayer(e){this.customLayers.set(e.layerId,e)}removeCustomLayer(e){this.removeSource(e),this.customLayers.delete(e.layerId),this.hoveringFeature?.layer.id===e.layerId&&(this.clearLongHoverTimeout(),this.hoveringFeature=void 0,this.hoveringFeatures=void 0,this.hoveringSourceWithLayers=void 0,this.hoveringHandler=void 0,this.updateHoverCursor(void 0,void 0)),this.lastClickedFeature?.layer.id===e.layerId&&(this.lastClickedFeature=void 0,this.lastClickedSourceWithLayers=void 0),e.detach()}getRenderedFeatures(e){const t=this.queryRenderedFeatures(e);return this.customLayers.size?this.withCustomLayerHits(e,t):t}withCustomLayerHits(e,t){let i;for(const n of this.customLayers.values()){if(!this.hasHandlerForLayer(n.layerId))continue;const t=n.hitFeatures(e);t.length&&(i??=[],i.push({layerId:n.layerId,hits:t}))}if(!i)return t;const s=new globalThis.Map(this.map.getLayersOrder().map((e,t)=>[e,t])),o=e=>s.get(e)??-1;i.sort((e,t)=>o(t.layerId)-o(e.layerId));const r=[];let a=0;for(const{layerId:n,hits:l}of i){for(;a<t.length&&o(t[a].layer.id)>o(n);)r.push(t[a++]);r.push(...l)}return r.concat(t.slice(a))}queryRenderedFeatures(e){const t=this.interactiveLayerIDs.every(this.isQueryable)?this.interactiveLayerIDs:this.interactiveLayerIDs.filter(this.isQueryable);if(!t.length)return noRenderedFeatures;const i={layers:t,validate:!1},s=this.config.precisionMode,o="point-then-box"===s||"point"===s?this.map.queryRenderedFeatures(e,i):noRenderedFeatures;return o.length||"point"===s?o:this.map.queryRenderedFeatures(this.toPaddedBounds(e),i)}clearLongHoverTimeout(){clearTimeout(this.longHoverTimeoutHandlerID)}restartLongHoverTimeout(){this.clearLongHoverTimeout(),this.longHoverTimeoutHandlerID=setTimeout(this.handleLongHoverTimeout,this.firstDelayedHoverSinceMapMove?this.config.longHoverDelayAfterMapMoveMS:this.config.longHoverDelayOnStillMapMS)}claimsHover(e){const t=this.hoveringFeature;return e&&t?isSameHoverTarget(e,t)&&this.claimingHandler(e)===this.hoveringHandler:e===t}claimingHandler(e){return this.firstHandler(interactiveEventTypes,e.layer.id,e)}rehover(e,t){const i=this.hoveringFeature,s=this.hoveringSourceWithLayers;this.hoveringFeatures=t,this.hoveringFeature=t[0],this.hoveringLngLat=e.lngLat,this.hoveringPoint=e.point,this.dispatchHoverEnter(e,i,s),this.restartLongHoverTimeout()}onMoveStart(){this.firstDelayedHoverSinceMapMove=!0,this.clearLongHoverTimeout()}onMouseOut(){this.clearLongHoverTimeout(),this.pendingMouseMove=void 0}onMouseDown(){this.mouseButtonDown||(this.lastCursorStyle=this.mapCanvas.style.cursor),this.mouseButtonDown=!0,this.mapCanvas.style.cursor=this.config.cursorOnMouseDown}onMouseUp(){this.mouseButtonDown=!1,this.mapCanvas.style.cursor=this.lastCursorStyle}onPressStart(e){if(this.onPressEnd(),this.dragJustEnded=!1,!this.isEnabled()||!this.hasHandlersOf(dragEventTypes))return;const t=this.getRenderedFeatures(e.point),[i]=t;i&&this.firstHandler(dragEventTypes,i.layer.id,i)&&(e.preventDefault(),this.press={feature:i,rendered:t,startPoint:e.point,lngLat:e.lngLat})}onPressMove(e){const t=this.press;if(!t)return;t.lngLat=e.lngLat;let{callerFeatures:i}=t;if(!i){if(t.startPoint.dist(e.point)<this.map._clickTolerance)return;this.clearLongHoverTimeout(),i=this.toCallerFeatures(t.rendered,t.feature),t.callerFeatures=i,this.dispatchDrag("dragstart",t,i)}this.dispatchDrag("drag",t,i)}onPressEnd(e){const t=this.press;t&&(this.press=void 0,t.callerFeatures&&(this.dragJustEnded=!0,this.hoverStaleAfterDrag=!0,t.lngLat=e??t.lngLat,this.dispatchDrag("dragend",t,t.callerFeatures)))}dispatchDrag(e,t,i){this.dispatchToHandlers(this.findHandlers([e],t.feature.layer.id),t.rendered,t.feature,t.lngLat,i)}onMouseMove(e){this.onPressMove(e),this.press?.callerFeatures||(this.pendingMouseMove=e,this.mouseMoveFrameRequested||(this.mouseMoveFrameRequested=!0,requestAnimationFrame(this.onMouseMoveFrame)))}handleMouseMove(e){if(!this.isEnabled()||this.press?.callerFeatures)return;this.lastHandledMouseMove=e,this.hoveringFeatures=this.getRenderedFeatures(e.point);const[t]=this.hoveringFeatures;if(t&&!this.hasHandlerForLayer(t.layer.id))return;const i=((e,t,i,s,o)=>{if(t){if(!s)return"changed";if(!isSameHoverTarget(t,s)||t.layer.id!==s.layer.id&&!o?.(t,s))return"changed";if(i&&(e.x-i.x!=0||e.y-i.y!=0))return"moving"}else if(s)return"changed";return"still"})(e.point,t,this.hoveringPoint,this.hoveringFeature,this.sameClaim),s="changed"===i||this.hoverStaleAfterDrag,o="moving"===i;if(this.hoverStaleAfterDrag=!1,!s&&!o)return;const r=!s&&!this.claimsHover(t),a=this.hoveringFeature,n=this.hoveringSourceWithLayers;let l;this.hoveringLngLat=e.lngLat,this.hoveringPoint=e.point,this.hoveringFeature=t,(s||r)&&(l=this.dispatchHoverEnter(e,a,n)),o&&this.dispatchHoverMove(e,l),this.restartLongHoverTimeout()}dispatchHoverEnter(e,t,i){const s=this.hoveringFeature?.layer.id,o=this.firstHandler(interactiveEventTypes,s,this.hoveringFeature),r=this.hoveringHandler;this.hoveringHandler=o,this.hoveringSourceWithLayers=o?.sourceWithLayers,this.updateHoverCursor(o,this.hoveringFeature);const a=t&&(i instanceof GeoJSONSourceWithLayers||i instanceof CustomLayerSourceWithLayers)?r?.config?.()?.hoverGracePeriodMS??this.config.hoverGracePeriodMS:0;return updateEventState("hover",this.hoveringFeature,t,this.hoveringSourceWithLayers,i,a>0),t&&a>0&&this.clearRecentHoverLater(t,i,a),this.dispatchToHandlers(this.findHandlers(["hover"],s),this.hoveringFeatures??noRenderedFeatures,this.hoveringFeature,e.lngLat)}dispatchHoverMove(e,t){const i=this.hoveringFeature?.layer.id;i&&this.handlers["hover-move"][i]&&this.dispatchToHandlers(this.findHandlers(["hover-move"],i),this.hoveringFeatures??noRenderedFeatures,this.hoveringFeature,e.lngLat,t)}dispatchToHandlers(e,t,i,s,o){let r=o;for(const a of e){let e;a.scope?.layerFilter?e=this.toCallerFeatures(t,i,a.layerIDs):(r??=this.toCallerFeatures(t,i),e=r),a.handler(e[0],s,e,a.sourceWithLayers)}return r}clearRecentHoverLater(e,t,i){const s=t instanceof CustomLayerSourceWithLayers?renderedRefId(e):shownRefId(e);if(void 0===s)return;const o=`${e.source} ${s}`,r=e.layer.id;clearTimeout(this.recentHovers.get(o)?.timeout);const a=setTimeout(()=>{const t=this.recentHovers.get(o)?.sourceWithLayers;this.recentHovers.delete(o);const i=this.sourceWithLayersFor(r)??t;i&&((e,t)=>{const i=keeperOf(e);if(i){const e=i.eventStateKeyOf(t);return void(void 0!==e&&"recently-hovered"===i.eventStateOf(e)&&i.putEventState(e,void 0))}if(!(e instanceof GeoJSONSourceWithLayers))return;const s=e.findById(shownRefId(t));"recently-hovered"===s?.feature.properties?.eventState&&e.clearEventState({index:s.index})})(i,e)},i);this.recentHovers.set(o,{timeout:a,sourceWithLayers:t})}updateHoverCursor(e,t){if(!e||!t)return void(this.mapCanvas.style.cursor=this.config.cursorOnMap);const i=this.firstHandler(dragEventTypes,t.layer.id,t);this.mapCanvas.style.cursor=i?i.config?.()?.cursorOnDraggable??this.config.cursorOnDraggable:e.config?.()?.cursorOnHover??this.config.cursorOnHover}onMapClick(e,t){if("click"===e&&this.dragJustEnded)return void(this.dragJustEnded=!1);if(!this.isEnabled())return;const i=this.getRenderedFeatures(t.point),s=this.lastClickedFeature;this.lastClickedFeature=i[0];const o=this.lastClickedSourceWithLayers,r=this.findHandlers([e],this.lastClickedFeature?.layer.id);this.lastClickedSourceWithLayers=this.firstHandler([e],this.lastClickedFeature?.layer.id,this.lastClickedFeature)?.sourceWithLayers,updateEventState(e,this.lastClickedFeature,s,this.lastClickedSourceWithLayers,o),this.dispatchToHandlers(r,i,this.lastClickedFeature,t.lngLat)}},labelFieldExceptions={ngt:"name","ngt-Latn":"name_ngt-Latn","zh-Hant":"name_zh-Hant","zh-Hans":"name_zh-Hans","ko-Latn-KR":"name_ko-Latn","nb-NO":"name_no","ru-Latn-RU":"name_ru-Latn"},isNameRead=e=>Array.isArray(e)&&2===e.length&&"get"===e[0]&&"name"===e[1],withLocalizedNameReads=(e,t)=>{if(isNameRead(e)||(i=e,Array.isArray(i)&&3===i.length&&"coalesce"===i[0]&&Array.isArray(i[1])&&"get"===i[1][0]&&"string"==typeof i[1][1]&&i[1][1].startsWith("name_")&&isNameRead(i[2])))return t;var i;if(!Array.isArray(e)||"literal"===e[0])return;let s=!1;const o=e.map(e=>{const i=withLocalizedNameReads(e,t);return void 0===i?e:(s=!0,i)});return s?o:void 0},localizedLayerTextField=(e,t)=>{const i=e.layout?.["text-field"];return"string"==typeof i?"{name}"===i?t:void 0:withLocalizedNameReads(i,t)},TomTomMapError=class extends Error{constructor(e,t){super(e,"cause"in t?{cause:t.cause}:void 0),this.sdkVersion="1.0.0-rc.6",this.name="TomTomMapError",this.code=t.code,this.canRetry=canRetrySDKErrorCode(t.code),this.status=t.status,this.apiErrorCode=t.apiErrorCode,this.privatePreviewAccess=t.privatePreviewAccess,this.sourceId=t.sourceId}},FETCH_FAILURE_MESSAGES=/^(Failed to fetch|NetworkError when attempting to fetch resource\.|Load failed)$/,toRequestError=(e,t)=>{const{message:i,status:s,apiErrorCode:o,privatePreviewAccess:r,...a}=e;let n=t;s?n=sdkErrorCodeForStatus(s):(0===s||FETCH_FAILURE_MESSAGES.test(i))&&(n="NETWORK_NOT_AVAILABLE");const{message:l,...c}=describeAPIError({message:i,code:n,apiErrorCode:o,privatePreviewAccess:r});return new TomTomMapError(l,{...a,...c,code:n,status:s||void 0})},isJSON=e=>!!(e instanceof Blob?e.type:e.headers.get("content-type"))?.includes("json"),readAPIError=async e=>{if(!isJSON(e))return{};const t=await e.text().then(JSON.parse).catch(()=>{});return{apiErrorCode:apiErrorCodeIn(t),apiMessage:apiErrorMessageIn(t)}},toTomTomMapRequestError=async(e,t)=>{const{sourceId:i}=t;if("fetchError"in e){const{fetchError:t}=e,s=t instanceof Error?t.message:String(t);return toRequestError({message:s,status:0,sourceId:i,cause:t},"NETWORK_NOT_AVAILABLE")}const{response:s}=e,{apiErrorCode:o,apiMessage:r}=await readAPIError(s),a=r?`: ${r}`:"";return toRequestError({message:`The ${i} request failed with ${s.status}${a}`,status:s.status,apiErrorCode:o,privatePreviewAccess:t.privatePreviewAccess,sourceId:i,cause:s},"INTERNAL")},addHandler=(e,t)=>{e.push(t);let i=!1;return()=>{if(i)return;i=!0;const s=e.indexOf(t);-1!==s&&e.splice(s,1)}},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 _styleKnobSettings(){return this.styleKnobSettings}_setStyleKnobSettings(e,t){if(this.styleKnobSettings=e,t.size)for(const i of this.styleKnobsAppliedHandlers)i(t)}_onStyleKnobsApplied(e){this.styleKnobsAppliedHandlers.push(e)}constructor(e){if(this.mapReady=!1,this._mapColors={},this.mapColorsHandlers=[],this.styleKnobSettings={},this.styleKnobsAppliedHandlers=[],this.styleChangeHandlers=[],this.errorHandlers=[],this.styleLoadFailureHandlers=[],this.vectorTilesReloadPending=!1,this.incidentTilesReloadPending=!1,this.styleRequestSequence=0,this.styleLayerIds=/* @__PURE__ */new Set,this.styleLoads=0,this.styleDataUnannounced=!1,this.setStyle=(e,t={})=>{const i={resetState:t.resetState??!1};this.mapReady=!1,this.styleLoadError=void 0;const s=++this.styleRequestSequence,o=i.resetState?e:((e,t)=>{const i="object"==typeof t?t.include:void 0;return i?"string"==typeof e?{type:"standard",id:e,include:i}:e.include?e:{...e,include:i}:e})(e,this._params.style);return this._params={...this._params,style:o},this._styleLightDarkTheme=getStyleLightDarkTheme(o),this.applyStyle(i,s)},this.getStyleInput=()=>this._params.style??"streetLight",this._params=mergeFromGlobal(e),!isSecureBaseURL(this._params.commonBaseURL))throw new TomTomMapError(insecureBaseURLMessage(this._params.commonBaseURL),{code:"INSECURE_BASE_URL"});void 0===this._params.style&&(this._params={...this._params,style:"streetLight"}),this._styleLightDarkTheme=getStyleLightDarkTheme(this._params.style);const t=loading||"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})()?loading:loading=import("./chunks/maplibre-gl-DudBHU-O.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)).catch(e=>console.error("Could not apply the MapLibre CSS",e)).finally(()=>{loading=void 0});!1!==this._params.registerMapLibreWorker&&(()=>{if("undefined"==typeof Worker||getWorkerUrl())return;const e=(()=>{try{const e=(()=>{const e=globalThis.Worker;let t;globalThis.Worker=new Proxy(e,{construct:(e,[i,s])=>(t={url:String(i),type:s?.type},{})});try{new Worker(new URL("./chunks/maplibre-gl-worker.js",import.meta.url),{type:"module"})}finally{globalThis.Worker=e}return t})(),t=import.meta.url;return"module"===e?.type&&e.url!==new URL("./chunks/maplibre-gl-worker.js",t).href?e.url:void 0}catch{return}})();e&&setWorkerUrl(e)})(),setWorkerCount(4),this.styleGivenToMapLibre=buildStyleInput(this._params);try{this.mapLibreMap=new Map$1({validateStyle:!1,maxTileCacheZoomLevels:22,cancelPendingTileRequestsWhileZooming:!1,...(i=this._params).mapLibre,style:buildStyleInput(i),attributionControl:!1,transformRequest:transformRequest(i)})}catch(a){throw a instanceof Error&&"GPUInitializationError"===a.name?new TomTomMapError(a.message,{code:"WEBGL_UNSUPPORTED",cause:a}):a}var i,s,o,r;t?.then(()=>this.fitCanvasToContainer()),this.mapLibreMap.on("error",e=>{const t=void 0!==this.failStyleLoadInFlight&&!("sourceId"in e),i=t?this.failStyleLoadInFlight:void 0,s=e=>{this.notifyErrorHandlers(e),i&&i===this.failStyleLoadInFlight&&i(e)},o=((e,t)=>{const i=e.error;if(i instanceof TomTomMapError)return i;const s="status"in i&&"number"==typeof i.status?i.status:void 0,o="sourceId"in e&&"string"==typeof e.sourceId?e.sourceId:void 0,r={message:(a=i.message,a.replace(/([?&]key=)[^&\s]+/g,"$1…")),status:s,sourceId:o,cause:i};var a;const n="body"in i&&i.body instanceof Blob&&isJSON(i.body)&&i.body;return s&&n?readAPIError(n).then(({apiErrorCode:e,apiMessage:i})=>toRequestError({...r,message:i?`${r.message}: ${i}`:r.message,apiErrorCode:e},t)):toRequestError(r,t)})(e,t?"STYLE_LOAD_FAILED":"INTERNAL");if(!(o instanceof Promise||this.pendingError))return void s(o);const r=(this.pendingError??Promise.resolve()).then(()=>o).then(s).catch(e=>console.error(e));this.pendingError=r,r.then(()=>{this.pendingError===r&&(this.pendingError=void 0)})}),this.mapLibreMap.on("webglcontextlost",e=>this.notifyErrorHandlers(new TomTomMapError("The browser lost the WebGL context the map draws with.",{code:"WEBGL_CONTEXT_LOST",cause:e.originalEvent}))),this.moduleSourcesAndLayers=ModuleSourcesAndLayers.for(this.mapLibreMap),this.styleLoadInFlight=this.initialStyleLoad(),this._eventsProxy=new EventsProxy(this.mapLibreMap,this._params?.events),s=this.mapLibreMap,o=this._params.attribution,r=()=>this._styleLightDarkTheme,s.addControl(new AttributionLogosControl(o,r))}initialStyleLoad(){const e=this._params.style;return new Promise(t=>this.onStyleLoadSettled(()=>{this.loadedStyleInput=e,this.styleRequestSequence?this.unfinishedStyle={}:this.handleStyleData(),t()},e=>{this.styleGivenToMapLibre=void 0,this.styleRequestSequence||this.failStyleLoad(e),t()}))}onStyleLoadSettled(e,t){const i=()=>{this.failStyleLoadInFlight=void 0,this.recordStyleLayers(),e()};this.failStyleLoadInFlight=e=>{this.failStyleLoadInFlight=void 0,this.mapLibreMap.off("style.load",i),t(e)},this.mapLibreMap.once("style.load",i)}failStyleLoad(e){this.styleLoadError=e;for(const t of this.styleLoadFailureHandlers.slice())t(e)}get _styleLoadError(){return this.styleLoadError}_onStyleLoadFailure(e){return addHandler(this.styleLoadFailureHandlers,e)}async applyStyle(e,t){if(await this.notifyHandlers("onStyleAboutToChange",e,t),this.isSuperseded(t))return;if(await(this.styleLoadInFlight?.catch(()=>{})),this.isSuperseded(t))return;const i=this.loadIntoMapLibre(!e.resetState);this.styleLoadInFlight=i;try{await i}catch(s){if(!this.isSuperseded(t))return void(await this.settleFailedLoad(s,t))}finally{this.styleLoadInFlight===i&&(this.styleLoadInFlight=void 0)}if(this.isSuperseded(t))this.unfinishedStyle={context:e};else{try{await this.handleStyleData(e,t)}catch(s){console.error(s)}this.isSuperseded(t)||this.moduleSourcesAndLayers.dropUnadopted()}}async settleFailedLoad(e,t){if(this.restoreLoadedStyleInput(),this.unfinishedStyle){if(await this.handleStyleData(this.unfinishedStyle.context,t),this.isSuperseded(t))return;this.moduleSourcesAndLayers.dropUnadopted()}else e instanceof TomTomMapError&&this.failStyleLoad(e);throw e}async loadIntoMapLibre(e){const t=this._params.style,i=buildStyleInput(this._params);if(i===this.styleGivenToMapLibre)return this.loadedStyleInput=t,void(this.styleDataUnannounced=!0);const s=this.styleGivenToMapLibre;this.styleGivenToMapLibre=i,await new Promise((o,r)=>{this.onStyleLoadSettled(()=>{this.loadedStyleInput=t,o()},e=>{this.styleGivenToMapLibre=s,r(e)}),this.mapLibreMap.setStyle(i,void 0===s?{validate:!1,diff:!1}:{validate:!1,transformStyle:(t,i)=>this.moduleSourcesAndLayers.carryInto(e?t:void 0,i)})})}isSuperseded(e){return e!==this.styleRequestSequence}restoreLoadedStyleInput(){void 0!==this.loadedStyleInput&&(this._params={...this._params,style:this.loadedStyleInput},this._styleLightDarkTheme=getStyleLightDarkTheme(this.loadedStyleInput))}fitCanvasToContainer(){if(this.mapLibreMap._removed)return;const e=this.mapLibreMap.getCanvas(),t=this.mapLibreMap.getContainer();e.clientWidth===t.clientWidth&&e.clientHeight===t.clientHeight||this.mapLibreMap.resize()}recordStyleLayers(){this.styleLoads++,this.styleLayerIds=new Set(this.mapLibreMap.getStyle().layers.map(e=>e.id).filter(e=>!this.moduleSourcesAndLayers.isCarried(e)))}_isStyleLayer(e){return this.styleLayerIds.has(e)}get _styleLoads(){return this.styleLoads}async notifyHandlers(e,t,i){const s=[...this.styleChangeHandlers].sort((e,t)=>(e.priority??0)-(t.priority??0));for(const r of s){if(void 0!==i&&this.isSuperseded(i))return;try{await(r[e]?.(t))}catch(o){console.error(o)}}}_setTomTomUserAgent(e){this._updateRequestParams({"tomtom-user-agent":e})}_updateRequestParams(e){this._params={...this._params,...e},this.mapLibreMap.setTransformRequest(transformRequest(this._params))}_setLanguage(e){const t=(e=>{const t=labelFieldExceptions[e]??`name_${e.split("-")[0]}`;return"name"===t?["get","name"]:["coalesce",["get",t],["get","name"]]})(e);for(const i of this.mapLibreMap.getStyle().layers){const e="symbol"===i.type&&this._isStyleLayer(i.id)?localizedLayerTextField(i,t):void 0;e&&this.mapLibreMap.setLayoutProperty(i.id,"text-field",e,{validate:!1})}}setLanguage(e){if(e===this._params.language)return;const t=trafficIncidentLanguage(this._params.language)!==trafficIncidentLanguage(e);this._updateRequestParams({language:e}),this.applyLanguage(t)}applyLanguage(e){this.mapReady?(this._params.language&&this._setLanguage(this._params.language),e&&reloadTiles(this.mapLibreMap,["vectorTilesIncidents"])):this.incidentTilesReloadPending||=e}setGeopoliticalView(e){e!==this._params.geopoliticalView&&(this._updateRequestParams({geopoliticalView:e}),this.reloadVectorTiles())}reloadVectorTiles(){this.mapReady?reloadTiles(this.mapLibreMap,vectorTileSourceIds(this.mapLibreMap)):this.vectorTilesReloadPending=!0}updateEventsConfig(e){this._eventsProxy.updateConfig(e)}getBBox(){const[[e,t],[i,s]]=this.mapLibreMap.getBounds().toArray();return[e,t,i,s]}async handleStyleData(e,t){this.unfinishedStyle=void 0;const{layers:i}=this.mapLibreMap.getStyle();for(const o of layersOfSources(i,["vectorTilesIncidents","vectorTilesFlow","hillshade"]))this.mapLibreMap.setLayoutProperty(o.id,"visibility","none",{validate:!1});const s=buildings3DExtrusionLayers(i);((e,t)=>{for(const i of t)void 0===i.layout?.["fill-extrusion-rounded-corner-distance"]&&e.setLayoutProperty(i.id,"fill-extrusion-rounded-corner-distance",1,{validate:!1})})(this.mapLibreMap,s),((e,t)=>{for(const i of t){const t=i.paint?.[COLOR]??"#000000";if(isWrapped(t))continue;const s=wrapZoomFreeParts(t,withBuildingStates);void 0!==s&&e.setPaintProperty(i.id,COLOR,s)}})(this.mapLibreMap,s),((e,t,i)=>{const s=pendingPinCategoriesSprites.get(i);if(s&&(i.off("styledata",s),pendingPinCategoriesSprites.delete(i)),i.getSprite().some(e=>"pinCategories"===e.id))return;const o=new URLSearchParams;setApiKeyParameter(o,e.apiKey),o.set("poi",`poi_${t}`),o.set("apiVersion","1"),o.set("apiChannel","preview");const r=()=>i.addSprite("pinCategories",`${e.commonBaseURL}/maps/orbis/assets/sprites/2.*/sprite?${o}`,{validate:!1});if(i.style.imageManager.isLoaded())return void r();const a=()=>{i.style.imageManager.isLoaded()&&(i.off("styledata",a),pendingPinCategoriesSprites.delete(i),r())};pendingPinCategoriesSprites.set(i,a),i.on("styledata",a)})(this._params,this._styleLightDarkTheme,this.mapLibreMap),this._params.language&&this._setLanguage(this._params.language),this.mapReady=!0,this.styleDataUnannounced&&(this.styleDataUnannounced=!1,this.mapLibreMap.fire("styledata",{dataType:"style"})),this.runPendingTileReloads(),e&&await this.notifyHandlers("onStyleChanged",e,t)}runPendingTileReloads(){const e=[...this.vectorTilesReloadPending?vectorTileSourceIds(this.mapLibreMap):[],...this.incidentTilesReloadPending?["vectorTilesIncidents"]:[]];this.vectorTilesReloadPending=!1,this.incidentTilesReloadPending=!1,reloadTiles(this.mapLibreMap,e)}addStyleChangeHandler(e){return addHandler(this.styleChangeHandlers,e)}addCustomLayer(e,t={}){return new CustomLayer(this,e,t)}addErrorHandler(e){return addHandler(this.errorHandlers,e)}notifyErrorHandlers(e){if(this.errorHandlers.length)for(const i of this.errorHandlers.slice())try{i(e)}catch(t){console.error(t)}else console.error(e)}},terrainKnobCatalogue=/* @__PURE__ */withIds({"hillshade.visible":{kind:"toggle",description:"The hillshade: light and shadow on the map surface that reveal the relief at any pitch.",default:!1},"hillshade.method":{kind:"enum",description:"How the relief is shaded: standard (one light), basic, igor (softer), combined, or multidirectional (four lights fanned over 135° around `hillshade.light.direction`).",options:hillshadeMethods},"hillshade.light.direction":{kind:"number",description:"Direction the light comes from, in degrees clockwise from the top of the screen, or from north with `hillshade.light.alignment` at `map` (335 while unset, as the style has it).",range:{min:0,max:359,step:1,bounds:"hard"}},"hillshade.light.altitude":{kind:"number",description:"Height of the light above the horizon, in degrees (0 = sunset, 90 = noon); lower casts longer shadows. Used by the basic, combined and multidirectional methods.",range:{min:0,max:90,step:1,bounds:"hard"}},"hillshade.light.alignment":{kind:"enum",description:"What `hillshade.light.direction` is measured from: viewport (the top of the screen, turning with the camera) or map (north, staying on the same slopes as the map rotates).",options:hillshadeLightAlignments},"hillshade.intensity":{kind:"number",description:"Strength of the shading (0 = flat); it raises nothing. The standard styles ramp it to zero by zoom 13; setting it replaces the ramp with a constant.",range:UNIT_RANGE},"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"}},"hillshade.colors.shaded":{kind:"color",description:"Colour of the slopes facing away from the light."},"hillshade.colors.lit":{kind:"color",description:"Colour of the slopes facing the light."},"hillshade.colors.steep":{kind:"color",description:"Colour accentuating the steepest terrain. Used by the standard method only."},"elevation.visible":{kind:"toggle",description:"The 3D surface, raised to the elevation data or flattened. Unset: flat, unless the style or MapLibre code raised a terrain of its own."},"elevation.exaggeration":{kind:"number",description:"Vertical scale of the 3D surface this module raises, `1` being true elevation; kept while `elevation.visible` is off. With it unset, a terrain the style or MapLibre code raised keeps its own.",range:{min:.5,max:3,step:.1,bounds:"hard-min"},default:1}}),terrainKnobIds=/* @__PURE__ */terrainKnobCatalogue.map(({id:e})=>e),TerrainModule=class TerrainModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,TerrainModule,()=>new TerrainModule(e,t),t,{sourceId:"hillshade",part:"terrain"})}constructor(e,t){super(e,t)}_initSourcesWithLayers(){const e=styleSourceWithLayers(this.mapLibreMap,"hillshade",TerrainModule.name);return this.captureMapTerrain(),{hillshade:e}}captureMapTerrain(){const e=this.mapLibreMap.getTerrain();"hillshade-terrain"!==e?.source&&(this.mapTerrain=e)}_applyConfig(e){return this.showHillshade(e?.hillshade?.visible??!1),hillshadeLook.apply(this.tomtomMap,e),this.showElevation(e?.elevation?.visible,e?.elevation?.exaggeration??1),e}_knobValue(e){return super._knobValue(e)??hillshadeLook.valueOf(this.tomtomMap,e)}setHillshadeVisible(e){this.showHillshade(e),this.storeConfig({hillshade:{...this.config?.hillshade,visible:e}})}isHillshadeVisible(){return this.config?.hillshade?.visible??!1}setElevationVisible(e){this.showElevation(e,this.config?.elevation?.exaggeration??1),this.storeConfig({elevation:{...this.config?.elevation,visible:e}})}isElevationVisible(){return this.config?.elevation?.visible??null!==this.mapLibreMap.getTerrain()}get events(){return this.lifecycleEvents()}showHillshade(e){this.tomtomMap.mapReady&&this.sourcesWithLayers.hillshade.setLayersVisibleThrough(this.visibilityComposer,"terrain.hillshade.visible",e)}showElevation(e,t){this.tomtomMap.mapReady&&(void 0===e||this.overridesMapTerrain||this.captureMapTerrain(),void 0===e?this.overridesMapTerrain&&this.setMapTerrain(this.mapTerrain):e?(new TomTomMapSource("hillshade-terrain",this.sourcesWithLayers.hillshade.source.spec).ensureAddedToMap(this.mapLibreMap),this.setMapTerrain({source:"hillshade-terrain",exaggeration:t})):this.setMapTerrain(null),this.overridesMapTerrain=void 0!==e)}setMapTerrain(e){isEqual(this.mapLibreMap.getTerrain(),e)||this.mapLibreMap.setTerrain(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",metrics:{congestionLevel:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},speed:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},travelTime:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},freeFlowSpeed:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"predefinedRange"}},networkLength:{palette:"trafficLight",height:{maxMeters:1e3,minMeters:0,scaleMode:"currentRange"}}},regionPolygon:{fill:{style:"filled",opacity:0},line:{opacity:.5,width:2}}},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}},paletteScaleMode=e=>"networkLength"===e?"currentRange":"predefinedRange",getActiveMetric=e=>e?.activeMetric??AREA_ANALYTICS_DEFAULTS.activeMetric,resolveColorStops=(e,t)=>{if(t?.colorStops?.stops.length)return t.colorStops;const i=PALETTE_COLORS[t?.palette??AREA_ANALYTICS_DEFAULTS.metrics[e].palette],s=(e=>"speed"===e||"freeFlowSpeed"===e)(e)?[...i].reverse():i;return{scaleMode:paletteScaleMode(e),stops:s.map((e,t)=>({value:t/(s.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)=>partBeforeLayerIDOf(e?.beforeLayerConfig,t,beforeLayerIDOf(DEFAULT_BEFORE_LAYER$1[t])),interpolationStops=e=>[...e].sort(([e],[t])=>e-t).filter(([e],t,i)=>i[t+1]?.[0]!==e).flat(),metricRange=(e,t,i)=>"currentRange"===t?i??DEFAULT_METRIC_RANGES[e]:DEFAULT_METRIC_RANGES[e],buildColorExpression$1=(e,t,i)=>{const{scaleMode:s,stops:o}=resolveColorStops(e,t);let r;if("predefinedRange"===s||"currentRange"===s){const{min:t,max:a}=metricRange(e,s,i);r=o.map(({value:e,color:i})=>[t+e/100*(a-t),i])}else r=o.map(({value:e,color:t})=>[e,t]);return["interpolate",["linear"],["get",e],...interpolationStops(r)]},buildHeatmapColorExpression=(e,t)=>{const{scaleMode:i,stops:s}=resolveColorStops(e,t);let o;if("predefinedRange"===i||"currentRange"===i)o=s.map(({value:e,color:t})=>[.3+e/100*.7,t]);else{const e=Math.min(...s.map(e=>e.value)),t=Math.max(...s.map(e=>e.value))-e||1;o=s.map(({value:i,color:s})=>[.3+(i-e)/t*.7,s])}return["interpolate",["linear"],["heatmap-density"],...interpolationStops([[0,"rgba(0,0,0,0)"],...o])]},buildHeightExpression=(e,t,i)=>{const s=AREA_ANALYTICS_DEFAULTS.metrics[e].height,o=t?.minMeters??s.minMeters,r=["coalesce",["get",e],0];if("raw"===t?.scaleMode){const i=t.metersPerUnit??1;return["max",o,["*","speed"===e?["-",DEFAULT_METRIC_RANGES.speed.max,r]:r,i]]}const a=t?.maxMeters??s.maxMeters,n=t?.scaleMode??s.scaleMode,{min:l,max:c}=metricRange(e,n,i);return["max",o,["min",a,["*",["/","speed"===e?["-",c,r]:["-",r,l],c-l||1],a]]]},buildHeatmapLayerSpec=(e,t,i)=>{const s=getActiveMetric(t),o=t?.metrics?.[s],{min:r,max:a}=i??DEFAULT_METRIC_RANGES[s],n=r+(a-r||1);return mergeLayerOverride({id:e,type:"heatmap",beforeID:beforeIDOf(t,"heatmap"),paint:{"heatmap-weight":["interpolate",["linear"],["get",s],r,0,n,1],"heatmap-intensity":/* @__PURE__ */zoomRamp(10,.5,14,2,16,4),"heatmap-color":buildHeatmapColorExpression(s,o),"heatmap-radius":/* @__PURE__ */zoomRamp(4,1,8,3,12,35,14,80,16,100),"heatmap-opacity":/* @__PURE__ */zoomRamp(4,.8,13,.8,17,0)}},t?.layers?.heatmap)},buildCellFillLayerSpec=(e,t,i,s,o)=>{const r=getActiveMetric(t);return mergeLayerOverride({id:e,type:"fill",beforeID:beforeIDOf(t,s),paint:{"fill-color":buildColorExpression$1(r,t?.metrics?.[r],i),"fill-opacity":.6}},o)},buildCellExtrusionLayerSpec=(e,t,i,s,o)=>{const r=getActiveMetric(t),a=t?.metrics?.[r];return mergeLayerOverride({id:e,type:"fill-extrusion",beforeID:beforeIDOf(t,s),paint:{"fill-extrusion-color":buildColorExpression$1(r,a,i),"fill-extrusion-height":buildHeightExpression(r,a?.height,i),"fill-extrusion-base":0,"fill-extrusion-opacity":.75}},o)},buildHexFillLayerSpec=(e,t,i)=>buildCellFillLayerSpec(e,t,i,"hexgrid-2d",t?.layers?.hexgridFill),buildHexExtrusionLayerSpec=(e,t,i)=>buildCellExtrusionLayerSpec(e,t,i,"hexgrid-3d",t?.layers?.hexgridExtrusion),buildSquareFillLayerSpec=(e,t,i)=>buildCellFillLayerSpec(e,t,i,"square-2d",t?.layers?.squareFill),buildSquareExtrusionLayerSpec=(e,t,i)=>buildCellExtrusionLayerSpec(e,t,i,"square-3d",t?.layers?.squareExtrusion),resolveRegionConfig=e=>{const t=AREA_ANALYTICS_DEFAULTS.regionPolygon;return{color:e?.color,fill:{opacity:clampFactor(e?.fill?.opacity,UNIT_RANGE,t.fill.opacity)},line:{opacity:clampFactor(e?.line?.opacity,UNIT_RANGE,t.line.opacity),width:Math.max(0,e?.line?.width??t.line.width)}}},buildRegionFillLayerSpec=(e,t,i)=>{const{color:s,fill:o}=resolveRegionConfig(t?.regionPolygon);return mergeLayerOverride({id:e,type:"fill",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"fill-color":s??themeContrastColor(i),"fill-opacity":o.opacity}},t?.layers?.regionFill)},buildRegionLineLayerSpec=(e,t,i)=>{const{color:s,line:o}=resolveRegionConfig(t?.regionPolygon);return mergeLayerOverride({id:e,type:"line",beforeID:mapStyleLayerIDs.lowestLabel,paint:{"line-color":s??themeContrastColor(i),"line-opacity":o.opacity,"line-width":o.width}},t?.layers?.regionLine)},activeEventStateWithin=e=>e?["all",toExpressionFilter(e),hasActiveEventState]:hasActiveEventState,buildPolygonOutlineLayerSpec=(e,t,i,s)=>mergeLayerOverride({id:e,type:"line",beforeID:t,...void 0!==i?.minzoom&&{minzoom:i.minzoom},...void 0!==i?.maxzoom&&{maxzoom:i.maxzoom},filter:activeEventStateWithin(i?.filter),paint:{"line-color":"#ffffff","line-width":["case",isClickEventState,3,2],"line-opacity":["case",isClickEventState,1,.8]}},s),buildHexOutlineLayerSpec=(e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"hexgrid-2d"),t?.layers?.hexgridFill,t?.layers?.hexgridOutline),buildSquareOutlineLayerSpec=(e,t)=>buildPolygonOutlineLayerSpec(e,beforeIDOf(t,"square-2d"),t?.layers?.squareFill,t?.layers?.squareOutline),buildExtrusionHighlightLayerSpec=(e,t)=>{const i=e.paint?.["fill-extrusion-height"];return mergeLayerOverride({...e,filter:activeEventStateWithin(e.filter),paint:{...e.paint,"fill-extrusion-color":"#ffffff","fill-extrusion-height":(s=i,mapNumericValue(s,e=>e+.5,e=>["+",e,.5])??i),"fill-extrusion-opacity":.6}},t);var s},buildHexExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildHexExtrusionLayerSpec(e,t,i),t?.layers?.hexgridExtrusionHighlight),buildSquareExtrusionHighlightLayerSpec=(e,t,i)=>buildExtrusionHighlightLayerSpec(buildSquareExtrusionLayerSpec(e,t,i),t?.layers?.squareExtrusionHighlight),INCIDENT_HIGHLIGHT_WIDTH_FACTOR_RANGE={min:1,max:1.8,step:.1,bounds:"hard"},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],buildColorExpression=e=>/* @__PURE__ */matchMagnitudeOfDelay({...e,fallback:e.major}),INNER_PATTERN=/* @__PURE__ */matchMagnitudeOfDelay({unknown:"traffic-incidents-no_delay-pattern",indefinite:"traffic-incidents-road_closed-pattern",fallback:""}),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],isUnfocused=["all",["==",["feature-state","focused"],!1],["!",hasActiveEventState]],haloOpacity=["case",isFocusedOrActive,1,0],highlightWidth=(e,t)=>null===t?e:scaledWhen(isFocusedOrActive,e,t),unfocusedScaled=(e,t)=>scaledWhen(isUnfocused,e,t),buildCanonicalIncidentLineLayers=(e,t,i,s,o,r)=>{const a=s?.widthFactor??null,n=s?.unfocusedOpacityFactor??1,l=(void 0!==r?.opacity||1!==n)&&{"line-opacity":unfocusedScaled(clampFactor(r?.opacity,UNIT_RANGE),n)},c=[];return null!==s&&c.push(mergeLayerOverride({id:`${e}-highlight-halo`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":s.outlineColor,"line-width":HALO_WIDTH,"line-blur":0,"line-opacity":haloOpacity},beforeID:t},o?.highlightHalo)),c.push(mergeLayerOverride({id:`${e}-outline`,type:"line",minzoom:6,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpression(i.outline),"line-width":highlightWidth(OUTLINE_WIDTH,a),...l},beforeID:t},o?.outline),mergeLayerOverride({id:`${e}-inner-solid`,type:"line",minzoom:6,filter:severitySolidFilter,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":buildColorExpression(i.inner),"line-width":highlightWidth(INNER_WIDTH,a),...l},beforeID:t},o?.innerSolid),mergeLayerOverride({id:`${e}-inner-chevron`,type:"line",minzoom:12,filter:severitySolidFilter,layout:{"line-cap":"butt","line-join":"round"},paint:{"line-pattern":"tt-traffic-incident-direction-chevron","line-width":highlightWidth(INNER_WIDTH,a),...l},beforeID:t},o?.innerChevron),mergeLayerOverride({id:`${e}-inner-pattern`,type:"line",minzoom:6,filter:severityDashedFilter,layout:{"line-cap":"round","line-join":"round"},paint:{"line-pattern":INNER_PATTERN,"line-width":highlightWidth(INNER_WIDTH,a),...l},beforeID:t},o?.innerPattern)),c},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",""],delayDeclutter=e=>["any",["!",["has","delayInSeconds"]],["step",["zoom"],[">",["get","delayInSeconds"],900],e,[">",["get","delayInSeconds"],600],e+1,[">",["get","delayInSeconds"],300],e+2,!0]],INCIDENT_MARKER_FILTER=["all",["!=",["get","magnitudeOfDelay"],"indefinite"],
4
+ /* @__PURE__ */delayDeclutter(14)],JAM_MARKER_FILTER=["all",["==",["get","category"],"jam"],["!=",["get","magnitudeOfDelay"],"unknown"],["!=",["get","magnitudeOfDelay"],"indefinite"],["!=",["get","delayInSeconds"],0],
5
+ /* @__PURE__ */delayDeclutter(13)],CLOSED_ROAD_FILTER=["==",["get","magnitudeOfDelay"],"indefinite"],DELAY_MINUTES=["round",["/",["to-number",["get","delayInSeconds"]],60]],JAM_ICON=["concat","traffic-jam-",["get","magnitudeOfDelay"],["case",["any",["<",DELAY_MINUTES,10],["==",["%",DELAY_MINUTES,60],0]],"-small",["<",DELAY_MINUTES,60],"-medium","-large"]],JAM_TEXT=["case",["!",["has","delayInSeconds"]],"",["<=",["get","delayInSeconds"],60],"1 min",[">=",DELAY_MINUTES,60],["concat",["to-string",["floor",["/",DELAY_MINUTES,60]]]," hr",["case",["==",["%",DELAY_MINUTES,60],0],"",["concat"," ",["to-string",["%",DELAY_MINUTES,60]]," min"]]],["concat",["to-string",DELAY_MINUTES]," min"]],SORT_KEY=["case",["has","delayInSeconds"],["*",-1,["get","delayInSeconds"]],0],buildCanonicalIncidentSymbolLayers=(e,t,i,s,o=1)=>{const r=unfocusedScaled(1,o),a=1!==o&&{"icon-opacity":r},n=1!==o&&{"text-opacity":r};return[mergeLayerOverride({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},...a&&{paint:a},beforeID:t},i?.incidentMarker),mergeLayerOverride({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":inTypeface(["NotoSans-CondensedBold"],s),"text-offset":[2.7,-.75],"text-size":JAM_TEXT_SIZE,"symbol-sort-key":SORT_KEY},paint:{"text-color":"hsl(210, 30%, 14%)",...a,...n},beforeID:t},i?.jamMarker),mergeLayerOverride({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},...a&&{paint:a},beforeID:t},i?.closedRoadMarker)]},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"},DELAY_MINUTES_RANGE={min:0,max:120,step:5,bounds:"hard-min"},roadCategoriesFilter=/* @__PURE__ */valuesFilterKnobs("filters.roadCategories","road categories",roadCategories),roadSubCategoriesFilter=/* @__PURE__ */(()=>/* @__PURE__ */valuesFilterKnobs("filters.roadSubCategories","street and service road kinds",[...streetRoadSubCategories,...serviceRoadSubCategories]))(),roadFilterKnobDefinitions=/* @__PURE__ */(()=>({"filters.roadCategories.show":roadCategoriesFilter.show,"filters.roadCategories.values":roadCategoriesFilter.values,"filters.roadSubCategories.show":roadSubCategoriesFilter.show,"filters.roadSubCategories.values":roadSubCategoriesFilter.values}))(),incidentCategoriesFilter=/* @__PURE__ */valuesFilterKnobs("filters.incidentCategories","incident categories",fullTrafficIncidentCategories),magnitudesFilter=/* @__PURE__ */valuesFilterKnobs("filters.magnitudes","delay magnitudes",indexedMagnitudes),flowKnobDefinitions=/* @__PURE__ */(()=>({visible:{kind:"toggle",description:"The traffic flow lines; hidden until shown.",default:!1},...roadFilterKnobDefinitions,"filters.roadClosures":{kind:"enum",description:"`only` draws just the closed roads, `all-except` the flow on every road but them.",options:filterShowModes},"colors.free":{kind:"color",description:"Flow colour of free-flowing roads; its outline follows."},"colors.slow":{kind:"color",description:"Flow colour of slow traffic; its outline follows."},"colors.queueing":{kind:"color",description:"Flow colour of queueing traffic; its outline follows."},"colors.stationary":{kind:"color",description:"Flow colour of stationary traffic; its outline follows."},"colors.closed":{kind:"color",description:"Outline colour of closed roads."},widthFactor:{kind:"factor",description:"Width of the flow lines.",range:WIDE_FACTOR_RANGE,default:1},opacityFactor:{kind:"factor",description:"Opacity of the flow lines and their outlines, over the style's own.",range:UNIT_RANGE,default:1}}))(),incidentsKnobDefinitions=/* @__PURE__ */(()=>({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`."},timeValidity:{kind:"enums",description:"Which incidents the tiles bring: `present` ones under way, `future` ones planned. A change reloads the incident tiles.",options:trafficIncidentTimeValidities,default:["present"]},...roadFilterKnobDefinitions,"filters.incidentCategories.show":incidentCategoriesFilter.show,"filters.incidentCategories.values":incidentCategoriesFilter.values,"filters.magnitudes.show":magnitudesFilter.show,"filters.magnitudes.values":magnitudesFilter.values,"filters.delays.required":{kind:"toggle",description:"Drop the incidents that report no delay.",default:!1},"filters.delays.minMinutes":{kind:"number",description:"Drop the incidents delaying traffic by less than this many minutes; those that report no delay stay unless `filters.delays.required`.",range:DELAY_MINUTES_RANGE},"colors.minor":{kind:"color",description:"Incident line colour for minor delays; its outline follows."},"colors.moderate":{kind:"color",description:"Incident line colour for moderate delays; its outline follows."},"colors.major":{kind:"color",description:"Incident line colour for major delays; its outline follows."},"colors.closed":{kind:"color",description:"Incident outline colour for closed roads."},widthFactor:{kind:"factor",description:"Width of the incident lines.",range:WIDE_FACTOR_RANGE,default:1},opacityFactor:{kind:"factor",description:"Opacity of the incident lines and their outlines, over the style's own; the icons stay opaque.",range:UNIT_RANGE,default:1}}))(),incidentDetailsKnobDefinitions={visible:{kind:"toggle",description:"The incident layers; hiding them keeps the shown incidents.",default:!0},"highlight.outline.color":{kind:"color",description:"Colour of the outline beneath the focused, hovered or clicked incidents. Unset: black on light styles, white on dark."},"highlight.line.widthFactor":{kind:"factor",description:"Multiplier on the line width of the focused, hovered or clicked incidents; `1` keeps the outline alone.",range:INCIDENT_HIGHLIGHT_WIDTH_FACTOR_RANGE,default:1.6},"highlight.unfocusedOpacityFactor":{kind:"factor",description:"Multiplier on the opacity of the incidents outside the focus set while a focus is active, lines, icons and text alike; `1` keeps them as they are.",range:UNIT_RANGE,default:1},"line.opacity":{kind:"number",description:"Opacity of the incident lines; the markers and the outline of a highlighted incident stay opaque.",range:UNIT_RANGE,default:1}},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 line colour of the region boundary. Unset: black on light styles, white on dark."},"regionPolygon.fill.style":{kind:"enum",description:"`filled` fills the region; `inverted` fills the world outside it instead.",options:/* @__PURE__ */everyOf()(["filled","inverted"]),default:AREA_ANALYTICS_DEFAULTS.regionPolygon.fill.style},"regionPolygon.fill.opacity":{kind:"number",description:"Fill opacity of the region.",range:UNIT_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.fill.opacity},"regionPolygon.line.opacity":{kind:"number",description:"Opacity of the region boundary line.",range:UNIT_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.line.opacity},"regionPolygon.line.width":{kind:"number",description:"Width of the region boundary line, in pixels.",range:OUTLINE_WIDTH_RANGE,default:AREA_ANALYTICS_DEFAULTS.regionPolygon.line.width}}))(),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.metrics[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.metrics[e].height.scaleMode}),"height.maxMeters":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.metrics[e].height.maxMeters}),"height.minMeters":e=>({kind:"number",description:`Height of the lowest \`${e}\` cells, in metres.`,range:HEIGHT_METERS_RANGE,default:AREA_ANALYTICS_DEFAULTS.metrics[e].height.minMeters}),"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[.../* @__PURE__ */withIds(areaAnalyticsKnobDefinitions),...areaAnalyticsMetricKeys.flatMap(t=>e.map(e=>({id:`metrics.${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),metricValuesBy=e=>({speed:e("speed"),freeFlowSpeed:e("freeFlowSpeed"),congestionLevel:e("congestionLevel"),travelTime:e("travelTime"),networkLength:e("networkLength")}),tileValueOf=(e,t)=>e[t]??0,metricValuesOf=e=>metricValuesBy(t=>tileValueOf(e,t)),tilesToPointFeatures=e=>({type:"FeatureCollection",features:e.features.flatMap(e=>e.properties?.tiledData?.tiles??[]).map((e,t)=>{const[i,s]=e.tileCentre,o=`tile-${t}-${i}-${s}`;return{type:"Feature",id:o,geometry:toPointGeometry([i,s]),properties:{id:o,...metricValuesOf(e)}}})}),hexWidthOf=(e,t)=>{const[i,,s]=e,o=bboxCenter(e)[1];return 2*t/distance([i,o],[s,o])*bboxLongitudeSpan(e)},turfHexLayout=(e,t)=>{const[i,s,,o]=e,r=bboxCenter(e)[0],a=bboxLongitudeSpan(e),n=hexWidthOf(e,t),l=2*t/distance([r,s],[r,o])*(o-s),c=n/2,d=Math.sqrt(3)/2*l,u=3/4*n,h=Math.floor((a-n)/(n-c/2)),p=(h*u-c/2-a)/2-c/2+u/2,y=Math.floor((o-s-d)/d),f={shape:"hex",origin:[i-p,s+(o-s-y*d)/2],width:n,height:l};return{lattice:f,cellOf:e=>latticeCellOf(f,withNearestLongitude(f.origin,e)),turfIndexOf:({column:e,row:t})=>e>=0&&e<=h&&t>=(1&e)&&t<=y?e*(y+1)-Math.floor(e/2)+t-(1&e):void 0}},turfSquareLayout=(e,t)=>{const[i,s,,o]=e,r=bboxLongitudeSpan(e),a=convertLength(t,"kilometers","degrees"),n=Math.floor(r/a),l=Math.floor((o-s)/a),c={shape:"square",origin:[i+(r-n*a)/2+a/2,s+(o-s-l*a)/2+a/2],width:a,height:a};return{lattice:c,cellOf:e=>{const[t,i]=withNearestLongitude(c.origin,e);return latticeCellOf(c,[t-1e-9,i-1e-9])},turfIndexOf:({column:e,row:t})=>e>=0&&e<n&&t>=0&&t<l?e*l+t:void 0}},hexLongitudePadding=(e,t)=>2/3*hexWidthOf(e,t),paddedBy=(e,t)=>[e[0]-t,e[1]-.005,e[2]+t,e[3]+.005],tilesToGridFeatures=(e,t,{layoutOf:i,longitudePaddingOf:s},o)=>({type:"FeatureCollection",features:e.features.flatMap((e,r)=>{const a=e.properties?.tiledData?.tiles??[],n=a.length?bboxFromGeoJSON(e):void 0;if(!n)return[];const l=s?.(paddedBy(n,.005),t)??0,c=paddedBy(n,Math.max(.005,l));return((e,{lattice:t,cellOf:i,turfIndexOf:s},o)=>{const r=/* @__PURE__ */new Map;for(const a of e){const e=i(a.tileCentre),t=s(e);if(void 0===t)continue;const o=r.get(t);if(o){for(const e of areaAnalyticsMetricKeys)o.sums[e]+=tileValueOf(a,e);o.count++}else r.set(t,{cell:e,sums:metricValuesOf(a),count:1})}return[...r.entries()].sort(([e],[t])=>e-t).map(([e,{cell:i,sums:s,count:r}])=>{const a=`${o}-${e}`,n=metricValuesBy(e=>((e,t,i)=>roundToDecimals(t/i,"travelTime"===e?1:0))(e,s[e],r));return{type:"Feature",id:a,geometry:latticeCellPolygon(t,i),properties:{id:a,...n}}})})(a,i(c,t),`${o}-${r}`)})}),tilesToHexFeatures=(e,t=.25)=>tilesToGridFeatures(e,t,{layoutOf:turfHexLayout,longitudePaddingOf:hexLongitudePadding},"hex"),tilesToSquareFeatures=(e,t=.5)=>tilesToGridFeatures(e,t,{layoutOf:turfSquareLayout},"square"),isRegionInverted=e=>"inverted"===(e?.regionPolygon?.fill?.style??AREA_ANALYTICS_DEFAULTS.regionPolygon.fill.style),dataSources=["hexgrid","square","heatmap"],TrafficAreaAnalyticsModule=class TrafficAreaAnalyticsModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new TrafficAreaAnalyticsModule(e,t)}constructor(e,t){super(e,t),this.lastAnalytics=null,this.shownFeaturesHandlers=[]}_initSourcesWithLayers(e,t){const i=this.instanceIndex,s=`area-analytics-heatmap-${i}`,o=`area-analytics-hexgrid-${i}`,r=`area-analytics-square-${i}`,a=`area-analytics-region-${i}`,n=`${s}-layer`,l=`${o}-fill`,c=`${o}-extrusion`,d=`${o}-outline`,u=`${o}-extrusion-highlight`,h=`${r}-fill`,p=`${r}-extrusion`,y=`${r}-outline`,f=`${r}-extrusion-highlight`,m=`${a}-fill`,g=`${a}-line`,b=this.lightDark;this.heatmapLayerSpec=buildHeatmapLayerSpec(n,e),this.hexFillLayerSpec=buildHexFillLayerSpec(l,e),this.hexExtrusionLayerSpec=buildHexExtrusionLayerSpec(c,e),this.squareFillLayerSpec=buildSquareFillLayerSpec(h,e),this.squareExtrusionLayerSpec=buildSquareExtrusionLayerSpec(p,e),this.regionFillLayerSpec=buildRegionFillLayerSpec(m,e,b),this.regionLineLayerSpec=buildRegionLineLayerSpec(g,e,b),this.hexOutlineLayerSpec=buildHexOutlineLayerSpec(d,e),this.hexExtrusionHighlightLayerSpec=buildHexExtrusionHighlightLayerSpec(u,e),this.squareOutlineLayerSpec=buildSquareOutlineLayerSpec(y,e),this.squareExtrusionHighlightLayerSpec=buildSquareExtrusionHighlightLayerSpec(f,e);const S={heatmap:new GeoJSONSourceWithLayers(this.mapLibreMap,s,[this.heatmapLayerSpec]),hexgrid:new GeoJSONSourceWithLayers(this.mapLibreMap,o,[this.hexFillLayerSpec,this.hexExtrusionLayerSpec]),square:new GeoJSONSourceWithLayers(this.mapLibreMap,r,[this.squareFillLayerSpec,this.squareExtrusionLayerSpec]),region:new GeoJSONSourceWithLayers(this.mapLibreMap,a,[this.regionFillLayerSpec,this.regionLineLayerSpec])};return this.addHighlightLayersToMap(o,r),S}_applyConfig(e){const t=this.config,i=e??{},s=Object.fromEntries(areaAnalyticsMetricKeys.map(e=>{const t=AREA_ANALYTICS_DEFAULTS.metrics[e],s=i.metrics?.[e];return[e,{...s,palette:s?.palette??t.palette,height:s?.height??t.height}]})),o={...i,activeMetric:i.activeMetric??AREA_ANALYTICS_DEFAULTS.activeMetric,displayMode:i.displayMode??AREA_ANALYTICS_DEFAULTS.displayMode,metrics:s};return this.config=o,this.applyLayerConfig(o),isEqual(o.regionPolygon,t?.regionPolygon)&&isEqual(o.layers?.regionFill,t?.layers?.regionFill)&&isEqual(o.layers?.regionLine,t?.layers?.regionLine)||this.applyRegionConfig(o,t),(o.beforeLayerConfig||t?.beforeLayerConfig)&&this.moveLayersToSpecPositions(),this.applyVisibility(o),o}moveLayersToSpecPositions(){for(const e of[this.heatmapLayerSpec,this.hexFillLayerSpec,this.hexOutlineLayerSpec,this.hexExtrusionLayerSpec,this.hexExtrusionHighlightLayerSpec,this.squareFillLayerSpec,this.squareOutlineLayerSpec,this.squareExtrusionLayerSpec,this.squareExtrusionHighlightLayerSpec])moveLayerBefore(this.mapLibreMap,e.id,e.beforeID)}discardShownData(){this.lastAnalytics=null}restoreDataAndConfigImpl(){const e=shownFeaturesOf(this.sourcesWithLayers);this.initSourcesWithLayers(this.config,!0),this.lastAnalytics?this.display(e):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.buildRegionFeatureCollection(e.features,isRegionInverted(this.config))}),emitShownFeatures(this.shownFeaturesHandlers,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 s={...this.config?.metrics};for(const o of i){const i={...s[o]};void 0===t?delete i[e]:i[e]=t,s[o]=i}this.config={...this.config,metrics:s}}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,s=this.sourcesWithLayers.hexgrid.shownFeatures.features.length>0,o=this.sourcesWithLayers.square.shownFeatures.features.length>0,r=this.sourcesWithLayers.region.shownFeatures.features.length>0;this.setLayersVisible([this.heatmapLayerSpec],"heatmap"===t&&i),this.setLayersVisible([this.hexExtrusionLayerSpec,this.hexExtrusionHighlightLayerSpec],"hexgrid-3d"===t&&s),this.setLayersVisible([this.hexFillLayerSpec,this.hexOutlineLayerSpec],"hexgrid-2d"===t&&s),this.setLayersVisible([this.squareExtrusionLayerSpec,this.squareExtrusionHighlightLayerSpec],"square-3d"===t&&o),this.setLayersVisible([this.squareFillLayerSpec,this.squareOutlineLayerSpec],"square-2d"===t&&o),this.setLayersVisible([this.regionFillLayerSpec,this.regionLineLayerSpec],r)}hideAllDataLayers(){this.setLayersVisible([this.heatmapLayerSpec,this.hexFillLayerSpec,this.hexExtrusionLayerSpec,this.hexOutlineLayerSpec,this.hexExtrusionHighlightLayerSpec,this.squareFillLayerSpec,this.squareExtrusionLayerSpec,this.squareOutlineLayerSpec,this.squareExtrusionHighlightLayerSpec,this.regionFillLayerSpec,this.regionLineLayerSpec],!1)}setLayersVisible(e,t){applyLayersVisibility(e,t,this.mapLibreMap)}addHighlightLayersToMap(e,t){addLayers([withSourceID(this.hexOutlineLayerSpec,e),withSourceID(this.hexExtrusionHighlightLayerSpec,e),withSourceID(this.squareOutlineLayerSpec,t),withSourceID(this.squareExtrusionHighlightLayerSpec,t)],this.mapLibreMap)}applyLayerConfig(e){const t=this.lastAnalytics?.properties.ranges?.[this.activeMetric],i=buildHeatmapLayerSpec(this.heatmapLayerSpec.id,e,t),s=buildHexFillLayerSpec(this.hexFillLayerSpec.id,e,t),o=buildHexExtrusionLayerSpec(this.hexExtrusionLayerSpec.id,e,t),r=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),c=buildHexOutlineLayerSpec(this.hexOutlineLayerSpec.id,e),d=buildSquareOutlineLayerSpec(this.squareOutlineLayerSpec.id,e);changeLayerProps(i,this.heatmapLayerSpec,this.mapLibreMap),changeLayerProps(s,this.hexFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.hexExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(r,this.hexExtrusionHighlightLayerSpec,this.mapLibreMap),changeLayerProps(c,this.hexOutlineLayerSpec,this.mapLibreMap),changeLayerProps(a,this.squareFillLayerSpec,this.mapLibreMap),changeLayerProps(n,this.squareExtrusionLayerSpec,this.mapLibreMap),changeLayerProps(l,this.squareExtrusionHighlightLayerSpec,this.mapLibreMap),changeLayerProps(d,this.squareOutlineLayerSpec,this.mapLibreMap),this.heatmapLayerSpec=i,this.hexFillLayerSpec=s,this.hexExtrusionLayerSpec=o,this.hexExtrusionHighlightLayerSpec=r,this.hexOutlineLayerSpec=c,this.squareFillLayerSpec=a,this.squareExtrusionLayerSpec=n,this.squareExtrusionHighlightLayerSpec=l,this.squareOutlineLayerSpec=d,this.applyFiltersToLayers()}applyRegionConfig(e,t){const i=this.lightDark,s=buildRegionFillLayerSpec(this.regionFillLayerSpec.id,e,i),o=buildRegionLineLayerSpec(this.regionLineLayerSpec.id,e,i);changeLayerProps(s,this.regionFillLayerSpec,this.mapLibreMap),changeLayerProps(o,this.regionLineLayerSpec,this.mapLibreMap),this.regionFillLayerSpec=s,this.regionLineLayerSpec=o;const r=isRegionInverted(e);this.lastAnalytics&&r!==isRegionInverted(t)&&this.sourcesWithLayers.region.show(this.buildRegionFeatureCollection(this.lastAnalytics.features,r),{automaticVisibility:!1})}applyFiltersToLayers(){const e=this.activeMetric,t=this.config?.metrics?.[e]?.filters,i=[];void 0!==t?.min&&i.push([">=",["get",e],t.min]),void 0!==t?.max&&i.push(["<=",["get",e],t.max]);for(const s of[this.hexFillLayerSpec,this.hexExtrusionLayerSpec,this.hexOutlineLayerSpec,this.hexExtrusionHighlightLayerSpec,this.squareFillLayerSpec,this.squareExtrusionLayerSpec,this.squareOutlineLayerSpec,this.squareExtrusionHighlightLayerSpec]){const e=s.filter?[toExpressionFilter(s.filter)]:[];this.mapLibreMap.setFilter(s.id,getMergedFilter("all",[...e,...i])??void 0,{validate:!1})}}buildRegionFeatureCollection(e,t){if(t&&e.length){const t="traffic-area-analytics-region-0";return{type:"FeatureCollection",features:[{...mask(featureCollection(e)),id:t,properties:{id:t}}]}}return{type:"FeatureCollection",features:e.map((e,t)=>{const i=`traffic-area-analytics-region-${t}`;return{...e,id:i,properties:{id:i}}})}}},DELAY_SECONDS=["to-number",["get","delay"]],addValuesFilter=(e,t,i,s)=>{isCompleteValuesFilter(e)&&i.push(((e,t,i)=>buildMappedValuesFilter(e,t.show,i?t.values.map(i):t.values))(t,e,s))},addCommonFilterExpressions=(e,t)=>{addValuesFilter(e.roadCategories,"road_category",t),addValuesFilter(e.roadSubCategories,"road_subcategory",t)},buildMapLibreIncidentsFilter=e=>{const t=[];addCommonFilterExpressions(e,t),addValuesFilter(e.incidentCategories,"icon_category_0",t,trafficIncidentToIconCategory),addValuesFilter(e.magnitudes,"magnitude_of_delay",t,e=>indexedMagnitudes.indexOf(e));const i=e.delays&&(({required:e,minMinutes:t=0})=>{if(t>0){const i=[">=",DELAY_SECONDS,60*t];return e?i:["any",["!",["has","delay"]],["==",["get","delay"],0],i]}return e?[">",DELAY_SECONDS,0]:null})(e.delays);return i&&t.push(i),getMergedFilter("all",t)},buildMapLibreAnyFilters=({any:e,...t},i)=>getMergedFilter("any",[t,...e??[]].map(i).filter(e=>!isNil(e))),buildMapLibreFlowFilter=e=>{const t=[];if(addCommonFilterExpressions(e,t),e.roadClosures){const i="only"===e.roadClosures?"==":"!=";t.push([i,["get","road_closure"],!0])}return getMergedFilter("all",t)},applyTrafficFilters=(e,{contributor:t,build:i},s,o,r)=>{const a=o&&i(o);(a||r&&i(r))&&((e,t,i,s)=>{for(const o of t)i.setClause(o.id,s,e)})(a??void 0,s,LayerFilterComposer.for(e),t)},FLOW_FILTERS={contributor:"traffic.flow",build:e=>buildMapLibreAnyFilters(e,buildMapLibreFlowFilter)},TrafficFlowModule=class TrafficFlowModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,TrafficFlowModule,()=>new TrafficFlowModule(e,t),t,{sourceId:"vectorTilesFlow",part:"trafficFlow"})}constructor(e,t){super(e,t)}_initSourcesWithLayers(){return this.appliedFilters??=new AppliedFilters,{trafficFlow:styleSourceWithLayers(this.mapLibreMap,"vectorTilesFlow",TrafficFlowModule.name)}}_applyConfig(e){return this._setVisible(e?.visible??!1,!1),this.appliedFilters.replace(this.tomtomMap,e?.filters,(e,t)=>applyTrafficFilters(this.tomtomMap,FLOW_FILTERS,this.sourcesWithLayers.trafficFlow._layerSpecs,e,t)),trafficFlowLook.apply(this.tomtomMap,e),e}_knobValue(e){return super._knobValue(e)??trafficFlowLook.valueOf(this.tomtomMap,e)}setVisible(e){this._setVisible(e)}_setVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficFlow.setLayersVisibleThrough(this.visibilityComposer,"trafficFlow.visible",e),t&&(this.config={...this.config,visible:e},this.emitConfigChange())}isVisible(){return this.config?.visible??!1}getRenderedFeatures(){return{trafficFlow:this.sourcesWithLayers.trafficFlow.queryRenderedFeatures().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%)"},warnedLayerIds=/* @__PURE__ */new WeakMap,readIncidentPalette=e=>{const t=new Map(e.getLayersOrder().map(e=>[e.trim(),e])),i=[],s=s=>{const o=t.get(s),r=void 0===o?void 0:e.getPaintProperty(o,"line-color");if("string"==typeof r)return r;void 0!==r&&i.push(s)},o={outline:{...FALLBACK_INCIDENT_PALETTE_outline},inner:{...FALLBACK_INCIDENT_PALETTE_inner}};for(const n of indexedMagnitudes){const e=LAYER_IDS[n],t=s(e.outline),i=s(e.inner);t&&(o.outline[n]=t),i&&(o.inner[n]=i)}const r=ofMap(warnedLayerIds,e,()=>/* @__PURE__ */new Set),a=i.filter(e=>!r.has(e));if(a.length>0){for(const e of a)r.add(e);console.warn("[TrafficIncidentDetailsModule] style layers have non-literal `line-color` (match/case/etc.); falling back to default colour for: "+a.join(", "))}return o},TrafficIncidentDetailsModule=class TrafficIncidentDetailsModule extends AbstractDataOwnedMapModule{static async create(e,t){return await waitUntilMapIsReady(e),new TrafficIncidentDetailsModule(e,t??{})}constructor(e,t){super(e,t),this.lastFocusIds=null,this.shownFeaturesHandlers=[],onStyleKnobsApplied(e,[...Object.values(incidentColorKnobIds),"labels.typeface"],()=>this.updateLayers(this.config))}buildLayerSpecs(e,t){const i=beforeLayerIDOf(t?.beforeLayerConfig??"lowestLabel"),s=((e,t)=>!1===e?null:{outlineColor:e?.outline?.color??themeContrastColor(t),widthFactor:clampFactor(e?.line?.widthFactor,INCIDENT_HIGHLIGHT_WIDTH_FACTOR_RANGE,1.6),unfocusedOpacityFactor:clampFactor(e?.unfocusedOpacityFactor,UNIT_RANGE)})(t?.highlight,this.tomtomMap.styleLightDarkTheme);return[...buildCanonicalIncidentLineLayers(e,i,readIncidentPalette(this.mapLibreMap),s,t?.layers,t?.line),...buildCanonicalIncidentSymbolLayers(e,i,t?.layers,mapTypefaceOf(this.tomtomMap),s?.unfocusedOpacityFactor)]}updateLayers(e){const{incidents:t}=this.sourcesWithLayers,i=this.buildLayerSpecs(t.sourceAndLayerIDs.sourceID,e);this.replaceSourceLayers(i,t._layerSpecs,t);const s=i.map(({id:e})=>e);t._layerSpecs.sort((e,t)=>s.indexOf(e.id)-s.indexOf(t.id)),t._updateSourceAndLayerIDs()}_initSourcesWithLayers(e,t){const i=`traffic-incident-details-${this.instanceIndex}`;return addOrUpdateImage("if-not-in-sprite","tt-traffic-incident-direction-chevron",staticImg('<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>'),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){applyLayersVisibility(this.sourcesWithLayers.incidents._layerSpecs,!1!==e?.visible,this.mapLibreMap)}applyBeforeLayer(e){const t=beforeLayerIDOf(e??"lowestLabel");for(const i of this.sourcesWithLayers.incidents.sourceAndLayerIDs.layerIDs)moveLayerBefore(this.mapLibreMap,i,t)}discardShownData(){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.sourcesWithLayers.incidents.show(e,{automaticVisibility:!1}),this.applyVisibility(this.config),emitShownFeatures(this.shownFeaturesHandlers,e)}async clear(){await this.waitUntilModuleReady(),this.clearFeatureState(),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();const{incidents:t}=this.sourcesWithLayers,i=t.shownFeatures.features.map(e=>e.properties.id).filter(e=>"string"==typeof e);if(0===i.length)return;this.lastFocusIds=e;const s=new Set(e),o=t.sourceAndLayerIDs.sourceID;for(const r of i)this.mapLibreMap.setFeatureState({source:o,id:r},{focused:s.has(r)})}clearFeatureState(){const{incidents:e}=this.sourcesWithLayers;0!==e.shownFeatures.features.length&&this.mapLibreMap.removeFeatureState({source:e.sourceAndLayerIDs.sourceID})}},INCIDENTS_FILTERS={contributor:"traffic.incidents",build:e=>buildMapLibreAnyFilters(e,buildMapLibreIncidentsFilter)},TrafficIncidentsModule=class TrafficIncidentsModule extends AbstractStyleOwnedMapModule{static get(e,t){return getStyleOwnedModule(e,TrafficIncidentsModule,()=>new TrafficIncidentsModule(e,t),t,{sourceId:"vectorTilesIncidents",part:"trafficIncidents"})}constructor(e,t){super(e,t)}_initSourcesWithLayers(){return this.appliedFilters??=new AppliedFilters,{trafficIncidents:styleSourceWithLayers(this.mapLibreMap,"vectorTilesIncidents",TrafficIncidentsModule.name)}}_applyConfig(e){const t=e?.icons?.visible;return isNil(t)?this._setVisible(e?.visible??!1,!1):(this._setVisible(e?.visible??!1,!1,e=>"symbol"!==e.type),this._setIconsVisible(t,!1)),this._applyTimeValidity(e?.timeValidity),this.appliedFilters.replace(this.tomtomMap,e?.filters,(e,t)=>applyTrafficFilters(this.tomtomMap,INCIDENTS_FILTERS,this.sourcesWithLayers.trafficIncidents._layerSpecs,e,t)),trafficIncidentsLook.apply(this.tomtomMap,e),e}_applyTimeValidity(e){const t=this.mapLibreMap.getSource("vectorTilesIncidents"),i=t?.serialize().tiles;if(!i)return;const s=i.map(t=>((e,t)=>{const[i,s=""]=e.split("?"),o=new URLSearchParams(s),r=trafficIncidentTimeValidities.filter(e=>t?.includes(e)),a=r.some(e=>"present"!==e)?r.join(","):null;if(o.get("timeValidityFilter")===a)return e;a?o.set("timeValidityFilter",a):o.delete("timeValidityFilter");const n=o.toString();return n?`${i}?${n}`:i})(t,e));isEqual(s,i)||t.setTiles(s)}_knobValue(e){return super._knobValue(e)??trafficIncidentsLook.valueOf(this.tomtomMap,e)}setIconsVisible(e){this._setIconsVisible(e)}_setIconsVisible(e,t=!0){this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisibleThrough(this.visibilityComposer,"trafficIncidents.visible",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=!0,i){if(this.tomtomMap.mapReady&&this.sourcesWithLayers.trafficIncidents.setLayersVisibleThrough(this.visibilityComposer,"trafficIncidents.visible",e,i),t){const{icons:t,...i}=this.config??{},{visible:s,...o}=t??{};this.config={...i,...!isEmpty(o)&&{icons:o},visible:e},this.emitConfigChange()}}isVisible(){return this.config?.visible??!1}isIconsVisible(){return this.config?.icons?.visible??this.isVisible()}getRenderedFeatures(){return{trafficIncidents:this.sourcesWithLayers.trafficIncidents.queryRenderedFeatures().map(trafficIncidentMapping)}}get events(){return this.moduleEvents(["trafficIncidents"],{mapping:trafficIncidentMapping})}},MERCATOR_UNITS_PER_EPSG3857_METER=1/(2*Math.PI*6378137),mercatorUnitsPerMeterAt=e=>MERCATOR_UNITS_PER_EPSG3857_METER/Math.cos(e*RADIANS_PER_DEGREE),localFrameMatrix=(e,t,i={})=>{const{altitude:s=0,units:o}=i,[,r]=t,a=MercatorCoordinate.fromLngLat(t),n="mercatorMeters"===o?MERCATOR_UNITS_PER_EPSG3857_METER:mercatorUnitsPerMeterAt(r),l=mercatorUnitsPerMeterAt(i.centerLatitude??r),c=[n,-n,l],d=[a.x,a.y,s*l],u=/* @__PURE__ */new Float64Array(16);for(let h=0;h<4;h++){u[12+h]=e[12+h];for(let t=0;t<3;t++)u[4*t+h]=e[4*t+h]*c[t],u[12+h]+=e[4*t+h]*d[t]}return u},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,areaOf=({left:e,top:t,right:i,bottom:s})=>Math.max(0,i-e)*Math.max(0,s-t),adjustVisibleBoundsForElement=(e,t,i,s,o)=>{const r=((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,s),a=e.left<=0&&e.right>=i,n=e.top<=0&&e.bottom>=s;!a||n?!n||a?((e,t,i,s,o)=>{const r=[{visible:{...t,left:Math.max(t.left,e.right+o)},edgeDistance:e.left},{visible:{...t,right:Math.min(t.right,e.left-o)},edgeDistance:i-e.right},{visible:{...t,top:Math.max(t.top,e.bottom+o)},edgeDistance:e.top},{visible:{...t,bottom:Math.min(t.bottom,e.top-o)},edgeDistance:s-e.bottom}],a=r.reduce((e,t)=>{const i=areaOf(t.visible)-areaOf(e.visible);return i>0||0===i&&t.edgeDistance<e.edgeDistance?t:e},r[0]);Object.assign(t,a.visible)})(r,t,i,s,o):((e,t,i,s)=>{e.left<=i-e.right?t.left=Math.max(t.left,e.right+s):t.right=Math.min(t.right,e.left-s)})(r,t,i,o):((e,t,i,s)=>{e.top<=i-e.bottom?t.top=Math.max(t.top,e.bottom+s):t.bottom=Math.min(t.bottom,e.top-s)})(r,t,s,o)},toElement=e=>"string"==typeof e?document.querySelector(e):e,getMapLibreMap=e=>"mapLibreMap"in e?e.mapLibreMap:e,calculateVisibleAreaBounds=({map:e,surroundingElements:t,paddingPX:i=0})=>{const s=getMapLibreMap(e).getContainer().getBoundingClientRect(),{width:o,height:r}=s,a={left:i,top:i,right:o-i,bottom:r-i};for(const n of t){const e=toElement(n);if(!e)continue;const t=e.getBoundingClientRect(),l=getRelativeElementBounds(t,s);!isElementOutsideContainer(l,o,r)&&areaOf(l)&&adjustVisibleBoundsForElement(l,a,o,r,i)}return a.left>=a.right||a.top>=a.bottom?null:{visibleAreaBounds:a,mapWidthPX:o,mapHeightPX:r}},calculatePaddedBBox=e=>{const t=calculateVisibleAreaBounds(e);if(!t)return null;const{left:i,top:s,right:o,bottom:r}=t.visibleAreaBounds,a=getMapLibreMap(e.map),n=[[i,r],[i,s],[o,s],[o,r]].map(([e,t])=>{const{lng:i,lat:s}=a.unproject([e,t]);return[i,s]});return bboxFromGeoJSON({type:"LineString",coordinates:n})??null},calculatePaddedCenter=e=>{const{map:t,surroundingElements:i}=e,s=calculatePaddedBBox({map:t,surroundingElements:i});return s?bboxCenter(s):null},mercatorY=e=>MercatorCoordinate.fromLngLat([0,e]).y,latitudeAt=e=>new MercatorCoordinate(0,e).toLngLat().lat,calculateFittingBBox=e=>{const t=calculateVisibleAreaBounds(e);if(!t)return null;const{visibleAreaBounds:i,mapWidthPX:s,mapHeightPX:o}=t,r=i.left/s,a=i.right/s,n=i.top/o,l=a-r,c=i.bottom/o-n,{toBeContainedBBox:d}=e,[u,h,,p]=d,y=mercatorY(clampLatitude(p)),f=mercatorY(clampLatitude(h)),m=bboxLongitudeSpan(d)/l,g=(f-y)/c,b=u-r*m,S=b+m,L=y-n*g;return[b,clampLatitude(latitudeAt(L+g)),S,clampLatitude(latitudeAt(L))]};export{AREA_ANALYTICS_DEFAULTS,ATTRIBUTION_BACKDROP_CLASS,ATTRIBUTION_CREDITS_CLASS,ATTRIBUTION_LOGOS_CLASS,ATTRIBUTION_LOGO_CLASS,AbstractDataOwnedMapModule,AbstractGeometriesModule,AbstractMapModule,AbstractSourceWithLayers,AbstractStyleOwnedMapModule,AddedSourceWithLayers,BASE_MAP_SOURCE_ID,BaseMapModule,CLICK_EVENT_STATES,CombinedEvents,CustomGeoJSONModule,CustomLayer,CustomLayerSourceWithLayers,DEFAULT_TEXT_SIZE,DESELECTED_ROUTE_FILTER,FINISH_INDEX,GeoJSONSourceWithLayers,GeometriesModule,HILLSHADE_SOURCE_ID,HOVER_EVENT_STATES,LayerFilterComposer,LayerSelection,MAP_BOLD_FONT,MAP_ITALIC_FONT,MAP_MEDIUM_FONT,MAP_REGULAR_FONT,MERCATOR_UNITS_PER_EPSG3857_METER,MIDDLE_INDEX,ModuleEvents,POI_SOURCE_ID,POIsModule,PlacesModule,ReachableRangesModule,RoutingModule,SELECTED_ROUTE_FILTER,START_INDEX,StyleSourceWithLayers,StylingFoundationsModule,TERRAIN_SOURCE_ID,TRAFFIC_FLOW_SOURCE_ID,TRAFFIC_INCIDENTS_SOURCE_ID,TerrainModule,TomTomMap,TomTomMapError,TrafficAreaAnalyticsModule,TrafficFlowModule,TrafficIncidentDetailsModule,TrafficIncidentsModule,UserEvents,UserEventsWithStates,applyMapPreset,areaAnalyticsPalettes,baseMapColorNames,baseMapKnobCatalogue,baseMapKnobIds,baseMapLayerGroupNames,bespokeSectionTypes,buildPlaceTitle,buildWaypointTitle,calculateFittingBBox,calculatePaddedBBox,calculatePaddedCenter,configWithKnobs,configWithoutKnob,customGeoJSONKnobCatalogue,customGeoJSONKnobIds,defaultRoutingLayers,drawnSectionTypes,existingAnchorLayerID,fillStyledGeometryConfig,filterShowModes,formatStyleHsl,generatedSectionTypes,geometriesKnobCatalogue,geometriesKnobIds,geometryFillStyles,geometryPaletteModes,getKnob,getMapLight,getStyleColor,hillshadeLightAlignments,hillshadeMethods,hueDistance,isMapColorName,knobEntryOf,knobValueIn,linePatterns,localFrameMatrix,mapColorKnobId,mapColorNames,mapFonts,mapPresetCatalogue,mapPresetIds,mapStyleLayerIDs,mapTypefaces,mentionsZoom,parseCssColor,placesKnobCatalogue,placesKnobIds,placesMarkerTypes,poiCategoryGroups,poisKnobCatalogue,poisKnobIds,preparePlacesForDisplay,reachableRangesKnobCatalogue,reachableRangesKnobIds,resetKnob,resolveColorStops,roadCategories,routingKnobCatalogue,routingKnobIds,runWhenMapIsReady,sectionDrawsByDefault,sectionSourceKey,sectionSupportsKnob,serviceRoadSubCategories,setKnob,setKnobs,standardStyleIDs,standardStyleIdOf,streetRoadSubCategories,styleColorKnobIds,styleModuleLayerGroupNames,styleParts,stylingFoundationsKnobAppliesTo,stylingFoundationsKnobCatalogue,stylingFoundationsKnobIds,stylingFoundationsKnobKinds,terrainKnobCatalogue,terrainKnobIds,toHsl,toPlaces,toTomTomMapRequestError,trafficAreaAnalyticsKnobCatalogue,trafficAreaAnalyticsKnobIds,trafficFlowKnobCatalogue,trafficFlowKnobIds,trafficIncidentDetailsKnobCatalogue,trafficIncidentDetailsKnobIds,trafficIncidentsKnobCatalogue,trafficIncidentsKnobIds,validateKnobValue,wrapZoomFreeParts};