@carto/api-client 0.5.0-alpha.7 → 0.5.0-alpha.9

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,2063 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __commonJS = (cb, mod2) => function __require() {
9
- return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
25
- mod2
26
- ));
27
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
-
29
- // node_modules/tilebelt/index.js
30
- var require_tilebelt = __commonJS({
31
- "node_modules/tilebelt/index.js"(exports, module) {
32
- "use strict";
33
- var d2r = Math.PI / 180;
34
- var r2d = 180 / Math.PI;
35
- function tileToBBOX(tile) {
36
- var e = tile2lon(tile[0] + 1, tile[2]);
37
- var w = tile2lon(tile[0], tile[2]);
38
- var s = tile2lat(tile[1] + 1, tile[2]);
39
- var n = tile2lat(tile[1], tile[2]);
40
- return [w, s, e, n];
41
- }
42
- function tileToGeoJSON(tile) {
43
- var bbox = tileToBBOX(tile);
44
- var poly = {
45
- type: "Polygon",
46
- coordinates: [
47
- [
48
- [bbox[0], bbox[1]],
49
- [bbox[0], bbox[3]],
50
- [bbox[2], bbox[3]],
51
- [bbox[2], bbox[1]],
52
- [bbox[0], bbox[1]]
53
- ]
54
- ]
55
- };
56
- return poly;
57
- }
58
- function tile2lon(x, z) {
59
- return x / Math.pow(2, z) * 360 - 180;
60
- }
61
- function tile2lat(y, z) {
62
- var n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
63
- return r2d * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
64
- }
65
- function pointToTile(lon, lat, z) {
66
- var tile = pointToTileFraction(lon, lat, z);
67
- tile[0] = Math.floor(tile[0]);
68
- tile[1] = Math.floor(tile[1]);
69
- return tile;
70
- }
71
- function getChildren(tile) {
72
- return [
73
- [tile[0] * 2, tile[1] * 2, tile[2] + 1],
74
- [tile[0] * 2 + 1, tile[1] * 2, tile[2] + 1],
75
- [tile[0] * 2 + 1, tile[1] * 2 + 1, tile[2] + 1],
76
- [tile[0] * 2, tile[1] * 2 + 1, tile[2] + 1]
77
- ];
78
- }
79
- function getParent(tile) {
80
- if (tile[0] % 2 === 0 && tile[1] % 2 === 0) {
81
- return [tile[0] / 2, tile[1] / 2, tile[2] - 1];
82
- } else if (tile[0] % 2 === 0 && !tile[1] % 2 === 0) {
83
- return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1];
84
- } else if (!tile[0] % 2 === 0 && tile[1] % 2 === 0) {
85
- return [(tile[0] - 1) / 2, tile[1] / 2, tile[2] - 1];
86
- } else {
87
- return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1];
88
- }
89
- }
90
- function getSiblings(tile) {
91
- return getChildren(getParent(tile));
92
- }
93
- function hasSiblings(tile, tiles2) {
94
- var siblings = getSiblings(tile);
95
- for (var i = 0; i < siblings.length; i++) {
96
- if (!hasTile(tiles2, siblings[i])) return false;
97
- }
98
- return true;
99
- }
100
- function hasTile(tiles2, tile) {
101
- for (var i = 0; i < tiles2.length; i++) {
102
- if (tilesEqual(tiles2[i], tile)) return true;
103
- }
104
- return false;
105
- }
106
- function tilesEqual(tile1, tile2) {
107
- return tile1[0] === tile2[0] && tile1[1] === tile2[1] && tile1[2] === tile2[2];
108
- }
109
- function tileToQuadkey(tile) {
110
- var index = "";
111
- for (var z = tile[2]; z > 0; z--) {
112
- var b = 0;
113
- var mask = 1 << z - 1;
114
- if ((tile[0] & mask) !== 0) b++;
115
- if ((tile[1] & mask) !== 0) b += 2;
116
- index += b.toString();
117
- }
118
- return index;
119
- }
120
- function quadkeyToTile(quadkey) {
121
- var x = 0;
122
- var y = 0;
123
- var z = quadkey.length;
124
- for (var i = z; i > 0; i--) {
125
- var mask = 1 << i - 1;
126
- switch (quadkey[z - i]) {
127
- case "0":
128
- break;
129
- case "1":
130
- x |= mask;
131
- break;
132
- case "2":
133
- y |= mask;
134
- break;
135
- case "3":
136
- x |= mask;
137
- y |= mask;
138
- break;
139
- }
140
- }
141
- return [x, y, z];
142
- }
143
- function bboxToTile(bboxCoords) {
144
- var min2 = pointToTile(bboxCoords[0], bboxCoords[1], 32);
145
- var max2 = pointToTile(bboxCoords[2], bboxCoords[3], 32);
146
- var bbox = [min2[0], min2[1], max2[0], max2[1]];
147
- var z = getBboxZoom(bbox);
148
- if (z === 0) return [0, 0, 0];
149
- var x = bbox[0] >>> 32 - z;
150
- var y = bbox[1] >>> 32 - z;
151
- return [x, y, z];
152
- }
153
- function getBboxZoom(bbox) {
154
- var MAX_ZOOM = 28;
155
- for (var z = 0; z < MAX_ZOOM; z++) {
156
- var mask = 1 << 32 - (z + 1);
157
- if ((bbox[0] & mask) != (bbox[2] & mask) || (bbox[1] & mask) != (bbox[3] & mask)) {
158
- return z;
159
- }
160
- }
161
- return MAX_ZOOM;
162
- }
163
- function pointToTileFraction(lon, lat, z) {
164
- var sin2 = Math.sin(lat * d2r), z2 = Math.pow(2, z), x = z2 * (lon / 360 + 0.5), y = z2 * (0.5 - 0.25 * Math.log((1 + sin2) / (1 - sin2)) / Math.PI);
165
- return [x, y, z];
166
- }
167
- module.exports = {
168
- tileToGeoJSON,
169
- tileToBBOX,
170
- getChildren,
171
- getParent,
172
- getSiblings,
173
- hasTile,
174
- hasSiblings,
175
- tilesEqual,
176
- tileToQuadkey,
177
- quadkeyToTile,
178
- pointToTile,
179
- bboxToTile,
180
- pointToTileFraction
181
- };
182
- }
183
- });
184
-
185
- // node_modules/@mapbox/tile-cover/index.js
186
- var require_tile_cover = __commonJS({
187
- "node_modules/@mapbox/tile-cover/index.js"(exports) {
188
- "use strict";
189
- var tilebelt = require_tilebelt();
190
- exports.geojson = function(geom, limits) {
191
- return {
192
- type: "FeatureCollection",
193
- features: getTiles(geom, limits).map(tileToFeature)
194
- };
195
- };
196
- function tileToFeature(t) {
197
- return {
198
- type: "Feature",
199
- geometry: tilebelt.tileToGeoJSON(t),
200
- properties: {}
201
- };
202
- }
203
- exports.tiles = getTiles;
204
- exports.indexes = function(geom, limits) {
205
- return getTiles(geom, limits).map(tilebelt.tileToQuadkey);
206
- };
207
- function getTiles(geom, limits) {
208
- var i, tile, coords = geom.coordinates, maxZoom = limits.max_zoom, tileHash = {}, tiles2 = [];
209
- if (geom.type === "Point") {
210
- return [tilebelt.pointToTile(coords[0], coords[1], maxZoom)];
211
- } else if (geom.type === "MultiPoint") {
212
- for (i = 0; i < coords.length; i++) {
213
- tile = tilebelt.pointToTile(coords[i][0], coords[i][1], maxZoom);
214
- tileHash[toID(tile[0], tile[1], tile[2])] = true;
215
- }
216
- } else if (geom.type === "LineString") {
217
- lineCover(tileHash, coords, maxZoom);
218
- } else if (geom.type === "MultiLineString") {
219
- for (i = 0; i < coords.length; i++) {
220
- lineCover(tileHash, coords[i], maxZoom);
221
- }
222
- } else if (geom.type === "Polygon") {
223
- polygonCover(tileHash, tiles2, coords, maxZoom);
224
- } else if (geom.type === "MultiPolygon") {
225
- for (i = 0; i < coords.length; i++) {
226
- polygonCover(tileHash, tiles2, coords[i], maxZoom);
227
- }
228
- } else {
229
- throw new Error("Geometry type not implemented");
230
- }
231
- if (limits.min_zoom !== maxZoom) {
232
- var len = tiles2.length;
233
- appendHashTiles(tileHash, tiles2);
234
- for (i = 0; i < len; i++) {
235
- var t = tiles2[i];
236
- tileHash[toID(t[0], t[1], t[2])] = true;
237
- }
238
- return mergeTiles(tileHash, tiles2, limits);
239
- }
240
- appendHashTiles(tileHash, tiles2);
241
- return tiles2;
242
- }
243
- function mergeTiles(tileHash, tiles2, limits) {
244
- var mergedTiles = [];
245
- for (var z = limits.max_zoom; z > limits.min_zoom; z--) {
246
- var parentTileHash = {};
247
- var parentTiles = [];
248
- for (var i = 0; i < tiles2.length; i++) {
249
- var t = tiles2[i];
250
- if (t[0] % 2 === 0 && t[1] % 2 === 0) {
251
- var id2 = toID(t[0] + 1, t[1], z), id3 = toID(t[0], t[1] + 1, z), id4 = toID(t[0] + 1, t[1] + 1, z);
252
- if (tileHash[id2] && tileHash[id3] && tileHash[id4]) {
253
- tileHash[toID(t[0], t[1], t[2])] = false;
254
- tileHash[id2] = false;
255
- tileHash[id3] = false;
256
- tileHash[id4] = false;
257
- var parentTile = [t[0] / 2, t[1] / 2, z - 1];
258
- if (z - 1 === limits.min_zoom) mergedTiles.push(parentTile);
259
- else {
260
- parentTileHash[toID(t[0] / 2, t[1] / 2, z - 1)] = true;
261
- parentTiles.push(parentTile);
262
- }
263
- }
264
- }
265
- }
266
- for (i = 0; i < tiles2.length; i++) {
267
- t = tiles2[i];
268
- if (tileHash[toID(t[0], t[1], t[2])]) mergedTiles.push(t);
269
- }
270
- tileHash = parentTileHash;
271
- tiles2 = parentTiles;
272
- }
273
- return mergedTiles;
274
- }
275
- function polygonCover(tileHash, tileArray, geom, zoom) {
276
- var intersections = [];
277
- for (var i = 0; i < geom.length; i++) {
278
- var ring = [];
279
- lineCover(tileHash, geom[i], zoom, ring);
280
- for (var j = 0, len = ring.length, k = len - 1; j < len; k = j++) {
281
- var m = (j + 1) % len;
282
- var y = ring[j][1];
283
- if ((y > ring[k][1] || y > ring[m][1]) && // not local minimum
284
- (y < ring[k][1] || y < ring[m][1]) && // not local maximum
285
- y !== ring[m][1]) intersections.push(ring[j]);
286
- }
287
- }
288
- intersections.sort(compareTiles);
289
- for (i = 0; i < intersections.length; i += 2) {
290
- y = intersections[i][1];
291
- for (var x = intersections[i][0] + 1; x < intersections[i + 1][0]; x++) {
292
- var id = toID(x, y, zoom);
293
- if (!tileHash[id]) {
294
- tileArray.push([x, y, zoom]);
295
- }
296
- }
297
- }
298
- }
299
- function compareTiles(a, b) {
300
- return a[1] - b[1] || a[0] - b[0];
301
- }
302
- function lineCover(tileHash, coords, maxZoom, ring) {
303
- var prevX, prevY;
304
- for (var i = 0; i < coords.length - 1; i++) {
305
- var start = tilebelt.pointToTileFraction(coords[i][0], coords[i][1], maxZoom), stop = tilebelt.pointToTileFraction(coords[i + 1][0], coords[i + 1][1], maxZoom), x0 = start[0], y0 = start[1], x1 = stop[0], y1 = stop[1], dx = x1 - x0, dy = y1 - y0;
306
- if (dy === 0 && dx === 0) continue;
307
- var sx = dx > 0 ? 1 : -1, sy = dy > 0 ? 1 : -1, x = Math.floor(x0), y = Math.floor(y0), tMaxX = dx === 0 ? Infinity : Math.abs(((dx > 0 ? 1 : 0) + x - x0) / dx), tMaxY = dy === 0 ? Infinity : Math.abs(((dy > 0 ? 1 : 0) + y - y0) / dy), tdx = Math.abs(sx / dx), tdy = Math.abs(sy / dy);
308
- if (x !== prevX || y !== prevY) {
309
- tileHash[toID(x, y, maxZoom)] = true;
310
- if (ring && y !== prevY) ring.push([x, y]);
311
- prevX = x;
312
- prevY = y;
313
- }
314
- while (tMaxX < 1 || tMaxY < 1) {
315
- if (tMaxX < tMaxY) {
316
- tMaxX += tdx;
317
- x += sx;
318
- } else {
319
- tMaxY += tdy;
320
- y += sy;
321
- }
322
- tileHash[toID(x, y, maxZoom)] = true;
323
- if (ring && y !== prevY) ring.push([x, y]);
324
- prevX = x;
325
- prevY = y;
326
- }
327
- }
328
- if (ring && y === ring[0][1]) ring.pop();
329
- }
330
- function appendHashTiles(hash, tiles2) {
331
- var keys = Object.keys(hash);
332
- for (var i = 0; i < keys.length; i++) {
333
- tiles2.push(fromID(+keys[i]));
334
- }
335
- }
336
- function toID(x, y, z) {
337
- var dim = 2 * (1 << z);
338
- return (dim * y + x) * 32 + z;
339
- }
340
- function fromID(id) {
341
- var z = id % 32, dim = 2 * (1 << z), xy = (id - z) / 32, x = xy % dim, y = (xy - x) / dim % dim;
342
- return [x, y, z];
343
- }
344
- }
345
- });
346
-
347
- // node_modules/thenby/thenBy.module.js
348
- var require_thenBy_module = __commonJS({
349
- "node_modules/thenby/thenBy.module.js"(exports, module) {
350
- "use strict";
351
- module.exports = function() {
352
- function identity(v) {
353
- return v;
354
- }
355
- function ignoreCase(v) {
356
- return typeof v === "string" ? v.toLowerCase() : v;
357
- }
358
- function makeCompareFunction(f, opt) {
359
- opt = typeof opt === "object" ? opt : { direction: opt };
360
- if (typeof f != "function") {
361
- var prop = f;
362
- f = function(v1) {
363
- return !!v1[prop] ? v1[prop] : "";
364
- };
365
- }
366
- if (f.length === 1) {
367
- var uf = f;
368
- var preprocess = opt.ignoreCase ? ignoreCase : identity;
369
- var cmp = opt.cmp || function(v1, v2) {
370
- return v1 < v2 ? -1 : v1 > v2 ? 1 : 0;
371
- };
372
- f = function(v1, v2) {
373
- return cmp(preprocess(uf(v1)), preprocess(uf(v2)));
374
- };
375
- }
376
- const descTokens = { "-1": "", desc: "" };
377
- if (opt.direction in descTokens) return function(v1, v2) {
378
- return -f(v1, v2);
379
- };
380
- return f;
381
- }
382
- function tb(func, opt) {
383
- var x = typeof this == "function" && !this.firstBy ? this : false;
384
- var y = makeCompareFunction(func, opt);
385
- var f = x ? function(a, b) {
386
- return x(a, b) || y(a, b);
387
- } : y;
388
- f.thenBy = tb;
389
- return f;
390
- }
391
- tb.firstBy = tb;
392
- return tb;
393
- }();
394
- }
395
- });
396
-
397
- // src/client.ts
398
- var client = "deck-gl-carto";
399
- function getClient() {
400
- return client;
401
- }
402
- function setClient(c) {
403
- client = c;
404
- }
405
-
406
- // src/constants.ts
407
- var FilterType = /* @__PURE__ */ ((FilterType2) => {
408
- FilterType2["IN"] = "in";
409
- FilterType2["BETWEEN"] = "between";
410
- FilterType2["CLOSED_OPEN"] = "closed_open";
411
- FilterType2["TIME"] = "time";
412
- FilterType2["STRING_SEARCH"] = "stringSearch";
413
- return FilterType2;
414
- })(FilterType || {});
415
- var ApiVersion = /* @__PURE__ */ ((ApiVersion2) => {
416
- ApiVersion2["V1"] = "v1";
417
- ApiVersion2["V2"] = "v2";
418
- ApiVersion2["V3"] = "v3";
419
- return ApiVersion2;
420
- })(ApiVersion || {});
421
- var DEFAULT_API_BASE_URL = "https://gcp-us-east1.api.carto.com";
422
- var TileFormat = /* @__PURE__ */ ((TileFormat2) => {
423
- TileFormat2["MVT"] = "mvt";
424
- TileFormat2["JSON"] = "json";
425
- TileFormat2["GEOJSON"] = "geojson";
426
- TileFormat2["BINARY"] = "binary";
427
- return TileFormat2;
428
- })(TileFormat || {});
429
- var SpatialIndex = /* @__PURE__ */ ((SpatialIndex2) => {
430
- SpatialIndex2["H3"] = "h3";
431
- SpatialIndex2["S2"] = "s2";
432
- SpatialIndex2["QUADBIN"] = "quadbin";
433
- return SpatialIndex2;
434
- })(SpatialIndex || {});
435
- var Provider = /* @__PURE__ */ ((Provider2) => {
436
- Provider2["BIGQUERY"] = "bigquery";
437
- Provider2["REDSHIFT"] = "redshift";
438
- Provider2["POSTGRES"] = "postgres";
439
- Provider2["SNOWFLAKE"] = "snowflake";
440
- Provider2["DATABRICKS"] = "databricks";
441
- Provider2["DATABRICKS_REST"] = "databricksRest";
442
- return Provider2;
443
- })(Provider || {});
444
-
445
- // src/utils/makeIntervalComplete.ts
446
- function makeIntervalComplete(intervals) {
447
- return intervals.map((val) => {
448
- if (val[0] === void 0 || val[0] === null) {
449
- return [Number.MIN_SAFE_INTEGER, val[1]];
450
- }
451
- if (val[1] === void 0 || val[1] === null) {
452
- return [val[0], Number.MAX_SAFE_INTEGER];
453
- }
454
- return val;
455
- });
456
- }
457
-
458
- // src/filters/FilterTypes.ts
459
- var filterFunctions = {
460
- ["in" /* IN */]: filterIn,
461
- ["between" /* BETWEEN */]: filterBetween,
462
- ["time" /* TIME */]: filterTime,
463
- ["closed_open" /* CLOSED_OPEN */]: filterClosedOpen,
464
- ["stringSearch" /* STRING_SEARCH */]: filterStringSearch
465
- };
466
- function filterIn(filterValues, featureValue) {
467
- return filterValues.includes(featureValue);
468
- }
469
- function filterBetween(filterValues, featureValue) {
470
- const checkRange = (range) => {
471
- const [lowerBound, upperBound] = range;
472
- return featureValue >= lowerBound && featureValue <= upperBound;
473
- };
474
- return makeIntervalComplete(filterValues).some(
475
- checkRange
476
- );
477
- }
478
- function filterTime(filterValues, featureValue) {
479
- const featureValueAsTimestamp = new Date(featureValue).getTime();
480
- if (isFinite(featureValueAsTimestamp)) {
481
- return filterBetween(filterValues, featureValueAsTimestamp);
482
- } else {
483
- throw new Error(`Column used to filter by time isn't well formatted.`);
484
- }
485
- }
486
- function filterClosedOpen(filterValues, featureValue) {
487
- const checkRange = (range) => {
488
- const [lowerBound, upperBound] = range;
489
- return featureValue >= lowerBound && featureValue < upperBound;
490
- };
491
- return makeIntervalComplete(filterValues).some(
492
- checkRange
493
- );
494
- }
495
- function filterStringSearch(filterValues, featureValue, params = {}) {
496
- const normalizedFeatureValue = normalize(featureValue, params);
497
- const stringRegExp = params.useRegExp ? filterValues : filterValues.map((filterValue) => {
498
- let stringRegExp2 = escapeRegExp(normalize(filterValue, params));
499
- if (params.mustStart) stringRegExp2 = `^${stringRegExp2}`;
500
- if (params.mustEnd) stringRegExp2 = `${stringRegExp2}$`;
501
- return stringRegExp2;
502
- });
503
- const regex = new RegExp(
504
- stringRegExp.join("|"),
505
- params.caseSensitive ? "g" : "gi"
506
- );
507
- return !!normalizedFeatureValue.match(regex);
508
- }
509
- var specialCharRegExp = /[.*+?^${}()|[\]\\]/g;
510
- var normalizeRegExp = /\p{Diacritic}/gu;
511
- function escapeRegExp(value) {
512
- return value.replace(specialCharRegExp, "\\$&");
513
- }
514
- function normalize(data, params) {
515
- let normalizedData = String(data);
516
- if (!params.keepSpecialCharacters)
517
- normalizedData = normalizedData.normalize("NFD").replace(normalizeRegExp, "");
518
- return normalizedData;
519
- }
520
-
521
- // src/filters/Filter.ts
522
- var LOGICAL_OPERATOR_METHODS = {
523
- and: "every",
524
- or: "some"
525
- };
526
- function passesFilter(columns, filters, feature, filtersLogicalOperator) {
527
- const method = LOGICAL_OPERATOR_METHODS[filtersLogicalOperator];
528
- return columns[method]((column) => {
529
- const columnFilters = filters[column];
530
- const columnFilterTypes = Object.keys(columnFilters);
531
- if (!feature || feature[column] === null || feature[column] === void 0) {
532
- return false;
533
- }
534
- return columnFilterTypes.every((filter) => {
535
- const filterFunction = filterFunctions[filter];
536
- if (!filterFunction) {
537
- throw new Error(`"${filter}" filter is not implemented.`);
538
- }
539
- return filterFunction(
540
- columnFilters[filter].values,
541
- feature[column],
542
- columnFilters[filter].params
543
- );
544
- });
545
- });
546
- }
547
- function _buildFeatureFilter({
548
- filters = {},
549
- type = "boolean",
550
- filtersLogicalOperator = "and"
551
- }) {
552
- const columns = Object.keys(filters);
553
- if (!columns.length) {
554
- return () => type === "number" ? 1 : true;
555
- }
556
- return (feature) => {
557
- const f = feature.properties || feature;
558
- const featurePassesFilter = passesFilter(
559
- columns,
560
- filters,
561
- f,
562
- filtersLogicalOperator
563
- );
564
- return type === "number" ? Number(featurePassesFilter) : featurePassesFilter;
565
- };
566
- }
567
- function applyFilters(features, filters, filtersLogicalOperator) {
568
- return Object.keys(filters).length ? features.filter(_buildFeatureFilter({ filters, filtersLogicalOperator })) : features;
569
- }
570
- function buildBinaryFeatureFilter({ filters = {} }) {
571
- const columns = Object.keys(filters);
572
- if (!columns.length) {
573
- return () => 1;
574
- }
575
- return (featureIdIdx, binaryData) => passesFilterUsingBinary(columns, filters, featureIdIdx, binaryData);
576
- }
577
- function getValueFromNumericProps(featureIdIdx, binaryData, { column }) {
578
- return binaryData.numericProps?.[column]?.value[featureIdIdx];
579
- }
580
- function getValueFromProperties(featureIdIdx, binaryData, { column }) {
581
- const propertyIdx = binaryData.featureIds.value[featureIdIdx];
582
- return binaryData.properties[propertyIdx]?.[column];
583
- }
584
- var GET_VALUE_BY_BINARY_PROP = {
585
- properties: getValueFromProperties,
586
- numericProps: getValueFromNumericProps
587
- };
588
- function getBinaryPropertyByFilterValues(filterValues) {
589
- return typeof filterValues.flat()[0] === "string" ? "properties" : "numericProps";
590
- }
591
- function getFeatureValue(featureIdIdx, binaryData, filter) {
592
- const { column, values } = filter;
593
- const binaryProp = getBinaryPropertyByFilterValues(values);
594
- const getFeatureValueFn = GET_VALUE_BY_BINARY_PROP[binaryProp];
595
- return getFeatureValueFn(featureIdIdx, binaryData, { column });
596
- }
597
- function passesFilterUsingBinary(columns, filters, featureIdIdx, binaryData) {
598
- return columns.every((column) => {
599
- const columnFilters = filters[column];
600
- return Object.entries(columnFilters).every(([type, { values }]) => {
601
- const filterFn = filterFunctions[type];
602
- if (!filterFn) {
603
- throw new Error(`"${type}" filter is not implemented.`);
604
- }
605
- if (!values) return 0;
606
- const featureValue = getFeatureValue(featureIdIdx, binaryData, {
607
- type,
608
- column,
609
- values
610
- });
611
- if (featureValue === void 0 || featureValue === null) return 0;
612
- return filterFn(values, featureValue);
613
- });
614
- });
615
- }
616
-
617
- // src/filters/geosjonFeatures.ts
618
- import intersects from "@turf/boolean-intersects";
619
- function geojsonFeatures({
620
- geojson,
621
- spatialFilter,
622
- uniqueIdProperty
623
- }) {
624
- let uniqueIdx = 0;
625
- const map = /* @__PURE__ */ new Map();
626
- if (!spatialFilter) {
627
- return [];
628
- }
629
- for (const feature of geojson.features) {
630
- const uniqueId = uniqueIdProperty ? feature.properties[uniqueIdProperty] : ++uniqueIdx;
631
- if (!map.has(uniqueId) && intersects(spatialFilter, feature)) {
632
- map.set(uniqueId, feature.properties);
633
- }
634
- }
635
- return Array.from(map.values());
636
- }
637
-
638
- // node_modules/@math.gl/core/dist/lib/common.js
639
- var RADIANS_TO_DEGREES = 1 / Math.PI * 180;
640
- var DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
641
- var DEFAULT_CONFIG = {
642
- EPSILON: 1e-12,
643
- debug: false,
644
- precision: 4,
645
- printTypes: false,
646
- printDegrees: false,
647
- printRowMajor: true,
648
- _cartographicRadians: false
649
- };
650
- globalThis.mathgl = globalThis.mathgl || { config: { ...DEFAULT_CONFIG } };
651
- var config = globalThis.mathgl.config;
652
- function isArray(value) {
653
- return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
654
- }
655
- function lerp(a, b, t) {
656
- if (isArray(a)) {
657
- return a.map((ai, i) => lerp(ai, b[i], t));
658
- }
659
- return t * b + (1 - t) * a;
660
- }
661
-
662
- // node_modules/@math.gl/web-mercator/dist/assert.js
663
- function assert(condition, message) {
664
- if (!condition) {
665
- throw new Error(message || "@math.gl/web-mercator: assertion failed.");
666
- }
667
- }
668
-
669
- // node_modules/@math.gl/web-mercator/dist/web-mercator-utils.js
670
- var PI = Math.PI;
671
- var PI_4 = PI / 4;
672
- var DEGREES_TO_RADIANS2 = PI / 180;
673
- var RADIANS_TO_DEGREES2 = 180 / PI;
674
- var TILE_SIZE = 512;
675
- function lngLatToWorld(lngLat) {
676
- const [lng, lat] = lngLat;
677
- assert(Number.isFinite(lng));
678
- assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, "invalid latitude");
679
- const lambda2 = lng * DEGREES_TO_RADIANS2;
680
- const phi2 = lat * DEGREES_TO_RADIANS2;
681
- const x = TILE_SIZE * (lambda2 + PI) / (2 * PI);
682
- const y = TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5))) / (2 * PI);
683
- return [x, y];
684
- }
685
- function worldToLngLat(xy) {
686
- const [x, y] = xy;
687
- const lambda2 = x / TILE_SIZE * (2 * PI) - PI;
688
- const phi2 = 2 * (Math.atan(Math.exp(y / TILE_SIZE * (2 * PI) - PI)) - PI_4);
689
- return [lambda2 * RADIANS_TO_DEGREES2, phi2 * RADIANS_TO_DEGREES2];
690
- }
691
-
692
- // node_modules/@math.gl/web-mercator/dist/get-bounds.js
693
- var DEGREES_TO_RADIANS3 = Math.PI / 180;
694
-
695
- // src/utils/transformToTileCoords.ts
696
- var TRANSFORM_FN = {
697
- Point: transformPoint,
698
- MultiPoint: transformMultiPoint,
699
- LineString: transformLineString,
700
- MultiLineString: transformMultiLineString,
701
- Polygon: transformPolygon,
702
- MultiPolygon: transformMultiPolygon
703
- };
704
- function transformToTileCoords(geometry, bbox) {
705
- const [west, south, east, north] = bbox;
706
- const nw = projectFlat([west, north]);
707
- const se = projectFlat([east, south]);
708
- const projectedBbox = [nw, se];
709
- if (geometry.type === "GeometryCollection") {
710
- throw new Error("Unsupported geometry type GeometryCollection");
711
- }
712
- const transformFn = TRANSFORM_FN[geometry.type];
713
- const coordinates = transformFn(geometry.coordinates, projectedBbox);
714
- return { ...geometry, coordinates };
715
- }
716
- function transformPoint([pointX, pointY], [nw, se]) {
717
- const x = inverseLerp(nw[0], se[0], pointX);
718
- const y = inverseLerp(nw[1], se[1], pointY);
719
- return [x, y];
720
- }
721
- function getPoints(geometry, bbox) {
722
- return geometry.map((g) => transformPoint(projectFlat(g), bbox));
723
- }
724
- function transformMultiPoint(multiPoint, bbox) {
725
- return getPoints(multiPoint, bbox);
726
- }
727
- function transformLineString(line, bbox) {
728
- return getPoints(line, bbox);
729
- }
730
- function transformMultiLineString(multiLineString, bbox) {
731
- return multiLineString.map(
732
- (lineString) => transformLineString(lineString, bbox)
733
- );
734
- }
735
- function transformPolygon(polygon, bbox) {
736
- return polygon.map((polygonRing) => getPoints(polygonRing, bbox));
737
- }
738
- function transformMultiPolygon(multiPolygon, bbox) {
739
- return multiPolygon.map((polygon) => transformPolygon(polygon, bbox));
740
- }
741
- function projectFlat(xyz) {
742
- return lngLatToWorld(xyz);
743
- }
744
- function inverseLerp(a, b, x) {
745
- return (x - a) / (b - a);
746
- }
747
-
748
- // src/filters/tileFeaturesGeometries.ts
749
- import bboxPolygon from "@turf/bbox-polygon";
750
- import intersects2 from "@turf/boolean-intersects";
751
- import booleanWithin from "@turf/boolean-within";
752
- import intersect from "@turf/intersect";
753
-
754
- // src/utils/transformTileCoordsToWGS84.ts
755
- var TRANSFORM_FN2 = {
756
- Point: transformPoint2,
757
- MultiPoint: transformMultiPoint2,
758
- LineString: transformLineString2,
759
- MultiLineString: transformMultiLineString2,
760
- Polygon: transformPolygon2,
761
- MultiPolygon: transformMultiPolygon2
762
- };
763
- function transformTileCoordsToWGS84(geometry, bbox) {
764
- const [west, south, east, north] = bbox;
765
- const nw = lngLatToWorld([west, north]);
766
- const se = lngLatToWorld([east, south]);
767
- const projectedBbox = [nw, se];
768
- if (geometry.type === "GeometryCollection") {
769
- throw new Error("Unsupported geometry type GeometryCollection");
770
- }
771
- const transformFn = TRANSFORM_FN2[geometry.type];
772
- const coordinates = transformFn(geometry.coordinates, projectedBbox);
773
- return { ...geometry, coordinates };
774
- }
775
- function transformPoint2([pointX, pointY], [nw, se]) {
776
- const x = lerp(nw[0], se[0], pointX);
777
- const y = lerp(nw[1], se[1], pointY);
778
- return worldToLngLat([x, y]);
779
- }
780
- function getPoints2(geometry, bbox) {
781
- return geometry.map((g) => transformPoint2(g, bbox));
782
- }
783
- function transformMultiPoint2(multiPoint, bbox) {
784
- return getPoints2(multiPoint, bbox);
785
- }
786
- function transformLineString2(line, bbox) {
787
- return getPoints2(line, bbox);
788
- }
789
- function transformMultiLineString2(multiLineString, bbox) {
790
- return multiLineString.map(
791
- (lineString) => transformLineString2(lineString, bbox)
792
- );
793
- }
794
- function transformPolygon2(polygon, bbox) {
795
- return polygon.map((polygonRing) => getPoints2(polygonRing, bbox));
796
- }
797
- function transformMultiPolygon2(multiPolygon, bbox) {
798
- return multiPolygon.map((polygon) => transformPolygon2(polygon, bbox));
799
- }
800
-
801
- // src/filters/tileFeaturesGeometries.ts
802
- import { featureCollection } from "@turf/helpers";
803
- var FEATURE_GEOM_PROPERTY = "__geomValue";
804
- function tileFeaturesGeometries({
805
- tiles: tiles2,
806
- tileFormat,
807
- spatialFilter,
808
- uniqueIdProperty,
809
- options
810
- }) {
811
- const map = /* @__PURE__ */ new Map();
812
- for (const tile of tiles2) {
813
- if (tile.isVisible === false || !tile.data) {
814
- continue;
815
- }
816
- const bbox = [
817
- tile.bbox.west,
818
- tile.bbox.south,
819
- tile.bbox.east,
820
- tile.bbox.north
821
- ];
822
- const bboxToGeom = bboxPolygon(bbox);
823
- const tileIsFullyVisible = booleanWithin(bboxToGeom, spatialFilter);
824
- const spatialFilterFeature = {
825
- type: "Feature",
826
- geometry: spatialFilter,
827
- properties: {}
828
- };
829
- const clippedGeometryToIntersect = intersect(
830
- featureCollection([bboxToGeom, spatialFilterFeature])
831
- );
832
- if (!clippedGeometryToIntersect) {
833
- continue;
834
- }
835
- const transformedGeometryToIntersect = tileFormat === "mvt" /* MVT */ ? transformToTileCoords(clippedGeometryToIntersect.geometry, bbox) : clippedGeometryToIntersect.geometry;
836
- createIndicesForPoints(tile.data.points);
837
- calculateFeatures({
838
- map,
839
- tileIsFullyVisible,
840
- geometryIntersection: transformedGeometryToIntersect,
841
- data: tile.data.points,
842
- type: "Point",
843
- bbox,
844
- tileFormat,
845
- uniqueIdProperty,
846
- options
847
- });
848
- calculateFeatures({
849
- map,
850
- tileIsFullyVisible,
851
- geometryIntersection: transformedGeometryToIntersect,
852
- data: tile.data.lines,
853
- type: "LineString",
854
- bbox,
855
- tileFormat,
856
- uniqueIdProperty,
857
- options
858
- });
859
- calculateFeatures({
860
- map,
861
- tileIsFullyVisible,
862
- geometryIntersection: transformedGeometryToIntersect,
863
- data: tile.data.polygons,
864
- type: "Polygon",
865
- bbox,
866
- tileFormat,
867
- uniqueIdProperty,
868
- options
869
- });
870
- }
871
- return Array.from(map.values());
872
- }
873
- function processTileFeatureProperties({
874
- map,
875
- data,
876
- startIndex,
877
- endIndex,
878
- type,
879
- bbox,
880
- tileFormat,
881
- uniqueIdProperty,
882
- storeGeometry,
883
- geometryIntersection
884
- }) {
885
- const tileProps = getPropertiesFromTile(data, startIndex);
886
- const uniquePropertyValue = getUniquePropertyValue(
887
- tileProps,
888
- uniqueIdProperty,
889
- map
890
- );
891
- if (!uniquePropertyValue || map.has(uniquePropertyValue)) {
892
- return;
893
- }
894
- let geometry = null;
895
- if (storeGeometry || geometryIntersection) {
896
- const { positions } = data;
897
- const ringCoordinates = getRingCoordinatesFor(
898
- startIndex,
899
- endIndex,
900
- positions
901
- );
902
- geometry = getFeatureByType(ringCoordinates, type);
903
- }
904
- if (geometry && geometryIntersection && !intersects2(geometry, geometryIntersection)) {
905
- return;
906
- }
907
- const properties = parseProperties(tileProps);
908
- if (storeGeometry && geometry) {
909
- properties[FEATURE_GEOM_PROPERTY] = tileFormat === "mvt" /* MVT */ ? transformTileCoordsToWGS84(geometry, bbox) : geometry;
910
- }
911
- map.set(uniquePropertyValue, properties);
912
- }
913
- function addIntersectedFeaturesInTile({
914
- map,
915
- data,
916
- geometryIntersection,
917
- type,
918
- bbox,
919
- tileFormat,
920
- uniqueIdProperty,
921
- options
922
- }) {
923
- const indices = getIndices(data);
924
- const storeGeometry = options?.storeGeometry || false;
925
- for (let i = 0; i < indices.length - 1; i++) {
926
- const startIndex = indices[i];
927
- const endIndex = indices[i + 1];
928
- processTileFeatureProperties({
929
- map,
930
- data,
931
- startIndex,
932
- endIndex,
933
- type,
934
- bbox,
935
- tileFormat,
936
- uniqueIdProperty,
937
- storeGeometry,
938
- geometryIntersection
939
- });
940
- }
941
- }
942
- function getIndices(data) {
943
- let indices;
944
- switch (data.type) {
945
- case "Point":
946
- indices = data.pointIndices;
947
- break;
948
- case "LineString":
949
- indices = data.pathIndices;
950
- break;
951
- case "Polygon":
952
- indices = data.primitivePolygonIndices;
953
- break;
954
- default:
955
- throw new Error(`Unexpected type, "${data.type}"`);
956
- }
957
- return indices.value;
958
- }
959
- function getFeatureId(data, startIndex) {
960
- return data.featureIds.value[startIndex];
961
- }
962
- function getPropertiesFromTile(data, startIndex) {
963
- const featureId = getFeatureId(data, startIndex);
964
- const { properties, numericProps, fields } = data;
965
- const result = {
966
- uniqueId: fields?.[featureId]?.id,
967
- properties: properties[featureId],
968
- numericProps: {}
969
- };
970
- for (const key in numericProps) {
971
- result.numericProps[key] = numericProps[key].value[startIndex];
972
- }
973
- return result;
974
- }
975
- function parseProperties(tileProps) {
976
- const { properties, numericProps } = tileProps;
977
- return Object.assign({}, properties, numericProps);
978
- }
979
- function getUniquePropertyValue(tileProps, uniqueIdProperty, map) {
980
- if (uniqueIdProperty) {
981
- return getValueFromTileProps(tileProps, uniqueIdProperty);
982
- }
983
- if (tileProps.uniqueId) {
984
- return tileProps.uniqueId;
985
- }
986
- const artificialId = map.size + 1;
987
- return getValueFromTileProps(tileProps, "cartodb_id") || getValueFromTileProps(tileProps, "geoid") || artificialId;
988
- }
989
- function getValueFromTileProps(tileProps, propertyName) {
990
- const { properties, numericProps } = tileProps;
991
- return numericProps[propertyName] || properties[propertyName];
992
- }
993
- function getFeatureByType(coordinates, type) {
994
- switch (type) {
995
- case "Polygon":
996
- return { type: "Polygon", coordinates: [coordinates] };
997
- case "LineString":
998
- return { type: "LineString", coordinates };
999
- case "Point":
1000
- return { type: "Point", coordinates: coordinates[0] };
1001
- default:
1002
- throw new Error("Invalid geometry type");
1003
- }
1004
- }
1005
- function getRingCoordinatesFor(startIndex, endIndex, positions) {
1006
- const ringCoordinates = [];
1007
- for (let j = startIndex; j < endIndex; j++) {
1008
- ringCoordinates.push(
1009
- Array.from(
1010
- positions.value.subarray(j * positions.size, (j + 1) * positions.size)
1011
- )
1012
- );
1013
- }
1014
- return ringCoordinates;
1015
- }
1016
- function calculateFeatures({
1017
- map,
1018
- tileIsFullyVisible,
1019
- geometryIntersection,
1020
- data,
1021
- type,
1022
- bbox,
1023
- tileFormat,
1024
- uniqueIdProperty,
1025
- options
1026
- }) {
1027
- if (!data?.properties.length) {
1028
- return;
1029
- }
1030
- if (tileIsFullyVisible) {
1031
- addAllFeaturesInTile({
1032
- map,
1033
- data,
1034
- type,
1035
- bbox,
1036
- tileFormat,
1037
- uniqueIdProperty,
1038
- options
1039
- });
1040
- } else {
1041
- addIntersectedFeaturesInTile({
1042
- map,
1043
- data,
1044
- geometryIntersection,
1045
- type,
1046
- bbox,
1047
- tileFormat,
1048
- uniqueIdProperty,
1049
- options
1050
- });
1051
- }
1052
- }
1053
- function addAllFeaturesInTile({
1054
- map,
1055
- data,
1056
- type,
1057
- bbox,
1058
- tileFormat,
1059
- uniqueIdProperty,
1060
- options
1061
- }) {
1062
- const indices = getIndices(data);
1063
- const storeGeometry = options?.storeGeometry || false;
1064
- for (let i = 0; i < indices.length - 1; i++) {
1065
- const startIndex = indices[i];
1066
- const endIndex = indices[i + 1];
1067
- processTileFeatureProperties({
1068
- map,
1069
- data,
1070
- startIndex,
1071
- endIndex,
1072
- type,
1073
- bbox,
1074
- tileFormat,
1075
- uniqueIdProperty,
1076
- storeGeometry
1077
- });
1078
- }
1079
- }
1080
- function createIndicesForPoints(data) {
1081
- const featureIds = data.featureIds.value;
1082
- const lastFeatureId = featureIds[featureIds.length - 1];
1083
- const PointIndicesArray = featureIds.constructor;
1084
- const pointIndices = {
1085
- value: new PointIndicesArray(featureIds.length + 1),
1086
- size: 1
1087
- };
1088
- pointIndices.value.set(featureIds);
1089
- pointIndices.value.set([lastFeatureId + 1], featureIds.length);
1090
- data.pointIndices = pointIndices;
1091
- }
1092
-
1093
- // node_modules/quadbin/dist/esm/index.js
1094
- var import_tile_cover = __toESM(require_tile_cover(), 1);
1095
- var B = [
1096
- 0x5555555555555555n,
1097
- 0x3333333333333333n,
1098
- 0x0f0f0f0f0f0f0f0fn,
1099
- 0x00ff00ff00ff00ffn,
1100
- 0x0000ffff0000ffffn,
1101
- 0x00000000ffffffffn
1102
- ];
1103
- var S = [0n, 1n, 2n, 4n, 8n, 16n];
1104
- function tileToCell(tile) {
1105
- if (tile.z < 0 || tile.z > 26) {
1106
- throw new Error("Wrong zoom");
1107
- }
1108
- const z = BigInt(tile.z);
1109
- let x = BigInt(tile.x) << 32n - z;
1110
- let y = BigInt(tile.y) << 32n - z;
1111
- for (let i = 0; i < 5; i++) {
1112
- const s = S[5 - i];
1113
- const b = B[4 - i];
1114
- x = (x | x << s) & b;
1115
- y = (y | y << s) & b;
1116
- }
1117
- const quadbin = 0x4000000000000000n | 1n << 59n | // | (mode << 59) | (mode_dep << 57)
1118
- z << 52n | (x | y << 1n) >> 12n | 0xfffffffffffffn >> z * 2n;
1119
- return quadbin;
1120
- }
1121
- function getResolution(quadbin) {
1122
- return quadbin >> 52n & 0x1fn;
1123
- }
1124
- function geometryToCells(geometry, resolution) {
1125
- const zoom = Number(resolution);
1126
- return (0, import_tile_cover.tiles)(geometry, {
1127
- min_zoom: zoom,
1128
- max_zoom: zoom
1129
- }).map(([x, y, z]) => tileToCell({ x, y, z }));
1130
- }
1131
-
1132
- // src/filters/tileFeaturesSpatialIndex.ts
1133
- import bboxClip from "@turf/bbox-clip";
1134
- import { getResolution as h3GetResolution, polygonToCells } from "h3-js";
1135
- function tileFeaturesSpatialIndex({
1136
- tiles: tiles2,
1137
- spatialFilter,
1138
- spatialDataColumn,
1139
- spatialDataType
1140
- }) {
1141
- const map = /* @__PURE__ */ new Map();
1142
- const spatialIndex = getSpatialIndex(spatialDataType);
1143
- const resolution = getResolution2(tiles2, spatialIndex);
1144
- const spatialIndexIDName = spatialDataColumn ? spatialDataColumn : spatialIndex;
1145
- if (!resolution) {
1146
- return [];
1147
- }
1148
- const cells = getCellsCoverGeometry(spatialFilter, spatialIndex, resolution);
1149
- if (!cells?.length) {
1150
- return [];
1151
- }
1152
- const cellsSet = new Set(cells);
1153
- for (const tile of tiles2) {
1154
- if (tile.isVisible === false || !tile.data) {
1155
- continue;
1156
- }
1157
- tile.data.forEach((d) => {
1158
- if (cellsSet.has(d.id)) {
1159
- map.set(d.id, { ...d.properties, [spatialIndexIDName]: d.id });
1160
- }
1161
- });
1162
- }
1163
- return Array.from(map.values());
1164
- }
1165
- function getResolution2(tiles2, spatialIndex) {
1166
- const data = tiles2.find((tile) => tile.data?.length)?.data;
1167
- if (!data) {
1168
- return;
1169
- }
1170
- if (spatialIndex === "quadbin" /* QUADBIN */) {
1171
- return Number(getResolution(data[0].id));
1172
- }
1173
- if (spatialIndex === "h3" /* H3 */) {
1174
- return h3GetResolution(data[0].id);
1175
- }
1176
- }
1177
- var bboxWest = [-180, -90, 0, 90];
1178
- var bboxEast = [0, -90, 180, 90];
1179
- function getCellsCoverGeometry(geometry, spatialIndex, resolution) {
1180
- if (spatialIndex === "quadbin" /* QUADBIN */) {
1181
- return geometryToCells(geometry, resolution);
1182
- }
1183
- if (spatialIndex === "h3" /* H3 */) {
1184
- return polygonToCells(
1185
- bboxClip(geometry, bboxWest).geometry.coordinates,
1186
- resolution,
1187
- true
1188
- ).concat(
1189
- polygonToCells(
1190
- bboxClip(geometry, bboxEast).geometry.coordinates,
1191
- resolution,
1192
- true
1193
- )
1194
- );
1195
- }
1196
- }
1197
- function getSpatialIndex(spatialDataType) {
1198
- switch (spatialDataType) {
1199
- case "h3":
1200
- return "h3" /* H3 */;
1201
- case "quadbin":
1202
- return "quadbin" /* QUADBIN */;
1203
- default:
1204
- throw new Error("Unexpected spatial data type");
1205
- }
1206
- }
1207
-
1208
- // src/constants-internal.ts
1209
- var V3_MINOR_VERSION = "3.4";
1210
- var DEFAULT_GEO_COLUMN = "geom";
1211
- var DEFAULT_MAX_LENGTH_URL = 7e3;
1212
- var DEFAULT_TILE_RESOLUTION = 0.5;
1213
- var DEFAULT_AGGREGATION_RES_LEVEL_H3 = 4;
1214
- var DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN = 6;
1215
-
1216
- // src/filters/tileFeatures.ts
1217
- function tileFeatures({
1218
- tiles: tiles2,
1219
- spatialFilter,
1220
- uniqueIdProperty,
1221
- tileFormat,
1222
- spatialDataColumn = DEFAULT_GEO_COLUMN,
1223
- spatialDataType,
1224
- options = {}
1225
- }) {
1226
- if (spatialDataType !== "geo") {
1227
- return tileFeaturesSpatialIndex({
1228
- tiles: tiles2,
1229
- spatialFilter,
1230
- spatialDataColumn,
1231
- spatialDataType
1232
- });
1233
- }
1234
- return tileFeaturesGeometries({
1235
- tiles: tiles2,
1236
- tileFormat,
1237
- spatialFilter,
1238
- uniqueIdProperty,
1239
- options
1240
- });
1241
- }
1242
-
1243
- // src/spatial-index.ts
1244
- var DEFAULT_TILE_SIZE = 512;
1245
- var QUADBIN_ZOOM_MAX_OFFSET = 4;
1246
- function getSpatialFiltersResolution(source, viewState) {
1247
- const dataResolution = source.dataResolution ?? Number.MAX_VALUE;
1248
- const aggregationResLevel = source.aggregationResLevel ?? (source.spatialDataType === "h3" ? DEFAULT_AGGREGATION_RES_LEVEL_H3 : DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN);
1249
- const aggregationResLevelOffset = Math.max(
1250
- 0,
1251
- Math.floor(aggregationResLevel)
1252
- );
1253
- const currentZoomInt = Math.ceil(viewState.zoom);
1254
- if (source.spatialDataType === "h3") {
1255
- const tileSize = DEFAULT_TILE_SIZE;
1256
- const maxResolutionForZoom = maxH3SpatialFiltersResolutions.find(
1257
- ([zoom]) => zoom === currentZoomInt
1258
- )?.[1] ?? Math.max(0, currentZoomInt - 3);
1259
- const maxSpatialFiltersResolution = maxResolutionForZoom ? Math.min(dataResolution, maxResolutionForZoom) : dataResolution;
1260
- const hexagonResolution = _getHexagonResolution(viewState, tileSize) + aggregationResLevelOffset;
1261
- return Math.min(hexagonResolution, maxSpatialFiltersResolution);
1262
- }
1263
- if (source.spatialDataType === "quadbin") {
1264
- const maxResolutionForZoom = currentZoomInt + QUADBIN_ZOOM_MAX_OFFSET;
1265
- const maxSpatialFiltersResolution = Math.min(
1266
- dataResolution,
1267
- maxResolutionForZoom
1268
- );
1269
- const quadsResolution = Math.floor(viewState.zoom) + aggregationResLevelOffset;
1270
- return Math.min(quadsResolution, maxSpatialFiltersResolution);
1271
- }
1272
- return void 0;
1273
- }
1274
- var maxH3SpatialFiltersResolutions = [
1275
- [20, 14],
1276
- [19, 13],
1277
- [18, 12],
1278
- [17, 11],
1279
- [16, 10],
1280
- [15, 9],
1281
- [14, 8],
1282
- [13, 7],
1283
- [12, 7],
1284
- [11, 7],
1285
- [10, 6],
1286
- [9, 6],
1287
- [8, 5],
1288
- [7, 4],
1289
- [6, 4],
1290
- [5, 3],
1291
- [4, 2],
1292
- [3, 1],
1293
- [2, 1],
1294
- [1, 0]
1295
- ];
1296
- var BIAS = 2;
1297
- function _getHexagonResolution(viewport, tileSize) {
1298
- const zoomOffset = Math.log2(tileSize / DEFAULT_TILE_SIZE);
1299
- const hexagonScaleFactor = 2 / 3 * (viewport.zoom - zoomOffset);
1300
- const latitudeScaleFactor = Math.log(
1301
- 1 / Math.cos(Math.PI * viewport.latitude / 180)
1302
- );
1303
- return Math.max(
1304
- 0,
1305
- Math.floor(hexagonScaleFactor + latitudeScaleFactor - BIAS)
1306
- );
1307
- }
1308
-
1309
- // src/widget-sources/widget-source.ts
1310
- var _WidgetSource = class _WidgetSource {
1311
- constructor(props) {
1312
- __publicField(this, "props");
1313
- this.props = { ..._WidgetSource.defaultProps, ...props };
1314
- }
1315
- _getSpatialFiltersResolution(source, spatialFilter, referenceViewState) {
1316
- if (!spatialFilter || source.spatialDataType === "geo") {
1317
- return;
1318
- }
1319
- if (!referenceViewState) {
1320
- throw new Error(
1321
- 'Missing required option, "spatialIndexReferenceViewState".'
1322
- );
1323
- }
1324
- return getSpatialFiltersResolution(source, referenceViewState);
1325
- }
1326
- };
1327
- __publicField(_WidgetSource, "defaultProps", {
1328
- apiVersion: "v3" /* V3 */,
1329
- apiBaseUrl: DEFAULT_API_BASE_URL,
1330
- clientId: getClient(),
1331
- filters: {},
1332
- filtersLogicalOperator: "and"
1333
- });
1334
- var WidgetSource = _WidgetSource;
1335
-
1336
- // src/operations/aggregation.ts
1337
- var aggregationFunctions = {
1338
- count: (values) => values.length,
1339
- min: (...args) => applyAggregationFunction(min, ...args),
1340
- max: (...args) => applyAggregationFunction(max, ...args),
1341
- sum: (...args) => applyAggregationFunction(sum, ...args),
1342
- avg: (...args) => applyAggregationFunction(avg, ...args)
1343
- };
1344
- function aggregate(feature, keys, operation) {
1345
- if (!keys?.length) {
1346
- throw new Error("Cannot aggregate a feature without having keys");
1347
- } else if (keys.length === 1) {
1348
- const value = feature[keys[0]];
1349
- return isPotentiallyValidNumber(value) ? Number(value) : value;
1350
- }
1351
- const aggregationFn = aggregationFunctions[operation];
1352
- if (!aggregationFn) {
1353
- throw new Error(`${operation} isn't a valid aggregation function`);
1354
- }
1355
- return aggregationFn(
1356
- keys.map((column) => {
1357
- const value = feature[column];
1358
- return isPotentiallyValidNumber(value) ? Number(value) : value;
1359
- })
1360
- );
1361
- }
1362
- function isPotentiallyValidNumber(value) {
1363
- return typeof value === "string" && value.trim().length > 0;
1364
- }
1365
- var applyAggregationFunction = (aggFn, values, keys, operation) => {
1366
- const normalizedKeys = normalizeKeys(keys);
1367
- const elements = (normalizedKeys?.length || 0) <= 1 ? filterFalsyElements(values, normalizedKeys || []) : values;
1368
- return aggFn(elements, keys, operation);
1369
- };
1370
- function filterFalsyElements(values, keys) {
1371
- const filterFn = (value) => value !== null && value !== void 0;
1372
- if (!keys?.length) {
1373
- return values.filter(filterFn);
1374
- }
1375
- return values.filter((v) => filterFn(v[keys[0]]));
1376
- }
1377
- function avg(values, keys, joinOperation) {
1378
- return sum(values, keys, joinOperation) / (values.length || 1);
1379
- }
1380
- function sum(values, keys, joinOperation) {
1381
- const normalizedKeys = normalizeKeys(keys);
1382
- if (normalizedKeys) {
1383
- return values.reduce(
1384
- (a, b) => a + aggregate(b, normalizedKeys, joinOperation),
1385
- 0
1386
- );
1387
- }
1388
- return values.reduce((a, b) => a + b, 0);
1389
- }
1390
- function min(values, keys, joinOperation) {
1391
- const normalizedKeys = normalizeKeys(keys);
1392
- if (normalizedKeys) {
1393
- return values.reduce(
1394
- (a, b) => Math.min(a, aggregate(b, normalizedKeys, joinOperation)),
1395
- Infinity
1396
- );
1397
- }
1398
- return Math.min(...values);
1399
- }
1400
- function max(values, keys, joinOperation) {
1401
- const normalizedKeys = normalizeKeys(keys);
1402
- if (normalizedKeys) {
1403
- return values.reduce(
1404
- (a, b) => Math.max(a, aggregate(b, normalizedKeys, joinOperation)),
1405
- -Infinity
1406
- );
1407
- }
1408
- return Math.max(...values);
1409
- }
1410
- function normalizeKeys(keys) {
1411
- return Array.isArray(keys) ? keys : typeof keys === "string" ? [keys] : void 0;
1412
- }
1413
-
1414
- // src/operations/applySorting.ts
1415
- var import_thenby = __toESM(require_thenBy_module(), 1);
1416
- function applySorting(features, {
1417
- sortBy,
1418
- sortByDirection = "asc",
1419
- sortByColumnType = "string"
1420
- } = {}) {
1421
- if (sortBy === void 0) {
1422
- return features;
1423
- }
1424
- const isValidSortBy = Array.isArray(sortBy) && sortBy.length || // sortBy can be an array of columns
1425
- typeof sortBy === "string";
1426
- if (!isValidSortBy) {
1427
- throw new Error("Sorting options are bad formatted");
1428
- }
1429
- const sortFn = createSortFn({
1430
- sortBy,
1431
- sortByDirection,
1432
- sortByColumnType: sortByColumnType || "string"
1433
- });
1434
- return features.sort(sortFn);
1435
- }
1436
- function createSortFn({
1437
- sortBy,
1438
- sortByDirection,
1439
- sortByColumnType
1440
- }) {
1441
- const [firstSortOption, ...othersSortOptions] = normalizeSortByOptions({
1442
- sortBy,
1443
- sortByDirection,
1444
- sortByColumnType
1445
- });
1446
- let sortFn = (0, import_thenby.firstBy)(...firstSortOption);
1447
- for (const sortOptions of othersSortOptions) {
1448
- sortFn = sortFn.thenBy(...sortOptions);
1449
- }
1450
- return sortFn;
1451
- }
1452
- function normalizeSortByOptions({
1453
- sortBy,
1454
- sortByDirection,
1455
- sortByColumnType
1456
- }) {
1457
- const numberFormat = sortByColumnType === "number" && {
1458
- cmp: (a, b) => a - b
1459
- };
1460
- if (!Array.isArray(sortBy)) {
1461
- sortBy = [sortBy];
1462
- }
1463
- return sortBy.map((sortByEl) => {
1464
- if (typeof sortByEl === "string") {
1465
- return [sortByEl, { direction: sortByDirection, ...numberFormat }];
1466
- }
1467
- if (Array.isArray(sortByEl)) {
1468
- if (sortByEl[1] === void 0) {
1469
- return [sortByEl, { direction: sortByDirection, ...numberFormat }];
1470
- }
1471
- if (typeof sortByEl[1] === "object") {
1472
- const othersSortOptions = numberFormat ? { ...numberFormat, ...sortByEl[1] } : sortByEl[1];
1473
- return [
1474
- sortByEl[0],
1475
- { direction: sortByDirection, ...othersSortOptions }
1476
- ];
1477
- }
1478
- }
1479
- return sortByEl;
1480
- });
1481
- }
1482
-
1483
- // src/operations/groupBy.ts
1484
- function groupValuesByColumn({
1485
- data,
1486
- valuesColumns,
1487
- joinOperation,
1488
- keysColumn,
1489
- operation
1490
- }) {
1491
- if (Array.isArray(data) && data.length === 0) {
1492
- return null;
1493
- }
1494
- const groups = data.reduce((accumulator, item) => {
1495
- const group = item[keysColumn];
1496
- const values = accumulator.get(group) || [];
1497
- accumulator.set(group, values);
1498
- const aggregatedValue = aggregate(item, valuesColumns, joinOperation);
1499
- const isValid = (operation === "count" ? true : aggregatedValue !== null) && aggregatedValue !== void 0;
1500
- if (isValid) {
1501
- values.push(aggregatedValue);
1502
- accumulator.set(group, values);
1503
- }
1504
- return accumulator;
1505
- }, /* @__PURE__ */ new Map());
1506
- const targetOperation = aggregationFunctions[operation];
1507
- if (targetOperation) {
1508
- return Array.from(groups).map(([name, value]) => ({
1509
- name,
1510
- value: targetOperation(value)
1511
- }));
1512
- }
1513
- return [];
1514
- }
1515
-
1516
- // src/utils/dateUtils.ts
1517
- function getUTCMonday(date) {
1518
- const dateCp = new Date(date);
1519
- const day = dateCp.getUTCDay();
1520
- const diff = dateCp.getUTCDate() - day + (day ? 1 : -6);
1521
- dateCp.setUTCDate(diff);
1522
- return Date.UTC(
1523
- dateCp.getUTCFullYear(),
1524
- dateCp.getUTCMonth(),
1525
- dateCp.getUTCDate()
1526
- );
1527
- }
1528
-
1529
- // src/operations/groupByDate.ts
1530
- var GROUP_KEY_FN_MAPPING = {
1531
- year: (date) => Date.UTC(date.getUTCFullYear()),
1532
- month: (date) => Date.UTC(date.getUTCFullYear(), date.getUTCMonth()),
1533
- week: (date) => getUTCMonday(date),
1534
- day: (date) => Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()),
1535
- hour: (date) => Date.UTC(
1536
- date.getUTCFullYear(),
1537
- date.getUTCMonth(),
1538
- date.getUTCDate(),
1539
- date.getUTCHours()
1540
- ),
1541
- minute: (date) => Date.UTC(
1542
- date.getUTCFullYear(),
1543
- date.getUTCMonth(),
1544
- date.getUTCDate(),
1545
- date.getUTCHours(),
1546
- date.getUTCMinutes()
1547
- ),
1548
- second: (date) => Date.UTC(
1549
- date.getUTCFullYear(),
1550
- date.getUTCMonth(),
1551
- date.getUTCDate(),
1552
- date.getUTCHours(),
1553
- date.getUTCMinutes(),
1554
- date.getUTCSeconds()
1555
- )
1556
- };
1557
- function groupValuesByDateColumn({
1558
- data,
1559
- valuesColumns,
1560
- joinOperation,
1561
- keysColumn,
1562
- groupType,
1563
- operation
1564
- }) {
1565
- if (Array.isArray(data) && data.length === 0) {
1566
- return null;
1567
- }
1568
- const groupKeyFn = GROUP_KEY_FN_MAPPING[groupType];
1569
- if (!groupKeyFn) {
1570
- return null;
1571
- }
1572
- const groups = data.reduce((acc, item) => {
1573
- const value = item[keysColumn];
1574
- const formattedValue = new Date(value);
1575
- const groupKey = groupKeyFn(formattedValue);
1576
- if (!isNaN(groupKey)) {
1577
- let groupedValues = acc.get(groupKey);
1578
- if (!groupedValues) {
1579
- groupedValues = [];
1580
- acc.set(groupKey, groupedValues);
1581
- }
1582
- const aggregatedValue = aggregate(item, valuesColumns, joinOperation);
1583
- const isValid = aggregatedValue !== null && aggregatedValue !== void 0;
1584
- if (isValid) {
1585
- groupedValues.push(aggregatedValue);
1586
- acc.set(groupKey, groupedValues);
1587
- }
1588
- }
1589
- return acc;
1590
- }, /* @__PURE__ */ new Map());
1591
- const targetOperation = aggregationFunctions[operation];
1592
- return [...groups.entries()].map(([name, value]) => ({
1593
- name,
1594
- value: targetOperation(value)
1595
- })).sort((a, b) => a.name - b.name);
1596
- }
1597
-
1598
- // src/operations/histogram.ts
1599
- function histogram({
1600
- data,
1601
- valuesColumns,
1602
- joinOperation,
1603
- ticks,
1604
- operation
1605
- }) {
1606
- if (Array.isArray(data) && data.length === 0) {
1607
- return [];
1608
- }
1609
- const binsContainer = [Number.MIN_SAFE_INTEGER, ...ticks].map(
1610
- (tick, index, arr) => ({
1611
- bin: index,
1612
- start: tick,
1613
- end: index === arr.length - 1 ? Number.MAX_SAFE_INTEGER : arr[index + 1],
1614
- values: []
1615
- })
1616
- );
1617
- data.forEach((feature) => {
1618
- const featureValue = aggregate(
1619
- feature,
1620
- valuesColumns,
1621
- joinOperation
1622
- );
1623
- const isValid = featureValue !== null && featureValue !== void 0;
1624
- if (!isValid) {
1625
- return;
1626
- }
1627
- const binContainer = binsContainer.find(
1628
- (bin) => bin.start <= featureValue && bin.end > featureValue
1629
- );
1630
- if (!binContainer) {
1631
- return;
1632
- }
1633
- binContainer.values.push(featureValue);
1634
- });
1635
- const targetOperation = aggregationFunctions[operation];
1636
- const transformedBins = binsContainer.map(
1637
- (binContainer) => binContainer.values
1638
- );
1639
- return transformedBins.map(
1640
- (values) => values.length ? targetOperation(values) : 0
1641
- );
1642
- }
1643
-
1644
- // src/operations/scatterPlot.ts
1645
- function scatterPlot({
1646
- data,
1647
- xAxisColumns,
1648
- xAxisJoinOperation,
1649
- yAxisColumns,
1650
- yAxisJoinOperation
1651
- }) {
1652
- return data.reduce(
1653
- (acc, feature) => {
1654
- const xValue = aggregate(
1655
- feature,
1656
- xAxisColumns,
1657
- xAxisJoinOperation
1658
- );
1659
- const xIsValid = xValue !== null && xValue !== void 0;
1660
- const yValue = aggregate(
1661
- feature,
1662
- yAxisColumns,
1663
- yAxisJoinOperation
1664
- );
1665
- const yIsValid = yValue !== null && yValue !== void 0;
1666
- if (xIsValid && yIsValid) {
1667
- acc.push([xValue, yValue]);
1668
- }
1669
- return acc;
1670
- },
1671
- []
1672
- );
1673
- }
1674
-
1675
- // src/utils.ts
1676
- var FILTER_TYPES = new Set(Object.values(FilterType));
1677
- var isFilterType = (type) => FILTER_TYPES.has(type);
1678
- function getApplicableFilters(owner, filters) {
1679
- if (!filters) return {};
1680
- const applicableFilters = {};
1681
- for (const column in filters) {
1682
- for (const type in filters[column]) {
1683
- if (!isFilterType(type)) continue;
1684
- const filter = filters[column][type];
1685
- const isApplicable = !owner || !filter?.owner || filter?.owner !== owner;
1686
- if (filter && isApplicable) {
1687
- applicableFilters[column] || (applicableFilters[column] = {});
1688
- applicableFilters[column][type] = filter;
1689
- }
1690
- }
1691
- }
1692
- return applicableFilters;
1693
- }
1694
- function normalizeObjectKeys(el) {
1695
- if (Array.isArray(el)) {
1696
- return el.map((value) => normalizeObjectKeys(value));
1697
- } else if (typeof el !== "object") {
1698
- return el;
1699
- }
1700
- return Object.entries(el).reduce(
1701
- (acc, [key, value]) => {
1702
- acc[key.toLowerCase()] = typeof value === "object" && value ? normalizeObjectKeys(value) : value;
1703
- return acc;
1704
- },
1705
- {}
1706
- );
1707
- }
1708
- function assert2(condition, message) {
1709
- if (!condition) {
1710
- throw new Error(message);
1711
- }
1712
- }
1713
- var _InvalidColumnError = class _InvalidColumnError extends Error {
1714
- constructor(message) {
1715
- super(`${_InvalidColumnError.NAME}: ${message}`);
1716
- this.name = _InvalidColumnError.NAME;
1717
- }
1718
- static is(error) {
1719
- return error instanceof _InvalidColumnError || error.message?.includes(_InvalidColumnError.NAME);
1720
- }
1721
- };
1722
- __publicField(_InvalidColumnError, "NAME", "InvalidColumnError");
1723
- var InvalidColumnError = _InvalidColumnError;
1724
- function isEmptyObject(object) {
1725
- for (const _ in object) {
1726
- return false;
1727
- }
1728
- return true;
1729
- }
1730
- var isObject = (x) => x !== null && typeof x === "object";
1731
- var isPureObject = (x) => isObject(x) && x.constructor === {}.constructor;
1732
-
1733
- // src/widget-sources/widget-tileset-source.ts
1734
- import { booleanEqual } from "@turf/boolean-equal";
1735
- var WidgetTilesetSource = class extends WidgetSource {
1736
- constructor() {
1737
- super(...arguments);
1738
- __publicField(this, "_tiles", []);
1739
- __publicField(this, "_features", []);
1740
- __publicField(this, "_tileFeatureExtractOptions", {});
1741
- __publicField(this, "_tileFeatureExtractPreviousInputs", {});
1742
- }
1743
- /**
1744
- * Loads features as a list of tiles (typically provided by deck.gl).
1745
- * After tiles are loaded, {@link extractTileFeatures} must be called
1746
- * before computing statistics on the tiles.
1747
- */
1748
- loadTiles(tiles2) {
1749
- this._tiles = tiles2;
1750
- this._features.length = 0;
1751
- }
1752
- /** Configures options used to extract features from tiles. */
1753
- setTileFeatureExtractOptions(options) {
1754
- this._tileFeatureExtractOptions = options;
1755
- this._features.length = 0;
1756
- }
1757
- _extractTileFeatures(spatialFilter) {
1758
- const prevInputs = this._tileFeatureExtractPreviousInputs;
1759
- if (this._features.length && prevInputs.spatialFilter && booleanEqual(prevInputs.spatialFilter, spatialFilter)) {
1760
- return;
1761
- }
1762
- this._features = tileFeatures({
1763
- tiles: this._tiles,
1764
- tileFormat: this.props.tileFormat,
1765
- ...this._tileFeatureExtractOptions,
1766
- spatialFilter,
1767
- spatialDataColumn: this.props.spatialDataColumn,
1768
- spatialDataType: this.props.spatialDataType
1769
- });
1770
- prevInputs.spatialFilter = spatialFilter;
1771
- }
1772
- /**
1773
- * Loads features as GeoJSON (used for testing).
1774
- * @experimental
1775
- * @internal Not for public use. Spatial filters in other method calls will be ignored.
1776
- */
1777
- loadGeoJSON({
1778
- geojson,
1779
- spatialFilter
1780
- }) {
1781
- this._features = geojsonFeatures({
1782
- geojson,
1783
- spatialFilter,
1784
- ...this._tileFeatureExtractOptions
1785
- });
1786
- this._tileFeatureExtractPreviousInputs.spatialFilter = spatialFilter;
1787
- }
1788
- async getFeatures() {
1789
- throw new Error("getFeatures not supported for tilesets");
1790
- }
1791
- async getFormula({
1792
- column = "*",
1793
- operation = "count",
1794
- joinOperation,
1795
- filters,
1796
- filterOwner,
1797
- spatialFilter
1798
- }) {
1799
- if (operation === "custom") {
1800
- throw new Error("Custom aggregation not supported for tilesets");
1801
- }
1802
- if (column && column !== "*" || operation !== "count") {
1803
- assertColumn(this._features, column);
1804
- }
1805
- const filteredFeatures = this._getFilteredFeatures(
1806
- spatialFilter,
1807
- filters,
1808
- filterOwner
1809
- );
1810
- if (filteredFeatures.length === 0 && operation !== "count") {
1811
- return { value: null };
1812
- }
1813
- const targetOperation = aggregationFunctions[operation];
1814
- return {
1815
- value: targetOperation(filteredFeatures, column, joinOperation)
1816
- };
1817
- }
1818
- async getHistogram({
1819
- operation = "count",
1820
- ticks,
1821
- column,
1822
- joinOperation,
1823
- filters,
1824
- filterOwner,
1825
- spatialFilter
1826
- }) {
1827
- const filteredFeatures = this._getFilteredFeatures(
1828
- spatialFilter,
1829
- filters,
1830
- filterOwner
1831
- );
1832
- if (!this._features.length) {
1833
- return [];
1834
- }
1835
- assertColumn(this._features, column);
1836
- return histogram({
1837
- data: filteredFeatures,
1838
- valuesColumns: normalizeColumns(column),
1839
- joinOperation,
1840
- ticks,
1841
- operation
1842
- });
1843
- }
1844
- async getCategories({
1845
- column,
1846
- operation = "count",
1847
- operationColumn,
1848
- joinOperation,
1849
- filters,
1850
- filterOwner,
1851
- spatialFilter
1852
- }) {
1853
- const filteredFeatures = this._getFilteredFeatures(
1854
- spatialFilter,
1855
- filters,
1856
- filterOwner
1857
- );
1858
- if (!filteredFeatures.length) {
1859
- return [];
1860
- }
1861
- assertColumn(this._features, column, operationColumn);
1862
- const groups = groupValuesByColumn({
1863
- data: filteredFeatures,
1864
- valuesColumns: normalizeColumns(operationColumn || column),
1865
- joinOperation,
1866
- keysColumn: column,
1867
- operation
1868
- });
1869
- return groups || [];
1870
- }
1871
- async getScatter({
1872
- xAxisColumn,
1873
- yAxisColumn,
1874
- xAxisJoinOperation,
1875
- yAxisJoinOperation,
1876
- filters,
1877
- filterOwner,
1878
- spatialFilter
1879
- }) {
1880
- const filteredFeatures = this._getFilteredFeatures(
1881
- spatialFilter,
1882
- filters,
1883
- filterOwner
1884
- );
1885
- if (!filteredFeatures.length) {
1886
- return [];
1887
- }
1888
- assertColumn(this._features, xAxisColumn, yAxisColumn);
1889
- return scatterPlot({
1890
- data: filteredFeatures,
1891
- xAxisColumns: normalizeColumns(xAxisColumn),
1892
- xAxisJoinOperation,
1893
- yAxisColumns: normalizeColumns(yAxisColumn),
1894
- yAxisJoinOperation
1895
- });
1896
- }
1897
- async getTable({
1898
- columns,
1899
- searchFilterColumn,
1900
- searchFilterText,
1901
- sortBy,
1902
- sortDirection,
1903
- sortByColumnType,
1904
- offset = 0,
1905
- limit = 10,
1906
- filters,
1907
- filterOwner,
1908
- spatialFilter
1909
- }) {
1910
- let filteredFeatures = this._getFilteredFeatures(
1911
- spatialFilter,
1912
- filters,
1913
- filterOwner
1914
- );
1915
- if (!filteredFeatures.length) {
1916
- return { rows: [], totalCount: 0 };
1917
- }
1918
- if (searchFilterColumn && searchFilterText) {
1919
- filteredFeatures = filteredFeatures.filter(
1920
- (row) => row[searchFilterColumn] && String(row[searchFilterColumn]).toLowerCase().includes(String(searchFilterText).toLowerCase())
1921
- );
1922
- }
1923
- let rows = applySorting(filteredFeatures, {
1924
- sortBy,
1925
- sortByDirection: sortDirection,
1926
- sortByColumnType
1927
- });
1928
- const totalCount = rows.length;
1929
- rows = rows.slice(
1930
- Math.min(offset, totalCount),
1931
- Math.min(offset + limit, totalCount)
1932
- );
1933
- rows = rows.map((srcRow) => {
1934
- const dstRow = {};
1935
- for (const column of columns) {
1936
- dstRow[column] = srcRow[column];
1937
- }
1938
- return dstRow;
1939
- });
1940
- return { rows, totalCount };
1941
- }
1942
- async getTimeSeries({
1943
- column,
1944
- stepSize,
1945
- operation,
1946
- operationColumn,
1947
- joinOperation,
1948
- filters,
1949
- filterOwner,
1950
- spatialFilter
1951
- }) {
1952
- const filteredFeatures = this._getFilteredFeatures(
1953
- spatialFilter,
1954
- filters,
1955
- filterOwner
1956
- );
1957
- if (!filteredFeatures.length) {
1958
- return { rows: [] };
1959
- }
1960
- assertColumn(this._features, column, operationColumn);
1961
- const rows = groupValuesByDateColumn({
1962
- data: filteredFeatures,
1963
- valuesColumns: normalizeColumns(operationColumn || column),
1964
- keysColumn: column,
1965
- groupType: stepSize,
1966
- operation,
1967
- joinOperation
1968
- }) || [];
1969
- return { rows };
1970
- }
1971
- async getRange({
1972
- column,
1973
- filters,
1974
- filterOwner,
1975
- spatialFilter
1976
- }) {
1977
- assertColumn(this._features, column);
1978
- const filteredFeatures = this._getFilteredFeatures(
1979
- spatialFilter,
1980
- filters,
1981
- filterOwner
1982
- );
1983
- if (!this._features.length) {
1984
- return null;
1985
- }
1986
- return {
1987
- min: aggregationFunctions.min(filteredFeatures, column),
1988
- max: aggregationFunctions.max(filteredFeatures, column)
1989
- };
1990
- }
1991
- /****************************************************************************
1992
- * INTERNAL
1993
- */
1994
- _getFilteredFeatures(spatialFilter, filters, filterOwner) {
1995
- assert2(spatialFilter, "spatialFilter required for tilesets");
1996
- this._extractTileFeatures(spatialFilter);
1997
- return applyFilters(
1998
- this._features,
1999
- getApplicableFilters(filterOwner, filters || this.props.filters),
2000
- this.props.filtersLogicalOperator || "and"
2001
- );
2002
- }
2003
- };
2004
- function assertColumn(features, ...columnArgs) {
2005
- const columns = Array.from(new Set(columnArgs.map(normalizeColumns).flat()));
2006
- const featureKeys = Object.keys(features[0]);
2007
- const invalidColumns = columns.filter(
2008
- (column) => !featureKeys.includes(column)
2009
- );
2010
- if (invalidColumns.length) {
2011
- throw new InvalidColumnError(
2012
- `Missing column(s): ${invalidColumns.join(", ")}`
2013
- );
2014
- }
2015
- }
2016
- function normalizeColumns(columns) {
2017
- return Array.isArray(columns) ? columns : typeof columns === "string" ? [columns] : [];
2018
- }
2019
-
2020
- export {
2021
- __publicField,
2022
- getClient,
2023
- setClient,
2024
- FilterType,
2025
- ApiVersion,
2026
- DEFAULT_API_BASE_URL,
2027
- TileFormat,
2028
- SpatialIndex,
2029
- Provider,
2030
- makeIntervalComplete,
2031
- filterFunctions,
2032
- _buildFeatureFilter,
2033
- applyFilters,
2034
- buildBinaryFeatureFilter,
2035
- geojsonFeatures,
2036
- transformToTileCoords,
2037
- FEATURE_GEOM_PROPERTY,
2038
- tileFeaturesGeometries,
2039
- tileFeaturesSpatialIndex,
2040
- V3_MINOR_VERSION,
2041
- DEFAULT_GEO_COLUMN,
2042
- DEFAULT_MAX_LENGTH_URL,
2043
- DEFAULT_TILE_RESOLUTION,
2044
- DEFAULT_AGGREGATION_RES_LEVEL_H3,
2045
- DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN,
2046
- tileFeatures,
2047
- getApplicableFilters,
2048
- normalizeObjectKeys,
2049
- assert2 as assert,
2050
- InvalidColumnError,
2051
- isEmptyObject,
2052
- isPureObject,
2053
- _getHexagonResolution,
2054
- WidgetSource,
2055
- aggregationFunctions,
2056
- aggregate,
2057
- applySorting,
2058
- groupValuesByColumn,
2059
- groupValuesByDateColumn,
2060
- histogram,
2061
- scatterPlot,
2062
- WidgetTilesetSource
2063
- };