@ksaa-nlp/gamehub-sdk 3.11.0 → 4.2.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.
Files changed (41) hide show
  1. package/README.md +69 -8
  2. package/SPEC.md +183 -35
  3. package/dist/gamehub-sdk.js +490 -77
  4. package/dist/gamehub-sdk.js.map +4 -4
  5. package/dist/src/bridge.d.ts.map +1 -1
  6. package/dist/src/bridge.js +124 -16
  7. package/dist/src/bridge.js.map +1 -1
  8. package/dist/src/constants.d.ts +1 -1
  9. package/dist/src/constants.d.ts.map +1 -1
  10. package/dist/src/constants.js +1 -1
  11. package/dist/src/constants.js.map +1 -1
  12. package/dist/src/init.js +3 -3
  13. package/dist/src/init.js.map +1 -1
  14. package/dist/src/main.d.ts +15 -9
  15. package/dist/src/main.d.ts.map +1 -1
  16. package/dist/src/main.js +12 -1
  17. package/dist/src/main.js.map +1 -1
  18. package/dist/src/multiplayer.d.ts +4 -0
  19. package/dist/src/multiplayer.d.ts.map +1 -0
  20. package/dist/src/multiplayer.js +91 -0
  21. package/dist/src/multiplayer.js.map +1 -0
  22. package/dist/src/server-entry.d.ts +15 -5
  23. package/dist/src/server-entry.d.ts.map +1 -1
  24. package/dist/src/session.d.ts.map +1 -1
  25. package/dist/src/session.js +301 -68
  26. package/dist/src/session.js.map +1 -1
  27. package/dist/src/settings.d.ts +7 -0
  28. package/dist/src/settings.d.ts.map +1 -0
  29. package/dist/src/settings.js +49 -0
  30. package/dist/src/settings.js.map +1 -0
  31. package/dist/src/state.d.ts +17 -2
  32. package/dist/src/state.d.ts.map +1 -1
  33. package/dist/src/state.js +6 -0
  34. package/dist/src/state.js.map +1 -1
  35. package/dist/types/api.d.ts +11 -3
  36. package/dist/types/api.d.ts.map +1 -1
  37. package/dist/types/bootstrap.d.ts +39 -0
  38. package/dist/types/bootstrap.d.ts.map +1 -1
  39. package/dist/types/session.d.ts +35 -6
  40. package/dist/types/session.d.ts.map +1 -1
  41. package/package.json +1 -1
package/README.md CHANGED
@@ -38,7 +38,8 @@ console.log('User auth:', sdk.isAuthenticated());
38
38
 
39
39
  // ... run the game ...
40
40
 
41
- await sdk.submitScore(1234, { level: 3, duration: 42 });
41
+ const result = await sdk.submitScore(1234, { level: 3, attempts: 4 });
42
+ if (!result.success) console.warn(result.code, result.error);
42
43
  sdk.notifyComplete({ score: 1234 });
43
44
  ```
44
45
 
@@ -54,7 +55,7 @@ const sdk = createSdk();
54
55
  sdk.isInitialized(); // false — bootstrap hasn't arrived yet
55
56
  await sdk.ready(); // does the postMessage handshake with the host
56
57
  sdk.isInitialized(); // true
57
- sdk.hasActiveSession(); // true if auth or league-match context is present
58
+ sdk.hasActiveSession(); // true while the current playthrough is open/retriable
58
59
  ```
59
60
 
60
61
  `ready()` is idempotent; you can call it from multiple places without worrying about races.
@@ -105,18 +106,37 @@ All fields default to `null`. Don't assume `gameSlug` exists before `ready()` re
105
106
  ```ts
106
107
  const result = await sdk.submitScore(score, {
107
108
  level: 3,
108
- duration: 42,
109
+ attempts: 4,
109
110
  custom: { combo: 7 },
110
111
  });
111
112
 
112
113
  if (result.success) {
113
- console.log('accepted:', result.accepted, 'timeTaken:', result.timeTaken);
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
+ });
114
125
  } else {
115
- console.error(result.error);
126
+ console.error(result.code, result.error);
116
127
  }
117
128
  ```
118
129
 
119
- `submitScore` opens a session automatically on first call. 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 returns `{ success: false, error: '...' }` — it never throws.
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.
120
140
 
121
141
  Embed guest results are administrative play records. Authenticated embed results are normal account-attributed scores and enter the standard leaderboards.
122
142
 
@@ -217,7 +237,7 @@ sdk.reportWord({
217
237
  });
