Member and Auth Controllers

The five auth controllers below are what the built-in default auth pages use, so a themed site.auth.login view signs a player in the same way. The cashier and account controllers further down run the product’s cashier, profile, settings and security pages the same way.

A controller is the host-owned view model of one screen. A template that replaces a screen with commands (sign in, register, deposit) cannot call the API itself, because the SDK gives theme code no store and no API client. Instead it calls the screen’s controller hook from @pe/sdk and gets four things back:

const { view, commands, status, errors } = useLoginController();
KeyWhat it holds
viewPlain data to render: the current step, flags, links, schema, slot ids
commandsFunctions the template calls from its event handlers. They return promises and never throw.
status'idle', 'submitting', 'success' or 'error', for the main command
errors{ form, fields }. form is { message, code, status } or null; fields maps a field name to a list of messages.

The default pages call the same hooks, so a themed screen and the built-in screen run the same code: the same requests, CSRF handling, error wording, state machine and redirects. A template provides markup only. Errors are ready to show: message is the server’s message when the server refused the request, and an i18n’d host string otherwise. status on a form error is the HTTP status, so 429 means the player was rate limited.

The types live in packages/shared/src/themes/controllers/ and are part of the contract (ThemeSdk); the implementations live in client/src/core/theme/sdk/controllers/.

Auth

The auth routes and their view ids:

RouteView idControllerdefault page
/loginsite.auth.loginuseLoginController()LoginPage.tsx
/registersite.auth.registeruseRegisterController()RegisterPage.tsx
/forgot-passwordsite.auth.forgotuseForgotPasswordController()ForgotPasswordPage.tsx
/reset-password?token=site.auth.resetuseResetPasswordController()ResetPasswordPage.tsx
/verify-email?token=site.auth.verifyuseVerifyEmailController()VerifyEmailPage.tsx
/register/completesite.auth.completeuseCompleteSignupController()CompleteSignupPage.tsx

All six fall back to site.auth, so one template can serve them all by switching on viewId. Two-factor authentication is not a separate route; it is a step of the login controller. The product has no captcha, remember-me option or magic link. Sign-in with Google, Discord and other providers comes from plugins through the external sign-in system (below); other plugins fill the auth.login.below-form and auth.register.below-form slots (see Plugin slots).

External sign-in (contract 0.1.3)

Plugins register sign-in providers (registry.auth.registerProvider), and the host shows them on the sign-in and register screens, in Settings and in the admin panel. A themed screen needs three things:

const { view } = useLoginController();
// view.providers: [{ id, name, label: 'Continue with Google', icon, brand, start() }]
// view.providerError: the failure of the last provider sign-in, worded per error code, or null
// view.linkNotice: a provider sign-in met this account: "An account with a***@x.com exists. Sign in to link your Google account."
// view.step === 'link-confirm': signed in, asking first. view.linkConfirm.message: "Link your Google account Pat to this account?"

<ProviderButtons providers={view.providers} disabled={busy} classNames={{ button: 'my-btn', icon: 'my-icon' }} />
  • ProviderButtons (SDK component) draws the "or" divider and one button per provider. The accessible name is "Continue with <Provider>". Each button carries the provider’s brand colours as the CSS variables --pe-provider-bg, --pe-provider-fg and --pe-provider-border, and the SDK adds the pe-provider-* hook classes. Pass classNames to style the row with the theme’s own classes (the host then adds no utility classes of its own to that element); the bundled themes use their ghost button and override the colours from the variables.
  • ProviderIcon draws one provider icon. Icons are SVG a plugin supplied: the server sanitises them and the host sanitises them again with an allowlist before writing the markup, so a theme must not draw icon.svg itself (the validator rejects dangerouslySetInnerHTML and innerHTML).
  • start() navigates the browser (a full page load) to the provider; it never fails in the page. A provider that fails or is declined sends the player back to the screen they started from with providerError set.
  • Two-factor authentication applies to every provider: after the provider the host opens the login controller’s existing two-factor step (view.step), so a themed login view needs no extra code.
  • Linking to an existing account: when a provider sign-in meets an account that already exists, the host opens /login with view.linkNotice set. The one-time ticket stays in router state, never in the URL. After the password (or 2FA) sign-in the controller stops at the link-confirm step: render view.linkConfirm.message with two buttons, commands.confirmLink() (view.linkConfirm.confirmLabel) and commands.cancelLink() (cancelLabel). Nothing is linked until the player confirms; both commands then continue to redirectTo. A themed site.auth.login must render this step, or a player with a pending link stays on it.
  • auth.register.fields: place <Slot id="auth.register.fields" passProps={{ values, setValue, errors }} /> in the register form (and in a themed site.auth.complete); keep the values in state and send them as register({ ...values, extra }). Plugin fills with the auth:signup capability add fields there.
  • site.auth.complete is the short "complete your profile" step after a provider sign-up that needs a username or an email. A theme that does not register it gets the host page inside its auth.card part (view="register", state="complete"). useCompleteSignupController() returns the provider, the pre-filled username with usernameSuggestions, the fields to show (the email only when the provider gave no usable one), the unticked marketing consents, the auth.register.fields slot id and commands.submit({ username, email, marketingEmails, extra }).
  • Settings → Sign-in methods: a themed member.settings view renders a panel from useSignInMethodsController() (view.identities, view.linkable, view.canSetPassword, commands.unlink(provider), commands.startSetPassword(provider), commands.setPassword(...)), with the section id sign-in-methods so /settings#sign-in-methods reaches it. The bundled themes show how.

