@deck.gl/carto 8.8.0-alpha.5 → 8.8.0-beta.2

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.
Files changed (109) hide show
  1. package/dist/dist.dev.js +13886 -13809
  2. package/dist/es5/api/layer-map.js +7 -5
  3. package/dist/es5/api/layer-map.js.map +1 -1
  4. package/dist/es5/layers/carto-layer.js.map +1 -1
  5. package/dist/es5/layers/carto-tile-layer.js.map +1 -1
  6. package/dist/es5/layers/h3-tile-layer.js +20 -10
  7. package/dist/es5/layers/h3-tile-layer.js.map +1 -1
  8. package/dist/es5/layers/h3-tileset-2d.js +4 -8
  9. package/dist/es5/layers/h3-tileset-2d.js.map +1 -1
  10. package/dist/es5/layers/quadkey-tile-layer.js +23 -12
  11. package/dist/es5/layers/quadkey-tile-layer.js.map +1 -1
  12. package/dist/es5/layers/quadkey-tileset-2d.js.map +1 -1
  13. package/dist/es5/layers/spatial-index-tile-layer.js +3 -0
  14. package/dist/es5/layers/spatial-index-tile-layer.js.map +1 -1
  15. package/dist/esm/api/layer-map.js +8 -6
  16. package/dist/esm/api/layer-map.js.map +1 -1
  17. package/dist/esm/layers/carto-layer.js.map +1 -1
  18. package/dist/esm/layers/carto-tile-layer.js.map +1 -1
  19. package/dist/esm/layers/h3-tile-layer.js +12 -6
  20. package/dist/esm/layers/h3-tile-layer.js.map +1 -1
  21. package/dist/esm/layers/h3-tileset-2d.js +5 -9
  22. package/dist/esm/layers/h3-tileset-2d.js.map +1 -1
  23. package/dist/esm/layers/quadkey-tile-layer.js +15 -8
  24. package/dist/esm/layers/quadkey-tile-layer.js.map +1 -1
  25. package/dist/esm/layers/quadkey-tileset-2d.js.map +1 -1
  26. package/dist/esm/layers/spatial-index-tile-layer.js +3 -0
  27. package/dist/esm/layers/spatial-index-tile-layer.js.map +1 -1
  28. package/dist.min.js +4 -4
  29. package/package.json +10 -9
  30. package/src/api/layer-map.ts +16 -7
  31. package/src/layers/carto-layer.ts +19 -7
  32. package/src/layers/carto-tile-layer.ts +3 -3
  33. package/src/layers/h3-tile-layer.ts +79 -0
  34. package/src/layers/{h3-tileset-2d.js → h3-tileset-2d.ts} +29 -26
  35. package/src/layers/quadkey-tile-layer.ts +69 -0
  36. package/src/layers/{quadkey-tileset-2d.js → quadkey-tileset-2d.ts} +10 -5
  37. package/src/layers/{spatial-index-tile-layer.js → spatial-index-tile-layer.ts} +9 -6
  38. package/typed/api/index.d.ts +4 -0
  39. package/typed/api/index.d.ts.map +1 -0
  40. package/typed/api/index.js +3 -0
  41. package/typed/api/layer-map.d.ts +54 -0
  42. package/typed/api/layer-map.d.ts.map +1 -0
  43. package/typed/api/layer-map.js +264 -0
  44. package/typed/api/maps-api-common.d.ts +65 -0
  45. package/typed/api/maps-api-common.d.ts.map +1 -0
  46. package/typed/api/maps-api-common.js +50 -0
  47. package/typed/api/maps-client.d.ts +18 -0
  48. package/typed/api/maps-client.d.ts.map +1 -0
  49. package/typed/api/maps-client.js +125 -0
  50. package/typed/api/maps-v3-client.d.ts +45 -0
  51. package/typed/api/maps-v3-client.d.ts.map +1 -0
  52. package/typed/api/maps-v3-client.js +304 -0
  53. package/typed/api/parseMap.d.ts +11 -0
  54. package/typed/api/parseMap.d.ts.map +1 -0
  55. package/typed/api/parseMap.js +178 -0
  56. package/typed/basemap.d.ts +10 -0
  57. package/typed/basemap.d.ts.map +1 -0
  58. package/typed/basemap.js +9 -0
  59. package/typed/config.d.ts +26 -0
  60. package/typed/config.d.ts.map +1 -0
  61. package/typed/config.js +35 -0
  62. package/typed/index.d.ts +12 -0
  63. package/typed/index.d.ts.map +1 -0
  64. package/typed/index.js +10 -0
  65. package/typed/layers/carto-layer.d.ts +96 -0
  66. package/typed/layers/carto-layer.d.ts.map +1 -0
  67. package/typed/layers/carto-layer.js +173 -0
  68. package/typed/layers/carto-tile-layer.d.ts +30 -0
  69. package/typed/layers/carto-tile-layer.d.ts.map +1 -0
  70. package/typed/layers/carto-tile-layer.js +105 -0
  71. package/typed/layers/h3-tile-layer.d.ts +21 -0
  72. package/typed/layers/h3-tile-layer.d.ts.map +1 -0
  73. package/typed/layers/h3-tile-layer.js +47 -0
  74. package/typed/layers/h3-tileset-2d.d.ts +18 -0
  75. package/typed/layers/h3-tileset-2d.d.ts.map +1 -0
  76. package/typed/layers/h3-tileset-2d.js +85 -0
  77. package/typed/layers/quadkey-tile-layer.d.ts +21 -0
  78. package/typed/layers/quadkey-tile-layer.d.ts.map +1 -0
  79. package/typed/layers/quadkey-tile-layer.js +42 -0
  80. package/typed/layers/quadkey-tileset-2d.d.ts +15 -0
  81. package/typed/layers/quadkey-tileset-2d.d.ts.map +1 -0
  82. package/typed/layers/quadkey-tileset-2d.js +36 -0
  83. package/typed/layers/schema/carto-tile.d.ts +44 -0
  84. package/typed/layers/schema/carto-tile.d.ts.map +1 -0
  85. package/typed/layers/schema/carto-tile.js +161 -0
  86. package/typed/layers/spatial-index-tile-layer.d.ts +12 -0
  87. package/typed/layers/spatial-index-tile-layer.d.ts.map +1 -0
  88. package/typed/layers/spatial-index-tile-layer.js +40 -0
  89. package/typed/package.json +6 -0
  90. package/typed/style/color-bins-style.d.ts +9 -0
  91. package/typed/style/color-bins-style.d.ts.map +1 -0
  92. package/typed/style/color-bins-style.js +12 -0
  93. package/typed/style/color-categories-style.d.ts +10 -0
  94. package/typed/style/color-categories-style.d.ts.map +1 -0
  95. package/typed/style/color-categories-style.js +16 -0
  96. package/typed/style/color-continuous-style.d.ts +9 -0
  97. package/typed/style/color-continuous-style.d.ts.map +1 -0
  98. package/typed/style/color-continuous-style.js +12 -0
  99. package/typed/style/palette.d.ts +7 -0
  100. package/typed/style/palette.d.ts.map +1 -0
  101. package/typed/style/palette.js +62 -0
  102. package/typed/style/utils.d.ts +8 -0
  103. package/typed/style/utils.d.ts.map +1 -0
  104. package/typed/style/utils.js +15 -0
  105. package/typed/utils.d.ts +2 -0
  106. package/typed/utils.d.ts.map +1 -0
  107. package/typed/utils.js +4 -0
  108. package/src/layers/h3-tile-layer.js +0 -52
  109. package/src/layers/quadkey-tile-layer.js +0 -47