218
238
  ```
219
239
 
220
- 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.
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 for logged-in users and submits it; guests see a login prompt). Pass `questions` / `words` instead of a single id to have the host render a dropdown so the player chooses which item to report.
221
241
 
222
242
  ## Pause/resume from the host
223
243
 
@@ -273,7 +293,7 @@ The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.coly
273
293
  const sdk = createSdk();
274
294
 
275
295
  // Lifecycle
276
- sdk.version; // '3.8.0'
296
+ sdk.version; // '4.0.0'
277
297
  sdk.ready(); // Promise<boolean>
278
298
  sdk.isInitialized(); // boolean
279
299
  sdk.isAuthenticated(); // boolean
@@ -362,3 +382,44 @@ See [SPEC.md §21bis](./SPEC.md#21bis-ugc-server-bundle-subpath) for the full co
362
382
  ## License
363
383
 
364
384
  ISC.
385
+
386
+ ## Account-wide game settings
387
+
388
+ Music is **off by default**, including guests and older hosts. GameHub delivers
389
+ saved account preferences in bootstrap and pushes updates in the current host.
390
+ The SDK provides settings; your game implements the audio behavior.
391
+
392
+ ```ts
393
+ await sdk.ready();
394
+ const initialSettings = sdk.getSettings(); // { musicEnabled: false } by default
395
+ const unsubscribe = sdk.onSettingsChange(({ musicEnabled }) => {
396
+ // Apply to current AND future background music; keep your local mute too.
397
+ audio.setMusicAllowed(musicEnabled);
398
+ });
399
+ // On game teardown:
400
+ unsubscribe();
401
+ ```
402
+
403
+ Callbacks immediately receive a snapshot and subsequently receive changes.
404
+ You can subscribe before `ready()` to keep music off during startup. Settings
405
+ are also available as `sdk.getBootstrap().settings`. Enabling music permits
406
+ playback subject to browser autoplay and the game's local mute; it must not
407
+ unmute sound effects or speech. Existing games need an integration update.
408
+
409
+ For a runnable reference game, serve the repository root with an HTTP static
410
+ server and open `packages/gamehub-sdk/demos/game-settings/index.html`.
411
+ The example host toggles music during gameplay; the game uses a separate gain
412
+ node for background music so sound effects remain independent. This is a
413
+ local integration demo; the GameHub profile is the production preference editor.
414
+
415
+ ## Multiplayer v2 (SDK 4.2)
416
+
417
+ Use `await sdk.ready()` before reading `sdk.getBootstrap().multiplayerLaunch`.
418
+ `requestMultiplayerLaunch()` requests only that already-bound launch from a
419
+ capable trusted host and accepts no room/game override. It returns reserved,
420
+ recoverable or terminal. The SDK owns no realtime connection or persistent token.
421
+ Use [@ksaa-nlp/gamehub-multiplayer](../gamehub-multiplayer/README.md) for socket,
422
+ state, clock and recovery lifecycle. The [Take Twenty-One starter](../../examples/take-twenty-one/README.md)
423
+ contains a complete authoring/build/upload example. V1 bootstrap is unchanged;
424
+ unsupported/native hosts do not advertise v2. Server-authoritative v2 rounds use
425
+ ctx.endMatch version 2 instead of browser submitScore/submitMatchResult.
package/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 3.11.0
3
+ Version: 4.2.0
4
4
  Status: Authoritative. Supersedes README/MIGRATION/CHANGELOG where they conflict.
5
5
 
6
6
  This document is the single source of truth for the GameHub SDK. Code, tests, and consumer docs follow this spec; if a behaviour is observed in code but not described here, treat it as undocumented and revisit before relying on it.
@@ -9,12 +9,13 @@ This document is the single source of truth for the GameHub SDK. Code, tests, an
9
9
 
10
10
  ## 1. Purpose
11
11
 
12
- The GameHub SDK is the client library that GameHub-hosted games use to talk to the GameHub platform. It is a thin, transport-agnostic adapter providing four capabilities:
12
+ The GameHub SDK is the client library that GameHub-hosted games use to talk to the GameHub platform. It is a thin, transport-agnostic adapter providing five capabilities:
13
13
 
14
14
  1. **Bootstrap pipeline.** A cross-origin `postMessage` handshake with the host page to discover the active game, the user's auth context, and (when applicable) a multiplayer reconnection token.
15
15
  2. **Sessions and scoring.** HTTP wrappers that open a session token and submit scores, with auto-init of the session when a submit is the first call.
16
16
  3. **Questions.** HTTP wrapper for the questions endpoint, used by quiz-style games.
17
17
  4. **League-match HTTP.** Wrappers for the league-match context fetch and the match-result submit endpoint.
18
+ 5. **Game settings.** Read account-wide preferences and subscribe to trusted host updates; games implement their own audio behavior.
18
19
 
19
20
  The SDK is not coupled to any realtime transport. When the host attaches a multiplayer room, the SDK exposes the connection parameters verbatim and the game opens its own socket.
20
21
 
@@ -24,7 +25,7 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
24
25
 
25
26
  - Discover the API base URL, the active game slug, and the league/match context from the iframe environment.
26
27
  - Exchange a small set of `postMessage` envelopes with the host page (bootstrap, auth, ready, init, command).
27
- - Hold a single in-memory session token and supply it to the GameHub REST API when submitting scores.
28
+ - Hold one in-memory playthrough session at a time, retain unknown submissions for exact retry, and clear terminal sessions so the same document can run sequential rounds.
28
29
  - Submit scores (`submitScore`, `submitMatchScore`) and league-match results (`submitMatchResult`).
29
30
  - Fetch questions (`getQuestions`) and words (`getWords`).
30
31
  - Request the host's report dialog for a question (`reportQuestion`) or word (`reportWord`).
@@ -61,6 +62,7 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
61
62
  | `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`, `getWords`. |
62
63
  | `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
