@ksaa-nlp/gamehub-sdk 3.8.0 → 4.0.0
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/README.md +130 -16
- package/SPEC.md +191 -70
- package/dist/gamehub-sdk.js +384 -90
- package/dist/gamehub-sdk.js.map +3 -3
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +118 -24
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/init.d.ts.map +1 -1
- package/dist/src/init.js +12 -5
- package/dist/src/init.js.map +1 -1
- package/dist/src/main.d.ts +3 -3
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +1 -0
- package/dist/src/main.js.map +1 -1
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +307 -71
- package/dist/src/session.js.map +1 -1
- package/dist/src/state.d.ts +14 -2
- package/dist/src/state.d.ts.map +1 -1
- package/dist/src/state.js +3 -0
- package/dist/src/state.js.map +1 -1
- package/dist/src/transport.d.ts +5 -0
- package/dist/src/transport.d.ts.map +1 -1
- package/dist/src/transport.js +29 -1
- package/dist/src/transport.js.map +1 -1
- package/dist/types/api.d.ts +11 -3
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/bootstrap.d.ts +9 -0
- package/dist/types/bootstrap.d.ts.map +1 -1
- package/dist/types/session.d.ts +35 -6
- package/dist/types/session.d.ts.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
# GameHub SDK
|
|
2
2
|
|
|
3
|
-
The client library GameHub-hosted games use to talk to the platform: auth, sessions, score submission, questions, league matches, and the bootstrap pipeline that hands games
|
|
3
|
+
The client library GameHub-hosted games use to talk to the platform: auth, sessions, score submission, questions, the words bank, league matches, and the bootstrap pipeline that hands games their multiplayer seat reservation.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Works in two host environments out of the box:
|
|
6
|
+
|
|
7
|
+
- **iframe** — the classic embedding; the SDK talks to its parent window over `postMessage`.
|
|
8
|
+
- **native WebView** — e.g. a Flutter app; the SDK talks to an injected `window.GameHubNativeHost` bridge.
|
|
9
|
+
|
|
10
|
+
It also runs **standalone** (served from the GameHub origin or in the dev harness). Detection is automatic — your game code is identical across all three. See [Host transports](#host-transports).
|
|
11
|
+
|
|
12
|
+
Transport-agnostic for realtime — no `@colyseus/sdk` dependency. Games that need multiplayer open their own socket.
|
|
6
13
|
|
|
7
14
|
For exhaustive contract details see [SPEC.md](./SPEC.md). The README below is a hands-on tour.
|
|
8
15
|
|
|
@@ -31,7 +38,8 @@ console.log('User auth:', sdk.isAuthenticated());
|
|
|
31
38
|
|
|
32
39
|
// ... run the game ...
|
|
33
40
|
|
|
34
|
-
await sdk.submitScore(1234, { level: 3,
|
|
41
|
+
const result = await sdk.submitScore(1234, { level: 3, attempts: 4 });
|
|
42
|
+
if (!result.success) console.warn(result.code, result.error);
|
|
35
43
|
sdk.notifyComplete({ score: 1234 });
|
|
36
44
|
```
|
|
37
45
|
|
|
@@ -47,11 +55,25 @@ const sdk = createSdk();
|
|
|
47
55
|
sdk.isInitialized(); // false — bootstrap hasn't arrived yet
|
|
48
56
|
await sdk.ready(); // does the postMessage handshake with the host
|
|
49
57
|
sdk.isInitialized(); // true
|
|
50
|
-
sdk.hasActiveSession(); // true
|
|
58
|
+
sdk.hasActiveSession(); // true while the current playthrough is open/retriable
|
|
51
59
|
```
|
|
52
60
|
|
|
53
61
|
`ready()` is idempotent; you can call it from multiple places without worrying about races.
|
|
54
62
|
|
|
63
|
+
## Host transports
|
|
64
|
+
|
|
65
|
+
The SDK auto-detects how to reach its host. You never choose the transport — the same game code runs everywhere.
|
|
66
|
+
|
|
67
|
+
| Transport | When | Wire |
|
|
68
|
+
| ------------- | ------------------------------------------------------------ | ----------------------------------------------- |
|
|
69
|
+
| `postmessage` | Game runs in an `<iframe>` (`window.parent !== window`) | `window.postMessage` to the parent |
|
|
70
|
+
| `native` | Game is the top document in a native WebView (Flutter, etc.) | injected `window.GameHubNativeHost` bridge |
|
|
71
|
+
| none | Standalone — dev harness or served from the GameHub origin | direct `fetch`; host round-trips resolve `null` |
|
|
72
|
+
|
|
73
|
+
The native bridge wins over the iframe check, so a WebView host always takes precedence. The native app must inject `window.GameHubNativeHost` **before** the SDK script loads. See [SPEC.md §6.7](./SPEC.md#67-native-bridge-transport) for the bridge contract a native host must implement.
|
|
74
|
+
|
|
75
|
+
**Host-proxied HTTP.** When embedded (iframe or native), the SDK does **not** issue cross-origin requests to the GameHub backend itself — it asks the host to proxy them. The host (same-origin with the backend, and holder of the bearer token) makes the real call and returns the result. This sidesteps CORS and keeps the auth token out of the game entirely. It's transparent: `submitScore`, `getQuestions`, etc. behave identically; only the wire underneath differs. Standalone, the SDK calls the backend directly. See [SPEC.md §6.6](./SPEC.md#66-host-proxied-api-transport).
|
|
76
|
+
|
|
55
77
|
## Bootstrap snapshot
|
|
56
78
|
|
|
57
79
|
`getBootstrap()` returns everything the host told us about this game launch:
|
|
@@ -64,12 +86,14 @@ bs.authToken; // Bearer token; null for guests
|
|
|
64
86
|
bs.leagueId; // string | null — set inside a league context
|
|
65
87
|
bs.gameId; // string | null — set inside a league context
|
|
66
88
|
bs.matchId; // string | null — set inside a league match
|
|
89
|
+
bs.sessionMode; // 'authenticated' | 'embed-guest' | 'league-guest' | null
|
|
67
90
|
bs.mode; // 'two_players_online' | 'two_players_local' | …
|
|
68
91
|
bs.playerName; // free-form display name
|
|
69
92
|
bs.playerCount; // free-form, e.g. '4'
|
|
70
93
|
bs.teamOneName; // free-form
|
|
71
94
|
bs.teamTwoName; // free-form
|
|
72
|
-
bs.
|
|
95
|
+
bs.profileId; // string | null — game profile chosen in the pre-start picker
|
|
96
|
+
bs.multiplayer; // reservation + wsEndpoint, with optional roomCode/role/connectionScope
|
|
73
97
|
bs.isBootstrapped; // true after the host has replied at least once
|
|
74
98
|
```
|
|
75
99
|
|
|
@@ -77,23 +101,44 @@ All fields default to `null`. Don't assume `gameSlug` exists before `ready()` re
|
|
|
77
101
|
|
|
78
102
|
## Submitting scores
|
|
79
103
|
|
|
80
|
-
### Standalone (single-player)
|
|
104
|
+
### Standalone or public embed (single-player)
|
|
81
105
|
|
|
82
106
|
```ts
|
|
83
107
|
const result = await sdk.submitScore(score, {
|
|
84
108
|
level: 3,
|
|
85
|
-
|
|
109
|
+
attempts: 4,
|
|
86
110
|
custom: { combo: 7 },
|
|
87
111
|
});
|
|
88
112
|
|
|
89
113
|
if (result.success) {
|
|
90
|
-
console.log('accepted:', result.
|
|
114
|
+
console.log('accepted:', result.sessionId, 'timeTaken:', result.timeTaken);
|
|
115
|
+
} else if (result.terminal) {
|
|
116
|
+
console.error('playthrough rejected:', result.code, result.error);
|
|
117
|
+
} else if (result.status === 'retriable' || result.retriable) {
|
|
118
|
+
// Retry the same score and metadata. The SDK retains the original token and
|
|
119
|
+
// exact request body until the server returns a terminal result.
|
|
120
|
+
await sdk.submitScore(score, {
|
|
121
|
+
level: 3,
|
|
122
|
+
attempts: 4,
|
|
123
|
+
custom: { combo: 7 },
|
|
124
|
+
});
|
|
91
125
|
} else {
|
|
92
|
-
console.error(result.error);
|
|
126
|
+
console.error(result.code, result.error);
|
|
93
127
|
}
|
|
94
128
|
```
|
|
95
129
|
|
|
96
|
-
`submitScore` opens a session automatically on first call.
|
|
130
|
+
`submitScore` opens a session automatically on first call. An accepted or terminally rejected result closes that playthrough immediately; the next `startSession()` or `submitScore()` creates a fresh session, so a game can run multiple rounds without reloading. Rate limits, live processing, server failures, timeouts, and other unknown outcomes keep the current session and first request body available for an explicit same-payload retry. Concurrent identical submissions share one host request, while a different concurrent payload resolves locally with `CONCURRENT_SUBMISSION_CONFLICT`.
|
|
131
|
+
|
|
132
|
+
Every public score method resolves one of four discriminated outcomes and never throws:
|
|
133
|
+
|
|
134
|
+
- `{ success: true, status: 'accepted', terminal: true, ... }`
|
|
135
|
+
- `{ success: false, status: 'rejected', terminal: true, ... }`
|
|
136
|
+
- `{ success: false, status: 'retriable', terminal: false, ... }`
|
|
137
|
+
- `{ success: false, status: 'failed', terminal: false, retriable, ... }`
|
|
138
|
+
|
|
139
|
+
In a public GameHub embed, the trusted host supplies either `sessionMode: 'embed-guest'` or `sessionMode: 'authenticated'` and transparently exchanges the same `/sessions/start` and `/sessions/submit` SDK calls for the correct host-owned flow. Games never create guest IDs or receive login codes, user JWTs, or opaque embed credentials. Outside a trusted embed mode, an unauthenticated standalone game with no league-match context resolves a failed result — it never throws.
|
|
140
|
+
|
|
141
|
+
Embed guest results are administrative play records. Authenticated embed results are normal account-attributed scores and enter the standard leaderboards.
|
|
97
142
|
|
|
98
143
|
### League match (one-score scoring)
|
|
99
144
|
|
|
@@ -141,6 +186,33 @@ questions.forEach((q) => {
|
|
|
141
186
|
|
|
142
187
|
`limit` is clamped to 100. Any failure (bad inputs, network error, malformed response) resolves to `[]` — there's no `error` field to check.
|
|
143
188
|
|
|
189
|
+
Pass `profileId` to draw from a specific game **profile**. When omitted, the SDK uses the bootstrap-supplied `profileId` (set by the player's pre-start picker), and otherwise falls back to the game's default profile:
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
const questions = await sdk.getQuestions({ profileId: 'beginner-pack' });
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Words (Words Bank)
|
|
196
|
+
|
|
197
|
+
For vocabulary games, `getWords` mirrors `getQuestions` but returns full nested `Word` entries (lemma, senses, word forms, relations):
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
const words = await sdk.getWords({
|
|
201
|
+
difficulty: 'medium',
|
|
202
|
+
tags: ['animals', 'nature'],
|
|
203
|
+
limit: 20,
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
words.forEach((w) => {
|
|
207
|
+
console.log(w.lemma, '→', w.senses?.[0]?.definition);
|
|
208
|
+
});
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
- `tags` (a `string[]`) is ANDed on top of the profile selection.
|
|
212
|
+
- `profileId` selects a game profile (the same profile carries both questions and words); falls back to the bootstrap `profileId`, then the default profile.
|
|
213
|
+
- `limit` is clamped to **50** (lower than questions' 100 because a full `Word` is heavier) and defaults to 50.
|
|
214
|
+
- Like `getQuestions`, any failure resolves to `[]`.
|
|
215
|
+
|
|
144
216
|
## Host signalling
|
|
145
217
|
|
|
146
218
|
Tell the host page things:
|
|
@@ -157,9 +229,15 @@ sdk.reportQuestion({ questionId: q.id, prompt: q.prompt });
|
|
|
157
229
|
sdk.reportQuestion({
|
|
158
230
|
questions: quiz.map((q) => ({ questionId: q.id, prompt: q.prompt })),
|
|
159
231
|
});
|
|
232
|
+
|
|
233
|
+
// Words Bank: report a word — same single/dropdown semantics, relabeled to lemma
|
|
234
|
+
sdk.reportWord({ wordId: w.id, lemma: w.lemma });
|
|
235
|
+
sdk.reportWord({
|
|
236
|
+
words: bank.map((w) => ({ wordId: w.id, lemma: w.lemma })),
|
|
237
|
+
});
|
|
160
238
|
```
|
|
161
239
|
|
|
162
|
-
All of these are fire-and-forget — they just
|
|
240
|
+
All of these are fire-and-forget — they just signal the host (over whichever transport is active). `reportQuestion` / `reportWord` ask the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it). Pass `questions` / `words` instead of a single id to have the host render a dropdown so the player chooses which item to report.
|
|
163
241
|
|
|
164
242
|
## Pause/resume from the host
|
|
165
243
|
|
|
@@ -174,7 +252,7 @@ Both are optional. The SDK doesn't pause anything itself; it just delivers the s
|
|
|
174
252
|
|
|
175
253
|
## Multiplayer
|
|
176
254
|
|
|
177
|
-
The SDK does not open a WebSocket. The host has already created a Colyseus room before the
|
|
255
|
+
The SDK does not open a WebSocket. The host has already created a Colyseus room before the game boots and passes a **seat reservation** in the bootstrap. Consume it yourself:
|
|
178
256
|
|
|
179
257
|
```ts
|
|
180
258
|
import { Client } from '@colyseus/sdk';
|
|
@@ -188,7 +266,9 @@ if (!multiplayer) {
|
|
|
188
266
|
}
|
|
189
267
|
|
|
190
268
|
const client = new Client(multiplayer.wsEndpoint);
|
|
191
|
-
const room = await client.
|
|
269
|
+
const room = await client.consumeSeatReservation<UgcState>(
|
|
270
|
+
multiplayer.reservation
|
|
271
|
+
);
|
|
192
272
|
|
|
193
273
|
const serverNow = attachServerClock(room);
|
|
194
274
|
|
|
@@ -197,7 +277,15 @@ room.onMessage('fx:answer', (msg) => playSound(msg));
|
|
|
197
277
|
room.send('answer:submit', { answer: 'B' });
|
|
198
278
|
```
|
|
199
279
|
|
|
200
|
-
|
|
280
|
+
`multiplayer.reservation` is a Colyseus `SeatReservation` (the `{ room, sessionId }` envelope) — feed it straight to `consumeSeatReservation`, which performs the clean first join. No reconnection-token handoff crosses the host→game boundary; after joining, the server mints `room.reconnectionToken` for the game to keep if it wants to reconnect later.
|
|
281
|
+
|
|
282
|
+
External embeds also provide `roomCode`, `role`, and `connectionScope` when
|
|
283
|
+
available. If the game persists its server-issued reconnection token, include
|
|
284
|
+
`connectionScope` in that storage key so two publisher tabs cannot reuse each
|
|
285
|
+
other's reconnect state. These fields are opaque launch context; the SDK never
|
|
286
|
+
opens a socket or writes reconnection data.
|
|
287
|
+
|
|
288
|
+
The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.colyseus.io/client/room/> for its full API. Install `@colyseus/sdk`, `@colyseus/schema`, and `@ksaa-nlp/colyseus-schemas` in your game; the SDK doesn't pull them in. This works the same inside a native WebView host — the game opens its own socket from inside the WebView; the SDK never proxies realtime traffic over the native bridge.
|
|
201
289
|
|
|
202
290
|
## API summary
|
|
203
291
|
|
|
@@ -205,7 +293,7 @@ The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.coly
|
|
|
205
293
|
const sdk = createSdk();
|
|
206
294
|
|
|
207
295
|
// Lifecycle
|
|
208
|
-
sdk.version; // '
|
|
296
|
+
sdk.version; // '4.0.0'
|
|
209
297
|
sdk.ready(); // Promise<boolean>
|
|
210
298
|
sdk.isInitialized(); // boolean
|
|
211
299
|
sdk.isAuthenticated(); // boolean
|
|
@@ -221,13 +309,17 @@ sdk.submitMatchResult({ winnerId, scores }); // Promise<SubmitScoreResult>
|
|
|
221
309
|
sdk.getMatchContext(); // Promise<MatchContext | null>
|
|
222
310
|
|
|
223
311
|
// Questions
|
|
224
|
-
sdk.getQuestions({ difficulty, category, limit }); // Promise<Question[]>
|
|
312
|
+
sdk.getQuestions({ difficulty, category, limit, profileId }); // Promise<Question[]>
|
|
313
|
+
|
|
314
|
+
// Words (Words Bank)
|
|
315
|
+
sdk.getWords({ difficulty, category, tags, limit, profileId }); // Promise<Word[]>
|
|
225
316
|
|
|
226
317
|
// Host signalling
|
|
227
318
|
sdk.notifyComplete(data?); // void
|
|
228
319
|
sdk.requestClose(); // void
|
|
229
320
|
sdk.logEvent(name, data?); // void
|
|
230
321
|
sdk.reportQuestion({ questionId?, prompt?, message?, questions? }); // void
|
|
322
|
+
sdk.reportWord({ wordId?, lemma?, message?, words? }); // void
|
|
231
323
|
|
|
232
324
|
// Context
|
|
233
325
|
sdk.getGameSlug(); // string | null
|
|
@@ -249,7 +341,10 @@ import type {
|
|
|
249
341
|
SubmitScoreResult,
|
|
250
342
|
StartSessionResult,
|
|
251
343
|
Question,
|
|
344
|
+
QuestionDifficulty,
|
|
252
345
|
QuestionOptions,
|
|
346
|
+
ReportQuestionData,
|
|
347
|
+
ReportableQuestion,
|
|
253
348
|
GameCompleteData,
|
|
254
349
|
EventData,
|
|
255
350
|
MatchContext,
|
|
@@ -258,9 +353,28 @@ import type {
|
|
|
258
353
|
MatchResultPayload,
|
|
259
354
|
ApiResponse,
|
|
260
355
|
ApiRequestOptions,
|
|
356
|
+
// Words Bank
|
|
357
|
+
Word,
|
|
358
|
+
WordDifficulty,
|
|
359
|
+
WordOptions,
|
|
360
|
+
ReportWordData,
|
|
361
|
+
ReportableWord,
|
|
362
|
+
WordSense,
|
|
363
|
+
WordForm,
|
|
261
364
|
} from '@ksaa-nlp/gamehub-sdk';
|
|
262
365
|
```
|
|
263
366
|
|
|
367
|
+
The full nested `Word` shape and its sub-interfaces (`WordSense`, `WordForm`, `Lookup`, `Synset`, `DynamicProperty`, …) are all re-exported from the package root — see [`types/word.ts`](./types/word.ts).
|
|
368
|
+
|
|
369
|
+
## Authoring server bundles (UGC)
|
|
370
|
+
|
|
371
|
+
For games with authoritative server logic running in the Colyseus UGC sandbox, the SDK ships two extra subpaths, separate from the browser runtime:
|
|
372
|
+
|
|
373
|
+
- `@ksaa-nlp/gamehub-sdk/server` — **types only** (`GuestModule`, `Ctx`, `PeerInfo`, …) for writing the guest module.
|
|
374
|
+
- `@ksaa-nlp/gamehub-sdk/server/dev` — `runLocal(guest, opts)`, a pure-Node harness to unit-test a guest bundle against a simulated room without `isolated-vm`.
|
|
375
|
+
|
|
376
|
+
See [SPEC.md §21bis](./SPEC.md#21bis-ugc-server-bundle-subpath) for the full contract.
|
|
377
|
+
|
|
264
378
|
## Specification
|
|
265
379
|
|
|
266
380
|
[SPEC.md](./SPEC.md) is the authoritative contract — postMessage taxonomy, state model, REST endpoints, error semantics, boundary rules, versioning policy. Read that before changing SDK internals or adding a new feature area.
|