@maptiler/client 3.1.0-rc.6 → 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,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const DEFAULT_API_HOST = "api.maptiler.com";
4
+ const EU_API_HOST = "api.maptiler.eu";
3
5
  function tryGettingFetch() {
4
6
  if (typeof self !== "undefined") {
5
7
  return fetch.bind(self);
@@ -20,6 +22,10 @@ class ClientConfig {
20
22
  * will be automatically resolved.
21
23
  */
22
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;
23
29
  /**
24
30
  * Number of tiles to keep in cache
25
31
  */
@@ -49,6 +55,32 @@ class ClientConfig {
49
55
  get fetch() {
50
56
  return this._fetch;
51
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
+ }
52
84
  }
53
85
  const config = new ClientConfig();
54
86
 
@@ -1018,12 +1050,6 @@ async function callFetch(resource, options = {}) {
1018
1050
  return config.fetch(resource, options);
1019
1051
  }
1020
1052
 
1021
- const defaults = {
1022
- maptilerApiURL: "https://api.maptiler.com/",
1023
- mapStyle: "streets-v2"
1024
- };
1025
- Object.freeze(defaults);
1026
-
1027
1053
  class ServiceError extends Error {
1028
1054
  constructor(res, customMessage = "") {
1029
1055
  super(
@@ -1096,7 +1122,7 @@ async function forward(query, options = {}) {
1096
1122
  }
1097
1123
  const endpoint = new URL(
1098
1124
  `geocoding/${encodeURIComponent(query)}.json`,
1099
- defaults.maptilerApiURL
1125
+ config.apiURL
1100
1126
  );
1101
1127
  addBaseGeocodingOptions(endpoint.searchParams, options);
1102
1128
  addLanguageGeocodingOptions(endpoint.searchParams, options);
@@ -1114,7 +1140,7 @@ async function reverse(position, options = {}) {
1114
1140
  }
1115
1141
  const endpoint = new URL(
1116
1142
  `geocoding/${position[0]},${position[1]}.json`,
1117
- defaults.maptilerApiURL
1143
+ config.apiURL
1118
1144
  );
1119
1145
  addBaseGeocodingOptions(endpoint.searchParams, options);
1120
1146
  addLanguageGeocodingOptions(endpoint.searchParams, options);
@@ -1126,7 +1152,7 @@ async function reverse(position, options = {}) {
1126
1152
  return await res.json();
1127
1153
  }
1128
1154
  async function byId(id, options = {}) {
1129
- const endpoint = new URL(`geocoding/${id}.json`, defaults.maptilerApiURL);
1155
+ const endpoint = new URL(`geocoding/${id}.json`, config.apiURL);
1130
1156
  addBaseGeocodingOptions(endpoint.searchParams, options);
1131
1157
  addLanguageGeocodingOptions(endpoint.searchParams, options);
1132
1158
  const res = await callFetch(endpoint.toString());
@@ -1140,10 +1166,7 @@ async function batch$1(queries, options = {}) {
1140
1166
  return [];
1141
1167
  }
1142
1168
  const joinedQuery = queries.map((query) => encodeURIComponent(query)).join(";");
1143
- const endpoint = new URL(
1144
- `geocoding/${joinedQuery}.json`,
1145
- defaults.maptilerApiURL
1146
- );
1169
+ const endpoint = new URL(`geocoding/${joinedQuery}.json`, config.apiURL);
1147
1170
  addBaseGeocodingOptions(endpoint.searchParams, options);
1148
1171
  addLanguageGeocodingOptions(endpoint.searchParams, options);
1149
1172
  addCommonForwardAndReverseGeocodingOptions(endpoint.searchParams, options);
@@ -1166,7 +1189,7 @@ const customMessages$3 = {
1166
1189
  403: "Key is missing, invalid or restricted"
1167
1190
  };
1168
1191
  async function info(options = {}) {
1169
- const endpoint = new URL(`geolocation/ip.json`, defaults.maptilerApiURL);
1192
+ const endpoint = new URL(`geolocation/ip.json`, config.apiURL);
1170
1193
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1171
1194
  if ("elevation" in options) {
1172
1195
  endpoint.searchParams.set(
@@ -1189,206 +1212,6 @@ const geolocation = {
1189
1212
  info
1190
1213
  };
1191
1214
 
1192
- /**
1193
- * Copyright 2020 Google LLC
1194
- *
1195
- * Licensed under the Apache License, Version 2.0 (the "License");
1196
- * you may not use this file except in compliance with the License.
1197
- * You may obtain a copy of the License at
1198
- *
1199
- * http://www.apache.org/licenses/LICENSE-2.0
1200
- *
1201
- * Unless required by applicable law or agreed to in writing, software
1202
- * distributed under the License is distributed on an "AS IS" BASIS,
1203
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1204
- * See the License for the specific language governing permissions and
1205
- * limitations under the License.
1206
- */
1207
- /**
1208
- * Decodes an encoded path string into a sequence of LatLngs.
1209
- *
1210
- * See {@link https://developers.google.com/maps/documentation/utilities/polylinealgorithm}
1211
- *
1212
- * #### Example
1213
- *
1214
- * ```js
1215
- * import { decode } from "@googlemaps/polyline-codec";
1216
- *
1217
- * const encoded = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";
1218
- * console.log(decode(encoded, 5));
1219
- * // [
1220
- * // [38.5, -120.2],
1221
- * // [40.7, -120.95],
1222
- * // [43.252, -126.453],
1223
- * // ]
1224
- * ```
1225
- */
1226
- var decode = function (encodedPath, precision) {
1227
- var factor = Math.pow(10, precision);
1228
- var len = encodedPath.length;
1229
- // For speed we preallocate to an upper bound on the final length, then
1230
- // truncate the array before returning.
1231
- var path = new Array(Math.floor(encodedPath.length / 2));
1232
- var index = 0;
1233
- var lat = 0;
1234
- var lng = 0;
1235
- var pointIndex = 0;
1236
- // This code has been profiled and optimized, so don't modify it without
1237
- // measuring its performance.
1238
- for (; index < len; ++pointIndex) {
1239
- // Fully unrolling the following loops speeds things up about 5%.
1240
- var result = 1;
1241
- var shift = 0;
1242
- var b = void 0;
1243
- do {
1244
- // Invariant: "result" is current partial result plus (1 << shift).
1245
- // The following line effectively clears this bit by decrementing "b".
1246
- b = encodedPath.charCodeAt(index++) - 63 - 1;
1247
- result += b << shift;
1248
- shift += 5;
1249
- } while (b >= 0x1f); // See note above.
1250
- lat += result & 1 ? ~(result >> 1) : result >> 1;
1251
- result = 1;
1252
- shift = 0;
1253
- do {
1254
- b = encodedPath.charCodeAt(index++) - 63 - 1;
1255
- result += b << shift;
1256
- shift += 5;
1257
- } while (b >= 0x1f);
1258
- lng += result & 1 ? ~(result >> 1) : result >> 1;
1259
- path[pointIndex] = [lat / factor, lng / factor];
1260
- }
1261
- // truncate array
1262
- path.length = pointIndex;
1263
- return path;
1264
- };
1265
-
1266
- function addLocations(search, locations) {
1267
- for (const loc of locations) {
1268
- search.append("location", `${loc.lon},${loc.lat}`);
1269
- }
1270
- }
1271
- function addResponseOptions(search, response) {
1272
- if (!response) return;
1273
- if (response.units) search.set("response.units", response.units);
1274
- if (response.language) search.set("response.language", response.language);
1275
- if (response.alternates !== void 0)
1276
- search.set("alternates", String(response.alternates));
1277
- if (response.additionalData?.detailLevel)
1278
- search.set(
1279
- "response.additionalData.detailLevel",
1280
- response.additionalData.detailLevel
1281
- );
1282
- }
1283
- function addProfileOptions(search, profile, opts) {
1284
- if (!opts) return;
1285
- if (profile === "car") {
1286
- const o = opts;
1287
- if (o.mode) search.set("car.mode", o.mode);
1288
- if (o.topSpeed) search.set("topSpeed", String(o.topSpeed));
1289
- if (o.avoidances?.tolls !== void 0)
1290
- search.set("avoidances.tolls", String(o.avoidances.tolls));
1291
- if (o.avoidances?.ferry !== void 0)
1292
- search.set("avoidances.ferry", String(o.avoidances.ferry));
1293
- if (o.avoidances?.highway !== void 0)
1294
- search.set("avoidances.highway", String(o.avoidances.highway));
1295
- }
1296
- if (profile === "truck") {
1297
- const o = opts;
1298
- if (o.height) search.set("truck.height", String(o.height));
1299
- if (o.weight) search.set("truck.weight", String(o.weight));
1300
- if (o.axleLoad) search.set("truck.axleLoad", String(o.axleLoad));
1301
- if (o.hazmat !== void 0) search.set("truck.hazmat", String(o.hazmat));
1302
- if (o.topSpeed) search.set("topSpeed", String(o.topSpeed));
1303
- if (o.avoidances?.tolls !== void 0)
1304
- search.set("avoidances.tolls", String(o.avoidances.tolls));
1305
- }
1306
- if (profile === "bicycle") {
1307
- const o = opts;
1308
- if (o.type) search.set("bicycle.type", o.type);
1309
- if (o.cyclingSpeed)
1310
- search.set("bicycle.cyclingSpeed", String(o.cyclingSpeed));
1311
- }
1312
- if (profile === "pedestrian") {
1313
- const o = opts;
1314
- if (o.walkingSpeed)
1315
- search.set("pedestrian.walkingSpeed", String(o.walkingSpeed));
1316
- }
1317
- }
1318
- function addRoutingOptions(search, options) {
1319
- const { adjustSearchParams } = options;
1320
- if (typeof adjustSearchParams === "function") {
1321
- adjustSearchParams(search);
1322
- }
1323
- search.set("key", config.apiKey);
1324
- }
1325
- function decodeLegGeometry(leg) {
1326
- if (typeof leg.geometry === "string") {
1327
- return decode(leg.geometry, 6).map(([lat, lon]) => [lon, lat]);
1328
- }
1329
- return leg.geometry;
1330
- }
1331
- async function processDirectionsResponse(res) {
1332
- if (!res.ok) {
1333
- throw new ServiceError(res);
1334
- }
1335
- const response = await res.json();
1336
- for (const leg of response.route.legs) {
1337
- leg.geometry = decodeLegGeometry(leg);
1338
- }
1339
- if (response.alternates) {
1340
- for (const alternateRoute of response.alternates) {
1341
- for (const leg of alternateRoute.legs) {
1342
- leg.geometry = decodeLegGeometry(leg);
1343
- }
1344
- }
1345
- }
1346
- return response;
1347
- }
1348
- async function directionsPost(body, options = {}) {
1349
- const { fetchExtras } = options;
1350
- const url = new URL("routing/v1/directions", defaults.maptilerApiURL);
1351
- addRoutingOptions(url.searchParams, options);
1352
- const headers = new Headers(fetchExtras?.headers);
1353
- headers.set("content-type", "application/json");
1354
- const res = await callFetch(url.toString(), {
1355
- ...fetchExtras,
1356
- method: "POST",
1357
- headers,
1358
- body: JSON.stringify(body)
1359
- });
1360
- return await processDirectionsResponse(res);
1361
- }
1362
- async function directionsGet(req, options = {}) {
1363
- const { fetchExtras } = options;
1364
- const url = new URL("routing/v1/directions", defaults.maptilerApiURL);
1365
- const search = url.searchParams;
1366
- search.set("profile", req.profile);
1367
- if (req.id) search.set("id", req.id);
1368
- if (req.departureTime) search.set("departureTime", req.departureTime);
1369
- if (req.arrivalTime) search.set("arrivalTime", req.arrivalTime);
1370
- addLocations(search, req.locations);
1371
- addResponseOptions(search, req.response);
1372
- addProfileOptions(search, req.profile, req.profileOptions);
1373
- addRoutingOptions(search, options);
1374
- const res = await callFetch(url.toString(), {
1375
- ...fetchExtras,
1376
- method: "GET",
1377
- body: null
1378
- });
1379
- return await processDirectionsResponse(res);
1380
- }
1381
- const routing = {
1382
- /**
1383
- * Get directions using POST request
1384
- */
1385
- directionsPost,
1386
- /**
1387
- * Get directions using GET request
1388
- */
1389
- directionsGet
1390
- };
1391
-
1392
1215
  const customMessages$2 = {
1393
1216
  403: "Key is missing, invalid or restricted"
1394
1217
  };
@@ -1396,10 +1219,7 @@ async function search(query, options = {}) {
1396
1219
  if (typeof query !== "string" || query.trim().length === 0) {
1397
1220
  throw new Error("The query must be a non-empty string");
1398
1221
  }
1399
- const endpoint = new URL(
1400
- `coordinates/search/${query}.json`,
1401
- defaults.maptilerApiURL
1402
- );
1222
+ const endpoint = new URL(`coordinates/search/${query}.json`, config.apiURL);
1403
1223
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1404
1224
  if ("limit" in options) {
1405
1225
  endpoint.searchParams.set("limit", options.limit.toString());
@@ -1428,7 +1248,7 @@ async function transform(positions, options = {}) {
1428
1248
  const coordinatesStr = (Array.isArray(positions[0]) ? positions : [positions]).map((coord) => `${coord[0]},${coord[1]}`).join(";");
1429
1249
  const endpoint = new URL(
1430
1250
  `coordinates/transform/${coordinatesStr}.json`,
1431
- defaults.maptilerApiURL
1251
+ config.apiURL
1432
1252
  );
1433
1253
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1434
1254
  if ("sourceCrs" in options) {
@@ -1468,7 +1288,7 @@ async function get(dataId, options = {}) {
1468
1288
  }
1469
1289
  const endpoint = new URL(
1470
1290
  `data/${encodeURIComponent(dataId)}/features.json`,
1471
- defaults.maptilerApiURL
1291
+ config.apiURL
1472
1292
  );
1473
1293
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1474
1294
  const urlWithParams = endpoint.toString();
@@ -1494,9 +1314,9 @@ function expandMapStyle(style) {
1494
1314
  if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
1495
1315
  expandedStyle = trimmed;
1496
1316
  } else if ((match = maptilerDomainRegex.exec(trimmed)) !== null) {
1497
- expandedStyle = `https://api.maptiler.com/maps/${match[1]}/style.json`;
1317
+ expandedStyle = `${config.apiURL}maps/${match[1]}/style.json`;
1498
1318
  } else {
1499
- expandedStyle = `https://api.maptiler.com/maps/${trimmed}/style.json`;
1319
+ expandedStyle = `${config.apiURL}maps/${trimmed}/style.json`;
1500
1320
  }
1501
1321
  return expandedStyle;
1502
1322
  }
@@ -2718,7 +2538,7 @@ function centered(center, zoom, options = {}) {
2718
2538
  }
2719
2539
  const endpoint = new URL(
2720
2540
  `maps/${encodeURIComponent(style)}/static/${center[0]},${center[1]},${zoom}/${width}x${height}${scale}.${format}`,
2721
- defaults.maptilerApiURL
2541
+ config.apiURL
2722
2542
  );
2723
2543
  if ("attribution" in options) {
2724
2544
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2767,7 +2587,7 @@ function bounded(boundingBox, options = {}) {
2767
2587
  }
2768
2588
  const endpoint = new URL(
2769
2589
  `maps/${encodeURIComponent(style)}/static/${boundingBox[0]},${boundingBox[1]},${boundingBox[2]},${boundingBox[3]}/${width}x${height}${scale}.${format}`,
2770
- defaults.maptilerApiURL
2590
+ config.apiURL
2771
2591
  );
2772
2592
  if ("attribution" in options) {
2773
2593
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2826,7 +2646,7 @@ function automatic(options = {}) {
2826
2646
  `maps/${encodeURIComponent(
2827
2647
  style
2828
2648
  )}/static/auto/${width}x${height}${scale}.${format}`,
2829
- defaults.maptilerApiURL
2649
+ config.apiURL
2830
2650
  );
2831
2651
  if ("attribution" in options) {
2832
2652
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -3317,6 +3137,7 @@ const TERRAIN_TILESET = "terrain-rgb-v2";
3317
3137
  const API_BATCH_SIZE = 50;
3318
3138
  const API_WARN_SIZE = 1e3;
3319
3139
  let terrainTileJson = null;
3140
+ let terrainTileJsonHost = null;
3320
3141
  const customMessages = {
3321
3142
  403: "Key is missing, invalid or restricted"
3322
3143
  };
@@ -3332,10 +3153,7 @@ async function computeOnServer(positions, apiKey) {
3332
3153
  const startPos = part * API_BATCH_SIZE;
3333
3154
  const batch2 = positions.slice(startPos, startPos + API_BATCH_SIZE);
3334
3155
  const batchEncoded = batch2.map((pos) => pos.join(",")).join(";");
3335
- const endpoint = new URL(
3336
- `elevation/${batchEncoded}.json`,
3337
- defaults.maptilerApiURL
3338
- );
3156
+ const endpoint = new URL(`elevation/${batchEncoded}.json`, config.apiURL);
3339
3157
  endpoint.searchParams.set("key", apiKey);
3340
3158
  return callFetch(endpoint.toString());
3341
3159
  }
@@ -3359,16 +3177,17 @@ async function computeOnServer(positions, apiKey) {
3359
3177
  return jsons.flat();
3360
3178
  }
3361
3179
  async function computeOnClient(positions, apiKey, zoom) {
3362
- if (!terrainTileJson) {
3180
+ if (!terrainTileJson || terrainTileJsonHost !== config.apiHost) {
3363
3181
  const endpoint = new URL(
3364
3182
  `tiles/${TERRAIN_TILESET}/tiles.json`,
3365
- defaults.maptilerApiURL
3183
+ config.apiURL
3366
3184
  );
3367
3185
  endpoint.searchParams.set("key", apiKey);
3368
3186
  const urlWithParams = endpoint.toString();
3369
3187
  const res = await callFetch(urlWithParams);
3370
3188
  if (res.ok) {
3371
3189
  terrainTileJson = await res.json();
3190
+ terrainTileJsonHost = config.apiHost;
3372
3191
  } else {
3373
3192
  throw new ServiceError(res, customMessages[res.status] ?? "");
3374
3193
  }
@@ -3536,7 +3355,6 @@ exports.isLanguageInfo = isLanguageInfo;
3536
3355
  exports.mapStylePresetList = mapStylePresetList;
3537
3356
  exports.math = math;
3538
3357
  exports.misc = misc;
3539
- exports.routing = routing;
3540
3358
  exports.staticMaps = staticMaps;
3541
3359
  exports.styleToStyle = styleToStyle;
3542
3360
  exports.toLanguageInfo = toLanguageInfo;