useLoginController()

The login screen is a state machine. view.step says which screen to draw:

credentials ─┬─► two-factor ───────────────────────────► signed in
             └─► admin-2fa-setup ─► admin-backup-codes ─► signed in
cancelTwoFactor() returns to credentials from any later step
with a pending provider link (view.linkNotice), "signed in" first stops at link-confirm:
link-confirm ─► confirmLink() | cancelLink() ─► redirectTo
interface LoginView {
  step: 'credentials' | 'two-factor' | 'admin-2fa-setup' | 'admin-backup-codes';
  registrationEnabled: boolean;          // the `registration` feature flag
  redirectTo: string;                    // where sign-in goes: the page the guard came from, else /lobby
  twoFactor: { method: 'totp' | 'backup-code'; admin: boolean } | null;  // on `two-factor`
  adminSetup: { secret: string; qrCodeUrl: string } | null;              // on `admin-2fa-setup`; null while loading
  backupCodes: string[] | null;          // on `admin-backup-codes`
  emailVerificationRequired: boolean;    // sign-in was refused for an unverified email
  notice: string | null;                 // informational message, e.g. "verification email sent"
  links: { forgotPassword: string; register: string };
  slots: { belowForm: 'auth.login.below-form' };
}

commands.login({ username, password }): Promise<void>
commands.submitTwoFactor(code): Promise<void>         // a TOTP code, or a backup code when method is 'backup-code'
commands.setTwoFactorMethod('totp' | 'backup-code'): void
commands.completeAdminSetup(code): Promise<void>      // first TOTP code of the forced admin setup
commands.continueAfterBackupCodes(): Promise<void>
commands.cancelTwoFactor(): void
commands.resendVerification(email): Promise<void>

On success the controller stores the session, loads the admin feature list for admins and moderators, and navigates to view.redirectTo with replace. The template does not navigate.

useRegisterController()

interface RegisterView {
  enabled: boolean;                      // the `registration` feature flag; draw a "registration disabled" screen when false
  fields: RegisterFieldView[];           // username, email, password, confirmPassword, referralCode, in display order
  consents: RegisterConsentView[];       // checkboxes below the fields: [{ name: 'marketingEmails', label, defaultChecked: false }]
  initialValues: RegisterValues;         // referralCode prefilled from ?ref= or the session; marketingEmails: false
  passwordRules: PasswordRuleView[];     // the checklist, all unmet
  completed: boolean;                    // registered; the player must verify the email before signing in
  links: { login: string };
  slots: { belowForm: 'auth.register.below-form' };
}

commands.register(values): Promise<void>
commands.validateField(name, value, values?): string[]   // client-side checks for one field
commands.checkPassword(password): PasswordRuleView[]    // live checklist: { id, label, met }
commands.goToLogin(): void                               // keeps the guard's redirect

Each field carries name, type, required, an i18n’d label and placeholder, autoComplete, and where they apply minLength, maxLength and pattern (a regular expression source). The referral code from ?ref=CODE is kept in sessionStorage while the player detours to sign-in, and its click is counted once per browser session; the template does nothing for this. register checks the confirmation (errors.form.code PASSWORDS_MISMATCH) and the password rules (errors.fields.password) before it calls the server, and keeps the server’s field errors in errors.fields.

Render each entry of view.consents as an unticked checkbox with its label, and pass its state as values.marketingEmails (a boolean) to commands.register. Leaving it out counts as "no". The answer is the player’s marketing email consent (source registration), so a themed register page without the checkbox signs nobody up for promotions; the player is then asked once after signing in.

Registration requirements. When the operator’s registration settings (or the certified compliance profile) require them, view.fields also lists firstName, lastName, dateOfBirth (YYYY-MM-DD, its label names the minimum age), phone, address, city, zipCode, country (two letters) and governmentId, all type: 'text', required: true, after the referral code. Their values are optional in RegisterValues, so read them as values[field.name] ?? ''. view.consents then also lists acceptTerms (with links to the terms and privacy pages in force) and affirmations, both with required: true; render them as unticked checkboxes and send values.acceptTerms and values.affirmations as booleans. register refuses an unticked required box before calling the server (errors.form.code CONSENT_REQUIRED), and the server answers a missing field, an under-age date of birth or a post-office box as field errors. With the default settings none of these appear, so a theme that renders view.fields and the required consents needs nothing else.

