@maptiler/client 3.1.0-rc.6 → 3.2.0-rc.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.
@@ -1,5 +1,7 @@
1
1
  import QuickLRU from 'quick-lru';
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(
@@ -1263,6 +1286,7 @@ var decode = function (encodedPath, precision) {
1263
1286
  return path;
1264
1287
  };
1265
1288
 
1289
+ const POLYLINE_PRECISION = 6;
1266
1290
  function addLocations(search, locations) {
1267
1291
  for (const loc of locations) {
1268
1292
  search.append("location", `${loc.lon},${loc.lat}`);
@@ -1270,84 +1294,115 @@ function addLocations(search, locations) {
1270
1294
  }
1271
1295
  function addResponseOptions(search, response) {
1272
1296
  if (!response) return;
1273
- if (response.units) search.set("response.units", response.units);
1274
- if (response.language) search.set("response.language", response.language);
1297
+ if (response.units !== void 0)
1298
+ search.set("response.units", response.units);
1299
+ if (response.language !== void 0)
1300
+ search.set("response.language", response.language);
1275
1301
  if (response.alternates !== void 0)
1276
1302
  search.set("alternates", String(response.alternates));
1277
- if (response.additionalData?.detailLevel)
1303
+ if (response.additionalData?.detailLevel !== void 0)
1278
1304
  search.set(
1279
1305
  "response.additionalData.detailLevel",
1280
1306
  response.additionalData.detailLevel
1281
1307
  );
1282
1308
  }
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));
1309
+ function addSpeedAndAvoidances(search, opts) {
1310
+ if (opts.topSpeed !== void 0)
1311
+ search.set("topSpeed", String(opts.topSpeed));
1312
+ const { avoidances } = opts;
1313
+ if (!avoidances) return;
1314
+ if (avoidances.tolls !== void 0)
1315
+ search.set("avoidances.tolls", String(avoidances.tolls));
1316
+ if (avoidances.ferry !== void 0)
1317
+ search.set("avoidances.ferry", String(avoidances.ferry));
1318
+ if (avoidances.highway !== void 0)
1319
+ search.set("avoidances.highway", String(avoidances.highway));
1320
+ }
1321
+ function addProfileOptions(search, req) {
1322
+ switch (req.profile) {
1323
+ case "car": {
1324
+ const opts = req.profileOptions;
1325
+ if (!opts) return;
1326
+ if (opts.mode !== void 0) search.set("car.mode", opts.mode);
1327
+ addSpeedAndAvoidances(search, opts);
1328
+ return;
1329
+ }
1330
+ case "truck": {
1331
+ const opts = req.profileOptions;
1332
+ if (!opts) return;
1333
+ if (opts.height !== void 0)
1334
+ search.set("truck.height", String(opts.height));
1335
+ if (opts.weight !== void 0)
1336
+ search.set("truck.weight", String(opts.weight));
1337
+ if (opts.axleLoad !== void 0)
1338
+ search.set("truck.axleLoad", String(opts.axleLoad));
1339
+ if (opts.hazmat !== void 0)
1340
+ search.set("truck.hazmat", String(opts.hazmat));
1341
+ addSpeedAndAvoidances(search, opts);
1342
+ return;
1343
+ }
1344
+ case "bicycle": {
1345
+ const opts = req.profileOptions;
1346
+ if (!opts) return;
1347
+ if (opts.type !== void 0) search.set("bicycle.type", opts.type);
1348
+ if (opts.cyclingSpeed !== void 0)
1349
+ search.set("bicycle.cyclingSpeed", String(opts.cyclingSpeed));
1350
+ return;
1351
+ }
1352
+ case "pedestrian": {
1353
+ const opts = req.profileOptions;
1354
+ if (!opts) return;
1355
+ if (opts.walkingSpeed !== void 0)
1356
+ search.set("pedestrian.walkingSpeed", String(opts.walkingSpeed));
1357
+ return;
1358
+ }
1316
1359
  }
1317
1360
  }
1318
1361
  function addRoutingOptions(search, options) {
1319
- const { adjustSearchParams } = options;
1362
+ const { adjustSearchParams, apiKey } = options;
1320
1363
  if (typeof adjustSearchParams === "function") {
1321
1364
  adjustSearchParams(search);
1322
1365
  }
1323
- search.set("key", config.apiKey);
1366
+ search.set("key", apiKey ?? config.apiKey);
1324
1367
  }
1325
- function decodeLegGeometry(leg) {
1326
- if (typeof leg.geometry === "string") {
1327
- return decode(leg.geometry, 6).map(([lat, lon]) => [lon, lat]);
1368
+ function decodeLegGeometry(geometry) {
1369
+ if (typeof geometry === "string") {
1370
+ return decode(geometry, POLYLINE_PRECISION).map(([lat, lon]) => [lon, lat]);
1328
1371
  }
1329
- return leg.geometry;
1372
+ return geometry;
1373
+ }
1374
+ function decodeRoute(route) {
1375
+ return {
1376
+ ...route,
1377
+ legs: route.legs.map((leg) => ({
1378
+ ...leg,
1379
+ geometry: decodeLegGeometry(leg.geometry)
1380
+ }))
1381
+ };
1382
+ }
1383
+ async function getErrorMessage(res) {
1384
+ let payload = null;
1385
+ try {
1386
+ payload = await res.json();
1387
+ } catch {
1388
+ return "";
1389
+ }
1390
+ return typeof payload?.message === "string" ? payload.message : "";
1330
1391
  }
1331
1392
  async function processDirectionsResponse(res) {
1332
1393
  if (!res.ok) {
1333
- throw new ServiceError(res);
1394
+ throw new ServiceError(res, await getErrorMessage(res));
1334
1395
  }
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
- }
1396
+ const { route, alternates, ...rest } = await res.json();
1397
+ const response = { ...rest, route: decodeRoute(route) };
1398
+ if (alternates) {
1399
+ response.alternates = alternates.map(decodeRoute);
1345
1400
  }
1346
1401
  return response;
1347
1402
  }
1348
1403
  async function directionsPost(body, options = {}) {
1349
1404
  const { fetchExtras } = options;
1350
- const url = new URL("routing/v1/directions", defaults.maptilerApiURL);
1405
+ const url = new URL("routing/v1/directions", config.apiURL);
1351
1406
  addRoutingOptions(url.searchParams, options);
1352
1407
  const headers = new Headers(fetchExtras?.headers);
1353
1408
  headers.set("content-type", "application/json");
@@ -1361,15 +1416,16 @@ async function directionsPost(body, options = {}) {
1361
1416
  }
1362
1417
  async function directionsGet(req, options = {}) {
1363
1418
  const { fetchExtras } = options;
1364
- const url = new URL("routing/v1/directions", defaults.maptilerApiURL);
1419
+ const url = new URL("routing/v1/directions", config.apiURL);
1365
1420
  const search = url.searchParams;
1366
1421
  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);
1422
+ if (req.id !== void 0) search.set("id", req.id);
1423
+ if (req.departureTime !== void 0)
1424
+ search.set("departureTime", req.departureTime);
1425
+ if (req.arrivalTime !== void 0) search.set("arrivalTime", req.arrivalTime);
1370
1426
  addLocations(search, req.locations);
1371
1427
  addResponseOptions(search, req.response);
1372
- addProfileOptions(search, req.profile, req.profileOptions);
1428
+ addProfileOptions(search, req);
1373
1429
  addRoutingOptions(search, options);
1374
1430
  const res = await callFetch(url.toString(), {
1375
1431
  ...fetchExtras,
@@ -1396,10 +1452,7 @@ async function search(query, options = {}) {
1396
1452
  if (typeof query !== "string" || query.trim().length === 0) {
1397
1453
  throw new Error("The query must be a non-empty string");
1398
1454
  }
1399
- const endpoint = new URL(
1400
- `coordinates/search/${query}.json`,
1401
- defaults.maptilerApiURL
1402
- );
1455
+ const endpoint = new URL(`coordinates/search/${query}.json`, config.apiURL);
1403
1456
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1404
1457
  if ("limit" in options) {
1405
1458
  endpoint.searchParams.set("limit", options.limit.toString());
@@ -1428,7 +1481,7 @@ async function transform(positions, options = {}) {
1428
1481
  const coordinatesStr = (Array.isArray(positions[0]) ? positions : [positions]).map((coord) => `${coord[0]},${coord[1]}`).join(";");
1429
1482
  const endpoint = new URL(
1430
1483
  `coordinates/transform/${coordinatesStr}.json`,
1431
- defaults.maptilerApiURL
1484
+ config.apiURL
1432
1485
  );
1433
1486
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1434
1487
  if ("sourceCrs" in options) {
@@ -1468,7 +1521,7 @@ async function get(dataId, options = {}) {
1468
1521
  }
1469
1522
  const endpoint = new URL(
1470
1523
  `data/${encodeURIComponent(dataId)}/features.json`,
1471
- defaults.maptilerApiURL
1524
+ config.apiURL
1472
1525
  );
1473
1526
  endpoint.searchParams.set("key", options.apiKey ?? config.apiKey);
1474
1527
  const urlWithParams = endpoint.toString();
@@ -1494,9 +1547,9 @@ function expandMapStyle(style) {
1494
1547
  if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
1495
1548
  expandedStyle = trimmed;
1496
1549
  } else if ((match = maptilerDomainRegex.exec(trimmed)) !== null) {
1497
- expandedStyle = `https://api.maptiler.com/maps/${match[1]}/style.json`;
1550
+ expandedStyle = `${config.apiURL}maps/${match[1]}/style.json`;
1498
1551
  } else {
1499
- expandedStyle = `https://api.maptiler.com/maps/${trimmed}/style.json`;
1552
+ expandedStyle = `${config.apiURL}maps/${trimmed}/style.json`;
1500
1553
  }
1501
1554
  return expandedStyle;
1502
1555
  }
@@ -2718,7 +2771,7 @@ function centered(center, zoom, options = {}) {
2718
2771
  }
2719
2772
  const endpoint = new URL(
2720
2773
  `maps/${encodeURIComponent(style)}/static/${center[0]},${center[1]},${zoom}/${width}x${height}${scale}.${format}`,
2721
- defaults.maptilerApiURL
2774
+ config.apiURL
2722
2775
  );
2723
2776
  if ("attribution" in options) {
2724
2777
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2767,7 +2820,7 @@ function bounded(boundingBox, options = {}) {
2767
2820
  }
2768
2821
  const endpoint = new URL(
2769
2822
  `maps/${encodeURIComponent(style)}/static/${boundingBox[0]},${boundingBox[1]},${boundingBox[2]},${boundingBox[3]}/${width}x${height}${scale}.${format}`,
2770
- defaults.maptilerApiURL
2823
+ config.apiURL
2771
2824
  );
2772
2825
  if ("attribution" in options) {
2773
2826
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -2826,7 +2879,7 @@ function automatic(options = {}) {
2826
2879
  `maps/${encodeURIComponent(
2827
2880
  style
2828
2881
  )}/static/auto/${width}x${height}${scale}.${format}`,
2829
- defaults.maptilerApiURL
2882
+ config.apiURL
2830
2883
  );
2831
2884
  if ("attribution" in options) {
2832
2885
  endpoint.searchParams.set("attribution", options.attribution.toString());
@@ -3023,6 +3076,7 @@ const TERRAIN_TILESET = "terrain-rgb-v2";
3023
3076
  const API_BATCH_SIZE = 50;
3024
3077
  const API_WARN_SIZE = 1e3;
3025
3078
  let terrainTileJson = null;
3079
+ let terrainTileJsonHost = null;
3026
3080
  const customMessages = {
3027
3081
  403: "Key is missing, invalid or restricted"
3028
3082
  };
@@ -3038,10 +3092,7 @@ async function computeOnServer(positions, apiKey) {
3038
3092
  const startPos = part * API_BATCH_SIZE;
3039
3093
  const batch2 = positions.slice(startPos, startPos + API_BATCH_SIZE);
3040
3094
  const batchEncoded = batch2.map((pos) => pos.join(",")).join(";");
3041
- const endpoint = new URL(
3042
- `elevation/${batchEncoded}.json`,
3043
- defaults.maptilerApiURL
3044
- );
3095
+ const endpoint = new URL(`elevation/${batchEncoded}.json`, config.apiURL);
3045
3096
  endpoint.searchParams.set("key", apiKey);
3046
3097
  return callFetch(endpoint.toString());
3047
3098
  }
@@ -3065,16 +3116,17 @@ async function computeOnServer(positions, apiKey) {
3065
3116
  return jsons.flat();
3066
3117
  }
3067
3118
  async function computeOnClient(positions, apiKey, zoom) {
3068
- if (!terrainTileJson) {
3119
+ if (!terrainTileJson || terrainTileJsonHost !== config.apiHost) {
3069
3120
  const endpoint = new URL(
3070
3121
  `tiles/${TERRAIN_TILESET}/tiles.json`,
3071
- defaults.maptilerApiURL
3122
+ config.apiURL
3072
3123
  );
3073
3124
  endpoint.searchParams.set("key", apiKey);
3074
3125
  const urlWithParams = endpoint.toString();
3075
3126
  const res = await callFetch(urlWithParams);
3076
3127
  if (res.ok) {
3077
3128
  terrainTileJson = await res.json();
3129
+ terrainTileJsonHost = config.apiHost;
3078
3130
  } else {
3079
3131
  throw new ServiceError(res, customMessages[res.status] ?? "");
3080
3132
  }