@@ -0,0 +1,264 @@
1
+ import { deviation, extent, groupSort, median, variance } from 'd3-array';
2
+ import { rgb } from 'd3-color';
3
+ import { scaleLinear, scaleOrdinal, scaleLog, scalePoint, scaleQuantile, scaleQuantize, scaleSqrt, scaleThreshold } from 'd3-scale';
4
+ import { format as d3Format } from 'd3-format';
5
+ import moment from 'moment-timezone';
6
+ import { CPUGridLayer, HeatmapLayer, HexagonLayer } from '@deck.gl/aggregation-layers';
7
+ import { GeoJsonLayer } from '@deck.gl/layers';
8
+ import { H3HexagonLayer, MVTLayer } from '@deck.gl/geo-layers';
9
+ import CartoTileLayer from '../layers/carto-tile-layer';
10
+ import { TILE_FORMATS } from './maps-api-common';
11
+ import { assert } from '../utils';
12
+ const SCALE_FUNCS = {
13
+ linear: scaleLinear,
14
+ ordinal: scaleOrdinal,
15
+ log: scaleLog,
16
+ point: scalePoint,
17
+ quantile: scaleQuantile,
18
+ quantize: scaleQuantize,
19
+ sqrt: scaleSqrt,
20
+ custom: scaleThreshold
21
+ };
22
+ const UNKNOWN_COLOR = '#868d91';
23
+ export const AGGREGATION = {
24
+ average: 'MEAN',
25
+ maximum: 'MAX',
26
+ minimum: 'MIN',
27
+ sum: 'SUM'
28
+ };
29
+ export const OPACITY_MAP = {
30
+ getFillColor: 'opacity',
31
+ getLineColor: 'strokeOpacity',
32
+ getTextColor: 'opacity'
33
+ };
34
+ const AGGREGATION_FUNC = {
35
+ 'count unique': (values, accessor) => groupSort(values, v => v.length, accessor).length,
36
+ median,
37
+ // Unfortunately mode() is only available in d3-array@3+ which is ESM only
38
+ mode: (values, accessor) => groupSort(values, v => v.length, accessor).pop(),
39
+ stddev: deviation,
40
+ variance
41
+ };
42
+ const hexToRGBA = c => {
43
+ const { r, g, b, opacity } = rgb(c);
44
+ return [r, g, b, 255 * opacity];
45
+ };
46
+ // Kepler -> Deck.gl
47
+ const sharedPropMap = {
48
+ color: 'getFillColor',
49
+ isVisible: 'visible',
50
+ label: 'cartoLabel',
51
+ textLabel: {
52
+ alignment: 'getTextAlignmentBaseline',
53
+ anchor: 'getTextAnchor',
54
+ color: 'getTextColor',
55
+ size: 'getTextSize'
56
+ },
57
+ visConfig: {
58
+ enable3d: 'extruded',
59
+ elevationScale: 'elevationScale',
60
+ filled: 'filled',
61
+ strokeColor: 'getLineColor',
62
+ stroked: 'stroked',
63
+ thickness: 'getLineWidth',
64
+ radius: 'getPointRadius',
65
+ wireframe: 'wireframe'
66
+ }
67
+ };
68
+ const aggregationVisConfig = {
69
+ colorAggregation: x => ({ colorAggregation: AGGREGATION[x] || AGGREGATION.sum }),
70
+ colorRange: x => ({ colorRange: x.colors.map(hexToRGBA) }),
71
+ coverage: 'coverage',
72
+ elevationPercentile: ['elevationLowerPercentile', 'elevationUpperPercentile'],
73
+ percentile: ['lowerPercentile', 'upperPercentile']
74
+ };
75
+ const defaultProps = {
76
+ lineMiterLimit: 2,
77
+ lineWidthUnits: 'pixels',
78
+ pointRadiusUnits: 'pixels',
79
+ rounded: true,
80
+ wrapLongitude: false
81
+ };
82
+ function mergePropMaps(a = {}, b = {}) {
83
+ return { ...a, ...b, visConfig: { ...a.visConfig, ...b.visConfig } };
84
+ }
85
+ export function getLayer(type, config, dataset) {
86
+ if (type === 'mvt' || type === 'tileset') {
87
+ return getTileLayer(dataset);
88
+ }
89
+ const geoColumn = dataset?.geoColumn;
90
+ const getPosition = d => d[geoColumn].coordinates;
91
+ const hexagonId = config.columns?.hex_id;
92
+ const layerTypeDefs = {
93
+ point: {
94
+ Layer: GeoJsonLayer,
95
+ propMap: { visConfig: { outline: 'stroked' } }
96
+ },
97
+ geojson: {
98
+ Layer: GeoJsonLayer
99
+ },
100
+ grid: {
101
+ Layer: CPUGridLayer,
102
+ propMap: { visConfig: { ...aggregationVisConfig, worldUnitSize: x => ({ cellSize: 1000 * x }) } },
103
+ defaultProps: { getPosition }
104
+ },
105
+ heatmap: {
106
+ Layer: HeatmapLayer,
107
+ propMap: { visConfig: { ...aggregationVisConfig, radius: 'radiusPixels' } },
108
+ defaultProps: { getPosition }
109
+ },
110
+ hexagon: {
111
+ Layer: HexagonLayer,
112
+ propMap: { visConfig: { ...aggregationVisConfig, worldUnitSize: x => ({ radius: 1000 * x }) } },
113
+ defaultProps: { getPosition }
114
+ },
115
+ hexagonId: {
116
+ Layer: H3HexagonLayer,
117
+ propMap: { visConfig: { coverage: 'coverage' } },
118
+ defaultProps: { getHexagon: d => d[hexagonId], stroked: false }
119
+ }
120
+ };
121
+ const layer = layerTypeDefs[type];
122
+ assert(layer, `Unsupported layer type: ${type}`);
123
+ return {
124
+ ...layer,
125
+ propMap: mergePropMaps(sharedPropMap, layer.propMap),
126
+ defaultProps: { ...defaultProps, ...layer.defaultProps }
127
+ };
128
+ }
129
+ function getTileLayer(dataset) {
130
+ const { data: { tiles: [tileUrl] } } = dataset;
131
+ /* global URL */
132
+ const formatTiles = new URL(tileUrl).searchParams.get('formatTiles') || TILE_FORMATS.MVT;
133
+ return {
134
+ Layer: formatTiles === TILE_FORMATS.MVT ? MVTLayer : CartoTileLayer,
135
+ propMap: sharedPropMap,
136
+ defaultProps: {
137
+ ...defaultProps,
138
+ uniqueIdProperty: 'geoid',
139
+ formatTiles
140
+ }
141
+ };
142
+ }
143
+ function domainFromAttribute(attribute, scaleType) {
144
+ if (scaleType === 'ordinal' || scaleType === 'point') {
145
+ return attribute.categories.map(c => c.category).filter(c => c !== undefined && c !== null);
146
+ }
147
+ let { min } = attribute;
148
+ if (scaleType === 'log' && min === 0) {
149
+ min = 1e-5;
150
+ }
151
+ return [min, attribute.max];
152
+ }
153
+ function domainFromValues(values, scaleType) {
154
+ if (scaleType === 'ordinal') {
155
+ return groupSort(values, g => -g.length, d => d);
156
+ }
157
+ else if (scaleType === 'quantile') {
158
+ return values.sort((a, b) => a - b);
159
+ }
160
+ else if (scaleType === 'log') {
161
+ const [d0, d1] = extent(values);
162
+ return [d0 === 0 ? 1e-5 : d0, d1];
163
+ }
164
+ return extent(values);
165
+ }
166
+ function calculateDomain(data, name, scaleType) {
167
+ if (data.tilestats) {
168
+ // Tileset data type
169
+ const { attributes } = data.tilestats.layers[0];
170
+ const attribute = attributes.find(a => a.attribute === name);
171
+ return domainFromAttribute(attribute, scaleType);
172
+ }
173
+ else if (data.features) {
174
+ // GeoJSON data type
175
+ const values = data.features.map(({ properties }) => properties[name]);
176
+ return domainFromValues(values, scaleType);
177
+ }
178
+ else if (Array.isArray(data) && data[0][name] !== undefined) {
179
+ // JSON data type
180
+ const values = data.map(properties => properties[name]);
181
+ return domainFromValues(values, scaleType);
182
+ }
183
+ return [0, 1];
184
+ }
185
+ function normalizeAccessor(accessor, data) {
186
+ if (data.features || data.tilestats) {
187
+ return ({ properties }) => {
188
+ return accessor(properties);
189
+ };
190
+ }
191
+ return accessor;
192
+ }
193
+ export function opacityToAlpha(opacity) {
194
+ return opacity !== undefined ? Math.round(255 * Math.pow(opacity, 1 / 2.2)) : 255;
195
+ }
196
+ export function getColorValueAccessor({ name }, colorAggregation, data) {
197
+ const aggregator = AGGREGATION_FUNC[colorAggregation];
198
+ const accessor = values => aggregator(values, p => p[name]);
199
+ return normalizeAccessor(accessor, data);
200
+ }
201
+ export function getColorAccessor({ name }, scaleType, { colors, colorMap }, opacity, data) {
202
+ const scale = SCALE_FUNCS[scaleType]();
203
+ let domain = [];
204
+ let scaleColor = [];
205
+ if (Array.isArray(colorMap)) {
206
+ colorMap.forEach(([value, color]) => {
207
+ domain.push(value);
208
+ scaleColor.push(color);
209
+ });
210
+ }
211
+ else {
212
+ domain = calculateDomain(data, name, scaleType);
213
+ scaleColor = colors;
214
+ }
215
+ if (scaleType === 'ordinal') {
216
+ domain = domain.slice(0, scaleColor.length);
217
+ }
218
+ scale.domain(domain);
219
+ scale.range(scaleColor);
220
+ scale.unknown(UNKNOWN_COLOR);
221
+ const alpha = opacityToAlpha(opacity);
222
+ const accessor = properties => {
223
+ const propertyValue = properties[name];
224
+ const { r, g, b } = rgb(scale(propertyValue));
225
+ return [r, g, b, propertyValue === null ? 0 : alpha];
226
+ };
227
+ return normalizeAccessor(accessor, data);
228
+ }
229
+ export function getSizeAccessor({ name }, scaleType, range, data) {
230
+ const scale = SCALE_FUNCS[scaleType]();
231
+ scale.domain(calculateDomain(data, name, scaleType));
232
+ scale.range(range);
233
+ const accessor = properties => {
234
+ return scale(properties[name]);
235
+ };
236
+ return normalizeAccessor(accessor, data);
237
+ }
238
+ const FORMATS = {
239
+ date: s => moment.utc(s).format('MM/DD/YY HH:mm:ssa'),
240
+ integer: d3Format('i'),
241
+ float: d3Format('.5f'),
242
+ timestamp: s => moment.utc(s).format('X'),
243
+ default: String
244
+ };
245
+ export function getTextAccessor({ name, type }, data) {
246
+ const format = FORMATS[type] || FORMATS.default;
247
+ const accessor = properties => {
248
+ return format(properties[name]);
249
+ };
250
+ return normalizeAccessor(accessor, data);
251
+ }
252
+ export function getTextPixelOffsetAccessor({ alignment, anchor, size }, radius) {
253
+ const padding = 20;
254
+ const signX = anchor === 'middle' ? 0 : anchor === 'start' ? 1 : -1;
255
+ const signY = alignment === 'center' ? 0 : alignment === 'bottom' ? 1 : -1;
256
+ const sizeOffset = alignment === 'center' ? 0 : size;
257
+ const calculateOffset = r => [signX * (r + padding), signY * (r + padding + sizeOffset)];
258
+ return typeof radius === 'function'
259
+ ? d => {
260
+ return calculateOffset(radius(d));
261
+ }
262
+ : calculateOffset(radius);
263
+ }
264
+ export { domainFromValues as _domainFromValues };
@@ -0,0 +1,65 @@
1
+ export declare const DEFAULT_USER_COMPONENT_IN_URL = "{user}";
2
+ export declare const DEFAULT_REGION_COMPONENT_IN_URL = "{region}";
3
+ export declare type ValuesOf<T extends {}> = T[keyof T];
4
+ export declare const API_VERSIONS: {
5
+ readonly V1: "v1";
6
+ readonly V2: "v2";
7
+ readonly V3: "v3";
8
+ };
9
+ export declare type ApiVersion = ValuesOf<typeof API_VERSIONS>;
10
+ export declare const DEFAULT_MAPS_URL_FORMAT: {
11
+ readonly v1: "https://{user}.carto.com/api/v1/map";
12
+ readonly v2: "https://maps-api-v2.{region}.carto.com/user/{user}";
13
+ };
14
+ export declare const MAP_TYPES: {
15
+ readonly QUERY: "query";
16
+ readonly TABLE: "table";
17
+ readonly TILESET: "tileset";
18
+ };
19
+ export declare type MapType = ValuesOf<typeof MAP_TYPES>;
20
+ export declare const COLUMNS_SUPPORT: MapType[];
21
+ export declare const GEO_COLUMN_SUPPORT: MapType[];
22
+ export declare const FORMATS: {
23
+ readonly GEOJSON: "geojson";
24
+ readonly NDJSON: "ndjson";
25
+ readonly TILEJSON: "tilejson";
26
+ readonly JSON: "json";
27
+ };
28
+ export declare type Format = ValuesOf<typeof FORMATS>;
29
+ export declare const TILE_FORMATS: {
30
+ readonly MVT: "mvt";
31
+ readonly JSON: "json";
32
+ readonly GEOJSON: "geojson";
33
+ readonly BINARY: "binary";
34
+ };
35
+ export declare type TileFormat = ValuesOf<typeof TILE_FORMATS>;
36
+ export declare enum SchemaFieldType {
37
+ Number = "number",
38
+ Bigint = "bigint",
39
+ String = "string",
40
+ Geometry = "geometry",
41
+ Timestamp = "timestamp",
42
+ Object = "object",
43
+ Boolean = "boolean",
44
+ Variant = "variant",
45
+ Unknown = "unknown"
46
+ }
47
+ export interface SchemaField {
48
+ name: string;
49
+ type: SchemaFieldType;
50
+ }
51
+ export interface MapInstantiation extends MapInstantiationFormats {
52
+ nrows: number;
53
+ size?: number;
54
+ schema: SchemaField[];
55
+ }
56
+ declare type MapInstantiationFormats = Record<Format, {
57
+ url: string[];
58
+ error?: any;
59
+ }>;
60
+ /**
61
+ * Simple encode parameter
62
+ */
63
+ export declare function encodeParameter(name: string, value: string | boolean | number): string;
64
+ export {};
65
+ //# sourceMappingURL=maps-api-common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maps-api-common.d.ts","sourceRoot":"","sources":["../../src/api/maps-api-common.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,6BAA6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AG,CAAC;CACb,CACF,CAAC;AAEF;;GAEG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAEtF"}
@@ -0,0 +1,50 @@
1
+ export const DEFAULT_USER_COMPONENT_IN_URL = '{user}';
2
+ export const DEFAULT_REGION_COMPONENT_IN_URL = '{region}';
3
+ export const API_VERSIONS = {
4
+ V1: 'v1',
5
+ V2: 'v2',
6
+ V3: 'v3'
7
+ };
8
+ export const DEFAULT_MAPS_URL_FORMAT = {
9
+ [API_VERSIONS.V1]: `https://${DEFAULT_USER_COMPONENT_IN_URL}.carto.com/api/v1/map`,
10
+ [API_VERSIONS.V2]: `https://maps-api-v2.${DEFAULT_REGION_COMPONENT_IN_URL}.carto.com/user/${DEFAULT_USER_COMPONENT_IN_URL}`
11
+ };
12
+ export const MAP_TYPES = {
13
+ QUERY: 'query',
14
+ TABLE: 'table',
15
+ TILESET: 'tileset'
16
+ };
17
+ export const COLUMNS_SUPPORT = [MAP_TYPES.TABLE];
18
+ export const GEO_COLUMN_SUPPORT = [MAP_TYPES.QUERY, MAP_TYPES.TABLE];
19
+ // AVAILABLE FORMATS
20
+ export const FORMATS = {
21
+ GEOJSON: 'geojson',
22
+ NDJSON: 'ndjson',
23
+ TILEJSON: 'tilejson',
24
+ JSON: 'json'
25
+ };
26
+ // AVAILABLE FORMATS FOR TILES
27
+ export const TILE_FORMATS = {
28
+ MVT: 'mvt',
29
+ JSON: 'json',
30
+ GEOJSON: 'geojson',
31
+ BINARY: 'binary'
32
+ };
33
+ export var SchemaFieldType;
34
+ (function (SchemaFieldType) {
35
+ SchemaFieldType["Number"] = "number";
36
+ SchemaFieldType["Bigint"] = "bigint";
37
+ SchemaFieldType["String"] = "string";
38
+ SchemaFieldType["Geometry"] = "geometry";
39
+ SchemaFieldType["Timestamp"] = "timestamp";
40
+ SchemaFieldType["Object"] = "object";
41
+ SchemaFieldType["Boolean"] = "boolean";
42
+ SchemaFieldType["Variant"] = "variant";
43
+ SchemaFieldType["Unknown"] = "unknown";
44
+ })(SchemaFieldType || (SchemaFieldType = {}));
45
+ /**
46
+ * Simple encode parameter
47
+ */
48
+ export function encodeParameter(name, value) {
49
+ return `${name}=${encodeURIComponent(value)}`;
50
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Maps API Client for Maps API v1 and Maps API v2
3
+ */
4
+ import { ClassicCredentials } from '../config';
5
+ import { MapType } from './maps-api-common';
6
+ export declare const CONNECTIONS: {
7
+ BIGQUERY: string;
8
+ CARTO: string;
9
+ };
10
+ /**
11
+ * Obtain a TileJson from Maps API v1 and v2
12
+ */
13
+ export declare function getDataV2({ type, source, credentials }: {
14
+ type: MapType;
15
+ source: string;
16
+ credentials?: Partial<ClassicCredentials>;
17
+ }): Promise<any>;
18
+ //# sourceMappingURL=maps-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maps-client.d.ts","sourceRoot":"","sources":["../../src/api/maps-client.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EACL,kBAAkB,EAInB,MAAM,WAAW,CAAC;AACnB,OAAO,EAML,OAAO,EAER,MAAM,mBAAmB,CAAC;AAE3B,eAAO,MAAM,WAAW;;;CAGvB,CAAC;AAKF;;GAEG;AACH,wBAAsB,SAAS,CAAC,EAC9B,IAAI,EACJ,MAAM,EACN,WAAW,EACZ,EAAE;IACD,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;CAC3C,gBAkCA"}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Maps API Client for Maps API v1 and Maps API v2
3
+ */
4
+ import { defaultClassicCredentials, defaultCloudNativeCredentials, getDefaultCredentials } from '../config';
5
+ import { API_VERSIONS, DEFAULT_MAPS_URL_FORMAT, DEFAULT_REGION_COMPONENT_IN_URL, DEFAULT_USER_COMPONENT_IN_URL, encodeParameter, MAP_TYPES } from './maps-api-common';
6
+ export const CONNECTIONS = {
7
+ BIGQUERY: 'bigquery',
8
+ CARTO: 'carto'
9
+ };
10
+ const BUFFER_SIZE = 16;
11
+ const TILE_EXTENT = 4096;
12
+ /**
13
+ * Obtain a TileJson from Maps API v1 and v2
14
+ */
15
+ export async function getDataV2({ type, source, credentials }) {
16
+ const defaultCredentials = getDefaultCredentials();
17
+ const apiVersion = credentials?.apiVersion || defaultCredentials.apiVersion;
18
+ // Only pick up default credentials if they have been defined for
19
+ // correct API version
20
+ const localCreds = {
21
+ ...(apiVersion === API_VERSIONS.V3 ? defaultCloudNativeCredentials : defaultClassicCredentials),
22
+ mapsUrl: DEFAULT_MAPS_URL_FORMAT[apiVersion],
23
+ ...(defaultCredentials.apiVersion === apiVersion && defaultCredentials),
24
+ ...credentials
25
+ };
26
+ let url;
27
+ const connection = type === MAP_TYPES.TILESET ? CONNECTIONS.BIGQUERY : CONNECTIONS.CARTO;
28
+ switch (apiVersion) {
29
+ case API_VERSIONS.V1:
30
+ // Maps API v1
31
+ const mapConfig = createMapConfig(source);
32
+ url = buildURLMapsAPIv1({ mapConfig, credentials: localCreds });
33
+ const layergroup = await request({ url, credentials: localCreds });
34
+ return layergroup.metadata.tilejson.vector;
35
+ case API_VERSIONS.V2:
36
+ // Maps API v2
37
+ url = buildURLMapsAPIv2({ connection, type, source, credentials: localCreds });
38
+ return await request({ url, credentials: localCreds });
39
+ default:
40
+ throw new Error(`Invalid maps API version. It should be ${API_VERSIONS.V1} or ${API_VERSIONS.V2}`);
41
+ }
42
+ }
43
+ /**
44
+ * Request against Maps API
45
+ */
46
+ async function request({ url, credentials }) {
47
+ let response;
48
+ try {
49
+ /* global fetch */
50
+ response = await fetch(url, {
51
+ headers: {
52
+ Accept: 'application/json'
53
+ }
54
+ });
55
+ }
56
+ catch (error) {
57
+ throw new Error(`Failed to connect to Maps API: ${error}`);
58
+ }
59
+ const json = await response.json();
60
+ if (!response.ok) {
61
+ dealWithError({ response, json, credentials });
62
+ }
63
+ return json;
64
+ }
65
+ /**
66
+ * Display proper message from Maps API error
67
+ */
68
+ function dealWithError({ response, json, credentials }) {
69
+ switch (response.status) {
70
+ case 401:
71
+ throw new Error(`Unauthorized access to Maps API: invalid combination of user ('${credentials.username}') and apiKey ('${credentials.apiKey}')`);
72
+ case 403:
73
+ throw new Error(`Unauthorized access to dataset: the provided apiKey('${credentials.apiKey}') doesn't provide access to the requested data`);
74
+ default:
75
+ const e = credentials.apiVersion === API_VERSIONS.V1 ? JSON.stringify(json.errors) : json.error;
76
+ throw new Error(e);
77
+ }
78
+ }
79
+ function initURLParameters(credentials) {
80
+ const encodedApiKey = encodeParameter('api_key', credentials.apiKey);
81
+ const encodedClient = encodeParameter('client', 'deck-gl-carto');
82
+ return [encodedApiKey, encodedClient];
83
+ }
84
+ /**
85
+ * Build a URL with all required parameters
86
+ */
87
+ function buildURLMapsAPIv1({ mapConfig, credentials }) {
88
+ const parameters = initURLParameters(credentials);
89
+ const cfg = JSON.stringify(mapConfig);
90
+ return `${mapsUrl(credentials)}?${parameters.join('&')}&${encodeParameter('config', cfg)}`;
91
+ }
92
+ function buildURLMapsAPIv2({ connection, type, source, credentials }) {
93
+ const parameters = initURLParameters(credentials);
94
+ // Query type is mapped to 'sql' at maps api v1
95
+ const mapsApiType = type === MAP_TYPES.QUERY ? 'sql' : type;
96
+ let url = `${mapsUrl(credentials)}/${connection}/${mapsApiType}?`;
97
+ url += `${encodeParameter('source', source)}&format=tilejson&${parameters.join('&')}`;
98
+ return url;
99
+ }
100
+ /**
101
+ * Prepare a url valid for the specified user
102
+ */
103
+ function mapsUrl(credentials) {
104
+ return credentials.mapsUrl
105
+ .replace(DEFAULT_USER_COMPONENT_IN_URL, credentials.username)
106
+ .replace(DEFAULT_REGION_COMPONENT_IN_URL, credentials.region);
107
+ }
108
+ function createMapConfig(sql) {
109
+ return {
110
+ version: '1.3.1',
111
+ buffersize: {
112
+ mvt: BUFFER_SIZE
113
+ },
114
+ layers: [
115
+ {
116
+ type: 'mapnik',
117
+ options: {
118
+ sql,
119
+ // eslint-disable-next-line camelcase
120
+ vector_extent: TILE_EXTENT
121
+ }
122
+ }
123
+ ]
124
+ };
125
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Maps API Client for Carto 3
3
+ */
4
+ import { CloudNativeCredentials } from '../config';
5
+ import { Format, MapInstantiation, MapType, SchemaField, TileFormat } from './maps-api-common';
6
+ declare type FetchLayerDataParams = {
7
+ type: MapType;
8
+ source: string;
9
+ connection: string;
10
+ credentials: CloudNativeCredentials;
11
+ geoColumn?: string;
12
+ columns?: string[];
13
+ clientId?: string;
14
+ format?: Format;
15
+ formatTiles?: TileFormat;
16
+ aggregationExp?: string;
17
+ aggregationResLevel?: number;
18
+ };
19
+ export declare function mapInstantiation({ type, source, connection, credentials, geoColumn, columns, clientId, aggregationExp, aggregationResLevel }: FetchLayerDataParams): Promise<MapInstantiation>;
20
+ export interface FetchLayerDataResult {
21
+ data: any;
22
+ format?: Format;
23
+ schema: SchemaField[];
24
+ }
25
+ export declare function fetchLayerData({ type, source, connection, credentials, geoColumn, columns, format, formatTiles, clientId, aggregationExp, aggregationResLevel }: FetchLayerDataParams): Promise<FetchLayerDataResult>;
26
+ export declare function getData({ type, source, connection, credentials, geoColumn, columns, format, clientId }: FetchLayerDataParams): Promise<any>;
27
+ export declare function fetchMap({ cartoMapId, clientId, credentials, autoRefresh, onNewData }: {
28
+ cartoMapId: string;
29
+ clientId: string;
30
+ credentials?: CloudNativeCredentials;
31
+ autoRefresh?: number;
32
+ onNewData?: (map: any) => void;
33
+ }): Promise<{
34
+ stopAutoRefresh: (() => void) | undefined;
35
+ id: any;
36
+ title: any;
37
+ description: any;
38
+ createdAt: any;
39
+ updatedAt: any;
40
+ initialViewState: any;
41
+ mapStyle: any;
42
+ layers: (import("@deck.gl/core").Layer<{}> | undefined)[];
43
+ }>;
44
+ export {};
45
+ //# sourceMappingURL=maps-v3-client.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