@ksaa-nlp/gamehub-react-native-sdk 0.0.0-stage → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +272 -2
  2. package/SPEC.md +265 -0
  3. package/dist/src/api-client.d.ts +7 -0
  4. package/dist/src/api-client.d.ts.map +1 -0
  5. package/dist/src/api-client.js +123 -0
  6. package/dist/src/api-client.js.map +1 -0
  7. package/dist/src/config.d.ts +15 -0
  8. package/dist/src/config.d.ts.map +1 -0
  9. package/dist/src/config.js +45 -0
  10. package/dist/src/config.js.map +1 -0
  11. package/dist/src/constants.d.ts +6 -0
  12. package/dist/src/constants.d.ts.map +1 -0
  13. package/dist/src/constants.js +6 -0
  14. package/dist/src/constants.js.map +1 -0
  15. package/dist/src/content.d.ts +7 -0
  16. package/dist/src/content.d.ts.map +1 -0
  17. package/dist/src/content.js +70 -0
  18. package/dist/src/content.js.map +1 -0
  19. package/dist/src/host-events.d.ts +7 -0
  20. package/dist/src/host-events.d.ts.map +1 -0
  21. package/dist/src/host-events.js +20 -0
  22. package/dist/src/host-events.js.map +1 -0
  23. package/dist/src/identity.d.ts +10 -0
  24. package/dist/src/identity.d.ts.map +1 -0
  25. package/dist/src/identity.js +27 -0
  26. package/dist/src/identity.js.map +1 -0
  27. package/dist/src/index.d.ts +6 -0
  28. package/dist/src/index.d.ts.map +1 -0
  29. package/dist/src/index.js +54 -0
  30. package/dist/src/index.js.map +1 -0
  31. package/dist/src/launch.d.ts +16 -0
  32. package/dist/src/launch.d.ts.map +1 -0
  33. package/dist/src/launch.js +115 -0
  34. package/dist/src/launch.js.map +1 -0
  35. package/dist/src/lobby-request.d.ts +4 -0
  36. package/dist/src/lobby-request.d.ts.map +1 -0
  37. package/dist/src/lobby-request.js +46 -0
  38. package/dist/src/lobby-request.js.map +1 -0
  39. package/dist/src/lobby.d.ts +33 -0
  40. package/dist/src/lobby.d.ts.map +1 -0
  41. package/dist/src/lobby.js +308 -0
  42. package/dist/src/lobby.js.map +1 -0
  43. package/dist/src/match-context.d.ts +10 -0
  44. package/dist/src/match-context.d.ts.map +1 -0
  45. package/dist/src/match-context.js +41 -0
  46. package/dist/src/match-context.js.map +1 -0
  47. package/dist/src/multiplayer-client.d.ts +27 -0
  48. package/dist/src/multiplayer-client.d.ts.map +1 -0
  49. package/dist/src/multiplayer-client.js +163 -0
  50. package/dist/src/multiplayer-client.js.map +1 -0
  51. package/dist/src/multiplayer-react.d.ts +4 -0
  52. package/dist/src/multiplayer-react.d.ts.map +1 -0
  53. package/dist/src/multiplayer-react.js +8 -0
  54. package/dist/src/multiplayer-react.js.map +1 -0
  55. package/dist/src/multiplayer-storage.d.ts +22 -0
  56. package/dist/src/multiplayer-storage.d.ts.map +1 -0
  57. package/dist/src/multiplayer-storage.js +65 -0
  58. package/dist/src/multiplayer-storage.js.map +1 -0
  59. package/dist/src/multiplayer-types.d.ts +54 -0
  60. package/dist/src/multiplayer-types.d.ts.map +1 -0
  61. package/dist/src/multiplayer-types.js +2 -0
  62. package/dist/src/multiplayer-types.js.map +1 -0
  63. package/dist/src/multiplayer.d.ts +5 -0
  64. package/dist/src/multiplayer.d.ts.map +1 -0
  65. package/dist/src/multiplayer.js +4 -0
  66. package/dist/src/multiplayer.js.map +1 -0
  67. package/dist/src/react.d.ts +11 -0
  68. package/dist/src/react.d.ts.map +1 -0
  69. package/dist/src/react.js +20 -0
  70. package/dist/src/react.js.map +1 -0
  71. package/dist/src/score.d.ts +9 -0
  72. package/dist/src/score.d.ts.map +1 -0
  73. package/dist/src/score.js +168 -0
  74. package/dist/src/score.js.map +1 -0
  75. package/dist/src/session-view.d.ts +4 -0
  76. package/dist/src/session-view.d.ts.map +1 -0
  77. package/dist/src/session-view.js +276 -0
  78. package/dist/src/session-view.js.map +1 -0
  79. package/dist/src/session.d.ts +10 -0
  80. package/dist/src/session.d.ts.map +1 -0
  81. package/dist/src/session.js +142 -0
  82. package/dist/src/session.js.map +1 -0
  83. package/dist/src/settings.d.ts +4 -0
  84. package/dist/src/settings.d.ts.map +1 -0
  85. package/dist/src/settings.js +40 -0
  86. package/dist/src/settings.js.map +1 -0
  87. package/dist/src/types.d.ts +125 -0
  88. package/dist/src/types.d.ts.map +1 -0
  89. package/dist/src/types.js +2 -0
  90. package/dist/src/types.js.map +1 -0
  91. package/dist/src/utils.d.ts +5 -0
  92. package/dist/src/utils.d.ts.map +1 -0
  93. package/dist/src/utils.js +16 -0
  94. package/dist/src/utils.js.map +1 -0
  95. package/dist/vendor/colyseus-schemas/clock.d.ts +15 -0
  96. package/dist/vendor/colyseus-schemas/clock.js +67 -0
  97. package/dist/vendor/colyseus-schemas/common.d.ts +35 -0
  98. package/dist/vendor/colyseus-schemas/common.js +15 -0
  99. package/dist/vendor/colyseus-schemas/multiplayer.d.ts +8 -0
  100. package/dist/vendor/colyseus-schemas/multiplayer.js +26 -0
  101. package/dist/vendor/colyseus-schemas/ugc.d.ts +53 -0
  102. package/dist/vendor/colyseus-schemas/ugc.js +124 -0
  103. package/dist/vendor/gamehub-multiplayer-contracts/index.d.ts +200 -0
  104. package/dist/vendor/gamehub-multiplayer-contracts/index.js +289 -0
  105. package/dist/vendor/match.d.ts +37 -0
  106. package/dist/vendor/match.d.ts.map +1 -0
  107. package/dist/vendor/match.js +2 -0
  108. package/dist/vendor/match.js.map +1 -0
  109. package/dist/vendor/multiplayer-client.d.ts +50 -0
  110. package/dist/vendor/multiplayer-client.d.ts.map +1 -0
  111. package/dist/vendor/multiplayer-client.js +268 -0
  112. package/dist/vendor/multiplayer-client.js.map +1 -0
  113. package/dist/vendor/multiplayer-session.d.ts +82 -0
  114. package/dist/vendor/multiplayer-session.d.ts.map +1 -0
  115. package/dist/vendor/multiplayer-session.js +2 -0
  116. package/dist/vendor/multiplayer-session.js.map +1 -0
  117. package/dist/vendor/question.d.ts +35 -0
  118. package/dist/vendor/question.d.ts.map +1 -0
  119. package/dist/vendor/question.js +20 -0
  120. package/dist/vendor/question.js.map +1 -0
  121. package/dist/vendor/session.d.ts +158 -0
  122. package/dist/vendor/session.d.ts.map +1 -0
  123. package/dist/vendor/session.js +2 -0
  124. package/dist/vendor/session.js.map +1 -0
  125. package/dist/vendor/word.d.ts +147 -0
  126. package/dist/vendor/word.d.ts.map +1 -0
  127. package/dist/vendor/word.js +15 -0
  128. package/dist/vendor/word.js.map +1 -0
  129. package/package.json +90 -4