useForgotPasswordController()

view: { sent: boolean; links: { login: string } }
commands.requestReset(email): Promise<void>

sent becomes true when the server accepts the request. The server never says whether the account exists, so the message should not either.

useResetPasswordController()

view: {
  hasToken: boolean;               // ?token= was present
  passwordRules: PasswordRuleView[];
  completed: boolean;              // the host navigates to /login after redirectDelayMs (3000)
  redirectDelayMs: number;
  tokenRejected: boolean;          // the token expired or is invalid: offer links.requestNewLink
  links: { login: string; requestNewLink: string };
}
commands.resetPassword({ password, confirmPassword }): Promise<void>
commands.checkPassword(password): PasswordRuleView[]

The token is read from the URL. A missing token gives errors.form.code MISSING_TOKEN without a request.

useVerifyEmailController()

view: {
  verification: 'no-token' | 'verifying' | 'verified' | 'failed';   // the URL token is verified on mount
  resendSent: boolean;
  resendCooldownSeconds: number;  // 60 after a resend, counting down
  links: { login: string };
}
commands.resend(email): Promise<void>

errors.form is the verification failure; errors.fields.email is a resend failure. status follows the resend command.

Plugin slots

Sign-in plugins render into the auth.login.below-form and auth.register.below-form slots. A themed login or register view should keep them below its form, so the operator’s Telegram or Steem buttons do not disappear. The ids are in view.slots.belowForm. A Slot component for theme code is not yet supported; until it lands, a themed auth view cannot render plugin fills, and an operator who relies on a sign-in plugin should keep the default login and register pages.

Example

A complete themed login view, as a theme bundle writes it:

import { useState } from 'react';
import { useLoginController, useT, Link } from '@pe/sdk';

export default function Login() {
  const t = useT();
  const { view, commands, status, errors } = useLoginController();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [code, setCode] = useState('');

  if (view.step === 'two-factor') {
    return (
      <form onSubmit={(e) => { e.preventDefault(); commands.submitTwoFactor(code); }}>
        <h1>{t('auth.twoFactor.title', 'Two-Factor Authentication')}</h1>
        {errors.form && <p role="alert">{errors.form.message}</p>}
        <input value={code} onChange={(e) => setCode(e.target.value)} autoComplete="one-time-code" />
        <button disabled={status === 'submitting'}>{t('auth.twoFactor.verify', 'Verify')}</button>
        <button type="button" onClick={commands.cancelTwoFactor}>{t('auth.twoFactor.backToLogin', 'Back to login')}</button>
      </form>
    );
  }

  return (
    <form onSubmit={(e) => { e.preventDefault(); commands.login({ username, password }); }}>
      <h1>{t('auth.login.title', 'Sign In')}</h1>
      {errors.form && <p role="alert">{errors.form.message}</p>}
      <input value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" />
      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
      <button disabled={status === 'submitting'}>{t('auth.login.title', 'Sign In')}</button>
      <Link to={view.links.forgotPassword}>{t('auth.login.forgotPassword', 'Forgot password?')}</Link>
      {view.registrationEnabled && <Link to={view.links.register}>{t('auth.login.createOne', 'Create one')}</Link>}
    </form>
  );
}

A real view also draws the admin-2fa-setup and admin-backup-codes steps, which an admin without 2FA reaches at sign-in while the site setting "Require two-factor authentication for admins" is on (it is off by default, and then such an admin is signed straight in, like a player without 2FA). Register it under views['site.auth.login'] in defineTheme and list the id under views in the manifest, as on Templates and View Ids.

Member controllers

The member controllers return { view, commands, status }: their commands resolve with { ok, message } instead of filling an errors object, and status carries state (loading, ready, and per controller disabled, signed-out, refused or error), the command in flight, busy, and the current error / success message.

Rules every controller keeps:

  • Form state is yours. Inputs, the selected method, the file picked: keep them in the template and pass them to a command. A command validates exactly as the product page does and sets status.error when it refuses.
  • The host keeps its guards. Feature toggles (cashier, coupons, bonuses, gameHistory, …) are applied inside the controller; a command for a switched-off feature refuses without calling the server. Destructive commands keep the host’s confirmation dialog (turning 2FA off, deleting the account) or acknowledgement rule (starting a break). Toasts are the host’s.
  • No API client, no store. Controllers are the only write path a theme has. The SDK still never hands out the API client, a store or the socket.
  • One instance per screen. Each call to a controller hook is its own instance with its own state; call it once in the template and pass view and commands down.

