SDK & CLI

Last Updated: November 2026 · Plugin API: 1.1

@poker-engine/plugin-sdk (in packages/plugin-sdk/) is the one place plugin authors get types, the manifest schema and test doubles from. The plugin CLI (tools/plugin/cli.ts) scaffolds, builds, tests and packs plugins that use it. Both target plugin API 1.1.

The SDK re-exports the engine’s own declarations rather than copying them, so a plugin compiles against exactly what the engine hands it at runtime.

Entry Points

ImportUse it inExports
@poker-engine/plugin-sdkserver codePluginRegistry, HookMap and hook payload types, ActionCallback, FilterCallback, HealthCheckResult, Express Request / Response / NextFunction / RequestHandler, PluginManifest + pluginManifestSchema, validatePluginManifest, PLUGIN_CAPABILITIES, definePlugin, settingsOf, SDK_API_VERSION, and for login providers (API 1.4) the provider types, defineOAuthProvider, defineCredentialProvider
@poker-engine/plugin-sdk/clientbrowser bundlePokerEngineClient (the type of window.__pokerEngine), PluginPageProps, PageRegistration, SlotFillRegistry, ClientHookRegistry, getEngine, runClientPlugin, pluginApiBase
@poker-engine/plugin-sdk/testingserver testscreateTestRegistry, TestRegistry, matchRoutePath, and for login providers runTestMapProfile, runTestCredential, AuthProviderError
@poker-engine/plugin-sdk/testing/clientclient testscreateTestEngine, TestEngine, createHttpError, toolkit doubles

Where the types come from:

SDK typeEngine source
PluginRegistrysrc/core/plugins/plugin-loader.ts
HookMap and payload interfacessrc/core/hooks/hook-map.ts
PluginManifest, pluginManifestSchemasrc/core/plugins/plugin-manifest.ts (the engine validates uploads with the same schema)
PokerEngineClientclient/src/core/engine-global.types.ts (window.__pokerEngine is declared with it in client/src/types/global.d.ts)

Inside this repository the SDK resolves to its TypeScript source: the root tsconfig.json and vitest.config.ts alias @poker-engine/plugin-sdk and @poker-engine/plugin-sdk/testing, and scaffolded plugins get the same aliases in their own tsconfig*.json and vitest.config.ts. npm run build --prefix packages/plugin-sdk writes dist/ (ESM bundles plus declarations) for use outside the repository.

Server API

definePlugin({ register, healthCheck? })

Type-checks a plugin definition and returns it unchanged. registry is typed as PluginRegistry inside both functions. The loader reads named exports, so re-export them:

import { definePlugin, settingsOf, type Request, type Response } from '@poker-engine/plugin-sdk';

const plugin = definePlugin({
  register(registry) {
    registry.registerRoute('GET', '/hello', async (_req: Request, res: Response) => {
      const message = await settingsOf(registry).string('greeting', 'Hello');
      res.json({ success: true, data: { message } });
    });
  },
  async healthCheck(registry) {
    return (await registry.settings.get('greeting')) ? { healthy: true } : { healthy: false, message: 'greeting not set' };
  },
});

export const { register, healthCheck } = plugin;
export default plugin;

settingsOf(registry)

The engine stores every setting as a string. settingsOf reads them typed:

MethodReturns
string(key, fallback = '')the value, or fallback when unset
boolean(key, fallback = false)true for 'true', false for 'false', else fallback
number(key, fallback = 0)a finite number, else fallback
json<T>(key, fallback)a json field parsed, else fallback (unset or not valid JSON)
list(key, fallback = [])a list field (JSON array of strings), else fallback

Manifest schema

pluginManifestSchema (zod) describes the pokerEnginePlugin object in package.json. The engine runs it in validatePluginPackage when a plugin is uploaded or upgraded, after the original providerType / displayName / name / version checks, and reports failures as Invalid pokerEnginePlugin manifest: <path>: <message>; ....

  • It accepts every manifest written for API 1.0. Unknown keys are kept, and configFields[].type is an open string (unknown types render as a text input).
  • apiVersion must be 1, 1.0, 1.1, 1.2, 1.3 or a patch of those (1.0.3, 1.3.0). Omitting it is allowed.
  • API 1.1 adds three fields:
