@bmap-analytics/core
v0.12.0
Published
BMAP analytics client — embed sessions, dashboards, and data. Framework agnostic.
Maintainers
Readme
@bmap-analytics/core
The framework-agnostic BMAP client. Use it directly in Vue, Svelte, Angular, or vanilla
JS; @bmap-analytics/react is a thin layer over it.
npm install @bmap-analytics/coreQuick start
import { createEmbedClient } from "@bmap-analytics/core";
const client = createEmbedClient({
baseUrl: "https://analytics.acme.com",
// From your backend. See @bmap-analytics/node.
token: () => fetchTokenFromMyServer(),
});
const { dashboard, data } = await client.load();
for (const widget of dashboard.widgets) {
const result = data.widgets.find((w) => w.widgetId === widget.id);
renderWithMyChartLibrary(widget.chart.type, result);
}Two clients, two credentials
| | createEmbedClient | createWorkspaceClient |
|---|---|---|
| token | an embed token your backend minted | the signed-in viewer's own BMAP token |
| scope | exactly one dashboard | whatever that account may see |
| can list? | no, by construction | yes |
EmbedClient does exactly what its token permits: read the one dashboard it was minted
for, and run that dashboard's widgets. There is no method that takes a dashboard id, no
method that takes a security context, and no way to supply an API key. That is not a gap
to be filled in a later version — the absence is the guarantee.
Listing therefore lives in WorkspaceClient, where the credential is one the viewer
already holds: everything it reaches, they could reach by signing in to BMAP and looking.
It adds no read, it saves the trip.
Listing dashboards and widgets
For a frontend-only integration — the viewer signs in to BMAP, picks a dashboard, and you mint them an embed token for it.
import { createWorkspaceClient } from "@bmap-analytics/core";
const workspace = createWorkspaceClient({
// Your BMAP deployment. There is no default — BMAP is installed per customer, so no
// address is right for everyone.
baseUrl: import.meta.env.VITE_BMAP_URL,
token: () => mySignedInUsersBmapToken(),
});
// Only once there is a viewer. A `token` function returns null before anyone has signed in,
// and calling then is refused — with a message saying so, but refused. Gate the call on your
// own session rather than letting a menu render itself into the error.
if (isSignedIn()) {
// Scoped by the server to their organization and their row rules — nothing to filter.
const dashboards = await workspace.dashboards.list();
const openable = dashboards.filter((d) => d.embeddable); // published, with a version
// The same `Dashboard` shape `EmbedClient.dashboard()` returns, so one renderer does both.
const detail = await workspace.dashboards.get(openable[0].id);
}
await workspace.widgets.list(); // every saved widget
await workspace.widgets.list({ dashboardId }); // one dashboard's tiles, in order
await workspace.widgets.list({ queryId }); // widgets drawing one query
await workspace.widgets.list({ withPlacements: true }); // + where each one appears
await workspace.widgets.placements(); // Map<widgetId, WidgetPlacement[]>
workspace.invalidate(); // after publishing or savingIn React, use the hooks instead — useDashboards() and useWidgets() in
@bmap-analytics/react handle the "no viewer yet" state as a state rather than as
an exception, which is what a component wants.
withPlacements and placements() read every dashboard to answer "where does this widget
appear", so they cost a request per dashboard (six at a time) rather than one. They are
opt-in for that reason. A widget with an empty placements is saved but not placed
anywhere, which is a normal state.
From a pick to a rendered dashboard
// The whole flow, once someone has chosen one.
const client = workspace.openDashboard(dashboardId);
const { dashboard, data } = await client.load();openDashboard mints an embed token from the viewer's own identity — no security context
is passed, or could be: the viewer is the caller, so a context they could type is a context
they could choose, and the server derives it from their identity instead. It grants no read
they did not already have; it exchanges a broad credential for a narrow one.
It also keeps that token alive. Embed tokens last ten minutes by default and
createEmbedClient asks for one on every request, so this re-mints when the current token
nears expiry — a page left open over lunch keeps working. Minting is lazy and shared: no
token is requested until the client is used, and ten widgets rendering at once produce one
session rather than ten rows in the audit trail.
For the raw token, e.g. to hand to something else:
const session = await workspace.createEmbedToken({ dashboardId, ttlSeconds, origin });
// { token, sessionId, dashboardId, expiresAt }Pass a viewer's token, never an API key. An API key is tenant-wide, and in a browser it
lets any viewer mint a token with any security context — so one is refused on sight, as is
an embed token (which is locked to a single dashboard and belongs to createEmbedClient).
Embed client API
await client.dashboard(); // layout, widget names, chart specs, filters (cached)
await client.data({ parameters }); // run every widget
await client.load(); // both, in parallel
await client.widgetResults(); // Map<widgetId, result>
await client.filterValues(key); // the options one select filter offers this viewer
client.invalidate(); // drop the cached definitionPassing token as a function rather than a string is what lets a long-lived page refresh
without rebuilding the client.
Filters
A dashboard's filter bar arrives on the definition as dashboard.filters, with the authored
starting values already keyed by parameter name in dashboard.defaultParameters. Driving a
filter is setting a parameter: each one names the query parameter it writes
(parameter, or parameterFrom/parameterTo for a range), and reaches only the widgets
whose saved query declares that name — a chart unrelated to time does not silently acquire a
date filter.
const { dashboard } = await client.load();
const filter = dashboard.filters.find((f) => f.kind === "select")!;
const list = await client.filterValues(filter.key, { search: "no" });
// { column, values, truncated }filterValues takes a filter key, not a dataset and a column. That is the server's
contract and the reason it is safe to call from a browser: an embed token is scoped to one
dashboard, and naming a column instead would turn this into a way to enumerate any column in
the tenant. The list is narrowed by the token's own security context too, so two viewers of
the same dashboard are offered different options — nobody is shown the existence of a value
they could not have queried.
search narrows server-side, and is worth using rather than filtering the returned array:
the list is capped, and truncated is how you learn there are values that never reached it.
A relative window — "last 30 days" — is sent as a parameter value of
{ $relative: { unit, count, anchor, includeCurrent } } rather than resolved here. The server
knows the tenant's timezone, resolves it once for every widget on the dashboard, and resolves
it the same way for a scheduled report, which has no browser at all.
Token helpers
import { decodeToken, shouldRefresh } from "@bmap-analytics/core";
decodeToken(token); // { expiresAt, dashboardId, sessionId }
shouldRefresh(token, 60); // true within 60s of expiryA JWT payload is base64, not encrypted, so the browser can read when a token expires. That is how the SDK refreshes before a request fails. None of it is a security check — the server verifies the signature on every request.
Script steps run in the browser
Most of a widget's post-query shaping happens in the engine. A Script step does not: it is JavaScript over the result, so the server passes those rows through and tells the client there is work outstanding.
EmbedClient handles this for you. data() and load() apply a widget's script steps
before returning, so rows reach your chart already shaped:
const { data } = await client.load(); // scripts already appliedThere is nothing to enable and nothing to install. It matters that it is automatic: a client that ignored the steps would draw numbers the dashboard's author never intended — not an error, just a quietly different answer on one surface.
Each script runs in a sandboxed iframe with an opaque origin and default-src 'none'. It can
compute, and it can reach nothing — no network, no cookies, no access to your page. Scripts
are capped at a few seconds; one that overruns fails its widget instead of hanging the tile.
A failing script becomes that widget's error, never a thrown exception — one tile that
cannot render must not blank the other nine. The rows are dropped rather than shown unshaped,
since displaying the server's raw numbers under a widget whose author asked for a
transformation would present figures nobody chose.
Applying them yourself
Only needed if you fetch rows through your own path rather than EmbedClient:
import { applyClientQlops, runScript } from "@bmap-analytics/core";
const { result, report } = await applyClientQlops(widgetResult, steps);
report?.logs; // whatever the script logged, for a debug panel
report?.failedStep; // set when one failed; the reason is on result.error
// Or run one script directly — what the Studio's editor preview uses.
const outcome = await runScript("function ScriptRun(rows) { return rows }", rows);The steps arrive with the dashboard definition, from the same backend as the rows. Browser execution adds no service to the path.
Errors
import { BmapError } from "@bmap-analytics/core";
try {
await client.data();
} catch (error) {
if (error instanceof BmapError && error.isRecoverableWithNewToken) {
await refreshMyToken();
}
}network, server, and rate_limited are retried automatically with exponential backoff
and jitter. forbidden is not — retrying a misconfiguration forever just makes it look
like an outage.
Per-widget errors are normal
A widget whose query cannot run returns an error string instead of rows, and the other
widgets still return data. One tile that cannot render must not blank the other nine, so
check result.error per widget rather than assuming the request either worked or did not.
ESM and CJS, TypeScript declarations, source maps, sideEffects: false, zero dependencies.