Import controllers from @pe/sdk like any other hook:

import { useCashierController, CashierMethodForm, Money } from '@pe/sdk';

The types are in the exported contract (contract/types/themes/controllers/): CashierController, ProfileController, SettingsController, SecurityController, ProtectionController and their view, command and value types.

Cashier

member.cashier (/cashier). The cashier’s tabs (deposit, withdraw, transfer, history, verification) are resolved inside the one view: view.tab, view.tabs and commands.setTab(tab). view.tabs leaves out transfer while the server refuses cashier transfers (a certified install, or the operator switched them off; GET /cashier/status transfer.available), and view.tab then reads deposit instead of transfer. Build the tab bar from view.tabs, not a fixed list.

useCashierController(): CashierController

View

FieldContents
enabledfeatures.cashier. While false the product shows "Cashier temporarily unavailable" and every command refuses; status.state is disabled
tab, tabsThe active tab and the product’s tab list with labels
balancesreal, virtual, tickets (each null while its feature, realMoney, virtualChips or tournaments, is off), wallets (GOLD, DIAMOND: balance, locked, available), currency, loaded (before the cashier balance arrives, real and virtual show the viewer’s cached balance)
deposit.methods, withdraw.methodsThe methods the server offers this player (gateway plugins included), each a CashierMethodView: id, name, type, systemId, direction, fields, flow, minAmount, maxAmount, fee, pluginForm
deposit.defaultMethodId, withdraw.defaultMethodIdThe first method, which the product preselects
deposit.lastResultThe last deposit: transactionId, status, amount, methodId, and cryptoAddress (currency, address, qrCode) for crypto
deposit.limitPrompttrue after the server refused a first deposit with DEPOSIT_LIMIT_PROMPT (a compliance profile asks for a deposit limit, or a recorded decline, first). Show the prompt in the cashier: useProtectionController().commands.saveLimits({ depositDaily }) or commands.declineLimitPrompt(), then call deposit again. Cleared when a deposit starts. Every bundled theme does this
withdraw.lastResult, transfer.lastResultThe last withdrawal (amount, fee, status, estimatedTime) and transfer (recipient, status)
transferminAmount, maxAmount (the real balance)
isAtTableThe player is seated: the server refuses withdrawals and transfers. Show the product’s warning
transactionsitems, total, page (1-based), pageSize (10), filters, typeOptions (labels for all, deposit, withdrawal, transfer, game, bonus), loaded
pendingWithdrawalsThe player’s pending withdrawals; null until loadPendingWithdrawals(). Each item’s optional cancellable is false while the site does not let players cancel a requested withdrawal: draw the cancel button only when it is not false (absent, from an older host, means cancellable; the server refuses a cancel it does not allow)
verificationidentity, address, payment (none, pending, verified, rejected; null until loaded), rejectionReason, types (per verification type: document types and the default), accept (the file input’s accept), maxFiles (1)
promoenabled (features.coupons) and lastResult

A method’s fields lists what it needs beyond the amount, with labels, placeholders and type: currency (a select, crypto deposits), phoneNumber (MuchBetter), address (crypto and BTCPay withdrawals), destination (the payout e-mail, phone or account the provider needs). flow says how a deposit continues: redirect, crypto-address, app-approval, telegram-invoice or direct. fee is null: the server reports the fee on the withdrawal result.

Commands

CommandDoes
setTab(tab)Switches tab and clears the messages. Opening history loads the current page; opening verification loads the status
deposit(methodId, { amount, currency?, phoneNumber?, metadata? })Validates the amount (and the MuchBetter phone number), then deposits. A provider redirect is followed only when its URL is on the method’s allow-list (cashier.error.invalidPaymentRedirect otherwise); a Telegram Stars invoice opens in Telegram. Resolves with outcome: redirecting, invoice-opened, pending, completed, failed, invalid, error or limit-prompt (see deposit.limitPrompt)
withdraw(methodId, { amount, address?, destination?, metadata? })Checks the amount against the balance, the wallet address and the destination field, then requests the payout. metadata is sent for methods whose plugin form collects it (Steem)
transfer({ recipient, amount, message? })Player-to-player transfer
cancelWithdrawal(transactionId)Cancels a pending withdrawal and refreshes the balance
loadTransactions(page?, filters?)Loads a history page; filters (type, status) replace the current ones
loadPendingWithdrawals()Fills view.pendingWithdrawals
loadVerification()Reloads the KYC status
uploadKyc({ type, documentType, files })Uploads one document (files holds exactly one File) and reloads the status
redeemPromo(code)Redeems a coupon code while promo.enabled
refresh()Re-reads balances, methods and the at-table flag
clearMessages()Clears status.error and status.success

