@gameplay-ai/sdk
v0.4.1
Published
Cliente do jogo para a API GamePlay.ai
Readme
@gameplay-ai/sdk
TypeScript client for the GamePlay.ai play API. The package ships no secrets, .env, or certificates. Tokens stay in memory: they never go on the URL, in cookies, or in local storage. Requests use Authorization: Bearer and credentials: "omit".
pnpm add @gameplay-ai/sdkMethod-by-method calls, responses, and notes live in Studio → Docs.
Declare leaderboard keys, achievement keys, catalog SKUs, and remote config on the game sheet there before you call them from the game.
Hosted iframe (website and Studio)
Games on gameplay.ai and Studio playtests run in an iframe. SDK 0.2.1
exports GAMEPLAY_FRAME_ORIGINS so the game lists official parents without
wildcards. connectGameplayFrame talks to that parent only.
List exact HTTP(S) origins — no paths, no wildcards. Import GAMEPLAY_FRAME_ORIGINS for the official store, Studio, preview, and local dev ports (5173 store, 3002 Studio). Production hosts are https://gameplay.ai, https://www.gameplay.ai, and https://studio.gameplay.ai. Add apiOrigins when the API origin differs from the store.
import {
connectGameplayFrame,
GAMEPLAY_FRAME_ORIGINS,
type GameplayLocale,
} from '@gameplay-ai/sdk';
let currentLocale: GameplayLocale = 'en';
let started = false;
const connection = connectGameplayFrame({
allowedOrigins: [...GAMEPLAY_FRAME_ORIGINS],
apiOrigins: ['https://api.gameplay.ai'],
onSession({ client, locale, roomId, guest }) {
currentLocale = locale ?? currentLocale;
startGame(client, currentLocale, roomId, guest);
started = true;
},
onLocaleChange(locale) {
currentLocale = locale;
if (started) setGameLanguage(locale);
},
});
function cleanupGameplay() {
connection.disconnect();
}onSession receives { gameId, guest, expiresAt, client, locale, roomId }. The token is not on that object. The helper announces gameplay:ready and accepts one gameplay:init from the listed parent.
Since SDK 0.2.2, session.roomId contains the room selected on the Multiplayer page.
After loading the account and interface, join that exact room and connect with
client.multiplayer.connect({ roomId: session.roomId }). If joining fails, show
the error so the player can choose another room. Ordinary launches, older hosts
and guest sessions provide null; they keep the game's usual entry flow.
Locales are pt-BR, en, and es (GameplayLocale). The host resolves system before sending. onLocaleChange may fire before the session (tester previews). The same locale twice does not fire again. A locale change does not restart the game or recreate the client.
connection.locale and session.locale are null until the host sends a language (older hosts). Call disconnect() when the match ends.
The website keeps the heartbeat. Use client for events and the APIs allowed for that session. Guests must not call save, shop, ranking, or achievements (those return 403).
startGame and setGameLanguage are your game's functions.
Guest (no store cookie)
import { createGameplayClient, openGuest } from '@gameplay-ai/sdk';
const guest = await openGuest({
baseUrl: 'https://api.gameplay-endpoint',
slug: 'your-game-slug',
});
const client = createGameplayClient({
baseUrl: 'https://api.gameplay-endpoint',
gameId: guest.gameId,
token: guest.token,
});
await client.heartbeat();
client.track([{ name: 'run_start', kind: 'event' }]);
const remote = await client.config();
const clock = await client.time();openGuest asks the API for a visitor token. The API creates sub. The game never sends playerId. Guest tokens work for heartbeat(), track(), config(), and time(). Do not log the token.
heartbeat() does not send country. The official country comes from the edge header.
track() takes a flat list. No nested objects, emails, or secret-looking fields. Events flush in a short batch (default 40 ms).
Account session
The store exchanges its cookie for a game token (POST /auth/session/game-token) and passes that token into createGameplayClient. The game never reads the store cookie.
import { createGameplayClient } from '@gameplay-ai/sdk';
const client = createGameplayClient({
baseUrl: 'https://api.gameplay-endpoint',
gameId: 'your-game-uuid',
token: gameToken,
});Remote config and clock
const clock = await client.time();
// clock.now — ISO 8601 UTC. Use this for seasons and offers, not the device clock.
const remote = await client.config();
// remote.revision, remote.payload — JSON published on the game sheet (up to 32 KB).Save with revision
const slot = await client.readSave(0);
try {
await client.writeSave({ level: 3, hp: 80 }, 0, slot.revision);
} catch (error) {
// 409 when another write won. Read again and retry.
}Leaderboard
Keys are the ones declared in Studio.
await client.submitScore('high_score', 1200);
const board = await client.leaderboard('high_score', 10);
const mine = await client.user.rank('high_score');
// mine is null until this player has a score.Gameplay.ai verified rankings
Static games with rules registered in the platform can use client.ranked. Call
client.ranked.capability() after an authenticated launch to detect the available mode.
solo() and soloAction() support Gem Merge. room() and roomAction() support chess rooms.
Send only an action, the current revision and the match or run ID. The platform applies the
rules and records the result with the same transaction. No game server URL or API key is needed.
The Studio boards used by the built-in modes must use Servidor exclusivo, descending order, maximum aggregation, no season and no score cap. Gameplay.ai reserves those board keys for its verified results.
Leaderboard Security & Anti-Cheat
Leaderboards in GamePlay.ai support two write modes:
- Client SDK (
client): The game client callsclient.submitScore(key, value). Ideal for casual, single-player, or client-driven experiences. - Server Authoritative (
server): The board cannot be written by the browser SDK. Anyclient.submitScore()call on a server-only board throws403 Forbidden. Use this for competitive games where only your dedicated server calculates or validates scores and posts them via the Server-to-Server API (POST /v1/leaderboards/:gameId/:userId/:keywith a developerApiKey). - Validation Bounds: Studio allows configuring
minScoreandmaxScore. Submissions outside these boundaries throw400 Bad Request. - Rate Limiting: SDK score submissions are throttled per session to prevent flooding and script abuse.
Connect a ranked game to its server
Set the ranking's write mode to Servidor exclusivo in Studio. Use a game-scoped API key
with identity:verify and leaderboard:write on the game server. Test and live keys can
verify and publish only in their own environment.
In the browser, configure your game's backend origin in connectGameplayFrame (or
createGameplayClient). Send actions to your server using client.backend.post.
The SDK sends the game token in the Authorization header to that origin and refuses
redirects. Configure your backend's CORS policy to allow your game's origin and the
Authorization and Content-Type headers. For games that resolve the backend later
from trusted Studio configuration, createGameplayBackend({ origin, token })
creates the same transport without creating another SDK client. Bind it using the
in-memory token from your createClient callback, and only use configuration
controlled by the game developer.
connectGameplayFrame({
allowedOrigins: [...GAMEPLAY_FRAME_ORIGINS],
apiOrigins: ['https://api.gameplay.ai'],
backendOrigin: 'https://server.mygame.example',
expectedGameId: GAME_ID,
onSession({ client, guest }) {
if (!guest) {
startRankedGame((move) => client.backend!.post('/ranked/move', move));
}
},
});In a Node.js backend, import @gameplay-ai/sdk/server. Your HTTP handler should take
the Bearer token from the request, verify it for this game and bind each run to the
verified player. The following example calls a game-specific engine.
import { createGameplayServer } from '@gameplay-ai/sdk/server';
const gameplay = createGameplayServer({
apiOrigin: 'https://api.gameplay.ai',
gameId: process.env.GAMEPLAY_GAME_ID!,
apiKey: process.env.GAMEPLAY_API_KEY!,
});
async function playRankedMove(gameToken: string, action: unknown) {
const player = await gameplay.verifyPlayer(gameToken, AbortSignal.timeout(5000));
const result = await gameEngine.applyMove(player.userId, action);
if (result.finished) {
await player.submitScore('high_score', result.score, AbortSignal.timeout(5000));
}
return result;
}The engine is responsible for rejecting invalid, duplicate and out-of-order actions and calculating the score from server-owned state, including game randomness and consumables. A valid token proves player identity only. Never publish a score read from the request body or from a browser-controlled save. Keep the API key in server environment variables, and use a new season or board if earlier scores were accepted directly from clients.
Shop
const catalog = await client.catalog();
await client.purchase('potion', 2);
const bag = await client.inventory();Achievements
const list = await client.achievements();
const result = await client.unlock('first_win');
// result.fresh is true only the first time this player unlocks the key.Player profile
const me = await client.user.getUser();
// username, XP, level, country, badges, activity — no email, no account prefs.Guest tokens get 403 on getUser().
Multiplayer rooms
const rooms = await client.multiplayer.list('casual');
const created = await client.multiplayer.create({
name: 'Room 1',
mode: 'casual',
capacity: 4,
});
await client.multiplayer.join(created.id);
const match = client.multiplayer.connect({
roomId: created.id,
});
match.onStatus((status) => {
/* connecting | open | closed */
});
match.onMessage((payload) => {
/* welcome | snapshot | state | peer-joined | peer-left | event | error */
});
match.send({ x: 10, y: 20, skin: 'neon' });
match.sendEvent('ready', true);
match.close();
await client.multiplayer.leave(created.id);Enable Multiplayer in Studio. SDK 0.2.0 uses the authenticated Gameplay transport
on the same API URL, including a host's /api proxy prefix. No game server or
WebSocket URL is required. Guests cannot join rooms. Pass url only to keep using
an existing external server with the legacy hello/input protocol.
match.status and onStatus report connecting, open and closed; onStatus
also reports the current value immediately. send publishes a complete player
state (16 KiB maximum, up to 30/s). sendEvent publishes an ordered named event
(4 KiB maximum, up to 10/s). Both return false while disconnected. States drop
under congestion; events are not replayed across reconnects.
The server supplies player identity and initial snapshots. Reconnects retry for 15 seconds and authenticate again. A host leaving transfers the room to another member; the final member leaving deletes it. Game rules and score validation remain the game's responsibility. See multiplayer protocol and deployment.
Errors
client.capture(error) batches traces to the API. Failed traces do not crash the game. Uncaught error and unhandledrejection on window are captured automatically.
More documentation
Studio Docs lists every SDK method with the HTTP path, a sample call, and the payload the game receives:
