@ksaa-nlp/gamehub-sdk 4.5.0 → 5.5.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.
Files changed (73) hide show
  1. package/README.md +103 -48
  2. package/SPEC.md +230 -57
  3. package/dist/gamehub-sdk.js +1 -1458
  4. package/dist/gamehub-sdk.js.map +4 -4
  5. package/dist/src/answers.d.ts +22 -0
  6. package/dist/src/answers.d.ts.map +1 -0
  7. package/dist/src/answers.js +139 -0
  8. package/dist/src/answers.js.map +1 -0
  9. package/dist/src/bot-driver.d.ts +2 -1
  10. package/dist/src/bot-driver.d.ts.map +1 -1
  11. package/dist/src/bot-driver.js +11 -1
  12. package/dist/src/bot-driver.js.map +1 -1
  13. package/dist/src/bridge.d.ts.map +1 -1
  14. package/dist/src/bridge.js +2 -35
  15. package/dist/src/bridge.js.map +1 -1
  16. package/dist/src/constants.d.ts +1 -1
  17. package/dist/src/constants.js +1 -1
  18. package/dist/src/init.js +7 -7
  19. package/dist/src/init.js.map +1 -1
  20. package/dist/src/loading.d.ts +5 -0
  21. package/dist/src/loading.d.ts.map +1 -0
  22. package/dist/src/loading.js +54 -0
  23. package/dist/src/loading.js.map +1 -0
  24. package/dist/src/main.d.ts +14 -3
  25. package/dist/src/main.d.ts.map +1 -1
  26. package/dist/src/main.js +12 -4
  27. package/dist/src/main.js.map +1 -1
  28. package/dist/src/multiplayer-client.d.ts +52 -0
  29. package/dist/src/multiplayer-client.d.ts.map +1 -0
  30. package/dist/src/multiplayer-client.js +286 -0
  31. package/dist/src/multiplayer-client.js.map +1 -0
  32. package/dist/src/multiplayer-entry.d.ts +9 -0
  33. package/dist/src/multiplayer-entry.d.ts.map +1 -0
  34. package/dist/src/multiplayer-entry.js +9 -0
  35. package/dist/src/multiplayer-entry.js.map +1 -0
  36. package/dist/src/multiplayer-session.d.ts.map +1 -1
  37. package/dist/src/multiplayer-session.js +3 -3
  38. package/dist/src/multiplayer-session.js.map +1 -1
  39. package/dist/src/multiplayer.d.ts.map +1 -1
  40. package/dist/src/multiplayer.js +2 -1
  41. package/dist/src/multiplayer.js.map +1 -1
  42. package/dist/src/session.d.ts.map +1 -1
  43. package/dist/src/session.js +28 -7
  44. package/dist/src/session.js.map +1 -1
  45. package/dist/src/state.d.ts +1 -2
  46. package/dist/src/state.d.ts.map +1 -1
  47. package/dist/src/state.js +0 -1
  48. package/dist/src/state.js.map +1 -1
  49. package/dist/types/bootstrap.d.ts +8 -45
  50. package/dist/types/bootstrap.d.ts.map +1 -1
  51. package/dist/types/loading.d.ts +6 -0
  52. package/dist/types/loading.d.ts.map +1 -0
  53. package/dist/types/loading.js +2 -0
  54. package/dist/types/loading.js.map +1 -0
  55. package/dist/types/multiplayer-session.d.ts +9 -8
  56. package/dist/types/multiplayer-session.d.ts.map +1 -1
  57. package/dist/types/question.d.ts +0 -1
  58. package/dist/types/question.d.ts.map +1 -1
  59. package/dist/types/question.js +0 -1
  60. package/dist/types/question.js.map +1 -1
  61. package/dist/types/session.d.ts +16 -0
  62. package/dist/types/session.d.ts.map +1 -1
  63. package/dist/vendor/colyseus-schemas/clock.d.ts +15 -0
  64. package/dist/vendor/colyseus-schemas/clock.js +67 -0
  65. package/dist/vendor/colyseus-schemas/common.d.ts +35 -0
  66. package/dist/vendor/colyseus-schemas/common.js +15 -0
  67. package/dist/vendor/colyseus-schemas/multiplayer.d.ts +8 -0
  68. package/dist/vendor/colyseus-schemas/multiplayer.js +26 -0
  69. package/dist/vendor/colyseus-schemas/ugc.d.ts +53 -0
  70. package/dist/vendor/colyseus-schemas/ugc.js +124 -0
  71. package/dist/vendor/gamehub-multiplayer-contracts/index.d.ts +200 -0
  72. package/dist/vendor/gamehub-multiplayer-contracts/index.js +289 -0
  73. package/package.json +34 -4
package/SPEC.md CHANGED
@@ -1,23 +1,110 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 4.5.0
3
+ Version: 5.5.1
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.
7
7
 