Successful deposits, withdrawals and promo codes refresh the balance and also update the viewer (useViewer().balance).

Gateway forms: CashierMethodForm

Payment plugins render their own fields through the cashier.deposit.method-list and cashier.withdraw.method-list slots. A template keeps them working by rendering CashierMethodForm under the method picker; it renders nothing when no plugin fills the slot for the selected method, so it is safe for every method. Methods with pluginForm: true are the ones a plugin may complete.

<CashierMethodForm direction="deposit" methodId={methodId} amount={amount} />
<CashierMethodForm
  direction="withdraw"
  methodId={methodId}
  onDestinationChange={setDestination}
  onMetadataChange={setMetadata}
/>

Pass the destination and metadata the plugin reports into withdraw().

Example

import { useState } from 'react';
import { useCashierController, CashierMethodForm, Money } from '@pe/sdk';

export default function Cashier() {
  const { view, commands, status } = useCashierController();
  const [amount, setAmount] = useState('');
  const [methodId, setMethodId] = useState('');
  if (!view.enabled) return <p>{status.error ?? 'The cashier is unavailable.'}</p>;
  const selected = view.deposit.methods.some((m) => m.id === methodId) ? methodId : view.deposit.defaultMethodId;

  return (
    <form onSubmit={(e) => { e.preventDefault(); void commands.deposit(selected, { amount }); }}>
      {view.balances.real !== null && <Money amount={view.balances.real} />}
      <input value={amount} onChange={(e) => setAmount(e.target.value)} inputMode="decimal" />
      {view.deposit.methods.map((m) => (
        <button key={m.id} type="button" aria-pressed={m.id === selected} onClick={() => setMethodId(m.id)}>{m.name}</button>
      ))}
      <CashierMethodForm direction="deposit" methodId={selected} amount={amount} />
      <button type="submit" disabled={status.busy}>Deposit</button>
      {status.error && <p role="alert">{status.error}</p>}
      {status.success && <p role="status">{status.success}</p>}
    </form>
  );
}

Not yet supported: virtual-currency packages and the DIAMOND-to-GOLD conversion (the server has them, the product’s cashier page does not use them yet), and server-side per-method limits and fees (the methods endpoint does not report them; minAmount is the product’s form minimum).

Account

Four controllers cover the signed-in player’s own account. All four pages stay behind sign-in.

View idRouteControllers
member.profile/profile and every ?tab=useProfileController, plus the two below for the tabs that use them
member.security/profile?tab=password and /profile?tab=securityuseSecurityController
member.settings/settingsuseSettingsController
(profile tab protection)/profile?tab=protectionuseProtectionController

member.security is tried first for the two security tabs and falls back to member.profile, so a theme that registers only member.profile still receives every tab and can render the security tabs from useSecurityController itself.

useProfileController(): ProfileController

Viewuser (id, username, email, firstName, lastName, avatarUrl, role); tab (from ?tab=, overview by default) and tabs (gated: hands needs gameHistory, bonuses needs bonuses; the tickets label carries the active count); balances (real, virtual, null while off); stats (handsPlayed, handsWon, handWinRate, totalWinnings, biggestPot, tournamentsPlayed, tournamentsWon, tournamentWinRate; null until loaded); variantStats and variantOptions (the per-variant filter); bonuses (enabled, loaded, available, credits, totalReceived); tickets (loaded, items, activeCount); features
CommandssetTab(tab) (writes ?tab=), updateProfile({ firstName, lastName }), uploadAvatar(file), loadStats(), loadVariantStats(), loadBonuses(), loadTickets(), redeemTicket(ticketId), clearMessages()
Statusstate (ready, signed-out), pending, busy, variantStatsLoading, error, success

The stats tab loads stats and variant stats the first time it opens and the bonuses tab loads bonuses, as the product page does; call the load* commands to load them elsewhere. A failed variant-stats load is silent, as in the product.

useSecurityController(options?): SecurityController

options.autoLoad (default true) loads the 2FA and deletion state on mount; pass false when the screen only changes the password.

Viewpassword (busy, error, success, fieldErrors, requirements, minLength); twoFactor (enabled, null until loaded; setup with qrCode and secret between start and enable; backupCodes, shown once; busy, error); dataExport (busy, error); deletion (loaded, pending with requestedAt, scheduledDeletionAt, daysUntilDeletion; busy, error); sessions (items: id, deviceInfo, ipAddress, userAgent, createdAt, lastActiveAt, expiresAt, isCurrent; null until loaded)
CommandschangePassword({ currentPassword, newPassword, confirmPassword }), checkPassword(value) (each rule with met, for a live checklist), startTwoFactorSetup(), cancelTwoFactorSetup(), enableTwoFactor({ token, password }), disableTwoFactor({ token }), dismissBackupCodes(), exportData() (downloads the JSON file), requestDeletion({ password }), cancelDeletion(), loadSessions(), revokeSession(id), refresh(), clearMessages()
Statusstate (loading, ready), pending, busy

