@pilimo/game-client
v1.0.0
Published
Browser / Node WebSocket client for the Pilimo game-server protocol, built on @pilimo/velo-client
Maintainers
Readme
@pilimo/game-client
Browser / Node.js client for the Pilimo game-server protocol, layered on
@pilimo/velo-client. The wire format is handled for you: the API deals in
codes and payloads.
| Feature | API |
|---|---|
| Match token handshake, decoded connect payload | GameClient.connect() |
| Script request / response | client.request() |
| Script pushes | client.onMatchMessage() |
| Player and match status broadcasts | client.onPlayerStatusChange(), client.onMatchStatusChange() |
| Names, scores and avatars from the public API | PlatformApi |
| Keepalive, criteria, optional timeouts | inherited from the Velo client |
Installation
npm install @pilimo/game-client@pilimo/velo-client is a dependency and comes with it. Inside this monorepo
it is linked with a file: dependency, so npm install here is enough.
| Entry | Use |
|---|---|
| import { GameClient } from '@pilimo/game-client' | bundlers, Node (ESM or CommonJS) |
| import { GameClient } from '@pilimo/game-client/browser' | one minified ESM file for <script type="module"> and import maps |
| dist/velo-game-client.js | classic <script> tag; exposes the VeloGame global |
Quick start
import { GameClient, MatchStatus, PlayerStatus, MatchRequestError } from '@pilimo/game-client';
// The match token comes from the launch URL fragment (see the game-development skill).
const { client, connectPayload } = await GameClient.connect(serverAddress, matchToken);
connectPayload.matchId; // string
connectPayload.players; // [{ id, status }] in join order
connectPayload.matchStatus; // MatchStatus.RUNNING, …
connectPayload.ranked; // boolean
connectPayload.gamePayload; // Uint8Array: the script's welcome payload
client.onMatchMessage(({ code, payload }) => { /* script push */ });
client.onPlayerStatusChange(({ playerId, status }) => { /* status === PlayerStatus.CONNECTED */ });
client.onMatchStatusChange(({ status }) => { if (status === MatchStatus.ENDED) { /* … */ } });
client.onClose((ev) => { /* reconnect with the same token */ });
// A script request. The script answers with its own code: 0 for OK, or one of
// its rejection codes (e.g. "not your turn"), returned here as a value.
const reply = await client.request(SCRIPT_MOVE, encodeMove(cell));
if (reply.code !== 0) showRejection(reply.code);
client.close();API
GameClient.connect(url, token, options?) → Promise<{ client, connectPayload }>
Opens the socket, sends the match token as the Velo handshake payload and
decodes the connect payload. options are the Velo client options
(criteria, keepalive, requestTimeout, handshakeTimeout,
socketFactory); keepalive is on by default.
Rejects with VeloHandshakeError (bad or expired token, match closed),
VeloConnectionError (socket failed or closed first) or GameProtocolError
(the connect payload was malformed; the socket is closed).
client.request(code, payload?, { timeout? }?) → Promise<{ code, payload }>
Sends a MATCH_REQUEST carrying the script-defined code and payload
(Uint8Array, string, or a JSON-serialisable object) and resolves with the
script's answer.
The script's own code is always returned, never thrown: Velo reserves codes
0–9, so every code a script chooses is 10 or above (the shipped games use 238
and up). MatchRequestError is thrown only for the reserved codes 1–9, which
the server itself sends when it could not reach the script: a malformed body
(1) or a script that never answered (3). Transport errors pass through
unchanged: VeloCriteriaViolation, VeloConnectionError, and
VeloTimeoutError when a timeout was configured.
Subscriptions
onMatchMessage, onPlayerStatusChange, onMatchStatusChange and onClose
each return an unsubscribe function. A listener that throws does not stop the
other listeners; the error is rethrown afterwards. Push codes this version
does not know are ignored, so a newer server keeps working with an older
client. A push whose payload does not decode closes the connection with code
4002.
client.close(code?, reason?), client.isConnected, client.veloClient
veloClient is the underlying VeloClient, for raw messages or streams.
PlatformApi
const api = new PlatformApi(PUBLIC_API_URL); // { fetch } is injectable
const details = await api.getMatchDetails(matchId); // PlatformMatchDetails | null
img.src = api.avatarUrl(userId); // 404 when the user has no avatarBoth calls are best effort: a failed request resolves to null rather than
throwing, so a flaky network never breaks the match.
Errors
| Class | When |
|---|---|
| GameClientError | Base class of this package's errors |
| GameProtocolError | A server payload does not match the wire format |
| MatchRequestError | The server failed a request with a reserved code 1–9 (code, payload) |
| VeloError and subclasses | Transport errors, re-exported from @pilimo/velo-client |
Development
npm install
npm test # vitest, no network: the socket and fetch are faked
npm run typecheck
npm run build # dist/esm, dist/cjs, dist/types, IIFE and ESM bundlesclient.ts composes wire.ts (codec), push-router.ts (push code → handler)
and platform-api.ts; each has its own test file under test/, and the client
is tested end to end over test/fake-socket.ts with bytes built by hand in
test/wire.ts from the two protocol specs.