8
+ ## Minified script-tag bundle (5.5.1)
9
+
10
+ The IIFE bundle (`dist/gamehub-sdk.js`, served at `/sdk/gamehub-sdk.js`) is now
11
+ built with esbuild `--minify`: about 28 KB raw and 9 KB gzip instead of 54 KB
12
+ and 12.4 KB. The public API, message types, the `window.GameHubSDK` global and
13
+ its method names are unchanged (object property names are not mangled); the
14
+ source map still maps the served file back to the sources. ESM entries are
15
+ unaffected. §20.3 lowers the budget to match.
16
+
17
+ ## Answer recording (5.5.0)
18
+
19
+ `sdk.recordAnswer({ questionId, correct, choice?, timeMs?, level? })` reports
20
+ one answered question for the platform's play analytics. It is fire-and-forget
21
+ (`void`, never throws, never blocks play):
22
+
23
+ - **Validation.** `questionId` is 1–64 characters of `A-Z a-z 0-9 _ : . -` (a
24
+ question-bank id from `getQuestions`, or the game's own stable id, never prompt
25
+ text); `correct` is a boolean; `choice` is the picked option's text (≤ 100
26
+ characters) or an integer index; `timeMs` is 0–600 000 (rounded); `level` is
27
+ an integer 0–1000. An invalid answer is dropped.
28
+ - **Scope.** Answers are kept only for a signed-in player's standalone account
29
+ session: a 24-hex session token, no league context and not an embed guest.
30
+ Otherwise the call does nothing. It does not start a session.
31
+ - **Delivery.** Each answer gets the next `seq` (0–499) of its session; later
32
+ answers are dropped. The SDK sends `POST /sessions/answers`
33
+ `{ token, answers: [...] }` (§16) when ten answers are queued, three seconds
34
+ after the last answer, and always before `submitScore` sends the score.
35
+ Batches hold at most 50 answers. A failed batch is dropped, not retried: it
36
+ loses analytics only, and the platform stores each `seq` once.
37
+ - **Anonymous storage.** The platform keeps answers without the player or the
38
+ session: the session token only authorizes the batch. The endpoint answers
39
+ `{ recorded }`, the number of new answers stored.
40
+
41
+ `RecordAnswerData` is exported with the other session types. The React Native
42
+ SDK 1.3.0 implements the same method and rules. Usage report: feature
43
+ `recordAnswer`, scanner 8, observed on the server endpoint (§21.7).
44
+
45
+ ## Platform loading presentation (5.4.0)
46
+
47
+ `sdk.setLoading(state, launch?)` requests the platform's common loading screen.
48
+ `GameLoadingState` is `loading | waiting-for-players | reconnecting | failed | null`.
49
+ `null` clears that channel. Call it before asset/content work and clear it before
50
+ interactive tutorials or gameplay; errors use `failed`. It does not mark players
51
+ ready, pause a room, fetch data or change game rules. `ready()` and wire `READY`
52
+ refer to SDK initialization, not game asset readiness.
53
+
54
+ The optional `GameLoadingLaunch` contains only `multiplayerSessionId`, `roundId`,
55
+ `attemptId`, `seatId`, `hostInstanceId`; it selects the separate multiplayer
56
+ channel. `MultiplayerClient` calls the optional `LaunchHost.setLoading` with this
57
+ identity automatically: connecting/finishing → loading, connected/loading →
58
+ waiting-for-players, reconnecting → reconnecting, failed → failed, playing/
59
+ completed/disposed → null. Status changes alone trigger reports; optional host
60
+ exceptions cannot break connection recovery. Native/custom launch hosts that
61
+ omit the optional method retain existing behavior, with no browser dependencies.
62
+
63
+ The maintained React Native SDK implements the same signal in version 1.2.0,
64
+ using a per-client loading owner, snapshot/subscription API and optional React
65
+ hook instead of a DOM bridge. Its loading types are copied from this package's
66
+ authoritative contract at build time. The mobile WebView host also accepts this
67
+ browser signal and renders loading outside the game; see the native SDK and
68
+ mobile app specifications for their lifecycle and document fencing contracts.
69
+
70
+ Supported iframe hosts supply an opaque `BootstrapConfig.loadingContext` on
71
+ bootstrap and rotate it on document load/replacement/retry. The transport emits
72
+ `GAMEHUB_SDK_LOADING` with `{loadingContext,state,launch?}` only after a valid
73
+ context arrives through the existing trusted bootstrap. Calls made before then
74
+ retain the latest value per channel; a new context replays both channels.
75
+ Invalid state/identity/context values are ignored. Only the five bounded identity
76
+ fields are copied, never reservations or credentials. Unsupported hosts and
77
+ standalone games receive no loading signal and retain their own fallback UI.
78
+ Hosts validate current iframe source, origin, context and all launch identity
79
+ fields; loading has no authority over results, scoring or session operations.
80
+
81
+ Solo, embed, standard multiplayer and AirConsole gameplay share the same host
82
+ component. The game stays mounted and continues work while its iframe is inert.
83
+ A continuous 45-second wait offers retry without cancelling the running game;
84
+ recovery can still clear the screen. Legacy bundles use document loading and
85
+ host-observed round progress after a launch request. They must adopt this SDK
86
+ and `setLoading` for otherwise invisible asset waits and local reconnection.
87
+ Immutable game packages are not rewritten by a platform deployment.
88
+
89
+ SDK Usage scanner 7 adds `setLoading` with the standard call-site detection,
90
+ Arabic labels, filtering and CSV. A valid current-document host signal records
91
+ runtime evidence once per mounted source; untrusted/stale signals do not count.
92
+ The package, SDK_VERSION and served JS/map are 5.4.0; the existing 52 KiB raw /
93
+ 12 KiB gzip distribution gate remains unchanged.
94
+
8
95
  ---
9
96
 
10
97
  ## 1. Purpose
11
98
 
12
99
  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
100
 
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.
101
+ 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) the bound multiplayer launch or lobby context.
15
102
  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
103
  3. **Questions.** HTTP wrapper for the questions endpoint, used by quiz-style games.
17
104
  4. **League-match HTTP.** Wrappers for the league-match context fetch and the match-result submit endpoint.
