@urban-toolkit/autk-grammar 5.0.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,3 +1,3 @@
1
- (function(h,E){typeof exports=="object"&&typeof module<"u"?E(exports,require("@urban-toolkit/autk-db"),require("@urban-toolkit/autk-map"),require("@urban-toolkit/autk-plot"),require("@urban-toolkit/autk-core"),require("@urban-toolkit/autk-compute")):typeof define=="function"&&define.amd?define(["exports","@urban-toolkit/autk-db","@urban-toolkit/autk-map","@urban-toolkit/autk-plot","@urban-toolkit/autk-core","@urban-toolkit/autk-compute"],E):(h=typeof globalThis<"u"?globalThis:h||self,E(h["autk-grammar"]={},h.autkDb,h.autkMap,h.autkPlot,h.autkCore,h.autkCompute))})(this,(function(h,E,F,N,A,J){"use strict";function K(t){const{spec:e,adapters:r}=t;let o;async function n(){let i;if(e.data)for(const l of e.data)i=await r.db.resolveSource(i,l);if(e.compute)for(const l of e.compute)i=await r.compute.resolveCompute(i,l);if(e.map)if(Array.isArray(e.map))for(let l=0;l<e.map.length;l++){let u=e.map[l];await r.map.resolveMap(i,u,l)}else await r.map.resolveMap(i,e.map);if(e.plot)if(Array.isArray(e.plot))for(let l=0;l<e.plot.length;l++)await r.plot.resolvePlot(i,e.plot[l],l);else await r.plot.resolvePlot(i,e.plot);o=i}function a(i){return console.log("Spec to update",i),new Promise(l=>{l()})}function s(){console.log("Function not implemented yet")}return{run:n,updatedSpec:a,destroy:s,get context(){return o}}}function X(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function $t(t){const e=t.layout??{},r=e.type??"vertical";if(r!=="vertical"&&r!=="horizontal"&&r!=="grid")throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(r)}.`);const o=e.gap??0;if(typeof o!="number"||!Number.isFinite(o)||o<0)throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(o)}.`);const n=e.columns??2;if(!Number.isInteger(n)||n<1)throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);const a=[...X(t.map).map((l,u)=>({kind:"map",index:u,id:l.id,key:l.id??u})),...X(t.plot).map((l,u)=>({kind:"plot",index:u,id:l.id,key:l.id??l.dataRef}))],s=r==="vertical"?1:r==="horizontal"?Math.max(a.length,1):n,i=a.map(({kind:l,index:u,id:c,key:f},p)=>({kind:l,index:u,...c!==void 0&&{id:c},key:f,row:Math.floor(p/s),column:p%s}));return{type:r,rows:Math.ceil(a.length/s),columns:s,gap:o,panes:i}}var z=(t=>(t.CAT_ACCENT="schemeAccent",t.CAT_DARK2="schemeDark2",t.CAT_CATEGORY10="schemeCategory10",t.CAT_OBSERVABLE10="schemeObservable10",t.CAT_PAIRED="schemePaired",t.CAT_PASTEL1="schemePastel1",t.CAT_PASTEL2="schemePastel2",t.CAT_SET1="schemeSet1",t.CAT_SET2="schemeSet2",t.CAT_SET3="schemeSet3",t.CAT_TABLEAU10="schemeTableau10",t.SEQ_REDS="interpolateReds",t.SEQ_BLUES="interpolateBlues",t.SEQ_GREENS="interpolateGreens",t.SEQ_GREYS="interpolateGreys",t.SEQ_ORANGES="interpolateOranges",t.SEQ_PURPLES="interpolatePurples",t.SEQ_TURBO="interpolateTurbo",t.SEQ_VIRIDIS="interpolateViridis",t.SEQ_INFERNO="interpolateInferno",t.SEQ_MAGMA="interpolateMagma",t.SEQ_PLASMA="interpolatePlasma",t.SEQ_CIVIDIS="interpolateCividis",t.SEQ_WARM="interpolateWarm",t.SEQ_COOL="interpolateCool",t.SEQ_CUBEHELIX_DEFAULT="interpolateCubehelixDefault",t.SEQ_BU_GN="interpolateBuGn",t.SEQ_BU_PU="interpolateBuPu",t.SEQ_GN_BU="interpolateGnBu",t.SEQ_OR_RD="interpolateOrRd",t.SEQ_PU_BU_GN="interpolatePuBuGn",t.SEQ_PU_BU="interpolatePuBu",t.SEQ_PU_RD="interpolatePuRd",t.SEQ_RD_PU="interpolateRdPu",t.SEQ_YL_GN_BU="interpolateYlGnBu",t.SEQ_YL_GN="interpolateYlGn",t.SEQ_YL_OR_BR="interpolateYlOrBr",t.SEQ_YL_OR_RD="interpolateYlOrRd",t.DIV_BR_BG="interpolateBrBG",t.DIV_PR_GN="interpolatePRGn",t.DIV_PI_YG="interpolatePiYG",t.DIV_PU_OR="interpolatePuOr",t.DIV_RED_BLUE="interpolateRdBu",t.DIV_RED_GREY="interpolateRdGy",t.DIV_RED_YELLOW_BLUE="interpolateRdYlBu",t.DIV_RED_YELLOW_GREEN="interpolateRdYlGn",t.DIV_SPECTRAL="interpolateSpectral",t))(z||{}),j=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(j||{});async function P(t,e){const r=e??E.DEFAULT_WORKSPACE_NAME;t.getCurrentWorkspace()!==r&&await t.setWorkspace(r)}function M(t,e){return t===void 0||t===E.DEFAULT_WORKSPACE_NAME?e:`${t}/${e}`}function Z(t){const e=new Set;for(const o of t)o?.id!=null&&e.add(JSON.stringify(o.id));const r=new Set;return t.map((o,n)=>{if(o?.id!=null)return o.id;let a=`autk-feature-${n}`;for(;e.has(JSON.stringify(a))||r.has(JSON.stringify(a));)a=`${a}-generated`;return r.add(JSON.stringify(a)),a})}function tt(t){const e=new Map;return Z(t).map(r=>{const o=JSON.stringify(r),n=e.get(o)??0;return e.set(o,n+1),n===0?o:`${o} ${n}`})}const et=new WeakMap;function Ft(t){let e=et.get(t);return e||(e=new Map,t.forEach((r,o)=>{const n=e.get(r);n?n.push(o):e.set(r,[o])}),et.set(t,e),e)}function B(t,e,r){const o=Ft(r),n=new Set;for(const a of t){const s=e[a];if(s!==void 0)for(const i of o.get(s)??[])n.add(i)}return[...n]}const Bt={type:"GeometryCollection",geometries:[]};function kt(t){const e=t.features??[],r=Z(e);let o=!1;const n=e.map((s,i)=>s==null||s.id!=null&&s.geometry!=null?s:(o=!0,{...s,id:r[i],geometry:s.geometry??Bt})),a=e.findIndex(s=>s?.geometry!=null);return a>0&&e[0]!=null&&e[0].geometry==null&&([n[0],n[a]]=[n[a],n[0]],o=!0),o?{...t,features:n}:t}function Gt(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const r=l=>new Error(`OSM source "${t.outputTableName}": ${l}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw r("queryArea takes either bbox or geocodeArea with areas, not both.");const o=e.bbox;if(!Array.isArray(o)||o.length!==4||!o.every(l=>typeof l=="number"&&Number.isFinite(l)))throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[n,a,s,i]=e.bbox;if(Math.abs(n)>180||Math.abs(s)>180)throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(a)>90||Math.abs(i)>90)throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");if(n>=s)throw r(`queryArea.bbox west (${n}) must be less than east (${s}); a box across the antimeridian is not supported.`);if(a>=i)throw r(`queryArea.bbox south (${a}) must be less than north (${i}).`);return{bbox:[n,a,s,i]}}function Dt(t){const{autoLoadLayers:e,...r}=t;return{...r,queryArea:Gt(t),autoLoadLayers:{layers:e?.layers??[]}}}function rt(t){return`${t?`coordinateFormat is set to "${t}"`:"no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`}function ot(t){let e=1/0,r=1/0,o=-1/0,n=-1/0;const a=i=>{if(Array.isArray(i)){if(typeof i[0]=="number"){const[l,u]=i;l<e&&(e=l),l>o&&(o=l),u<r&&(r=u),u>n&&(n=u);return}for(const l of i)a(l)}},s=i=>{i&&(i.type==="GeometryCollection"?i.geometries.forEach(s):a(i.coordinates))};for(const i of t.features??[])s(i?.geometry);return e<=o?[e,r,o,n]:void 0}function nt(t,e){function r(o,n){if(!n||!n.db)return;const a=document.getElementById(n.db);if(a){const s=o.getTablesMetadata();a.innerHTML+="<ul>";for(const i of s)a.innerHTML+=`<li>${i.name}: (${i.source}, ${i.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${s.length}</p>`}}return{async resolveSource(o,n){let a=o;a||(a=new E.AutkDb,await a.init());const{workspace:s}=n;await P(a,s);let{type:i,workspace:l,...u}=n;switch(i){case"osm":return await a.loadOsm(Dt(u)),r(a,t),a;case"csv":return await a.loadCsv(u),r(a,t),a;case"json":return await a.loadJson(u),r(a,t),a;case"geojson":{const c=u;let f;c.geojsonFileUrl?f=await(await fetch(c.geojsonFileUrl)).json():f=c.geojsonObject,e&&f&&e.set(M(s,c.outputTableName),f);const p=f?(()=>{const m={...c,geojsonObject:kt(f)};return delete m.geojsonFileUrl,m})():c,g=/^EPSG:4326$/i.test(p.coordinateFormat??"EPSG:4326"),d=f&&g?ot(f):void 0;if(d&&(d[1]<-90||d[3]>90))throw new Error(`GeoJSON layer "${p.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${d.join(", ")}]), so they cannot be EPSG:4326 degrees. ${rt(p.coordinateFormat)}`);try{await a.loadGeojson(p)}catch(m){throw new Error(`Failed to load GeoJSON layer "${p.outputTableName}": ${m instanceof Error?m.message:String(m)}`)}try{const m=await a.getBoundingBoxFromLayer(p.outputTableName),y=25e6;if(!isFinite(m.minLon)||!isFinite(m.minLat)||!isFinite(m.maxLon)||!isFinite(m.maxLat)||Math.abs(m.minLon)>y||Math.abs(m.maxLon)>y||Math.abs(m.minLat)>y||Math.abs(m.maxLat)>y)throw new Error(`Geometry bounding box after transform is invalid for layer "${p.outputTableName}" (bbox: [${m.minLon}, ${m.minLat}, ${m.maxLon}, ${m.maxLat}]). ${rt(p.coordinateFormat)} The workspace uses ${E.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(m){if(m instanceof Error&&m.message.includes("bounding box after transform"))throw m}return r(a,t),a}case"geotiff":return await a.loadGeoTiff(u),r(a,t),a;case"heatmap":{const c=u;if(c.groupBy?.some(f=>f.aggregateFn==="collect"))throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await a.buildHeatmap({tableJoinName:c.joinDataRef,near:c.near,outputTableName:c.outputTableName,grid:c.grid,...c.groupBy&&{groupBy:c.groupBy}}),r(a,t),a}case"join":{const c=u;if(await a.spatialQuery({tableRootName:c.dataRef,tableJoinName:c.joinDataRef,...c.near&&{near:c.near},...c.groupBy&&{groupBy:c.groupBy}}),e){const f=await a.getLayer(c.dataRef);e.set(M(s,c.dataRef),f)}return r(a,t),a}default:return}}}}function at(t,e,r){if(!t)return r();let o=t.get(e);return o||(o=r(),t.set(e,o)),o}function it(t,e){return t?.id??e}function x(t,e){return e===void 0?!0:typeof e=="number"?t.mapIndex===e:t.mapId===e}function st(t,e,r){const o=t?.get(e)??[];o.includes(r)||t?.set(e,[...o,r])}const lt=6378137,U=.0818191908426215;function jt(t,e){if(t===void 0||typeof t=="number"&&Number.isFinite(t)&&t>0)return;const r=typeof t=="number"?String(t):JSON.stringify(t);throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${r}.`)}function xt(t){const e=Math.exp(-t/lt);let r=Math.PI/2-2*Math.atan(e);for(let o=0;o<10;o++){const n=U*Math.sin(r),a=Math.PI/2-2*Math.atan(e*((1-n)/(1+n))**(U/2));if(Math.abs(a-r)<1e-12)return a;r=a}return r}function Ut(t,e){if(/^EPSG:3395$/i.test(t)){const r=xt(e),o=U*Math.sin(r);return Math.sqrt(1-o*o)/Math.cos(r)}return/^EPSG:3857$/i.test(t)?Math.cosh(e/lt):1}function Qt(t,e,r,o){if(t===void 0||e!=="points")return;const n=o();if(n)return t*Ut(r,(n[1]+n[3])/2)}function I(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function Yt(t,e){const r=new Set;for(const o of t.layerRefs){const n=I(o);if(r.has(n))throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(n)}}const Vt=/^#[0-9a-fA-F]{6}$/;function ut(t,e,r){if(!Vt.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return A.ColorMap.hexToRgb(t)}function Wt(t,e){const r={};return t.color!=null&&(r.color=ut(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=ut(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function Ht(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapRange!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function qt(t,e){const r=t.features?.[0]?.properties?.[e];return r instanceof Float32Array?r:ArrayBuffer.isView(r)&&!(r instanceof DataView)||Array.isArray(r)?Float32Array.from(r,o=>Number.isFinite(Number(o))?Number(o):NaN):null}function Jt(t,e,r,o,n){if(A.ColorMap.isCategorical(e.interpolator))return;if(n!=null){const u=r!=null?[n[0],r,n[1]]:[n[0],n[1]];return o===!0?u.reverse():u}if(!t)return;let a=0,s=0;for(let u=0;u<t.length;u++){const c=t[u];Number.isFinite(c)&&(s++,r!=null&&(a=Math.max(a,Math.abs(c-r))))}const i=r!=null&&a>0;if(s===0||!i&&o!==!0)return;const l=i&&r!=null?[r-a,r,r+a]:A.ColorMap.resolveDomainFromData(t,e);return o===!0?[...l].reverse():l}function Kt(t,e){if(!(e==null||A.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function Xt(t){const e=t.colorMapRange;if(e===void 0)return;const r=s=>new Error(`Layer "${I(t)}": ${s}`);if(!Array.isArray(e)||e.length!==2||!e.every(s=>typeof s=="number"&&Number.isFinite(s)))throw r("colorMapRange must hold two numbers, [low, high].");const[o,n]=e;if(o>=n)throw r(`colorMapRange low (${o}) must be less than high (${n}).`);if(t.colorMapDomain!==void 0)throw r("set colorMapRange or colorMapDomain, not both.");const a=t.colorMapCenter;if(a!=null&&(a<o||a>n))throw r(`colorMapCenter (${a}) must lie within colorMapRange [${o}, ${n}].`)}function zt(t,e){return e&&e.length>0?{type:A.ColorMapDomainStrategy.USER,params:e}:t?.mode===j.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:A.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:A.ColorMapDomainStrategy.PERCENTILE}:{type:A.ColorMapDomainStrategy.MIN_MAX}}function Zt(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function te(t,e,r){const o=e.split("."),n={...t};let a=n;for(let s=0;s<o.length-1;s++)a[o[s]]={...a[o[s]]??{}},a=a[o[s]];return a[o[o.length-1]]=r,n}function ee(t,e){const o=t.features?.[0]?.properties?.bands??[];return o.find(a=>a.id===e||a.label===e?.replace(/\./g,"_"))?.id??o[0]?.id??e??""}function ct(t,e){if(e.zoom===void 0&&!e.pitch&&!e.bearing)return;const r=t.camera,[o,n]=r.getLookAt(),a=e.zoom!==void 0?1e4/Math.pow(2,e.zoom-10):Math.abs(r.getEye()[2]),s=(e.pitch??0)*Math.PI/180,i=(e.bearing??0)*Math.PI/180,l=[o-a*Math.sin(s)*Math.sin(i),n-a*Math.sin(s)*Math.cos(i),a*Math.cos(s)];r.resetCamera([Math.sin(i),Math.cos(i),0],[o,n,0],l)}function re(t,e,r,o){const a=t.layerManager.searchByLayerId(e)?.components;return Array.isArray(a)?a.map((s,i)=>{const l=Number.isInteger(s?.featureIndex)?s.featureIndex:i;return r[o[l]]??""}):o.map(s=>r[s]??"")}function oe(t,e,r,o,n,a){async function s(i,l,u){let c={};for(const p of l.getTablesMetadata())p.type!==void 0&&(c[p.name]=p.type);const f=[];for(const p of u.layerRefs){const g=p.dataRef,d=I(p),m=M(u.workspace,g),y=n?.get(m)??c[g],w=p.getFnv,R=r?.get(m)??(y==="raster"?await l.getRaster(g):await at(a,m,()=>l.getLayer(g))),_=R.features??[],St=y==="raster"?[]:_.flatMap((b,S)=>b?.geometry!=null?[S]:[]),C=y==="raster"?R:{...R,features:St.map(b=>_[b])},vt=y==="raster"?ee(C,w):"";y==="raster"?i.loadCollection(d,{collection:C,type:"raster",property:vt}):i.loadCollection(d,{collection:C,type:y}),p.opacity!=null&&i.updateRenderInfo(d,{opacity:p.opacity});const Ct=Wt(p,d);Object.keys(Ct).length>0&&i.updateRenderInfo(d,Ct);const me=l.getWorkspaceConfiguration().coordinateFormat,It=Qt(p.pointSize,y,me,()=>ot(C));It!==void 0&&i.updateRenderInfo(d,{pointSize:It}),Ht(p,y)&&i.updateRenderInfo(d,{isColorMap:!0}),p.isPick&&i.updateRenderInfo(d,{isPick:!0}),p.isSkip&&i.updateRenderInfo(d,{isSkip:!0});const{catchAllCategory:G,colorMapDomain:$}=p;let Pt=C,Lt=$;if(w&&G&&$?.length){const b=new Set($);Pt={...C,features:C.features.map(S=>{const Ot=S.properties,q=Zt(Ot,w);return q==null||!b.has(String(q))?{...S,properties:te(Ot,w,G)}:S})},Lt=b.has(G)?$:[...$,G]}const Nt=y==="raster"&&p.transferFunction!=null;Nt&&i.layerManager.searchByLayerId(d)?.setTransferFunction?.(p.transferFunction);const D=p.colorMapRange,Tt=y==="raster"&&(D!=null||p.colorMapCenter!=null||p.colorMapReverse===!0);if(p.colorMapInterpolator||Tt||D){const b={interpolator:p.colorMapInterpolator??i.layerManager.searchByLayerId(d)?.layerRenderInfo.colormap.config.interpolator??A.ColorMapInterpolator.SEQ_REDS,domainSpec:zt(p.normalization,Lt)};let S;Tt?S=Jt(qt(C,vt),b,p.colorMapCenter,p.colorMapReverse,D):y!=="raster"&&(S=Kt(b,D)),S&&(b.domainSpec={type:A.ColorMapDomainStrategy.USER,params:S}),i.updateColorMap(d,{colorMap:b})}else Nt&&i.updateColorMap(d,{colorMap:{}});if(w&&y!=="raster"){const b=w.startsWith("properties.")?w:`properties.${w}`;i.updateThematic(d,{collection:Pt,property:b})}f.push(y==="raster"?[]:re(i,d,tt(_),St))}return f}return{async resolveMap(i,l,u=0){if(t&&t.map&&i){Yt(l,u);for(const d of l.layerRefs)Xt(d),jt(d.pointSize,I(d));let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[u]):c=document.getElementById(t.map),!c)throw new Error("Could not find rendering target for map: "+t.map);if(!(c instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const f=new F.AutkMap(c);let p;try{l.style&&f.style.setPredefinedStyle(l.style),await f.init(),await P(i,l.workspace),p=await s(f,i,l)}catch(d){try{f.destroy()}catch{}throw d}const g=it(l,u);l.layerRefs.forEach((d,m)=>e?.push({map:f,mapIndex:u,mapId:g,layerId:I(d),dataRef:d.dataRef,rows:p[m]})),o&&(o[u]=f),l.camera&&ct(f,l.camera),f.draw()}}}}function ne(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function T(t){return t.id??t.dataRef}function ft(t,e,r,o){const{map:n,layerId:a}=o;n.updateRenderInfo(a,{isPick:!0}),n.events.on(F.MapEvent.PICKING,({layerId:s,selection:i})=>{s===a&&t.setSelection(B(i,o.rows,e))});for(const s of r)t.events.on(s,({selection:i})=>{n.setHighlightedIds(a,B(i,e,o.rows))})}async function ae(t,e,r,o){const n=t.getTablesMetadata().find(a=>a.name===e);return n&&!E.isRenderableTable(n)?{type:"FeatureCollection",features:(await t.getTable(e)).map(s=>({type:"Feature",geometry:null,properties:s}))}:at(o,r,()=>t.getLayer(e))}function ie(t,e,r,o,n,a,s,i){return{async resolvePlot(l,u,c=0){if(!t||!t.plot)return;const f=Array.isArray(t.plot)?t.plot[c]:t.plot;if(f===void 0)throw new Error(`Plot ${c} has no target: the plot targets name ${t.plot.length} elements.`);const p=document.getElementById(f);if(!p)throw new Error(`Could not find plot target: ${f}`);const g=l;if(!g)throw new Error("No data context available for plot.");await P(g,u.workspace);const d=M(u.workspace,u.dataRef),m=a?.get(d)??n?.get(d)??await ae(g,u.dataRef,d,i),y=u.events??[],w=new N.AutkPlot(p,{type:ne(u.mark),collection:m,attributes:{axis:u.axis,...u.color&&{color:u.color}},labels:{axis:u.axis,title:u.title},events:y,...u.width&&{width:u.width},...u.height&&{height:u.height},...u.margins&&{margins:u.margins},...u.transform&&{transform:u.transform}});r?.set(T(u),w);const R=tt(m.features??[]);s?.set(T(u),R);for(const _ of e??[])!u.mapRef||_.dataRef!==u.mapRef||(ft(w,R,y,_),st(o,T(u),_))}}}const Q=134217728,se=4,le=32;function pt(t){return Array.isArray(t)?t.join(`
2
- `):t}function v(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function O(t,e){return t instanceof Map?t.get(e):t[e]}function k(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function dt(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))v(o)&&e.push(o);return e}function mt(t){return[...new Set([t.dataRef,...dt(t).map(e=>e.fromFeature.layer)])]}function Y(t){for(const e of dt(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function ht(t,e,r){const o=t.fromFeature,n=r!==void 0&&o.iterate==="all"?r:o.index??0,a=O(e,o.layer)?.features?.[n];return a?k(a,o.path):void 0}function V(t,e,r){if(!t)return;const o={};for(const[n,a]of Object.entries(t)){if(!v(a)){o[n]=a;continue}const s=Number(ht(a,e,r)??NaN);Number.isFinite(s)?o[n]=s:typeof a.default=="number"&&(o[n]=a.default)}return o}function W(t,e,r){if(!t)return;const o={};for(const[n,a]of Object.entries(t)){if(!v(a)){o[n]=a;continue}const s=ht(a,e,r),i=Array.isArray(s)?s:Array.isArray(a.default)?a.default:void 0;if(!i)continue;const l=a.cols??(Array.isArray(i[0])?i[0].length:0);l>0?o[n]={data:i,cols:l}:console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`)}return o}function ue(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function yt(t){return v(t)&&t.fromFeature.iterate==="batched"}function gt(t,e){return Object.values(e??{}).some(yt)?le:Object.values(t??{}).some(yt)?se:0}function wt(t,e,r=Q){const o=gt(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function bt(t,e,r,o=Q){const n={},a={},s=[];for(const l of[t,e])for(const u of Object.values(l??{}))v(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&s.push(u.fromFeature.path);if(s.length>0){const l=r.length;r=r.filter(u=>s.every(c=>ue(k(u,c)))),r.length<l&&console.info(`[autk-grammar] batched compute dropped ${l-r.length} feature(s) missing ${s.join(", ")}`)}const i=wt(t,e,o);r.length>i&&(console.warn(`[autk-grammar] batched compute capped at ${i} features (got ${r.length}): its largest packed array takes ${gt(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,i));for(const[l,u]of Object.entries(t??{}))if(v(u)&&u.fromFeature.iterate==="batched"){const c=typeof u.default=="number"?u.default:void 0;a[l]=r.map(f=>{const p=Number(k(f,u.fromFeature.path)??c);return Number.isFinite(p)?p:0})}else typeof u=="number"&&(n[l]=u);for(const[l,u]of Object.entries(e??{})){if(!v(u)||u.fromFeature.iterate!=="batched")continue;const c=[];for(const f of r){const p=k(f,u.fromFeature.path);let g=1/0,d=1/0,m=-1/0,y=-1/0;if(Array.isArray(p))for(const w of p){if(!Array.isArray(w)||w.length<2)continue;const R=Number(w[0]),_=Number(w[1]);!Number.isFinite(R)||!Number.isFinite(_)||(g=Math.min(g,R),d=Math.min(d,_),m=Math.max(m,R),y=Math.max(y,_))}Number.isFinite(g)||(g=0,d=0,m=0,y=0),c.push(g,d,m,d,m,y,g,y)}a[l]=c}return n.num_features=r.length,{uniforms:n,uniformArrays:a}}function H(t,e,r){const o=O(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n={collection:o,variableMapping:t.attributes,wgslBody:pt(t.wgslFunction)};t.attributeArrays&&(n.attributeArrays=t.attributeArrays),t.attributeMatrices&&(n.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(n.uniformArrays=t.uniformArrays),t.outputColumnName&&(n.resultField=t.outputColumnName),t.outputColumns&&(n.outputColumns=t.outputColumns);const a=Y(t);if(a?.mode==="batched"){const u=O(e,a.layer)?.features??[],c=bt(t.uniforms,t.uniformMatrices,u),f=V(_t(t.uniforms),e)??{},p=W(_t(t.uniformMatrices),e);return n.uniforms={...f,...c.uniforms},n.uniformArrays={...n.uniformArrays??{},...c.uniformArrays},p&&Object.keys(p).length>0&&(n.uniformMatrices=p),n}const s=a?.mode==="all"?r:void 0,i=V(t.uniforms,e,s),l=W(t.uniformMatrices,e,s);return i&&(n.uniforms=i),l&&(n.uniformMatrices=l),n}function _t(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(v(e)&&e.fromFeature.iterate==="batched")))}function ce(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function Et(t,e,r){const o=Y(t);if(o?.mode!=="all")return r(H(t,e));const n=O(e,t.dataRef);if(!n)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const a=ce(t),s=structuredClone(n);for(const l of s.features){const u=l.properties??={},c=u.compute??={};for(const f of a)c[f]=0}const i=O(e,o.layer)?.features?.length??0;for(let l=0;l<i;l++){const u=await r({...H(t,e,l),collection:s});s.features.forEach((c,f)=>{const p=c.properties?.compute,g=u.features[f]?.properties?.compute;if(!(!p||!g))for(const d of a){const m=Number(g[d]);Number.isFinite(m)&&(p[d]+=m)}})}return s}const At=["surface","parks","water","roads","buildings","polygons","polylines"];function fe(t,e,r,o){return o?.get(M(r,e))??t.getTablesMetadata().find(n=>n.name===e)?.type}function Mt(t,e){async function r(s,i,l){return t?.get(M(l,i))??await s.getLayer(i)}function o(s,i,l,u,c){if(!t)return;const f=u.outputTableName??l;t.set(M(u.workspace,f),i);const p=u.layerType??c??fe(s,l,u.workspace,e);u.outputTableName&&p&&e?.set(M(u.workspace,f),p)}async function n(s,i){for(const c of i.layers)if(!At.includes(c.type))throw new Error(`Render pass "${i.outputTableName}": layer "${c.id}" has the type "${c.type}", which a render pass cannot draw. A layer's type is one of ${At.join(", ")}.`);const l=await Promise.all(i.layers.map(async c=>({id:c.id,collection:await r(s,c.dataRef,i.workspace),type:c.type,objectIdProperty:c.objectIdProperty}))),u=await new J.AutkComputeEngine().renderPipeline({layers:l,viewpoints:{collection:await r(s,i.viewpoints.dataRef,i.workspace),strategy:i.viewpoints.strategy,sampling:i.viewpoints.sampling},aggregation:i.aggregation,camera:i.camera,tileSize:i.tileSize});o(s,u,i.viewpoints.dataRef,i,i.viewpoints.strategy?.type==="building-windows"?"points":void 0)}async function a(s,i){const l={};for(const f of mt(i)){const p=t?.get(M(i.workspace,f));if(p)l[f]=p;else if(f===i.dataRef)l[f]=await s.getLayer(f);else try{l[f]=await s.getLayer(f)}catch{l[f]=void 0}}const u=new J.AutkComputeEngine,c=await Et(i,l,f=>u.gpgpuPipeline(f));o(s,c,i.dataRef,i)}return{async resolveCompute(s,i){if(s)return await P(s,i.workspace),i.type==="render"?await n(s,i):await a(s,i),s}}}class Rt{_listeners=new Map;on(e,r){this._listeners.has(e)||this._listeners.set(e,new Set);const o=this._listeners.get(e);return o.add(r),()=>o.delete(r)}emit(e,r){this._listeners.get(e)?.forEach(o=>o(r))}}function L(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function pe(t){const e=new Set;for(const o of[...L(t.map),...L(t.plot)])if(o.id!==void 0){if(o.id==="")throw new Error("A map or plot has an empty id.");if(e.has(o.id))throw new Error(`Two maps or plots have the id "${o.id}"; an id names one view.`);e.add(o.id)}const r=new Map;for(const o of L(t.plot)){const n=T(o),a=r.get(n);if(a)throw new Error(a.id===void 0&&o.id===void 0?`Two plots of the table "${n}" have no id; give each plot an id.`:`A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);r.set(n,o)}}class de{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_computeTypes=new Map;_data={};_layers=[];_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotLinks=new Map;_plotRows=new Map;_exports=new Map;_geojsonCache=new Map;interactions=new Rt;constructor(e){this.dataAdapter=nt(e,this._geojsonCache),this.mapAdapter=oe(e,this._layers,this._computeCache,this._maps,this._computeTypes,this._exports),this.plotAdapter=ie(e,this._layers,this._plotRegistry,this._plotLinks,this._geojsonCache,this._computeCache,this._plotRows,this._exports),this.computeAdapter=Mt(this._computeCache,this._computeTypes)}get workspaceCrs(){return E.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayers(e,r){return this._layersOf(e,r).map(({map:o,layerId:n})=>({map:o,layerId:n}))}mapLayer(e,r){return this.mapLayers(e,r).pop()}_layersOf(e,r){return this._layers.filter(o=>o.dataRef===e&&x(o,r))}destroy(){for(const e of this._fwdCleanups)e();this._fwdCleanups=[];for(const e of this._maps)e.destroy();this._maps.length=0,this._layers.length=0,this._plotRegistry.clear(),this._plotLinks.clear(),this._plotRows.clear(),this._exports.clear(),this._geojsonCache.clear(),this._computeCache.clear(),this._computeTypes.clear(),this.grammarEngine=void 0,this._data={}}async run(e){if(!this.dataAdapter)throw new Error("Database adapter not initialized. Please call the constructor first.");if(!this.mapAdapter)throw new Error("Map engine not initialized. Please call the constructor first.");if(!this.plotAdapter)throw new Error("Plot adapter not initialized. Please call the constructor first.");if(!this.computeAdapter)throw new Error("Compute adapter not initialized. Please call the constructor first.");pe(e),this.destroy(),this.grammarEngine=K({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run();const r=this.grammarEngine.context;if(r&&await P(r),this._wireLinks(e),this._rewireInteractions(e),!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const n of r.getLayersMetadata())Object.defineProperty(o,n.name,{get:()=>{const a=this._computeCache.get(n.name);return a?Promise.resolve(a):r.getLayer(n.name)},enumerable:!0,configurable:!0});for(const n of this._computeCache.keys())n in o||Object.defineProperty(o,n,{get:()=>Promise.resolve(this._computeCache.get(n)),enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r,o){const n=this._layersOf(e,o);for(const{map:a,layerId:s}of n)a.setHighlightedIds(s,r);this._selectInLinkedPlots(n,r)}clearHighlightOnMap(e,r){const o=this._layersOf(e,r);for(const{map:n,layerId:a}of o)n.clearHighlightedIds(a);this._selectInLinkedPlots(o,[])}clearHighlightOnPlot(e,r){this._plotRegistry.get(e)?.setSelection([]);for(const o of this._plotLinks.get(e)??[])x(o,r)&&o.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r,o){this._plotRegistry.get(e)?.setSelection(r);const n=this._plotRows.get(e)??[];for(const a of this._plotLinks.get(e)??[])x(a,o)&&a.map.setHighlightedIds(a.layerId,B(r,n,a.rows))}_selectInLinkedPlots(e,r){for(const[o,n]of this._plotLinks){const a=n.filter(l=>e.includes(l));if(a.length===0)continue;const s=this._plotRows.get(o)??[],i=new Set(a.flatMap(l=>B(r,l.rows,s)));this._plotRegistry.get(o)?.setSelection([...i])}}_wireLinks(e){const r=L(e.map),o=L(e.plot);for(const n of e.links??[]){const a=o.find(f=>T(f)===n.source),s=this._plotRegistry.get(n.source);if(!a||!s)throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);const i=r.findIndex(f=>f.id===n.target),l=this._maps[i];if(i<0||!l)throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);const u=r[i].layerRefs.find(f=>n.layer!==void 0?I(f)===n.layer:f.dataRef===a.dataRef);if(!u)throw new Error(n.layer!==void 0?`Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".`:`Link from "${n.source}": map "${n.target}" draws no layer of the table "${a.dataRef}"; name the layer.`);const c=this._layers.find(f=>f.mapIndex===i&&f.layerId===I(u));c&&(ft(s,this._plotRows.get(n.source)??[],a.events??[],c),st(this._plotLinks,n.source,c))}}_rewireInteractions(e){for(const o of this._fwdCleanups)o();this._fwdCleanups=[];const r=L(e.map);this._maps.forEach((o,n)=>{const a=it(r[n],n),s=({layerId:i,selection:l})=>{this.interactions.emit("map:picking",{mapId:a,layerId:i,selection:l})};o.events.on(F.MapEvent.PICKING,s),this._fwdCleanups.push(()=>o.events.off(F.MapEvent.PICKING,s))});for(const[o,n]of this._plotRegistry)for(const a of[N.PlotEvent.CLICK,N.PlotEvent.BRUSH,N.PlotEvent.BRUSH_X,N.PlotEvent.BRUSH_Y]){const s=({selection:i})=>{this.interactions.emit("plot:selection",{plotId:o,event:a,selection:i})};n.events.on(a,s),this._fwdCleanups.push(()=>n.events.off(a,s))}}}h.AutkGrammar=de,h.ColorMapInterpolator=z,h.GrammarEventEmitter=Rt,h.NormalizationMode=j,h.STORAGE_BUFFER_BINDING_SIZE=Q,h.applyCamera=ct,h.arrangeViews=$t,h.buildBatchedUniforms=bt,h.computeLayerNames=mt,h.createComputeAdapter=Mt,h.createDataAdapter=nt,h.createEngine=K,h.enterWorkspace=P,h.findIterateSource=Y,h.isFromFeature=v,h.joinWgsl=pt,h.maxBatchedFeatures=wt,h.resolveComputeParams=H,h.resolveUniformMatrices=W,h.resolveUniforms=V,h.runCompute=Et,h.tableKey=M,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(g,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("@urban-toolkit/autk-db"),require("@urban-toolkit/autk-map"),require("@urban-toolkit/autk-plot"),require("@urban-toolkit/autk-core"),require("@urban-toolkit/autk-compute")):typeof define=="function"&&define.amd?define(["exports","@urban-toolkit/autk-db","@urban-toolkit/autk-map","@urban-toolkit/autk-plot","@urban-toolkit/autk-core","@urban-toolkit/autk-compute"],_):(g=typeof globalThis<"u"?globalThis:g||self,_(g["autk-grammar"]={},g.autkDb,g.autkMap,g.autkPlot,g.autkCore,g.autkCompute))})(this,(function(g,_,F,I,b,X){"use strict";function Z(t){const{spec:e,adapters:o}=t;let r;async function n(){let s;if(e.workspaces?.length&&o.db.resolveWorkspaces&&(s=await o.db.resolveWorkspaces(s,e.workspaces)),e.data)for(const i of e.data)s=await o.db.resolveSource(s,i);if(e.compute)for(const i of e.compute)s=await o.compute.resolveCompute(s,i);if(e.map)if(Array.isArray(e.map))for(let i=0;i<e.map.length;i++){let u=e.map[i];await o.map.resolveMap(s,u,i)}else await o.map.resolveMap(s,e.map);if(e.plot)if(Array.isArray(e.plot))for(let i=0;i<e.plot.length;i++)await o.plot.resolvePlot(s,e.plot[i],i);else await o.plot.resolvePlot(s,e.plot);r=s}function l(s){return console.log("Spec to update",s),new Promise(i=>{i()})}function a(){console.log("Function not implemented yet")}return{run:n,updatedSpec:l,destroy:a,get context(){return r}}}function tt(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function qt(t){const e=t.layout??{},o=e.type??"vertical";if(o!=="vertical"&&o!=="horizontal"&&o!=="grid")throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(o)}.`);const r=e.gap??0;if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(r)}.`);const n=e.columns??2;if(!Number.isInteger(n)||n<1)throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);const l=[...tt(t.map).map((i,u)=>({kind:"map",index:u,id:i.id,key:i.id??u})),...tt(t.plot).map((i,u)=>({kind:"plot",index:u,id:i.id,key:i.id??i.dataRef}))],a=o==="vertical"?1:o==="horizontal"?Math.max(l.length,1):n,s=l.map(({kind:i,index:u,id:d,key:c},f)=>({kind:i,index:u,...d!==void 0&&{id:d},key:c,row:Math.floor(f/a),column:f%a}));return{type:o,rows:Math.ceil(l.length/a),columns:a,gap:r,panes:s}}var et=(t=>(t.CAT_ACCENT="schemeAccent",t.CAT_DARK2="schemeDark2",t.CAT_CATEGORY10="schemeCategory10",t.CAT_OBSERVABLE10="schemeObservable10",t.CAT_PAIRED="schemePaired",t.CAT_PASTEL1="schemePastel1",t.CAT_PASTEL2="schemePastel2",t.CAT_SET1="schemeSet1",t.CAT_SET2="schemeSet2",t.CAT_SET3="schemeSet3",t.CAT_TABLEAU10="schemeTableau10",t.SEQ_REDS="interpolateReds",t.SEQ_BLUES="interpolateBlues",t.SEQ_GREENS="interpolateGreens",t.SEQ_GREYS="interpolateGreys",t.SEQ_ORANGES="interpolateOranges",t.SEQ_PURPLES="interpolatePurples",t.SEQ_TURBO="interpolateTurbo",t.SEQ_VIRIDIS="interpolateViridis",t.SEQ_INFERNO="interpolateInferno",t.SEQ_MAGMA="interpolateMagma",t.SEQ_PLASMA="interpolatePlasma",t.SEQ_CIVIDIS="interpolateCividis",t.SEQ_WARM="interpolateWarm",t.SEQ_COOL="interpolateCool",t.SEQ_CUBEHELIX_DEFAULT="interpolateCubehelixDefault",t.SEQ_BU_GN="interpolateBuGn",t.SEQ_BU_PU="interpolateBuPu",t.SEQ_GN_BU="interpolateGnBu",t.SEQ_OR_RD="interpolateOrRd",t.SEQ_PU_BU_GN="interpolatePuBuGn",t.SEQ_PU_BU="interpolatePuBu",t.SEQ_PU_RD="interpolatePuRd",t.SEQ_RD_PU="interpolateRdPu",t.SEQ_YL_GN_BU="interpolateYlGnBu",t.SEQ_YL_GN="interpolateYlGn",t.SEQ_YL_OR_BR="interpolateYlOrBr",t.SEQ_YL_OR_RD="interpolateYlOrRd",t.DIV_BR_BG="interpolateBrBG",t.DIV_PR_GN="interpolatePRGn",t.DIV_PI_YG="interpolatePiYG",t.DIV_PU_OR="interpolatePuOr",t.DIV_RED_BLUE="interpolateRdBu",t.DIV_RED_GREY="interpolateRdGy",t.DIV_RED_YELLOW_BLUE="interpolateRdYlBu",t.DIV_RED_YELLOW_GREEN="interpolateRdYlGn",t.DIV_SPECTRAL="interpolateSpectral",t))(et||{}),U=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(U||{});async function N(t,e){const o=e??_.DEFAULT_WORKSPACE_NAME;t.getCurrentWorkspace()!==o&&await t.setWorkspace(o)}function v(t,e){return t===void 0||t===_.DEFAULT_WORKSPACE_NAME?e:`${t}/${e}`}const ot=new WeakMap;function Ht(t,e){ot.set(t,e)}function Jt(t,e){const o=t&&ot.get(t);return o!==void 0&&o.toUpperCase()===e.toUpperCase()?t:void 0}function rt(t){const e=new Set;for(const r of t)r?.id!=null&&e.add(JSON.stringify(r.id));const o=new Set;return t.map((r,n)=>{if(r?.id!=null)return r.id;let l=`autk-feature-${n}`;for(;e.has(JSON.stringify(l))||o.has(JSON.stringify(l));)l=`${l}-generated`;return o.add(JSON.stringify(l)),l})}function nt(t){const e=new Map;return rt(t).map(o=>{const r=JSON.stringify(o),n=e.get(r)??0;return e.set(r,n+1),n===0?r:`${r} ${n}`})}const at=new WeakMap;function Kt(t){let e=at.get(t);return e||(e=new Map,t.forEach((o,r)=>{const n=e.get(o);n?n.push(r):e.set(o,[r])}),at.set(t,e),e)}function B(t,e,o){const r=Kt(o),n=new Set;for(const l of t){const a=e[l];if(a!==void 0)for(const s of r.get(a)??[])n.add(s)}return[...n]}const zt={type:"GeometryCollection",geometries:[]};function Xt(t){const e=t.features??[],o=rt(e);let r=!1;const n=e.map((a,s)=>a==null||a.id!=null&&a.geometry!=null?a:(r=!0,{...a,id:o[s],geometry:a.geometry??zt})),l=e.findIndex(a=>a?.geometry!=null);return l>0&&e[0]!=null&&e[0].geometry==null&&([n[0],n[l]]=[n[l],n[0]],r=!0),r?{...t,features:n}:t}function Zt(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const o=i=>new Error(`OSM source "${t.outputTableName}": ${i}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw o("queryArea takes either bbox or geocodeArea with areas, not both.");const r=e.bbox;if(!Array.isArray(r)||r.length!==4||!r.every(i=>typeof i=="number"&&Number.isFinite(i)))throw o("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[n,l,a,s]=e.bbox;if(Math.abs(n)>180||Math.abs(a)>180)throw o("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(l)>90||Math.abs(s)>90)throw o("queryArea.bbox south and north must be latitudes from -90 to 90.");if(n>=a)throw o(`queryArea.bbox west (${n}) must be less than east (${a}); a box across the antimeridian is not supported.`);if(l>=s)throw o(`queryArea.bbox south (${l}) must be less than north (${s}).`);return{bbox:[n,l,a,s]}}function te(t){const{autoLoadLayers:e,...o}=t;if(t.pbfFileUrl!==void 0&&(t.tagSets?.length??0)>0)throw new Error(`OSM source "${t.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);return{...o,queryArea:Zt(t),autoLoadLayers:{layers:e?.layers??[],...e?.coordinateFormat!==void 0&&{coordinateFormat:e.coordinateFormat}}}}function it(t){return`${t?`coordinateFormat is set to "${t}"`:"no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`}function W(t){return t===void 0||t===_.DEFAULT_WORKSPACE_NAME?"the default workspace":`the workspace "${t}"`}function st(t){if(t!=null)return typeof t=="string"?t:JSON.stringify(t)}async function ee(t,e,o,r){const n=new Map;for(const s of(await t.getLayer(e.name)).features){const i=st(s.properties?.[r]);if(i!==void 0){if(s.id===void 0||s.id===null)throw new Error("its rows have no feature id to update them by.");n.set(i,[...n.get(i)??[],s.id])}}const l=o.features.flatMap(s=>{const i=st(s.properties?.[r]);return i===void 0?[]:(n.get(i)??[]).map(u=>({...s,id:u}))}),a=e.columns.some(s=>s.name==="geojson_id")?"geojson_id":"id";return{data:{...o,features:l},idColumn:a}}async function lt(t){if(t)return t;const e=new _.AutkDb;return await e.init(),e}function ut(t){let e=1/0,o=1/0,r=-1/0,n=-1/0;const l=s=>{if(Array.isArray(s)){if(typeof s[0]=="number"){const[i,u]=s;i<e&&(e=i),i>r&&(r=i),u<o&&(o=u),u>n&&(n=u);return}for(const i of s)l(i)}},a=s=>{s&&(s.type==="GeometryCollection"?s.geometries.forEach(a):l(s.coordinates))};for(const s of t.features??[])a(s?.geometry);return e<=r?[e,o,r,n]:void 0}function ct(t,e){function o(n,l){if(!l||!l.db)return;const a=document.getElementById(l.db);if(a){const s=n.getTablesMetadata();a.innerHTML+="<ul>";for(const i of s)a.innerHTML+=`<li>${i.name}: (${i.source}, ${i.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${s.length}</p>`}}async function r(n,l,a){if(!e)return;const s=v(l,a),i=n.getTablesMetadata().find(u=>u.name===a);i&&_.isRenderableTable(i)?e.set(s,await n.getLayer(a)):e.delete(s)}return{async resolveWorkspaces(n,l){const a=await lt(n),s=new Set;for(const{name:i,coordinateFormat:u,precisionGrid:d}of l){const c=i??_.DEFAULT_WORKSPACE_NAME;if(s.has(c))throw new Error(`workspaces sets ${W(i)} twice; give each workspace one entry.`);s.add(c);try{await a.setWorkspace(c,{coordinateFormat:u,precisionGrid:d})}catch(f){throw new Error(`workspaces, ${W(i)}: ${f instanceof Error?f.message:String(f)}`)}}return await N(a),a},async resolveSource(n,l){const a=await lt(n),{workspace:s}=l;await N(a,s);let{type:i,workspace:u,...d}=l;switch(i){case"osm":return await a.loadOsm(te(d)),o(a,t),a;case"csv":return await a.loadCsv(d),o(a,t),a;case"json":return await a.loadJson(d),o(a,t),a;case"geojson":{const c=d;let f;c.geojsonFileUrl?f=await(await fetch(c.geojsonFileUrl)).json():f=c.geojsonObject,e&&f&&(e.set(v(s,c.outputTableName),f),Ht(f,c.coordinateFormat??"EPSG:4326"));const m=f?(()=>{const p={...c,geojsonObject:Xt(f)};return delete p.geojsonFileUrl,p})():c,h=/^EPSG:4326$/i.test(m.coordinateFormat??"EPSG:4326"),y=f&&h?ut(f):void 0;if(y&&(y[1]<-90||y[3]>90))throw new Error(`GeoJSON layer "${m.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${y.join(", ")}]), so they cannot be EPSG:4326 degrees. ${it(m.coordinateFormat)}`);try{await a.loadGeojson(m)}catch(p){throw new Error(`Failed to load GeoJSON layer "${m.outputTableName}": ${p instanceof Error?p.message:String(p)}`)}try{const p=await a.getBoundingBoxFromLayer(m.outputTableName),w=25e6;if(!isFinite(p.minLon)||!isFinite(p.minLat)||!isFinite(p.maxLon)||!isFinite(p.maxLat)||Math.abs(p.minLon)>w||Math.abs(p.maxLon)>w||Math.abs(p.minLat)>w||Math.abs(p.maxLat)>w)throw new Error(`Geometry bounding box after transform is invalid for layer "${m.outputTableName}" (bbox: [${p.minLon}, ${p.minLat}, ${p.maxLon}, ${p.maxLat}]). ${it(m.coordinateFormat)} The workspace uses ${a.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`)}catch(p){if(p instanceof Error&&p.message.includes("bounding box after transform"))throw p}return o(a,t),a}case"geotiff":return await a.loadGeoTiff(d),o(a,t),a;case"heatmap":{const c=d;if(c.groupBy?.some(f=>f.aggregateFn==="collect"))throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await a.buildHeatmap({tableJoinName:c.joinDataRef,near:c.near,outputTableName:c.outputTableName,grid:c.grid,...c.groupBy&&{groupBy:c.groupBy}}),o(a,t),a}case"join":{const c=d;if(await a.spatialQuery({tableRootName:c.dataRef,tableJoinName:c.joinDataRef,...c.near&&{near:c.near},...c.groupBy&&{groupBy:c.groupBy}}),e){const f=await a.getLayer(c.dataRef);e.set(v(s,c.dataRef),f)}return o(a,t),a}case"sql":{const c=d;try{await a.rawQuery({query:c.query,output:{type:"CREATE_TABLE",tableName:c.outputTableName,source:"user",...c.layerType!==void 0&&{tableType:c.layerType}}})}catch(f){throw new Error(`SQL source "${c.outputTableName}": ${f instanceof Error?f.message:String(f)}`)}return e?.delete(v(s,c.outputTableName)),o(a,t),a}case"update":{const c=d,f=y=>new Error(`Update of "${c.dataRef}": ${y}`);if(c.geojsonObject===void 0==(c.jsonObject===void 0))throw f("give its rows in geojsonObject or in jsonObject, one of the two.");if(c.strategy==="update"&&!c.idColumn)throw f("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");let m=c.geojsonObject??c.jsonObject,h=c.idColumn;try{const y=a.getTablesMetadata().find(p=>p.name===c.dataRef);if(c.strategy==="update"&&c.geojsonObject&&h?.startsWith("properties.")&&y&&_.isVectorTable(y)&&({data:m,idColumn:h}=await ee(a,y,c.geojsonObject,h.slice(11)),m.features.length===0))return o(a,t),a;await a.updateTable({tableName:c.dataRef,data:m,strategy:c.strategy,...h!==void 0&&{idColumn:h}})}catch(y){throw f(y instanceof Error?y.message:String(y))}return await r(a,s,c.dataRef),o(a,t),a}case"drop":{const c=d;if(!a.getTablesMetadata().some(f=>f.name===c.dataRef))throw new Error(`Drop of "${c.dataRef}": ${W(s)} holds no table of that name.`);return await a.removeLayer(c.dataRef),e?.delete(v(s,c.dataRef)),o(a,t),a}default:throw new Error(`Unknown data source type "${String(i)}".`)}}}}function ft(t,e){return e===!0?`${t} osm-elements`:t}function dt(t){return t===!0?{osmElements:!0}:void 0}function pt(t,e,o){if(!t)return o();let r=t.get(e);return r||(r=o(),t.set(e,r)),r}function mt(t,e){return t?.id??e}function Q(t,e){return e===void 0?!0:typeof e=="number"?t.mapIndex===e:t.mapId===e}function ht(t,e,o){const r=t?.get(e)??[];r.includes(o)||t?.set(e,[...r,o])}const yt=6378137,Y=.0818191908426215;function oe(t,e){if(t===void 0||typeof t=="number"&&Number.isFinite(t)&&t>0)return;const o=typeof t=="number"?String(t):JSON.stringify(t);throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${o}.`)}function re(t){const e=Math.exp(-t/yt);let o=Math.PI/2-2*Math.atan(e);for(let r=0;r<10;r++){const n=Y*Math.sin(o),l=Math.PI/2-2*Math.atan(e*((1-n)/(1+n))**(Y/2));if(Math.abs(l-o)<1e-12)return l;o=l}return o}function ne(t,e){if(/^EPSG:3395$/i.test(t)){const o=re(e),r=Y*Math.sin(o);return Math.sqrt(1-r*r)/Math.cos(o)}return/^EPSG:3857$/i.test(t)?Math.cosh(e/yt):1}function ae(t,e,o,r){if(t===void 0||e!=="points")return;const n=r();if(n)return t*ne(o,(n[1]+n[3])/2)}const gt=/^#[0-9a-fA-F]{6}$/;function wt(t,e){if(t===void 0)return;if(!Array.isArray(t)||t.length!==2||!t.every(n=>typeof n=="number"&&Number.isFinite(n)))return"colorMapRange must hold two numbers, [low, high].";const[o,r]=t;if(o>=r)return`colorMapRange low (${o}) must be less than high (${r}).`;if(e!==void 0)return"set colorMapRange or colorMapDomain, not both."}function bt(t,e){return e&&e.length>0?{type:b.ColorMapDomainStrategy.USER,params:e}:t?.mode===U.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:b.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:b.ColorMapDomainStrategy.PERCENTILE}:{type:b.ColorMapDomainStrategy.MIN_MAX}}function T(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function ie(t,e){const o=new Set;for(const r of t.layerRefs){const n=T(r);if(o.has(n))throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);o.add(n)}}function Et(t,e,o){if(!gt.test(t))throw new Error(`Layer "${o}": ${e} must be a color written #rrggbb, not "${t}".`);return b.ColorMap.hexToRgb(t)}function se(t,e){const o={};return t.color!=null&&(o.color=Et(t.color,"color",e)),t.stroke===!1?o.showBorders=!1:t.stroke!=null&&(o.strokeColor=Et(t.stroke,"stroke",e)),t.width!=null&&(o.polylinesWidth=t.width),o}function le(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapRange!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function ue(t,e){const o=t.features?.[0]?.properties?.[e];return o instanceof Float32Array?o:ArrayBuffer.isView(o)&&!(o instanceof DataView)||Array.isArray(o)?Float32Array.from(o,r=>Number.isFinite(Number(r))?Number(r):NaN):null}function ce(t,e,o,r,n){if(b.ColorMap.isCategorical(e.interpolator))return;if(n!=null){const u=o!=null?[n[0],o,n[1]]:[n[0],n[1]];return r===!0?u.reverse():u}if(!t)return;let l=0,a=0;for(let u=0;u<t.length;u++){const d=t[u];Number.isFinite(d)&&(a++,o!=null&&(l=Math.max(l,Math.abs(d-o))))}const s=o!=null&&l>0;if(a===0||!s&&r!==!0)return;const i=s&&o!=null?[o-l,o,o+l]:b.ColorMap.resolveDomainFromData(t,e);return r===!0?[...i].reverse():i}function fe(t,e){if(!(e==null||b.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function de(t){const e=t.colorMapRange;if(e===void 0)return;const o=s=>new Error(`Layer "${T(t)}": ${s}`),r=wt(e,t.colorMapDomain);if(r)throw o(r);const[n,l]=e,a=t.colorMapCenter;if(a!=null&&(a<n||a>l))throw o(`colorMapCenter (${a}) must lie within colorMapRange [${n}, ${l}].`)}function pe(t,e){return e.split(".").reduce((o,r)=>{if(!(o==null||typeof o!="object"))return o[r]},t)}function me(t,e,o){const r=e.split("."),n={...t};let l=n;for(let a=0;a<r.length-1;a++)l[r[a]]={...l[r[a]]??{}},l=l[r[a]];return l[r[r.length-1]]=o,n}function he(t,e){const r=t.features?.[0]?.properties?.bands??[];return r.find(l=>l.id===e||l.label===e?.replace(/\./g,"_"))?.id??r[0]?.id??e??""}function _t(t){const{pitch:e}=t;return e===void 0||typeof e=="number"&&e>=0&&e<90?void 0:`camera.pitch must be at least 0 and less than 90 degrees, not ${typeof e=="number"?String(e):JSON.stringify(e)}: at 90 the eye would sit on the ground, edge-on to the map's flat layers, and the map could not pan.`}function vt(t,e){const o=_t(e);if(o)throw new Error(o);if(e.zoom===void 0&&!e.pitch&&!e.bearing)return;const r=t.camera,[n,l]=r.getLookAt(),a=e.zoom!==void 0?1e4/Math.pow(2,e.zoom-10):Math.abs(r.getEye()[2]),s=(e.pitch??0)*Math.PI/180,i=(e.bearing??0)*Math.PI/180,u=[n-a*Math.sin(s)*Math.sin(i),l-a*Math.sin(s)*Math.cos(i),a*Math.cos(s)],d=[Math.cos(s)*Math.sin(i),Math.cos(s)*Math.cos(i),Math.sin(s)];r.resetCamera(d,[n,l,0],u)}function ye(t,e,o,r){const l=t.layerManager.searchByLayerId(e)?.components;return Array.isArray(l)?l.map((a,s)=>{const i=Number.isInteger(a?.featureIndex)?a.featureIndex:s;return o[r[i]]??""}):r.map(a=>o[a]??"")}function ge(t,e,o,r,n,l){async function a(s,i,u){let d={};for(const f of i.getTablesMetadata())f.type!==void 0&&(d[f.name]=f.type);const c=[];for(const f of u.layerRefs){const m=f.dataRef,h=T(f),y=v(u.workspace,m),p=n?.get(y)??d[m],w=f.getFnv,M=o?.get(y)??(p==="raster"?await i.getRaster(m):await pt(l,ft(y,f.osmElements),()=>i.getLayer(m,dt(f.osmElements)))),C=M.features??[],L=p==="raster"?[]:C.flatMap((E,R)=>E?.geometry!=null?[R]:[]),P=p==="raster"?M:{...M,features:L.map(E=>C[E])},Gt=p==="raster"?he(P,w):"";p==="raster"?s.loadCollection(h,{collection:P,type:"raster",property:Gt}):s.loadCollection(h,{collection:P,type:p}),f.opacity!=null&&s.updateRenderInfo(h,{opacity:f.opacity});const Dt=se(f,h);Object.keys(Dt).length>0&&s.updateRenderInfo(h,Dt);const xe=i.getWorkspaceConfiguration().coordinateFormat,xt=ae(f.pointSize,p,xe,()=>ut(P));xt!==void 0&&s.updateRenderInfo(h,{pointSize:xt}),le(f,p)&&s.updateRenderInfo(h,{isColorMap:!0}),f.isPick&&s.updateRenderInfo(h,{isPick:!0}),f.isSkip&&s.updateRenderInfo(h,{isSkip:!0});const{catchAllCategory:D,colorMapDomain:k}=f;let Ut=P,Wt=k;if(w&&D&&k?.length){const E=new Set(k);Ut={...P,features:P.features.map(R=>{const Vt=R.properties,z=pe(Vt,w);return z==null||!E.has(String(z))?{...R,properties:me(Vt,w,D)}:R})},Wt=E.has(D)?k:[...k,D]}const Qt=p==="raster"&&f.transferFunction!=null;Qt&&s.layerManager.searchByLayerId(h)?.setTransferFunction?.(f.transferFunction);const x=f.colorMapRange,Yt=p==="raster"&&(x!=null||f.colorMapCenter!=null||f.colorMapReverse===!0);if(f.colorMapInterpolator||Yt||x){const E={interpolator:f.colorMapInterpolator??s.layerManager.searchByLayerId(h)?.layerRenderInfo.colormap.config.interpolator??b.ColorMapInterpolator.SEQ_REDS,domainSpec:bt(f.normalization,Wt)};let R;Yt?R=ce(ue(P,Gt),E,f.colorMapCenter,f.colorMapReverse,x):p!=="raster"&&(R=fe(E,x)),R&&(E.domainSpec={type:b.ColorMapDomainStrategy.USER,params:R}),s.updateColorMap(h,{colorMap:E})}else Qt&&s.updateColorMap(h,{colorMap:{}});if(w&&p!=="raster"){const E=w.startsWith("properties.")?w:`properties.${w}`;s.updateThematic(h,{collection:Ut,property:E})}c.push(p==="raster"?[]:ye(s,h,nt(C),L))}return c}return{async resolveMap(s,i,u=0){if(t&&t.map&&s){ie(i,u);for(const y of i.layerRefs)de(y),oe(y.pointSize,T(y));const d=i.camera&&_t(i.camera);if(d)throw new Error(`Map ${u}: ${d}`);let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[u]):c=document.getElementById(t.map),!c)throw new Error("Could not find rendering target for map: "+t.map);if(!(c instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const f=new F.AutkMap(c);let m;try{i.style&&f.style.setPredefinedStyle(i.style),await f.init(),await N(s,i.workspace),m=await a(f,s,i)}catch(y){try{f.destroy()}catch{}throw y}const h=mt(i,u);i.layerRefs.forEach((y,p)=>e?.push({map:f,mapIndex:u,mapId:h,layerId:T(y),dataRef:y.dataRef,rows:m[p]})),r&&(r[u]=f),i.camera&&vt(f,i.camera),f.draw()}}}}function A(t){return t.id??t.dataRef}const we=new Set(Object.values(b.ColorMapInterpolator));function Mt(t,e,o){if(e!==void 0){if(typeof e!="string"||!we.has(e))return`${t} ${JSON.stringify(e)} is not a color scheme.`;if(b.ColorMap.isCategorical(e)!==o)return o?`${t} "${e}" is not a categorical scheme: categories take a scheme* scheme, such as schemeTableau10.`:`${t} "${e}" is a categorical scheme: numbers take an interpolate* scheme, and categories take categoricalColorMapInterpolator.`}}const be=/^(?:.?[<>=^])?[-+( ]?[$#]?0?\d*,?(?:\.\d+)?~?[a-zA-Z%]?$/;function Ee(t){if(t===void 0)return;if(!Array.isArray(t)||t.length!==2)return"tickFormats must hold two d3-format specifiers, [x, y].";const e=t.findIndex(o=>typeof o!="string"||!be.test(o));if(e>=0)return`tickFormats[${e}] ${JSON.stringify(t[e])} is not a d3-format specifier, such as "~s", ",d" or ".0%".`}function _e(t,e){if(t===void 0)return;if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))return"axisLabels must be a list of titles, one for each column of axis.";if(t.length>e.length)return`axisLabels has ${t.length} titles for the ${e.length} columns of axis.`;const o=t.find((r,n)=>t.indexOf(r)!==n);if(o!==void 0)return`axisLabels gives two axes the title ${JSON.stringify(o)}.`}function At(t,e){if(!(e===void 0||typeof e=="string"&&gt.test(e)))return`${t} must be a color written #rrggbb, not ${JSON.stringify(e)}.`}function ve(t){if(t!==void 0&&(!Array.isArray(t)||!t.every(e=>Number.isInteger(e)&&e>=0)))return"selection must list the positions of rows, whole numbers from 0."}function Me(t){const e=Mt("colorMapInterpolator",t.colorMapInterpolator,!1)??Mt("categoricalColorMapInterpolator",t.categoricalColorMapInterpolator,!0)??wt(t.colorMapRange,t.colorMapDomain)??Ee(t.tickFormats)??_e(t.axisLabels,t.axis)??ve(t.selection)??At("markColor",t.markColor)??At("highlightColor",t.highlightColor);if(e)throw new Error(`Plot "${A(t)}": ${e}`)}function Ae(t){const e={};for(const[o,r]of[["markColor","mark"],["highlightColor","highlight"]]){let n;for(const l of t){const a=l[o];if(a!==void 0){if(n&&n[o].toLowerCase()!==a.toLowerCase())throw new Error(`Plots "${A(n)}" and "${A(l)}" set different ${o} values, "${n[o]}" and "${a}": autk-plot draws every plot of a page in one ${r} color.`);n??=l}}n&&(e[o]=n[o])}return e}function Se(t,e){const o=t.selection?.find(r=>r>=e);if(o!==void 0)throw new Error(`Plot "${A(t)}": selection names row ${o}, but the plot draws ${e===1?"1 row":`${e} rows`}.`)}function Ce(t,e){return t===void 0||t==="@transform"?!1:e.some(o=>{const r=b.valueAtPath(o?.properties??{},t);return typeof r=="string"&&isNaN(Number(r))})}function Re(t,e){const o=t.colorMapRange;if(o!==void 0&&!Ce(t.color,e))return{type:b.ColorMapDomainStrategy.USER,params:[o[0],o[1]]};if(!(t.normalization===void 0&&t.colorMapDomain===void 0))return bt(t.normalization,t.colorMapDomain)}function Ie(t){return t.axis.map((e,o)=>t.axisLabels?.[o]??(e==="@transform"?"value":e))}function $e(t,e){const o=Re(t,e);return{labels:{axis:Ie(t),title:t.title},...t.colorMapInterpolator!==void 0&&{colorMapInterpolator:t.colorMapInterpolator},...t.categoricalColorMapInterpolator!==void 0&&{categoricalColorMapInterpolator:t.categoricalColorMapInterpolator},...o&&{domainSpec:o},...t.tickFormats!==void 0&&{tickFormats:[...t.tickFormats]}}}function Pe(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}let j;function Ne(t){t.markColor===void 0&&t.highlightColor===void 0&&!j||(j??={markColor:I.PlotStyle.default,highlightColor:I.PlotStyle.highlight},I.PlotStyle.setDefaultColor(t.markColor??j.markColor),I.PlotStyle.setHighlightColor(t.highlightColor??j.highlightColor))}function St(t,e,o,r){const{map:n,layerId:l}=r;n.updateRenderInfo(l,{isPick:!0}),n.events.on(F.MapEvent.PICKING,({layerId:a,selection:s})=>{a===l&&t.setSelection(B(s,r.rows,e))});for(const a of o)t.events.on(a,({selection:s})=>{n.setHighlightedIds(l,B(s,e,r.rows))})}async function Te(t,e,o,r,n){const l=t.getTablesMetadata().find(a=>a.name===e);return l&&!_.isRenderableTable(l)?{type:"FeatureCollection",features:(await t.getTable(e)).map(s=>({type:"Feature",geometry:null,properties:s}))}:pt(r,ft(o,n),()=>t.getLayer(e,dt(n)))}function Le(t,e,o,r,n,l,a,s){return{async resolvePlot(i,u,d=0){if(!t||!t.plot)return;const c=Array.isArray(t.plot)?t.plot[d]:t.plot;if(c===void 0)throw new Error(`Plot ${d} has no target: the plot targets name ${t.plot.length} elements.`);const f=document.getElementById(c);if(!f)throw new Error(`Could not find plot target: ${c}`);const m=i;if(!m)throw new Error("No data context available for plot.");await N(m,u.workspace);const h=v(u.workspace,u.dataRef),y=u.osmElements===!0?void 0:n?.get(h),p=l?.get(h)??y??await Te(m,u.dataRef,h,s,u.osmElements);Se(u,p.features?.length??0);const w=u.events??[],M=new I.AutkPlot(f,{type:Pe(u.mark),collection:p,attributes:{axis:u.axis,...u.color&&{color:u.color}},events:w,...$e(u,p.features??[]),...u.width&&{width:u.width},...u.height&&{height:u.height},...u.margins&&{margins:u.margins},...u.transform&&{transform:u.transform}});u.mark==="scatter"&&u.color!==void 0&&M.setSelection([]),o?.set(A(u),M);const C=nt(p.features??[]);a?.set(A(u),C);for(const L of e??[])!u.mapRef||L.dataRef!==u.mapRef||(St(M,C,w,L),ht(r,A(u),L))}}}const V=134217728,Oe=4,ke=32;function Ct(t){return Array.isArray(t)?t.join(`
2
+ `):t}function $(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function O(t,e){return t instanceof Map?t.get(e):t[e]}function G(t,e){return e.split(".").reduce((o,r)=>{if(!(o==null||typeof o!="object"))return o[r]},t)}function Rt(t){const e=[];for(const o of[t.uniforms,t.uniformMatrices])for(const r of Object.values(o??{}))$(r)&&e.push(r);return e}function It(t){return[...new Set([t.dataRef,...Rt(t).map(e=>e.fromFeature.layer)])]}function q(t){for(const e of Rt(t)){const{iterate:o,layer:r}=e.fromFeature;if(o==="all"||o==="batched")return{mode:o,layer:r}}return null}function $t(t,e,o){const r=t.fromFeature,n=o!==void 0&&r.iterate==="all"?o:r.index??0,l=O(e,r.layer)?.features?.[n];return l?G(l,r.path):void 0}function H(t,e,o){if(!t)return;const r={};for(const[n,l]of Object.entries(t)){if(!$(l)){r[n]=l;continue}const a=Number($t(l,e,o)??NaN);Number.isFinite(a)?r[n]=a:typeof l.default=="number"&&(r[n]=l.default)}return r}function J(t,e,o){if(!t)return;const r={};for(const[n,l]of Object.entries(t)){if(!$(l)){r[n]=l;continue}const a=$t(l,e,o),s=Array.isArray(a)?a:Array.isArray(l.default)?l.default:void 0;if(!s)continue;const i=l.cols??(Array.isArray(s[0])?s[0].length:0);i>0?r[n]={data:s,cols:i}:console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`)}return r}function Fe(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function Pt(t){return $(t)&&t.fromFeature.iterate==="batched"}function Nt(t,e){return Object.values(e??{}).some(Pt)?ke:Object.values(t??{}).some(Pt)?Oe:0}function Tt(t,e,o=V){const r=Nt(t,e);return r>0?Math.floor(o/r):Number.POSITIVE_INFINITY}function Lt(t,e,o,r=V){const n={},l={},a=[];for(const i of[t,e])for(const u of Object.values(i??{}))$(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&a.push(u.fromFeature.path);if(a.length>0){const i=o.length;o=o.filter(u=>a.every(d=>Fe(G(u,d)))),o.length<i&&console.info(`[autk-grammar] batched compute dropped ${i-o.length} feature(s) missing ${a.join(", ")}`)}const s=Tt(t,e,r);o.length>s&&(console.warn(`[autk-grammar] batched compute capped at ${s} features (got ${o.length}): its largest packed array takes ${Nt(t,e)} B per feature, and a storage buffer binding holds ${r} B`),o=o.slice(0,s));for(const[i,u]of Object.entries(t??{}))if($(u)&&u.fromFeature.iterate==="batched"){const d=typeof u.default=="number"?u.default:void 0;l[i]=o.map(c=>{const f=Number(G(c,u.fromFeature.path)??d);return Number.isFinite(f)?f:0})}else typeof u=="number"&&(n[i]=u);for(const[i,u]of Object.entries(e??{})){if(!$(u)||u.fromFeature.iterate!=="batched")continue;const d=[];for(const c of o){const f=G(c,u.fromFeature.path);let m=1/0,h=1/0,y=-1/0,p=-1/0;if(Array.isArray(f))for(const w of f){if(!Array.isArray(w)||w.length<2)continue;const M=Number(w[0]),C=Number(w[1]);!Number.isFinite(M)||!Number.isFinite(C)||(m=Math.min(m,M),h=Math.min(h,C),y=Math.max(y,M),p=Math.max(p,C))}Number.isFinite(m)||(m=0,h=0,y=0,p=0),d.push(m,h,y,h,y,p,m,p)}l[i]=d}return n.num_features=o.length,{uniforms:n,uniformArrays:l}}function K(t,e,o){const r=O(e,t.dataRef);if(!r)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n={collection:r,variableMapping:t.attributes,wgslBody:Ct(t.wgslFunction)};t.attributeArrays&&(n.attributeArrays=t.attributeArrays),t.attributeMatrices&&(n.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(n.uniformArrays=t.uniformArrays),t.outputColumnName&&(n.resultField=t.outputColumnName),t.outputColumns&&(n.outputColumns=t.outputColumns);const l=q(t);if(l?.mode==="batched"){const u=O(e,l.layer)?.features??[],d=Lt(t.uniforms,t.uniformMatrices,u),c=H(Ot(t.uniforms),e)??{},f=J(Ot(t.uniformMatrices),e);return n.uniforms={...c,...d.uniforms},n.uniformArrays={...n.uniformArrays??{},...d.uniformArrays},f&&Object.keys(f).length>0&&(n.uniformMatrices=f),n}const a=l?.mode==="all"?o:void 0,s=H(t.uniforms,e,a),i=J(t.uniformMatrices,e,a);return s&&(n.uniforms=s),i&&(n.uniformMatrices=i),n}function Ot(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!($(e)&&e.fromFeature.iterate==="batched")))}function Be(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function kt(t,e,o){const r=q(t);if(r?.mode!=="all")return o(K(t,e));const n=O(e,t.dataRef);if(!n)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const l=Be(t),a=structuredClone(n);for(const i of a.features){const u=i.properties??={},d=u.compute??={};for(const c of l)d[c]=0}const s=O(e,r.layer)?.features?.length??0;for(let i=0;i<s;i++){const u=await o({...K(t,e,i),collection:a});a.features.forEach((d,c)=>{const f=d.properties?.compute,m=u.features[c]?.properties?.compute;if(!(!f||!m))for(const h of l){const y=Number(m[h]);Number.isFinite(y)&&(f[h]+=y)}})}return a}const Ft=["surface","parks","water","roads","buildings","polygons","polylines"];function je(t,e,o,r){return r?.get(v(o,e))??t.getTablesMetadata().find(n=>n.name===e)?.type}function Bt(t,e,o){async function r(s,i,u){return t?.get(v(u,i))??await s.getLayer(i)}function n(s,i,u,d,c){if(!t)return;const f=d.outputTableName??u;t.set(v(d.workspace,f),i);const m=d.layerType??c??je(s,u,d.workspace,e);d.outputTableName&&m&&e?.set(v(d.workspace,f),m)}async function l(s,i){for(const c of i.layers)if(!Ft.includes(c.type))throw new Error(`Render pass "${i.outputTableName}": layer "${c.id}" has the type "${c.type}", which a render pass cannot draw. A layer's type is one of ${Ft.join(", ")}.`);const u=await Promise.all(i.layers.map(async c=>({id:c.id,collection:await r(s,c.dataRef,i.workspace),type:c.type,objectIdProperty:c.objectIdProperty}))),d=await new X.AutkComputeEngine().renderPipeline({layers:u,viewpoints:{collection:await r(s,i.viewpoints.dataRef,i.workspace),strategy:i.viewpoints.strategy,sampling:i.viewpoints.sampling},aggregation:i.aggregation,camera:i.camera,tileSize:i.tileSize});n(s,d,i.viewpoints.dataRef,i,i.viewpoints.strategy?.type==="building-windows"?"points":void 0)}async function a(s,i){const u={},d=s.getWorkspaceConfiguration().coordinateFormat;for(const m of It(i)){const h=v(i.workspace,m),y=t?.get(h)??(m===i.dataRef?void 0:Jt(o?.get(h),d));if(y)u[m]=y;else if(m===i.dataRef)u[m]=await s.getLayer(m);else try{u[m]=await s.getLayer(m)}catch{u[m]=void 0}}const c=new X.AutkComputeEngine,f=await kt(i,u,m=>c.gpgpuPipeline(m));n(s,f,i.dataRef,i)}return{async resolveCompute(s,i){if(s)return await N(s,i.workspace),i.type==="render"?await l(s,i):await a(s,i),s}}}class jt{_listeners=new Map;on(e,o){this._listeners.has(e)||this._listeners.set(e,new Set);const r=this._listeners.get(e);return r.add(o),()=>r.delete(o)}emit(e,o){this._listeners.get(e)?.forEach(r=>r(o))}}function S(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Ge(t){const e=new Set;for(const r of[...S(t.map),...S(t.plot)])if(r.id!==void 0){if(r.id==="")throw new Error("A map or plot has an empty id.");if(e.has(r.id))throw new Error(`Two maps or plots have the id "${r.id}"; an id names one view.`);e.add(r.id)}const o=new Map;for(const r of S(t.plot)){const n=A(r),l=o.get(n);if(l)throw new Error(l.id===void 0&&r.id===void 0?`Two plots of the table "${n}" have no id; give each plot an id.`:`A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);o.set(n,r)}}class De{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_computeTypes=new Map;_data={};_layers=[];_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotLinks=new Map;_plotRows=new Map;_exports=new Map;_geojsonCache=new Map;interactions=new jt;constructor(e){this.dataAdapter=ct(e,this._geojsonCache),this.mapAdapter=ge(e,this._layers,this._computeCache,this._maps,this._computeTypes,this._exports),this.plotAdapter=Le(e,this._layers,this._plotRegistry,this._plotLinks,this._geojsonCache,this._computeCache,this._plotRows,this._exports),this.computeAdapter=Bt(this._computeCache,this._computeTypes,this._geojsonCache)}get workspaceCrs(){return _.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayers(e,o){return this._layersOf(e,o).map(({map:r,layerId:n})=>({map:r,layerId:n}))}mapLayer(e,o){return this.mapLayers(e,o).pop()}_layersOf(e,o){return this._layers.filter(r=>r.dataRef===e&&Q(r,o))}destroy(){for(const e of this._fwdCleanups)e();this._fwdCleanups=[];for(const e of this._maps)e.destroy();this._maps.length=0,this._layers.length=0,this._plotRegistry.clear(),this._plotLinks.clear(),this._plotRows.clear(),this._exports.clear(),this._geojsonCache.clear(),this._computeCache.clear(),this._computeTypes.clear(),this.grammarEngine=void 0,this._data={}}async run(e){if(!this.dataAdapter)throw new Error("Database adapter not initialized. Please call the constructor first.");if(!this.mapAdapter)throw new Error("Map engine not initialized. Please call the constructor first.");if(!this.plotAdapter)throw new Error("Plot adapter not initialized. Please call the constructor first.");if(!this.computeAdapter)throw new Error("Compute adapter not initialized. Please call the constructor first.");Ge(e);for(const l of S(e.plot))Me(l);const o=Ae(S(e.plot));this.destroy(),S(e.plot).length>0&&Ne(o),this.grammarEngine=Z({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run();const r=this.grammarEngine.context;if(r&&await N(r),this._wireLinks(e),this._selectFromTheStart(e),this._rewireInteractions(e),!r){console.warn("Grammar engine produced no data context."),this._data={};return}const n={};for(const l of r.getLayersMetadata())Object.defineProperty(n,l.name,{get:()=>{const a=this._computeCache.get(l.name);return a?Promise.resolve(a):r.getLayer(l.name)},enumerable:!0,configurable:!0});for(const l of this._computeCache.keys())l in n||Object.defineProperty(n,l,{get:()=>Promise.resolve(this._computeCache.get(l)),enumerable:!0,configurable:!0});this._data=n}highlightOnMap(e,o,r){const n=this._layersOf(e,r);for(const{map:l,layerId:a}of n)l.setHighlightedIds(a,o);this._selectInLinkedPlots(n,o)}clearHighlightOnMap(e,o){const r=this._layersOf(e,o);for(const{map:n,layerId:l}of r)n.clearHighlightedIds(l);this._selectInLinkedPlots(r,[])}clearHighlightOnPlot(e,o){this._plotRegistry.get(e)?.setSelection([]);for(const r of this._plotLinks.get(e)??[])Q(r,o)&&r.map.clearHighlightedIds(r.layerId)}setPlotSelection(e,o,r){this._plotRegistry.get(e)?.setSelection(o);const n=this._plotRows.get(e)??[];for(const l of this._plotLinks.get(e)??[])Q(l,r)&&l.map.setHighlightedIds(l.layerId,B(o,n,l.rows))}_selectInLinkedPlots(e,o){for(const[r,n]of this._plotLinks){const l=n.filter(i=>e.includes(i));if(l.length===0)continue;const a=this._plotRows.get(r)??[],s=new Set(l.flatMap(i=>B(o,i.rows,a)));this._plotRegistry.get(r)?.setSelection([...s])}}_wireLinks(e){const o=S(e.map),r=S(e.plot);for(const n of e.links??[]){const l=r.find(c=>A(c)===n.source),a=this._plotRegistry.get(n.source);if(!l||!a)throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);const s=o.findIndex(c=>c.id===n.target),i=this._maps[s];if(s<0||!i)throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);const u=o[s].layerRefs.find(c=>n.layer!==void 0?T(c)===n.layer:c.dataRef===l.dataRef);if(!u)throw new Error(n.layer!==void 0?`Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".`:`Link from "${n.source}": map "${n.target}" draws no layer of the table "${l.dataRef}"; name the layer.`);const d=this._layers.find(c=>c.mapIndex===s&&c.layerId===T(u));d&&(St(a,this._plotRows.get(n.source)??[],l.events??[],d),ht(this._plotLinks,n.source,d))}}_selectFromTheStart(e){for(const o of S(e.plot))o.selection&&o.selection.length>0&&this.setPlotSelection(A(o),o.selection)}_rewireInteractions(e){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const o=S(e.map);this._maps.forEach((r,n)=>{const l=mt(o[n],n),a=({layerId:s,selection:i})=>{this.interactions.emit("map:picking",{mapId:l,layerId:s,selection:i})};r.events.on(F.MapEvent.PICKING,a),this._fwdCleanups.push(()=>r.events.off(F.MapEvent.PICKING,a))});for(const[r,n]of this._plotRegistry)for(const l of[I.PlotEvent.CLICK,I.PlotEvent.BRUSH,I.PlotEvent.BRUSH_X,I.PlotEvent.BRUSH_Y]){const a=({selection:s})=>{this.interactions.emit("plot:selection",{plotId:r,event:l,selection:s})};n.events.on(l,a),this._fwdCleanups.push(()=>n.events.off(l,a))}}}g.AutkGrammar=De,g.ColorMapInterpolator=et,g.GrammarEventEmitter=jt,g.NormalizationMode=U,g.STORAGE_BUFFER_BINDING_SIZE=V,g.applyCamera=vt,g.arrangeViews=qt,g.buildBatchedUniforms=Lt,g.computeLayerNames=It,g.createComputeAdapter=Bt,g.createDataAdapter=ct,g.createEngine=Z,g.enterWorkspace=N,g.findIterateSource=q,g.isFromFeature=$,g.joinWgsl=Ct,g.maxBatchedFeatures=Tt,g.resolveComputeParams=K,g.resolveUniformMatrices=J,g.resolveUniforms=H,g.runCompute=kt,g.tableKey=v,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
3
3
  //# sourceMappingURL=autk-grammar.umd.cjs.map