Using Plugin Data in a Theme

Theme contract 0.2.0. The hooks live in client/src/core/theme/sdk/plugin-data.ts, the plugin page route in client/src/core/theme/runtime/PluginViewTemplate.tsx.

A plugin can add things a theme wants to draw in its own markup: a progression plugin’s level, XP and missions, a daily wheel, a friends list, a season pass. Plugin slots render the plugin’s own UI; this page is for the other case, where the theme renders the data and the plugin only serves it.

A theme still cannot call fetch, open a socket or touch storage (the scanner refuses all three, and the string /api/ too). It asks the host instead, through four SDK hooks. The host sends the request to that plugin’s own route namespace and nowhere else.

The four hooks

import { usePluginQuery, usePluginAction, usePluginEvent, usePluginAvailable } from '@pe/sdk';
HookReturnsUse it for
usePluginQuery<T>(providerType, path, options?){ data, loading, error, available, refetch }Reading: GET /api/v1/plugins/<providerType><path>
usePluginAction(providerType)(method, path, body?) => Promise<T>Writing: POST, PUT, PATCH, DELETE on the same namespace
usePluginEvent(providerType, event, handler)nothingReacting to the plugin’s realtime event plugin:<providerType>:<event>
usePluginAvailable(providerType)booleanShowing or hiding a whole feature (a nav item, a dashboard card)

providerType is the plugin’s id (progression, daily-wheel, social). path is relative to the plugin’s routes: '/me', 'missions', '/friends/requests'. Never write /api/v1/plugins/… yourself.

usePluginQuery

interface ProgressionMe { level: number; xp: number; nextLevelXp: number }

export function LevelBadge() {
  const { data, loading, error, available } = usePluginQuery<ProgressionMe>('progression', '/me', {
    refetchOnEvent: ['xp-gained', 'level-up'],
  });
  if (!available) return null;              // plugin not installed or turned off
  if (loading && !data) return <span className="fh-badge fh-badge--loading" />;
  if (error || !data) return null;
  return <span className="fh-badge">Lv {data.level}</span>;
}
FieldMeaning
dataThe plugin’s response data (the { success, data } envelope already unwrapped), or null
loadingTrue until the first answer, during a refetch (the previous data stays), and while the host is still finding out whether the plugin is active
errorA PluginRequestError (below), or null. A failed refetch keeps the previous data
availableThe plugin is active on this site. While it is false nothing is sent and data is null
refetch()Fetch again now; resolves when the request settles and never rejects

Options:

OptionDefaultMeaning
paramsnoneQuery-string parameters. null and undefined values are left out. Part of the cache key
enabledtruefalse holds the request (loading false, data null), for a query that waits on another
refetchOnEventnoneThe plugin’s realtime event names after which the query fetches again

Caching. Queries with the same plugin, path and parameters share one cache entry and one request, however many components mount them. A query refetches when it mounts and its data is more than 30 seconds old, when the plugin is activated or updated, when the viewer signs in, out or as someone else, after a successful usePluginAction call for the same plugin, and on its refetchOnEvent events. A deactivated plugin’s data is dropped at once.

usePluginAction

export function ClaimButton({ missionId }: { missionId: string }) {
  const send = usePluginAction('progression');
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);
  const claim = async () => {
    setBusy(true);
    try {
      await send('POST', `/missions/${missionId}/claim`);
    } catch (error) {
      setProblem((error as { code?: string }).code === 'conflict' ? 'Already claimed' : 'Could not claim');
    } finally {
      setBusy(false);
    }
  };
  return <button disabled={busy} onClick={claim}>{problem ?? 'Claim'}</button>;
}

The function is stable for a given providerType (safe in effect dependencies). The request goes through the same client plugin bundles use (engine.http): cookies, the CSRF header, a silent session refresh on 401, and no retry on a 5xx, so an action never runs twice by accident. DELETE takes no body. After a success, every mounted query of that plugin refetches, so a claimed mission disappears from the list without extra code.

usePluginEvent

usePluginEvent('daily-wheel', 'spin-result', (payload) => {
  const { prize } = payload as { prize: number };
  setLastPrize(prize);
});

The handler always sees the latest props (it is kept in a ref); the subscription lasts while the component is mounted. Events of a plugin that is not active are dropped. Payloads are whatever the plugin emits (ctx.realtime on the server); treat them as untrusted input and narrow their type before use.

usePluginAvailable