18
105
  5. **Game settings.** Read account-wide preferences and subscribe to trusted host updates; games implement their own audio behavior.
19
106
 
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.
107
+ The main entry and script-tag bundle are not coupled to any realtime transport. Multiplayer games request their bound launch through the SDK and open their own socket with `MultiplayerClient` from the opt-in `./multiplayer` subpath (§21ter), whose realtime packages are optional peers; see [the multiplayer reference](../../specs/multiplayer.md).
21
108
 
22
109
  ## 2. Scope and non-goals
23
110
 
@@ -30,20 +117,21 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
30
117
  - Fetch questions (`getQuestions`) and words (`getWords`).
31
118
  - Request the host's report dialog for a question (`reportQuestion`) or word (`reportWord`).
32
119
  - Surface a bootstrap snapshot (`getBootstrap()`) including the trusted
33
- `sessionMode` and opaque `multiplayer` block.
120
+ `sessionMode` and multiplayer launch/lobby context.
34
121
  - Forward player-visible host commands (`pause`, `resume`) to optional `window.onGameHubPause` / `onGameHubResume` callbacks.
35
122
  - Type definitions for authoring UGC server bundles (`./server` subpath), plus the optional bundled `createBotDriver` helper.
36
123
  - Node-only dev harness (`./server/dev` subpath) for unit-testing a guest bundle against a simulated `ctx`.
124
+ - The game-owned Colyseus connection for a bound v2 round (`./multiplayer` subpath, §21ter), opt-in and outside the main entry and the IIFE bundle.
37
125
 
38
126
  ### Out of scope
39
127
 
40
- - Opening or managing WebSocket / WebRTC / SSE connections.
41
- - Maintaining live realtime room state, peer rosters, message routing, or reconnection.
128
+ - Opening or managing WebSocket / WebRTC / SSE connections from the main entry, `./browser` or the IIFE bundle. Only the `./multiplayer` subpath opens a socket (§21ter).
129
+ - Maintaining live realtime room state, peer rosters, message routing, or reconnection outside the `./multiplayer` subpath.
42
130
  - Server-side authority for **browser-side** game logic. The `./server` subpath holds types and the pure `createBotDriver` helper; authoritative server logic for UGC games runs inside the colyseus UGC sandbox (`packages/colyseus/src/rooms/ugc/`).
43
131
  - Persistent storage. The SDK keeps everything in memory; refresh resets it.
44
132
  - UI. The SDK never renders or injects DOM.
45
133
  - Analytics. `logEvent` forwards a payload to the host via postMessage; the SDK does not POST to any analytics endpoint itself.
46
- - Realtime time-sync. Server-clock helpers ship in `@ksaa-nlp/colyseus-schemas/clock`, not here.
134
+ - Realtime time-sync in the main entry. The server-clock helper's source is `@ksaa-nlp/colyseus-schemas/clock`; only `./multiplayer` ships a copy (§21ter).
47
135
  - Multi-tenant or multi-game state. The SDK assumes one game slug per page load.
48
136
 
49
137
  ## 3. Architecture
@@ -67,11 +155,13 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
67
155
  | `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`, `WORDS_LIMIT_CAP`. |
68
156
  | `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
69
157
  | `types/api.ts` | `ApiResponse`, `ApiRequestOptions`. |
70
- | `types/bootstrap.ts` | `BootstrapMultiplayer`, `BootstrapConfig`, `BootstrapData`. |
158
+ | `types/bootstrap.ts` | `BootstrapConfig`, `BootstrapData`, `MultiplayerLaunchContext` (alias of the contracts' `LaunchReference`), `SdkSeatReservation`. |
71
159
  | `types/session.ts` | `Question`, `QuestionOptions`, `ScoreMetadata`, `EventData`, `GameCompleteData`, `StartSessionResult`, `SubmitScoreResult`, `WordOptions`, `ReportWordData`, `ReportableWord` (re-exports `Word`). |
72
160
  | `types/word.ts` | `Word` + sub-interfaces (`WordSense`, `WordForm`, `Lookup`, `Synset`, `FormRepresentation`, `DynamicProp`, …) — Words Bank feature. |
73
161
  | `types/match.ts` | `MatchParticipantMember`, `MatchParticipant`, `MatchContext`, `MatchResultPayload`. |
74
162
  | `src/server-entry.ts` | `./server` subpath. Types (`GuestModule`, `Ctx`, `PeerInfo`, `BroadcastOptions`, `EndMatchPayload`, `CreateOptions`) plus `createBotDriver` from `src/bot-driver.ts`, its only runtime code. No imports from the browser SDK; safe for tooling that compiles the bundle on Node. |
163
+ | `src/multiplayer-entry.ts` | `./multiplayer` subpath. Re-exports `MultiplayerClient` and its types plus all of `@ksaa-nlp/gamehub-multiplayer-contracts`. Never imported by `main.ts` or `browser-entry.ts`. |
164
+ | `src/multiplayer-client.ts` | `MultiplayerClient`: the game-owned Colyseus connection, reconnect-token handling and recovery (§21ter). The only module importing `@colyseus/sdk` and the copied schemas (`#colyseus-schemas/*`). |
75
165
  | `src/server-dev-harness.ts` | `./server/dev` subpath. `runLocal(guest, opts)` returns a `LocalRoom` that simulates the colyseus host (`join`, `send`, `leave`, `advance`, etc.) and records every bridge call to `outbox`. Pure Node — does not import `isolated-vm` or anything browser. |
