@ksaa-nlp/gamehub-sdk 4.2.0 → 4.3.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 CHANGED
@@ -423,3 +423,36 @@ state, clock and recovery lifecycle. The [Take Twenty-One starter](../../example
423
423
  contains a complete authoring/build/upload example. V1 bootstrap is unchanged;
424
424
  unsupported/native hosts do not advertise v2. Server-authoritative v2 rounds use
425
425
  ctx.endMatch version 2 instead of browser submitScore/submitMatchResult.
426
+
427
+ ## Create and join inside your game (SDK 4.3)
428
+
429
+ Declare `lobbyUi: "game"` in `gamehub.multiplayer.json`, then disable the game's
430
+ platform-lobby setting. Wait for bootstrap and implement the menu using typed
431
+ host controls. Hosts retain authentication and session ownership.
432
+
433
+ ```ts
434
+ await sdk.ready();
435
+ const off = sdk.onMultiplayerSessionChange(({ session, busy, error }) => {
436
+ // Render roster, ready/start controls and errors. Disable operations while busy.
437
+ });
438
+ await sdk.requestMultiplayerSession({ operation: 'create', type: 'player' });
439
+ // In another browser:
440
+ await sdk.requestMultiplayerSession({
441
+ operation: 'join',
442
+ roomCode: '123456',
443
+ displayName: 'Player',
444
+ type: 'player',
445
+ });
446
+ await sdk.requestMultiplayerSession({ operation: 'ready', ready: true });
447
+ // Current host only; all minimum human/player and readiness rules still apply.
448
+ await sdk.requestMultiplayerSession({ operation: 'start' });
449
+ off();
450
+ ```
451
+
452
+ Use `multiplayerEntry` to prefill invitation code and spectator intent. Public
453
+ session snapshots contain invitation URLs, limits, roster and current round
454
+ phase. Rematch availability follows terminal round phases, not only eventual
455
+ session retirement. Start transitions to a newly mounted pinned game document;
456
+ read `multiplayerLaunch` there and connect the multiplayer adapter. Lobby menus
457
+ cannot start/submit ordinary client scores. See the starter for ready/start,
458
+ bots, leave and rematch controls.
package/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 4.2.0
3
+ Version: 4.3.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.
@@ -62,7 +62,7 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
62
62
  | `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`, `getWords`. |
63
63
  | `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
64
64
  | `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
65
- | `src/settings.ts` | Settings snapshots, validated merge and isolated subscriptions. |
65
+ | `src/settings.ts` | Settings snapshots, validated merge and isolated subscriptions. |
66
66
  | `src/state.ts` | `SdkState` interface + the singleton `state` object. All mutable state lives here. |
67
67
  | `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`, `WORDS_LIMIT_CAP`. |
68
68
  | `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
@@ -665,10 +665,10 @@ Two modes:
665
665
 
666
666
  ### 14.7a Game settings
667
667
 
668
- | Method | Returns | Notes |
669
- | --- | --- | --- |
670
- | `getSettings()` | `GameSettings` | Detached effective snapshot; default music off. |
671
- | `onSettingsChange(listener)` | `() => void` | Immediate snapshot, then changes; unsubscribe on game teardown. |
668
+ | Method | Returns | Notes |
669
+ | ---------------------------- | -------------- | --------------------------------------------------------------- |
670
+ | `getSettings()` | `GameSettings` | Detached effective snapshot; default music off. |
671
+ | `onSettingsChange(listener)` | `() => void` | Immediate snapshot, then changes; unsubscribe on game teardown. |
672
672
 
673
673
  ### 14.7 Read-only context
674
674
 
@@ -972,7 +972,7 @@ These rules exist because of a real prior regression where transport-related cle
972
972
 
973
973
  ### 20.3 Bundle budget
974
974
 
975
- The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **44 KiB raw** and **10 KiB gzip**, the latter being the figure that matters most on the wire. The raw budget was historically 25 KB; native transport and the reliable multi-round lifecycle deliberately exceed that historical target. SDK 4.2.0 combines account music settings and multiplayer v2: **43,567 bytes raw / 9,804 bytes gzip**. The merged features deliberately raise the raw limit from 42 KiB to 44 KiB while retaining the 10 KiB gzip limit. Further growth requires a deliberate release review.
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.
976
976
 
977
977
  ### 20.4 No runtime dependencies
978
978
 
@@ -1161,8 +1161,8 @@ and bounded metadata. The v2 room requires the v2 result shape and enriches it
1161
1161
  with trusted provenance. `ctx.endMatch` is a proposal, not a saved acknowledgement.
1162
1162
  Legacy endMatch payloads remain valid in legacy rooms.
1163
1163
 
1164
- SDK_VERSION, npm version and served JS/map are 4.2.0. The distribution gate is
1165
- 44 KiB raw / 10 KiB gzip (the raw increase covers v2 validation and game settings); runtime
1164
+ SDK_VERSION, npm version and served JS/map are 4.3.0. The distribution gate is
1165
+ 52 KiB raw / 12 KiB gzip (the raw increase covers v2 validation and game settings); runtime
1166
1166
  dependencies remain empty. Scanner version 3 includes requestMultiplayerLaunch,
1167
1167
  endMatch, seededPlayers and the static-only game-settings APIs; version-2 scans
1168
1168
  are stale after rebasing onto the game-settings release. A launch request
@@ -1172,3 +1172,39 @@ observation is not successful admission; see the
1172
1172
  ## Seeded participants (4.2.0)
1173
1173
 
1174
1174
  `SeededPlayer` adds optional `kind: human|bot`, `seatId` and `peerId`. Missing kind means human for legacy hosts. V2 always supplies these fields; userId/seatId/peerId are the same opaque stable seat ID, never a bot/account credential. Bots do not connect or receive `onJoin`; the UGC bundle owns their legal moves using normal state/rules and `ctx.setTimeout`. All roster players, including bots, belong in endMatch scores. No realtime dependency is introduced. SDK Usage scanner 3 represents the widened data capability as `seededPlayers`: static identifiers are possible evidence; a trusted first UGC round-start acknowledgement confirms roster delivery. It does not prove a game consumed the field or that its bot algorithm acted. See the report specification.
1175
+
1176
+ ## Lobby control v2 (4.3.0)
1177
+
1178
+ The optional capability `multiplayer.lobby.v2` enables game-owned lobby UI.
1179
+ `requestMultiplayerSession(request: MultiplayerSessionRequest)` sends the typed
1180
+ discriminated request to the host's POST `/multiplayer/session` bridge and returns
1181
+ `{success:true,data:MultiplayerLobbyState}` or `{success:false,error:{code,message,
1182
+ retryable}}`. Operations and their fields are defined in
1183
+ `types/multiplayer-session.ts`: create (type/passcode), join (code/name/type/
1184
+ passcode), ready (boolean), remove-bot (seatId), read/start/leave/rematch/add-bot.
1185
+ There are no caller-supplied game, session, host, profile, key or revision fields.
1186
+ The host binds these and the server enforces its normal admission/authority.
1187
+ Native/legacy hosts without the capability return `PROTOCOL_UNSUPPORTED`.
1188
+
1189
+ `onMultiplayerSessionChange(listener)` returns an unsubscribe function and
1190
+ immediately emits a detached snapshot, then trusted host pushes and successful
1191
+ request results. Callback exceptions are isolated and registrations unsubscribe
1192
+ independently. SDK validates bounded fields and copies only public roster, limits,
1193
+ phase/reason, invitation URLs and errors, never host credentials or URLs used for
1194
+ content/reservations. Invalid snapshots are ignored. `getBootstrap()` includes
1195
+ `multiplayerSession` (empty when absent) and `multiplayerEntry` (null or trusted
1196
+ initial create/join intent, code, seat type). New host pushes use
1197
+ `GAMEHUB_SDK_MULTIPLAYER_SESSION` and retain direct-parent/origin pinning.
1198
+
1199
+ Before a round exists, the bootstrap uses `mode:multiplayer_lobby` and null
1200
+ `multiplayerLaunch`. Both lobby capability and a launch suppress auth exchange
1201
+ and prohibit ordinary session creation/submission, even with a stale cached solo
1202
+ token. A loading round is a new pinned document with the existing launch contract;
1203
+ `requestMultiplayerLaunch()` semantics remain unchanged. In-flight lobby replies
1204
+ are fenced against a changed slug/launch. Hosts retain all storage and sockets
1205
+ remain in the separate adapter.
1206
+
1207
+ SDK Usage scanner 4 includes both new APIs, with Arabic admin/filter/CSV support.
1208
+ Successful validated host lobby requests observe `requestMultiplayerSession`;
1209
+ `onMultiplayerSessionChange` is static-only because delivered state does not prove
1210
+ a subscription. Observations do not prove admission or a started round.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "4.2.0";
4
+ var SDK_VERSION = "4.3.0";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
7
  var HOST_API_TIMEOUT_MS = 15e3;
@@ -10,6 +10,7 @@
10
10
 
11
11
  // src/state.ts
12
12
  var state = {
13
+ multiplayerEntry: null,
13
14
  gameSettings: { musicEnabled: false },
14
15
  settingsListeners: /* @__PURE__ */ new Set(),
15
16
  bootstrapLaunch: null,
@@ -45,6 +46,170 @@
45
46
  matchContextPromise: null
46
47
  };
47
48
 
49
+ // src/multiplayer-session.ts
50
+ var listeners = /* @__PURE__ */ new Set();
51
+ var empty = {
52
+ session: null,
53
+ busy: false,
54
+ error: null,
55
+ disconnected: false
56
+ };
57
+ var current = empty;
58
+ var id = (value) => typeof value === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(value);
59
+ function parseLobbyState(value) {
60
+ if (!value || typeof value !== "object") return null;
61
+ const v = value;
62
+ if (typeof v.busy !== "boolean" || typeof v.disconnected !== "boolean")
63
+ return null;
64
+ const error2 = v.error;
65
+ if (error2 !== null && (!error2 || !id(error2.code) || typeof error2.message !== "string" || error2.message.length > 1e3 || typeof error2.retryable !== "boolean"))
66
+ return null;
67
+ const s = v.session;
68
+ if (s !== null) {
69
+ if (!s || ![s.multiplayerSessionId, s.hostSeatId, s.ownSeatId].every(id) || typeof s.gameSlug !== "string" || !/^[a-z0-9-]{1,100}$/.test(s.gameSlug) || !/^\d{6}$/.test(s.roomCode) || !["waiting", "in_round", "completed", "closed"].includes(s.phase) || !Number.isSafeInteger(s.revision) || s.revision < 0 || typeof s.rematchAllowed !== "boolean" || !Array.isArray(s.seats) || s.seats.length > 272)
70
+ return null;
71
+ for (const url of [s.invitationUrl, s.spectatorInvitationUrl]) {
72
+ if (url !== void 0 && (typeof url !== "string" || url.length > 2048 || !/^https?:\/\//.test(url)))
73
+ return null;
74
+ }
75
+ const p = s.playerPolicy;
76
+ if (!p || ![
77
+ p.minPlayers,
78
+ p.maxPlayers,
79
+ p.minHumanPlayers,
80
+ p.maxBots,
81
+ p.maxSpectators
82
+ ].every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 256) || p.minPlayers < 1 || p.minHumanPlayers < 1 || p.maxPlayers < p.minPlayers || p.minHumanPlayers > p.maxPlayers || p.maxBots > p.maxPlayers - p.minHumanPlayers || p.maxSpectators > 16)
83
+ return null;
84
+ if (!s.seats.every(
85
+ (seat) => seat && id(seat.seatId) && typeof seat.displayName === "string" && seat.displayName.length <= 80 && ["human", "bot"].includes(seat.kind) && ["player", "spectator"].includes(seat.type) && typeof seat.ready === "boolean" && typeof seat.online === "boolean"
86
+ ))
87
+ return null;
88
+ if (s.round !== null && (!s.round || !id(s.round.roundId) || ![
89
+ "preparing",
90
+ "loading",
91
+ "playing",
92
+ "finishing",
93
+ "completed",
94
+ "aborted",
95
+ "interrupted"
96
+ ].includes(s.round.phase) || s.round.reason !== null && (typeof s.round.reason !== "string" || s.round.reason.length > 1e3)))
97
+ return null;
98
+ }
99
+ return {
100
+ busy: v.busy,
101
+ disconnected: v.disconnected,
102
+ error: error2 ? { code: error2.code, message: error2.message, retryable: error2.retryable } : null,
103
+ session: s ? {
104
+ ...s.invitationUrl ? { invitationUrl: s.invitationUrl } : {},
105
+ ...s.spectatorInvitationUrl ? { spectatorInvitationUrl: s.spectatorInvitationUrl } : {},
106
+ multiplayerSessionId: s.multiplayerSessionId,
107
+ gameSlug: s.gameSlug,
108
+ roomCode: s.roomCode,
109
+ phase: s.phase,
110
+ revision: s.revision,
111
+ hostSeatId: s.hostSeatId,
112
+ ownSeatId: s.ownSeatId,
113
+ rematchAllowed: s.rematchAllowed,
114
+ playerPolicy: {
115
+ minPlayers: s.playerPolicy.minPlayers,
116
+ maxPlayers: s.playerPolicy.maxPlayers,
117
+ minHumanPlayers: s.playerPolicy.minHumanPlayers,
118
+ maxBots: s.playerPolicy.maxBots,
119
+ maxSpectators: s.playerPolicy.maxSpectators
120
+ },
121
+ seats: s.seats.map((seat) => ({
122
+ seatId: seat.seatId,
123
+ displayName: seat.displayName,
124
+ kind: seat.kind,
125
+ type: seat.type,
126
+ ready: seat.ready,
127
+ online: seat.online
128
+ })),
129
+ round: s.round ? {
130
+ roundId: s.round.roundId,
131
+ phase: s.round.phase,
132
+ reason: s.round.reason
133
+ } : null
134
+ } : null
135
+ };
136
+ }
137
+ function acceptLobbyState(value) {
138
+ const parsed = parseLobbyState(value);
139
+ if (!parsed) return;
140
+ current = parsed;
141
+ for (const listener of listeners) {
142
+ try {
143
+ listener(structuredClone(current));
144
+ } catch {
145
+ }
146
+ }
147
+ }
148
+ function lobbySnapshot() {
149
+ return structuredClone(current);
150
+ }
151
+ function onMultiplayerSessionChange(listener) {
152
+ const subscription = (value) => listener(value);
153
+ listeners.add(subscription);
154
+ try {
155
+ subscription(lobbySnapshot());
156
+ } catch {
157
+ }
158
+ return () => {
159
+ listeners.delete(subscription);
160
+ };
161
+ }
162
+ async function requestMultiplayerSession(request) {
163
+ if (!state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
164
+ return {
165
+ success: false,
166
+ error: {
167
+ code: "PROTOCOL_UNSUPPORTED",
168
+ message: "This host does not support multiplayer lobby controls",
169
+ retryable: false
170
+ }
171
+ };
172
+ const slug = state.gameSlug;
173
+ const launch = state.bootstrapLaunch;
174
+ try {
175
+ const response = await requestApiFromParent("/multiplayer/session", {
176
+ method: "POST",
177
+ body: request
178
+ });
179
+ if (slug !== state.gameSlug || launch !== state.bootstrapLaunch)
180
+ return {
181
+ success: false,
182
+ error: {
183
+ code: "STALE_ATTEMPT",
184
+ message: "The multiplayer context changed",
185
+ retryable: false
186
+ }
187
+ };
188
+ const parsed = response.success ? parseLobbyState(response.data) : null;
189
+ if (parsed && (!parsed.session || parsed.session.gameSlug === slug)) {
190
+ acceptLobbyState(parsed);
191
+ return { success: true, data: lobbySnapshot() };
192
+ }
193
+ return {
194
+ success: false,
195
+ error: {
196
+ code: response.error?.code ?? "UNAVAILABLE",
197
+ message: response.error?.message ?? "Lobby request failed",
198
+ retryable: response.error?.details?.terminal !== true
199
+ }
200
+ };
201
+ } catch {
202
+ return {
203
+ success: false,
204
+ error: {
205
+ code: "UNAVAILABLE",
206
+ message: "Lobby request timed out; refresh status before retrying",
207
+ retryable: true
208
+ }
209
+ };
210
+ }
211
+ }
212
+
48
213
  // src/settings.ts
49
214
  function getSettings() {
50
215
  return { ...state.gameSettings };
@@ -251,6 +416,24 @@
251
416
  function mergeBootstrapConfig(config = {}) {
252
417
  if (!config || typeof config !== "object" || Array.isArray(config)) return;
253
418
  mergeSettings(config.settings);
419
+ if (config.multiplayerSession !== void 0)
420
+ acceptLobbyState(
421
+ config.multiplayerSession ?? {
422
+ session: null,
423
+ busy: false,
424
+ error: null,
425
+ disconnected: false
426
+ }
427
+ );
428
+ if (config.multiplayerEntry === null) state.multiplayerEntry = null;
429
+ else if (config.multiplayerEntry && ["create", "join"].includes(config.multiplayerEntry.action)) {
430
+ const entry = config.multiplayerEntry;
431
+ state.multiplayerEntry = {
432
+ action: entry.action,
433
+ ...typeof entry.roomCode === "string" && /^\d{6}$/.test(entry.roomCode) ? { roomCode: entry.roomCode } : {},
434
+ ...entry.type === "player" || entry.type === "spectator" ? { type: entry.type } : {}
435
+ };
436
+ }
254
437
  const apply = (key, raw) => {
255
438
  const next = trimToNullable(raw);
256
439
  if (next === void 0) return;
@@ -298,6 +481,8 @@
298
481
  }
299
482
  function snapshotBootstrap() {
300
483
  return {
484
+ multiplayerEntry: state.multiplayerEntry,
485
+ multiplayerSession: lobbySnapshot(),
301
486
  settings: getSettings(),
302
487
  gameSlug: state.gameSlug,
303
488
  authToken: state.authToken,
@@ -653,7 +838,7 @@
653
838
  }
654
839
  }
655
840
  async function startSession() {
656
- if (state.bootstrapLaunch)
841
+ if (state.bootstrapLaunch || state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
657
842
  return { success: false, error: "Multiplayer rounds own their results" };
658
843
  if (state.sessionToken) return { success: true, token: state.sessionToken };
659
844
  if (state.sessionStartPromise) return await state.sessionStartPromise;
@@ -748,6 +933,12 @@
748
933
  }
749
934
  async function submitScore(score, meta = {}) {
750
935
  await ensureInitialized();
936
+ if (state.bootstrapLaunch || state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
937
+ return failedResult(
938
+ "FORBIDDEN",
939
+ "Multiplayer rounds own their results",
940
+ false
941
+ );
751
942
  if (!state.isInitialized) {
752
943
  return failedResult(
753
944
  "SDK_NOT_INITIALIZED",
@@ -968,7 +1159,7 @@
968
1159
  state.isAutoInitializing = false;
969
1160
  return false;
970
1161
  }
971
- if (!state.authToken && !state.bootstrapLaunch) {
1162
+ if (!state.authToken && !state.bootstrapLaunch && !state.bootstrapCapabilities.includes("multiplayer.lobby.v2")) {
972
1163
  state.authToken = await getAuthTokenFromParent();
973
1164
  }
974
1165
  state.isInitialized = true;
@@ -1011,6 +1202,8 @@
1011
1202
  state.bootstrapReceived = true;
1012
1203
  mergeBootstrapConfig(data.payload);
1013
1204
  }
1205
+ if (type === MESSAGE_PREFIX + "_MULTIPLAYER_SESSION" && state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
1206
+ acceptLobbyState(data.payload);
1014
1207
  if (type === MESSAGE_PREFIX + "_SET_AUTH") {
1015
1208
  state.authToken = data.token;
1016
1209
  if (state.gameSlug && !state.sessionToken && !state.sessionStartPromise && (state.authToken || state.leagueId && state.gameId && state.matchId)) {
@@ -1137,6 +1330,11 @@
1137
1330
  return !!state.sessionToken;
1138
1331
  },
1139
1332
  requestMultiplayerLaunch,
1333
+ requestMultiplayerSession,
1334
+ onMultiplayerSessionChange(listener) {
1335
+ installHostMessageListener();
1336
+ return onMultiplayerSessionChange(listener);
1337
+ },
1140
1338
  async startSession() {
1141
1339
  await ensureInitialized();
1142
1340
  if (state.sessionStartPromise) return await state.sessionStartPromise;
@@ -1205,6 +1403,8 @@
1205
1403
  },
1206
1404
  getBootstrap() {
1207
1405
  return {
1406
+ multiplayerEntry: state.multiplayerEntry,
1407
+ multiplayerSession: lobbySnapshot(),
1208
1408
  settings: getSettings(),
1209
1409
  gameSlug: state.gameSlug,
1210
1410
  authToken: state.authToken,