@tomtom-org/maps-sdk 0.58.0 → 0.58.1

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.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@tomtom-org/maps-sdk",
3
3
  "author": "TomTom International B.V.",
4
4
  "license": "See in LICENSE.txt",
5
- "version": "0.58.0",
5
+ "version": "0.58.1",
6
6
  "description": "TomTom maps, search, geocoding, routing, isochrones, EV and traffic for JavaScript — typed GeoJSON services and a MapLibre GL JS map.",
7
7
  "homepage": "https://docs.tomtom.com/maps-sdk-js/introduction/overview",
8
8
  "repository": {
@@ -3,6 +3,41 @@ NOT bundled into this package: your package manager installs them alongside it a
3
3
  your application bundles them. The licenses below apply to those copies, and each of
4
4
  these components may in turn install its own dependencies under their own licenses.
5
5
 
6
+ Name: @turf/turf
7
+ Version: 7.4.0
8
+ License: MIT
9
+ Bundled: false (peer dependency)
10
+ Description: a JavaScript library for performing geospatial operations with GeoJSON
11
+ Repository: git://github.com/Turfjs/turf.git
12
+ Homepage: https://github.com/Turfjs/turf
13
+ Author: Turf Authors
14
+ License Text:
15
+ ===
16
+
17
+ The MIT License (MIT)
18
+
19
+ Copyright (c) 2017 TurfJS
20
+
21
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
22
+ this software and associated documentation files (the "Software"), to deal in
23
+ the Software without restriction, including without limitation the rights to
24
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
25
+ the Software, and to permit persons to whom the Software is furnished to do so,
26
+ subject to the following conditions:
27
+
28
+ The above copyright notice and this permission notice shall be included in all
29
+ copies or substantial portions of the Software.
30
+
31
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
33
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
34
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
35
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
36
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37
+
38
+
39
+ ---
40
+
6
41
  Name: lodash-es
7
42
  Version: 4.18.1
8
43
  License: MIT
@@ -7795,6 +7795,34 @@ type TrafficIncidentDetailsByBBoxParams = TrafficIncidentDetailsBaseParams & {
7795
7795
  * ```
7796
7796
  */
7797
7797
  bbox: HasBBox;
7798
+ polygon?: never;
7799
+ ids?: never;
7800
+ };
7801
+ /**
7802
+ * Parameters for fetching incidents within a polygon, such as a city boundary.
7803
+ *
7804
+ * @remarks
7805
+ * The API only accepts a bounding box, so the request is sent with the polygon's bounding box and the
7806
+ * response is then trimmed to the incidents that intersect the polygon. A `LineString` incident that
7807
+ * crosses the boundary is kept. The 10,000 km² limit applies to that bounding box.
7808
+ *
7809
+ * @example
7810
+ * ```typescript
7811
+ * const place = await geocodeOne('Amsterdam');
7812
+ * const params: TrafficIncidentDetailsByPolygonParams = {
7813
+ * polygon: await geometryData({ geometries: [place] })
7814
+ * };
7815
+ * ```
7816
+ *
7817
+ * @group Traffic
7818
+ */
7819
+ type TrafficIncidentDetailsByPolygonParams = TrafficIncidentDetailsBaseParams & {
7820
+ /**
7821
+ * Area to query: a `Polygon` or `MultiPolygon`, a `Feature` wrapping one, or a `FeatureCollection` of
7822
+ * them, such as the {@link PolygonFeatures} that {@link geometryData} returns.
7823
+ */
7824
+ polygon: Polygon | MultiPolygon | Feature<Polygon | MultiPolygon> | FeatureCollection<Polygon | MultiPolygon>;
7825
+ bbox?: never;
7798
7826
  ids?: never;
7799
7827
  };
7800
7828
  /**
@@ -7826,30 +7854,33 @@ type TrafficIncidentDetailsByIdsParams = TrafficIncidentDetailsBaseParams & {
7826
7854
  */
7827
7855
  ids: string[];
7828
7856
  bbox?: never;
7857
+ polygon?: never;
7829
7858
  };
7830
7859
  /**
7831
7860
  * Parameters for the Traffic Incident Details service.
7832
7861
  *
7833
- * Provide either a `bbox` to search within an area, or a list of `ids` to
7834
- * look up specific incidents.
7862
+ * Provide one of a `bbox` or a `polygon` to search within an area, or a list of `ids` to look up
7863
+ * specific incidents.
7835
7864
  *
7836
7865
  * @group Traffic
7837
7866
  */
7838
- type TrafficIncidentDetailsParams = TrafficIncidentDetailsByBBoxParams | TrafficIncidentDetailsByIdsParams;
7867
+ type TrafficIncidentDetailsParams = TrafficIncidentDetailsByBBoxParams | TrafficIncidentDetailsByPolygonParams | TrafficIncidentDetailsByIdsParams;
7839
7868
  //#endregion
7840
7869
  //#region src/traffic-incident-details/trafficIncidentDetails.d.ts
7841
7870
  /**
7842
7871
  * Fetch detailed information about traffic incidents.
7843
7872
  *
7844
- * Query incidents either by a geographic bounding box or by a list of incident IDs.
7873
+ * Query incidents by a geographic bounding box, by a polygon, or by a list of incident IDs.
7845
7874
  * Results are GeoJSON Features whose geometry is a `Point` (localised incidents) or
7846
7875
  * a `LineString` (incidents spanning a stretch of road).
7847
7876
  *
7848
7877
  * @remarks
7849
- * **Two query modes:**
7878
+ * **Three query modes:**
7850
7879
  *
7851
7880
  * - **Bounding box** (`bbox`): Returns all incidents within the given area.
7852
7881
  * Maximum area is 10,000 km².
7882
+ * - **Polygon** (`polygon`): Returns the incidents that intersect a polygon, such as a city boundary.
7883
+ * The request covers the polygon's bounding box, and the response is trimmed to the polygon.
7853
7884
  * - **By IDs** (`ids`): Returns the specified incidents directly.
7854
7885
  * GET is used automatically for up to 5 IDs; POST for up to 100 IDs.
7855
7886
  *
@@ -7860,7 +7891,7 @@ type TrafficIncidentDetailsParams = TrafficIncidentDetailsByBBoxParams | Traffic
7860
7891
  * - Time information: start/end times and whether the incident is `present` or `future`
7861
7892
  * - Events: one or more detailed event descriptions
7862
7893
  *
7863
- * @param params - Traffic Incident Details parameters (bbox or ids)
7894
+ * @param params - Traffic Incident Details parameters (bbox, polygon or ids)
7864
7895
  *
7865
7896
  * @returns Promise resolving to a {@link TrafficIncidentDetails} object containing the matching incidents
7866
7897
  *
@@ -7880,6 +7911,15 @@ type TrafficIncidentDetailsParams = TrafficIncidentDetailsByBBoxParams | Traffic
7880
7911
  *
7881
7912
  * @example
7882
7913
  * ```typescript
7914
+ * // Query within a city boundary rather than its bounding box
7915
+ * const place = await geocodeOne('Amsterdam');
7916
+ * const result = await trafficIncidentDetails({
7917
+ * polygon: await geometryData({ geometries: [place] })
7918
+ * });
7919
+ * ```
7920
+ *
7921
+ * @example
7922
+ * ```typescript
7883
7923
  * // Query up to 5 specific incidents by ID (GET)
7884
7924
  * const result = await trafficIncidentDetails({
7885
7925
  * ids: ['incident-id-1', 'incident-id-2']
@@ -7911,4 +7951,4 @@ type TrafficIncidentDetailsParams = TrafficIncidentDetailsByBBoxParams | Traffic
7911
7951
  */
7912
7952
  export declare const trafficIncidentDetails: (params: TrafficIncidentDetailsParams) => Promise<TrafficIncidentDetails>;
7913
7953
  //#endregion
7914
- export type { AdditionalDataAPI, AlongRouteSearchParams, AlongRouteSearchPayloadAPI, AlongRouteSearchRequestAPI, AlongRouteSearchResponse, AlongRouteSearchResponseAPI, AlongRouteSearchResultAPI, AlongRouteSortBy, AreaAnalyticsDateInput, ArrivalSide, BookmarkIntent, BookmarkIntentDetails, BrandSuggestion, CalculateRouteParams, CategorySuggestion, ChargingStationsAvailabilityParams, ChargingStopsStrategy, Circle, CircleAPI, CommonServiceParamsWithZoom, ComputeTravelTimeFor, CoordinateIntent, CoordinateIntentAPI, CoordinateIntentDetails, CoordinateIntentDetailsAPI, ExtendedRouteRepresentation, FunctionalRoadClass, FuzzySearchParams, FuzzySearchResponse, FuzzySearchResponseAPI, FuzzySearchResultAPI, GeocodingParams, GeocodingProps, GeocodingResponse, GeometriesInput, GeometryAPI, GeometryDataParams, GeometryDataResponseAPI, GeometryParams, GeometryPlaceParams, GeometrySearchFeatureCollectionProps, GeometrySearchParams, GeometrySearchPayloadAPI, GeometrySearchRequestAPI, GeometrySearchResponse, GeometrySearchResponseAPI, GeometrySearchResultAPI, GuidanceParams, InputSectionType, InputSectionTypes, LegCostModel, MaxNumberOfAlternatives, NearbyIntent, NearbyIntentAPI, NearbyIntentDetails, NearbyIntentDetailsAPI, POICategoriesParams, POICategoriesResponse, POICategoryResult, PlaceDetailsMandatoryParams, PlaceDetailsOptionalParams, PlaceDetailsParams, PlaceDetailsResponse, PlaceDetailsResponseAPI, PlaceDetailsResultAPI, PlaceSuggestion, PoiCategoriesResponseAPI, PoiCategoryAPI, PolygonAPI, QueryIntent, QueryIntentAPI, RefinementSuggestion, ReverseGeocodingMandatoryParams, ReverseGeocodingOptionalParams, ReverseGeocodingParams, RoutePointAPI, RouteStopOptions, SearchGeometryInput, SearchSuggestion, SearchSuggestionKind, SearchSuggestionsParams, SearchSuggestionsResponse, TrafficAreaAnalyticsDateRange, TrafficAreaAnalyticsDays, TrafficAreaAnalyticsParams, TrafficIncidentDetailsByBBoxParams, TrafficIncidentDetailsByIdsParams, TrafficIncidentDetailsParams, W3WIntent, W3WIntentDetails, arrivalSides, chargingStopsStrategies, functionalRoadClasses };
7954
+ export type { AdditionalDataAPI, AlongRouteSearchParams, AlongRouteSearchPayloadAPI, AlongRouteSearchRequestAPI, AlongRouteSearchResponse, AlongRouteSearchResponseAPI, AlongRouteSearchResultAPI, AlongRouteSortBy, AreaAnalyticsDateInput, ArrivalSide, BookmarkIntent, BookmarkIntentDetails, BrandSuggestion, CalculateRouteParams, CategorySuggestion, ChargingStationsAvailabilityParams, ChargingStopsStrategy, Circle, CircleAPI, CommonServiceParamsWithZoom, ComputeTravelTimeFor, CoordinateIntent, CoordinateIntentAPI, CoordinateIntentDetails, CoordinateIntentDetailsAPI, ExtendedRouteRepresentation, FunctionalRoadClass, FuzzySearchParams, FuzzySearchResponse, FuzzySearchResponseAPI, FuzzySearchResultAPI, GeocodingParams, GeocodingProps, GeocodingResponse, GeometriesInput, GeometryAPI, GeometryDataParams, GeometryDataResponseAPI, GeometryParams, GeometryPlaceParams, GeometrySearchFeatureCollectionProps, GeometrySearchParams, GeometrySearchPayloadAPI, GeometrySearchRequestAPI, GeometrySearchResponse, GeometrySearchResponseAPI, GeometrySearchResultAPI, GuidanceParams, InputSectionType, InputSectionTypes, LegCostModel, MaxNumberOfAlternatives, NearbyIntent, NearbyIntentAPI, NearbyIntentDetails, NearbyIntentDetailsAPI, POICategoriesParams, POICategoriesResponse, POICategoryResult, PlaceDetailsMandatoryParams, PlaceDetailsOptionalParams, PlaceDetailsParams, PlaceDetailsResponse, PlaceDetailsResponseAPI, PlaceDetailsResultAPI, PlaceSuggestion, PoiCategoriesResponseAPI, PoiCategoryAPI, PolygonAPI, QueryIntent, QueryIntentAPI, RefinementSuggestion, ReverseGeocodingMandatoryParams, ReverseGeocodingOptionalParams, ReverseGeocodingParams, RoutePointAPI, RouteStopOptions, SearchGeometryInput, SearchSuggestion, SearchSuggestionKind, SearchSuggestionsParams, SearchSuggestionsResponse, TrafficAreaAnalyticsDateRange, TrafficAreaAnalyticsDays, TrafficAreaAnalyticsParams, TrafficIncidentDetailsByBBoxParams, TrafficIncidentDetailsByIdsParams, TrafficIncidentDetailsByPolygonParams, TrafficIncidentDetailsParams, W3WIntent, W3WIntentDetails, arrivalSides, chargingStopsStrategies, functionalRoadClasses };
@@ -1,2 +1,2 @@
1
- import{TomTomConfig as e,areaAnalyticsMetricKeys as t,avoidableTypes as n,bboxFromCoordsArray as r,bboxFromGeoJSON as o,bboxOnlyIfWithArea as a,currentTypes as i,generateId as s,generateTomTomHeaders as c,geographyTypes as u,getPosition as l,getPositionStrict as d,getRoutePlanningLocationType as p,inputSectionTypesWithGuidance as m,isProxyCredentialsMode as g,mergeFromGlobal as h,plugTypes as y,poiCategories as f,poiCategoriesToID as T,poiIDsToCategories as R,toPointGeometry as I,trafficIncidentRequestCategories as b,views as S}from"@tomtom-org/maps-sdk/core";import{z as C}from"zod";import{countBy as v,isNil as A,maxBy as P,minBy as L,omit as M,partition as E,pick as w,uniqBy as D}from"lodash-es";var O=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),N=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},x={[O.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[O.FORBIDDEN]:"Request failed with status code 403"},B=class extends N{constructor(e,t,n){super(e,t),this.status=n,this.status&&x[this.status]&&(this.message=x[this.status])}},H=class extends N{constructor(e,t){super("The operation was aborted.",e),this.name="AbortError",this.cause=t}},_=(e,t)=>{const{data:n,message:r,status:o}=e;return new B(n?.error||n?.errorText||r,t,o)},F=(e,t,n,r)=>{if(r?.aborted&&e===r.reason)return new H(t,r.reason);if(r?.aborted&&"AbortError"===e?.name)return new H(t,r.reason);if(e.status){const r=e;return n?n(r,t):_(r,t)}return new N(e.message,t)},U=(e,t)=>new N(e.message,t,e.issues),G=C.object({apiKey:C.string().optional(),commonBaseURL:C.string().optional(),customServiceBaseURL:C.string().optional(),language:C.string().optional()}),k=(e,t=0)=>{const n=e.path.length>0?`${e.path.join(".")}: `:"";if("invalid_union"===e.code){const r=e.unionErrors;if(r?.length)return`${n}no matching union member (${r.map((e,n)=>`option[${n}]: { ${e.issues.map(e=>k(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},K=class extends Error{constructor(e){super(`${e.issues.map(e=>k(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},W=async(e,t,n)=>{if(e.signal?.aborted)throw new H(n,e.signal.reason);const r=t.getAPIVersion?.(e),o=h({...e,...r&&{apiVersion:r}});if(void 0===e.validateRequest||e.validateRequest)try{((e,t)=>{const n=(t?.schema?G.extend(t.schema.shape):G).superRefine((e,n)=>{if("commonBaseURL"in e||"customServiceBaseURL"in e||n.addIssue({code:"custom",message:"commonBaseURL or customServiceBaseURL is required"}),t?.refinements?.length)for(const r of t.refinements)r.check(e)||n.addIssue({code:"custom",message:r.message})}).safeParse(e);if(!n.success)throw new K(n.error)})(o,t.requestValidation)}catch(s){throw U(s,n)}const a=t.buildRequest(o),i=c(o);e.onAPIRequest?.(a);try{const n=await t.sendRequest(a,i,{signal:e.signal});return e.onAPIResponse?.(a,n),t.parseResponse(await n.data,o)}catch(s){throw e.onAPIResponse?.(a,s),F(s,n,t.parseResponseError,e.signal)}},j=class e extends Error{constructor(t,n,r){super(n??`HTTP Error ${t}`),this.name="FetchError",this.status=t,this.data=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},V=async e=>{if(e.ok)return{data:await e.json(),status:e.status};let t,n;const r=e.headers.get("content-type");throw e.bodyUsed?t=e.statusText:r?.includes("application/json")?(n=await e.json(),t=n?.errorText??n?.message??n?.detailedError?.message):r?.includes("text/xml")&&(n=await e.text(),t=e.statusText),new j(e.status,t,n)},q=(e,t)=>new Promise((n,r)=>{if(t?.aborted)return void r(t.reason);const o=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})}),Y=async(t,n)=>{const r=e.instance.get().retry;if(!r)return t();const{initialWaitMs:o,backoffFactor:a,timeoutMs:i}=r,s=Date.now();let c=o,u=await t();for(;429===u.status;){const e=Number.parseInt(u.headers.get("retry-after")??"",10),r=Number.isFinite(e)?1e3*e:c;if(Date.now()-s+r>i)break;await u.text().catch(()=>{}),await q(r,n),c*=a,u=await t()}return u},$=()=>g()?"include":void 0,Z=async(e,t,n)=>V(await Y(()=>{const r=$(),{url:o,headers:a}=e instanceof URL?{url:e,headers:void 0}:e,i={headers:{...t,...a}};return r&&(i.credentials=r),n?.signal&&(i.signal=n.signal),fetch(o,i)},n?.signal)),z=async(e,t,n)=>V(await Y(()=>{const r=$(),o={method:"POST",body:JSON.stringify(e.data),headers:{...t,...e.headers,"Content-Type":"application/json"}};return r&&(o.credentials=r),n?.signal&&(o.signal=n.signal),fetch(e.url,o)},n?.signal)),J=async(e,t,n)=>{if("GET"===e.method)return Z(e,t,n);if("POST"===e.method)return z(e,t,n);throw new Error(`Unsupported HTTP method received: ${e.method}`)},Q=C.array(C.array(C.number())),X=C.object({type:C.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:C.union([C.array(C.number()),Q,C.array(C.array(C.array(C.number()))),C.array(C.array(C.array(C.array(C.number()))))]),radius:C.optional(C.number()),radiusMeters:C.optional(C.number()),bbox:C.optional(C.array(C.number()))}).check(C.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),ee=C.object({type:C.literal("Feature"),geometry:X,id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),te=C.object({type:C.literal("FeatureCollection"),features:C.array(ee),id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),ne=C.union([C.tuple([C.number().min(-180).max(180),C.number().min(-90).max(90)]),C.tuple([C.number().min(-180).max(180),C.number().min(-90).max(90),C.number()]),C.object({type:C.literal("Point"),coordinates:C.array(C.number())}),ee]),re=C.union([C.array(C.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),C.array(C.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),oe=C.union([X,ee,te]),ae=C.union([re,oe,C.array(oe)]),ie=C.object({query:C.string().optional(),position:ne.optional(),limit:C.number().max(100).optional(),extendedPostalCodesFor:C.array(C.string()).optional(),mapcodes:C.array(C.string()).optional(),view:C.enum(S).optional(),geographyTypes:C.array(C.string()).optional()}),se=C.object({indexes:C.array(C.string()).optional(),poiCategories:C.array(C.enum(f)).optional(),poiBrands:C.array(C.string()).optional(),connectors:C.array(C.string()).optional(),fuelTypes:C.array(C.string()).optional(),openingHours:C.string().optional(),timeZone:C.string().optional(),relatedPois:C.string().optional(),minPowerKW:C.number().optional(),maxPowerKW:C.number().optional(),minFuzzyLevel:C.number().optional(),maxFuzzyLevel:C.number().optional()}),ce=ie.extend(se.shape),ue=C.object({type:C.literal("LineString"),coordinates:Q}),le=C.object({type:C.literal("Feature"),geometry:ue}),de=Q,pe=C.union([ue,le,de]),me=C.object({route:pe,maxDetourTimeSeconds:C.number().int().positive()}),ge=C.object({sortBy:C.enum(["detourTime","detourOffset"]).optional()}),he=ce.extend({...me.shape,...ge.shape}),ye=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",fe=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let o;const a=Math.ceil(n/t);for(o=0;o<n;o+=a)r.push(e[o]);return t>1&&o>=n-a&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},Te=e=>({...e.apiKey&&{"TomTom-Api-Key":e.apiKey},...!A(e.apiVersion)&&{"TomTom-Api-Version":String(e.apiVersion)}}),Re=e=>({...Te(e),...e.language&&{"Accept-Language":e.language}}),Ie=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),t.apiKey&&e.append("key",t.apiKey),t.language&&e.append("language",t.language)},be=e=>Te(e),Se=(e,t)=>{t.language&&e.append("language",t.language)},Ce=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},ve=(e,t,n)=>{!A(n)&&e.append(t,String(n))},Ae=(e,t)=>{if(!t)return;if(void 0!==t.position)return((e,t)=>{const n=l(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))})(e,t.position),void ve(e,"radius",t.radiusMeters);const n=o(t.boundingBox);n&&(e.append("topLeft",ye([n[3],n[0]])),e.append("btmRight",ye([n[1],n[2]])))},Pe=(e,t)=>{const n=e.searchParams;Se(n,t),ve(n,"limit",t.limit),Ce(n,"fuelSet",t.fuelTypes),Ce(n,"idxSet",t.indexes),Ce(n,"brandSet",t.poiBrands),t.poiCategories&&Ce(n,"categorySet",t.poiCategories.map(e=>T[e])),Ce(n,"connectorSet",t.connectors),Ce(n,"mapcodes",t.mapcodes),Ce(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),ve(n,"minPowerKW",t.minPowerKW),ve(n,"maxPowerKW",t.maxPowerKW),ve(n,"view",t.view),ve(n,"openingHours",t.openingHours),ve(n,"timeZone",t.timeZone),ve(n,"relatedPois",t.relatedPois),Ce(n,"entityTypeSet",t.geographyTypes)},Le=(e,t)=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/${t}`,Me=e=>{const t={count:0,statusCounts:{}};for(const n of e)for(const e of n.chargingPoints)t.count++,t.statusCounts[e.status]=(t.statusCounts[e.status]||0)+1;return t},Ee=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,we=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>Ee(r,e.connector));if(e){if(e.count++,t){const n=e.statusCounts;e.statusCounts[t]=(n[t]||0)+1}}else n.push({connector:r,count:1,statusCounts:t?{[t]:1}:{}})}},De=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>Ee(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Oe=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)we(e.connectors,e.status,t);return t},Ne=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",xe=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},Be=e=>`${e[1]},${e[0]}`,He=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=xe(e.southWest),n=xe(e.northEast)),[t[0],t[1],n[0],n[1]]},_e=e=>[e.lon,e.lat],Fe=e=>{const{year:t,month:n,day:r}=(e=>{const t=e.split("-");return{year:Number.parseInt(t[0]),month:Number.parseInt(t[1]),day:Number.parseInt(t[2])}})(e.date);return{dateYYYYMMDD:e.date,year:t,month:n,day:r,hour:e.hour,minute:e.minute,date:new Date(t,n-1,r,e.hour,e.minute)}},Ue=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,Ge=e=>{const t=e.timeRanges.map(e=>({start:Fe(e.startTime),end:Fe(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:Ue(t)}},ke=e=>{const{position:t,entryPoints:n,poi:r,id:o,dist:a,boundingBox:i,chargingPark:s,...c}=e,u=s?.connectors?.map(e=>({...M(e,"connectorType"),type:e.connectorType,chargingSpeed:Ne(e.ratedPowerKW)}));return{type:"Feature",geometry:I(_e(t)),...i&&{bbox:He(i)},id:o,properties:{...M(c,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:_e(e.position)}))},...u?.length&&{chargingPark:{...s,connectors:De(u)}},...r&&{poi:{name:r.name,categories:(r.categorySet?.map(e=>R[e.id])??[]).filter(e=>!!e),localizedCategories:r.categories??[],...r.phone&&{phone:r.phone},...r.brands&&{brands:r.brands.map(e=>e.name)},...r.url&&{url:r.url},...r.openingHours&&{openingHours:Ge(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},Ke=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:_e(t)},...n}},We={requestValidation:{schema:he},buildRequest:e=>{const t=new URL((e=>Le(e,`searchAlongRoute/${encodeURIComponent(e.query??"")}.json`))(e));Pe(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),ve(n,"sortBy",e.sortBy),ve(n,"spreadingMode","plan"),{url:t,headers:be(e),data:{route:{points:(r=e.route,Array.isArray(r)?{type:"LineString",coordinates:r}:"Feature"===r.type?r.geometry:r).coordinates.map(e=>({lat:e[1],lon:e[0]}))}}};var r},sendRequest:z,parseResponse:e=>{const t=e.results.map(ke),n=a(o(t));return{type:"FeatureCollection",properties:{...Ke(e.summary)},features:t,...n&&{bbox:n}}}},je=async e=>W(e,We,"AlongRouteSearch"),Ve=G.extend({id:C.string()}),qe=["fast","short","efficient","thrilling"],Ye=["all","unknown","none"],$e={requestValidation:{schema:Ve},buildRequest:e=>{const t=new URL((e=>Le(e,"ev/id"))(e)),n=t.searchParams;return Ie(n,e),n.append("id",e.id),t},sendRequest:Z,parseResponse:e=>{const t=e.results?.[0];return t?{id:t.id,accessType:t.accessType,chargingStations:(n=t.chargingStations,n.map(e=>({...e,chargingPoints:e.chargingPoints.map(e=>({...e,connectors:e.connectors?.map(e=>({...e,chargingSpeed:Ne(e.ratedPowerKW)}))}))}))),chargingPointAvailability:Me(t.chargingStations),connectorAvailabilities:Oe(t.chargingStations),...t.openingHours&&{openingHours:Ge(t.openingHours)}}:void 0;var n},parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new B(n,t,e.status)}},Ze=async e=>W(e,$e,"EVChargingStationsAvailability"),ze=async(e,t)=>{const n=e.properties.dataSources?.chargingAvailability?.id;if(n)try{const r=await Ze({...t,id:n}),o=e.properties.poi;return r?{...e,properties:{...e.properties,...o&&{poi:{...o,openingHours:r.openingHours}},chargingPark:{...e.properties.chargingPark,availability:r}}}:void 0}catch(r){return void console.error(r)}};async function Je(e,t){const{excludeIfAvailabilityUnknown:n,...r}=t??{},a=[];for(const o of e.features){const e=await ze(o,r);e?a.push(e):n||a.push(o)}return{...e,features:a,bbox:o(a)}}var Qe=e=>Boolean(e&&"availability"in e&&e.availability),Xe=async(e,t,n)=>{const r="string"==typeof t?{query:t}:t,[o]=(await n({...r,limit:1})).features;if(!o)throw new Error(`${e}: no results found for "${r.query}"`);return o},et=C.object({position:ne,radiusMeters:C.number().optional()}),tt=C.union([et,C.object({boundingBox:ae})]),nt=C.object({typeahead:C.boolean().optional(),offset:C.number().max(1900).optional(),geoBias:tt.optional(),countries:C.array(C.string()).optional()}),rt=G.extend(ie.shape).extend(nt.shape).extend({query:C.string()}),ot=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:I(_e(t)),...n&&{bbox:He(n)},id:s,properties:{...M(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...o&&{entryPoints:o.map(e=>({...e,position:_e(e.position)}))},...a&&{addressRanges:{...a,from:_e(a.from),to:_e(a.to)}}}}},at={requestValidation:{schema:rt},buildRequest:e=>{const t=new URL(`${(e=>Le(e,"geocode"))(e)}/${encodeURIComponent(e.query)}.json`),n=t.searchParams;return Se(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!A(e.limit)&&n.append("limit",String(e.limit)),!A(e.offset)&&n.append("ofs",String(e.offset)),Ae(n,e.geoBias),e.countries&&n.append("countrySet",ye(e.countries)),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",ye(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",ye(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",ye(e.geographyTypes)),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>{const t=e.results.map(ot),n=a(o(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}}},it=async e=>W(e,at,"Geocode"),st=async e=>Xe("geocodeOne",e,it),ct=C.object({geometries:C.union([te,C.array(C.union([C.string(),ee])).min(1).max(20)])}),ut=C.object({zoom:C.number().min(0).max(22).optional()}),lt=ct.extend(ut.shape),dt=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),pt={requestValidation:{schema:lt},buildRequest:e=>{const t=new URL((e=>Le(e,"additionalData.json"))(e)),n=t.searchParams;return((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:dt(t):dt(t.features),e.append("geometries",ye(n))})(n,e.geometries),ve(n,"geometriesZoom",e.zoom),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??s(),bbox:o(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:o(t),features:t}}};async function mt(e){const t=await W(e,pt,"GeometryData");return Array.isArray(e.geometries)||"FeatureCollection"!==e.geometries.type?t:((e,t)=>{const n=e.features.reduce((e,t)=>{const n=t.properties.dataSources?.geometry?.id;return n&&(e[n]={...t.properties,placeCoordinates:t.geometry.coordinates}),e},{}),r=t.features.map(e=>e.id&&n[e.id]?{...e,properties:n[e.id]}:e);return{type:"FeatureCollection",bbox:t.bbox,features:r}})(e.geometries,t)}var gt=C.object({entityId:C.string()}),ht=C.object({mapcodes:C.array(C.string()).optional(),view:C.enum(S).optional(),openingHours:C.string().optional(),timeZone:C.string().optional(),relatedPois:C.string().optional()}),yt=gt.extend(ht.shape),ft={requestValidation:{schema:yt},buildRequest:e=>{const t=new URL(`${(e=>Le(e,"place.json"))(e)}`),n=t.searchParams;return Se(n,e),ve(n,"entityId",e.entityId),Ce(n,"mapcodes",e.mapcodes),ve(n,"view",e.view),ve(n,"openingHours",e.openingHours),ve(n,"timeZone",e.timeZone),ve(n,"relatedPois",e.relatedPois),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>e.results?.length?ke(e.results[0]):void 0},Tt=async e=>W(e,ft,"PlaceDetails"),Rt=/* @__PURE__ */new Map,It=/* @__PURE__ */new Map,bt="en-GB",St=e=>e??bt,Ct=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),vt=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(Ct);for(const r of e)t[r]=n}return t},At=G.extend({filters:C.array(C.string()).optional()}),Pt=e=>{const t=R[e.id];return t?{code:t,name:e.name,childCategoryCodes:e.childCategoryIds.map(e=>R[e]).filter(e=>!!e),synonyms:e.synonyms}:(console.error(`Received unknown POI category ID ${e.id} (${e.name}). This category will be skipped and unavailable for filtering.`),null)},Lt={requestValidation:{schema:At},buildRequest:e=>{const t=Le(e,"poiCategories.json"),n=new URL(t);return Se(n.searchParams,e),{url:n,headers:be(e)}},getAPIVersion:()=>1,sendRequest:Z,parseResponse:e=>({poiCategories:e.poiCategories.map(Pt).filter(e=>null!==e)})},Mt=(e,t)=>{const n=(e=>It.get(e??bt)??{})(e),r=/* @__PURE__ */new Map;for(const o of t){const e=Ct(o);for(const[t,o]of Object.entries(n))t.includes(e)&&o&&r.set(o.code,o)}for(const o of r.values())for(const e of o.childCategoryCodes)r.delete(e);return[...r.values()]},Et=async(e={})=>{const{language:t}=h(e);let n=(e=>Rt.get(St(e)))(t);return n||(n=(await W(e,Lt,"POICategories")).poiCategories,((e,t)=>{const n=St(e);Rt.set(n,t),It.set(n,vt(t))})(t,n)),e.filters?.length?{poiCategories:Mt(t,e.filters)}:{poiCategories:n}},wt=async(e={})=>{const{poiCategories:t}=await Et(e);return t.map(e=>e.code)},Dt=(e,t)=>{const{data:n,message:r,status:o}=e;return new B(n?.error?.description??n?.detailedError?.message??r,t,o)},Ot=(e,t)=>e*t/100,Nt=e=>"engineType"in e&&"electric"===e.engineType,xt=e=>{if(Nt(e)&&e.model&&!("variantId"in e.model))return e.model.engine},Bt=(e,t,n)=>{A(n)||(e[t]=String(n))},Ht=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),_t=e=>{const t={};return e?(Bt(t,"accelerationEfficiency",e.acceleration),Bt(t,"decelerationEfficiency",e.deceleration),Bt(t,"uphillEfficiency",e.uphill),Bt(t,"downhillEfficiency",e.downhill),t):t},Ft=e=>{const t={};return e.speedsToConsumptionsKWH?.length&&(t.constantSpeedConsumptionInkWhPerHundredkm=Ht(e.speedsToConsumptionsKWH)),Bt(t,"auxiliaryPowerInkW",e.auxiliaryPowerInkW),Bt(t,"consumptionInkWhPerkmAltitudeGain",e.consumptionInKWHPerKMAltitudeGain),Bt(t,"recuperationInkWhPerkmAltitudeLoss",e.recuperationInKWHPerKMAltitudeLoss),{...t,..._t(e.efficiency)}},Ut=e=>{const t=e.consumption,n={};return t.speedsToConsumptionsLiters?.length&&(n.constantSpeedConsumptionInLitersPerHundredkm=Ht(t.speedsToConsumptionsLiters)),Bt(n,"auxiliaryPowerInLitersPerHour",t.auxiliaryPowerInLitersPerHour),Bt(n,"fuelEnergyDensityInMJoulesPerLiter",t.fuelEnergyDensityInMJoulesPerLiter),{...n,..._t(t.efficiency)}},Gt=e=>xt(e)?.charging?.maxChargeKWH,kt=e=>{const t={};return e.charging?.maxChargeKWH&&(t.maxChargeInkWh=String(e.charging.maxChargeKWH)),t},Kt=e=>{const t=e.state?.currentChargeInkWh;if(!A(t))return t;const n=e.state?.currentChargePCT,r=Gt(e);return!A(n)&&r?Ot(r,n):void 0},Wt=e=>{const t={};return Bt(t,"currentChargeInkWh",Kt(e)),t},jt=e=>{const t={};return Bt(t,"currentFuelInLiters",e.state?.currentFuelInLiters),t},Vt=e=>Nt(e)?e.preferences?.chargingPreferences:void 0,qt=(e,t)=>{for(const[n,r]of Object.entries(t))e.set(n,r)},Yt=C.number().positive(),$t=C.number().min(0),Zt=C.number().min(0).max(100),zt=Yt.optional(),Jt=$t.optional(),Qt=C.number().min(0).max(1).optional(),Xt=C.object({speedKMH:C.number(),consumptionUnitsPer100KM:C.number()}),en={efficiency:C.object({acceleration:Qt,deceleration:Qt,uphill:Qt,downhill:Qt}).optional()},tn=C.array(Xt).min(1).max(25),nn=C.object({...en,speedsToConsumptionsLiters:tn,auxiliaryPowerInLitersPerHour:Jt,fuelEnergyDensityInMJoulesPerLiter:C.number().min(1).optional()}),rn=C.object({...en,speedsToConsumptionsKWH:tn,auxiliaryPowerInkW:Jt,consumptionInKWHPerKMAltitudeGain:C.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Jt}),on=C.object({currentType:C.enum(i),plugTypes:C.array(C.enum(y)).min(1),efficiency:Qt,baseLoadInkW:Jt,maxPowerInkW:Jt,maxVoltageInV:Jt,maxCurrentInA:Jt,voltageRange:C.object({minVoltageInV:Jt,maxVoltageInV:C.number().optional()}).optional()}),an=C.object({stateOfChargeInkWh:$t,maxPowerInkW:Yt}),sn=C.object({maxChargeKWH:Yt,batteryCurve:C.array(an).max(20).optional(),chargingConnectors:C.array(on).min(1).optional(),chargingTimeOffsetInSec:Jt}),cn=C.object({consumption:nn}),un=C.object({consumption:rn,charging:sn.optional()}),ln=C.object({weightKG:zt}).optional(),dn=C.object({variantId:C.string()}),pn=C.object({dimensions:ln,engine:C.union([cn,un]).optional()}),mn=C.union([dn,pn]).optional(),gn=C.object({heading:C.number().min(0).max(360).optional()}),hn=gn.extend({currentFuelInLiters:$t}),yn=gn.extend({currentChargePCT:Zt}),fn=gn.extend({currentChargeInkWh:$t}),Tn=C.union([yn,fn]),Rn=C.object({minChargeAtDestinationPCT:Zt,minChargeAtChargingStopsPCT:C.number().min(0).max(50)}),In=C.object({minChargeAtDestinationInkWh:$t,minChargeAtChargingStopsInkWh:$t}),bn=C.union([Rn,In]),Sn=C.object({chargingPreferences:bn.optional()}),Cn={model:mn,restrictions:C.object({maxSpeedKMH:C.number().min(0).max(250).optional(),tollTransponder:C.enum(Ye).optional()}).optional()},vn=C.object({...Cn,engineType:C.undefined().optional(),state:gn.optional()}),An=C.object({...Cn,engineType:C.literal("combustion"),state:hn.optional()}),Pn=C.object({...Cn,engineType:C.literal("electric"),state:Tn.optional(),preferences:Sn.optional()}),Ln=C.union([C.discriminatedUnion("engineType",[An,Pn]),vn]),Mn=C.object({avoid:C.array(C.enum(n)).optional(),traffic:C.enum(["live","historical"]).optional(),routeType:C.enum(qe).optional(),avoidAreas:C.array(ae).max(10).optional()}),En=C.object({option:C.enum(["departAt","arriveBy"]),date:C.date()}),wn=C.object({costModel:Mn.optional(),travelMode:C.string().optional(),vehicle:Ln.optional(),when:En.optional()}),Dn=["timeMinutes","remainingChargePCT","spentChargePCT","spentFuelLiters","distanceKM"],On=C.object({origin:ne,budget:C.object({type:C.enum(Dn),value:C.number().min(0)})}),Nn=C.enum(n).exclude(["alreadyUsedRoads"]),xn=Ln.check(C.refine(e=>!(e.state&&"heading"in e.state),"vehicle.state.heading: calculateReachableRange has no vehicle heading parameter. Remove it, or use calculateRoute, which accepts it."),C.refine(e=>!("electric"===e.engineType&&e.preferences&&"chargingPreferences"in e.preferences),"vehicle.preferences.chargingPreferences: calculateReachableRange plans no charging stops. Remove them, or use calculateRoute, which plans stops for them.")),Bn=En.check(C.refine(e=>"arriveBy"!==e.option,"when.arriveBy: calculateReachableRange has no arrival-time parameter. Use when.departAt instead, or omit when entirely.")),Hn=Mn.extend({avoid:C.array(Nn).optional(),avoidAreas:C.unknown().optional()}).check(C.refine(e=>void 0===e.avoidAreas,"costModel.avoidAreas: calculateReachableRange has no avoid-areas parameter. Remove it — the other cost-model options are accepted.")),_n=C.object({when:Bn.optional(),vehicle:xn.optional(),costModel:Hn.optional(),maxFerryLengthMeters:C.number().min(0).optional(),smoothing:C.enum(["none","weak","strong"]).optional()}),Fn=wn.extend(On.extend(_n.shape).shape),Un=/* @__PURE__ */new Set(["spentChargePCT","remainingChargePCT"]),Gn={check:e=>!Un.has(e.budget.type)||!!e.vehicle&&void 0!==Gt(e.vehicle),message:"budget: a charge budget is a percentage of the battery, so it needs a capacity to convert against. Set vehicle.engineType to 'electric' and vehicle.model.engine.charging.maxChargeKWH, or budget by time or distance instead."},kn={check:e=>"remainingChargePCT"!==e.budget.type||!!e.vehicle&&void 0!==Kt(e.vehicle),message:"budget.remainingChargePCT: a range down to a remaining charge is measured from the charge the vehicle sets off with. Set vehicle.state.currentChargeInkWh or vehicle.state.currentChargePCT, or use spentChargePCT to budget a share of the battery instead."},Kn={schema:Fn,refinements:[Gn,kn]},Wn=e=>({...e.costModel?.routeType&&{routeType:e.costModel.routeType},...e.costModel?.traffic&&{traffic:e.costModel.traffic},...e.costModel?.avoid?.length&&{avoids:e.costModel.avoid},...e.travelMode&&{travelMode:e.travelMode},..."departAt"===e.when?.option&&e.when.date&&{departureDateTime:e.when.date.toISOString()}}),jn=e=>e.model&&"variantId"in e.model?e.model.variantId:void 0,Vn=e=>{const t={};return Nt(e)&&(t.vehicleEngineType="electric"),e.model&&!("variantId"in e.model)&&e.model.dimensions?.weightKG&&(t.vehicleWeightInKilograms=e.model.dimensions.weightKG),e.restrictions?.maxSpeedKMH&&(t.vehicleMaxSpeedInKilometersPerHour=e.restrictions.maxSpeedKMH),e.restrictions?.tollTransponder&&(t.vehicleHasElectronicTollCollectionTransponder=e.restrictions.tollTransponder),t},qn=(e,t)=>{const n=xt(t),r=(e=>"engineType"in e&&"combustion"===e.engineType?e.model?.engine:void 0)(t);var o;qt(e.searchParams,Nt(t)?{...n&&(o=n,{...Ft(o.consumption),...kt(o)}),...Wt(t)}:{...r&&Ut(r),...jt(t)})},Yn=(e,t)=>{const n=jn(t);n&&e.searchParams.set("vehicleModelId",n),qn(e,t)},$n=e=>({origin:{type:"Point",coordinates:d(e.origin)},...Wn(e),...e.vehicle&&Vn(e.vehicle)}),Zn=e=>({...Re(e),Attributes:"reachableRange(boundary)"}),zn=Object.keys({origin:!0,budget:!0,costModel:!0,vehicle:!0,travelMode:!0,when:!0,maxFerryLengthMeters:!0,smoothing:!0}),Jn={requestValidation:Kn,buildRequest:e=>{const t=(e=>new URL(e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange`))(e);return((e,t)=>{const n=t.budget,r=t.vehicle&&Gt(t.vehicle);switch(n.type){case"timeMinutes":e.append("timeBudgetInSec",(60*n.value).toString());break;case"distanceKM":e.append("distanceBudgetInMeters",(1e3*n.value).toString());break;case"spentFuelLiters":e.append("fuelBudgetInLiters",n.value.toString());break;case"spentChargePCT":r&&e.append("energyBudgetInkWh",Ot(r,n.value).toString());break;case"remainingChargePCT":{const o=t.vehicle&&Kt(t.vehicle);if(r&&void 0!==o){const t=Ot(r,n.value);e.append("energyBudgetInkWh",Math.max(0,o-t).toString())}break}}})(t.searchParams,e),ve(t.searchParams,"maxFerryLengthInMeters",e.maxFerryLengthMeters),ve(t.searchParams,"smoothing",e.smoothing??"strong"),e.vehicle&&Yn(t,e.vehicle),{method:"POST",url:t,data:$n(e),headers:Zn(e)}},sendRequest:J,parseResponse:(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:o(n),properties:w(t,zn)}},parseResponseError:Dt,getAPIVersion:()=>3},Qn=async e=>W(e,Jn,"Reachable Range"),Xn=(...e)=>{const t=e.filter(e=>!!e);return t.length<2?t[0]:AbortSignal.any(t)},er=async(e,t)=>{const n=[];for(const o of e){const e=Xn(o.signal,t?.signal);try{n.push(await Qn({...o,...e&&{signal:e}}))}catch(a){if(!(a instanceof B)||403===a.status||429===a.status)throw a}}const r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},tr={Country:"country",CountrySubdivision:"countrySubdivision",CountrySecondarySubdivision:"countrySecondarySubdivision",CountryTertiarySubdivision:"countryTertiarySubdivision",Municipality:"municipality",MunicipalitySubdivision:"municipalitySubdivision",MunicipalitySecondarySubdivision:"municipalitySecondarySubdivision",Neighbourhood:"neighborhood",PostalCodeArea:"postalCode"},nr={AF:"AFG",AX:"ALA",AL:"ALB",DZ:"DZA",AS:"ASM",AD:"AND",AO:"AGO",AI:"AIA",AQ:"ATA",AG:"ATG",AR:"ARG",AM:"ARM",AW:"ABW",AU:"AUS",AT:"AUT",AZ:"AZE",BS:"BHS",BH:"BHR",BD:"BGD",BB:"BRB",BY:"BLR",BE:"BEL",BZ:"BLZ",BJ:"BEN",BM:"BMU",BT:"BTN",BO:"BOL",BQ:"BES",BA:"BIH",BW:"BWA",BV:"BVT",BR:"BRA",IO:"IOT",BN:"BRN",BG:"BGR",BF:"BFA",BI:"BDI",CV:"CPV",KH:"KHM",CM:"CMR",CA:"CAN",KY:"CYM",CF:"CAF",TD:"TCD",CL:"CHL",CN:"CHN",CX:"CXR",CC:"CCK",CO:"COL",KM:"COM",CG:"COG",CD:"COD",CK:"COK",CR:"CRI",CI:"CIV",HR:"HRV",CU:"CUB",CW:"CUW",CY:"CYP",CZ:"CZE",DK:"DNK",DJ:"DJI",DM:"DMA",DO:"DOM",EC:"ECU",EG:"EGY",SV:"SLV",GQ:"GNQ",ER:"ERI",EE:"EST",SZ:"SWZ",ET:"ETH",FK:"FLK",FO:"FRO",FJ:"FJI",FI:"FIN",FR:"FRA",GF:"GUF",PF:"PYF",TF:"ATF",GA:"GAB",GM:"GMB",GE:"GEO",DE:"DEU",GH:"GHA",GI:"GIB",GR:"GRC",GL:"GRL",GD:"GRD",GP:"GLP",GU:"GUM",GT:"GTM",GG:"GGY",GN:"GIN",GW:"GNB",GY:"GUY",HT:"HTI",HM:"HMD",VA:"VAT",HN:"HND",HK:"HKG",HU:"HUN",IS:"ISL",IN:"IND",ID:"IDN",IR:"IRN",IQ:"IRQ",IE:"IRL",IM:"IMN",IL:"ISR",IT:"ITA",JM:"JAM",JP:"JPN",JE:"JEY",JO:"JOR",KZ:"KAZ",KE:"KEN",KI:"KIR",KP:"PRK",KR:"KOR",KW:"KWT",KG:"KGZ",LA:"LAO",LV:"LVA",LB:"LBN",LS:"LSO",LR:"LBR",LY:"LBY",LI:"LIE",LT:"LTU",LU:"LUX",MO:"MAC",MG:"MDG",MW:"MWI",MY:"MYS",MV:"MDV",ML:"MLI",MT:"MLT",MH:"MHL",MQ:"MTQ",MR:"MRT",MU:"MUS",YT:"MYT",MX:"MEX",FM:"FSM",MD:"MDA",MC:"MCO",MN:"MNG",ME:"MNE",MS:"MSR",MA:"MAR",MZ:"MOZ",MM:"MMR",NA:"NAM",NR:"NRU",NP:"NPL",NL:"NLD",NC:"NCL",NZ:"NZL",NI:"NIC",NE:"NER",NG:"NGA",NU:"NIU",NF:"NFK",MK:"MKD",MP:"MNP",NO:"NOR",OM:"OMN",PK:"PAK",PW:"PLW",PS:"PSE",PA:"PAN",PG:"PNG",PY:"PRY",PE:"PER",PH:"PHL",PN:"PCN",PL:"POL",PT:"PRT",PR:"PRI",QA:"QAT",RE:"REU",RO:"ROU",RU:"RUS",RW:"RWA",BL:"BLM",SH:"SHN",KN:"KNA",LC:"LCA",MF:"MAF",PM:"SPM",VC:"VCT",WS:"WSM",SM:"SMR",ST:"STP",SA:"SAU",SN:"SEN",RS:"SRB",SC:"SYC",SL:"SLE",SG:"SGP",SX:"SXM",SK:"SVK",SI:"SVN",SB:"SLB",SO:"SOM",ZA:"ZAF",GS:"SGS",SS:"SSD",ES:"ESP",LK:"LKA",SD:"SDN",SR:"SUR",SJ:"SJM",SE:"SWE",CH:"CHE",SY:"SYR",TW:"TWN",TJ:"TJK",TZ:"TZA",TH:"THA",TL:"TLS",TG:"TGO",TK:"TKL",TO:"TON",TT:"TTO",TN:"TUN",TR:"TUR",TM:"TKM",TC:"TCA",TV:"TUV",UG:"UGA",UA:"UKR",AE:"ARE",GB:"GBR",US:"USA",UM:"UMI",UY:"URY",UZ:"UZB",VU:"VUT",VE:"VEN",VN:"VNM",VG:"VGB",VI:"VIR",WF:"WLF",EH:"ESH",YE:"YEM",ZM:"ZMB",ZW:"ZWE"},rr=e=>nr[e]??e,or={street:"Street",area:"Geography",address:"Point Address"},ar=Object.fromEntries(Object.entries(tr).map(([e,t])=>[t,e])),ir=e=>{const{street:t,houseNumber:n,countryCodeIso2:r,...o}=e;return{...o,...t&&{streetName:t},...n&&{streetNumber:n},...r&&{countryCode:r,countryCodeISO3:rr(r)}}},sr=C.object({position:ne}),cr=C.object({geographyTypes:C.array(C.enum(u)).optional(),heading:C.number().min(-360).max(360).optional(),radiusMeters:C.number().positive().max(5e6).optional(),view:C.enum(S).optional()}),ur={requestValidation:{schema:sr.extend(cr.shape)},buildRequest:e=>{const[t,n]=d(e.position),r=new URL((e=>Le(e,"reverseGeocode"))(e)),o=r.searchParams;return o.append("position",`${t},${n}`),!A(e.radiusMeters)&&o.append("radiusInMeters",String(e.radiusMeters)),e.geographyTypes&&o.append("areaTypes",e.geographyTypes.map(e=>tr[e]).join(",")),!A(e.heading)&&o.append("vehicleHeadingInDegrees",String(e.heading)),e.view&&o.append("geopoliticalView",e.view),{url:r,headers:{...Re(e),Attributes:"results(*)"}}},getAPIVersion:()=>2,sendRequest:Z,parseResponse:(e,t)=>{const n=e.results[0];return{type:"Feature",geometry:I(d(t.position)),id:n?.id??s(),...n&&{properties:{type:or[n.type],address:{freeformAddress:n.title,...ir(n.address)},...n.areaType&&{geographyType:[ar[n.areaType]],dataSources:{geometry:{id:n.id}}},...n.accessPoints?.length&&{entryPoints:n.accessPoints.map(e=>({position:e.position.coordinates}))},originalPosition:n.position.coordinates}}}}},lr=async e=>W(e,ur,"ReverseGeocode"),dr=["tollVignette","tollRoad","roadShields","importantRoadStretch"],pr=e=>{const t=["summary","legs(summary,path)"],n=e.sectionTypes;if(!n||n.length>0){t.push("sections");const r=!n;for(const e of dr)(r||n.includes(e))&&t.push(`sections.${e}`);e.guidance&&(r||n.includes("lanes"))&&t.push("sections.lanes")}0!==e.extendedRouteRepresentations?.length&&t.push("progressPoints"),e.guidance&&t.push("instructions(*,nextRoadInformation.roadShields.iconReference,previousRoadInformation.roadShields.iconReference,signpost.exitIconReference,distanceToPreviousTrafficLightInMeters)");const r=`routes(${t.join(",")})`;return e.guidance?`roadShieldAtlasReference,${r}`:r},mr=e=>{const t=e.state?.heading;return{...Vn(e),...!A(t)&&{vehicleHeadingInDegrees:t}}},gr=(e,t)=>{Yn(e,t),qt(e.searchParams,(e=>{const t=Vt(e),n={};if(!t)return n;const r=t;if(!A(r.minChargeAtDestinationInkWh)||!A(r.minChargeAtChargingStopsInkWh))return Bt(n,"minChargeAtDestinationInkWh",r.minChargeAtDestinationInkWh),Bt(n,"minChargeAtChargingStopsInkWh",r.minChargeAtChargingStopsInkWh),n;const o=Gt(e);if(!o)return n;const a=t;return A(a.minChargeAtDestinationPCT)||(n.minChargeAtDestinationInkWh=String(Ot(o,a.minChargeAtDestinationPCT))),A(a.minChargeAtChargingStopsPCT)||(n.minChargeAtChargingStopsInkWh=String(Ot(o,a.minChargeAtChargingStopsPCT))),n})(t))},hr=e=>!!e.vehicle&&!!Vt(e.vehicle),yr="vehicle.model.variantId is only supported for EV routes with charging stops: set vehicle.preferences.chargingPreferences, or describe the vehicle with vehicle.model.dimensions and vehicle.model.engine instead.",fr=e=>{const t=(e=>Array.isArray(e)?e:e.geometry.coordinates)(e),n=(e=>{if(!Array.isArray(e))return e.properties?.sections?.leg})(e);if(n&&n.length>1&&n.every(e=>null!=e.startPointIndex&&null!=e.endPointIndex)){const e=n.map(e=>{const n=e.startPointIndex??0,r=e.endPointIndex??0;return{coordinate:t[n],legToNext:{path:{type:"LineString",coordinates:t.slice(n,r+1)}}}});return e.push({coordinate:t[n.at(-1)?.endPointIndex??t.length-1]}),e}return[{coordinate:t[0],legToNext:{path:{type:"LineString",coordinates:t}}},{coordinate:t.at(-1)??t[0]}]},Tr=e=>{if(!Array.isArray(e)&&"properties"in e)return e.properties??void 0},Rr=e=>{const t=e.options;if(!t)return{};const n={...t.pauseDurationSeconds&&{pauseDurationInSeconds:t.pauseDurationSeconds},...t.candidateEntryPoints?.length&&{entryPoints:(r=t.candidateEntryPoints,{type:"MultiPoint",coordinates:r.map(e=>d(e))}),...!A(t.preferredEntryPointIndex)&&{preferredEntryPointIndex:t.preferredEntryPointIndex}}};var r;return{...t.legCostModel?.routeType&&{routeType:t.legCostModel.routeType},...t.legCostModel?.avoid?.length&&{avoids:t.legCostModel.avoid.map(e=>({name:e}))},...Object.keys(n).length>0&&{routeStop:n}}},Ir=(e,t)=>{t.computeTravelTimeFor&&e.searchParams.set("computeTravelTimeFor",t.computeTravelTimeFor)},br=C.union([ne,X]),Sr=C.union([Q,ee]),Cr=C.object({locations:C.array(C.union([br,Sr])).min(1)}),vr=C.object({arrivalSide:C.enum(["any","curb"]).optional(),chargingStopsStrategy:C.enum(["automaticFastest","manualFastest","automaticFastestWithFallbackToManual"]).optional(),computeTravelTimeFor:C.enum(["none","all"]).optional(),maxAlternatives:C.number().min(0).max(5).optional(),sectionTypes:C.array(C.enum(m)).optional()}),Ar={schema:wn.extend(Cr.extend(vr.shape).shape),refinements:[{check:e=>{const t=e.locations.map(p),n=t.filter(e=>"waypoint"===e).length,r=t.filter(e=>"path"===e).length;return n>=2||r>=1},message:"At least 2 waypoints or 1 path (route reconstruction) is required."},{check:e=>!e.chargingStopsStrategy||hr(e),message:"chargingStopsStrategy: set vehicle.preferences.chargingPreferences as well — an EV route needs a minimum charge at the destination, which only the charging preferences provide."},{check:e=>!(e.vehicle&&jn(e.vehicle))||hr(e),message:yr},{check:e=>{const t=e.locations.at(-1);return!t||"waypoint"!==p(t)||!t.properties?.pauseDurationSeconds},message:"pauseDurationSeconds is not supported on the destination: the routing API requires the wait on the last leg to be 0."}]},Pr={other:"unknown",accident:"accident",fog:"fog",danger:"dangerousConditions",rain:"rain",frost:"ice",jam:"jam","lane-closed":"laneClosed","road-closed":"roadClosed",roadworks:"roadWorks",wind:"wind",flooding:"flooding","broken-down-vehicle":"brokenDownVehicle"},Lr=new Map(Object.entries(Pr)),Mr=new Map(b.map(e=>[Pr[e],e])),Er=new Map(Object.entries({unknown:"unknown",minor:"minor",moderate:"moderate",major:"major",undefined:"indefinite"})),wr=e=>Lr.get(e)??e,Dr=e=>Mr.get(e)??"other",Or=e=>Er.get(e)??"unknown",Nr=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},xr=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,o=[r.coordinate.longitude,r.coordinate.latitude],a=[r.street,r.houseNumber].filter(Boolean),i=a.length>0?a.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:o},properties:{...M(e,["chargingConnectionInfo","chargingParkLocation"]),type:"POI",address:{freeformAddress:i,...r.street&&{streetName:r.street},...r.houseNumber&&{streetNumber:r.houseNumber},...r.city&&{municipality:r.city},...r.region&&{countrySubdivision:r.region},...r.postalCode&&{postalCode:r.postalCode},...r.country&&{country:r.country}},...n&&{chargingConnectionInfo:{plugType:n.chargingPlugType,currentInA:n.chargingCurrentInA,voltageInV:n.chargingVoltageInV,chargingPowerInkW:n.chargingPowerInkW,currentType:Nr(n.chargingCurrentType),chargingSpeed:Ne(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:Ne(e.chargingParkPowerInkW)}}}},Br=(e,t)=>{const n=t?.vehicle&&Gt(t.vehicle);return{lengthInMeters:e.lengthInMeters,travelTimeInSeconds:e.travelDurationInSeconds,trafficDelayInSeconds:e.trafficDelayDurationInSeconds??0,trafficLengthInMeters:e.trafficLengthInMeters??0,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,departureTime:new Date(e.departureDateTime),arrivalTime:new Date(e.arrivalDateTime),deviationDistanceInMeters:e.deviationDistanceInMeters,deviationTimeInSeconds:e.deviationDurationInSeconds,...e.deviationPoint&&{deviationPoint:e.deviationPoint.coordinates},fuelConsumptionInLiters:e.fuelConsumptionInLiters,totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh,...n&&(()=>{const t=e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh;return t?{batteryConsumptionInPCT:100*t/n}:void 0})(),remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:xr(e.chargingInformationAtEndOfLeg,n)}}},Hr=(e,t)=>e.reduce((n,r,o)=>{const a=r.path.coordinates.length,i=0===o?0:n[o-1]?.endPointIndex;let c;A(i)||(c=0===i?Math.max(a-1,0):i+a);const u=((e,t)=>{if(!t)return;const n=new Date(e.summary.arrivalDateTime).getTime(),r=new Date(t.summary.departureDateTime).getTime();if(Number.isNaN(n)||Number.isNaN(r))return;const o=Math.round((r-n)/1e3);return o>0?o:void 0})(r,e[o+1]),{originalWaypointIndexAtEndOfLeg:l}=r.summary;return n.push({...!A(i)&&{startPointIndex:i},...void 0!==c&&{endPointIndex:c},...!A(l)&&{originalWaypointIndex:l},summary:{...Br(r.summary,t),...void 0!==u&&{stopTimeInSeconds:u}},id:s()}),n},[]),_r=e=>({id:s(),startPointIndex:e.startPathIndex,endPointIndex:e.endPathIndex}),Fr=(e,t)=>{const n={leg:Hr(e.legs,t)},r=e.sections;if(!r)return n;const o=(e,t)=>{t?.length&&(n[e]=t.map(_r))};return o("carTrain",r.carTrain),o("ferry",r.ferry),o("tunnel",r.tunnel),o("motorway",r.motorway),o("pedestrian",r.pedestrian),o("toll",r.toll),o("tollRoad",r.tollRoad),o("carpool",r.carpool),o("urban",r.urban),o("unpaved",r.unpaved),o("lowEmissionZone",r.lowEmissionZone),r.country?.length&&(n.country=r.country.map(e=>({..._r(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:rr(e.countryCodeIso2??"")}))),r.travelMode?.length&&(n.vehicleRestricted=r.travelMode.filter(e=>"other"===e.travelMode).map(_r)),r.traffic?.length&&(n.traffic=r.traffic.map(e=>{return{..._r(e),delayInSeconds:e.delayDurationInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKilometersPerHour,categories:(t=e,t.tec?.causes?.length?t.tec.causes.map(e=>{switch(e.mainCauseCode){case 1:return"jam";case 2:return"accident";case 3:return"roadworks";case 4:return"narrow-lanes";case 5:return"road-closed";case 9:return"danger";case 11:return"animals-on-road";case 13:return"broken-down-vehicle";case 16:return"lane-closed";case 17:return"wind";case 18:return"fog";case 19:return"rain";case 22:return"frost";case 23:return"flooding";default:return"other"}}):[Dr(t.iconCategory)]),magnitudeOfDelay:Or(e.delayMagnitude),tec:e.tec,...e.eventId&&{eventId:e.eventId}};var t})),r.speedLimit?.length&&(n.speedLimit=r.speedLimit.map(e=>{const t=e.speedRestrictions?.find(e=>"maximum"===e.type)?.inKilometersPerHour;return A(t)?void 0:{..._r(e),maxSpeedLimitInKmh:t}}).filter(e=>!!e)),r.lanes?.length&&(n.lanes=r.lanes.map(e=>({..._r(e),lanes:(e.lanes??[]).map(e=>({directions:e.directions.map(e=>Vr[e]??e),...e.follow&&{follow:Vr[e.follow]??e.follow}})),laneSeparators:(e.laneSeparators??[]).map(e=>qr[e]??e),properties:e.properties}))),r.roadShields?.length&&(n.roadShields=r.roadShields.map(e=>({..._r(e),roadShieldReferences:e.roadShieldReferences}))),r.tollVignette?.length&&(n.tollVignette=r.tollVignette.map(e=>({..._r(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:rr(e.countryCodeIso2??"")}))),r.importantRoadStretch?.length&&(n.importantRoadStretch=r.importantRoadStretch.map(e=>({..._r(e),index:e.importantRoadStretchIndex,...e.streetName&&{streetName:e.streetName.text},...e.roadNumbers?.length&&{roadNumbers:e.roadNumbers.map(e=>e.text)}}))),((e,t)=>{if(!t)return;const n=new Set(t);for(const r of Object.keys(e))"leg"===r||n.has(r)||delete e[r]})(n,t.sectionTypes),n},Ur=1e-4,Gr=(e,t)=>Math.abs(e[0]-t[0])<Ur&&Math.abs(e[1]-t[1])<Ur,kr={depart:"DEPART",waypointLeft:"WAYPOINT_LEFT",waypointRight:"WAYPOINT_RIGHT",waypointReached:"WAYPOINT_REACHED",waypointAhead:"WAYPOINT_AHEAD",arrive:"ARRIVE",arriveLeft:"ARRIVE_LEFT",arriveRight:"ARRIVE_RIGHT",arriveAhead:"ARRIVE_AHEAD",continueStraight:"STRAIGHT",keepLeft:"KEEP_LEFT",keepRight:"KEEP_RIGHT",turnSlightRight:"SLIGHT_RIGHT",turnRight:"TURN_RIGHT",turnSharpRight:"SHARP_RIGHT",turnSlightLeft:"SLIGHT_LEFT",turnLeft:"TURN_LEFT",turnSharpLeft:"SHARP_LEFT",makeUTurn:"MAKE_UTURN",roundaboutStraight:"ROUNDABOUT_STRAIGHT",roundaboutSharpRight:"ROUNDABOUT_SHARP_RIGHT",roundaboutRight:"ROUNDABOUT_RIGHT",roundaboutSlightRight:"ROUNDABOUT_SLIGHT_RIGHT",roundaboutSlightLeft:"ROUNDABOUT_SLIGHT_LEFT",roundaboutLeft:"ROUNDABOUT_LEFT",roundaboutSharpLeft:"ROUNDABOUT_SHARP_LEFT",roundaboutBack:"ROUNDABOUT_BACK",exitRoundabout:"EXIT_ROUNDABOUT",exitMotorwayLeft:"EXIT_MOTORWAY_LEFT",exitMotorwayRight:"EXIT_MOTORWAY_RIGHT",switchMotorwayLeft:"SWITCH_MOTORWAY_LEFT",switchMotorwayRight:"SWITCH_MOTORWAY_RIGHT",enterCarpoolLaneLeft:"ENTER_CARPOOL_LANE_LEFT",enterCarpoolLaneRight:"ENTER_CARPOOL_LANE_RIGHT",exitCarpoolLaneLeft:"EXIT_CARPOOL_LANE_LEFT",exitCarpoolLaneRight:"EXIT_CARPOOL_LANE_RIGHT",mergeLeftLane:"MERGE_LEFT_LANE",mergeRightLane:"MERGE_RIGHT_LANE",takeShipFerry:"TAKE_SHIP_FERRY",takeCarTrain:"TAKE_CAR_TRAIN",leaveShipFerry:"LEAVE_SHIP_FERRY",leaveCarTrain:"LEAVE_CAR_TRAIN",crossBorder:"CROSS_BORDER",passTollgate:"TOLLGATE"},Kr={urban:"URBAN",motorway:"MOTORWAY",controlledAccess:"CONTROLLED_ACCESS"},Wr={endOfRoad:"END_OF_ROAD",atTrafficLight:"AT_TRAFFIC_LIGHT",onToBridge:"ON_TO_BRIDGE",onBridge:"ON_BRIDGE",afterBridge:"AFTER_BRIDGE",intoTunnel:"INTO_TUNNEL",insideTunnel:"INSIDE_TUNNEL",afterTunnel:"AFTER_TUNNEL"},jr={cashCoinsAndBills:"CASH_COINS_AND_BILLS",cashBillsOnly:"CASH_BILLS_ONLY",cashCoinsOnly:"CASH_COINS_ONLY",cashExactChange:"CASH_EXACT_CHANGE",creditCard:"CREDIT_CARD",debitCard:"DEBIT_CARD",travelCard:"TRAVEL_CARD",etc:"ETC",etcTransponder:"ETC_TRANSPONDER",etcVideoCamera:"ETC_VIDEO_CAMERA",subscription:"SUBSCRIPTION"},Vr={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",rightUTurn:"RIGHT_U_TURN",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",leftUTurn:"LEFT_U_TURN"},qr={unknown:"UNKNOWN",noMarking:"NO_MARKING",longDashed:"LONG_DASHED",doubleSolid:"DOUBLE_SOLID",singleSolid:"SINGLE_SOLID",solidDashed:"SOLID_DASHED",dashedSolid:"DASHED_SOLID",shortDashed:"SHORT_DASHED",shadedAreaMarking:"SHADED_AREA_MARKING",dashedBlocks:"DASHED_BLOCKS",doubleDashed:"DOUBLE_DASHED",crossingAlert:"CROSSING_ALERT",physicalDivider:"PHYSICAL_DIVIDER",physicalDividerLessThan3m:"PHYSICAL_DIVIDER_LESS_THAN_3M",physicalDividerGuardrail:"PHYSICAL_DIVIDER_GUARDRAIL",curb:"CURB"},Yr={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",back:"BACK"},$r={regular:"REGULAR",small:"SMALL"},Zr={left:"LEFT",right:"RIGHT",leftAndRight:"LEFT_AND_RIGHT"},zr={properties:[]},Jr=e=>({text:e.text}),Qr=e=>({properties:(e.properties??[]).map(e=>Kr[e]??e.toUpperCase()),...e.roadNames?.length&&{streetName:Jr(e.roadNames[0].identifier)},...e.countryCodeIso2&&{countryCode:rr(e.countryCodeIso2)},...e.roadShields?.length&&{roadShields:e.roadShields.map(e=>({roadNumber:e.roadNumber?Jr(e.roadNumber):{text:""},countryCode:rr(e.countryCodeIso2??""),...e.countrySubdivisionCodeIso&&{stateCode:e.countrySubdivisionCodeIso},...e.iconReference&&{roadShieldReference:e.iconReference}}))}}),Xr=e=>({...e.tollgateName&&{tollgateName:Jr(e.tollgateName)},...e.tollPaymentTypes?.length&&{tollPaymentTypes:e.tollPaymentTypes.map(e=>jr[e]??e)},...e.countryCrossingFromName&&{countryCrossingFromName:Jr(e.countryCrossingFromName)},...e.countryCrossingFromCodeIso2&&{countryCrossingFromCode:rr(e.countryCrossingFromCodeIso2)},...e.countryCrossingToName&&{countryCrossingToName:Jr(e.countryCrossingToName)},...e.countryCrossingToCodeIso2&&{countryCrossingToCode:rr(e.countryCrossingToCodeIso2)}}),eo=e=>Yr[e]??e,to=e=>{return{...e.message&&{message:e.message},...e.intersectionName&&{intersectionName:Jr(e.intersectionName)},...e.drivingSide&&{drivingSide:e.drivingSide.toUpperCase()},...e.landmark&&{landmark:Wr[e.landmark]??e.landmark},...!A(e.distanceToPreviousTrafficLightInMeters)&&{trafficLightOffsetInMeters:e.distanceToPreviousTrafficLightInMeters},...e.sideRoads&&{sideRoads:(n=e.sideRoads,n.map(e=>({side:Zr[e.side]??e.side,offsetFromManeuverInMeters:e.offsetFromManeuverInMeters,...!A(e.isDrivable)&&{isDrivable:e.isDrivable}})))},...e.maneuverView&&{maneuverView:(t=e.maneuverView,{...t.onRouteAngle&&{onRouteAngle:eo(t.onRouteAngle)},offRouteAngles:(t.offRouteAngles??[]).map(eo)})},...e.roundaboutType&&{roundaboutType:$r[e.roundaboutType]??e.roundaboutType},...!A(e.isManeuverObligatory)&&{isManeuverObligatory:e.isManeuverObligatory},...!A(e.changeOfAngleInDegrees)&&{changeOfAngleInDegrees:e.changeOfAngleInDegrees},...!A(e.ambiguousExitOffsetFromManeuverInMeters)&&{offsetOfAmbiguousExitFromManeuverInMeters:e.ambiguousExitOffsetFromManeuverInMeters},...!A(e.roundaboutExitNumber)&&{roundaboutExitNumber:e.roundaboutExitNumber}};var t,n},no=(e,t)=>{const n=e.signpost?(e=>{if(e.exitName||e.exitNumber||e.towardName)return{...e.exitName&&{exitName:Jr(e.exitName)},...e.exitNumber&&{exitNumber:Jr(e.exitNumber)},towardName:e.towardName?Jr(e.towardName):{text:""}}})(e.signpost):void 0,r=(e.nextRoadInformation?.roadShields??[]).map(e=>e.iconReference).filter(e=>!!e);return{...n&&{signpost:n},...t&&{roadShieldAtlasReference:t},...r.length&&{roadShieldReferences:r},...e.signpost?.exitIconReference&&{signpostRoadShieldReferences:[e.signpost.exitIconReference]}}},ro=(e,t,n,r)=>({maneuverPoint:t,pathPointIndex:n,routeOffsetInMeters:e.routeOffsetInMeters,maneuver:e.maneuver?kr[e.maneuver]??e.maneuver:e.maneuver,routePath:(e.routePath??[]).map(e=>({point:e.point.coordinates,distanceInMeters:e.distanceFromRouteStartInMeters,travelTimeInSeconds:e.travelTimeFromRouteStartInSeconds})),nextRoadInfo:e.nextRoadInformation?Qr(e.nextRoadInformation):zr,previousRoadInfo:e.previousRoadInformation?Qr(e.previousRoadInformation):zr,...to(e),...no(e,r),...Xr(e)}),oo=(e,t,n)=>{const r=[];let o=0;for(const a of e){const e=a.maneuverPoint.coordinates;for(let n=o;n<t.length;n++)if(Gr(t[n],e)){o=n;break}r.push(ro(a,e,o,n))}return{instructions:r}},ao={requestValidation:Ar,buildRequest:e=>{const t=e.locations.map(p).includes("path"),n=((e,t)=>{const n=[];for(const r of e)if("waypoint"===p(r)){const e=Tr(r),o=e?.candidateEntryPoints?.length?"ignore":t,[a,i]=d(r,{useEntryPoint:o});n.push({coordinate:[a,i],...e&&{options:e}})}else n.push(...fr(r));return n})(e.locations,e.useEntryPoints),r=(e=>{const t={type:"Point",coordinates:e[0].coordinate},n={type:"Point",coordinates:(e.at(-1)??e[0]).coordinate},r=e.slice(1,-1);return{origin:t,destination:n,...r.length&&{waypoints:{type:"MultiPoint",coordinates:r.map(e=>e.coordinate)}}}})(n),a=(e=>{return{...Wn(e),...e.maxAlternatives&&{maxPathAlternativeRoutes:e.maxAlternatives},..."arriveBy"===e.when?.option&&e.when.date&&{arrivalDateTime:e.when.date.toISOString()},...e.guidance&&{guidance:"instructions",instructionPhonetics:"ipa"},...e.costModel?.avoidAreas?.length&&{avoidAreas:(t=e.costModel.avoidAreas,{rectangles:t.map(e=>{const t=o(e);if(!t)throw new Error("Could not derive a bounding box from an avoidAreas rectangle");const[n,r,a,i]=t;return{type:"Feature",bbox:[n,r,a,i],geometry:null}})})},...e.arrivalSide&&{arrivalSidePreference:"curb"===e.arrivalSide?"curbSide":"anySide"}};var t})(e),i=(e=>({...Re(e),Attributes:pr(e)}))(e),s=((e,t)=>{const n=e.slice(1).map((t,n)=>({...e[n].legToNext,...Rr(t)}));if(t||!n.every(e=>0===Object.keys(e).length))return n})(n,t),c={routePlanningLocations:r,...a,...s&&{legs:s},...e.vehicle&&mr(e.vehicle)};if(hr(e)){const t=((e,t,n)=>{const r=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateLongDistanceEVRoute`,o=new URL(r);gr(o,e.vehicle),e.chargingStopsStrategy&&o.searchParams.set("chargingStopsStrategy",e.chargingStopsStrategy);const a=xt(e.vehicle)?.charging;if(!jn(e.vehicle)&&!a?.chargingConnectors?.length)throw new Error("Charging preferences require a charging model: set vehicle.model.engine.charging.chargingConnectors (or a predefined vehicle.model.variantId) to plan charging stops.");return{method:"POST",url:o,data:{...t,...a&&{chargingParameters:{...a.batteryCurve?.length&&{batteryCurve:a.batteryCurve},...a.chargingConnectors?.length&&{chargingConnectors:[...a.chargingConnectors]},...!A(a.chargingTimeOffsetInSec)&&{chargingTimeOffsetInSec:a.chargingTimeOffsetInSec}}},vehicleEngineType:"electric"},headers:n}})(e,c,i);return Ir(t.url,e),t}if(e.vehicle&&jn(e.vehicle))throw new Error(yr);const u=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/routes/calculate`,l=new URL(u);return e.vehicle&&qn(l,e.vehicle),Ir(l,e),{method:"POST",url:l,data:c,headers:i}},sendRequest:J,parseResponse:(e,t)=>{const n=e.routes.map((n,r)=>((e,t,n,r)=>{const a={type:"LineString",coordinates:e.legs.flatMap(e=>e.path.coordinates)};return{type:"Feature",geometry:a,id:s(),bbox:o(a),properties:{index:t,summary:Br(e.summary,n),sections:Fr(e,n),...e.instructions?.length&&{guidance:oo(e.instructions,a.coordinates,r)},...e.progressPoints&&{progress:e.progressPoints.map(e=>({pointIndex:e.pathIndex,distanceInMeters:e.distanceInMeters,travelTimeInSeconds:e.travelDurationInSeconds}))}}}})(n,r,t,e.roadShieldAtlasReference)),r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},parseResponseError:Dt,getAPIVersion:()=>3},io=async e=>W(e,ao,"Routing"),so=C.object({minFuzzyLevel:C.number().min(1).max(4).optional(),maxFuzzyLevel:C.number().min(1).max(4).optional()}),co=ce.extend(nt.extend(so.shape).shape),uo=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:_e(e.details)}};break;case"NEARBY":t={...e,details:{position:_e({lon:e.details.lon,lat:e.details.lat}),text:e.details.text,query:e.details.query}};break;case"BOOKMARK":case"W3W":t=e}return t},lo={requestValidation:{schema:co},buildRequest:e=>{const t=new URL(`${(e=>Le(e,`search/${encodeURIComponent(e.query??"")}.json`))(e)}`);Pe(t,e);const n=t.searchParams;return ve(n,"typeahead",e.typeahead),ve(n,"ofs",e.offset),Ce(n,"countrySet",e.countries),Ae(n,e.geoBias),ve(n,"minFuzzyLevel",e.minFuzzyLevel),ve(n,"maxFuzzyLevel",e.maxFuzzyLevel),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>{const t=e.results.map(ke),n=a(o(t)),r=e.summary.queryIntent?.map(uo);return{type:"FeatureCollection",properties:{...Ke(e.summary),...r&&{queryIntent:r}},features:t,...n&&{bbox:n}}}},po=C.object({geometries:C.array(C.union([te,X]))}),mo=ce.extend(po.shape),go=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:Be(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:fe(e.coordinates[0],50).map(e=>Be(e))}];case"MultiPolygon":return e.coordinates.length>50?(e=>{let t=/* @__PURE__ */new Map;return e.coordinates.forEach(e=>{const n=r(e[0]);if(n){const r=Math.abs((n[2]-n[0])*(n[3]-n[1]));t.set(e,r)}}),t=new Map([...t.entries()].sort((e,t)=>t[1]-e[1]).splice(0,50)),[...t.keys()]})(e).flatMap(e=>go({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>go({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>go(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},ho={requestValidation:{schema:mo},buildRequest:e=>{const t=new URL(`${n=e,Le(n,`geometrySearch/${encodeURIComponent(n.query??"")}.json`)}`);var n;return Pe(t,e),{url:t,headers:be(e),data:{geometryList:e.geometries.flatMap(go)}}},sendRequest:z,parseResponse:e=>{const t=e.results.map(ke),n=a(o(t));return{type:"FeatureCollection",properties:{...Ke(e.summary)},features:t,...n&&{bbox:n}}}},yo=async e=>"route"in e?je(e):"geometries"in e?(async e=>W(e,ho,"GeometrySearch"))(e):(async e=>W(e,lo,"FuzzySearch"))(e),fo=async e=>Xe("discoverOnePlace",e,yo),To=C.object({query:C.string()}),Ro=C.object({geoBias:et.optional(),limit:C.number().max(100).optional(),countries:C.array(C.string()).optional(),resultTypes:C.array(C.string()).optional()}),Io=To.extend(Ro.shape),bo={requestValidation:{schema:Io},buildRequest:e=>{const t=new URL(`${n=e,Le(n,`autocomplete/${encodeURIComponent(n.query)}.json`)}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",Se(r,e),ve(r,"limit",e.limit),Ae(r,e.geoBias),Ce(r,"countrySet",e.countries),Ce(r,"resultSet",e.resultTypes),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:_e(t)},radiusMeters:n.radius}},results:(r=e.results,r.map(e=>({segments:e.segments.map(e=>{if((e=>"category"===e.type)(e)){const{id:t,...n}=e;return{...n,category:R[Number(t)]}}return e})})))};var r}},So=async e=>W(e,bo,"Autocomplete"),Co=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean),vo=e=>"category"===e.type&&e.matchedAlternativeName?[e.value,e.matchedAlternativeName]:[e.value],Ao=(e,t)=>{const n=t.flatMap(({segments:t})=>{const[n]=t;return 1===t.length&&"plaintext"!==n.type&&vo(n).some(t=>((e,t)=>{const n=Co(t).join(""),r=Co(e);return""!==n&&r.some((e,t)=>r.slice(t).join("").startsWith(n))})(t,e))?[n]:[]});return n.find(t=>vo(t).some(t=>((e,t)=>{const[n,...r]=Co(t);return 0===r.length&&Co(e).some(e=>e.startsWith(n)&&2*n.length>=e.length)})(t,e)))??n[0]},Po=({query:e,concept:t,places:n,maxResults:r})=>{const o=D(n,e=>e.id),a="none"===t.status?o:E(o,t=>((e,t)=>{const n=Co(e);return Co(t).every(e=>n.some(t=>t.startsWith(e)))})(t.title,e)).flat();return[..."shown"===t.status?[t.suggestion]:[],...a].slice(0,r)},Lo="SearchSuggestions",Mo={brand:!0,category:!0},Eo=e=>e in Mo,wo={place:["POI"],address:["PAD","Addr","XStr"],street:["Str"],area:["Geo"]},Do={POI:"place",Street:"street",Geography:"area","Point Address":"address","Address Range":"address","Cross Street":"address"},Oo=e=>e*Math.PI/180,No=(e,t)=>e.properties.distance??(t&&(([e,t],[n,r])=>{const o=Math.sin(Oo(r-t)/2)**2+Math.cos(Oo(t))*Math.cos(Oo(r))*Math.sin(Oo(n-e)/2)**2;return 12742017.6*Math.asin(Math.sqrt(o))})(t,e.geometry.coordinates)),xo=(e,t)=>{const n=l(t)??void 0,r=((e,t)=>{if(t)return L(e,e=>No(e,t))?.properties.address.countryCode;const n=v(e,e=>e.properties.address.countryCode);return P(Object.keys(n),e=>n[e])})(e,n);return e.map(e=>((e,t,n)=>{const{type:r,address:o,poi:a}=e.properties,i=o.freeformAddress.split(", ").filter(Boolean),[s="",...c]=a?.name?[a.name,...i]:i,u=o.countryCode!==t?o.country:void 0;return{kind:Do[r],id:String(e.id),title:s,subtitles:u?[...c,u]:c,distanceInMeters:No(e,n),resolve:async()=>({...e,properties:M(e.properties,["distance","score"])})}})(e,r,n))},Bo=e=>{if(e instanceof H)throw new H(Lo,e.cause);if(e instanceof B)throw new B(e.message,Lo,e.status);if(e instanceof N)throw new N(e.message,Lo,e.issues);throw e},Ho=(e,t)=>{const n={...t,..."brand"===e.type?{poiBrands:[e.value]}:{poiCategories:[e.category]}},r={title:e.value,refineParams:n,refine:e=>yo({...n,...e&&{signal:e}})};return"brand"===e.type?{...r,kind:"brand"}:{...r,kind:"category",category:e.category}},_o=(e,t)=>D(e.flatMap(e=>e.segments.flatMap(e=>"plaintext"===e.type?[]:[Ho(e,t)])),e=>`${e.kind}:${e.title}`),Fo=(e,t,n,r)=>{const o=Ao(e,t);return o?"brand"!==o.type||((e,t)=>{const n=Co(e).join("");return t.slice(0,5).some(e=>e.properties.poi?.brands?.some(e=>Co(e).join("")===n))})(o.value,n)?{status:"shown",suggestion:Ho(o,r)}:{status:"withheld"}:{status:"none"}},Uo=async e=>{const{query:t,maxResults:n,filters:r,origin:o,view:a,signal:i,...s}=e,c=r?.countries,u=Math.max(1,Math.min(n??5,10)),{placeKinds:l,refinementKinds:d,wantsPlaces:p,wantsRefinements:m}=(e=>{const t=e?.filter(e=>!Eo(e)),n=e?.filter(Eo);return{placeKinds:t,refinementKinds:n,wantsPlaces:!e||Boolean(t?.length),wantsRefinements:!e||Boolean(n?.length)}})(r?.kinds),g=o&&{position:o},h=(r?.boundingBox&&{boundingBox:r.boundingBox})??g,y={...M(s,["onAPIRequest","onAPIResponse","apiVersion"]),query:"",countries:c,geoBias:h,view:a},f={...s,signal:i,query:t,limit:10,countries:c,view:a,typeahead:!0,geoBias:h,indexes:l?.flatMap(e=>wo[e]),poiCategories:r?.poiTypes,geographyTypes:r?.areaTypes},[T,R]=await Promise.all([p?yo(f):void 0,m?So({...s,signal:i,query:t,limit:u,countries:c,geoBias:g,resultTypes:d??["brand","category"]}):void 0]).catch(Bo),I=R?.results??[];if(!p)return{suggestions:_o(I,y).slice(0,u)};const b=(T?.features??[]).filter(e=>!l||l.includes(Do[e.properties.type]));return{suggestions:Po({query:t,concept:Fo(t,I,b,y),places:xo(b,o),maxResults:u})}},Go=864e5,ko=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n},Ko=e=>ko(/* @__PURE__ */new Date,-e),Wo=e=>e instanceof Date?e.toISOString().slice(0,10):e,jo=e=>Date.parse(Wo(e)),Vo=/(?:Z|[+-]\d{2}:\d{2})$/,qo=e=>new Date(Vo.test(e)?e:`${e}Z`),Yo=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],$o={speed:{dataType:"SPEED",field:"v"},freeFlowSpeed:{dataType:"FREE_FLOW_SPEED",field:"fv"},congestionLevel:{dataType:"CONGESTION_LEVEL",field:"c"},travelTime:{dataType:"TRAVEL_TIME",field:"t"},networkLength:{dataType:"NETWORK_LENGTH",field:"l"}},Zo=Array.from({length:24},(e,t)=>t),zo=e=>Yo.indexOf(e),Jo=(e,n)=>{const r={};for(const o of t){const t=e[$o[o].field];void 0!==t&&(r[o]=n(t))}return r},Qo=e=>Jo(e,e=>e),Xo=e=>t.find(t=>$o[t].dataType===e),ea=e=>{const t=qo(e);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,date:new Date(jo(t)),hour:t.getUTCHours()}},ta={yearly:({year:e})=>({year:e}),monthly:({year:e,month:t})=>({year:e,month:t}),weekly:({date:e})=>(e=>{const t=ko(e,4-(e.getUTCDay()||7)),n=t.getUTCFullYear(),r=(t.getTime()-Date.UTC(n,0,1))/Go;return{year:n,week:Math.floor(r/7)+1}})(e),daily:({date:e})=>({date:e}),hourly:({date:e,hour:t})=>({date:e,hour:t})},na=(e,t)=>e.map(e=>({...ta[t](ea(e.time)),...Qo(e)})),ra={MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,SUNDAY:7},oa=e=>{const[t,n]=e.time.split("-"),r=Object.hasOwn(ra,t)?ra[t]:void 0;return void 0===r?void 0:{day:r,hour:Number(n),...Qo(e)}},aa=({day:e,hour:t})=>24*(e-1)+t,ia=e=>({tileCentre:[e.lon,e.lat],...Qo(e)}),sa=e=>({startDate:qo(e.startDate),endDate:qo(e.endDate),labels:e.labels.map(({name:e})=>e)}),ca=e=>{return{...e.yearly&&{yearly:na(e.yearly,"yearly")},...e.monthly&&{monthly:na(e.monthly,"monthly")},...e.weekly&&{weekly:na(e.weekly,"weekly")},...e.daily&&{daily:na(e.daily,"daily")},...e.hourly&&{hourly:na(e.hourly,"hourly")},...e.average&&{average:(t=e.average,t.map(oa).filter(e=>void 0!==e).sort((e,t)=>aa(e)-aa(t)))}};var t},ua=e=>Jo(e,e=>e.map(sa)),la=e=>{return{type:e.type,id:e.id,geometry:e.geometry,properties:(t=e.properties,{name:t.name,...void 0!==t.timezone&&{timezone:t.timezone},level:t.level,baseData:Qo(t.baseData),timedData:ca(t.timedData),...t.tiledData&&{tiledData:{tiles:t.tiledData.tiles.map(ia)}},...t.anomalies&&{anomalies:ua(t.anomalies)}}),bbox:o(e.geometry)};var t},da=e=>{const n=e.flatMap(e=>e.properties.tiledData?.tiles??[]),r={};for(const o of t){const e=n.map(e=>e[o]).filter(e=>null!=e);e.length>0&&(r[o]={min:Math.min(...e),max:Math.max(...e)})}return r},pa=e=>{const t=e.map(jo);return{startDate:new Date(Math.min(...t)),endDate:new Date(Math.max(...t))}},ma=C.union([C.date(),C.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),ga=C.union([C.object({type:C.literal("Polygon"),coordinates:C.array(C.array(C.array(C.number()))).min(1)}),C.object({type:C.literal("MultiPolygon"),coordinates:C.array(C.array(C.array(C.array(C.number())))).min(1)})]),ha=e=>jo(e)<=jo(Ko(2)),ya={requestValidation:{schema:G.extend({name:C.string().optional(),startDate:ma.optional(),endDate:ma.optional(),days:C.array(ma).min(1).optional(),metrics:C.union([C.array(C.enum(t)).min(1),C.literal("all")]),functionalRoadClasses:C.union([C.array(C.enum(Yo)).min(1),C.literal("all")]),hours:C.union([C.array(C.number().int().min(0).max(23)).min(1),C.literal("all")]),geometry:ga}).refine(e=>{const t=void 0!==e.days,n=void 0!==e.startDate;if(t&&n)return!1;if(!t&&!n)return!1;if(void 0!==e.startDate){const t=e.endDate??Ko(3),n=(jo(t)-jo(e.startDate))/Go;return n>=1&&n<=31}return!0},{message:"Provide either startDate (with optional endDate, at least 1 day apart and within 31 days) or days — but not both"}).refine(e=>void 0!==e.days?e.days.every(ha):void 0===e.endDate||ha(e.endDate),{message:"Dates must be at least 2 days before today"})},buildRequest:e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));Ie(n.searchParams,e);const r=Array.isArray(e.days)?{days:e.days.map(Wo)}:{startDate:Wo(e.startDate??Ko(4)),endDate:Wo(e.endDate??Ko(3))};return{method:"POST",url:n,data:{name:e.name??`Maps SDK JS Area Analytics Report ${/* @__PURE__ */(new Date).toISOString()}`,...r,dataTypes:("all"===e.metrics?t:e.metrics).map(e=>$o[e].dataType),frcs:"all"===e.functionalRoadClasses?Yo.map((e,t)=>t):e.functionalRoadClasses.map(zo),hours:"all"===e.hours?Zo:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},sendRequest:J,parseResponse:e=>{const t=e.features.map(la);return{type:"FeatureCollection",properties:{...pa(e.properties.days),metrics:e.properties.dataTypes.map(Xo).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:da(t)},features:t}}},fa=async e=>W(e,ya,"TrafficAreaAnalytics"),Ta=["incidents.type","incidents.geometry.type","incidents.geometry.coordinates",...Object.keys({id:!0,iconCategory:!0,magnitudeOfDelay:!0,"events.description":!0,"events.code":!0,"events.iconCategory":!0,startTime:!0,endTime:!0,from:!0,to:!0,lengthInMeters:!0,delayInSeconds:!0,roadNumbers:!0,timeValidity:!0,probabilityOfOccurrence:!0,numberOfReports:!0,lastReportTime:!0}).map(e=>`incidents.properties.${e}`)].join(","),Ra=e=>({description:e.description,code:e.code,category:Dr(e.iconCategory)}),Ia=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:Dr(t.iconCategory),magnitudeOfDelay:Or(t.magnitudeOfDelay),events:(t.events??[]).map(Ra),...t.startTime&&{startTime:new Date(t.startTime)},...t.endTime&&{endTime:new Date(t.endTime)},...t.from&&{from:t.from},...t.to&&{to:t.to},...null!=t.lengthInMeters&&{lengthInMeters:t.lengthInMeters},...null!=t.delayInSeconds&&{delayInSeconds:t.delayInSeconds},...t.roadNumbers&&{roadNumbers:t.roadNumbers},timeValidity:t.timeValidity,...t.probabilityOfOccurrence&&{probabilityOfOccurrence:t.probabilityOfOccurrence},...null!=t.numberOfReports&&{numberOfReports:t.numberOfReports},...t.lastReportTime&&{lastReportTime:new Date(t.lastReportTime)}}}},ba={requestValidation:{schema:G.extend({bbox:ae.optional(),ids:C.array(C.string()).optional(),categoryFilter:C.array(C.enum(b)).optional(),timeValidityFilter:C.array(C.enum(["present","future"])).optional()}).refine(e=>!(e.bbox&&e.ids),{message:"Provide either bbox or ids, not both"})},getAPIVersion:()=>2,buildRequest:e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidents/details`)(e)),n=t.searchParams;((e,t)=>{Ce(e,"iconCategories",t.categoryFilter?.map(wr)),Ce(e,"timeValidity",t.timeValidityFilter)})(n,e);const r=(e=>({...Re(e),Attributes:Ta}))(e);if(e.ids){const{ids:o}=e;return o.length>5?{method:"POST",url:t,headers:r,data:{ids:o}}:(n.append("ids",o.join(",")),{method:"GET",url:t,headers:r})}const a=o(e.bbox);return a&&n.append("bbox",a.join(",")),{method:"GET",url:t,headers:r}},sendRequest:J,parseResponse:e=>({type:"FeatureCollection",features:(e.incidents??[]).filter(e=>null!==e).map(Ia)})},Sa=async e=>W(e,ba,"TrafficIncidentDetails");export{x as APIErrorCode,H as SDKAbortError,N as SDKError,B as SDKServiceError,je as alongRouteSearch,Dn as budgetTypes,F as buildResponseError,U as buildValidationError,Qn as calculateReachableRange,er as calculateReachableRanges,io as calculateRoute,fo as discoverOnePlace,yo as discoverPlaces,Ze as evChargingStationsAvailability,it as geocode,st as geocodeOne,mt as geometryData,Et as getPOICategories,wt as getPOICategoryCodes,Tt as getPlaceDetails,ze as getPlaceWithEVAvailability,Je as getPlacesWithEVAvailability,Uo as getSearchSuggestions,Qe as hasChargingAvailability,_ as parseDefaultResponseError,lr as reverseGeocode,qe as routeTypes,Ye as tollTransponderOptions,fa as trafficAreaAnalytics,Sa as trafficIncidentDetails};
1
+ import{TomTomConfig as e,areaAnalyticsMetricKeys as t,avoidableTypes as n,bboxFromCoordsArray as r,bboxFromGeoJSON as o,bboxOnlyIfWithArea as a,currentTypes as i,generateId as s,generateTomTomHeaders as c,geographyTypes as l,getPosition as u,getPositionStrict as d,getRoutePlanningLocationType as p,inputSectionTypesWithGuidance as m,isProxyCredentialsMode as g,mergeFromGlobal as h,plugTypes as y,poiCategories as f,poiCategoriesToID as T,poiIDsToCategories as R,toPointGeometry as b,trafficIncidentRequestCategories as I,views as S}from"@tomtom-org/maps-sdk/core";import{z as C}from"zod";import{countBy as v,isNil as A,maxBy as P,minBy as L,omit as M,partition as E,pick as w,uniqBy as D}from"lodash-es";import{bbox as x,booleanIntersects as O}from"@turf/turf";var N=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),B=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},H={[N.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[N.FORBIDDEN]:"Request failed with status code 403"},_=class extends B{constructor(e,t,n){super(e,t),this.status=n,this.status&&H[this.status]&&(this.message=H[this.status])}},F=class extends B{constructor(e,t){super("The operation was aborted.",e),this.name="AbortError",this.cause=t}},U=(e,t)=>{const{data:n,message:r,status:o}=e;return new _(n?.error||n?.errorText||r,t,o)},G=(e,t,n,r)=>{if(r?.aborted&&e===r.reason)return new F(t,r.reason);if(r?.aborted&&"AbortError"===e?.name)return new F(t,r.reason);if(e.status){const r=e;return n?n(r,t):U(r,t)}return new B(e.message,t)},k=(e,t)=>new B(e.message,t,e.issues),K=C.object({apiKey:C.string().optional(),commonBaseURL:C.string().optional(),customServiceBaseURL:C.string().optional(),language:C.string().optional()}),W=(e,t=0)=>{const n=e.path.length>0?`${e.path.join(".")}: `:"";if("invalid_union"===e.code){const r=e.unionErrors;if(r?.length)return`${n}no matching union member (${r.map((e,n)=>`option[${n}]: { ${e.issues.map(e=>W(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},j=class extends Error{constructor(e){super(`${e.issues.map(e=>W(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},V=async(e,t,n)=>{if(e.signal?.aborted)throw new F(n,e.signal.reason);const r=t.getAPIVersion?.(e),o=h({...e,...r&&{apiVersion:r}});if(void 0===e.validateRequest||e.validateRequest)try{((e,t)=>{const n=(t?.schema?K.extend(t.schema.shape):K).superRefine((e,n)=>{if("commonBaseURL"in e||"customServiceBaseURL"in e||n.addIssue({code:"custom",message:"commonBaseURL or customServiceBaseURL is required"}),t?.refinements?.length)for(const r of t.refinements)r.check(e)||n.addIssue({code:"custom",message:r.message})}).safeParse(e);if(!n.success)throw new j(n.error)})(o,t.requestValidation)}catch(s){throw k(s,n)}const a=t.buildRequest(o),i=c(o);e.onAPIRequest?.(a);try{const n=await t.sendRequest(a,i,{signal:e.signal});return e.onAPIResponse?.(a,n),t.parseResponse(await n.data,o)}catch(s){throw e.onAPIResponse?.(a,s),G(s,n,t.parseResponseError,e.signal)}},q=class e extends Error{constructor(t,n,r){super(n??`HTTP Error ${t}`),this.name="FetchError",this.status=t,this.data=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Y=async e=>{if(e.ok)return{data:await e.json(),status:e.status};let t,n;const r=e.headers.get("content-type");throw e.bodyUsed?t=e.statusText:r?.includes("application/json")?(n=await e.json(),t=n?.errorText??n?.message??n?.detailedError?.message):r?.includes("text/xml")&&(n=await e.text(),t=e.statusText),new q(e.status,t,n)},$=(e,t)=>new Promise((n,r)=>{if(t?.aborted)return void r(t.reason);const o=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})}),Z=async(t,n)=>{const r=e.instance.get().retry;if(!r)return t();const{initialWaitMs:o,backoffFactor:a,timeoutMs:i}=r,s=Date.now();let c=o,l=await t();for(;429===l.status;){const e=Number.parseInt(l.headers.get("retry-after")??"",10),r=Number.isFinite(e)?1e3*e:c;if(Date.now()-s+r>i)break;await l.text().catch(()=>{}),await $(r,n),c*=a,l=await t()}return l},z=()=>g()?"include":void 0,J=async(e,t,n)=>Y(await Z(()=>{const r=z(),{url:o,headers:a}=e instanceof URL?{url:e,headers:void 0}:e,i={headers:{...t,...a}};return r&&(i.credentials=r),n?.signal&&(i.signal=n.signal),fetch(o,i)},n?.signal)),Q=async(e,t,n)=>Y(await Z(()=>{const r=z(),o={method:"POST",body:JSON.stringify(e.data),headers:{...t,...e.headers,"Content-Type":"application/json"}};return r&&(o.credentials=r),n?.signal&&(o.signal=n.signal),fetch(e.url,o)},n?.signal)),X=async(e,t,n)=>{if("GET"===e.method)return J(e,t,n);if("POST"===e.method)return Q(e,t,n);throw new Error(`Unsupported HTTP method received: ${e.method}`)},ee=C.array(C.array(C.number())),te=C.object({type:C.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:C.union([C.array(C.number()),ee,C.array(C.array(C.array(C.number()))),C.array(C.array(C.array(C.array(C.number()))))]),radius:C.optional(C.number()),radiusMeters:C.optional(C.number()),bbox:C.optional(C.array(C.number()))}).check(C.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),ne=C.object({type:C.literal("Feature"),geometry:te,id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),re=C.object({type:C.literal("FeatureCollection"),features:C.array(ne),id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),oe=C.union([C.tuple([C.number().min(-180).max(180),C.number().min(-90).max(90)]),C.tuple([C.number().min(-180).max(180),C.number().min(-90).max(90),C.number()]),C.object({type:C.literal("Point"),coordinates:C.array(C.number())}),ne]),ae=C.union([C.array(C.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),C.array(C.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),ie=C.union([te,ne,re]),se=C.union([ae,ie,C.array(ie)]),ce=C.object({query:C.string().optional(),position:oe.optional(),limit:C.number().max(100).optional(),extendedPostalCodesFor:C.array(C.string()).optional(),mapcodes:C.array(C.string()).optional(),view:C.enum(S).optional(),geographyTypes:C.array(C.string()).optional()}),le=C.object({indexes:C.array(C.string()).optional(),poiCategories:C.array(C.enum(f)).optional(),poiBrands:C.array(C.string()).optional(),connectors:C.array(C.string()).optional(),fuelTypes:C.array(C.string()).optional(),openingHours:C.string().optional(),timeZone:C.string().optional(),relatedPois:C.string().optional(),minPowerKW:C.number().optional(),maxPowerKW:C.number().optional(),minFuzzyLevel:C.number().optional(),maxFuzzyLevel:C.number().optional()}),ue=ce.extend(le.shape),de=C.object({type:C.literal("LineString"),coordinates:ee}),pe=C.object({type:C.literal("Feature"),geometry:de}),me=ee,ge=C.union([de,pe,me]),he=C.object({route:ge,maxDetourTimeSeconds:C.number().int().positive()}),ye=C.object({sortBy:C.enum(["detourTime","detourOffset"]).optional()}),fe=ue.extend({...he.shape,...ye.shape}),Te=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",Re=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let o;const a=Math.ceil(n/t);for(o=0;o<n;o+=a)r.push(e[o]);return t>1&&o>=n-a&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},be=e=>({...e.apiKey&&{"TomTom-Api-Key":e.apiKey},...!A(e.apiVersion)&&{"TomTom-Api-Version":String(e.apiVersion)}}),Ie=e=>({...be(e),...e.language&&{"Accept-Language":e.language}}),Se=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),t.apiKey&&e.append("key",t.apiKey),t.language&&e.append("language",t.language)},Ce=e=>be(e),ve=(e,t)=>{t.language&&e.append("language",t.language)},Ae=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},Pe=(e,t,n)=>{!A(n)&&e.append(t,String(n))},Le=(e,t)=>{if(!t)return;if(void 0!==t.position)return((e,t)=>{const n=u(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))})(e,t.position),void Pe(e,"radius",t.radiusMeters);const n=o(t.boundingBox);n&&(e.append("topLeft",Te([n[3],n[0]])),e.append("btmRight",Te([n[1],n[2]])))},Me=(e,t)=>{const n=e.searchParams;ve(n,t),Pe(n,"limit",t.limit),Ae(n,"fuelSet",t.fuelTypes),Ae(n,"idxSet",t.indexes),Ae(n,"brandSet",t.poiBrands),t.poiCategories&&Ae(n,"categorySet",t.poiCategories.map(e=>T[e])),Ae(n,"connectorSet",t.connectors),Ae(n,"mapcodes",t.mapcodes),Ae(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),Pe(n,"minPowerKW",t.minPowerKW),Pe(n,"maxPowerKW",t.maxPowerKW),Pe(n,"view",t.view),Pe(n,"openingHours",t.openingHours),Pe(n,"timeZone",t.timeZone),Pe(n,"relatedPois",t.relatedPois),Ae(n,"entityTypeSet",t.geographyTypes)},Ee=(e,t)=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/${t}`,we=e=>{const t={count:0,statusCounts:{}};for(const n of e)for(const e of n.chargingPoints)t.count++,t.statusCounts[e.status]=(t.statusCounts[e.status]||0)+1;return t},De=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,xe=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>De(r,e.connector));if(e){if(e.count++,t){const n=e.statusCounts;e.statusCounts[t]=(n[t]||0)+1}}else n.push({connector:r,count:1,statusCounts:t?{[t]:1}:{}})}},Oe=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>De(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Ne=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)xe(e.connectors,e.status,t);return t},Be=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",He=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},_e=e=>`${e[1]},${e[0]}`,Fe=e=>{let t,n;return(e=>void 0!==e.topLeftPoint)(e)?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=He(e.southWest),n=He(e.northEast)),[t[0],t[1],n[0],n[1]]},Ue=e=>[e.lon,e.lat],Ge=e=>{const{year:t,month:n,day:r}=(e=>{const t=e.split("-");return{year:Number.parseInt(t[0]),month:Number.parseInt(t[1]),day:Number.parseInt(t[2])}})(e.date);return{dateYYYYMMDD:e.date,year:t,month:n,day:r,hour:e.hour,minute:e.minute,date:new Date(t,n-1,r,e.hour,e.minute)}},ke=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,Ke=e=>{const t=e.timeRanges.map(e=>({start:Ge(e.startTime),end:Ge(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:ke(t)}},We=e=>{const{position:t,entryPoints:n,poi:r,id:o,dist:a,boundingBox:i,chargingPark:s,...c}=e,l=s?.connectors?.map(e=>({...M(e,"connectorType"),type:e.connectorType,chargingSpeed:Be(e.ratedPowerKW)}));return{type:"Feature",geometry:b(Ue(t)),...i&&{bbox:Fe(i)},id:o,properties:{...M(c,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:Ue(e.position)}))},...l?.length&&{chargingPark:{...s,connectors:Oe(l)}},...r&&{poi:{name:r.name,categories:(r.categorySet?.map(e=>R[e.id])??[]).filter(e=>!!e),localizedCategories:r.categories??[],...r.phone&&{phone:r.phone},...r.brands&&{brands:r.brands.map(e=>e.name)},...r.url&&{url:r.url},...r.openingHours&&{openingHours:Ke(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},je=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:Ue(t)},...n}},Ve={requestValidation:{schema:fe},buildRequest:e=>{const t=new URL((e=>Ee(e,`searchAlongRoute/${encodeURIComponent(e.query??"")}.json`))(e));Me(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),Pe(n,"sortBy",e.sortBy),Pe(n,"spreadingMode","plan"),{url:t,headers:Ce(e),data:{route:{points:(r=e.route,Array.isArray(r)?{type:"LineString",coordinates:r}:"Feature"===r.type?r.geometry:r).coordinates.map(e=>({lat:e[1],lon:e[0]}))}}};var r},sendRequest:Q,parseResponse:e=>{const t=e.results.map(We),n=a(o(t));return{type:"FeatureCollection",properties:{...je(e.summary)},features:t,...n&&{bbox:n}}}},qe=async e=>V(e,Ve,"AlongRouteSearch"),Ye=K.extend({id:C.string()}),$e=["fast","short","efficient","thrilling"],Ze=["all","unknown","none"],ze={requestValidation:{schema:Ye},buildRequest:e=>{const t=new URL((e=>Ee(e,"ev/id"))(e)),n=t.searchParams;return Se(n,e),n.append("id",e.id),t},sendRequest:J,parseResponse:e=>{const t=e.results?.[0];return t?{id:t.id,accessType:t.accessType,chargingStations:(n=t.chargingStations,n.map(e=>({...e,chargingPoints:e.chargingPoints.map(e=>({...e,connectors:e.connectors?.map(e=>({...e,chargingSpeed:Be(e.ratedPowerKW)}))}))}))),chargingPointAvailability:we(t.chargingStations),connectorAvailabilities:Ne(t.chargingStations),...t.openingHours&&{openingHours:Ke(t.openingHours)}}:void 0;var n},parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new _(n,t,e.status)}},Je=async e=>V(e,ze,"EVChargingStationsAvailability"),Qe=async(e,t)=>{const n=e.properties.dataSources?.chargingAvailability?.id;if(n)try{const r=await Je({...t,id:n}),o=e.properties.poi;return r?{...e,properties:{...e.properties,...o&&{poi:{...o,openingHours:r.openingHours}},chargingPark:{...e.properties.chargingPark,availability:r}}}:void 0}catch(r){return void console.error(r)}};async function Xe(e,t){const{excludeIfAvailabilityUnknown:n,...r}=t??{},a=[];for(const o of e.features){const e=await Qe(o,r);e?a.push(e):n||a.push(o)}return{...e,features:a,bbox:o(a)}}var et=e=>Boolean(e&&"availability"in e&&e.availability),tt=async(e,t,n)=>{const r="string"==typeof t?{query:t}:t,[o]=(await n({...r,limit:1})).features;if(!o)throw new Error(`${e}: no results found for "${r.query}"`);return o},nt=C.object({position:oe,radiusMeters:C.number().optional()}),rt=C.union([nt,C.object({boundingBox:se})]),ot=C.object({typeahead:C.boolean().optional(),offset:C.number().max(1900).optional(),geoBias:rt.optional(),countries:C.array(C.string()).optional()}),at=K.extend(ce.shape).extend(ot.shape).extend({query:C.string()}),it=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:b(Ue(t)),...n&&{bbox:Fe(n)},id:s,properties:{...M(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...o&&{entryPoints:o.map(e=>({...e,position:Ue(e.position)}))},...a&&{addressRanges:{...a,from:Ue(a.from),to:Ue(a.to)}}}}},st={requestValidation:{schema:at},buildRequest:e=>{const t=new URL(`${(e=>Ee(e,"geocode"))(e)}/${encodeURIComponent(e.query)}.json`),n=t.searchParams;return ve(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!A(e.limit)&&n.append("limit",String(e.limit)),!A(e.offset)&&n.append("ofs",String(e.offset)),Le(n,e.geoBias),e.countries&&n.append("countrySet",Te(e.countries)),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",Te(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",Te(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",Te(e.geographyTypes)),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const t=e.results.map(it),n=a(o(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}}},ct=async e=>V(e,st,"Geocode"),lt=async e=>tt("geocodeOne",e,ct),ut=C.object({geometries:C.union([re,C.array(C.union([C.string(),ne])).min(1).max(20)])}),dt=C.object({zoom:C.number().min(0).max(22).optional()}),pt=ut.extend(dt.shape),mt=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),gt={requestValidation:{schema:pt},buildRequest:e=>{const t=new URL((e=>Ee(e,"additionalData.json"))(e)),n=t.searchParams;return((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:mt(t):mt(t.features),e.append("geometries",Te(n))})(n,e.geometries),Pe(n,"geometriesZoom",e.zoom),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??s(),bbox:o(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:o(t),features:t}}};async function ht(e){const t=await V(e,gt,"GeometryData");return Array.isArray(e.geometries)||"FeatureCollection"!==e.geometries.type?t:((e,t)=>{const n=e.features.reduce((e,t)=>{const n=t.properties.dataSources?.geometry?.id;return n&&(e[n]={...t.properties,placeCoordinates:t.geometry.coordinates}),e},{}),r=t.features.map(e=>e.id&&n[e.id]?{...e,properties:n[e.id]}:e);return{type:"FeatureCollection",bbox:t.bbox,features:r}})(e.geometries,t)}var yt=C.object({entityId:C.string()}),ft=C.object({mapcodes:C.array(C.string()).optional(),view:C.enum(S).optional(),openingHours:C.string().optional(),timeZone:C.string().optional(),relatedPois:C.string().optional()}),Tt=yt.extend(ft.shape),Rt={requestValidation:{schema:Tt},buildRequest:e=>{const t=new URL(`${(e=>Ee(e,"place.json"))(e)}`),n=t.searchParams;return ve(n,e),Pe(n,"entityId",e.entityId),Ae(n,"mapcodes",e.mapcodes),Pe(n,"view",e.view),Pe(n,"openingHours",e.openingHours),Pe(n,"timeZone",e.timeZone),Pe(n,"relatedPois",e.relatedPois),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>e.results?.length?We(e.results[0]):void 0},bt=async e=>V(e,Rt,"PlaceDetails"),It=/* @__PURE__ */new Map,St=/* @__PURE__ */new Map,Ct="en-GB",vt=e=>e??Ct,At=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),Pt=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(At);for(const r of e)t[r]=n}return t},Lt=K.extend({filters:C.array(C.string()).optional()}),Mt=e=>{const t=R[e.id];return t?{code:t,name:e.name,childCategoryCodes:e.childCategoryIds.map(e=>R[e]).filter(e=>!!e),synonyms:e.synonyms}:(console.error(`Received unknown POI category ID ${e.id} (${e.name}). This category will be skipped and unavailable for filtering.`),null)},Et={requestValidation:{schema:Lt},buildRequest:e=>{const t=Ee(e,"poiCategories.json"),n=new URL(t);return ve(n.searchParams,e),{url:n,headers:Ce(e)}},getAPIVersion:()=>1,sendRequest:J,parseResponse:e=>({poiCategories:e.poiCategories.map(Mt).filter(e=>null!==e)})},wt=(e,t)=>{const n=(e=>St.get(e??Ct)??{})(e),r=/* @__PURE__ */new Map;for(const o of t){const e=At(o);for(const[t,o]of Object.entries(n))t.includes(e)&&o&&r.set(o.code,o)}for(const o of r.values())for(const e of o.childCategoryCodes)r.delete(e);return[...r.values()]},Dt=async(e={})=>{const{language:t}=h(e);let n=(e=>It.get(vt(e)))(t);return n||(n=(await V(e,Et,"POICategories")).poiCategories,((e,t)=>{const n=vt(e);It.set(n,t),St.set(n,Pt(t))})(t,n)),e.filters?.length?{poiCategories:wt(t,e.filters)}:{poiCategories:n}},xt=async(e={})=>{const{poiCategories:t}=await Dt(e);return t.map(e=>e.code)},Ot=(e,t)=>{const{data:n,message:r,status:o}=e;return new _(n?.error?.description??n?.detailedError?.message??r,t,o)},Nt=(e,t)=>e*t/100,Bt=e=>"engineType"in e&&"electric"===e.engineType,Ht=e=>{if(Bt(e)&&e.model&&!("variantId"in e.model))return e.model.engine},_t=(e,t,n)=>{A(n)||(e[t]=String(n))},Ft=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),Ut=e=>{const t={};return e?(_t(t,"accelerationEfficiency",e.acceleration),_t(t,"decelerationEfficiency",e.deceleration),_t(t,"uphillEfficiency",e.uphill),_t(t,"downhillEfficiency",e.downhill),t):t},Gt=e=>{const t={};return e.speedsToConsumptionsKWH?.length&&(t.constantSpeedConsumptionInkWhPerHundredkm=Ft(e.speedsToConsumptionsKWH)),_t(t,"auxiliaryPowerInkW",e.auxiliaryPowerInkW),_t(t,"consumptionInkWhPerkmAltitudeGain",e.consumptionInKWHPerKMAltitudeGain),_t(t,"recuperationInkWhPerkmAltitudeLoss",e.recuperationInKWHPerKMAltitudeLoss),{...t,...Ut(e.efficiency)}},kt=e=>{const t=e.consumption,n={};return t.speedsToConsumptionsLiters?.length&&(n.constantSpeedConsumptionInLitersPerHundredkm=Ft(t.speedsToConsumptionsLiters)),_t(n,"auxiliaryPowerInLitersPerHour",t.auxiliaryPowerInLitersPerHour),_t(n,"fuelEnergyDensityInMJoulesPerLiter",t.fuelEnergyDensityInMJoulesPerLiter),{...n,...Ut(t.efficiency)}},Kt=e=>Ht(e)?.charging?.maxChargeKWH,Wt=e=>{const t={};return e.charging?.maxChargeKWH&&(t.maxChargeInkWh=String(e.charging.maxChargeKWH)),t},jt=e=>{const t=e.state?.currentChargeInkWh;if(!A(t))return t;const n=e.state?.currentChargePCT,r=Kt(e);return!A(n)&&r?Nt(r,n):void 0},Vt=e=>{const t={};return _t(t,"currentChargeInkWh",jt(e)),t},qt=e=>{const t={};return _t(t,"currentFuelInLiters",e.state?.currentFuelInLiters),t},Yt=e=>Bt(e)?e.preferences?.chargingPreferences:void 0,$t=(e,t)=>{for(const[n,r]of Object.entries(t))e.set(n,r)},Zt=C.number().positive(),zt=C.number().min(0),Jt=C.number().min(0).max(100),Qt=Zt.optional(),Xt=zt.optional(),en=C.number().min(0).max(1).optional(),tn=C.object({speedKMH:C.number(),consumptionUnitsPer100KM:C.number()}),nn={efficiency:C.object({acceleration:en,deceleration:en,uphill:en,downhill:en}).optional()},rn=C.array(tn).min(1).max(25),on=C.object({...nn,speedsToConsumptionsLiters:rn,auxiliaryPowerInLitersPerHour:Xt,fuelEnergyDensityInMJoulesPerLiter:C.number().min(1).optional()}),an=C.object({...nn,speedsToConsumptionsKWH:rn,auxiliaryPowerInkW:Xt,consumptionInKWHPerKMAltitudeGain:C.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Xt}),sn=C.object({currentType:C.enum(i),plugTypes:C.array(C.enum(y)).min(1),efficiency:en,baseLoadInkW:Xt,maxPowerInkW:Xt,maxVoltageInV:Xt,maxCurrentInA:Xt,voltageRange:C.object({minVoltageInV:Xt,maxVoltageInV:C.number().optional()}).optional()}),cn=C.object({stateOfChargeInkWh:zt,maxPowerInkW:Zt}),ln=C.object({maxChargeKWH:Zt,batteryCurve:C.array(cn).max(20).optional(),chargingConnectors:C.array(sn).min(1).optional(),chargingTimeOffsetInSec:Xt}),un=C.object({consumption:on}),dn=C.object({consumption:an,charging:ln.optional()}),pn=C.object({weightKG:Qt}).optional(),mn=C.object({variantId:C.string()}),gn=C.object({dimensions:pn,engine:C.union([un,dn]).optional()}),hn=C.union([mn,gn]).optional(),yn=C.object({heading:C.number().min(0).max(360).optional()}),fn=yn.extend({currentFuelInLiters:zt}),Tn=yn.extend({currentChargePCT:Jt}),Rn=yn.extend({currentChargeInkWh:zt}),bn=C.union([Tn,Rn]),In=C.object({minChargeAtDestinationPCT:Jt,minChargeAtChargingStopsPCT:C.number().min(0).max(50)}),Sn=C.object({minChargeAtDestinationInkWh:zt,minChargeAtChargingStopsInkWh:zt}),Cn=C.union([In,Sn]),vn=C.object({chargingPreferences:Cn.optional()}),An={model:hn,restrictions:C.object({maxSpeedKMH:C.number().min(0).max(250).optional(),tollTransponder:C.enum(Ze).optional()}).optional()},Pn=C.object({...An,engineType:C.undefined().optional(),state:yn.optional()}),Ln=C.object({...An,engineType:C.literal("combustion"),state:fn.optional()}),Mn=C.object({...An,engineType:C.literal("electric"),state:bn.optional(),preferences:vn.optional()}),En=C.union([C.discriminatedUnion("engineType",[Ln,Mn]),Pn]),wn=C.object({avoid:C.array(C.enum(n)).optional(),traffic:C.enum(["live","historical"]).optional(),routeType:C.enum($e).optional(),avoidAreas:C.array(se).max(10).optional()}),Dn=C.object({option:C.enum(["departAt","arriveBy"]),date:C.date()}),xn=C.object({costModel:wn.optional(),travelMode:C.string().optional(),vehicle:En.optional(),when:Dn.optional()}),On=["timeMinutes","remainingChargePCT","spentChargePCT","spentFuelLiters","distanceKM"],Nn=C.object({origin:oe,budget:C.object({type:C.enum(On),value:C.number().min(0)})}),Bn=C.enum(n).exclude(["alreadyUsedRoads"]),Hn=En.check(C.refine(e=>!(e.state&&"heading"in e.state),"vehicle.state.heading: calculateReachableRange has no vehicle heading parameter. Remove it, or use calculateRoute, which accepts it."),C.refine(e=>!("electric"===e.engineType&&e.preferences&&"chargingPreferences"in e.preferences),"vehicle.preferences.chargingPreferences: calculateReachableRange plans no charging stops. Remove them, or use calculateRoute, which plans stops for them.")),_n=Dn.check(C.refine(e=>"arriveBy"!==e.option,"when.arriveBy: calculateReachableRange has no arrival-time parameter. Use when.departAt instead, or omit when entirely.")),Fn=wn.extend({avoid:C.array(Bn).optional(),avoidAreas:C.unknown().optional()}).check(C.refine(e=>void 0===e.avoidAreas,"costModel.avoidAreas: calculateReachableRange has no avoid-areas parameter. Remove it — the other cost-model options are accepted.")),Un=C.object({when:_n.optional(),vehicle:Hn.optional(),costModel:Fn.optional(),maxFerryLengthMeters:C.number().min(0).optional(),smoothing:C.enum(["none","weak","strong"]).optional()}),Gn=xn.extend(Nn.extend(Un.shape).shape),kn=/* @__PURE__ */new Set(["spentChargePCT","remainingChargePCT"]),Kn={check:e=>!kn.has(e.budget.type)||!!e.vehicle&&void 0!==Kt(e.vehicle),message:"budget: a charge budget is a percentage of the battery, so it needs a capacity to convert against. Set vehicle.engineType to 'electric' and vehicle.model.engine.charging.maxChargeKWH, or budget by time or distance instead."},Wn={check:e=>"remainingChargePCT"!==e.budget.type||!!e.vehicle&&void 0!==jt(e.vehicle),message:"budget.remainingChargePCT: a range down to a remaining charge is measured from the charge the vehicle sets off with. Set vehicle.state.currentChargeInkWh or vehicle.state.currentChargePCT, or use spentChargePCT to budget a share of the battery instead."},jn={schema:Gn,refinements:[Kn,Wn]},Vn=e=>({...e.costModel?.routeType&&{routeType:e.costModel.routeType},...e.costModel?.traffic&&{traffic:e.costModel.traffic},...e.costModel?.avoid?.length&&{avoids:e.costModel.avoid},...e.travelMode&&{travelMode:e.travelMode},..."departAt"===e.when?.option&&e.when.date&&{departureDateTime:e.when.date.toISOString()}}),qn=e=>e.model&&"variantId"in e.model?e.model.variantId:void 0,Yn=e=>{const t={};return Bt(e)&&(t.vehicleEngineType="electric"),e.model&&!("variantId"in e.model)&&e.model.dimensions?.weightKG&&(t.vehicleWeightInKilograms=e.model.dimensions.weightKG),e.restrictions?.maxSpeedKMH&&(t.vehicleMaxSpeedInKilometersPerHour=e.restrictions.maxSpeedKMH),e.restrictions?.tollTransponder&&(t.vehicleHasElectronicTollCollectionTransponder=e.restrictions.tollTransponder),t},$n=(e,t)=>{const n=Ht(t),r=(e=>"engineType"in e&&"combustion"===e.engineType?e.model?.engine:void 0)(t);var o;$t(e.searchParams,Bt(t)?{...n&&(o=n,{...Gt(o.consumption),...Wt(o)}),...Vt(t)}:{...r&&kt(r),...qt(t)})},Zn=(e,t)=>{const n=qn(t);n&&e.searchParams.set("vehicleModelId",n),$n(e,t)},zn=e=>({origin:{type:"Point",coordinates:d(e.origin)},...Vn(e),...e.vehicle&&Yn(e.vehicle)}),Jn=e=>({...Ie(e),Attributes:"reachableRange(boundary)"}),Qn=Object.keys({origin:!0,budget:!0,costModel:!0,vehicle:!0,travelMode:!0,when:!0,maxFerryLengthMeters:!0,smoothing:!0}),Xn={requestValidation:jn,buildRequest:e=>{const t=(e=>new URL(e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange`))(e);return((e,t)=>{const n=t.budget,r=t.vehicle&&Kt(t.vehicle);switch(n.type){case"timeMinutes":e.append("timeBudgetInSec",(60*n.value).toString());break;case"distanceKM":e.append("distanceBudgetInMeters",(1e3*n.value).toString());break;case"spentFuelLiters":e.append("fuelBudgetInLiters",n.value.toString());break;case"spentChargePCT":r&&e.append("energyBudgetInkWh",Nt(r,n.value).toString());break;case"remainingChargePCT":{const o=t.vehicle&&jt(t.vehicle);if(r&&void 0!==o){const t=Nt(r,n.value);e.append("energyBudgetInkWh",Math.max(0,o-t).toString())}break}}})(t.searchParams,e),Pe(t.searchParams,"maxFerryLengthInMeters",e.maxFerryLengthMeters),Pe(t.searchParams,"smoothing",e.smoothing??"strong"),e.vehicle&&Zn(t,e.vehicle),{method:"POST",url:t,data:zn(e),headers:Jn(e)}},sendRequest:X,parseResponse:(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:o(n),properties:w(t,Qn)}},parseResponseError:Ot,getAPIVersion:()=>3},er=async e=>V(e,Xn,"Reachable Range"),tr=(...e)=>{const t=e.filter(e=>!!e);return t.length<2?t[0]:AbortSignal.any(t)},nr=async(e,t)=>{const n=[];for(const o of e){const e=tr(o.signal,t?.signal);try{n.push(await er({...o,...e&&{signal:e}}))}catch(a){if(!(a instanceof _)||403===a.status||429===a.status)throw a}}const r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},rr={Country:"country",CountrySubdivision:"countrySubdivision",CountrySecondarySubdivision:"countrySecondarySubdivision",CountryTertiarySubdivision:"countryTertiarySubdivision",Municipality:"municipality",MunicipalitySubdivision:"municipalitySubdivision",MunicipalitySecondarySubdivision:"municipalitySecondarySubdivision",Neighbourhood:"neighborhood",PostalCodeArea:"postalCode"},or={AF:"AFG",AX:"ALA",AL:"ALB",DZ:"DZA",AS:"ASM",AD:"AND",AO:"AGO",AI:"AIA",AQ:"ATA",AG:"ATG",AR:"ARG",AM:"ARM",AW:"ABW",AU:"AUS",AT:"AUT",AZ:"AZE",BS:"BHS",BH:"BHR",BD:"BGD",BB:"BRB",BY:"BLR",BE:"BEL",BZ:"BLZ",BJ:"BEN",BM:"BMU",BT:"BTN",BO:"BOL",BQ:"BES",BA:"BIH",BW:"BWA",BV:"BVT",BR:"BRA",IO:"IOT",BN:"BRN",BG:"BGR",BF:"BFA",BI:"BDI",CV:"CPV",KH:"KHM",CM:"CMR",CA:"CAN",KY:"CYM",CF:"CAF",TD:"TCD",CL:"CHL",CN:"CHN",CX:"CXR",CC:"CCK",CO:"COL",KM:"COM",CG:"COG",CD:"COD",CK:"COK",CR:"CRI",CI:"CIV",HR:"HRV",CU:"CUB",CW:"CUW",CY:"CYP",CZ:"CZE",DK:"DNK",DJ:"DJI",DM:"DMA",DO:"DOM",EC:"ECU",EG:"EGY",SV:"SLV",GQ:"GNQ",ER:"ERI",EE:"EST",SZ:"SWZ",ET:"ETH",FK:"FLK",FO:"FRO",FJ:"FJI",FI:"FIN",FR:"FRA",GF:"GUF",PF:"PYF",TF:"ATF",GA:"GAB",GM:"GMB",GE:"GEO",DE:"DEU",GH:"GHA",GI:"GIB",GR:"GRC",GL:"GRL",GD:"GRD",GP:"GLP",GU:"GUM",GT:"GTM",GG:"GGY",GN:"GIN",GW:"GNB",GY:"GUY",HT:"HTI",HM:"HMD",VA:"VAT",HN:"HND",HK:"HKG",HU:"HUN",IS:"ISL",IN:"IND",ID:"IDN",IR:"IRN",IQ:"IRQ",IE:"IRL",IM:"IMN",IL:"ISR",IT:"ITA",JM:"JAM",JP:"JPN",JE:"JEY",JO:"JOR",KZ:"KAZ",KE:"KEN",KI:"KIR",KP:"PRK",KR:"KOR",KW:"KWT",KG:"KGZ",LA:"LAO",LV:"LVA",LB:"LBN",LS:"LSO",LR:"LBR",LY:"LBY",LI:"LIE",LT:"LTU",LU:"LUX",MO:"MAC",MG:"MDG",MW:"MWI",MY:"MYS",MV:"MDV",ML:"MLI",MT:"MLT",MH:"MHL",MQ:"MTQ",MR:"MRT",MU:"MUS",YT:"MYT",MX:"MEX",FM:"FSM",MD:"MDA",MC:"MCO",MN:"MNG",ME:"MNE",MS:"MSR",MA:"MAR",MZ:"MOZ",MM:"MMR",NA:"NAM",NR:"NRU",NP:"NPL",NL:"NLD",NC:"NCL",NZ:"NZL",NI:"NIC",NE:"NER",NG:"NGA",NU:"NIU",NF:"NFK",MK:"MKD",MP:"MNP",NO:"NOR",OM:"OMN",PK:"PAK",PW:"PLW",PS:"PSE",PA:"PAN",PG:"PNG",PY:"PRY",PE:"PER",PH:"PHL",PN:"PCN",PL:"POL",PT:"PRT",PR:"PRI",QA:"QAT",RE:"REU",RO:"ROU",RU:"RUS",RW:"RWA",BL:"BLM",SH:"SHN",KN:"KNA",LC:"LCA",MF:"MAF",PM:"SPM",VC:"VCT",WS:"WSM",SM:"SMR",ST:"STP",SA:"SAU",SN:"SEN",RS:"SRB",SC:"SYC",SL:"SLE",SG:"SGP",SX:"SXM",SK:"SVK",SI:"SVN",SB:"SLB",SO:"SOM",ZA:"ZAF",GS:"SGS",SS:"SSD",ES:"ESP",LK:"LKA",SD:"SDN",SR:"SUR",SJ:"SJM",SE:"SWE",CH:"CHE",SY:"SYR",TW:"TWN",TJ:"TJK",TZ:"TZA",TH:"THA",TL:"TLS",TG:"TGO",TK:"TKL",TO:"TON",TT:"TTO",TN:"TUN",TR:"TUR",TM:"TKM",TC:"TCA",TV:"TUV",UG:"UGA",UA:"UKR",AE:"ARE",GB:"GBR",US:"USA",UM:"UMI",UY:"URY",UZ:"UZB",VU:"VUT",VE:"VEN",VN:"VNM",VG:"VGB",VI:"VIR",WF:"WLF",EH:"ESH",YE:"YEM",ZM:"ZMB",ZW:"ZWE"},ar=e=>or[e]??e,ir={street:"Street",area:"Geography",address:"Point Address"},sr=Object.fromEntries(Object.entries(rr).map(([e,t])=>[t,e])),cr=e=>{const{street:t,houseNumber:n,countryCodeIso2:r,...o}=e;return{...o,...t&&{streetName:t},...n&&{streetNumber:n},...r&&{countryCode:r,countryCodeISO3:ar(r)}}},lr=C.object({position:oe}),ur=C.object({geographyTypes:C.array(C.enum(l)).optional(),heading:C.number().min(-360).max(360).optional(),radiusMeters:C.number().positive().max(5e6).optional(),view:C.enum(S).optional()}),dr=lr.extend(ur.shape),pr={requestValidation:{schema:dr},buildRequest:e=>{const[t,n]=d(e.position),r=new URL((e=>Ee(e,"reverseGeocode"))(e)),o=r.searchParams;return o.append("position",`${t},${n}`),!A(e.radiusMeters)&&o.append("radiusInMeters",String(e.radiusMeters)),e.geographyTypes&&o.append("areaTypes",e.geographyTypes.map(e=>rr[e]).join(",")),!A(e.heading)&&o.append("vehicleHeadingInDegrees",String(e.heading)),e.view&&o.append("geopoliticalView",e.view),{url:r,headers:{...Ie(e),Attributes:"results(*)"}}},getAPIVersion:()=>2,sendRequest:J,parseResponse:(e,t)=>{const n=e.results[0];return{type:"Feature",geometry:b(d(t.position)),id:n?.id??s(),...n&&{properties:{type:ir[n.type],address:{freeformAddress:n.title,...cr(n.address)},...n.areaType&&{geographyType:[sr[n.areaType]],dataSources:{geometry:{id:n.id}}},...n.accessPoints?.length&&{entryPoints:n.accessPoints.map(e=>({position:e.position.coordinates}))},originalPosition:n.position.coordinates}}}}},mr=async e=>V(e,pr,"ReverseGeocode"),gr=["tollVignette","tollRoad","roadShields","importantRoadStretch"],hr=e=>{const t=["summary","legs(summary,path)"],n=e.sectionTypes;if(!n||n.length>0){t.push("sections");const r=!n;for(const e of gr)(r||n.includes(e))&&t.push(`sections.${e}`);e.guidance&&(r||n.includes("lanes"))&&t.push("sections.lanes")}0!==e.extendedRouteRepresentations?.length&&t.push("progressPoints"),e.guidance&&t.push("instructions(*,nextRoadInformation.roadShields.iconReference,previousRoadInformation.roadShields.iconReference,signpost.exitIconReference,distanceToPreviousTrafficLightInMeters)");const r=`routes(${t.join(",")})`;return e.guidance?`roadShieldAtlasReference,${r}`:r},yr=e=>{const t=e.state?.heading;return{...Yn(e),...!A(t)&&{vehicleHeadingInDegrees:t}}},fr=(e,t)=>{Zn(e,t),$t(e.searchParams,(e=>{const t=Yt(e),n={};if(!t)return n;const r=t;if(!A(r.minChargeAtDestinationInkWh)||!A(r.minChargeAtChargingStopsInkWh))return _t(n,"minChargeAtDestinationInkWh",r.minChargeAtDestinationInkWh),_t(n,"minChargeAtChargingStopsInkWh",r.minChargeAtChargingStopsInkWh),n;const o=Kt(e);if(!o)return n;const a=t;return A(a.minChargeAtDestinationPCT)||(n.minChargeAtDestinationInkWh=String(Nt(o,a.minChargeAtDestinationPCT))),A(a.minChargeAtChargingStopsPCT)||(n.minChargeAtChargingStopsInkWh=String(Nt(o,a.minChargeAtChargingStopsPCT))),n})(t))},Tr=e=>!!e.vehicle&&!!Yt(e.vehicle),Rr="vehicle.model.variantId is only supported for EV routes with charging stops: set vehicle.preferences.chargingPreferences, or describe the vehicle with vehicle.model.dimensions and vehicle.model.engine instead.",br=e=>{const t=(e=>Array.isArray(e)?e:e.geometry.coordinates)(e),n=(e=>{if(!Array.isArray(e))return e.properties?.sections?.leg})(e);if(n&&n.length>1&&n.every(e=>null!=e.startPointIndex&&null!=e.endPointIndex)){const e=n.map(e=>{const n=e.startPointIndex??0,r=e.endPointIndex??0;return{coordinate:t[n],legToNext:{path:{type:"LineString",coordinates:t.slice(n,r+1)}}}});return e.push({coordinate:t[n.at(-1)?.endPointIndex??t.length-1]}),e}return[{coordinate:t[0],legToNext:{path:{type:"LineString",coordinates:t}}},{coordinate:t.at(-1)??t[0]}]},Ir=e=>{if(!Array.isArray(e)&&"properties"in e)return e.properties??void 0},Sr=e=>{const t=e.options;if(!t)return{};const n={...t.pauseDurationSeconds&&{pauseDurationInSeconds:t.pauseDurationSeconds},...t.candidateEntryPoints?.length&&{entryPoints:(r=t.candidateEntryPoints,{type:"MultiPoint",coordinates:r.map(e=>d(e))}),...!A(t.preferredEntryPointIndex)&&{preferredEntryPointIndex:t.preferredEntryPointIndex}}};var r;return{...t.legCostModel?.routeType&&{routeType:t.legCostModel.routeType},...t.legCostModel?.avoid?.length&&{avoids:t.legCostModel.avoid.map(e=>({name:e}))},...Object.keys(n).length>0&&{routeStop:n}}},Cr=(e,t)=>{t.computeTravelTimeFor&&e.searchParams.set("computeTravelTimeFor",t.computeTravelTimeFor)},vr=C.union([oe,te]),Ar=C.union([ee,ne]),Pr=C.object({locations:C.array(C.union([vr,Ar])).min(1)}),Lr=C.object({arrivalSide:C.enum(["any","curb"]).optional(),chargingStopsStrategy:C.enum(["automaticFastest","manualFastest","automaticFastestWithFallbackToManual"]).optional(),computeTravelTimeFor:C.enum(["none","all"]).optional(),maxAlternatives:C.number().min(0).max(5).optional(),sectionTypes:C.array(C.enum(m)).optional()}),Mr={schema:xn.extend(Pr.extend(Lr.shape).shape),refinements:[{check:e=>{const t=e.locations.map(p),n=t.filter(e=>"waypoint"===e).length,r=t.filter(e=>"path"===e).length;return n>=2||r>=1},message:"At least 2 waypoints or 1 path (route reconstruction) is required."},{check:e=>!e.chargingStopsStrategy||Tr(e),message:"chargingStopsStrategy: set vehicle.preferences.chargingPreferences as well — an EV route needs a minimum charge at the destination, which only the charging preferences provide."},{check:e=>!(e.vehicle&&qn(e.vehicle))||Tr(e),message:Rr},{check:e=>{const t=e.locations.at(-1);return!t||"waypoint"!==p(t)||!t.properties?.pauseDurationSeconds},message:"pauseDurationSeconds is not supported on the destination: the routing API requires the wait on the last leg to be 0."}]},Er={other:"unknown",accident:"accident",fog:"fog",danger:"dangerousConditions",rain:"rain",frost:"ice",jam:"jam","lane-closed":"laneClosed","road-closed":"roadClosed",roadworks:"roadWorks",wind:"wind",flooding:"flooding","broken-down-vehicle":"brokenDownVehicle"},wr=new Map(Object.entries(Er)),Dr=new Map(I.map(e=>[Er[e],e])),xr=new Map(Object.entries({unknown:"unknown",minor:"minor",moderate:"moderate",major:"major",undefined:"indefinite"})),Or=e=>wr.get(e)??e,Nr=e=>Dr.get(e)??"other",Br=e=>xr.get(e)??"unknown",Hr=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},_r=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,o=[r.coordinate.longitude,r.coordinate.latitude],a=[r.street,r.houseNumber].filter(Boolean),i=a.length>0?a.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:o},properties:{...M(e,["chargingConnectionInfo","chargingParkLocation"]),type:"POI",address:{freeformAddress:i,...r.street&&{streetName:r.street},...r.houseNumber&&{streetNumber:r.houseNumber},...r.city&&{municipality:r.city},...r.region&&{countrySubdivision:r.region},...r.postalCode&&{postalCode:r.postalCode},...r.country&&{country:r.country}},...n&&{chargingConnectionInfo:{plugType:n.chargingPlugType,currentInA:n.chargingCurrentInA,voltageInV:n.chargingVoltageInV,chargingPowerInkW:n.chargingPowerInkW,currentType:Hr(n.chargingCurrentType),chargingSpeed:Be(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:Be(e.chargingParkPowerInkW)}}}},Fr=(e,t)=>{const n=t?.vehicle&&Kt(t.vehicle);return{lengthInMeters:e.lengthInMeters,travelTimeInSeconds:e.travelDurationInSeconds,trafficDelayInSeconds:e.trafficDelayDurationInSeconds??0,trafficLengthInMeters:e.trafficLengthInMeters??0,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,departureTime:new Date(e.departureDateTime),arrivalTime:new Date(e.arrivalDateTime),deviationDistanceInMeters:e.deviationDistanceInMeters,deviationTimeInSeconds:e.deviationDurationInSeconds,...e.deviationPoint&&{deviationPoint:e.deviationPoint.coordinates},fuelConsumptionInLiters:e.fuelConsumptionInLiters,totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh,...n&&(()=>{const t=e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh;return t?{batteryConsumptionInPCT:100*t/n}:void 0})(),remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:_r(e.chargingInformationAtEndOfLeg,n)}}},Ur=(e,t)=>e.reduce((n,r,o)=>{const a=r.path.coordinates.length,i=0===o?0:n[o-1]?.endPointIndex;let c;A(i)||(c=0===i?Math.max(a-1,0):i+a);const l=((e,t)=>{if(!t)return;const n=new Date(e.summary.arrivalDateTime).getTime(),r=new Date(t.summary.departureDateTime).getTime();if(Number.isNaN(n)||Number.isNaN(r))return;const o=Math.round((r-n)/1e3);return o>0?o:void 0})(r,e[o+1]),{originalWaypointIndexAtEndOfLeg:u}=r.summary;return n.push({...!A(i)&&{startPointIndex:i},...void 0!==c&&{endPointIndex:c},...!A(u)&&{originalWaypointIndex:u},summary:{...Fr(r.summary,t),...void 0!==l&&{stopTimeInSeconds:l}},id:s()}),n},[]),Gr=e=>({id:s(),startPointIndex:e.startPathIndex,endPointIndex:e.endPathIndex}),kr=(e,t)=>{const n={leg:Ur(e.legs,t)},r=e.sections;if(!r)return n;const o=(e,t)=>{t?.length&&(n[e]=t.map(Gr))};return o("carTrain",r.carTrain),o("ferry",r.ferry),o("tunnel",r.tunnel),o("motorway",r.motorway),o("pedestrian",r.pedestrian),o("toll",r.toll),o("tollRoad",r.tollRoad),o("carpool",r.carpool),o("urban",r.urban),o("unpaved",r.unpaved),o("lowEmissionZone",r.lowEmissionZone),r.country?.length&&(n.country=r.country.map(e=>({...Gr(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:ar(e.countryCodeIso2??"")}))),r.travelMode?.length&&(n.vehicleRestricted=r.travelMode.filter(e=>"other"===e.travelMode).map(Gr)),r.traffic?.length&&(n.traffic=r.traffic.map(e=>{return{...Gr(e),delayInSeconds:e.delayDurationInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKilometersPerHour,categories:(t=e,t.tec?.causes?.length?t.tec.causes.map(e=>{switch(e.mainCauseCode){case 1:return"jam";case 2:return"accident";case 3:return"roadworks";case 4:return"narrow-lanes";case 5:return"road-closed";case 9:return"danger";case 11:return"animals-on-road";case 13:return"broken-down-vehicle";case 16:return"lane-closed";case 17:return"wind";case 18:return"fog";case 19:return"rain";case 22:return"frost";case 23:return"flooding";default:return"other"}}):[Nr(t.iconCategory)]),magnitudeOfDelay:Br(e.delayMagnitude),tec:e.tec,...e.eventId&&{eventId:e.eventId}};var t})),r.speedLimit?.length&&(n.speedLimit=r.speedLimit.map(e=>{const t=e.speedRestrictions?.find(e=>"maximum"===e.type)?.inKilometersPerHour;return A(t)?void 0:{...Gr(e),maxSpeedLimitInKmh:t}}).filter(e=>!!e)),r.lanes?.length&&(n.lanes=r.lanes.map(e=>({...Gr(e),lanes:(e.lanes??[]).map(e=>({directions:e.directions.map(e=>$r[e]??e),...e.follow&&{follow:$r[e.follow]??e.follow}})),laneSeparators:(e.laneSeparators??[]).map(e=>Zr[e]??e),properties:e.properties}))),r.roadShields?.length&&(n.roadShields=r.roadShields.map(e=>({...Gr(e),roadShieldReferences:e.roadShieldReferences}))),r.tollVignette?.length&&(n.tollVignette=r.tollVignette.map(e=>({...Gr(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:ar(e.countryCodeIso2??"")}))),r.importantRoadStretch?.length&&(n.importantRoadStretch=r.importantRoadStretch.map(e=>({...Gr(e),index:e.importantRoadStretchIndex,...e.streetName&&{streetName:e.streetName.text},...e.roadNumbers?.length&&{roadNumbers:e.roadNumbers.map(e=>e.text)}}))),((e,t)=>{if(!t)return;const n=new Set(t);for(const r of Object.keys(e))"leg"===r||n.has(r)||delete e[r]})(n,t.sectionTypes),n},Kr=1e-4,Wr=(e,t)=>Math.abs(e[0]-t[0])<Kr&&Math.abs(e[1]-t[1])<Kr,jr={depart:"DEPART",waypointLeft:"WAYPOINT_LEFT",waypointRight:"WAYPOINT_RIGHT",waypointReached:"WAYPOINT_REACHED",waypointAhead:"WAYPOINT_AHEAD",arrive:"ARRIVE",arriveLeft:"ARRIVE_LEFT",arriveRight:"ARRIVE_RIGHT",arriveAhead:"ARRIVE_AHEAD",continueStraight:"STRAIGHT",keepLeft:"KEEP_LEFT",keepRight:"KEEP_RIGHT",turnSlightRight:"SLIGHT_RIGHT",turnRight:"TURN_RIGHT",turnSharpRight:"SHARP_RIGHT",turnSlightLeft:"SLIGHT_LEFT",turnLeft:"TURN_LEFT",turnSharpLeft:"SHARP_LEFT",makeUTurn:"MAKE_UTURN",roundaboutStraight:"ROUNDABOUT_STRAIGHT",roundaboutSharpRight:"ROUNDABOUT_SHARP_RIGHT",roundaboutRight:"ROUNDABOUT_RIGHT",roundaboutSlightRight:"ROUNDABOUT_SLIGHT_RIGHT",roundaboutSlightLeft:"ROUNDABOUT_SLIGHT_LEFT",roundaboutLeft:"ROUNDABOUT_LEFT",roundaboutSharpLeft:"ROUNDABOUT_SHARP_LEFT",roundaboutBack:"ROUNDABOUT_BACK",exitRoundabout:"EXIT_ROUNDABOUT",exitMotorwayLeft:"EXIT_MOTORWAY_LEFT",exitMotorwayRight:"EXIT_MOTORWAY_RIGHT",switchMotorwayLeft:"SWITCH_MOTORWAY_LEFT",switchMotorwayRight:"SWITCH_MOTORWAY_RIGHT",enterCarpoolLaneLeft:"ENTER_CARPOOL_LANE_LEFT",enterCarpoolLaneRight:"ENTER_CARPOOL_LANE_RIGHT",exitCarpoolLaneLeft:"EXIT_CARPOOL_LANE_LEFT",exitCarpoolLaneRight:"EXIT_CARPOOL_LANE_RIGHT",mergeLeftLane:"MERGE_LEFT_LANE",mergeRightLane:"MERGE_RIGHT_LANE",takeShipFerry:"TAKE_SHIP_FERRY",takeCarTrain:"TAKE_CAR_TRAIN",leaveShipFerry:"LEAVE_SHIP_FERRY",leaveCarTrain:"LEAVE_CAR_TRAIN",crossBorder:"CROSS_BORDER",passTollgate:"TOLLGATE"},Vr={urban:"URBAN",motorway:"MOTORWAY",controlledAccess:"CONTROLLED_ACCESS"},qr={endOfRoad:"END_OF_ROAD",atTrafficLight:"AT_TRAFFIC_LIGHT",onToBridge:"ON_TO_BRIDGE",onBridge:"ON_BRIDGE",afterBridge:"AFTER_BRIDGE",intoTunnel:"INTO_TUNNEL",insideTunnel:"INSIDE_TUNNEL",afterTunnel:"AFTER_TUNNEL"},Yr={cashCoinsAndBills:"CASH_COINS_AND_BILLS",cashBillsOnly:"CASH_BILLS_ONLY",cashCoinsOnly:"CASH_COINS_ONLY",cashExactChange:"CASH_EXACT_CHANGE",creditCard:"CREDIT_CARD",debitCard:"DEBIT_CARD",travelCard:"TRAVEL_CARD",etc:"ETC",etcTransponder:"ETC_TRANSPONDER",etcVideoCamera:"ETC_VIDEO_CAMERA",subscription:"SUBSCRIPTION"},$r={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",rightUTurn:"RIGHT_U_TURN",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",leftUTurn:"LEFT_U_TURN"},Zr={unknown:"UNKNOWN",noMarking:"NO_MARKING",longDashed:"LONG_DASHED",doubleSolid:"DOUBLE_SOLID",singleSolid:"SINGLE_SOLID",solidDashed:"SOLID_DASHED",dashedSolid:"DASHED_SOLID",shortDashed:"SHORT_DASHED",shadedAreaMarking:"SHADED_AREA_MARKING",dashedBlocks:"DASHED_BLOCKS",doubleDashed:"DOUBLE_DASHED",crossingAlert:"CROSSING_ALERT",physicalDivider:"PHYSICAL_DIVIDER",physicalDividerLessThan3m:"PHYSICAL_DIVIDER_LESS_THAN_3M",physicalDividerGuardrail:"PHYSICAL_DIVIDER_GUARDRAIL",curb:"CURB"},zr={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",back:"BACK"},Jr={regular:"REGULAR",small:"SMALL"},Qr={left:"LEFT",right:"RIGHT",leftAndRight:"LEFT_AND_RIGHT"},Xr={properties:[]},eo=e=>({text:e.text}),to=e=>({properties:(e.properties??[]).map(e=>Vr[e]??e.toUpperCase()),...e.roadNames?.length&&{streetName:eo(e.roadNames[0].identifier)},...e.countryCodeIso2&&{countryCode:ar(e.countryCodeIso2)},...e.roadShields?.length&&{roadShields:e.roadShields.map(e=>({roadNumber:e.roadNumber?eo(e.roadNumber):{text:""},countryCode:ar(e.countryCodeIso2??""),...e.countrySubdivisionCodeIso&&{stateCode:e.countrySubdivisionCodeIso},...e.iconReference&&{roadShieldReference:e.iconReference}}))}}),no=e=>({...e.tollgateName&&{tollgateName:eo(e.tollgateName)},...e.tollPaymentTypes?.length&&{tollPaymentTypes:e.tollPaymentTypes.map(e=>Yr[e]??e)},...e.countryCrossingFromName&&{countryCrossingFromName:eo(e.countryCrossingFromName)},...e.countryCrossingFromCodeIso2&&{countryCrossingFromCode:ar(e.countryCrossingFromCodeIso2)},...e.countryCrossingToName&&{countryCrossingToName:eo(e.countryCrossingToName)},...e.countryCrossingToCodeIso2&&{countryCrossingToCode:ar(e.countryCrossingToCodeIso2)}}),ro=e=>zr[e]??e,oo=e=>{return{...e.message&&{message:e.message},...e.intersectionName&&{intersectionName:eo(e.intersectionName)},...e.drivingSide&&{drivingSide:e.drivingSide.toUpperCase()},...e.landmark&&{landmark:qr[e.landmark]??e.landmark},...!A(e.distanceToPreviousTrafficLightInMeters)&&{trafficLightOffsetInMeters:e.distanceToPreviousTrafficLightInMeters},...e.sideRoads&&{sideRoads:(n=e.sideRoads,n.map(e=>({side:Qr[e.side]??e.side,offsetFromManeuverInMeters:e.offsetFromManeuverInMeters,...!A(e.isDrivable)&&{isDrivable:e.isDrivable}})))},...e.maneuverView&&{maneuverView:(t=e.maneuverView,{...t.onRouteAngle&&{onRouteAngle:ro(t.onRouteAngle)},offRouteAngles:(t.offRouteAngles??[]).map(ro)})},...e.roundaboutType&&{roundaboutType:Jr[e.roundaboutType]??e.roundaboutType},...!A(e.isManeuverObligatory)&&{isManeuverObligatory:e.isManeuverObligatory},...!A(e.changeOfAngleInDegrees)&&{changeOfAngleInDegrees:e.changeOfAngleInDegrees},...!A(e.ambiguousExitOffsetFromManeuverInMeters)&&{offsetOfAmbiguousExitFromManeuverInMeters:e.ambiguousExitOffsetFromManeuverInMeters},...!A(e.roundaboutExitNumber)&&{roundaboutExitNumber:e.roundaboutExitNumber}};var t,n},ao=(e,t)=>{const n=e.signpost?(e=>{if(e.exitName||e.exitNumber||e.towardName)return{...e.exitName&&{exitName:eo(e.exitName)},...e.exitNumber&&{exitNumber:eo(e.exitNumber)},towardName:e.towardName?eo(e.towardName):{text:""}}})(e.signpost):void 0,r=(e.nextRoadInformation?.roadShields??[]).map(e=>e.iconReference).filter(e=>!!e);return{...n&&{signpost:n},...t&&{roadShieldAtlasReference:t},...r.length&&{roadShieldReferences:r},...e.signpost?.exitIconReference&&{signpostRoadShieldReferences:[e.signpost.exitIconReference]}}},io=(e,t,n,r)=>({maneuverPoint:t,pathPointIndex:n,routeOffsetInMeters:e.routeOffsetInMeters,maneuver:e.maneuver?jr[e.maneuver]??e.maneuver:e.maneuver,routePath:(e.routePath??[]).map(e=>({point:e.point.coordinates,distanceInMeters:e.distanceFromRouteStartInMeters,travelTimeInSeconds:e.travelTimeFromRouteStartInSeconds})),nextRoadInfo:e.nextRoadInformation?to(e.nextRoadInformation):Xr,previousRoadInfo:e.previousRoadInformation?to(e.previousRoadInformation):Xr,...oo(e),...ao(e,r),...no(e)}),so=(e,t,n)=>{const r=[];let o=0;for(const a of e){const e=a.maneuverPoint.coordinates;for(let n=o;n<t.length;n++)if(Wr(t[n],e)){o=n;break}r.push(io(a,e,o,n))}return{instructions:r}},co={requestValidation:Mr,buildRequest:e=>{const t=e.locations.map(p).includes("path"),n=((e,t)=>{const n=[];for(const r of e)if("waypoint"===p(r)){const e=Ir(r),o=e?.candidateEntryPoints?.length?"ignore":t,[a,i]=d(r,{useEntryPoint:o});n.push({coordinate:[a,i],...e&&{options:e}})}else n.push(...br(r));return n})(e.locations,e.useEntryPoints),r=(e=>{const t={type:"Point",coordinates:e[0].coordinate},n={type:"Point",coordinates:(e.at(-1)??e[0]).coordinate},r=e.slice(1,-1);return{origin:t,destination:n,...r.length&&{waypoints:{type:"MultiPoint",coordinates:r.map(e=>e.coordinate)}}}})(n),a=(e=>{return{...Vn(e),...e.maxAlternatives&&{maxPathAlternativeRoutes:e.maxAlternatives},..."arriveBy"===e.when?.option&&e.when.date&&{arrivalDateTime:e.when.date.toISOString()},...e.guidance&&{guidance:"instructions",instructionPhonetics:"ipa"},...e.costModel?.avoidAreas?.length&&{avoidAreas:(t=e.costModel.avoidAreas,{rectangles:t.map(e=>{const t=o(e);if(!t)throw new Error("Could not derive a bounding box from an avoidAreas rectangle");const[n,r,a,i]=t;return{type:"Feature",bbox:[n,r,a,i],geometry:null}})})},...e.arrivalSide&&{arrivalSidePreference:"curb"===e.arrivalSide?"curbSide":"anySide"}};var t})(e),i=(e=>({...Ie(e),Attributes:hr(e)}))(e),s=((e,t)=>{const n=e.slice(1).map((t,n)=>({...e[n].legToNext,...Sr(t)}));if(t||!n.every(e=>0===Object.keys(e).length))return n})(n,t),c={routePlanningLocations:r,...a,...s&&{legs:s},...e.vehicle&&yr(e.vehicle)};if(Tr(e)){const t=((e,t,n)=>{const r=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateLongDistanceEVRoute`,o=new URL(r);fr(o,e.vehicle),e.chargingStopsStrategy&&o.searchParams.set("chargingStopsStrategy",e.chargingStopsStrategy);const a=Ht(e.vehicle)?.charging;if(!qn(e.vehicle)&&!a?.chargingConnectors?.length)throw new Error("Charging preferences require a charging model: set vehicle.model.engine.charging.chargingConnectors (or a predefined vehicle.model.variantId) to plan charging stops.");return{method:"POST",url:o,data:{...t,...a&&{chargingParameters:{...a.batteryCurve?.length&&{batteryCurve:a.batteryCurve},...a.chargingConnectors?.length&&{chargingConnectors:[...a.chargingConnectors]},...!A(a.chargingTimeOffsetInSec)&&{chargingTimeOffsetInSec:a.chargingTimeOffsetInSec}}},vehicleEngineType:"electric"},headers:n}})(e,c,i);return Cr(t.url,e),t}if(e.vehicle&&qn(e.vehicle))throw new Error(Rr);const l=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/routes/calculate`,u=new URL(l);return e.vehicle&&$n(u,e.vehicle),Cr(u,e),{method:"POST",url:u,data:c,headers:i}},sendRequest:X,parseResponse:(e,t)=>{const n=e.routes.map((n,r)=>((e,t,n,r)=>{const a={type:"LineString",coordinates:e.legs.flatMap(e=>e.path.coordinates)};return{type:"Feature",geometry:a,id:s(),bbox:o(a),properties:{index:t,summary:Fr(e.summary,n),sections:kr(e,n),...e.instructions?.length&&{guidance:so(e.instructions,a.coordinates,r)},...e.progressPoints&&{progress:e.progressPoints.map(e=>({pointIndex:e.pathIndex,distanceInMeters:e.distanceInMeters,travelTimeInSeconds:e.travelDurationInSeconds}))}}}})(n,r,t,e.roadShieldAtlasReference)),r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},parseResponseError:Ot,getAPIVersion:()=>3},lo=async e=>V(e,co,"Routing"),uo=C.object({minFuzzyLevel:C.number().min(1).max(4).optional(),maxFuzzyLevel:C.number().min(1).max(4).optional()}),po=ue.extend(ot.extend(uo.shape).shape),mo=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:Ue(e.details)}};break;case"NEARBY":t={...e,details:{position:Ue({lon:e.details.lon,lat:e.details.lat}),text:e.details.text,query:e.details.query}};break;case"BOOKMARK":case"W3W":t=e}return t},go={requestValidation:{schema:po},buildRequest:e=>{const t=new URL(`${(e=>Ee(e,`search/${encodeURIComponent(e.query??"")}.json`))(e)}`);Me(t,e);const n=t.searchParams;return Pe(n,"typeahead",e.typeahead),Pe(n,"ofs",e.offset),Ae(n,"countrySet",e.countries),Le(n,e.geoBias),Pe(n,"minFuzzyLevel",e.minFuzzyLevel),Pe(n,"maxFuzzyLevel",e.maxFuzzyLevel),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const t=e.results.map(We),n=a(o(t)),r=e.summary.queryIntent?.map(mo);return{type:"FeatureCollection",properties:{...je(e.summary),...r&&{queryIntent:r}},features:t,...n&&{bbox:n}}}},ho=C.object({geometries:C.array(C.union([re,te]))}),yo=ue.extend(ho.shape),fo=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:_e(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:Re(e.coordinates[0],50).map(e=>_e(e))}];case"MultiPolygon":return e.coordinates.length>50?(e=>{let t=/* @__PURE__ */new Map;return e.coordinates.forEach(e=>{const n=r(e[0]);if(n){const r=Math.abs((n[2]-n[0])*(n[3]-n[1]));t.set(e,r)}}),t=new Map([...t.entries()].sort((e,t)=>t[1]-e[1]).splice(0,50)),[...t.keys()]})(e).flatMap(e=>fo({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>fo({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>fo(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},To={requestValidation:{schema:yo},buildRequest:e=>{const t=new URL(`${n=e,Ee(n,`geometrySearch/${encodeURIComponent(n.query??"")}.json`)}`);var n;return Me(t,e),{url:t,headers:Ce(e),data:{geometryList:e.geometries.flatMap(fo)}}},sendRequest:Q,parseResponse:e=>{const t=e.results.map(We),n=a(o(t));return{type:"FeatureCollection",properties:{...je(e.summary)},features:t,...n&&{bbox:n}}}},Ro=async e=>"route"in e?qe(e):"geometries"in e?(async e=>V(e,To,"GeometrySearch"))(e):(async e=>V(e,go,"FuzzySearch"))(e),bo=async e=>tt("discoverOnePlace",e,Ro),Io=C.object({query:C.string()}),So=C.object({geoBias:nt.optional(),limit:C.number().max(100).optional(),countries:C.array(C.string()).optional(),resultTypes:C.array(C.string()).optional()}),Co=Io.extend(So.shape),vo={requestValidation:{schema:Co},buildRequest:e=>{const t=new URL(`${n=e,Ee(n,`autocomplete/${encodeURIComponent(n.query)}.json`)}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",ve(r,e),Pe(r,"limit",e.limit),Le(r,e.geoBias),Ae(r,"countrySet",e.countries),Ae(r,"resultSet",e.resultTypes),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:Ue(t)},radiusMeters:n.radius}},results:(r=e.results,r.map(e=>({segments:e.segments.map(e=>{if((e=>"category"===e.type)(e)){const{id:t,...n}=e;return{...n,category:R[Number(t)]}}return e})})))};var r}},Ao=async e=>V(e,vo,"Autocomplete"),Po=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean),Lo=e=>"category"===e.type&&e.matchedAlternativeName?[e.value,e.matchedAlternativeName]:[e.value],Mo=(e,t)=>{const n=t.flatMap(({segments:t})=>{const[n]=t;return 1===t.length&&"plaintext"!==n.type&&Lo(n).some(t=>((e,t)=>{const n=Po(t).join(""),r=Po(e);return""!==n&&r.some((e,t)=>r.slice(t).join("").startsWith(n))})(t,e))?[n]:[]});return n.find(t=>Lo(t).some(t=>((e,t)=>{const[n,...r]=Po(t);return 0===r.length&&Po(e).some(e=>e.startsWith(n)&&2*n.length>=e.length)})(t,e)))??n[0]},Eo=({query:e,concept:t,places:n,maxResults:r})=>{const o=D(n,e=>e.id),a="none"===t.status?o:E(o,t=>((e,t)=>{const n=Po(e);return Po(t).every(e=>n.some(t=>t.startsWith(e)))})(t.title,e)).flat();return[..."shown"===t.status?[t.suggestion]:[],...a].slice(0,r)},wo="SearchSuggestions",Do={brand:!0,category:!0},xo=e=>e in Do,Oo={place:["POI"],address:["PAD","Addr","XStr"],street:["Str"],area:["Geo"]},No={POI:"place",Street:"street",Geography:"area","Point Address":"address","Address Range":"address","Cross Street":"address"},Bo=e=>e*Math.PI/180,Ho=(e,t)=>e.properties.distance??(t&&(([e,t],[n,r])=>{const o=Math.sin(Bo(r-t)/2)**2+Math.cos(Bo(t))*Math.cos(Bo(r))*Math.sin(Bo(n-e)/2)**2;return 12742017.6*Math.asin(Math.sqrt(o))})(t,e.geometry.coordinates)),_o=(e,t)=>{const n=u(t)??void 0,r=((e,t)=>{if(t)return L(e,e=>Ho(e,t))?.properties.address.countryCode;const n=v(e,e=>e.properties.address.countryCode);return P(Object.keys(n),e=>n[e])})(e,n);return e.map(e=>((e,t,n)=>{const{type:r,address:o,poi:a}=e.properties,i=o.freeformAddress.split(", ").filter(Boolean),[s="",...c]=a?.name?[a.name,...i]:i,l=o.countryCode!==t?o.country:void 0;return{kind:No[r],id:String(e.id),title:s,subtitles:l?[...c,l]:c,distanceInMeters:Ho(e,n),resolve:async()=>({...e,properties:M(e.properties,["distance","score"])})}})(e,r,n))},Fo=e=>{if(e instanceof F)throw new F(wo,e.cause);if(e instanceof _)throw new _(e.message,wo,e.status);if(e instanceof B)throw new B(e.message,wo,e.issues);throw e},Uo=(e,t)=>{const n={...t,..."brand"===e.type?{poiBrands:[e.value]}:{poiCategories:[e.category]}},r={title:e.value,refineParams:n,refine:e=>Ro({...n,...e&&{signal:e}})};return"brand"===e.type?{...r,kind:"brand"}:{...r,kind:"category",category:e.category}},Go=(e,t)=>D(e.flatMap(e=>e.segments.flatMap(e=>"plaintext"===e.type?[]:[Uo(e,t)])),e=>`${e.kind}:${e.title}`),ko=(e,t,n,r)=>{const o=Mo(e,t);return o?"brand"!==o.type||((e,t)=>{const n=Po(e).join("");return t.slice(0,5).some(e=>e.properties.poi?.brands?.some(e=>Po(e).join("")===n))})(o.value,n)?{status:"shown",suggestion:Uo(o,r)}:{status:"withheld"}:{status:"none"}},Ko=async e=>{const{query:t,maxResults:n,filters:r,origin:o,view:a,signal:i,...s}=e,c=r?.countries,l=Math.max(1,Math.min(n??5,10)),{placeKinds:u,refinementKinds:d,wantsPlaces:p,wantsRefinements:m}=(e=>{const t=e?.filter(e=>!xo(e)),n=e?.filter(xo);return{placeKinds:t,refinementKinds:n,wantsPlaces:!e||Boolean(t?.length),wantsRefinements:!e||Boolean(n?.length)}})(r?.kinds),g=o&&{position:o},h=(r?.boundingBox&&{boundingBox:r.boundingBox})??g,y={...M(s,["onAPIRequest","onAPIResponse","apiVersion"]),query:"",countries:c,geoBias:h,view:a},f={...s,signal:i,query:t,limit:10,countries:c,view:a,typeahead:!0,geoBias:h,indexes:u?.flatMap(e=>Oo[e]),poiCategories:r?.poiTypes,geographyTypes:r?.areaTypes},[T,R]=await Promise.all([p?Ro(f):void 0,m?Ao({...s,signal:i,query:t,limit:l,countries:c,geoBias:g,resultTypes:d??["brand","category"]}):void 0]).catch(Fo),b=R?.results??[];if(!p)return{suggestions:Go(b,y).slice(0,l)};const I=(T?.features??[]).filter(e=>!u||u.includes(No[e.properties.type]));return{suggestions:Eo({query:t,concept:ko(t,b,I,y),places:_o(I,o),maxResults:l})}},Wo=864e5,jo=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n},Vo=e=>jo(/* @__PURE__ */new Date,-e),qo=e=>e instanceof Date?e.toISOString().slice(0,10):e,Yo=e=>Date.parse(qo(e)),$o=/(?:Z|[+-]\d{2}:\d{2})$/,Zo=e=>new Date($o.test(e)?e:`${e}Z`),zo=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],Jo={speed:{dataType:"SPEED",field:"v"},freeFlowSpeed:{dataType:"FREE_FLOW_SPEED",field:"fv"},congestionLevel:{dataType:"CONGESTION_LEVEL",field:"c"},travelTime:{dataType:"TRAVEL_TIME",field:"t"},networkLength:{dataType:"NETWORK_LENGTH",field:"l"}},Qo=Array.from({length:24},(e,t)=>t),Xo=e=>zo.indexOf(e),ea=(e,n)=>{const r={};for(const o of t){const t=e[Jo[o].field];void 0!==t&&(r[o]=n(t))}return r},ta=e=>ea(e,e=>e),na=e=>t.find(t=>Jo[t].dataType===e),ra=e=>{const t=Zo(e);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,date:new Date(Yo(t)),hour:t.getUTCHours()}},oa={yearly:({year:e})=>({year:e}),monthly:({year:e,month:t})=>({year:e,month:t}),weekly:({date:e})=>(e=>{const t=jo(e,4-(e.getUTCDay()||7)),n=t.getUTCFullYear(),r=(t.getTime()-Date.UTC(n,0,1))/Wo;return{year:n,week:Math.floor(r/7)+1}})(e),daily:({date:e})=>({date:e}),hourly:({date:e,hour:t})=>({date:e,hour:t})},aa=(e,t)=>e.map(e=>({...oa[t](ra(e.time)),...ta(e)})),ia={MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,SUNDAY:7},sa=e=>{const[t,n]=e.time.split("-"),r=Object.hasOwn(ia,t)?ia[t]:void 0;return void 0===r?void 0:{day:r,hour:Number(n),...ta(e)}},ca=({day:e,hour:t})=>24*(e-1)+t,la=e=>({tileCentre:[e.lon,e.lat],...ta(e)}),ua=e=>({startDate:Zo(e.startDate),endDate:Zo(e.endDate),labels:e.labels.map(({name:e})=>e)}),da=e=>{return{...e.yearly&&{yearly:aa(e.yearly,"yearly")},...e.monthly&&{monthly:aa(e.monthly,"monthly")},...e.weekly&&{weekly:aa(e.weekly,"weekly")},...e.daily&&{daily:aa(e.daily,"daily")},...e.hourly&&{hourly:aa(e.hourly,"hourly")},...e.average&&{average:(t=e.average,t.map(sa).filter(e=>void 0!==e).sort((e,t)=>ca(e)-ca(t)))}};var t},pa=e=>ea(e,e=>e.map(ua)),ma=e=>{return{type:e.type,id:e.id,geometry:e.geometry,properties:(t=e.properties,{name:t.name,...void 0!==t.timezone&&{timezone:t.timezone},level:t.level,baseData:ta(t.baseData),timedData:da(t.timedData),...t.tiledData&&{tiledData:{tiles:t.tiledData.tiles.map(la)}},...t.anomalies&&{anomalies:pa(t.anomalies)}}),bbox:o(e.geometry)};var t},ga=e=>{const n=e.flatMap(e=>e.properties.tiledData?.tiles??[]),r={};for(const o of t){const e=n.map(e=>e[o]).filter(e=>null!=e);e.length>0&&(r[o]={min:Math.min(...e),max:Math.max(...e)})}return r},ha=e=>{const t=e.map(Yo);return{startDate:new Date(Math.min(...t)),endDate:new Date(Math.max(...t))}},ya=C.union([C.date(),C.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),fa=C.union([C.object({type:C.literal("Polygon"),coordinates:C.array(C.array(C.array(C.number()))).min(1)}),C.object({type:C.literal("MultiPolygon"),coordinates:C.array(C.array(C.array(C.array(C.number())))).min(1)})]),Ta=e=>Yo(e)<=Yo(Vo(2)),Ra={requestValidation:{schema:K.extend({name:C.string().optional(),startDate:ya.optional(),endDate:ya.optional(),days:C.array(ya).min(1).optional(),metrics:C.union([C.array(C.enum(t)).min(1),C.literal("all")]),functionalRoadClasses:C.union([C.array(C.enum(zo)).min(1),C.literal("all")]),hours:C.union([C.array(C.number().int().min(0).max(23)).min(1),C.literal("all")]),geometry:fa}).refine(e=>{const t=void 0!==e.days,n=void 0!==e.startDate;if(t&&n)return!1;if(!t&&!n)return!1;if(void 0!==e.startDate){const t=e.endDate??Vo(3),n=(Yo(t)-Yo(e.startDate))/Wo;return n>=1&&n<=31}return!0},{message:"Provide either startDate (with optional endDate, at least 1 day apart and within 31 days) or days — but not both"}).refine(e=>void 0!==e.days?e.days.every(Ta):void 0===e.endDate||Ta(e.endDate),{message:"Dates must be at least 2 days before today"})},buildRequest:e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));Se(n.searchParams,e);const r=Array.isArray(e.days)?{days:e.days.map(qo)}:{startDate:qo(e.startDate??Vo(4)),endDate:qo(e.endDate??Vo(3))};return{method:"POST",url:n,data:{name:e.name??`Maps SDK JS Area Analytics Report ${/* @__PURE__ */(new Date).toISOString()}`,...r,dataTypes:("all"===e.metrics?t:e.metrics).map(e=>Jo[e].dataType),frcs:"all"===e.functionalRoadClasses?zo.map((e,t)=>t):e.functionalRoadClasses.map(Xo),hours:"all"===e.hours?Qo:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},sendRequest:X,parseResponse:e=>{const t=e.features.map(ma);return{type:"FeatureCollection",properties:{...ha(e.properties.days),metrics:e.properties.dataTypes.map(na).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:ga(t)},features:t}}},ba=async e=>V(e,Ra,"TrafficAreaAnalytics"),Ia=["incidents.type","incidents.geometry.type","incidents.geometry.coordinates",...Object.keys({id:!0,iconCategory:!0,magnitudeOfDelay:!0,"events.description":!0,"events.code":!0,"events.iconCategory":!0,startTime:!0,endTime:!0,from:!0,to:!0,lengthInMeters:!0,delayInSeconds:!0,roadNumbers:!0,timeValidity:!0,probabilityOfOccurrence:!0,numberOfReports:!0,lastReportTime:!0}).map(e=>`incidents.properties.${e}`)].join(","),Sa=e=>({description:e.description,code:e.code,category:Nr(e.iconCategory)}),Ca=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:Nr(t.iconCategory),magnitudeOfDelay:Br(t.magnitudeOfDelay),events:(t.events??[]).map(Sa),...t.startTime&&{startTime:new Date(t.startTime)},...t.endTime&&{endTime:new Date(t.endTime)},...t.from&&{from:t.from},...t.to&&{to:t.to},...null!=t.lengthInMeters&&{lengthInMeters:t.lengthInMeters},...null!=t.delayInSeconds&&{delayInSeconds:t.delayInSeconds},...t.roadNumbers&&{roadNumbers:t.roadNumbers},timeValidity:t.timeValidity,...t.probabilityOfOccurrence&&{probabilityOfOccurrence:t.probabilityOfOccurrence},...null!=t.numberOfReports&&{numberOfReports:t.numberOfReports},...t.lastReportTime&&{lastReportTime:new Date(t.lastReportTime)}}}},va=e=>"Polygon"===e.type?{type:"Polygon",coordinates:e.coordinates}:{type:"MultiPolygon",coordinates:e.coordinates},Aa=(e,t)=>{const n=(e=>"FeatureCollection"===e.type?e.features.map(e=>e.geometry):["Feature"===e.type?e.geometry:e])(t).map(va).map(e=>({geometry:e,bbox:x(e)}));return e.filter(e=>{const t=x(e.geometry);return n.some(n=>{return r=t,o=n.bbox,r[0]<=o[2]&&o[0]<=r[2]&&r[1]<=o[3]&&o[1]<=r[3]&&O(e.geometry,n.geometry);var r,o})})},Pa=C.array(C.number()).min(2,"a position needs at least two coordinates"),La=C.array(Pa).min(4,"a linear ring needs at least four positions"),Ma=C.array(La).min(1,"a Polygon needs at least one ring"),Ea=C.discriminatedUnion("type",[C.object({type:C.literal("Polygon"),coordinates:Ma}),C.object({type:C.literal("MultiPolygon"),coordinates:C.array(Ma).min(1,"a MultiPolygon needs at least one polygon")})]),wa=C.object({type:C.literal("Feature"),geometry:Ea,id:C.union([C.string(),C.number()]).optional(),properties:C.unknown().optional()}),Da=C.union([Ea,wa,C.object({type:C.literal("FeatureCollection"),features:C.array(wa).min(1,"a FeatureCollection polygon needs at least one feature")})]),xa={requestValidation:{schema:K.extend({bbox:se.optional(),polygon:Da.optional(),ids:C.array(C.string()).min(1,"ids must contain at least one id").optional(),categoryFilter:C.array(C.enum(I)).optional(),timeValidityFilter:C.array(C.enum(["present","future"])).optional()}),refinements:[{check:e=>1===[e.bbox,e.polygon,e.ids].filter(Boolean).length,message:"Provide exactly one of bbox, polygon or ids"}]},getAPIVersion:()=>2,buildRequest:e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidents/details`)(e)),n=t.searchParams;((e,t)=>{Ae(e,"iconCategories",t.categoryFilter?.map(Or)),Ae(e,"timeValidity",t.timeValidityFilter)})(n,e);const r=(e=>({...Ie(e),Attributes:Ia}))(e);if(e.ids){const{ids:o}=e;return o.length>5?{method:"POST",url:t,headers:r,data:{ids:o}}:(n.append("ids",o.join(",")),{method:"GET",url:t,headers:r})}const a=e.polygon?x(e.polygon,{recompute:!0}):o(e.bbox);return a&&n.append("bbox",a.join(",")),{method:"GET",url:t,headers:r}},sendRequest:X,parseResponse:(e,t)=>{const n=(e.incidents??[]).filter(e=>null!==e).map(Ca);return{type:"FeatureCollection",features:t?.polygon?Aa(n,t.polygon):n}}},Oa=async e=>V(e,xa,"TrafficIncidentDetails");export{H as APIErrorCode,F as SDKAbortError,B as SDKError,_ as SDKServiceError,qe as alongRouteSearch,On as budgetTypes,G as buildResponseError,k as buildValidationError,er as calculateReachableRange,nr as calculateReachableRanges,lo as calculateRoute,bo as discoverOnePlace,Ro as discoverPlaces,Je as evChargingStationsAvailability,ct as geocode,lt as geocodeOne,ht as geometryData,Dt as getPOICategories,xt as getPOICategoryCodes,bt as getPlaceDetails,Qe as getPlaceWithEVAvailability,Xe as getPlacesWithEVAvailability,Ko as getSearchSuggestions,et as hasChargingAvailability,U as parseDefaultResponseError,mr as reverseGeocode,$e as routeTypes,Ze as tollTransponderOptions,ba as trafficAreaAnalytics,Oa as trafficIncidentDetails};
2
2
  //# sourceMappingURL=services.es.js.map