76
166
 
77
167
  ### 3.2 Singleton model
@@ -101,10 +191,13 @@ This is the only place in the package that does work on import. Module / npm con
101
191
  | `dist/src/main.js` | ESM entry. Pure on import. |
102
192
  | `dist/src/main.d.ts` | Public type surface. |
103
193
  | `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. |
194
+ | `dist/src/multiplayer-entry.js` | ESM `./multiplayer` subpath. Pure on import; resolves the optional peers `@colyseus/sdk` and `@colyseus/schema`. |
195
+ | `dist/vendor/gamehub-multiplayer-contracts/` | Build-time copy of the private contracts workspace's `index` (`.js`, `.d.ts`), resolved through the `#multiplayer-contracts` import map (§21ter). |
196
+ | `dist/vendor/colyseus-schemas/` | Build-time copy of the private schemas workspace's `clock`, `common`, `multiplayer` and `ugc` (`.js`, `.d.ts`), resolved through the `#colyseus-schemas/*` import map (§21ter). |
104
197
  | `dist/gamehub-sdk.js` | IIFE bundle for `<script>` tag use, target ES2020, no external deps. Includes `browser-entry.ts`. Marked `sideEffects: true`. |
105
198
  | `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/`. |
106
199
 
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.
200
+ `build:vendor` rebuilds `packages/gamehub-multiplayer-contracts` and `packages/colyseus-schemas` and copies their shipped modules into `dist/vendor/` (`scripts/vendor-workspace.mjs`); `build:tsc` runs it first. `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.
108
201
 
109
202
  ### 4.2 Package metadata
110
203
 
@@ -113,15 +206,18 @@ This is the only place in the package that does work on import. Module / npm con
113
206
  - `exports`:
114
207
  - `"."` → `./dist/src/main.js` (pure entry).
115
208
  - `"./browser"` → `./dist/src/browser-entry.js` (side-effectful entry).
209
+ - `"./multiplayer"` → `./dist/src/multiplayer-entry.js` (game-owned realtime connection, §21ter).
210
+ - `"./server"`, `"./server/dev"` → UGC server-bundle types and dev harness (§21bis).
116
211
  - `"./gamehub-sdk.js"` → `./dist/gamehub-sdk.js` (raw IIFE).
117
212
  - `"./package.json"` → `./package.json`.
118
213
  - `sideEffects`: `["./dist/src/browser-entry.js", "./dist/gamehub-sdk.js"]` — everything else is tree-shakeable.
119
214
  - `files`: only `dist/**/*`, `README.md`, `CHANGELOG.md`, `MIGRATION.md` are published.
120
- - `dependencies`: none.
121
- - `peerDependencies`: none.
122
- - `devDependencies`: `esbuild`, `typescript`.
215
+ - `dependencies`: none. Workspace contracts and schemas ship as copies under `dist/vendor/`.
216
+ - `peerDependencies`: `@colyseus/sdk` ^0.18.5 and `@colyseus/schema` ^5.0.36, both marked optional in `peerDependenciesMeta`. Only `./multiplayer` imports them; games that use it install `@colyseus/sdk`, which depends on `@colyseus/schema`, so one copy serves both the decoder and the copied state classes.
217
+ - `imports`: `#multiplayer-contracts` → `./dist/vendor/gamehub-multiplayer-contracts/index`, `#colyseus-schemas/*` → `./dist/vendor/colyseus-schemas/*` (`types` and `default`). The private workspace packages are never dependencies.
218
+ - `devDependencies`: the two peers (for building and testing the subpath), `esbuild`, `typescript`.
123
219
 
124
- The SDK has zero runtime dependencies. Adding one requires a deliberate decision and a major-version bump.
220
+ Adding a runtime dependency or another peer, or making a peer required, is a deliberate decision and a major-version bump (§20.4).
125
221
 
126
222
  ### 4.3 Target environments
127
223
 
@@ -180,6 +276,7 @@ The full taxonomy follows. It applies to **both** transports identically.
180
276
  | SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
181
277
  | SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
182
278
  | 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. |
279
+ | SDK → host | `GUEST_SCORE` | Fired by `submitScore` when no session can open for an unauthenticated player (§8.2), before it resolves `SESSION_START_FAILED`. Carries `{ score }`, the floored valid score; nothing is recorded. Unverified: hosts use it for display only (§9.1). |
183
280
  | SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
184
281
  | SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
185
282
  | SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
@@ -222,14 +319,6 @@ On the **native** transport there is no web origin: inbound `HostMessage.origin`
222
319
  - Empty string after trim → `null`.
223
320
  - Explicit `null` in the payload → `null`.
224
321
  - Non-string and non-null → ignored (field left as-is).
225
- - `multiplayer`:
226
- - Explicit `null` → `null`.
227
- - Object with a `reservation` object (string `name`, `sessionId`, `roomId` — the `SdkSeatReservation` shape) and a string `wsEndpoint` → only `wsEndpoint` is trimmed; the `reservation` object is stored as-is.
228
- - Optional `roomCode`, `role`, and `connectionScope` strings are copied only
229
- when non-empty and bounded. `connectionScope` lets a game partition its own
230
- reconnect storage by public embed and outer-host instance; the SDK neither
231
- stores nor interprets it.
232
- - Any other shape → ignored (field left as-is).
233
322
  - `sessionMode` accepts only `'authenticated'`, `'embed-guest'`,
234
323
  `'league-guest'`, or explicit `null`; every other value is ignored. The