63
64
  | `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
65
+ | `src/settings.ts` | Settings snapshots, validated merge and isolated subscriptions. |
64
66
  | `src/state.ts` | `SdkState` interface + the singleton `state` object. All mutable state lives here. |
65
67
  | `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`, `WORDS_LIMIT_CAP`. |
66
68
  | `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
@@ -100,6 +102,7 @@ This is the only place in the package that does work on import. Module / npm con
100
102
  | `dist/src/main.d.ts` | Public type surface. |
101
103
  | `dist/src/browser-entry.js` | ESM entry that performs the same side effects as the IIFE bundle. Used by frameworks that want a tree-shakeable side-effectful import. |
102
104
  | `dist/gamehub-sdk.js` | IIFE bundle for `<script>` tag use, target ES2020, no external deps. Includes `browser-entry.ts`. Marked `sideEffects: true`. |
105
+ | `dist/gamehub-sdk.js.map` | Source map for the IIFE bundle. The app-served JS and map are refreshed together under `packages/gamehub/public/sdk/`. |
103
106
 
104
107
  `build:tsc` emits ESM with `.js` extensions in imports (NodeNext) and full `.d.ts` files. `build:bundle` runs esbuild over `src/browser-entry.ts` to produce the IIFE.
105
108
 
@@ -176,7 +179,7 @@ The full taxonomy follows. It applies to **both** transports identically.
176
179
  | host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
177
180
  | SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
178
181
  | SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
179
- | SDK → host | `SCORE_SUBMITTED` | Fired when a score is accepted. Carries `{ score, accepted, timeTaken }`. |
182
+ | SDK → host | `SCORE_SUBMITTED` | Fired only when a score is accepted. Carries `{ score, sessionId, status: 'accepted', terminal: true, serverDurationMs, timeTaken, replayed? }`; score metadata is never included. |
180
183
  | SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
181
184
  | SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
182
185
  | SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
@@ -233,13 +236,42 @@ On the **native** transport there is no web origin: inbound `HostMessage.origin`
233
236
 
234
237
  This lets the host clear fields explicitly (via `null`) without overwriting unset fields.
235
238
 
239
+ ### 6.4a Account-wide game settings
240
+
241
+ `GameSettings` is `{ readonly musicEnabled: boolean }`. The effective default is
242
+ `false` for guests, standalone execution, old hosts, missing/invalid initial
243
+ preferences and legacy accounts. No setting enables sound implicitly.
244
+
245
+ `BootstrapConfig.settings` is optional. Omission preserves current settings;
246
+ explicit `null` resets music to false. A non-array object with a boolean
247
+ `musicEnabled` applies that value and strips unknown fields. Every other shape
248
+ is ignored. `BootstrapData.settings` always contains a detached snapshot.
249
+ Settings use the existing correlated `BOOTSTRAP` and subsequent unsolicited
250
+ `BOOTSTRAP` protocol, with exactly the existing parent/origin/native trust rules.
251
+ No new message type, storage or realtime transport is introduced.
252
+
253
+ `getSettings()` synchronously returns a detached snapshot. It does not wait for
254
+ initialization. `onSettingsChange(listener)` installs the ambient host listener,
255
+ registers a callback, immediately delivers a fresh snapshot, and returns an
256
+ idempotent unsubscribe function. Subscribing before `ready()` is supported.
257
+ Subsequent callbacks run synchronously only when the effective value changes.
258
+ Each registration is independent, including repeated registrations of the same
259
+ function. Listener exceptions cannot escape or prevent delivery to other
260
+ listeners; consumer mutation never changes SDK state. Callbacks are local and
261
+ emit no telemetry. `ready()` can still be awaited before reading settings.
262
+
263
+ Games must apply `false` to all current and future background music. `true`
264
+ permits music subject to their own mute and browser autoplay rules; it does not
265
+ force playback. Sound effects, speech and instructional audio are unaffected.
266
+ The SDK does not control HTML media, Web Audio, game engines or DOM elements.
267
+
236
268
  ### 6.5 Bootstrap lifecycle
237
269
 
238
270
  1. **Idle.** `state.bootstrapReceived = false`.
239
271
  2. **Request.** First call to `requestBootstrapFromParent()` posts `BOOTSTRAP_REQUEST` and starts the timeout.
240
272
  3. **Response.** Host replies with `BOOTSTRAP` carrying the matching `messageId`. `state.bootstrapReceived = true`; the direct parent's non-opaque origin is pinned.
241
273
  4. **Cache.** Subsequent calls return `snapshotBootstrap()` synchronously (wrapped in a resolved promise).
242
- 5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing callers do not get re-notified.
274
+ 5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing bootstrap callers do not get re-notified; settings subscriptions are notified when the effective settings change.
243
275
 
244
276
  A standalone (non-iframe) game has no parent; `requestBootstrapFromParent()` resolves `null` immediately, and `state.bootstrapReceived` stays `false`. `autoInit()` still runs the slug-only path.
245
277
 
@@ -264,7 +296,7 @@ Protocol details:
264
296
  - The host attaches authority from **its own** context. For authenticated
265
297
  external embeds this is an opaque embed credential held only in outer-host
