Skip to content

Architecture

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/bi-components/src/connectors/duckdb-wasm.js"></script>
<!-- or, inside a sandboxed iframe -->
<script type="module" src="https://unytics.io/bi-components/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, 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 options (period_comparison_method, date_granularity, or any key of your own).
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; a trailing alias (measures="sum(ca) as ca") is used as the displayed name. 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="revenue" by="region" compare="yoy">

The component sends an intention expressed with the names of a measures dictionary. The spec is what the engine behind the Host receives:

HTML attribute QuerySpec key
measure (charts, score cards) / measures (<data-table> only) metrics: string[]
by + breakdown-by dimensions: string[] \| null
attributes="store_name,city" 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
param-* params (see below)
global filters, minus the component's own dimension filters
global date range date_range

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

Extending the spec: params

The standard fields above are all the library knows. Anything specific to your connector or engine goes through param-* attributes, in both modes:

<score-card measure="revenue" param-scope="like_for_like" param-with-tax>
{ "mode": "semantic", "metrics": ["revenue"], "params": { "scope": "like_for_like", "with_tax": true } }

The library carries params without interpreting them (they also keep two score cards apart when batching). On the Host side they are dropped unless you validate them: give sanitizeParams: (params) => cleanParams to HostBridge, a function that returns what it accepts or throws.

Decided by the Host only

An iframe cannot add arguments to a query: unknown keys are dropped, and params only pass your validator. Whatever depends on the user (rights, row-level security, cache keys) is added by enforce, which is Host code.

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="revenue" granularity="month"> has no by).
  • formats: { column: "eur" | "pct" | "int" | "dec" }, used by axes, tooltips, score cards and tables. An explicit format / formats="revenue: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.
  • 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) that are identical apart from their metrics, issued within 4 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, restrictFilters } 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) => ({                                                    // Host rules, applied last
    ...spec,
    filters: restrictFilters(spec.filters, { region: user.regions }),      // row-level security
  }),
  resolveQuery: (spec) => callYourEngine(spec),                            // -> { rows, meta }
});