235
324
  trusted host, not uploaded game code, selects this authority mode.
@@ -323,7 +412,7 @@ interface GameHubNativeHost {
323
412
  - 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`).
324
413
  - 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.
325
414
  - 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`).
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.
415
+ - Native hosts advertise no multiplayer capability. The SDK never proxies realtime traffic over the bridge (§19.1).
327
416
 
328
417
  ## 7. Authentication
329
418
 
@@ -395,6 +484,7 @@ On success, the SDK posts `SESSION_STARTED { token }` to the host.
395
484
  - 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
485
  - `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
486
  - Posts `SCORE_SUBMITTED` only for accepted outcomes. The telemetry contains lifecycle fields, never arbitrary `meta`.
487
+ - With no session and an unauthenticated player (no token, no league match, no trusted `embed-guest`/`authenticated` mode), posts `GUEST_SCORE { score: floor(score) }` when `score` is valid, then resolves `SESSION_START_FAILED` as before. Never with `meta`. The score is the game's own claim: a host may show or share it but must not record or reward it.
398
488
  - Every public score method resolves a result and never throws.
399
489
 
400
490
  ### 9.2 `submitMatchScore(score, meta?)`
@@ -564,8 +654,6 @@ interface SdkState {
564
654
  bootstrapTeamOneName: string | null;
565
655
  bootstrapTeamTwoName: string | null;
566
656
 
567
- // Multiplayer block (opaque to the SDK)
568
- bootstrapMultiplayer: BootstrapMultiplayer | null;
569
657
  bootstrapReceived: boolean;
570
658
 
571
659
  // Init lifecycle
@@ -631,7 +719,8 @@ bootstrap merge; subscriptions hold callbacks only in memory.
631
719
 
632
720
  | Method | Returns | Notes |
633
721
  | -------------------------------- | ---------------------------- | ------------------------------------------------------------------------------- |
634
- | `submitScore(score, meta?)` | `Promise<SubmitScoreResult>` | Auto-opens a session if needed. Never throws. |
722
+ | `submitScore(score, meta?)` | `Promise<SubmitScoreResult>` | Auto-opens a session if needed. Sends queued answers first. Never throws. |
723
+ | `recordAnswer(answer)` | `void` | Queues one answered question for the signed-in session; see 5.5.0 above. |
635
724
  | `submitMatchScore(score, meta?)` | `Promise<SubmitScoreResult>` | Requires `matchId`. Augments `meta` with `matchId/leagueId/gameId`. |
636
725
  | `submitMatchResult(result?)` | `Promise<SubmitScoreResult>` | Zero-score wrapper over `submitMatchScore`; payload goes to `meta.matchResult`. |
637
726
 
@@ -695,14 +784,6 @@ interface SdkSeatReservation {
695
784
  devMode?: boolean;
696
785
  }
697
786
 
698
- interface BootstrapMultiplayer {
699
- reservation: SdkSeatReservation;
700
- wsEndpoint: string;
701
- roomCode?: string;
702
- role?: string;
703
- connectionScope?: string;
704
- }
705
-
706
787
  interface GameSettings {
707
788
  readonly musicEnabled: boolean;
708
789
  }
@@ -721,7 +802,6 @@ interface BootstrapConfig {
721
802
  teamOneName?: string | null;
722
803
  teamTwoName?: string | null;
723
804
  profileId?: string | null;
724
- multiplayer?: BootstrapMultiplayer | null;
725
805
  }
726
806
 
727
807
  interface BootstrapData {
@@ -738,7 +818,6 @@ interface BootstrapData {
738
818
  teamOneName: string | null;
739
819
  teamTwoName: string | null;
740
820
  profileId: string | null;
741
- multiplayer: BootstrapMultiplayer | null;
742
821
  isBootstrapped: boolean;
743
822
  }
744
823
 
@@ -896,6 +975,7 @@ The SDK assumes the GameHub server exposes the following endpoints. When embedde
896
975
  | POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
897
976
  | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
898
977
  | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
978
+ | POST | `/sessions/answers` | Bearer (account session) | `{ token, answers }` | `{ success: true, data: { recorded } }`; the SDK ignores the response |
899
979
  | 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
980
  | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
901
981
  | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
@@ -929,20 +1009,20 @@ The SDK expects (but tolerates absence of) a `{ success, data, token?, error? }`
929
1009
 
930
1010
  These rules exist because of a real prior regression where transport-related cleanup deleted unrelated HTTP plumbing. They are tight on purpose.
931
1011
 
932
- ### 19.1 No realtime in the SDK
1012
+ ### 19.1 Realtime only in `./multiplayer`
933
1013
 
934
- - The SDK must not import any realtime client (`@colyseus/sdk`, `ws`, `socket.io-client`, …).
935
- - The SDK must not open a `WebSocket`, `EventSource`, or `RTCPeerConnection`.
936
- - The `bootstrapMultiplayer` field is opaque. The SDK validates the reservation,
937
- endpoint, and optional bounded room/role/scope strings; it does not parse or
938
- interpret them.
939
- - The server-clock helper (`attachServerClock`) belongs in `@ksaa-nlp/colyseus-schemas/clock`, not here.
1014
+ - The main entry, `./browser`, `./server`, `./server/dev` and the IIFE bundle must not import any realtime client (`@colyseus/sdk`, `@colyseus/schema`, `#colyseus-schemas/*`, `ws`, `socket.io-client`, …) and must not open a `WebSocket`, `EventSource`, or `RTCPeerConnection`.
1015
+ - `src/multiplayer-client.ts` is the only module that imports `@colyseus/sdk` and `#colyseus-schemas/*`; it is reachable only through `./multiplayer`. No other transport is added there.
1016
+ - Multiplayer launch context and reservations are validated as bounded opaque
1017
+ data by the main entry and consumed only by `MultiplayerClient`.
1018
+ - The server-clock helper (`attachServerClock`) is maintained in `@ksaa-nlp/colyseus-schemas/clock`; the SDK only ships its copy. `MultiplayerClient` attaches it and exposes `serverNow()`.
1019
+ - The copied schema modules are never edited or bundled: they import only each other, `@colyseus/schema` and (type-only) `@colyseus/sdk`.
940
1020
 