266
298
  memory; it is never added to bootstrap or an `API_REQUEST`.
267
- - `API_RESPONSE.ok === true` carries the parsed JSON envelope in `result`; the promise resolves with it. `ok === false` carries an `error` string; the promise rejects. The per-call `try/catch` blocks in `session.ts` / `match-context.ts` turn either outcome into the usual degraded result — public methods still never throw (§17).
299
+ - `API_RESPONSE.ok` describes the host exchange, not the backend HTTP status. Whenever the backend returned a parseable `{ success: boolean, ... }` envelope, the host sends `ok: true` and carries that envelope in `result`, including structured non-2xx errors. `ok: false` is reserved for host validation, network, or malformed-response failure and carries an `error` string. The SDK validates bounded error `code`/`message` plus `details.terminal`, `details.sessionStatus`, and `details.retryAfterMs`; score methods map those fields without inspecting message text.
268
300
  - Timeout is `HOST_API_TIMEOUT_MS` (15 000 ms), larger than the 2 s bootstrap/auth timeout because the round-trip includes the host's real network call. On timeout the promise rejects and the call degrades.
269
301
  - `messageId` is `'api_' + Date.now() + '_' + <seq>`, where `<seq>` is a monotonic counter so concurrent proxied calls (e.g. session start + questions) never collide.
270
302
 