Each section keeps its own error, as the product’s panels do. disableTwoFactor and requestDeletion open the host’s confirmation dialog and resolve { ok: false, message: null } when the player cancels. When the server answers that 2FA is already on (for example, set up on another device) twoFactor.enabled turns true and the set-up closes.

useSettingsController(): SettingsController

Viewtheme (state: loading, ready, refused while the operator does not let players choose or the server answers 403, error; site, options, selected (null = the site theme), saving); colorScheme (value: dark, light or system; options with labels); language (current, rtl, options with code, name, flag, rtl); preferences (sounds and volumes, animation speed, card and pot animations, chip stacks, four-colour deck, chat, notifications, compact mode); marketing (state: loading, ready, error; optedIn; emailConfirmed), the marketing email consent shown next to preferences.emailNotifications
CommandschooseTheme(slug | null) (optimistic; reverts on failure; re-resolves the theme without a reload), setColorScheme(value), setLanguage(code) (saved to the profile when signed in), updatePreferences(values) (keys outside the server’s allow-list are dropped), resetPreferences(), setMarketingEmails(optIn) (saved with source settings)
Statusstate, pending, error

The theme list is requested only while appearance.allowUserThemeChoice is on. A theme the player chooses must declare a scheme for setColorScheme to show an effect; a theme with one scheme keeps it.

useProtectionController(): ProtectionController

Responsible-gaming limits and breaks (the profile’s protection tab).

Viewlimits (depositDaily, lossDaily, lossWeekly, sessionMinutes; null until loaded), pending (increases wait 24 hours: value, activatesAt), fields (labels, min, max, step), restricted, permanent, excludedUntil, coolOffUntil, exclusionOptions (days or permanent), coolOffOptions
CommandssaveLimits(values) (empty or null removes a personal limit), startBreak({ kind: 'exclusion' | 'cool-off', days, acknowledged }), reload()
Statusstate (loading, ready, error), busy, error, saved

startBreak refuses unless acknowledged is true; the template must show the product’s warning and an explicit "I understand" control. Once the server accepts the break the host disconnects, signs the player out and goes to /login.

Lobby and tournaments

useLobbyController(): LobbyController

View ids: member.lobby, member.lobby.cash, member.lobby.tournaments, member.lobby.private.

It subscribes to the lobby socket while mounted. The table list arrives through the socket only (lobby_state plus incremental updates), for guests too. Tournaments and the player’s private games are fetched over HTTP when the hook mounts and again after any command that changes them. The read-only useLobby() stays for sections: on any other page it starts the same socket subscription (and loads the tournaments) while a component that calls it is mounted, for guests too, and stands down while the lobby page runs its own. Merge tags read the lobby without starting it.

