@ksaa-nlp/gamehub-sdk 3.11.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -7
- package/SPEC.md +90 -31
- package/dist/gamehub-sdk.js +344 -74
- package/dist/gamehub-sdk.js.map +3 -3
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +92 -15
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/constants.js.map +1 -1
- package/dist/src/init.js +2 -2
- package/dist/src/init.js.map +1 -1
- package/dist/src/main.d.ts +2 -2
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js.map +1 -1
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +299 -68
- package/dist/src/session.js.map +1 -1
- package/dist/src/state.d.ts +12 -1
- package/dist/src/state.d.ts.map +1 -1
- package/dist/src/state.js +2 -0
- package/dist/src/state.js.map +1 -1
- package/dist/types/api.d.ts +11 -3
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/session.d.ts +35 -6
- package/dist/types/session.d.ts.map +1 -1
- package/package.json +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,
|
|
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
|
|
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
|
-
|
|
109
|
+
attempts: 4,
|
|
109
110
|
custom: { combo: 7 },
|
|
110
111
|
});
|
|
111
112
|
|
|
112
113
|
if (result.success) {
|
|
113
|
-
console.log('accepted:', result.
|
|
114
|
+
console.log('accepted:', result.sessionId, 'timeTaken:', result.timeTaken);
|
|
115
|
+
} else if (result.terminal) {
|
|
116
|
+
console.error('playthrough rejected:', result.code, result.error);
|
|
117
|
+
} else if (result.status === 'retriable' || result.retriable) {
|
|
118
|
+
// Retry the same score and metadata. The SDK retains the original token and
|
|
119
|
+
// exact request body until the server returns a terminal result.
|
|
120
|
+
await sdk.submitScore(score, {
|
|
121
|
+
level: 3,
|
|
122
|
+
attempts: 4,
|
|
123
|
+
custom: { combo: 7 },
|
|
124
|
+
});
|
|
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.
|
|
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
|
|
|
@@ -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; // '
|
|
296
|
+
sdk.version; // '4.0.0'
|
|
277
297
|
sdk.ready(); // Promise<boolean>
|
|
278
298
|
sdk.isInitialized(); // boolean
|
|
279
299
|
sdk.isAuthenticated(); // boolean
|
package/SPEC.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# GameHub SDK — Specification
|
|
2
2
|
|
|
3
|
-
Version:
|
|
3
|
+
Version: 4.0.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.
|
|
@@ -24,7 +24,7 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
|
|
|
24
24
|
|
|
25
25
|
- Discover the API base URL, the active game slug, and the league/match context from the iframe environment.
|
|
26
26
|
- Exchange a small set of `postMessage` envelopes with the host page (bootstrap, auth, ready, init, command).
|
|
27
|
-
- Hold
|
|
27
|
+
- 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
28
|
- Submit scores (`submitScore`, `submitMatchScore`) and league-match results (`submitMatchResult`).
|
|
29
29
|
- Fetch questions (`getQuestions`) and words (`getWords`).
|
|
30
30
|
- Request the host's report dialog for a question (`reportQuestion`) or word (`reportWord`).
|
|
@@ -100,6 +100,7 @@ This is the only place in the package that does work on import. Module / npm con
|
|
|
100
100
|
| `dist/src/main.d.ts` | Public type surface. |
|
|
101
101
|
| `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
102
|
| `dist/gamehub-sdk.js` | IIFE bundle for `<script>` tag use, target ES2020, no external deps. Includes `browser-entry.ts`. Marked `sideEffects: true`. |
|
|
103
|
+
| `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
104
|
|
|
104
105
|
`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
106
|
|
|
@@ -176,7 +177,7 @@ The full taxonomy follows. It applies to **both** transports identically.
|
|
|
176
177
|
| host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
|
|
177
178
|
| SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
|
|
178
179
|
| 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 }
|
|
180
|
+
| 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
181
|
| SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
|
|
181
182
|
| SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
|
|
182
183
|
| SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
|
|
@@ -264,7 +265,7 @@ Protocol details:
|
|
|
264
265
|
- The host attaches authority from **its own** context. For authenticated
|
|
265
266
|
external embeds this is an opaque embed credential held only in outer-host
|
|
266
267
|
memory; it is never added to bootstrap or an `API_REQUEST`.
|
|
267
|
-
- `API_RESPONSE.ok
|
|
268
|
+
- `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
269
|
- 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
270
|
- `messageId` is `'api_' + Date.now() + '_' + <seq>`, where `<seq>` is a monotonic counter so concurrent proxied calls (e.g. session start + questions) never collide.
|
|
270
271
|
|
|
@@ -290,7 +291,7 @@ interface GameHubNativeHost {
|
|
|
290
291
|
- The native app implements `postMessage` (typically forwarding to its WebView message channel — e.g. `flutter_inappwebview`'s `callHandler`).
|
|
291
292
|
- 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
293
|
- 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`).
|
|
294
|
+
- 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
295
|
- 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
296
|
|
|
296
297
|
## 7. Authentication
|
|
@@ -334,7 +335,7 @@ If the host posts `SET_AUTH` mid-session, the new token is used for subsequent r
|
|
|
334
335
|
|
|
335
336
|
### 8.3 Idempotency
|
|
336
337
|
|
|
337
|
-
Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-circuit to `{ success: true, token }`. Concurrent callers share `state.sessionStartPromise`.
|
|
338
|
+
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
339
|
|
|
339
340
|
### 8.4 Session start triggers
|
|
340
341
|
|
|
@@ -355,10 +356,15 @@ On success, the SDK posts `SESSION_STARTED { token }` to the host.
|
|
|
355
356
|
|
|
356
357
|
- Awaits `ensureInitialized()`.
|
|
357
358
|
- If no session, opens one (or awaits the in-flight start).
|
|
358
|
-
- Validates: `score` must be
|
|
359
|
+
- 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
360
|
- POSTs to `/sessions/submit` with `{ token, score, meta }`.
|
|
360
|
-
-
|
|
361
|
-
-
|
|
361
|
+
- 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.
|
|
362
|
+
- 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.
|
|
363
|
+
- 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.
|
|
364
|
+
- 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.
|
|
365
|
+
- `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`.
|
|
366
|
+
- Posts `SCORE_SUBMITTED` only for accepted outcomes. The telemetry contains lifecycle fields, never arbitrary `meta`.
|
|
367
|
+
- Every public score method resolves a result and never throws.
|
|
362
368
|
|
|
363
369
|
### 9.2 `submitMatchScore(score, meta?)`
|
|
364
370
|
|
|
@@ -538,6 +544,12 @@ interface SdkState {
|
|
|
538
544
|
bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;
|
|
539
545
|
parentOrigin: string | null;
|
|
540
546
|
sessionStartPromise: Promise<StartSessionResult> | null;
|
|
547
|
+
submissionPromise: Promise<SubmitScoreResult> | null;
|
|
548
|
+
pendingSubmission: {
|
|
549
|
+
token: string;
|
|
550
|
+
canonicalPayload: string;
|
|
551
|
+
body: { token: string; score: number; meta: Record<string, unknown> };
|
|
552
|
+
} | null;
|
|
541
553
|
|
|
542
554
|
// League match (HTTP)
|
|
543
555
|
matchContext: MatchContext | null;
|
|
@@ -549,7 +561,8 @@ interface SdkState {
|
|
|
549
561
|
|
|
550
562
|
- `apiBase` is set exactly once, by `detectEnvironment()`, before any HTTP request. It is never mutated afterwards.
|
|
551
563
|
- `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
|
|
564
|
+
- 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.
|
|
565
|
+
- `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
566
|
- `matchContext` is set at most once. Stale match context across renavigations is the host's problem (refresh resets the SDK).
|
|
554
567
|
- All `*Promise` fields are cleared when their underlying operation settles (success or failure).
|
|
555
568
|
|
|
@@ -700,12 +713,41 @@ interface StartSessionResult {
|
|
|
700
713
|
error?: string;
|
|
701
714
|
}
|
|
702
715
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
716
|
+
type SubmitScoreResult =
|
|
717
|
+
| {
|
|
718
|
+
success: true;
|
|
719
|
+
status: 'accepted';
|
|
720
|
+
terminal: true;
|
|
721
|
+
sessionId: string;
|
|
722
|
+
serverDurationMs: number;
|
|
723
|
+
timeTaken: number;
|
|
724
|
+
replayed?: true;
|
|
725
|
+
}
|
|
726
|
+
| {
|
|
727
|
+
success: false;
|
|
728
|
+
status: 'rejected';
|
|
729
|
+
terminal: true;
|
|
730
|
+
code: string;
|
|
731
|
+
error: string;
|
|
732
|
+
sessionStatus?: string;
|
|
733
|
+
}
|
|
734
|
+
| {
|
|
735
|
+
success: false;
|
|
736
|
+
status: 'retriable';
|
|
737
|
+
terminal: false;
|
|
738
|
+
code: 'SUBMISSION_IN_PROGRESS' | 'RATE_LIMITED';
|
|
739
|
+
error: string;
|
|
740
|
+
retryAfterMs?: number;
|
|
741
|
+
sessionStatus?: string;
|
|
742
|
+
}
|
|
743
|
+
| {
|
|
744
|
+
success: false;
|
|
745
|
+
status: 'failed';
|
|
746
|
+
terminal: false;
|
|
747
|
+
code: string;
|
|
748
|
+
error: string;
|
|
749
|
+
retriable: boolean;
|
|
750
|
+
};
|
|
709
751
|
|
|
710
752
|
interface GameCompleteData {
|
|
711
753
|
score?: number;
|
|
@@ -778,7 +820,15 @@ interface ApiResponse {
|
|
|
778
820
|
success: boolean;
|
|
779
821
|
data?: any;
|
|
780
822
|
token?: string;
|
|
781
|
-
error?: {
|
|
823
|
+
error?: {
|
|
824
|
+
code?: string;
|
|
825
|
+
message?: string;
|
|
826
|
+
details?: {
|
|
827
|
+
terminal?: boolean;
|
|
828
|
+
sessionStatus?: string;
|
|
829
|
+
retryAfterMs?: number;
|
|
830
|
+
};
|
|
831
|
+
};
|
|
782
832
|
}
|
|
783
833
|
|
|
784
834
|
interface ApiRequestOptions {
|
|
@@ -793,14 +843,14 @@ interface ApiRequestOptions {
|
|
|
793
843
|
|
|
794
844
|
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
845
|
|
|
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 }`
|
|
846
|
+
| Method | Path | Auth | Request body | Successful response shape |
|
|
847
|
+
| ------ | ----------------------------------------------- | ---------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
848
|
+
| POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
|
|
849
|
+
| POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
|
|
850
|
+
| POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
|
|
851
|
+
| 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 |
|
|
852
|
+
| GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
|
|
853
|
+
| GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
|
|
804
854
|
|
|
805
855
|
### 16.1 Response envelope
|
|
806
856
|
|
|
@@ -808,14 +858,14 @@ The SDK expects (but tolerates absence of) a `{ success, data, token?, error? }`
|
|
|
808
858
|
|
|
809
859
|
### 16.2 Failure surface
|
|
810
860
|
|
|
811
|
-
-
|
|
861
|
+
- 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
862
|
- `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
863
|
- 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
864
|
|
|
815
865
|
## 17. Error handling philosophy
|
|
816
866
|
|
|
817
867
|
- **Never throw to consumers.** Every public method returns either a typed success/failure result, or the degraded value (`null` / `[]`).
|
|
818
|
-
- **
|
|
868
|
+
- **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
869
|
- **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
870
|
- **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
871
|
- **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 +924,7 @@ These rules exist because of a real prior regression where transport-related cle
|
|
|
874
924
|
|
|
875
925
|
### 20.3 Bundle budget
|
|
876
926
|
|
|
877
|
-
The IIFE bundle (`dist/gamehub-sdk.js`)
|
|
927
|
+
The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **40 KB raw** and **10 KB 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. Current 4.0.0 size: **38,130 bytes raw / 8,570 bytes gzip**. Further growth requires a deliberate release review.
|
|
878
928
|
|
|
879
929
|
### 20.4 No runtime dependencies
|
|
880
930
|
|
|
@@ -919,8 +969,11 @@ The SDK ships focused Node tests for transport trust-boundary behavior. Every ch
|
|
|
919
969
|
### 21.4 Score submission
|
|
920
970
|
|
|
921
971
|
- `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
|
-
-
|
|
923
|
-
-
|
|
972
|
+
- 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.
|
|
973
|
+
- 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`.
|
|
974
|
+
- Two sequential accepted rounds in one document create and submit distinct session tokens.
|
|
975
|
+
- Concurrent canonical-identical calls issue one host request; a different concurrent payload resolves `CONCURRENT_SUBMISSION_CONFLICT` locally.
|
|
976
|
+
- `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
977
|
- In public embed mode, the game still emits `/sessions/start` and
|
|
925
978
|
`/sessions/submit`; the host binds and rewrites those requests for guest or
|
|
926
979
|
authenticated play. The SDK never creates or stores the embed guest ID,
|
|
@@ -930,7 +983,7 @@ The SDK ships focused Node tests for transport trust-boundary behavior. Every ch
|
|
|
930
983
|
|
|
931
984
|
- 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
985
|
- 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.
|
|
986
|
+
- 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
987
|
|
|
935
988
|
### 21.5 League-match path
|
|
936
989
|
|
|
@@ -957,6 +1010,12 @@ admin contract/UI/CSV, automated tests, and both package specifications. A
|
|
|
957
1010
|
method that cannot cross an observable host or server boundary must be
|
|
958
1011
|
explicitly classified as static-only.
|
|
959
1012
|
|
|
1013
|
+
Version 4.0.0 changes the lifecycle/result contract of the existing
|
|
1014
|
+
`startSession` and `submitScore` capabilities but adds no public method, alias,
|
|
1015
|
+
or capability. Their existing Usage Intelligence feature IDs and accepted-only
|
|
1016
|
+
server-operation observation remain authoritative; no scanner/report inventory
|
|
1017
|
+
version change is required for this release.
|
|
1018
|
+
|
|
960
1019
|
## 21bis. UGC server bundle subpath
|
|
961
1020
|
|
|
962
1021
|
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.
|