@urban-toolkit/autk-grammar 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"autk-grammar.umd.cjs","sources":["../../../grammar/dist/the-urban-grammar.js","../src/adapters/data.ts","../src/adapters/map.ts","../src/adapters/plot.ts","../src/adapters/compute.ts","../src/types.ts","../src/main.ts"],"sourcesContent":["function m(e) {\n const { spec: _, adapters: S } = e;\n let t;\n async function s() {\n let E;\n if (_.data)\n for (const i of _.data)\n E = await S.db.resolveSource(E, i);\n if (_.compute)\n for (const i of _.compute)\n E = await S.compute.resolveCompute(E, i);\n if (_.map)\n if (Array.isArray(_.map))\n for (let i = 0; i < _.map.length; i++) {\n let u = _.map[i];\n await S.map.resolveMap(E, u, i);\n }\n else\n await S.map.resolveMap(E, _.map);\n if (_.plot)\n if (Array.isArray(_.plot))\n for (const i of _.plot)\n await S.plot.resolvePlot(E, i);\n else\n await S.plot.resolvePlot(E, _.plot);\n t = E;\n }\n function R(E) {\n return console.log(\"Spec to update\", E), new Promise((i) => {\n i();\n });\n }\n function c() {\n console.log(\"Function not implemented yet\");\n }\n return { run: s, updatedSpec: R, destroy: c, get context() {\n return t;\n } };\n}\nvar n = /* @__PURE__ */ ((e) => (e.CAT_ACCENT = \"schemeAccent\", e.CAT_DARK2 = \"schemeDark2\", e.CAT_CATEGORY10 = \"schemeCategory10\", e.CAT_OBSERVABLE10 = \"schemeObservable10\", e.CAT_PAIRED = \"schemePaired\", e.CAT_PASTEL1 = \"schemePastel1\", e.CAT_PASTEL2 = \"schemePastel2\", e.CAT_SET1 = \"schemeSet1\", e.CAT_SET2 = \"schemeSet2\", e.CAT_SET3 = \"schemeSet3\", e.CAT_TABLEAU10 = \"schemeTableau10\", e.SEQ_REDS = \"interpolateReds\", e.SEQ_BLUES = \"interpolateBlues\", e.SEQ_GREENS = \"interpolateGreens\", e.SEQ_GREYS = \"interpolateGreys\", e.SEQ_ORANGES = \"interpolateOranges\", e.SEQ_PURPLES = \"interpolatePurples\", e.SEQ_TURBO = \"interpolateTurbo\", e.SEQ_VIRIDIS = \"interpolateViridis\", e.SEQ_INFERNO = \"interpolateInferno\", e.SEQ_MAGMA = \"interpolateMagma\", e.SEQ_PLASMA = \"interpolatePlasma\", e.SEQ_CIVIDIS = \"interpolateCividis\", e.SEQ_WARM = \"interpolateWarm\", e.SEQ_COOL = \"interpolateCool\", e.SEQ_BU_GN = \"interpolateBuGn\", e.SEQ_BU_PU = \"interpolateBuPu\", e.SEQ_GN_BU = \"interpolateGnBu\", e.SEQ_OR_RD = \"interpolateOrRd\", e.SEQ_PU_BU = \"interpolatePuBu\", e.SEQ_PU_RD = \"interpolatePuRd\", e.SEQ_RD_PU = \"interpolateRdPu\", e.SEQ_YL_GN = \"interpolateYlGn\", e.SEQ_YL_OR_BR = \"interpolateYlOrBr\", e.SEQ_YL_OR_RD = \"interpolateYlOrRd\", e.DIV_BR_BG = \"interpolateBrBG\", e.DIV_PR_GN = \"interpolatePRGn\", e.DIV_PI_YG = \"interpolatePiYG\", e.DIV_PU_OR = \"interpolatePuOr\", e.DIV_RED_BLUE = \"interpolateRdBu\", e.DIV_RED_GREY = \"interpolateRdGy\", e.DIV_RED_YELLOW_BLUE = \"interpolateRdYlBu\", e.DIV_RED_YELLOW_GREEN = \"interpolateRdYlGn\", e.DIV_SPECTRAL = \"interpolateSpectral\", e))(n || {}), A = /* @__PURE__ */ ((e) => (e.MIN_MAX = \"minMax\", e.PERCENTILE = \"percentile\", e))(A || {});\nexport {\n n as ColorMapInterpolator,\n A as NormalizationMode,\n m as createEngine\n};\n//# sourceMappingURL=the-urban-grammar.js.map\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect\n * `autoLoadLayers` and no longer take `dropOsmTable`.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n return { ...rest, autoLoadLayers: { layers: autoLoadLayers?.layers ?? [] } };\n}\n\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n return {\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb | undefined> {\n\n let db = context;\n\n if(!db){\n db = new AutkDb();\n await db.init();\n }\n\n let {type, ...rest_spec} = spec;\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 geojsonData = geojsonSpec.geojsonObject;\n }\n\n if (cache && geojsonData) cache.set(geojsonSpec.outputTableName, geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch\n const loadSpec = geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: geojsonData }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec;\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n const crsHint = loadSpec.coordinateFormat\n ? `coordinateFormat is set to \"${loadSpec.coordinateFormat}\"`\n : `no coordinateFormat was specified — defaulting to EPSG:4326 (WGS84 per RFC 7946)`;\n throw new Error(\n `Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}. ` +\n `${crsHint}. Verify that coordinateFormat matches the actual CRS of the input data.`\n );\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for DEFAULT_WORKSPACE_COORDINATE_FORMAT (EPSG:3395)\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `Verify that coordinateFormat matches the actual CRS of the input data. ` +\n `The workspace uses ${DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.) — skip validation\n }\n print(db, targets);\n return db;\n }\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n await db.buildHeatmap({\n tableJoinName: hm.tableJoinName,\n near: { distance: hm.near.distance },\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy as any }),\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.tableRootName,\n tableJoinName: jn.tableJoinName,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.tableRootName);\n cache.set(jn.tableRootName, updated);\n }\n print(db, targets);\n return db;\n }\n default:\n return\n }\n }\n }\n}\n","import { MapAdapter, MapSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, ComputeCache } from '../types';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport { ColorMapDomainStrategy } from '@urban-toolkit/autk-core';\nimport type { ColorMapConfig, ColorMapDomainSpec, LayerType } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\n\nfunction buildDomainSpec(\n normalization: MapSpec['layerRefs'][number]['normalization'],\n colorMapDomain?: string[],\n): ColorMapDomainSpec {\n if (colorMapDomain && colorMapDomain.length > 0)\n return { type: ColorMapDomainStrategy.USER, params: colorMapDomain };\n if (normalization?.mode === NormalizationMode.PERCENTILE) {\n const hasExplicitBounds =\n normalization.lowerPercentile !== undefined || normalization.upperPercentile !== undefined;\n if (hasExplicitBounds)\n return {\n type: ColorMapDomainStrategy.PERCENTILE,\n params: [normalization.lowerPercentile ?? 0, normalization.upperPercentile ?? 100],\n };\n return { type: ColorMapDomainStrategy.PERCENTILE };\n }\n return { type: ColorMapDomainStrategy.MIN_MAX };\n}\n\nfunction valueAtPath(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, obj);\n}\n\nfunction setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> {\n const keys = path.split('.');\n const result = { ...obj };\n let current = result as Record<string, unknown>;\n for (let i = 0; i < keys.length - 1; i++) {\n current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown> ?? {}) };\n current = current[keys[i]] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n return result;\n}\n\n/**\n * Resolves a grammar value path such as `count.noise` to the raster band that holds it.\n * autk-db stores heatmap values in bands (`band_1`, ...) labelled `<aggregateFn>_<table>`.\n */\nfunction rasterBand(collection: { features?: { properties?: unknown }[] }, getFnv?: string): string {\n const props = collection.features?.[0]?.properties as { bands?: { id: string; label?: string }[] } | undefined;\n const bands = props?.bands ?? [];\n const band = bands.find((b) => b.id === getFnv || b.label === getFnv?.replace(/\\./g, '_'));\n return band?.id ?? bands[0]?.id ?? getFnv ?? '';\n}\n\nexport function createMapAdapter(targets?: Targets, registry?: MapRegistry, computeCache?: ComputeCache): MapAdapter {\n\n async function loadLayers(map: AutkMap, context: AutkDb, spec: MapSpec): Promise<void> {\n let tableToTypeMap: {[tableName: string]: string} = {};\n for(const table of context.getTablesMetadata()) {\n if(table.type !== undefined) tableToTypeMap[table.name] = table.type;\n }\n\n for(const layerRef of spec.layerRefs){\n const name = layerRef.dataRef;\n const type = tableToTypeMap[name] as LayerType;\n const getFnv = layerRef.getFnv;\n\n const rawData = computeCache?.get(name) ?? await context.getLayer(name);\n // Raster tables (e.g. heatmaps) are a single feature with no geometry, so keep them as-is.\n const data = type === 'raster' ? rawData : {\n ...rawData,\n features: (rawData.features ?? []).filter((f: any) => f.geometry != null),\n };\n\n if(type === 'raster') {\n map.loadCollection(name, { collection: data, type: 'raster', property: rasterBand(data, getFnv) });\n } else {\n map.loadCollection(name, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(name, { opacity: layerRef.opacity });\n\n // Enable the colormap by default for thematic (getFnv) vector layers so\n // autk-grammar maps render coloured-by-value out of the box. autk-map\n // attaches a default colour ramp to every layer, so this works even when\n // the spec omits colorMapInterpolator. Callers can still opt out by\n // setting isColorMap: false explicitly. Raster layers manage their own ramp.\n const enableColorMap = layerRef.isColorMap ?? (getFnv != null && type !== 'raster');\n if(enableColorMap)\n map.updateRenderInfo(name, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(name, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(name, { isSkip: true });\n\n // When catchAllCategory is set, remap features whose property value is not\n // in colorMapDomain to the catch-all label, and extend the domain to include it.\n const { catchAllCategory, colorMapDomain } = layerRef;\n let thematicData = data;\n let effectiveDomain = colorMapDomain;\n\n if(getFnv && catchAllCategory && colorMapDomain?.length) {\n const allowed = new Set(colorMapDomain);\n thematicData = {\n ...data,\n features: data.features.map((f: any) => {\n const props = f.properties as Record<string, unknown>;\n const val = valueAtPath(props, getFnv);\n if(val === undefined || val === null || !allowed.has(String(val))) {\n return { ...f, properties: setValueAtPath(props, getFnv, catchAllCategory) };\n }\n return f;\n }),\n };\n effectiveDomain = allowed.has(catchAllCategory)\n ? colorMapDomain\n : [...colorMapDomain, catchAllCategory];\n }\n\n if(layerRef.colorMapInterpolator) {\n const colormapConfig: ColorMapConfig = {\n // urban-grammar ColorMapInterpolator values are string-compatible\n // with autk-core ColorMapInterpolator at runtime\n interpolator: layerRef.colorMapInterpolator as unknown as ColorMapConfig['interpolator'],\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n map.updateRenderInfo(name, { colormap: { config: colormapConfig }, isColorMap: true });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(name, { collection: thematicData, property });\n }\n }\n }\n\n return {\n async resolveMap(context: AutkDb | undefined, spec: MapSpec, index: number = 0): Promise<void> {\n if(targets && targets.map && context){\n\n let canvas;\n\n if(Array.isArray(targets.map)){\n canvas = document.getElementById(targets.map[index]);\n }else{\n canvas = document.getElementById(targets.map);\n }\n\n if(!canvas)\n throw new Error(\"Could not find rendering target for map: \"+targets.map);\n\n if(!(canvas instanceof HTMLCanvasElement))\n throw new Error(\"Target for map is not a canvas: \"+targets.map);\n\n const map = new AutkMap(canvas);\n\n if(spec.style)\n map.style.setPredefinedStyle(spec.style)\n\n await map.init();\n await loadLayers(map, context, spec);\n\n if(registry)\n for(const layerRef of spec.layerRefs)\n registry.set(layerRef.dataRef, map);\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, PlotRegistry, PlotMapLinks, GeoJsonCache } from '../types';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkPlot, PlotEvent as AutkPlotEvent } from '@urban-toolkit/autk-plot';\nimport type { PlotEventData, PlotType, PlotTransformConfig } from '@urban-toolkit/autk-plot';\nimport { AutkMap, MapEvent } from '@urban-toolkit/autk-map';\nimport type { MapEventData } from '@urban-toolkit/autk-map';\nimport { FeatureCollection } from 'geojson';\n\n// autk-map 3 publishes MapEventData extending a type its .d.ts cannot resolve\n// (the import points at ../../autk-core/src), so `selection` is invisible here.\ntype MapSelection = MapEventData & { selection: number[] };\n\nfunction grammarMarkToPlotType(mark: PlotMark): PlotType {\n const mapping: Record<PlotMark, PlotType> = {\n 'scatter': 'scatterplot',\n 'bar': 'barchart',\n 'line': 'linechart',\n 'linechart': 'linechart',\n 'parallel-coordinates': 'parallel-coordinates',\n 'table': 'table',\n 'heatmatrix': 'heatmatrix',\n };\n return mapping[mark];\n}\n\nexport function createPlotAdapter(targets?: Targets, registry?: MapRegistry, plotRegistry?: PlotRegistry, plotMapLinks?: PlotMapLinks, cache?: GeoJsonCache): PlotAdapter {\n\n return {\n async resolvePlot(context: unknown, spec: PlotSpec): Promise<void> {\n if(!targets || !targets.plot) return;\n\n const div = document.getElementById(targets.plot);\n if(!div) throw new Error(`Could not find plot target: ${targets.plot}`);\n\n const db = context as AutkDb | undefined;\n if(!db) throw new Error('No data context available for plot.');\n\n const geojson: FeatureCollection = cache?.get(spec.dataRef) ?? await db.getLayer(spec.dataRef);\n\n const events = (spec.events ?? []) as unknown as AutkPlotEvent[];\n\n const plot = new AutkPlot(div, {\n type: grammarMarkToPlotType(spec.mark),\n collection: geojson,\n attributes: { axis: spec.axis, ...(spec.color && { color: spec.color }) },\n labels: { axis: spec.axis, title: spec.title },\n events,\n ...(spec.width && { width: spec.width }),\n ...(spec.height && { height: spec.height }),\n ...(spec.margins && { margins: spec.margins }),\n ...(spec.transform && { transform: spec.transform as PlotTransformConfig }),\n });\n\n plotRegistry?.set(spec.dataRef, plot);\n if (spec.mapRef) plotMapLinks?.set(spec.dataRef, spec.mapRef);\n\n // Wire map ↔ plot events if a mapRef is specified\n if(spec.mapRef && registry) {\n const map: AutkMap | undefined = registry.get(spec.mapRef);\n\n if(map) {\n map.updateRenderInfo(spec.mapRef, { isPick: true });\n\n map.events.on(MapEvent.PICKING, ({ selection }: MapSelection) => {\n plot.setSelection(selection);\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(spec.mapRef!, selection);\n });\n }\n }\n }\n }\n }\n}\n","import { ComputeAdapter, ComputeSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkComputeEngine } from '@urban-toolkit/autk-compute';\nimport { FeatureCollection } from 'geojson';\nimport { ComputeCache } from '../types';\n\nexport function createComputeAdapter(cache?: ComputeCache): ComputeAdapter {\n\n return {\n async resolveCompute(context: AutkDb | undefined, spec: ComputeSpec): Promise<AutkDb | undefined> {\n if(context){\n const geojson: FeatureCollection = await context.getLayer(spec.dataRef);\n const engine = new AutkComputeEngine();\n\n const result = await engine.gpgpuPipeline({\n collection: geojson,\n variableMapping: spec.attributes,\n wgslBody: spec.wglsFunction,\n ...(spec.outputColumnName && { resultField: spec.outputColumnName }),\n ...(spec.outputColumns && { outputColumns: spec.outputColumns }),\n ...(spec.attributeArrays && { attributeArrays: spec.attributeArrays }),\n ...(spec.attributeMatrices && { attributeMatrices: spec.attributeMatrices }),\n ...(spec.uniforms && { uniforms: spec.uniforms }),\n ...(spec.uniformArrays && { uniformArrays: spec.uniformArrays }),\n ...(spec.uniformMatrices && { uniformMatrices: spec.uniformMatrices }),\n });\n\n if (cache) cache.set(spec.dataRef, result);\n\n return context;\n }\n }\n }\n}\n","import type { UrbanSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { AutkPlot } from '@urban-toolkit/autk-plot';\nimport type { FeatureCollection } from 'geojson';\n\nexport type Targets = {\n compute?: string,\n db?: string,\n map?: string[] | string,\n plot?: string\n}\n\nexport type MapRegistry = Map<string, AutkMap>;\nexport type PlotRegistry = Map<string, AutkPlot>;\nexport type PlotMapLinks = Map<string, string>; // plotId (dataRef) → mapRef (layerId)\nexport type GeoJsonCache = Map<string, FeatureCollection>;\nexport type ComputeCache = Map<string, FeatureCollection>;\n\nexport type AutkGrammarSpec = UrbanSpec;\n\n// Grammar-level interaction payloads — no autk internals leak through the public API\nexport interface GrammarPickingEvent {\n layerId: string;\n selection: number[];\n}\n\nexport interface GrammarPlotSelectionEvent {\n plotId: string;\n event: 'click' | 'brush' | 'brushX' | 'brushY';\n selection: number[];\n}\n\nexport type GrammarEventRecord = {\n 'map:picking': GrammarPickingEvent;\n 'plot:selection': GrammarPlotSelectionEvent;\n};\n\n// Self-contained typed emitter — does not import from autk packages\nexport class GrammarEventEmitter {\n private _listeners: Map<string, Set<(p: unknown) => void>> = new Map();\n\n on<K extends keyof GrammarEventRecord>(\n event: K,\n listener: (payload: GrammarEventRecord[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n const bucket = this._listeners.get(event)!;\n bucket.add(listener as (p: unknown) => void);\n return () => bucket.delete(listener as (p: unknown) => void);\n }\n\n /** @internal */\n emit<K extends keyof GrammarEventRecord>(event: K, payload: GrammarEventRecord[K]): void {\n this._listeners.get(event)?.forEach(l => l(payload));\n }\n}\n\n","import { DataAdapter, MapAdapter, PlotAdapter, ComputeAdapter, IEngine, UrbanSpec, createEngine } from \"@urban-toolkit/the-urban-grammar\";\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from \"@urban-toolkit/autk-db\";\nimport { MapEvent } from \"@urban-toolkit/autk-map\";\nimport type { AutkMap } from \"@urban-toolkit/autk-map\";\nimport type { MapEventData } from \"@urban-toolkit/autk-map\";\nimport { PlotEvent } from \"@urban-toolkit/autk-plot\";\nimport type { PlotEventData } from \"@urban-toolkit/autk-plot\";\nimport { FeatureCollection } from \"geojson\";\nimport { createDataAdapter } from \"./adapters/data\";\nimport { createMapAdapter } from \"./adapters/map\";\nimport { createPlotAdapter } from \"./adapters/plot\";\nimport { createComputeAdapter } from \"./adapters/compute\";\nimport { Targets, MapRegistry, PlotRegistry, PlotMapLinks, GeoJsonCache, ComputeCache, GrammarEventEmitter } from \"./types\";\nimport type { GrammarPlotSelectionEvent } from \"./types\";\n\n// autk-map 3 publishes MapEventData extending a type its .d.ts cannot resolve\n// (the import points at ../../autk-core/src), so `selection` is invisible here.\ntype MapSelection = MapEventData & { selection: number[] };\n\nexport class AutkGrammar {\n private dataAdapter?: DataAdapter;\n private mapAdapter?: MapAdapter;\n private plotAdapter?: PlotAdapter;\n private computeAdapter?: ComputeAdapter;\n private grammarEngine?: IEngine;\n private _computeCache: ComputeCache = new Map();\n private _data: Record<string, Promise<FeatureCollection>> = {};\n private _mapRegistry: MapRegistry = new Map();\n private _plotRegistry: PlotRegistry = new Map();\n private _fwdCleanups: Array<() => void> = [];\n private _plotMapLinks: PlotMapLinks = new Map();\n\n readonly interactions = new GrammarEventEmitter();\n\n constructor(targets?: Targets) {\n const cache: GeoJsonCache = new Map();\n this.dataAdapter = createDataAdapter(targets, cache);\n this.mapAdapter = createMapAdapter(targets, this._mapRegistry, this._computeCache);\n this.plotAdapter = createPlotAdapter(targets, this._mapRegistry, this._plotRegistry, this._plotMapLinks, cache);\n this.computeAdapter = createComputeAdapter(this._computeCache);\n }\n\n /**\n * The coordinate reference system used internally by the autk workspace.\n *\n * Input data is expected in EPSG:4326 (WGS84) by default and is transformed\n * to this CRS on load. Consumers that prepare data for injection (e.g. by\n * serialising a GeoDataFrame) can read this value and reproject accordingly\n * instead of hard-coding a CRS string.\n */\n get workspaceCrs(): string {\n return DEFAULT_WORKSPACE_COORDINATE_FORMAT;\n }\n\n get data(): Record<string, Promise<FeatureCollection>> {\n return this._data;\n }\n\n async run(spec: UrbanSpec) {\n if(!this.dataAdapter)\n throw new Error('Database adapter not initialized. Please call the constructor first.');\n\n if(!this.mapAdapter)\n throw new Error('Map engine not initialized. Please call the constructor first.');\n\n if(!this.plotAdapter)\n throw new Error('Plot adapter not initialized. Please call the constructor first.');\n\n if(!this.computeAdapter)\n throw new Error('Compute adapter not initialized. Please call the constructor first.');\n\n this._mapRegistry.clear();\n this._plotRegistry.clear();\n this._plotMapLinks.clear();\n\n this.grammarEngine = createEngine({\n spec,\n adapters: {\n db: this.dataAdapter,\n map: this.mapAdapter,\n plot: this.plotAdapter,\n compute: this.computeAdapter\n }\n });\n\n await this.grammarEngine.run();\n this._rewireInteractions();\n\n const db = this.grammarEngine.context as AutkDb | undefined;\n if (!db) {\n console.warn('Grammar engine produced no data context.');\n this._data = {};\n return;\n }\n\n const dataObj: Record<string, Promise<FeatureCollection>> = {};\n for (const table of db.getLayersMetadata()) {\n Object.defineProperty(dataObj, table.name, {\n get: () => {\n const computed = this._computeCache.get(table.name);\n return computed ? Promise.resolve(computed) : db.getLayer(table.name);\n },\n enumerable: true,\n configurable: true,\n });\n }\n this._data = dataObj;\n }\n\n /**\n * Highlights features on the map layer identified by `layerId`.\n * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.\n */\n highlightOnMap(layerId: string, featureIds: number[]): void {\n this._mapRegistry.get(layerId)?.setHighlightedIds(layerId, featureIds);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === layerId) this._plotRegistry.get(plotId)?.setSelection(featureIds);\n }\n }\n\n /**\n * Clears highlighted features on the map layer identified by `layerId`.\n * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.\n */\n clearHighlightOnMap(layerId: string): void {\n this._mapRegistry.get(layerId)?.clearHighlightedIds(layerId);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === layerId) this._plotRegistry.get(plotId)?.setSelection([]);\n }\n }\n\n /**\n * Clears the selection on the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is cleared too.\n */\n clearHighlightOnPlot(plotId: string): void {\n this._plotRegistry.get(plotId)?.setSelection([]);\n const mapRef = this._plotMapLinks.get(plotId);\n if (mapRef) this._mapRegistry.get(mapRef)?.clearHighlightedIds(mapRef);\n }\n\n /**\n * Applies a selection to the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is updated too.\n */\n setPlotSelection(plotId: string, featureIds: number[]): void {\n this._plotRegistry.get(plotId)?.setSelection(featureIds);\n const mapRef = this._plotMapLinks.get(plotId);\n if (mapRef) this._mapRegistry.get(mapRef)?.setHighlightedIds(mapRef, featureIds);\n }\n\n private _rewireInteractions(): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n\n // Wire each unique map → grammar bus\n // Multiple layerRefs can share one AutkMap instance; deduplicate to avoid double-subscription\n const seenMaps = new Set<AutkMap>();\n for (const [layerId, map] of this._mapRegistry) {\n if (seenMaps.has(map)) continue;\n seenMaps.add(map);\n const handler = ({ selection }: MapSelection) => {\n this.interactions.emit('map:picking', { layerId, selection });\n };\n map.events.on(MapEvent.PICKING, handler);\n this._fwdCleanups.push(() => map.events.off(MapEvent.PICKING, handler));\n }\n\n // Wire each plot → grammar bus (all four event types)\n for (const [plotId, plot] of this._plotRegistry) {\n for (const ev of [PlotEvent.CLICK, PlotEvent.BRUSH, PlotEvent.BRUSH_X, PlotEvent.BRUSH_Y] as const) {\n const handler = ({ selection }: PlotEventData) => {\n this.interactions.emit('plot:selection', {\n plotId,\n event: ev as GrammarPlotSelectionEvent['event'],\n selection,\n });\n };\n plot.events.on(ev, handler);\n this._fwdCleanups.push(() => plot.events.off(ev, handler));\n }\n }\n }\n}\n"],"names":["m","e","_","S","t","E","i","R","c","n","A","toLoadOsmParams","spec","autoLoadLayers","rest","createDataAdapter","targets","cache","print","db","div","tables","table","context","AutkDb","type","rest_spec","geojsonSpec","geojsonData","loadSpec","s","err","crsHint","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","jn","updated","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","key","setValueAtPath","value","keys","result","current","rasterBand","collection","getFnv","bands","b","createMapAdapter","registry","computeCache","loadLayers","map","tableToTypeMap","layerRef","name","rawData","data","f","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","colormapConfig","property","index","canvas","AutkMap","grammarMarkToPlotType","mark","createPlotAdapter","plotRegistry","plotMapLinks","geojson","events","plot","AutkPlot","MapEvent","selection","event","createComputeAdapter","AutkComputeEngine","GrammarEventEmitter","listener","bucket","payload","l","AutkGrammar","createEngine","dataObj","computed","layerId","featureIds","plotId","mapRef","cleanup","seenMaps","handler","ev","PlotEvent"],"mappings":"omBAAA,SAASA,EAAEC,EAAG,CACZ,KAAM,CAAE,KAAMC,EAAG,SAAUC,CAAC,EAAKF,EACjC,IAAIG,EACJ,eAAe,GAAI,CACjB,IAAIC,EACJ,GAAIH,EAAE,KACJ,UAAWI,KAAKJ,EAAE,KAChBG,EAAI,MAAMF,EAAE,GAAG,cAAcE,EAAGC,CAAC,EACrC,GAAIJ,EAAE,QACJ,UAAWI,KAAKJ,EAAE,QAChBG,EAAI,MAAMF,EAAE,QAAQ,eAAeE,EAAGC,CAAC,EAC3C,GAAIJ,EAAE,IACJ,GAAI,MAAM,QAAQA,EAAE,GAAG,EACrB,QAASI,EAAI,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pB,MAAMC,MAAe,IACrB,SAAW,CAACL,EAASzC,CAAG,IAAK,KAAK,aAAc,CAC5C,GAAI8C,EAAS,IAAI9C,CAAG,EAAG,SACvB8C,EAAS,IAAI9C,CAAG,EAChB,MAAM+C,EAAU,CAAC,CAAE,UAAAnB,KAA8B,CAC7C,KAAK,aAAa,KAAK,cAAe,CAAE,QAAAa,EAAS,UAAAb,EAAW,CAChE,EACA5B,EAAI,OAAO,GAAG2B,EAAAA,SAAS,QAASoB,CAAO,EACvC,KAAK,aAAa,KAAK,IAAM/C,EAAI,OAAO,IAAI2B,EAAAA,SAAS,QAASoB,CAAO,CAAC,CAC1E,CAGA,SAAW,CAACJ,EAAQlB,CAAI,IAAK,KAAK,cAC9B,UAAWuB,IAAM,CAACC,EAAAA,UAAU,MAAOA,EAAAA,UAAU,MAAOA,YAAU,QAASA,EAAAA,UAAU,OAAO,EAAY,CAChG,MAAMF,EAAU,CAAC,CAAE,UAAAnB,KAA+B,CAC9C,KAAK,aAAa,KAAK,iBAAkB,CACrC,OAAAe,EACA,MAAOK,EACP,UAAApB,CAAA,CACH,CACL,EACAH,EAAK,OAAO,GAAGuB,EAAID,CAAO,EAC1B,KAAK,aAAa,KAAK,IAAMtB,EAAK,OAAO,IAAIuB,EAAID,CAAO,CAAC,CAC7D,CAER,CACJ"}
1
+ {"version":3,"file":"autk-grammar.umd.cjs","sources":["../../../grammar/dist/the-urban-grammar.js","../src/adapters/data.ts","../src/adapters/map.ts","../src/adapters/plot.ts","../src/compute-params.ts","../src/adapters/compute.ts","../src/types.ts","../src/main.ts"],"sourcesContent":["function P(e) {\n const { spec: _, adapters: S } = e;\n let t;\n async function s() {\n let E;\n if (_.data)\n for (const i of _.data)\n E = await S.db.resolveSource(E, i);\n if (_.compute)\n for (const i of _.compute)\n E = await S.compute.resolveCompute(E, i);\n if (_.map)\n if (Array.isArray(_.map))\n for (let i = 0; i < _.map.length; i++) {\n let u = _.map[i];\n await S.map.resolveMap(E, u, i);\n }\n else\n await S.map.resolveMap(E, _.map);\n if (_.plot)\n if (Array.isArray(_.plot))\n for (const i of _.plot)\n await S.plot.resolvePlot(E, i);\n else\n await S.plot.resolvePlot(E, _.plot);\n t = E;\n }\n function R(E) {\n return console.log(\"Spec to update\", E), new Promise((i) => {\n i();\n });\n }\n function c() {\n console.log(\"Function not implemented yet\");\n }\n return { run: s, updatedSpec: R, destroy: c, get context() {\n return t;\n } };\n}\nvar n = /* @__PURE__ */ ((e) => (e.CAT_ACCENT = \"schemeAccent\", e.CAT_DARK2 = \"schemeDark2\", e.CAT_CATEGORY10 = \"schemeCategory10\", e.CAT_OBSERVABLE10 = \"schemeObservable10\", e.CAT_PAIRED = \"schemePaired\", e.CAT_PASTEL1 = \"schemePastel1\", e.CAT_PASTEL2 = \"schemePastel2\", e.CAT_SET1 = \"schemeSet1\", e.CAT_SET2 = \"schemeSet2\", e.CAT_SET3 = \"schemeSet3\", e.CAT_TABLEAU10 = \"schemeTableau10\", e.SEQ_REDS = \"interpolateReds\", e.SEQ_BLUES = \"interpolateBlues\", e.SEQ_GREENS = \"interpolateGreens\", e.SEQ_GREYS = \"interpolateGreys\", e.SEQ_ORANGES = \"interpolateOranges\", e.SEQ_PURPLES = \"interpolatePurples\", e.SEQ_TURBO = \"interpolateTurbo\", e.SEQ_VIRIDIS = \"interpolateViridis\", e.SEQ_INFERNO = \"interpolateInferno\", e.SEQ_MAGMA = \"interpolateMagma\", e.SEQ_PLASMA = \"interpolatePlasma\", e.SEQ_CIVIDIS = \"interpolateCividis\", e.SEQ_WARM = \"interpolateWarm\", e.SEQ_COOL = \"interpolateCool\", e.SEQ_CUBEHELIX_DEFAULT = \"interpolateCubehelixDefault\", e.SEQ_BU_GN = \"interpolateBuGn\", e.SEQ_BU_PU = \"interpolateBuPu\", e.SEQ_GN_BU = \"interpolateGnBu\", e.SEQ_OR_RD = \"interpolateOrRd\", e.SEQ_PU_BU_GN = \"interpolatePuBuGn\", e.SEQ_PU_BU = \"interpolatePuBu\", e.SEQ_PU_RD = \"interpolatePuRd\", e.SEQ_RD_PU = \"interpolateRdPu\", e.SEQ_YL_GN_BU = \"interpolateYlGnBu\", e.SEQ_YL_GN = \"interpolateYlGn\", e.SEQ_YL_OR_BR = \"interpolateYlOrBr\", e.SEQ_YL_OR_RD = \"interpolateYlOrRd\", e.DIV_BR_BG = \"interpolateBrBG\", e.DIV_PR_GN = \"interpolatePRGn\", e.DIV_PI_YG = \"interpolatePiYG\", e.DIV_PU_OR = \"interpolatePuOr\", e.DIV_RED_BLUE = \"interpolateRdBu\", e.DIV_RED_GREY = \"interpolateRdGy\", e.DIV_RED_YELLOW_BLUE = \"interpolateRdYlBu\", e.DIV_RED_YELLOW_GREEN = \"interpolateRdYlGn\", e.DIV_SPECTRAL = \"interpolateSpectral\", e))(n || {}), A = /* @__PURE__ */ ((e) => (e.MIN_MAX = \"minMax\", e.PERCENTILE = \"percentile\", e))(A || {});\nexport {\n n as ColorMapInterpolator,\n A as NormalizationMode,\n P as createEngine\n};\n//# sourceMappingURL=the-urban-grammar.js.map\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect\n * `autoLoadLayers` and no longer take `dropOsmTable`.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n return { ...rest, autoLoadLayers: { layers: autoLoadLayers?.layers ?? [] } };\n}\n\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n return {\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb | undefined> {\n\n let db = context;\n\n if(!db){\n db = new AutkDb();\n await db.init();\n }\n\n let {type, ...rest_spec} = spec;\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 loader tolerates null geometry and missing properties, which the inline type allows.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(geojsonSpec.outputTableName, geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: geojsonData }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n const crsHint = loadSpec.coordinateFormat\n ? `coordinateFormat is set to \"${loadSpec.coordinateFormat}\"`\n : `no coordinateFormat was specified — defaulting to EPSG:4326 (WGS84 per RFC 7946)`;\n throw new Error(\n `Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}. ` +\n `${crsHint}. Verify that coordinateFormat matches the actual CRS of the input data.`\n );\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for DEFAULT_WORKSPACE_COORDINATE_FORMAT (EPSG:3395)\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `Verify that coordinateFormat matches the actual CRS of the input data. ` +\n `The workspace uses ${DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.) — skip validation\n }\n print(db, targets);\n return db;\n }\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n await db.buildHeatmap({\n tableJoinName: hm.tableJoinName,\n near: { distance: hm.near.distance },\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy as any }),\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.tableRootName,\n tableJoinName: jn.tableJoinName,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.tableRootName);\n cache.set(jn.tableRootName, updated);\n }\n print(db, targets);\n return db;\n }\n default:\n return\n }\n }\n }\n}\n","import { MapAdapter, MapSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, ComputeCache } from '../types';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport { ColorMapDomainStrategy } from '@urban-toolkit/autk-core';\nimport type { ColorMapConfig, ColorMapDomainSpec, LayerType } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\n\nfunction buildDomainSpec(\n normalization: MapSpec['layerRefs'][number]['normalization'],\n colorMapDomain?: string[],\n): ColorMapDomainSpec {\n if (colorMapDomain && colorMapDomain.length > 0)\n return { type: ColorMapDomainStrategy.USER, params: colorMapDomain };\n if (normalization?.mode === NormalizationMode.PERCENTILE) {\n const hasExplicitBounds =\n normalization.lowerPercentile !== undefined || normalization.upperPercentile !== undefined;\n if (hasExplicitBounds)\n return {\n type: ColorMapDomainStrategy.PERCENTILE,\n params: [normalization.lowerPercentile ?? 0, normalization.upperPercentile ?? 100],\n };\n return { type: ColorMapDomainStrategy.PERCENTILE };\n }\n return { type: ColorMapDomainStrategy.MIN_MAX };\n}\n\nfunction valueAtPath(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, obj);\n}\n\nfunction setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> {\n const keys = path.split('.');\n const result = { ...obj };\n let current = result as Record<string, unknown>;\n for (let i = 0; i < keys.length - 1; i++) {\n current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown> ?? {}) };\n current = current[keys[i]] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n return result;\n}\n\n/**\n * Resolves a grammar value path such as `count.noise` to the raster band that holds it.\n * autk-db stores heatmap values in bands (`band_1`, ...) labelled `<aggregateFn>_<table>`.\n */\nfunction rasterBand(collection: { features?: { properties?: unknown }[] }, getFnv?: string): string {\n const props = collection.features?.[0]?.properties as { bands?: { id: string; label?: string }[] } | undefined;\n const bands = props?.bands ?? [];\n const band = bands.find((b) => b.id === getFnv || b.label === getFnv?.replace(/\\./g, '_'));\n return band?.id ?? bands[0]?.id ?? getFnv ?? '';\n}\n\nexport function createMapAdapter(targets?: Targets, registry?: MapRegistry, computeCache?: ComputeCache): MapAdapter {\n\n async function loadLayers(map: AutkMap, context: AutkDb, spec: MapSpec): Promise<void> {\n let tableToTypeMap: {[tableName: string]: string} = {};\n for(const table of context.getTablesMetadata()) {\n if(table.type !== undefined) tableToTypeMap[table.name] = table.type;\n }\n\n for(const layerRef of spec.layerRefs){\n const name = layerRef.dataRef;\n const type = tableToTypeMap[name] as LayerType;\n const getFnv = layerRef.getFnv;\n\n const rawData = computeCache?.get(name) ?? await context.getLayer(name);\n // Raster tables (e.g. heatmaps) are a single feature with no geometry, so keep them as-is.\n const data = type === 'raster' ? rawData : {\n ...rawData,\n features: (rawData.features ?? []).filter((f: any) => f.geometry != null),\n };\n\n if(type === 'raster') {\n map.loadCollection(name, { collection: data, type: 'raster', property: rasterBand(data, getFnv) });\n } else {\n map.loadCollection(name, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(name, { opacity: layerRef.opacity });\n\n // Enable the colormap by default for thematic (getFnv) vector layers so\n // autk-grammar maps render coloured-by-value out of the box. autk-map\n // attaches a default colour ramp to every layer, so this works even when\n // the spec omits colorMapInterpolator. Callers can still opt out by\n // setting isColorMap: false explicitly. Raster layers manage their own ramp.\n const enableColorMap = layerRef.isColorMap ?? (getFnv != null && type !== 'raster');\n if(enableColorMap)\n map.updateRenderInfo(name, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(name, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(name, { isSkip: true });\n\n // When catchAllCategory is set, remap features whose property value is not\n // in colorMapDomain to the catch-all label, and extend the domain to include it.\n const { catchAllCategory, colorMapDomain } = layerRef;\n let thematicData = data;\n let effectiveDomain = colorMapDomain;\n\n if(getFnv && catchAllCategory && colorMapDomain?.length) {\n const allowed = new Set(colorMapDomain);\n thematicData = {\n ...data,\n features: data.features.map((f: any) => {\n const props = f.properties as Record<string, unknown>;\n const val = valueAtPath(props, getFnv);\n if(val === undefined || val === null || !allowed.has(String(val))) {\n return { ...f, properties: setValueAtPath(props, getFnv, catchAllCategory) };\n }\n return f;\n }),\n };\n effectiveDomain = allowed.has(catchAllCategory)\n ? colorMapDomain\n : [...colorMapDomain, catchAllCategory];\n }\n\n if(layerRef.colorMapInterpolator) {\n const colormapConfig: ColorMapConfig = {\n // urban-grammar ColorMapInterpolator values are string-compatible\n // with autk-core ColorMapInterpolator at runtime\n interpolator: layerRef.colorMapInterpolator as unknown as ColorMapConfig['interpolator'],\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n map.updateRenderInfo(name, { colormap: { config: colormapConfig }, isColorMap: true });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(name, { collection: thematicData, property });\n }\n }\n }\n\n return {\n async resolveMap(context: AutkDb | undefined, spec: MapSpec, index: number = 0): Promise<void> {\n if(targets && targets.map && context){\n\n let canvas;\n\n if(Array.isArray(targets.map)){\n canvas = document.getElementById(targets.map[index]);\n }else{\n canvas = document.getElementById(targets.map);\n }\n\n if(!canvas)\n throw new Error(\"Could not find rendering target for map: \"+targets.map);\n\n if(!(canvas instanceof HTMLCanvasElement))\n throw new Error(\"Target for map is not a canvas: \"+targets.map);\n\n const map = new AutkMap(canvas);\n\n if(spec.style)\n map.style.setPredefinedStyle(spec.style)\n\n await map.init();\n await loadLayers(map, context, spec);\n\n if(registry)\n for(const layerRef of spec.layerRefs)\n registry.set(layerRef.dataRef, map);\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, PlotRegistry, PlotMapLinks, GeoJsonCache } from '../types';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkPlot, PlotEvent as AutkPlotEvent } from '@urban-toolkit/autk-plot';\nimport type { PlotEventData, PlotType, PlotTransformConfig } from '@urban-toolkit/autk-plot';\nimport { AutkMap, MapEvent } from '@urban-toolkit/autk-map';\nimport type { MapEventData } from '@urban-toolkit/autk-map';\nimport { FeatureCollection } from 'geojson';\n\n// autk-map 3 publishes MapEventData extending a type its .d.ts cannot resolve\n// (the import points at ../../autk-core/src), so `selection` is invisible here.\ntype MapSelection = MapEventData & { selection: number[] };\n\nfunction grammarMarkToPlotType(mark: PlotMark): PlotType {\n const mapping: Record<PlotMark, PlotType> = {\n 'scatter': 'scatterplot',\n 'bar': 'barchart',\n 'line': 'linechart',\n 'linechart': 'linechart',\n 'parallel-coordinates': 'parallel-coordinates',\n 'table': 'table',\n 'heatmatrix': 'heatmatrix',\n };\n return mapping[mark];\n}\n\nexport function createPlotAdapter(targets?: Targets, registry?: MapRegistry, plotRegistry?: PlotRegistry, plotMapLinks?: PlotMapLinks, cache?: GeoJsonCache): PlotAdapter {\n\n return {\n async resolvePlot(context: unknown, spec: PlotSpec): Promise<void> {\n if(!targets || !targets.plot) return;\n\n const div = document.getElementById(targets.plot);\n if(!div) throw new Error(`Could not find plot target: ${targets.plot}`);\n\n const db = context as AutkDb | undefined;\n if(!db) throw new Error('No data context available for plot.');\n\n const geojson: FeatureCollection = cache?.get(spec.dataRef) ?? await db.getLayer(spec.dataRef);\n\n const events = (spec.events ?? []) as unknown as AutkPlotEvent[];\n\n const plot = new AutkPlot(div, {\n type: grammarMarkToPlotType(spec.mark),\n collection: geojson,\n attributes: { axis: spec.axis, ...(spec.color && { color: spec.color }) },\n labels: { axis: spec.axis, title: spec.title },\n events,\n ...(spec.width && { width: spec.width }),\n ...(spec.height && { height: spec.height }),\n ...(spec.margins && { margins: spec.margins }),\n ...(spec.transform && { transform: spec.transform as PlotTransformConfig }),\n });\n\n plotRegistry?.set(spec.dataRef, plot);\n if (spec.mapRef) plotMapLinks?.set(spec.dataRef, spec.mapRef);\n\n // Wire map ↔ plot events if a mapRef is specified\n if(spec.mapRef && registry) {\n const map: AutkMap | undefined = registry.get(spec.mapRef);\n\n if(map) {\n map.updateRenderInfo(spec.mapRef, { isPick: true });\n\n map.events.on(MapEvent.PICKING, ({ selection }: MapSelection) => {\n plot.setSelection(selection);\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(spec.mapRef!, selection);\n });\n }\n }\n }\n }\n }\n}\n","import type { ComputeSpec, FromFeatureDirective } from '@urban-toolkit/the-urban-grammar';\nimport type { GpgpuPipelineParams } from '@urban-toolkit/autk-compute';\nimport type { Feature, FeatureCollection } from 'geojson';\n\n/** Tables a compute pass can read, keyed by table name. */\nexport type ComputeLayers = Record<string, FeatureCollection | undefined> | Map<string, FeatureCollection>;\n\n/** Runs one GPU dispatch, for example `params => new AutkComputeEngine().gpgpuPipeline(params)`. */\nexport type ComputeRunner = (params: GpgpuPipelineParams) => Promise<FeatureCollection>;\n\n/**\n * Most features a `batched` directive packs. Uniform arrays live in WebGPU uniform buffers, which\n * DX12 caps at 64 KB; a matrix entry packs 8 floats (32 B) per feature, so 2000 features use\n * 64,000 B and keep a margin below the cap.\n */\nexport const MAX_BATCHED_FEATURES = 2000;\n\ntype UniformEntry = number | FromFeatureDirective;\ntype MatrixEntry = { data: number[][]; cols: number } | FromFeatureDirective;\n\n/** Joins a `wglsFunction` written as an array of lines. Any other separator would let a `//` comment swallow the lines after it. */\nexport function joinWgsl(body: string | string[]): string {\n return Array.isArray(body) ? body.join('\\n') : body;\n}\n\n/** True when a uniform entry reads its value from a feature. */\nexport function isFromFeature(value: unknown): value is FromFeatureDirective {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n && typeof (value as FromFeatureDirective).fromFeature === 'object'\n && (value as FromFeatureDirective).fromFeature !== null;\n}\n\nfunction lookup(layers: ComputeLayers, name: string): FeatureCollection | undefined {\n return layers instanceof Map ? layers.get(name) : layers[name];\n}\n\nfunction valueAtPath(item: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, item);\n}\n\nfunction directives(block: ComputeSpec): FromFeatureDirective[] {\n const out: FromFeatureDirective[] = [];\n for (const cfg of [block.uniforms, block.uniformMatrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value)) out.push(value);\n }\n }\n return out;\n}\n\n/** Every table a compute pass reads: its `dataRef` plus each `fromFeature` layer. */\nexport function computeLayerNames(block: ComputeSpec): string[] {\n return [...new Set([block.dataRef, ...directives(block).map(d => d.fromFeature.layer)])];\n}\n\n/**\n * The iteration a compute pass asks for, or `null`. Every iterating directive must read the same\n * layer; the first one found decides the mode and the layer.\n */\nexport function findIterateSource(block: ComputeSpec): { mode: 'all' | 'batched'; layer: string } | null {\n for (const d of directives(block)) {\n const { iterate, layer } = d.fromFeature;\n if (iterate === 'all' || iterate === 'batched') return { mode: iterate, layer };\n }\n return null;\n}\n\nfunction resolveDirective(d: FromFeatureDirective, layers: ComputeLayers, iterateIndex?: number): unknown {\n const ff = d.fromFeature;\n const index = iterateIndex !== undefined && ff.iterate === 'all' ? iterateIndex : (ff.index ?? 0);\n const feature = lookup(layers, ff.layer)?.features?.[index];\n return feature ? valueAtPath(feature, ff.path) : undefined;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniforms` to numbers. An entry that does not resolve to a\n * finite number takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, number> | undefined {\n if (!uniforms) return undefined;\n const out: Record<string, number> = {};\n for (const [key, value] of Object.entries(uniforms)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const num = Number(resolveDirective(value, layers, iterateIndex) ?? NaN);\n if (Number.isFinite(num)) out[key] = num;\n else if (typeof value.default === 'number') out[key] = value.default;\n }\n return out;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniformMatrices` to `{ data, cols }`. An entry that does\n * not resolve to an array takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniformMatrices(\n matrices: Record<string, MatrixEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, { data: number[][]; cols: number }> | undefined {\n if (!matrices) return undefined;\n const out: Record<string, { data: number[][]; cols: number }> = {};\n for (const [key, value] of Object.entries(matrices)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const resolved = resolveDirective(value, layers, iterateIndex);\n const data = Array.isArray(resolved) ? (resolved as number[][])\n : Array.isArray(value.default) ? value.default : undefined;\n if (!data) continue;\n const cols = value.cols ?? (Array.isArray(data[0]) ? data[0].length : 0);\n if (cols > 0) out[key] = { data, cols };\n else console.warn(`[autk-grammar] uniform matrix \"${key}\" has no column count; entry dropped`);\n }\n return out;\n}\n\nfunction isFiniteValue(v: unknown): boolean {\n return v !== undefined && v !== null && !(typeof v === 'number' && !Number.isFinite(v));\n}\n\n/**\n * Packs every feature of a `batched` layer into uniform arrays:\n * - a scalar entry becomes an array of one value per feature, under the entry's name;\n * - a matrix entry becomes each feature's axis-aligned bounding box as four corners\n * `[xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]`, eight values per feature;\n * - `num_features` holds the feature count.\n * Features missing a `required` path are dropped first, and at most {@link MAX_BATCHED_FEATURES}\n * are packed. Plain numbers pass through; other entries that do not iterate are left to\n * {@link resolveComputeParams}.\n */\nexport function buildBatchedUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n sources: Feature[],\n): { uniforms: Record<string, number>; uniformArrays: Record<string, number[]> } {\n const outUniforms: Record<string, number> = {};\n const outArrays: Record<string, number[]> = {};\n\n const required: string[] = [];\n for (const cfg of [uniforms, matrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched' && value.fromFeature.required) {\n required.push(value.fromFeature.path);\n }\n }\n }\n if (required.length > 0) {\n const before = sources.length;\n sources = sources.filter(f => required.every(p => isFiniteValue(valueAtPath(f, p))));\n if (sources.length < before) {\n console.info(`[autk-grammar] batched compute dropped ${before - sources.length} feature(s) missing ${required.join(', ')}`);\n }\n }\n if (sources.length > MAX_BATCHED_FEATURES) {\n console.warn(`[autk-grammar] batched compute capped at ${MAX_BATCHED_FEATURES} features (got ${sources.length})`);\n sources = sources.slice(0, MAX_BATCHED_FEATURES);\n }\n\n for (const [key, value] of Object.entries(uniforms ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched') {\n const fallback = typeof value.default === 'number' ? value.default : undefined;\n outArrays[key] = sources.map(f => {\n const num = Number(valueAtPath(f, value.fromFeature.path) ?? fallback);\n return Number.isFinite(num) ? num : 0;\n });\n } else if (typeof value === 'number') {\n outUniforms[key] = value;\n }\n }\n\n for (const [key, value] of Object.entries(matrices ?? {})) {\n if (!isFromFeature(value) || value.fromFeature.iterate !== 'batched') continue;\n const data: number[] = [];\n for (const f of sources) {\n const ring = valueAtPath(f, value.fromFeature.path);\n let xmin = Infinity, ymin = Infinity, xmax = -Infinity, ymax = -Infinity;\n if (Array.isArray(ring)) {\n for (const coord of ring) {\n if (!Array.isArray(coord) || coord.length < 2) continue;\n const x = Number(coord[0]);\n const y = Number(coord[1]);\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n xmin = Math.min(xmin, x); ymin = Math.min(ymin, y);\n xmax = Math.max(xmax, x); ymax = Math.max(ymax, y);\n }\n }\n // A degenerate feature gets a zero-area box, so the shader's loop runs but adds nothing.\n if (!Number.isFinite(xmin)) { xmin = 0; ymin = 0; xmax = 0; ymax = 0; }\n data.push(xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax);\n }\n outArrays[key] = data;\n }\n\n outUniforms.num_features = sources.length;\n return { uniforms: outUniforms, uniformArrays: outArrays };\n}\n\n/**\n * Turns a compute pass into the parameters of one GPU dispatch. Pure: it reads `layers` and runs\n * nothing. With `iterate: 'all'`, pass the feature index as `iterateIndex` for each dispatch (see\n * {@link runCompute}). Throws when the pass's `dataRef` is not in `layers`.\n */\nexport function resolveComputeParams(block: ComputeSpec, layers: ComputeLayers, iterateIndex?: number): GpgpuPipelineParams {\n const collection = lookup(layers, block.dataRef);\n if (!collection) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n\n const params: GpgpuPipelineParams = {\n collection,\n variableMapping: block.attributes,\n wgslBody: joinWgsl(block.wglsFunction),\n };\n if (block.attributeArrays) params.attributeArrays = block.attributeArrays;\n if (block.attributeMatrices) params.attributeMatrices = block.attributeMatrices;\n if (block.uniformArrays) params.uniformArrays = block.uniformArrays;\n if (block.outputColumnName) params.resultField = block.outputColumnName;\n if (block.outputColumns) params.outputColumns = block.outputColumns;\n\n const iterate = findIterateSource(block);\n if (iterate?.mode === 'batched') {\n const sources = lookup(layers, iterate.layer)?.features ?? [];\n const packed = buildBatchedUniforms(block.uniforms, block.uniformMatrices, sources);\n // Entries that do not iterate resolve as they would without iteration.\n const single = resolveUniforms(notBatched(block.uniforms), layers) ?? {};\n const matrices = resolveUniformMatrices(notBatched(block.uniformMatrices), layers);\n params.uniforms = { ...single, ...packed.uniforms };\n params.uniformArrays = { ...(params.uniformArrays ?? {}), ...packed.uniformArrays };\n if (matrices && Object.keys(matrices).length > 0) params.uniformMatrices = matrices;\n return params;\n }\n\n const index = iterate?.mode === 'all' ? iterateIndex : undefined;\n const uniforms = resolveUniforms(block.uniforms, layers, index);\n const matrices = resolveUniformMatrices(block.uniformMatrices, layers, index);\n if (uniforms) params.uniforms = uniforms;\n if (matrices) params.uniformMatrices = matrices;\n return params;\n}\n\nfunction notBatched<T>(entries: Record<string, T> | undefined): Record<string, T> | undefined {\n if (!entries) return undefined;\n return Object.fromEntries(Object.entries(entries).filter(([, v]) => !(isFromFeature(v) && v.fromFeature.iterate === 'batched')));\n}\n\nfunction outputColumns(block: ComputeSpec): string[] {\n return block.outputColumns ?? (block.outputColumnName ? [block.outputColumnName] : []);\n}\n\n/**\n * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is\n * one dispatch per feature of the iterated layer, and each output column holds the sum over them.\n */\nexport async function runCompute(block: ComputeSpec, layers: ComputeLayers, run: ComputeRunner): Promise<FeatureCollection> {\n const iterate = findIterateSource(block);\n if (iterate?.mode !== 'all') return run(resolveComputeParams(block, layers));\n\n const target = lookup(layers, block.dataRef);\n if (!target) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n const columns = outputColumns(block);\n const summed: FeatureCollection = structuredClone(target);\n for (const f of summed.features) {\n const props = (f.properties ??= {}) as Record<string, unknown>;\n const compute = (props.compute ??= {}) as Record<string, number>;\n for (const col of columns) compute[col] = 0;\n }\n\n const count = lookup(layers, iterate.layer)?.features?.length ?? 0;\n for (let i = 0; i < count; i++) {\n const step = await run({ ...resolveComputeParams(block, layers, i), collection: summed });\n summed.features.forEach((f, j) => {\n const dst = (f.properties as Record<string, unknown> | null)?.compute as Record<string, number> | undefined;\n const src = (step.features[j]?.properties as Record<string, unknown> | null)?.compute as Record<string, unknown> | undefined;\n if (!dst || !src) return;\n for (const col of columns) {\n const inc = Number(src[col]);\n if (Number.isFinite(inc)) dst[col] += inc;\n }\n });\n }\n return summed;\n}\n","import { ComputeAdapter, ComputeSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkComputeEngine } from '@urban-toolkit/autk-compute';\nimport { FeatureCollection } from 'geojson';\nimport { ComputeCache } from '../types';\nimport { computeLayerNames, runCompute } from '../compute-params';\n\nexport function createComputeAdapter(cache?: ComputeCache): ComputeAdapter {\n\n return {\n async resolveCompute(context: AutkDb | undefined, spec: ComputeSpec): Promise<AutkDb | undefined> {\n if(context){\n // A table an earlier compute pass wrote is read from the cache, so passes chain.\n // Only the pass's own table must load; a `fromFeature` table that cannot\n // falls back to the directive's `default`.\n const layers: Record<string, FeatureCollection | undefined> = {};\n for (const name of computeLayerNames(spec)) {\n const cached = cache?.get(name);\n if (cached) layers[name] = cached;\n else if (name === spec.dataRef) layers[name] = await context.getLayer(name);\n else {\n try { layers[name] = await context.getLayer(name); }\n catch { layers[name] = undefined; }\n }\n }\n\n const engine = new AutkComputeEngine();\n const result = await runCompute(spec, layers, params => engine.gpgpuPipeline(params));\n\n if (cache) cache.set(spec.dataRef, result);\n\n return context;\n }\n }\n }\n}\n","import type { UrbanSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { AutkPlot } from '@urban-toolkit/autk-plot';\nimport type { FeatureCollection } from 'geojson';\n\nexport type Targets = {\n compute?: string,\n db?: string,\n map?: string[] | string,\n plot?: string\n}\n\nexport type MapRegistry = Map<string, AutkMap>;\nexport type PlotRegistry = Map<string, AutkPlot>;\nexport type PlotMapLinks = Map<string, string>; // plotId (dataRef) → mapRef (layerId)\nexport type GeoJsonCache = Map<string, FeatureCollection>;\nexport type ComputeCache = Map<string, FeatureCollection>;\n\nexport type AutkGrammarSpec = UrbanSpec;\n\n// Grammar-level interaction payloads — no autk internals leak through the public API\nexport interface GrammarPickingEvent {\n layerId: string;\n selection: number[];\n}\n\nexport interface GrammarPlotSelectionEvent {\n plotId: string;\n event: 'click' | 'brush' | 'brushX' | 'brushY';\n selection: number[];\n}\n\nexport type GrammarEventRecord = {\n 'map:picking': GrammarPickingEvent;\n 'plot:selection': GrammarPlotSelectionEvent;\n};\n\n// Self-contained typed emitter — does not import from autk packages\nexport class GrammarEventEmitter {\n private _listeners: Map<string, Set<(p: unknown) => void>> = new Map();\n\n on<K extends keyof GrammarEventRecord>(\n event: K,\n listener: (payload: GrammarEventRecord[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n const bucket = this._listeners.get(event)!;\n bucket.add(listener as (p: unknown) => void);\n return () => bucket.delete(listener as (p: unknown) => void);\n }\n\n /** @internal */\n emit<K extends keyof GrammarEventRecord>(event: K, payload: GrammarEventRecord[K]): void {\n this._listeners.get(event)?.forEach(l => l(payload));\n }\n}\n\n","import { DataAdapter, MapAdapter, PlotAdapter, ComputeAdapter, IEngine, UrbanSpec, createEngine } from \"@urban-toolkit/the-urban-grammar\";\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from \"@urban-toolkit/autk-db\";\nimport { MapEvent } from \"@urban-toolkit/autk-map\";\nimport type { AutkMap } from \"@urban-toolkit/autk-map\";\nimport type { MapEventData } from \"@urban-toolkit/autk-map\";\nimport { PlotEvent } from \"@urban-toolkit/autk-plot\";\nimport type { PlotEventData } from \"@urban-toolkit/autk-plot\";\nimport { FeatureCollection } from \"geojson\";\nimport { createDataAdapter } from \"./adapters/data\";\nimport { createMapAdapter } from \"./adapters/map\";\nimport { createPlotAdapter } from \"./adapters/plot\";\nimport { createComputeAdapter } from \"./adapters/compute\";\nimport { Targets, MapRegistry, PlotRegistry, PlotMapLinks, GeoJsonCache, ComputeCache, GrammarEventEmitter } from \"./types\";\nimport type { GrammarPlotSelectionEvent } from \"./types\";\n\n// autk-map 3 publishes MapEventData extending a type its .d.ts cannot resolve\n// (the import points at ../../autk-core/src), so `selection` is invisible here.\ntype MapSelection = MapEventData & { selection: number[] };\n\nexport class AutkGrammar {\n private dataAdapter?: DataAdapter;\n private mapAdapter?: MapAdapter;\n private plotAdapter?: PlotAdapter;\n private computeAdapter?: ComputeAdapter;\n private grammarEngine?: IEngine;\n private _computeCache: ComputeCache = new Map();\n private _data: Record<string, Promise<FeatureCollection>> = {};\n private _mapRegistry: MapRegistry = new Map();\n private _plotRegistry: PlotRegistry = new Map();\n private _fwdCleanups: Array<() => void> = [];\n private _plotMapLinks: PlotMapLinks = new Map();\n\n readonly interactions = new GrammarEventEmitter();\n\n constructor(targets?: Targets) {\n const cache: GeoJsonCache = new Map();\n this.dataAdapter = createDataAdapter(targets, cache);\n this.mapAdapter = createMapAdapter(targets, this._mapRegistry, this._computeCache);\n this.plotAdapter = createPlotAdapter(targets, this._mapRegistry, this._plotRegistry, this._plotMapLinks, cache);\n this.computeAdapter = createComputeAdapter(this._computeCache);\n }\n\n /**\n * The coordinate reference system used internally by the autk workspace.\n *\n * Input data is expected in EPSG:4326 (WGS84) by default and is transformed\n * to this CRS on load. Consumers that prepare data for injection (e.g. by\n * serialising a GeoDataFrame) can read this value and reproject accordingly\n * instead of hard-coding a CRS string.\n */\n get workspaceCrs(): string {\n return DEFAULT_WORKSPACE_COORDINATE_FORMAT;\n }\n\n get data(): Record<string, Promise<FeatureCollection>> {\n return this._data;\n }\n\n async run(spec: UrbanSpec) {\n if(!this.dataAdapter)\n throw new Error('Database adapter not initialized. Please call the constructor first.');\n\n if(!this.mapAdapter)\n throw new Error('Map engine not initialized. Please call the constructor first.');\n\n if(!this.plotAdapter)\n throw new Error('Plot adapter not initialized. Please call the constructor first.');\n\n if(!this.computeAdapter)\n throw new Error('Compute adapter not initialized. Please call the constructor first.');\n\n this._mapRegistry.clear();\n this._plotRegistry.clear();\n this._plotMapLinks.clear();\n this._computeCache.clear();\n\n this.grammarEngine = createEngine({\n spec,\n adapters: {\n db: this.dataAdapter,\n map: this.mapAdapter,\n plot: this.plotAdapter,\n compute: this.computeAdapter\n }\n });\n\n await this.grammarEngine.run();\n this._rewireInteractions();\n\n const db = this.grammarEngine.context as AutkDb | undefined;\n if (!db) {\n console.warn('Grammar engine produced no data context.');\n this._data = {};\n return;\n }\n\n const dataObj: Record<string, Promise<FeatureCollection>> = {};\n for (const table of db.getLayersMetadata()) {\n Object.defineProperty(dataObj, table.name, {\n get: () => {\n const computed = this._computeCache.get(table.name);\n return computed ? Promise.resolve(computed) : db.getLayer(table.name);\n },\n enumerable: true,\n configurable: true,\n });\n }\n this._data = dataObj;\n }\n\n /**\n * Highlights features on the map layer identified by `layerId`.\n * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.\n */\n highlightOnMap(layerId: string, featureIds: number[]): void {\n this._mapRegistry.get(layerId)?.setHighlightedIds(layerId, featureIds);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === layerId) this._plotRegistry.get(plotId)?.setSelection(featureIds);\n }\n }\n\n /**\n * Clears highlighted features on the map layer identified by `layerId`.\n * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.\n */\n clearHighlightOnMap(layerId: string): void {\n this._mapRegistry.get(layerId)?.clearHighlightedIds(layerId);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === layerId) this._plotRegistry.get(plotId)?.setSelection([]);\n }\n }\n\n /**\n * Clears the selection on the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is cleared too.\n */\n clearHighlightOnPlot(plotId: string): void {\n this._plotRegistry.get(plotId)?.setSelection([]);\n const mapRef = this._plotMapLinks.get(plotId);\n if (mapRef) this._mapRegistry.get(mapRef)?.clearHighlightedIds(mapRef);\n }\n\n /**\n * Applies a selection to the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is updated too.\n */\n setPlotSelection(plotId: string, featureIds: number[]): void {\n this._plotRegistry.get(plotId)?.setSelection(featureIds);\n const mapRef = this._plotMapLinks.get(plotId);\n if (mapRef) this._mapRegistry.get(mapRef)?.setHighlightedIds(mapRef, featureIds);\n }\n\n private _rewireInteractions(): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n\n // Wire each unique map → grammar bus\n // Multiple layerRefs can share one AutkMap instance; deduplicate to avoid double-subscription\n const seenMaps = new Set<AutkMap>();\n for (const [layerId, map] of this._mapRegistry) {\n if (seenMaps.has(map)) continue;\n seenMaps.add(map);\n const handler = ({ selection }: MapSelection) => {\n this.interactions.emit('map:picking', { layerId, selection });\n };\n map.events.on(MapEvent.PICKING, handler);\n this._fwdCleanups.push(() => map.events.off(MapEvent.PICKING, handler));\n }\n\n // Wire each plot → grammar bus (all four event types)\n for (const [plotId, plot] of this._plotRegistry) {\n for (const ev of [PlotEvent.CLICK, PlotEvent.BRUSH, PlotEvent.BRUSH_X, PlotEvent.BRUSH_Y] as const) {\n const handler = ({ selection }: PlotEventData) => {\n this.interactions.emit('plot:selection', {\n plotId,\n event: ev as GrammarPlotSelectionEvent['event'],\n selection,\n });\n };\n plot.events.on(ev, handler);\n this._fwdCleanups.push(() => plot.events.off(ev, handler));\n }\n }\n }\n}\n"],"names":["P","e","_","S","t","E","u","R","c","n","A","toLoadOsmParams","spec","autoLoadLayers","rest","createDataAdapter","targets","cache","print","db","div","tables","table","context","AutkDb","type","rest_spec","geojsonSpec","geojsonData","loadSpec","s","err","crsHint","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","jn","updated","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","key","setValueAtPath","value","keys","result","current","i","rasterBand","collection","getFnv","bands","b","createMapAdapter","registry","computeCache","loadLayers","map","tableToTypeMap","layerRef","name","rawData","data","f","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","colormapConfig","property","index","canvas","AutkMap","grammarMarkToPlotType","mark","createPlotAdapter","plotRegistry","plotMapLinks","geojson","events","plot","AutkPlot","MapEvent","selection","event","MAX_BATCHED_FEATURES","joinWgsl","body","isFromFeature","lookup","layers","item","directives","block","out","cfg","computeLayerNames","d","findIterateSource","iterate","layer","resolveDirective","iterateIndex","ff","feature","resolveUniforms","uniforms","num","resolveUniformMatrices","matrices","resolved","cols","isFiniteValue","v","buildBatchedUniforms","sources","outUniforms","outArrays","required","before","p","fallback","ring","xmin","ymin","xmax","ymax","coord","x","y","resolveComputeParams","params","packed","single","notBatched","entries","outputColumns","runCompute","run","target","columns","summed","compute","col","count","step","j","dst","src","inc","createComputeAdapter","cached","engine","AutkComputeEngine","GrammarEventEmitter","listener","bucket","payload","l","AutkGrammar","createEngine","dataObj","computed","layerId","featureIds","plotId","mapRef","cleanup","seenMaps","handler","ev","PlotEvent"],"mappings":"omBAAA,SAASA,EAAEC,EAAG,CACZ,KAAM,CAAE,KAAMC,EAAG,SAAUC,CAAC,EAAKF,EACjC,IAAIG,EACJ,eAAe,GAAI,CACjB,IAAIC,EACJ,GAAIH,EAAE,KACJ,UAAW,KAAKA,EAAE,KAChBG,EAAI,MAAMF,EAAE,GAAG,cAAcE,EAAG,CAAC,EACrC,GAAIH,EAAE,QACJ,UAAW,KAAKA,EAAE,QAChBG,EAAI,MAAMF,EAAE,QAAQ,eAAeE,EAAG,CAAC,EAC3C,GAAIH,EAAE,IACJ,GAAI,MAAM,QAAQA,EAAE,GAAG,EACrB,QAAS,EAAI,EAAG,EAAIA,EAAE,IAAI,OAAQ,IAAK,CACrC,IAAII,EAAIJ,EAAE,IAAI,CAAC,EACf,MAAMC,EAAE,IAAI,WAAWE,EAAGC,EAAG,CAAC,CAChC,MAEA,MAAMH,EAAE,IAAI,WAAWE,EAAGH,EAAE,GAAG,EACnC,GAAIA,EAAE,KACJ,GAAI,MAAM,QAAQA,EAAE,IAAI,EACtB,UAAW,KAAKA,EAAE,KAChB,MAAMC,EAAE,KAAK,YAAYE,EAAG,CAAC,OAE/B,MAAMF,EAAE,KAAK,YAAYE,EAAGH,EAAE,IAAI,EACtCE,EAAIC,CACN,CACA,SAASE,EAAEF,EAAG,CACZ,OAAO,QAAQ,IAAI,iBAAkBA,CAAC,EAAG,IAAI,QAAS,GAAM,CAC1D,EAAC,CACH,CAAC,CACH,CACA,SAASG,GAAI,CACX,QAAQ,IAAI,8BAA8B,CAC5C,CACA,MAAO,CAAE,IAAK,EAAG,YAAaD,EAAG,QAASC,EAAG,IAAI,SAAU,CACzD,OAAOJ,CACT,CAAC,CACH,CACG,IAACK,GAAsBR,IAAOA,EAAE,WAAa,eAAgBA,EAAE,UAAY,cAAeA,EAAE,eAAiB,mBAAoBA,EAAE,iBAAmB,q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