@urban-toolkit/autk-grammar 4.4.1 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,327 +1,601 @@
1
- import { AutkDb as z, DEFAULT_WORKSPACE_COORDINATE_FORMAT as k } from "@urban-toolkit/autk-db";
2
- import { AutkMap as Z, MapEvent as B } from "@urban-toolkit/autk-map";
3
- import { AutkPlot as tt, PlotEvent as I } from "@urban-toolkit/autk-plot";
4
- import { ColorMapInterpolator as et, ColorMapDomainStrategy as M, ColorMap as v } from "@urban-toolkit/autk-core";
5
- import { AutkComputeEngine as rt } from "@urban-toolkit/autk-compute";
6
- function ot(t) {
1
+ import { DEFAULT_WORKSPACE_NAME as j, isVectorTable as Nt, AutkDb as Tt, isRenderableTable as dt, DEFAULT_WORKSPACE_COORDINATE_FORMAT as $t } from "@urban-toolkit/autk-db";
2
+ import { AutkMap as Ot, MapEvent as Q } from "@urban-toolkit/autk-map";
3
+ import { AutkPlot as kt, PlotEvent as k } from "@urban-toolkit/autk-plot";
4
+ import { ColorMapInterpolator as Ft, ColorMapDomainStrategy as P, ColorMap as B } from "@urban-toolkit/autk-core";
5
+ import { AutkComputeEngine as Z } from "@urban-toolkit/autk-compute";
6
+ function Bt(t) {
7
7
  const { spec: e, adapters: r } = t;
8
8
  let o;
9
- async function i() {
10
- let a;
11
- if (e.data)
12
- for (const s of e.data)
13
- a = await r.db.resolveSource(a, s);
9
+ async function n() {
10
+ let i;
11
+ if (e.workspaces?.length && r.db.resolveWorkspaces && (i = await r.db.resolveWorkspaces(i, e.workspaces)), e.data)
12
+ for (const l of e.data)
13
+ i = await r.db.resolveSource(i, l);
14
14
  if (e.compute)
15
- for (const s of e.compute)
16
- a = await r.compute.resolveCompute(a, s);
15
+ for (const l of e.compute)
16
+ i = await r.compute.resolveCompute(i, l);
17
17
  if (e.map)
18
18
  if (Array.isArray(e.map))
19
- for (let s = 0; s < e.map.length; s++) {
20
- let u = e.map[s];
21
- await r.map.resolveMap(a, u, s);
19
+ for (let l = 0; l < e.map.length; l++) {
20
+ let u = e.map[l];
21
+ await r.map.resolveMap(i, u, l);
22
22
  }
23
23
  else
24
- await r.map.resolveMap(a, e.map);
24
+ await r.map.resolveMap(i, e.map);
25
25
  if (e.plot)
26
26
  if (Array.isArray(e.plot))
27
- for (const s of e.plot)
28
- await r.plot.resolvePlot(a, s);
27
+ for (let l = 0; l < e.plot.length; l++)
28
+ await r.plot.resolvePlot(i, e.plot[l], l);
29
29
  else
30
- await r.plot.resolvePlot(a, e.plot);
31
- o = a;
30
+ await r.plot.resolvePlot(i, e.plot);
31
+ o = i;
32
32
  }
33
- function n(a) {
34
- return console.log("Spec to update", a), new Promise((s) => {
35
- s();
33
+ function s(i) {
34
+ return console.log("Spec to update", i), new Promise((l) => {
35
+ l();
36
36
  });
37
37
  }
38
- function l() {
38
+ function a() {
39
39
  console.log("Function not implemented yet");
40
40
  }
41
- return { run: i, updatedSpec: n, destroy: l, get context() {
41
+ return { run: n, updatedSpec: s, destroy: a, get context() {
42
42
  return o;
43
43
  } };
44
44
  }
45
- var nt = /* @__PURE__ */ ((t) => (t.CAT_ACCENT = "schemeAccent", t.CAT_DARK2 = "schemeDark2", t.CAT_CATEGORY10 = "schemeCategory10", t.CAT_OBSERVABLE10 = "schemeObservable10", t.CAT_PAIRED = "schemePaired", t.CAT_PASTEL1 = "schemePastel1", t.CAT_PASTEL2 = "schemePastel2", t.CAT_SET1 = "schemeSet1", t.CAT_SET2 = "schemeSet2", t.CAT_SET3 = "schemeSet3", t.CAT_TABLEAU10 = "schemeTableau10", t.SEQ_REDS = "interpolateReds", t.SEQ_BLUES = "interpolateBlues", t.SEQ_GREENS = "interpolateGreens", t.SEQ_GREYS = "interpolateGreys", t.SEQ_ORANGES = "interpolateOranges", t.SEQ_PURPLES = "interpolatePurples", t.SEQ_TURBO = "interpolateTurbo", t.SEQ_VIRIDIS = "interpolateViridis", t.SEQ_INFERNO = "interpolateInferno", t.SEQ_MAGMA = "interpolateMagma", t.SEQ_PLASMA = "interpolatePlasma", t.SEQ_CIVIDIS = "interpolateCividis", t.SEQ_WARM = "interpolateWarm", t.SEQ_COOL = "interpolateCool", t.SEQ_CUBEHELIX_DEFAULT = "interpolateCubehelixDefault", t.SEQ_BU_GN = "interpolateBuGn", t.SEQ_BU_PU = "interpolateBuPu", t.SEQ_GN_BU = "interpolateGnBu", t.SEQ_OR_RD = "interpolateOrRd", t.SEQ_PU_BU_GN = "interpolatePuBuGn", t.SEQ_PU_BU = "interpolatePuBu", t.SEQ_PU_RD = "interpolatePuRd", t.SEQ_RD_PU = "interpolateRdPu", t.SEQ_YL_GN_BU = "interpolateYlGnBu", t.SEQ_YL_GN = "interpolateYlGn", t.SEQ_YL_OR_BR = "interpolateYlOrBr", t.SEQ_YL_OR_RD = "interpolateYlOrRd", t.DIV_BR_BG = "interpolateBrBG", t.DIV_PR_GN = "interpolatePRGn", t.DIV_PI_YG = "interpolatePiYG", t.DIV_PU_OR = "interpolatePuOr", t.DIV_RED_BLUE = "interpolateRdBu", t.DIV_RED_GREY = "interpolateRdGy", t.DIV_RED_YELLOW_BLUE = "interpolateRdYlBu", t.DIV_RED_YELLOW_GREEN = "interpolateRdYlGn", t.DIV_SPECTRAL = "interpolateSpectral", t))(nt || {}), H = /* @__PURE__ */ ((t) => (t.MIN_MAX = "minMax", t.PERCENTILE = "percentile", t))(H || {});
46
- function at(t) {
45
+ function tt(t) {
46
+ return t === void 0 ? [] : Array.isArray(t) ? t : [t];
47
+ }
48
+ function Te(t) {
49
+ const e = t.layout ?? {}, r = e.type ?? "vertical";
50
+ if (r !== "vertical" && r !== "horizontal" && r !== "grid")
51
+ throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(r)}.`);
52
+ const o = e.gap ?? 0;
53
+ if (typeof o != "number" || !Number.isFinite(o) || o < 0)
54
+ throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(o)}.`);
55
+ const n = e.columns ?? 2;
56
+ if (!Number.isInteger(n) || n < 1)
57
+ throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);
58
+ const s = [
59
+ ...tt(t.map).map((l, u) => ({ kind: "map", index: u, id: l.id, key: l.id ?? u })),
60
+ ...tt(t.plot).map((l, u) => ({ kind: "plot", index: u, id: l.id, key: l.id ?? l.dataRef }))
61
+ ], a = r === "vertical" ? 1 : r === "horizontal" ? Math.max(s.length, 1) : n, i = s.map(({ kind: l, index: u, id: d, key: c }, f) => ({
62
+ kind: l,
63
+ index: u,
64
+ ...d !== void 0 && { id: d },
65
+ key: c,
66
+ row: Math.floor(f / a),
67
+ column: f % a
68
+ }));
69
+ return { type: r, rows: Math.ceil(s.length / a), columns: a, gap: o, panes: i };
70
+ }
71
+ var xt = /* @__PURE__ */ ((t) => (t.CAT_ACCENT = "schemeAccent", t.CAT_DARK2 = "schemeDark2", t.CAT_CATEGORY10 = "schemeCategory10", t.CAT_OBSERVABLE10 = "schemeObservable10", t.CAT_PAIRED = "schemePaired", t.CAT_PASTEL1 = "schemePastel1", t.CAT_PASTEL2 = "schemePastel2", t.CAT_SET1 = "schemeSet1", t.CAT_SET2 = "schemeSet2", t.CAT_SET3 = "schemeSet3", t.CAT_TABLEAU10 = "schemeTableau10", t.SEQ_REDS = "interpolateReds", t.SEQ_BLUES = "interpolateBlues", t.SEQ_GREENS = "interpolateGreens", t.SEQ_GREYS = "interpolateGreys", t.SEQ_ORANGES = "interpolateOranges", t.SEQ_PURPLES = "interpolatePurples", t.SEQ_TURBO = "interpolateTurbo", t.SEQ_VIRIDIS = "interpolateViridis", t.SEQ_INFERNO = "interpolateInferno", t.SEQ_MAGMA = "interpolateMagma", t.SEQ_PLASMA = "interpolatePlasma", t.SEQ_CIVIDIS = "interpolateCividis", t.SEQ_WARM = "interpolateWarm", t.SEQ_COOL = "interpolateCool", t.SEQ_CUBEHELIX_DEFAULT = "interpolateCubehelixDefault", t.SEQ_BU_GN = "interpolateBuGn", t.SEQ_BU_PU = "interpolateBuPu", t.SEQ_GN_BU = "interpolateGnBu", t.SEQ_OR_RD = "interpolateOrRd", t.SEQ_PU_BU_GN = "interpolatePuBuGn", t.SEQ_PU_BU = "interpolatePuBu", t.SEQ_PU_RD = "interpolatePuRd", t.SEQ_RD_PU = "interpolateRdPu", t.SEQ_YL_GN_BU = "interpolateYlGnBu", t.SEQ_YL_GN = "interpolateYlGn", t.SEQ_YL_OR_BR = "interpolateYlOrBr", t.SEQ_YL_OR_RD = "interpolateYlOrRd", t.DIV_BR_BG = "interpolateBrBG", t.DIV_PR_GN = "interpolatePRGn", t.DIV_PI_YG = "interpolatePiYG", t.DIV_PU_OR = "interpolatePuOr", t.DIV_RED_BLUE = "interpolateRdBu", t.DIV_RED_GREY = "interpolateRdGy", t.DIV_RED_YELLOW_BLUE = "interpolateRdYlBu", t.DIV_RED_YELLOW_GREEN = "interpolateRdYlGn", t.DIV_SPECTRAL = "interpolateSpectral", t))(xt || {}), pt = /* @__PURE__ */ ((t) => (t.MIN_MAX = "minMax", t.PERCENTILE = "percentile", t))(pt || {});
72
+ async function I(t, e) {
73
+ const r = e ?? j;
74
+ t.getCurrentWorkspace() !== r && await t.setWorkspace(r);
75
+ }
76
+ function b(t, e) {
77
+ return t === void 0 || t === j ? e : `${t}/${e}`;
78
+ }
79
+ function mt(t) {
80
+ const e = /* @__PURE__ */ new Set();
81
+ for (const o of t)
82
+ o?.id != null && e.add(JSON.stringify(o.id));
83
+ const r = /* @__PURE__ */ new Set();
84
+ return t.map((o, n) => {
85
+ if (o?.id != null) return o.id;
86
+ let s = `autk-feature-${n}`;
87
+ for (; e.has(JSON.stringify(s)) || r.has(JSON.stringify(s)); ) s = `${s}-generated`;
88
+ return r.add(JSON.stringify(s)), s;
89
+ });
90
+ }
91
+ function ht(t) {
92
+ const e = /* @__PURE__ */ new Map();
93
+ return mt(t).map((r) => {
94
+ const o = JSON.stringify(r), n = e.get(o) ?? 0;
95
+ return e.set(o, n + 1), n === 0 ? o : `${o} ${n}`;
96
+ });
97
+ }
98
+ const et = /* @__PURE__ */ new WeakMap();
99
+ function jt(t) {
100
+ let e = et.get(t);
101
+ return e || (e = /* @__PURE__ */ new Map(), t.forEach((r, o) => {
102
+ const n = e.get(r);
103
+ n ? n.push(o) : e.set(r, [o]);
104
+ }), et.set(t, e), e);
105
+ }
106
+ function x(t, e, r) {
107
+ const o = jt(r), n = /* @__PURE__ */ new Set();
108
+ for (const s of t) {
109
+ const a = e[s];
110
+ if (a !== void 0)
111
+ for (const i of o.get(a) ?? []) n.add(i);
112
+ }
113
+ return [...n];
114
+ }
115
+ const Gt = { type: "GeometryCollection", geometries: [] };
116
+ function Dt(t) {
117
+ const e = t.features ?? [], r = mt(e);
118
+ let o = !1;
119
+ const n = e.map((a, i) => a == null || a.id != null && a.geometry != null ? a : (o = !0, { ...a, id: r[i], geometry: a.geometry ?? Gt })), s = e.findIndex((a) => a?.geometry != null);
120
+ return s > 0 && e[0] != null && e[0].geometry == null && ([n[0], n[s]] = [n[s], n[0]], o = !0), o ? { ...t, features: n } : t;
121
+ }
122
+ function Ut(t) {
47
123
  const { queryArea: e } = t;
48
124
  if (e.bbox === void 0) return { geocodeArea: e.geocodeArea, areas: e.areas };
49
- const r = (s) => new Error(`OSM source "${t.outputTableName}": ${s}`);
125
+ const r = (l) => new Error(`OSM source "${t.outputTableName}": ${l}`);
50
126
  if (e.geocodeArea !== void 0 || e.areas !== void 0)
51
127
  throw r("queryArea takes either bbox or geocodeArea with areas, not both.");
52
128
  const o = e.bbox;
53
- if (!Array.isArray(o) || o.length !== 4 || !o.every((s) => typeof s == "number" && Number.isFinite(s)))
129
+ if (!Array.isArray(o) || o.length !== 4 || !o.every((l) => typeof l == "number" && Number.isFinite(l)))
54
130
  throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");
55
- const [i, n, l, a] = e.bbox;
56
- if (Math.abs(i) > 180 || Math.abs(l) > 180)
131
+ const [n, s, a, i] = e.bbox;
132
+ if (Math.abs(n) > 180 || Math.abs(a) > 180)
57
133
  throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");
58
- if (Math.abs(n) > 90 || Math.abs(a) > 90)
134
+ if (Math.abs(s) > 90 || Math.abs(i) > 90)
59
135
  throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");
60
- if (i >= l)
61
- throw r(`queryArea.bbox west (${i}) must be less than east (${l}); a box across the antimeridian is not supported.`);
62
136
  if (n >= a)
63
- throw r(`queryArea.bbox south (${n}) must be less than north (${a}).`);
64
- return { bbox: [i, n, l, a] };
137
+ throw r(`queryArea.bbox west (${n}) must be less than east (${a}); a box across the antimeridian is not supported.`);
138
+ if (s >= i)
139
+ throw r(`queryArea.bbox south (${s}) must be less than north (${i}).`);
140
+ return { bbox: [n, s, a, i] };
65
141
  }
66
- function it(t) {
142
+ function Qt(t) {
67
143
  const { autoLoadLayers: e, ...r } = t;
68
- return { ...r, queryArea: at(t), autoLoadLayers: { layers: e?.layers ?? [] } };
144
+ if (t.pbfFileUrl !== void 0 && (t.tagSets?.length ?? 0) > 0)
145
+ throw new Error(`OSM source "${t.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);
146
+ return {
147
+ ...r,
148
+ queryArea: Ut(t),
149
+ autoLoadLayers: {
150
+ layers: e?.layers ?? [],
151
+ ...e?.coordinateFormat !== void 0 && { coordinateFormat: e.coordinateFormat }
152
+ }
153
+ };
69
154
  }
70
- function D(t) {
155
+ function rt(t) {
71
156
  return `${t ? `coordinateFormat is set to "${t}"` : "no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`;
72
157
  }
73
- function st(t) {
74
- let e = 1 / 0, r = 1 / 0, o = -1 / 0, i = -1 / 0;
75
- const n = (a) => {
76
- if (Array.isArray(a)) {
77
- if (typeof a[0] == "number") {
78
- const [s, u] = a;
79
- s < e && (e = s), s > o && (o = s), u < r && (r = u), u > i && (i = u);
158
+ function D(t) {
159
+ return t === void 0 || t === j ? "the default workspace" : `the workspace "${t}"`;
160
+ }
161
+ function ot(t) {
162
+ if (t != null)
163
+ return typeof t == "string" ? t : JSON.stringify(t);
164
+ }
165
+ async function Yt(t, e, r, o) {
166
+ const n = /* @__PURE__ */ new Map();
167
+ for (const i of (await t.getLayer(e.name)).features) {
168
+ const l = ot(i.properties?.[o]);
169
+ if (l !== void 0) {
170
+ if (i.id === void 0 || i.id === null)
171
+ throw new Error("its rows have no feature id to update them by.");
172
+ n.set(l, [...n.get(l) ?? [], i.id]);
173
+ }
174
+ }
175
+ const s = r.features.flatMap((i) => {
176
+ const l = ot(i.properties?.[o]);
177
+ return l === void 0 ? [] : (n.get(l) ?? []).map((u) => ({ ...i, id: u }));
178
+ }), a = e.columns.some((i) => i.name === "geojson_id") ? "geojson_id" : "id";
179
+ return { data: { ...r, features: s }, idColumn: a };
180
+ }
181
+ async function nt(t) {
182
+ if (t) return t;
183
+ const e = new Tt();
184
+ return await e.init(), e;
185
+ }
186
+ function yt(t) {
187
+ let e = 1 / 0, r = 1 / 0, o = -1 / 0, n = -1 / 0;
188
+ const s = (i) => {
189
+ if (Array.isArray(i)) {
190
+ if (typeof i[0] == "number") {
191
+ const [l, u] = i;
192
+ l < e && (e = l), l > o && (o = l), u < r && (r = u), u > n && (n = u);
80
193
  return;
81
194
  }
82
- for (const s of a) n(s);
195
+ for (const l of i) s(l);
83
196
  }
84
- }, l = (a) => {
85
- a && (a.type === "GeometryCollection" ? a.geometries.forEach(l) : n(a.coordinates));
197
+ }, a = (i) => {
198
+ i && (i.type === "GeometryCollection" ? i.geometries.forEach(a) : s(i.coordinates));
86
199
  };
87
- for (const a of t.features ?? []) l(a?.geometry);
88
- return e <= o ? [e, r, o, i] : void 0;
200
+ for (const i of t.features ?? []) a(i?.geometry);
201
+ return e <= o ? [e, r, o, n] : void 0;
89
202
  }
90
- function lt(t, e) {
91
- function r(o, i) {
92
- if (!i || !i.db)
203
+ function Vt(t, e) {
204
+ function r(n, s) {
205
+ if (!s || !s.db)
93
206
  return;
94
- const n = document.getElementById(i.db);
95
- if (n) {
96
- const l = o.getTablesMetadata();
97
- n.innerHTML += "<ul>";
98
- for (const a of l)
99
- n.innerHTML += `<li>${a.name}: (${a.source}, ${a.type}) </li>`;
100
- n.innerHTML += "</ul>", n.innerHTML += `<p>Number of tables: ${l.length}</p>`;
207
+ const a = document.getElementById(s.db);
208
+ if (a) {
209
+ const i = n.getTablesMetadata();
210
+ a.innerHTML += "<ul>";
211
+ for (const l of i)
212
+ a.innerHTML += `<li>${l.name}: (${l.source}, ${l.type}) </li>`;
213
+ a.innerHTML += "</ul>", a.innerHTML += `<p>Number of tables: ${i.length}</p>`;
101
214
  }
102
215
  }
216
+ async function o(n, s, a) {
217
+ if (!e) return;
218
+ const i = b(s, a), l = n.getTablesMetadata().find((u) => u.name === a);
219
+ l && dt(l) ? e.set(i, await n.getLayer(a)) : e.delete(i);
220
+ }
103
221
  return {
104
- async resolveSource(o, i) {
105
- let n = o;
106
- n || (n = new z(), await n.init());
107
- let { type: l, ...a } = i;
222
+ async resolveWorkspaces(n, s) {
223
+ const a = await nt(n), i = /* @__PURE__ */ new Set();
224
+ for (const { name: l, coordinateFormat: u, precisionGrid: d } of s) {
225
+ const c = l ?? j;
226
+ if (i.has(c))
227
+ throw new Error(`workspaces sets ${D(l)} twice; give each workspace one entry.`);
228
+ i.add(c);
229
+ try {
230
+ await a.setWorkspace(c, { coordinateFormat: u, precisionGrid: d });
231
+ } catch (f) {
232
+ throw new Error(`workspaces, ${D(l)}: ${f instanceof Error ? f.message : String(f)}`);
233
+ }
234
+ }
235
+ return await I(a), a;
236
+ },
237
+ async resolveSource(n, s) {
238
+ const a = await nt(n), { workspace: i } = s;
239
+ await I(a, i);
240
+ let { type: l, workspace: u, ...d } = s;
108
241
  switch (l) {
109
242
  case "osm":
110
- return await n.loadOsm(it(a)), r(n, t), n;
243
+ return await a.loadOsm(Qt(d)), r(a, t), a;
111
244
  case "csv":
112
- return await n.loadCsv(a), r(n, t), n;
245
+ return await a.loadCsv(d), r(a, t), a;
113
246
  case "json":
114
- return await n.loadJson(a), r(n, t), n;
247
+ return await a.loadJson(d), r(a, t), a;
115
248
  case "geojson": {
116
- const s = a;
117
- let u;
118
- s.geojsonFileUrl ? u = await (await fetch(s.geojsonFileUrl)).json() : u = s.geojsonObject, e && u && e.set(s.outputTableName, u);
119
- const c = u ? (() => {
120
- const f = { ...s, geojsonObject: u };
121
- return delete f.geojsonFileUrl, f;
122
- })() : s, d = /^EPSG:4326$/i.test(c.coordinateFormat ?? "EPSG:4326"), p = u && d ? st(u) : void 0;
123
- if (p && (p[1] < -90 || p[3] > 90))
249
+ const c = d;
250
+ let f;
251
+ c.geojsonFileUrl ? f = await (await fetch(c.geojsonFileUrl)).json() : f = c.geojsonObject, e && f && e.set(b(i, c.outputTableName), f);
252
+ const y = f ? (() => {
253
+ const p = { ...c, geojsonObject: Dt(f) };
254
+ return delete p.geojsonFileUrl, p;
255
+ })() : c, m = /^EPSG:4326$/i.test(y.coordinateFormat ?? "EPSG:4326"), h = f && m ? yt(f) : void 0;
256
+ if (h && (h[1] < -90 || h[3] > 90))
124
257
  throw new Error(
125
- `GeoJSON layer "${c.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${p.join(", ")}]), so they cannot be EPSG:4326 degrees. ${D(c.coordinateFormat)}`
258
+ `GeoJSON layer "${y.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${h.join(", ")}]), so they cannot be EPSG:4326 degrees. ${rt(y.coordinateFormat)}`
126
259
  );
127
260
  try {
128
- await n.loadGeojson(c);
129
- } catch (f) {
130
- throw new Error(`Failed to load GeoJSON layer "${c.outputTableName}": ${f instanceof Error ? f.message : String(f)}`);
261
+ await a.loadGeojson(y);
262
+ } catch (p) {
263
+ throw new Error(`Failed to load GeoJSON layer "${y.outputTableName}": ${p instanceof Error ? p.message : String(p)}`);
131
264
  }
132
265
  try {
133
- const f = await n.getBoundingBoxFromLayer(c.outputTableName), m = 25e6;
134
- if (!isFinite(f.minLon) || !isFinite(f.minLat) || !isFinite(f.maxLon) || !isFinite(f.maxLat) || Math.abs(f.minLon) > m || Math.abs(f.maxLon) > m || Math.abs(f.minLat) > m || Math.abs(f.maxLat) > m)
266
+ const p = await a.getBoundingBoxFromLayer(y.outputTableName), w = 25e6;
267
+ if (!isFinite(p.minLon) || !isFinite(p.minLat) || !isFinite(p.maxLon) || !isFinite(p.maxLat) || Math.abs(p.minLon) > w || Math.abs(p.maxLon) > w || Math.abs(p.minLat) > w || Math.abs(p.maxLat) > w)
135
268
  throw new Error(
136
- `Geometry bounding box after transform is invalid for layer "${c.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). ${D(c.coordinateFormat)} The workspace uses ${k}; input is expected in EPSG:4326 by default.`
269
+ `Geometry bounding box after transform is invalid for layer "${y.outputTableName}" (bbox: [${p.minLon}, ${p.minLat}, ${p.maxLon}, ${p.maxLat}]). ${rt(y.coordinateFormat)} The workspace uses ${a.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`
137
270
  );
138
- } catch (f) {
139
- if (f instanceof Error && f.message.includes("bounding box after transform")) throw f;
271
+ } catch (p) {
272
+ if (p instanceof Error && p.message.includes("bounding box after transform")) throw p;
140
273
  }
141
- return r(n, t), n;
274
+ return r(a, t), a;
142
275
  }
276
+ case "geotiff":
277
+ return await a.loadGeoTiff(d), r(a, t), a;
143
278
  case "heatmap": {
144
- const s = a;
145
- return await n.buildHeatmap({
146
- tableJoinName: s.tableJoinName,
147
- near: { distance: s.near.distance },
148
- outputTableName: s.outputTableName,
149
- grid: s.grid,
150
- ...s.groupBy && { groupBy: s.groupBy }
151
- }), r(n, t), n;
279
+ const c = d;
280
+ if (c.groupBy?.some((f) => f.aggregateFn === "collect"))
281
+ throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);
282
+ return await a.buildHeatmap({
283
+ tableJoinName: c.joinDataRef,
284
+ near: c.near,
285
+ outputTableName: c.outputTableName,
286
+ grid: c.grid,
287
+ ...c.groupBy && { groupBy: c.groupBy }
288
+ }), r(a, t), a;
152
289
  }
153
290
  case "join": {
154
- const s = a;
155
- if (await n.spatialQuery({
156
- tableRootName: s.tableRootName,
157
- tableJoinName: s.tableJoinName,
158
- ...s.near && { near: s.near },
159
- ...s.groupBy && { groupBy: s.groupBy }
291
+ const c = d;
292
+ if (await a.spatialQuery({
293
+ tableRootName: c.dataRef,
294
+ tableJoinName: c.joinDataRef,
295
+ ...c.near && { near: c.near },
296
+ ...c.groupBy && { groupBy: c.groupBy }
160
297
  }), e) {
161
- const u = await n.getLayer(s.tableRootName);
162
- e.set(s.tableRootName, u);
298
+ const f = await a.getLayer(c.dataRef);
299
+ e.set(b(i, c.dataRef), f);
163
300
  }
164
- return r(n, t), n;
301
+ return r(a, t), a;
302
+ }
303
+ case "sql": {
304
+ const c = d;
305
+ try {
306
+ await a.rawQuery({
307
+ query: c.query,
308
+ output: {
309
+ type: "CREATE_TABLE",
310
+ tableName: c.outputTableName,
311
+ source: "user",
312
+ ...c.layerType !== void 0 && { tableType: c.layerType }
313
+ }
314
+ });
315
+ } catch (f) {
316
+ throw new Error(`SQL source "${c.outputTableName}": ${f instanceof Error ? f.message : String(f)}`);
317
+ }
318
+ return e?.delete(b(i, c.outputTableName)), r(a, t), a;
319
+ }
320
+ case "update": {
321
+ const c = d, f = (h) => new Error(`Update of "${c.dataRef}": ${h}`);
322
+ if (c.geojsonObject === void 0 == (c.jsonObject === void 0))
323
+ throw f("give its rows in geojsonObject or in jsonObject, one of the two.");
324
+ if (c.strategy === "update" && !c.idColumn)
325
+ throw f("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");
326
+ let y = c.geojsonObject ?? c.jsonObject, m = c.idColumn;
327
+ try {
328
+ const h = a.getTablesMetadata().find((p) => p.name === c.dataRef);
329
+ if (c.strategy === "update" && c.geojsonObject && m?.startsWith("properties.") && h && Nt(h) && ({ data: y, idColumn: m } = await Yt(a, h, c.geojsonObject, m.slice(11)), y.features.length === 0))
330
+ return r(a, t), a;
331
+ await a.updateTable({
332
+ tableName: c.dataRef,
333
+ data: y,
334
+ strategy: c.strategy,
335
+ ...m !== void 0 && { idColumn: m }
336
+ });
337
+ } catch (h) {
338
+ throw f(h instanceof Error ? h.message : String(h));
339
+ }
340
+ return await o(a, i, c.dataRef), r(a, t), a;
341
+ }
342
+ case "drop": {
343
+ const c = d;
344
+ if (!a.getTablesMetadata().some((f) => f.name === c.dataRef))
345
+ throw new Error(`Drop of "${c.dataRef}": ${D(i)} holds no table of that name.`);
346
+ return await a.removeLayer(c.dataRef), e?.delete(b(i, c.dataRef)), r(a, t), a;
165
347
  }
166
348
  default:
167
- return;
349
+ throw new Error(`Unknown data source type "${String(l)}".`);
168
350
  }
169
351
  }
170
352
  };
171
353
  }
172
- function N(t) {
354
+ function wt(t, e) {
355
+ return e === !0 ? `${t} osm-elements` : t;
356
+ }
357
+ function gt(t) {
358
+ return t === !0 ? { osmElements: !0 } : void 0;
359
+ }
360
+ function bt(t, e, r) {
361
+ if (!t) return r();
362
+ let o = t.get(e);
363
+ return o || (o = r(), t.set(e, o)), o;
364
+ }
365
+ function _t(t, e) {
366
+ return t?.id ?? e;
367
+ }
368
+ function U(t, e) {
369
+ return e === void 0 ? !0 : typeof e == "number" ? t.mapIndex === e : t.mapId === e;
370
+ }
371
+ function Et(t, e, r) {
372
+ const o = t?.get(e) ?? [];
373
+ o.includes(r) || t?.set(e, [...o, r]);
374
+ }
375
+ const Mt = 6378137, Y = 0.0818191908426215;
376
+ function Wt(t, e) {
377
+ if (t === void 0 || typeof t == "number" && Number.isFinite(t) && t > 0) return;
378
+ const r = typeof t == "number" ? String(t) : JSON.stringify(t);
379
+ throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${r}.`);
380
+ }
381
+ function Ht(t) {
382
+ const e = Math.exp(-t / Mt);
383
+ let r = Math.PI / 2 - 2 * Math.atan(e);
384
+ for (let o = 0; o < 10; o++) {
385
+ const n = Y * Math.sin(r), s = Math.PI / 2 - 2 * Math.atan(e * ((1 - n) / (1 + n)) ** (Y / 2));
386
+ if (Math.abs(s - r) < 1e-12) return s;
387
+ r = s;
388
+ }
389
+ return r;
390
+ }
391
+ function qt(t, e) {
392
+ if (/^EPSG:3395$/i.test(t)) {
393
+ const r = Ht(e), o = Y * Math.sin(r);
394
+ return Math.sqrt(1 - o * o) / Math.cos(r);
395
+ }
396
+ return /^EPSG:3857$/i.test(t) ? Math.cosh(e / Mt) : 1;
397
+ }
398
+ function Jt(t, e, r, o) {
399
+ if (t === void 0 || e !== "points") return;
400
+ const n = o();
401
+ if (n)
402
+ return t * qt(r, (n[1] + n[3]) / 2);
403
+ }
404
+ function R(t) {
173
405
  return typeof t.title == "string" && t.title !== "" ? t.title : t.dataRef;
174
406
  }
175
- function ut(t, e) {
407
+ function Kt(t, e) {
176
408
  const r = /* @__PURE__ */ new Set();
177
409
  for (const o of t.layerRefs) {
178
- const i = N(o);
179
- if (r.has(i))
180
- throw new Error(`Map ${e} draws two layers with the id "${i}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);
181
- r.add(i);
410
+ const n = R(o);
411
+ if (r.has(n))
412
+ throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);
413
+ r.add(n);
182
414
  }
183
415
  }
184
- const ct = /^#[0-9a-fA-F]{6}$/;
185
- function G(t, e, r) {
186
- if (!ct.test(t))
416
+ const Xt = /^#[0-9a-fA-F]{6}$/;
417
+ function at(t, e, r) {
418
+ if (!Xt.test(t))
187
419
  throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);
188
- return v.hexToRgb(t);
420
+ return B.hexToRgb(t);
189
421
  }
190
- function ft(t, e) {
422
+ function zt(t, e) {
191
423
  const r = {};
192
- return t.color != null && (r.color = G(t.color, "color", e)), t.stroke === !1 ? r.showBorders = !1 : t.stroke != null && (r.strokeColor = G(t.stroke, "stroke", e)), t.width != null && (r.polylinesWidth = t.width), r;
424
+ return t.color != null && (r.color = at(t.color, "color", e)), t.stroke === !1 ? r.showBorders = !1 : t.stroke != null && (r.strokeColor = at(t.stroke, "stroke", e)), t.width != null && (r.polylinesWidth = t.width), r;
193
425
  }
194
- function pt(t, e) {
426
+ function Zt(t, e) {
195
427
  return t.isColorMap != null ? t.isColorMap : e === "raster" ? t.colorMapInterpolator != null || t.colorMapRange != null || t.colorMapCenter != null || t.colorMapReverse === !0 : t.color != null ? !1 : t.colorMapInterpolator != null || t.getFnv != null;
196
428
  }
197
- function mt(t, e) {
429
+ function te(t, e) {
198
430
  const r = t.features?.[0]?.properties?.[e];
199
431
  return r instanceof Float32Array ? r : ArrayBuffer.isView(r) && !(r instanceof DataView) || Array.isArray(r) ? Float32Array.from(r, (o) => Number.isFinite(Number(o)) ? Number(o) : NaN) : null;
200
432
  }
201
- function dt(t, e, r, o, i) {
202
- if (v.isCategorical(e.interpolator)) return;
203
- if (i != null) {
204
- const u = r != null ? [i[0], r, i[1]] : [i[0], i[1]];
433
+ function ee(t, e, r, o, n) {
434
+ if (B.isCategorical(e.interpolator)) return;
435
+ if (n != null) {
436
+ const u = r != null ? [n[0], r, n[1]] : [n[0], n[1]];
205
437
  return o === !0 ? u.reverse() : u;
206
438
  }
207
439
  if (!t) return;
208
- let n = 0, l = 0;
440
+ let s = 0, a = 0;
209
441
  for (let u = 0; u < t.length; u++) {
210
- const c = t[u];
211
- Number.isFinite(c) && (l++, r != null && (n = Math.max(n, Math.abs(c - r))));
442
+ const d = t[u];
443
+ Number.isFinite(d) && (a++, r != null && (s = Math.max(s, Math.abs(d - r))));
212
444
  }
213
- const a = r != null && n > 0;
214
- if (l === 0 || !a && o !== !0) return;
215
- const s = a && r != null ? [r - n, r, r + n] : v.resolveDomainFromData(t, e);
216
- return o === !0 ? [...s].reverse() : s;
445
+ const i = r != null && s > 0;
446
+ if (a === 0 || !i && o !== !0) return;
447
+ const l = i && r != null ? [r - s, r, r + s] : B.resolveDomainFromData(t, e);
448
+ return o === !0 ? [...l].reverse() : l;
217
449
  }
218
- function ht(t, e) {
219
- if (!(e == null || v.isCategorical(t.interpolator)))
450
+ function re(t, e) {
451
+ if (!(e == null || B.isCategorical(t.interpolator)))
220
452
  return [e[0], e[1]];
221
453
  }
222
- function yt(t) {
454
+ function oe(t) {
223
455
  const e = t.colorMapRange;
224
456
  if (e === void 0) return;
225
- const r = (l) => new Error(`Layer "${N(t)}": ${l}`);
226
- if (!Array.isArray(e) || e.length !== 2 || !e.every((l) => typeof l == "number" && Number.isFinite(l)))
457
+ const r = (a) => new Error(`Layer "${R(t)}": ${a}`);
458
+ if (!Array.isArray(e) || e.length !== 2 || !e.every((a) => typeof a == "number" && Number.isFinite(a)))
227
459
  throw r("colorMapRange must hold two numbers, [low, high].");
228
- const [o, i] = e;
229
- if (o >= i)
230
- throw r(`colorMapRange low (${o}) must be less than high (${i}).`);
460
+ const [o, n] = e;
461
+ if (o >= n)
462
+ throw r(`colorMapRange low (${o}) must be less than high (${n}).`);
231
463
  if (t.colorMapDomain !== void 0)
232
464
  throw r("set colorMapRange or colorMapDomain, not both.");
233
- const n = t.colorMapCenter;
234
- if (n != null && (n < o || n > i))
235
- throw r(`colorMapCenter (${n}) must lie within colorMapRange [${o}, ${i}].`);
465
+ const s = t.colorMapCenter;
466
+ if (s != null && (s < o || s > n))
467
+ throw r(`colorMapCenter (${s}) must lie within colorMapRange [${o}, ${n}].`);
236
468
  }
237
- function gt(t, e) {
238
- return e && e.length > 0 ? { type: M.USER, params: e } : t?.mode === H.PERCENTILE ? t.lowerPercentile !== void 0 || t.upperPercentile !== void 0 ? {
239
- type: M.PERCENTILE,
469
+ function ne(t, e) {
470
+ return e && e.length > 0 ? { type: P.USER, params: e } : t?.mode === pt.PERCENTILE ? t.lowerPercentile !== void 0 || t.upperPercentile !== void 0 ? {
471
+ type: P.PERCENTILE,
240
472
  params: [t.lowerPercentile ?? 0, t.upperPercentile ?? 100]
241
- } : { type: M.PERCENTILE } : { type: M.MIN_MAX };
473
+ } : { type: P.PERCENTILE } : { type: P.MIN_MAX };
242
474
  }
243
- function bt(t, e) {
475
+ function ae(t, e) {
244
476
  return e.split(".").reduce((r, o) => {
245
477
  if (!(r == null || typeof r != "object"))
246
478
  return r[o];
247
479
  }, t);
248
480
  }
249
- function _t(t, e, r) {
250
- const o = e.split("."), i = { ...t };
251
- let n = i;
252
- for (let l = 0; l < o.length - 1; l++)
253
- n[o[l]] = { ...n[o[l]] ?? {} }, n = n[o[l]];
254
- return n[o[o.length - 1]] = r, i;
481
+ function ie(t, e, r) {
482
+ const o = e.split("."), n = { ...t };
483
+ let s = n;
484
+ for (let a = 0; a < o.length - 1; a++)
485
+ s[o[a]] = { ...s[o[a]] ?? {} }, s = s[o[a]];
486
+ return s[o[o.length - 1]] = r, n;
255
487
  }
256
- function Et(t, e) {
488
+ function se(t, e) {
257
489
  const o = t.features?.[0]?.properties?.bands ?? [];
258
- return o.find((n) => n.id === e || n.label === e?.replace(/\./g, "_"))?.id ?? o[0]?.id ?? e ?? "";
259
- }
260
- function wt(t, e, r, o, i) {
261
- async function n(l, a, s) {
262
- let u = {};
263
- for (const c of a.getTablesMetadata())
264
- c.type !== void 0 && (u[c.name] = c.type);
265
- for (const c of s.layerRefs) {
266
- const d = c.dataRef, p = N(c), f = u[d], m = c.getFnv, h = r?.get(d) ?? await a.getLayer(d), y = f === "raster" ? h : {
267
- ...h,
268
- features: (h.features ?? []).filter((g) => g.geometry != null)
269
- }, w = f === "raster" ? Et(y, m) : "";
270
- f === "raster" ? l.loadCollection(p, { collection: y, type: "raster", property: w }) : l.loadCollection(p, { collection: y, type: f }), c.opacity != null && l.updateRenderInfo(p, { opacity: c.opacity });
271
- const A = ft(c, p);
272
- Object.keys(A).length > 0 && l.updateRenderInfo(p, A), pt(c, f) && l.updateRenderInfo(p, { isColorMap: !0 }), c.isPick && l.updateRenderInfo(p, { isPick: !0 }), c.isSkip && l.updateRenderInfo(p, { isSkip: !0 });
273
- const { catchAllCategory: b, colorMapDomain: R } = c;
274
- let F = y, T = R;
275
- if (m && b && R?.length) {
276
- const g = new Set(R);
277
- F = {
278
- ...y,
279
- features: y.features.map((_) => {
280
- const $ = _.properties, P = bt($, m);
281
- return P == null || !g.has(String(P)) ? { ..._, properties: _t($, m, b) } : _;
490
+ return o.find((s) => s.id === e || s.label === e?.replace(/\./g, "_"))?.id ?? o[0]?.id ?? e ?? "";
491
+ }
492
+ function At(t) {
493
+ const { pitch: e } = t;
494
+ return e === void 0 || typeof e == "number" && e >= 0 && e < 90 ? void 0 : `camera.pitch must be at least 0 and less than 90 degrees, not ${typeof e == "number" ? String(e) : JSON.stringify(e)}: at 90 the eye would sit on the ground, edge-on to the map's flat layers, and the map could not pan.`;
495
+ }
496
+ function le(t, e) {
497
+ const r = At(e);
498
+ if (r) throw new Error(r);
499
+ if (e.zoom === void 0 && !e.pitch && !e.bearing) return;
500
+ const o = t.camera, [n, s] = o.getLookAt(), a = e.zoom !== void 0 ? 1e4 / Math.pow(2, e.zoom - 10) : Math.abs(o.getEye()[2]), i = (e.pitch ?? 0) * Math.PI / 180, l = (e.bearing ?? 0) * Math.PI / 180, u = [
501
+ n - a * Math.sin(i) * Math.sin(l),
502
+ s - a * Math.sin(i) * Math.cos(l),
503
+ a * Math.cos(i)
504
+ ], d = [Math.cos(i) * Math.sin(l), Math.cos(i) * Math.cos(l), Math.sin(i)];
505
+ o.resetCamera(d, [n, s, 0], u);
506
+ }
507
+ function ue(t, e, r, o) {
508
+ const s = t.layerManager.searchByLayerId(e)?.components;
509
+ return Array.isArray(s) ? s.map((a, i) => {
510
+ const l = Number.isInteger(a?.featureIndex) ? a.featureIndex : i;
511
+ return r[o[l]] ?? "";
512
+ }) : o.map((a) => r[a] ?? "");
513
+ }
514
+ function ce(t, e, r, o, n, s) {
515
+ async function a(i, l, u) {
516
+ let d = {};
517
+ for (const f of l.getTablesMetadata())
518
+ f.type !== void 0 && (d[f.name] = f.type);
519
+ const c = [];
520
+ for (const f of u.layerRefs) {
521
+ const y = f.dataRef, m = R(f), h = b(u.workspace, y), p = n?.get(h) ?? d[y], w = f.getFnv, _ = r?.get(h) ?? (p === "raster" ? await l.getRaster(y) : await bt(s, wt(h, f.osmElements), () => l.getLayer(y, gt(f.osmElements)))), E = _.features ?? [], S = p === "raster" ? [] : E.flatMap((g, M) => g?.geometry != null ? [M] : []), A = p === "raster" ? _ : { ..._, features: S.map((g) => E[g]) }, V = p === "raster" ? se(A, w) : "";
522
+ p === "raster" ? i.loadCollection(m, { collection: A, type: "raster", property: V }) : i.loadCollection(m, { collection: A, type: p }), f.opacity != null && i.updateRenderInfo(m, { opacity: f.opacity });
523
+ const W = zt(f, m);
524
+ Object.keys(W).length > 0 && i.updateRenderInfo(m, W);
525
+ const Pt = l.getWorkspaceConfiguration().coordinateFormat, H = Jt(f.pointSize, p, Pt, () => yt(A));
526
+ H !== void 0 && i.updateRenderInfo(m, { pointSize: H }), Zt(f, p) && i.updateRenderInfo(m, { isColorMap: !0 }), f.isPick && i.updateRenderInfo(m, { isPick: !0 }), f.isSkip && i.updateRenderInfo(m, { isSkip: !0 });
527
+ const { catchAllCategory: $, colorMapDomain: L } = f;
528
+ let q = A, J = L;
529
+ if (w && $ && L?.length) {
530
+ const g = new Set(L);
531
+ q = {
532
+ ...A,
533
+ features: A.features.map((M) => {
534
+ const z = M.properties, G = ae(z, w);
535
+ return G == null || !g.has(String(G)) ? { ...M, properties: ie(z, w, $) } : M;
282
536
  })
283
- }, T = g.has(b) ? R : [...R, b];
537
+ }, J = g.has($) ? L : [...L, $];
284
538
  }
285
- const O = f === "raster" && c.transferFunction != null;
286
- O && l.layerManager.searchByLayerId(p)?.setTransferFunction?.(c.transferFunction);
287
- const C = c.colorMapRange, x = f === "raster" && (C != null || c.colorMapCenter != null || c.colorMapReverse === !0);
288
- if (c.colorMapInterpolator || x || C) {
539
+ const K = p === "raster" && f.transferFunction != null;
540
+ K && i.layerManager.searchByLayerId(m)?.setTransferFunction?.(f.transferFunction);
541
+ const O = f.colorMapRange, X = p === "raster" && (O != null || f.colorMapCenter != null || f.colorMapReverse === !0);
542
+ if (f.colorMapInterpolator || X || O) {
289
543
  const g = {
290
544
  // urban-grammar ColorMapInterpolator values are string-compatible
291
545
  // with autk-core ColorMapInterpolator at runtime
292
- interpolator: c.colorMapInterpolator ?? l.layerManager.searchByLayerId(p)?.layerRenderInfo.colormap.config.interpolator ?? et.SEQ_REDS,
293
- domainSpec: gt(c.normalization, T)
546
+ interpolator: f.colorMapInterpolator ?? i.layerManager.searchByLayerId(m)?.layerRenderInfo.colormap.config.interpolator ?? Ft.SEQ_REDS,
547
+ domainSpec: ne(f.normalization, J)
294
548
  };
295
- let _;
296
- x ? _ = dt(mt(y, w), g, c.colorMapCenter, c.colorMapReverse, C) : f !== "raster" && (_ = ht(g, C)), _ && (g.domainSpec = { type: M.USER, params: _ }), l.updateColorMap(p, { colorMap: g });
297
- } else O && l.updateColorMap(p, { colorMap: {} });
298
- if (m && f !== "raster") {
299
- const g = m.startsWith("properties.") ? m : `properties.${m}`;
300
- l.updateThematic(p, { collection: F, property: g });
549
+ let M;
550
+ X ? M = ee(te(A, V), g, f.colorMapCenter, f.colorMapReverse, O) : p !== "raster" && (M = re(g, O)), M && (g.domainSpec = { type: P.USER, params: M }), i.updateColorMap(m, { colorMap: g });
551
+ } else K && i.updateColorMap(m, { colorMap: {} });
552
+ if (w && p !== "raster") {
553
+ const g = w.startsWith("properties.") ? w : `properties.${w}`;
554
+ i.updateThematic(m, { collection: q, property: g });
301
555
  }
556
+ c.push(p === "raster" ? [] : ue(i, m, ht(E), S));
302
557
  }
558
+ return c;
303
559
  }
304
560
  return {
305
- async resolveMap(l, a, s = 0) {
306
- if (t && t.map && l) {
307
- ut(a, s);
308
- for (const d of a.layerRefs)
309
- yt(d);
310
- let u;
311
- if (Array.isArray(t.map) ? u = document.getElementById(t.map[s]) : u = document.getElementById(t.map), !u)
561
+ async resolveMap(i, l, u = 0) {
562
+ if (t && t.map && i) {
563
+ Kt(l, u);
564
+ for (const h of l.layerRefs)
565
+ oe(h), Wt(h.pointSize, R(h));
566
+ const d = l.camera && At(l.camera);
567
+ if (d)
568
+ throw new Error(`Map ${u}: ${d}`);
569
+ let c;
570
+ if (Array.isArray(t.map) ? c = document.getElementById(t.map[u]) : c = document.getElementById(t.map), !c)
312
571
  throw new Error("Could not find rendering target for map: " + t.map);
313
- if (!(u instanceof HTMLCanvasElement))
572
+ if (!(c instanceof HTMLCanvasElement))
314
573
  throw new Error("Target for map is not a canvas: " + t.map);
315
- const c = new Z(u);
316
- a.style && c.style.setPredefinedStyle(a.style), await c.init(), await n(c, l, a);
317
- for (const d of a.layerRefs)
318
- e?.set(d.dataRef, c), i?.set(d.dataRef, N(d));
319
- o && (o[s] = c), c.draw();
574
+ const f = new Ot(c);
575
+ let y;
576
+ try {
577
+ l.style && f.style.setPredefinedStyle(l.style), await f.init(), await I(i, l.workspace), y = await a(f, i, l);
578
+ } catch (h) {
579
+ try {
580
+ f.destroy();
581
+ } catch {
582
+ }
583
+ throw h;
584
+ }
585
+ const m = _t(l, u);
586
+ l.layerRefs.forEach((h, p) => e?.push({
587
+ map: f,
588
+ mapIndex: u,
589
+ mapId: m,
590
+ layerId: R(h),
591
+ dataRef: h.dataRef,
592
+ rows: y[p]
593
+ })), o && (o[u] = f), l.camera && le(f, l.camera), f.draw();
320
594
  }
321
595
  }
322
596
  };
323
597
  }
324
- function At(t) {
598
+ function fe(t) {
325
599
  return {
326
600
  scatter: "scatterplot",
327
601
  bar: "barchart",
@@ -332,229 +606,280 @@ function At(t) {
332
606
  heatmatrix: "heatmatrix"
333
607
  }[t];
334
608
  }
335
- function Rt(t, e, r, o, i, n) {
609
+ function N(t) {
610
+ return t.id ?? t.dataRef;
611
+ }
612
+ function vt(t, e, r, o) {
613
+ const { map: n, layerId: s } = o;
614
+ n.updateRenderInfo(s, { isPick: !0 }), n.events.on(Q.PICKING, ({ layerId: a, selection: i }) => {
615
+ a === s && t.setSelection(x(i, o.rows, e));
616
+ });
617
+ for (const a of r)
618
+ t.events.on(a, ({ selection: i }) => {
619
+ n.setHighlightedIds(s, x(i, e, o.rows));
620
+ });
621
+ }
622
+ async function de(t, e, r, o, n) {
623
+ const s = t.getTablesMetadata().find((a) => a.name === e);
624
+ return s && !dt(s) ? { type: "FeatureCollection", features: (await t.getTable(e)).map((i) => ({ type: "Feature", geometry: null, properties: i })) } : bt(o, wt(r, n), () => t.getLayer(e, gt(n)));
625
+ }
626
+ function pe(t, e, r, o, n, s, a, i) {
336
627
  return {
337
- async resolvePlot(l, a) {
628
+ async resolvePlot(l, u, d = 0) {
338
629
  if (!t || !t.plot) return;
339
- const s = document.getElementById(t.plot);
340
- if (!s) throw new Error(`Could not find plot target: ${t.plot}`);
341
- const u = l;
342
- if (!u) throw new Error("No data context available for plot.");
343
- const c = i?.get(a.dataRef) ?? await u.getLayer(a.dataRef), d = a.events ?? [], p = new tt(s, {
344
- type: At(a.mark),
345
- collection: c,
346
- attributes: { axis: a.axis, ...a.color && { color: a.color } },
347
- labels: { axis: a.axis, title: a.title },
348
- events: d,
349
- ...a.width && { width: a.width },
350
- ...a.height && { height: a.height },
351
- ...a.margins && { margins: a.margins },
352
- ...a.transform && { transform: a.transform }
630
+ const c = Array.isArray(t.plot) ? t.plot[d] : t.plot;
631
+ if (c === void 0) throw new Error(`Plot ${d} has no target: the plot targets name ${t.plot.length} elements.`);
632
+ const f = document.getElementById(c);
633
+ if (!f) throw new Error(`Could not find plot target: ${c}`);
634
+ const y = l;
635
+ if (!y) throw new Error("No data context available for plot.");
636
+ await I(y, u.workspace);
637
+ const m = b(u.workspace, u.dataRef), h = u.osmElements === !0 ? void 0 : n?.get(m), p = s?.get(m) ?? h ?? await de(y, u.dataRef, m, i, u.osmElements), w = u.events ?? [], _ = new kt(f, {
638
+ type: fe(u.mark),
639
+ collection: p,
640
+ attributes: { axis: u.axis, ...u.color && { color: u.color } },
641
+ labels: { axis: u.axis, title: u.title },
642
+ events: w,
643
+ ...u.width && { width: u.width },
644
+ ...u.height && { height: u.height },
645
+ ...u.margins && { margins: u.margins },
646
+ ...u.transform && { transform: u.transform }
353
647
  });
354
- if (r?.set(a.dataRef, p), a.mapRef && o?.set(a.dataRef, a.mapRef), a.mapRef && e) {
355
- const f = e.get(a.mapRef), m = n?.get(a.mapRef) ?? a.mapRef;
356
- if (f) {
357
- f.updateRenderInfo(m, { isPick: !0 }), f.events.on(B.PICKING, ({ selection: h }) => {
358
- p.setSelection(h);
359
- });
360
- for (const h of d)
361
- p.events.on(h, ({ selection: y }) => {
362
- f.setHighlightedIds(m, y);
363
- });
364
- }
365
- }
648
+ r?.set(N(u), _);
649
+ const E = ht(p.features ?? []);
650
+ a?.set(N(u), E);
651
+ for (const S of e ?? [])
652
+ !u.mapRef || S.dataRef !== u.mapRef || (vt(_, E, w, S), Et(o, N(u), S));
366
653
  }
367
654
  };
368
655
  }
369
- const q = 134217728, Mt = 4, St = 32;
370
- function Ct(t) {
656
+ const Rt = 134217728, me = 4, he = 32;
657
+ function ye(t) {
371
658
  return Array.isArray(t) ? t.join(`
372
659
  `) : t;
373
660
  }
374
- function E(t) {
661
+ function v(t) {
375
662
  return !!t && typeof t == "object" && !Array.isArray(t) && typeof t.fromFeature == "object" && t.fromFeature !== null;
376
663
  }
377
- function S(t, e) {
664
+ function T(t, e) {
378
665
  return t instanceof Map ? t.get(e) : t[e];
379
666
  }
380
- function L(t, e) {
667
+ function F(t, e) {
381
668
  return e.split(".").reduce((r, o) => {
382
669
  if (!(r == null || typeof r != "object"))
383
670
  return r[o];
384
671
  }, t);
385
672
  }
386
- function W(t) {
673
+ function St(t) {
387
674
  const e = [];
388
675
  for (const r of [t.uniforms, t.uniformMatrices])
389
676
  for (const o of Object.values(r ?? {}))
390
- E(o) && e.push(o);
677
+ v(o) && e.push(o);
391
678
  return e;
392
679
  }
393
- function It(t) {
394
- return [.../* @__PURE__ */ new Set([t.dataRef, ...W(t).map((e) => e.fromFeature.layer)])];
680
+ function we(t) {
681
+ return [.../* @__PURE__ */ new Set([t.dataRef, ...St(t).map((e) => e.fromFeature.layer)])];
395
682
  }
396
- function X(t) {
397
- for (const e of W(t)) {
683
+ function Ct(t) {
684
+ for (const e of St(t)) {
398
685
  const { iterate: r, layer: o } = e.fromFeature;
399
686
  if (r === "all" || r === "batched") return { mode: r, layer: o };
400
687
  }
401
688
  return null;
402
689
  }
403
- function J(t, e, r) {
404
- const o = t.fromFeature, i = r !== void 0 && o.iterate === "all" ? r : o.index ?? 0, n = S(e, o.layer)?.features?.[i];
405
- return n ? L(n, o.path) : void 0;
690
+ function It(t, e, r) {
691
+ const o = t.fromFeature, n = r !== void 0 && o.iterate === "all" ? r : o.index ?? 0, s = T(e, o.layer)?.features?.[n];
692
+ return s ? F(s, o.path) : void 0;
406
693
  }
407
- function j(t, e, r) {
694
+ function it(t, e, r) {
408
695
  if (!t) return;
409
696
  const o = {};
410
- for (const [i, n] of Object.entries(t)) {
411
- if (!E(n)) {
412
- o[i] = n;
697
+ for (const [n, s] of Object.entries(t)) {
698
+ if (!v(s)) {
699
+ o[n] = s;
413
700
  continue;
414
701
  }
415
- const l = Number(J(n, e, r) ?? NaN);
416
- Number.isFinite(l) ? o[i] = l : typeof n.default == "number" && (o[i] = n.default);
702
+ const a = Number(It(s, e, r) ?? NaN);
703
+ Number.isFinite(a) ? o[n] = a : typeof s.default == "number" && (o[n] = s.default);
417
704
  }
418
705
  return o;
419
706
  }
420
- function U(t, e, r) {
707
+ function st(t, e, r) {
421
708
  if (!t) return;
422
709
  const o = {};
423
- for (const [i, n] of Object.entries(t)) {
424
- if (!E(n)) {
425
- o[i] = n;
710
+ for (const [n, s] of Object.entries(t)) {
711
+ if (!v(s)) {
712
+ o[n] = s;
426
713
  continue;
427
714
  }
428
- const l = J(n, e, r), a = Array.isArray(l) ? l : Array.isArray(n.default) ? n.default : void 0;
429
- if (!a) continue;
430
- const s = n.cols ?? (Array.isArray(a[0]) ? a[0].length : 0);
431
- s > 0 ? o[i] = { data: a, cols: s } : console.warn(`[autk-grammar] uniform matrix "${i}" has no column count; entry dropped`);
715
+ const a = It(s, e, r), i = Array.isArray(a) ? a : Array.isArray(s.default) ? s.default : void 0;
716
+ if (!i) continue;
717
+ const l = s.cols ?? (Array.isArray(i[0]) ? i[0].length : 0);
718
+ l > 0 ? o[n] = { data: i, cols: l } : console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`);
432
719
  }
433
720
  return o;
434
721
  }
435
- function Lt(t) {
722
+ function ge(t) {
436
723
  return t != null && !(typeof t == "number" && !Number.isFinite(t));
437
724
  }
438
- function Q(t) {
439
- return E(t) && t.fromFeature.iterate === "batched";
725
+ function lt(t) {
726
+ return v(t) && t.fromFeature.iterate === "batched";
440
727
  }
441
- function K(t, e) {
442
- return Object.values(e ?? {}).some(Q) ? St : Object.values(t ?? {}).some(Q) ? Mt : 0;
728
+ function Lt(t, e) {
729
+ return Object.values(e ?? {}).some(lt) ? he : Object.values(t ?? {}).some(lt) ? me : 0;
443
730
  }
444
- function vt(t, e, r = q) {
445
- const o = K(t, e);
731
+ function be(t, e, r = Rt) {
732
+ const o = Lt(t, e);
446
733
  return o > 0 ? Math.floor(r / o) : Number.POSITIVE_INFINITY;
447
734
  }
448
- function Nt(t, e, r, o = q) {
449
- const i = {}, n = {}, l = [];
450
- for (const s of [t, e])
451
- for (const u of Object.values(s ?? {}))
452
- E(u) && u.fromFeature.iterate === "batched" && u.fromFeature.required && l.push(u.fromFeature.path);
453
- if (l.length > 0) {
454
- const s = r.length;
455
- r = r.filter((u) => l.every((c) => Lt(L(u, c)))), r.length < s && console.info(`[autk-grammar] batched compute dropped ${s - r.length} feature(s) missing ${l.join(", ")}`);
456
- }
457
- const a = vt(t, e, o);
458
- r.length > a && (console.warn(
459
- `[autk-grammar] batched compute capped at ${a} features (got ${r.length}): its largest packed array takes ${K(t, e)} B per feature, and a storage buffer binding holds ${o} B`
460
- ), r = r.slice(0, a));
461
- for (const [s, u] of Object.entries(t ?? {}))
462
- if (E(u) && u.fromFeature.iterate === "batched") {
463
- const c = typeof u.default == "number" ? u.default : void 0;
464
- n[s] = r.map((d) => {
465
- const p = Number(L(d, u.fromFeature.path) ?? c);
466
- return Number.isFinite(p) ? p : 0;
735
+ function _e(t, e, r, o = Rt) {
736
+ const n = {}, s = {}, a = [];
737
+ for (const l of [t, e])
738
+ for (const u of Object.values(l ?? {}))
739
+ v(u) && u.fromFeature.iterate === "batched" && u.fromFeature.required && a.push(u.fromFeature.path);
740
+ if (a.length > 0) {
741
+ const l = r.length;
742
+ r = r.filter((u) => a.every((d) => ge(F(u, d)))), r.length < l && console.info(`[autk-grammar] batched compute dropped ${l - r.length} feature(s) missing ${a.join(", ")}`);
743
+ }
744
+ const i = be(t, e, o);
745
+ r.length > i && (console.warn(
746
+ `[autk-grammar] batched compute capped at ${i} features (got ${r.length}): its largest packed array takes ${Lt(t, e)} B per feature, and a storage buffer binding holds ${o} B`
747
+ ), r = r.slice(0, i));
748
+ for (const [l, u] of Object.entries(t ?? {}))
749
+ if (v(u) && u.fromFeature.iterate === "batched") {
750
+ const d = typeof u.default == "number" ? u.default : void 0;
751
+ s[l] = r.map((c) => {
752
+ const f = Number(F(c, u.fromFeature.path) ?? d);
753
+ return Number.isFinite(f) ? f : 0;
467
754
  });
468
- } else typeof u == "number" && (i[s] = u);
469
- for (const [s, u] of Object.entries(e ?? {})) {
470
- if (!E(u) || u.fromFeature.iterate !== "batched") continue;
471
- const c = [];
472
- for (const d of r) {
473
- const p = L(d, u.fromFeature.path);
474
- let f = 1 / 0, m = 1 / 0, h = -1 / 0, y = -1 / 0;
475
- if (Array.isArray(p))
476
- for (const w of p) {
755
+ } else typeof u == "number" && (n[l] = u);
756
+ for (const [l, u] of Object.entries(e ?? {})) {
757
+ if (!v(u) || u.fromFeature.iterate !== "batched") continue;
758
+ const d = [];
759
+ for (const c of r) {
760
+ const f = F(c, u.fromFeature.path);
761
+ let y = 1 / 0, m = 1 / 0, h = -1 / 0, p = -1 / 0;
762
+ if (Array.isArray(f))
763
+ for (const w of f) {
477
764
  if (!Array.isArray(w) || w.length < 2) continue;
478
- const A = Number(w[0]), b = Number(w[1]);
479
- !Number.isFinite(A) || !Number.isFinite(b) || (f = Math.min(f, A), m = Math.min(m, b), h = Math.max(h, A), y = Math.max(y, b));
765
+ const _ = Number(w[0]), E = Number(w[1]);
766
+ !Number.isFinite(_) || !Number.isFinite(E) || (y = Math.min(y, _), m = Math.min(m, E), h = Math.max(h, _), p = Math.max(p, E));
480
767
  }
481
- Number.isFinite(f) || (f = 0, m = 0, h = 0, y = 0), c.push(f, m, h, m, h, y, f, y);
768
+ Number.isFinite(y) || (y = 0, m = 0, h = 0, p = 0), d.push(y, m, h, m, h, p, y, p);
482
769
  }
483
- n[s] = c;
770
+ s[l] = d;
484
771
  }
485
- return i.num_features = r.length, { uniforms: i, uniformArrays: n };
772
+ return n.num_features = r.length, { uniforms: n, uniformArrays: s };
486
773
  }
487
- function Y(t, e, r) {
488
- const o = S(e, t.dataRef);
774
+ function ut(t, e, r) {
775
+ const o = T(e, t.dataRef);
489
776
  if (!o) throw new Error(`compute: table "${t.dataRef}" is not loaded`);
490
- const i = {
777
+ const n = {
491
778
  collection: o,
492
779
  variableMapping: t.attributes,
493
- wgslBody: Ct(t.wglsFunction)
780
+ wgslBody: ye(t.wgslFunction)
494
781
  };
495
- t.attributeArrays && (i.attributeArrays = t.attributeArrays), t.attributeMatrices && (i.attributeMatrices = t.attributeMatrices), t.uniformArrays && (i.uniformArrays = t.uniformArrays), t.outputColumnName && (i.resultField = t.outputColumnName), t.outputColumns && (i.outputColumns = t.outputColumns);
496
- const n = X(t);
497
- if (n?.mode === "batched") {
498
- const u = S(e, n.layer)?.features ?? [], c = Nt(t.uniforms, t.uniformMatrices, u), d = j(V(t.uniforms), e) ?? {}, p = U(V(t.uniformMatrices), e);
499
- return i.uniforms = { ...d, ...c.uniforms }, i.uniformArrays = { ...i.uniformArrays ?? {}, ...c.uniformArrays }, p && Object.keys(p).length > 0 && (i.uniformMatrices = p), i;
782
+ t.attributeArrays && (n.attributeArrays = t.attributeArrays), t.attributeMatrices && (n.attributeMatrices = t.attributeMatrices), t.uniformArrays && (n.uniformArrays = t.uniformArrays), t.outputColumnName && (n.resultField = t.outputColumnName), t.outputColumns && (n.outputColumns = t.outputColumns);
783
+ const s = Ct(t);
784
+ if (s?.mode === "batched") {
785
+ const u = T(e, s.layer)?.features ?? [], d = _e(t.uniforms, t.uniformMatrices, u), c = it(ct(t.uniforms), e) ?? {}, f = st(ct(t.uniformMatrices), e);
786
+ return n.uniforms = { ...c, ...d.uniforms }, n.uniformArrays = { ...n.uniformArrays ?? {}, ...d.uniformArrays }, f && Object.keys(f).length > 0 && (n.uniformMatrices = f), n;
500
787
  }
501
- const l = n?.mode === "all" ? r : void 0, a = j(t.uniforms, e, l), s = U(t.uniformMatrices, e, l);
502
- return a && (i.uniforms = a), s && (i.uniformMatrices = s), i;
788
+ const a = s?.mode === "all" ? r : void 0, i = it(t.uniforms, e, a), l = st(t.uniformMatrices, e, a);
789
+ return i && (n.uniforms = i), l && (n.uniformMatrices = l), n;
503
790
  }
504
- function V(t) {
791
+ function ct(t) {
505
792
  if (t)
506
- return Object.fromEntries(Object.entries(t).filter(([, e]) => !(E(e) && e.fromFeature.iterate === "batched")));
793
+ return Object.fromEntries(Object.entries(t).filter(([, e]) => !(v(e) && e.fromFeature.iterate === "batched")));
507
794
  }
508
- function Pt(t) {
795
+ function Ee(t) {
509
796
  return t.outputColumns ?? (t.outputColumnName ? [t.outputColumnName] : []);
510
797
  }
511
- async function Bt(t, e, r) {
512
- const o = X(t);
513
- if (o?.mode !== "all") return r(Y(t, e));
514
- const i = S(e, t.dataRef);
515
- if (!i) throw new Error(`compute: table "${t.dataRef}" is not loaded`);
516
- const n = Pt(t), l = structuredClone(i);
517
- for (const s of l.features) {
518
- const u = s.properties ??= {}, c = u.compute ??= {};
519
- for (const d of n) c[d] = 0;
520
- }
521
- const a = S(e, o.layer)?.features?.length ?? 0;
522
- for (let s = 0; s < a; s++) {
523
- const u = await r({ ...Y(t, e, s), collection: l });
524
- l.features.forEach((c, d) => {
525
- const p = c.properties?.compute, f = u.features[d]?.properties?.compute;
526
- if (!(!p || !f))
527
- for (const m of n) {
528
- const h = Number(f[m]);
529
- Number.isFinite(h) && (p[m] += h);
798
+ async function Me(t, e, r) {
799
+ const o = Ct(t);
800
+ if (o?.mode !== "all") return r(ut(t, e));
801
+ const n = T(e, t.dataRef);
802
+ if (!n) throw new Error(`compute: table "${t.dataRef}" is not loaded`);
803
+ const s = Ee(t), a = structuredClone(n);
804
+ for (const l of a.features) {
805
+ const u = l.properties ??= {}, d = u.compute ??= {};
806
+ for (const c of s) d[c] = 0;
807
+ }
808
+ const i = T(e, o.layer)?.features?.length ?? 0;
809
+ for (let l = 0; l < i; l++) {
810
+ const u = await r({ ...ut(t, e, l), collection: a });
811
+ a.features.forEach((d, c) => {
812
+ const f = d.properties?.compute, y = u.features[c]?.properties?.compute;
813
+ if (!(!f || !y))
814
+ for (const m of s) {
815
+ const h = Number(y[m]);
816
+ Number.isFinite(h) && (f[m] += h);
530
817
  }
531
818
  });
532
819
  }
533
- return l;
820
+ return a;
534
821
  }
535
- function Ft(t) {
536
- return {
537
- async resolveCompute(e, r) {
538
- if (e) {
539
- const o = {};
540
- for (const l of It(r)) {
541
- const a = t?.get(l);
542
- if (a) o[l] = a;
543
- else if (l === r.dataRef) o[l] = await e.getLayer(l);
544
- else
545
- try {
546
- o[l] = await e.getLayer(l);
547
- } catch {
548
- o[l] = void 0;
549
- }
822
+ const ft = ["surface", "parks", "water", "roads", "buildings", "polygons", "polylines"];
823
+ function Ae(t, e, r, o) {
824
+ return o?.get(b(r, e)) ?? t.getTablesMetadata().find((n) => n.name === e)?.type;
825
+ }
826
+ function ve(t, e) {
827
+ async function r(a, i, l) {
828
+ return t?.get(b(l, i)) ?? await a.getLayer(i);
829
+ }
830
+ function o(a, i, l, u, d) {
831
+ if (!t) return;
832
+ const c = u.outputTableName ?? l;
833
+ t.set(b(u.workspace, c), i);
834
+ const f = u.layerType ?? d ?? Ae(a, l, u.workspace, e);
835
+ u.outputTableName && f && e?.set(b(u.workspace, c), f);
836
+ }
837
+ async function n(a, i) {
838
+ for (const d of i.layers)
839
+ if (!ft.includes(d.type))
840
+ throw new Error(`Render pass "${i.outputTableName}": layer "${d.id}" has the type "${d.type}", which a render pass cannot draw. A layer's type is one of ${ft.join(", ")}.`);
841
+ const l = await Promise.all(i.layers.map(async (d) => ({
842
+ id: d.id,
843
+ collection: await r(a, d.dataRef, i.workspace),
844
+ type: d.type,
845
+ objectIdProperty: d.objectIdProperty
846
+ }))), u = await new Z().renderPipeline({
847
+ layers: l,
848
+ viewpoints: {
849
+ collection: await r(a, i.viewpoints.dataRef, i.workspace),
850
+ strategy: i.viewpoints.strategy,
851
+ sampling: i.viewpoints.sampling
852
+ },
853
+ aggregation: i.aggregation,
854
+ camera: i.camera,
855
+ tileSize: i.tileSize
856
+ });
857
+ o(a, u, i.viewpoints.dataRef, i, i.viewpoints.strategy?.type === "building-windows" ? "points" : void 0);
858
+ }
859
+ async function s(a, i) {
860
+ const l = {};
861
+ for (const c of we(i)) {
862
+ const f = t?.get(b(i.workspace, c));
863
+ if (f) l[c] = f;
864
+ else if (c === i.dataRef) l[c] = await a.getLayer(c);
865
+ else
866
+ try {
867
+ l[c] = await a.getLayer(c);
868
+ } catch {
869
+ l[c] = void 0;
550
870
  }
551
- const i = new rt(), n = await Bt(r, o, (l) => i.gpgpuPipeline(l));
552
- return t && t.set(r.dataRef, n), e;
553
- }
871
+ }
872
+ const u = new Z(), d = await Me(i, l, (c) => u.gpgpuPipeline(c));
873
+ o(a, d, i.dataRef, i);
874
+ }
875
+ return {
876
+ async resolveCompute(a, i) {
877
+ if (a)
878
+ return await I(a, i.workspace), i.type === "render" ? await n(a, i) : await s(a, i), a;
554
879
  }
555
880
  };
556
881
  }
557
- class Tt {
882
+ class Re {
558
883
  _listeners = /* @__PURE__ */ new Map();
559
884
  on(e, r) {
560
885
  this._listeners.has(e) || this._listeners.set(e, /* @__PURE__ */ new Set());
@@ -566,27 +891,50 @@ class Tt {
566
891
  this._listeners.get(e)?.forEach((o) => o(r));
567
892
  }
568
893
  }
569
- class jt {
894
+ function C(t) {
895
+ return t === void 0 ? [] : Array.isArray(t) ? t : [t];
896
+ }
897
+ function Se(t) {
898
+ const e = /* @__PURE__ */ new Set();
899
+ for (const o of [...C(t.map), ...C(t.plot)])
900
+ if (o.id !== void 0) {
901
+ if (o.id === "") throw new Error("A map or plot has an empty id.");
902
+ if (e.has(o.id)) throw new Error(`Two maps or plots have the id "${o.id}"; an id names one view.`);
903
+ e.add(o.id);
904
+ }
905
+ const r = /* @__PURE__ */ new Map();
906
+ for (const o of C(t.plot)) {
907
+ const n = N(o), s = r.get(n);
908
+ if (s)
909
+ throw new Error(s.id === void 0 && o.id === void 0 ? `Two plots of the table "${n}" have no id; give each plot an id.` : `A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);
910
+ r.set(n, o);
911
+ }
912
+ }
913
+ class $e {
570
914
  dataAdapter;
571
915
  mapAdapter;
572
916
  plotAdapter;
573
917
  computeAdapter;
574
918
  grammarEngine;
575
919
  _computeCache = /* @__PURE__ */ new Map();
920
+ _computeTypes = /* @__PURE__ */ new Map();
576
921
  _data = {};
577
- _mapRegistry = /* @__PURE__ */ new Map();
578
- _mapLayerIds = /* @__PURE__ */ new Map();
922
+ _layers = [];
579
923
  _maps = [];
580
924
  _plotRegistry = /* @__PURE__ */ new Map();
581
925
  _fwdCleanups = [];
582
- _plotMapLinks = /* @__PURE__ */ new Map();
583
- interactions = new Tt();
926
+ _plotLinks = /* @__PURE__ */ new Map();
927
+ _plotRows = /* @__PURE__ */ new Map();
928
+ _exports = /* @__PURE__ */ new Map();
929
+ /** Each GeoJSON table a run loaded and each table a join wrote, which its plots read before the database. */
930
+ _geojsonCache = /* @__PURE__ */ new Map();
931
+ interactions = new Re();
584
932
  constructor(e) {
585
- const r = /* @__PURE__ */ new Map();
586
- this.dataAdapter = lt(e, r), this.mapAdapter = wt(e, this._mapRegistry, this._computeCache, this._maps, this._mapLayerIds), this.plotAdapter = Rt(e, this._mapRegistry, this._plotRegistry, this._plotMapLinks, r, this._mapLayerIds), this.computeAdapter = Ft(this._computeCache);
933
+ this.dataAdapter = Vt(e, this._geojsonCache), this.mapAdapter = ce(e, this._layers, this._computeCache, this._maps, this._computeTypes, this._exports), this.plotAdapter = pe(e, this._layers, this._plotRegistry, this._plotLinks, this._geojsonCache, this._computeCache, this._plotRows, this._exports), this.computeAdapter = ve(this._computeCache, this._computeTypes);
587
934
  }
588
935
  /**
589
- * The coordinate reference system used internally by the autk workspace.
936
+ * The coordinate reference system autk-db stores a workspace's tables in, unless the spec's `workspaces` sets
937
+ * another for it.
590
938
  *
591
939
  * Input data is expected in EPSG:4326 (WGS84) by default and is transformed
592
940
  * to this CRS on load. Consumers that prepare data for injection (e.g. by
@@ -594,7 +942,7 @@ class jt {
594
942
  * instead of hard-coding a CRS string.
595
943
  */
596
944
  get workspaceCrs() {
597
- return k;
945
+ return $t;
598
946
  }
599
947
  get data() {
600
948
  return this._data;
@@ -610,18 +958,51 @@ class jt {
610
958
  get maps() {
611
959
  return this._maps;
612
960
  }
961
+ /**
962
+ * Every layer the maps of the last {@link run} draw for a table, found by the table's name (a layer's `dataRef`):
963
+ * for each, the map that draws it and the layer's id in that map, which is its `title`, else its `dataRef`. The
964
+ * maps come in the spec's order, each map's layers bottom first. Empty when no map draws the table.
965
+ *
966
+ * @param dataRef The table's name.
967
+ * @param mapId The map to look in, by its {@link MapId}: a string names a map by its `id`, a number by its index in
968
+ * the spec's `map` list. Without it, every map.
969
+ */
970
+ mapLayers(e, r) {
971
+ return this._layersOf(e, r).map(({ map: o, layerId: n }) => ({ map: o, layerId: n }));
972
+ }
613
973
  /**
614
974
  * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):
615
975
  * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.
616
- * `undefined` when no map draws the table. When several layers draw it, the last one.
976
+ * `undefined` when no map draws the table. When several layers draw it, the last one, which is the last map's;
977
+ * {@link mapLayers} lists them all.
978
+ *
979
+ * @param dataRef The table's name.
980
+ * @param mapId The map to look in, by its {@link MapId}: a string names a map by its `id`, a number by its index in
981
+ * the spec's `map` list. Without it, every map.
617
982
  *
618
983
  * @example
619
984
  * const layer = grammar.mapLayer('buildings');
620
985
  * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });
621
986
  */
622
- mapLayer(e) {
623
- const r = this._mapRegistry.get(e);
624
- return r ? { map: r, layerId: this._mapLayerIds.get(e) ?? e } : void 0;
987
+ mapLayer(e, r) {
988
+ return this.mapLayers(e, r).pop();
989
+ }
990
+ /** The drawn layers of a table, on every map or on the one `mapId` names. */
991
+ _layersOf(e, r) {
992
+ return this._layers.filter((o) => o.dataRef === e && U(o, r));
993
+ }
994
+ /**
995
+ * Releases what the last run created: every map (its layers' GPU buffers, its textures, its canvas context, the
996
+ * controls it adds to the page and its event handlers) and the grammar's own registries, caches and event
997
+ * forwarding. autk-map's maps share one GPU device, which stays for the maps of the next run. Call it before the
998
+ * page or the container goes away; `run` calls it before it starts, so running a new spec on the same instance
999
+ * does not leak the maps of the old one.
1000
+ */
1001
+ destroy() {
1002
+ for (const e of this._fwdCleanups) e();
1003
+ this._fwdCleanups = [];
1004
+ for (const e of this._maps) e.destroy();
1005
+ this._maps.length = 0, this._layers.length = 0, this._plotRegistry.clear(), this._plotLinks.clear(), this._plotRows.clear(), this._exports.clear(), this._geojsonCache.clear(), this._computeCache.clear(), this._computeTypes.clear(), this.grammarEngine = void 0, this._data = {};
625
1006
  }
626
1007
  async run(e) {
627
1008
  if (!this.dataAdapter)
@@ -632,7 +1013,7 @@ class jt {
632
1013
  throw new Error("Plot adapter not initialized. Please call the constructor first.");
633
1014
  if (!this.computeAdapter)
634
1015
  throw new Error("Compute adapter not initialized. Please call the constructor first.");
635
- this._mapRegistry.clear(), this._mapLayerIds.clear(), this._maps.length = 0, this._plotRegistry.clear(), this._plotMapLinks.clear(), this._computeCache.clear(), this.grammarEngine = ot({
1016
+ Se(e), this.destroy(), this.grammarEngine = Bt({
636
1017
  spec: e,
637
1018
  adapters: {
638
1019
  db: this.dataAdapter,
@@ -640,103 +1021,164 @@ class jt {
640
1021
  plot: this.plotAdapter,
641
1022
  compute: this.computeAdapter
642
1023
  }
643
- }), await this.grammarEngine.run(), this._rewireInteractions();
1024
+ }), await this.grammarEngine.run();
644
1025
  const r = this.grammarEngine.context;
645
- if (!r) {
1026
+ if (r && await I(r), this._wireLinks(e), this._rewireInteractions(e), !r) {
646
1027
  console.warn("Grammar engine produced no data context."), this._data = {};
647
1028
  return;
648
1029
  }
649
1030
  const o = {};
650
- for (const i of r.getLayersMetadata())
651
- Object.defineProperty(o, i.name, {
1031
+ for (const n of r.getLayersMetadata())
1032
+ Object.defineProperty(o, n.name, {
652
1033
  get: () => {
653
- const n = this._computeCache.get(i.name);
654
- return n ? Promise.resolve(n) : r.getLayer(i.name);
1034
+ const s = this._computeCache.get(n.name);
1035
+ return s ? Promise.resolve(s) : r.getLayer(n.name);
655
1036
  },
656
1037
  enumerable: !0,
657
1038
  configurable: !0
658
1039
  });
1040
+ for (const n of this._computeCache.keys())
1041
+ n in o || Object.defineProperty(o, n, {
1042
+ get: () => Promise.resolve(this._computeCache.get(n)),
1043
+ enumerable: !0,
1044
+ configurable: !0
1045
+ });
659
1046
  this._data = o;
660
1047
  }
661
1048
  /**
662
- * Highlights features on the map layer that draws the table `dataRef` (see {@link mapLayer}).
663
- * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.
1049
+ * Highlights features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}), or only
1050
+ * in the map `mapId` names. If a plot is linked to one of those layers, by a link or its `mapRef`, the plot
1051
+ * selection is updated too, to the same rows: the plot finds them by their feature ids, since it can draw the
1052
+ * table's rows in another order and draws the rows without a geometry, which a layer leaves out.
1053
+ *
1054
+ * @param dataRef The table's name.
1055
+ * @param featureIds The features to highlight: their positions among those the layer draws.
1056
+ * @param mapId The map to highlight on, by its {@link MapId}: a string names a map by its `id`, a number by its
1057
+ * index in the spec's `map` list. Without it, every map that draws the table.
664
1058
  */
665
- highlightOnMap(e, r) {
666
- const o = this.mapLayer(e);
667
- o?.map.setHighlightedIds(o.layerId, r);
668
- for (const [i, n] of this._plotMapLinks)
669
- n === e && this._plotRegistry.get(i)?.setSelection(r);
1059
+ highlightOnMap(e, r, o) {
1060
+ const n = this._layersOf(e, o);
1061
+ for (const { map: s, layerId: a } of n) s.setHighlightedIds(a, r);
1062
+ this._selectInLinkedPlots(n, r);
670
1063
  }
671
1064
  /**
672
- * Clears highlighted features on the map layer that draws the table `dataRef` (see {@link mapLayer}).
673
- * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.
1065
+ * Clears highlighted features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}),
1066
+ * or only in the map `mapId` names. If a plot is linked to one of those layers, by a link or its `mapRef`, the plot
1067
+ * selection is cleared too.
1068
+ *
1069
+ * @param dataRef The table's name.
1070
+ * @param mapId The map to clear, by its {@link MapId}: a string names a map by its `id`, a number by its index in
1071
+ * the spec's `map` list. Without it, every map that draws the table.
674
1072
  */
675
- clearHighlightOnMap(e) {
676
- const r = this.mapLayer(e);
677
- r?.map.clearHighlightedIds(r.layerId);
678
- for (const [o, i] of this._plotMapLinks)
679
- i === e && this._plotRegistry.get(o)?.setSelection([]);
1073
+ clearHighlightOnMap(e, r) {
1074
+ const o = this._layersOf(e, r);
1075
+ for (const { map: n, layerId: s } of o) n.clearHighlightedIds(s);
1076
+ this._selectInLinkedPlots(o, []);
680
1077
  }
681
1078
  /**
682
- * Clears the selection on the plot identified by `plotId` (its dataRef).
683
- * If that plot is linked to a map via `mapRef`, the map highlight is cleared too.
1079
+ * Clears the selection on the plot `plotId` names: its `id`, else its `dataRef`.
1080
+ * If that plot is linked to map layers, by links or its `mapRef`, their highlights are cleared too: on every map,
1081
+ * or only on the map `mapId` names.
1082
+ *
1083
+ * @param plotId The plot: its `id`, else its `dataRef`.
1084
+ * @param mapId The map whose linked layers to clear, by its {@link MapId}: a string names a map by its `id`, a
1085
+ * number by its index in the spec's `map` list. Without it, every linked layer.
684
1086
  */
685
- clearHighlightOnPlot(e) {
1087
+ clearHighlightOnPlot(e, r) {
686
1088
  this._plotRegistry.get(e)?.setSelection([]);
687
- const r = this._plotMapLinks.get(e), o = r ? this.mapLayer(r) : void 0;
688
- o?.map.clearHighlightedIds(o.layerId);
1089
+ for (const o of this._plotLinks.get(e) ?? [])
1090
+ U(o, r) && o.map.clearHighlightedIds(o.layerId);
689
1091
  }
690
1092
  /**
691
- * Applies a selection to the plot identified by `plotId` (its dataRef).
692
- * If that plot is linked to a map via `mapRef`, the map highlight is updated too.
1093
+ * Applies a selection to the plot `plotId` names: its `id`, else its `dataRef`.
1094
+ * If that plot is linked to map layers, by links or its `mapRef`, their highlights are updated too, to the same rows
1095
+ * (see {@link highlightOnMap}): on every map, or only on the map `mapId` names.
1096
+ *
1097
+ * @param plotId The plot: its `id`, else its `dataRef`.
1098
+ * @param featureIds The features to select: their positions among those the plot draws.
1099
+ * @param mapId The map whose linked layers to highlight, by its {@link MapId}: a string names a map by its `id`, a
1100
+ * number by its index in the spec's `map` list. Without it, every linked layer.
693
1101
  */
694
- setPlotSelection(e, r) {
1102
+ setPlotSelection(e, r, o) {
695
1103
  this._plotRegistry.get(e)?.setSelection(r);
696
- const o = this._plotMapLinks.get(e), i = o ? this.mapLayer(o) : void 0;
697
- i?.map.setHighlightedIds(i.layerId, r);
1104
+ const n = this._plotRows.get(e) ?? [];
1105
+ for (const s of this._plotLinks.get(e) ?? [])
1106
+ U(s, o) && s.map.setHighlightedIds(s.layerId, x(r, n, s.rows));
1107
+ }
1108
+ /**
1109
+ * Applies a selection made on `layers`, by their positions `featureIds`, to every plot linked to one of them, at the
1110
+ * plot's own positions of the selected rows.
1111
+ */
1112
+ _selectInLinkedPlots(e, r) {
1113
+ for (const [o, n] of this._plotLinks) {
1114
+ const s = n.filter((l) => e.includes(l));
1115
+ if (s.length === 0) continue;
1116
+ const a = this._plotRows.get(o) ?? [], i = new Set(s.flatMap((l) => x(r, l.rows, a)));
1117
+ this._plotRegistry.get(o)?.setSelection([...i]);
1118
+ }
698
1119
  }
699
- _rewireInteractions() {
700
- for (const r of this._fwdCleanups) r();
1120
+ /** Wires each entry of `links` between a plot and a layer of a map, both now drawn. */
1121
+ _wireLinks(e) {
1122
+ const r = C(e.map), o = C(e.plot);
1123
+ for (const n of e.links ?? []) {
1124
+ const s = o.find((c) => N(c) === n.source), a = this._plotRegistry.get(n.source);
1125
+ if (!s || !a)
1126
+ throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);
1127
+ const i = r.findIndex((c) => c.id === n.target), l = this._maps[i];
1128
+ if (i < 0 || !l)
1129
+ throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);
1130
+ const u = r[i].layerRefs.find((c) => n.layer !== void 0 ? R(c) === n.layer : c.dataRef === s.dataRef);
1131
+ if (!u)
1132
+ throw new Error(n.layer !== void 0 ? `Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".` : `Link from "${n.source}": map "${n.target}" draws no layer of the table "${s.dataRef}"; name the layer.`);
1133
+ const d = this._layers.find((c) => c.mapIndex === i && c.layerId === R(u));
1134
+ d && (vt(a, this._plotRows.get(n.source) ?? [], s.events ?? [], d), Et(this._plotLinks, n.source, d));
1135
+ }
1136
+ }
1137
+ _rewireInteractions(e) {
1138
+ for (const o of this._fwdCleanups) o();
701
1139
  this._fwdCleanups = [];
702
- const e = /* @__PURE__ */ new Set();
703
- for (const [r, o] of this._mapRegistry) {
704
- if (e.has(o)) continue;
705
- e.add(o);
706
- const i = ({ selection: n }) => {
707
- this.interactions.emit("map:picking", { layerId: r, selection: n });
1140
+ const r = C(e.map);
1141
+ this._maps.forEach((o, n) => {
1142
+ const s = _t(r[n], n), a = ({ layerId: i, selection: l }) => {
1143
+ this.interactions.emit("map:picking", { mapId: s, layerId: i, selection: l });
708
1144
  };
709
- o.events.on(B.PICKING, i), this._fwdCleanups.push(() => o.events.off(B.PICKING, i));
710
- }
711
- for (const [r, o] of this._plotRegistry)
712
- for (const i of [I.CLICK, I.BRUSH, I.BRUSH_X, I.BRUSH_Y]) {
713
- const n = ({ selection: l }) => {
1145
+ o.events.on(Q.PICKING, a), this._fwdCleanups.push(() => o.events.off(Q.PICKING, a));
1146
+ });
1147
+ for (const [o, n] of this._plotRegistry)
1148
+ for (const s of [k.CLICK, k.BRUSH, k.BRUSH_X, k.BRUSH_Y]) {
1149
+ const a = ({ selection: i }) => {
714
1150
  this.interactions.emit("plot:selection", {
715
- plotId: r,
716
- event: i,
717
- selection: l
1151
+ plotId: o,
1152
+ event: s,
1153
+ selection: i
718
1154
  });
719
1155
  };
720
- o.events.on(i, n), this._fwdCleanups.push(() => o.events.off(i, n));
1156
+ n.events.on(s, a), this._fwdCleanups.push(() => n.events.off(s, a));
721
1157
  }
722
1158
  }
723
1159
  }
724
1160
  export {
725
- jt as AutkGrammar,
726
- nt as ColorMapInterpolator,
727
- Tt as GrammarEventEmitter,
728
- H as NormalizationMode,
729
- q as STORAGE_BUFFER_BINDING_SIZE,
730
- Nt as buildBatchedUniforms,
731
- It as computeLayerNames,
732
- ot as createEngine,
733
- X as findIterateSource,
734
- E as isFromFeature,
735
- Ct as joinWgsl,
736
- vt as maxBatchedFeatures,
737
- Y as resolveComputeParams,
738
- U as resolveUniformMatrices,
739
- j as resolveUniforms,
740
- Bt as runCompute
1161
+ $e as AutkGrammar,
1162
+ xt as ColorMapInterpolator,
1163
+ Re as GrammarEventEmitter,
1164
+ pt as NormalizationMode,
1165
+ Rt as STORAGE_BUFFER_BINDING_SIZE,
1166
+ le as applyCamera,
1167
+ Te as arrangeViews,
1168
+ _e as buildBatchedUniforms,
1169
+ we as computeLayerNames,
1170
+ ve as createComputeAdapter,
1171
+ Vt as createDataAdapter,
1172
+ Bt as createEngine,
1173
+ I as enterWorkspace,
1174
+ Ct as findIterateSource,
1175
+ v as isFromFeature,
1176
+ ye as joinWgsl,
1177
+ be as maxBatchedFeatures,
1178
+ ut as resolveComputeParams,
1179
+ st as resolveUniformMatrices,
1180
+ it as resolveUniforms,
1181
+ Me as runCompute,
1182
+ b as tableKey
741
1183
  };
742
1184
  //# sourceMappingURL=autk-grammar.js.map