@maptiler/client 3.1.0-rc.5 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
- import { decode } from '@googlemaps/polyline-codec';
2
1
  import QuickLRU from 'quick-lru';
3
2
 
3
+ const DEFAULT_API_HOST = "api.maptiler.com";
4
+ const EU_API_HOST = "api.maptiler.eu";
4
5
  function tryGettingFetch() {
5
6
  if (typeof self !== "undefined") {
6
7
  return fetch.bind(self);
@@ -21,6 +22,10 @@ class ClientConfig {
21
22
  * will be automatically resolved.
22
23
  */
23
24
  this._fetch = tryGettingFetch();
25
+ /**
26
+ * Whether to use the EU-based `api.maptiler.eu` host instead of the default `api.maptiler.com`
27
+ */
28
+ this._useEuEndpoints = false;
24
29
  /**
25
30
  * Number of tiles to keep in cache
26
31
  */
@@ -50,6 +55,32 @@ class ClientConfig {
50
55
  get fetch() {
51
56
  return this._fetch;
52
57
  }
58
+ /**
59
+ * Switch between the default `api.maptiler.com` host and the EU-based `api.maptiler.eu` host.
60
+ * Set to `false` to switch back to the default.
61
+ */
62
+ set useEuEndpoints(value) {
63
+ this._useEuEndpoints = value;
64
+ }
65
+ /**
66
+ * Whether the EU-based `api.maptiler.eu` host is currently in use instead of the default `api.maptiler.com`
67
+ */
68
+ get useEuEndpoints() {
69
+ return this._useEuEndpoints;
70
+ }
71
+ /**
72
+ * The host currently used for the MapTiler API requests (`api.maptiler.com` or `api.maptiler.eu`)
73
+ */
74
+ get apiHost() {
75
+ return this._useEuEndpoints ? EU_API_HOST : DEFAULT_API_HOST;
76
+ }
77
+ /**
78
+ * The base URL currently used for the MapTiler API requests
79
+ * (`https://api.maptiler.com/` or `https://api.maptiler.eu/`)
80
+ */
81
+ get apiURL() {
82
+ return `https://${this.apiHost}/`;
83
+ }
53
84
  }
54
85
  const config = new ClientConfig();
55
86
 
@@ -1019,12 +1050,6 @@ async function callFetch(resource, options = {}) {
1019
1050
  return config.fetch(resource, options);
1020
1051
  }
1021
1052
 
1022
- const defaults = {
1023
- maptilerApiURL: "https://api.maptiler.com/",
1024
- mapStyle: "streets-v2"
1025
- };
1026
- Object.freeze(defaults);
1027
-
1028
1053
  class ServiceError extends Error {
1029
1054
  constructor(res, customMessage = "") {
1030
1055
  super(
@@ -1097,7 +1122,7 @@ async function forward(query, options = {}) {
1097
1122
  }
1098
1123
  const endpoint = new URL(
1099
1124
  `geocoding/${encodeURIComponent(query)}.json`,
1100
- defaults.maptilerApiURL
1125
+ config.apiURL
1101
1126
  );
1102
1127
  addBaseGeocodingOptions(endpoint.searchParams, options);
1103
1128
  addLanguageGeocodingOptions(endpoint.searchParams, options);
@@ -1115,7 +1140,7 @@ async function reverse(position, options = {}) {
1115
1140
  }
1116
1141
  const endpoint = new URL(
1117
1142
  `geocoding/${position[0]},${position[1]}.json`,
1118
- defaults.maptilerApiURL
1143
+ config.apiURL
1119
1144
  );
1120
1145
  addBaseGeocodingOptions(endpoint.searchParams, options);
1121
1146
  addLanguageGeocodingOptions(endpoint.searchParams, options);
@@ -1127,7 +1152,7 @@ async function reverse(position, options = {}) {
1127
1152
  return await res.json();
1128
1153
  }
1129
1154
  async function byId(id, options = {}) {
1130
- const endpoint = new URL(`geocoding/${id}.json`, defaults.maptilerApiURL);
1155
+ const endpoint = new URL(`geocoding/${id}.json`, config.apiURL);
1131
1156
  addBaseGeocodingOptions(endpoint.searchParams, options);
1132
1157
  addLanguageGeocodingOptions(endpoint.searchParams, options);
1133
1158
  const res = await callFetch(endpoint.toString());
@@ -1141,10 +1166,7 @@ async function batch$1(queries, options = {}) {
1141
1166
  return [];
1142
1167
  }
1143
1168
  const joinedQuery = queries.map((query) => encodeURIComponent(query)).join(";");
1144
- const endpoint = new URL(
1145
- `geocoding/${joinedQuery}.json`,
1146
- defaults.maptilerApiURL
1147
- );
1169
+ const endpoint = new URL(`geocoding/${joinedQuery}.json`, config.apiURL);
1148
1170
  addBaseGeocodingOptions(endpoint.searchParams, options);
1149
1171
  addLanguageGeocodingOptions(endpoint.searchParams, options);
1150
1172
  addCommonForwardAndReverseGeocodingOptions(endpoint.searchParams, options);
@@ -1167,7 +1189,7 @@ const customMessages$3 = {
1167
1189
  403: "Key is missing, invalid or restricted"
1168
1190
  };
1169
1191
  async function info(options = {}) {
1170
- const endpoint = new URL(`geolocation/ip.json`, defaults.maptilerApiURL);
1192
+ const endpoint = new URL(`geolocation/ip.json`, config.apiURL);
1171
1193
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1172
1194
  if ("elevation" in options) {
1173
1195
  endpoint.searchParams.set(
@@ -1190,132 +1212,6 @@ const geolocation = {
1190
1212
  info
1191
1213
  };
1192
1214
 
1193
- function addLocations(search, locations) {
1194
- for (const loc of locations) {
1195
- search.append("location", `${loc.lon},${loc.lat}`);
1196
- }
1197
- }
1198
- function addResponseOptions(search, response) {
1199
- if (!response) return;
1200
- if (response.units) search.set("response.units", response.units);
1201
- if (response.language) search.set("response.language", response.language);
1202
- if (response.alternates !== void 0)
1203
- search.set("alternates", String(response.alternates));
1204
- if (response.additionalData?.detailLevel)
1205
- search.set(
1206
- "response.additionalData.detailLevel",
1207
- response.additionalData.detailLevel
1208
- );
1209
- }
1210
- function addProfileOptions(search, profile, opts) {
1211
- if (!opts) return;
1212
- if (profile === "car") {
1213
- const o = opts;
1214
- if (o.mode) search.set("car.mode", o.mode);
1215
- if (o.topSpeed) search.set("topSpeed", String(o.topSpeed));
1216
- if (o.avoidances?.tolls !== void 0)
1217
- search.set("avoidances.tolls", String(o.avoidances.tolls));
1218
- if (o.avoidances?.ferry !== void 0)
1219
- search.set("avoidances.ferry", String(o.avoidances.ferry));
1220
- if (o.avoidances?.highway !== void 0)
1221
- search.set("avoidances.highway", String(o.avoidances.highway));
1222
- }
1223
- if (profile === "truck") {
1224
- const o = opts;
1225
- if (o.height) search.set("truck.height", String(o.height));
1226
- if (o.weight) search.set("truck.weight", String(o.weight));
1227
- if (o.axleLoad) search.set("truck.axleLoad", String(o.axleLoad));
1228
- if (o.hazmat !== void 0) search.set("truck.hazmat", String(o.hazmat));
1229
- if (o.topSpeed) search.set("topSpeed", String(o.topSpeed));
1230
- if (o.avoidances?.tolls !== void 0)
1231
- search.set("avoidances.tolls", String(o.avoidances.tolls));
1232
- }
1233
- if (profile === "bicycle") {
1234
- const o = opts;
1235
- if (o.type) search.set("bicycle.type", o.type);
1236
- if (o.cyclingSpeed)
1237
- search.set("bicycle.cyclingSpeed", String(o.cyclingSpeed));
1238
- }
1239
- if (profile === "pedestrian") {
1240
- const o = opts;
1241
- if (o.walkingSpeed)
1242
- search.set("pedestrian.walkingSpeed", String(o.walkingSpeed));
1243
- }
1244
- }
1245
- function addRoutingOptions(search, options) {
1246
- const { adjustSearchParams } = options;
1247
- if (typeof adjustSearchParams === "function") {
1248
- adjustSearchParams(search);
1249
- }
1250
- search.set("key", config.apiKey);
1251
- }
1252
- function decodeLegGeometry(leg) {
1253
- if (typeof leg.geometry === "string") {
1254
- return decode(leg.geometry, 6).map(([lat, lon]) => [lon, lat]);
1255
- }
1256
- return leg.geometry;
1257
- }
1258
- async function processDirectionsResponse(res) {
1259
- if (!res.ok) {
1260
- throw new ServiceError(res);
1261
- }
1262
- const response = await res.json();
1263
- for (const leg of response.route.legs) {
1264
- leg.geometry = decodeLegGeometry(leg);
1265
- }
1266
- if (response.alternates) {
1267
- for (const alternateRoute of response.alternates) {
1268
- for (const leg of alternateRoute.legs) {
1269
- leg.geometry = decodeLegGeometry(leg);
1270
- }
1271
- }
1272
- }
1273
- return response;
1274
- }
1275
- async function directionsPost(body, options = {}) {
1276
- const { fetchExtras } = options;
1277
- const url = new URL("routing/v1/directions", defaults.maptilerApiURL);
1278
- addRoutingOptions(url.searchParams, options);
1279
- const headers = new Headers(fetchExtras?.headers);
1280
- headers.set("content-type", "application/json");
1281
- const res = await callFetch(url.toString(), {
1282
- ...fetchExtras,
1283
- method: "POST",
1284
- headers,
1285
- body: JSON.stringify(body)
1286
- });
1287
- return await processDirectionsResponse(res);
1288
- }
1289
- async function directionsGet(req, options = {}) {
1290
- const { fetchExtras } = options;
1291
- const url = new URL("routing/v1/directions", defaults.maptilerApiURL);
1292
- const search = url.searchParams;
1293
- search.set("profile", req.profile);
1294
- if (req.id) search.set("id", req.id);
1295
- if (req.departureTime) search.set("departureTime", req.departureTime);
1296
- if (req.arrivalTime) search.set("arrivalTime", req.arrivalTime);
1297
- addLocations(search, req.locations);
1298
- addResponseOptions(search, req.response);
1299
- addProfileOptions(search, req.profile, req.profileOptions);
1300
- addRoutingOptions(search, options);
1301
- const res = await callFetch(url.toString(), {
1302
- ...fetchExtras,
1303
- method: "GET",
1304
- body: null
1305
- });
1306
- return await processDirectionsResponse(res);
1307
- }
1308
- const routing = {
1309
- /**
1310
- * Get directions using POST request
1311
- */
1312
- directionsPost,
1313
- /**
1314
- * Get directions using GET request
1315
- */
1316
- directionsGet
1317
- };
1318
-
1319
1215
  const customMessages$2 = {
1320
1216
  403: "Key is missing, invalid or restricted"
1321
1217
  };
@@ -1323,10 +1219,7 @@ async function search(query, options = {}) {
1323
1219
  if (typeof query !== "string" || query.trim().length === 0) {
1324
1220
  throw new Error("The query must be a non-empty string");
1325
1221
  }
1326
- const endpoint = new URL(
1327
- `coordinates/search/${query}.json`,
1328
- defaults.maptilerApiURL
1329
- );
1222
+ const endpoint = new URL(`coordinates/search/${query}.json`, config.apiURL);
1330
1223
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1331
1224
  if ("limit" in options) {
1332
1225
  endpoint.searchParams.set("limit", options.limit.toString());
@@ -1355,7 +1248,7 @@ async function transform(positions, options = {}) {
1355
1248
  const coordinatesStr = (Array.isArray(positions[0]) ? positions : [positions]).map((coord) => `${coord[0]},${coord[1]}`).join(";");
1356
1249
  const endpoint = new URL(
1357
1250
  `coordinates/transform/${coordinatesStr}.json`,
1358
- defaults.maptilerApiURL
1251
+ config.apiURL
1359
1252
  );
1360
1253
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1361
1254
  if ("sourceCrs" in options) {
@@ -1395,7 +1288,7 @@ async function get(dataId, options = {}) {
1395
1288
  }
1396
1289
  const endpoint = new URL(
1397
1290
  `data/${encodeURIComponent(dataId)}/features.json`,
1398
- defaults.maptilerApiURL
1291
+ config.apiURL
1399
1292
  );
1400
1293
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1401
1294
  const urlWithParams = endpoint.toString();
@@ -1421,9 +1314,9 @@ function expandMapStyle(style) {
1421
1314
  if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
1422
1315
  expandedStyle = trimmed;
1423
1316
  } else if ((match = maptilerDomainRegex.exec(trimmed)) !== null) {
1424
- expandedStyle = `https://api.maptiler.com/maps/${match[1]}/style.json`;
1317
+ expandedStyle = `${config.apiURL}maps/${match[1]}/style.json`;
1425
1318
  } else {
1426
- expandedStyle = `https://api.maptiler.com/maps/${trimmed}/style.json`;
1319
+ expandedStyle = `${config.apiURL}maps/${trimmed}/style.json`;
1427
1320
  }
1428
1321
  return expandedStyle;
1429
1322
  }
@@ -2645,7 +2538,7 @@ function centered(center, zoom, options = {}) {
2645
2538
  }
2646
2539
  const endpoint = new URL(
2647
2540
  `maps/${encodeURIComponent(style)}/static/${center[0]},${center[1]},${zoom}/${width}x${height}${scale}.${format}`,
2648
- defaults.maptilerApiURL
2541
+ config.apiURL
2649
2542
  );
2650
2543
  if ("attribution" in options) {
2651
2544
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2694,7 +2587,7 @@ function bounded(boundingBox, options = {}) {
2694
2587
  }
2695
2588
  const endpoint = new URL(
2696
2589
  `maps/${encodeURIComponent(style)}/static/${boundingBox[0]},${boundingBox[1]},${boundingBox[2]},${boundingBox[3]}/${width}x${height}${scale}.${format}`,
2697
- defaults.maptilerApiURL
2590
+ config.apiURL
2698
2591
  );
2699
2592
  if ("attribution" in options) {
2700
2593
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2753,7 +2646,7 @@ function automatic(options = {}) {
2753
2646
  `maps/${encodeURIComponent(
2754
2647
  style
2755
2648
  )}/static/auto/${width}x${height}${scale}.${format}`,
2756
- defaults.maptilerApiURL
2649
+ config.apiURL
2757
2650
  );
2758
2651
  if ("attribution" in options) {
2759
2652
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2950,6 +2843,7 @@ const TERRAIN_TILESET = "terrain-rgb-v2";
2950
2843
  const API_BATCH_SIZE = 50;
2951
2844
  const API_WARN_SIZE = 1e3;
2952
2845
  let terrainTileJson = null;
2846
+ let terrainTileJsonHost = null;
2953
2847
  const customMessages = {
2954
2848
  403: "Key is missing, invalid or restricted"
2955
2849
  };
@@ -2965,10 +2859,7 @@ async function computeOnServer(positions, apiKey) {
2965
2859
  const startPos = part * API_BATCH_SIZE;
2966
2860
  const batch2 = positions.slice(startPos, startPos + API_BATCH_SIZE);
2967
2861
  const batchEncoded = batch2.map((pos) => pos.join(",")).join(";");
2968
- const endpoint = new URL(
2969
- `elevation/${batchEncoded}.json`,
2970
- defaults.maptilerApiURL
2971
- );
2862
+ const endpoint = new URL(`elevation/${batchEncoded}.json`, config.apiURL);
2972
2863
  endpoint.searchParams.set("key", apiKey);
2973
2864
  return callFetch(endpoint.toString());
2974
2865
  }
@@ -2992,16 +2883,17 @@ async function computeOnServer(positions, apiKey) {
2992
2883
  return jsons.flat();
2993
2884
  }
2994
2885
  async function computeOnClient(positions, apiKey, zoom) {
2995
- if (!terrainTileJson) {
2886
+ if (!terrainTileJson || terrainTileJsonHost !== config.apiHost) {
2996
2887
  const endpoint = new URL(
2997
2888
  `tiles/${TERRAIN_TILESET}/tiles.json`,
2998
- defaults.maptilerApiURL
2889
+ config.apiURL
2999
2890
  );
3000
2891
  endpoint.searchParams.set("key", apiKey);
3001
2892
  const urlWithParams = endpoint.toString();
3002
2893
  const res = await callFetch(urlWithParams);
3003
2894
  if (res.ok) {
3004
2895
  terrainTileJson = await res.json();
2896
+ terrainTileJsonHost = config.apiHost;
3005
2897
  } else {
3006
2898
  throw new ServiceError(res, customMessages[res.status] ?? "");
3007
2899
  }
@@ -3139,5 +3031,5 @@ const elevation = {
3139
3031
  fromMultiLineString
3140
3032
  };
3141
3033
 
3142
- export { ClientConfig, ISOLanguage, Language, MapStyle, MapStyleVariant, NonISOLanguage, ReferenceMapStyle, ServiceError, areSameLanguages, bufferToPixelDataBrowser, canParsePixelData, circumferenceAtLatitude, config, coordinates, data, defaultReferenceStyleMap, elevation, expandMapStyle, geocoding, geolocation, getAutoLanguage, getBufferToPixelDataParser, getLanguageInfoFromCode, getLanguageInfoFromFlag, getLanguageInfoFromKey, getTileCache, isLanguageInfo, mapStylePresetList, math, misc, routing, staticMaps, styleToStyle, toLanguageInfo };
3034
+ export { ClientConfig, ISOLanguage, Language, MapStyle, MapStyleVariant, NonISOLanguage, ReferenceMapStyle, ServiceError, areSameLanguages, bufferToPixelDataBrowser, canParsePixelData, circumferenceAtLatitude, config, coordinates, data, defaultReferenceStyleMap, elevation, expandMapStyle, geocoding, geolocation, getAutoLanguage, getBufferToPixelDataParser, getLanguageInfoFromCode, getLanguageInfoFromFlag, getLanguageInfoFromKey, getTileCache, isLanguageInfo, mapStylePresetList, math, misc, staticMaps, styleToStyle, toLanguageInfo };
3143
3035
  //# sourceMappingURL=maptiler-client.mjs.map