941
1021
  ### 19.2 HTTP plumbing is transport-agnostic
942
1022
 
943
1023
  - `submitMatchResult`, `getMatchContext`, `MatchContext`, and `MatchResultPayload` are **not** part of any realtime stack.
944
1024
  - A future cleanup that removes realtime support **must not** delete league-match HTTP code as collateral.
945
- - The match-context endpoint is plain HTTP and continues to work even with `bootstrap.multiplayer === null`.
1025
+ - The match-context endpoint is plain HTTP and continues to work without any multiplayer bootstrap context.
946
1026
 
947
1027
  ### 19.3 No DOM injection
948
1028
 
@@ -951,7 +1031,7 @@ These rules exist because of a real prior regression where transport-related cle
951
1031
 
952
1032
  ### 19.4 No storage
953
1033
 
954
- - The SDK must not call `localStorage`, `sessionStorage`, `IndexedDB`, or cookies.
1034
+ - The SDK must not call `localStorage`, `sessionStorage`, `IndexedDB`, or cookies. `MultiplayerClient` reads and writes reconnect tokens only through the `TokenStorage` object the game passes in; it never reaches for a global store.
955
1035
  - Tokens (auth and session) live in memory only; refresh resets them. Persistent identity is the host page's responsibility.
956
1036
 
957
1037
  ### 19.5 Singleton
@@ -972,11 +1052,11 @@ These rules exist because of a real prior regression where transport-related cle
972
1052
 
973
1053
  ### 20.3 Bundle budget
974
1054
 
975
- The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **52 KiB raw** and **12 KiB gzip**. SDK 4.3 deliberately raises the previous 44/10 KiB limits to include bounded lobby-state validation, typed host controls and independent subscriptions. Runtime dependencies remain empty; the distribution test checks the built and served bytes and both budgets.
1055
+ The IIFE bundle (`dist/gamehub-sdk.js`) is minified and must remain under **36 KiB raw** and **11 KiB gzip**. SDK 4.3 raised the earlier 44/10 KiB limits of the unminified bundle to 52/12 KiB for bounded lobby-state validation, typed host controls and independent subscriptions; 5.5.0's `recordAnswer` crossed them, and 5.5.1 minifies the bundle (about 28 KB raw / 9 KB gzip) and sets the current limits. Runtime dependencies remain empty; the distribution test checks the built and served bytes and both budgets.
976
1056
 
977
- ### 20.4 No runtime dependencies
1057
+ ### 20.4 Runtime dependencies
978
1058
 
979
- `package.json` `dependencies` and `peerDependencies` must remain empty. Adding either is a major-version event and requires updating §2 (non-goals) and §19 (boundary rules).
1059
+ `dependencies` must stay empty: the private `@ksaa-nlp/gamehub-multiplayer-contracts` and `@ksaa-nlp/colyseus-schemas` workspaces ship as build-time copies (§21ter), never as dependencies. `peerDependencies` contains only the optional realtime peers of `./multiplayer` (§4.2). Adding any dependency or other peer, or making a peer required, is a major-version event and requires updating §2 (non-goals) and §19 (boundary rules). The distribution test enforces this.
980
1060
 
981
1061
  ## 21. Testing acceptance criteria
982
1062
 
@@ -1041,8 +1121,8 @@ The SDK ships focused Node tests for transport trust-boundary behavior. Every ch
1041
1121
 
1042
1122
  ### 21.6 Boundary
1043
1123
 
1044
- - `grep -rn "@colyseus" src/ types/` returns only comment references (no import statements).
1045
- - `npm pack --dry-run` produces a tarball whose `peerDependencies` and `dependencies` are both empty/absent.
1124
+ - Built `main.js`, `browser-entry.js` and `server-entry.js` contain no import of `@colyseus/*` or `#colyseus-schemas/*`, and the IIFE bundle contains neither Colyseus nor `MultiplayerClient` (distribution test).
1125
+ - `package.json` `dependencies` is empty and both peers are optional (distribution test).
1046
1126
 
1047
1127
  ### 21.7 SDK Usage Intelligence Report synchronization
1048
1128
 
@@ -1071,6 +1151,11 @@ filters/CSV and fixtures are synchronized. Runtime aggregation excludes these
1071
1151
  local APIs. The example in `demos/game-settings/` is a reference game and
1072
1152
  host for manual testing of global/local mute and live preference updates.
1073
1153
 
1154
+ Version 5.5.0 adds `recordAnswer` (scanner version 8, Arabic label
1155
+ «الإجابات»). It is observed at runtime when `POST /api/sessions/answers` (or
1156
+ its authenticated-embed twin) accepts a batch for a valid session, whether or
1157
+ not the platform stores answers; answer values are never part of telemetry.
1158
+
1074
1159
  ## 21bis. UGC server bundle subpath