iframe.srcdoc = buildSrcdoc({ body: dashboardHtml, ...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, sort_by among the returned columns (including the time column of a time series, timeColumn, "date" by default); unknown keys are dropped;
  • accepts a query with a dimension and no metric as "the values of this dimension" (asked by <ui-filter>); valuesMetric names the metric to use if your engine needs one;
  • 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 BI Components modules as data: URLs (a sandboxed iframe cannot fetch them); buildSrcdoc puts the CSP first.

Calling a server from resolveQuery

resolveQuery usually forwards the validated spec to your backend with an HTTP call (fetch), one call per QUERY_REQ.

Streamlit

A Streamlit component value is not a message queue but a single state value, overwritten by each call. A dashboard sends several requests in the same millisecond (the batch of score cards, each chart, each table): sent one by one, only the last one would reach Python and the other components would wait until their timeout.

The Streamlit server of the playground shows the pattern that works, with st.components.v2: resolveQuery gathers the queries during a fixed 10 ms window, then sends every query still waiting for an answer as one value; Python answers the missing ones and reruns once. See Embed in your app.

Row-level security

Apply the user's restrictions in enforce with restrictFilters, which intersects them with what the iframe asked instead of overwriting it:

import { restrictFilters } from './src/connectors/host-bridge.js';

enforce: (spec) => ({ ...spec, filters: restrictFilters(spec.filters, { store_code: ['M001', 'M002', 'M003'] }) })
  • no filter asked on the dimension: the user's three stores;
  • a click on M001: M001 only, so cross-filtering keeps working on restricted dimensions;
  • only values outside the user's scope (M999): the query is refused with an access error;
  • a user whose allowed list is empty: refused as well. An empty list never means "no restriction".

Security model: a dashboard written by someone else

The case to design for: a malicious author writes a dashboard (HTML and JavaScript, both allowed), and another person opens it. The dashboard then runs with the rights of the person looking at it.

What the author's code can do, by design

  • Query anything the viewer is allowed to see (dictionary and row-level security apply to the viewer, not to the author), and display whatever it wants inside its frame, including wrong numbers or a fake form.
  • Send messages to the Host: queries, filter changes, error reports.

What it cannot do

Attack Stopped by
Read the Host page, its cookies, storage or tokens sandbox="allow-scripts" without allow-same-origin: the dashboard has its own empty origin. HostBridge refuses to start on an iframe with any other sandbox flag.
Send data out with fetch, images, CSS, fonts, forms, beacons The CSP of the dashboard (default-src 'none', connect-src 'none', form-action 'none').
Navigate itself to https://evil.example/?data=... buildSrcdoc puts the dashboard in a second sandboxed frame, inside a small document written by the library whose CSP is frame-src 'none'. The Host needs no configuration for this.
Navigate the Host page, open popups or dialogs, start downloads The sandbox (no allow-top-navigation, allow-popups, allow-modals, allow-downloads).
Run SQL or ask for anything outside the dictionary HostBridge validation; table mode is off by default.
See more than the viewer enforce and restrictFilters, which run on the Host.
Flood the engine in the viewer's name maxPendingQueries (200 at a time by default).

What remains, and what the Host must do about it

The browser no longer lets data out directly, so the remaining ways out go through the Host or through the viewer:

  1. Anything the Host stores or shows to other people is a way out. The dashboard chooses the filter values, the options and the text of its error reports. If the Host saves that state in a shared place (a saved view, a shareable URL) or shows a dashboard's errors to its author, the author can encode the viewer's data in it and read it later.
    • Keep what comes from the iframe private to the viewer. Do not persist it in anything the author can read.
    • Never give onRuntimeError messages to the author or to a shared log without review. HostBridge clips them (500 characters, 2000 for the stack) and bounds filter values (256 characters), which limits the volume but does not close the channel.
  2. variables are readable by the dashboard. Never put tokens, e-mail addresses or anything secret in them.
  3. Other message listeners of your page. The dashboard can call postMessage on any window above it. HostBridge only accepts messages from its own iframe; your other message listeners must check event.source or event.origin (which is "null" for the dashboard) too.
  4. The viewer can be fooled. The dashboard can ask the viewer to copy a text, scan a QR code or type a password. Show clearly, outside the frame, who wrote the dashboard, and never let a dashboard's content look like your own interface.
  5. Low-volume technical channels. WebRTC and DNS hints are not covered by connect-src. The first script of the dashboard removes the WebRTC constructors and any nested frame (which would get them back), but this is JavaScript defense in depth, not a browser guarantee. A determined author may still leak a few bytes per second.
  6. Availability. A dashboard can freeze the tab with an endless loop. Nothing here prevents it; reloading without the dashboard does.

In short: with these protections a malicious dashboard cannot take over the viewer's session or the Host, and has no direct way to send data out. Treat what it shows as untrusted, and treat what it sends you as untrusted text you keep private.

Checked in Chromium by the end-to-end tests (navigation, nested frames, WebRTC, network requests). Other browsers have not been tested.

Where the iframe gets its libraries

The components import ECharts by its jsDelivr URL. bundleModules(urls, { libraries }) decides what that URL resolves to inside the iframe, with an import map, and returns the matching CSP:

libraries The iframe loads the libraries from Origins allowed by the CSP
'inline' (default) copies embedded in the srcdoc by the Host none: no network access at all
{ origin: 'https://cdn.acme.com' } your own CDN that origin only
'jsdelivr' the public jsDelivr CDN https://cdn.jsdelivr.net only
  • Inline adds about 1.45 MB to the srcdoc (ECharts). The Host fetches the libraries once per page and reuses them for every iframe. source: (libraryUrl) => url makes the Host fetch them from its own domain instead of jsDelivr.
  • Your own CDN must send CORS headers (the iframe has an opaque origin). Files are expected at the same paths as on jsDelivr (/npm/echarts@6.1.0/dist/echarts.esm.min.js); pass url: (libraryUrl) => yourUrl for another layout.

A standalone page (no iframe) can redirect the libraries the same way, with its own import map placed before the BI Components scripts:

<script type="importmap">
{ "imports": { "https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.esm.min.js": "/vendor/echarts.esm.min.js" } }
</script>

Theme

window.dashboard.theme.mode drives data-theme on <html>. Components read CSS variables: --bic-bg, --bic-fg, --bic-border, --bic-primary, --bic-success, --bic-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());