view fieldMeaning
taball, cash, tournaments or private, from the route
tabs{ id, href, active } for each tab the operator’s feature toggles allow
isLiveThe lobby socket is connected
isRestrictedThe licence is invalid or not configured. Show tables as closing and hide joins, as the default lobby does.
isLoggedIn, featuresSign-in state and the tournaments, privateGames, realMoney and virtualChips toggles
balanceMode, balanceModes, balancereal or play, the modes the operator enables, and the viewer’s balance in the current mode. If only one mode is enabled, the hook selects it.
filtersstakes, gameType, showEmpty, showFull, search, speed, tournamentFormat
tablesCash tables after the filters: stakes, buy-ins, seatsTaken / seatCount / seatsOpen, isFull, status, ruleProfile, and the href / watchHref routes. Contract 0.2.3: playMoney (the table plays for play chips: show a "Play money" tag on every such row, in every list; the host derives it from mode, the one source, so mode === 'virtual' and playMoney always agree and a theme may read either; the public lobby view (useLobbyView) passes the same mode and tournament currency) and mixedRotation ({ games, handsPerVariant } at a mixed-game table, the engine’s game names in order; null otherwise)
tournamentsTournaments after search, speed and format, in the lobby’s order: sit-and-gos by fill, scheduled tournaments by start time, the two interleaved on all. Contract 0.2.3: playMoney (currency is VIRTUAL_CHIPS)
privateGamesThe viewer’s private games after the search; isOwner marks the ones they created. Contract 0.2.3: playMoney
sngCountdown{ tournamentId, startsIn, tableId } while a sit-and-go the viewer joined is starting
rulesHrefContract 0.2.3: the game rules page (/pages/rules). A theme that replaces the lobby links it near the lobby title, in its own style. While a theme is active the host also links Game rules in the strip below the footer, so a theme without the link still has the rules one click away
CommandBehaviour
selectTab(tab)Navigates to the tab’s route; the route sets the tab
setFilters(patch), resetFilters()Change the lobby filters (the store is shared, so the lobby.filters part area sees the same values)
setBalanceMode(mode)Switches between real money and play money (persisted like the default toggle)
openTable(id)Opens the table page. Seat selection, the buy-in dialog and the waitlist are part of the table page and its layout, not of the lobby.
watchTable(id)Opens the spectator view
openTournament(id)Opens member.tournament.detail
registerTournament(id), unregisterTournament(id)Register or unregister from the lobby, then refetch the tournament list
validatePrivateGame(input)The create form’s rules: small blind below big blind, min buy-in at most max, ante at most big blind
createPrivateGame(input)Validates, creates the table and adds it to privateGames; resolves to { tableId, inviteCode }
joinPrivateGame({ tableIdOrCode, password })Joins with the table password, then opens the table
deletePrivateGame(id)Asks the player to confirm, then deletes. Resolves to { deleted: false } when they cancel. The players still seated get their chips back: between hands they are cashed out at once; during a hand the table deals no new hand and closes, with the same cash-out, when the hand ends, and the result has closesAfterHand: true.
privateGameJoinLink(code)The shareable /lobby?join=<code> link (the joiner still needs the password)
createPrivateGameInviteLink(tableId)A one-time direct-join link that skips the password: { url, expiresAt }
acceptPrivateGameInvite(token)Consumes a direct-join token and opens the table
copyPrivateGameCode(code), copyPrivateGameJoinLink(code), copyPrivateGameInviteLink(tableId)Copy the invite code, the join link (resolves to { url }) or a new one-time direct-join link (created like createPrivateGameInviteLink, resolves to { url, expiresAt }) to the clipboard. Themes may not use the clipboard themselves (js.forbidden-api), so the host copies, with the Clipboard API and a selected-text fallback. A refused copy resolves ok: false and sets errors.action. These three are optional on the type: check that one exists before showing a Copy button, and otherwise show the value for the player to select.
refresh()Asks the socket for a fresh table list and refetches tournaments and private games

The default lobby redirects ?join= and ?invite= links to the private tab and handles them there. A themed member.lobby.private template reads the query itself, with useNavigate and the URL, and calls joinPrivateGame or acceptPrivateGameInvite.

useTournamentController(tournamentId: string): TournamentController

View id: member.tournament.detail (the route passes params.tournamentId).

view fieldMeaning
tournamentName, variant, limit, format, currency, buy-in, start, status, speed, registered / max players, prize pool, satellite target, handForHand
tournament.clockCurrent and next level (smallBlind, bigBlind, ante), seconds remaining, level-change timing, break status
tournament.structureRule profile, family, registration and payout policy, level duration, late-registration window, whether rebuy, add-on and re-entry are on, and the raw rule settings as settings
tournament.payouts{ position, percentage, amount } from the rule profile; amount is the share of the current prize pool
registrationisRegistered (false once eliminated), isParticipant (played in this tournament, eliminated or not), canRegister, canUnregister, and the server’s reason when registration is closed for this player
entryOptionsrebuy, addOn and reentry: enabled, eligible, remaining, chips, cost, level window
canUseRegistrationRegistration buttons apply now (registering, or late registration while running)
playersStandings (rank, chips, eliminated, finish, entries, rebuys, add-ons, isViewer). The server shows standings to participants only, so the list is empty for anyone else.
myTableIdThe viewer’s table once the tournament has seated them
isBusy, messageA command is running; the last command’s success message

Commands: register(), unregister(), rebuy(), addOn(), reentry(), openMyTable(), login(), backToLobby(), refresh(), loadPlayers(). Each money command refetches the tournament after it succeeds.

History and hands

useHandHistoryController(options?: { pageSize?: number }): HandHistoryController

View id: member.history (route /history, signed-in only). The same list is also the Hands tab of the profile page.

  • view.hands: { id, gameId, handNumber, tableId, tableName, variant, startedAt, endedAt, pot, players, isWinner, profit, href }, where href is the hand’s replay route.
  • view.filters: { result: 'all' | 'win' | 'loss', from, to, tableId }. Dates are ISO strings or null.
  • view.pageInfo: { page, pageSize, total, totalPages } (default page size 20).
  • Commands: setPage(n), nextPage(), previousPage(), setFilters(patch) (returns to page 1), openHand(gameId), refresh().
  • view.trackerExportAvailable and commands.downloadTrackerExport(fromDay, toDay) (both optional, added without a contract bump): while the site allows it, the player can download their own hands of a date range (YYYY-MM-DD, inclusive) as a text file that hand-tracking tools import. Show your download control only while trackerExportAvailable is true; the server picks the player from the session and refuses the download when the operator switched it off or certified mode locks it.

