@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,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@urban-toolkit/autk-db");async function w(o,t){const a=t??h.DEFAULT_WORKSPACE_NAME;o.getCurrentWorkspace()!==a&&await o.setWorkspace(a)}function g(o,t){return o===void 0||o===h.DEFAULT_WORKSPACE_NAME?t:`${o}/${t}`}function A(o){const t=new Set;for(const c of o)c?.id!=null&&t.add(JSON.stringify(c.id));const a=new Set;return o.map((c,s)=>{if(c?.id!=null)return c.id;let e=`autk-feature-${s}`;for(;t.has(JSON.stringify(e))||a.has(JSON.stringify(e));)e=`${e}-generated`;return a.add(JSON.stringify(e)),e})}const $={type:"GeometryCollection",geometries:[]};function E(o){const t=o.features??[],a=A(t);let c=!1;const s=t.map((u,r)=>u==null||u.id!=null&&u.geometry!=null?u:(c=!0,{...u,id:a[r],geometry:u.geometry??$})),e=t.findIndex(u=>u?.geometry!=null);return e>0&&t[0]!=null&&t[0].geometry==null&&([s[0],s[e]]=[s[e],s[0]],c=!0),c?{...o,features:s}:o}function L(o){const{queryArea:t}=o;if(t.bbox===void 0)return{geocodeArea:t.geocodeArea,areas:t.areas};const a=l=>new Error(`OSM source "${o.outputTableName}": ${l}`);if(t.geocodeArea!==void 0||t.areas!==void 0)throw a("queryArea takes either bbox or geocodeArea with areas, not both.");const c=t.bbox;if(!Array.isArray(c)||c.length!==4||!c.every(l=>typeof l=="number"&&Number.isFinite(l)))throw a("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[s,e,u,r]=t.bbox;if(Math.abs(s)>180||Math.abs(u)>180)throw a("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(e)>90||Math.abs(r)>90)throw a("queryArea.bbox south and north must be latitudes from -90 to 90.");if(s>=u)throw a(`queryArea.bbox west (${s}) must be less than east (${u}); a box across the antimeridian is not supported.`);if(e>=r)throw a(`queryArea.bbox south (${e}) must be less than north (${r}).`);return{bbox:[s,e,u,r]}}function N(o){const{autoLoadLayers:t,...a}=o;return{...a,queryArea:L(o),autoLoadLayers:{layers:t?.layers??[]}}}function p(o){return`${o?`coordinateFormat is set to "${o}"`:"no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`}function S(o){let t=1/0,a=1/0,c=-1/0,s=-1/0;const e=r=>{if(Array.isArray(r)){if(typeof r[0]=="number"){const[l,d]=r;l<t&&(t=l),l>c&&(c=l),d<a&&(a=d),d>s&&(s=d);return}for(const l of r)e(l)}},u=r=>{r&&(r.type==="GeometryCollection"?r.geometries.forEach(u):e(r.coordinates))};for(const r of o.features??[])u(r?.geometry);return t<=c?[t,a,c,s]:void 0}function T(o,t){function a(c,s){if(!s||!s.db)return;const e=document.getElementById(s.db);if(e){const u=c.getTablesMetadata();e.innerHTML+="<ul>";for(const r of u)e.innerHTML+=`<li>${r.name}: (${r.source}, ${r.type}) </li>`;e.innerHTML+="</ul>",e.innerHTML+=`<p>Number of tables: ${u.length}</p>`}}return{async resolveSource(c,s){let e=c;e||(e=new h.AutkDb,await e.init());const{workspace:u}=s;await w(e,u);let{type:r,workspace:l,...d}=s;switch(r){case"osm":return await e.loadOsm(N(d)),a(e,o),e;case"csv":return await e.loadCsv(d),a(e,o),e;case"json":return await e.loadJson(d),a(e,o),e;case"geojson":{const n=d;let f;n.geojsonFileUrl?f=await(await fetch(n.geojsonFileUrl)).json():f=n.geojsonObject,t&&f&&t.set(g(u,n.outputTableName),f);const b=f?(()=>{const i={...n,geojsonObject:E(f)};return delete i.geojsonFileUrl,i})():n,x=/^EPSG:4326$/i.test(b.coordinateFormat??"EPSG:4326"),m=f&&x?S(f):void 0;if(m&&(m[1]<-90||m[3]>90))throw new Error(`GeoJSON layer "${b.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${m.join(", ")}]), so they cannot be EPSG:4326 degrees. ${p(b.coordinateFormat)}`);try{await e.loadGeojson(b)}catch(i){throw new Error(`Failed to load GeoJSON layer "${b.outputTableName}": ${i instanceof Error?i.message:String(i)}`)}try{const i=await e.getBoundingBoxFromLayer(b.outputTableName),y=25e6;if(!isFinite(i.minLon)||!isFinite(i.minLat)||!isFinite(i.maxLon)||!isFinite(i.maxLat)||Math.abs(i.minLon)>y||Math.abs(i.maxLon)>y||Math.abs(i.minLat)>y||Math.abs(i.maxLat)>y)throw new Error(`Geometry bounding box after transform is invalid for layer "${b.outputTableName}" (bbox: [${i.minLon}, ${i.minLat}, ${i.maxLon}, ${i.maxLat}]). ${p(b.coordinateFormat)} The workspace uses ${h.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(i){if(i instanceof Error&&i.message.includes("bounding box after transform"))throw i}return a(e,o),e}case"geotiff":return await e.loadGeoTiff(d),a(e,o),e;case"heatmap":{const n=d;if(n.groupBy?.some(f=>f.aggregateFn==="collect"))throw new Error(`Heatmap "${n.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await e.buildHeatmap({tableJoinName:n.joinDataRef,near:n.near,outputTableName:n.outputTableName,grid:n.grid,...n.groupBy&&{groupBy:n.groupBy}}),a(e,o),e}case"join":{const n=d;if(await e.spatialQuery({tableRootName:n.dataRef,tableJoinName:n.joinDataRef,...n.near&&{near:n.near},...n.groupBy&&{groupBy:n.groupBy}}),t){const f=await e.getLayer(n.dataRef);t.set(g(u,n.dataRef),f)}return a(e,o),e}default:return}}}}exports.createDataAdapter=T;exports.enterWorkspace=w;exports.tableKey=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("@urban-toolkit/autk-db");async function $(o,a){const n=a??w.DEFAULT_WORKSPACE_NAME;o.getCurrentWorkspace()!==n&&await o.setWorkspace(n)}function g(o,a){return o===void 0||o===w.DEFAULT_WORKSPACE_NAME?a:`${o}/${a}`}function S(o){const a=new Set;for(const l of o)l?.id!=null&&a.add(JSON.stringify(l.id));const n=new Set;return o.map((l,u)=>{if(l?.id!=null)return l.id;let i=`autk-feature-${u}`;for(;a.has(JSON.stringify(i))||n.has(JSON.stringify(i));)i=`${i}-generated`;return n.add(JSON.stringify(i)),i})}const L={type:"GeometryCollection",geometries:[]};function x(o){const a=o.features??[],n=S(a);let l=!1;const u=a.map((e,r)=>e==null||e.id!=null&&e.geometry!=null?e:(l=!0,{...e,id:n[r],geometry:e.geometry??L})),i=a.findIndex(e=>e?.geometry!=null);return i>0&&a[0]!=null&&a[0].geometry==null&&([u[0],u[i]]=[u[i],u[0]],l=!0),l?{...o,features:u}:o}function N(o){const{queryArea:a}=o;if(a.bbox===void 0)return{geocodeArea:a.geocodeArea,areas:a.areas};const n=s=>new Error(`OSM source "${o.outputTableName}": ${s}`);if(a.geocodeArea!==void 0||a.areas!==void 0)throw n("queryArea takes either bbox or geocodeArea with areas, not both.");const l=a.bbox;if(!Array.isArray(l)||l.length!==4||!l.every(s=>typeof s=="number"&&Number.isFinite(s)))throw n("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[u,i,e,r]=a.bbox;if(Math.abs(u)>180||Math.abs(e)>180)throw n("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(i)>90||Math.abs(r)>90)throw n("queryArea.bbox south and north must be latitudes from -90 to 90.");if(u>=e)throw n(`queryArea.bbox west (${u}) must be less than east (${e}); a box across the antimeridian is not supported.`);if(i>=r)throw n(`queryArea.bbox south (${i}) must be less than north (${r}).`);return{bbox:[u,i,e,r]}}function O(o){const{autoLoadLayers:a,...n}=o;if(o.pbfFileUrl!==void 0&&(o.tagSets?.length??0)>0)throw new Error(`OSM source "${o.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);return{...n,queryArea:N(o),autoLoadLayers:{layers:a?.layers??[],...a?.coordinateFormat!==void 0&&{coordinateFormat:a.coordinateFormat}}}}function T(o){return`${o?`coordinateFormat is set to "${o}"`:"no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`}function E(o){return o===void 0||o===w.DEFAULT_WORKSPACE_NAME?"the default workspace":`the workspace "${o}"`}function j(o){if(o!=null)return typeof o=="string"?o:JSON.stringify(o)}async function v(o,a,n,l){const u=new Map;for(const r of(await o.getLayer(a.name)).features){const s=j(r.properties?.[l]);if(s!==void 0){if(r.id===void 0||r.id===null)throw new Error("its rows have no feature id to update them by.");u.set(s,[...u.get(s)??[],r.id])}}const i=n.features.flatMap(r=>{const s=j(r.properties?.[l]);return s===void 0?[]:(u.get(s)??[]).map(y=>({...r,id:y}))}),e=a.columns.some(r=>r.name==="geojson_id")?"geojson_id":"id";return{data:{...n,features:i},idColumn:e}}async function A(o){if(o)return o;const a=new w.AutkDb;return await a.init(),a}function F(o){let a=1/0,n=1/0,l=-1/0,u=-1/0;const i=r=>{if(Array.isArray(r)){if(typeof r[0]=="number"){const[s,y]=r;s<a&&(a=s),s>l&&(l=s),y<n&&(n=y),y>u&&(u=y);return}for(const s of r)i(s)}},e=r=>{r&&(r.type==="GeometryCollection"?r.geometries.forEach(e):i(r.coordinates))};for(const r of o.features??[])e(r?.geometry);return a<=l?[a,n,l,u]:void 0}function M(o,a){function n(u,i){if(!i||!i.db)return;const e=document.getElementById(i.db);if(e){const r=u.getTablesMetadata();e.innerHTML+="<ul>";for(const s of r)e.innerHTML+=`<li>${s.name}: (${s.source}, ${s.type}) </li>`;e.innerHTML+="</ul>",e.innerHTML+=`<p>Number of tables: ${r.length}</p>`}}async function l(u,i,e){if(!a)return;const r=g(i,e),s=u.getTablesMetadata().find(y=>y.name===e);s&&w.isRenderableTable(s)?a.set(r,await u.getLayer(e)):a.delete(r)}return{async resolveWorkspaces(u,i){const e=await A(u),r=new Set;for(const{name:s,coordinateFormat:y,precisionGrid:b}of i){const t=s??w.DEFAULT_WORKSPACE_NAME;if(r.has(t))throw new Error(`workspaces sets ${E(s)} twice; give each workspace one entry.`);r.add(t);try{await e.setWorkspace(t,{coordinateFormat:y,precisionGrid:b})}catch(c){throw new Error(`workspaces, ${E(s)}: ${c instanceof Error?c.message:String(c)}`)}}return await $(e),e},async resolveSource(u,i){const e=await A(u),{workspace:r}=i;await $(e,r);let{type:s,workspace:y,...b}=i;switch(s){case"osm":return await e.loadOsm(O(b)),n(e,o),e;case"csv":return await e.loadCsv(b),n(e,o),e;case"json":return await e.loadJson(b),n(e,o),e;case"geojson":{const t=b;let c;t.geojsonFileUrl?c=await(await fetch(t.geojsonFileUrl)).json():c=t.geojsonObject,a&&c&&a.set(g(r,t.outputTableName),c);const m=c?(()=>{const d={...t,geojsonObject:x(c)};return delete d.geojsonFileUrl,d})():t,p=/^EPSG:4326$/i.test(m.coordinateFormat??"EPSG:4326"),f=c&&p?F(c):void 0;if(f&&(f[1]<-90||f[3]>90))throw new Error(`GeoJSON layer "${m.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${f.join(", ")}]), so they cannot be EPSG:4326 degrees. ${T(m.coordinateFormat)}`);try{await e.loadGeojson(m)}catch(d){throw new Error(`Failed to load GeoJSON layer "${m.outputTableName}": ${d instanceof Error?d.message:String(d)}`)}try{const d=await e.getBoundingBoxFromLayer(m.outputTableName),h=25e6;if(!isFinite(d.minLon)||!isFinite(d.minLat)||!isFinite(d.maxLon)||!isFinite(d.maxLat)||Math.abs(d.minLon)>h||Math.abs(d.maxLon)>h||Math.abs(d.minLat)>h||Math.abs(d.maxLat)>h)throw new Error(`Geometry bounding box after transform is invalid for layer "${m.outputTableName}" (bbox: [${d.minLon}, ${d.minLat}, ${d.maxLon}, ${d.maxLat}]). ${T(m.coordinateFormat)} The workspace uses ${e.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`)}catch(d){if(d instanceof Error&&d.message.includes("bounding box after transform"))throw d}return n(e,o),e}case"geotiff":return await e.loadGeoTiff(b),n(e,o),e;case"heatmap":{const t=b;if(t.groupBy?.some(c=>c.aggregateFn==="collect"))throw new Error(`Heatmap "${t.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await e.buildHeatmap({tableJoinName:t.joinDataRef,near:t.near,outputTableName:t.outputTableName,grid:t.grid,...t.groupBy&&{groupBy:t.groupBy}}),n(e,o),e}case"join":{const t=b;if(await e.spatialQuery({tableRootName:t.dataRef,tableJoinName:t.joinDataRef,...t.near&&{near:t.near},...t.groupBy&&{groupBy:t.groupBy}}),a){const c=await e.getLayer(t.dataRef);a.set(g(r,t.dataRef),c)}return n(e,o),e}case"sql":{const t=b;try{await e.rawQuery({query:t.query,output:{type:"CREATE_TABLE",tableName:t.outputTableName,source:"user",...t.layerType!==void 0&&{tableType:t.layerType}}})}catch(c){throw new Error(`SQL source "${t.outputTableName}": ${c instanceof Error?c.message:String(c)}`)}return a?.delete(g(r,t.outputTableName)),n(e,o),e}case"update":{const t=b,c=f=>new Error(`Update of "${t.dataRef}": ${f}`);if(t.geojsonObject===void 0==(t.jsonObject===void 0))throw c("give its rows in geojsonObject or in jsonObject, one of the two.");if(t.strategy==="update"&&!t.idColumn)throw c("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");let m=t.geojsonObject??t.jsonObject,p=t.idColumn;try{const f=e.getTablesMetadata().find(d=>d.name===t.dataRef);if(t.strategy==="update"&&t.geojsonObject&&p?.startsWith("properties.")&&f&&w.isVectorTable(f)&&({data:m,idColumn:p}=await v(e,f,t.geojsonObject,p.slice(11)),m.features.length===0))return n(e,o),e;await e.updateTable({tableName:t.dataRef,data:m,strategy:t.strategy,...p!==void 0&&{idColumn:p}})}catch(f){throw c(f instanceof Error?f.message:String(f))}return await l(e,r,t.dataRef),n(e,o),e}case"drop":{const t=b;if(!e.getTablesMetadata().some(c=>c.name===t.dataRef))throw new Error(`Drop of "${t.dataRef}": ${E(r)} holds no table of that name.`);return await e.removeLayer(t.dataRef),a?.delete(g(r,t.dataRef)),n(e,o),e}default:throw new Error(`Unknown data source type "${String(s)}".`)}}}}exports.createDataAdapter=M;exports.enterWorkspace=$;exports.tableKey=g;
2
2
  //# sourceMappingURL=autk-grammar-data.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"autk-grammar-data.cjs","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, 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"],"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","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","s","readAsDegrees","extent","err","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","group","jn","updated"],"mappings":"0HAUA,eAAsBA,EAAeC,EAAYC,EAAmC,CAChF,MAAMC,EAAOD,GAAaE,EAAAA,uBACtBH,EAAG,wBAA0BE,GAAM,MAAMF,EAAG,aAAaE,CAAI,CACrE,CAOO,SAASE,EAASH,EAA+BC,EAAsB,CAC1E,OAAOD,IAAc,QAAaA,IAAcE,EAAAA,uBAAyBD,EAAO,GAAGD,CAAS,IAAIC,CAAI,EACxG,CCPO,SAASG,EAAWC,EAA2E,CAClG,MAAMC,MAAU,IAChB,UAAWC,KAAWF,EACdE,GAAS,IAAM,MAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC,EAE/D,MAAMC,MAAY,IAClB,OAAOH,EAAS,IAAI,CAACE,EAASE,IAAU,CACpC,GAAIF,GAAS,IAAM,KAAM,OAAOA,EAAQ,GACxC,IAAIG,EAAK,gBAAgBD,CAAK,GAC9B,KAAOH,EAAI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","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":"0HAUA,eAAsBA,EAAeC,EAAYC,EAAmC,CAChF,MAAMC,EAAOD,GAAaE,EAAAA,uBACtBH,EAAG,wBAA0BE,GAAM,MAAMF,EAAG,aAAaE,CAAI,CACrE,CAOO,SAASE,EAASH,EAA+BC,EAAsB,CAC1E,OAAOD,IAAc,QAAaA,IAAcE,EAAAA,uBAAyBD,EAAO,GAAGD,CAAS,IAAIC,CAAI,EACxG,CCPO,SAASG,EAAWC,EAA2E,CAClG,MAAMC,MAAU,IAChB,UAAWC,KAAWF,EACdE,GAAS,IAAM,MAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC,EAE/D,MAAMC,MAAY,IAClB,OAAOH,EAAS,IAAI,CAACE,EAASE,IAAU,CACpC,GAAIF,GAAS,IAAM,KAAM,OAAOA,EAAQ,GACxC,IAAIG,EAAK,gBAAgBD,CAAK,GAC9B,KAAOH,EAAI,IAAI,KAAK,UAAUI,CAAE,CAAC,GAAKF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,GAAGA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M,IAAI,MAAM,YAAYA,EAAK,OAAO,MAAMxD,EAAelC,CAAS,CAAC,+BAA+B,EAC1G,aAAMD,EAAG,YAAY2F,EAAK,OAAO,EACjC/B,GAAO,OAAOxD,EAASH,EAAW0F,EAAK,OAAO,CAAC,EAC/C9B,EAAM7D,EAAI2D,CAAO,EACV3D,CACX,CACA,QAGI,MAAM,IAAI,MAAM,6BAA6B,OAAOuE,CAAI,CAAC,IAAI,CAAA,CAEzE,CAAA,CAER"}
@@ -17,14 +17,15 @@ declare interface BoundingBox {
17
17
  /**
18
18
  * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the
19
19
  * autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and
20
- * returns the database.
20
+ * returns the database. Its `resolveWorkspaces(db, workspaces)` sets each workspace a spec's `workspaces` lists to its
21
+ * CRS and precision grid, before the first source loads, leaves the default workspace current and returns the database.
21
22
  *
22
23
  * A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the
23
24
  * `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables
24
- * after each load. `cache`, when given, receives each GeoJSON table and each table a join wrote, under
25
- * {@link tableKey}.
25
+ * after each load. `cache`, when given, receives each GeoJSON table and each table a join or an update wrote, under
26
+ * {@link tableKey}, and loses each table a `sql` source replaces or a `drop` source drops.
26
27
  */
27
- export declare function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter;
28
+ export declare function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): Required<DataAdapter>;
28
29
 
29
30
  /**
30
31
  * Loads a CSV table from exactly one of `csvFileUrl` or `csvObject`.
@@ -80,13 +81,30 @@ export declare interface CustomDataSourceSpec extends TableSourceBase {
80
81
 
81
82
  export declare interface DataAdapter {
82
83
  resolveSource(context: unknown, spec: DataSourceSpec): Promise<unknown>;
84
+ /**
85
+ * Sets up the workspaces a spec's `workspaces` lists, before its first source loads, and returns the context. An
86
+ * adapter without workspaces leaves it out, and the engine then skips `workspaces`.
87
+ */
88
+ resolveWorkspaces?(context: unknown, workspaces: WorkspaceSpec[]): Promise<unknown>;
83
89
  }
84
90
 
85
91
  /**
86
92
  * One entry of `data`. The `type` field selects which fields apply.
87
93
  * @discriminator type
88
94
  */
89
- export declare type DataSourceSpec = OsmDataSourceSpec | CsvDataSourceSpec | JsonDataSourceSpec | CustomDataSourceSpec | GeoTiffDataSourceSpec | HeatmapSourceSpec | JoinSourceSpec;
95
+ export declare type DataSourceSpec = OsmDataSourceSpec | CsvDataSourceSpec | JsonDataSourceSpec | CustomDataSourceSpec | GeoTiffDataSourceSpec | HeatmapSourceSpec | JoinSourceSpec | SqlSourceSpec | UpdateSourceSpec | DropSourceSpec;
96
+
97
+ /**
98
+ * Drops a table, so the sources, compute passes, maps and plots after it no longer find it, and `AutkGrammar.data` no
99
+ * longer lists it. Read by the Autark adapter only.
100
+ */
101
+ export declare interface DropSourceSpec {
102
+ type: 'drop';
103
+ /** Workspace of the table. */
104
+ workspace?: WorkspaceName;
105
+ /** The table to drop. */
106
+ dataRef: string;
107
+ }
90
108
 
91
109
  /**
92
110
  * Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.
@@ -153,6 +171,12 @@ export declare interface HeatmapSourceSpec extends TableSourceBase {
153
171
  column: string;
154
172
  /** How the rows combine into the cell's value: any aggregate but `collect`, which lists rows, while a cell holds one value. */
155
173
  aggregateFn?: HeatmapAggregateFunction;
174
+ /**
175
+ * Rescale the band's values from 0 to 1 across the grid's cells. It needs an autk-db with
176
+ * urban-toolkit/autark#132, which also adds `_norm` to the band's label; autk-db 4.1.1 builds the band from the
177
+ * values as they are.
178
+ */
179
+ normalize?: boolean;
156
180
  }>;
157
181
  /** Grid resolution. */
158
182
  grid: {
@@ -269,15 +293,36 @@ declare interface OsmBoundingBoxArea {
269
293
 
270
294
  /**
271
295
  * Loads OpenStreetMap data for a named area or a box, from Overpass or from a PBF extract.
296
+ * @if { "required": ["pbfFileUrl"] }
297
+ * @then { "not": { "required": ["tagSets"], "properties": { "tagSets": { "minItems": 1 } } } }
272
298
  */
273
299
  export declare interface OsmDataSourceSpec extends TableSourceBase {
274
300
  type: 'osm';
275
301
  /** URL of a local or remote `.osm.pbf` extract to read instead of querying Overpass. */
276
302
  pbfFileUrl?: string;
303
+ /**
304
+ * Features chosen by their tags, each set as a table of its own, `<outputTableName>_<name>_<type>`, cut to the
305
+ * area. A set that matches no feature in the area makes no table. Read from the Overpass API only: a source with
306
+ * `pbfFileUrl` cannot take them. Read by the Autark adapter only.
307
+ * @maxItems 8
308
+ */
309
+ tagSets?: OsmTagSet[];
310
+ /**
311
+ * Query the Overpass API again rather than read the answer the browser cached for this area, its layers and its tag
312
+ * sets, which autk-db keeps for 24 hours. A source with `pbfFileUrl` reads its file each time and ignores it. Read
313
+ * by the Autark adapter only.
314
+ */
315
+ forceRefresh?: boolean;
277
316
  /** Split the raw OSM table into one table per layer, named `<outputTableName>_<layer>`. */
278
317
  autoLoadLayers?: {
279
318
  /** Currently ignored by both adapters. */
280
319
  dropOsmTable?: boolean;
320
+ /**
321
+ * CRS of the OpenStreetMap data's coordinates, as an EPSG string. Defaults to `'EPSG:4326'`, the degrees the
322
+ * Overpass API and OpenStreetMap's extracts give. The layers and the tag sets are read in it. Read by the Autark
323
+ * adapter only.
324
+ */
325
+ coordinateFormat?: string;
281
326
  layers: Array<LayerType>;
282
327
  };
283
328
  /** Area to load: sub-areas inside a geocoded region (`geocodeArea` with `areas`), or a box (`bbox`), not both. */
@@ -296,6 +341,69 @@ declare interface OsmNamedArea {
296
341
  bbox?: undefined;
297
342
  }
298
343
 
344
+ /**
345
+ * An OpenStreetMap tag a tag set matches: the tag `key` with the value `value`, or with any value when `value` is
346
+ * omitted.
347
+ */
348
+ export declare type OsmTagFilter = {
349
+ /**
350
+ * The tag's key, such as `amenity` or `addr:street`: letters, digits, `_`, `:`, `.` and `-`, starting with a letter
351
+ * or a digit.
352
+ * @pattern ^[A-Za-z0-9][A-Za-z0-9_:.-]{0,254}$
353
+ */
354
+ key: string;
355
+ /**
356
+ * The tag's value, such as `cafe`. Without it, the key with any value matches.
357
+ * @minLength 1
358
+ * @maxLength 255
359
+ */
360
+ value?: string;
361
+ };
362
+
363
+ /**
364
+ * OpenStreetMap features chosen by their tags, as one table of one geometry type.
365
+ */
366
+ export declare type OsmTagSet = {
367
+ /**
368
+ * Names the set's table, `<outputTableName>_<name>_<type>`: a lowercase letter, then up to 31 lowercase letters,
369
+ * digits or `_`. No two sets of a source share a name.
370
+ * @pattern ^[a-z][a-z0-9_]{0,31}$
371
+ */
372
+ name: string;
373
+ /**
374
+ * The geometry the table holds: `points`, the tagged nodes; `polylines`, the open ways and the ways tagged as
375
+ * lines (`highway`, `barrier`, `railway`, `waterway`, or `area=no`); `polygons`, the other closed ways and the
376
+ * multipolygon relations.
377
+ */
378
+ type: 'points' | 'polylines' | 'polygons';
379
+ /**
380
+ * The tags a feature is chosen by: it is in the set when it has any one of them.
381
+ * @minItems 1
382
+ * @maxItems 64
383
+ */
384
+ tags: OsmTagFilter[];
385
+ };
386
+
387
+ /**
388
+ * Saves the rows of a SQL query over the workspace's tables as a new table. Read by the Autark adapter only.
389
+ */
390
+ export declare interface SqlSourceSpec extends TableSourceBase {
391
+ type: 'sql';
392
+ /**
393
+ * A `SELECT`, or a `WITH` query that ends in one, in DuckDB's SQL, over the tables of the source's workspace by their
394
+ * names. autk-db refuses any other statement, and any query in which `insert`, `update`, `delete`, `create`,
395
+ * `alter`, `drop`, `truncate` or `replace` appears as a word, even inside a string.
396
+ * @minLength 1
397
+ */
398
+ query: string;
399
+ /**
400
+ * How a map draws the new table, whose geometry must then be in a column named `geometry`, in the workspace's CRS,
401
+ * as the workspace's tables hold it. Without it, the table has no layer type: a plot draws its rows, while a map
402
+ * does not draw it and `AutkGrammar.data` does not list it.
403
+ */
404
+ layerType?: LayerType;
405
+ }
406
+
299
407
  /**
300
408
  * The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so
301
409
  * two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and
@@ -328,6 +436,43 @@ export declare type Targets = {
328
436
  plot?: string[] | string;
329
437
  };
330
438
 
439
+ /**
440
+ * Replaces or changes the rows of a table already loaded, with rows given inline: a FeatureCollection for a table with
441
+ * a geometry, an array of objects for a table without one. Read by the Autark adapter only.
442
+ * @if { "required": ["geojsonObject"] }
443
+ * @then { "not": { "required": ["jsonObject"] }, "if": { "required": ["strategy"], "properties": { "strategy": { "const": "update" } } }, "then": { "required": ["idColumn"] } }
444
+ * @else { "required": ["jsonObject"], "if": { "required": ["strategy"], "properties": { "strategy": { "const": "update" } } }, "then": { "required": ["idColumn"] } }
445
+ */
446
+ export declare interface UpdateSourceSpec {
447
+ type: 'update';
448
+ /** Workspace of the table. */
449
+ workspace?: WorkspaceName;
450
+ /** The table to change. */
451
+ dataRef: string;
452
+ /**
453
+ * `replace` swaps every row of the table for the given rows. `update` changes the rows whose `idColumn` value a
454
+ * given row has: in a table with a geometry, each takes the given row's geometry and properties, and no row is
455
+ * added; in a table without one, the given rows replace them, and those that match no row are added.
456
+ */
457
+ strategy: 'replace' | 'update';
458
+ /**
459
+ * With `update`, the column that matches a given row to the table's rows: a column such as `month`, or a feature
460
+ * property as `properties.<name>`, such as `properties.parcel_id`.
461
+ * @minLength 1
462
+ */
463
+ idColumn?: string;
464
+ /**
465
+ * The rows of a table with a geometry. autk-db stores their coordinates as they come, so they are in the
466
+ * workspace's CRS, as `AutkGrammar.data` gives a table's features.
467
+ */
468
+ geojsonObject?: InlineFeatureCollection;
469
+ /**
470
+ * The rows of a table without a geometry, such as a CSV or JSON table loaded without `geometryColumns`.
471
+ * @minItems 1
472
+ */
473
+ jsonObject?: Array<Record<string, unknown>>;
474
+ }
475
+
331
476
  /**
332
477
  * Geometry from one column holding WKT text such as `POLYGON((...))`. Read by the Autark adapter only.
333
478
  */
@@ -346,4 +491,26 @@ declare type WktGeometryColumns = {
346
491
  */
347
492
  export declare type WorkspaceName = string;
348
493
 
494
+ /**
495
+ * How a workspace stores its tables: the coordinate system they are kept in, and the grid their coordinates are rounded
496
+ * to. Read by the Autark adapter only.
497
+ */
498
+ export declare type WorkspaceSpec = {
499
+ /** The workspace, by the name sources, compute passes, maps and plots give as their `workspace`. Without it, the default workspace. */
500
+ name?: WorkspaceName;
501
+ /**
502
+ * CRS the workspace stores its tables in, as an EPSG string such as `'EPSG:3857'`. Each source is transformed to
503
+ * it as it loads, its maps draw in its units, and so are the lengths given in workspace units, such as a join's
504
+ * `near.distance`. autk-db's default is `'EPSG:3395'`, World Mercator, in meters.
505
+ * @minLength 1
506
+ */
507
+ coordinateFormat: string;
508
+ /**
509
+ * Grid every stored coordinate is rounded to, in the CRS's units. autk-db's default is `0.01`, a centimeter in World
510
+ * Mercator. A geometry the grid collapses is refused as it loads.
511
+ * @exclusiveMinimum 0
512
+ */
513
+ precisionGrid: number;
514
+ };
515
+
349
516
  export { }