@urban-toolkit/autk-grammar 5.0.0 → 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 +1 @@
1
- {"version":3,"file":"autk-grammar.js","sources":["../../../grammar/dist/the-urban-grammar.js","../src/workspace.ts","../src/rows.ts","../src/adapters/data.ts","../src/drawn.ts","../src/point-size.ts","../src/adapters/map.ts","../src/adapters/plot.ts","../src/compute-params.ts","../src/adapters/compute.ts","../src/types.ts","../src/main.ts"],"sourcesContent":["function B(e) {\n const { spec: t, adapters: _ } = e;\n let s;\n async function u() {\n let n;\n if (t.data)\n for (const i of t.data)\n n = await _.db.resolveSource(n, i);\n if (t.compute)\n for (const i of t.compute)\n n = await _.compute.resolveCompute(n, i);\n if (t.map)\n if (Array.isArray(t.map))\n for (let i = 0; i < t.map.length; i++) {\n let E = t.map[i];\n await _.map.resolveMap(n, E, i);\n }\n else\n await _.map.resolveMap(n, t.map);\n if (t.plot)\n if (Array.isArray(t.plot))\n for (let i = 0; i < t.plot.length; i++)\n await _.plot.resolvePlot(n, t.plot[i], i);\n else\n await _.plot.resolvePlot(n, t.plot);\n s = n;\n }\n function S(n) {\n return console.log(\"Spec to update\", n), new Promise((i) => {\n i();\n });\n }\n function c() {\n console.log(\"Function not implemented yet\");\n }\n return { run: u, updatedSpec: S, destroy: c, get context() {\n return s;\n } };\n}\nfunction A(e) {\n return e === void 0 ? [] : Array.isArray(e) ? e : [e];\n}\nfunction G(e) {\n const t = e.layout ?? {}, _ = t.type ?? \"vertical\";\n if (_ !== \"vertical\" && _ !== \"horizontal\" && _ !== \"grid\")\n throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(_)}.`);\n const s = t.gap ?? 0;\n if (typeof s != \"number\" || !Number.isFinite(s) || s < 0)\n throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(s)}.`);\n const u = t.columns ?? 2;\n if (!Number.isInteger(u) || u < 1)\n throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(u)}.`);\n const S = [\n ...A(e.map).map((i, E) => ({ kind: \"map\", index: E, id: i.id, key: i.id ?? E })),\n ...A(e.plot).map((i, E) => ({ kind: \"plot\", index: E, id: i.id, key: i.id ?? i.dataRef }))\n ], c = _ === \"vertical\" ? 1 : _ === \"horizontal\" ? Math.max(S.length, 1) : u, n = S.map(({ kind: i, index: E, id: m, key: d }, R) => ({\n kind: i,\n index: E,\n ...m !== void 0 && { id: m },\n key: d,\n row: Math.floor(R / c),\n column: R % c\n }));\n return { type: _, rows: Math.ceil(S.length / c), columns: c, gap: s, panes: n };\n}\nvar P = /* @__PURE__ */ ((e) => (e.CAT_ACCENT = \"schemeAccent\", e.CAT_DARK2 = \"schemeDark2\", e.CAT_CATEGORY10 = \"schemeCategory10\", e.CAT_OBSERVABLE10 = \"schemeObservable10\", e.CAT_PAIRED = \"schemePaired\", e.CAT_PASTEL1 = \"schemePastel1\", e.CAT_PASTEL2 = \"schemePastel2\", e.CAT_SET1 = \"schemeSet1\", e.CAT_SET2 = \"schemeSet2\", e.CAT_SET3 = \"schemeSet3\", e.CAT_TABLEAU10 = \"schemeTableau10\", e.SEQ_REDS = \"interpolateReds\", e.SEQ_BLUES = \"interpolateBlues\", e.SEQ_GREENS = \"interpolateGreens\", e.SEQ_GREYS = \"interpolateGreys\", e.SEQ_ORANGES = \"interpolateOranges\", e.SEQ_PURPLES = \"interpolatePurples\", e.SEQ_TURBO = \"interpolateTurbo\", e.SEQ_VIRIDIS = \"interpolateViridis\", e.SEQ_INFERNO = \"interpolateInferno\", e.SEQ_MAGMA = \"interpolateMagma\", e.SEQ_PLASMA = \"interpolatePlasma\", e.SEQ_CIVIDIS = \"interpolateCividis\", e.SEQ_WARM = \"interpolateWarm\", e.SEQ_COOL = \"interpolateCool\", e.SEQ_CUBEHELIX_DEFAULT = \"interpolateCubehelixDefault\", e.SEQ_BU_GN = \"interpolateBuGn\", e.SEQ_BU_PU = \"interpolateBuPu\", e.SEQ_GN_BU = \"interpolateGnBu\", e.SEQ_OR_RD = \"interpolateOrRd\", e.SEQ_PU_BU_GN = \"interpolatePuBuGn\", e.SEQ_PU_BU = \"interpolatePuBu\", e.SEQ_PU_RD = \"interpolatePuRd\", e.SEQ_RD_PU = \"interpolateRdPu\", e.SEQ_YL_GN_BU = \"interpolateYlGnBu\", e.SEQ_YL_GN = \"interpolateYlGn\", e.SEQ_YL_OR_BR = \"interpolateYlOrBr\", e.SEQ_YL_OR_RD = \"interpolateYlOrRd\", e.DIV_BR_BG = \"interpolateBrBG\", e.DIV_PR_GN = \"interpolatePRGn\", e.DIV_PI_YG = \"interpolatePiYG\", e.DIV_PU_OR = \"interpolatePuOr\", e.DIV_RED_BLUE = \"interpolateRdBu\", e.DIV_RED_GREY = \"interpolateRdGy\", e.DIV_RED_YELLOW_BLUE = \"interpolateRdYlBu\", e.DIV_RED_YELLOW_GREEN = \"interpolateRdYlGn\", e.DIV_SPECTRAL = \"interpolateSpectral\", e))(P || {}), f = /* @__PURE__ */ ((e) => (e.MIN_MAX = \"minMax\", e.PERCENTILE = \"percentile\", e))(f || {});\nexport {\n P as ColorMapInterpolator,\n f as NormalizationMode,\n G as arrangeViews,\n B as createEngine\n};\n//# sourceMappingURL=the-urban-grammar.js.map\n","import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\n\n/**\n * Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.\n * It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.\n *\n * Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that\n * reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current\n * workspace only.\n */\nexport async function enterWorkspace(db: AutkDb, workspace?: string): Promise<void> {\n const name = workspace ?? DEFAULT_WORKSPACE_NAME;\n if (db.getCurrentWorkspace() !== name) await db.setWorkspace(name);\n}\n\n/**\n * The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so\n * two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and\n * `createComputeAdapter` with it.\n */\nexport function tableKey(workspace: string | undefined, name: string): string {\n return workspace === undefined || workspace === DEFAULT_WORKSPACE_NAME ? name : `${workspace}/${name}`;\n}\n","import type { Feature } from 'geojson';\n\n/**\n * A selection passes between a plot and a map layer by the rows each drew, not by positions. A plot draws its table's\n * rows in the order the host handed them, while a map layer draws autk-db's export of the table, which can keep the\n * rows in an order of its own and leaves out those without a geometry, so one position can be another row in each\n * view. Each row is known in both by its feature id, which autk-db keeps in its export. Nothing here needs a GPU or a\n * database, so the unit tests run it in Node.\n */\n\n/**\n * The id autk-db gives each feature of a GeoJSON source: its own `id`, else `autk-feature-<index>`, with `-generated`\n * added while another feature has that id. The data adapter hands autk-db features that carry these ids, so autk-db\n * keeps them in its export whatever rule it would use itself.\n */\nexport function featureIds(features: readonly (Feature | null | undefined)[]): Array<string | number> {\n const own = new Set<string>();\n for (const feature of features) {\n if (feature?.id != null) own.add(JSON.stringify(feature.id));\n }\n const given = new Set<string>();\n return features.map((feature, index) => {\n if (feature?.id != null) return feature.id;\n let id = `autk-feature-${index}`;\n while (own.has(JSON.stringify(id)) || given.has(JSON.stringify(id))) id = `${id}-generated`;\n given.add(JSON.stringify(id));\n return id;\n });\n}\n\n/**\n * The key of each row of a collection, which names the row in every view of its table: its id as {@link featureIds}\n * gives it, written as JSON so that `3` and `\"3\"` stay apart, and the times that id came before when it repeats.\n */\nexport function rowKeys(features: readonly (Feature | null | undefined)[]): string[] {\n const seen = new Map<string, number>();\n return featureIds(features).map((id) => {\n const json = JSON.stringify(id);\n const before = seen.get(json) ?? 0;\n seen.set(json, before + 1);\n return before === 0 ? json : `${json} ${before}`;\n });\n}\n\n/** Each key's positions, built once for each list of keys. */\nconst positionsByKey = new WeakMap<readonly string[], Map<string, number[]>>();\n\nfunction positionsOf(keys: readonly string[]): Map<string, number[]> {\n let positions = positionsByKey.get(keys);\n if (positions) return positions;\n positions = new Map();\n keys.forEach((key, position) => {\n const list = positions!.get(key);\n if (list) list.push(position);\n else positions!.set(key, [position]);\n });\n positionsByKey.set(keys, positions);\n return positions;\n}\n\n/**\n * The positions in one view of the rows at the positions `ids` in another, each view given by the key of the row at\n * each of its positions. A row the other view does not draw has no position there, and a row it draws at several\n * positions has each of them.\n */\nexport function translateIds(ids: readonly number[], from: readonly string[], to: readonly string[]): number[] {\n const positions = positionsOf(to);\n const translated = new Set<number>();\n for (const id of ids) {\n const key = from[id];\n if (key === undefined) continue;\n for (const position of positions.get(key) ?? []) translated.add(position);\n }\n return [...translated];\n}\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, GeoTiffDataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection, Geometry } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { featureIds } from '../rows';\n\n/** An empty geometry: a GeometryCollection with none in it, which a map draws as nothing. */\nconst NO_GEOMETRY: Geometry = { type: 'GeometryCollection', geometries: [] };\n\n/**\n * A GeoJSON source's collection as autk-db loads it, row for row.\n *\n * - Each feature carries the id autk-db gives it (see `featureIds`), from its place in the source. autk-db keeps the\n * id in its export, so a row a map draws from the export is found among the source's own rows, which a plot draws.\n * - autk-db refuses a feature whose geometry is null, which GeoJSON allows, so such a feature gets an empty one: a map\n * draws nothing for it, and a plot still counts it.\n * - autk-db reads the layer's type off the first feature, so a first feature without a geometry trades places with the\n * first that has one. Each keeps its id, so the rows are still found by it.\n */\nfunction loadableCollection(collection: FeatureCollection): FeatureCollection {\n const features = collection.features ?? [];\n const ids = featureIds(features);\n let changed = false;\n const loadable = features.map((feature, index) => {\n if (feature == null || (feature.id != null && feature.geometry != null)) return feature;\n changed = true;\n return { ...feature, id: ids[index], geometry: feature.geometry ?? NO_GEOMETRY };\n });\n const first = features.findIndex((feature) => feature?.geometry != null);\n if (first > 0 && features[0] != null && features[0].geometry == null) {\n [loadable[0], loadable[first]] = [loadable[first], loadable[0]];\n changed = true;\n }\n return changed ? { ...collection, features: loadable } : collection;\n}\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect\n * `autoLoadLayers` and no longer take `dropOsmTable`.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n return { ...rest, queryArea: queryAreaOf(spec), autoLoadLayers: { layers: autoLoadLayers?.layers ?? [] } };\n}\n\n/**\n * The CRS advice. Only a bounding-box check gives it, when the box shows that a layer's coordinates\n * are not in the CRS it was loaded as; any other load error is autk-db's own message.\n */\nfunction crsAdvice(coordinateFormat: string | undefined): string {\n const assumed = coordinateFormat\n ? `coordinateFormat is set to \"${coordinateFormat}\"`\n : 'no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)';\n return `${assumed}. Verify that coordinateFormat matches the actual CRS of the input data.`;\n}\n\n/** The [minX, minY, maxX, maxY] of every position in a collection, or undefined when it has none. */\nexport function extentOf(collection: FeatureCollection): [number, number, number, number] | undefined {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visitPositions = (value: unknown): void => {\n if (!Array.isArray(value)) return;\n if (typeof value[0] === 'number') {\n const [x, y] = value as number[];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n return;\n }\n for (const inner of value) visitPositions(inner);\n };\n const visitGeometry = (geometry: Geometry | null | undefined): void => {\n if (!geometry) return;\n if (geometry.type === 'GeometryCollection') geometry.geometries.forEach(visitGeometry);\n else visitPositions(geometry.coordinates);\n };\n for (const feature of collection.features ?? []) visitGeometry(feature?.geometry);\n return minX <= maxX ? [minX, minY, maxX, maxY] : undefined;\n}\n\n/**\n * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the\n * autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and\n * returns the database.\n *\n * A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the\n * `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables\n * after each load. `cache`, when given, receives each GeoJSON table and each table a join wrote, under\n * {@link tableKey}.\n */\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n return {\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb | undefined> {\n\n let db = context;\n\n if(!db){\n db = new AutkDb();\n await db.init();\n }\n\n const { workspace } = spec as { workspace?: string };\n await enterWorkspace(db, workspace);\n\n let {type, workspace: _workspace, ...rest_spec} = spec as DataSourceSpec & { workspace?: string };\n\n switch (type) {\n case 'osm':\n await db.loadOsm(toLoadOsmParams(rest_spec as OsmDataSourceSpec));\n print(db, targets);\n return db;\n case 'csv':\n await db.loadCsv(rest_spec as CsvDataSourceSpec);\n print(db, targets);\n return db;\n case 'json':\n await db.loadJson(rest_spec as JsonDataSourceSpec);\n print(db, targets);\n return db;\n case 'geojson': {\n const geojsonSpec = rest_spec as CustomDataSourceSpec;\n let geojsonData: FeatureCollection | undefined;\n\n if (geojsonSpec.geojsonFileUrl) {\n const response = await fetch(geojsonSpec.geojsonFileUrl);\n geojsonData = await response.json() as FeatureCollection;\n } else {\n // The inline type allows a feature whose geometry is null, which autk-db refuses: loadableCollection\n // gives such a feature an empty geometry before autk-db loads it.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch, as autk-db loads it (see\n // loadableCollection). The cache keeps the source's own rows, in their order, for its plots.\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: loadableCollection(geojsonData) }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n // Degrees put every y within -90 to 90, so a y outside it shows a layer in another CRS. The\n // transform makes such a y infinite, and autk-db would refuse the layer with a grid error.\n // A longitude past 180 is not checked: the transform wraps it.\n const readAsDegrees = /^EPSG:4326$/i.test(loadSpec.coordinateFormat ?? 'EPSG:4326');\n const extent = geojsonData && readAsDegrees ? extentOf(geojsonData) : undefined;\n if (extent && (extent[1] < -90 || extent[3] > 90)) {\n throw new Error(\n `GeoJSON layer \"${loadSpec.outputTableName}\" has y coordinates outside -90 to 90 ` +\n `(bbox: [${extent.join(', ')}]), so they cannot be EPSG:4326 degrees. ${crsAdvice(loadSpec.coordinateFormat)}`\n );\n }\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n throw new Error(`Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for DEFAULT_WORKSPACE_COORDINATE_FORMAT (EPSG:3395)\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `${crsAdvice(loadSpec.coordinateFormat)} ` +\n `The workspace uses ${DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.): skip validation\n }\n print(db, targets);\n return db;\n }\n case 'geotiff':\n await db.loadGeoTiff(rest_spec as GeoTiffDataSourceSpec);\n print(db, targets);\n return db;\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n // The schema refuses collect in a heatmap, but a spec that was not checked against it reaches here.\n if (hm.groupBy?.some((group) => (group.aggregateFn as string | undefined) === 'collect'))\n throw new Error(`Heatmap \"${hm.outputTableName}\": aggregateFn \"collect\" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);\n await db.buildHeatmap({\n tableJoinName: hm.joinDataRef,\n near: hm.near,\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy }),\n });\n print(db, targets);\n return db;\n }\n case 'join': {\n const jn = rest_spec as JoinSourceSpec;\n await db.spatialQuery({\n tableRootName: jn.dataRef,\n tableJoinName: jn.joinDataRef,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.dataRef);\n cache.set(tableKey(workspace, jn.dataRef), updated);\n }\n print(db, targets);\n return db;\n }\n default:\n return\n }\n }\n }\n}\n","import type { MapSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { FeatureCollection } from 'geojson';\nimport type { MapId } from './types';\n\n/** A layer a map of the last run draws, as the map adapter registers it once the map's layers are loaded. */\nexport interface DrawnLayer {\n /** The map that draws it. */\n map: AutkMap;\n /** The map's index in the spec's `map` list. */\n mapIndex: number;\n /** The map's {@link MapId}: its `id`, else its index. */\n mapId: MapId;\n /** The layer's id in the map: its `title`, else its `dataRef`. */\n layerId: string;\n /** The table the layer draws. */\n dataRef: string;\n /** The key of the row the layer draws at each of its positions (see `rowKeys`); empty for a raster. */\n rows: readonly string[];\n}\n\n/** Every layer the maps of the last run draw, one entry per layer of each map: the maps in order, layers bottom first. */\nexport type DrawnLayers = DrawnLayer[];\n\n/** The layers each plot is linked to, by a link or its `mapRef`, keyed by the plot's `id`, else its `dataRef`. */\nexport type PlotLinks = Map<string, DrawnLayer[]>;\n\n/** The key of the row each plot draws at each of its positions (see `rowKeys`), keyed by the plot's `id`, else its `dataRef`. */\nexport type PlotRows = Map<string, readonly string[]>;\n\n/** The export of each table a map or a plot of the last run read, by its `tableKey`. */\nexport type LayerExports = Map<string, Promise<FeatureCollection>>;\n\n/** A table's export, taken once a run, so the maps and the plots of one table draw the same rows. */\nexport function exportOf(exports: LayerExports | undefined, key: string, load: () => Promise<FeatureCollection>): Promise<FeatureCollection> {\n if (!exports) return load();\n let collection = exports.get(key);\n if (!collection) {\n collection = load();\n exports.set(key, collection);\n }\n return collection;\n}\n\n/** A map's {@link MapId}: its `id`, else its index in the spec's `map` list, which `arrangeViews` gives its pane as its `key`. */\nexport function mapIdOf(spec: MapSpec | undefined, index: number): MapId {\n return spec?.id ?? index;\n}\n\n/**\n * Whether a layer is on the map `mapId` names: a string names a map by its `id`, a number by its index. Without one,\n * every layer is.\n */\nexport function isOnMap(layer: DrawnLayer, mapId?: MapId): boolean {\n if (mapId === undefined) return true;\n return typeof mapId === 'number' ? layer.mapIndex === mapId : layer.mapId === mapId;\n}\n\n/** Records that a plot is linked to a layer, once. */\nexport function addPlotLink(links: PlotLinks | undefined, plotKey: string, layer: DrawnLayer): void {\n const linked = links?.get(plotKey) ?? [];\n if (!linked.includes(layer)) links?.set(plotKey, [...linked, layer]);\n}\n","/**\n * A points layer's `pointSize`, the radius of its points in meters on the ground, as autk-map's `pointSize`, a radius\n * in the workspace's planar units. Nothing here needs a GPU or a database, so the unit tests run it in Node.\n */\n\n/** WGS84's semi-major axis, in meters: the radius of Web Mercator's sphere and of World Mercator's ellipsoid. */\nconst WGS84_A = 6378137;\n\n/** WGS84's first eccentricity, which shapes World Mercator's ellipsoid. */\nconst WGS84_E = 0.0818191908426215;\n\n/** Refuses a `pointSize` that is not a number of meters greater than 0, naming the layer. An unset one passes. */\nexport function checkPointSize(pointSize: unknown, layerId: string): void {\n if (pointSize === undefined) return;\n if (typeof pointSize === 'number' && Number.isFinite(pointSize) && pointSize > 0) return;\n const shown = typeof pointSize === 'number' ? String(pointSize) : JSON.stringify(pointSize);\n throw new Error(`Layer \"${layerId}\": pointSize must be a number of meters greater than 0, not ${shown}.`);\n}\n\n/** The latitude, in radians, of a World Mercator (EPSG:3395) planar y, on the WGS84 ellipsoid. */\nfunction worldMercatorLatitude(y: number): number {\n const t = Math.exp(-y / WGS84_A);\n let phi = Math.PI / 2 - 2 * Math.atan(t);\n for (let i = 0; i < 10; i++) {\n const s = WGS84_E * Math.sin(phi);\n const next = Math.PI / 2 - 2 * Math.atan(t * ((1 - s) / (1 + s)) ** (WGS84_E / 2));\n if (Math.abs(next - phi) < 1e-12) return next;\n phi = next;\n }\n return phi;\n}\n\n/**\n * How many planar units of the workspace CRS `crs` one meter on the ground spans at the planar y `y`: Mercator's scale\n * factor at the latitude φ of `y`. In World Mercator (EPSG:3395, autk-db's default), on the WGS84 ellipsoid, it is\n * sec φ times sqrt(1 - e² sin² φ); in Web Mercator (EPSG:3857), on a sphere, sec φ. Any other CRS is taken as\n * projected in meters, so a meter is one planar unit.\n */\nexport function planarUnitsPerMeter(crs: string, y: number): number {\n if (/^EPSG:3395$/i.test(crs)) {\n const phi = worldMercatorLatitude(y);\n const s = WGS84_E * Math.sin(phi);\n return Math.sqrt(1 - s * s) / Math.cos(phi);\n }\n // On the sphere, sec φ of the latitude of y is cosh(y / a).\n if (/^EPSG:3857$/i.test(crs)) return Math.cosh(y / WGS84_A);\n return 1;\n}\n\n/**\n * The radius autk-map draws a layer's points with, in the planar units of the workspace CRS `crs`: `pointSize` meters\n * at the middle of the layer's planar y. `extent` gives the layer's `[minX, minY, maxX, maxY]` in workspace units, or\n * `undefined` when it has no points, and is read only for a points layer that sets `pointSize`. `undefined` when the\n * layer sets none, which keeps autk-map's default, when it is not a points layer, which ignores it, and when it has\n * no points.\n */\nexport function planarPointSize(\n pointSize: number | undefined,\n type: string | undefined,\n crs: string,\n extent: () => readonly number[] | undefined,\n): number | undefined {\n if (pointSize === undefined || type !== 'points') return undefined;\n const box = extent();\n if (!box) return undefined;\n return pointSize * planarUnitsPerMeter(crs, (box[1] + box[3]) / 2);\n}\n","import type { FeatureCollection } from 'geojson';\nimport { MapAdapter, MapLayerSpec, MapSpec, CameraSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { Targets, ComputeCache, ComputeLayerTypes } from '../types';\nimport { DrawnLayers, LayerExports, exportOf, mapIdOf } from '../drawn';\nimport { rowKeys } from '../rows';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport type { LayerRenderInfo } from '@urban-toolkit/autk-map';\nimport { ColorMap, ColorMapDomainStrategy, ColorMapInterpolator } from '@urban-toolkit/autk-core';\nimport type { ColorHEX, ColorMapConfig, ColorMapDomainSpec, ColorRGB, LayerType, TransferFunction } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { extentOf } from './data';\nimport { checkPointSize, planarPointSize } from '../point-size';\n\n/** The id a layer has in its map: its `title`, else its `dataRef`. */\nexport function layerIdOf(layerRef: MapLayerSpec): string {\n return typeof layerRef.title === 'string' && layerRef.title !== '' ? layerRef.title : layerRef.dataRef;\n}\n\n/** Refuses a map whose layers would share an id. */\nfunction checkLayerIds(spec: MapSpec, index: number): void {\n const ids = new Set<string>();\n for (const layerRef of spec.layerRefs) {\n const id = layerIdOf(layerRef);\n if (ids.has(id))\n throw new Error(`Map ${index} draws two layers with the id \"${id}\". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);\n ids.add(id);\n }\n}\n\nconst HEX_COLOR = /^#[0-9a-fA-F]{6}$/;\n\nfunction hexColor(value: string, key: string, layerId: string): ColorRGB {\n if (!HEX_COLOR.test(value))\n throw new Error(`Layer \"${layerId}\": ${key} must be a color written #rrggbb, not \"${value}\".`);\n return ColorMap.hexToRgb(value as ColorHEX);\n}\n\n/** What `color`, `stroke` and `width` set on the layer's autk-map render info. */\nfunction styleRenderInfo(layerRef: MapLayerSpec, layerId: string): Partial<LayerRenderInfo> {\n const renderInfo: Partial<LayerRenderInfo> = {};\n if (layerRef.color != null)\n renderInfo.color = hexColor(layerRef.color, 'color', layerId);\n if (layerRef.stroke === false)\n renderInfo.showBorders = false;\n else if (layerRef.stroke != null)\n renderInfo.strokeColor = hexColor(layerRef.stroke, 'stroke', layerId);\n if (layerRef.width != null)\n renderInfo.polylinesWidth = layerRef.width;\n return renderInfo;\n}\n\n/**\n * Whether the layer is colored by value. An explicit `isColorMap` decides. A raster layer is colored by value\n * either way, and this only shows or hides its legend. Otherwise a layer with a `color` is drawn in it, and a\n * layer with a scheme or a `getFnv` value is colored by value.\n */\nfunction colorsByValue(layerRef: MapLayerSpec, type: LayerType): boolean {\n if (layerRef.isColorMap != null) return layerRef.isColorMap;\n if (type === 'raster')\n return layerRef.colorMapInterpolator != null || layerRef.colorMapRange != null || layerRef.colorMapCenter != null\n || layerRef.colorMapReverse === true;\n if (layerRef.color != null) return false;\n return layerRef.colorMapInterpolator != null || layerRef.getFnv != null;\n}\n\n/** A raster band's values, as autk-map reads them. */\nfunction bandValues(collection: { features?: { properties?: unknown }[] }, band: string): Float32Array | null {\n const values = (collection.features?.[0]?.properties as Record<string, unknown> | undefined)?.[band];\n if (values instanceof Float32Array) return values;\n if ((ArrayBuffer.isView(values) && !(values instanceof DataView)) || Array.isArray(values))\n return Float32Array.from(values as ArrayLike<number>, (v) => (Number.isFinite(Number(v)) ? Number(v) : NaN));\n return null;\n}\n\n/**\n * The domain of a raster's color scale when the layer sets a range, a center or reverse, or `undefined` when it\n * sets none of them, the scheme is categorical, or, without a range, the band has no value. A range is the domain:\n * `[low, high]`, or `[low, center, high]` with a center. Without one, a scale centered on `center` runs from the\n * center less the farthest value's distance to it, to the center plus that distance; when every value is the\n * center, it is not centered. Otherwise it is the domain autk-map resolves from `config`. `reverse` turns it around.\n */\nexport function rasterScaleDomain(\n values: Float32Array | null, config: ColorMapConfig, center?: number, reverse?: boolean, range?: [number, number],\n): number[] | undefined {\n if (ColorMap.isCategorical(config.interpolator)) return undefined;\n if (range != null) {\n const domain = center != null ? [range[0], center, range[1]] : [range[0], range[1]];\n return reverse === true ? domain.reverse() : domain;\n }\n if (!values) return undefined;\n let reach = 0;\n let finite = 0;\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n if (!Number.isFinite(value)) continue;\n finite++;\n if (center != null) reach = Math.max(reach, Math.abs(value - center));\n }\n const centered = center != null && reach > 0;\n if (finite === 0 || (!centered && reverse !== true)) return undefined;\n const domain = centered && center != null\n ? [center - reach, center, center + reach]\n : ColorMap.resolveDomainFromData(values, config) as number[];\n return reverse === true ? [...domain].reverse() : domain;\n}\n\n/**\n * The domain of a vector layer's color scale: its range, unless the scheme is categorical. autk-map colors a vector\n * layer on the GPU from its domain's first value to its last, which must be the higher, so the domain is neither\n * centered nor reversed.\n */\nfunction vectorScaleDomain(config: ColorMapConfig, range?: [number, number]): number[] | undefined {\n if (range == null || ColorMap.isCategorical(config.interpolator)) return undefined;\n return [range[0], range[1]];\n}\n\n/**\n * Refuses a `colorMapRange` that is not two numbers with low less than high, one set with `colorMapDomain`, and\n * one whose layer's `colorMapCenter` lies outside it. The schema refuses the same shapes and the pairing with\n * `colorMapDomain`, but JSON Schema cannot compare two values: a low above its high and a center outside the range\n * are refused only here.\n */\nfunction checkColorMapRange(layerRef: MapLayerSpec): void {\n const range: unknown = layerRef.colorMapRange;\n if (range === undefined) return;\n const refuse = (message: string) => new Error(`Layer \"${layerIdOf(layerRef)}\": ${message}`);\n if (!Array.isArray(range) || range.length !== 2 || !range.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('colorMapRange must hold two numbers, [low, high].');\n const [low, high] = range as [number, number];\n if (low >= high)\n throw refuse(`colorMapRange low (${low}) must be less than high (${high}).`);\n if (layerRef.colorMapDomain !== undefined)\n throw refuse('set colorMapRange or colorMapDomain, not both.');\n const center = layerRef.colorMapCenter;\n if (center != null && (center < low || center > high))\n throw refuse(`colorMapCenter (${center}) must lie within colorMapRange [${low}, ${high}].`);\n}\n\nfunction buildDomainSpec(\n normalization: MapSpec['layerRefs'][number]['normalization'],\n colorMapDomain?: string[],\n): ColorMapDomainSpec {\n if (colorMapDomain && colorMapDomain.length > 0)\n return { type: ColorMapDomainStrategy.USER, params: colorMapDomain };\n if (normalization?.mode === NormalizationMode.PERCENTILE) {\n const hasExplicitBounds =\n normalization.lowerPercentile !== undefined || normalization.upperPercentile !== undefined;\n if (hasExplicitBounds)\n return {\n type: ColorMapDomainStrategy.PERCENTILE,\n params: [normalization.lowerPercentile ?? 0, normalization.upperPercentile ?? 100],\n };\n return { type: ColorMapDomainStrategy.PERCENTILE };\n }\n return { type: ColorMapDomainStrategy.MIN_MAX };\n}\n\nfunction valueAtPath(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, obj);\n}\n\nfunction setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> {\n const keys = path.split('.');\n const result = { ...obj };\n let current = result as Record<string, unknown>;\n for (let i = 0; i < keys.length - 1; i++) {\n current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown> ?? {}) };\n current = current[keys[i]] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n return result;\n}\n\n/**\n * Resolves a grammar value path such as `count.noise` to the raster band that holds it.\n * autk-db stores heatmap values in bands (`band_1`, ...) labelled `<aggregateFn>_<table>`.\n */\nfunction rasterBand(collection: { features?: { properties?: unknown }[] }, getFnv?: string): string {\n const props = collection.features?.[0]?.properties as { bands?: { id: string; label?: string }[] } | undefined;\n const bands = props?.bands ?? [];\n const band = bands.find((b) => b.id === getFnv || b.label === getFnv?.replace(/\\./g, '_'));\n return band?.id ?? bands[0]?.id ?? getFnv ?? '';\n}\n\n/**\n * Moves a map's camera as `camera` says, from the view that fits the map's layers. The camera reports each change,\n * so the map redraws without a request.\n *\n * The map adapter calls it once the map's layers are loaded and before the map's first `draw()`. A host that builds\n * its own map from a spec's `map` entry calls it at the same point, so the map looks from where the grammar's would.\n */\nexport function applyCamera(map: AutkMap, camera: CameraSpec): void {\n if(camera.zoom === undefined && !camera.pitch && !camera.bearing) return;\n\n // Turn the view around the point it looks at: the eye moves on a sphere around that point, so the data stays\n // in view at any pitch. `pitch` is the angle from straight down and `bearing` the compass heading of the view,\n // clockwise from north.\n const view = map.camera;\n const [x, y] = view.getLookAt();\n const distance = camera.zoom !== undefined ? 10000 / Math.pow(2, camera.zoom - 10) : Math.abs(view.getEye()[2]);\n const pitch = (camera.pitch ?? 0) * Math.PI / 180;\n const bearing = (camera.bearing ?? 0) * Math.PI / 180;\n const eye = [\n x - distance * Math.sin(pitch) * Math.sin(bearing),\n y - distance * Math.sin(pitch) * Math.cos(bearing),\n distance * Math.cos(pitch),\n ];\n view.resetCamera([Math.sin(bearing), Math.cos(bearing), 0], [x, y, 0], eye);\n}\n\n/**\n * The key of the row a vector layer draws at each of its positions. autk-map draws each feature it is handed as one\n * component, in order, and none for a feature with nothing to draw; a component names its feature by its index among\n * those handed (`featureIndex`). `kept` gives the table row of each feature handed, and `keys` each table row's key.\n */\nfunction drawnRowKeys(map: AutkMap, layerId: string, keys: readonly string[], kept: readonly number[]): string[] {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as { components?: Array<{ featureIndex?: number }> } | null;\n const components = layer?.components;\n if (!Array.isArray(components)) return kept.map((row) => keys[row] ?? '');\n return components.map((component, position) => {\n const handed = Number.isInteger(component?.featureIndex) ? component.featureIndex! : position;\n return keys[kept[handed]] ?? '';\n });\n}\n\n/**\n * The map adapter `AutkGrammar` runs. Each map it draws goes in `maps` at its index, and each of its layers in `layers`,\n * with the rows it draws, so every map stays known, though several draw one table. A table's export is taken once a\n * run, in `exports`, which the plot adapter reads too.\n */\nexport function createMapAdapter(targets?: Targets, layers?: DrawnLayers, computeCache?: ComputeCache, maps?: AutkMap[], computeTypes?: ComputeLayerTypes, exports?: LayerExports): MapAdapter {\n\n /** Loads each layer of `spec` on `map`, and gives the keys of the rows each draws, in the order of the layers. */\n async function loadLayers(map: AutkMap, context: AutkDb, spec: MapSpec): Promise<string[][]> {\n let tableToTypeMap: {[tableName: string]: string} = {};\n for(const table of context.getTablesMetadata()) {\n if(table.type !== undefined) tableToTypeMap[table.name] = table.type;\n }\n\n const drawn: string[][] = [];\n for(const layerRef of spec.layerRefs){\n const name = layerRef.dataRef;\n const layerId = layerIdOf(layerRef);\n const key = tableKey(spec.workspace, name);\n const type = (computeTypes?.get(key) ?? tableToTypeMap[name]) as LayerType;\n const getFnv = layerRef.getFnv;\n\n const rawData = computeCache?.get(key) ?? (type === 'raster' ? await context.getRaster(name) as unknown as FeatureCollection : await exportOf(exports, key, () => context.getLayer(name)));\n // Raster tables (e.g. heatmaps) are a single feature with no geometry, so keep them as-is. A vector layer\n // is handed the rows with a geometry: `kept` holds the table row of each.\n const rows = rawData.features ?? [];\n const kept = type === 'raster' ? [] : rows.flatMap((feature, row) => (feature?.geometry != null ? [row] : []));\n const data = type === 'raster' ? rawData : { ...rawData, features: kept.map((row) => rows[row]) };\n const band = type === 'raster' ? rasterBand(data, getFnv) : '';\n\n if(type === 'raster') {\n map.loadCollection(layerId, { collection: data, type: 'raster', property: band });\n } else {\n map.loadCollection(layerId, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(layerId, { opacity: layerRef.opacity });\n\n const style = styleRenderInfo(layerRef, layerId);\n if(Object.keys(style).length > 0)\n map.updateRenderInfo(layerId, style);\n\n // pointSize is in meters on the ground, and autk-map's in planar units, which Mercator stretches away\n // from the equator: the layer's points are sized at the middle of its extent.\n const crs = context.getWorkspaceConfiguration().coordinateFormat;\n const pointSize = planarPointSize(layerRef.pointSize, type, crs, () => extentOf(data));\n if(pointSize !== undefined)\n map.updateRenderInfo(layerId, { pointSize });\n\n // Thematic (getFnv) vector layers are colored by value out of the box: autk-map\n // attaches a default colour ramp to every layer, so this works even when the\n // spec omits colorMapInterpolator (see colorsByValue).\n if(colorsByValue(layerRef, type))\n map.updateRenderInfo(layerId, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(layerId, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(layerId, { isSkip: true });\n\n // When catchAllCategory is set, remap features whose property value is not\n // in colorMapDomain to the catch-all label, and extend the domain to include it.\n const { catchAllCategory, colorMapDomain } = layerRef;\n let thematicData = data;\n let effectiveDomain = colorMapDomain;\n\n if(getFnv && catchAllCategory && colorMapDomain?.length) {\n const allowed = new Set(colorMapDomain);\n thematicData = {\n ...data,\n features: data.features.map((f: any) => {\n const props = f.properties as Record<string, unknown>;\n const val = valueAtPath(props, getFnv);\n if(val === undefined || val === null || !allowed.has(String(val))) {\n return { ...f, properties: setValueAtPath(props, getFnv, catchAllCategory) };\n }\n return f;\n }),\n };\n effectiveDomain = allowed.has(catchAllCategory)\n ? colorMapDomain\n : [...colorMapDomain, catchAllCategory];\n }\n\n // A raster's transfer function is only stored by setTransferFunction; the\n // updateColorMap below colors the cells again with it.\n const rasterTransfer = type === 'raster' && layerRef.transferFunction != null;\n if(rasterTransfer) {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as\n { setTransferFunction?: (transferFunction: TransferFunction) => void } | null;\n layer?.setTransferFunction?.(layerRef.transferFunction as TransferFunction);\n }\n\n // The scheme and its domain go through updateColorMap, which colors a raster's\n // cells again and gives the legend its labels. A vector layer keeps the domain\n // in its config, where the updateThematic below reads it.\n const range = layerRef.colorMapRange;\n const rasterScale = type === 'raster' && (range != null || layerRef.colorMapCenter != null || layerRef.colorMapReverse === true);\n if(layerRef.colorMapInterpolator || rasterScale || range) {\n const colormapConfig: ColorMapConfig = {\n // urban-grammar ColorMapInterpolator values are string-compatible\n // with autk-core ColorMapInterpolator at runtime\n interpolator: (layerRef.colorMapInterpolator as unknown as ColorMapConfig['interpolator'] | undefined)\n ?? map.layerManager.searchByLayerId(layerId)?.layerRenderInfo.colormap.config.interpolator\n ?? ColorMapInterpolator.SEQ_REDS,\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n let domain: number[] | undefined;\n if(rasterScale)\n domain = rasterScaleDomain(bandValues(data, band), colormapConfig, layerRef.colorMapCenter, layerRef.colorMapReverse, range);\n else if(type !== 'raster')\n domain = vectorScaleDomain(colormapConfig, range);\n if(domain)\n colormapConfig.domainSpec = { type: ColorMapDomainStrategy.USER, params: domain };\n map.updateColorMap(layerId, { colorMap: colormapConfig });\n } else if(rasterTransfer) {\n map.updateColorMap(layerId, { colorMap: {} });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(layerId, { collection: thematicData, property });\n }\n\n drawn.push(type === 'raster' ? [] : drawnRowKeys(map, layerId, rowKeys(rows), kept));\n }\n return drawn;\n }\n\n return {\n async resolveMap(context: AutkDb | undefined, spec: MapSpec, index: number = 0): Promise<void> {\n if(targets && targets.map && context){\n\n checkLayerIds(spec, index);\n for(const layerRef of spec.layerRefs) {\n checkColorMapRange(layerRef);\n checkPointSize(layerRef.pointSize, layerIdOf(layerRef));\n }\n\n let canvas;\n\n if(Array.isArray(targets.map)){\n canvas = document.getElementById(targets.map[index]);\n }else{\n canvas = document.getElementById(targets.map);\n }\n\n if(!canvas)\n throw new Error(\"Could not find rendering target for map: \"+targets.map);\n\n if(!(canvas instanceof HTMLCanvasElement))\n throw new Error(\"Target for map is not a canvas: \"+targets.map);\n\n const map = new AutkMap(canvas);\n\n // A map is known to the grammar, which destroys it, once its layers are loaded. One that fails before\n // is destroyed here, so its controls, event handlers and GPU buffers do not outlive the failed run.\n let drawn: string[][];\n try {\n if(spec.style)\n map.style.setPredefinedStyle(spec.style)\n\n await map.init();\n await enterWorkspace(context, spec.workspace);\n drawn = await loadLayers(map, context, spec);\n } catch(error) {\n try {\n map.destroy();\n } catch {\n // The run reports the load's error, not the teardown's.\n }\n throw error;\n }\n\n const mapId = mapIdOf(spec, index);\n spec.layerRefs.forEach((layerRef, at) => layers?.push({\n map, mapIndex: index, mapId, layerId: layerIdOf(layerRef), dataRef: layerRef.dataRef, rows: drawn[at],\n }));\n\n if(maps)\n maps[index] = map;\n\n if(spec.camera)\n applyCamera(map, spec.camera);\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { Targets, PlotRegistry, GeoJsonCache, ComputeCache } from '../types';\nimport { addPlotLink, exportOf } from '../drawn';\nimport type { DrawnLayer, DrawnLayers, LayerExports, PlotLinks, PlotRows } from '../drawn';\nimport { rowKeys, translateIds } from '../rows';\nimport { AutkDb, isRenderableTable } from '@urban-toolkit/autk-db';\nimport { AutkPlot, PlotEvent as AutkPlotEvent } from '@urban-toolkit/autk-plot';\nimport type { PlotEventData, PlotType, PlotTransformConfig } from '@urban-toolkit/autk-plot';\nimport { MapEvent } from '@urban-toolkit/autk-map';\nimport type { MapEventData } from '@urban-toolkit/autk-map';\nimport { FeatureCollection } from 'geojson';\n\nfunction grammarMarkToPlotType(mark: PlotMark): PlotType {\n const mapping: Record<PlotMark, PlotType> = {\n 'scatter': 'scatterplot',\n 'bar': 'barchart',\n 'line': 'linechart',\n 'linechart': 'linechart',\n 'parallel-coordinates': 'parallel-coordinates',\n 'table': 'table',\n 'heatmatrix': 'heatmatrix',\n };\n return mapping[mark];\n}\n\n/** How a plot is known to links and to `AutkGrammar`: its `id`, else its `dataRef`. */\nexport function plotKey(spec: PlotSpec): string {\n return spec.id ?? spec.dataRef;\n}\n\n/**\n * Links a plot to a layer of a map: picking on the layer selects the features in the plot, and a selection in\n * the plot highlights them on the layer. `rows` holds the key of the row the plot draws at each position: a selection\n * passes between the two by the rows each drew (see `translateIds`), since one position can be another row in each.\n */\nexport function linkPlotToLayer(plot: AutkPlot, rows: readonly string[], events: AutkPlotEvent[], layer: DrawnLayer): void {\n const { map, layerId } = layer;\n map.updateRenderInfo(layerId, { isPick: true });\n\n // A pick names the layer it was made on, so a pick on another layer of the map leaves the plot alone.\n map.events.on(MapEvent.PICKING, ({ layerId: picked, selection }: MapEventData) => {\n if (picked === layerId) plot.setSelection(translateIds(selection, layer.rows, rows));\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(layerId, translateIds(selection, rows, layer.rows));\n });\n }\n}\n\n/**\n * A table's rows as a plot reads them from autk-db: the export of a table with a geometry, the one the maps of the run\n * draw, and for a table without one, such as a CSV or JSON table loaded without `geometryColumns`, which autk-db does\n * not export as a layer, its rows, each a feature without a geometry. autk-plot reads only the features' properties.\n */\nasync function tableRows(db: AutkDb, name: string, key: string, exports?: LayerExports): Promise<FeatureCollection> {\n const table = db.getTablesMetadata().find((candidate) => candidate.name === name);\n if (table && !isRenderableTable(table)) {\n const rows = await db.getTable(name);\n // A feature without a geometry, which GeoJSON allows and the plot does not read.\n return { type: 'FeatureCollection', features: rows.map((properties) => ({ type: 'Feature', geometry: null, properties })) } as unknown as FeatureCollection;\n }\n return exportOf(exports, key, () => db.getLayer(name));\n}\n\n/**\n * The plot adapter `AutkGrammar` runs. Each plot it draws goes in `plotRegistry`, and the keys of the rows it draws in\n * `plotRows`, by the plot's `id`, else its `dataRef`. A table it reads from autk-db is the export the maps of the run\n * draw, from `exports`.\n */\nexport function createPlotAdapter(targets?: Targets, layers?: DrawnLayers, plotRegistry?: PlotRegistry, plotLinks?: PlotLinks, cache?: GeoJsonCache, computeCache?: ComputeCache, plotRows?: PlotRows, exports?: LayerExports): PlotAdapter {\n\n return {\n async resolvePlot(context: unknown, spec: PlotSpec, index: number = 0): Promise<void> {\n if(!targets || !targets.plot) return;\n\n // One id holds every plot; a list gives each plot its own, in the order of the plots.\n const target = Array.isArray(targets.plot) ? targets.plot[index] : targets.plot;\n if(target === undefined) throw new Error(`Plot ${index} has no target: the plot targets name ${targets.plot.length} elements.`);\n\n const div = document.getElementById(target);\n if(!div) throw new Error(`Could not find plot target: ${target}`);\n\n const db = context as AutkDb | undefined;\n if(!db) throw new Error('No data context available for plot.');\n\n await enterWorkspace(db, spec.workspace);\n const key = tableKey(spec.workspace, spec.dataRef);\n const geojson: FeatureCollection = computeCache?.get(key) ?? cache?.get(key) ?? await tableRows(db, spec.dataRef, key, exports);\n\n const events = (spec.events ?? []) as unknown as AutkPlotEvent[];\n\n const plot = new AutkPlot(div, {\n type: grammarMarkToPlotType(spec.mark),\n collection: geojson,\n attributes: { axis: spec.axis, ...(spec.color && { color: spec.color }) },\n labels: { axis: spec.axis, title: spec.title },\n events,\n ...(spec.width && { width: spec.width }),\n ...(spec.height && { height: spec.height }),\n ...(spec.margins && { margins: spec.margins }),\n ...(spec.transform && { transform: spec.transform as PlotTransformConfig }),\n });\n\n plotRegistry?.set(plotKey(spec), plot);\n // autk-plot names a row by its position in the collection it draws.\n const rows = rowKeys(geojson.features ?? []);\n plotRows?.set(plotKey(spec), rows);\n\n // mapRef names the table of the layers to link to: every layer that draws it, in every map. The maps are\n // drawn before the plots.\n for(const layer of layers ?? []) {\n if(!spec.mapRef || layer.dataRef !== spec.mapRef) continue;\n linkPlotToLayer(plot, rows, events, layer);\n addPlotLink(plotLinks, plotKey(spec), layer);\n }\n }\n }\n}\n","import type { GpgpuComputeSpec, FromFeatureDirective } from '@urban-toolkit/the-urban-grammar';\nimport type { GpgpuPipelineParams } from '@urban-toolkit/autk-compute';\nimport type { Feature, FeatureCollection } from 'geojson';\n\n/** Tables a compute pass can read, keyed by table name. */\nexport type ComputeLayers = Record<string, FeatureCollection | undefined> | Map<string, FeatureCollection>;\n\n/** Runs one GPU dispatch, for example `params => new AutkComputeEngine().gpgpuPipeline(params)`. */\nexport type ComputeRunner = (params: GpgpuPipelineParams) => Promise<FeatureCollection>;\n\n/**\n * The storage buffer binding every WebGPU device supports: the default\n * `maxStorageBufferBindingSize`, 128 MiB. autk-compute 4 reads each array a `batched` directive\n * packs from a read-only storage buffer of its own, so every packed array must fit one binding.\n * autk-compute 3 bound them as uniform buffers, which hold 64 KiB (2048 bounding boxes).\n */\nexport const STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/** Bytes a feature adds to a packed array: one f32 for a scalar entry, a bounding box of eight for a matrix entry. */\nconst SCALAR_BYTES = 4;\nconst BOX_BYTES = 8 * 4;\n\ntype UniformEntry = number | FromFeatureDirective;\ntype MatrixEntry = { data: number[][]; cols: number } | FromFeatureDirective;\n\n/** Joins a `wgslFunction` written as an array of lines. Any other separator would let a `//` comment swallow the lines after it. */\nexport function joinWgsl(body: string | string[]): string {\n return Array.isArray(body) ? body.join('\\n') : body;\n}\n\n/** True when a uniform entry reads its value from a feature. */\nexport function isFromFeature(value: unknown): value is FromFeatureDirective {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n && typeof (value as FromFeatureDirective).fromFeature === 'object'\n && (value as FromFeatureDirective).fromFeature !== null;\n}\n\nfunction lookup(layers: ComputeLayers, name: string): FeatureCollection | undefined {\n return layers instanceof Map ? layers.get(name) : layers[name];\n}\n\nfunction valueAtPath(item: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, item);\n}\n\nfunction directives(block: GpgpuComputeSpec): FromFeatureDirective[] {\n const out: FromFeatureDirective[] = [];\n for (const cfg of [block.uniforms, block.uniformMatrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value)) out.push(value);\n }\n }\n return out;\n}\n\n/** Every table a compute pass reads: its `dataRef` plus each `fromFeature` layer. */\nexport function computeLayerNames(block: GpgpuComputeSpec): string[] {\n return [...new Set([block.dataRef, ...directives(block).map(d => d.fromFeature.layer)])];\n}\n\n/**\n * The iteration a compute pass asks for, or `null`. Every iterating directive must read the same\n * layer; the first one found decides the mode and the layer.\n */\nexport function findIterateSource(block: GpgpuComputeSpec): { mode: 'all' | 'batched'; layer: string } | null {\n for (const d of directives(block)) {\n const { iterate, layer } = d.fromFeature;\n if (iterate === 'all' || iterate === 'batched') return { mode: iterate, layer };\n }\n return null;\n}\n\nfunction resolveDirective(d: FromFeatureDirective, layers: ComputeLayers, iterateIndex?: number): unknown {\n const ff = d.fromFeature;\n const index = iterateIndex !== undefined && ff.iterate === 'all' ? iterateIndex : (ff.index ?? 0);\n const feature = lookup(layers, ff.layer)?.features?.[index];\n return feature ? valueAtPath(feature, ff.path) : undefined;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniforms` to numbers. An entry that does not resolve to a\n * finite number takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, number> | undefined {\n if (!uniforms) return undefined;\n const out: Record<string, number> = {};\n for (const [key, value] of Object.entries(uniforms)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const num = Number(resolveDirective(value, layers, iterateIndex) ?? NaN);\n if (Number.isFinite(num)) out[key] = num;\n else if (typeof value.default === 'number') out[key] = value.default;\n }\n return out;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniformMatrices` to `{ data, cols }`. An entry that does\n * not resolve to an array takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniformMatrices(\n matrices: Record<string, MatrixEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, { data: number[][]; cols: number }> | undefined {\n if (!matrices) return undefined;\n const out: Record<string, { data: number[][]; cols: number }> = {};\n for (const [key, value] of Object.entries(matrices)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const resolved = resolveDirective(value, layers, iterateIndex);\n const data = Array.isArray(resolved) ? (resolved as number[][])\n : Array.isArray(value.default) ? value.default : undefined;\n if (!data) continue;\n const cols = value.cols ?? (Array.isArray(data[0]) ? data[0].length : 0);\n if (cols > 0) out[key] = { data, cols };\n else console.warn(`[autk-grammar] uniform matrix \"${key}\" has no column count; entry dropped`);\n }\n return out;\n}\n\nfunction isFiniteValue(v: unknown): boolean {\n return v !== undefined && v !== null && !(typeof v === 'number' && !Number.isFinite(v));\n}\n\nfunction isBatched(value: unknown): boolean {\n return isFromFeature(value) && value.fromFeature.iterate === 'batched';\n}\n\n/** Bytes one feature adds to the largest array a batched pass packs, or 0 when it packs none. */\nfunction batchedBytesPerFeature(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n): number {\n if (Object.values(matrices ?? {}).some(isBatched)) return BOX_BYTES;\n if (Object.values(uniforms ?? {}).some(isBatched)) return SCALAR_BYTES;\n return 0;\n}\n\n/**\n * Most features a batched pass packs: as many as its largest array holds in one storage buffer\n * binding of `bindingSize` bytes. With {@link STORAGE_BUFFER_BINDING_SIZE} that is 4,194,304\n * features for a pass with a matrix entry, and 33,554,432 for one with scalar entries only.\n */\nexport function maxBatchedFeatures(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): number {\n const bytes = batchedBytesPerFeature(uniforms, matrices);\n return bytes > 0 ? Math.floor(bindingSize / bytes) : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Packs every feature of a `batched` layer into uniform arrays:\n * - a scalar entry becomes an array of one value per feature, under the entry's name;\n * - a matrix entry becomes each feature's axis-aligned bounding box as four corners\n * `[xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]`, eight values per feature;\n * - `num_features` holds the feature count.\n * Features missing a `required` path are dropped first, and at most {@link maxBatchedFeatures}\n * are packed: as many as the largest array holds in one storage buffer binding of `bindingSize`\n * bytes. Plain numbers pass through; other entries that do not iterate are left to\n * {@link resolveComputeParams}.\n */\nexport function buildBatchedUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n sources: Feature[],\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): { uniforms: Record<string, number>; uniformArrays: Record<string, number[]> } {\n const outUniforms: Record<string, number> = {};\n const outArrays: Record<string, number[]> = {};\n\n const required: string[] = [];\n for (const cfg of [uniforms, matrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched' && value.fromFeature.required) {\n required.push(value.fromFeature.path);\n }\n }\n }\n if (required.length > 0) {\n const before = sources.length;\n sources = sources.filter(f => required.every(p => isFiniteValue(valueAtPath(f, p))));\n if (sources.length < before) {\n console.info(`[autk-grammar] batched compute dropped ${before - sources.length} feature(s) missing ${required.join(', ')}`);\n }\n }\n const limit = maxBatchedFeatures(uniforms, matrices, bindingSize);\n if (sources.length > limit) {\n console.warn(\n `[autk-grammar] batched compute capped at ${limit} features (got ${sources.length}): `\n + `its largest packed array takes ${batchedBytesPerFeature(uniforms, matrices)} B per feature, `\n + `and a storage buffer binding holds ${bindingSize} B`,\n );\n sources = sources.slice(0, limit);\n }\n\n for (const [key, value] of Object.entries(uniforms ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched') {\n const fallback = typeof value.default === 'number' ? value.default : undefined;\n outArrays[key] = sources.map(f => {\n const num = Number(valueAtPath(f, value.fromFeature.path) ?? fallback);\n return Number.isFinite(num) ? num : 0;\n });\n } else if (typeof value === 'number') {\n outUniforms[key] = value;\n }\n }\n\n for (const [key, value] of Object.entries(matrices ?? {})) {\n if (!isFromFeature(value) || value.fromFeature.iterate !== 'batched') continue;\n const data: number[] = [];\n for (const f of sources) {\n const ring = valueAtPath(f, value.fromFeature.path);\n let xmin = Infinity, ymin = Infinity, xmax = -Infinity, ymax = -Infinity;\n if (Array.isArray(ring)) {\n for (const coord of ring) {\n if (!Array.isArray(coord) || coord.length < 2) continue;\n const x = Number(coord[0]);\n const y = Number(coord[1]);\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n xmin = Math.min(xmin, x); ymin = Math.min(ymin, y);\n xmax = Math.max(xmax, x); ymax = Math.max(ymax, y);\n }\n }\n // A degenerate feature gets a zero-area box, so the shader's loop runs but adds nothing.\n if (!Number.isFinite(xmin)) { xmin = 0; ymin = 0; xmax = 0; ymax = 0; }\n data.push(xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax);\n }\n outArrays[key] = data;\n }\n\n outUniforms.num_features = sources.length;\n return { uniforms: outUniforms, uniformArrays: outArrays };\n}\n\n/**\n * Turns a compute pass into the parameters of one GPU dispatch. Pure: it reads `layers` and runs\n * nothing. With `iterate: 'all'`, pass the feature index as `iterateIndex` for each dispatch (see\n * {@link runCompute}). Throws when the pass's `dataRef` is not in `layers`.\n */\nexport function resolveComputeParams(block: GpgpuComputeSpec, layers: ComputeLayers, iterateIndex?: number): GpgpuPipelineParams {\n const collection = lookup(layers, block.dataRef);\n if (!collection) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n\n const params: GpgpuPipelineParams = {\n collection,\n variableMapping: block.attributes,\n wgslBody: joinWgsl(block.wgslFunction),\n };\n if (block.attributeArrays) params.attributeArrays = block.attributeArrays;\n if (block.attributeMatrices) params.attributeMatrices = block.attributeMatrices;\n if (block.uniformArrays) params.uniformArrays = block.uniformArrays;\n if (block.outputColumnName) params.resultField = block.outputColumnName;\n if (block.outputColumns) params.outputColumns = block.outputColumns;\n\n const iterate = findIterateSource(block);\n if (iterate?.mode === 'batched') {\n const sources = lookup(layers, iterate.layer)?.features ?? [];\n const packed = buildBatchedUniforms(block.uniforms, block.uniformMatrices, sources);\n // Entries that do not iterate resolve as they would without iteration.\n const single = resolveUniforms(notBatched(block.uniforms), layers) ?? {};\n const matrices = resolveUniformMatrices(notBatched(block.uniformMatrices), layers);\n params.uniforms = { ...single, ...packed.uniforms };\n params.uniformArrays = { ...(params.uniformArrays ?? {}), ...packed.uniformArrays };\n if (matrices && Object.keys(matrices).length > 0) params.uniformMatrices = matrices;\n return params;\n }\n\n const index = iterate?.mode === 'all' ? iterateIndex : undefined;\n const uniforms = resolveUniforms(block.uniforms, layers, index);\n const matrices = resolveUniformMatrices(block.uniformMatrices, layers, index);\n if (uniforms) params.uniforms = uniforms;\n if (matrices) params.uniformMatrices = matrices;\n return params;\n}\n\nfunction notBatched<T>(entries: Record<string, T> | undefined): Record<string, T> | undefined {\n if (!entries) return undefined;\n return Object.fromEntries(Object.entries(entries).filter(([, v]) => !(isFromFeature(v) && v.fromFeature.iterate === 'batched')));\n}\n\nfunction outputColumns(block: GpgpuComputeSpec): string[] {\n return block.outputColumns ?? (block.outputColumnName ? [block.outputColumnName] : []);\n}\n\n/**\n * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is\n * one dispatch per feature of the iterated layer, and each output column holds the sum over them.\n */\nexport async function runCompute(block: GpgpuComputeSpec, layers: ComputeLayers, run: ComputeRunner): Promise<FeatureCollection> {\n const iterate = findIterateSource(block);\n if (iterate?.mode !== 'all') return run(resolveComputeParams(block, layers));\n\n const target = lookup(layers, block.dataRef);\n if (!target) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n const columns = outputColumns(block);\n const summed: FeatureCollection = structuredClone(target);\n for (const f of summed.features) {\n const props = (f.properties ??= {}) as Record<string, unknown>;\n const compute = (props.compute ??= {}) as Record<string, number>;\n for (const col of columns) compute[col] = 0;\n }\n\n const count = lookup(layers, iterate.layer)?.features?.length ?? 0;\n for (let i = 0; i < count; i++) {\n const step = await run({ ...resolveComputeParams(block, layers, i), collection: summed });\n summed.features.forEach((f, j) => {\n const dst = (f.properties as Record<string, unknown> | null)?.compute as Record<string, number> | undefined;\n const src = (step.features[j]?.properties as Record<string, unknown> | null)?.compute as Record<string, unknown> | undefined;\n if (!dst || !src) return;\n for (const col of columns) {\n const inc = Number(src[col]);\n if (Number.isFinite(inc)) dst[col] += inc;\n }\n });\n }\n return summed;\n}\n","import { ComputeAdapter, ComputeSpec, GpgpuComputeSpec, RenderComputeSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { LayerType, RenderLayerSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkComputeEngine } from '@urban-toolkit/autk-compute';\nimport { FeatureCollection } from 'geojson';\nimport { ComputeCache, ComputeLayerTypes } from '../types';\nimport { computeLayerNames, runCompute } from '../compute-params';\nimport { enterWorkspace, tableKey } from '../workspace';\n\n/**\n * The layer types a render pass draws. autk-compute skips a layer of any other type, points among them, with only a\n * warning, so the adapter refuses one.\n */\nconst RENDER_LAYER_TYPES: ReadonlyArray<RenderLayerSpec['type']> = ['surface', 'parks', 'water', 'roads', 'buildings', 'polygons', 'polylines'];\n\n/** The type of the table `name`, which the database knows or an earlier pass wrote. */\nfunction layerTypeOf(db: AutkDb, name: string, workspace: string | undefined, types?: ComputeLayerTypes): LayerType | undefined {\n return types?.get(tableKey(workspace, name)) ?? db.getTablesMetadata().find((table) => table.name === name)?.type as LayerType | undefined;\n}\n\n/**\n * The compute adapter `AutkGrammar` runs. Its `resolveCompute(db, pass)` runs one entry of a spec's `compute`, a\n * GPGPU pass or a render pass, on autk-compute, in the pass's workspace, which it leaves current. It does nothing\n * without a database.\n *\n * A host calls it to run compute passes exactly as the grammar does. The passes need WebGPU, and their results are\n * kept only in the caches: `cache` receives each pass's result under {@link tableKey} of its `outputTableName`, or of\n * the table it computed over, and a later pass reads a table from it first. `types` receives the layer type of each\n * table a pass wrote under its own `outputTableName`, which a map needs to draw it.\n */\nexport function createComputeAdapter(cache?: ComputeCache, types?: ComputeLayerTypes): ComputeAdapter {\n\n /** Reads a table, from the cache when an earlier pass wrote it there. */\n async function read(db: AutkDb, name: string, workspace?: string): Promise<FeatureCollection> {\n return cache?.get(tableKey(workspace, name)) ?? await db.getLayer(name);\n }\n\n /**\n * Stores a pass's result under `outputTableName`, or, without it, in place of the table `source`. A map draws a\n * new table as the spec's `layerType` says, else as `resultType`, else as it draws `source`.\n */\n function store(db: AutkDb, result: FeatureCollection, source: string, spec: GpgpuComputeSpec | RenderComputeSpec, resultType?: LayerType): void {\n if (!cache) return;\n const name = spec.outputTableName ?? source;\n cache.set(tableKey(spec.workspace, name), result);\n const type = spec.layerType ?? resultType ?? layerTypeOf(db, source, spec.workspace, types);\n if (spec.outputTableName && type) types?.set(tableKey(spec.workspace, name), type);\n }\n\n async function resolveRender(db: AutkDb, spec: RenderComputeSpec): Promise<void> {\n for (const layer of spec.layers) {\n if (!(RENDER_LAYER_TYPES as readonly string[]).includes(layer.type))\n throw new Error(`Render pass \"${spec.outputTableName}\": layer \"${layer.id}\" has the type \"${layer.type}\", which a render pass cannot draw. A layer's type is one of ${RENDER_LAYER_TYPES.join(', ')}.`);\n }\n\n const layers = await Promise.all(spec.layers.map(async (layer) => ({\n id: layer.id,\n collection: await read(db, layer.dataRef, spec.workspace),\n type: layer.type,\n objectIdProperty: layer.objectIdProperty,\n })));\n\n const result = await new AutkComputeEngine().renderPipeline({\n layers,\n viewpoints: {\n collection: await read(db, spec.viewpoints.dataRef, spec.workspace),\n strategy: spec.viewpoints.strategy,\n sampling: spec.viewpoints.sampling,\n },\n aggregation: spec.aggregation,\n camera: spec.camera,\n tileSize: spec.tileSize,\n });\n\n // With `building-windows` the result holds one point per window, not the viewpoints' features.\n store(db, result, spec.viewpoints.dataRef, spec, spec.viewpoints.strategy?.type === 'building-windows' ? 'points' : undefined);\n }\n\n async function resolveGpgpu(db: AutkDb, spec: GpgpuComputeSpec): Promise<void> {\n // A table an earlier compute pass wrote is read from the cache, so passes chain.\n // Only the pass's own table must load; a `fromFeature` table that cannot\n // falls back to the directive's `default`.\n const layers: Record<string, FeatureCollection | undefined> = {};\n for (const name of computeLayerNames(spec)) {\n const cached = cache?.get(tableKey(spec.workspace, name));\n if (cached) layers[name] = cached;\n else if (name === spec.dataRef) layers[name] = await db.getLayer(name);\n else {\n try { layers[name] = await db.getLayer(name); }\n catch { layers[name] = undefined; }\n }\n }\n\n const engine = new AutkComputeEngine();\n const result = await runCompute(spec, layers, params => engine.gpgpuPipeline(params));\n\n store(db, result, spec.dataRef, spec);\n }\n\n return {\n async resolveCompute(context: AutkDb | undefined, spec: ComputeSpec): Promise<AutkDb | undefined> {\n if (!context) return;\n await enterWorkspace(context, spec.workspace);\n if (spec.type === 'render') await resolveRender(context, spec);\n else await resolveGpgpu(context, spec);\n return context;\n }\n }\n}\n","import type { UrbanSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { AutkPlot } from '@urban-toolkit/autk-plot';\nimport type { LayerType } from '@urban-toolkit/the-urban-grammar';\nimport type { FeatureCollection } from 'geojson';\n\n/** The elements of the page `AutkGrammar` draws in, by id. */\nexport type Targets = {\n /** Not read by the adapter. */\n compute?: string,\n /** Id of an element that lists the loaded tables after each data source. */\n db?: string,\n /** Id of the canvas a map draws on, or a list of ids, one canvas per entry of `map`, in order. */\n map?: string[] | string,\n /**\n * Id of the element the plots draw in, or a list of ids, one element per entry of `plot`, in order. With one id,\n * every plot draws in that element.\n */\n plot?: string[] | string\n}\n\n/**\n * How the grammar names a map of the spec: its `id`, else its index in the spec's `map` list (0 for a single map).\n * `map:picking` events name the map by it, and the calls that take a `mapId` (`mapLayers`, `mapLayer`,\n * `highlightOnMap`, `clearHighlightOnMap`, `setPlotSelection`, `clearHighlightOnPlot`) address one map with it: a\n * string names a map by its `id`, a number by its index.\n */\nexport type MapId = string | number;\n\nexport type PlotRegistry = Map<string, AutkPlot>;\n\n/** A layer a map of the last run draws, as `AutkGrammar.mapLayer` finds it by its table's name. */\nexport interface GrammarMapLayer {\n /** The map that draws the layer. */\n map: AutkMap;\n /** The layer's id in that map: its `title`, else its `dataRef`. */\n layerId: string;\n}\nexport type GeoJsonCache = Map<string, FeatureCollection>;\nexport type ComputeCache = Map<string, FeatureCollection>;\n/** How the map draws a table a compute pass wrote under `outputTableName`, which the database does not know. */\nexport type ComputeLayerTypes = Map<string, LayerType>;\n\nexport type AutkGrammarSpec = UrbanSpec;\n\n// Grammar-level interaction payloads: no autk internals leak through the public API\nexport interface GrammarPickingEvent {\n /** The map the pick was made on, by its {@link MapId}: its `id`, else its index in the spec's `map` list. */\n mapId: MapId;\n /** The picked layer's id in its map: its `title`, else its `dataRef`. */\n layerId: string;\n selection: number[];\n}\n\nexport interface GrammarPlotSelectionEvent {\n /** The plot's `id`, else its `dataRef`. */\n plotId: string;\n event: 'click' | 'brush' | 'brushX' | 'brushY';\n selection: number[];\n}\n\nexport type GrammarEventRecord = {\n 'map:picking': GrammarPickingEvent;\n 'plot:selection': GrammarPlotSelectionEvent;\n};\n\n// Self-contained typed emitter: it does not import from autk packages\nexport class GrammarEventEmitter {\n private _listeners: Map<string, Set<(p: unknown) => void>> = new Map();\n\n on<K extends keyof GrammarEventRecord>(\n event: K,\n listener: (payload: GrammarEventRecord[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n const bucket = this._listeners.get(event)!;\n bucket.add(listener as (p: unknown) => void);\n return () => bucket.delete(listener as (p: unknown) => void);\n }\n\n /** @internal */\n emit<K extends keyof GrammarEventRecord>(event: K, payload: GrammarEventRecord[K]): void {\n this._listeners.get(event)?.forEach(l => l(payload));\n }\n}\n\n","import { DataAdapter, MapAdapter, PlotAdapter, ComputeAdapter, IEngine, PlotSpec, UrbanSpec, createEngine } from \"@urban-toolkit/the-urban-grammar\";\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from \"@urban-toolkit/autk-db\";\nimport { MapEvent } from \"@urban-toolkit/autk-map\";\nimport type { AutkMap } from \"@urban-toolkit/autk-map\";\nimport type { MapEventData } from \"@urban-toolkit/autk-map\";\nimport { PlotEvent } from \"@urban-toolkit/autk-plot\";\nimport type { PlotEventData } from \"@urban-toolkit/autk-plot\";\nimport { FeatureCollection } from \"geojson\";\nimport { createDataAdapter } from \"./adapters/data\";\nimport { createMapAdapter } from \"./adapters/map\";\nimport { createPlotAdapter, linkPlotToLayer, plotKey } from \"./adapters/plot\";\nimport { layerIdOf } from \"./adapters/map\";\nimport { enterWorkspace } from \"./workspace\";\nimport { createComputeAdapter } from \"./adapters/compute\";\nimport { Targets, PlotRegistry, GeoJsonCache, ComputeCache, ComputeLayerTypes, GrammarEventEmitter } from \"./types\";\nimport type { GrammarMapLayer, GrammarPlotSelectionEvent, MapId } from \"./types\";\nimport { DrawnLayer, DrawnLayers, LayerExports, PlotLinks, PlotRows, addPlotLink, isOnMap, mapIdOf } from \"./drawn\";\nimport { translateIds } from \"./rows\";\n\nfunction asList<T>(value: T[] | T | undefined): T[] {\n return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\n/**\n * An id names one view: no two maps or plots may share one, and an id is never empty. A plot without an id is known\n * by its dataRef, so no two plots may be known by one name either: two plots of a table without ids, or a plot whose\n * id is the dataRef of a plot without one.\n */\nfunction checkViewIds(spec: UrbanSpec): void {\n const seen = new Set<string>();\n for (const view of [...asList(spec.map), ...asList(spec.plot)]) {\n if (view.id === undefined) continue;\n if (view.id === '') throw new Error('A map or plot has an empty id.');\n if (seen.has(view.id)) throw new Error(`Two maps or plots have the id \"${view.id}\"; an id names one view.`);\n seen.add(view.id);\n }\n const plots = new Map<string, PlotSpec>();\n for (const plot of asList(spec.plot)) {\n const key = plotKey(plot);\n const known = plots.get(key);\n if (known)\n throw new Error(known.id === undefined && plot.id === undefined\n ? `Two plots of the table \"${key}\" have no id; give each plot an id.`\n : `A plot's id \"${key}\" is the dataRef of a plot without an id; give each plot an id.`);\n plots.set(key, plot);\n }\n}\n\nexport class AutkGrammar {\n private dataAdapter?: DataAdapter;\n private mapAdapter?: MapAdapter;\n private plotAdapter?: PlotAdapter;\n private computeAdapter?: ComputeAdapter;\n private grammarEngine?: IEngine;\n private _computeCache: ComputeCache = new Map();\n private _computeTypes: ComputeLayerTypes = new Map();\n private _data: Record<string, Promise<FeatureCollection>> = {};\n private _layers: DrawnLayers = [];\n private _maps: AutkMap[] = [];\n private _plotRegistry: PlotRegistry = new Map();\n private _fwdCleanups: Array<() => void> = [];\n private _plotLinks: PlotLinks = new Map();\n private _plotRows: PlotRows = new Map();\n private _exports: LayerExports = new Map();\n /** Each GeoJSON table a run loaded and each table a join wrote, which its plots read before the database. */\n private _geojsonCache: GeoJsonCache = new Map();\n\n readonly interactions = new GrammarEventEmitter();\n\n constructor(targets?: Targets) {\n this.dataAdapter = createDataAdapter(targets, this._geojsonCache);\n this.mapAdapter = createMapAdapter(targets, this._layers, this._computeCache, this._maps, this._computeTypes, this._exports);\n this.plotAdapter = createPlotAdapter(targets, this._layers, this._plotRegistry, this._plotLinks, this._geojsonCache, this._computeCache, this._plotRows, this._exports);\n this.computeAdapter = createComputeAdapter(this._computeCache, this._computeTypes);\n }\n\n /**\n * The coordinate reference system used internally by the autk workspace.\n *\n * Input data is expected in EPSG:4326 (WGS84) by default and is transformed\n * to this CRS on load. Consumers that prepare data for injection (e.g. by\n * serialising a GeoDataFrame) can read this value and reproject accordingly\n * instead of hard-coding a CRS string.\n */\n get workspaceCrs(): string {\n return DEFAULT_WORKSPACE_COORDINATE_FORMAT;\n }\n\n get data(): Record<string, Promise<FeatureCollection>> {\n return this._data;\n }\n\n /**\n * The maps the last {@link run} drew, one per `map` entry of the spec, in order.\n *\n * Each map draws on demand: one frame once its layers are loaded, then one each\n * time it changes. Between frames a map canvas can read back empty, so to read a\n * map's pixels (for example with `canvas.toDataURL()`), call its `requestRender()`\n * and read in a `requestAnimationFrame` callback registered after that call.\n */\n get maps(): readonly AutkMap[] {\n return this._maps;\n }\n\n /**\n * Every layer the maps of the last {@link run} draw for a table, found by the table's name (a layer's `dataRef`):\n * for each, the map that draws it and the layer's id in that map, which is its `title`, else its `dataRef`. The\n * maps come in the spec's order, each map's layers bottom first. Empty when no map draws the table.\n *\n * @param dataRef The table's name.\n * @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\n * the spec's `map` list. Without it, every map.\n */\n mapLayers(dataRef: string, mapId?: MapId): GrammarMapLayer[] {\n return this._layersOf(dataRef, mapId).map(({ map, layerId }) => ({ map, layerId }));\n }\n\n /**\n * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):\n * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.\n * `undefined` when no map draws the table. When several layers draw it, the last one, which is the last map's;\n * {@link mapLayers} lists them all.\n *\n * @param dataRef The table's name.\n * @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\n * the spec's `map` list. Without it, every map.\n *\n * @example\n * const layer = grammar.mapLayer('buildings');\n * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });\n */\n mapLayer(dataRef: string, mapId?: MapId): GrammarMapLayer | undefined {\n return this.mapLayers(dataRef, mapId).pop();\n }\n\n /** The drawn layers of a table, on every map or on the one `mapId` names. */\n private _layersOf(dataRef: string, mapId?: MapId): DrawnLayer[] {\n return this._layers.filter((layer) => layer.dataRef === dataRef && isOnMap(layer, mapId));\n }\n\n /**\n * Releases what the last run created: every map (its layers' GPU buffers, its textures, its canvas context, the\n * controls it adds to the page and its event handlers) and the grammar's own registries, caches and event\n * forwarding. autk-map's maps share one GPU device, which stays for the maps of the next run. Call it before the\n * page or the container goes away; `run` calls it before it starts, so running a new spec on the same instance\n * does not leak the maps of the old one.\n */\n destroy(): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n for (const map of this._maps) map.destroy();\n this._maps.length = 0;\n this._layers.length = 0;\n this._plotRegistry.clear();\n this._plotLinks.clear();\n this._plotRows.clear();\n this._exports.clear();\n this._geojsonCache.clear();\n this._computeCache.clear();\n this._computeTypes.clear();\n this.grammarEngine = undefined;\n this._data = {};\n }\n\n async run(spec: UrbanSpec) {\n if(!this.dataAdapter)\n throw new Error('Database adapter not initialized. Please call the constructor first.');\n\n if(!this.mapAdapter)\n throw new Error('Map engine not initialized. Please call the constructor first.');\n\n if(!this.plotAdapter)\n throw new Error('Plot adapter not initialized. Please call the constructor first.');\n\n if(!this.computeAdapter)\n throw new Error('Compute adapter not initialized. Please call the constructor first.');\n\n checkViewIds(spec);\n\n this.destroy();\n\n this.grammarEngine = createEngine({\n spec,\n adapters: {\n db: this.dataAdapter,\n map: this.mapAdapter,\n plot: this.plotAdapter,\n compute: this.computeAdapter\n }\n });\n\n await this.grammarEngine.run();\n const db = this.grammarEngine.context as AutkDb | undefined;\n // Leave the database in the default workspace, whose tables `data` lists.\n if (db) await enterWorkspace(db);\n this._wireLinks(spec);\n this._rewireInteractions(spec);\n\n if (!db) {\n console.warn('Grammar engine produced no data context.');\n this._data = {};\n return;\n }\n\n const dataObj: Record<string, Promise<FeatureCollection>> = {};\n for (const table of db.getLayersMetadata()) {\n Object.defineProperty(dataObj, table.name, {\n get: () => {\n const computed = this._computeCache.get(table.name);\n return computed ? Promise.resolve(computed) : db.getLayer(table.name);\n },\n enumerable: true,\n configurable: true,\n });\n }\n // A table a compute pass wrote under its own name is not in the database.\n for (const name of this._computeCache.keys()) {\n if (name in dataObj) continue;\n Object.defineProperty(dataObj, name, {\n get: () => Promise.resolve(this._computeCache.get(name)!),\n enumerable: true,\n configurable: true,\n });\n }\n this._data = dataObj;\n }\n\n /**\n * Highlights features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}), or only\n * in the map `mapId` names. If a plot is linked to one of those layers, by a link or its `mapRef`, the plot\n * selection is updated too, to the same rows: the plot finds them by their feature ids, since it can draw the\n * table's rows in another order and draws the rows without a geometry, which a layer leaves out.\n *\n * @param dataRef The table's name.\n * @param featureIds The features to highlight: their positions among those the layer draws.\n * @param mapId The map to highlight on, by its {@link MapId}: a string names a map by its `id`, a number by its\n * index in the spec's `map` list. Without it, every map that draws the table.\n */\n highlightOnMap(dataRef: string, featureIds: number[], mapId?: MapId): void {\n const layers = this._layersOf(dataRef, mapId);\n for (const { map, layerId } of layers) map.setHighlightedIds(layerId, featureIds);\n this._selectInLinkedPlots(layers, featureIds);\n }\n\n /**\n * Clears highlighted features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}),\n * 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\n * selection is cleared too.\n *\n * @param dataRef The table's name.\n * @param mapId The map to clear, by its {@link MapId}: a string names a map by its `id`, a number by its index in\n * the spec's `map` list. Without it, every map that draws the table.\n */\n clearHighlightOnMap(dataRef: string, mapId?: MapId): void {\n const layers = this._layersOf(dataRef, mapId);\n for (const { map, layerId } of layers) map.clearHighlightedIds(layerId);\n this._selectInLinkedPlots(layers, []);\n }\n\n /**\n * Clears the selection on the plot `plotId` names: its `id`, else its `dataRef`.\n * If that plot is linked to map layers, by links or its `mapRef`, their highlights are cleared too: on every map,\n * or only on the map `mapId` names.\n *\n * @param plotId The plot: its `id`, else its `dataRef`.\n * @param mapId The map whose linked layers to clear, by its {@link MapId}: a string names a map by its `id`, a\n * number by its index in the spec's `map` list. Without it, every linked layer.\n */\n clearHighlightOnPlot(plotId: string, mapId?: MapId): void {\n this._plotRegistry.get(plotId)?.setSelection([]);\n for (const layer of this._plotLinks.get(plotId) ?? []) {\n if (isOnMap(layer, mapId)) layer.map.clearHighlightedIds(layer.layerId);\n }\n }\n\n /**\n * Applies a selection to the plot `plotId` names: its `id`, else its `dataRef`.\n * If that plot is linked to map layers, by links or its `mapRef`, their highlights are updated too, to the same rows\n * (see {@link highlightOnMap}): on every map, or only on the map `mapId` names.\n *\n * @param plotId The plot: its `id`, else its `dataRef`.\n * @param featureIds The features to select: their positions among those the plot draws.\n * @param mapId The map whose linked layers to highlight, by its {@link MapId}: a string names a map by its `id`, a\n * number by its index in the spec's `map` list. Without it, every linked layer.\n */\n setPlotSelection(plotId: string, featureIds: number[], mapId?: MapId): void {\n this._plotRegistry.get(plotId)?.setSelection(featureIds);\n // A layer is lit at its own positions of the selected rows.\n const rows = this._plotRows.get(plotId) ?? [];\n for (const layer of this._plotLinks.get(plotId) ?? []) {\n if (isOnMap(layer, mapId)) layer.map.setHighlightedIds(layer.layerId, translateIds(featureIds, rows, layer.rows));\n }\n }\n\n /**\n * Applies a selection made on `layers`, by their positions `featureIds`, to every plot linked to one of them, at the\n * plot's own positions of the selected rows.\n */\n private _selectInLinkedPlots(layers: DrawnLayer[], featureIds: number[]): void {\n for (const [plotId, linked] of this._plotLinks) {\n const selected = linked.filter((layer) => layers.includes(layer));\n if (selected.length === 0) continue;\n const rows = this._plotRows.get(plotId) ?? [];\n const ids = new Set(selected.flatMap((layer) => translateIds(featureIds, layer.rows, rows)));\n this._plotRegistry.get(plotId)?.setSelection([...ids]);\n }\n }\n\n /** Wires each entry of `links` between a plot and a layer of a map, both now drawn. */\n private _wireLinks(spec: UrbanSpec): void {\n const maps = asList(spec.map);\n const plots = asList(spec.plot);\n for (const link of spec.links ?? []) {\n const plotSpec = plots.find((p) => plotKey(p) === link.source);\n const plot = this._plotRegistry.get(link.source);\n if (!plotSpec || !plot)\n throw new Error(`Link source \"${link.source}\" is not the id (or the dataRef) of a plot of this specification.`);\n\n const mapIndex = maps.findIndex((m) => m.id === link.target);\n const map = this._maps[mapIndex];\n if (mapIndex < 0 || !map)\n throw new Error(`Link target \"${link.target}\" is not the id of a map of this specification.`);\n\n const layerRef = maps[mapIndex].layerRefs.find((l) =>\n link.layer !== undefined ? layerIdOf(l) === link.layer : l.dataRef === plotSpec.dataRef);\n if (!layerRef)\n throw new Error(link.layer !== undefined\n ? `Link from \"${link.source}\": map \"${link.target}\" has no layer \"${link.layer}\".`\n : `Link from \"${link.source}\": map \"${link.target}\" draws no layer of the table \"${plotSpec.dataRef}\"; name the layer.`);\n\n // The link names its map, so it is that map's layer that it links, though other maps draw the table too.\n const layer = this._layers.find((drawn) => drawn.mapIndex === mapIndex && drawn.layerId === layerIdOf(layerRef));\n if (!layer) continue;\n linkPlotToLayer(plot, this._plotRows.get(link.source) ?? [], (plotSpec.events ?? []) as unknown as PlotEvent[], layer);\n addPlotLink(this._plotLinks, link.source, layer);\n }\n }\n\n private _rewireInteractions(spec: UrbanSpec): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n\n // Wire every map to the grammar bus once, though several maps can draw one table, and name the map in each\n // pick. autk-map names the picked layer by its id in the map, which is its title, else its dataRef.\n const maps = asList(spec.map);\n this._maps.forEach((map, index) => {\n const mapId = mapIdOf(maps[index], index);\n const handler = ({ layerId, selection }: MapEventData) => {\n this.interactions.emit('map:picking', { mapId, layerId, selection });\n };\n map.events.on(MapEvent.PICKING, handler);\n this._fwdCleanups.push(() => map.events.off(MapEvent.PICKING, handler));\n });\n\n // Wire each plot → grammar bus (all four event types)\n for (const [plotId, plot] of this._plotRegistry) {\n for (const ev of [PlotEvent.CLICK, PlotEvent.BRUSH, PlotEvent.BRUSH_X, PlotEvent.BRUSH_Y] as const) {\n const handler = ({ selection }: PlotEventData) => {\n this.interactions.emit('plot:selection', {\n plotId,\n event: ev as GrammarPlotSelectionEvent['event'],\n selection,\n });\n };\n plot.events.on(ev, handler);\n this._fwdCleanups.push(() => plot.events.off(ev, handler));\n }\n }\n }\n}\n"],"names":["B","e","t","_","s","u","n","i","E","S","c","A","G","m","d","R","P","f","enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","featureIds","features","own","feature","given","index","id","rowKeys","seen","json","before","positionsByKey","positionsOf","keys","positions","key","position","list","translateIds","ids","from","to","translated","NO_GEOMETRY","loadableCollection","collection","changed","loadable","first","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","crsAdvice","coordinateFormat","extentOf","minX","minY","maxX","maxY","visitPositions","x","y","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","table","context","AutkDb","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","readAsDegrees","extent","err","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","group","jn","updated","exportOf","exports","load","mapIdOf","isOnMap","layer","mapId","addPlotLink","links","plotKey","linked","WGS84_A","WGS84_E","checkPointSize","pointSize","layerId","shown","worldMercatorLatitude","phi","next","planarUnitsPerMeter","crs","planarPointSize","layerIdOf","layerRef","checkLayerIds","HEX_COLOR","hexColor","ColorMap","styleRenderInfo","renderInfo","colorsByValue","bandValues","band","values","v","rasterScaleDomain","config","center","reverse","range","domain","reach","finite","centered","vectorScaleDomain","checkColorMapRange","low","high","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","setValueAtPath","result","current","rasterBand","getFnv","bands","b","applyCamera","map","camera","view","distance","pitch","bearing","eye","drawnRowKeys","kept","components","component","handed","row","createMapAdapter","layers","computeCache","maps","computeTypes","loadLayers","tableToTypeMap","drawn","rawData","rows","data","style","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","rasterTransfer","rasterScale","colormapConfig","ColorMapInterpolator","property","canvas","AutkMap","error","at","grammarMarkToPlotType","mark","linkPlotToLayer","plot","events","MapEvent","picked","selection","event","tableRows","candidate","isRenderableTable","properties","createPlotAdapter","plotRegistry","plotLinks","plotRows","target","geojson","AutkPlot","STORAGE_BUFFER_BINDING_SIZE","SCALAR_BYTES","BOX_BYTES","joinWgsl","body","isFromFeature","lookup","item","directives","block","out","cfg","computeLayerNames","findIterateSource","iterate","resolveDirective","iterateIndex","ff","resolveUniforms","uniforms","num","resolveUniformMatrices","matrices","resolved","cols","isFiniteValue","isBatched","batchedBytesPerFeature","maxBatchedFeatures","bindingSize","bytes","buildBatchedUniforms","sources","outUniforms","outArrays","required","p","limit","fallback","ring","xmin","ymin","xmax","ymax","coord","resolveComputeParams","params","packed","single","notBatched","entries","outputColumns","runCompute","run","columns","summed","compute","col","count","step","j","dst","src","inc","RENDER_LAYER_TYPES","layerTypeOf","types","createComputeAdapter","read","store","source","resultType","resolveRender","AutkComputeEngine","resolveGpgpu","cached","engine","GrammarEventEmitter","listener","bucket","payload","l","asList","checkViewIds","plots","known","AutkGrammar","dataRef","cleanup","createEngine","dataObj","comput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AAK;AAC9B,iBAAWmH,KAAM,CAACC,EAAU,OAAOA,EAAU,OAAOA,EAAU,SAASA,EAAU,OAAO,GAAY;AAChG,cAAMF,IAAU,CAAC,EAAE,WAAA9G,QAA+B;AAC9C,eAAK,aAAa,KAAK,kBAAkB;AAAA,YACrC,QAAAyG;AAAA,YACA,OAAOM;AAAA,YACP,WAAA/G;AAAA,UAAA,CACH;AAAA,QACL;AACA,QAAAJ,EAAK,OAAO,GAAGmH,GAAID,CAAO,GAC1B,KAAK,aAAa,KAAK,MAAMlH,EAAK,OAAO,IAAImH,GAAID,CAAO,CAAC;AAAA,MAC7D;AAAA,EAER;AACJ;"}
1
+ {"version":3,"file":"autk-grammar.js","sources":["../../../grammar/dist/the-urban-grammar.js","../src/workspace.ts","../src/rows.ts","../src/adapters/data.ts","../src/drawn.ts","../src/point-size.ts","../src/adapters/map.ts","../src/adapters/plot.ts","../src/compute-params.ts","../src/adapters/compute.ts","../src/types.ts","../src/main.ts"],"sourcesContent":["function f(e) {\n const { spec: t, adapters: s } = e;\n let _;\n async function c() {\n let n;\n if (t.workspaces?.length && s.db.resolveWorkspaces && (n = await s.db.resolveWorkspaces(n, t.workspaces)), t.data)\n for (const i of t.data)\n n = await s.db.resolveSource(n, i);\n if (t.compute)\n for (const i of t.compute)\n n = await s.compute.resolveCompute(n, i);\n if (t.map)\n if (Array.isArray(t.map))\n for (let i = 0; i < t.map.length; i++) {\n let E = t.map[i];\n await s.map.resolveMap(n, E, i);\n }\n else\n await s.map.resolveMap(n, t.map);\n if (t.plot)\n if (Array.isArray(t.plot))\n for (let i = 0; i < t.plot.length; i++)\n await s.plot.resolvePlot(n, t.plot[i], i);\n else\n await s.plot.resolvePlot(n, t.plot);\n _ = n;\n }\n function S(n) {\n return console.log(\"Spec to update\", n), new Promise((i) => {\n i();\n });\n }\n function u() {\n console.log(\"Function not implemented yet\");\n }\n return { run: c, updatedSpec: S, destroy: u, get context() {\n return _;\n } };\n}\nfunction A(e) {\n return e === void 0 ? [] : Array.isArray(e) ? e : [e];\n}\nfunction B(e) {\n const t = e.layout ?? {}, s = t.type ?? \"vertical\";\n if (s !== \"vertical\" && s !== \"horizontal\" && s !== \"grid\")\n throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(s)}.`);\n const _ = t.gap ?? 0;\n if (typeof _ != \"number\" || !Number.isFinite(_) || _ < 0)\n throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(_)}.`);\n const c = t.columns ?? 2;\n if (!Number.isInteger(c) || c < 1)\n throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(c)}.`);\n const S = [\n ...A(e.map).map((i, E) => ({ kind: \"map\", index: E, id: i.id, key: i.id ?? E })),\n ...A(e.plot).map((i, E) => ({ kind: \"plot\", index: E, id: i.id, key: i.id ?? i.dataRef }))\n ], u = s === \"vertical\" ? 1 : s === \"horizontal\" ? Math.max(S.length, 1) : c, n = S.map(({ kind: i, index: E, id: m, key: d }, R) => ({\n kind: i,\n index: E,\n ...m !== void 0 && { id: m },\n key: d,\n row: Math.floor(R / u),\n column: R % u\n }));\n return { type: s, rows: Math.ceil(S.length / u), columns: u, gap: _, panes: n };\n}\nvar a = /* @__PURE__ */ ((e) => (e.CAT_ACCENT = \"schemeAccent\", e.CAT_DARK2 = \"schemeDark2\", e.CAT_CATEGORY10 = \"schemeCategory10\", e.CAT_OBSERVABLE10 = \"schemeObservable10\", e.CAT_PAIRED = \"schemePaired\", e.CAT_PASTEL1 = \"schemePastel1\", e.CAT_PASTEL2 = \"schemePastel2\", e.CAT_SET1 = \"schemeSet1\", e.CAT_SET2 = \"schemeSet2\", e.CAT_SET3 = \"schemeSet3\", e.CAT_TABLEAU10 = \"schemeTableau10\", e.SEQ_REDS = \"interpolateReds\", e.SEQ_BLUES = \"interpolateBlues\", e.SEQ_GREENS = \"interpolateGreens\", e.SEQ_GREYS = \"interpolateGreys\", e.SEQ_ORANGES = \"interpolateOranges\", e.SEQ_PURPLES = \"interpolatePurples\", e.SEQ_TURBO = \"interpolateTurbo\", e.SEQ_VIRIDIS = \"interpolateViridis\", e.SEQ_INFERNO = \"interpolateInferno\", e.SEQ_MAGMA = \"interpolateMagma\", e.SEQ_PLASMA = \"interpolatePlasma\", e.SEQ_CIVIDIS = \"interpolateCividis\", e.SEQ_WARM = \"interpolateWarm\", e.SEQ_COOL = \"interpolateCool\", e.SEQ_CUBEHELIX_DEFAULT = \"interpolateCubehelixDefault\", e.SEQ_BU_GN = \"interpolateBuGn\", e.SEQ_BU_PU = \"interpolateBuPu\", e.SEQ_GN_BU = \"interpolateGnBu\", e.SEQ_OR_RD = \"interpolateOrRd\", e.SEQ_PU_BU_GN = \"interpolatePuBuGn\", e.SEQ_PU_BU = \"interpolatePuBu\", e.SEQ_PU_RD = \"interpolatePuRd\", e.SEQ_RD_PU = \"interpolateRdPu\", e.SEQ_YL_GN_BU = \"interpolateYlGnBu\", e.SEQ_YL_GN = \"interpolateYlGn\", e.SEQ_YL_OR_BR = \"interpolateYlOrBr\", e.SEQ_YL_OR_RD = \"interpolateYlOrRd\", e.DIV_BR_BG = \"interpolateBrBG\", e.DIV_PR_GN = \"interpolatePRGn\", e.DIV_PI_YG = \"interpolatePiYG\", e.DIV_PU_OR = \"interpolatePuOr\", e.DIV_RED_BLUE = \"interpolateRdBu\", e.DIV_RED_GREY = \"interpolateRdGy\", e.DIV_RED_YELLOW_BLUE = \"interpolateRdYlBu\", e.DIV_RED_YELLOW_GREEN = \"interpolateRdYlGn\", e.DIV_SPECTRAL = \"interpolateSpectral\", e))(a || {}), P = /* @__PURE__ */ ((e) => (e.MIN_MAX = \"minMax\", e.PERCENTILE = \"percentile\", e))(P || {});\nexport {\n a as ColorMapInterpolator,\n P as NormalizationMode,\n B as arrangeViews,\n f as createEngine\n};\n//# sourceMappingURL=the-urban-grammar.js.map\n","import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\n\n/**\n * Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.\n * It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.\n *\n * Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that\n * reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current\n * workspace only.\n */\nexport async function enterWorkspace(db: AutkDb, workspace?: string): Promise<void> {\n const name = workspace ?? DEFAULT_WORKSPACE_NAME;\n if (db.getCurrentWorkspace() !== name) await db.setWorkspace(name);\n}\n\n/**\n * The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so\n * two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and\n * `createComputeAdapter` with it.\n */\nexport function tableKey(workspace: string | undefined, name: string): string {\n return workspace === undefined || workspace === DEFAULT_WORKSPACE_NAME ? name : `${workspace}/${name}`;\n}\n","import type { Feature } from 'geojson';\n\n/**\n * A selection passes between a plot and a map layer by the rows each drew, not by positions. A plot draws its table's\n * rows in the order the host handed them, while a map layer draws autk-db's export of the table, which can keep the\n * rows in an order of its own and leaves out those without a geometry, so one position can be another row in each\n * view. Each row is known in both by its feature id, which autk-db keeps in its export. Nothing here needs a GPU or a\n * database, so the unit tests run it in Node.\n */\n\n/**\n * The id autk-db gives each feature of a GeoJSON source: its own `id`, else `autk-feature-<index>`, with `-generated`\n * added while another feature has that id. The data adapter hands autk-db features that carry these ids, so autk-db\n * keeps them in its export whatever rule it would use itself.\n */\nexport function featureIds(features: readonly (Feature | null | undefined)[]): Array<string | number> {\n const own = new Set<string>();\n for (const feature of features) {\n if (feature?.id != null) own.add(JSON.stringify(feature.id));\n }\n const given = new Set<string>();\n return features.map((feature, index) => {\n if (feature?.id != null) return feature.id;\n let id = `autk-feature-${index}`;\n while (own.has(JSON.stringify(id)) || given.has(JSON.stringify(id))) id = `${id}-generated`;\n given.add(JSON.stringify(id));\n return id;\n });\n}\n\n/**\n * The key of each row of a collection, which names the row in every view of its table: its id as {@link featureIds}\n * gives it, written as JSON so that `3` and `\"3\"` stay apart, and the times that id came before when it repeats.\n */\nexport function rowKeys(features: readonly (Feature | null | undefined)[]): string[] {\n const seen = new Map<string, number>();\n return featureIds(features).map((id) => {\n const json = JSON.stringify(id);\n const before = seen.get(json) ?? 0;\n seen.set(json, before + 1);\n return before === 0 ? json : `${json} ${before}`;\n });\n}\n\n/** Each key's positions, built once for each list of keys. */\nconst positionsByKey = new WeakMap<readonly string[], Map<string, number[]>>();\n\nfunction positionsOf(keys: readonly string[]): Map<string, number[]> {\n let positions = positionsByKey.get(keys);\n if (positions) return positions;\n positions = new Map();\n keys.forEach((key, position) => {\n const list = positions!.get(key);\n if (list) list.push(position);\n else positions!.set(key, [position]);\n });\n positionsByKey.set(keys, positions);\n return positions;\n}\n\n/**\n * The positions in one view of the rows at the positions `ids` in another, each view given by the key of the row at\n * each of its positions. A row the other view does not draw has no position there, and a row it draws at several\n * positions has each of them.\n */\nexport function translateIds(ids: readonly number[], from: readonly string[], to: readonly string[]): number[] {\n const positions = positionsOf(to);\n const translated = new Set<number>();\n for (const id of ids) {\n const key = from[id];\n if (key === undefined) continue;\n for (const position of positions.get(key) ?? []) translated.add(position);\n }\n return [...translated];\n}\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, DropSourceSpec, GeoTiffDataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec, SqlSourceSpec, UpdateSourceSpec, WorkspaceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_NAME, isRenderableTable, isVectorTable } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams, Table } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection, Geometry } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { featureIds } from '../rows';\n\n/** An empty geometry: a GeometryCollection with none in it, which a map draws as nothing. */\nconst NO_GEOMETRY: Geometry = { type: 'GeometryCollection', geometries: [] };\n\n/**\n * A GeoJSON source's collection as autk-db loads it, row for row.\n *\n * - Each feature carries the id autk-db gives it (see `featureIds`), from its place in the source. autk-db keeps the\n * id in its export, so a row a map draws from the export is found among the source's own rows, which a plot draws.\n * - autk-db refuses a feature whose geometry is null, which GeoJSON allows, so such a feature gets an empty one: a map\n * draws nothing for it, and a plot still counts it.\n * - autk-db reads the layer's type off the first feature, so a first feature without a geometry trades places with the\n * first that has one. Each keeps its id, so the rows are still found by it.\n */\nfunction loadableCollection(collection: FeatureCollection): FeatureCollection {\n const features = collection.features ?? [];\n const ids = featureIds(features);\n let changed = false;\n const loadable = features.map((feature, index) => {\n if (feature == null || (feature.id != null && feature.geometry != null)) return feature;\n changed = true;\n return { ...feature, id: ids[index], geometry: feature.geometry ?? NO_GEOMETRY };\n });\n const first = features.findIndex((feature) => feature?.geometry != null);\n if (first > 0 && features[0] != null && features[0].geometry == null) {\n [loadable[0], loadable[first]] = [loadable[first], loadable[0]];\n changed = true;\n }\n return changed ? { ...collection, features: loadable } : collection;\n}\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect `autoLoadLayers`, with the CRS of the source's\n * coordinates when it gives one, and no longer take `dropOsmTable`. autk-db reads `tagSets` from the Overpass API only,\n * so a source that also names a PBF extract is refused here, by its name.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n if (spec.pbfFileUrl !== undefined && (spec.tagSets?.length ?? 0) > 0)\n throw new Error(`OSM source \"${spec.outputTableName}\": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);\n return {\n ...rest,\n queryArea: queryAreaOf(spec),\n autoLoadLayers: {\n layers: autoLoadLayers?.layers ?? [],\n ...(autoLoadLayers?.coordinateFormat !== undefined && { coordinateFormat: autoLoadLayers.coordinateFormat }),\n },\n };\n}\n\n/**\n * The CRS advice. Only a bounding-box check gives it, when the box shows that a layer's coordinates\n * are not in the CRS it was loaded as; any other load error is autk-db's own message.\n */\nfunction crsAdvice(coordinateFormat: string | undefined): string {\n const assumed = coordinateFormat\n ? `coordinateFormat is set to \"${coordinateFormat}\"`\n : 'no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)';\n return `${assumed}. Verify that coordinateFormat matches the actual CRS of the input data.`;\n}\n\n/** How a message names a workspace: the default one, or another by its name. */\nfunction workspaceLabel(name: string | undefined): string {\n return name === undefined || name === DEFAULT_WORKSPACE_NAME ? 'the default workspace' : `the workspace \"${name}\"`;\n}\n\n/** A feature property's value as SQL's `->>` reads it: a string as it is, any other value as its JSON. */\nfunction propertyText(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n return typeof value === 'string' ? value : JSON.stringify(value);\n}\n\n/**\n * The rows of an update of a layer keyed by a feature property, `properties.<name>`, keyed instead by the feature ids of\n * the table's rows they match. autk-db 4.1.1 matches such a key with `table.properties->>'name' =\n * staging.properties->>'name'`, which DuckDB reads so that the comparison is NULL: no row matches, and nothing is\n * updated. It matches a plain column as written. So each given feature goes to every row whose property has its value,\n * compared as text, as `->>` reads it, under that row's id in autk-db's export: its `geojson_id`, else its `id`.\n */\nasync function updateByFeatureId(db: AutkDb, table: Table, rows: FeatureCollection, property: string): Promise<{ data: FeatureCollection, idColumn: string }> {\n const ids = new Map<string, Array<string | number>>();\n for (const row of (await db.getLayer(table.name)).features) {\n const key = propertyText((row.properties as Record<string, unknown> | null)?.[property]);\n if (key === undefined) continue;\n if (row.id === undefined || row.id === null)\n throw new Error('its rows have no feature id to update them by.');\n ids.set(key, [...(ids.get(key) ?? []), row.id]);\n }\n const features = rows.features.flatMap((feature) => {\n const key = propertyText((feature.properties as Record<string, unknown> | null)?.[property]);\n return key === undefined ? [] : (ids.get(key) ?? []).map((id) => ({ ...feature, id }));\n });\n const idColumn = table.columns.some((column) => column.name === 'geojson_id') ? 'geojson_id' : 'id';\n return { data: { ...rows, features }, idColumn };\n}\n\n/** The database a source loads into: `context`, else a new one. */\nasync function database(context: AutkDb | undefined): Promise<AutkDb> {\n if (context) return context;\n const db = new AutkDb();\n await db.init();\n return db;\n}\n\n/** The [minX, minY, maxX, maxY] of every position in a collection, or undefined when it has none. */\nexport function extentOf(collection: FeatureCollection): [number, number, number, number] | undefined {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visitPositions = (value: unknown): void => {\n if (!Array.isArray(value)) return;\n if (typeof value[0] === 'number') {\n const [x, y] = value as number[];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n return;\n }\n for (const inner of value) visitPositions(inner);\n };\n const visitGeometry = (geometry: Geometry | null | undefined): void => {\n if (!geometry) return;\n if (geometry.type === 'GeometryCollection') geometry.geometries.forEach(visitGeometry);\n else visitPositions(geometry.coordinates);\n };\n for (const feature of collection.features ?? []) visitGeometry(feature?.geometry);\n return minX <= maxX ? [minX, minY, maxX, maxY] : undefined;\n}\n\n/**\n * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the\n * autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and\n * returns the database. Its `resolveWorkspaces(db, workspaces)` sets each workspace a spec's `workspaces` lists to its\n * CRS and precision grid, before the first source loads, leaves the default workspace current and returns the database.\n *\n * A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the\n * `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables\n * after each load. `cache`, when given, receives each GeoJSON table and each table a join or an update wrote, under\n * {@link tableKey}, and loses each table a `sql` source replaces or a `drop` source drops.\n */\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): Required<DataAdapter> {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n /**\n * Puts a table a source changed in `cache` as autk-db now exports it, as a join's, or takes it out when autk-db does\n * not export it as a layer: the plots read a table from the cache before autk-db.\n */\n async function recache(db: AutkDb, workspace: string | undefined, name: string): Promise<void> {\n if (!cache) return;\n const key = tableKey(workspace, name);\n const table = db.getTablesMetadata().find((candidate) => candidate.name === name);\n if (table && isRenderableTable(table)) cache.set(key, await db.getLayer(name));\n else cache.delete(key);\n }\n\n return {\n async resolveWorkspaces(context: AutkDb | undefined, workspaces: WorkspaceSpec[]): Promise<AutkDb> {\n const db = await database(context);\n const named = new Set<string>();\n for (const { name, coordinateFormat, precisionGrid } of workspaces) {\n const workspace = name ?? DEFAULT_WORKSPACE_NAME;\n if (named.has(workspace))\n throw new Error(`workspaces sets ${workspaceLabel(name)} twice; give each workspace one entry.`);\n named.add(workspace);\n // autk-db creates the workspace with this configuration, or sets it on the one that exists while it\n // holds no table, the default workspace among them.\n try {\n await db.setWorkspace(workspace, { coordinateFormat, precisionGrid });\n } catch (err) {\n throw new Error(`workspaces, ${workspaceLabel(name)}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n // Each source, compute pass, map and plot enters its own workspace.\n await enterWorkspace(db);\n return db;\n },\n\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb> {\n\n const db = await database(context);\n\n const { workspace } = spec as { workspace?: string };\n await enterWorkspace(db, workspace);\n\n let {type, workspace: _workspace, ...rest_spec} = spec as DataSourceSpec & { workspace?: string };\n\n switch (type) {\n case 'osm':\n await db.loadOsm(toLoadOsmParams(rest_spec as OsmDataSourceSpec));\n print(db, targets);\n return db;\n case 'csv':\n await db.loadCsv(rest_spec as CsvDataSourceSpec);\n print(db, targets);\n return db;\n case 'json':\n await db.loadJson(rest_spec as JsonDataSourceSpec);\n print(db, targets);\n return db;\n case 'geojson': {\n const geojsonSpec = rest_spec as CustomDataSourceSpec;\n let geojsonData: FeatureCollection | undefined;\n\n if (geojsonSpec.geojsonFileUrl) {\n const response = await fetch(geojsonSpec.geojsonFileUrl);\n geojsonData = await response.json() as FeatureCollection;\n } else {\n // The inline type allows a feature whose geometry is null, which autk-db refuses: loadableCollection\n // gives such a feature an empty geometry before autk-db loads it.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch, as autk-db loads it (see\n // loadableCollection). The cache keeps the source's own rows, in their order, for its plots.\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: loadableCollection(geojsonData) }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n // Degrees put every y within -90 to 90, so a y outside it shows a layer in another CRS. The\n // transform makes such a y infinite, and autk-db would refuse the layer with a grid error.\n // A longitude past 180 is not checked: the transform wraps it.\n const readAsDegrees = /^EPSG:4326$/i.test(loadSpec.coordinateFormat ?? 'EPSG:4326');\n const extent = geojsonData && readAsDegrees ? extentOf(geojsonData) : undefined;\n if (extent && (extent[1] < -90 || extent[3] > 90)) {\n throw new Error(\n `GeoJSON layer \"${loadSpec.outputTableName}\" has y coordinates outside -90 to 90 ` +\n `(bbox: [${extent.join(', ')}]), so they cannot be EPSG:4326 degrees. ${crsAdvice(loadSpec.coordinateFormat)}`\n );\n }\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n throw new Error(`Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for World Mercator (EPSG:3395), autk-db's default CRS\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `${crsAdvice(loadSpec.coordinateFormat)} ` +\n `The workspace uses ${db.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.): skip validation\n }\n print(db, targets);\n return db;\n }\n case 'geotiff':\n await db.loadGeoTiff(rest_spec as GeoTiffDataSourceSpec);\n print(db, targets);\n return db;\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n // The schema refuses collect in a heatmap, but a spec that was not checked against it reaches here.\n if (hm.groupBy?.some((group) => (group.aggregateFn as string | undefined) === 'collect'))\n throw new Error(`Heatmap \"${hm.outputTableName}\": aggregateFn \"collect\" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);\n await db.buildHeatmap({\n tableJoinName: hm.joinDataRef,\n near: hm.near,\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy }),\n });\n print(db, targets);\n return db;\n }\n case 'join': {\n const jn = rest_spec as JoinSourceSpec;\n await db.spatialQuery({\n tableRootName: jn.dataRef,\n tableJoinName: jn.joinDataRef,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.dataRef);\n cache.set(tableKey(workspace, jn.dataRef), updated);\n }\n print(db, targets);\n return db;\n }\n case 'sql': {\n const sql = rest_spec as SqlSourceSpec;\n try {\n await db.rawQuery({\n query: sql.query,\n output: {\n type: 'CREATE_TABLE',\n tableName: sql.outputTableName,\n source: 'user',\n ...(sql.layerType !== undefined && { tableType: sql.layerType }),\n },\n });\n } catch (err) {\n throw new Error(`SQL source \"${sql.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n // A query saved under the name of a GeoJSON table replaces it, so the plots no longer read its rows.\n cache?.delete(tableKey(workspace, sql.outputTableName));\n print(db, targets);\n return db;\n }\n case 'update': {\n const update = rest_spec as UpdateSourceSpec;\n const refuse = (message: string) => new Error(`Update of \"${update.dataRef}\": ${message}`);\n // The schema refuses these shapes too, but a spec that was not checked against it reaches here.\n if ((update.geojsonObject === undefined) === (update.jsonObject === undefined))\n throw refuse('give its rows in geojsonObject or in jsonObject, one of the two.');\n if (update.strategy === 'update' && !update.idColumn)\n throw refuse(\"the update strategy needs an idColumn, the column that matches a given row to the table's rows.\");\n let data = (update.geojsonObject ?? update.jsonObject) as FeatureCollection | Record<string, unknown>[];\n let idColumn = update.idColumn;\n try {\n // A layer keyed by a feature property is matched here, then updated by its rows' feature ids.\n const table = db.getTablesMetadata().find((candidate) => candidate.name === update.dataRef);\n if (update.strategy === 'update' && update.geojsonObject && idColumn?.startsWith('properties.') && table && isVectorTable(table)) {\n ({ data, idColumn } = await updateByFeatureId(db, table, update.geojsonObject as FeatureCollection, idColumn.slice('properties.'.length)));\n // No row has a given key, so the table stays as it is, as autk-db leaves it.\n if ((data as FeatureCollection).features.length === 0) {\n print(db, targets);\n return db;\n }\n }\n await db.updateTable({\n tableName: update.dataRef,\n data,\n strategy: update.strategy,\n ...(idColumn !== undefined && { idColumn }),\n });\n } catch (err) {\n throw refuse(err instanceof Error ? err.message : String(err));\n }\n await recache(db, workspace, update.dataRef);\n print(db, targets);\n return db;\n }\n case 'drop': {\n const drop = rest_spec as DropSourceSpec;\n // autk-db drops a table it does not hold without a word, so a name that names none is refused here.\n if (!db.getTablesMetadata().some((table) => table.name === drop.dataRef))\n throw new Error(`Drop of \"${drop.dataRef}\": ${workspaceLabel(workspace)} holds no table of that name.`);\n await db.removeLayer(drop.dataRef);\n cache?.delete(tableKey(workspace, drop.dataRef));\n print(db, targets);\n return db;\n }\n default:\n // The schema refuses any other type, but a spec that was not checked against it reaches here. Handing\n // the engine no database would make the next source start a new one, without the tables before it.\n throw new Error(`Unknown data source type \"${String(type)}\".`);\n }\n }\n }\n}\n","import type { MapSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { FeatureCollection } from 'geojson';\nimport type { MapId } from './types';\n\n/** A layer a map of the last run draws, as the map adapter registers it once the map's layers are loaded. */\nexport interface DrawnLayer {\n /** The map that draws it. */\n map: AutkMap;\n /** The map's index in the spec's `map` list. */\n mapIndex: number;\n /** The map's {@link MapId}: its `id`, else its index. */\n mapId: MapId;\n /** The layer's id in the map: its `title`, else its `dataRef`. */\n layerId: string;\n /** The table the layer draws. */\n dataRef: string;\n /** The key of the row the layer draws at each of its positions (see `rowKeys`); empty for a raster. */\n rows: readonly string[];\n}\n\n/** Every layer the maps of the last run draw, one entry per layer of each map: the maps in order, layers bottom first. */\nexport type DrawnLayers = DrawnLayer[];\n\n/** The layers each plot is linked to, by a link or its `mapRef`, keyed by the plot's `id`, else its `dataRef`. */\nexport type PlotLinks = Map<string, DrawnLayer[]>;\n\n/** The key of the row each plot draws at each of its positions (see `rowKeys`), keyed by the plot's `id`, else its `dataRef`. */\nexport type PlotRows = Map<string, readonly string[]>;\n\n/** The export of each table a map or a plot of the last run read, by its `tableKey`. */\nexport type LayerExports = Map<string, Promise<FeatureCollection>>;\n\n/**\n * The key of a table's export in {@link LayerExports}: its `tableKey`, with ` osm-elements` added for the export of one\n * feature per OpenStreetMap element, which a layer or a plot with `osmElements` reads. A table's name holds no space, so\n * the two never meet.\n */\nexport function exportKey(key: string, osmElements?: boolean): string {\n return osmElements === true ? `${key} osm-elements` : key;\n}\n\n/** autk-db's options for a table's export: one feature per OpenStreetMap element with `osmElements`, else none. */\nexport function exportOptions(osmElements?: boolean): { osmElements: true } | undefined {\n return osmElements === true ? { osmElements: true } : undefined;\n}\n\n/** A table's export, taken once a run, so the maps and the plots of one table draw the same rows. */\nexport function exportOf(exports: LayerExports | undefined, key: string, load: () => Promise<FeatureCollection>): Promise<FeatureCollection> {\n if (!exports) return load();\n let collection = exports.get(key);\n if (!collection) {\n collection = load();\n exports.set(key, collection);\n }\n return collection;\n}\n\n/** A map's {@link MapId}: its `id`, else its index in the spec's `map` list, which `arrangeViews` gives its pane as its `key`. */\nexport function mapIdOf(spec: MapSpec | undefined, index: number): MapId {\n return spec?.id ?? index;\n}\n\n/**\n * Whether a layer is on the map `mapId` names: a string names a map by its `id`, a number by its index. Without one,\n * every layer is.\n */\nexport function isOnMap(layer: DrawnLayer, mapId?: MapId): boolean {\n if (mapId === undefined) return true;\n return typeof mapId === 'number' ? layer.mapIndex === mapId : layer.mapId === mapId;\n}\n\n/** Records that a plot is linked to a layer, once. */\nexport function addPlotLink(links: PlotLinks | undefined, plotKey: string, layer: DrawnLayer): void {\n const linked = links?.get(plotKey) ?? [];\n if (!linked.includes(layer)) links?.set(plotKey, [...linked, layer]);\n}\n","/**\n * A points layer's `pointSize`, the radius of its points in meters on the ground, as autk-map's `pointSize`, a radius\n * in the workspace's planar units. Nothing here needs a GPU or a database, so the unit tests run it in Node.\n */\n\n/** WGS84's semi-major axis, in meters: the radius of Web Mercator's sphere and of World Mercator's ellipsoid. */\nconst WGS84_A = 6378137;\n\n/** WGS84's first eccentricity, which shapes World Mercator's ellipsoid. */\nconst WGS84_E = 0.0818191908426215;\n\n/** Refuses a `pointSize` that is not a number of meters greater than 0, naming the layer. An unset one passes. */\nexport function checkPointSize(pointSize: unknown, layerId: string): void {\n if (pointSize === undefined) return;\n if (typeof pointSize === 'number' && Number.isFinite(pointSize) && pointSize > 0) return;\n const shown = typeof pointSize === 'number' ? String(pointSize) : JSON.stringify(pointSize);\n throw new Error(`Layer \"${layerId}\": pointSize must be a number of meters greater than 0, not ${shown}.`);\n}\n\n/** The latitude, in radians, of a World Mercator (EPSG:3395) planar y, on the WGS84 ellipsoid. */\nfunction worldMercatorLatitude(y: number): number {\n const t = Math.exp(-y / WGS84_A);\n let phi = Math.PI / 2 - 2 * Math.atan(t);\n for (let i = 0; i < 10; i++) {\n const s = WGS84_E * Math.sin(phi);\n const next = Math.PI / 2 - 2 * Math.atan(t * ((1 - s) / (1 + s)) ** (WGS84_E / 2));\n if (Math.abs(next - phi) < 1e-12) return next;\n phi = next;\n }\n return phi;\n}\n\n/**\n * How many planar units of the workspace CRS `crs` one meter on the ground spans at the planar y `y`: Mercator's scale\n * factor at the latitude φ of `y`. In World Mercator (EPSG:3395, autk-db's default), on the WGS84 ellipsoid, it is\n * sec φ times sqrt(1 - e² sin² φ); in Web Mercator (EPSG:3857), on a sphere, sec φ. Any other CRS is taken as\n * projected in meters, so a meter is one planar unit.\n */\nexport function planarUnitsPerMeter(crs: string, y: number): number {\n if (/^EPSG:3395$/i.test(crs)) {\n const phi = worldMercatorLatitude(y);\n const s = WGS84_E * Math.sin(phi);\n return Math.sqrt(1 - s * s) / Math.cos(phi);\n }\n // On the sphere, sec φ of the latitude of y is cosh(y / a).\n if (/^EPSG:3857$/i.test(crs)) return Math.cosh(y / WGS84_A);\n return 1;\n}\n\n/**\n * The radius autk-map draws a layer's points with, in the planar units of the workspace CRS `crs`: `pointSize` meters\n * at the middle of the layer's planar y. `extent` gives the layer's `[minX, minY, maxX, maxY]` in workspace units, or\n * `undefined` when it has no points, and is read only for a points layer that sets `pointSize`. `undefined` when the\n * layer sets none, which keeps autk-map's default, when it is not a points layer, which ignores it, and when it has\n * no points.\n */\nexport function planarPointSize(\n pointSize: number | undefined,\n type: string | undefined,\n crs: string,\n extent: () => readonly number[] | undefined,\n): number | undefined {\n if (pointSize === undefined || type !== 'points') return undefined;\n const box = extent();\n if (!box) return undefined;\n return pointSize * planarUnitsPerMeter(crs, (box[1] + box[3]) / 2);\n}\n","import type { FeatureCollection } from 'geojson';\nimport { MapAdapter, MapLayerSpec, MapSpec, CameraSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { Targets, ComputeCache, ComputeLayerTypes } from '../types';\nimport { DrawnLayers, LayerExports, exportKey, exportOf, exportOptions, mapIdOf } from '../drawn';\nimport { rowKeys } from '../rows';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport type { LayerRenderInfo } from '@urban-toolkit/autk-map';\nimport { ColorMap, ColorMapDomainStrategy, ColorMapInterpolator } from '@urban-toolkit/autk-core';\nimport type { ColorHEX, ColorMapConfig, ColorMapDomainSpec, ColorRGB, LayerType, TransferFunction } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { extentOf } from './data';\nimport { checkPointSize, planarPointSize } from '../point-size';\n\n/** The id a layer has in its map: its `title`, else its `dataRef`. */\nexport function layerIdOf(layerRef: MapLayerSpec): string {\n return typeof layerRef.title === 'string' && layerRef.title !== '' ? layerRef.title : layerRef.dataRef;\n}\n\n/** Refuses a map whose layers would share an id. */\nfunction checkLayerIds(spec: MapSpec, index: number): void {\n const ids = new Set<string>();\n for (const layerRef of spec.layerRefs) {\n const id = layerIdOf(layerRef);\n if (ids.has(id))\n throw new Error(`Map ${index} draws two layers with the id \"${id}\". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);\n ids.add(id);\n }\n}\n\nconst HEX_COLOR = /^#[0-9a-fA-F]{6}$/;\n\nfunction hexColor(value: string, key: string, layerId: string): ColorRGB {\n if (!HEX_COLOR.test(value))\n throw new Error(`Layer \"${layerId}\": ${key} must be a color written #rrggbb, not \"${value}\".`);\n return ColorMap.hexToRgb(value as ColorHEX);\n}\n\n/** What `color`, `stroke` and `width` set on the layer's autk-map render info. */\nfunction styleRenderInfo(layerRef: MapLayerSpec, layerId: string): Partial<LayerRenderInfo> {\n const renderInfo: Partial<LayerRenderInfo> = {};\n if (layerRef.color != null)\n renderInfo.color = hexColor(layerRef.color, 'color', layerId);\n if (layerRef.stroke === false)\n renderInfo.showBorders = false;\n else if (layerRef.stroke != null)\n renderInfo.strokeColor = hexColor(layerRef.stroke, 'stroke', layerId);\n if (layerRef.width != null)\n renderInfo.polylinesWidth = layerRef.width;\n return renderInfo;\n}\n\n/**\n * Whether the layer is colored by value. An explicit `isColorMap` decides. A raster layer is colored by value\n * either way, and this only shows or hides its legend. Otherwise a layer with a `color` is drawn in it, and a\n * layer with a scheme or a `getFnv` value is colored by value.\n */\nfunction colorsByValue(layerRef: MapLayerSpec, type: LayerType): boolean {\n if (layerRef.isColorMap != null) return layerRef.isColorMap;\n if (type === 'raster')\n return layerRef.colorMapInterpolator != null || layerRef.colorMapRange != null || layerRef.colorMapCenter != null\n || layerRef.colorMapReverse === true;\n if (layerRef.color != null) return false;\n return layerRef.colorMapInterpolator != null || layerRef.getFnv != null;\n}\n\n/** A raster band's values, as autk-map reads them. */\nfunction bandValues(collection: { features?: { properties?: unknown }[] }, band: string): Float32Array | null {\n const values = (collection.features?.[0]?.properties as Record<string, unknown> | undefined)?.[band];\n if (values instanceof Float32Array) return values;\n if ((ArrayBuffer.isView(values) && !(values instanceof DataView)) || Array.isArray(values))\n return Float32Array.from(values as ArrayLike<number>, (v) => (Number.isFinite(Number(v)) ? Number(v) : NaN));\n return null;\n}\n\n/**\n * The domain of a raster's color scale when the layer sets a range, a center or reverse, or `undefined` when it\n * sets none of them, the scheme is categorical, or, without a range, the band has no value. A range is the domain:\n * `[low, high]`, or `[low, center, high]` with a center. Without one, a scale centered on `center` runs from the\n * center less the farthest value's distance to it, to the center plus that distance; when every value is the\n * center, it is not centered. Otherwise it is the domain autk-map resolves from `config`. `reverse` turns it around.\n */\nexport function rasterScaleDomain(\n values: Float32Array | null, config: ColorMapConfig, center?: number, reverse?: boolean, range?: [number, number],\n): number[] | undefined {\n if (ColorMap.isCategorical(config.interpolator)) return undefined;\n if (range != null) {\n const domain = center != null ? [range[0], center, range[1]] : [range[0], range[1]];\n return reverse === true ? domain.reverse() : domain;\n }\n if (!values) return undefined;\n let reach = 0;\n let finite = 0;\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n if (!Number.isFinite(value)) continue;\n finite++;\n if (center != null) reach = Math.max(reach, Math.abs(value - center));\n }\n const centered = center != null && reach > 0;\n if (finite === 0 || (!centered && reverse !== true)) return undefined;\n const domain = centered && center != null\n ? [center - reach, center, center + reach]\n : ColorMap.resolveDomainFromData(values, config) as number[];\n return reverse === true ? [...domain].reverse() : domain;\n}\n\n/**\n * The domain of a vector layer's color scale: its range, unless the scheme is categorical. autk-map colors a vector\n * layer on the GPU from its domain's first value to its last, which must be the higher, so the domain is neither\n * centered nor reversed.\n */\nfunction vectorScaleDomain(config: ColorMapConfig, range?: [number, number]): number[] | undefined {\n if (range == null || ColorMap.isCategorical(config.interpolator)) return undefined;\n return [range[0], range[1]];\n}\n\n/**\n * Refuses a `colorMapRange` that is not two numbers with low less than high, one set with `colorMapDomain`, and\n * one whose layer's `colorMapCenter` lies outside it. The schema refuses the same shapes and the pairing with\n * `colorMapDomain`, but JSON Schema cannot compare two values: a low above its high and a center outside the range\n * are refused only here.\n */\nfunction checkColorMapRange(layerRef: MapLayerSpec): void {\n const range: unknown = layerRef.colorMapRange;\n if (range === undefined) return;\n const refuse = (message: string) => new Error(`Layer \"${layerIdOf(layerRef)}\": ${message}`);\n if (!Array.isArray(range) || range.length !== 2 || !range.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('colorMapRange must hold two numbers, [low, high].');\n const [low, high] = range as [number, number];\n if (low >= high)\n throw refuse(`colorMapRange low (${low}) must be less than high (${high}).`);\n if (layerRef.colorMapDomain !== undefined)\n throw refuse('set colorMapRange or colorMapDomain, not both.');\n const center = layerRef.colorMapCenter;\n if (center != null && (center < low || center > high))\n throw refuse(`colorMapCenter (${center}) must lie within colorMapRange [${low}, ${high}].`);\n}\n\nfunction buildDomainSpec(\n normalization: MapSpec['layerRefs'][number]['normalization'],\n colorMapDomain?: string[],\n): ColorMapDomainSpec {\n if (colorMapDomain && colorMapDomain.length > 0)\n return { type: ColorMapDomainStrategy.USER, params: colorMapDomain };\n if (normalization?.mode === NormalizationMode.PERCENTILE) {\n const hasExplicitBounds =\n normalization.lowerPercentile !== undefined || normalization.upperPercentile !== undefined;\n if (hasExplicitBounds)\n return {\n type: ColorMapDomainStrategy.PERCENTILE,\n params: [normalization.lowerPercentile ?? 0, normalization.upperPercentile ?? 100],\n };\n return { type: ColorMapDomainStrategy.PERCENTILE };\n }\n return { type: ColorMapDomainStrategy.MIN_MAX };\n}\n\nfunction valueAtPath(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, obj);\n}\n\nfunction setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> {\n const keys = path.split('.');\n const result = { ...obj };\n let current = result as Record<string, unknown>;\n for (let i = 0; i < keys.length - 1; i++) {\n current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown> ?? {}) };\n current = current[keys[i]] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n return result;\n}\n\n/**\n * Resolves a grammar value path such as `count.noise` to the raster band that holds it.\n * autk-db stores heatmap values in bands (`band_1`, ...) labelled `<aggregateFn>_<table>`.\n */\nfunction rasterBand(collection: { features?: { properties?: unknown }[] }, getFnv?: string): string {\n const props = collection.features?.[0]?.properties as { bands?: { id: string; label?: string }[] } | undefined;\n const bands = props?.bands ?? [];\n const band = bands.find((b) => b.id === getFnv || b.label === getFnv?.replace(/\\./g, '_'));\n return band?.id ?? bands[0]?.id ?? getFnv ?? '';\n}\n\n/**\n * Why a run refuses `camera`, or `undefined` when it takes it: a pitch that is not at least 0 and less than 90 degrees.\n * At 90 the eye would sit on the ground, edge-on to the map's flat layers, and autk-map's pan, which moves the eye by\n * its height, would stand still. The schema refuses the same pitches.\n */\nfunction cameraRefusal(camera: CameraSpec): string | undefined {\n const { pitch } = camera as { pitch?: unknown };\n if (pitch === undefined || (typeof pitch === 'number' && pitch >= 0 && pitch < 90)) return undefined;\n const shown = typeof pitch === 'number' ? String(pitch) : JSON.stringify(pitch);\n return `camera.pitch must be at least 0 and less than 90 degrees, not ${shown}: at 90 the eye would sit on the ground, edge-on to the map's flat layers, and the map could not pan.`;\n}\n\n/**\n * Moves a map's camera as `camera` says, from the view that fits the map's layers. The camera reports each change,\n * so the map redraws without a request. It refuses a pitch that is not at least 0 and less than 90 degrees.\n *\n * The map adapter calls it once the map's layers are loaded and before the map's first `draw()`. A host that builds\n * its own map from a spec's `map` entry calls it at the same point, so the map looks from where the grammar's would.\n */\nexport function applyCamera(map: AutkMap, camera: CameraSpec): void {\n const refused = cameraRefusal(camera);\n if(refused) throw new Error(refused);\n if(camera.zoom === undefined && !camera.pitch && !camera.bearing) return;\n\n // Turn the view around the point it looks at: the eye moves on a sphere around that point, so the data stays\n // in view at any pitch. `pitch` is the angle from straight down and `bearing` the compass heading of the view,\n // clockwise from north.\n const view = map.camera;\n const [x, y] = view.getLookAt();\n const distance = camera.zoom !== undefined ? 10000 / Math.pow(2, camera.zoom - 10) : Math.abs(view.getEye()[2]);\n const pitch = (camera.pitch ?? 0) * Math.PI / 180;\n const bearing = (camera.bearing ?? 0) * Math.PI / 180;\n const eye = [\n x - distance * Math.sin(pitch) * Math.sin(bearing),\n y - distance * Math.sin(pitch) * Math.cos(bearing),\n distance * Math.cos(pitch),\n ];\n // The view's up direction: across the line of sight at any pitch, toward the far side of the view, as autk-map's own\n // tilt leaves it. autk-map's pan, tilt and zoom at the cursor move along it and take it to be across the line of\n // sight; a horizontal one is not, beyond a pitch of 0. The view itself is the same either way.\n const up = [Math.cos(pitch) * Math.sin(bearing), Math.cos(pitch) * Math.cos(bearing), Math.sin(pitch)];\n view.resetCamera(up, [x, y, 0], eye);\n}\n\n/**\n * The key of the row a vector layer draws at each of its positions. autk-map draws each feature it is handed as one\n * component, in order, and none for a feature with nothing to draw; a component names its feature by its index among\n * those handed (`featureIndex`). `kept` gives the table row of each feature handed, and `keys` each table row's key.\n */\nfunction drawnRowKeys(map: AutkMap, layerId: string, keys: readonly string[], kept: readonly number[]): string[] {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as { components?: Array<{ featureIndex?: number }> } | null;\n const components = layer?.components;\n if (!Array.isArray(components)) return kept.map((row) => keys[row] ?? '');\n return components.map((component, position) => {\n const handed = Number.isInteger(component?.featureIndex) ? component.featureIndex! : position;\n return keys[kept[handed]] ?? '';\n });\n}\n\n/**\n * The map adapter `AutkGrammar` runs. Each map it draws goes in `maps` at its index, and each of its layers in `layers`,\n * with the rows it draws, so every map stays known, though several draw one table. A table's export is taken once a\n * run, in `exports`, which the plot adapter reads too.\n */\nexport function createMapAdapter(targets?: Targets, layers?: DrawnLayers, computeCache?: ComputeCache, maps?: AutkMap[], computeTypes?: ComputeLayerTypes, exports?: LayerExports): MapAdapter {\n\n /** Loads each layer of `spec` on `map`, and gives the keys of the rows each draws, in the order of the layers. */\n async function loadLayers(map: AutkMap, context: AutkDb, spec: MapSpec): Promise<string[][]> {\n let tableToTypeMap: {[tableName: string]: string} = {};\n for(const table of context.getTablesMetadata()) {\n if(table.type !== undefined) tableToTypeMap[table.name] = table.type;\n }\n\n const drawn: string[][] = [];\n for(const layerRef of spec.layerRefs){\n const name = layerRef.dataRef;\n const layerId = layerIdOf(layerRef);\n const key = tableKey(spec.workspace, name);\n const type = (computeTypes?.get(key) ?? tableToTypeMap[name]) as LayerType;\n const getFnv = layerRef.getFnv;\n\n const rawData = computeCache?.get(key) ?? (type === 'raster'\n ? await context.getRaster(name) as unknown as FeatureCollection\n : await exportOf(exports, exportKey(key, layerRef.osmElements), () => context.getLayer(name, exportOptions(layerRef.osmElements))));\n // Raster tables (e.g. heatmaps) are a single feature with no geometry, so keep them as-is. A vector layer\n // is handed the rows with a geometry: `kept` holds the table row of each.\n const rows = rawData.features ?? [];\n const kept = type === 'raster' ? [] : rows.flatMap((feature, row) => (feature?.geometry != null ? [row] : []));\n const data = type === 'raster' ? rawData : { ...rawData, features: kept.map((row) => rows[row]) };\n const band = type === 'raster' ? rasterBand(data, getFnv) : '';\n\n if(type === 'raster') {\n map.loadCollection(layerId, { collection: data, type: 'raster', property: band });\n } else {\n map.loadCollection(layerId, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(layerId, { opacity: layerRef.opacity });\n\n const style = styleRenderInfo(layerRef, layerId);\n if(Object.keys(style).length > 0)\n map.updateRenderInfo(layerId, style);\n\n // pointSize is in meters on the ground, and autk-map's in planar units, which Mercator stretches away\n // from the equator: the layer's points are sized at the middle of its extent.\n const crs = context.getWorkspaceConfiguration().coordinateFormat;\n const pointSize = planarPointSize(layerRef.pointSize, type, crs, () => extentOf(data));\n if(pointSize !== undefined)\n map.updateRenderInfo(layerId, { pointSize });\n\n // Thematic (getFnv) vector layers are colored by value out of the box: autk-map\n // attaches a default colour ramp to every layer, so this works even when the\n // spec omits colorMapInterpolator (see colorsByValue).\n if(colorsByValue(layerRef, type))\n map.updateRenderInfo(layerId, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(layerId, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(layerId, { isSkip: true });\n\n // When catchAllCategory is set, remap features whose property value is not\n // in colorMapDomain to the catch-all label, and extend the domain to include it.\n const { catchAllCategory, colorMapDomain } = layerRef;\n let thematicData = data;\n let effectiveDomain = colorMapDomain;\n\n if(getFnv && catchAllCategory && colorMapDomain?.length) {\n const allowed = new Set(colorMapDomain);\n thematicData = {\n ...data,\n features: data.features.map((f: any) => {\n const props = f.properties as Record<string, unknown>;\n const val = valueAtPath(props, getFnv);\n if(val === undefined || val === null || !allowed.has(String(val))) {\n return { ...f, properties: setValueAtPath(props, getFnv, catchAllCategory) };\n }\n return f;\n }),\n };\n effectiveDomain = allowed.has(catchAllCategory)\n ? colorMapDomain\n : [...colorMapDomain, catchAllCategory];\n }\n\n // A raster's transfer function is only stored by setTransferFunction; the\n // updateColorMap below colors the cells again with it.\n const rasterTransfer = type === 'raster' && layerRef.transferFunction != null;\n if(rasterTransfer) {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as\n { setTransferFunction?: (transferFunction: TransferFunction) => void } | null;\n layer?.setTransferFunction?.(layerRef.transferFunction as TransferFunction);\n }\n\n // The scheme and its domain go through updateColorMap, which colors a raster's\n // cells again and gives the legend its labels. A vector layer keeps the domain\n // in its config, where the updateThematic below reads it.\n const range = layerRef.colorMapRange;\n const rasterScale = type === 'raster' && (range != null || layerRef.colorMapCenter != null || layerRef.colorMapReverse === true);\n if(layerRef.colorMapInterpolator || rasterScale || range) {\n const colormapConfig: ColorMapConfig = {\n // urban-grammar ColorMapInterpolator values are string-compatible\n // with autk-core ColorMapInterpolator at runtime\n interpolator: (layerRef.colorMapInterpolator as unknown as ColorMapConfig['interpolator'] | undefined)\n ?? map.layerManager.searchByLayerId(layerId)?.layerRenderInfo.colormap.config.interpolator\n ?? ColorMapInterpolator.SEQ_REDS,\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n let domain: number[] | undefined;\n if(rasterScale)\n domain = rasterScaleDomain(bandValues(data, band), colormapConfig, layerRef.colorMapCenter, layerRef.colorMapReverse, range);\n else if(type !== 'raster')\n domain = vectorScaleDomain(colormapConfig, range);\n if(domain)\n colormapConfig.domainSpec = { type: ColorMapDomainStrategy.USER, params: domain };\n map.updateColorMap(layerId, { colorMap: colormapConfig });\n } else if(rasterTransfer) {\n map.updateColorMap(layerId, { colorMap: {} });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(layerId, { collection: thematicData, property });\n }\n\n drawn.push(type === 'raster' ? [] : drawnRowKeys(map, layerId, rowKeys(rows), kept));\n }\n return drawn;\n }\n\n return {\n async resolveMap(context: AutkDb | undefined, spec: MapSpec, index: number = 0): Promise<void> {\n if(targets && targets.map && context){\n\n checkLayerIds(spec, index);\n for(const layerRef of spec.layerRefs) {\n checkColorMapRange(layerRef);\n checkPointSize(layerRef.pointSize, layerIdOf(layerRef));\n }\n // Refused before the map is made, so a refused camera leaves nothing on the page.\n const refusedCamera = spec.camera && cameraRefusal(spec.camera);\n if(refusedCamera)\n throw new Error(`Map ${index}: ${refusedCamera}`);\n\n let canvas;\n\n if(Array.isArray(targets.map)){\n canvas = document.getElementById(targets.map[index]);\n }else{\n canvas = document.getElementById(targets.map);\n }\n\n if(!canvas)\n throw new Error(\"Could not find rendering target for map: \"+targets.map);\n\n if(!(canvas instanceof HTMLCanvasElement))\n throw new Error(\"Target for map is not a canvas: \"+targets.map);\n\n const map = new AutkMap(canvas);\n\n // A map is known to the grammar, which destroys it, once its layers are loaded. One that fails before\n // is destroyed here, so its controls, event handlers and GPU buffers do not outlive the failed run.\n let drawn: string[][];\n try {\n if(spec.style)\n map.style.setPredefinedStyle(spec.style)\n\n await map.init();\n await enterWorkspace(context, spec.workspace);\n drawn = await loadLayers(map, context, spec);\n } catch(error) {\n try {\n map.destroy();\n } catch {\n // The run reports the load's error, not the teardown's.\n }\n throw error;\n }\n\n const mapId = mapIdOf(spec, index);\n spec.layerRefs.forEach((layerRef, at) => layers?.push({\n map, mapIndex: index, mapId, layerId: layerIdOf(layerRef), dataRef: layerRef.dataRef, rows: drawn[at],\n }));\n\n if(maps)\n maps[index] = map;\n\n if(spec.camera)\n applyCamera(map, spec.camera);\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { Targets, PlotRegistry, GeoJsonCache, ComputeCache } from '../types';\nimport { addPlotLink, exportKey, exportOf, exportOptions } from '../drawn';\nimport type { DrawnLayer, DrawnLayers, LayerExports, PlotLinks, PlotRows } from '../drawn';\nimport { rowKeys, translateIds } from '../rows';\nimport { AutkDb, isRenderableTable } from '@urban-toolkit/autk-db';\nimport { AutkPlot, PlotEvent as AutkPlotEvent } from '@urban-toolkit/autk-plot';\nimport type { PlotEventData, PlotType, PlotTransformConfig } from '@urban-toolkit/autk-plot';\nimport { MapEvent } from '@urban-toolkit/autk-map';\nimport type { MapEventData } from '@urban-toolkit/autk-map';\nimport { FeatureCollection } from 'geojson';\n\nfunction grammarMarkToPlotType(mark: PlotMark): PlotType {\n const mapping: Record<PlotMark, PlotType> = {\n 'scatter': 'scatterplot',\n 'bar': 'barchart',\n 'line': 'linechart',\n 'linechart': 'linechart',\n 'parallel-coordinates': 'parallel-coordinates',\n 'table': 'table',\n 'heatmatrix': 'heatmatrix',\n };\n return mapping[mark];\n}\n\n/** How a plot is known to links and to `AutkGrammar`: its `id`, else its `dataRef`. */\nexport function plotKey(spec: PlotSpec): string {\n return spec.id ?? spec.dataRef;\n}\n\n/**\n * Links a plot to a layer of a map: picking on the layer selects the features in the plot, and a selection in\n * the plot highlights them on the layer. `rows` holds the key of the row the plot draws at each position: a selection\n * passes between the two by the rows each drew (see `translateIds`), since one position can be another row in each.\n */\nexport function linkPlotToLayer(plot: AutkPlot, rows: readonly string[], events: AutkPlotEvent[], layer: DrawnLayer): void {\n const { map, layerId } = layer;\n map.updateRenderInfo(layerId, { isPick: true });\n\n // A pick names the layer it was made on, so a pick on another layer of the map leaves the plot alone.\n map.events.on(MapEvent.PICKING, ({ layerId: picked, selection }: MapEventData) => {\n if (picked === layerId) plot.setSelection(translateIds(selection, layer.rows, rows));\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(layerId, translateIds(selection, rows, layer.rows));\n });\n }\n}\n\n/**\n * A table's rows as a plot reads them from autk-db: the export of a table with a geometry, the one the maps of the run\n * draw, one feature per OpenStreetMap element with `osmElements`, and for a table without one, such as a CSV or JSON\n * table loaded without `geometryColumns`, which autk-db does not export as a layer, its rows, each a feature without a\n * geometry. autk-plot reads only the features' properties.\n */\nasync function tableRows(db: AutkDb, name: string, key: string, exports?: LayerExports, osmElements?: boolean): Promise<FeatureCollection> {\n const table = db.getTablesMetadata().find((candidate) => candidate.name === name);\n if (table && !isRenderableTable(table)) {\n const rows = await db.getTable(name);\n // A feature without a geometry, which GeoJSON allows and the plot does not read.\n return { type: 'FeatureCollection', features: rows.map((properties) => ({ type: 'Feature', geometry: null, properties })) } as unknown as FeatureCollection;\n }\n return exportOf(exports, exportKey(key, osmElements), () => db.getLayer(name, exportOptions(osmElements)));\n}\n\n/**\n * The plot adapter `AutkGrammar` runs. Each plot it draws goes in `plotRegistry`, and the keys of the rows it draws in\n * `plotRows`, by the plot's `id`, else its `dataRef`. A table it reads from autk-db is the export the maps of the run\n * draw, from `exports`.\n */\nexport function createPlotAdapter(targets?: Targets, layers?: DrawnLayers, plotRegistry?: PlotRegistry, plotLinks?: PlotLinks, cache?: GeoJsonCache, computeCache?: ComputeCache, plotRows?: PlotRows, exports?: LayerExports): PlotAdapter {\n\n return {\n async resolvePlot(context: unknown, spec: PlotSpec, index: number = 0): Promise<void> {\n if(!targets || !targets.plot) return;\n\n // One id holds every plot; a list gives each plot its own, in the order of the plots.\n const target = Array.isArray(targets.plot) ? targets.plot[index] : targets.plot;\n if(target === undefined) throw new Error(`Plot ${index} has no target: the plot targets name ${targets.plot.length} elements.`);\n\n const div = document.getElementById(target);\n if(!div) throw new Error(`Could not find plot target: ${target}`);\n\n const db = context as AutkDb | undefined;\n if(!db) throw new Error('No data context available for plot.');\n\n await enterWorkspace(db, spec.workspace);\n const key = tableKey(spec.workspace, spec.dataRef);\n // The rows of a GeoJSON source or a join are a row per feature, so a plot of OSM elements reads autk-db's.\n const cached = spec.osmElements === true ? undefined : cache?.get(key);\n const geojson: FeatureCollection = computeCache?.get(key) ?? cached ?? await tableRows(db, spec.dataRef, key, exports, spec.osmElements);\n\n const events = (spec.events ?? []) as unknown as AutkPlotEvent[];\n\n const plot = new AutkPlot(div, {\n type: grammarMarkToPlotType(spec.mark),\n collection: geojson,\n attributes: { axis: spec.axis, ...(spec.color && { color: spec.color }) },\n labels: { axis: spec.axis, title: spec.title },\n events,\n ...(spec.width && { width: spec.width }),\n ...(spec.height && { height: spec.height }),\n ...(spec.margins && { margins: spec.margins }),\n ...(spec.transform && { transform: spec.transform as PlotTransformConfig }),\n });\n\n plotRegistry?.set(plotKey(spec), plot);\n // autk-plot names a row by its position in the collection it draws.\n const rows = rowKeys(geojson.features ?? []);\n plotRows?.set(plotKey(spec), rows);\n\n // mapRef names the table of the layers to link to: every layer that draws it, in every map. The maps are\n // drawn before the plots.\n for(const layer of layers ?? []) {\n if(!spec.mapRef || layer.dataRef !== spec.mapRef) continue;\n linkPlotToLayer(plot, rows, events, layer);\n addPlotLink(plotLinks, plotKey(spec), layer);\n }\n }\n }\n}\n","import type { GpgpuComputeSpec, FromFeatureDirective } from '@urban-toolkit/the-urban-grammar';\nimport type { GpgpuPipelineParams } from '@urban-toolkit/autk-compute';\nimport type { Feature, FeatureCollection } from 'geojson';\n\n/** Tables a compute pass can read, keyed by table name. */\nexport type ComputeLayers = Record<string, FeatureCollection | undefined> | Map<string, FeatureCollection>;\n\n/** Runs one GPU dispatch, for example `params => new AutkComputeEngine().gpgpuPipeline(params)`. */\nexport type ComputeRunner = (params: GpgpuPipelineParams) => Promise<FeatureCollection>;\n\n/**\n * The storage buffer binding every WebGPU device supports: the default\n * `maxStorageBufferBindingSize`, 128 MiB. autk-compute 4 reads each array a `batched` directive\n * packs from a read-only storage buffer of its own, so every packed array must fit one binding.\n * autk-compute 3 bound them as uniform buffers, which hold 64 KiB (2048 bounding boxes).\n */\nexport const STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/** Bytes a feature adds to a packed array: one f32 for a scalar entry, a bounding box of eight for a matrix entry. */\nconst SCALAR_BYTES = 4;\nconst BOX_BYTES = 8 * 4;\n\ntype UniformEntry = number | FromFeatureDirective;\ntype MatrixEntry = { data: number[][]; cols: number } | FromFeatureDirective;\n\n/** Joins a `wgslFunction` written as an array of lines. Any other separator would let a `//` comment swallow the lines after it. */\nexport function joinWgsl(body: string | string[]): string {\n return Array.isArray(body) ? body.join('\\n') : body;\n}\n\n/** True when a uniform entry reads its value from a feature. */\nexport function isFromFeature(value: unknown): value is FromFeatureDirective {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n && typeof (value as FromFeatureDirective).fromFeature === 'object'\n && (value as FromFeatureDirective).fromFeature !== null;\n}\n\nfunction lookup(layers: ComputeLayers, name: string): FeatureCollection | undefined {\n return layers instanceof Map ? layers.get(name) : layers[name];\n}\n\nfunction valueAtPath(item: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, item);\n}\n\nfunction directives(block: GpgpuComputeSpec): FromFeatureDirective[] {\n const out: FromFeatureDirective[] = [];\n for (const cfg of [block.uniforms, block.uniformMatrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value)) out.push(value);\n }\n }\n return out;\n}\n\n/** Every table a compute pass reads: its `dataRef` plus each `fromFeature` layer. */\nexport function computeLayerNames(block: GpgpuComputeSpec): string[] {\n return [...new Set([block.dataRef, ...directives(block).map(d => d.fromFeature.layer)])];\n}\n\n/**\n * The iteration a compute pass asks for, or `null`. Every iterating directive must read the same\n * layer; the first one found decides the mode and the layer.\n */\nexport function findIterateSource(block: GpgpuComputeSpec): { mode: 'all' | 'batched'; layer: string } | null {\n for (const d of directives(block)) {\n const { iterate, layer } = d.fromFeature;\n if (iterate === 'all' || iterate === 'batched') return { mode: iterate, layer };\n }\n return null;\n}\n\nfunction resolveDirective(d: FromFeatureDirective, layers: ComputeLayers, iterateIndex?: number): unknown {\n const ff = d.fromFeature;\n const index = iterateIndex !== undefined && ff.iterate === 'all' ? iterateIndex : (ff.index ?? 0);\n const feature = lookup(layers, ff.layer)?.features?.[index];\n return feature ? valueAtPath(feature, ff.path) : undefined;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniforms` to numbers. An entry that does not resolve to a\n * finite number takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, number> | undefined {\n if (!uniforms) return undefined;\n const out: Record<string, number> = {};\n for (const [key, value] of Object.entries(uniforms)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const num = Number(resolveDirective(value, layers, iterateIndex) ?? NaN);\n if (Number.isFinite(num)) out[key] = num;\n else if (typeof value.default === 'number') out[key] = value.default;\n }\n return out;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniformMatrices` to `{ data, cols }`. An entry that does\n * not resolve to an array takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniformMatrices(\n matrices: Record<string, MatrixEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, { data: number[][]; cols: number }> | undefined {\n if (!matrices) return undefined;\n const out: Record<string, { data: number[][]; cols: number }> = {};\n for (const [key, value] of Object.entries(matrices)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const resolved = resolveDirective(value, layers, iterateIndex);\n const data = Array.isArray(resolved) ? (resolved as number[][])\n : Array.isArray(value.default) ? value.default : undefined;\n if (!data) continue;\n const cols = value.cols ?? (Array.isArray(data[0]) ? data[0].length : 0);\n if (cols > 0) out[key] = { data, cols };\n else console.warn(`[autk-grammar] uniform matrix \"${key}\" has no column count; entry dropped`);\n }\n return out;\n}\n\nfunction isFiniteValue(v: unknown): boolean {\n return v !== undefined && v !== null && !(typeof v === 'number' && !Number.isFinite(v));\n}\n\nfunction isBatched(value: unknown): boolean {\n return isFromFeature(value) && value.fromFeature.iterate === 'batched';\n}\n\n/** Bytes one feature adds to the largest array a batched pass packs, or 0 when it packs none. */\nfunction batchedBytesPerFeature(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n): number {\n if (Object.values(matrices ?? {}).some(isBatched)) return BOX_BYTES;\n if (Object.values(uniforms ?? {}).some(isBatched)) return SCALAR_BYTES;\n return 0;\n}\n\n/**\n * Most features a batched pass packs: as many as its largest array holds in one storage buffer\n * binding of `bindingSize` bytes. With {@link STORAGE_BUFFER_BINDING_SIZE} that is 4,194,304\n * features for a pass with a matrix entry, and 33,554,432 for one with scalar entries only.\n */\nexport function maxBatchedFeatures(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): number {\n const bytes = batchedBytesPerFeature(uniforms, matrices);\n return bytes > 0 ? Math.floor(bindingSize / bytes) : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Packs every feature of a `batched` layer into uniform arrays:\n * - a scalar entry becomes an array of one value per feature, under the entry's name;\n * - a matrix entry becomes each feature's axis-aligned bounding box as four corners\n * `[xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]`, eight values per feature;\n * - `num_features` holds the feature count.\n * Features missing a `required` path are dropped first, and at most {@link maxBatchedFeatures}\n * are packed: as many as the largest array holds in one storage buffer binding of `bindingSize`\n * bytes. Plain numbers pass through; other entries that do not iterate are left to\n * {@link resolveComputeParams}.\n */\nexport function buildBatchedUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n sources: Feature[],\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): { uniforms: Record<string, number>; uniformArrays: Record<string, number[]> } {\n const outUniforms: Record<string, number> = {};\n const outArrays: Record<string, number[]> = {};\n\n const required: string[] = [];\n for (const cfg of [uniforms, matrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched' && value.fromFeature.required) {\n required.push(value.fromFeature.path);\n }\n }\n }\n if (required.length > 0) {\n const before = sources.length;\n sources = sources.filter(f => required.every(p => isFiniteValue(valueAtPath(f, p))));\n if (sources.length < before) {\n console.info(`[autk-grammar] batched compute dropped ${before - sources.length} feature(s) missing ${required.join(', ')}`);\n }\n }\n const limit = maxBatchedFeatures(uniforms, matrices, bindingSize);\n if (sources.length > limit) {\n console.warn(\n `[autk-grammar] batched compute capped at ${limit} features (got ${sources.length}): `\n + `its largest packed array takes ${batchedBytesPerFeature(uniforms, matrices)} B per feature, `\n + `and a storage buffer binding holds ${bindingSize} B`,\n );\n sources = sources.slice(0, limit);\n }\n\n for (const [key, value] of Object.entries(uniforms ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched') {\n const fallback = typeof value.default === 'number' ? value.default : undefined;\n outArrays[key] = sources.map(f => {\n const num = Number(valueAtPath(f, value.fromFeature.path) ?? fallback);\n return Number.isFinite(num) ? num : 0;\n });\n } else if (typeof value === 'number') {\n outUniforms[key] = value;\n }\n }\n\n for (const [key, value] of Object.entries(matrices ?? {})) {\n if (!isFromFeature(value) || value.fromFeature.iterate !== 'batched') continue;\n const data: number[] = [];\n for (const f of sources) {\n const ring = valueAtPath(f, value.fromFeature.path);\n let xmin = Infinity, ymin = Infinity, xmax = -Infinity, ymax = -Infinity;\n if (Array.isArray(ring)) {\n for (const coord of ring) {\n if (!Array.isArray(coord) || coord.length < 2) continue;\n const x = Number(coord[0]);\n const y = Number(coord[1]);\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n xmin = Math.min(xmin, x); ymin = Math.min(ymin, y);\n xmax = Math.max(xmax, x); ymax = Math.max(ymax, y);\n }\n }\n // A degenerate feature gets a zero-area box, so the shader's loop runs but adds nothing.\n if (!Number.isFinite(xmin)) { xmin = 0; ymin = 0; xmax = 0; ymax = 0; }\n data.push(xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax);\n }\n outArrays[key] = data;\n }\n\n outUniforms.num_features = sources.length;\n return { uniforms: outUniforms, uniformArrays: outArrays };\n}\n\n/**\n * Turns a compute pass into the parameters of one GPU dispatch. Pure: it reads `layers` and runs\n * nothing. With `iterate: 'all'`, pass the feature index as `iterateIndex` for each dispatch (see\n * {@link runCompute}). Throws when the pass's `dataRef` is not in `layers`.\n */\nexport function resolveComputeParams(block: GpgpuComputeSpec, layers: ComputeLayers, iterateIndex?: number): GpgpuPipelineParams {\n const collection = lookup(layers, block.dataRef);\n if (!collection) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n\n const params: GpgpuPipelineParams = {\n collection,\n variableMapping: block.attributes,\n wgslBody: joinWgsl(block.wgslFunction),\n };\n if (block.attributeArrays) params.attributeArrays = block.attributeArrays;\n if (block.attributeMatrices) params.attributeMatrices = block.attributeMatrices;\n if (block.uniformArrays) params.uniformArrays = block.uniformArrays;\n if (block.outputColumnName) params.resultField = block.outputColumnName;\n if (block.outputColumns) params.outputColumns = block.outputColumns;\n\n const iterate = findIterateSource(block);\n if (iterate?.mode === 'batched') {\n const sources = lookup(layers, iterate.layer)?.features ?? [];\n const packed = buildBatchedUniforms(block.uniforms, block.uniformMatrices, sources);\n // Entries that do not iterate resolve as they would without iteration.\n const single = resolveUniforms(notBatched(block.uniforms), layers) ?? {};\n const matrices = resolveUniformMatrices(notBatched(block.uniformMatrices), layers);\n params.uniforms = { ...single, ...packed.uniforms };\n params.uniformArrays = { ...(params.uniformArrays ?? {}), ...packed.uniformArrays };\n if (matrices && Object.keys(matrices).length > 0) params.uniformMatrices = matrices;\n return params;\n }\n\n const index = iterate?.mode === 'all' ? iterateIndex : undefined;\n const uniforms = resolveUniforms(block.uniforms, layers, index);\n const matrices = resolveUniformMatrices(block.uniformMatrices, layers, index);\n if (uniforms) params.uniforms = uniforms;\n if (matrices) params.uniformMatrices = matrices;\n return params;\n}\n\nfunction notBatched<T>(entries: Record<string, T> | undefined): Record<string, T> | undefined {\n if (!entries) return undefined;\n return Object.fromEntries(Object.entries(entries).filter(([, v]) => !(isFromFeature(v) && v.fromFeature.iterate === 'batched')));\n}\n\nfunction outputColumns(block: GpgpuComputeSpec): string[] {\n return block.outputColumns ?? (block.outputColumnName ? [block.outputColumnName] : []);\n}\n\n/**\n * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is\n * one dispatch per feature of the iterated layer, and each output column holds the sum over them.\n */\nexport async function runCompute(block: GpgpuComputeSpec, layers: ComputeLayers, run: ComputeRunner): Promise<FeatureCollection> {\n const iterate = findIterateSource(block);\n if (iterate?.mode !== 'all') return run(resolveComputeParams(block, layers));\n\n const target = lookup(layers, block.dataRef);\n if (!target) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n const columns = outputColumns(block);\n const summed: FeatureCollection = structuredClone(target);\n for (const f of summed.features) {\n const props = (f.properties ??= {}) as Record<string, unknown>;\n const compute = (props.compute ??= {}) as Record<string, number>;\n for (const col of columns) compute[col] = 0;\n }\n\n const count = lookup(layers, iterate.layer)?.features?.length ?? 0;\n for (let i = 0; i < count; i++) {\n const step = await run({ ...resolveComputeParams(block, layers, i), collection: summed });\n summed.features.forEach((f, j) => {\n const dst = (f.properties as Record<string, unknown> | null)?.compute as Record<string, number> | undefined;\n const src = (step.features[j]?.properties as Record<string, unknown> | null)?.compute as Record<string, unknown> | undefined;\n if (!dst || !src) return;\n for (const col of columns) {\n const inc = Number(src[col]);\n if (Number.isFinite(inc)) dst[col] += inc;\n }\n });\n }\n return summed;\n}\n","import { ComputeAdapter, ComputeSpec, GpgpuComputeSpec, RenderComputeSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { LayerType, RenderLayerSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkComputeEngine } from '@urban-toolkit/autk-compute';\nimport { FeatureCollection } from 'geojson';\nimport { ComputeCache, ComputeLayerTypes } from '../types';\nimport { computeLayerNames, runCompute } from '../compute-params';\nimport { enterWorkspace, tableKey } from '../workspace';\n\n/**\n * The layer types a render pass draws. autk-compute skips a layer of any other type, points among them, with only a\n * warning, so the adapter refuses one.\n */\nconst RENDER_LAYER_TYPES: ReadonlyArray<RenderLayerSpec['type']> = ['surface', 'parks', 'water', 'roads', 'buildings', 'polygons', 'polylines'];\n\n/** The type of the table `name`, which the database knows or an earlier pass wrote. */\nfunction layerTypeOf(db: AutkDb, name: string, workspace: string | undefined, types?: ComputeLayerTypes): LayerType | undefined {\n return types?.get(tableKey(workspace, name)) ?? db.getTablesMetadata().find((table) => table.name === name)?.type as LayerType | undefined;\n}\n\n/**\n * The compute adapter `AutkGrammar` runs. Its `resolveCompute(db, pass)` runs one entry of a spec's `compute`, a\n * GPGPU pass or a render pass, on autk-compute, in the pass's workspace, which it leaves current. It does nothing\n * without a database.\n *\n * A host calls it to run compute passes exactly as the grammar does. The passes need WebGPU, and their results are\n * kept only in the caches: `cache` receives each pass's result under {@link tableKey} of its `outputTableName`, or of\n * the table it computed over, and a later pass reads a table from it first. `types` receives the layer type of each\n * table a pass wrote under its own `outputTableName`, which a map needs to draw it.\n */\nexport function createComputeAdapter(cache?: ComputeCache, types?: ComputeLayerTypes): ComputeAdapter {\n\n /** Reads a table, from the cache when an earlier pass wrote it there. */\n async function read(db: AutkDb, name: string, workspace?: string): Promise<FeatureCollection> {\n return cache?.get(tableKey(workspace, name)) ?? await db.getLayer(name);\n }\n\n /**\n * Stores a pass's result under `outputTableName`, or, without it, in place of the table `source`. A map draws a\n * new table as the spec's `layerType` says, else as `resultType`, else as it draws `source`.\n */\n function store(db: AutkDb, result: FeatureCollection, source: string, spec: GpgpuComputeSpec | RenderComputeSpec, resultType?: LayerType): void {\n if (!cache) return;\n const name = spec.outputTableName ?? source;\n cache.set(tableKey(spec.workspace, name), result);\n const type = spec.layerType ?? resultType ?? layerTypeOf(db, source, spec.workspace, types);\n if (spec.outputTableName && type) types?.set(tableKey(spec.workspace, name), type);\n }\n\n async function resolveRender(db: AutkDb, spec: RenderComputeSpec): Promise<void> {\n for (const layer of spec.layers) {\n if (!(RENDER_LAYER_TYPES as readonly string[]).includes(layer.type))\n throw new Error(`Render pass \"${spec.outputTableName}\": layer \"${layer.id}\" has the type \"${layer.type}\", which a render pass cannot draw. A layer's type is one of ${RENDER_LAYER_TYPES.join(', ')}.`);\n }\n\n const layers = await Promise.all(spec.layers.map(async (layer) => ({\n id: layer.id,\n collection: await read(db, layer.dataRef, spec.workspace),\n type: layer.type,\n objectIdProperty: layer.objectIdProperty,\n })));\n\n const result = await new AutkComputeEngine().renderPipeline({\n layers,\n viewpoints: {\n collection: await read(db, spec.viewpoints.dataRef, spec.workspace),\n strategy: spec.viewpoints.strategy,\n sampling: spec.viewpoints.sampling,\n },\n aggregation: spec.aggregation,\n camera: spec.camera,\n tileSize: spec.tileSize,\n });\n\n // With `building-windows` the result holds one point per window, not the viewpoints' features.\n store(db, result, spec.viewpoints.dataRef, spec, spec.viewpoints.strategy?.type === 'building-windows' ? 'points' : undefined);\n }\n\n async function resolveGpgpu(db: AutkDb, spec: GpgpuComputeSpec): Promise<void> {\n // A table an earlier compute pass wrote is read from the cache, so passes chain.\n // Only the pass's own table must load; a `fromFeature` table that cannot\n // falls back to the directive's `default`.\n const layers: Record<string, FeatureCollection | undefined> = {};\n for (const name of computeLayerNames(spec)) {\n const cached = cache?.get(tableKey(spec.workspace, name));\n if (cached) layers[name] = cached;\n else if (name === spec.dataRef) layers[name] = await db.getLayer(name);\n else {\n try { layers[name] = await db.getLayer(name); }\n catch { layers[name] = undefined; }\n }\n }\n\n const engine = new AutkComputeEngine();\n const result = await runCompute(spec, layers, params => engine.gpgpuPipeline(params));\n\n store(db, result, spec.dataRef, spec);\n }\n\n return {\n async resolveCompute(context: AutkDb | undefined, spec: ComputeSpec): Promise<AutkDb | undefined> {\n if (!context) return;\n await enterWorkspace(context, spec.workspace);\n if (spec.type === 'render') await resolveRender(context, spec);\n else await resolveGpgpu(context, spec);\n return context;\n }\n }\n}\n","import type { UrbanSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { AutkPlot } from '@urban-toolkit/autk-plot';\nimport type { LayerType } from '@urban-toolkit/the-urban-grammar';\nimport type { FeatureCollection } from 'geojson';\n\n/** The elements of the page `AutkGrammar` draws in, by id. */\nexport type Targets = {\n /** Not read by the adapter. */\n compute?: string,\n /** Id of an element that lists the loaded tables after each data source. */\n db?: string,\n /** Id of the canvas a map draws on, or a list of ids, one canvas per entry of `map`, in order. */\n map?: string[] | string,\n /**\n * Id of the element the plots draw in, or a list of ids, one element per entry of `plot`, in order. With one id,\n * every plot draws in that element.\n */\n plot?: string[] | string\n}\n\n/**\n * How the grammar names a map of the spec: its `id`, else its index in the spec's `map` list (0 for a single map).\n * `map:picking` events name the map by it, and the calls that take a `mapId` (`mapLayers`, `mapLayer`,\n * `highlightOnMap`, `clearHighlightOnMap`, `setPlotSelection`, `clearHighlightOnPlot`) address one map with it: a\n * string names a map by its `id`, a number by its index.\n */\nexport type MapId = string | number;\n\nexport type PlotRegistry = Map<string, AutkPlot>;\n\n/** A layer a map of the last run draws, as `AutkGrammar.mapLayer` finds it by its table's name. */\nexport interface GrammarMapLayer {\n /** The map that draws the layer. */\n map: AutkMap;\n /** The layer's id in that map: its `title`, else its `dataRef`. */\n layerId: string;\n}\nexport type GeoJsonCache = Map<string, FeatureCollection>;\nexport type ComputeCache = Map<string, FeatureCollection>;\n/** How the map draws a table a compute pass wrote under `outputTableName`, which the database does not know. */\nexport type ComputeLayerTypes = Map<string, LayerType>;\n\nexport type AutkGrammarSpec = UrbanSpec;\n\n// Grammar-level interaction payloads: no autk internals leak through the public API\nexport interface GrammarPickingEvent {\n /** The map the pick was made on, by its {@link MapId}: its `id`, else its index in the spec's `map` list. */\n mapId: MapId;\n /** The picked layer's id in its map: its `title`, else its `dataRef`. */\n layerId: string;\n selection: number[];\n}\n\nexport interface GrammarPlotSelectionEvent {\n /** The plot's `id`, else its `dataRef`. */\n plotId: string;\n event: 'click' | 'brush' | 'brushX' | 'brushY';\n selection: number[];\n}\n\nexport type GrammarEventRecord = {\n 'map:picking': GrammarPickingEvent;\n 'plot:selection': GrammarPlotSelectionEvent;\n};\n\n// Self-contained typed emitter: it does not import from autk packages\nexport class GrammarEventEmitter {\n private _listeners: Map<string, Set<(p: unknown) => void>> = new Map();\n\n on<K extends keyof GrammarEventRecord>(\n event: K,\n listener: (payload: GrammarEventRecord[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n const bucket = this._listeners.get(event)!;\n bucket.add(listener as (p: unknown) => void);\n return () => bucket.delete(listener as (p: unknown) => void);\n }\n\n /** @internal */\n emit<K extends keyof GrammarEventRecord>(event: K, payload: GrammarEventRecord[K]): void {\n this._listeners.get(event)?.forEach(l => l(payload));\n }\n}\n\n","import { DataAdapter, MapAdapter, PlotAdapter, ComputeAdapter, IEngine, PlotSpec, UrbanSpec, createEngine } from \"@urban-toolkit/the-urban-grammar\";\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from \"@urban-toolkit/autk-db\";\nimport { MapEvent } from \"@urban-toolkit/autk-map\";\nimport type { AutkMap } from \"@urban-toolkit/autk-map\";\nimport type { MapEventData } from \"@urban-toolkit/autk-map\";\nimport { PlotEvent } from \"@urban-toolkit/autk-plot\";\nimport type { PlotEventData } from \"@urban-toolkit/autk-plot\";\nimport { FeatureCollection } from \"geojson\";\nimport { createDataAdapter } from \"./adapters/data\";\nimport { createMapAdapter } from \"./adapters/map\";\nimport { createPlotAdapter, linkPlotToLayer, plotKey } from \"./adapters/plot\";\nimport { layerIdOf } from \"./adapters/map\";\nimport { enterWorkspace } from \"./workspace\";\nimport { createComputeAdapter } from \"./adapters/compute\";\nimport { Targets, PlotRegistry, GeoJsonCache, ComputeCache, ComputeLayerTypes, GrammarEventEmitter } from \"./types\";\nimport type { GrammarMapLayer, GrammarPlotSelectionEvent, MapId } from \"./types\";\nimport { DrawnLayer, DrawnLayers, LayerExports, PlotLinks, PlotRows, addPlotLink, isOnMap, mapIdOf } from \"./drawn\";\nimport { translateIds } from \"./rows\";\n\nfunction asList<T>(value: T[] | T | undefined): T[] {\n return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\n/**\n * An id names one view: no two maps or plots may share one, and an id is never empty. A plot without an id is known\n * by its dataRef, so no two plots may be known by one name either: two plots of a table without ids, or a plot whose\n * id is the dataRef of a plot without one.\n */\nfunction checkViewIds(spec: UrbanSpec): void {\n const seen = new Set<string>();\n for (const view of [...asList(spec.map), ...asList(spec.plot)]) {\n if (view.id === undefined) continue;\n if (view.id === '') throw new Error('A map or plot has an empty id.');\n if (seen.has(view.id)) throw new Error(`Two maps or plots have the id \"${view.id}\"; an id names one view.`);\n seen.add(view.id);\n }\n const plots = new Map<string, PlotSpec>();\n for (const plot of asList(spec.plot)) {\n const key = plotKey(plot);\n const known = plots.get(key);\n if (known)\n throw new Error(known.id === undefined && plot.id === undefined\n ? `Two plots of the table \"${key}\" have no id; give each plot an id.`\n : `A plot's id \"${key}\" is the dataRef of a plot without an id; give each plot an id.`);\n plots.set(key, plot);\n }\n}\n\nexport class AutkGrammar {\n private dataAdapter?: DataAdapter;\n private mapAdapter?: MapAdapter;\n private plotAdapter?: PlotAdapter;\n private computeAdapter?: ComputeAdapter;\n private grammarEngine?: IEngine;\n private _computeCache: ComputeCache = new Map();\n private _computeTypes: ComputeLayerTypes = new Map();\n private _data: Record<string, Promise<FeatureCollection>> = {};\n private _layers: DrawnLayers = [];\n private _maps: AutkMap[] = [];\n private _plotRegistry: PlotRegistry = new Map();\n private _fwdCleanups: Array<() => void> = [];\n private _plotLinks: PlotLinks = new Map();\n private _plotRows: PlotRows = new Map();\n private _exports: LayerExports = new Map();\n /** Each GeoJSON table a run loaded and each table a join wrote, which its plots read before the database. */\n private _geojsonCache: GeoJsonCache = new Map();\n\n readonly interactions = new GrammarEventEmitter();\n\n constructor(targets?: Targets) {\n this.dataAdapter = createDataAdapter(targets, this._geojsonCache);\n this.mapAdapter = createMapAdapter(targets, this._layers, this._computeCache, this._maps, this._computeTypes, this._exports);\n this.plotAdapter = createPlotAdapter(targets, this._layers, this._plotRegistry, this._plotLinks, this._geojsonCache, this._computeCache, this._plotRows, this._exports);\n this.computeAdapter = createComputeAdapter(this._computeCache, this._computeTypes);\n }\n\n /**\n * The coordinate reference system autk-db stores a workspace's tables in, unless the spec's `workspaces` sets\n * another for it.\n *\n * Input data is expected in EPSG:4326 (WGS84) by default and is transformed\n * to this CRS on load. Consumers that prepare data for injection (e.g. by\n * serialising a GeoDataFrame) can read this value and reproject accordingly\n * instead of hard-coding a CRS string.\n */\n get workspaceCrs(): string {\n return DEFAULT_WORKSPACE_COORDINATE_FORMAT;\n }\n\n get data(): Record<string, Promise<FeatureCollection>> {\n return this._data;\n }\n\n /**\n * The maps the last {@link run} drew, one per `map` entry of the spec, in order.\n *\n * Each map draws on demand: one frame once its layers are loaded, then one each\n * time it changes. Between frames a map canvas can read back empty, so to read a\n * map's pixels (for example with `canvas.toDataURL()`), call its `requestRender()`\n * and read in a `requestAnimationFrame` callback registered after that call.\n */\n get maps(): readonly AutkMap[] {\n return this._maps;\n }\n\n /**\n * Every layer the maps of the last {@link run} draw for a table, found by the table's name (a layer's `dataRef`):\n * for each, the map that draws it and the layer's id in that map, which is its `title`, else its `dataRef`. The\n * maps come in the spec's order, each map's layers bottom first. Empty when no map draws the table.\n *\n * @param dataRef The table's name.\n * @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\n * the spec's `map` list. Without it, every map.\n */\n mapLayers(dataRef: string, mapId?: MapId): GrammarMapLayer[] {\n return this._layersOf(dataRef, mapId).map(({ map, layerId }) => ({ map, layerId }));\n }\n\n /**\n * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):\n * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.\n * `undefined` when no map draws the table. When several layers draw it, the last one, which is the last map's;\n * {@link mapLayers} lists them all.\n *\n * @param dataRef The table's name.\n * @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\n * the spec's `map` list. Without it, every map.\n *\n * @example\n * const layer = grammar.mapLayer('buildings');\n * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });\n */\n mapLayer(dataRef: string, mapId?: MapId): GrammarMapLayer | undefined {\n return this.mapLayers(dataRef, mapId).pop();\n }\n\n /** The drawn layers of a table, on every map or on the one `mapId` names. */\n private _layersOf(dataRef: string, mapId?: MapId): DrawnLayer[] {\n return this._layers.filter((layer) => layer.dataRef === dataRef && isOnMap(layer, mapId));\n }\n\n /**\n * Releases what the last run created: every map (its layers' GPU buffers, its textures, its canvas context, the\n * controls it adds to the page and its event handlers) and the grammar's own registries, caches and event\n * forwarding. autk-map's maps share one GPU device, which stays for the maps of the next run. Call it before the\n * page or the container goes away; `run` calls it before it starts, so running a new spec on the same instance\n * does not leak the maps of the old one.\n */\n destroy(): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n for (const map of this._maps) map.destroy();\n this._maps.length = 0;\n this._layers.length = 0;\n this._plotRegistry.clear();\n this._plotLinks.clear();\n this._plotRows.clear();\n this._exports.clear();\n this._geojsonCache.clear();\n this._computeCache.clear();\n this._computeTypes.clear();\n this.grammarEngine = undefined;\n this._data = {};\n }\n\n async run(spec: UrbanSpec) {\n if(!this.dataAdapter)\n throw new Error('Database adapter not initialized. Please call the constructor first.');\n\n if(!this.mapAdapter)\n throw new Error('Map engine not initialized. Please call the constructor first.');\n\n if(!this.plotAdapter)\n throw new Error('Plot adapter not initialized. Please call the constructor first.');\n\n if(!this.computeAdapter)\n throw new Error('Compute adapter not initialized. Please call the constructor first.');\n\n checkViewIds(spec);\n\n this.destroy();\n\n this.grammarEngine = createEngine({\n spec,\n adapters: {\n db: this.dataAdapter,\n map: this.mapAdapter,\n plot: this.plotAdapter,\n compute: this.computeAdapter\n }\n });\n\n await this.grammarEngine.run();\n const db = this.grammarEngine.context as AutkDb | undefined;\n // Leave the database in the default workspace, whose tables `data` lists.\n if (db) await enterWorkspace(db);\n this._wireLinks(spec);\n this._rewireInteractions(spec);\n\n if (!db) {\n console.warn('Grammar engine produced no data context.');\n this._data = {};\n return;\n }\n\n const dataObj: Record<string, Promise<FeatureCollection>> = {};\n for (const table of db.getLayersMetadata()) {\n Object.defineProperty(dataObj, table.name, {\n get: () => {\n const computed = this._computeCache.get(table.name);\n return computed ? Promise.resolve(computed) : db.getLayer(table.name);\n },\n enumerable: true,\n configurable: true,\n });\n }\n // A table a compute pass wrote under its own name is not in the database.\n for (const name of this._computeCache.keys()) {\n if (name in dataObj) continue;\n Object.defineProperty(dataObj, name, {\n get: () => Promise.resolve(this._computeCache.get(name)!),\n enumerable: true,\n configurable: true,\n });\n }\n this._data = dataObj;\n }\n\n /**\n * Highlights features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}), or only\n * in the map `mapId` names. If a plot is linked to one of those layers, by a link or its `mapRef`, the plot\n * selection is updated too, to the same rows: the plot finds them by their feature ids, since it can draw the\n * table's rows in another order and draws the rows without a geometry, which a layer leaves out.\n *\n * @param dataRef The table's name.\n * @param featureIds The features to highlight: their positions among those the layer draws.\n * @param mapId The map to highlight on, by its {@link MapId}: a string names a map by its `id`, a number by its\n * index in the spec's `map` list. Without it, every map that draws the table.\n */\n highlightOnMap(dataRef: string, featureIds: number[], mapId?: MapId): void {\n const layers = this._layersOf(dataRef, mapId);\n for (const { map, layerId } of layers) map.setHighlightedIds(layerId, featureIds);\n this._selectInLinkedPlots(layers, featureIds);\n }\n\n /**\n * Clears highlighted features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}),\n * 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\n * selection is cleared too.\n *\n * @param dataRef The table's name.\n * @param mapId The map to clear, by its {@link MapId}: a string names a map by its `id`, a number by its index in\n * the spec's `map` list. Without it, every map that draws the table.\n */\n clearHighlightOnMap(dataRef: string, mapId?: MapId): void {\n const layers = this._layersOf(dataRef, mapId);\n for (const { map, layerId } of layers) map.clearHighlightedIds(layerId);\n this._selectInLinkedPlots(layers, []);\n }\n\n /**\n * Clears the selection on the plot `plotId` names: its `id`, else its `dataRef`.\n * If that plot is linked to map layers, by links or its `mapRef`, their highlights are cleared too: on every map,\n * or only on the map `mapId` names.\n *\n * @param plotId The plot: its `id`, else its `dataRef`.\n * @param mapId The map whose linked layers to clear, by its {@link MapId}: a string names a map by its `id`, a\n * number by its index in the spec's `map` list. Without it, every linked layer.\n */\n clearHighlightOnPlot(plotId: string, mapId?: MapId): void {\n this._plotRegistry.get(plotId)?.setSelection([]);\n for (const layer of this._plotLinks.get(plotId) ?? []) {\n if (isOnMap(layer, mapId)) layer.map.clearHighlightedIds(layer.layerId);\n }\n }\n\n /**\n * Applies a selection to the plot `plotId` names: its `id`, else its `dataRef`.\n * If that plot is linked to map layers, by links or its `mapRef`, their highlights are updated too, to the same rows\n * (see {@link highlightOnMap}): on every map, or only on the map `mapId` names.\n *\n * @param plotId The plot: its `id`, else its `dataRef`.\n * @param featureIds The features to select: their positions among those the plot draws.\n * @param mapId The map whose linked layers to highlight, by its {@link MapId}: a string names a map by its `id`, a\n * number by its index in the spec's `map` list. Without it, every linked layer.\n */\n setPlotSelection(plotId: string, featureIds: number[], mapId?: MapId): void {\n this._plotRegistry.get(plotId)?.setSelection(featureIds);\n // A layer is lit at its own positions of the selected rows.\n const rows = this._plotRows.get(plotId) ?? [];\n for (const layer of this._plotLinks.get(plotId) ?? []) {\n if (isOnMap(layer, mapId)) layer.map.setHighlightedIds(layer.layerId, translateIds(featureIds, rows, layer.rows));\n }\n }\n\n /**\n * Applies a selection made on `layers`, by their positions `featureIds`, to every plot linked to one of them, at the\n * plot's own positions of the selected rows.\n */\n private _selectInLinkedPlots(layers: DrawnLayer[], featureIds: number[]): void {\n for (const [plotId, linked] of this._plotLinks) {\n const selected = linked.filter((layer) => layers.includes(layer));\n if (selected.length === 0) continue;\n const rows = this._plotRows.get(plotId) ?? [];\n const ids = new Set(selected.flatMap((layer) => translateIds(featureIds, layer.rows, rows)));\n this._plotRegistry.get(plotId)?.setSelection([...ids]);\n }\n }\n\n /** Wires each entry of `links` between a plot and a layer of a map, both now drawn. */\n private _wireLinks(spec: UrbanSpec): void {\n const maps = asList(spec.map);\n const plots = asList(spec.plot);\n for (const link of spec.links ?? []) {\n const plotSpec = plots.find((p) => plotKey(p) === link.source);\n const plot = this._plotRegistry.get(link.source);\n if (!plotSpec || !plot)\n throw new Error(`Link source \"${link.source}\" is not the id (or the dataRef) of a plot of this specification.`);\n\n const mapIndex = maps.findIndex((m) => m.id === link.target);\n const map = this._maps[mapIndex];\n if (mapIndex < 0 || !map)\n throw new Error(`Link target \"${link.target}\" is not the id of a map of this specification.`);\n\n const layerRef = maps[mapIndex].layerRefs.find((l) =>\n link.layer !== undefined ? layerIdOf(l) === link.layer : l.dataRef === plotSpec.dataRef);\n if (!layerRef)\n throw new Error(link.layer !== undefined\n ? `Link from \"${link.source}\": map \"${link.target}\" has no layer \"${link.layer}\".`\n : `Link from \"${link.source}\": map \"${link.target}\" draws no layer of the table \"${plotSpec.dataRef}\"; name the layer.`);\n\n // The link names its map, so it is that map's layer that it links, though other maps draw the table too.\n const layer = this._layers.find((drawn) => drawn.mapIndex === mapIndex && drawn.layerId === layerIdOf(layerRef));\n if (!layer) continue;\n linkPlotToLayer(plot, this._plotRows.get(link.source) ?? [], (plotSpec.events ?? []) as unknown as PlotEvent[], layer);\n addPlotLink(this._plotLinks, link.source, layer);\n }\n }\n\n private _rewireInteractions(spec: UrbanSpec): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n\n // Wire every map to the grammar bus once, though several maps can draw one table, and name the map in each\n // pick. autk-map names the picked layer by its id in the map, which is its title, else its dataRef.\n const maps = asList(spec.map);\n this._maps.forEach((map, index) => {\n const mapId = mapIdOf(maps[index], index);\n const handler = ({ layerId, selection }: MapEventData) => {\n this.interactions.emit('map:picking', { mapId, layerId, selection });\n };\n map.events.on(MapEvent.PICKING, handler);\n this._fwdCleanups.push(() => map.events.off(MapEvent.PICKING, handler));\n });\n\n // Wire each plot → grammar bus (all four event types)\n for (const [plotId, plot] of this._plotRegistry) {\n for (const ev of [PlotEvent.CLICK, PlotEvent.BRUSH, PlotEvent.BRUSH_X, PlotEvent.BRUSH_Y] as const) {\n const handler = ({ selection }: PlotEventData) => {\n this.interactions.emit('plot:selection', {\n plotId,\n event: ev as GrammarPlotSelectionEvent['event'],\n selection,\n });\n };\n plot.events.on(ev, handler);\n this._fwdCleanups.push(() => plot.events.off(ev, handler));\n }\n }\n }\n}\n"],"names":["f","e","t","s","_","c","n","i","E","S","u","A","B","m","d","R","a","P","enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","featureIds","features","own","feature","given","index","id","rowKeys","seen","json","before","positionsByKey","positionsOf","keys","positions","key","position","list","translateIds","ids","from","to","translated","NO_GEOMETRY","loadableCollection","collection","changed","loadable","first","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","crsAdvice","coordinateFormat","workspaceLabel","propertyText","updateByFeatureId","table","rows","property","row","idColumn","column","database","context","AutkDb","extentOf","minX","minY","maxX","maxY","visitPositions","x","y","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","recache","candidate","isRenderableTable","workspaces","named","precisionGrid","err","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","readAsDegrees","extent","bbox","WORLD_EXTENT","bboxErr","hm","group","jn","updated","sql","update","data","isVectorTable","drop","exportKey","osmElements","exportOptions","exportOf","exports","load","mapIdOf","isOnMap","layer","mapId","addPlotLink","links","plotKey","linked","WGS84_A","WGS84_E","checkPointSize","pointSize","layerId","shown","worldMercatorLatitude","phi","next","planarUnitsPerMeter","crs","planarPointSize","layerIdOf","layerRef","checkLayerIds","HEX_COLOR","hexColor","ColorMap","styleRenderInfo","renderInfo","colorsByValue","bandValues","band","values","v","rasterScaleDomain","config","center","reverse","range","domain","reach","finite","centered","vectorScaleDomain","checkColorMapRange","low","high","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","setValueAtPath","result","current","rasterBand","getFnv","bands","b","cameraRefusal","camera","pitch","applyCamera","map","refused","view","distance","bearing","eye","up","drawnRowKeys","kept","components","component","handed","createMapAdapter","layers","computeCache","maps","computeTypes","loadLayers","tableToTypeMap","drawn","rawData","style","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","rasterTransfer","rasterScale","colormapConfig","ColorMapInterpolator","refusedCamera","canvas","AutkMap","error","at","grammarMarkToPlotType","mark","linkPlotToLayer","plot","events","MapEvent","picked","selection","event","tableRows","properties","createPlotAdapter","plotRegistry","plotLinks","plotRows","target","cached","geojson","AutkPlot","STORAGE_BUFFER_BINDING_SIZE","SCALAR_BYTES","BOX_BYTES","joinWgsl","body","isFromFeature","lookup","item","directives","block","out","cfg","computeLayerNames","findIterateSource","iterate","resolveDirective","iterateIndex","ff","resolveUniforms","uniforms","num","resolveUniformMatrices","matrices","resolved","cols","isFiniteValue","isBatched","batchedBytesPerFeature","maxBatchedFeatures","bindingSize","bytes","buildBatchedUniforms","sources","outUniforms","outArrays","required","p","limit","fallback","ring","xmin","ymin","xmax","ymax","coord","resolveComputeParams","params","packed","single","notBatched","entries","outputColumns","runCompute","run","columns","summed","compute","col","count","step","j","dst","src","inc","RENDER_LAYER_TYPES","layerTypeOf","types","createComputeAdapter","read","store","source","resultType","resolveRender","AutkComputeEngine","resolveGpgpu","engine","GrammarEventEmitter","listener","bucket","payload","l","asList","checkViewIds","plots","known","AutkGrammar","DEFAULT_WORKSPACE_COORDINATE_FORMAT","dataRef","cleanup","createEngine","dataObj","computed","plotId","selected","link","plotSpec","mapIndex","handler","ev","PlotEvent"],"mappings":";;;;;AAAA,SAASA,GAAEC,GAAG;AACZ,QAAM,EAAE,MAAMC,GAAG,UAAUC,EAAC,IAAKF;AACjC,MAAIG;AACJ,iBAAeC,IAAI;AACjB,QAAIC;AACJ,QAAIJ,EAAE,YAAY,UAAUC,EAAE,GAAG,sBAAsBG,IAAI,MAAMH,EAAE,GAAG,kBAAkBG,GAAGJ,EAAE,UAAU,IAAIA,EAAE;AAC3G,iBAAWK,KAAKL,EAAE;AAChB,QAAAI,IAAI,MAAMH,EAAE,GAAG,cAAcG,GAAGC,CAAC;AACrC,QAAIL,EAAE;AACJ,iBAAWK,KAAKL,EAAE;AAChB,QAAAI,IAAI,MAAMH,EAAE,QAAQ,eAAeG,GAAGC,CAAC;AAC3C,QAAIL,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,GAAG;AACrB,iBAASK,IAAI,GAAGA,IAAIL,EAAE,IAAI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