@@ -290,7 +322,7 @@ interface GameHubNativeHost {
290
322
  - The native app implements `postMessage` (typically forwarding to its WebView message channel — e.g. `flutter_inappwebview`'s `callHandler`).
291
323
  - The SDK installs `receive` when the transport is constructed. The native app calls `window.GameHubNativeHost.receive(env)` to deliver every host → SDK envelope (`BOOTSTRAP`, `AUTH_RESPONSE`, `API_RESPONSE`, `SET_AUTH`, `COMMAND`).
292
324
  - Envelope shapes, `messageId` correlation, and timeouts (§6.3) are identical to the postMessage transport. The native host must therefore echo the `messageId` on `BOOTSTRAP`/`AUTH_RESPONSE`/`API_RESPONSE` exactly as an iframe host does.
293
- - The native host is responsible for the same protocol an iframe host implements: replying to `BOOTSTRAP_REQUEST`/`AUTH_REQUEST`, proxying `API_REQUEST` (performing the real HTTPS call natively — see §6.6), and reacting to one-way signals (`REQUEST_CLOSE`, `QUESTION_REPORT`, `WORD_REPORT`, `SCORE_SUBMITTED`, `GAME_COMPLETE`, `LOG_EVENT`).
325
+ - The native host is responsible for the same protocol an iframe host implements: replying to `BOOTSTRAP_REQUEST`/`AUTH_REQUEST`, proxying `API_REQUEST` (performing the real HTTPS call natively and preserving parseable backend failure envelopes with `ok: true` — see §6.6), and reacting to one-way signals (`REQUEST_CLOSE`, `QUESTION_REPORT`, `WORD_REPORT`, accepted-only `SCORE_SUBMITTED`, `GAME_COMPLETE`, `LOG_EVENT`).
294
326
  - Multiplayer is unchanged: the host passes `bootstrap.multiplayer` `{ reservation, wsEndpoint }`, and the game opens its own Colyseus WebSocket from inside the WebView (§19.1). The SDK does not proxy realtime traffic over the bridge.
295
327
 
296
328
  ## 7. Authentication
@@ -334,7 +366,7 @@ If the host posts `SET_AUTH` mid-session, the new token is used for subsequent r
334
366
 
335
367
  ### 8.3 Idempotency
336
368
 
337
- Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-circuit to `{ success: true, token }`. Concurrent callers share `state.sessionStartPromise`. The SDK never starts a second session.
369
+ Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-circuit to `{ success: true, token }`. Concurrent callers share `state.sessionStartPromise`. An accepted or terminally rejected submission clears the token and all start/submission state; only then may the next `startSession()` create the next playthrough.
338
370
 
339
371
  ### 8.4 Session start triggers
340
372
 
@@ -355,10 +387,15 @@ On success, the SDK posts `SESSION_STARTED { token }` to the host.
355
387
 
356
388
  - Awaits `ensureInitialized()`.
357
389
  - If no session, opens one (or awaits the in-flight start).
358
- - Validates: `score` must be a non-negative number; coerced to `Math.floor(score)` before submit.
390
+ - Validates: `score` must be finite and floor to an integer from 0 through 10,000,000. Metadata must match the server's 32 KiB/depth/key/string/array JSON bounds. Invalid input resolves locally before a submission is bound.
359
391
  - POSTs to `/sessions/submit` with `{ token, score, meta }`.
360
- - On success or `data.accepted`, posts `SCORE_SUBMITTED { score, accepted, timeTaken }` to the host and resolves `{ success: true, accepted, timeTaken }`.
361
- - On failure, resolves `{ success: false, error }`. Never throws.
392
+ - Snapshots the first JSON-serializable body exactly. Its canonical concurrency key is `{ floor(score), sanitized/capped attempts, clientMeta }`, with server-authoritative identity, duration, session, and source keys excluded to match the server submission hash.
393
+ - Concurrent calls with the same token and canonical payload share one in-flight request. A different payload resolves locally as a non-retriable `CONCURRENT_SUBMISSION_CONFLICT` and never races the server.
394
+ - An accepted target response resolves `{ success: true, status: 'accepted', terminal: true, sessionId, serverDurationMs, timeTaken, replayed? }`. Guest/league storage responses are normalized to this same public accepted shape.
395
+ - A structured terminal error resolves `{ success: false, status: 'rejected', terminal: true, code, error, sessionStatus? }`. Accepted and rejected terminal outcomes clear the token/start/submission/pending state after accepted host notification.
396
+ - `RATE_LIMITED` and `SUBMISSION_IN_PROGRESS` resolve the retriable variant. Server/transport failures resolve the failed variant. All non-terminal outcomes retain the active token and exact first body; an explicit same-payload call retries it and can consume `replayed: true`.
397
+ - Posts `SCORE_SUBMITTED` only for accepted outcomes. The telemetry contains lifecycle fields, never arbitrary `meta`.
398
+ - Every public score method resolves a result and never throws.
362
399
 
363
400
  ### 9.2 `submitMatchScore(score, meta?)`
364
401
 
@@ -486,7 +523,7 @@ Full field tables in `types/word.ts` and `specs/words-bank-feature.md` §3.
486
523
  Mirrors `reportQuestion`: fires the `WORD_REPORT` postMessage with
487
524
  `{ wordId?, lemma?, message?, words? }` for the host to render its
488
525
  `ReportWordDialog`. No-ops outside the host iframe (the SDK never calls the
489
- report endpoint itself). See §6.1.
526
+ report endpoint itself). The host requires login, using the same guest/expired-session login prompt as question reports. This is host/API behavior only; the SDK message contract and version are unchanged. See §6.1.
490
527
 
491
528
  ## 12. Host command channel
492
529
 
@@ -538,6 +575,12 @@ interface SdkState {
538
575
  bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;
539
576
  parentOrigin: string | null;
540
577
  sessionStartPromise: Promise<StartSessionResult> | null;
578
+ submissionPromise: Promise<SubmitScoreResult> | null;
579
+ pendingSubmission: {
580
+ token: string;
581
+ canonicalPayload: string;
582
+ body: { token: string; score: number; meta: Record<string, unknown> };
583
+ } | null;
541
584
 
542
585
  // League match (HTTP)
543
586
  matchContext: MatchContext | null;
@@ -545,11 +588,16 @@ interface SdkState {
545
588
  }
546
589
  ```
547
590
 
591
+ The singleton also owns `gameSettings` (initial `{ musicEnabled: false }`) and
592
+ `settingsListeners` (initial empty Set). Settings mutate only via the validated
593
+ bootstrap merge; subscriptions hold callbacks only in memory.
594
+
548
595
  ### 13.1 Invariants
549
596
 
550
597
  - `apiBase` is set exactly once, by `detectEnvironment()`, before any HTTP request. It is never mutated afterwards.
551
598
  - `gameSlug` may be updated by the bootstrap merge but should be considered stable after `isInitialized = true`. Changing the slug mid-session is undefined behaviour.
552
- - `sessionToken` is set at most once per page load. The SDK never invalidates or rotates it.
599
+ - At most one `sessionToken` is active. A terminal result clears it synchronously after accepted host notification; the next round receives a distinct token without reloading.
600
+ - `pendingSubmission` is bound to the active token and canonical payload. Non-terminal outcomes retain its exact body; terminal outcomes clear it together with `submissionPromise`, `sessionStartPromise`, and the token.
553
601
  - `matchContext` is set at most once. Stale match context across renavigations is the host's problem (refresh resets the SDK).
554
602
  - All `*Promise` fields are cleared when their underlying operation settles (success or failure).
555
603
 
@@ -608,13 +656,20 @@ interface SdkState {
608
656
  | `logEvent(eventName, eventData?)` | `void` | `LOG_EVENT { event: eventName, data: eventData }` |
609
657
  | `reportQuestion(data)` | `void` | `QUESTION_REPORT { questionId?, prompt?, message?, questions? }` |
610
658
 
611
- `reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog. The host owns the dialog (the SDK renders no DOM — see §19.3) and submits the report, collecting the reason, an optional message, and — for guests — name/email. Like the other host signals it no-ops outside an iframe.
659
+ `reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog. The host owns the dialog (the SDK renders no DOM — see §19.3) and submits the report, collecting the reason and an optional message for logged-in users. Guests receive a login prompt from the host; report endpoints require a verified account token. A host submission returning `401` also shows the login prompt. Like the other host signals it no-ops outside an iframe.
612
660
 
613
661
  Two modes:
614
662
 
615
663
  - **Single question** — pass `questionId` (and optionally `prompt`). The dialog reports that one question.
616
664
  - **Pick from a list** — pass `questions: ReportableQuestion[]` (each `{ questionId, prompt? }`). The host renders a dropdown so the player chooses which question to report; `questionId`, when also supplied, pre-selects an entry. The `questions` array is forwarded verbatim (each entry normalised to `{ questionId, prompt }`) on the `QUESTION_REPORT` envelope.
617
665
 
666
+ ### 14.7a Game settings
667
+
668
+ | Method | Returns | Notes |
669
+ | --- | --- | --- |
670
+ | `getSettings()` | `GameSettings` | Detached effective snapshot; default music off. |
671
+ | `onSettingsChange(listener)` | `() => void` | Immediate snapshot, then changes; unsubscribe on game teardown. |
672
+
618
673
  ### 14.7 Read-only context
619
674
 
620
675
  | Method | Returns | Notes |
@@ -648,7 +703,12 @@ interface BootstrapMultiplayer {
648
703
  connectionScope?: string;
649
704
  }
650
705
 
706
+ interface GameSettings {
707
+ readonly musicEnabled: boolean;
708
+ }
709
+
651
710
  interface BootstrapConfig {
711
+ settings?: GameSettings | null;
652
712
  gameSlug?: string | null;
653
713
  authToken?: string | null;
654
714
  leagueId?: string | null;
@@ -665,6 +725,7 @@ interface BootstrapConfig {
665
725
  }
666
726
 
667
727
  interface BootstrapData {
728
+ settings: GameSettings;
668
729
  gameSlug: string | null;
669
730
  authToken: string | null;
670
731
  leagueId: string | null;
@@ -700,12 +761,41 @@ interface StartSessionResult {
700
761
  error?: string;
701
762
  }
702
763
 
703
- interface SubmitScoreResult {
704
- success: boolean;
705
- accepted?: boolean;
706
- timeTaken?: number;
707
- error?: string;
708
- }
764
+ type SubmitScoreResult =
765
+ | {
766
+ success: true;
767
+ status: 'accepted';
768
+ terminal: true;
769
+ sessionId: string;
770
+ serverDurationMs: number;
771
+ timeTaken: number;
772
+ replayed?: true;
773
+ }
774
+ | {
775
+ success: false;
776
+ status: 'rejected';
777
+ terminal: true;
778
+ code: string;
779
+ error: string;
780
+ sessionStatus?: string;
781
+ }
782
+ | {
783
+ success: false;
784
+ status: 'retriable';
785
+ terminal: false;
786
+ code: 'SUBMISSION_IN_PROGRESS' | 'RATE_LIMITED';
787
+ error: string;
788
+ retryAfterMs?: number;
789
+ sessionStatus?: string;
790
+ }
791
+ | {
792
+ success: false;
793
+ status: 'failed';
794
+ terminal: false;
795
+ code: string;
796
+ error: string;
797
+ retriable: boolean;
798
+ };
709
799
 
710
800
  interface GameCompleteData {
711
801
  score?: number;
@@ -778,7 +868,15 @@ interface ApiResponse {
778
868
  success: boolean;
779
869
  data?: any;
780
870
  token?: string;
781
- error?: { message?: string };
871
+ error?: {
872
+ code?: string;
873
+ message?: string;
874
+ details?: {
875
+ terminal?: boolean;
876
+ sessionStatus?: string;
877
+ retryAfterMs?: number;
878
+ };
879
+ };
782
880
  }
783
881
 
784
882
  interface ApiRequestOptions {
@@ -793,14 +891,14 @@ interface ApiRequestOptions {
793
891
 
794
892
  The SDK assumes the GameHub server exposes the following endpoints. When embedded these are reached via the host proxy (§6.6); standalone they are reached directly under `state.apiBase`. Either way the SDK calls `apiRequest` with the same `endpoint` path. Any change to these contracts must be coordinated server-side and is a major-version event for the SDK.
795
893
 
796
- | Method | Path | Auth | Request body | Successful response shape |
797
- | ------ | ----------------------------------------------- | ---------------------------------- | ------------------------ | ------------------------------------------------------------------ |
798
- | POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
799
- | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
800
- | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
801
- | POST | `/sessions/submit` | optional | `{ token, score, meta }` | `{ success: true, data: { accepted, timeTaken } }` |
802
- | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
803
- | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
894
+ | Method | Path | Auth | Request body | Successful response shape |
895
+ | ------ | ----------------------------------------------- | ---------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
896
+ | POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
897
+ | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
898
+ | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
899
+ | POST | `/sessions/submit` | optional | `{ token, score, meta }` | Account target: `{ success: true, data: { status: 'accepted', terminal: true, sessionId, serverDurationMs, timeTaken, replayed? } }`; guest/league accepted responses are normalized by the SDK |
900
+ | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
901
+ | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
804
902
 
805
903
  ### 16.1 Response envelope
806
904
 
@@ -808,14 +906,14 @@ The SDK expects (but tolerates absence of) a `{ success, data, token?, error? }`
808
906
 
809
907
  ### 16.2 Failure surface
810
908
 
811
- - Non-2xx HTTP responses are parsed as JSON and surfaced via the returned `SubmitScoreResult.error` / `null` / `[]` (depending on the call).
909
+ - Structured non-2xx HTTP envelopes are surfaced to score calls as terminal, retriable, or failed discriminated results; other calls degrade to `null` / `[]` as documented.
812
910
  - `fetch` exceptions (network failure, malformed JSON) are caught by every public method and surfaced as the same failure shape. The SDK never throws past its public surface.
813
911
  - When embedded, a host-proxy rejection (host-reported error, or `HOST_API_TIMEOUT_MS` timeout — see §6.6) surfaces identically: the call degrades to its failure shape. CORS is no longer a failure mode for embedded games, since the host (same-origin with the backend) makes the actual request.
814
912
 
815
913
  ## 17. Error handling philosophy
816
914
 
817
915
  - **Never throw to consumers.** Every public method returns either a typed success/failure result, or the degraded value (`null` / `[]`).
818
- - **No retries.** A single attempt per call. Consumers retry if they want to.
916
+ - **Explicit score retry only.** The SDK never autonomously repeats a network call. After an unknown/retriable score outcome, a consumer retries the same call; the SDK reuses the original session token and exact first request body. A different payload is refused until the session becomes terminal.
819
917
  - **No global error reporting.** Errors are logged with the `[GameHubSDK]` prefix via `console.warn` / `console.error`. The SDK does not POST to any error endpoint.
820
918
  - **No timeouts on direct HTTP.** The standalone `fetch` path inherits `fetch`'s default behaviour. The postMessage handshakes have timeouts (2 s for bootstrap/auth), and the host-proxied API transport has its own `HOST_API_TIMEOUT_MS` (15 s) cap (§6.6).
821
919
  - **Silent degradation on partial bootstrap.** Missing fields are tolerated where possible (`getQuestions` works without `gameId`, falling back to slug; `submitScore` requires auth or a league-match session but no realtime context).
@@ -874,7 +972,7 @@ These rules exist because of a real prior regression where transport-related cle
874
972
 
875
973
  ### 20.3 Bundle budget
876
974
 
877
- The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **10 KB gzip**, the figure that matters on the wire. The raw budget was historically **25 KB**; the native-bridge transport added in 3.8.0 (a deliberate new feature area — §6.7) pushed raw past that historical target. Current 3.11.0 size: 27,997 bytes raw / 6,285 bytes gzip. Further growth should be a deliberate decision tied to a release note, and gzip remains the hard ceiling.
975
+ The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **44 KiB raw** and **10 KiB gzip**, the latter being the figure that matters most on the wire. The raw budget was historically 25 KB; native transport and the reliable multi-round lifecycle deliberately exceed that historical target. SDK 4.2.0 combines account music settings and multiplayer v2: **43,567 bytes raw / 9,804 bytes gzip**. The merged features deliberately raise the raw limit from 42 KiB to 44 KiB while retaining the 10 KiB gzip limit. Further growth requires a deliberate release review.
878
976
 
879
977
  ### 20.4 No runtime dependencies
880
978
 
@@ -919,8 +1017,11 @@ The SDK ships focused Node tests for transport trust-boundary behavior. Every ch
919
1017
  ### 21.4 Score submission
920
1018
 
921
1019
  - `submitScore(42, { level: 3 })` causes a POST to `/api/sessions/submit` with `{ token, score: 42, meta: { level: 3 } }` and Bearer auth. When embedded (the default), this travels as an `API_REQUEST` `{ endpoint: '/sessions/submit', method: 'POST', body: { … } }` and the **host** performs the POST with its own bearer auth (§6.6); standalone, the SDK POSTs directly.
922
- - Returns `{ success: true, accepted: true, timeTaken: <n> }` on a `{ success: true, data: { accepted: true, timeTaken: 1234 } }` server response.
923
- - Fires `SCORE_SUBMITTED { score: 42, accepted: true, timeTaken: 1234 }` to the host.
1020
+ - The target account response resolves the accepted terminal variant and fires accepted-only `SCORE_SUBMITTED`; terminal rejection resolves the rejected variant and emits no score telemetry. Both immediately make `hasActiveSession()` false.
1021
+ - Rate limit, live processing, `SERVER_ERROR`, host failure, and timeout retain the token and exact first body. A same-payload retry can resolve accepted with `replayed: true`.
1022
+ - Two sequential accepted rounds in one document create and submit distinct session tokens.
1023
+ - Concurrent canonical-identical calls issue one host request; a different concurrent payload resolves `CONCURRENT_SUBMISSION_CONFLICT` locally.
1024
+ - `SCORE_SUBMITTED` contains score/session/lifecycle/duration fields only. The trusted host parser strips score/session/duration before lifecycle publication and never forwards arbitrary score metadata.
924
1025
  - In public embed mode, the game still emits `/sessions/start` and
925
1026
  `/sessions/submit`; the host binds and rewrites those requests for guest or
926
1027
  authenticated play. The SDK never creates or stores the embed guest ID,
@@ -930,7 +1031,7 @@ The SDK ships focused Node tests for transport trust-boundary behavior. Every ch
930
1031
 
931
1032
  - Inside an iframe, no public method issues a direct cross-origin `fetch`; each `apiRequest` posts an `API_REQUEST` and resolves on the matching `API_RESPONSE`.
932
1033
  - A host that never replies leaves the call pending until `HOST_API_TIMEOUT_MS` (15 s), after which it degrades to the usual failure shape.
933
- - An `API_RESPONSE { ok: false, error }` degrades identically. The host must reject requests outside the documented SDK REST method/path/query/body allowlist, even when the endpoint is a relative GameHub API path.
1034
+ - An `API_RESPONSE { ok: false, error }` degrades identically. A parseable backend failure envelope travels as `{ ok: true, result: { success: false, error: ... } }` so terminal/retriable details survive. The host must reject requests outside the documented SDK REST method/path/query/body allowlist, even when the endpoint is a relative GameHub API path.
934
1035
 
935
1036
  ### 21.5 League-match path
936
1037
 
@@ -957,6 +1058,19 @@ admin contract/UI/CSV, automated tests, and both package specifications. A
957
1058
  method that cannot cross an observable host or server boundary must be
958
1059
  explicitly classified as static-only.
959
1060
 
1061
+ Version 4.0.0 changes the lifecycle/result contract of the existing
1062
+ `startSession` and `submitScore` capabilities but adds no public method, alias,
1063
+ or capability. Their existing Usage Intelligence feature IDs and accepted-only
1064
+ server-operation observation remain authoritative; no scanner/report inventory
1065
+ version change is required for this release.
1066
+
1067
+ Version 4.1.0 adds `getSettings` and `onSettingsChange`, both static-only in the
1068
+ Usage Intelligence Report: a host delivering preferences proves neither their
1069
+ consumption nor audio compliance. Scanner version 2, admin Arabic labels,
1070
+ filters/CSV and fixtures are synchronized. Runtime aggregation excludes these
1071
+ local APIs. The example in `demos/game-settings/` is a reference game and
1072
+ host for manual testing of global/local mute and live preference updates.
1073
+
960
1074
  ## 21bis. UGC server bundle subpath
961
1075
 
962
1076
  The `./server` and `./server/dev` subpaths are separate from the browser SDK. Importing them has **no overlap** with the iframe runtime — they target the colyseus UGC sandbox, not the browser host.
@@ -1024,3 +1138,37 @@ expect(room.outbox).toContainEqual({
1024
1138
  - **Host.** The GameHub-served page that frames the game in an iframe. Owns auth, matchmaking, and the bootstrap pipeline.
1025
1139
  - **Game.** The iframe-hosted application that consumes this SDK.
1026
1140
  - **Standalone.** A game loaded outside an iframe. `isInIframe()` returns false; the bootstrap pipeline is skipped.
1141
+
1142
+ ## Launch v2 (4.2.0)
1143
+
1144
+ The authoritative cross-package contract is [multiplayer v2](../../specs/multiplayer.md).
1145
+ Optional bootstrap `capabilities` and `multiplayerLaunch` are separate from the
1146
+ unchanged required v1 `multiplayer.reservation` shape. `requestMultiplayerLaunch()`
1147
+ is a no-argument, single-flight request to the trusted host for its already-bound
1148
+ round. It validates bounded replies and fences a changed launch context. It owns
1149
+ no socket or persistent storage. Old/native hosts do not advertise v2 and return
1150
+ `PROTOCOL_UNSUPPORTED`; no fallback room is chosen.
1151
+
1152
+ `ready()` completes bootstrap before a module consumer reads its launch. V2
1153
+ bootstrap suppresses unrelated client-scored session creation; the host permits
1154
+ only the bound launch request and the backend rejects browser ownership of
1155
+ server-multiplayer PlayerSessions. Solo and legacy HTTP methods retain their
1156
+ existing semantics. The separate `@ksaa-nlp/gamehub-multiplayer` package owns
1157
+ Colyseus state, clock and recovery tokens.
1158
+
1159
+ Server `EndMatchPayload` adds optional version 2, per-seat scores, winner seat IDs
1160
+ and bounded metadata. The v2 room requires the v2 result shape and enriches it
1161
+ with trusted provenance. `ctx.endMatch` is a proposal, not a saved acknowledgement.
1162
+ Legacy endMatch payloads remain valid in legacy rooms.
1163
+
1164
+ SDK_VERSION, npm version and served JS/map are 4.2.0. The distribution gate is
1165
+ 44 KiB raw / 10 KiB gzip (the raw increase covers v2 validation and game settings); runtime
1166
+ dependencies remain empty. Scanner version 3 includes requestMultiplayerLaunch,
1167
+ endMatch, seededPlayers and the static-only game-settings APIs; version-2 scans
1168
+ are stale after rebasing onto the game-settings release. A launch request
1169
+ observation is not successful admission; see the
1170
+ [usage report](../../specs/sdk-usage-report.md).
1171
+
1172
+ ## Seeded participants (4.2.0)
1173
+
1174
+ `SeededPlayer` adds optional `kind: human|bot`, `seatId` and `peerId`. Missing kind means human for legacy hosts. V2 always supplies these fields; userId/seatId/peerId are the same opaque stable seat ID, never a bot/account credential. Bots do not connect or receive `onJoin`; the UGC bundle owns their legal moves using normal state/rules and `ctx.setTimeout`. All roster players, including bots, belong in endMatch scores. No realtime dependency is introduced. SDK Usage scanner 3 represents the widened data capability as `seededPlayers`: static identifiers are possible evidence; a trusted first UGC round-start acknowledgement confirms roster delivery. It does not prove a game consumed the field or that its bot algorithm acted. See the report specification.