Skip to content

Architecture

Static BI components are decoupled from the way queries are executed. A component only knows one thing: window.dashboard.

 <score-card>  <bar-chart>  <line-chart>  <data-table>  <ui-filter>   custom scripts
        \            |            |             |            |            /
         +-------------------- window.dashboard ---------------------+
                     |                                   |
        connectors/duckdb-wasm.js            connectors/iframe-bridge.js
        DuckDB-WASM in the browser           postMessage  <->  Host (connectors/host-bridge.js)
        (static files, zero backend)         (sandboxed iframe, queries run in the parent app)

Pick a connector with one script tag; nothing else changes in the page:

<script type="module" src="https://unytics.io/static_bi/src/connectors/duckdb-wasm.js"></script>
<!-- or, inside a sandboxed iframe -->
<script type="module" src="https://unytics.io/static_bi/src/connectors/iframe-bridge.js"></script>

The window.dashboard contract

Member Description
query(specOrQueryId, { timeoutMs = 30000 }) Returns Promise<{ rows, meta }>. Takes a QuerySpec object, or the id (string) of a named query: a query registered by the Host, or a <source-view> of the page with the DuckDB connector. meta is optional rendering help: { time_col, formats, comparisons, benchmarks, labels }. When filters / date_range are omitted from the spec, the current global state is used.
filters.get(dimension) / filters.getAll() Current selection: string, string[] or undefined.
filters.set(dimension, value) Sets a filter, or removes it with null.
filters.toggle(dimension, value, { multi }) What a click does. Simple click: select / unselect the value. multi: true (Ctrl / Cmd + click): add / remove the value of a multi-selection.
filters.clear() Removes every dimension filter.
filters.getDateRange() / filters.setDateRange([start, end] \| null) The date range ("YYYY-MM-DD" strings), kept apart from dimension filters.
filters.getOptions() / filters.setOption(key, value) Global business options (perimetre_amounts, period_comparison_method, date_granularity...).
variables Read-only configuration values given by the Host.
theme { mode: "light" \| "dark", palette: string[] }.
subscribe(callback) callback({ type }) is called on every change: filters, dateRange, options, variables, theme, sourcesReady. Returns unsubscribe().
registerSource(config) Used by <source-table> / <source-view> with the DuckDB connector: { name, url \| data \| sql, columns, dateColumn }.
ready() Tells the Host that the initial render is done. Called automatically when every component has rendered once.