package/README.md CHANGED
@@ -1,3 +1,273 @@
1
- # Temporary Holding Version
1
+ # GameHub SDK for React Native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ GameHub sessions, scores, questions, words and league matches for **native React
4
+ Native games**. Supports Expo and bare React Native without native modules.
5
+ This is separate from the browser SDK and the GameHub Expo host application.
6
+
7
+ ```sh
8
+ npm install @ksaa-nlp/gamehub-react-native-sdk
9
+ ```
10
+
11
+ Inside this monorepo, add `"@ksaa-nlp/gamehub-react-native-sdk": "*"` to the
12
+ consumer workspace dependencies and install from the repository root.
13
+
14
+ ```ts
15
+ import { createSdk } from '@ksaa-nlp/gamehub-react-native-sdk';
16
+
17
+ // Read these values from your app's environment and authentication state.
18
+ const sdk = createSdk({
19
+ apiBaseUrl: config.gameHubApiUrl, // e.g. https://your-gamehub.example/api
20
+ gameSlug: 'my-native-game',
21
+ authToken: accountToken,
22
+ profileId: selectedProfileId, // optional question/word profile
23
+ onHostEvent(event) {
24
+ if (event.type === 'REQUEST_CLOSE') navigation.goBack();
25
+ if (event.type === 'GAME_COMPLETE') showResults(event.payload);
26
+ },
27
+ });
28
+
29
+ const questions = await sdk.getQuestions({ difficulty: 'easy', limit: 10 });
30
+ const words = await sdk.getWords({ limit: 10 });
31
+
32
+ // Start when play begins, so server-measured duration includes gameplay.
33
+ const session = await sdk.startSession();
34
+ if (!session.success) showSessionError(session.error);
35
+
36
+ const outcome = await sdk.submitScore(100, { attempts: 3 });
37
+ if (outcome.success) showAcceptedScore(outcome);
38
+ else if (!outcome.terminal) showRetryOrError(outcome);
39
+
40
+ // Call on logout, account change, or token replacement.
41
+ sdk.setAuthToken(nextAccountToken ?? null);
42
+ ```
43
+
44
+ Create one stable SDK instance per game context. It owns in-memory session state;
45
+ recreating it discards retries. `submitScore` can start a session automatically,
46
+ but explicitly starting when gameplay begins records a useful server duration.
47
+ An accepted or terminally rejected score clears the session for the next round.
48
+ Unknown or retriable results keep the original payload: retry with the same score
49
+ and metadata. There is no automatic retry and changed submissions are refused.
50
+
51
+ React integration is optional:
52
+
53
+ ```tsx
54
+ import { GameHubProvider, useGameHubSdk, useGameHubSettings }
55
+ from '@ksaa-nlp/gamehub-react-native-sdk/react';
56
+
57
+ function NativeGame() {
58
+ const sdk = useGameHubSdk();
59
+ const { musicEnabled } = useGameHubSettings();
60
+ // Apply musicEnabled to your own audio engine.
61
+ return <GameScreen onExit={() => sdk.requestClose()} musicEnabled={musicEnabled} />;
62
+ }
63
+
64
+ function GameRoot() {
65
+ return <GameHubProvider sdk={sdk}><NativeGame /></GameHubProvider>;
66
+ }
67
+
68
+ // Synchronize this from the account preferences managed by your application.
69
+ sdk.setSettings({ musicEnabled: currentUser.gamePreferences.musicEnabled });
70
+ ```
71
+
72
+ `getSettings()` returns a stable immutable snapshot; music defaults off.
73
+ `onSettingsChange` emits immediately and returns an unsubscribe function.
74
+ The provider requires an existing SDK instance and does not start requests.
75
+ React 18.2 or 19 is required only for the `/react` entry. Core imports do not
76
+ load React, React Native, Expo, a WebView, or any realtime transport.
77
+
78
+ League games configure `leagueId`, `gameId` and optionally `matchId` on creation.
79
+ Use `getMatchContext()`, `submitMatchScore(score, meta)` or
80
+ `submitMatchResult(result)` as appropriate; server admission rules still apply.
81
+ Sessions and content use the same HTTP contracts as the browser SDK. Shared
82
+ contract types (`Question`, `Word`, `ScoreMetadata`, `SubmitScoreResult`,
83
+ `MatchContext`, etc.) are exported from this package.
84
+
85
+ The API URL is required and includes `/api` and any deployment prefix. HTTPS is
86
+ required; HTTP loopback URLs are permitted for local development. On a physical
87
+ device, use a reachable HTTPS development server. Auth tokens are kept in memory;
88
+ your app owns login and secure persistence. Requests time out after 15 seconds
89
+ by default (`requestTimeoutMs` overrides this). A custom `fetch` can be injected.
90
+ Auth changes invalidate pending results, sessions, and cached league context.
91
+
92
+ `notifyComplete`, `requestClose`, `reportQuestion`, `reportWord` and `logEvent`
93
+ send typed events to `onHostEvent`. Your application supplies navigation, result
94
+ screens, report forms and analytics handlers. These methods do nothing without
95
+ that callback. They do not open platform UI or send reports by themselves.
96
+
97
+ Existing web games inside a native WebView continue to use
98
+ `@ksaa-nlp/gamehub-sdk`. Version 1.1 adds optional native multiplayer below.
99
+ The [SPEC](./SPEC.md) defines precise behavior and usage-report boundaries.
100
+
101
+ From the monorepo root:
102
+
103
+ ```sh
104
+ npm run build:sdk:native
105
+ npm run test:sdk:native
106
+ npm run test:sdk:native:metro # Expo 54 iOS/Android export and React resolution smoke
107
+ npm -w @ksaa-nlp/gamehub-react-native-sdk run typecheck
108
+ npm -w @ksaa-nlp/gamehub-react-native-sdk run typecheck:consumer
109
+ npm -w @ksaa-nlp/gamehub-react-native-sdk pack --dry-run
110
+ ```
111
+
112
+ The root `npm run build` builds deployed services. Build and test this SDK
113
+ separately with the native commands above.
114
+
115
+ Builds copy the canonical HTTP type files from `packages/gamehub-sdk/types/`
116
+ unchanged, then compile them locally. Generated `vendor/` and `dist/` files must
117
+ not be edited. Published consumers need no sibling workspace packages.
118
+
119
+
120
+ ## Native multiplayer
121
+
122
+ Install the realtime peers only when the game uses multiplayer:
123
+
124
+ ```sh
125
+ npm install @colyseus/sdk @colyseus/schema
126
+ ```
127
+
128
+ For Expo 54/Metro, select the browser fallback for `ws` in your existing
129
+ `metro.config.js`. React Native supplies `globalThis.WebSocket`; the Node `ws`
130
+ implementation must stay out of the mobile bundle. Keep your existing Expo
131
+ configuration and add this before exporting it:
132
+
133
+ ```js
134
+ const previousResolver = config.resolver.resolveRequest;
135
+ config.resolver.resolveRequest = (context, moduleName, platform) => {
136
+ if (moduleName === 'ws' && (platform === 'ios' || platform === 'android')) {
137
+ return context.resolveRequest({
138
+ ...context,
139
+ unstable_enablePackageExports: false,
140
+ mainFields: ['react-native', 'browser', 'main'],
141
+ }, moduleName, platform);
142
+ }
143
+ return previousResolver
144
+ ? previousResolver(context, moduleName, platform)
145
+ : context.resolveRequest(context, moduleName, platform);
146
+ };
147
+ ```
148
+
149
+ This uses Metro's [per-package resolver configuration](https://metrobundler.dev/docs/package-exports/#example-custom-resolver).
150
+ The iOS/Android smoke check exercises this setup and checks for one React and
151
+ one schema runtime. In monorepos, keep Expo's
152
+ `experiments.autolinkingModuleResolution` enabled so hooks resolve to the app's
153
+ React. Native multiplayer type consumers also include `ES2021.WeakRef` for
154
+ the canonical schema declarations, alongside React Native globals.
155
+
156
+ Configure the SDK with a stable host identity and a secure ID generator from
157
+ your app. Keep one SDK instance per game and identity context.
158
+
159
+ ```ts
160
+ import { createSdk } from '@ksaa-nlp/gamehub-react-native-sdk';
161
+ import { MultiplayerClient } from '@ksaa-nlp/gamehub-react-native-sdk/multiplayer';
162
+ import { AppState } from 'react-native';
163
+
164
+ const sdk = createSdk({
165
+ apiBaseUrl: config.gameHubApiUrl,
166
+ gameSlug: 'my-native-game',
167
+ authToken: accountToken,
168
+ multiplayer: {
169
+ hostInstanceId: persistedHostId,
170
+ createId: () => secureRandomUuid(), // supplied by your app
171
+ // sessionId: persistedSessionId, // restore with an explicit read
172
+ // resumeToken: secureGuestCredential, // existing guest join policy only
173
+ },
174
+ });
175
+
176
+ const unsubscribe = sdk.onMultiplayerSessionChange(({ session, error }) => {
177
+ renderLobby(session, error);
178
+ });
179
+ const created = await sdk.requestMultiplayerSession({ operation: 'create', type: 'player' });
180
+ // Or join: { operation: 'join', roomCode: '123456', displayName: 'Player', type: 'player' }
181
+ if (created.success) {
182
+ await sdk.requestMultiplayerSession({ operation: 'ready', ready: true });
183
+ // The host starts when the required players are ready.
184
+ await sdk.requestMultiplayerSession({ operation: 'start' });
185
+ }
186
+
187
+ const launch = sdk.getMultiplayerLaunch();
188
+ if (launch) {
189
+ const client = new MultiplayerClient(sdk, launch, {
190
+ appState: AppState,
191
+ storage: reconnectStorage, // optional sync/async getItem/setItem/removeItem
192
+ });
193
+ const stop = client.subscribe((snapshot) => {
194
+ const counter = snapshot.state?.game.get('counter');
195
+ if (counter) renderCounter(JSON.parse(counter.json));
196
+ renderConnection(snapshot.status, snapshot.error);
197
+ });
198
+ await client.connect();
199
+ client.send('increment', { amount: 1 }); // your approved UGC action protocol
200
+ // On exit: stop(); await client.leave();
201
+ }
202
+ // On leaving the lobby: await sdk.requestMultiplayerSession({ operation: 'leave' });
203
+ // On unmount: unsubscribe();
204
+ ```
205
+
206
+ Applications own lobby UI, secure identity/credential persistence and login.
207
+ Account tokens are sent as Bearer credentials; guest resume tokens only enable
208
+ the backend's existing join/resume flow. Store the session ID if the app needs
209
+ to restore a lobby after restart, then request `{operation:'read'}`. No guest
210
+ creation permission is granted. Server code remains authored through the browser
211
+ SDK's `/server` and `/server/dev` entries and runs only on the server.
212
+
213
+ `requestMultiplayerLaunch()` exposes reserved, recoverable and terminal outcomes;
214
+ the client consumes reservations automatically. The SDK validates game, host,
215
+ seat and round binding. Solo/league scoring is blocked while multiplayer owns
216
+ the context. Since 1.1.1, a failed initial create/join with no bound session
217
+ releases that ownership, so your app can explicitly start solo/league play
218
+ without calling `leave`. Create retries keep their idempotency key. Failed
219
+ operations on a bound session or pending restoration keep ownership.
220
+ Only a server-acknowledged `ctx.endMatch` completes multiplayer.
221
+ Native and browser clients use the same schema/actions/results and approved
222
+ UGC server package. Their installed game protocol must match; the SDK does not
223
+ perform automatic version negotiation or native OTA updates.
224
+
225
+ `./react` exports `useGameHubMultiplayerSession()` for lobby UI inside
226
+ `GameHubProvider`. The optional `./multiplayer/react` entry exports
227
+ `useMultiplayerSnapshot(client)` for an existing round client. Hooks unsubscribe
228
+ on unmount; create a new round client after rematch. Returning to an active app
229
+ resumes the core connection without leaving on background. Recovery remains
230
+ bounded by the backend's grace window. Async storage failures allow memory-only
231
+ play and are visible as `storageAvailable:false`.
232
+
233
+ Main and `./react` imports remain free of realtime transports. The published
234
+ package includes build-time copies of the unchanged browser core and shared
235
+ contracts/schemas; it does not depend on the browser SDK at runtime.
236
+
237
+ ## Source responsibilities and browser SDK comparison
238
+
239
+ The native SDK implements the browser SDK's game-facing HTTP, settings, lobby,
240
+ launch and realtime capabilities. Its app supplies configuration and account
241
+ tokens explicitly; host events call `onHostEvent`. These callbacks require app
242
+ handlers to show UI, submit reports or record analytics. Native settings are
243
+ synchronized by the app. Browser-only bootstrap and server tools are not native
244
+ client responsibilities.
245
+
246
+ Every file in `packages/gamehub-sdk/src/` maps as follows:
247
+
248
+ | Browser source | Native implementation or platform difference |
249
+ | --- | --- |
250
+ | `main.ts` | `index.ts` composes an isolated client; native contracts live in `types.ts`. Native adds token/settings setters and direct lobby/launch getters. |
251
+ | `api-client.ts` | `api-client.ts` calls HTTP directly with Bearer/resume headers, timeouts and response validation. |
252
+ | `session.ts` | `session.ts` owns sessions/submissions; `score.ts` validates/normalizes scores; `content.ts` fetches questions/words. |
253
+ | `match-context.ts` | `match-context.ts` owns cached league-match reads. |
254
+ | `settings.ts` | `settings.ts` owns immutable preferences and subscriptions; the app calls `setSettings`. |
255
+ | `state.ts` | State is owned by individual native factories/classes; `identity.ts` owns token generations. No shared singleton. |
256
+ | `constants.ts` | `constants.ts` owns native version/defaults/limits. Browser message prefixes/timeouts are unnecessary. |
257
+ | `utils.ts` | `utils.ts` provides native JSON helpers. Browser detection, URL query discovery and browser logging helpers are not carried over. |
258
+ | `init.ts` | `config.ts` validates explicit app configuration; `identity.ts` supports token changes. No automatic bootstrap/session start or browser pause/resume globals. |
259
+ | `bridge.ts` | HTTP goes through `api-client.ts`; one-way host signals go through `host-events.ts`. No browser handshake, bootstrap snapshot or correlated host API proxy. |
260
+ | `transport.ts` | Direct native fetch and app callbacks replace iframe postMessage/WebView transport. The native SDK does not wrap a WebView. |
261
+ | `browser-entry.ts` | Intentionally absent: native apps import the factory; there is no script-tag/global singleton or `isInIframe` API. |
262
+ | `multiplayer-session.ts` | `lobby.ts` performs native HTTP session operations/polling; `lobby-request.ts` validates inputs and `session-view.ts` validates responses. Native returns the shared HTTP `SessionView`, rather than the browser host's lobby projection. |
263
+ | `multiplayer.ts` | `launch.ts` performs bound HTTP reservations with stale-context fencing. Native `multiplayer.ts` is the optional realtime package entry. |
264
+ | `multiplayer-client.ts` | Copied unchanged at build time into generated `vendor/`; native `multiplayer-client.ts` adapts app lifecycle and `multiplayer-storage.ts` adapts async storage. `multiplayer-types.ts` owns native interfaces. |
265
+ | `multiplayer-entry.ts` | Native `multiplayer.ts` exports the adapter and shared wire contracts; realtime peers remain optional. |
266
+ | `server-entry.ts` | Intentionally stays in the browser SDK's `/server` entry for authoring UGC server code. |
267
+ | `server-dev-harness.ts` | Intentionally stays in the browser SDK's `/server/dev` entry for local server tests. |
268
+ | `bot-driver.ts` | Intentionally stays in the server authoring SDK. Native clients can manage bot seats and receive their state; bot moves execute on the server. |
269
+
270
+ `react.ts` additionally owns the native provider and SDK/settings/lobby hooks;
271
+ `multiplayer-react.ts` owns the realtime snapshot hook. Neither duplicates the
272
+ realtime core. The complete native file ownership contract is in
273
+ [SPEC.md — Source ownership](./SPEC.md#source-ownership).
package/SPEC.md ADDED
@@ -0,0 +1,265 @@
1
+ # GameHub React Native SDK
2
+
3
+ Version: 1.1.1. Status: authoritative.
4
+
5
+ ## Purpose and boundaries
6
+
7
+ `@ksaa-nlp/gamehub-react-native-sdk` is a sibling npm workspace for games
8
+ implemented directly in React Native. It uses the existing GameHub HTTP APIs;
9
+ it is independent of the browser SDK singleton and of the Expo application.
10
+ It does not wrap a WebView, implement login/navigation, or grant guest
11
+ admission. Optional native multiplayer uses the existing HTTP admission and
12
+ Colyseus round protocol; server authoring remains in the browser SDK server
13
+ entries. The main and `./react` entries stay transport-agnostic. Existing web games keep using
14
+ `@ksaa-nlp/gamehub-sdk`, including its native WebView bridge.
15
+
16
+ ## Configuration and public API
17
+
18
+ `createSdk(options): NativeSdk` constructs an isolated client without starting
19
+ network activity. Required options are `apiBaseUrl` (absolute HTTP(S) API root,
20
+ including `/api`, with an optional deployment prefix) and nonempty `gameSlug`.
21
+ No production origin is embedded. URLs containing credentials, query or hash
22
+ are rejected. HTTPS is required except HTTP loopback development hosts.
23
+ Optional options: `authToken`, `gameId`, `leagueId`, `matchId`, `profileId`,
24
+ `settings: {musicEnabled:boolean}`, `fetch` (injectable Fetch-compatible
25
+ transport), `requestTimeoutMs` (positive finite, default 15000), and `onHostEvent`.
26
+ `gameId` is required with `leagueId`; `leagueId` is required with `matchId`.
27
+
28
+ Public methods:
29
+
30
+ - `version`, `getGameSlug()`, `isInitialized()`, `isAuthenticated()`,
31
+ `hasActiveSession()`, `ready(): Promise<boolean>` (configuration is synchronous).
32
+ - `setAuthToken(token: string | null)` clears sessions and cached match context
33
+ when changed. In-flight work captures its identity epoch and cannot publish
34
+ state, events, or successful results into a newer identity. Apps call this
35
+ on logout, login, or token replacement; tokens remain in memory only.
36
+ - `startSession()`, `submitScore(score, meta?)`, `submitMatchScore(score, meta?)`,
37
+ `submitMatchResult(result?)`, `getMatchContext()` follow the browser SDK's
38
+ HTTP result types and endpoint selection. Each path segment is encoded.
39
+ - `getQuestions(options?)` and `getWords(options?)` use explicit profile options,
40
+ then configured profile. Limits default/cap at 100 questions and 50 words, must be finite positive
41
+ integers; invalid options/errors return `[]`. Questions normalize numeric
42
+ answers to strings. Failed match-context reads return `null`.
43
+ - `getSettings()`, `setSettings(settings)`, `onSettingsChange(listener)` manage
44
+ immutable in-memory snapshots. Subscriptions emit immediately and return an
45
+ unsubscribe function. Music defaults off. The caller synchronizes account
46
+ preferences; this package does not persist or fetch them automatically.
47
+ - `notifyComplete(data?)`, `requestClose()`, `reportQuestion(data)`,
48
+ `reportWord(data)`, `logEvent(name, data?)` invoke optional `onHostEvent` with
49
+ `{type,payload}`. Types are `GAME_COMPLETE`, `REQUEST_CLOSE`, `QUESTION_REPORT`,
50
+ `WORD_REPORT`, `EVENT`, `SESSION_STARTED`, `SCORE_SUBMITTED`. No callback means
51
+ no-op. Callback/listener exceptions cannot change an HTTP operation's result.
52
+
53
+ The `./react` subpath exports `GameHubProvider` (`sdk` and `children` props),
54
+ `useGameHubSdk()` and `useGameHubSettings()`. Hooks require the provider and
55
+ throw a clear error otherwise. The provider accepts an existing stable SDK
56
+ instance; it does not own its authentication or issue requests. Settings use
57
+ React's external-store subscription mechanism and unsubscribe on unmount.
58
+ React is an optional peer, required for React hook subpaths; the main entry does
59
+ not import React or React Native. No native modules/config plugins are needed.
60
+
61
+ ## HTTP and session lifecycle
62
+
63
+ All requests attach the current account Bearer token if supplied, parse the
64
+ GameHub envelope, and have a bounded timeout. Non-JSON, malformed success or
65
+ transport failures must never be treated as accepted scores. HTTP failure
66
+ status overrides an inconsistent `success:true` envelope. Auth errors are
67
+ returned to the caller; the app owns login/revocation handling.
68
+
69
+ Standalone session start requires an account token. League session paths use
70
+ configured IDs and rely on backend admission. Concurrent starts are deduplicated.
71
+ Score validation follows browser bounds: finite 0..10,000,000 score (floored),
72
+ JSON object metadata, depth <=5, <=200 keys, <=100 characters per key, <=2048
73
+ characters per string, <=100 entries per array, <=32 KiB UTF-8, no prototype
74
+ keys or non-JSON values. Attempts normalize/cap at 1,000,000. Client timing is
75
+ never authoritative. Validation works without `TextEncoder` or Node globals.
76
+
77
+ Submissions are bound to the session plus normalized score/attempts/client
78
+ metadata. Concurrent equivalent submissions share a request; changed payloads
79
+ are rejected. Unknown/retriable outcomes retain the exact original request
80
+ for retry and never automatically retry. Accepted and terminal rejected
81
+ outcomes clear the session, permitting sequential rounds. Successful account
82
+ submissions require `status:accepted`, `terminal:true`, a session ID, and finite
83
+ server timing; legacy league `accepted:true,timeTaken` is also supported.
84
+ Results reuse the existing SDK discriminated union, including retry-after
85
+ details. Explicit identity changes invalidate all previous work.
86
+
87
+ ## Source ownership
88
+
89
+ `src/index.ts` composes per-instance feature owners and exports the existing
90
+ public factory, version and types. It contains no HTTP, scoring, content,
91
+ settings or persistence implementation. Internal modules are not new package
92
+ subpaths or public APIs. The responsibility refactor preserves the 1.1.0
93
+ behavior and API; it does not add browser bootstrap or server-authoring APIs.
94
+
95
+ | Source | Responsibility |
96
+ | --- | --- |
97
+ | `config.ts` | Validate the fixed API URL, game/league/profile context and HTTP options. |
98
+ | `constants.ts` | Package version, request timeout and content limits. |
99
+ | `identity.ts` | In-memory account token and generation used to fence stale work. |
100
+ | `api-client.ts` | Fetch, auth/resume headers, bounded timeout, envelope parsing and identity fencing. |
101
+ | `session.ts` | Solo/league session lifecycle, submissions, deduplication, exact retries and terminal cleanup. |
102
+ | `score.ts` | Pure score/metadata validation, canonical payloads and result normalization. |
103
+ | `match-context.ts` | Cached, deduplicated league-match context reads and invalidation. |
104
+ | `content.ts` | Question/word queries, profiles, limits and answer normalization. |
105
+ | `settings.ts` | Immutable preference snapshots and subscriptions. |
106
+ | `host-events.ts` | Isolated callbacks for completion, close, reports, analytics and session/score events. |
107
+ | `lobby.ts` | Multiplayer session operations, ownership, revisions, immutable snapshots and polling. |
108
+ | `lobby-request.ts` | Validate allowed lobby operations and caller input fields. |
109
+ | `session-view.ts` | Validate and project server session, roster, round and result views. |
110
+ | `launch.ts` | Deduplicate and validate reservations against the current launch/generation. |
111
+ | `multiplayer.ts` | Optional realtime public entry and re-exports. |
112
+ | `multiplayer-client.ts` | Native round/lifecycle adapter around the unchanged generated realtime core. |
113
+ | `multiplayer-storage.ts` | Async token hydration, synchronous core cache, serialized persistence and disposal fencing. |
114
+ | `multiplayer-types.ts` | Native realtime, storage and lifecycle interfaces. |
115
+ | `react.ts` | Optional provider and SDK/settings/lobby hooks. |
116
+ | `multiplayer-react.ts` | Optional realtime snapshot hook. |
117
+ | `types.ts` | Native main-entry contracts and canonical HTTP type re-exports. |
118
+ | `utils.ts` | Internal JSON-object, nonnegative-integer and recursive-freeze helpers. |
119
+
120
+ Each feature owns its mutable state inside its factory or instance. The
121
+ composition root resets session and match state on identity changes or lobby
122
+ ownership; lobby changes invalidate bound realtime adapters. The browser core
123
+ continues to own sockets, schema synchronization, clock and reconnect behavior.
124
+
125
+ ## Distribution and shared contracts
126
+
127
+ ESM JavaScript plus declarations under `dist/`, with `react-native` conditions
128
+ and ordinary import/default exports. Node test tooling is development-only.
129
+ `build:types` copies the unchanged `session`, `question`, `word`, and
130
+ `match` TypeScript contract files from the browser SDK into generated `vendor/`;
131
+ the build compiles them into the package. Never hand-edit generated copies.
132
+ There is no runtime dependency on the browser SDK, private workspaces, Node,
133
+ DOM, or Expo. The optional realtime entries require the external peers
134
+ `@colyseus/sdk` and `@colyseus/schema`; React remains external. One root lockfile is used.
135
+ The native HTTP envelope exports `ApiResponse` (`data:unknown`), `ApiError`, and
136
+ `ApiErrorDetails`. Browser-only `ApiRequestOptions` is not exported. Declarations
137
+ must typecheck in a React Native consumer using ES2020 and React Native globals,
138
+ without DOM or `skipLibCheck`. The optional multiplayer entry additionally uses
139
+ `ES2021.WeakRef`, required by the canonical schema declarations.
140
+
141
+ SDK Usage Intelligence currently scans uploaded HTML/JavaScript game artifacts.
142
+ This package adds no public API to the browser SDK and no native artifact
143
+ ingestion to that report. Existing HTTP-backed feature IDs are observed by the
144
+ backend unchanged; native configuration, native lobby/realtime adapters, React hooks, and local host events
145
+ are outside that report's static inventory. No native usage coverage is claimed.
146
+
147
+ ## Acceptance requirements
148
+
149
+ - REQ-001: New workspace builds, exposes main and React entries with declarations,
150
+ packs independently, and resolves in an Expo 54/Metro consumer. Main imports
151
+ without DOM, React, Node runtime modules, or browser singleton dependencies.
152
+ - REQ-002: Explicit validated configuration, isolated clients, bounded HTTP,
153
+ Bearer auth, token changes and stale-request suppression are covered by tests.
154
+ - REQ-003: Session deduplication, valid score results, terminal cleanup, exact
155
+ retries/conflicts, invalid metadata, and sequential rounds have executable tests.
156
+ - REQ-004: Content/profile and league endpoint selection, numeric answers,
157
+ settings snapshots/subscriptions, host events, and React provider/hooks have tests.
158
+ - REQ-005: README examples, package specification, workspace/build/lockfile wiring
159
+ and report coverage boundaries are documented; existing SDK tests still pass.
160
+
161
+ ## Implementation plan
162
+
163
+ 1. Add workspace metadata, native client, and generated shared type build.
164
+ 2. Add optional React provider/hooks and package usage documentation.
165
+ 3. Wire root builds and lockfile; document native/report boundaries.
166
+ 4. Run native SDK and existing SDK tests, typecheck, pack inspection and Metro
167
+ consumer bundling; obtain independent code/security review and fix findings.
168
+
169
+
170
+ ## Native multiplayer (1.1.0)
171
+
172
+ The acceptance contract and implementation plan for this extension are in
173
+ [React Native SDK UGC multiplayer](../../specs/react-native-sdk-multiplayer.md).
174
+ The shared backend protocol is [multiplayer v2](../../specs/multiplayer.md).
175
+
176
+ Optional `multiplayer` options contain `hostInstanceId` (1..160 base64url-style
177
+ ID characters), `createId():string` (app-supplied secure ID generation), optional
178
+ `resumeToken` (43..128 base64url characters), optional `sessionId` for restoring
179
+ an existing context with `read`, and `pollIntervalMs` (1000..60000, default 2500).
180
+ The SDK never generates weak credentials. Configuration performs no network
181
+ activity. Account Bearer and guest `x-gamehub-resume` credentials use existing
182
+ backend authorization; guest creation does not bypass account-only policy.
183
+ Apps persist their identity, session ID and credentials.
184
+
185
+ Main entry APIs:
186
+
187
+ - `requestMultiplayerSession(request)` accepts create, join, ready, read, start,
188
+ leave, rematch, add-bot and remove-bot operations. It returns
189
+ `NativeMultiplayerSessionResult`. SDK supplies game, host, profile, create key,
190
+ revision and round bindings; callers cannot override them.
191
+ - `getMultiplayerSession()` returns a stable immutable
192
+ `NativeMultiplayerSessionState` containing `{session:SessionView|null,busy,error,
193
+ disconnected}`. `onMultiplayerSessionChange(listener)` immediately emits that
194
+ snapshot, isolates callback errors and returns an unsubscribe function.
195
+ - `getMultiplayerLaunch()` returns the current validated `LaunchReference` or
196
+ null. `requestMultiplayerLaunch()` returns the shared `LaunchOutcome` union,
197
+ including reserved, recoverable and terminal variants.
198
+ - `./react` adds `useGameHubMultiplayerSession()`, using the existing provider
199
+ and React external-store subscription mechanism.
200
+
201
+ Omitted multiplayer configuration returns `PROTOCOL_UNSUPPORTED` without a
202
+ request. Equivalent concurrent operations deduplicate; conflicting work returns
203
+ `BUSY`. Create retries retain their idempotency key; successful leave rotates it.
204
+ While the first create/join is pending, multiplayer owns the context. If that
205
+ request fails without binding a session (including malformed responses,
206
+ transport errors or timeouts), ownership is released before the idle snapshot
207
+ is published. Callers can explicitly start solo/league play without calling
208
+ leave; create retries still retain their key. A bound session or pending
209
+ restoration keeps ownership after failed reads, mutations or leave requests.
210
+ Stale requests cannot release a newer identity's ownership.
211
+ New create/join operations are refused while a session is active or restoration
212
+ is pending. Session views validate version, game, roster, IDs, revisions and
213
+ bound round/seat/host launch references. Responses cannot regress either session
214
+ or round revision. Only successful `{left:true}` acknowledges leave.
215
+
216
+ All operations POST to the existing `/multiplayer/sessions`, `/join` or
217
+ `/:sessionId/:operation` routes beneath `apiBaseUrl`. Polling reads run only
218
+ while subscribed and bound to a session, with no overlapping reads. Last
219
+ unsubscribe, leave and authentication changes stop polling. Explicit reads work
220
+ without subscriptions. Malformed responses and HTTP/transport/timeout failures
221
+ remain typed failures. SDK identity changes fence pending lobby, reservation,
222
+ solo-session and score responses and clear lobby/launch state. Multiplayer
223
+ ownership blocks ordinary solo and league score submissions, including cached
224
+ solo tokens; multiplayer completion requires server-acknowledged `ctx.endMatch`.
225
+
226
+ `./multiplayer` exports `MultiplayerClient`, `MultiplayerSnapshot`,
227
+ `ConnectionStatus`, `LaunchHost`, `MultiplayerClientOptions`, `TokenStorage`,
228
+ `AppStateSource` and the shared wire contracts. Constructor:
229
+ `new MultiplayerClient(host, launch, {storage?, appState?, clientFactory?})`.
230
+ The native SDK is a compatible launch host. The client exposes `connect()`,
231
+ `subscribe(listener)`, `getSnapshot()`, `send(type,payload)`, `serverNow()` and
232
+ `leave()`. Each client belongs to one round; create another after rematch.
233
+ Host changes invalidate old clients and remove reconnect credentials. The
234
+ unchanged browser core owns reservation consumption, synchronization, clock and
235
+ bounded reconnect behavior. Game state uses canonical schema values:
236
+ `state.game.get(key)?.json` contains a JSON string.
237
+
238
+ Storage supplies synchronous or asynchronous `getItem`, `setItem`, and
239
+ `removeItem`. Hydration precedes connection and persistence is serialized so
240
+ leave/logout removal wins over queued writes. Storage errors allow memory-only
241
+ play and set `storageAvailable:false`. Explicit leave removes credentials and
242
+ closes late sockets. `appState` structurally accepts React Native `AppState`:
243
+ `addEventListener('change', listener):{remove():void}`. Returning to `active`
244
+ calls the core's connect method; backgrounding does not leave a seat or add
245
+ another retry loop. Leave/context invalidation removes lifecycle listeners.
246
+ Recovery is limited by the server grace window.
247
+
248
+ `./multiplayer/react` exports `useMultiplayerSnapshot(client)`, with stable
249
+ snapshots and unmount cleanup. Consumers own lobby/game UI and secure storage.
250
+ The native action/state protocol must match the selected approved UGC package;
251
+ automatic version negotiation, arbitrary custom server messages and native OTA
252
+ updates are outside this change.
253
+
254
+ Builds generate an unchanged source copy of browser `multiplayer-client.ts`,
255
+ copy HTTP/lobby types and exact compiled contracts/schema modules. Generated
256
+ `vendor/` and `dist/` are never hand-edited. Only realtime entries import
257
+ Colyseus. Published packages contain all copies and require no private sibling
258
+ workspace at runtime. Expo 54 iOS/Android Metro smoke covers lobby and realtime
259
+ hooks with one React runtime and one schema runtime.
260
+ For the installed Colyseus peer, consumers configure Metro's `ws` resolution
261
+ to use legacy browser/main fields on iOS/Android, as shown in the README. Native
262
+ WebSocket handles transport; Node's `ws/lib` modules must not enter the bundle.
263
+ The smoke check uses a generated standalone Expo consumer, extends the mobile
264
+ workspace's Metro configuration and enables Expo autolinking, without changing
265
+ the mobile application's configuration or release identity.
@@ -0,0 +1,7 @@
1
+ import type { ApiResponse } from './types.js';
2
+ import type { NativeConfig } from './config.js';
3
+ import type { NativeIdentity } from './identity.js';
4
+ /** Direct native HTTP transport: bounded requests, envelopes and identity fencing. */
5
+ export declare function createApiClient(config: NativeConfig, identity: NativeIdentity): (path: string, generation: number, body?: unknown, resumeToken?: string) => Promise<ApiResponse>;
6
+ export type ApiRequest = ReturnType<typeof createApiClient>;
7
+ //# sourceMappingURL=api-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-client.d.ts","sourceRoot":"","sources":["../../src/api-client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD,sFAAsF;AACtF,wBAAgB,eAAe,CAC7B,MAAM,EAAE,YAAY,EACpB,QAAQ,EAAE,cAAc,UAIhB,MAAM,cACA,MAAM,SACX,OAAO,gBACA,MAAM,KACnB,OAAO,CAAC,WAAW,CAAC,CAsHxB;AACD,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC"}