FieldTypeRules
capabilitiesstring[]Each one of PLUGIN_CAPABILITIES: storage, wallet:credit-virtual, wallet:credit-real, wallet:credit-tickets, wallet:debit-virtual, wallet:transfer-virtual, wallet:transfer-real (API 1.2), bonus, realtime, scheduler, notify:in-app, notify:push, notify:email, notify:email-address (API 1.3), hooks:player-actions, hooks:account-data, game:rake, game:bot-decide (API 1.3), users:read, presence (API 1.2). Unknown capabilities fail validation.
hooks{ optIn: string[] }Hooks that only fire when a plugin asks for them, e.g. game:player:action. optIn defaults to []. Opting in to game:player:action without hooks:player-actions in capabilities fails validation.
localesRecord<string, string>Language code (en, pt-BR) to a JSON file inside the package (dist/locales/en.json). Absolute paths, backslashes and .. segments are rejected.

validatePluginManifest(value) returns { success: true, manifest } or { success: false, error } with the same message format the engine uses.

Client API

import { useState } from 'react';
import { runClientPlugin, type PokerEngineClient, type PluginPageProps } from '@poker-engine/plugin-sdk/client';

function Badge() {
  return <span>New</span>;
}

function setup(engine: PokerEngineClient) {
  engine.fills.register('layout.main.header.end', Badge, { providerType: 'my-plugin' });
}

runClientPlugin('my-plugin', setup);
FunctionDescription
runClientPlugin(providerType, setup)Runs setup(window.__pokerEngine). A missing engine or a throwing setup is logged with the plugin name and returns false; it never throws, so one plugin cannot stop the others loading.
getEngine()window.__pokerEngine, or an error when the bundle runs outside the engine.
pluginApiBase(providerType, engine?)Absolute URL of the plugin’s server routes, e.g. https://host/api/v1/plugins/my-plugin.

JSX and React

Write components with JSX ("jsx": "react-jsx"). The scaffold’s build.client.mjs does not bundle React: it rewrites these imports to the engine’s copies on window.__pokerEngine:

ImportResolves to
reactwindow.__pokerEngine.React
react-dom, react-dom/clientwindow.__pokerEngine.ReactDOM (createRoot, createPortal, flushSync)
react/jsx-runtimewindow.__pokerEngine.jsxRuntime (jsx, jsxs, Fragment)

The engine client is typed against React 18; the scaffold’s tsconfig.client.json points react at the same declarations the client uses.

Testing

createTestRegistry(options?)

An in-memory PluginRegistry. Every method is a vitest spy (vi.fn), so expect(registry.logger.info).toHaveBeenCalledWith(...) and registry.settings.get.mockRejectedValueOnce(...) work.

OptionDescription
providerTypeDefaults to test-plugin.
settingsInitial settings (Record<string, string>).
balancesInitial wallet balances per user: { u1: { virtual: 100 } }.
usersUsers for the users:read doubles (API 1.2): [{ id, username, ...profile fields, hasDeposited?, handsPlayed?, tournamentsPlayed? }].
presencePresence per user id for the presence double: { u1: { online: true, tables: [...] } }.
botsBots registry.bots reports (API 1.3): BotSummary[]. isBot is true for these ids and for any id starting bot_.
showBotBadgeWhat registry.bots.showBotBadge() answers (API 1.4). Defaults to false.
botDecisionsThe decisions registry.bots.recentDecisions() answers from, newest first (API 1.4), filtered by tableId, handNumber, botId and id and limited like the engine (default 50, at most 500).
overridesReplace methods or namespaces, merged one level deep: { users: { findByExternalId: vi.fn(...) } }.

Besides the API 1.0 namespaces it provides the API 1.1 ones, so code written against them can be tested before or without a database:

