@urban-toolkit/autk-grammar 5.1.0 → 5.2.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-data.js","sources":["../../src/workspace.ts","../../src/rows.ts","../../src/adapters/data.ts"],"sourcesContent":["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"],"names":["enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","featureIds","features","own","feature","given","index","id","NO_GEOMETRY","loadableCollection","collection","ids","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","key","idColumn","column","database","context","AutkDb","extentOf","minX","minY","maxX","maxY","visitPositions","x","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","recache","candidate","isRenderableTable","workspaces","named","precisionGrid","err","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","s","readAsDegrees","extent","bbox","WORLD_EXTENT","bboxErr","hm","group","jn","updated","sql","update","data","isVectorTable","drop"],"mappings":";AAUA,eAAsBA,EAAeC,GAAYC,GAAmC;AAChF,QAAMC,IAAOD,KAAaE;AAC1B,EAAIH,EAAG,0BAA0BE,KAAM,MAAMF,EAAG,aAAaE,CAAI;AACrE;AAOO,SAASE,EAASH,GAA+BC,GAAsB;AAC1E,SAAOD,MAAc,UAAaA,MAAcE,IAAyBD,IAAO,GAAGD,CAAS,IAAIC,CAAI;AACxG;ACPO,SAASG,EAAWC,GAA2E;AAClG,QAAMC,wBAAU,IAAA;AAChB,aAAWC,KAAWF;AAClB,IAAIE,GAAS,MAAM,QAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC;AAE/D,QAAMC,wBAAY,IAAA;AAClB,SAAOH,EAAS,IAAI,CAACE,GAASE,MAAU;AACpC,QAAI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ows.ts","../../src/adapters/data.ts"],"sourcesContent":["import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection } from 'geojson';\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\n/** The CRS of the coordinates of each collection a GeoJSON source put in a cache: the source's own. */\nconst sourceCrs = new WeakMap<FeatureCollection, string>();\n\n/**\n * Notes that a GeoJSON source put `collection` in a cache as it gave it, with its coordinates in `crs`, its\n * `coordinateFormat`, which autk-db transforms to its workspace's CRS as it loads the source.\n */\nexport function noteSourceCrs(collection: FeatureCollection, crs: string): void {\n sourceCrs.set(collection, crs);\n}\n\n/**\n * `collection` when a GeoJSON source put it in a cache with its coordinates in `workspaceCrs`, the CRS autk-db keeps its\n * workspace in, else `undefined`: a compute pass compares a `fromFeature` table's coordinates with its own table's,\n * which autk-db keeps in the workspace's CRS.\n */\nexport function inWorkspaceCrs(collection: FeatureCollection | undefined, workspaceCrs: string): FeatureCollection | undefined {\n const crs = collection && sourceCrs.get(collection);\n return crs !== undefined && crs.toUpperCase() === workspaceCrs.toUpperCase() ? collection : undefined;\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, noteSourceCrs, 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) {\n cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n // autk-db reads a GeoJSON source in EPSG:4326 unless it names another CRS.\n noteSourceCrs(geojsonData, geojsonSpec.coordinateFormat ?? 'EPSG:4326');\n }\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"],"names":["enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","sourceCrs","noteSourceCrs","collection","crs","featureIds","features","own","feature","given","index","id","NO_GEOMETRY","loadableCollection","ids","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","key","idColumn","column","database","context","AutkDb","extentOf","minX","minY","maxX","maxY","visitPositions","x","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","recache","candidate","isRenderableTable","workspaces","named","precisionGrid","err","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","s","readAsDegrees","extent","bbox","WORLD_EXTENT","bboxEr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AI,UAAU,OAAOA,CAAG,CAAC;AAAA,UACjE;AACA,uBAAMN,EAAQnE,GAAIC,GAAW0F,EAAO,OAAO,GAC3C3B,EAAMhE,GAAI8D,CAAO,GACV9D;AAAA,QACX;AAAA,QACA,KAAK,QAAQ;AACT,gBAAM8F,IAAOlB;AAEb,cAAI,CAAC5E,EAAG,kBAAA,EAAoB,KAAK,CAACyC,MAAUA,EAAM,SAASqD,EAAK,OAAO;AACnE,kBAAM,IAAI,MAAM,YAAYA,EAAK,OAAO,MAAMxD,EAAerC,CAAS,CAAC,+BAA+B;AAC1G,uBAAMD,EAAG,YAAY8F,EAAK,OAAO,GACjC/B,GAAO,OAAO3D,EAASH,GAAW6F,EAAK,OAAO,CAAC,GAC/C9B,EAAMhE,GAAI8D,CAAO,GACV9D;AAAA,QACX;AAAA,QACA;AAGI,gBAAM,IAAI,MAAM,6BAA6B,OAAO0E,CAAI,CAAC,IAAI;AAAA,MAAA;AAAA,IAEzE;AAAA,EAAA;AAER;"}
package/dist/index.d.ts CHANGED
@@ -164,6 +164,12 @@ export declare class AutkGrammar {
164
164
  private _selectInLinkedPlots;
165
165
  /** Wires each entry of `links` between a plot and a layer of a map, both now drawn. */
166
166
  private _wireLinks;
167
+ /**
168
+ * Applies each plot's `selection` once the plots and their links exist, as `setPlotSelection` does: the plot selects
169
+ * the rows, and the layers it is linked to, by `mapRef` or `links`, highlight them. autk-plot's `setSelection` emits
170
+ * no event, so no `plot:selection` reports it.
171
+ */
172
+ private _selectFromTheStart;
167
173
  private _rewireInteractions;
168
174
  }
169
175
 
@@ -224,6 +230,9 @@ export declare type CameraSpec = {
224
230
  bearing?: number;
225
231
  };
226
232
 
233
+ /** A categorical color scheme: a `scheme*` name, one color for each category. */
234
+ export declare type CategoricalColorMapInterpolator = ColorMapInterpolator.CAT_ACCENT | ColorMapInterpolator.CAT_DARK2 | ColorMapInterpolator.CAT_CATEGORY10 | ColorMapInterpolator.CAT_OBSERVABLE10 | ColorMapInterpolator.CAT_PAIRED | ColorMapInterpolator.CAT_PASTEL1 | ColorMapInterpolator.CAT_PASTEL2 | ColorMapInterpolator.CAT_SET1 | ColorMapInterpolator.CAT_SET2 | ColorMapInterpolator.CAT_SET3 | ColorMapInterpolator.CAT_TABLEAU10;
235
+
227
236
  /** Color scheme for a colored map layer: `scheme*` names are categorical, `interpolate*` names are sequential or diverging. */
228
237
  export declare enum ColorMapInterpolator {
229
238
  CAT_ACCENT = "schemeAccent",
@@ -310,6 +319,9 @@ export declare type ComputeRunner = (params: GpgpuPipelineParams) => Promise<Fea
310
319
  /** One entry of `compute`. A pass with `type: 'render'` is a {@link RenderComputeSpec}, any other a {@link GpgpuComputeSpec}. */
311
320
  export declare type ComputeSpec = GpgpuComputeSpec | RenderComputeSpec;
312
321
 
322
+ /** A sequential or diverging color scheme: an `interpolate*` name, a color for each number of a scale. */
323
+ export declare type ContinuousColorMapInterpolator = ColorMapInterpolator.SEQ_REDS | ColorMapInterpolator.SEQ_BLUES | ColorMapInterpolator.SEQ_GREENS | ColorMapInterpolator.SEQ_GREYS | ColorMapInterpolator.SEQ_ORANGES | ColorMapInterpolator.SEQ_PURPLES | ColorMapInterpolator.SEQ_TURBO | ColorMapInterpolator.SEQ_VIRIDIS | ColorMapInterpolator.SEQ_INFERNO | ColorMapInterpolator.SEQ_MAGMA | ColorMapInterpolator.SEQ_PLASMA | ColorMapInterpolator.SEQ_CIVIDIS | ColorMapInterpolator.SEQ_WARM | ColorMapInterpolator.SEQ_COOL | ColorMapInterpolator.SEQ_CUBEHELIX_DEFAULT | ColorMapInterpolator.SEQ_BU_GN | ColorMapInterpolator.SEQ_BU_PU | ColorMapInterpolator.SEQ_GN_BU | ColorMapInterpolator.SEQ_OR_RD | ColorMapInterpolator.SEQ_PU_BU_GN | ColorMapInterpolator.SEQ_PU_BU | ColorMapInterpolator.SEQ_PU_RD | ColorMapInterpolator.SEQ_RD_PU | ColorMapInterpolator.SEQ_YL_GN_BU | ColorMapInterpolator.SEQ_YL_GN | ColorMapInterpolator.SEQ_YL_OR_BR | ColorMapInterpolator.SEQ_YL_OR_RD | ColorMapInterpolator.DIV_BR_BG | ColorMapInterpolator.DIV_PR_GN | ColorMapInterpolator.DIV_PI_YG | ColorMapInterpolator.DIV_PU_OR | ColorMapInterpolator.DIV_RED_BLUE | ColorMapInterpolator.DIV_RED_GREY | ColorMapInterpolator.DIV_RED_YELLOW_BLUE | ColorMapInterpolator.DIV_RED_YELLOW_GREEN | ColorMapInterpolator.DIV_SPECTRAL;
324
+
313
325
  /**
314
326
  * The compute adapter `AutkGrammar` runs. Its `resolveCompute(db, pass)` runs one entry of a spec's `compute`, a
315
327
  * GPGPU pass or a render pass, on autk-compute, in the pass's workspace, which it leaves current. It does nothing
@@ -318,9 +330,11 @@ export declare type ComputeSpec = GpgpuComputeSpec | RenderComputeSpec;
318
330
  * A host calls it to run compute passes exactly as the grammar does. The passes need WebGPU, and their results are
319
331
  * kept only in the caches: `cache` receives each pass's result under {@link tableKey} of its `outputTableName`, or of
320
332
  * the table it computed over, and a later pass reads a table from it first. `types` receives the layer type of each
321
- * table a pass wrote under its own `outputTableName`, which a map needs to draw it.
333
+ * table a pass wrote under its own `outputTableName`, which a map needs to draw it. `sources` is the cache the data
334
+ * adapter fills: a pass reads a `fromFeature` table from it next, as its plots read theirs, when a GeoJSON source put
335
+ * the table there with its coordinates in the workspace's CRS.
322
336
  */
323
- export declare function createComputeAdapter(cache?: ComputeCache, types?: ComputeLayerTypes): ComputeAdapter;
337
+ export declare function createComputeAdapter(cache?: ComputeCache, types?: ComputeLayerTypes, sources?: GeoJsonCache): ComputeAdapter;
324
338
 
325
339
  /**
326
340
  * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the
@@ -453,7 +467,11 @@ export declare function findIterateSource(block: GpgpuComputeSpec): {
453
467
  */
454
468
  export declare type FromFeatureDirective = {
455
469
  fromFeature: {
456
- /** Table to read from. */
470
+ /**
471
+ * Table to read from. The Autark adapter reads it as an earlier compute pass wrote it; else, when a GeoJSON source
472
+ * loaded it with its coordinates in its workspace's CRS, as the source gave its features, each building part with
473
+ * its own outline; else as autk-db keeps it, a buildings table's geometry inside a GeometryCollection.
474
+ */
457
475
  layer: string;
458
476
  /** Dot path from the feature root, for example `properties.height` or `geometry.coordinates.0`. */
459
477
  path: string;
@@ -1101,7 +1119,79 @@ export declare interface PlotBase {
1101
1119
  * @minItems 1
1102
1120
  */
1103
1121
  axis: string[];
1122
+ /**
1123
+ * Column whose values color the marks: a scatter plot's points, a bar chart's bars, and the lines of parallel
1124
+ * coordinates, which a click on an axis's title colors by that axis instead. When every value is a number, or a
1125
+ * string that reads as one, the marks take `colorMapInterpolator`'s scheme; otherwise the values are categories,
1126
+ * and take `categoricalColorMapInterpolator`'s. A heat matrix colors its cells by their values, which `@transform`
1127
+ * names. Line charts and tables color no mark by value.
1128
+ */
1104
1129
  color?: string;
1130
+ /**
1131
+ * Color scheme of marks colored by numbers: a sequential or diverging `interpolate*` scheme, `interpolateReds` by
1132
+ * default. The scale's low end takes the scheme's first color and its high end its last: the lowest and highest
1133
+ * values, unless `colorMapRange` or `normalization` sets them. A categorical `scheme*` name is refused, since
1134
+ * categories take `categoricalColorMapInterpolator`. Read by the Autark adapter; the deck.gl adapter ignores it.
1135
+ */
1136
+ colorMapInterpolator?: ContinuousColorMapInterpolator;
1137
+ /**
1138
+ * Color scheme of marks colored by categories: a categorical `scheme*` scheme, `schemeObservable10` by default.
1139
+ * The categories take the scheme's colors in the order they first appear, or in `colorMapDomain`'s order, and those
1140
+ * past the scheme's last color take that one. A sequential or diverging `interpolate*` name is refused. Read by the
1141
+ * Autark adapter; the deck.gl adapter ignores it.
1142
+ */
1143
+ categoricalColorMapInterpolator?: CategoricalColorMapInterpolator;
1144
+ /**
1145
+ * How the ends of the color scale of numbers are found: `minMax`, the default, takes the lowest and highest
1146
+ * values; `percentile` takes the values at the `lowerPercentile` and `upperPercentile` percentiles, 2 and 98 when
1147
+ * it gives neither, else 0 and 100 for the one it leaves out. Categories ignore it. A map layer's `normalization`
1148
+ * reads the same way. Read by the Autark adapter; the deck.gl adapter ignores it.
1149
+ */
1150
+ normalization?: MapLayerSpec['normalization'];
1151
+ /**
1152
+ * Ends of the color scale of numbers, as `[low, high]` with low less than high. The plot is colored over this range
1153
+ * instead of its lowest and highest values, so plots and map layers that set the same range color the same value
1154
+ * alike. Values that are categories ignore it, as a layer with a categorical scheme does, and it cannot be set with
1155
+ * `colorMapDomain`. Read by the Autark adapter; the deck.gl adapter ignores it.
1156
+ * @uniqueItems true
1157
+ */
1158
+ colorMapRange?: [low: number, high: number];
1159
+ /**
1160
+ * Categories the plot is colored over, in order: the first takes the categorical scheme's first color, and so on.
1161
+ * The values are read as categories, numbers too, and a mark whose value is not among them is drawn in the mark
1162
+ * color. It cannot be set with `colorMapRange`. Read by the Autark adapter; the deck.gl adapter ignores it.
1163
+ */
1164
+ colorMapDomain?: string[];
1165
+ /**
1166
+ * Color of the marks that are neither colored by value nor selected, as `#rrggbb`: `#bfbfbf` by default. autk-plot
1167
+ * keeps one mark color for the page, so every plot it draws there takes it: a run refuses two plots that set
1168
+ * different ones, and a run whose plots set none gives back autk-plot's. Read by the Autark adapter; the deck.gl
1169
+ * adapter ignores it.
1170
+ */
1171
+ markColor?: HexColor;
1172
+ /**
1173
+ * Color of the selected marks, and of a table's selected rows, as `#rrggbb`: `#5dade2` by default. autk-plot keeps
1174
+ * one highlight color for the page, so every plot it draws there takes it: a run refuses two plots that set
1175
+ * different ones, and a run whose plots set none gives back autk-plot's. Read by the Autark adapter; the deck.gl
1176
+ * adapter ignores it.
1177
+ */
1178
+ highlightColor?: HexColor;
1179
+ /**
1180
+ * d3-format specifiers of the tick labels of the plot's axes, `[x, y]`: a scatter plot's x and y axes; a bar or line
1181
+ * chart's x axis, for labels that read as numbers, and its y axis; and every axis of numbers of parallel coordinates,
1182
+ * which read only the first. Heat matrices and tables ignore it. Without it, `['~s', '~s']`. Read by the Autark
1183
+ * adapter; the deck.gl adapter ignores it.
1184
+ */
1185
+ tickFormats?: [x: TickFormat, y: TickFormat];
1186
+ /**
1187
+ * Titles of the plot's axes, in the order of `axis`, in place of the column names: the x and y axes' titles of a
1188
+ * scatter plot, a bar chart, a line chart and a heat matrix, each axis's title of parallel coordinates, and a table's
1189
+ * column headers. An axis without a title keeps its column's name, and an axis that holds a transform's output,
1190
+ * `@transform`, is titled `value`. A run refuses more titles than `axis` has columns, and two titles alike, since a
1191
+ * table finds the column to sort by its header. Read by the Autark adapter; the deck.gl adapter ignores it.
1192
+ * @uniqueItems true
1193
+ */
1194
+ axisLabels?: string[];
1105
1195
  title?: string;
1106
1196
  /** Interactions the plot emits. */
1107
1197
  events?: PlotEvent[];
@@ -1122,6 +1212,14 @@ export declare interface PlotBase {
1122
1212
  };
1123
1213
  /** `dataRef` of the map layer this plot links its selection to. A shorthand for a link in `links`. */
1124
1214
  mapRef?: string;
1215
+ /**
1216
+ * Rows selected when the plot is drawn, by their positions among the rows it draws, as `plot:selection` events and
1217
+ * `setPlotSelection` name them. The plot draws them in its highlight color (a binned plot, the bins that hold them),
1218
+ * and the map layers it is linked to, by `mapRef` or `links`, highlight the same rows, as after `setPlotSelection`.
1219
+ * No `plot:selection` event reports it. A run refuses a position past the plot's last row. Read by the Autark
1220
+ * adapter; the deck.gl adapter ignores it.
1221
+ */
1222
+ selection?: RowPosition[];
1125
1223
  /**
1126
1224
  * Plot an OpenStreetMap layer table as one row per OSM element it was built from, each with the element's tags,
1127
1225
  * `osm_type` and `osm_id` (and `building_id` in a buildings table), rather than one row per table row. A table that
@@ -1142,6 +1240,8 @@ export declare type PlotRegistry = Map<string, AutkPlot>;
1142
1240
  /**
1143
1241
  * A plot view. The `mark` field selects which transforms apply.
1144
1242
  * @discriminator mark
1243
+ * @if { "required": ["colorMapRange"] }
1244
+ * @then { "not": { "required": ["colorMapDomain"] } }
1145
1245
  */
1146
1246
  export declare type PlotSpec = ScatterPlotSpec | BarPlotSpec | LinePlotSpec | ParallelCoordinatesPlotSpec | TablePlotSpec | HeatmatrixPlotSpec;
1147
1247
 
@@ -1314,6 +1414,13 @@ export declare function resolveUniformMatrices(matrices: Record<string, MatrixEn
1314
1414
  */
1315
1415
  export declare function resolveUniforms(uniforms: Record<string, UniformEntry> | undefined, layers: ComputeLayers, iterateIndex?: number): Record<string, number> | undefined;
1316
1416
 
1417
+ /**
1418
+ * A row of a table as a view draws it: its position among the rows the view draws, from 0.
1419
+ * @minimum 0
1420
+ * @multipleOf 1
1421
+ */
1422
+ declare type RowPosition = number;
1423
+
1317
1424
  /**
1318
1425
  * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is
1319
1426
  * one dispatch per feature of the iterated layer, and each output column holds the sum over them.
@@ -1406,6 +1513,13 @@ export declare type Targets = {
1406
1513
  plot?: string[] | string;
1407
1514
  };
1408
1515
 
1516
+ /**
1517
+ * A d3-format specifier, such as `~s`, `,d`, `.2f` or `.0%`: d3-format's
1518
+ * `[[fill]align][sign][symbol][0][width][,][.precision][~][type]`.
1519
+ * @pattern ^(?:.?[<>=^])?[-+( ]?[$#]?0?\d*,?(?:\.\d+)?~?[a-zA-Z%]?$
1520
+ */
1521
+ declare type TickFormat = string;
1522
+
1409
1523
  declare type UniformEntry = number | FromFeatureDirective;
1410
1524
 
1411
1525
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urban-toolkit/autk-grammar",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
4
4
  "description": "A declarative grammar for urban visual analytics, built on Autark",
5
5
  "license": "MIT",
6
6
  "author": "Gustavo Moreira",