@urban-toolkit/autk-grammar 4.1.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"autk-grammar.js","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, maps?: AutkMap[]): 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 if(maps)\n maps[index] = 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\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 }: MapEventData) => {\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 * The storage buffer binding every WebGPU device supports: the default\n * `maxStorageBufferBindingSize`, 128 MiB. autk-compute 4 reads each array a `batched` directive\n * packs from a read-only storage buffer of its own, so every packed array must fit one binding.\n * autk-compute 3 bound them as uniform buffers, which hold 64 KiB (2048 bounding boxes).\n */\nexport const STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/** Bytes a feature adds to a packed array: one f32 for a scalar entry, a bounding box of eight for a matrix entry. */\nconst SCALAR_BYTES = 4;\nconst BOX_BYTES = 8 * 4;\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\nfunction isBatched(value: unknown): boolean {\n return isFromFeature(value) && value.fromFeature.iterate === 'batched';\n}\n\n/** Bytes one feature adds to the largest array a batched pass packs, or 0 when it packs none. */\nfunction batchedBytesPerFeature(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n): number {\n if (Object.values(matrices ?? {}).some(isBatched)) return BOX_BYTES;\n if (Object.values(uniforms ?? {}).some(isBatched)) return SCALAR_BYTES;\n return 0;\n}\n\n/**\n * Most features a batched pass packs: as many as its largest array holds in one storage buffer\n * binding of `bindingSize` bytes. With {@link STORAGE_BUFFER_BINDING_SIZE} that is 4,194,304\n * features for a pass with a matrix entry, and 33,554,432 for one with scalar entries only.\n */\nexport function maxBatchedFeatures(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): number {\n const bytes = batchedBytesPerFeature(uniforms, matrices);\n return bytes > 0 ? Math.floor(bindingSize / bytes) : Number.POSITIVE_INFINITY;\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 maxBatchedFeatures}\n * are packed: as many as the largest array holds in one storage buffer binding of `bindingSize`\n * bytes. 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 bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\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 const limit = maxBatchedFeatures(uniforms, matrices, bindingSize);\n if (sources.length > limit) {\n console.warn(\n `[autk-grammar] batched compute capped at ${limit} features (got ${sources.length}): `\n + `its largest packed array takes ${batchedBytesPerFeature(uniforms, matrices)} B per feature, `\n + `and a storage buffer binding holds ${bindingSize} B`,\n );\n sources = sources.slice(0, limit);\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\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 _maps: AutkMap[] = [];\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, this._maps);\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 /**\n * The maps the last {@link run} drew, one per `map` entry of the spec, in order.\n *\n * Each map draws on demand: one frame once its layers are loaded, then one each\n * time it changes. Between frames a map canvas can read back empty, so to read a\n * map's pixels (for example with `canvas.toDataURL()`), call its `requestRender()`\n * and read in a `requestAnimationFrame` callback registered after that call.\n */\n get maps(): readonly AutkMap[] {\n return this._maps;\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._maps.length = 0;\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 }: MapEventData) => {\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","maps","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","STORAGE_BUFFER_BINDING_SIZE","SCALAR_BYTES","BOX_BYTES","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","isBatched","batchedBytesPerFeature","maxBatchedFeatures","bindingSize","bytes","buildBatchedUniforms","sources","outUniforms","outArrays","required","before","p","limit","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":";;;;;AAAA,SAASA,EAAEC,GAAG;AACZ,QAAM,EAAE,MAAMC,GAAG,UAAUC,EAAC,IAAKF;AACjC,MAAIG;AACJ,iBAAe,IAAI;AACjB,QAAIC;AACJ,QAAIH,EAAE;AACJ,iBAAW,KAAKA,EAAE;AAChB,QAAAG,IAAI,MAAMF,EAAE,GAAG,cAAcE,GAAG,CAAC;AACrC,QAAIH,EAAE;AACJ,iBAAW,KAAKA,EAAE;AAChB,QAAAG,IAAI,MAAMF,EAAE,QAAQ,eAAeE,GAAG,CAAC;AAC3C,QAAIH,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,GAAG;AACrB,iBAAS,IAAI,GAAG,IAAIA,EAAE,IAAI,QAAQ,KAAK;AACrC,cAAII,IAAIJ,EAAE,IAAI,CAAC;AACf,gBAAMC,EAAE,IAAI,WAAWE,GAAGC,GAAG,CAAC;AAAA,QAChC;AAAA;AAEA,cAAMH,EAAE,IAAI,WAAWE,GAAGH,EAAE,GAAG;AACnC,QAAIA,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,IAAI;AACtB,mBAAW,KAAKA,EA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,aAAK,aAAa,KAAK,eAAe,EAAE,SAAAwF,GAAS,WAAAxF,GAAW;AAAA,MAChE;AACA,MAAA5B,EAAI,OAAO,GAAG2B,EAAS,SAAS+F,CAAO,GACvC,KAAK,aAAa,KAAK,MAAM1H,EAAI,OAAO,IAAI2B,EAAS,SAAS+F,CAAO,CAAC;AAAA,IAC1E;AAGA,eAAW,CAACJ,GAAQ7F,CAAI,KAAK,KAAK;AAC9B,iBAAWkG,KAAM,CAACC,EAAU,OAAOA,EAAU,OAAOA,EAAU,SAASA,EAAU,OAAO,GAAY;AAChG,cAAMF,IAAU,CAAC,EAAE,WAAA9F,QAA+B;AAC9C,eAAK,aAAa,KAAK,kBAAkB;AAAA,YACrC,QAAA0F;AAAA,YACA,OAAOK;AAAA,YACP,WAAA/F;AAAA,UAAA,CACH;AAAA,QACL;AACA,QAAAH,EAAK,OAAO,GAAGkG,GAAID,CAAO,GAC1B,KAAK,aAAa,KAAK,MAAMjG,EAAK,OAAO,IAAIkG,GAAID,CAAO,CAAC;AAAA,MAC7D;AAAA,EAER;AACJ;"}
1
+ {"version":3,"file":"autk-grammar.js","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, MapLayerSpec, MapSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, MapLayerIds, ComputeCache } from '../types';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport type { LayerRenderInfo } from '@urban-toolkit/autk-map';\nimport { ColorMap, ColorMapDomainStrategy, ColorMapInterpolator } from '@urban-toolkit/autk-core';\nimport type { ColorHEX, ColorMapConfig, ColorMapDomainSpec, ColorRGB, LayerType, TransferFunction } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\n\n/** The id a layer has in its map: its `title`, else its `dataRef`. */\nexport function layerIdOf(layerRef: MapLayerSpec): string {\n return typeof layerRef.title === 'string' && layerRef.title !== '' ? layerRef.title : layerRef.dataRef;\n}\n\n/** Refuses a map whose layers would share an id. */\nfunction checkLayerIds(spec: MapSpec, index: number): void {\n const ids = new Set<string>();\n for (const layerRef of spec.layerRefs) {\n const id = layerIdOf(layerRef);\n if (ids.has(id))\n throw new Error(`Map ${index} draws two layers with the id \"${id}\". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);\n ids.add(id);\n }\n}\n\nconst HEX_COLOR = /^#[0-9a-fA-F]{6}$/;\n\nfunction hexColor(value: string, key: string, layerId: string): ColorRGB {\n if (!HEX_COLOR.test(value))\n throw new Error(`Layer \"${layerId}\": ${key} must be a color written #rrggbb, not \"${value}\".`);\n return ColorMap.hexToRgb(value as ColorHEX);\n}\n\n/** What `color`, `stroke` and `width` set on the layer's autk-map render info. */\nfunction styleRenderInfo(layerRef: MapLayerSpec, layerId: string): Partial<LayerRenderInfo> {\n const renderInfo: Partial<LayerRenderInfo> = {};\n if (layerRef.color != null)\n renderInfo.color = hexColor(layerRef.color, 'color', layerId);\n if (layerRef.stroke === false)\n renderInfo.showBorders = false;\n else if (layerRef.stroke != null)\n renderInfo.strokeColor = hexColor(layerRef.stroke, 'stroke', layerId);\n if (layerRef.width != null)\n renderInfo.polylinesWidth = layerRef.width;\n return renderInfo;\n}\n\n/**\n * Whether the layer is colored by value. An explicit `isColorMap` decides. A raster layer is colored by value\n * either way, and this only shows or hides its legend. Otherwise a layer with a `color` is drawn in it, and a\n * layer with a scheme or a `getFnv` value is colored by value.\n */\nfunction colorsByValue(layerRef: MapLayerSpec, type: LayerType): boolean {\n if (layerRef.isColorMap != null) return layerRef.isColorMap;\n if (type === 'raster')\n return layerRef.colorMapInterpolator != null || layerRef.colorMapCenter != null || layerRef.colorMapReverse === true;\n if (layerRef.color != null) return false;\n return layerRef.colorMapInterpolator != null || layerRef.getFnv != null;\n}\n\n/** A raster band's values, as autk-map reads them. */\nfunction bandValues(collection: { features?: { properties?: unknown }[] }, band: string): Float32Array | null {\n const values = (collection.features?.[0]?.properties as Record<string, unknown> | undefined)?.[band];\n if (values instanceof Float32Array) return values;\n if ((ArrayBuffer.isView(values) && !(values instanceof DataView)) || Array.isArray(values))\n return Float32Array.from(values as ArrayLike<number>, (v) => (Number.isFinite(Number(v)) ? Number(v) : NaN));\n return null;\n}\n\n/**\n * The domain of a raster's centered or reversed color scale, or `undefined` when the layer asks for neither, the\n * scheme is categorical, or the band has no value. Centered on `center`, it runs from the center less the farthest\n * value's distance to it, to the center plus that distance; when every value is the center, it is not centered.\n * Otherwise it is the domain autk-map resolves from `config`. `reverse` turns it around.\n */\nexport function rasterScaleDomain(values: Float32Array, config: ColorMapConfig, center?: number, reverse?: boolean): number[] | undefined {\n if (ColorMap.isCategorical(config.interpolator)) return undefined;\n let reach = 0;\n let finite = 0;\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n if (!Number.isFinite(value)) continue;\n finite++;\n if (center != null) reach = Math.max(reach, Math.abs(value - center));\n }\n const centered = center != null && reach > 0;\n if (finite === 0 || (!centered && reverse !== true)) return undefined;\n const domain = centered && center != null\n ? [center - reach, center, center + reach]\n : ColorMap.resolveDomainFromData(values, config) as number[];\n return reverse === true ? [...domain].reverse() : domain;\n}\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, maps?: AutkMap[], layerIds?: MapLayerIds): 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 layerId = layerIdOf(layerRef);\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 const band = type === 'raster' ? rasterBand(data, getFnv) : '';\n\n if(type === 'raster') {\n map.loadCollection(layerId, { collection: data, type: 'raster', property: band });\n } else {\n map.loadCollection(layerId, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(layerId, { opacity: layerRef.opacity });\n\n const style = styleRenderInfo(layerRef, layerId);\n if(Object.keys(style).length > 0)\n map.updateRenderInfo(layerId, style);\n\n // Thematic (getFnv) vector layers are colored by value out of the box: autk-map\n // attaches a default colour ramp to every layer, so this works even when the\n // spec omits colorMapInterpolator (see colorsByValue).\n if(colorsByValue(layerRef, type))\n map.updateRenderInfo(layerId, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(layerId, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(layerId, { 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 // A raster's transfer function is only stored by setTransferFunction; the\n // updateColorMap below colors the cells again with it.\n const rasterTransfer = type === 'raster' && layerRef.transferFunction != null;\n if(rasterTransfer) {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as\n { setTransferFunction?: (transferFunction: TransferFunction) => void } | null;\n layer?.setTransferFunction?.(layerRef.transferFunction as TransferFunction);\n }\n\n // The scheme and its domain go through updateColorMap, which colors a raster's\n // cells again and gives the legend its labels.\n const rasterScale = type === 'raster' && (layerRef.colorMapCenter != null || layerRef.colorMapReverse === true);\n if(layerRef.colorMapInterpolator || rasterScale) {\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'] | undefined)\n ?? map.layerManager.searchByLayerId(layerId)?.layerRenderInfo.colormap.config.interpolator\n ?? ColorMapInterpolator.SEQ_REDS,\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n const values = rasterScale ? bandValues(data, band) : null;\n const domain = values\n ? rasterScaleDomain(values, colormapConfig, layerRef.colorMapCenter, layerRef.colorMapReverse)\n : undefined;\n if(domain)\n colormapConfig.domainSpec = { type: ColorMapDomainStrategy.USER, params: domain };\n map.updateColorMap(layerId, { colorMap: colormapConfig });\n } else if(rasterTransfer) {\n map.updateColorMap(layerId, { colorMap: {} });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(layerId, { 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 checkLayerIds(spec, index);\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 for(const layerRef of spec.layerRefs) {\n registry?.set(layerRef.dataRef, map);\n layerIds?.set(layerRef.dataRef, layerIdOf(layerRef));\n }\n\n if(maps)\n maps[index] = map;\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, MapLayerIds, 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\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, layerIds?: MapLayerIds): 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. mapRef names the layer's\n // table; the layer's id in its map is its title, else that name.\n if(spec.mapRef && registry) {\n const map: AutkMap | undefined = registry.get(spec.mapRef);\n const layerId = layerIds?.get(spec.mapRef) ?? spec.mapRef;\n\n if(map) {\n map.updateRenderInfo(layerId, { isPick: true });\n\n map.events.on(MapEvent.PICKING, ({ selection }: MapEventData) => {\n plot.setSelection(selection);\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(layerId, 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 * The storage buffer binding every WebGPU device supports: the default\n * `maxStorageBufferBindingSize`, 128 MiB. autk-compute 4 reads each array a `batched` directive\n * packs from a read-only storage buffer of its own, so every packed array must fit one binding.\n * autk-compute 3 bound them as uniform buffers, which hold 64 KiB (2048 bounding boxes).\n */\nexport const STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/** Bytes a feature adds to a packed array: one f32 for a scalar entry, a bounding box of eight for a matrix entry. */\nconst SCALAR_BYTES = 4;\nconst BOX_BYTES = 8 * 4;\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\nfunction isBatched(value: unknown): boolean {\n return isFromFeature(value) && value.fromFeature.iterate === 'batched';\n}\n\n/** Bytes one feature adds to the largest array a batched pass packs, or 0 when it packs none. */\nfunction batchedBytesPerFeature(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n): number {\n if (Object.values(matrices ?? {}).some(isBatched)) return BOX_BYTES;\n if (Object.values(uniforms ?? {}).some(isBatched)) return SCALAR_BYTES;\n return 0;\n}\n\n/**\n * Most features a batched pass packs: as many as its largest array holds in one storage buffer\n * binding of `bindingSize` bytes. With {@link STORAGE_BUFFER_BINDING_SIZE} that is 4,194,304\n * features for a pass with a matrix entry, and 33,554,432 for one with scalar entries only.\n */\nexport function maxBatchedFeatures(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): number {\n const bytes = batchedBytesPerFeature(uniforms, matrices);\n return bytes > 0 ? Math.floor(bindingSize / bytes) : Number.POSITIVE_INFINITY;\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 maxBatchedFeatures}\n * are packed: as many as the largest array holds in one storage buffer binding of `bindingSize`\n * bytes. 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 bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\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 const limit = maxBatchedFeatures(uniforms, matrices, bindingSize);\n if (sources.length > limit) {\n console.warn(\n `[autk-grammar] batched compute capped at ${limit} features (got ${sources.length}): `\n + `its largest packed array takes ${batchedBytesPerFeature(uniforms, matrices)} B per feature, `\n + `and a storage buffer binding holds ${bindingSize} B`,\n );\n sources = sources.slice(0, limit);\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 MapLayerIds = Map<string, string>; // dataRef → id of the layer that draws it in the map the MapRegistry holds for it\nexport type PlotRegistry = Map<string, AutkPlot>;\nexport type PlotMapLinks = Map<string, string>; // plotId (dataRef) → mapRef (dataRef of a map layer)\n\n/** A layer a map of the last run draws, as `AutkGrammar.mapLayer` finds it by its table's name. */\nexport interface GrammarMapLayer {\n /** The map that draws the layer. */\n map: AutkMap;\n /** The layer's id in that map: its `title`, else its `dataRef`. */\n layerId: string;\n}\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, MapLayerIds, PlotRegistry, PlotMapLinks, GeoJsonCache, ComputeCache, GrammarEventEmitter } from \"./types\";\nimport type { GrammarMapLayer, GrammarPlotSelectionEvent } from \"./types\";\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 _mapLayerIds: MapLayerIds = new Map();\n private _maps: AutkMap[] = [];\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, this._maps, this._mapLayerIds);\n this.plotAdapter = createPlotAdapter(targets, this._mapRegistry, this._plotRegistry, this._plotMapLinks, cache, this._mapLayerIds);\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 /**\n * The maps the last {@link run} drew, one per `map` entry of the spec, in order.\n *\n * Each map draws on demand: one frame once its layers are loaded, then one each\n * time it changes. Between frames a map canvas can read back empty, so to read a\n * map's pixels (for example with `canvas.toDataURL()`), call its `requestRender()`\n * and read in a `requestAnimationFrame` callback registered after that call.\n */\n get maps(): readonly AutkMap[] {\n return this._maps;\n }\n\n /**\n * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):\n * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.\n * `undefined` when no map draws the table. When several layers draw it, the last one.\n *\n * @example\n * const layer = grammar.mapLayer('buildings');\n * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });\n */\n mapLayer(dataRef: string): GrammarMapLayer | undefined {\n const map = this._mapRegistry.get(dataRef);\n return map ? { map, layerId: this._mapLayerIds.get(dataRef) ?? dataRef } : undefined;\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._mapLayerIds.clear();\n this._maps.length = 0;\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 that draws the table `dataRef` (see {@link mapLayer}).\n * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.\n */\n highlightOnMap(dataRef: string, featureIds: number[]): void {\n const layer = this.mapLayer(dataRef);\n layer?.map.setHighlightedIds(layer.layerId, featureIds);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === dataRef) this._plotRegistry.get(plotId)?.setSelection(featureIds);\n }\n }\n\n /**\n * Clears highlighted features on the map layer that draws the table `dataRef` (see {@link mapLayer}).\n * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.\n */\n clearHighlightOnMap(dataRef: string): void {\n const layer = this.mapLayer(dataRef);\n layer?.map.clearHighlightedIds(layer.layerId);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === dataRef) 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 const layer = mapRef ? this.mapLayer(mapRef) : undefined;\n layer?.map.clearHighlightedIds(layer.layerId);\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 const layer = mapRef ? this.mapLayer(mapRef) : undefined;\n layer?.map.setHighlightedIds(layer.layerId, 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 }: MapEventData) => {\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","s","E","i","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","err","crsHint","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","jn","updated","layerIdOf","layerRef","checkLayerIds","index","ids","id","HEX_COLOR","hexColor","value","key","layerId","ColorMap","styleRenderInfo","renderInfo","colorsByValue","bandValues","collection","band","values","v","rasterScaleDomain","config","center","reverse","reach","finite","centered","domain","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","setValueAtPath","keys","result","current","rasterBand","getFnv","bands","b","createMapAdapter","registry","computeCache","maps","layerIds","loadLayers","map","tableToTypeMap","name","rawData","data","f","style","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","rasterTransfer","rasterScale","colormapConfig","ColorMapInterpolator","property","canvas","AutkMap","grammarMarkToPlotType","mark","createPlotAdapter","plotRegistry","plotMapLinks","geojson","events","plot","AutkPlot","MapEvent","selection","event","STORAGE_BUFFER_BINDING_SIZE","SCALAR_BYTES","BOX_BYTES","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","isBatched","batchedBytesPerFeature","maxBatchedFeatures","bindingSize","bytes","buildBatchedUniforms","sources","outUniforms","outArrays","required","before","p","limit","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","dataRef","createEngine","dataObj","computed","feat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&typeof module<"u"?b(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"],b):(m=typeof globalThis<"u"?globalThis:m||self,b(m["autk-grammar"]={},m.autkDb,m.autkMap,m.autkPlot,m.autkCore,m.autkCompute))})(this,(function(m,b,M,w,v,X){"use strict";function D(t){const{spec:e,adapters:r}=t;let o;async function s(){let l;if(e.data)for(const i of e.data)l=await r.db.resolveSource(l,i);if(e.compute)for(const i of e.compute)l=await r.compute.resolveCompute(l,i);if(e.map)if(Array.isArray(e.map))for(let i=0;i<e.map.length;i++){let u=e.map[i];await r.map.resolveMap(l,u,i)}else await r.map.resolveMap(l,e.map);if(e.plot)if(Array.isArray(e.plot))for(const i of e.plot)await r.plot.resolvePlot(l,i);else await r.plot.resolvePlot(l,e.plot);o=l}function a(l){return console.log("Spec to update",l),new Promise(i=>{i()})}function n(){console.log("Function not implemented yet")}return{run:s,updatedSpec:a,destroy:n,get context(){return o}}}var j=(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))(j||{}),L=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(L||{});function Z(t){const{autoLoadLayers:e,...r}=t;return{...r,autoLoadLayers:{layers:e?.layers??[]}}}function z(t,e){function r(o,s){if(!s||!s.db)return;const a=document.getElementById(s.db);if(a){const n=o.getTablesMetadata();a.innerHTML+="<ul>";for(const l of n)a.innerHTML+=`<li>${l.name}: (${l.source}, ${l.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${n.length}</p>`}}return{async resolveSource(o,s){let a=o;a||(a=new b.AutkDb,await a.init());let{type:n,...l}=s;switch(n){case"osm":return await a.loadOsm(Z(l)),r(a,t),a;case"csv":return await a.loadCsv(l),r(a,t),a;case"json":return await a.loadJson(l),r(a,t),a;case"geojson":{const i=l;let u;i.geojsonFileUrl?u=await(await fetch(i.geojsonFileUrl)).json():u=i.geojsonObject,e&&u&&e.set(i.outputTableName,u);const c=u?(()=>{const f={...i,geojsonObject:u};return delete f.geojsonFileUrl,f})():i;try{await a.loadGeojson(c)}catch(f){const p=c.coordinateFormat?`coordinateFormat is set to "${c.coordinateFormat}"`:"no coordinateFormat was specified — defaulting to EPSG:4326 (WGS84 per RFC 7946)";throw new Error(`Failed to load GeoJSON layer "${c.outputTableName}": ${f instanceof Error?f.message:String(f)}. ${p}. Verify that coordinateFormat matches the actual CRS of the input data.`)}try{const f=await a.getBoundingBoxFromLayer(c.outputTableName),p=25e6;if(!isFinite(f.minLon)||!isFinite(f.minLat)||!isFinite(f.maxLon)||!isFinite(f.maxLat)||Math.abs(f.minLon)>p||Math.abs(f.maxLon)>p||Math.abs(f.minLat)>p||Math.abs(f.maxLat)>p)throw new Error(`Geometry bounding box after transform is invalid for layer "${c.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). Verify that coordinateFormat matches the actual CRS of the input data. The workspace uses ${b.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(f){if(f instanceof Error&&f.message.includes("bounding box after transform"))throw f}return r(a,t),a}case"heatmap":{const i=l;return await a.buildHeatmap({tableJoinName:i.tableJoinName,near:{distance:i.near.distance},outputTableName:i.outputTableName,grid:i.grid,...i.groupBy&&{groupBy:i.groupBy}}),r(a,t),a}case"join":{const i=l;if(await a.spatialQuery({tableRootName:i.tableRootName,tableJoinName:i.tableJoinName,...i.near&&{near:i.near},...i.groupBy&&{groupBy:i.groupBy}}),e){const u=await a.getLayer(i.tableRootName);e.set(i.tableRootName,u)}return r(a,t),a}default:return}}}}function tt(t,e){return e&&e.length>0?{type:v.ColorMapDomainStrategy.USER,params:e}:t?.mode===L.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:v.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:v.ColorMapDomainStrategy.PERCENTILE}:{type:v.ColorMapDomainStrategy.MIN_MAX}}function et(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function rt(t,e,r){const o=e.split("."),s={...t};let a=s;for(let n=0;n<o.length-1;n++)a[o[n]]={...a[o[n]]??{}},a=a[o[n]];return a[o[o.length-1]]=r,s}function at(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 ot(t,e,r,o){async function s(a,n,l){let i={};for(const u of n.getTablesMetadata())u.type!==void 0&&(i[u.name]=u.type);for(const u of l.layerRefs){const c=u.dataRef,f=i[c],p=u.getFnv,d=r?.get(c)??await n.getLayer(c),h=f==="raster"?d:{...d,features:(d.features??[]).filter(R=>R.geometry!=null)};f==="raster"?a.loadCollection(c,{collection:h,type:"raster",property:at(h,p)}):a.loadCollection(c,{collection:h,type:f}),u.opacity!=null&&a.updateRenderInfo(c,{opacity:u.opacity}),(u.isColorMap??(p!=null&&f!=="raster"))&&a.updateRenderInfo(c,{isColorMap:!0}),u.isPick&&a.updateRenderInfo(c,{isPick:!0}),u.isSkip&&a.updateRenderInfo(c,{isSkip:!0});const{catchAllCategory:g,colorMapDomain:y}=u;let A=h,S=y;if(p&&g&&y?.length){const R=new Set(y);A={...h,features:h.features.map(O=>{const J=O.properties,G=et(J,p);return G==null||!R.has(String(G))?{...O,properties:rt(J,p,g)}:O})},S=R.has(g)?y:[...y,g]}if(u.colorMapInterpolator){const R={interpolator:u.colorMapInterpolator,domainSpec:tt(u.normalization,S)};a.updateRenderInfo(c,{colormap:{config:R},isColorMap:!0})}if(p&&f!=="raster"){const R=p.startsWith("properties.")?p:`properties.${p}`;a.updateThematic(c,{collection:A,property:R})}}}return{async resolveMap(a,n,l=0){if(t&&t.map&&a){let i;if(Array.isArray(t.map)?i=document.getElementById(t.map[l]):i=document.getElementById(t.map),!i)throw new Error("Could not find rendering target for map: "+t.map);if(!(i instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const u=new M.AutkMap(i);if(n.style&&u.style.setPredefinedStyle(n.style),await u.init(),await s(u,a,n),e)for(const c of n.layerRefs)e.set(c.dataRef,u);o&&(o[l]=u),u.draw()}}}}function nt(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function it(t,e,r,o,s){return{async resolvePlot(a,n){if(!t||!t.plot)return;const l=document.getElementById(t.plot);if(!l)throw new Error(`Could not find plot target: ${t.plot}`);const i=a;if(!i)throw new Error("No data context available for plot.");const u=s?.get(n.dataRef)??await i.getLayer(n.dataRef),c=n.events??[],f=new w.AutkPlot(l,{type:nt(n.mark),collection:u,attributes:{axis:n.axis,...n.color&&{color:n.color}},labels:{axis:n.axis,title:n.title},events:c,...n.width&&{width:n.width},...n.height&&{height:n.height},...n.margins&&{margins:n.margins},...n.transform&&{transform:n.transform}});if(r?.set(n.dataRef,f),n.mapRef&&o?.set(n.dataRef,n.mapRef),n.mapRef&&e){const p=e.get(n.mapRef);if(p){p.updateRenderInfo(n.mapRef,{isPick:!0}),p.events.on(M.MapEvent.PICKING,({selection:d})=>{f.setSelection(d)});for(const d of c)f.events.on(d,({selection:h})=>{p.setHighlightedIds(n.mapRef,h)})}}}}}const N=134217728,st=4,ut=32;function U(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 C(t,e){return t instanceof Map?t.get(e):t[e]}function P(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function Q(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))_(o)&&e.push(o);return e}function $(t){return[...new Set([t.dataRef,...Q(t).map(e=>e.fromFeature.layer)])]}function I(t){for(const e of Q(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function k(t,e,r){const o=t.fromFeature,s=r!==void 0&&o.iterate==="all"?r:o.index??0,a=C(e,o.layer)?.features?.[s];return a?P(a,o.path):void 0}function T(t,e,r){if(!t)return;const o={};for(const[s,a]of Object.entries(t)){if(!_(a)){o[s]=a;continue}const n=Number(k(a,e,r)??NaN);Number.isFinite(n)?o[s]=n:typeof a.default=="number"&&(o[s]=a.default)}return o}function B(t,e,r){if(!t)return;const o={};for(const[s,a]of Object.entries(t)){if(!_(a)){o[s]=a;continue}const n=k(a,e,r),l=Array.isArray(n)?n:Array.isArray(a.default)?a.default:void 0;if(!l)continue;const i=a.cols??(Array.isArray(l[0])?l[0].length:0);i>0?o[s]={data:l,cols:i}:console.warn(`[autk-grammar] uniform matrix "${s}" has no column count; entry dropped`)}return o}function lt(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function Y(t){return _(t)&&t.fromFeature.iterate==="batched"}function x(t,e){return Object.values(e??{}).some(Y)?ut:Object.values(t??{}).some(Y)?st:0}function H(t,e,r=N){const o=x(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function V(t,e,r,o=N){const s={},a={},n=[];for(const i of[t,e])for(const u of Object.values(i??{}))_(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&n.push(u.fromFeature.path);if(n.length>0){const i=r.length;r=r.filter(u=>n.every(c=>lt(P(u,c)))),r.length<i&&console.info(`[autk-grammar] batched compute dropped ${i-r.length} feature(s) missing ${n.join(", ")}`)}const l=H(t,e,o);r.length>l&&(console.warn(`[autk-grammar] batched compute capped at ${l} features (got ${r.length}): its largest packed array takes ${x(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,l));for(const[i,u]of Object.entries(t??{}))if(_(u)&&u.fromFeature.iterate==="batched"){const c=typeof u.default=="number"?u.default:void 0;a[i]=r.map(f=>{const p=Number(P(f,u.fromFeature.path)??c);return Number.isFinite(p)?p:0})}else typeof u=="number"&&(s[i]=u);for(const[i,u]of Object.entries(e??{})){if(!_(u)||u.fromFeature.iterate!=="batched")continue;const c=[];for(const f of r){const p=P(f,u.fromFeature.path);let d=1/0,h=1/0,E=-1/0,g=-1/0;if(Array.isArray(p))for(const y of p){if(!Array.isArray(y)||y.length<2)continue;const A=Number(y[0]),S=Number(y[1]);!Number.isFinite(A)||!Number.isFinite(S)||(d=Math.min(d,A),h=Math.min(h,S),E=Math.max(E,A),g=Math.max(g,S))}Number.isFinite(d)||(d=0,h=0,E=0,g=0),c.push(d,h,E,h,E,g,d,g)}a[i]=c}return s.num_features=r.length,{uniforms:s,uniformArrays:a}}function F(t,e,r){const o=C(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const s={collection:o,variableMapping:t.attributes,wgslBody:U(t.wglsFunction)};t.attributeArrays&&(s.attributeArrays=t.attributeArrays),t.attributeMatrices&&(s.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(s.uniformArrays=t.uniformArrays),t.outputColumnName&&(s.resultField=t.outputColumnName),t.outputColumns&&(s.outputColumns=t.outputColumns);const a=I(t);if(a?.mode==="batched"){const u=C(e,a.layer)?.features??[],c=V(t.uniforms,t.uniformMatrices,u),f=T(W(t.uniforms),e)??{},p=B(W(t.uniformMatrices),e);return s.uniforms={...f,...c.uniforms},s.uniformArrays={...s.uniformArrays??{},...c.uniformArrays},p&&Object.keys(p).length>0&&(s.uniformMatrices=p),s}const n=a?.mode==="all"?r:void 0,l=T(t.uniforms,e,n),i=B(t.uniformMatrices,e,n);return l&&(s.uniforms=l),i&&(s.uniformMatrices=i),s}function W(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(_(e)&&e.fromFeature.iterate==="batched")))}function ft(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function q(t,e,r){const o=I(t);if(o?.mode!=="all")return r(F(t,e));const s=C(e,t.dataRef);if(!s)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const a=ft(t),n=structuredClone(s);for(const i of n.features){const u=i.properties??={},c=u.compute??={};for(const f of a)c[f]=0}const l=C(e,o.layer)?.features?.length??0;for(let i=0;i<l;i++){const u=await r({...F(t,e,i),collection:n});n.features.forEach((c,f)=>{const p=c.properties?.compute,d=u.features[f]?.properties?.compute;if(!(!p||!d))for(const h of a){const E=Number(d[h]);Number.isFinite(E)&&(p[h]+=E)}})}return n}function ct(t){return{async resolveCompute(e,r){if(e){const o={};for(const n of $(r)){const l=t?.get(n);if(l)o[n]=l;else if(n===r.dataRef)o[n]=await e.getLayer(n);else try{o[n]=await e.getLayer(n)}catch{o[n]=void 0}}const s=new X.AutkComputeEngine,a=await q(r,o,n=>s.gpgpuPipeline(n));return t&&t.set(r.dataRef,a),e}}}}class K{_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))}}class pt{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_data={};_mapRegistry=new Map;_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotMapLinks=new Map;interactions=new K;constructor(e){const r=new Map;this.dataAdapter=z(e,r),this.mapAdapter=ot(e,this._mapRegistry,this._computeCache,this._maps),this.plotAdapter=it(e,this._mapRegistry,this._plotRegistry,this._plotMapLinks,r),this.computeAdapter=ct(this._computeCache)}get workspaceCrs(){return b.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}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.");this._mapRegistry.clear(),this._maps.length=0,this._plotRegistry.clear(),this._plotMapLinks.clear(),this._computeCache.clear(),this.grammarEngine=D({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run(),this._rewireInteractions();const r=this.grammarEngine.context;if(!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const s of r.getLayersMetadata())Object.defineProperty(o,s.name,{get:()=>{const a=this._computeCache.get(s.name);return a?Promise.resolve(a):r.getLayer(s.name)},enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r){this._mapRegistry.get(e)?.setHighlightedIds(e,r);for(const[o,s]of this._plotMapLinks)s===e&&this._plotRegistry.get(o)?.setSelection(r)}clearHighlightOnMap(e){this._mapRegistry.get(e)?.clearHighlightedIds(e);for(const[r,o]of this._plotMapLinks)o===e&&this._plotRegistry.get(r)?.setSelection([])}clearHighlightOnPlot(e){this._plotRegistry.get(e)?.setSelection([]);const r=this._plotMapLinks.get(e);r&&this._mapRegistry.get(r)?.clearHighlightedIds(r)}setPlotSelection(e,r){this._plotRegistry.get(e)?.setSelection(r);const o=this._plotMapLinks.get(e);o&&this._mapRegistry.get(o)?.setHighlightedIds(o,r)}_rewireInteractions(){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const e=new Set;for(const[r,o]of this._mapRegistry){if(e.has(o))continue;e.add(o);const s=({selection:a})=>{this.interactions.emit("map:picking",{layerId:r,selection:a})};o.events.on(M.MapEvent.PICKING,s),this._fwdCleanups.push(()=>o.events.off(M.MapEvent.PICKING,s))}for(const[r,o]of this._plotRegistry)for(const s of[w.PlotEvent.CLICK,w.PlotEvent.BRUSH,w.PlotEvent.BRUSH_X,w.PlotEvent.BRUSH_Y]){const a=({selection:n})=>{this.interactions.emit("plot:selection",{plotId:r,event:s,selection:n})};o.events.on(s,a),this._fwdCleanups.push(()=>o.events.off(s,a))}}}m.AutkGrammar=pt,m.ColorMapInterpolator=j,m.GrammarEventEmitter=K,m.NormalizationMode=L,m.STORAGE_BUFFER_BINDING_SIZE=N,m.buildBatchedUniforms=V,m.computeLayerNames=$,m.createEngine=D,m.findIterateSource=I,m.isFromFeature=_,m.joinWgsl=U,m.maxBatchedFeatures=H,m.resolveComputeParams=F,m.resolveUniformMatrices=B,m.resolveUniforms=T,m.runCompute=q,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(m,R){typeof exports=="object"&&typeof module<"u"?R(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"],R):(m=typeof globalThis<"u"?globalThis:m||self,R(m["autk-grammar"]={},m.autkDb,m.autkMap,m.autkPlot,m.autkCore,m.autkCompute))})(this,(function(m,R,N,C,E,at){"use strict";function $(t){const{spec:e,adapters:r}=t;let o;async function i(){let n;if(e.data)for(const s of e.data)n=await r.db.resolveSource(n,s);if(e.compute)for(const s of e.compute)n=await r.compute.resolveCompute(n,s);if(e.map)if(Array.isArray(e.map))for(let s=0;s<e.map.length;s++){let c=e.map[s];await r.map.resolveMap(n,c,s)}else await r.map.resolveMap(n,e.map);if(e.plot)if(Array.isArray(e.plot))for(const s of e.plot)await r.plot.resolvePlot(n,s);else await r.plot.resolvePlot(n,e.plot);o=n}function a(n){return console.log("Spec to update",n),new Promise(s=>{s()})}function l(){console.log("Function not implemented yet")}return{run:i,updatedSpec:a,destroy:l,get context(){return o}}}var Q=(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))(Q||{}),B=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(B||{});function nt(t){const{autoLoadLayers:e,...r}=t;return{...r,autoLoadLayers:{layers:e?.layers??[]}}}function it(t,e){function r(o,i){if(!i||!i.db)return;const a=document.getElementById(i.db);if(a){const l=o.getTablesMetadata();a.innerHTML+="<ul>";for(const n of l)a.innerHTML+=`<li>${n.name}: (${n.source}, ${n.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${l.length}</p>`}}return{async resolveSource(o,i){let a=o;a||(a=new R.AutkDb,await a.init());let{type:l,...n}=i;switch(l){case"osm":return await a.loadOsm(nt(n)),r(a,t),a;case"csv":return await a.loadCsv(n),r(a,t),a;case"json":return await a.loadJson(n),r(a,t),a;case"geojson":{const s=n;let c;s.geojsonFileUrl?c=await(await fetch(s.geojsonFileUrl)).json():c=s.geojsonObject,e&&c&&e.set(s.outputTableName,c);const u=c?(()=>{const f={...s,geojsonObject:c};return delete f.geojsonFileUrl,f})():s;try{await a.loadGeojson(u)}catch(f){const p=u.coordinateFormat?`coordinateFormat is set to "${u.coordinateFormat}"`:"no coordinateFormat was specified — defaulting to EPSG:4326 (WGS84 per RFC 7946)";throw new Error(`Failed to load GeoJSON layer "${u.outputTableName}": ${f instanceof Error?f.message:String(f)}. ${p}. Verify that coordinateFormat matches the actual CRS of the input data.`)}try{const f=await a.getBoundingBoxFromLayer(u.outputTableName),p=25e6;if(!isFinite(f.minLon)||!isFinite(f.minLat)||!isFinite(f.maxLon)||!isFinite(f.maxLat)||Math.abs(f.minLon)>p||Math.abs(f.maxLon)>p||Math.abs(f.minLat)>p||Math.abs(f.maxLat)>p)throw new Error(`Geometry bounding box after transform is invalid for layer "${u.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). Verify that coordinateFormat matches the actual CRS of the input data. The workspace uses ${R.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(f){if(f instanceof Error&&f.message.includes("bounding box after transform"))throw f}return r(a,t),a}case"heatmap":{const s=n;return await a.buildHeatmap({tableJoinName:s.tableJoinName,near:{distance:s.near.distance},outputTableName:s.outputTableName,grid:s.grid,...s.groupBy&&{groupBy:s.groupBy}}),r(a,t),a}case"join":{const s=n;if(await a.spatialQuery({tableRootName:s.tableRootName,tableJoinName:s.tableJoinName,...s.near&&{near:s.near},...s.groupBy&&{groupBy:s.groupBy}}),e){const c=await a.getLayer(s.tableRootName);e.set(s.tableRootName,c)}return r(a,t),a}default:return}}}}function F(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function st(t,e){const r=new Set;for(const o of t.layerRefs){const i=F(o);if(r.has(i))throw new Error(`Map ${e} draws two layers with the id "${i}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(i)}}const lt=/^#[0-9a-fA-F]{6}$/;function k(t,e,r){if(!lt.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return E.ColorMap.hexToRgb(t)}function ut(t,e){const r={};return t.color!=null&&(r.color=k(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=k(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function ct(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function ft(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 pt(t,e,r,o){if(E.ColorMap.isCategorical(e.interpolator))return;let i=0,a=0;for(let s=0;s<t.length;s++){const c=t[s];Number.isFinite(c)&&(a++,r!=null&&(i=Math.max(i,Math.abs(c-r))))}const l=r!=null&&i>0;if(a===0||!l&&o!==!0)return;const n=l&&r!=null?[r-i,r,r+i]:E.ColorMap.resolveDomainFromData(t,e);return o===!0?[...n].reverse():n}function mt(t,e){return e&&e.length>0?{type:E.ColorMapDomainStrategy.USER,params:e}:t?.mode===B.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:E.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:E.ColorMapDomainStrategy.PERCENTILE}:{type:E.ColorMapDomainStrategy.MIN_MAX}}function dt(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function ht(t,e,r){const o=e.split("."),i={...t};let a=i;for(let l=0;l<o.length-1;l++)a[o[l]]={...a[o[l]]??{}},a=a[o[l]];return a[o[o.length-1]]=r,i}function yt(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 gt(t,e,r,o,i){async function a(l,n,s){let c={};for(const u of n.getTablesMetadata())u.type!==void 0&&(c[u.name]=u.type);for(const u of s.layerRefs){const f=u.dataRef,p=F(u),d=c[f],h=u.getFnv,y=r?.get(f)??await n.getLayer(f),g=d==="raster"?y:{...y,features:(y.features??[]).filter(_=>_.geometry!=null)},w=d==="raster"?yt(g,h):"";d==="raster"?l.loadCollection(p,{collection:g,type:"raster",property:w}):l.loadCollection(p,{collection:g,type:d}),u.opacity!=null&&l.updateRenderInfo(p,{opacity:u.opacity});const S=ut(u,p);Object.keys(S).length>0&&l.updateRenderInfo(p,S),ct(u,d)&&l.updateRenderInfo(p,{isColorMap:!0}),u.isPick&&l.updateRenderInfo(p,{isPick:!0}),u.isSkip&&l.updateRenderInfo(p,{isSkip:!0});const{catchAllCategory:A,colorMapDomain:v}=u;let tt=g,et=v;if(h&&A&&v?.length){const _=new Set(v);tt={...g,features:g.features.map(M=>{const L=M.properties,U=dt(L,h);return U==null||!_.has(String(U))?{...M,properties:ht(L,h,A)}:M})},et=_.has(A)?v:[...v,A]}const rt=d==="raster"&&u.transferFunction!=null;rt&&l.layerManager.searchByLayerId(p)?.setTransferFunction?.(u.transferFunction);const ot=d==="raster"&&(u.colorMapCenter!=null||u.colorMapReverse===!0);if(u.colorMapInterpolator||ot){const _={interpolator:u.colorMapInterpolator??l.layerManager.searchByLayerId(p)?.layerRenderInfo.colormap.config.interpolator??E.ColorMapInterpolator.SEQ_REDS,domainSpec:mt(u.normalization,et)},M=ot?ft(g,w):null,L=M?pt(M,_,u.colorMapCenter,u.colorMapReverse):void 0;L&&(_.domainSpec={type:E.ColorMapDomainStrategy.USER,params:L}),l.updateColorMap(p,{colorMap:_})}else rt&&l.updateColorMap(p,{colorMap:{}});if(h&&d!=="raster"){const _=h.startsWith("properties.")?h:`properties.${h}`;l.updateThematic(p,{collection:tt,property:_})}}}return{async resolveMap(l,n,s=0){if(t&&t.map&&l){st(n,s);let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[s]):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 u=new N.AutkMap(c);n.style&&u.style.setPredefinedStyle(n.style),await u.init(),await a(u,l,n);for(const f of n.layerRefs)e?.set(f.dataRef,u),i?.set(f.dataRef,F(f));o&&(o[s]=u),u.draw()}}}}function _t(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function Et(t,e,r,o,i,a){return{async resolvePlot(l,n){if(!t||!t.plot)return;const s=document.getElementById(t.plot);if(!s)throw new Error(`Could not find plot target: ${t.plot}`);const c=l;if(!c)throw new Error("No data context available for plot.");const u=i?.get(n.dataRef)??await c.getLayer(n.dataRef),f=n.events??[],p=new C.AutkPlot(s,{type:_t(n.mark),collection:u,attributes:{axis:n.axis,...n.color&&{color:n.color}},labels:{axis:n.axis,title:n.title},events:f,...n.width&&{width:n.width},...n.height&&{height:n.height},...n.margins&&{margins:n.margins},...n.transform&&{transform:n.transform}});if(r?.set(n.dataRef,p),n.mapRef&&o?.set(n.dataRef,n.mapRef),n.mapRef&&e){const d=e.get(n.mapRef),h=a?.get(n.mapRef)??n.mapRef;if(d){d.updateRenderInfo(h,{isPick:!0}),d.events.on(N.MapEvent.PICKING,({selection:y})=>{p.setSelection(y)});for(const y of f)p.events.on(y,({selection:g})=>{d.setHighlightedIds(h,g)})}}}}}const T=134217728,bt=4,At=32;function x(t){return Array.isArray(t)?t.join(`
2
+ `):t}function b(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function I(t,e){return t instanceof Map?t.get(e):t[e]}function P(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function V(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))b(o)&&e.push(o);return e}function Y(t){return[...new Set([t.dataRef,...V(t).map(e=>e.fromFeature.layer)])]}function O(t){for(const e of V(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function H(t,e,r){const o=t.fromFeature,i=r!==void 0&&o.iterate==="all"?r:o.index??0,a=I(e,o.layer)?.features?.[i];return a?P(a,o.path):void 0}function D(t,e,r){if(!t)return;const o={};for(const[i,a]of Object.entries(t)){if(!b(a)){o[i]=a;continue}const l=Number(H(a,e,r)??NaN);Number.isFinite(l)?o[i]=l:typeof a.default=="number"&&(o[i]=a.default)}return o}function G(t,e,r){if(!t)return;const o={};for(const[i,a]of Object.entries(t)){if(!b(a)){o[i]=a;continue}const l=H(a,e,r),n=Array.isArray(l)?l:Array.isArray(a.default)?a.default:void 0;if(!n)continue;const s=a.cols??(Array.isArray(n[0])?n[0].length:0);s>0?o[i]={data:n,cols:s}:console.warn(`[autk-grammar] uniform matrix "${i}" has no column count; entry dropped`)}return o}function Rt(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function W(t){return b(t)&&t.fromFeature.iterate==="batched"}function q(t,e){return Object.values(e??{}).some(W)?At:Object.values(t??{}).some(W)?bt:0}function K(t,e,r=T){const o=q(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function X(t,e,r,o=T){const i={},a={},l=[];for(const s of[t,e])for(const c of Object.values(s??{}))b(c)&&c.fromFeature.iterate==="batched"&&c.fromFeature.required&&l.push(c.fromFeature.path);if(l.length>0){const s=r.length;r=r.filter(c=>l.every(u=>Rt(P(c,u)))),r.length<s&&console.info(`[autk-grammar] batched compute dropped ${s-r.length} feature(s) missing ${l.join(", ")}`)}const n=K(t,e,o);r.length>n&&(console.warn(`[autk-grammar] batched compute capped at ${n} features (got ${r.length}): its largest packed array takes ${q(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,n));for(const[s,c]of Object.entries(t??{}))if(b(c)&&c.fromFeature.iterate==="batched"){const u=typeof c.default=="number"?c.default:void 0;a[s]=r.map(f=>{const p=Number(P(f,c.fromFeature.path)??u);return Number.isFinite(p)?p:0})}else typeof c=="number"&&(i[s]=c);for(const[s,c]of Object.entries(e??{})){if(!b(c)||c.fromFeature.iterate!=="batched")continue;const u=[];for(const f of r){const p=P(f,c.fromFeature.path);let d=1/0,h=1/0,y=-1/0,g=-1/0;if(Array.isArray(p))for(const w of p){if(!Array.isArray(w)||w.length<2)continue;const S=Number(w[0]),A=Number(w[1]);!Number.isFinite(S)||!Number.isFinite(A)||(d=Math.min(d,S),h=Math.min(h,A),y=Math.max(y,S),g=Math.max(g,A))}Number.isFinite(d)||(d=0,h=0,y=0,g=0),u.push(d,h,y,h,y,g,d,g)}a[s]=u}return i.num_features=r.length,{uniforms:i,uniformArrays:a}}function j(t,e,r){const o=I(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const i={collection:o,variableMapping:t.attributes,wgslBody:x(t.wglsFunction)};t.attributeArrays&&(i.attributeArrays=t.attributeArrays),t.attributeMatrices&&(i.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(i.uniformArrays=t.uniformArrays),t.outputColumnName&&(i.resultField=t.outputColumnName),t.outputColumns&&(i.outputColumns=t.outputColumns);const a=O(t);if(a?.mode==="batched"){const c=I(e,a.layer)?.features??[],u=X(t.uniforms,t.uniformMatrices,c),f=D(J(t.uniforms),e)??{},p=G(J(t.uniformMatrices),e);return i.uniforms={...f,...u.uniforms},i.uniformArrays={...i.uniformArrays??{},...u.uniformArrays},p&&Object.keys(p).length>0&&(i.uniformMatrices=p),i}const l=a?.mode==="all"?r:void 0,n=D(t.uniforms,e,l),s=G(t.uniformMatrices,e,l);return n&&(i.uniforms=n),s&&(i.uniformMatrices=s),i}function J(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(b(e)&&e.fromFeature.iterate==="batched")))}function wt(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function Z(t,e,r){const o=O(t);if(o?.mode!=="all")return r(j(t,e));const i=I(e,t.dataRef);if(!i)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const a=wt(t),l=structuredClone(i);for(const s of l.features){const c=s.properties??={},u=c.compute??={};for(const f of a)u[f]=0}const n=I(e,o.layer)?.features?.length??0;for(let s=0;s<n;s++){const c=await r({...j(t,e,s),collection:l});l.features.forEach((u,f)=>{const p=u.properties?.compute,d=c.features[f]?.properties?.compute;if(!(!p||!d))for(const h of a){const y=Number(d[h]);Number.isFinite(y)&&(p[h]+=y)}})}return l}function St(t){return{async resolveCompute(e,r){if(e){const o={};for(const l of Y(r)){const n=t?.get(l);if(n)o[l]=n;else if(l===r.dataRef)o[l]=await e.getLayer(l);else try{o[l]=await e.getLayer(l)}catch{o[l]=void 0}}const i=new at.AutkComputeEngine,a=await Z(r,o,l=>i.gpgpuPipeline(l));return t&&t.set(r.dataRef,a),e}}}}class z{_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))}}class Mt{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_data={};_mapRegistry=new Map;_mapLayerIds=new Map;_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotMapLinks=new Map;interactions=new z;constructor(e){const r=new Map;this.dataAdapter=it(e,r),this.mapAdapter=gt(e,this._mapRegistry,this._computeCache,this._maps,this._mapLayerIds),this.plotAdapter=Et(e,this._mapRegistry,this._plotRegistry,this._plotMapLinks,r,this._mapLayerIds),this.computeAdapter=St(this._computeCache)}get workspaceCrs(){return R.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayer(e){const r=this._mapRegistry.get(e);return r?{map:r,layerId:this._mapLayerIds.get(e)??e}:void 0}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.");this._mapRegistry.clear(),this._mapLayerIds.clear(),this._maps.length=0,this._plotRegistry.clear(),this._plotMapLinks.clear(),this._computeCache.clear(),this.grammarEngine=$({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run(),this._rewireInteractions();const r=this.grammarEngine.context;if(!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const i of r.getLayersMetadata())Object.defineProperty(o,i.name,{get:()=>{const a=this._computeCache.get(i.name);return a?Promise.resolve(a):r.getLayer(i.name)},enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r){const o=this.mapLayer(e);o?.map.setHighlightedIds(o.layerId,r);for(const[i,a]of this._plotMapLinks)a===e&&this._plotRegistry.get(i)?.setSelection(r)}clearHighlightOnMap(e){const r=this.mapLayer(e);r?.map.clearHighlightedIds(r.layerId);for(const[o,i]of this._plotMapLinks)i===e&&this._plotRegistry.get(o)?.setSelection([])}clearHighlightOnPlot(e){this._plotRegistry.get(e)?.setSelection([]);const r=this._plotMapLinks.get(e),o=r?this.mapLayer(r):void 0;o?.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r){this._plotRegistry.get(e)?.setSelection(r);const o=this._plotMapLinks.get(e),i=o?this.mapLayer(o):void 0;i?.map.setHighlightedIds(i.layerId,r)}_rewireInteractions(){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const e=new Set;for(const[r,o]of this._mapRegistry){if(e.has(o))continue;e.add(o);const i=({selection:a})=>{this.interactions.emit("map:picking",{layerId:r,selection:a})};o.events.on(N.MapEvent.PICKING,i),this._fwdCleanups.push(()=>o.events.off(N.MapEvent.PICKING,i))}for(const[r,o]of this._plotRegistry)for(const i of[C.PlotEvent.CLICK,C.PlotEvent.BRUSH,C.PlotEvent.BRUSH_X,C.PlotEvent.BRUSH_Y]){const a=({selection:l})=>{this.interactions.emit("plot:selection",{plotId:r,event:i,selection:l})};o.events.on(i,a),this._fwdCleanups.push(()=>o.events.off(i,a))}}}m.AutkGrammar=Mt,m.ColorMapInterpolator=Q,m.GrammarEventEmitter=z,m.NormalizationMode=B,m.STORAGE_BUFFER_BINDING_SIZE=T,m.buildBatchedUniforms=X,m.computeLayerNames=Y,m.createEngine=$,m.findIterateSource=O,m.isFromFeature=b,m.joinWgsl=x,m.maxBatchedFeatures=K,m.resolveComputeParams=j,m.resolveUniformMatrices=G,m.resolveUniforms=D,m.runCompute=Z,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
3
3
  //# sourceMappingURL=autk-grammar.umd.cjs.map