NamespaceBehaviour in the double
storage.global, storage.user(userId)get, set, merge (shallow), update (compare-and-set, one key at a time), delete, list(prefix?) over an in-memory JSON store. Keys must match ^[a-z0-9:_-]{1,128}$; values are capped at 64 KB and stored as copies.
storage.query(key, { orderBy, direction?, limit?, offset?, where? })Sorts users’ values for key by a dot path; where.op is eq, gt, gte, lt or lte. Returns [{ userId, value }].
walletcreditVirtual, creditReal, creditTickets, debitVirtual (throws on overdraft), getBalance, and transfer (API 1.2: moves between test balances, replays a repeated idempotencyKey, throws on a reused key, an overdraft or a self-transfer; each transfer is listed in registry.test.transfers), backed by in-memory balances.
bonuscredit, listForUser.
realtimetoUser, toTable, broadcast (spies that validate names and payloads like the engine), on (records the handler).
schedulerevery, cron, once, cancel, list (records jobs in registry.test.jobs).
notifyinApp, push, email with the engine’s result shapes and daily limits (TestNotifyRateLimitError); sends are recorded in registry.test.notifications.
users (API 1.2)getProfiles, findByUsername, search, query, stats over the in-memory users, with the engine’s limits (500 ids, 2-character search, 20 results, bots and blocked users left out of search and, by default, of query; opaque keyset cursor).
presence (API 1.2)get(userIds): known users and users with presence set; default offline with no tables.
bots (API 1.3, 1.4)list, get, isBot over the bots option; say(botId, tableId, message) records the line in registry.test.botLines and answers { sent: false, reason } like the engine for a non-bot (not-a-bot), a listed bot at another table (not-seated), an empty line (empty) or a line moderation would change (moderated); showBotBadge; recentDecisions(query).

The double does not enforce capabilities. The engine implementations, with capability checks, are documented in Storage, Wallet, Realtime, Scheduler, Notifications, Users and Presence.

registry.test drives what the plugin registered:

HelperDescription
request(method, path, { body?, params?, query?, headers?, user? })Calls the matching route (Express-style :params) through its handler chain; resolves { status, body, headers }.
doAction(hook, ...args) / applyFilters(hook, value, ...args)Fires recorded actions and filters in priority order.
emitRealtime(event, { userId, socketId }, payload)Calls the handler registered with realtime.on.
runJob(jobId)Runs a scheduled job now.
auditLogEvery registry.audit.logAdminAction(req, entry) call (API 1.4), with the admin id from req.user.sub; the double throws without one, like the engine.
teardown()Runs the callbacks registered with registry.onTeardown (API 1.4), newest first, once, as the engine does on switch-off, upgrade or the circuit breaker. teardownCallbacks holds the ones not run yet.
addUser({ id, username, ... }) / setPresence(userId, { online?, lastSeenAt?, tables? })Add a user to the users:read doubles; set what presence.get reports. Fire user:online / user:offline with doAction.
settings, routes, actions, filters, jobs, balances, globalStorage, userStorage, notifications, bots, botLinesThe recorded state.
import { createTestRegistry } from '@poker-engine/plugin-sdk/testing';
import { register } from '../server/index';

it('serves the greeting', async () => {
  const registry = createTestRegistry({ settings: { greeting: 'Hi' } });
  await register(registry);
  const res = await registry.test.request('GET', '/hello');
  expect(res.body).toEqual({ success: true, data: { message: 'Hi' } });
});

createTestEngine(options?)

A window.__pokerEngine double. fills, pages and hooks are the engine’s real registry classes; socket.for(type) returns spied on/off/emit, and engine.emitServerEvent(providerType, event, payload) simulates a server push; React, ReactDOM and jsxRuntime are the real libraries; api.buildUrl, auth.login, startup.registerPreRenderHook and theme.register are spies. engine.install() sets it as window.__pokerEngine and returns an undo function. Options: apiBaseUrl (default /api/v1), version, user (for auth.currentUser()), language.

