@carto/api-client 0.5.0-alpha.6 → 0.5.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/worker.js CHANGED
@@ -1,13 +1,2128 @@
1
- import {
2
- WidgetTilesetSource
3
- } from "./chunk-LEI5PI5X.js";
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
+
403
+ // src/constants.ts
404
+ var FilterType = /* @__PURE__ */ ((FilterType2) => {
405
+ FilterType2["IN"] = "in";
406
+ FilterType2["BETWEEN"] = "between";
407
+ FilterType2["CLOSED_OPEN"] = "closed_open";
408
+ FilterType2["TIME"] = "time";
409
+ FilterType2["STRING_SEARCH"] = "stringSearch";
410
+ return FilterType2;
411
+ })(FilterType || {});
412
+ var DEFAULT_API_BASE_URL = "https://gcp-us-east1.api.carto.com";
413
+
414
+ // src/constants-internal.ts
415
+ var DEFAULT_GEO_COLUMN = "geom";
416
+ var DEFAULT_AGGREGATION_RES_LEVEL_H3 = 4;
417
+ var DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN = 6;
418
+
419
+ // src/spatial-index.ts
420
+ var DEFAULT_TILE_SIZE = 512;
421
+ var QUADBIN_ZOOM_MAX_OFFSET = 4;
422
+ function getSpatialFiltersResolution(source2, viewState) {
423
+ const dataResolution = source2.dataResolution ?? Number.MAX_VALUE;
424
+ const aggregationResLevel = source2.aggregationResLevel ?? (source2.spatialDataType === "h3" ? DEFAULT_AGGREGATION_RES_LEVEL_H3 : DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN);
425
+ const aggregationResLevelOffset = Math.max(
426
+ 0,
427
+ Math.floor(aggregationResLevel)
428
+ );
429
+ const currentZoomInt = Math.ceil(viewState.zoom);
430
+ if (source2.spatialDataType === "h3") {
431
+ const tileSize = DEFAULT_TILE_SIZE;
432
+ const maxResolutionForZoom = maxH3SpatialFiltersResolutions.find(
433
+ ([zoom]) => zoom === currentZoomInt
434
+ )?.[1] ?? Math.max(0, currentZoomInt - 3);
435
+ const maxSpatialFiltersResolution = maxResolutionForZoom ? Math.min(dataResolution, maxResolutionForZoom) : dataResolution;
436
+ const hexagonResolution = _getHexagonResolution(viewState, tileSize) + aggregationResLevelOffset;
437
+ return Math.min(hexagonResolution, maxSpatialFiltersResolution);
438
+ }
439
+ if (source2.spatialDataType === "quadbin") {
440
+ const maxResolutionForZoom = currentZoomInt + QUADBIN_ZOOM_MAX_OFFSET;
441
+ const maxSpatialFiltersResolution = Math.min(
442
+ dataResolution,
443
+ maxResolutionForZoom
444
+ );
445
+ const quadsResolution = Math.floor(viewState.zoom) + aggregationResLevelOffset;
446
+ return Math.min(quadsResolution, maxSpatialFiltersResolution);
447
+ }
448
+ return void 0;
449
+ }
450
+ var maxH3SpatialFiltersResolutions = [
451
+ [20, 14],
452
+ [19, 13],
453
+ [18, 12],
454
+ [17, 11],
455
+ [16, 10],
456
+ [15, 9],
457
+ [14, 8],
458
+ [13, 7],
459
+ [12, 7],
460
+ [11, 7],
461
+ [10, 6],
462
+ [9, 6],
463
+ [8, 5],
464
+ [7, 4],
465
+ [6, 4],
466
+ [5, 3],
467
+ [4, 2],
468
+ [3, 1],
469
+ [2, 1],
470
+ [1, 0]
471
+ ];
472
+ var BIAS = 2;
473
+ function _getHexagonResolution(viewport, tileSize) {
474
+ const zoomOffset = Math.log2(tileSize / DEFAULT_TILE_SIZE);
475
+ const hexagonScaleFactor = 2 / 3 * (viewport.zoom - zoomOffset);
476
+ const latitudeScaleFactor = Math.log(
477
+ 1 / Math.cos(Math.PI * viewport.latitude / 180)
478
+ );
479
+ return Math.max(
480
+ 0,
481
+ Math.floor(hexagonScaleFactor + latitudeScaleFactor - BIAS)
482
+ );
483
+ }
484
+
485
+ // src/widget-sources/widget-source.ts
486
+ var _WidgetSource = class _WidgetSource {
487
+ constructor(props) {
488
+ __publicField(this, "props");
489
+ this.props = { ..._WidgetSource.defaultProps, ...props };
490
+ }
491
+ /**
492
+ * Destroys the widget source and releases allocated resources.
493
+ *
494
+ * For remote sources (tables, queries) this has no effect, but for local
495
+ * sources (tilesets, rasters) these resources will affect performance
496
+ * and stability if many (10+) sources are created and not released.
497
+ */
498
+ destroy() {
499
+ }
500
+ _getSpatialFiltersResolution(source2, spatialFilter, referenceViewState) {
501
+ if (!spatialFilter || source2.spatialDataType === "geo") {
502
+ return;
503
+ }
504
+ if (!referenceViewState) {
505
+ throw new Error(
506
+ 'Missing required option, "spatialIndexReferenceViewState".'
507
+ );
508
+ }
509
+ return getSpatialFiltersResolution(source2, referenceViewState);
510
+ }
511
+ };
512
+ __publicField(_WidgetSource, "defaultProps", {
513
+ apiVersion: "v3" /* V3 */,
514
+ apiBaseUrl: DEFAULT_API_BASE_URL,
515
+ clientId: getClient(),
516
+ filters: {},
517
+ filtersLogicalOperator: "and"
518
+ });
519
+ var WidgetSource = _WidgetSource;
520
+
521
+ // src/utils.ts
522
+ var FILTER_TYPES = new Set(Object.values(FilterType));
523
+ var isFilterType = (type) => FILTER_TYPES.has(type);
524
+ function getApplicableFilters(owner, filters) {
525
+ if (!filters) return {};
526
+ const applicableFilters = {};
527
+ for (const column in filters) {
528
+ for (const type in filters[column]) {
529
+ if (!isFilterType(type)) continue;
530
+ const filter = filters[column][type];
531
+ const isApplicable = !owner || !filter?.owner || filter?.owner !== owner;
532
+ if (filter && isApplicable) {
533
+ applicableFilters[column] || (applicableFilters[column] = {});
534
+ applicableFilters[column][type] = filter;
535
+ }
536
+ }
537
+ }
538
+ return applicableFilters;
539
+ }
540
+ function assert(condition, message) {
541
+ if (!condition) {
542
+ throw new Error(message);
543
+ }
544
+ }
545
+ var _InvalidColumnError = class _InvalidColumnError extends Error {
546
+ constructor(message) {
547
+ super(`${_InvalidColumnError.NAME}: ${message}`);
548
+ this.name = _InvalidColumnError.NAME;
549
+ }
550
+ static is(error) {
551
+ return error instanceof _InvalidColumnError || error.message?.includes(_InvalidColumnError.NAME);
552
+ }
553
+ };
554
+ __publicField(_InvalidColumnError, "NAME", "InvalidColumnError");
555
+ var InvalidColumnError = _InvalidColumnError;
556
+
557
+ // src/utils/makeIntervalComplete.ts
558
+ function makeIntervalComplete(intervals) {
559
+ return intervals.map((val) => {
560
+ if (val[0] === void 0 || val[0] === null) {
561
+ return [Number.MIN_SAFE_INTEGER, val[1]];
562
+ }
563
+ if (val[1] === void 0 || val[1] === null) {
564
+ return [val[0], Number.MAX_SAFE_INTEGER];
565
+ }
566
+ return val;
567
+ });
568
+ }
569
+
570
+ // src/filters/FilterTypes.ts
571
+ var filterFunctions = {
572
+ ["in" /* IN */]: filterIn,
573
+ ["between" /* BETWEEN */]: filterBetween,
574
+ ["time" /* TIME */]: filterTime,
575
+ ["closed_open" /* CLOSED_OPEN */]: filterClosedOpen,
576
+ ["stringSearch" /* STRING_SEARCH */]: filterStringSearch
577
+ };
578
+ function filterIn(filterValues, featureValue) {
579
+ return filterValues.includes(featureValue);
580
+ }
581
+ function filterBetween(filterValues, featureValue) {
582
+ const checkRange = (range) => {
583
+ const [lowerBound, upperBound] = range;
584
+ return featureValue >= lowerBound && featureValue <= upperBound;
585
+ };
586
+ return makeIntervalComplete(filterValues).some(
587
+ checkRange
588
+ );
589
+ }
590
+ function filterTime(filterValues, featureValue) {
591
+ const featureValueAsTimestamp = new Date(featureValue).getTime();
592
+ if (isFinite(featureValueAsTimestamp)) {
593
+ return filterBetween(filterValues, featureValueAsTimestamp);
594
+ } else {
595
+ throw new Error(`Column used to filter by time isn't well formatted.`);
596
+ }
597
+ }
598
+ function filterClosedOpen(filterValues, featureValue) {
599
+ const checkRange = (range) => {
600
+ const [lowerBound, upperBound] = range;
601
+ return featureValue >= lowerBound && featureValue < upperBound;
602
+ };
603
+ return makeIntervalComplete(filterValues).some(
604
+ checkRange
605
+ );
606
+ }
607
+ function filterStringSearch(filterValues, featureValue, params = {}) {
608
+ const normalizedFeatureValue = normalize(featureValue, params);
609
+ const stringRegExp = params.useRegExp ? filterValues : filterValues.map((filterValue) => {
610
+ let stringRegExp2 = escapeRegExp(normalize(filterValue, params));
611
+ if (params.mustStart) stringRegExp2 = `^${stringRegExp2}`;
612
+ if (params.mustEnd) stringRegExp2 = `${stringRegExp2}$`;
613
+ return stringRegExp2;
614
+ });
615
+ const regex = new RegExp(
616
+ stringRegExp.join("|"),
617
+ params.caseSensitive ? "g" : "gi"
618
+ );
619
+ return !!normalizedFeatureValue.match(regex);
620
+ }
621
+ var specialCharRegExp = /[.*+?^${}()|[\]\\]/g;
622
+ var normalizeRegExp = /\p{Diacritic}/gu;
623
+ function escapeRegExp(value) {
624
+ return value.replace(specialCharRegExp, "\\$&");
625
+ }
626
+ function normalize(data, params) {
627
+ let normalizedData = String(data);
628
+ if (!params.keepSpecialCharacters)
629
+ normalizedData = normalizedData.normalize("NFD").replace(normalizeRegExp, "");
630
+ return normalizedData;
631
+ }
632
+
633
+ // src/filters/Filter.ts
634
+ var LOGICAL_OPERATOR_METHODS = {
635
+ and: "every",
636
+ or: "some"
637
+ };
638
+ function passesFilter(columns, filters, feature, filtersLogicalOperator) {
639
+ const method = LOGICAL_OPERATOR_METHODS[filtersLogicalOperator];
640
+ return columns[method]((column) => {
641
+ const columnFilters = filters[column];
642
+ const columnFilterTypes = Object.keys(columnFilters);
643
+ if (!feature || feature[column] === null || feature[column] === void 0) {
644
+ return false;
645
+ }
646
+ return columnFilterTypes.every((filter) => {
647
+ const filterFunction = filterFunctions[filter];
648
+ if (!filterFunction) {
649
+ throw new Error(`"${filter}" filter is not implemented.`);
650
+ }
651
+ return filterFunction(
652
+ columnFilters[filter].values,
653
+ feature[column],
654
+ columnFilters[filter].params
655
+ );
656
+ });
657
+ });
658
+ }
659
+ function _buildFeatureFilter({
660
+ filters = {},
661
+ type = "boolean",
662
+ filtersLogicalOperator = "and"
663
+ }) {
664
+ const columns = Object.keys(filters);
665
+ if (!columns.length) {
666
+ return () => type === "number" ? 1 : true;
667
+ }
668
+ return (feature) => {
669
+ const f = feature.properties || feature;
670
+ const featurePassesFilter = passesFilter(
671
+ columns,
672
+ filters,
673
+ f,
674
+ filtersLogicalOperator
675
+ );
676
+ return type === "number" ? Number(featurePassesFilter) : featurePassesFilter;
677
+ };
678
+ }
679
+ function applyFilters(features, filters, filtersLogicalOperator) {
680
+ return Object.keys(filters).length ? features.filter(_buildFeatureFilter({ filters, filtersLogicalOperator })) : features;
681
+ }
682
+
683
+ // src/filters/geosjonFeatures.ts
684
+ import intersects from "@turf/boolean-intersects";
685
+ function geojsonFeatures({
686
+ geojson,
687
+ spatialFilter,
688
+ uniqueIdProperty
689
+ }) {
690
+ let uniqueIdx = 0;
691
+ const map = /* @__PURE__ */ new Map();
692
+ if (!spatialFilter) {
693
+ return [];
694
+ }
695
+ for (const feature of geojson.features) {
696
+ const uniqueId = uniqueIdProperty ? feature.properties[uniqueIdProperty] : ++uniqueIdx;
697
+ if (!map.has(uniqueId) && intersects(spatialFilter, feature)) {
698
+ map.set(uniqueId, feature.properties);
699
+ }
700
+ }
701
+ return Array.from(map.values());
702
+ }
703
+
704
+ // src/filters/tileFeaturesGeometries.ts
705
+ import bboxPolygon from "@turf/bbox-polygon";
706
+ import intersects2 from "@turf/boolean-intersects";
707
+ import booleanWithin from "@turf/boolean-within";
708
+ import intersect from "@turf/intersect";
709
+
710
+ // node_modules/@math.gl/core/dist/lib/common.js
711
+ var RADIANS_TO_DEGREES = 1 / Math.PI * 180;
712
+ var DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
713
+ var DEFAULT_CONFIG = {
714
+ EPSILON: 1e-12,
715
+ debug: false,
716
+ precision: 4,
717
+ printTypes: false,
718
+ printDegrees: false,
719
+ printRowMajor: true,
720
+ _cartographicRadians: false
721
+ };
722
+ globalThis.mathgl = globalThis.mathgl || { config: { ...DEFAULT_CONFIG } };
723
+ var config = globalThis.mathgl.config;
724
+ function isArray(value) {
725
+ return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
726
+ }
727
+ function lerp(a, b, t) {
728
+ if (isArray(a)) {
729
+ return a.map((ai, i) => lerp(ai, b[i], t));
730
+ }
731
+ return t * b + (1 - t) * a;
732
+ }
733
+
734
+ // node_modules/@math.gl/web-mercator/dist/assert.js
735
+ function assert2(condition, message) {
736
+ if (!condition) {
737
+ throw new Error(message || "@math.gl/web-mercator: assertion failed.");
738
+ }
739
+ }
740
+
741
+ // node_modules/@math.gl/web-mercator/dist/web-mercator-utils.js
742
+ var PI = Math.PI;
743
+ var PI_4 = PI / 4;
744
+ var DEGREES_TO_RADIANS2 = PI / 180;
745
+ var RADIANS_TO_DEGREES2 = 180 / PI;
746
+ var TILE_SIZE = 512;
747
+ function lngLatToWorld(lngLat) {
748
+ const [lng, lat] = lngLat;
749
+ assert2(Number.isFinite(lng));
750
+ assert2(Number.isFinite(lat) && lat >= -90 && lat <= 90, "invalid latitude");
751
+ const lambda2 = lng * DEGREES_TO_RADIANS2;
752
+ const phi2 = lat * DEGREES_TO_RADIANS2;
753
+ const x = TILE_SIZE * (lambda2 + PI) / (2 * PI);
754
+ const y = TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5))) / (2 * PI);
755
+ return [x, y];
756
+ }
757
+ function worldToLngLat(xy) {
758
+ const [x, y] = xy;
759
+ const lambda2 = x / TILE_SIZE * (2 * PI) - PI;
760
+ const phi2 = 2 * (Math.atan(Math.exp(y / TILE_SIZE * (2 * PI) - PI)) - PI_4);
761
+ return [lambda2 * RADIANS_TO_DEGREES2, phi2 * RADIANS_TO_DEGREES2];
762
+ }
763
+
764
+ // node_modules/@math.gl/web-mercator/dist/get-bounds.js
765
+ var DEGREES_TO_RADIANS3 = Math.PI / 180;
766
+
767
+ // src/utils/transformToTileCoords.ts
768
+ var TRANSFORM_FN = {
769
+ Point: transformPoint,
770
+ MultiPoint: transformMultiPoint,
771
+ LineString: transformLineString,
772
+ MultiLineString: transformMultiLineString,
773
+ Polygon: transformPolygon,
774
+ MultiPolygon: transformMultiPolygon
775
+ };
776
+ function transformToTileCoords(geometry, bbox) {
777
+ const [west, south, east, north] = bbox;
778
+ const nw = projectFlat([west, north]);
779
+ const se = projectFlat([east, south]);
780
+ const projectedBbox = [nw, se];
781
+ if (geometry.type === "GeometryCollection") {
782
+ throw new Error("Unsupported geometry type GeometryCollection");
783
+ }
784
+ const transformFn = TRANSFORM_FN[geometry.type];
785
+ const coordinates = transformFn(geometry.coordinates, projectedBbox);
786
+ return { ...geometry, coordinates };
787
+ }
788
+ function transformPoint([pointX, pointY], [nw, se]) {
789
+ const x = inverseLerp(nw[0], se[0], pointX);
790
+ const y = inverseLerp(nw[1], se[1], pointY);
791
+ return [x, y];
792
+ }
793
+ function getPoints(geometry, bbox) {
794
+ return geometry.map((g) => transformPoint(projectFlat(g), bbox));
795
+ }
796
+ function transformMultiPoint(multiPoint, bbox) {
797
+ return getPoints(multiPoint, bbox);
798
+ }
799
+ function transformLineString(line, bbox) {
800
+ return getPoints(line, bbox);
801
+ }
802
+ function transformMultiLineString(multiLineString, bbox) {
803
+ return multiLineString.map(
804
+ (lineString) => transformLineString(lineString, bbox)
805
+ );
806
+ }
807
+ function transformPolygon(polygon, bbox) {
808
+ return polygon.map((polygonRing) => getPoints(polygonRing, bbox));
809
+ }
810
+ function transformMultiPolygon(multiPolygon, bbox) {
811
+ return multiPolygon.map((polygon) => transformPolygon(polygon, bbox));
812
+ }
813
+ function projectFlat(xyz) {
814
+ return lngLatToWorld(xyz);
815
+ }
816
+ function inverseLerp(a, b, x) {
817
+ return (x - a) / (b - a);
818
+ }
819
+
820
+ // src/utils/transformTileCoordsToWGS84.ts
821
+ var TRANSFORM_FN2 = {
822
+ Point: transformPoint2,
823
+ MultiPoint: transformMultiPoint2,
824
+ LineString: transformLineString2,
825
+ MultiLineString: transformMultiLineString2,
826
+ Polygon: transformPolygon2,
827
+ MultiPolygon: transformMultiPolygon2
828
+ };
829
+ function transformTileCoordsToWGS84(geometry, bbox) {
830
+ const [west, south, east, north] = bbox;
831
+ const nw = lngLatToWorld([west, north]);
832
+ const se = lngLatToWorld([east, south]);
833
+ const projectedBbox = [nw, se];
834
+ if (geometry.type === "GeometryCollection") {
835
+ throw new Error("Unsupported geometry type GeometryCollection");
836
+ }
837
+ const transformFn = TRANSFORM_FN2[geometry.type];
838
+ const coordinates = transformFn(geometry.coordinates, projectedBbox);
839
+ return { ...geometry, coordinates };
840
+ }
841
+ function transformPoint2([pointX, pointY], [nw, se]) {
842
+ const x = lerp(nw[0], se[0], pointX);
843
+ const y = lerp(nw[1], se[1], pointY);
844
+ return worldToLngLat([x, y]);
845
+ }
846
+ function getPoints2(geometry, bbox) {
847
+ return geometry.map((g) => transformPoint2(g, bbox));
848
+ }
849
+ function transformMultiPoint2(multiPoint, bbox) {
850
+ return getPoints2(multiPoint, bbox);
851
+ }
852
+ function transformLineString2(line, bbox) {
853
+ return getPoints2(line, bbox);
854
+ }
855
+ function transformMultiLineString2(multiLineString, bbox) {
856
+ return multiLineString.map(
857
+ (lineString) => transformLineString2(lineString, bbox)
858
+ );
859
+ }
860
+ function transformPolygon2(polygon, bbox) {
861
+ return polygon.map((polygonRing) => getPoints2(polygonRing, bbox));
862
+ }
863
+ function transformMultiPolygon2(multiPolygon, bbox) {
864
+ return multiPolygon.map((polygon) => transformPolygon2(polygon, bbox));
865
+ }
866
+
867
+ // src/filters/tileFeaturesGeometries.ts
868
+ import { featureCollection } from "@turf/helpers";
869
+ var FEATURE_GEOM_PROPERTY = "__geomValue";
870
+ function tileFeaturesGeometries({
871
+ tiles: tiles2,
872
+ tileFormat,
873
+ spatialFilter,
874
+ uniqueIdProperty,
875
+ options
876
+ }) {
877
+ const map = /* @__PURE__ */ new Map();
878
+ for (const tile of tiles2) {
879
+ if (tile.isVisible === false || !tile.data) {
880
+ continue;
881
+ }
882
+ const bbox = [
883
+ tile.bbox.west,
884
+ tile.bbox.south,
885
+ tile.bbox.east,
886
+ tile.bbox.north
887
+ ];
888
+ const bboxToGeom = bboxPolygon(bbox);
889
+ const tileIsFullyVisible = booleanWithin(bboxToGeom, spatialFilter);
890
+ const spatialFilterFeature = {
891
+ type: "Feature",
892
+ geometry: spatialFilter,
893
+ properties: {}
894
+ };
895
+ const clippedGeometryToIntersect = intersect(
896
+ featureCollection([bboxToGeom, spatialFilterFeature])
897
+ );
898
+ if (!clippedGeometryToIntersect) {
899
+ continue;
900
+ }
901
+ const transformedGeometryToIntersect = tileFormat === "mvt" /* MVT */ ? transformToTileCoords(clippedGeometryToIntersect.geometry, bbox) : clippedGeometryToIntersect.geometry;
902
+ createIndicesForPoints(tile.data.points);
903
+ calculateFeatures({
904
+ map,
905
+ tileIsFullyVisible,
906
+ geometryIntersection: transformedGeometryToIntersect,
907
+ data: tile.data.points,
908
+ type: "Point",
909
+ bbox,
910
+ tileFormat,
911
+ uniqueIdProperty,
912
+ options
913
+ });
914
+ calculateFeatures({
915
+ map,
916
+ tileIsFullyVisible,
917
+ geometryIntersection: transformedGeometryToIntersect,
918
+ data: tile.data.lines,
919
+ type: "LineString",
920
+ bbox,
921
+ tileFormat,
922
+ uniqueIdProperty,
923
+ options
924
+ });
925
+ calculateFeatures({
926
+ map,
927
+ tileIsFullyVisible,
928
+ geometryIntersection: transformedGeometryToIntersect,
929
+ data: tile.data.polygons,
930
+ type: "Polygon",
931
+ bbox,
932
+ tileFormat,
933
+ uniqueIdProperty,
934
+ options
935
+ });
936
+ }
937
+ return Array.from(map.values());
938
+ }
939
+ function processTileFeatureProperties({
940
+ map,
941
+ data,
942
+ startIndex,
943
+ endIndex,
944
+ type,
945
+ bbox,
946
+ tileFormat,
947
+ uniqueIdProperty,
948
+ storeGeometry,
949
+ geometryIntersection
950
+ }) {
951
+ const tileProps = getPropertiesFromTile(data, startIndex);
952
+ const uniquePropertyValue = getUniquePropertyValue(
953
+ tileProps,
954
+ uniqueIdProperty,
955
+ map
956
+ );
957
+ if (!uniquePropertyValue || map.has(uniquePropertyValue)) {
958
+ return;
959
+ }
960
+ let geometry = null;
961
+ if (storeGeometry || geometryIntersection) {
962
+ const { positions } = data;
963
+ const ringCoordinates = getRingCoordinatesFor(
964
+ startIndex,
965
+ endIndex,
966
+ positions
967
+ );
968
+ geometry = getFeatureByType(ringCoordinates, type);
969
+ }
970
+ if (geometry && geometryIntersection && !intersects2(geometry, geometryIntersection)) {
971
+ return;
972
+ }
973
+ const properties = parseProperties(tileProps);
974
+ if (storeGeometry && geometry) {
975
+ properties[FEATURE_GEOM_PROPERTY] = tileFormat === "mvt" /* MVT */ ? transformTileCoordsToWGS84(geometry, bbox) : geometry;
976
+ }
977
+ map.set(uniquePropertyValue, properties);
978
+ }
979
+ function addIntersectedFeaturesInTile({
980
+ map,
981
+ data,
982
+ geometryIntersection,
983
+ type,
984
+ bbox,
985
+ tileFormat,
986
+ uniqueIdProperty,
987
+ options
988
+ }) {
989
+ const indices = getIndices(data);
990
+ const storeGeometry = options?.storeGeometry || false;
991
+ for (let i = 0; i < indices.length - 1; i++) {
992
+ const startIndex = indices[i];
993
+ const endIndex = indices[i + 1];
994
+ processTileFeatureProperties({
995
+ map,
996
+ data,
997
+ startIndex,
998
+ endIndex,
999
+ type,
1000
+ bbox,
1001
+ tileFormat,
1002
+ uniqueIdProperty,
1003
+ storeGeometry,
1004
+ geometryIntersection
1005
+ });
1006
+ }
1007
+ }
1008
+ function getIndices(data) {
1009
+ let indices;
1010
+ switch (data.type) {
1011
+ case "Point":
1012
+ indices = data.pointIndices;
1013
+ break;
1014
+ case "LineString":
1015
+ indices = data.pathIndices;
1016
+ break;
1017
+ case "Polygon":
1018
+ indices = data.primitivePolygonIndices;
1019
+ break;
1020
+ default:
1021
+ throw new Error(`Unexpected type, "${data.type}"`);
1022
+ }
1023
+ return indices.value;
1024
+ }
1025
+ function getFeatureId(data, startIndex) {
1026
+ return data.featureIds.value[startIndex];
1027
+ }
1028
+ function getPropertiesFromTile(data, startIndex) {
1029
+ const featureId = getFeatureId(data, startIndex);
1030
+ const { properties, numericProps, fields } = data;
1031
+ const result = {
1032
+ uniqueId: fields?.[featureId]?.id,
1033
+ properties: properties[featureId],
1034
+ numericProps: {}
1035
+ };
1036
+ for (const key in numericProps) {
1037
+ result.numericProps[key] = numericProps[key].value[startIndex];
1038
+ }
1039
+ return result;
1040
+ }
1041
+ function parseProperties(tileProps) {
1042
+ const { properties, numericProps } = tileProps;
1043
+ return Object.assign({}, properties, numericProps);
1044
+ }
1045
+ function getUniquePropertyValue(tileProps, uniqueIdProperty, map) {
1046
+ if (uniqueIdProperty) {
1047
+ return getValueFromTileProps(tileProps, uniqueIdProperty);
1048
+ }
1049
+ if (tileProps.uniqueId) {
1050
+ return tileProps.uniqueId;
1051
+ }
1052
+ const artificialId = map.size + 1;
1053
+ return getValueFromTileProps(tileProps, "cartodb_id") || getValueFromTileProps(tileProps, "geoid") || artificialId;
1054
+ }
1055
+ function getValueFromTileProps(tileProps, propertyName) {
1056
+ const { properties, numericProps } = tileProps;
1057
+ return numericProps[propertyName] || properties[propertyName];
1058
+ }
1059
+ function getFeatureByType(coordinates, type) {
1060
+ switch (type) {
1061
+ case "Polygon":
1062
+ return { type: "Polygon", coordinates: [coordinates] };
1063
+ case "LineString":
1064
+ return { type: "LineString", coordinates };
1065
+ case "Point":
1066
+ return { type: "Point", coordinates: coordinates[0] };
1067
+ default:
1068
+ throw new Error("Invalid geometry type");
1069
+ }
1070
+ }
1071
+ function getRingCoordinatesFor(startIndex, endIndex, positions) {
1072
+ const ringCoordinates = [];
1073
+ for (let j = startIndex; j < endIndex; j++) {
1074
+ ringCoordinates.push(
1075
+ Array.from(
1076
+ positions.value.subarray(j * positions.size, (j + 1) * positions.size)
1077
+ )
1078
+ );
1079
+ }
1080
+ return ringCoordinates;
1081
+ }
1082
+ function calculateFeatures({
1083
+ map,
1084
+ tileIsFullyVisible,
1085
+ geometryIntersection,
1086
+ data,
1087
+ type,
1088
+ bbox,
1089
+ tileFormat,
1090
+ uniqueIdProperty,
1091
+ options
1092
+ }) {
1093
+ if (!data?.properties.length) {
1094
+ return;
1095
+ }
1096
+ if (tileIsFullyVisible) {
1097
+ addAllFeaturesInTile({
1098
+ map,
1099
+ data,
1100
+ type,
1101
+ bbox,
1102
+ tileFormat,
1103
+ uniqueIdProperty,
1104
+ options
1105
+ });
1106
+ } else {
1107
+ addIntersectedFeaturesInTile({
1108
+ map,
1109
+ data,
1110
+ geometryIntersection,
1111
+ type,
1112
+ bbox,
1113
+ tileFormat,
1114
+ uniqueIdProperty,
1115
+ options
1116
+ });
1117
+ }
1118
+ }
1119
+ function addAllFeaturesInTile({
1120
+ map,
1121
+ data,
1122
+ type,
1123
+ bbox,
1124
+ tileFormat,
1125
+ uniqueIdProperty,
1126
+ options
1127
+ }) {
1128
+ const indices = getIndices(data);
1129
+ const storeGeometry = options?.storeGeometry || false;
1130
+ for (let i = 0; i < indices.length - 1; i++) {
1131
+ const startIndex = indices[i];
1132
+ const endIndex = indices[i + 1];
1133
+ processTileFeatureProperties({
1134
+ map,
1135
+ data,
1136
+ startIndex,
1137
+ endIndex,
1138
+ type,
1139
+ bbox,
1140
+ tileFormat,
1141
+ uniqueIdProperty,
1142
+ storeGeometry
1143
+ });
1144
+ }
1145
+ }
1146
+ function createIndicesForPoints(data) {
1147
+ const featureIds = data.featureIds.value;
1148
+ const lastFeatureId = featureIds[featureIds.length - 1];
1149
+ const PointIndicesArray = featureIds.constructor;
1150
+ const pointIndices = {
1151
+ value: new PointIndicesArray(featureIds.length + 1),
1152
+ size: 1
1153
+ };
1154
+ pointIndices.value.set(featureIds);
1155
+ pointIndices.value.set([lastFeatureId + 1], featureIds.length);
1156
+ data.pointIndices = pointIndices;
1157
+ }
1158
+
1159
+ // node_modules/quadbin/dist/esm/index.js
1160
+ var import_tile_cover = __toESM(require_tile_cover(), 1);
1161
+ var B = [
1162
+ 0x5555555555555555n,
1163
+ 0x3333333333333333n,
1164
+ 0x0f0f0f0f0f0f0f0fn,
1165
+ 0x00ff00ff00ff00ffn,
1166
+ 0x0000ffff0000ffffn,
1167
+ 0x00000000ffffffffn
1168
+ ];
1169
+ var S = [0n, 1n, 2n, 4n, 8n, 16n];
1170
+ function tileToCell(tile) {
1171
+ if (tile.z < 0 || tile.z > 26) {
1172
+ throw new Error("Wrong zoom");
1173
+ }
1174
+ const z = BigInt(tile.z);
1175
+ let x = BigInt(tile.x) << 32n - z;
1176
+ let y = BigInt(tile.y) << 32n - z;
1177
+ for (let i = 0; i < 5; i++) {
1178
+ const s = S[5 - i];
1179
+ const b = B[4 - i];
1180
+ x = (x | x << s) & b;
1181
+ y = (y | y << s) & b;
1182
+ }
1183
+ const quadbin = 0x4000000000000000n | 1n << 59n | // | (mode << 59) | (mode_dep << 57)
1184
+ z << 52n | (x | y << 1n) >> 12n | 0xfffffffffffffn >> z * 2n;
1185
+ return quadbin;
1186
+ }
1187
+ function getResolution(quadbin) {
1188
+ return quadbin >> 52n & 0x1fn;
1189
+ }
1190
+ function geometryToCells(geometry, resolution) {
1191
+ const zoom = Number(resolution);
1192
+ return (0, import_tile_cover.tiles)(geometry, {
1193
+ min_zoom: zoom,
1194
+ max_zoom: zoom
1195
+ }).map(([x, y, z]) => tileToCell({ x, y, z }));
1196
+ }
1197
+
1198
+ // src/filters/tileFeaturesSpatialIndex.ts
1199
+ import bboxClip from "@turf/bbox-clip";
1200
+ import { getResolution as h3GetResolution, polygonToCells } from "h3-js";
1201
+ function tileFeaturesSpatialIndex({
1202
+ tiles: tiles2,
1203
+ spatialFilter,
1204
+ spatialDataColumn,
1205
+ spatialDataType
1206
+ }) {
1207
+ const map = /* @__PURE__ */ new Map();
1208
+ const spatialIndex = getSpatialIndex(spatialDataType);
1209
+ const resolution = getResolution2(tiles2, spatialIndex);
1210
+ const spatialIndexIDName = spatialDataColumn ? spatialDataColumn : spatialIndex;
1211
+ if (!resolution) {
1212
+ return [];
1213
+ }
1214
+ const cells = getCellsCoverGeometry(spatialFilter, spatialIndex, resolution);
1215
+ if (!cells?.length) {
1216
+ return [];
1217
+ }
1218
+ const cellsSet = new Set(cells);
1219
+ for (const tile of tiles2) {
1220
+ if (tile.isVisible === false || !tile.data) {
1221
+ continue;
1222
+ }
1223
+ tile.data.forEach((d) => {
1224
+ if (cellsSet.has(d.id)) {
1225
+ map.set(d.id, { ...d.properties, [spatialIndexIDName]: d.id });
1226
+ }
1227
+ });
1228
+ }
1229
+ return Array.from(map.values());
1230
+ }
1231
+ function getResolution2(tiles2, spatialIndex) {
1232
+ const data = tiles2.find((tile) => tile.data?.length)?.data;
1233
+ if (!data) {
1234
+ return;
1235
+ }
1236
+ if (spatialIndex === "quadbin" /* QUADBIN */) {
1237
+ return Number(getResolution(data[0].id));
1238
+ }
1239
+ if (spatialIndex === "h3" /* H3 */) {
1240
+ return h3GetResolution(data[0].id);
1241
+ }
1242
+ }
1243
+ var bboxWest = [-180, -90, 0, 90];
1244
+ var bboxEast = [0, -90, 180, 90];
1245
+ function getCellsCoverGeometry(geometry, spatialIndex, resolution) {
1246
+ if (spatialIndex === "quadbin" /* QUADBIN */) {
1247
+ return geometryToCells(geometry, resolution);
1248
+ }
1249
+ if (spatialIndex === "h3" /* H3 */) {
1250
+ return polygonToCells(
1251
+ bboxClip(geometry, bboxWest).geometry.coordinates,
1252
+ resolution,
1253
+ true
1254
+ ).concat(
1255
+ polygonToCells(
1256
+ bboxClip(geometry, bboxEast).geometry.coordinates,
1257
+ resolution,
1258
+ true
1259
+ )
1260
+ );
1261
+ }
1262
+ }
1263
+ function getSpatialIndex(spatialDataType) {
1264
+ switch (spatialDataType) {
1265
+ case "h3":
1266
+ return "h3" /* H3 */;
1267
+ case "quadbin":
1268
+ return "quadbin" /* QUADBIN */;
1269
+ default:
1270
+ throw new Error("Unexpected spatial data type");
1271
+ }
1272
+ }
1273
+
1274
+ // src/filters/tileFeatures.ts
1275
+ function tileFeatures({
1276
+ tiles: tiles2,
1277
+ spatialFilter,
1278
+ uniqueIdProperty,
1279
+ tileFormat,
1280
+ spatialDataColumn = DEFAULT_GEO_COLUMN,
1281
+ spatialDataType,
1282
+ options = {}
1283
+ }) {
1284
+ if (spatialDataType !== "geo") {
1285
+ return tileFeaturesSpatialIndex({
1286
+ tiles: tiles2,
1287
+ spatialFilter,
1288
+ spatialDataColumn,
1289
+ spatialDataType
1290
+ });
1291
+ }
1292
+ return tileFeaturesGeometries({
1293
+ tiles: tiles2,
1294
+ tileFormat,
1295
+ spatialFilter,
1296
+ uniqueIdProperty,
1297
+ options
1298
+ });
1299
+ }
1300
+
1301
+ // src/operations/aggregation.ts
1302
+ var aggregationFunctions = {
1303
+ count: (values) => values.length,
1304
+ min: (...args) => applyAggregationFunction(min, ...args),
1305
+ max: (...args) => applyAggregationFunction(max, ...args),
1306
+ sum: (...args) => applyAggregationFunction(sum, ...args),
1307
+ avg: (...args) => applyAggregationFunction(avg, ...args)
1308
+ };
1309
+ function aggregate(feature, keys, operation) {
1310
+ if (!keys?.length) {
1311
+ throw new Error("Cannot aggregate a feature without having keys");
1312
+ } else if (keys.length === 1) {
1313
+ const value = feature[keys[0]];
1314
+ return isPotentiallyValidNumber(value) ? Number(value) : value;
1315
+ }
1316
+ const aggregationFn = aggregationFunctions[operation];
1317
+ if (!aggregationFn) {
1318
+ throw new Error(`${operation} isn't a valid aggregation function`);
1319
+ }
1320
+ return aggregationFn(
1321
+ keys.map((column) => {
1322
+ const value = feature[column];
1323
+ return isPotentiallyValidNumber(value) ? Number(value) : value;
1324
+ })
1325
+ );
1326
+ }
1327
+ function isPotentiallyValidNumber(value) {
1328
+ return typeof value === "string" && value.trim().length > 0;
1329
+ }
1330
+ var applyAggregationFunction = (aggFn, values, keys, operation) => {
1331
+ const normalizedKeys = normalizeKeys(keys);
1332
+ const elements = (normalizedKeys?.length || 0) <= 1 ? filterFalsyElements(values, normalizedKeys || []) : values;
1333
+ return aggFn(elements, keys, operation);
1334
+ };
1335
+ function filterFalsyElements(values, keys) {
1336
+ const filterFn = (value) => value !== null && value !== void 0;
1337
+ if (!keys?.length) {
1338
+ return values.filter(filterFn);
1339
+ }
1340
+ return values.filter((v) => filterFn(v[keys[0]]));
1341
+ }
1342
+ function avg(values, keys, joinOperation) {
1343
+ return sum(values, keys, joinOperation) / (values.length || 1);
1344
+ }
1345
+ function sum(values, keys, joinOperation) {
1346
+ const normalizedKeys = normalizeKeys(keys);
1347
+ if (normalizedKeys) {
1348
+ return values.reduce(
1349
+ (a, b) => a + aggregate(b, normalizedKeys, joinOperation),
1350
+ 0
1351
+ );
1352
+ }
1353
+ return values.reduce((a, b) => a + b, 0);
1354
+ }
1355
+ function min(values, keys, joinOperation) {
1356
+ const normalizedKeys = normalizeKeys(keys);
1357
+ if (normalizedKeys) {
1358
+ return values.reduce(
1359
+ (a, b) => Math.min(a, aggregate(b, normalizedKeys, joinOperation)),
1360
+ Infinity
1361
+ );
1362
+ }
1363
+ return Math.min(...values);
1364
+ }
1365
+ function max(values, keys, joinOperation) {
1366
+ const normalizedKeys = normalizeKeys(keys);
1367
+ if (normalizedKeys) {
1368
+ return values.reduce(
1369
+ (a, b) => Math.max(a, aggregate(b, normalizedKeys, joinOperation)),
1370
+ -Infinity
1371
+ );
1372
+ }
1373
+ return Math.max(...values);
1374
+ }
1375
+ function normalizeKeys(keys) {
1376
+ return Array.isArray(keys) ? keys : typeof keys === "string" ? [keys] : void 0;
1377
+ }
1378
+
1379
+ // src/operations/applySorting.ts
1380
+ var import_thenby = __toESM(require_thenBy_module(), 1);
1381
+ function applySorting(features, {
1382
+ sortBy,
1383
+ sortByDirection = "asc",
1384
+ sortByColumnType = "string"
1385
+ } = {}) {
1386
+ if (sortBy === void 0) {
1387
+ return features;
1388
+ }
1389
+ const isValidSortBy = Array.isArray(sortBy) && sortBy.length || // sortBy can be an array of columns
1390
+ typeof sortBy === "string";
1391
+ if (!isValidSortBy) {
1392
+ throw new Error("Sorting options are bad formatted");
1393
+ }
1394
+ const sortFn = createSortFn({
1395
+ sortBy,
1396
+ sortByDirection,
1397
+ sortByColumnType: sortByColumnType || "string"
1398
+ });
1399
+ return features.sort(sortFn);
1400
+ }
1401
+ function createSortFn({
1402
+ sortBy,
1403
+ sortByDirection,
1404
+ sortByColumnType
1405
+ }) {
1406
+ const [firstSortOption, ...othersSortOptions] = normalizeSortByOptions({
1407
+ sortBy,
1408
+ sortByDirection,
1409
+ sortByColumnType
1410
+ });
1411
+ let sortFn = (0, import_thenby.firstBy)(...firstSortOption);
1412
+ for (const sortOptions of othersSortOptions) {
1413
+ sortFn = sortFn.thenBy(...sortOptions);
1414
+ }
1415
+ return sortFn;
1416
+ }
1417
+ function normalizeSortByOptions({
1418
+ sortBy,
1419
+ sortByDirection,
1420
+ sortByColumnType
1421
+ }) {
1422
+ const numberFormat = sortByColumnType === "number" && {
1423
+ cmp: (a, b) => a - b
1424
+ };
1425
+ if (!Array.isArray(sortBy)) {
1426
+ sortBy = [sortBy];
1427
+ }
1428
+ return sortBy.map((sortByEl) => {
1429
+ if (typeof sortByEl === "string") {
1430
+ return [sortByEl, { direction: sortByDirection, ...numberFormat }];
1431
+ }
1432
+ if (Array.isArray(sortByEl)) {
1433
+ if (sortByEl[1] === void 0) {
1434
+ return [sortByEl, { direction: sortByDirection, ...numberFormat }];
1435
+ }
1436
+ if (typeof sortByEl[1] === "object") {
1437
+ const othersSortOptions = numberFormat ? { ...numberFormat, ...sortByEl[1] } : sortByEl[1];
1438
+ return [
1439
+ sortByEl[0],
1440
+ { direction: sortByDirection, ...othersSortOptions }
1441
+ ];
1442
+ }
1443
+ }
1444
+ return sortByEl;
1445
+ });
1446
+ }
1447
+
1448
+ // src/operations/groupBy.ts
1449
+ function groupValuesByColumn({
1450
+ data,
1451
+ valuesColumns,
1452
+ joinOperation,
1453
+ keysColumn,
1454
+ operation
1455
+ }) {
1456
+ if (Array.isArray(data) && data.length === 0) {
1457
+ return null;
1458
+ }
1459
+ const groups = data.reduce((accumulator, item) => {
1460
+ const group = item[keysColumn];
1461
+ const values = accumulator.get(group) || [];
1462
+ accumulator.set(group, values);
1463
+ const aggregatedValue = aggregate(item, valuesColumns, joinOperation);
1464
+ const isValid = (operation === "count" ? true : aggregatedValue !== null) && aggregatedValue !== void 0;
1465
+ if (isValid) {
1466
+ values.push(aggregatedValue);
1467
+ accumulator.set(group, values);
1468
+ }
1469
+ return accumulator;
1470
+ }, /* @__PURE__ */ new Map());
1471
+ const targetOperation = aggregationFunctions[operation];
1472
+ if (targetOperation) {
1473
+ return Array.from(groups).map(([name, value]) => ({
1474
+ name,
1475
+ value: targetOperation(value)
1476
+ }));
1477
+ }
1478
+ return [];
1479
+ }
1480
+
1481
+ // src/utils/dateUtils.ts
1482
+ function getUTCMonday(date) {
1483
+ const dateCp = new Date(date);
1484
+ const day = dateCp.getUTCDay();
1485
+ const diff = dateCp.getUTCDate() - day + (day ? 1 : -6);
1486
+ dateCp.setUTCDate(diff);
1487
+ return Date.UTC(
1488
+ dateCp.getUTCFullYear(),
1489
+ dateCp.getUTCMonth(),
1490
+ dateCp.getUTCDate()
1491
+ );
1492
+ }
1493
+
1494
+ // src/operations/groupByDate.ts
1495
+ var GROUP_KEY_FN_MAPPING = {
1496
+ year: (date) => Date.UTC(date.getUTCFullYear()),
1497
+ month: (date) => Date.UTC(date.getUTCFullYear(), date.getUTCMonth()),
1498
+ week: (date) => getUTCMonday(date),
1499
+ day: (date) => Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()),
1500
+ hour: (date) => Date.UTC(
1501
+ date.getUTCFullYear(),
1502
+ date.getUTCMonth(),
1503
+ date.getUTCDate(),
1504
+ date.getUTCHours()
1505
+ ),
1506
+ minute: (date) => Date.UTC(
1507
+ date.getUTCFullYear(),
1508
+ date.getUTCMonth(),
1509
+ date.getUTCDate(),
1510
+ date.getUTCHours(),
1511
+ date.getUTCMinutes()
1512
+ ),
1513
+ second: (date) => Date.UTC(
1514
+ date.getUTCFullYear(),
1515
+ date.getUTCMonth(),
1516
+ date.getUTCDate(),
1517
+ date.getUTCHours(),
1518
+ date.getUTCMinutes(),
1519
+ date.getUTCSeconds()
1520
+ )
1521
+ };
1522
+ function groupValuesByDateColumn({
1523
+ data,
1524
+ valuesColumns,
1525
+ joinOperation,
1526
+ keysColumn,
1527
+ groupType,
1528
+ operation
1529
+ }) {
1530
+ if (Array.isArray(data) && data.length === 0) {
1531
+ return null;
1532
+ }
1533
+ const groupKeyFn = GROUP_KEY_FN_MAPPING[groupType];
1534
+ if (!groupKeyFn) {
1535
+ return null;
1536
+ }
1537
+ const groups = data.reduce((acc, item) => {
1538
+ const value = item[keysColumn];
1539
+ const formattedValue = new Date(value);
1540
+ const groupKey = groupKeyFn(formattedValue);
1541
+ if (!isNaN(groupKey)) {
1542
+ let groupedValues = acc.get(groupKey);
1543
+ if (!groupedValues) {
1544
+ groupedValues = [];
1545
+ acc.set(groupKey, groupedValues);
1546
+ }
1547
+ const aggregatedValue = aggregate(item, valuesColumns, joinOperation);
1548
+ const isValid = aggregatedValue !== null && aggregatedValue !== void 0;
1549
+ if (isValid) {
1550
+ groupedValues.push(aggregatedValue);
1551
+ acc.set(groupKey, groupedValues);
1552
+ }
1553
+ }
1554
+ return acc;
1555
+ }, /* @__PURE__ */ new Map());
1556
+ const targetOperation = aggregationFunctions[operation];
1557
+ return [...groups.entries()].map(([name, value]) => ({
1558
+ name,
1559
+ value: targetOperation(value)
1560
+ })).sort((a, b) => a.name - b.name);
1561
+ }
1562
+
1563
+ // src/operations/histogram.ts
1564
+ function histogram({
1565
+ data,
1566
+ valuesColumns,
1567
+ joinOperation,
1568
+ ticks,
1569
+ operation
1570
+ }) {
1571
+ if (Array.isArray(data) && data.length === 0) {
1572
+ return [];
1573
+ }
1574
+ const binsContainer = [Number.MIN_SAFE_INTEGER, ...ticks].map(
1575
+ (tick, index, arr) => ({
1576
+ bin: index,
1577
+ start: tick,
1578
+ end: index === arr.length - 1 ? Number.MAX_SAFE_INTEGER : arr[index + 1],
1579
+ values: []
1580
+ })
1581
+ );
1582
+ data.forEach((feature) => {
1583
+ const featureValue = aggregate(
1584
+ feature,
1585
+ valuesColumns,
1586
+ joinOperation
1587
+ );
1588
+ const isValid = featureValue !== null && featureValue !== void 0;
1589
+ if (!isValid) {
1590
+ return;
1591
+ }
1592
+ const binContainer = binsContainer.find(
1593
+ (bin) => bin.start <= featureValue && bin.end > featureValue
1594
+ );
1595
+ if (!binContainer) {
1596
+ return;
1597
+ }
1598
+ binContainer.values.push(featureValue);
1599
+ });
1600
+ const targetOperation = aggregationFunctions[operation];
1601
+ const transformedBins = binsContainer.map(
1602
+ (binContainer) => binContainer.values
1603
+ );
1604
+ return transformedBins.map(
1605
+ (values) => values.length ? targetOperation(values) : 0
1606
+ );
1607
+ }
1608
+
1609
+ // src/operations/scatterPlot.ts
1610
+ function scatterPlot({
1611
+ data,
1612
+ xAxisColumns,
1613
+ xAxisJoinOperation,
1614
+ yAxisColumns,
1615
+ yAxisJoinOperation
1616
+ }) {
1617
+ return data.reduce(
1618
+ (acc, feature) => {
1619
+ const xValue = aggregate(
1620
+ feature,
1621
+ xAxisColumns,
1622
+ xAxisJoinOperation
1623
+ );
1624
+ const xIsValid = xValue !== null && xValue !== void 0;
1625
+ const yValue = aggregate(
1626
+ feature,
1627
+ yAxisColumns,
1628
+ yAxisJoinOperation
1629
+ );
1630
+ const yIsValid = yValue !== null && yValue !== void 0;
1631
+ if (xIsValid && yIsValid) {
1632
+ acc.push([xValue, yValue]);
1633
+ }
1634
+ return acc;
1635
+ },
1636
+ []
1637
+ );
1638
+ }
1639
+
1640
+ // src/widget-sources/widget-tileset-source-impl.ts
1641
+ import { booleanEqual } from "@turf/boolean-equal";
1642
+ var WidgetTilesetSourceImpl = class extends WidgetSource {
1643
+ constructor() {
1644
+ super(...arguments);
1645
+ __publicField(this, "_tiles", []);
1646
+ __publicField(this, "_features", []);
1647
+ __publicField(this, "_tileFeatureExtractOptions", {});
1648
+ __publicField(this, "_tileFeatureExtractPreviousInputs", {});
1649
+ }
1650
+ /**
1651
+ * Loads features as a list of tiles (typically provided by deck.gl).
1652
+ * After tiles are loaded, {@link extractTileFeatures} must be called
1653
+ * before computing statistics on the tiles.
1654
+ */
1655
+ loadTiles(tiles2) {
1656
+ this._tiles = tiles2;
1657
+ this._features.length = 0;
1658
+ }
1659
+ /** Configures options used to extract features from tiles. */
1660
+ setTileFeatureExtractOptions(options) {
1661
+ this._tileFeatureExtractOptions = options;
1662
+ this._features.length = 0;
1663
+ }
1664
+ _extractTileFeatures(spatialFilter) {
1665
+ const prevInputs = this._tileFeatureExtractPreviousInputs;
1666
+ if (this._features.length && prevInputs.spatialFilter && booleanEqual(prevInputs.spatialFilter, spatialFilter)) {
1667
+ return;
1668
+ }
1669
+ this._features = tileFeatures({
1670
+ tiles: this._tiles,
1671
+ tileFormat: this.props.tileFormat,
1672
+ ...this._tileFeatureExtractOptions,
1673
+ spatialFilter,
1674
+ spatialDataColumn: this.props.spatialDataColumn,
1675
+ spatialDataType: this.props.spatialDataType
1676
+ });
1677
+ prevInputs.spatialFilter = spatialFilter;
1678
+ }
1679
+ /**
1680
+ * Loads features as GeoJSON (used for testing).
1681
+ * @experimental
1682
+ * @internal Not for public use. Spatial filters in other method calls will be ignored.
1683
+ */
1684
+ loadGeoJSON({
1685
+ geojson,
1686
+ spatialFilter
1687
+ }) {
1688
+ this._features = geojsonFeatures({
1689
+ geojson,
1690
+ spatialFilter,
1691
+ ...this._tileFeatureExtractOptions
1692
+ });
1693
+ this._tileFeatureExtractPreviousInputs.spatialFilter = spatialFilter;
1694
+ }
1695
+ async getFeatures() {
1696
+ throw new Error("getFeatures not supported for tilesets");
1697
+ }
1698
+ async getFormula({
1699
+ column = "*",
1700
+ operation = "count",
1701
+ joinOperation,
1702
+ filters,
1703
+ filterOwner,
1704
+ spatialFilter
1705
+ }) {
1706
+ if (operation === "custom") {
1707
+ throw new Error("Custom aggregation not supported for tilesets");
1708
+ }
1709
+ if (column && column !== "*" || operation !== "count") {
1710
+ assertColumn(this._features, column);
1711
+ }
1712
+ const filteredFeatures = this._getFilteredFeatures(
1713
+ spatialFilter,
1714
+ filters,
1715
+ filterOwner
1716
+ );
1717
+ if (filteredFeatures.length === 0 && operation !== "count") {
1718
+ return { value: null };
1719
+ }
1720
+ const targetOperation = aggregationFunctions[operation];
1721
+ return {
1722
+ value: targetOperation(filteredFeatures, column, joinOperation)
1723
+ };
1724
+ }
1725
+ async getHistogram({
1726
+ operation = "count",
1727
+ ticks,
1728
+ column,
1729
+ joinOperation,
1730
+ filters,
1731
+ filterOwner,
1732
+ spatialFilter
1733
+ }) {
1734
+ const filteredFeatures = this._getFilteredFeatures(
1735
+ spatialFilter,
1736
+ filters,
1737
+ filterOwner
1738
+ );
1739
+ if (!this._features.length) {
1740
+ return [];
1741
+ }
1742
+ assertColumn(this._features, column);
1743
+ return histogram({
1744
+ data: filteredFeatures,
1745
+ valuesColumns: normalizeColumns(column),
1746
+ joinOperation,
1747
+ ticks,
1748
+ operation
1749
+ });
1750
+ }
1751
+ async getCategories({
1752
+ column,
1753
+ operation = "count",
1754
+ operationColumn,
1755
+ joinOperation,
1756
+ filters,
1757
+ filterOwner,
1758
+ spatialFilter
1759
+ }) {
1760
+ const filteredFeatures = this._getFilteredFeatures(
1761
+ spatialFilter,
1762
+ filters,
1763
+ filterOwner
1764
+ );
1765
+ if (!filteredFeatures.length) {
1766
+ return [];
1767
+ }
1768
+ assertColumn(this._features, column, operationColumn);
1769
+ const groups = groupValuesByColumn({
1770
+ data: filteredFeatures,
1771
+ valuesColumns: normalizeColumns(operationColumn || column),
1772
+ joinOperation,
1773
+ keysColumn: column,
1774
+ operation
1775
+ });
1776
+ return groups || [];
1777
+ }
1778
+ async getScatter({
1779
+ xAxisColumn,
1780
+ yAxisColumn,
1781
+ xAxisJoinOperation,
1782
+ yAxisJoinOperation,
1783
+ filters,
1784
+ filterOwner,
1785
+ spatialFilter
1786
+ }) {
1787
+ const filteredFeatures = this._getFilteredFeatures(
1788
+ spatialFilter,
1789
+ filters,
1790
+ filterOwner
1791
+ );
1792
+ if (!filteredFeatures.length) {
1793
+ return [];
1794
+ }
1795
+ assertColumn(this._features, xAxisColumn, yAxisColumn);
1796
+ return scatterPlot({
1797
+ data: filteredFeatures,
1798
+ xAxisColumns: normalizeColumns(xAxisColumn),
1799
+ xAxisJoinOperation,
1800
+ yAxisColumns: normalizeColumns(yAxisColumn),
1801
+ yAxisJoinOperation
1802
+ });
1803
+ }
1804
+ async getTable({
1805
+ columns,
1806
+ searchFilterColumn,
1807
+ searchFilterText,
1808
+ sortBy,
1809
+ sortDirection,
1810
+ sortByColumnType,
1811
+ offset = 0,
1812
+ limit = 10,
1813
+ filters,
1814
+ filterOwner,
1815
+ spatialFilter
1816
+ }) {
1817
+ let filteredFeatures = this._getFilteredFeatures(
1818
+ spatialFilter,
1819
+ filters,
1820
+ filterOwner
1821
+ );
1822
+ if (!filteredFeatures.length) {
1823
+ return { rows: [], totalCount: 0 };
1824
+ }
1825
+ if (searchFilterColumn && searchFilterText) {
1826
+ filteredFeatures = filteredFeatures.filter(
1827
+ (row) => row[searchFilterColumn] && String(row[searchFilterColumn]).toLowerCase().includes(String(searchFilterText).toLowerCase())
1828
+ );
1829
+ }
1830
+ let rows = applySorting(filteredFeatures, {
1831
+ sortBy,
1832
+ sortByDirection: sortDirection,
1833
+ sortByColumnType
1834
+ });
1835
+ const totalCount = rows.length;
1836
+ rows = rows.slice(
1837
+ Math.min(offset, totalCount),
1838
+ Math.min(offset + limit, totalCount)
1839
+ );
1840
+ rows = rows.map((srcRow) => {
1841
+ const dstRow = {};
1842
+ for (const column of columns) {
1843
+ dstRow[column] = srcRow[column];
1844
+ }
1845
+ return dstRow;
1846
+ });
1847
+ return { rows, totalCount };
1848
+ }
1849
+ async getTimeSeries({
1850
+ column,
1851
+ stepSize,
1852
+ operation,
1853
+ operationColumn,
1854
+ joinOperation,
1855
+ filters,
1856
+ filterOwner,
1857
+ spatialFilter
1858
+ }) {
1859
+ const filteredFeatures = this._getFilteredFeatures(
1860
+ spatialFilter,
1861
+ filters,
1862
+ filterOwner
1863
+ );
1864
+ if (!filteredFeatures.length) {
1865
+ return { rows: [] };
1866
+ }
1867
+ assertColumn(this._features, column, operationColumn);
1868
+ const rows = groupValuesByDateColumn({
1869
+ data: filteredFeatures,
1870
+ valuesColumns: normalizeColumns(operationColumn || column),
1871
+ keysColumn: column,
1872
+ groupType: stepSize,
1873
+ operation,
1874
+ joinOperation
1875
+ }) || [];
1876
+ return { rows };
1877
+ }
1878
+ async getRange({
1879
+ column,
1880
+ filters,
1881
+ filterOwner,
1882
+ spatialFilter
1883
+ }) {
1884
+ assertColumn(this._features, column);
1885
+ const filteredFeatures = this._getFilteredFeatures(
1886
+ spatialFilter,
1887
+ filters,
1888
+ filterOwner
1889
+ );
1890
+ if (!this._features.length) {
1891
+ return null;
1892
+ }
1893
+ return {
1894
+ min: aggregationFunctions.min(filteredFeatures, column),
1895
+ max: aggregationFunctions.max(filteredFeatures, column)
1896
+ };
1897
+ }
1898
+ /****************************************************************************
1899
+ * INTERNAL
1900
+ */
1901
+ _getFilteredFeatures(spatialFilter, filters, filterOwner) {
1902
+ assert(spatialFilter, "spatialFilter required for tilesets");
1903
+ this._extractTileFeatures(spatialFilter);
1904
+ return applyFilters(
1905
+ this._features,
1906
+ getApplicableFilters(filterOwner, filters || this.props.filters),
1907
+ this.props.filtersLogicalOperator || "and"
1908
+ );
1909
+ }
1910
+ };
1911
+ function assertColumn(features, ...columnArgs) {
1912
+ const columns = Array.from(new Set(columnArgs.map(normalizeColumns).flat()));
1913
+ const featureKeys = Object.keys(features[0]);
1914
+ const invalidColumns = columns.filter(
1915
+ (column) => !featureKeys.includes(column)
1916
+ );
1917
+ if (invalidColumns.length) {
1918
+ throw new InvalidColumnError(
1919
+ `Missing column(s): ${invalidColumns.join(", ")}`
1920
+ );
1921
+ }
1922
+ }
1923
+ function normalizeColumns(columns) {
1924
+ return Array.isArray(columns) ? columns : typeof columns === "string" ? [columns] : [];
1925
+ }
1926
+
1927
+ // src/widget-sources/widget-tileset-source.ts
1928
+ var WidgetTilesetSource = class extends WidgetSource {
1929
+ constructor(props) {
1930
+ super(props);
1931
+ __publicField(this, "_localImpl", null);
1932
+ __publicField(this, "_workerImpl", null);
1933
+ __publicField(this, "_workerEnabled");
1934
+ __publicField(this, "_workerNextRequestId", 1);
1935
+ this._workerEnabled = (props.widgetSourceWorker ?? true) && true;
1936
+ this._localImpl = this._workerEnabled ? null : new WidgetTilesetSourceImpl(this.props);
1937
+ }
1938
+ destroy() {
1939
+ this._localImpl?.destroy();
1940
+ this._localImpl = null;
1941
+ this._workerImpl?.terminate();
1942
+ this._workerImpl = null;
1943
+ super.destroy();
1944
+ }
1945
+ /////////////////////////////////////////////////////////////////////////////
1946
+ // WEB WORKER MANAGEMENT
1947
+ /**
1948
+ * Returns an initialized Worker, to be reused for the lifecycle of this
1949
+ * source instance.
1950
+ */
1951
+ _getWorker() {
1952
+ if (this._workerImpl || this._localImpl) {
1953
+ return this._workerImpl;
1954
+ }
1955
+ try {
1956
+ this._workerImpl = new Worker(new URL("worker.js", import.meta.url), {
1957
+ type: "module",
1958
+ name: "cartowidgettileset"
1959
+ });
1960
+ this._workerImpl.postMessage({
1961
+ method: "init" /* INIT */,
1962
+ params: [this.props]
1963
+ });
1964
+ return this._workerImpl;
1965
+ } catch {
1966
+ this._workerEnabled = false;
1967
+ this._localImpl = new WidgetTilesetSourceImpl(this.props);
1968
+ return null;
1969
+ }
1970
+ }
1971
+ /** Executes a given method on the worker. */
1972
+ _executeWorkerMethod(method, params, signal) {
1973
+ const worker = this._getWorker();
1974
+ if (!worker) {
1975
+ return this._localImpl[method](...params);
1976
+ }
1977
+ const requestId = this._workerNextRequestId++;
1978
+ const options = params[0];
1979
+ if (options?.spatialIndexReferenceViewState) {
1980
+ const { zoom, latitude, longitude } = options.spatialIndexReferenceViewState;
1981
+ options.spatialIndexReferenceViewState = { zoom, latitude, longitude };
1982
+ }
1983
+ let resolve = null;
1984
+ let reject = null;
1985
+ function onMessage(e) {
1986
+ const response = e.data;
1987
+ if (response.requestId !== requestId) return;
1988
+ if (signal?.aborted) {
1989
+ reject(new Error(signal.reason));
1990
+ } else if (response.ok) {
1991
+ resolve(response.result);
1992
+ } else {
1993
+ reject(new Error(response.error));
1994
+ }
1995
+ }
1996
+ function onAbort() {
1997
+ reject(new Error(signal.reason));
1998
+ }
1999
+ worker.addEventListener("message", onMessage);
2000
+ signal?.addEventListener("abort", onAbort);
2001
+ const promise = new Promise((_resolve, _reject) => {
2002
+ resolve = _resolve;
2003
+ reject = _reject;
2004
+ worker.postMessage({
2005
+ requestId,
2006
+ method,
2007
+ params
2008
+ });
2009
+ });
2010
+ void promise.finally(() => {
2011
+ worker.removeEventListener("message", onMessage);
2012
+ signal?.removeEventListener("abort", onAbort);
2013
+ });
2014
+ return promise;
2015
+ }
2016
+ /////////////////////////////////////////////////////////////////////////////
2017
+ // DATA LOADING
2018
+ /**
2019
+ * Loads features as a list of tiles (typically provided by deck.gl).
2020
+ * After tiles are loaded, {@link extractTileFeatures} must be called
2021
+ * before computing statistics on the tiles.
2022
+ */
2023
+ loadTiles(tiles2) {
2024
+ const worker = this._getWorker();
2025
+ if (!worker) {
2026
+ return this._localImpl.loadTiles(tiles2);
2027
+ }
2028
+ tiles2 = tiles2.map(({ id, bbox, data }) => ({
2029
+ id,
2030
+ bbox,
2031
+ data
2032
+ }));
2033
+ worker.postMessage({
2034
+ method: "loadTiles" /* LOAD_TILES */,
2035
+ params: [tiles2]
2036
+ });
2037
+ }
2038
+ /** Configures options used to extract features from tiles. */
2039
+ setTileFeatureExtractOptions(options) {
2040
+ const worker = this._getWorker();
2041
+ if (!worker) {
2042
+ return this._localImpl?.setTileFeatureExtractOptions(options);
2043
+ }
2044
+ worker.postMessage({
2045
+ type: "setTileFeatureExtractOptions" /* SET_TILE_FEATURE_EXTRACT_OPTIONS */,
2046
+ params: [options]
2047
+ });
2048
+ }
2049
+ /**
2050
+ * Loads features as GeoJSON (used for testing).
2051
+ * @experimental
2052
+ * @internal Not for public use. Spatial filters in other method calls will be ignored.
2053
+ */
2054
+ loadGeoJSON({
2055
+ geojson,
2056
+ spatialFilter
2057
+ }) {
2058
+ const worker = this._getWorker();
2059
+ if (!worker) {
2060
+ return this._localImpl.loadGeoJSON({ geojson, spatialFilter });
2061
+ }
2062
+ worker.postMessage({
2063
+ method: "loadGeoJSON" /* LOAD_GEOJSON */,
2064
+ params: [{ geojson, spatialFilter }]
2065
+ });
2066
+ }
2067
+ /////////////////////////////////////////////////////////////////////////////
2068
+ // WIDGETS API
2069
+ // eslint-disable-next-line @typescript-eslint/require-await
2070
+ async getFeatures() {
2071
+ throw new Error("getFeatures not supported for tilesets");
2072
+ }
2073
+ async getFormula({
2074
+ signal,
2075
+ ...options
2076
+ }) {
2077
+ return this._executeWorkerMethod("getFormula" /* GET_FORMULA */, [options], signal);
2078
+ }
2079
+ async getHistogram({
2080
+ signal,
2081
+ ...options
2082
+ }) {
2083
+ return this._executeWorkerMethod("getHistogram" /* GET_HISTOGRAM */, [options], signal);
2084
+ }
2085
+ async getCategories({
2086
+ signal,
2087
+ ...options
2088
+ }) {
2089
+ return this._executeWorkerMethod("getCategories" /* GET_CATEGORIES */, [options], signal);
2090
+ }
2091
+ async getScatter({
2092
+ signal,
2093
+ ...options
2094
+ }) {
2095
+ return this._executeWorkerMethod("getScatter" /* GET_SCATTER */, [options], signal);
2096
+ }
2097
+ async getTable({
2098
+ signal,
2099
+ ...options
2100
+ }) {
2101
+ return this._executeWorkerMethod("getTable" /* GET_TABLE */, [options], signal);
2102
+ }
2103
+ async getTimeSeries({
2104
+ signal,
2105
+ ...options
2106
+ }) {
2107
+ return this._executeWorkerMethod("getTimeSeries" /* GET_TIME_SERIES */, [options], signal);
2108
+ }
2109
+ async getRange({
2110
+ signal,
2111
+ ...options
2112
+ }) {
2113
+ return this._executeWorkerMethod("getRange" /* GET_RANGE */, [options], signal);
2114
+ }
2115
+ };
4
2116
 
5
2117
  // src/workers/widget-tileset-worker.ts
6
2118
  var source;
7
2119
  addEventListener("message", (e) => {
8
2120
  const { method, params, requestId } = e.data;
9
2121
  if (method === "init" /* INIT */) {
10
- source = new WidgetTilesetSource(params[0]);
2122
+ source = new WidgetTilesetSource({
2123
+ ...params[0],
2124
+ widgetSourceWorker: false
2125
+ });
11
2126
  return;
12
2127
  }
13
2128
  if (!source) {