@ksaa-nlp/gamehub-sdk 0.1.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 +546 -0
- package/dist/gamehub-sdk.d.ts +694 -0
- package/dist/gamehub-sdk.js +1693 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.mjs +6 -0
- package/package.json +31 -0
- package/scripts/emit-module-entry.mjs +96 -0
- package/src/api-client.ts +33 -0
- package/src/bridge.ts +312 -0
- package/src/constants.ts +24 -0
- package/src/init.ts +335 -0
- package/src/main.ts +287 -0
- package/src/match-context.ts +52 -0
- package/src/multiplayer.ts +525 -0
- package/src/session.ts +240 -0
- package/src/state.ts +78 -0
- package/src/utils.ts +68 -0
- package/tsconfig.json +33 -0
- package/types/api.ts +21 -0
- package/types/bootstrap.ts +65 -0
- package/types/match.ts +41 -0
- package/types/multiplayer.ts +118 -0
- package/types/session.ts +67 -0
|
@@ -0,0 +1,694 @@
|
|
|
1
|
+
declare namespace GameHub {
|
|
2
|
+
/**
|
|
3
|
+
* The envelope returned by the GameHub REST API.
|
|
4
|
+
*/
|
|
5
|
+
interface ApiResponse {
|
|
6
|
+
success: boolean;
|
|
7
|
+
data?: any;
|
|
8
|
+
token?: string;
|
|
9
|
+
error?: {
|
|
10
|
+
message?: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Options accepted by {@link Api.apiRequest}.
|
|
15
|
+
*/
|
|
16
|
+
interface ApiRequestOptions {
|
|
17
|
+
method?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: any;
|
|
20
|
+
credentials?: RequestCredentials;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
declare namespace GameHub {
|
|
24
|
+
/**
|
|
25
|
+
* A single member belonging to a match participant (team player).
|
|
26
|
+
*/
|
|
27
|
+
interface MatchParticipantMember {
|
|
28
|
+
leaguePlayerId: string;
|
|
29
|
+
fullname?: string;
|
|
30
|
+
avatar?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A participant (individual or team) in a league match.
|
|
34
|
+
*/
|
|
35
|
+
interface MatchParticipant {
|
|
36
|
+
participantId: string;
|
|
37
|
+
name?: string;
|
|
38
|
+
members?: MatchParticipantMember[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The full context for a league match this game is being played in.
|
|
42
|
+
*/
|
|
43
|
+
interface MatchContext {
|
|
44
|
+
id: string;
|
|
45
|
+
leagueId: string;
|
|
46
|
+
gameId: string;
|
|
47
|
+
participant1: MatchParticipant;
|
|
48
|
+
participant2: MatchParticipant;
|
|
49
|
+
status: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Payload submitted via {@link Session.submitMatchResult}.
|
|
53
|
+
*/
|
|
54
|
+
interface MatchResultPayload {
|
|
55
|
+
winnerId?: string;
|
|
56
|
+
reason?: string;
|
|
57
|
+
scores?: Record<string, number>;
|
|
58
|
+
details?: Record<string, any>;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
declare namespace GameHub {
|
|
62
|
+
/**
|
|
63
|
+
* Static room metadata supplied by the host during bootstrap.
|
|
64
|
+
*
|
|
65
|
+
* Peer counts and peer lists are deliberately excluded because they'd be
|
|
66
|
+
* stale by the time the game reads them. Use {@link Multiplayer.getPeers}
|
|
67
|
+
* and the `room_joined` / `peer_joined` / `peer_left` events for the
|
|
68
|
+
* live peer state.
|
|
69
|
+
*/
|
|
70
|
+
interface BootstrapRoom {
|
|
71
|
+
roomCode: string | null;
|
|
72
|
+
shareId: string | null;
|
|
73
|
+
maxPlayers: number | null;
|
|
74
|
+
role: string | null;
|
|
75
|
+
roomToken: string | null;
|
|
76
|
+
wsUrl: string | null;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The configuration the host sends via postMessage to seed SDK state.
|
|
80
|
+
*/
|
|
81
|
+
interface BootstrapConfig {
|
|
82
|
+
gameSlug?: string | null;
|
|
83
|
+
authToken?: string | null;
|
|
84
|
+
leagueId?: string | null;
|
|
85
|
+
gameId?: string | null;
|
|
86
|
+
matchId?: string | null;
|
|
87
|
+
participant1Id?: string | null;
|
|
88
|
+
participant2Id?: string | null;
|
|
89
|
+
participant1MemberIds?: string[];
|
|
90
|
+
participant2MemberIds?: string[];
|
|
91
|
+
playerName?: string | null;
|
|
92
|
+
/** The peerId the server assigned to this player. Use
|
|
93
|
+
* {@link Multiplayer.selfId} after join for the live value. */
|
|
94
|
+
peerId?: string | null;
|
|
95
|
+
room?: Partial<BootstrapRoom> | null;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Snapshot of the SDK's bootstrap-sourced state, returned by
|
|
99
|
+
* {@link GameHubSDK.getBootstrap}.
|
|
100
|
+
*
|
|
101
|
+
* This snapshot contains only static session metadata. For the live room
|
|
102
|
+
* and peer state, use {@link Multiplayer.getRoom}, {@link Multiplayer.getPeers},
|
|
103
|
+
* and the `room_joined` / `peer_joined` / `peer_left` events.
|
|
104
|
+
*/
|
|
105
|
+
interface BootstrapData {
|
|
106
|
+
gameSlug: string | null;
|
|
107
|
+
authToken: string | null;
|
|
108
|
+
leagueId: string | null;
|
|
109
|
+
gameId: string | null;
|
|
110
|
+
matchId: string | null;
|
|
111
|
+
match: MatchContext | null;
|
|
112
|
+
participant1Id: string | null;
|
|
113
|
+
participant2Id: string | null;
|
|
114
|
+
participant1MemberIds: string[];
|
|
115
|
+
participant2MemberIds: string[];
|
|
116
|
+
playerName: string | null;
|
|
117
|
+
/** The peerId the server assigned to this player. */
|
|
118
|
+
peerId: string | null;
|
|
119
|
+
/** Static room metadata. `null` for non-multiplayer sessions. */
|
|
120
|
+
room: BootstrapRoom | null;
|
|
121
|
+
isBootstrapped: boolean;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
declare namespace GameHub {
|
|
125
|
+
/**
|
|
126
|
+
* Information needed to connect to a multiplayer room's WebSocket.
|
|
127
|
+
*/
|
|
128
|
+
interface JoinInfo {
|
|
129
|
+
wsUrl: string;
|
|
130
|
+
roomToken: string;
|
|
131
|
+
gameSlug: string;
|
|
132
|
+
roomCode: string;
|
|
133
|
+
peerId: string;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* A peer in a multiplayer room.
|
|
137
|
+
*/
|
|
138
|
+
interface Peer {
|
|
139
|
+
peerId: string;
|
|
140
|
+
role?: string;
|
|
141
|
+
metadata?: Record<string, any>;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Public info about the current multiplayer room, returned by
|
|
145
|
+
* {@link Multiplayer.getRoom}.
|
|
146
|
+
*/
|
|
147
|
+
interface RoomInfo {
|
|
148
|
+
roomCode: string;
|
|
149
|
+
shareId: string;
|
|
150
|
+
shareUrl?: string;
|
|
151
|
+
peerId: string;
|
|
152
|
+
role: string;
|
|
153
|
+
gameSlug: string;
|
|
154
|
+
roomToken: string;
|
|
155
|
+
wsUrl: string;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Internal book-keeping for the currently-joined room.
|
|
159
|
+
*/
|
|
160
|
+
interface MpRoom {
|
|
161
|
+
roomCode: string;
|
|
162
|
+
shareId: string;
|
|
163
|
+
shareUrl?: string;
|
|
164
|
+
peerId: string;
|
|
165
|
+
role: string;
|
|
166
|
+
gameSlug: string;
|
|
167
|
+
roomToken: string;
|
|
168
|
+
wsUrl: string;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Parameters used by {@link Multiplayer.connect} to open / re-open a WS.
|
|
172
|
+
*/
|
|
173
|
+
interface MpJoinRequest {
|
|
174
|
+
roomCode: string;
|
|
175
|
+
roomToken: string;
|
|
176
|
+
wsUrl: string;
|
|
177
|
+
gameSlug: string;
|
|
178
|
+
peerId: string;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Listener for a single multiplayer event (or all events via `'*'`).
|
|
182
|
+
*/
|
|
183
|
+
type MpEventHandler = (payload: any) => void;
|
|
184
|
+
/** Options accepted when creating a room. */
|
|
185
|
+
interface RoomOptions {
|
|
186
|
+
maxPlayers?: number;
|
|
187
|
+
passcode?: string;
|
|
188
|
+
}
|
|
189
|
+
/** Options accepted when joining a room. */
|
|
190
|
+
interface JoinOptions {
|
|
191
|
+
passcode?: string;
|
|
192
|
+
displayName?: string;
|
|
193
|
+
/**
|
|
194
|
+
* When true, the SDK locally marks this peer as a view-only guest:
|
|
195
|
+
* {@link Multiplayer.send} and {@link Multiplayer.broadcast} become no-ops
|
|
196
|
+
* and score submission (`submitScore` / `submitMatchResult`) is blocked.
|
|
197
|
+
* The peer still receives every broadcast so it can mirror host state.
|
|
198
|
+
*/
|
|
199
|
+
asViewer?: boolean;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Shape of the `message` event emitted for every peer-originated game event.
|
|
203
|
+
*/
|
|
204
|
+
interface MpMessage<T = any> {
|
|
205
|
+
roomCode: string;
|
|
206
|
+
fromPeerId: string;
|
|
207
|
+
eventName: string;
|
|
208
|
+
payload: T;
|
|
209
|
+
seq: number;
|
|
210
|
+
sentAt: number;
|
|
211
|
+
}
|
|
212
|
+
/** Result returned by `multiplayer.createRoom`. */
|
|
213
|
+
interface CreateRoomResult {
|
|
214
|
+
success: boolean;
|
|
215
|
+
roomCode?: string;
|
|
216
|
+
shareId?: string;
|
|
217
|
+
shareUrl?: string;
|
|
218
|
+
peerId?: string;
|
|
219
|
+
roomToken?: string;
|
|
220
|
+
error?: string;
|
|
221
|
+
}
|
|
222
|
+
/** Result returned by `multiplayer.joinRoom` / `joinRoomByLink`. */
|
|
223
|
+
interface JoinRoomResult {
|
|
224
|
+
success: boolean;
|
|
225
|
+
roomCode?: string;
|
|
226
|
+
shareId?: string;
|
|
227
|
+
peerId?: string;
|
|
228
|
+
roomToken?: string;
|
|
229
|
+
error?: string;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
declare namespace GameHub {
|
|
233
|
+
/**
|
|
234
|
+
* Optional metadata attached to a score submission.
|
|
235
|
+
*/
|
|
236
|
+
interface ScoreMetadata {
|
|
237
|
+
matchResult?: MatchResultPayload;
|
|
238
|
+
level?: number;
|
|
239
|
+
duration?: number;
|
|
240
|
+
custom?: Record<string, any>;
|
|
241
|
+
[key: string]: any;
|
|
242
|
+
}
|
|
243
|
+
/** Payload sent via {@link GameHubSDK.notifyComplete}. */
|
|
244
|
+
interface GameCompleteData {
|
|
245
|
+
score?: number;
|
|
246
|
+
status?: string;
|
|
247
|
+
meta?: Record<string, any>;
|
|
248
|
+
}
|
|
249
|
+
/** Payload sent via {@link GameHubSDK.logEvent}. */
|
|
250
|
+
interface EventData {
|
|
251
|
+
category?: string;
|
|
252
|
+
label?: string;
|
|
253
|
+
value?: number;
|
|
254
|
+
properties?: Record<string, any>;
|
|
255
|
+
}
|
|
256
|
+
/** Options accepted by {@link GameHubSDK.getQuestions}. */
|
|
257
|
+
interface QuestionOptions {
|
|
258
|
+
difficulty?: 'easy' | 'medium' | 'hard' | string;
|
|
259
|
+
category?: string | number;
|
|
260
|
+
limit?: number;
|
|
261
|
+
}
|
|
262
|
+
/** A single question as returned by {@link GameHubSDK.getQuestions}. */
|
|
263
|
+
interface Question {
|
|
264
|
+
id: string;
|
|
265
|
+
difficulty?: 'easy' | 'medium' | 'hard' | string;
|
|
266
|
+
category?: string;
|
|
267
|
+
prompt: string;
|
|
268
|
+
choices: string[];
|
|
269
|
+
answer: string | number;
|
|
270
|
+
explanation?: string;
|
|
271
|
+
points: number;
|
|
272
|
+
}
|
|
273
|
+
/** Result returned by `startSession`. */
|
|
274
|
+
interface StartSessionResult {
|
|
275
|
+
success: boolean;
|
|
276
|
+
token?: string | null;
|
|
277
|
+
error?: string;
|
|
278
|
+
}
|
|
279
|
+
/** Result returned by `submitScore` / `submitMatchScore`. */
|
|
280
|
+
interface SubmitScoreResult {
|
|
281
|
+
success: boolean;
|
|
282
|
+
accepted?: boolean;
|
|
283
|
+
timeTaken?: number;
|
|
284
|
+
error?: string;
|
|
285
|
+
/**
|
|
286
|
+
* `true` when the SDK intentionally skipped the network call (e.g. the
|
|
287
|
+
* current peer is not the host in an online match, or is a view-only
|
|
288
|
+
* guest). Treat this as "not-an-error" — the host will submit instead.
|
|
289
|
+
*/
|
|
290
|
+
skipped?: boolean;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
declare namespace GameHub {
|
|
294
|
+
/**
|
|
295
|
+
* Bundle version reported by the SDK. Bumped at release time.
|
|
296
|
+
*/
|
|
297
|
+
const SDK_VERSION = "0.1.0";
|
|
298
|
+
/**
|
|
299
|
+
* Prefix applied to every cross-origin postMessage the SDK emits and accepts.
|
|
300
|
+
* Keeps our messages isolated from unrelated frames on the same page.
|
|
301
|
+
*/
|
|
302
|
+
const MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
303
|
+
/** How long to wait for the host to reply to bootstrap/auth requests. */
|
|
304
|
+
const PARENT_REQUEST_TIMEOUT_MS = 2000;
|
|
305
|
+
/** Maximum number of WebSocket reconnect attempts before giving up. */
|
|
306
|
+
const MP_MAX_RECONNECT_ATTEMPTS = 5;
|
|
307
|
+
/** Hard cap on reconnect backoff. */
|
|
308
|
+
const MP_MAX_RECONNECT_DELAY_MS = 10000;
|
|
309
|
+
/** Upper bound used when the caller doesn't pass an explicit limit. */
|
|
310
|
+
const QUESTIONS_LIMIT_CAP = 100;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Centralised mutable state for the SDK singleton.
|
|
314
|
+
*
|
|
315
|
+
* Everything here is module-global by design — the SDK is a singleton per
|
|
316
|
+
* window and this is the single source of truth. Keeping it in one file makes
|
|
317
|
+
* lifetime and invalidation rules easier to audit than spreading `let`s across
|
|
318
|
+
* every feature module.
|
|
319
|
+
*/
|
|
320
|
+
declare namespace GameHub.State {
|
|
321
|
+
let sdkOrigin: string;
|
|
322
|
+
let sdkPathPrefix: string;
|
|
323
|
+
let runtimeBasePath: string;
|
|
324
|
+
let apiBase: string;
|
|
325
|
+
let gameSlug: string | null;
|
|
326
|
+
let sessionToken: string | null;
|
|
327
|
+
let authToken: string | null;
|
|
328
|
+
let leagueId: string | null;
|
|
329
|
+
let gameId: string | null;
|
|
330
|
+
let matchId: string | null;
|
|
331
|
+
let participant1Id: string | null;
|
|
332
|
+
let participant2Id: string | null;
|
|
333
|
+
let participant1MemberIds: string[];
|
|
334
|
+
let participant2MemberIds: string[];
|
|
335
|
+
let matchContext: MatchContext | null;
|
|
336
|
+
let matchContextPromise: Promise<MatchContext | null> | null;
|
|
337
|
+
let bootstrapShareId: string | null;
|
|
338
|
+
let bootstrapRoomCode: string | null;
|
|
339
|
+
let bootstrapRoomRole: string | null;
|
|
340
|
+
let bootstrapRoomToken: string | null;
|
|
341
|
+
let bootstrapWsUrl: string | null;
|
|
342
|
+
let bootstrapPlayerName: string | null;
|
|
343
|
+
let bootstrapPeerId: string | null;
|
|
344
|
+
let bootstrapMaxPlayers: number | null;
|
|
345
|
+
let bootstrapReceived: boolean;
|
|
346
|
+
let isInitialized: boolean;
|
|
347
|
+
let isAutoInitializing: boolean;
|
|
348
|
+
let autoInitPromise: Promise<boolean> | null;
|
|
349
|
+
let bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;
|
|
350
|
+
let parentOrigin: string | null;
|
|
351
|
+
let sessionStartPromise: Promise<StartSessionResult> | null;
|
|
352
|
+
let lastAutoJoinShareId: string | null;
|
|
353
|
+
let lastAutoJoinRoomCode: string | null;
|
|
354
|
+
let mpSocket: WebSocket | null;
|
|
355
|
+
let mpReconnectTimer: ReturnType<typeof setTimeout> | null;
|
|
356
|
+
let mpReconnectAttempts: number;
|
|
357
|
+
let mpExpectedClose: boolean;
|
|
358
|
+
let mpRoom: MpRoom | null;
|
|
359
|
+
let mpLastJoinRequest: MpJoinRequest | null;
|
|
360
|
+
const mpPeers: Map<string, Peer>;
|
|
361
|
+
const mpHandlers: Map<string, Set<MpEventHandler>>;
|
|
362
|
+
/**
|
|
363
|
+
* Highest `seq` we've already delivered to game code, per sending peer.
|
|
364
|
+
* Used to drop late/duplicate `game_event` frames so a reconnect or a
|
|
365
|
+
* buffered message can't double-advance game state.
|
|
366
|
+
*/
|
|
367
|
+
const mpLastSeqByPeer: Map<string, number>;
|
|
368
|
+
/**
|
|
369
|
+
* Local override for view-only guests. The server doesn't know about
|
|
370
|
+
* viewers — this is a client-side flag the SDK flips when the game joins
|
|
371
|
+
* with `{ asViewer: true }`. It gates outbound `send`/`broadcast` and
|
|
372
|
+
* score submission.
|
|
373
|
+
*/
|
|
374
|
+
let mpViewerOverride: boolean;
|
|
375
|
+
}
|
|
376
|
+
declare namespace GameHub.Utils {
|
|
377
|
+
/**
|
|
378
|
+
* Logs with a consistent `[GameHubSDK]` prefix so host-page developers can
|
|
379
|
+
* easily filter SDK messages in their console.
|
|
380
|
+
*/
|
|
381
|
+
function warn(message: string, ...rest: any[]): void;
|
|
382
|
+
function error(message: string, ...rest: any[]): void;
|
|
383
|
+
/**
|
|
384
|
+
* Flattens the standard `{ success, data }` envelope returned by our REST API
|
|
385
|
+
* down to the inner `data` payload, or returns the raw response if it isn't
|
|
386
|
+
* shaped that way.
|
|
387
|
+
*/
|
|
388
|
+
function unwrapResult(result: ApiResponse | null | undefined): any;
|
|
389
|
+
/**
|
|
390
|
+
* Extracts a share ID from either:
|
|
391
|
+
* - a full multiplayer URL (`/join?mp=<shareId>`), or
|
|
392
|
+
* - a short path where the last segment is the share ID itself.
|
|
393
|
+
* Returns null if the link can't be parsed.
|
|
394
|
+
*/
|
|
395
|
+
function extractShareIdFromLink(link: string): string | null;
|
|
396
|
+
/**
|
|
397
|
+
* Safely read a query-string parameter, falling back to a regex scan when
|
|
398
|
+
* URLSearchParams is unavailable (very old browsers / odd runtimes).
|
|
399
|
+
*/
|
|
400
|
+
function readQueryParam(name: string): string | null;
|
|
401
|
+
/**
|
|
402
|
+
* Reads a CSV query parameter and returns the trimmed, non-empty values.
|
|
403
|
+
*/
|
|
404
|
+
function readCsvQueryParam(name: string): string[];
|
|
405
|
+
}
|
|
406
|
+
declare namespace GameHub.Api {
|
|
407
|
+
/**
|
|
408
|
+
* Performs a request against the GameHub REST API, prefixing the configured
|
|
409
|
+
* API base, attaching the Bearer auth token when available, and parsing the
|
|
410
|
+
* JSON response.
|
|
411
|
+
*
|
|
412
|
+
* Throws whatever `fetch`/`JSON.parse` throw — callers decide whether to
|
|
413
|
+
* retry, fall back, or surface the error to the host.
|
|
414
|
+
*/
|
|
415
|
+
function apiRequest(endpoint: string, options?: ApiRequestOptions): Promise<ApiResponse>;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Cross-origin communication layer between the game iframe and its host page.
|
|
419
|
+
*
|
|
420
|
+
* Messages are namespaced with {@link GameHub.MESSAGE_PREFIX} so we don't pick
|
|
421
|
+
* up unrelated postMessage traffic. The host is expected to implement a small
|
|
422
|
+
* protocol (BOOTSTRAP_REQUEST / BOOTSTRAP, AUTH_REQUEST / AUTH_RESPONSE, etc.).
|
|
423
|
+
*/
|
|
424
|
+
declare namespace GameHub.Bridge {
|
|
425
|
+
/**
|
|
426
|
+
* Fold a {@link BootstrapConfig} from the host into internal state. Accepts
|
|
427
|
+
* partial configs: only the fields that are explicitly set (including
|
|
428
|
+
* explicit `null`s used to clear a value) are applied.
|
|
429
|
+
*/
|
|
430
|
+
function mergeBootstrapConfig(config?: BootstrapConfig): void;
|
|
431
|
+
/**
|
|
432
|
+
* Ask the host for its bootstrap payload. Resolves `null` if the game is
|
|
433
|
+
* standalone (no parent), if the host doesn't reply within the timeout, or
|
|
434
|
+
* if we're not in an iframe.
|
|
435
|
+
*
|
|
436
|
+
* Subsequent calls after a successful bootstrap short-circuit to the cached
|
|
437
|
+
* state snapshot.
|
|
438
|
+
*/
|
|
439
|
+
function requestBootstrapFromParent(): Promise<BootstrapConfig | null>;
|
|
440
|
+
/**
|
|
441
|
+
* Ask the host for a fresh auth token. The host may also use the response to
|
|
442
|
+
* override league/match context — when it does, we prefer its values over
|
|
443
|
+
* whatever was on the URL.
|
|
444
|
+
*/
|
|
445
|
+
function getAuthTokenFromParent(): Promise<string | null>;
|
|
446
|
+
/**
|
|
447
|
+
* Fire a namespaced message up to the host window. Silently no-ops when we
|
|
448
|
+
* aren't inside an iframe.
|
|
449
|
+
*/
|
|
450
|
+
function sendToParent(type: string, data: Record<string, any>): void;
|
|
451
|
+
}
|
|
452
|
+
declare namespace GameHub.MatchCtx {
|
|
453
|
+
/**
|
|
454
|
+
* Lazily load the match context for a league game. Results are cached on
|
|
455
|
+
* {@link GameHub.State.matchContext}; concurrent callers share a single
|
|
456
|
+
* in-flight request via {@link GameHub.State.matchContextPromise}.
|
|
457
|
+
*
|
|
458
|
+
* Resolves `null` when required context (league or match id) is missing, or
|
|
459
|
+
* when the server returns an error — callers decide how to degrade.
|
|
460
|
+
*/
|
|
461
|
+
function fetchMatchContext(): Promise<MatchContext | null>;
|
|
462
|
+
}
|
|
463
|
+
declare namespace GameHub.Session {
|
|
464
|
+
/**
|
|
465
|
+
* Starts a new game session and caches the returned session token. Safe to
|
|
466
|
+
* call multiple times — the cached token short-circuits subsequent calls.
|
|
467
|
+
*
|
|
468
|
+
* Endpoint is selected from the active context:
|
|
469
|
+
* - league + game + match → scoped match session
|
|
470
|
+
* - league + game → scoped league session
|
|
471
|
+
* - otherwise → standalone session (requires auth)
|
|
472
|
+
*/
|
|
473
|
+
function startSession(): Promise<StartSessionResult>;
|
|
474
|
+
/**
|
|
475
|
+
* Submit a score to the current session. If no session exists yet we try to
|
|
476
|
+
* open one (re-using any in-flight start attempt).
|
|
477
|
+
*/
|
|
478
|
+
function submitScore(score: number, meta?: ScoreMetadata): Promise<SubmitScoreResult>;
|
|
479
|
+
/**
|
|
480
|
+
* Convenience wrapper that tags a score with the current league match
|
|
481
|
+
* context. Fails early if there's no matchId — a plain {@link submitScore}
|
|
482
|
+
* is the right call in that case.
|
|
483
|
+
*/
|
|
484
|
+
function submitMatchScore(score: number, meta?: ScoreMetadata): Promise<SubmitScoreResult>;
|
|
485
|
+
/**
|
|
486
|
+
* Submit a match result (winner, scores, etc.) with a zero placeholder
|
|
487
|
+
* score — the server derives the real leaderboard entries from the result
|
|
488
|
+
* payload.
|
|
489
|
+
*/
|
|
490
|
+
function submitMatchResult(result?: MatchResultPayload): Promise<SubmitScoreResult>;
|
|
491
|
+
/**
|
|
492
|
+
* Fetch questions for this game. Returns an empty array on any failure or
|
|
493
|
+
* invalid input — callers can treat "no questions" as the degraded state.
|
|
494
|
+
*/
|
|
495
|
+
function getQuestions(options?: QuestionOptions): Promise<Question[]>;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Multiplayer layer: room creation/join, WebSocket connection management,
|
|
499
|
+
* reconnection, and an event emitter for game code to listen on.
|
|
500
|
+
*/
|
|
501
|
+
declare namespace GameHub.Multiplayer {
|
|
502
|
+
/**
|
|
503
|
+
* Dispatch an event to per-name listeners and the wildcard (`'*'`) listeners.
|
|
504
|
+
* Handler errors are caught and logged so a buggy listener can't break the
|
|
505
|
+
* socket loop.
|
|
506
|
+
*/
|
|
507
|
+
function emit(eventName: string, payload: any): void;
|
|
508
|
+
/**
|
|
509
|
+
* Detach listeners from the current socket and close it. Idempotent.
|
|
510
|
+
* The caller is responsible for clearing {@link GameHub.State.mpRoom} and
|
|
511
|
+
* related state — this function only touches the transport.
|
|
512
|
+
*/
|
|
513
|
+
function clearSocket(): void;
|
|
514
|
+
/**
|
|
515
|
+
* Open a WebSocket for the given join info and wire up the message/close
|
|
516
|
+
* handlers. Automatically reconnects with exponential backoff up to
|
|
517
|
+
* {@link GameHub.MP_MAX_RECONNECT_ATTEMPTS} attempts.
|
|
518
|
+
*/
|
|
519
|
+
function connect(joinInfo: JoinInfo): void;
|
|
520
|
+
/**
|
|
521
|
+
* Create a room for the current game and connect as the host.
|
|
522
|
+
*/
|
|
523
|
+
function createRoom(options?: RoomOptions): Promise<CreateRoomResult>;
|
|
524
|
+
/**
|
|
525
|
+
* Join an existing room by its short alphanumeric code.
|
|
526
|
+
*/
|
|
527
|
+
function joinRoom(roomCode: string, options?: JoinOptions): Promise<JoinRoomResult>;
|
|
528
|
+
/**
|
|
529
|
+
* Join an existing room by its share ID or full share URL.
|
|
530
|
+
*/
|
|
531
|
+
function joinRoomByLink(link: string, options?: JoinOptions): Promise<JoinRoomResult>;
|
|
532
|
+
/**
|
|
533
|
+
* Disconnect from the current room. If we're the host, also ask the server
|
|
534
|
+
* to close the room so stragglers get booted cleanly.
|
|
535
|
+
*/
|
|
536
|
+
function leaveRoom(reason?: string): Promise<void>;
|
|
537
|
+
/**
|
|
538
|
+
* Send a custom game event to every other peer in the room. Returns false
|
|
539
|
+
* when the socket isn't open or the current peer is a view-only guest.
|
|
540
|
+
*/
|
|
541
|
+
function send(eventName: string, payload?: Record<string, any>): boolean;
|
|
542
|
+
/**
|
|
543
|
+
* Host-only variant of {@link send}. Silently no-ops (and logs a warning) if
|
|
544
|
+
* the current peer isn't the host. Use this for authoritative state updates
|
|
545
|
+
* — grid shuffles, turn advances, round resolution — so a guest that
|
|
546
|
+
* accidentally calls it can't corrupt the match.
|
|
547
|
+
*/
|
|
548
|
+
function broadcast(eventName: string, payload?: Record<string, any>): boolean;
|
|
549
|
+
/** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */
|
|
550
|
+
function getRole(): string | null;
|
|
551
|
+
/** @returns true when the current peer is the room's authoritative host. */
|
|
552
|
+
function isHost(): boolean;
|
|
553
|
+
/** @returns true when the current peer joined with `{ asViewer: true }`. */
|
|
554
|
+
function isViewer(): boolean;
|
|
555
|
+
/**
|
|
556
|
+
* Returns the peerId of the current player (self), or null if not joined.
|
|
557
|
+
* Convenience for filtering self-originated echoes inside a `message`
|
|
558
|
+
* listener: `if (msg.fromPeerId === selfId()) return;`.
|
|
559
|
+
*/
|
|
560
|
+
function selfId(): string | null;
|
|
561
|
+
/**
|
|
562
|
+
* Subscribe to a multiplayer event. Use `'*'` to receive every event.
|
|
563
|
+
* Returns an unsubscribe function.
|
|
564
|
+
*/
|
|
565
|
+
function on(eventName: string, handler: MpEventHandler): () => void;
|
|
566
|
+
/** @returns a copy of the current room descriptor, or null if not in one. */
|
|
567
|
+
function getRoom(): RoomInfo | null;
|
|
568
|
+
/** @returns every peer currently in the room (self included). */
|
|
569
|
+
function getPeers(): Peer[];
|
|
570
|
+
/** @returns whether the WebSocket is currently open. */
|
|
571
|
+
function isConnected(): boolean;
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* SDK discovery + auto-initialisation.
|
|
575
|
+
*
|
|
576
|
+
* Detects the API base URL (from the `<script>` tag or the page location),
|
|
577
|
+
* the active game slug, and the league/match context from the URL. Then
|
|
578
|
+
* exchanges a few postMessages with the host to pick up an auth token and the
|
|
579
|
+
* full bootstrap payload before opening a session and auto-joining any
|
|
580
|
+
* pending multiplayer room.
|
|
581
|
+
*/
|
|
582
|
+
declare namespace GameHub.Init {
|
|
583
|
+
/**
|
|
584
|
+
* One-off environment detection. Should be called exactly once at SDK boot
|
|
585
|
+
* time, before any other Init function.
|
|
586
|
+
*/
|
|
587
|
+
function detectEnvironment(): void;
|
|
588
|
+
/**
|
|
589
|
+
* Orchestrates the full SDK boot sequence:
|
|
590
|
+
* 1. Request bootstrap config from the host (seeds slug + context).
|
|
591
|
+
* 2. Exchange for an auth token if we don't already have one.
|
|
592
|
+
* 3. Notify the host that we've booted, then fetch match context.
|
|
593
|
+
* 4. Open a session if we can, and auto-join any pending multiplayer room.
|
|
594
|
+
*
|
|
595
|
+
* Safe to call multiple times — concurrent callers share a single promise.
|
|
596
|
+
*/
|
|
597
|
+
function autoInit(): Promise<boolean>;
|
|
598
|
+
/**
|
|
599
|
+
* Ensures init has at least started; callers `await` this before touching
|
|
600
|
+
* any state that depends on bootstrap / auth having resolved.
|
|
601
|
+
*/
|
|
602
|
+
function ensureInitialized(): Promise<boolean>;
|
|
603
|
+
/**
|
|
604
|
+
* Wires up the ambient message listener the host uses to push updates into
|
|
605
|
+
* the running SDK (fresh bootstrap, rotated auth, pause/resume commands).
|
|
606
|
+
*/
|
|
607
|
+
function installHostMessageListener(): void;
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Public SDK surface — the one and only object that game code interacts with.
|
|
611
|
+
*
|
|
612
|
+
* Games load this as a plain `<script>` tag, so we expose ourselves via
|
|
613
|
+
* `window.GameHubSDK`. We also emit a `module.exports` assignment for the
|
|
614
|
+
* rare case of CommonJS-style consumption in a build tool, but CommonJS is
|
|
615
|
+
* not the primary distribution channel.
|
|
616
|
+
*/
|
|
617
|
+
declare namespace GameHub.Public {
|
|
618
|
+
/**
|
|
619
|
+
* Shape of {@link window.GameHubSDK}. Documented separately from the
|
|
620
|
+
* implementation so the public API is easy to scan.
|
|
621
|
+
*/
|
|
622
|
+
interface Sdk {
|
|
623
|
+
readonly version: string;
|
|
624
|
+
/** @returns true after auto-init has successfully resolved. */
|
|
625
|
+
isInitialized(): boolean;
|
|
626
|
+
/** @returns true when an auth token is currently known. */
|
|
627
|
+
isAuthenticated(): boolean;
|
|
628
|
+
/** @returns true when a live session token has been issued. */
|
|
629
|
+
hasActiveSession(): boolean;
|
|
630
|
+
/** Manually start a session (auto-init already attempts this). */
|
|
631
|
+
startSession(): Promise<StartSessionResult>;
|
|
632
|
+
/** Submit a final score for the current session. */
|
|
633
|
+
submitScore(score: number, meta?: ScoreMetadata): Promise<SubmitScoreResult>;
|
|
634
|
+
/** Submit a score attached to the active league match. */
|
|
635
|
+
submitMatchScore(score: number, meta?: ScoreMetadata): Promise<SubmitScoreResult>;
|
|
636
|
+
/** Submit a full match result (winner, scores, etc.). */
|
|
637
|
+
submitMatchResult(result?: MatchResultPayload): Promise<SubmitScoreResult>;
|
|
638
|
+
/** Signal the host that the game is ready to begin another round. */
|
|
639
|
+
playAgain(): Promise<{
|
|
640
|
+
success: boolean;
|
|
641
|
+
token: string | null;
|
|
642
|
+
}>;
|
|
643
|
+
/** Tell the host the game has finished (shows completion UI). */
|
|
644
|
+
notifyComplete(data?: GameCompleteData): void;
|
|
645
|
+
/** Ask the host to close the game/iframe and return to the lobby. */
|
|
646
|
+
requestClose(): void;
|
|
647
|
+
/** Emit a custom analytics event to the host. */
|
|
648
|
+
logEvent(eventName: string, eventData?: EventData): void;
|
|
649
|
+
/** @returns the resolved game slug, or null if we never found one. */
|
|
650
|
+
getGameSlug(): string | null;
|
|
651
|
+
/** @returns whether the SDK is running inside an iframe. */
|
|
652
|
+
isInIframe(): boolean;
|
|
653
|
+
/** Awaitable barrier — resolves when the SDK has booted. */
|
|
654
|
+
ready(): Promise<boolean>;
|
|
655
|
+
/** @returns a snapshot of bootstrap-sourced state for debugging. */
|
|
656
|
+
getBootstrap(): BootstrapData;
|
|
657
|
+
/** Fetch the match context (lazy; cached after first success). */
|
|
658
|
+
getMatchContext(): Promise<MatchContext | null>;
|
|
659
|
+
/** Fetch questions for quiz-style games. Returns [] on failure. */
|
|
660
|
+
getQuestions(options?: QuestionOptions): Promise<Question[]>;
|
|
661
|
+
/** Multiplayer sub-API. */
|
|
662
|
+
multiplayer: {
|
|
663
|
+
createRoom(options?: RoomOptions): Promise<CreateRoomResult>;
|
|
664
|
+
joinRoom(roomCode: string, options?: JoinOptions): Promise<JoinRoomResult>;
|
|
665
|
+
joinRoomByLink(link: string, options?: JoinOptions): Promise<JoinRoomResult>;
|
|
666
|
+
leaveRoom(reason?: string): Promise<void>;
|
|
667
|
+
/** Send a custom event to every peer in the room. Blocked for viewers. */
|
|
668
|
+
send(eventName: string, payload?: Record<string, any>): boolean;
|
|
669
|
+
/**
|
|
670
|
+
* Host-only send. No-ops for guests and viewers. Use this for
|
|
671
|
+
* authoritative state updates (grid shuffles, turn changes, round end).
|
|
672
|
+
*/
|
|
673
|
+
broadcast(eventName: string, payload?: Record<string, any>): boolean;
|
|
674
|
+
on(eventName: string, handler: MpEventHandler): () => void;
|
|
675
|
+
getRoom(): RoomInfo | null;
|
|
676
|
+
getPeers(): Peer[];
|
|
677
|
+
isConnected(): boolean;
|
|
678
|
+
/** @returns the peer's role (`host`, `player`, `viewer`) or null. */
|
|
679
|
+
getRole(): string | null;
|
|
680
|
+
/** @returns true if this peer is the authoritative host. */
|
|
681
|
+
isHost(): boolean;
|
|
682
|
+
/** @returns true if this peer joined as a view-only guest. */
|
|
683
|
+
isViewer(): boolean;
|
|
684
|
+
/** @returns the peerId of the local player (self), or null. */
|
|
685
|
+
selfId(): string | null;
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Assemble the public API object. Methods are thin adapters that route to
|
|
690
|
+
* the internal `GameHub.*` namespaces — keeping the surface area small and
|
|
691
|
+
* the internals freely refactorable.
|
|
692
|
+
*/
|
|
693
|
+
function create(): Sdk;
|
|
694
|
+
}
|