Two additions exist for scripts: sync({ theme, variables, ... }) pushes a state from outside (this is what a Host's STATE_SYNC does, and how a standalone page switches to dark mode), and with the DuckDB connector sql(query) runs raw SQL on the local database.

The QuerySpec, in two modes

The presence of the table attribute decides the mode.

Table mode: table="..." is present

<bar-chart table="stocks" measure="avg(stock_value)" by="company" breakdown-by="sector" order_by="avg(stock_value) desc" limit="20">
{
  "mode": "table",
  "table": "stocks",
  "metrics": ["avg(stock_value)"],
  "dimensions": ["company"],
  "breakdown": "sector",
  "attributes": [],
  "filters": { "country": ["US", "FR"] },
  "date_range": ["2026-01-01", "2026-11-30"],
  "sort_by": "avg(stock_value)",
  "sort_ascending": false,
  "limit": 20
}

Measures and dimensions are SQL expressions. The SQL itself is only written by the connector (sql_compiler.js): WHERE (with IN (...) for multi-selections and the date range when the table has a date-column), GROUP BY, ORDER BY, LIMIT. Result rows are keyed by the exact strings of the spec (row["avg(stock_value)"]).

Semantic mode: no table attribute

<bar-chart measure="ca_ttc" by="region" compare="yoy">

The component sends an intention expressed with the names of a measures dictionary. The spec is aligned with the signature of the Python engine living behind the Host:

HTML attribute QuerySpec key
measure (charts, score cards) / measures (<data-table> only) metrics: string[]
by + breakdown-by dimensions: string[] \| null
attributes="nom_magasin,ville" attributes: string[] \| null
granularity="day\|week\|month\|quarter\|year" date_granularity
compare="yoy\|mom\|prev_period" period_comparison_method
sort-by (or order_by), sort-asc, limit sort_by, sort_ascending, limit
benchmark="..." benchmark_mode
perimetre-amounts (or the global option) perimetre_amounts: boolean
global filters, minus the component's own dimension filters
global date range date_range

granularity, compare and benchmark written without a value follow the global option of the same meaning (date_granularity, period_comparison_method, benchmark_mode), so a <ui-filter option="date_granularity"> can drive them.

Decided by the Host only

allow_read_non_store_entity and cache_by can never be set from the HTML or from the iframe. The Host drops them from any incoming message and injects its own values from the authenticated user.

One measure per chart, several per table

Charts and score cards take a single measure (one coherent Y axis); several series come from breakdown-by. Only <data-table> accepts measures="sum(a), round(avg(b), 2)": commas inside parentheses do not split.

What meta is used for

  • time_col: name of the time column of a semantic time series (<line-chart measure="ca_ttc" granularity="month"> has no by).
  • formats: { column: "eur" | "pct" | "int" | "dec" }, used by axes, tooltips, score cards and tables. An explicit format / formats="ca_ttc:eur" attribute wins.
  • comparisons: { metric: column holding the comparison value }. Score cards show a colored variation badge, line and bar charts draw the comparison period.
  • benchmarks: { metric: column holding the benchmark value }, drawn as a dashed series.
  • labels: { column: display name }.

Connector 1: duckdb-wasm.js

window.dashboard powered by DuckDB-WASM in a Web Worker. It registers the sources declared by <source-table> (Parquet, CSV, JSON, records) and <source-view> (SQL), compiles table-mode specs and runs them locally. Queries wait for their table to be loaded. A global filter only applies to the tables that have the filtered column. src/connectors/duckdb.js (v1 url) re-exports it.

Connector 2: iframe-bridge.js + host-bridge.js

For untrusted or generated dashboards. The page runs in

<iframe sandbox="allow-scripts" referrerpolicy="no-referrer" srcdoc="..."></iframe>

with a CSP connect-src 'none' as first element of its <head>: opaque origin, no network, no access to the parent DOM, cookies or storage. iframe-bridge.js implements window.dashboard with serialized postMessage messages only:

Message Direction Payload
BRIDGE_READY iframe → Host the bridge is installed, waiting for the state
STATE_SYNC Host → iframe { payload: { filters, dateRange, options, variables, theme } }
QUERY_REQ iframe → Host { reqId, spec }
QUERY_RES Host → iframe { reqId, rows, meta } or { reqId, error }
FILTER_SET iframe → Host { filters, dateRange, options } after a user interaction
DASHBOARD_READY iframe → Host initial render done
RUNTIME_ERROR iframe → Host { message, line, stack } from window.onerror / unhandled rejections
  • Batching: semantic queries without dimensions (score cards) sharing the same filters, date range, comparison, benchmark and perimeter, issued within 15 ms, travel as one QUERY_REQ with all their metrics. Each caller gets back its own metric.
  • Timeouts and replacement: a request times out after 30 s by default; a new query of a component replaces its previous one, whose late answer is ignored.
  • No flicker: theme or filter changes are pushed with STATE_SYNC; the srcdoc is never reloaded.

On the Host side, HostBridge:

import { HostBridge, bundleModules, buildSrcdoc } from './src/connectors/host-bridge.js';

const bridge = new HostBridge({
  iframe,
  dictionary: { metrics: [...], dimensions: [...], attributes: [...] },   // white lists
  allowTableMode: false,                                                   // reject mode "table" and raw SQL
  enforce: (spec) => ({                                                    // server-side rules, applied last
    ...spec,
    filters: { ...spec.filters, region: user.region },                     // row-level security
    allow_read_non_store_entity: user.isHeadOffice,
    cache_by: [`user:${user.id}`],
  }),
  resolveQuery: (spec) => callYourEngine(spec),                            // -> { rows, meta }
});

iframe.srcdoc = buildSrcdoc({ body: dashboardHtml, modules: await bundleModules([...]) });
bridge.setState({ theme: { mode: 'dark' } });                              // STATE_SYNC, no reload
  • accepts a message only if event.source === iframe.contentWindow (the origin of a sandboxed iframe is "null", so it proves nothing);
  • rebuilds every spec from a strict schema: names from the dictionary, primitives only in filters, bounded limit; unknown keys are dropped;
  • with allowTableMode: true and tables: { name: [columns] }, checks that every SQL expression only uses known columns and a list of safe functions (no sub-query, no table function) before compilation;
  • bundleModules inlines the static_bi modules as data: URLs (a sandboxed iframe cannot fetch them); buildSrcdoc puts the CSP first.

The iframe needs script-src https://cdn.jsdelivr.net to load ECharts. If that is too permissive for you, serve ECharts from your own domain or inline it, and tighten csp accordingly.

Theme

window.dashboard.theme.mode drives data-theme on <html>. Components read CSS variables: --sbi-bg, --sbi-fg, --sbi-border, --sbi-primary, --sbi-success, --sbi-error, which default to the DaisyUI variables (--color-base-100, --color-base-content, --color-base-300, --color-primary...) when the page defines them. The same values feed an ECharts theme named "app", so custom charts match the built-in ones:

const chart = window.echarts.init(element, 'app');
window.dashboard.subscribe((change) => change.type === 'theme' && rebuildMyChart());