1075
1160
 
1076
1161
  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.
@@ -1131,10 +1216,9 @@ expect(room.outbox).toContainEqual({
1131
1216
 
1132
1217
  ## 22. Glossary
1133
1218
 
1134
- - **Bootstrap.** The set of context the host gives the iframe at load: slug, IDs, auth, multiplayer block, display strings.
1219
+ - **Bootstrap.** The set of context the host gives the iframe at load: slug, IDs, auth, multiplayer launch/lobby context, display strings.
1135
1220
  - **Session.** A server-issued token representing a single playthrough. Used to authenticate `submitScore`.
1136
1221
  - **League match.** A scheduled game between two participants tracked by GameHub's league system. Has its own session endpoint that allows guest submitters.
1137
- - **Multiplayer block.** The opaque `{ reservation, wsEndpoint }` pair the host provides for the game to open its own realtime connection, where `reservation` is the Colyseus seat-reservation (`SdkSeatReservation`).
1138
1222
  - **Host.** The GameHub-served page that frames the game in an iframe. Owns auth, matchmaking, and the bootstrap pipeline.
1139
1223
  - **Game.** The iframe-hosted application that consumes this SDK.
1140
1224
  - **Standalone.** A game loaded outside an iframe. `isInIframe()` returns false; the bootstrap pipeline is skipped.
@@ -1142,8 +1226,7 @@ expect(room.outbox).toContainEqual({
1142
1226
  ## Launch v2 (4.2.0)
1143
1227
 
1144
1228
  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()`
1229
+ Optional bootstrap `capabilities` and `multiplayerLaunch` carry the bound round. `requestMultiplayerLaunch()`
1147
1230
  is a no-argument, single-flight request to the trusted host for its already-bound
1148
1231
  round. It validates bounded replies and fences a changed launch context. It owns
1149
1232
  no socket or persistent storage. Old/native hosts do not advertise v2 and return
@@ -1153,15 +1236,15 @@ no socket or persistent storage. Old/native hosts do not advertise v2 and return
1153
1236
  bootstrap suppresses unrelated client-scored session creation; the host permits
1154
1237
  only the bound launch request and the backend rejects browser ownership of
1155
1238
  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.
1239
+ existing semantics. `MultiplayerClient` (`./multiplayer`, §21ter) owns Colyseus
1240
+ state, clock and recovery tokens.
1158
1241
 
1159
1242
  Server `EndMatchPayload` adds optional version 2, per-seat scores, winner seat IDs
1160
1243
  and bounded metadata. The v2 room requires the v2 result shape and enriches it
1161
1244
  with trusted provenance. `ctx.endMatch` is a proposal, not a saved acknowledgement.
1162
1245
  Legacy endMatch payloads remain valid in legacy rooms.
1163
1246
 
1164
- SDK_VERSION, npm version and served JS/map are 4.5.0. The distribution gate is
1247
+ SDK_VERSION, npm version and served JS/map are 5.0.0. The distribution gate is
1165
1248
  52 KiB raw / 12 KiB gzip (the raw increase covers v2 validation and game settings); runtime
1166
1249
  dependencies remain empty. Scanner version 3 includes requestMultiplayerLaunch,
1167
1250
  endMatch, seededPlayers and the static-only game-settings APIs; version-2 scans
@@ -1235,9 +1318,99 @@ and prohibit ordinary session creation/submission, even with a stale cached solo
1235
1318
  token. A loading round is a new pinned document with the existing launch contract;
1236
1319
  `requestMultiplayerLaunch()` semantics remain unchanged. In-flight lobby replies
1237
1320
  are fenced against a changed slug/launch. Hosts retain all storage and sockets
1238
- remain in the separate adapter.
1321
+ remain in `MultiplayerClient` (§21ter).
1239
1322
 
1240
1323
  SDK Usage scanner 4 includes both new APIs, with Arabic admin/filter/CSV support.
1241
1324
  Successful validated host lobby requests observe `requestMultiplayerSession`;
1242
1325
  `onMultiplayerSessionChange` is static-only because delivered state does not prove
1243
1326
  a subscription. Observations do not prove admission or a started round.
1327
+
1328
+ ## Legacy multiplayer block removed (5.0.0)
1329
+
1330
+ Breaking: `BootstrapMultiplayer`, `BootstrapConfig.multiplayer` and
1331
+ `BootstrapData.multiplayer` are removed. No GameHub host had populated the
1332
+ block since generic v1 multiplayer was retired; a `multiplayer` field sent by an
1333
+ older host is ignored. Games use `multiplayerLaunch`, `requestMultiplayerLaunch()`
1334
+ and `MultiplayerClient` from `./multiplayer` (§21ter; see
1335
+ [the multiplayer reference](../../specs/multiplayer.md)). `SdkSeatReservation`
1336
+ remains as the reserved-launch reservation type.
1337
+
1338
+ ## 21ter. Multiplayer subpath (5.0.0)
1339
+
1340
+ - **Native build consumer.** The sibling `@ksaa-nlp/gamehub-react-native-sdk`
1341
+ builds an unchanged source copy of `src/multiplayer-client.ts` and
1342
+ `types/{session,question,word,match,multiplayer-session}.ts` through its
1343
+ `scripts/copy-types.mjs`. These files are shared build inputs: changes must
1344
+ pass both this package's tests and `npm run test:sdk:native`. Changes to
1345
+ imports, runtime dependencies or platform assumptions also require
1346
+ `npm run test:sdk:native:metro` for iOS/Android. Keep the realtime core free
1347
+ of browser globals. Generated native `vendor/` and `dist/` copies are never
1348
+ edited; the published native package has no runtime dependency on this SDK.
1349
+ - **`@ksaa-nlp/gamehub-sdk/multiplayer`** exports `MultiplayerClient`,
1350
+ `ConnectionStatus`, `LaunchHost`, `MultiplayerSnapshot`, `TokenStorage` and
1351
+ re-exports every contract. The full API, storage and recovery contract is §10 of
1352
+ [the multiplayer reference](../../specs/multiplayer.md#10-game-adapter-ksaa-nlpgamehub-sdkmultiplayer).
1353
+ `MultiplayerClient` accepts any `LaunchHost` (an object with
1354
+ `requestMultiplayerLaunch()`), normally the `Sdk` itself.
1355
+ - **Contracts copy.** The private `@ksaa-nlp/gamehub-multiplayer-contracts`
1356
+ workspace holds the wire contracts. The SDK build rebuilds it and copies
1357
+ `index` into `dist/vendor/gamehub-multiplayer-contracts/`; every SDK module
1358
+ imports it as `#multiplayer-contracts`, and `./multiplayer` re-exports all of
1359
+ it. The copy must stay import-free. The SDK's own lobby and launch types take `BotLevel`, `SeatType`, `SessionPhase`,
1360
+ `ParticipantKind`, `LaunchReference` and both capability strings from it
1361
+ instead of redeclaring them; `createBotDriver`'s `BotLevel` and level list come
1362
+ from it too.
1363
+ - **Schema copy.** `@ksaa-nlp/colyseus-schemas` is a private workspace. The
1364
+ same `build:vendor` step rebuilds it and copies `clock`, `common`, `multiplayer` and `ugc`
1365
+ into `dist/vendor/colyseus-schemas/`; `multiplayer-client.ts` imports them as
1366
+ `#colyseus-schemas/clock` and `#colyseus-schemas/multiplayer`, and the
1367
+ `package.json` `imports` map resolves that path inside the SDK for both this
1368
+ build and consumers (TypeScript `moduleResolution` `node16`, `nodenext` or
1369
+ `bundler`, which `./multiplayer` already requires). The distribution test
1370
+ checks the copy is byte-identical to the schemas `dist/` minus source-map
1371
+ comments, imports only siblings, `@colyseus/schema` and `@colyseus/sdk`, and
1372
+ that nothing in `dist/` names either private package. A contracts or schema
1373
+ change therefore ships as an SDK release; the SDK has no runtime
1374
+ dependencies.
1375
+ - **Peers.** `@colyseus/sdk` ^0.18.5 and `@colyseus/schema` ^5.0.36 are optional
1376
+ peers. A game importing `./multiplayer` installs `@colyseus/sdk`, which brings
1377
+ the single `@colyseus/schema` copy that both the decoder and the copied
1378
+ classes use; solo games and script-tag users need neither. The IIFE bundle
1379
+ does not change.
1380
+
1381
+ **Usage report.** `MultiplayerClient` is feature `MultiplayerClient`, static-only
1382
+ (the game's own socket crosses no host boundary the report can observe).
1383
+ Scanner version 6 detects it through the `"gamehub.mp.v2"` reconnect-token
1384
+ namespace literal the class always builds, which survives minification and
1385
+ is tree-shaken with the class. A bare `MultiplayerClient` identifier is only `possible`. See
1386
+ [the usage report](../../specs/sdk-usage-report.md).
1387
+
1388
+ ## Party contract distribution (5.1.0)
1389
+
1390
+ The 5.1.0 release includes the updated vendored common schema constants
1391
+ (`PLATFORM_MESSAGES`) and `PartyGameResult` contract from the private workspaces.
1392
+ Package version, `SDK_VERSION`, the rebuilt IIFE and its served web copy report
1393
+ 5.1.0 together. No new SDK method or runtime dependency is introduced. Publish
1394
+ this SDK release with the party deployment; a local build is not an npm publish.
1395
+
1396
+ ## Ended lobby membership contract (5.2.0)
1397
+
1398
+ The vendored multiplayer contracts 1.3.0 add `SEAT_LEFT` to the exported error
1399
+ vocabulary, distinguishing ended membership from explicit `SEAT_REMOVED`.
1400
+ Hosts clear stale lobby membership and saved restoration state; a fresh join
1401
+ still follows the current room admission rules. This widens the error type on
1402
+ existing operations and introduces no SDK method, capability or usage-report
1403
+ feature. The existing lobby-control observation strategy remains unchanged.
1404
+ Package version, `SDK_VERSION` and served JS/map report 5.2.0 together.
1405
+
1406
+ ## Guest round score (5.3.0)
1407
+
1408
+ `submitScore` from an unauthenticated player on the standalone play page now
1409
+ posts `GUEST_SCORE { score }` (§6.1, §9.1) before resolving the unchanged
1410
+ `SESSION_START_FAILED`. The GameHub play page uses it to offer «شارك نتيجتك»
1411
+ to guests; nothing is stored. No method, public type or runtime dependency is
1412
+ added, and the usage report needs no new feature: a game still calls the
1413
+ tracked `submitScore`, and the host does not count `GUEST_SCORE` as a runtime
1414
+ observation, since a browser report must not fabricate a score call
1415
+ ([usage report §11.3](../../specs/sdk-usage-report.md)). Package version,
1416
+ `SDK_VERSION` and served JS/map report 5.3.0 together.