@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,2 +1,2 @@
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;
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}`}const A=new WeakMap;function L(o,a){A.set(o,a)}function x(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 N={type:"GeometryCollection",geometries:[]};function O(o){const a=o.features??[],n=x(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??N})),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 F(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 v(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:F(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 S(o){if(o!=null)return typeof o=="string"?o:JSON.stringify(o)}async function M(o,a,n,l){const u=new Map;for(const r of(await o.getLayer(a.name)).features){const s=S(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=S(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 j(o){if(o)return o;const a=new w.AutkDb;return await a.init(),a}function k(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 R(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 j(u),r=new Set;for(const{name:s,coordinateFormat:y,precisionGrid:m}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:m})}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 j(u),{workspace:r}=i;await $(e,r);let{type:s,workspace:y,...m}=i;switch(s){case"osm":return await e.loadOsm(v(m)),n(e,o),e;case"csv":return await e.loadCsv(m),n(e,o),e;case"json":return await e.loadJson(m),n(e,o),e;case"geojson":{const t=m;let c;t.geojsonFileUrl?c=await(await fetch(t.geojsonFileUrl)).json():c=t.geojsonObject,a&&c&&(a.set(g(r,t.outputTableName),c),L(c,t.coordinateFormat??"EPSG:4326"));const b=c?(()=>{const d={...t,geojsonObject:O(c)};return delete d.geojsonFileUrl,d})():t,p=/^EPSG:4326$/i.test(b.coordinateFormat??"EPSG:4326"),f=c&&p?k(c):void 0;if(f&&(f[1]<-90||f[3]>90))throw new Error(`GeoJSON layer "${b.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${f.join(", ")}]), so they cannot be EPSG:4326 degrees. ${T(b.coordinateFormat)}`);try{await e.loadGeojson(b)}catch(d){throw new Error(`Failed to load GeoJSON layer "${b.outputTableName}": ${d instanceof Error?d.message:String(d)}`)}try{const d=await e.getBoundingBoxFromLayer(b.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 "${b.outputTableName}" (bbox: [${d.minLon}, ${d.minLat}, ${d.maxLon}, ${d.maxLat}]). ${T(b.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(m),n(e,o),e;case"heatmap":{const t=m;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=m;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=m;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=m,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 b=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:b,idColumn:p}=await M(e,f,t.geojsonObject,p.slice(11)),b.features.length===0))return n(e,o),e;await e.updateTable({tableName:t.dataRef,data:b,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=m;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=R;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, 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,EAAK,GAAGA,CAAE,aAC/E,OAAAF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,EACrBA,CACX,CAAC,CACL,CCnBA,MAAMC,EAAwB,CAAE,KAAM,qBAAsB,WAAY,CAAA,CAAC,EAYzE,SAASC,EAAmBC,EAAkD,CAC1E,MAAMR,EAAWQ,EAAW,UAAY,CAAA,EAClCC,EAAMV,EAAWC,CAAQ,EAC/B,IAAIU,EAAU,GACd,MAAMC,EAAWX,EAAS,IAAI,CAACE,EAASE,IAChCF,GAAW,MAASA,EAAQ,IAAM,MAAQA,EAAQ,UAAY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apters/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","bboxErr","hm","group","jn","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AG,kBAAA,EAAoB,KAAMoE,GAAcA,EAAU,OAASuB,EAAO,OAAO,EAC1F,GAAIA,EAAO,WAAa,UAAYA,EAAO,eAAiB7C,GAAU,WAAW,aAAa,GAAKL,GAASoD,EAAAA,cAAcpD,CAAK,IAC1H,CAAE,KAAAmD,EAAM,SAAA9C,CAAA,EAAa,MAAMN,EAAkBxC,EAAIyC,EAAOkD,EAAO,cAAoC7C,EAAS,MAAM,EAAoB,CAAC,EAEnI8C,EAA2B,SAAS,SAAW,GAChD,OAAA5B,EAAMhE,EAAI8D,CAAO,EACV9D,EAGf,MAAMA,EAAG,YAAY,CACjB,UAAW2F,EAAO,QAClB,KAAAC,EACA,SAAUD,EAAO,SACjB,GAAI7C,IAAa,QAAa,CAAE,SAAAA,CAAA,CAAS,CAC5C,CACL,OAAS2B,EAAK,CACV,MAAMhD,EAAOgD,aAAe,MAAQA,EAAI,QAAU,OAAOA,CAAG,CAAC,CACjE,CACA,aAAMN,EAAQnE,EAAIC,EAAW0F,EAAO,OAAO,EAC3C3B,EAAMhE,EAAI8D,CAAO,EACV9D,CACX,CACA,IAAK,OAAQ,CACT,MAAM8F,EAAOlB,EAEb,GAAI,CAAC5E,EAAG,kBAAA,EAAoB,KAAMyC,GAAUA,EAAM,OAASqD,EAAK,OAAO,EACnE,MAAM,IAAI,MAAM,YAAYA,EAAK,OAAO,MAAMxD,EAAerC,CAAS,CAAC,+BAA+B,EAC1G,aAAMD,EAAG,YAAY8F,EAAK,OAAO,EACjC/B,GAAO,OAAO3D,EAASH,EAAW6F,EAAK,OAAO,CAAC,EAC/C9B,EAAMhE,EAAI8D,CAAO,EACV9D,CACX,CACA,QAGI,MAAM,IAAI,MAAM,6BAA6B,OAAO0E,CAAI,CAAC,IAAI,CAAA,CAEzE,CAAA,CAER"}
@@ -1,64 +1,68 @@
1
- import { DEFAULT_WORKSPACE_NAME as h, isVectorTable as L, AutkDb as S, isRenderableTable as N } from "@urban-toolkit/autk-db";
2
- async function j(o, a) {
3
- const n = a ?? h;
1
+ import { DEFAULT_WORKSPACE_NAME as h, isVectorTable as S, AutkDb as L, isRenderableTable as N } from "@urban-toolkit/autk-db";
2
+ async function E(o, r) {
3
+ const n = r ?? h;
4
4
  o.getCurrentWorkspace() !== n && await o.setWorkspace(n);
5
5
  }
6
- function w(o, a) {
7
- return o === void 0 || o === h ? a : `${o}/${a}`;
6
+ function w(o, r) {
7
+ return o === void 0 || o === h ? r : `${o}/${r}`;
8
8
  }
9
- function v(o) {
10
- const a = /* @__PURE__ */ new Set();
9
+ const v = /* @__PURE__ */ new WeakMap();
10
+ function F(o, r) {
11
+ v.set(o, r);
12
+ }
13
+ function O(o) {
14
+ const r = /* @__PURE__ */ new Set();
11
15
  for (const f of o)
12
- f?.id != null && a.add(JSON.stringify(f.id));
16
+ f?.id != null && r.add(JSON.stringify(f.id));
13
17
  const n = /* @__PURE__ */ new Set();
14
18
  return o.map((f, u) => {
15
19
  if (f?.id != null) return f.id;
16
20
  let i = `autk-feature-${u}`;
17
- for (; a.has(JSON.stringify(i)) || n.has(JSON.stringify(i)); ) i = `${i}-generated`;
21
+ for (; r.has(JSON.stringify(i)) || n.has(JSON.stringify(i)); ) i = `${i}-generated`;
18
22
  return n.add(JSON.stringify(i)), i;
19
23
  });
20
24
  }
21
- const O = { type: "GeometryCollection", geometries: [] };
22
- function A(o) {
23
- const a = o.features ?? [], n = v(a);
25
+ const A = { type: "GeometryCollection", geometries: [] };
26
+ function k(o) {
27
+ const r = o.features ?? [], n = O(r);
24
28
  let f = !1;
25
- const u = a.map((e, r) => e == null || e.id != null && e.geometry != null ? e : (f = !0, { ...e, id: n[r], geometry: e.geometry ?? O })), i = a.findIndex((e) => e?.geometry != null);
26
- return i > 0 && a[0] != null && a[0].geometry == null && ([u[0], u[i]] = [u[i], u[0]], f = !0), f ? { ...o, features: u } : o;
29
+ const u = r.map((e, a) => e == null || e.id != null && e.geometry != null ? e : (f = !0, { ...e, id: n[a], geometry: e.geometry ?? A })), i = r.findIndex((e) => e?.geometry != null);
30
+ return i > 0 && r[0] != null && r[0].geometry == null && ([u[0], u[i]] = [u[i], u[0]], f = !0), f ? { ...o, features: u } : o;
27
31
  }
28
- function F(o) {
29
- const { queryArea: a } = o;
30
- if (a.bbox === void 0) return { geocodeArea: a.geocodeArea, areas: a.areas };
32
+ function M(o) {
33
+ const { queryArea: r } = o;
34
+ if (r.bbox === void 0) return { geocodeArea: r.geocodeArea, areas: r.areas };
31
35
  const n = (s) => new Error(`OSM source "${o.outputTableName}": ${s}`);
32
- if (a.geocodeArea !== void 0 || a.areas !== void 0)
36
+ if (r.geocodeArea !== void 0 || r.areas !== void 0)
33
37
  throw n("queryArea takes either bbox or geocodeArea with areas, not both.");
34
- const f = a.bbox;
38
+ const f = r.bbox;
35
39
  if (!Array.isArray(f) || f.length !== 4 || !f.every((s) => typeof s == "number" && Number.isFinite(s)))
36
40
  throw n("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");
37
- const [u, i, e, r] = a.bbox;
41
+ const [u, i, e, a] = r.bbox;
38
42
  if (Math.abs(u) > 180 || Math.abs(e) > 180)
39
43
  throw n("queryArea.bbox west and east must be longitudes from -180 to 180.");
40
- if (Math.abs(i) > 90 || Math.abs(r) > 90)
44
+ if (Math.abs(i) > 90 || Math.abs(a) > 90)
41
45
  throw n("queryArea.bbox south and north must be latitudes from -90 to 90.");
42
46
  if (u >= e)
43
47
  throw n(`queryArea.bbox west (${u}) must be less than east (${e}); a box across the antimeridian is not supported.`);
44
- if (i >= r)
45
- throw n(`queryArea.bbox south (${i}) must be less than north (${r}).`);
46
- return { bbox: [u, i, e, r] };
48
+ if (i >= a)
49
+ throw n(`queryArea.bbox south (${i}) must be less than north (${a}).`);
50
+ return { bbox: [u, i, e, a] };
47
51
  }
48
- function k(o) {
49
- const { autoLoadLayers: a, ...n } = o;
52
+ function R(o) {
53
+ const { autoLoadLayers: r, ...n } = o;
50
54
  if (o.pbfFileUrl !== void 0 && (o.tagSets?.length ?? 0) > 0)
51
55
  throw new Error(`OSM source "${o.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);
52
56
  return {
53
57
  ...n,
54
- queryArea: F(o),
58
+ queryArea: M(o),
55
59
  autoLoadLayers: {
56
- layers: a?.layers ?? [],
57
- ...a?.coordinateFormat !== void 0 && { coordinateFormat: a.coordinateFormat }
60
+ layers: r?.layers ?? [],
61
+ ...r?.coordinateFormat !== void 0 && { coordinateFormat: r.coordinateFormat }
58
62
  }
59
63
  };
60
64
  }
61
- function E(o) {
65
+ function j(o) {
62
66
  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.`;
63
67
  }
64
68
  function $(o) {
@@ -68,85 +72,85 @@ function T(o) {
68
72
  if (o != null)
69
73
  return typeof o == "string" ? o : JSON.stringify(o);
70
74
  }
71
- async function M(o, a, n, f) {
75
+ async function C(o, r, n, f) {
72
76
  const u = /* @__PURE__ */ new Map();
73
- for (const r of (await o.getLayer(a.name)).features) {
74
- const s = T(r.properties?.[f]);
77
+ for (const a of (await o.getLayer(r.name)).features) {
78
+ const s = T(a.properties?.[f]);
75
79
  if (s !== void 0) {
76
- if (r.id === void 0 || r.id === null)
80
+ if (a.id === void 0 || a.id === null)
77
81
  throw new Error("its rows have no feature id to update them by.");
78
- u.set(s, [...u.get(s) ?? [], r.id]);
82
+ u.set(s, [...u.get(s) ?? [], a.id]);
79
83
  }
80
84
  }
81
- const i = n.features.flatMap((r) => {
82
- const s = T(r.properties?.[f]);
83
- return s === void 0 ? [] : (u.get(s) ?? []).map((y) => ({ ...r, id: y }));
84
- }), e = a.columns.some((r) => r.name === "geojson_id") ? "geojson_id" : "id";
85
+ const i = n.features.flatMap((a) => {
86
+ const s = T(a.properties?.[f]);
87
+ return s === void 0 ? [] : (u.get(s) ?? []).map((y) => ({ ...a, id: y }));
88
+ }), e = r.columns.some((a) => a.name === "geojson_id") ? "geojson_id" : "id";
85
89
  return { data: { ...n, features: i }, idColumn: e };
86
90
  }
87
91
  async function x(o) {
88
92
  if (o) return o;
89
- const a = new S();
90
- return await a.init(), a;
93
+ const r = new L();
94
+ return await r.init(), r;
91
95
  }
92
- function R(o) {
93
- let a = 1 / 0, n = 1 / 0, f = -1 / 0, u = -1 / 0;
94
- const i = (r) => {
95
- if (Array.isArray(r)) {
96
- if (typeof r[0] == "number") {
97
- const [s, y] = r;
98
- s < a && (a = s), s > f && (f = s), y < n && (n = y), y > u && (u = y);
96
+ function G(o) {
97
+ let r = 1 / 0, n = 1 / 0, f = -1 / 0, u = -1 / 0;
98
+ const i = (a) => {
99
+ if (Array.isArray(a)) {
100
+ if (typeof a[0] == "number") {
101
+ const [s, y] = a;
102
+ s < r && (r = s), s > f && (f = s), y < n && (n = y), y > u && (u = y);
99
103
  return;
100
104
  }
101
- for (const s of r) i(s);
105
+ for (const s of a) i(s);
102
106
  }
103
- }, e = (r) => {
104
- r && (r.type === "GeometryCollection" ? r.geometries.forEach(e) : i(r.coordinates));
107
+ }, e = (a) => {
108
+ a && (a.type === "GeometryCollection" ? a.geometries.forEach(e) : i(a.coordinates));
105
109
  };
106
- for (const r of o.features ?? []) e(r?.geometry);
107
- return a <= f ? [a, n, f, u] : void 0;
110
+ for (const a of o.features ?? []) e(a?.geometry);
111
+ return r <= f ? [r, n, f, u] : void 0;
108
112
  }
109
- function C(o, a) {
113
+ function B(o, r) {
110
114
  function n(u, i) {
111
115
  if (!i || !i.db)
112
116
  return;
113
117
  const e = document.getElementById(i.db);
114
118
  if (e) {
115
- const r = u.getTablesMetadata();
119
+ const a = u.getTablesMetadata();
116
120
  e.innerHTML += "<ul>";
117
- for (const s of r)
121
+ for (const s of a)
118
122
  e.innerHTML += `<li>${s.name}: (${s.source}, ${s.type}) </li>`;
119
- e.innerHTML += "</ul>", e.innerHTML += `<p>Number of tables: ${r.length}</p>`;
123
+ e.innerHTML += "</ul>", e.innerHTML += `<p>Number of tables: ${a.length}</p>`;
120
124
  }
121
125
  }
122
126
  async function f(u, i, e) {
123
- if (!a) return;
124
- const r = w(i, e), s = u.getTablesMetadata().find((y) => y.name === e);
125
- s && N(s) ? a.set(r, await u.getLayer(e)) : a.delete(r);
127
+ if (!r) return;
128
+ const a = w(i, e), s = u.getTablesMetadata().find((y) => y.name === e);
129
+ s && N(s) ? r.set(a, await u.getLayer(e)) : r.delete(a);
126
130
  }
127
131
  return {
128
132
  async resolveWorkspaces(u, i) {
129
- const e = await x(u), r = /* @__PURE__ */ new Set();
133
+ const e = await x(u), a = /* @__PURE__ */ new Set();
130
134
  for (const { name: s, coordinateFormat: y, precisionGrid: m } of i) {
131
135
  const t = s ?? h;
132
- if (r.has(t))
136
+ if (a.has(t))
133
137
  throw new Error(`workspaces sets ${$(s)} twice; give each workspace one entry.`);
134
- r.add(t);
138
+ a.add(t);
135
139
  try {
136
140
  await e.setWorkspace(t, { coordinateFormat: y, precisionGrid: m });
137
141
  } catch (c) {
138
142
  throw new Error(`workspaces, ${$(s)}: ${c instanceof Error ? c.message : String(c)}`);
139
143
  }
140
144
  }
141
- return await j(e), e;
145
+ return await E(e), e;
142
146
  },
143
147
  async resolveSource(u, i) {
144
- const e = await x(u), { workspace: r } = i;
145
- await j(e, r);
148
+ const e = await x(u), { workspace: a } = i;
149
+ await E(e, a);
146
150
  let { type: s, workspace: y, ...m } = i;
147
151
  switch (s) {
148
152
  case "osm":
149
- return await e.loadOsm(k(m)), n(e, o), e;
153
+ return await e.loadOsm(R(m)), n(e, o), e;
150
154
  case "csv":
151
155
  return await e.loadCsv(m), n(e, o), e;
152
156
  case "json":
@@ -154,14 +158,14 @@ function C(o, a) {
154
158
  case "geojson": {
155
159
  const t = m;
156
160
  let c;
157
- t.geojsonFileUrl ? c = await (await fetch(t.geojsonFileUrl)).json() : c = t.geojsonObject, a && c && a.set(w(r, t.outputTableName), c);
161
+ t.geojsonFileUrl ? c = await (await fetch(t.geojsonFileUrl)).json() : c = t.geojsonObject, r && c && (r.set(w(a, t.outputTableName), c), F(c, t.coordinateFormat ?? "EPSG:4326"));
158
162
  const b = c ? (() => {
159
- const d = { ...t, geojsonObject: A(c) };
163
+ const d = { ...t, geojsonObject: k(c) };
160
164
  return delete d.geojsonFileUrl, d;
161
- })() : t, p = /^EPSG:4326$/i.test(b.coordinateFormat ?? "EPSG:4326"), l = c && p ? R(c) : void 0;
165
+ })() : t, p = /^EPSG:4326$/i.test(b.coordinateFormat ?? "EPSG:4326"), l = c && p ? G(c) : void 0;
162
166
  if (l && (l[1] < -90 || l[3] > 90))
163
167
  throw new Error(
164
- `GeoJSON layer "${b.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${l.join(", ")}]), so they cannot be EPSG:4326 degrees. ${E(b.coordinateFormat)}`
168
+ `GeoJSON layer "${b.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${l.join(", ")}]), so they cannot be EPSG:4326 degrees. ${j(b.coordinateFormat)}`
165
169
  );
166
170
  try {
167
171
  await e.loadGeojson(b);
@@ -172,7 +176,7 @@ function C(o, a) {
172
176
  const d = await e.getBoundingBoxFromLayer(b.outputTableName), g = 25e6;
173
177
  if (!isFinite(d.minLon) || !isFinite(d.minLat) || !isFinite(d.maxLon) || !isFinite(d.maxLat) || Math.abs(d.minLon) > g || Math.abs(d.maxLon) > g || Math.abs(d.minLat) > g || Math.abs(d.maxLat) > g)
174
178
  throw new Error(
175
- `Geometry bounding box after transform is invalid for layer "${b.outputTableName}" (bbox: [${d.minLon}, ${d.minLat}, ${d.maxLon}, ${d.maxLat}]). ${E(b.coordinateFormat)} The workspace uses ${e.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`
179
+ `Geometry bounding box after transform is invalid for layer "${b.outputTableName}" (bbox: [${d.minLon}, ${d.minLat}, ${d.maxLon}, ${d.maxLat}]). ${j(b.coordinateFormat)} The workspace uses ${e.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`
176
180
  );
177
181
  } catch (d) {
178
182
  if (d instanceof Error && d.message.includes("bounding box after transform")) throw d;
@@ -200,9 +204,9 @@ function C(o, a) {
200
204
  tableJoinName: t.joinDataRef,
201
205
  ...t.near && { near: t.near },
202
206
  ...t.groupBy && { groupBy: t.groupBy }
203
- }), a) {
207
+ }), r) {
204
208
  const c = await e.getLayer(t.dataRef);
205
- a.set(w(r, t.dataRef), c);
209
+ r.set(w(a, t.dataRef), c);
206
210
  }
207
211
  return n(e, o), e;
208
212
  }
@@ -221,7 +225,7 @@ function C(o, a) {
221
225
  } catch (c) {
222
226
  throw new Error(`SQL source "${t.outputTableName}": ${c instanceof Error ? c.message : String(c)}`);
223
227
  }
224
- return a?.delete(w(r, t.outputTableName)), n(e, o), e;
228
+ return r?.delete(w(a, t.outputTableName)), n(e, o), e;
225
229
  }
226
230
  case "update": {
227
231
  const t = m, c = (l) => new Error(`Update of "${t.dataRef}": ${l}`);
@@ -232,7 +236,7 @@ function C(o, a) {
232
236
  let b = t.geojsonObject ?? t.jsonObject, p = t.idColumn;
233
237
  try {
234
238
  const l = e.getTablesMetadata().find((d) => d.name === t.dataRef);
235
- if (t.strategy === "update" && t.geojsonObject && p?.startsWith("properties.") && l && L(l) && ({ data: b, idColumn: p } = await M(e, l, t.geojsonObject, p.slice(11)), b.features.length === 0))
239
+ if (t.strategy === "update" && t.geojsonObject && p?.startsWith("properties.") && l && S(l) && ({ data: b, idColumn: p } = await C(e, l, t.geojsonObject, p.slice(11)), b.features.length === 0))
236
240
  return n(e, o), e;
237
241
  await e.updateTable({
238
242
  tableName: t.dataRef,
@@ -243,13 +247,13 @@ function C(o, a) {
243
247
  } catch (l) {
244
248
  throw c(l instanceof Error ? l.message : String(l));
245
249
  }
246
- return await f(e, r, t.dataRef), n(e, o), e;
250
+ return await f(e, a, t.dataRef), n(e, o), e;
247
251
  }
248
252
  case "drop": {
249
253
  const t = m;
250
254
  if (!e.getTablesMetadata().some((c) => c.name === t.dataRef))
251
- throw new Error(`Drop of "${t.dataRef}": ${$(r)} holds no table of that name.`);
252
- return await e.removeLayer(t.dataRef), a?.delete(w(r, t.dataRef)), n(e, o), e;
255
+ throw new Error(`Drop of "${t.dataRef}": ${$(a)} holds no table of that name.`);
256
+ return await e.removeLayer(t.dataRef), r?.delete(w(a, t.dataRef)), n(e, o), e;
253
257
  }
254
258
  default:
255
259
  throw new Error(`Unknown data source type "${String(s)}".`);
@@ -258,8 +262,8 @@ function C(o, a) {
258
262
  };
259
263
  }
260
264
  export {
261
- C as createDataAdapter,
262
- j as enterWorkspace,
265
+ B as createDataAdapter,
266
+ E as enterWorkspace,
263
267
  w as tableKey
264
268
  };
265
269
  //# sourceMappingURL=autk-grammar-data.js.map