@hypequery/embed
v0.1.0
Published
Embed Hypequery's hosted analytics chat and dashboards in any web page with an iframe.
Maintainers
Readme
@hypequery/embed
Put a hypequery project's chat and dashboards in your product. hypequery hosts
the embed; your page frames it with mountEmbed, which handles the iframe,
the handshake, tokens and the commands and events between your page and the
embed. Any web page works, with or without a framework.
npm install @hypequery/embedimport { mountEmbed } from "@hypequery/embed";
const embed = mountEmbed({
container: document.getElementById("analytics"),
url: "https://app.hypequery.com/embed/acme-analytics",
getToken: () => fetch("/api/hypequery-token", { method: "POST" }).then((r) => r.json()),
onEvent: (event) => console.info(event),
});
embed.ask("How are we trending?");To build your own AI or your own UI instead, use hypequery Core:
@hypequery/agent gives your agent typed, tenant-scoped tools, and
@hypequery/react gives your components the data without an assistant.
1. Allow your origins
In hypequery Cloud, add each origin your pages run on to the project's
allowed origins (Customer access › Where your app runs): https://app.acme.com,
https://*.acme.com for its subdomains, or http://localhost:3000 while you
develop. The list does two things:
- Framing. The hosted embed's Content-Security-Policy sends that list as
frame-ancestors, so the browser refuses to show it in a page on any other origin. With no origins listed, it can't be framed at all. - Talking. The embed answers postMessage only from the window that framed
it, and only if its origin is listed.
mountEmbedlikewise accepts messages only from its own iframe and the embed's origin.
2. Mint tokens on your server
Each end user gets a short-lived token, minted by your backend for the
signed-in user. The embed asks your page for one when it starts and again
before it expires; your page calls getToken, which calls your backend.
Tokens are passed over postMessage and kept in memory: never in a URL, a
cookie or storage. Any of these works:
A server API key: your backend calls
POST /embed/tokenson the project's customer API domain with the key, and returns the response's{ token, expiresAt }.// POST /api/hypequery-token, in your backend const response = await fetch("https://acme-analytics.hypequery.app/embed/tokens", { method: "POST", headers: { authorization: `Bearer ${process.env.HYPEQUERY_SERVER_KEY}`, "content-type": "application/json", }, body: JSON.stringify({ subject: session.userId, tenantId: session.orgId, permissionSet: "customers", }), }); const { token, expiresAt } = await response.json(); return Response.json({ token, expiresAt });A managed signing key: create one in Cloud and sign tokens locally with
mintAgentTokenfrom@hypequery/agent, with no network call. Tokens last at most 15 minutes.import { mintAgentToken } from "@hypequery/agent"; const { token, expiresAt } = await mintAgentToken({ signingKey: process.env.HYPEQUERY_AGENT_KEY!, tenant: session.orgId, subject: session.userId, permissionSet: "customers", }); return Response.json({ token, expiresAt });Your identity provider's JWT, when the project trusts your issuer.
getToken returns the token, or { token, expiresAt }; expiresAt may be an
ISO string, a Date, milliseconds, or a JWT's exp in seconds. The tenant
comes from the token, so an end user only ever sees their own tenant's rows,
through their permission set.
3. Mount it
import { mountEmbed, type HostEvent } from "@hypequery/embed";
const embed = mountEmbed({
container, // where the iframe goes
url: "https://app.hypequery.com/embed/acme-analytics",
getToken,
onEvent: (event: HostEvent) => {},
onThreadChange: (threadId) => {}, // keep it in your URL, if you like
onDashboardChange: (dashboardId) => {},
});url is https://app.hypequery.com/embed/{endpoint}, where {endpoint} is
the one in the project's customer API domain ({endpoint}.hypequery.app).
Without a build step
Your customer API domain serves mountEmbed as one script (about 2 KB), so a
plain HTML page needs no package or bundler. It sets window.hypequery:
<div id="analytics" style="height: 640px"></div>
<script src="https://acme-analytics.hypequery.app/sdk/v2/embed.js"></script>
<script>
hypequery.mountEmbed({
container: document.getElementById("analytics"),
url: "https://app.hypequery.com/embed/acme-analytics",
getToken: () => fetch("/api/hypequery-token", { method: "POST" }).then((r) => r.json()),
});
</script>v2 is the bridge version (below): fixes reach the same URL within an hour.
Options
| Option | |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| container | The element the iframe goes in. |
| url | The project's hosted embed. |
| getToken | () => Promise<token \| { token, expiresAt }>, called whenever the embed needs a token. |
| view | "chat" (the default: chat, recent threads and dashboards) or "dashboard" (one dashboard on its own). |
| threadId | The conversation to open; null for a new one. |
| dashboardId | The dashboard to open; with view: "dashboard", the one to show. |
| chat | With view: "dashboard": offer the chat beside it. |
| theme | Colors, chart palette, radius, fonts and density (EmbedTheme). |
| pageFilters | Filters from your page (QueryFilter[]) every query carries, shown as locked chips. |
| starterPrompts, greeting, locale | What a new conversation shows. |
| title | The iframe's accessible name; "Analytics assistant" by default. |
| autoResize | Grow the iframe to its content, e.g. a dashboard in a page that scrolls. Off by default: the iframe fills its container's height. |
| onEvent, onThreadChange, onDashboardChange | What the embed reports (below). |
Commands
mountEmbed returns the iframe and these commands. Commands sent before the
embed is ready are queued, and if the embed reloads it gets the options as
the commands have left them.
| Command | |
| ------------------------------------ | ---------------------------------------- |
| ask(text) | Ask a question in the open conversation. |
| openThread(threadId \| null) | Open a conversation, or start a new one. |
| openDashboard(dashboardId \| null) | Open a dashboard, or close it. |
| setContext(pageFilters) | Replace your page's filters. |
| setTheme(theme) | Restyle the embed. |
| destroy() | Remove the iframe and stop listening. |
A page filter compares one of the dataset's declared filters with a value:
embed.setContext([
{
kind: "comparison",
operator: "eq",
left: { kind: "reference", name: "region" },
right: { kind: "literal", value: "EMEA" },
},
]);Events
onEvent receives a HostEvent. Events carry the query and counts, never
result rows: a page that needs the data fetches it.
| Event | |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| { type: "answer", threadId, answer, rowCount } | The assistant answered with a chart: its title, dataset, query and chart spec. |
| { type: "dashboardSaved", dashboardId, revision } | The end user or the assistant saved a dashboard. |
| { type: "error", code, message } | Something failed in the embed. |
| { type: "usageLimit", message, limit?, retryAfterSeconds? } | A usage limit refused a message. limit is user-messages, tenant-messages or tenant-tokens. The embed already says so; this is for your own UI. |
onThreadChange and onDashboardChange report the open conversation and
dashboard as the end user moves between them.
Theme
embed.setTheme({
colorScheme: "dark",
colors: { accent: "#0f766e" },
chartPalette: ["#0f766e", "#7c3aed"],
radius: { lg: "16px" },
fontFamily: "Inter, sans-serif",
density: "compact",
});Anything left out keeps hypequery's default for the color scheme.
icon replaces hypequery's mark on the empty chat and beside each reply:
an https: URL on an origin listed exactly in the project's allowed origins
(a https://*. wildcard entry doesn't cover it), a data:image/ URL
(png, jpeg, gif, webp or svg+xml), { light, dark } to follow colorScheme,
or "none" to show no mark. Anything else, or an image that fails to load,
shows hypequery's mark.
embed.setTheme({
icon: { light: "https://app.acme.com/mark.svg", dark: "https://app.acme.com/mark-dark.svg" },
});Versions
BRIDGE_VERSION is the postMessage protocol between your page and the embed,
and EMBED_PROTOCOL_VERSION the shape of what the embed reports. Both are 2.
mountEmbed and the hosted embed ignore messages from another bridge
version.
Public API
@hypequery/embed and @hypequery/embed/iframe are the same: mountEmbed,
BRIDGE_VERSION, EMBED_PROTOCOL_VERSION, and the types MountEmbedOptions,
MountedEmbed, EmbedFrameOptions, EmbedCommand, HostEvent, Answer,
EmbedUsageLimit, QueryFilter, QueryLiteral, FilterOperator,
EmbedTheme, EmbedIcon and EmbedToken. They need no framework: React and React DOM
are optional peer dependencies, and mountEmbed loads neither.
Entry points under @hypequery/embed/internal/* are hypequery Cloud's own:
the hosted embed's React app and the components Cloud's product renders.
They have no compatibility promise and can change or go in any release.