usePluginAvailable('season-pass') is true while the plugin is active and re-renders on activation and deactivation. Use it to hide a whole feature, for example a "Season" item in the theme’s navigation, when the operator has not installed the plugin.

Errors

usePluginQuery reports, and usePluginAction rejects with, a PluginRequestError: an Error with name: 'PluginRequestError', a code, the HTTP status (or null), the providerType and details (the plugin’s field errors on a 400 or 422, or null). The hooks never throw during render: a missing plugin is an ordinary state, and a theme that throws is deactivated.

codeWhen
unavailableThe plugin is not active; nothing was sent
invalid-requestA bad plugin id, a path that leaves the namespace, a method other than the four, a DELETE with a body; nothing was sent
unauthorized401 after the host’s silent refresh: the viewer is signed out
forbidden403
not-found404: the plugin has no such route
validation400 or 422; see details
conflict409
rate-limited429
server5xx or any other status
networkNo response

What the host checks

  • The namespace. The path is rejected, with no request, when it is an absolute URL, starts with //, contains .. or . segments (also percent-encoded), a backslash, an encoded slash or a control character. The URL the client would request is checked again after the browser’s own normalisation and must still sit under /api/v1/plugins/<providerType>.
  • Activation. The host loads the list of active plugins from GET /api/v1/config/active-plugins (plugins with a frontend bundle, a client-visible setting or a public or authenticated route; backend-only plugins are not listed) the first time a hook asks, and follows the plugin:activated, plugin:updated, plugin:deactivated and plugin:auto-disabled socket events. Nothing reaches a plugin outside the list.
  • The viewer. Requests carry the viewer’s session like any host request; the plugin’s own route guards (requireAuth and friends) decide what the viewer may see. A theme gets nothing a plugin page in the same browser could not get.
  • Events. Only plugin:<providerType>:<event> events with valid names ([A-Za-z0-9][A-Za-z0-9:._-]{0,63}) reach a handler.

A screen for a plugin page

A plugin’s user pages live at /ext/<providerType>/<path>. A theme can render its own screen there, built from the hooks above, by registering a template under a member.plugin.* view id:

URLView ids tried, most specific first
/ext/progressionmember.plugin.progression
/ext/progression/missionsmember.plugin.progression.missions → member.plugin.progression
/ext/social/friends/requestsmember.plugin.social.friends.requests → member.plugin.social.friends → member.plugin.social
defineTheme({
  slug: 'my-theme',
  views: {
    'member.plugin.progression': () => import('./views/plugins/progression'),
    'member.plugin.social.friends': () => import('./views/plugins/friends'),
  },
});
"views": { "member.plugin.progression": {}, "member.plugin.social.friends": {} }
  • One path segment becomes one view-id segment, up to four, stopping at the first segment that is not a lowercase id segment (/u/Alice tries member.plugin.social.u). A template receives params.providerType and params.path (/friends/requests, / for the plugin’s root) and can read the rest of the path from it.
  • The template renders only while the plugin is active. The plugin owns the URL namespace: the theme’s screen can render at /ext/<providerType>/<path> even when the plugin registered no client page there, but a theme cannot invent URLs outside an active plugin’s namespace. With the plugin inactive the URL behaves as before (the host’s "Plugin Not Available" page).
  • Without a matching template, the plugin’s own page renders, as before. A page redirect the plugin declares (plugin API 1.3) wins over a template.
  • The route stays behind sign-in. A plugin id with an underscore (daily_wheel) cannot be a view-id segment, so its pages always render the plugin’s own page.

Agreeing on data shapes

The plugin decides its routes and payloads; the theme reads them. There is no shared type between a plugin and a theme, so:

  • Document the routes your theme relies on next to the theme (the plugin author documents them in the plugin’s README; see Extension Points › Themes read plugin routes).
  • Narrow data before use and render nothing for shapes you do not recognise, so an older or newer plugin version cannot break the screen.
  • Keep the plugin’s own slot fills in mind: a theme that draws a plugin’s feature itself and also places the slot the plugin fills will show it twice. Leave that plugin out of the slot with exclude (the other plugins’ fills still render):
<Slot id="layout.main.header.end" exclude={['progression', 'daily-wheel']} />

Or do not place a slot whose every fill the theme replaces (for example, no lobby.sidebar in a theme that draws its own lobby side column).

Try the live demo Pricing

Have questions about Poker Engine? We reply fast.