anfra docsAlpha
Plugins

Build a plugin

The steps to write, build and install a plugin, with a minimal example

This page shows the shape of a plugin. For every option, the kernel API, testing and the pre-ship checklist, read the plugin guide.

Build it with a coding agent

Give your agent the plugin guide and the notes example, then describe the plugin: "Read the anfra plugin guide and build a plugin that…". Ask it to review its work against the guide's checklist.

The example is a notes plugin: readers leave notes on a query, the host stores them, and authors get Anfra.notes and query.notes. A plugin needs only the halves it uses: drop the frame half for a host-only plugin, or the calls for a frame-only one.

1. Pick a name

Lowercase letters, digits and dashes, such as notes or acme-share. It prefixes everything the plugin adds: notes.add, Anfra.notes. anfra and plugins are reserved.

2. Write the host half

Each call is a handler. frame: true lets the data app make it.

import { invalidRequest } from '@holistics/anfra-sdk/common';
import { definePlugin, type FrameHalf } from '@holistics/anfra-sdk/host';

export const createNotesPlugin = (store: NotesStore, frame: FrameHalf) => definePlugin({
  name: 'notes',
  version: '1.0.0',
  host: {
    calls: {
      list: { frame: true, handler: (req, call) => store.list(about(req), call.signal) },
    },
  },
  frame,
});

function about (req: unknown): string {
  const value = (req as { about?: unknown })?.about;
  if (typeof value !== 'string' || !value) throw invalidRequest('Give the query name as `about`.');
  return value;
}

The app builds every request, so check each one, and reject with the SDK's errors (invalidRequest, forbidden) when the author should read the message. Other errors reach the app only as call_failed. A host half can also accept events and add commands and tabs. See the guide.

Depend on another plugin

List the plugins yours needs in requires. The host refuses to start when one is missing, so your plugin can rely on its calls:

definePlugin({
  name: 'notes-export',
  version: '1.0.0',
  requires: ['notes', 'export'],
  host: { /* ... */ },
});

3. Write the frame half

The frame half's default export receives the kernel, the API a frame half registers everything through. It imports only types, because it runs bundled inside the sandbox.

import type { FrameKernel, Query } from '@holistics/anfra-sdk/app';

export default function setup (kernel: FrameKernel) {
  const list = (about: string) => kernel.call('notes.list', { about });

  kernel.provide({ list });                                       // Anfra.notes
  kernel.provideOnQuery((query: Query) => ({ list: () => list(query.name) })); // query.notes
}

The kernel can also add menu items, modals and popovers, and draw in the plugin's own layer over the app.

Annotate a query's data

A plugin that has something to say about a query's data, such as an anomalous month, a target or a forecast, sets annotations on the query with kernel.annotate(). It never draws on the app's chart. The app draws them with its chart's own marks, and the SDK shows the ones it doesn't draw as a badge on the chart.

kernel.onApp((app) => {
  const done = new WeakMap();
  app.subscribe(() => {
    for (const query of Object.values(app.queries)) {
      const { result } = query;
      if (!result || done.get(query) === result) continue;   // annotating notifies too
      done.set(query, result);
      kernel.annotate(query, [
        { id: 'spike', kind: 'mark', anchor: { rows: [{ month: '2026-03-01' }], measure: 'revenue' }, label: 'Spike', severity: 'warning' },
        { kind: 'line', anchor: { column: 'revenue', value: '120000' }, label: 'Target' },
      ], { result });
    }
  });
});
  • Kinds: mark and focus on rows, line at a value, band over a range, and series through new points, such as a forecast with lower and upper bounds. You can't add a kind or choose a colour. severity (info, warning, critical) lets the app pick the colour from its theme.
  • Anchors use the query's own column aliases. Name a row by its dimension values, such as { month: '2026-03-01' }, never by its position. Values are strings, like the values in the rows.
  • Each call replaces your plugin's set on that query. Pass [] to clear it. Other plugins' annotations are kept apart from yours.
  • Pass the result you computed from. If the reader has changed a filter since, result is no longer the query's current result. The call then changes nothing and returns false.
  • Annotate each new result. Your annotations are removed when the query's result is replaced (by a changed filter, a refresh or a new sort), and as soon as the app edits the query. Loading another page with fetchMore() keeps them.
  • A malformed annotation throws: an unknown kind or column, a measure that isn't a measure column, or an anchor of the wrong shape. A row that isn't in the result is skipped.
  • Actions on annotations, such as "Explain this anomaly", are ordinary kernel.menuItem({ target: 'rows' }) items. The menu's target has annotations, the ones on its rows, so when can show your item only on your own. The badge's list shows the same items. The target's at is where the reader opened the item (the right-click in the menu, the badge in its list), so a popover about the rows opens there: kernel.popover({ anchor: target.at ?? target.node ?? { x: 16, y: 16 }, ... }).
  • The host never sees annotations. If your host half computes them, have the frame half call it and set what it returns.

Split initial and lazy code

The setup loads in every frame, so keep it small: register the API and menu items, and nothing heavy. Put code that is large or only needed sometimes, such as a renderer, a chart library or a modal's UI, in a body: a module whose default export is what kernel.body() resolves to. The body is fetched the first time you call kernel.body(), so frames that never use it never load it.

src/body.ts
export default { drawPanel };                     // what kernel.body() resolves to
src/frame.ts
kernel.provide({
  async show (about: string) {
    const { drawPanel } = await kernel.body<typeof import('./body').default>();   // loaded on first call
    drawPanel(kernel.layer(), await list(about));
  },
});

4. Build and package it

buildFrameHalf (needs esbuild) bundles the frame half into script source. Run it before your package's own build, and pass the result as frame:

build.mjs
import { writeFile } from 'node:fs/promises';
import { buildFrameHalf } from '@holistics/anfra-sdk/build';

const frame = await buildFrameHalf({ setup: 'src/frame.ts', body: 'src/body.ts' }); // body is optional
await writeFile('src/frame-half.generated.ts', `export default ${JSON.stringify(frame)};\n`);
src/index.ts
import frame from './frame-half.generated';
import { createNotesPlugin, type NotesStore } from './plugin';

export const notesPlugin = (store: NotesStore) => createNotesPlugin(store, frame);

To give TypeScript authors Anfra.notes, add your API to the SDK's AnfraPlugins interface. See the guide.

5. Install it in a host

import { createHost } from '@holistics/anfra-sdk/host';
import { corePlugin } from '@holistics/anfra-sdk/plugins';
import { notesPlugin } from '@acme/anfra-notes';

const host = createHost({ plugins: [corePlugin(backend), notesPlugin(myStore)] });
host.mount({ container, definition, datasets, user });

Every host installs core, with its backend for the core API. Data apps then check for your plugin before using it: if (Anfra.plugins.has('notes')).

6. Test it

Test the host half with host.call('notes.list', {...}) on a host that has the plugin. Test the frame half with testFrame() from @holistics/anfra-sdk/testing, which runs your setup against a stand-in host. See the guide for examples.

On this page