@splattervault/server 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/LICENSE +21 -0
- package/README.md +380 -2
- package/dist/index.cjs +1594 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +14370 -0
- package/dist/index.d.ts +14370 -0
- package/dist/index.js +40 -0
- package/package.json +80 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@splattervault/server` are listed here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package uses [semantic versioning](https://semver.org/);
|
|
5
|
+
while it is 0.x, a minor version may change the API.
|
|
6
|
+
|
|
7
|
+
## [0.1.1] - 2026-11-15
|
|
8
|
+
|
|
9
|
+
Follows the corrected Studio API description (API main c002ca7f, https://splattervault.com/docs/studio/swagger.json).
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `poolClaimConflict(err)`: tells a `serverPools.claim` 409 apart by the API's message: `"no_warm_server"` (none idle:
|
|
14
|
+
start a session instead) or `"busy"` (the "— retry" messages: contention; trying the claim again shortly is safe;
|
|
15
|
+
nothing was claimed). The SDK still never retries a claim itself (it starts servers). The README and
|
|
16
|
+
`examples/match-server.ts` show the fallback.
|
|
17
|
+
|
|
18
|
+
### Changed (types, from the API description)
|
|
19
|
+
|
|
20
|
+
- `CreditBalance`: `createdAt` and `updatedAt` are now `string | null` (an organization API key's answer has null
|
|
21
|
+
dates); new fields `availableBalance`, `graceExpiresAt` (`string | null`) and `user` (an object, or null; null for
|
|
22
|
+
an organization key). Code that assigned `createdAt` to a non-null `string` must now handle null. The SDK itself
|
|
23
|
+
never reads these fields.
|
|
24
|
+
- Every GET operation's parameters now list an optional `If-None-Match` header, and its answers `ETag`, `304` and
|
|
25
|
+
`x-request-id` headers (`components["headers"]["RequestId"]`); `serverPools.claim` lists its `409` answer. Request
|
|
26
|
+
and answer bodies are unchanged apart from `CreditBalance`.
|
|
27
|
+
|
|
28
|
+
### Documentation
|
|
29
|
+
|
|
30
|
+
- The game-server session and billing routes never answer 429 (the API sets no rate limit on them): said so in the
|
|
31
|
+
README and on `Sessions` / `Billing`; only the studio routes answer `429 rate_limited`.
|
|
32
|
+
- Conditional requests: every GET documents ETags, but the SDK never sends `If-None-Match` itself, so it never meets
|
|
33
|
+
a 304; if you send one in `headers`, it adds `Cache-Control: max-age=0` and a 304 rejects with status 304 (as in
|
|
34
|
+
0.1.0). The contract test now checks exactly that instead of "no operation documents ETags".
|
|
35
|
+
|
|
36
|
+
## [0.1.0] - 2026-11-15 (preview)
|
|
37
|
+
|
|
38
|
+
The first release: the Studio API's server operations (organization API key) for Node.js 18 and later.
|
|
39
|
+
|
|
40
|
+
### Added
|
|
41
|
+
|
|
42
|
+
- `SplatterVault` client with the API key from `apiKey` or `SV_API_KEY`; refuses to start in a browser, a web
|
|
43
|
+
worker or React Native unless `dangerouslyAllowBrowser`; never shows the key in logs, `util.inspect`, JSON or errors.
|
|
44
|
+
- Game-server sessions: `sessions.create/list/get/listMine/stop/rename/reschedule/cancelSchedule`, the same for
|
|
45
|
+
subscription-billed sessions under `sessions.subscription`, `serverPools.claim`, `games.getConfigurableArgs`, and
|
|
46
|
+
`sessions.waitUntilReady` (polls until the game is ready; `SessionWaitError` with `session_ended` / `wait_timeout`).
|
|
47
|
+
- Billing: `billing.getCredits/getCreditStats/getOrgCredits/getOrgSubscriptions/getOrgCreditsById/getOrgSubscriptionById/getSubscriptions/getUsage`.
|
|
48
|
+
- Player sign-in from your backend: `players.signIn/import/erase`.
|
|
49
|
+
- Player data: `playerData.resolve/get/update/clear/getMany/writeMany/getGameData/updateGameData/import/listErasedPlayers`
|
|
50
|
+
and the `playerData.erasedPlayerPages` page iterator.
|
|
51
|
+
- Store: `store.getCatalog/getPlayer/getHistory/grant/consume/purchase/updateItem/reverse/syncMetaPurchases/importCatalog/importHoldings`
|
|
52
|
+
and the `store.historyPages` page iterator. Store changes send an `Idempotency-Key` (made per call, reused on
|
|
53
|
+
retries, or yours with `{ idempotencyKey }`; `null` makes one, so `err.idempotencyKey` can be passed straight back).
|
|
54
|
+
- Offline player-token verification: `verifyPlayerToken`, `createPlayerTokenVerifier`, `sv.verifyPlayerToken`
|
|
55
|
+
(Ed25519 with `node:crypto`; the JWKS from `GET /player-auth/keys` cached per its Cache-Control, at least 60 s and
|
|
56
|
+
at most an hour, fetched again on an unknown key id, stale keys usable 300 s while the API is unreachable; the API's
|
|
57
|
+
own checks plus your game id; sign-in methods added later are accepted).
|
|
58
|
+
- `readSessionEnvironment()` for game processes started by SplatterVault.
|
|
59
|
+
- `SplatterVaultError` with `status`, `code`, `message`, `details`, `retryAfter`, `requestId` (both API error shapes),
|
|
60
|
+
`outcomeUnknown` (a write that may or may not have been applied) and `idempotencyKey` (the key a store change was
|
|
61
|
+
sent with, to resend it exactly once).
|
|
62
|
+
- Retries for safe calls only, on network errors, timeouts, 408, 429, 500, 502, 503 and 504, honouring `Retry-After`,
|
|
63
|
+
with jittered exponential backoff: reads, lookups, imports and `clear`; store changes with the same Idempotency-Key
|
|
64
|
+
and body (also after a resend meets its own in-progress `idempotency_conflict`); player-data writes whose every op
|
|
65
|
+
has `ifVersion` only after 408, 429 or 503 (never after an unknown outcome; a resend that meets `version_conflict` is
|
|
66
|
+
`outcome_unknown`). Per-attempt timeouts; `AbortSignal` support.
|
|
67
|
+
- Safety: redirects are never followed (`redirect_not_followed`), so the API key never goes to another address; plain
|
|
68
|
+
http only for loopback hosts (or `dangerouslyAllowInsecureHttp`), for the API and the player-token keys alike;
|
|
69
|
+
numeric options validated (NaN, Infinity and out-of-range values throw); `.` and `..` path parameters and empty
|
|
70
|
+
`stores` / `keys` lists refused; the SDK refuses to start in Electron and NW.js as in browsers.
|
|
71
|
+
- One copy for `import` and `require` (the ES module entry re-exports the CommonJS build): `instanceof` holds across
|
|
72
|
+
both, and the key cache is shared.
|
|
73
|
+
- Request and answer types generated from the Studio API's OpenAPI description (`npm run generate`).
|
|
74
|
+
- ESM and CommonJS builds with type declarations; no runtime dependencies.
|
|
75
|
+
|
|
76
|
+
### API description
|
|
77
|
+
|
|
78
|
+
- `openapi/studio-api.json` is the corrected Studio API description: `StoreHoldingsImportRequest.rows[].balances` is
|
|
79
|
+
`{ [currency code]: amount }` (an integer of at least 0 per code), not a list of `{ currency, amount }`. The
|
|
80
|
+
generated type changed accordingly (`balances?: { [key: string]: number }`).
|
|
81
|
+
- `ServerSession` now lists `ready`, `readyAt` and `readyDeadlineAt` (optional; the times nullable), so `ReadySession`
|
|
82
|
+
is an alias of `ServerSession`.
|
|
83
|
+
- Its code samples now name the key variable `SV_API_KEY`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SplatterVault
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,381 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @splattervault/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The SplatterVault SDK for your **game backend and game servers** (Node.js 18+, TypeScript types included, no
|
|
4
|
+
runtime dependencies).
|
|
5
|
+
|
|
6
|
+
- **Game servers**: start a dedicated server for a match, or claim a warm one from a pool in seconds; stop, rename,
|
|
7
|
+
reschedule; credits and subscriptions.
|
|
8
|
+
- **Players**: sign players in with your own ids, import players from other systems, erase a player and everything
|
|
9
|
+
kept about them.
|
|
10
|
+
- **Player data**: read and write each player's data and your game's data, with versions for safe concurrent changes.
|
|
11
|
+
- **Store**: grant, consume, buy with virtual currency and reverse, each applied exactly once; catalog and holdings
|
|
12
|
+
imports.
|
|
13
|
+
- **Player tokens**: verify, offline, that a player connecting to your game server really signed in to SplatterVault.
|
|
14
|
+
|
|
15
|
+
> **Preview (0.x).** The API surface may still change between minor versions; see the [CHANGELOG](CHANGELOG.md).
|
|
16
|
+
|
|
17
|
+
## Your API key stays on your servers
|
|
18
|
+
|
|
19
|
+
This SDK calls the Studio API with an **organization API key** (`sv_org_...`). Anyone who holds that key can act as
|
|
20
|
+
your studio: grant items, read and erase players, start servers billed to you. So:
|
|
21
|
+
|
|
22
|
+
- Put the key only on your backend and game servers (an environment variable or your secret manager). **Never in a
|
|
23
|
+
game build, a web page or a mobile app**, never in a repository.
|
|
24
|
+
- The SDK refuses to start in a browser, a web worker, React Native, Electron or NW.js (anything you ship to players),
|
|
25
|
+
and it never logs or prints the key (not even in `console.log(sv)` or in errors).
|
|
26
|
+
- The key only travels over https to the URL you configured: the SDK refuses a plain-http `baseUrl` except for
|
|
27
|
+
localhost / 127.0.0.1 / [::1] (a local mock), and it **never follows a redirect** (a 3xx is an error with code
|
|
28
|
+
`redirect_not_followed`), so the key is never sent to another address.
|
|
29
|
+
- Give each key only the permissions it needs (console → your organization → API keys), and rotate it if it leaks.
|
|
30
|
+
|
|
31
|
+
Game clients do not use this SDK. They sign their player in (Steam, Meta, email, a guest, your own backend…) and call
|
|
32
|
+
the player routes with a short-lived **player token**, using the SDK of their engine:
|
|
33
|
+
[Unity](https://github.com/splattervault/unity-sdk), [Unreal](https://github.com/splattervault/unreal-sdk) or
|
|
34
|
+
[Godot](https://github.com/splattervault/godot-sdk).
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npm install @splattervault/server
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Works from ESM (`import`) and CommonJS (`require`), on Node.js 18, 20, 22 and later. Both load the same single copy of
|
|
43
|
+
the SDK (the ES module entry re-exports the CommonJS build), so `instanceof SplatterVaultError` holds whichever way an
|
|
44
|
+
error was created.
|
|
45
|
+
|
|
46
|
+
## Quick start
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { SplatterVault } from "@splattervault/server";
|
|
50
|
+
|
|
51
|
+
const sv = new SplatterVault({ apiKey: process.env.SV_API_KEY });
|
|
52
|
+
// With no apiKey option, the SDK reads SV_API_KEY itself.
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
One client per process is enough; it is safe to share.
|
|
56
|
+
|
|
57
|
+
### Give a match a dedicated server
|
|
58
|
+
|
|
59
|
+
Claim a warm server from one of your pools (it is already running: seconds), or start a new session (about a
|
|
60
|
+
minute):
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { poolClaimConflict, SplatterVault } from "@splattervault/server";
|
|
64
|
+
|
|
65
|
+
const sv = new SplatterVault();
|
|
66
|
+
|
|
67
|
+
async function serverForMatch(matchId: string) {
|
|
68
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
69
|
+
try {
|
|
70
|
+
const claim = await sv.serverPools.claim(12, { friendlyName: `Match ${matchId}`, mode: "Ranked" });
|
|
71
|
+
return claim; // { sessionId, serverInstanceId, connection: { host, primaryPort, code, ... } | null }
|
|
72
|
+
} catch (err) {
|
|
73
|
+
const conflict = poolClaimConflict(err); // a 409 claimed nothing; null for any other error
|
|
74
|
+
if (conflict === "busy" && attempt === 1) {
|
|
75
|
+
await new Promise((r) => setTimeout(r, 1000)); // contention: one more try shortly
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (conflict === null) throw err;
|
|
79
|
+
break; // "no_warm_server" (or still busy): start a new one instead
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const session = await sv.sessions.create({
|
|
83
|
+
gameTypeConfigKey: "my-game",
|
|
84
|
+
region: "NYC3",
|
|
85
|
+
friendlyName: `Match ${matchId}`,
|
|
86
|
+
idleTimeoutMinutes: 15 // stops itself 15 minutes after the last player leaves
|
|
87
|
+
});
|
|
88
|
+
// "Pending" until the server is up: wait until the game says it is ready (up to 5 minutes by default).
|
|
89
|
+
const ready = await sv.sessions.waitUntilReady(session.id);
|
|
90
|
+
return { sessionId: ready.id, connection: ready.connection ?? null };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// When the match is over:
|
|
94
|
+
const { totalCost } = await sv.sessions.stop(sessionId); // credits billed for this session
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`waitUntilReady` polls the session with a growing interval (2 s, then up to 10 s) until it is Active and its game
|
|
98
|
+
says it is ready (`ready: true`; a game with no ready signal is returned once its `readyDeadlineAt` passes, with
|
|
99
|
+
`ready: false`; `{ waitForGameReady: false }` returns as soon as it is Active). It rejects with a `SessionWaitError`:
|
|
100
|
+
`session_ended` (with `sessionStatus` and `stopReason`, e.g. `GAME_CRASH`) or `wait_timeout` (`timeoutMs`, default
|
|
101
|
+
5 minutes), and honours `signal`.
|
|
102
|
+
|
|
103
|
+
Creating a session, stopping one and claiming a pool server are **never retried by the SDK** (a repeat could start or
|
|
104
|
+
claim a second server). After a network error, look for the session with `sv.sessions.list()` before trying again.
|
|
105
|
+
|
|
106
|
+
A claim's `409` claims nothing, and the API tells its kinds apart only by the message: `poolClaimConflict(err)`
|
|
107
|
+
answers `"no_warm_server"` ("No warm server available in this pool": start a session instead) or `"busy"` (the
|
|
108
|
+
messages ending in "— retry": another claim was running, or the idle server could not take the session; trying the
|
|
109
|
+
claim again shortly is safe), and null for any other error.
|
|
110
|
+
|
|
111
|
+
### Verify a player's token on your game server
|
|
112
|
+
|
|
113
|
+
The game client sends its player token when it connects; your server checks it **offline** against SplatterVault's
|
|
114
|
+
public keys (Ed25519; fetched once, then cached as long as the API's `Cache-Control` allows, and fetched again when a
|
|
115
|
+
token names a new key):
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { createPlayerTokenVerifier, PlayerTokenError } from "@splattervault/server";
|
|
119
|
+
|
|
120
|
+
const verifier = createPlayerTokenVerifier({ gameId: 42 }); // one for the life of the server
|
|
121
|
+
|
|
122
|
+
async function onConnect(token: string) {
|
|
123
|
+
try {
|
|
124
|
+
const claims = await verifier.verify(token);
|
|
125
|
+
return claims.sub; // the player's SplatterVault id
|
|
126
|
+
} catch (err) {
|
|
127
|
+
if (err instanceof PlayerTokenError) {
|
|
128
|
+
// token_expired: the client refreshes its token and connects again
|
|
129
|
+
// keys_unavailable: SplatterVault could not be reached to fetch the keys: try again shortly
|
|
130
|
+
// token_invalid: refuse (err.reason says which check failed, for your logs)
|
|
131
|
+
}
|
|
132
|
+
throw err;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
It checks what the API itself checks: the signature, `iss` = `splattervault`, `aud` = `sv-player:<your game id>`
|
|
138
|
+
(a token for another of your games is refused), `iat` and `exp` with 30 seconds of clock tolerance, no `nbf`, and the
|
|
139
|
+
shape of every claim. Verifying needs no API key (the keys are public), so it also works in a game server that holds
|
|
140
|
+
none. With a client at hand: `await sv.verifyPlayerToken(token, { gameId: 42 })`; or the one-off
|
|
141
|
+
`verifyPlayerToken(token, { gameId: 42 })`.
|
|
142
|
+
|
|
143
|
+
What offline verification cannot know:
|
|
144
|
+
|
|
145
|
+
- **Erased players and changed owners.** The API refuses a token whose player was erased since it was issued
|
|
146
|
+
(`player_deleted`), or whose game moved to another owner (`token_invalid`). Offline, such a token still verifies
|
|
147
|
+
until it expires (at most an hour). Where it matters, ask the API: `sv.store.getPlayer(claims.sub)` answers
|
|
148
|
+
`player_not_found` for an erased player.
|
|
149
|
+
- **New sign-in methods.** `claims.amr` holds one sign-in method; a method SplatterVault adds after this SDK version is
|
|
150
|
+
accepted too (the signature still proves SplatterVault issued the token), where the API's own list is closed.
|
|
151
|
+
|
|
152
|
+
The keys are cached as the answer's `Cache-Control` says, but at least 60 seconds and at most an hour; while
|
|
153
|
+
SplatterVault cannot be reached, the last keys keep working for `staleIfErrorSeconds` (default 300) after they
|
|
154
|
+
expired, and a failed fetch is not tried again for 10 seconds.
|
|
155
|
+
|
|
156
|
+
### Grant a store item
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const result = await sv.store.grant(
|
|
160
|
+
playerId, // a SplatterVault player id, or "steam:7656...", "studio:<your id>", ...
|
|
161
|
+
{ lines: [{ sku: "trophy_s3", quantity: 1 }, { currency: "GOLD", amount: 100 }], reason: "Season 3 reward" },
|
|
162
|
+
{ idempotencyKey: `season3:${playerId}` } // optional: see "Exactly once" below
|
|
163
|
+
);
|
|
164
|
+
console.log(result.replayed, result.balances);
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`consume`, `purchase` (with `expectedPrice`), `updateItem` and `reverse` work the same way.
|
|
168
|
+
|
|
169
|
+
**Exactly once.** Every store change carries an `Idempotency-Key`. By default the SDK makes one per call and sends
|
|
170
|
+
the same one, with the same body, on its own retries, so a lost answer never applies a change twice. To stay
|
|
171
|
+
exactly-once across your own retries and process restarts too, pass a key derived from your own record
|
|
172
|
+
(`reward:${matchId}:${playerId}`): the same key and request again answers the first result with `replayed: true`; the
|
|
173
|
+
same key with a different request is `409 idempotency_conflict`.
|
|
174
|
+
|
|
175
|
+
When a change fails with `err.outcomeUnknown` (no answer, or a 500/502/504, even after the SDK's own retries), it may
|
|
176
|
+
have been applied. Send it again **with the same key** (`{ idempotencyKey: err.idempotencyKey }`, the same body), at
|
|
177
|
+
once or from a "Retry" button: never call `grant` or `purchase` again without the key, which could apply it twice.
|
|
178
|
+
|
|
179
|
+
### Write player data
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
// Read, then change only what you read (ifVersion): a concurrent change makes it fail with version_conflict.
|
|
183
|
+
const { data } = await sv.playerData.get(42, playerId, { stores: ["readonly"], keys: ["settings"] });
|
|
184
|
+
const settings = data.readonly?.settings;
|
|
185
|
+
await sv.playerData.update(42, playerId, {
|
|
186
|
+
ops: [{ op: "set", store: "readonly", key: "settings", value: { music: false }, ifVersion: settings?.version ?? 0 }]
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// A counter: no read needed (never sent twice by the SDK; after an unknown outcome you cannot tell if it counted).
|
|
190
|
+
await sv.playerData.update(42, playerId, { ops: [{ op: "inc", store: "readonly", key: "xp", by: 50 }] });
|
|
191
|
+
|
|
192
|
+
// Your game's own data; players read "public" within 30 seconds.
|
|
193
|
+
await sv.playerData.updateGameData(42, { ops: [{ op: "set", store: "public", key: "motd", value: "Season 3 is live" }] });
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Stores: a player's `player` (the game client may write it), `readonly` (only your backend writes it) and `internal`
|
|
197
|
+
(players never see it); a game's `public` and `internal`. Writes are all or nothing. `stores` and `keys` may be left
|
|
198
|
+
out (everything) but not empty.
|
|
199
|
+
|
|
200
|
+
**When the answer is lost.** A write that got no answer, a timeout, a 500, 502 or 504 may or may not have been
|
|
201
|
+
applied: the error has `outcomeUnknown: true`, and the SDK does not send it again (even with `ifVersion`: the second
|
|
202
|
+
send could meet the first one's own new version). The same goes for a write the SDK did resend (only ever after a 408,
|
|
203
|
+
429 or 503, which prove nothing was applied) that then meets `version_conflict`: it is reported as code
|
|
204
|
+
`outcome_unknown`, never as a plain conflict. To recover, read the key again: if its version moved and the value is
|
|
205
|
+
the one you wrote, your write was applied. Never just apply your change again on top. A value that carries its own
|
|
206
|
+
mark makes this easy (see `recordWin` in [examples/rewards.ts](examples/rewards.ts), which keeps the ids of the
|
|
207
|
+
matches it counted).
|
|
208
|
+
|
|
209
|
+
### Sign players in from your backend
|
|
210
|
+
|
|
211
|
+
Use your own accounts and still give players SplatterVault tokens (store, player data):
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
const { token, expiresAt, player } = await sv.players.signIn({ gameId: 42, externalId: "user-981", displayName: "Nova" });
|
|
215
|
+
// Send token to the game client. The same externalId is always the same player (player.id).
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Errors
|
|
219
|
+
|
|
220
|
+
Every refusal is a `SplatterVaultError`:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import { SplatterVaultError } from "@splattervault/server";
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
await sv.store.purchase(playerId, { sku: "sword", currency: "GOLD", expectedPrice: 250 });
|
|
227
|
+
} catch (err) {
|
|
228
|
+
if (err instanceof SplatterVaultError) {
|
|
229
|
+
switch (err.code) {
|
|
230
|
+
case "insufficient_funds": /* tell the player */ break;
|
|
231
|
+
case "price_changed": /* show the new price */ break;
|
|
232
|
+
default: throw err;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
| Field | What it is |
|
|
239
|
+
|---|---|
|
|
240
|
+
| `code` | The API's stable `error` code (`insufficient_funds`, `version_conflict`, `rate_limited`, `player_not_found`…). **Key your handling on it.** The set is open: handle an unknown code by `status`. Null for the session and billing routes' refusals, which have no code (see `errorName`). SDK codes: `network_error`, `timeout`, `aborted` (status 0); `invalid_response`, `redirect_not_followed`, `outcome_unknown` (with the answer's status). |
|
|
241
|
+
| `status` | The HTTP status; 0 when no answer arrived. |
|
|
242
|
+
| `message` | `"<code> (HTTP <status>): <the API's sentence>"`: for logs, not for parsing. |
|
|
243
|
+
| `details` | More about some refusals, e.g. `version_conflict`: `[{ store, key, version }]`; `limit_exceeded`: `{ limit, max }`; `banned`: `{ type, scopes }`. |
|
|
244
|
+
| `retryAfter` | The answer's `Retry-After`, in seconds, or null. |
|
|
245
|
+
| `requestId` | The answer's `x-request-id`: quote it when you contact support. |
|
|
246
|
+
| `errorName`, `errors` | The session and billing routes' `{ name, errors }` (e.g. `BAD_REQUEST`). |
|
|
247
|
+
| `outcomeUnknown` | True when a write may or may not have been applied (no answer, 500/502/504, an abort mid-send, a resent `ifVersion` write that met a conflict). Always false for reads. |
|
|
248
|
+
| `idempotencyKey` | The `Idempotency-Key` a store change was sent with (yours or the SDK's): send the change again with it to settle an unknown outcome. |
|
|
249
|
+
| `operationId`, `method`, `path`, `attempts`, `body` | What failed, and how many times it was sent. |
|
|
250
|
+
|
|
251
|
+
`err.is("rate_limited")`, `err.isTransient` (408, 429, 500, 502, 503, 504 or no answer) and `err.isNetworkError` help too. Each
|
|
252
|
+
operation's codes are listed in the [Studio API reference](https://splattervault.com/docs/studio).
|
|
253
|
+
|
|
254
|
+
Rate limits: the studio routes (player sign-in, player data, the store) answer `429 rate_limited` with `Retry-After`
|
|
255
|
+
when a key or a player sends too much. The game-server session and billing routes set no rate limit of their own:
|
|
256
|
+
they never answer 429 (their transient failures are 500, 502, 503, 504 or no answer).
|
|
257
|
+
|
|
258
|
+
## Retries, timeouts and cancellation
|
|
259
|
+
|
|
260
|
+
The SDK sends a request again by itself only when that is **safe**, and only after a transient failure: no answer
|
|
261
|
+
(network error or timeout), or HTTP 408, 429, 500, 502, 503 or 504. Never after another 4xx or a redirect.
|
|
262
|
+
|
|
263
|
+
| Retried after any transient failure | Retried only after 408, 429, 503 | Not retried (a repeat could act twice) |
|
|
264
|
+
|---|---|---|
|
|
265
|
+
| Every read (GET) | Player-data writes whose every op has `ifVersion` (see "When the answer is lost") | Creating, stopping, renaming, rescheduling or cancelling a session |
|
|
266
|
+
| Store changes (same `Idempotency-Key` and body each time) | | Claiming a pool server |
|
|
267
|
+
| Lookups (`playerData.resolve`, `playerData.getMany`) and `playerData.clear` | | Player-data writes without `ifVersion` (e.g. `inc`) |
|
|
268
|
+
| Imports (the same rows again change nothing) | | Studio sign-in, erasing a player, the Meta purchase check |
|
|
269
|
+
|
|
270
|
+
A resent store change that meets `409 idempotency_conflict` can only be meeting its own first send still in progress
|
|
271
|
+
(same key, same body), so it is retried too.
|
|
272
|
+
|
|
273
|
+
- Up to `maxRetries` retries (default 2, at most 20), with exponential backoff and jitter (0.5 s, 1 s, … up to 8 s).
|
|
274
|
+
- A `Retry-After` is always honoured, never shortened. One longer than `retry.maxRetryAfterMs` (default 10 s) is not
|
|
275
|
+
waited out: the error is thrown with `retryAfter` set, for you to schedule.
|
|
276
|
+
- `timeoutMs` (default 30 s, 1 ms to 2147483647 ms) bounds each attempt, answer included. Creating or claiming servers
|
|
277
|
+
gets at least 60 s, imports at least 120 s.
|
|
278
|
+
- Numeric options are checked when you set them: NaN, Infinity or out-of-range values throw a `RangeError`.
|
|
279
|
+
- Every method takes options last: `{ signal, timeoutMs, maxRetries, headers }` (and `idempotencyKey` for store
|
|
280
|
+
changes). An aborted `signal` ends the call at once, also during a wait, with code `aborted`.
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
const sv = new SplatterVault({ maxRetries: 3, timeoutMs: 10_000, retry: { maxRetryAfterMs: 30_000 } });
|
|
284
|
+
await sv.billing.getOrgCredits({}, { signal: AbortSignal.timeout(5000) });
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
## Pages
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
// A player's store history, newest first, 50 a page.
|
|
291
|
+
for await (const page of sv.store.historyPages(playerId)) {
|
|
292
|
+
for (const txn of page.txns) console.log(txn.kind, txn.createdAt);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Erased players, for deleting what YOUR database keeps about them. Save `next` after each page; poll every few minutes.
|
|
296
|
+
for await (const page of sv.playerData.erasedPlayerPages(savedCursor ? { cursor: savedCursor } : { since: "2026-11-01T00:00:00Z" })) {
|
|
297
|
+
await deleteFromMyDatabase(page.players.map((p) => p.id));
|
|
298
|
+
savedCursor = page.next;
|
|
299
|
+
}
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
## On a SplatterVault game server
|
|
303
|
+
|
|
304
|
+
A game process that SplatterVault starts gets a few session variables (never the server's own credentials):
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
import { readSessionEnvironment } from "@splattervault/server";
|
|
308
|
+
|
|
309
|
+
const env = readSessionEnvironment(); // reads process.env
|
|
310
|
+
// { onSplatterVault, sessionId, code, gameType, mode, serverName, friendlyName, buildChannel, slavePort }
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
On a server of its own (a session you created), `sessionId` is the session's id. On a **pool** server `sessionId` is
|
|
314
|
+
null (the claim does not set it: use the `sessionId` that `serverPools.claim()` answered) and only `code` is the
|
|
315
|
+
claiming match's; `mode`, `serverName` and `friendlyName` are from when the pool server booted.
|
|
316
|
+
|
|
317
|
+
## API
|
|
318
|
+
|
|
319
|
+
| Namespace | Methods |
|
|
320
|
+
|---|---|
|
|
321
|
+
| `sv.sessions` | `create`, `list`, `get`, `waitUntilReady`, `listMine`, `stop`, `rename`, `reschedule`, `cancelSchedule` |
|
|
322
|
+
| `sv.sessions.subscription` | `create`, `list`, `stop`, `rename`, `reschedule`, `cancelSchedule` (subscription-billed) |
|
|
323
|
+
| `sv.serverPools` | `claim` |
|
|
324
|
+
| `sv.games` | `getConfigurableArgs` |
|
|
325
|
+
| `sv.billing` | `getCredits`, `getCreditStats`, `getOrgCredits`, `getOrgSubscriptions`, `getOrgCreditsById`, `getOrgSubscriptionById`, `getSubscriptions`, `getUsage` |
|
|
326
|
+
| `sv.players` | `signIn`, `import`, `erase` |
|
|
327
|
+
| `sv.playerData` | `resolve`, `get`, `update`, `clear`, `getMany`, `writeMany`, `getGameData`, `updateGameData`, `import`, `listErasedPlayers`, `erasedPlayerPages` |
|
|
328
|
+
| `sv.store` | `getCatalog`, `getPlayer`, `getHistory`, `historyPages`, `grant`, `consume`, `purchase`, `updateItem`, `reverse`, `syncMetaPurchases`, `importCatalog`, `importHoldings` |
|
|
329
|
+
| `sv` | `verifyPlayerToken` |
|
|
330
|
+
| functions | `verifyPlayerToken`, `createPlayerTokenVerifier`, `readSessionEnvironment`, `newIdempotencyKey`, `poolClaimConflict` |
|
|
331
|
+
|
|
332
|
+
Each method's documentation names its API operation (`@see POST /store/studio/players/{player}/grants`). Request and
|
|
333
|
+
answer types (`ServerSession`, `StoreTxnResult`, `DataOp`, …) are exported, generated from the API's OpenAPI
|
|
334
|
+
description; `Schemas`, `components`, `operations` and `paths` hold all of them.
|
|
335
|
+
|
|
336
|
+
Options of `new SplatterVault(options)`:
|
|
337
|
+
|
|
338
|
+
| Option | Default | |
|
|
339
|
+
|---|---|---|
|
|
340
|
+
| `apiKey` | `process.env.SV_API_KEY` | Your organization API key. |
|
|
341
|
+
| `baseUrl` | `https://splattervault.com/rest` | https only; http for localhost / 127.0.0.1 / [::1]. |
|
|
342
|
+
| `fetch` | `globalThis.fetch` | Any `fetch`-compatible function (proxies, tests). |
|
|
343
|
+
| `maxRetries` | `2` | Retries after the first attempt (safe calls only). |
|
|
344
|
+
| `timeoutMs` | `30000` | Per attempt. |
|
|
345
|
+
| `retry` | `{ baseDelayMs: 500, maxDelayMs: 8000, maxRetryAfterMs: 10000 }` | |
|
|
346
|
+
| `userAgent` | | Prefixed to the SDK's User-Agent. |
|
|
347
|
+
| `dangerouslyAllowBrowser` | `false` | See "Your API key stays on your servers". |
|
|
348
|
+
| `dangerouslyAllowInsecureHttp` | `false` | Allows a plain-http `baseUrl` on another host (the key travels unencrypted). |
|
|
349
|
+
|
|
350
|
+
### Testing your code
|
|
351
|
+
|
|
352
|
+
Pass a `fetch` to answer requests yourself, and a `baseUrl` to point the SDK at a local server:
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
const sv = new SplatterVault({
|
|
356
|
+
apiKey: "sv_org_test",
|
|
357
|
+
fetch: async (url, init) => new Response(JSON.stringify({ balance: 100 }), { status: 200 })
|
|
358
|
+
});
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
## Developing this SDK
|
|
362
|
+
|
|
363
|
+
```sh
|
|
364
|
+
npm install
|
|
365
|
+
npm run generate # src/generated/studio-api.ts from openapi/studio-api.json (or: npm run generate -- <file or URL>)
|
|
366
|
+
npm run check # typecheck, lint, tests, build, then the packed package from ESM and CJS
|
|
367
|
+
npm run docs # API documentation (HTML) into docs/
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
Integration tests run against the local API mock in [`tools/sdk-mock`](tools/sdk-mock/README.md) (Node 18+, no
|
|
371
|
+
dependencies, fake test credentials; it never calls SplatterVault) when `SV_MOCK_URL` is set:
|
|
372
|
+
|
|
373
|
+
```sh
|
|
374
|
+
node tools/sdk-mock/server.mjs --port 8787 & # or, in its own terminal: npm run mock
|
|
375
|
+
SV_MOCK_URL=http://127.0.0.1:8787/rest npm test # every test, including the integration suite
|
|
376
|
+
npm run mock:selftest # the mock's own check against openapi/studio-api.json
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
## License
|
|
380
|
+
|
|
381
|
+
[MIT](LICENSE)
|