The operator’s Game history feature toggle gates the endpoint. When it is off, the load fails with the server’s message in errors.load.

useHandReplayController(gameId: string): HandReplayController

View id: member.hand (route /history/:gameId, which passes params.gameId).

  • view.hand: the board, pot and side pots, players (seat, starting stack, holeCards, folded, all-in, hand description, isViewer), every action (name, seat, action, label, amount, street), streets (board and pot at each street marker with that street’s actions) and winners.
  • Hole cards follow the server’s rule: the viewer’s own cards and the cards shown at showdown. Everyone else’s are null.
  • view.step, view.stepCount, view.visibleActions: a replay cursor. It starts at the end of the hand.
  • Commands: next(), previous(), goTo(step), showAll(), backToHistory(), refresh().

A player who was not in the hand gets the server’s "not a participant" message in errors.load.

Notifications, leaderboard, affiliate

useNotificationsController(options?: { pageSize?: number }): NotificationsController

View id: member.notifications (route /notifications, signed-in only). Notifications are the messages the operator sends a player from Players › Support Inbox (Compose message). They are plain text: render body as text, never as HTML.

  • view.notifications: { id, category, subject, body, sender, isRead, createdAt }, newest first.
  • view.unreadCount, view.unreadOnly, view.pageInfo.
  • Commands: markRead(id) (updates in place, so an unread-only list does not reorder under the player), markAllRead(), remove(id) (asks the player to confirm first), setUnreadOnly(flag) (returns to page 1), setPage(n), refresh().

The server endpoints are GET /user/notifications, GET /user/notifications/unread-count, POST /user/notifications/read-all, PATCH /user/notifications/:id/read and DELETE /user/notifications/:id. Every query is scoped to the signed-in player. Deleting a notification removes the message for the operator too, because a message is one record shared by sender and recipient.

useLeaderboardController(options?: { pageSize?: number }): LeaderboardController

View id: member.leaderboard.

  • view.entries: { rank, playerId, username, handsPlayed, handsWon, winRate, winnings, vpip, pfr, isViewer }.
  • view.gameType ('' for every game), view.sortBy (winnings, winRate, handsPlayed, handsWon), view.gameTypes and view.sorts as { value, label } options, and view.pageInfo.
  • Commands: setGameType(value) and setSortBy(value) (both return to page 1), setPage(n), refresh().

useAffiliateController(): AffiliateController

View id: member.affiliate.

  • view.enabled: the operator’s affiliate toggle. When it is off, status is idle.
  • view.tab: overview, referrals, rewards, leaderboard or network. Each tab’s data loads the first time the tab opens.
  • view.overview: the referral code and link, clicks, conversion rate, referral counts, total earnings, rank and percentile by referrals and by earnings, recent referrals and earnings by period, and earnings by level.
  • view.referrals with view.referralsPage; view.rewards (the payout history) with view.rewardsPage and view.rewardsTotal.
  • view.leaderboard: { period, byReferrals, byEarnings }. view.network: { size, earnings, byLevel }.
  • view.copied: true for two seconds after a copy.
  • Commands: selectTab(tab), setReferralsPage(n), setRewardsPage(n), setLeaderboardPeriod(period), copyReferralLink(), refresh() (reloads the open tab).

Other member pages

Agent portal

Every agent portal route has a view id. A theme can replace any of these screens:

RouteView id
/agentagent.overview
/agent/playersagent.players
/agent/players/:idagent.player
/agent/sub-agentsagent.sub-agents
/agent/clubsagent.clubs
/agent/clubs/:idagent.club
/agent/commissionsagent.commissions
/agent/wholesaleagent.wholesale
/agent/reportsagent.reports

agent.* ids do not fall back to each other. Register a template under each id you replace; any id without one renders the default page. Agent templates render inside the agent layout and its sign-in guard.

useAgentController(): AgentController

For agent.overview:

  • view.stats: { agentBalance, controlledBalance, totalPlayers, activePlayers, totalEarnings, pendingHoldbackTotal }.
  • view.permissions: the granted permission keys (subagent.create, club.create, reports.own_commission, …).
  • view.pages: { id, href } for every agent page.
  • Commands: openPage(page), can(permission), refresh().

The other agent pages (players, player detail, sub-agents, clubs, club detail, commissions, wholesale, reports) have no controller yet. A theme can wrap their screens with its own layout around the host components, or present read-only data. Replacing their forms is not yet supported.

Plugin pages

member.plugin.<providerType> covers /ext/<providerType>/* and the public plugin routes. The plugin owns the page’s behaviour, so there is no controller. A template replaces the whole page, plugin content included, so register one only if the theme provides that plugin’s screen itself.

Try the live demo Pricing

Have questions about Poker Engine? We reply fast.