The API 1.1 toolkit has doubles too: ui components render plain HTML with data-pe-ui, ui.toast.* and ui.confirm are spies; i18n is an in-memory store with setLanguage(lang); http.for(type) returns the same client of spies each time; auth.setUser(user | null) notifies auth.subscribe callbacks; createHttpError(message, code, status) builds the error engine.http rejects with. See Client Toolkit.

import { createTestEngine } from '@poker-engine/plugin-sdk/testing/client';
import { setup } from '../client/plugin';

it('registers the badge', () => {
  const engine = createTestEngine();
  setup(engine);
  expect(engine.fills.getFills('layout.main.header.end')).toHaveLength(1);
});

CLI

Run from the repository root. A bare slug means plugins/<slug>; anything containing a / is a path.

CommandWhat it does
npm run plugin:create <slug> -- [--name "Display Name"] [--description "..."] [--dir <parent>]Scaffolds <parent>/<slug>/ (default parent plugins/). The slug becomes the providerType and must match ^[a-z][a-z0-9_-]*$. Refuses an existing directory.
npm run plugin:build <slug>Validates the manifest, installs the plugin’s own runtime dependencies when it has a package-lock.json and one is missing (npm ci --omit=dev in the plugin), runs the plugin’s build script (type-check, then esbuild), and checks that dist/server/index.js, the frontend bundle and any locales files exist.
npm run plugin:test <slug> [-- <vitest args>]Installs the plugin’s own runtime dependencies the same way, then runs the plugin’s test script. Dev tools (TypeScript, esbuild, vitest, React) resolve from the repository root’s node_modules.
npm run plugin:pack <slug>Builds, validates, then npm packs <slug>-<version>.tgz in the plugin directory, ready to upload in Extensions › Plugins.
npm run plugin:validate <slug> [-- --built]Checks the manifest against pluginManifestSchema; --built also requires the dist/ files.
npm run plugin:typecheckType-checks the CLI and the SDK.

Generated files

FilePurpose
package.jsonManifest with apiVersion: "1.3", capabilities: [], one greeting config field and a /hello user page; scripts typecheck, build, test, pack; dev dependencies pinned to the engine’s versions for building outside the repository.
tsconfig.jsonServer and server tests (no DOM).
tsconfig.client.jsonClient and client tests (DOM, jsx: react-jsx).
build.server.mjsesbuild → dist/server/index.js, ESM, Node 22. The SDK runtime and npm dependencies are bundled; zod stays external because the engine provides it.
build.client.mjsesbuild → dist/client/index.js, an IIFE with React externalised to window.__pokerEngine (see JSX and React).
vitest.config.tsSDK aliases and src/**/*.test.{ts,tsx}.
src/server/index.tsdefinePlugin with a GET /hello route and a health check.
src/client/plugin.tsxComponents and setup(engine).
src/client/index.tsxBundle entry: runClientPlugin(PROVIDER_TYPE, setup).
src/__tests__/register.test.tsManifest validation, the route and the health check through createTestRegistry.
src/__tests__/client.test.tsxFill and page registration through createTestEngine, plus a JSX render.

plugins/demo-plugin is the worked example: it was generated with the CLI and extended with a zod-validated POST route, a settings validation filter, a plugin:settings:saved action, two fills, a user page, an admin page and a nav:items:user client filter. Its built dist/ is committed so the engine auto-discovers it without a build step.

End-to-end tests

The engine’s Playwright suite auto-discovers the built plugins under plugins/. See Plugin Development Guide: End-to-End Tests.

Building outside this repository

The generated tsconfig*.json and vitest.config.ts point at packages/plugin-sdk/src with relative paths. For a plugin kept elsewhere, build the SDK (npm run build --prefix packages/plugin-sdk), install it into the plugin (npm install <path-to>/packages/plugin-sdk), run npm install for the pinned dev dependencies, and remove the paths entries and the vitest aliases so the package’s exports are used.

Try the live demo Pricing

Have questions about Poker Engine? We reply fast.