@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.
@@ -0,0 +1,56 @@
1
+ /// <reference path="./gamehub-sdk.d.ts" />
2
+
3
+ /**
4
+ * Module-mode entry for TypeScript / ES-module consumers. The runtime is a
5
+ * plain IIFE that attaches `window.GameHubSDK` (and `module.exports = sdk`
6
+ * for CommonJS interop) — this .d.ts re-exposes the same instance with an
7
+ * importable type.
8
+ *
9
+ * Generated by scripts/emit-module-entry.mjs; do not edit by hand.
10
+ */
11
+
12
+ // Re-export every public type under the module's namespace so consumers can
13
+ // write `gamehubSdk.BootstrapData` (import = syntax) or import them directly
14
+ // via dot access.
15
+ declare namespace gamehubSdk {
16
+ export type ApiResponse = GameHub.ApiResponse;
17
+ export type ApiRequestOptions = GameHub.ApiRequestOptions;
18
+
19
+ export type MatchContext = GameHub.MatchContext;
20
+ export type MatchParticipant = GameHub.MatchParticipant;
21
+ export type MatchParticipantMember = GameHub.MatchParticipantMember;
22
+ export type MatchResultPayload = GameHub.MatchResultPayload;
23
+
24
+ export type BootstrapConfig = GameHub.BootstrapConfig;
25
+ export type BootstrapData = GameHub.BootstrapData;
26
+ export type BootstrapRoom = GameHub.BootstrapRoom;
27
+
28
+ export type JoinInfo = GameHub.JoinInfo;
29
+ export type Peer = GameHub.Peer;
30
+ export type RoomInfo = GameHub.RoomInfo;
31
+ export type MpRoom = GameHub.MpRoom;
32
+ export type MpJoinRequest = GameHub.MpJoinRequest;
33
+ export type MpEventHandler = GameHub.MpEventHandler;
34
+ export type MpMessage<T = any> = GameHub.MpMessage<T>;
35
+ export type RoomOptions = GameHub.RoomOptions;
36
+ export type JoinOptions = GameHub.JoinOptions;
37
+ export type CreateRoomResult = GameHub.CreateRoomResult;
38
+ export type JoinRoomResult = GameHub.JoinRoomResult;
39
+
40
+ export type ScoreMetadata = GameHub.ScoreMetadata;
41
+ export type GameCompleteData = GameHub.GameCompleteData;
42
+ export type EventData = GameHub.EventData;
43
+ export type QuestionOptions = GameHub.QuestionOptions;
44
+ export type Question = GameHub.Question;
45
+ export type StartSessionResult = GameHub.StartSessionResult;
46
+ export type SubmitScoreResult = GameHub.SubmitScoreResult;
47
+
48
+ export type Sdk = GameHub.Public.Sdk;
49
+ }
50
+
51
+ declare const gamehubSdk: GameHub.Public.Sdk;
52
+
53
+ // `export =` mirrors the runtime (`module.exports = sdk`) so consumers get the
54
+ // raw SDK object both from `require()` and, with esModuleInterop, from
55
+ // `import sdk from 'gamehub-sdk'`.
56
+ export = gamehubSdk;
package/dist/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ import './gamehub-sdk.js';
2
+
3
+ const sdk = (typeof globalThis !== 'undefined' && globalThis.GameHubSDK) ||
4
+ (typeof window !== 'undefined' && window.GameHubSDK);
5
+
6
+ export default sdk;
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@ksaa-nlp/gamehub-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Browser SDK that lets GameHub-hosted games talk to the platform (auth, sessions, scores, multiplayer).",
5
+ "main": "./dist/gamehub-sdk.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "author": "KSAANLP",
9
+ "license": "ISC",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/gamehub-sdk.js",
15
+ "default": "./dist/gamehub-sdk.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "src/**/*",
20
+ "types/**/*",
21
+ "dist/**/*",
22
+ "scripts/**/*",
23
+ "tsconfig.json",
24
+ "README.md"
25
+ ],
26
+ "scripts": {
27
+ "build": "npx tsc -p ./tsconfig.json && node scripts/emit-module-entry.mjs",
28
+ "pack": "npm run build && npm pack",
29
+ "publish": "npm run pack && npm publish"
30
+ }
31
+ }
@@ -0,0 +1,96 @@
1
+ // Emits a module-mode TypeScript declaration alongside the outFile-generated
2
+ // namespace .d.ts. Consumers import this via the package's `types` entry:
3
+ //
4
+ // import gamehubSdk from 'gamehub-sdk';
5
+ // import gamehubSdk = require('gamehub-sdk');
6
+ //
7
+ // The companion file is needed because `outFile` + namespaces emits a
8
+ // script-mode .d.ts (no top-level exports), which TypeScript refuses to
9
+ // treat as a module. This shim re-exposes the namespace members as a proper
10
+ // importable module while still letting game pages use the global
11
+ // `window.GameHubSDK` via <script> tags.
12
+
13
+ import { writeFileSync } from 'node:fs';
14
+ import { dirname, join } from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ const __dirname = dirname(fileURLToPath(import.meta.url));
18
+ const distDir = join(__dirname, '..', 'dist');
19
+ const outPath = join(distDir, 'index.d.ts');
20
+ const esmPath = join(distDir, 'index.mjs');
21
+
22
+ // ESM entry for bundlers (Vite, webpack, esbuild). The underlying
23
+ // `gamehub-sdk.js` is a script-mode IIFE that attaches `window.GameHubSDK`
24
+ // as a side effect — we import it for that side effect, then re-export the
25
+ // global as the module's default.
26
+ const esmContent = `import './gamehub-sdk.js';
27
+
28
+ const sdk = (typeof globalThis !== 'undefined' && globalThis.GameHubSDK) ||
29
+ (typeof window !== 'undefined' && window.GameHubSDK);
30
+
31
+ export default sdk;
32
+ `;
33
+
34
+ writeFileSync(esmPath, esmContent);
35
+ console.log('Wrote ' + esmPath);
36
+
37
+ const content = `/// <reference path="./gamehub-sdk.d.ts" />
38
+
39
+ /**
40
+ * Module-mode entry for TypeScript / ES-module consumers. The runtime is a
41
+ * plain IIFE that attaches \`window.GameHubSDK\` (and \`module.exports = sdk\`
42
+ * for CommonJS interop) — this .d.ts re-exposes the same instance with an
43
+ * importable type.
44
+ *
45
+ * Generated by scripts/emit-module-entry.mjs; do not edit by hand.
46
+ */
47
+
48
+ // Re-export every public type under the module's namespace so consumers can
49
+ // write \`gamehubSdk.BootstrapData\` (import = syntax) or import them directly
50
+ // via dot access.
51
+ declare namespace gamehubSdk {
52
+ export type ApiResponse = GameHub.ApiResponse;
53
+ export type ApiRequestOptions = GameHub.ApiRequestOptions;
54
+
55
+ export type MatchContext = GameHub.MatchContext;
56
+ export type MatchParticipant = GameHub.MatchParticipant;
57
+ export type MatchParticipantMember = GameHub.MatchParticipantMember;
58
+ export type MatchResultPayload = GameHub.MatchResultPayload;
59
+
60
+ export type BootstrapConfig = GameHub.BootstrapConfig;
61
+ export type BootstrapData = GameHub.BootstrapData;
62
+ export type BootstrapRoom = GameHub.BootstrapRoom;
63
+
64
+ export type JoinInfo = GameHub.JoinInfo;
65
+ export type Peer = GameHub.Peer;
66
+ export type RoomInfo = GameHub.RoomInfo;
67
+ export type MpRoom = GameHub.MpRoom;
68
+ export type MpJoinRequest = GameHub.MpJoinRequest;
69
+ export type MpEventHandler = GameHub.MpEventHandler;
70
+ export type MpMessage<T = any> = GameHub.MpMessage<T>;
71
+ export type RoomOptions = GameHub.RoomOptions;
72
+ export type JoinOptions = GameHub.JoinOptions;
73
+ export type CreateRoomResult = GameHub.CreateRoomResult;
74
+ export type JoinRoomResult = GameHub.JoinRoomResult;
75
+
76
+ export type ScoreMetadata = GameHub.ScoreMetadata;
77
+ export type GameCompleteData = GameHub.GameCompleteData;
78
+ export type EventData = GameHub.EventData;
79
+ export type QuestionOptions = GameHub.QuestionOptions;
80
+ export type Question = GameHub.Question;
81
+ export type StartSessionResult = GameHub.StartSessionResult;
82
+ export type SubmitScoreResult = GameHub.SubmitScoreResult;
83
+
84
+ export type Sdk = GameHub.Public.Sdk;
85
+ }
86
+
87
+ declare const gamehubSdk: GameHub.Public.Sdk;
88
+
89
+ // \`export =\` mirrors the runtime (\`module.exports = sdk\`) so consumers get the
90
+ // raw SDK object both from \`require()\` and, with esModuleInterop, from
91
+ // \`import sdk from 'gamehub-sdk'\`.
92
+ export = gamehubSdk;
93
+ `;
94
+
95
+ writeFileSync(outPath, content);
96
+ console.log('Wrote ' + outPath);
@@ -0,0 +1,33 @@
1
+ namespace GameHub.Api {
2
+ /**
3
+ * Performs a request against the GameHub REST API, prefixing the configured
4
+ * API base, attaching the Bearer auth token when available, and parsing the
5
+ * JSON response.
6
+ *
7
+ * Throws whatever `fetch`/`JSON.parse` throw — callers decide whether to
8
+ * retry, fall back, or surface the error to the host.
9
+ */
10
+ export async function apiRequest(
11
+ endpoint: string,
12
+ options: ApiRequestOptions = {}
13
+ ): Promise<ApiResponse> {
14
+ const url = GameHub.State.apiBase + endpoint;
15
+ const headers: Record<string, string> = {
16
+ 'Content-Type': 'application/json',
17
+ ...(options.headers || {}),
18
+ };
19
+
20
+ if (GameHub.State.authToken) {
21
+ headers.Authorization = 'Bearer ' + GameHub.State.authToken;
22
+ }
23
+
24
+ const response = await fetch(url, {
25
+ ...options,
26
+ credentials: options.credentials || 'same-origin',
27
+ headers,
28
+ body: options.body ? JSON.stringify(options.body) : undefined,
29
+ });
30
+
31
+ return response.json();
32
+ }
33
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Cross-origin communication layer between the game iframe and its host page.
3
+ *
4
+ * Messages are namespaced with {@link GameHub.MESSAGE_PREFIX} so we don't pick
5
+ * up unrelated postMessage traffic. The host is expected to implement a small
6
+ * protocol (BOOTSTRAP_REQUEST / BOOTSTRAP, AUTH_REQUEST / AUTH_RESPONSE, etc.).
7
+ */
8
+ namespace GameHub.Bridge {
9
+ /**
10
+ * Fold a {@link BootstrapConfig} from the host into internal state. Accepts
11
+ * partial configs: only the fields that are explicitly set (including
12
+ * explicit `null`s used to clear a value) are applied.
13
+ */
14
+ export function mergeBootstrapConfig(config: BootstrapConfig = {}): void {
15
+ if (!config || typeof config !== 'object') return;
16
+ const S = GameHub.State;
17
+
18
+ if (typeof config.gameSlug === 'string' && config.gameSlug.trim()) {
19
+ S.gameSlug = config.gameSlug.trim();
20
+ }
21
+
22
+ if (typeof config.authToken === 'string') {
23
+ S.authToken = config.authToken;
24
+ } else if (config.authToken === null) {
25
+ S.authToken = null;
26
+ }
27
+
28
+ if (typeof config.leagueId === 'string' && config.leagueId.trim()) {
29
+ S.leagueId = config.leagueId.trim();
30
+ } else if (config.leagueId === null) {
31
+ S.leagueId = null;
32
+ }
33
+
34
+ if (typeof config.gameId === 'string' && config.gameId.trim()) {
35
+ S.gameId = config.gameId.trim();
36
+ } else if (config.gameId === null) {
37
+ S.gameId = null;
38
+ }
39
+
40
+ if (typeof config.matchId === 'string' && config.matchId.trim()) {
41
+ S.matchId = config.matchId.trim();
42
+ } else if (config.matchId === null) {
43
+ S.matchId = null;
44
+ }
45
+
46
+ if (
47
+ typeof config.participant1Id === 'string' &&
48
+ config.participant1Id.trim()
49
+ ) {
50
+ S.participant1Id = config.participant1Id.trim();
51
+ } else if (config.participant1Id === null) {
52
+ S.participant1Id = null;
53
+ }
54
+
55
+ if (
56
+ typeof config.participant2Id === 'string' &&
57
+ config.participant2Id.trim()
58
+ ) {
59
+ S.participant2Id = config.participant2Id.trim();
60
+ } else if (config.participant2Id === null) {
61
+ S.participant2Id = null;
62
+ }
63
+
64
+ if (Array.isArray(config.participant1MemberIds)) {
65
+ S.participant1MemberIds = config.participant1MemberIds.filter(Boolean);
66
+ }
67
+
68
+ if (Array.isArray(config.participant2MemberIds)) {
69
+ S.participant2MemberIds = config.participant2MemberIds.filter(Boolean);
70
+ }
71
+
72
+ if (typeof config.playerName === 'string' && config.playerName.trim()) {
73
+ S.bootstrapPlayerName = config.playerName.trim();
74
+ } else if (config.playerName === null) {
75
+ S.bootstrapPlayerName = null;
76
+ }
77
+
78
+ if (typeof config.peerId === 'string' && config.peerId.trim()) {
79
+ S.bootstrapPeerId = config.peerId.trim();
80
+ } else if (config.peerId === null) {
81
+ S.bootstrapPeerId = null;
82
+ }
83
+
84
+ // `room` is an object on the wire so roomCode/shareId/maxPlayers and
85
+ // optional live join credentials stay
86
+ // grouped — but SDK state keeps them flat to avoid allocating a fresh
87
+ // object on every merge and to keep URL-seeded values (e.g. from
88
+ // `?roomCode=`) in the same place.
89
+ if (config.room && typeof config.room === 'object') {
90
+ const room = config.room;
91
+
92
+ if (typeof room.roomCode === 'string' && room.roomCode.trim()) {
93
+ S.bootstrapRoomCode = room.roomCode.trim().toUpperCase();
94
+ } else if (room.roomCode === null) {
95
+ S.bootstrapRoomCode = null;
96
+ }
97
+
98
+ if (typeof room.shareId === 'string' && room.shareId.trim()) {
99
+ S.bootstrapShareId = room.shareId.trim();
100
+ } else if (room.shareId === null) {
101
+ S.bootstrapShareId = null;
102
+ }
103
+
104
+ if (
105
+ typeof room.maxPlayers === 'number' &&
106
+ Number.isFinite(room.maxPlayers)
107
+ ) {
108
+ S.bootstrapMaxPlayers = room.maxPlayers;
109
+ } else if (room.maxPlayers === null) {
110
+ S.bootstrapMaxPlayers = null;
111
+ }
112
+
113
+ if (typeof room.role === 'string' && room.role.trim()) {
114
+ S.bootstrapRoomRole = room.role.trim();
115
+ } else if (room.role === null) {
116
+ S.bootstrapRoomRole = null;
117
+ }
118
+
119
+ if (typeof room.roomToken === 'string' && room.roomToken.trim()) {
120
+ S.bootstrapRoomToken = room.roomToken.trim();
121
+ } else if (room.roomToken === null) {
122
+ S.bootstrapRoomToken = null;
123
+ }
124
+
125
+ if (typeof room.wsUrl === 'string' && room.wsUrl.trim()) {
126
+ S.bootstrapWsUrl = room.wsUrl.trim();
127
+ } else if (room.wsUrl === null) {
128
+ S.bootstrapWsUrl = null;
129
+ }
130
+ } else if (config.room === null) {
131
+ S.bootstrapRoomCode = null;
132
+ S.bootstrapShareId = null;
133
+ S.bootstrapMaxPlayers = null;
134
+ S.bootstrapRoomRole = null;
135
+ S.bootstrapRoomToken = null;
136
+ S.bootstrapWsUrl = null;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Ask the host for its bootstrap payload. Resolves `null` if the game is
142
+ * standalone (no parent), if the host doesn't reply within the timeout, or
143
+ * if we're not in an iframe.
144
+ *
145
+ * Subsequent calls after a successful bootstrap short-circuit to the cached
146
+ * state snapshot.
147
+ */
148
+ export function requestBootstrapFromParent(): Promise<BootstrapConfig | null> {
149
+ const S = GameHub.State;
150
+
151
+ if (window.parent === window) {
152
+ return Promise.resolve(null);
153
+ }
154
+
155
+ if (S.bootstrapReceived) {
156
+ return Promise.resolve({
157
+ gameSlug: S.gameSlug,
158
+ authToken: S.authToken,
159
+ leagueId: S.leagueId,
160
+ gameId: S.gameId,
161
+ matchId: S.matchId,
162
+ participant1Id: S.participant1Id,
163
+ participant2Id: S.participant2Id,
164
+ participant1MemberIds: S.participant1MemberIds,
165
+ participant2MemberIds: S.participant2MemberIds,
166
+ playerName: S.bootstrapPlayerName,
167
+ peerId: S.bootstrapPeerId,
168
+ room: S.bootstrapRoomCode
169
+ ? {
170
+ roomCode: S.bootstrapRoomCode,
171
+ shareId: S.bootstrapShareId,
172
+ maxPlayers: S.bootstrapMaxPlayers,
173
+ role: S.bootstrapRoomRole,
174
+ roomToken: S.bootstrapRoomToken,
175
+ wsUrl: S.bootstrapWsUrl,
176
+ }
177
+ : null,
178
+ });
179
+ }
180
+
181
+ if (S.bootstrapRequestPromise) {
182
+ return S.bootstrapRequestPromise;
183
+ }
184
+
185
+ S.bootstrapRequestPromise = new Promise<BootstrapConfig | null>(
186
+ (resolve) => {
187
+ const messageId = Date.now().toString();
188
+ let settled = false;
189
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
190
+
191
+ const handler = (event: MessageEvent) => {
192
+ if (
193
+ event.data &&
194
+ event.data.type === GameHub.MESSAGE_PREFIX + '_BOOTSTRAP' &&
195
+ event.data.payload
196
+ ) {
197
+ if (event.data.messageId && event.data.messageId !== messageId) {
198
+ return;
199
+ }
200
+
201
+ if (settled) return;
202
+ settled = true;
203
+ window.removeEventListener('message', handler);
204
+ if (timeoutId) clearTimeout(timeoutId);
205
+ S.parentOrigin = event.origin;
206
+ S.bootstrapReceived = true;
207
+ mergeBootstrapConfig(event.data.payload);
208
+ resolve(event.data.payload);
209
+ }
210
+ };
211
+
212
+ window.addEventListener('message', handler);
213
+ window.parent.postMessage(
214
+ {
215
+ type: GameHub.MESSAGE_PREFIX + '_BOOTSTRAP_REQUEST',
216
+ messageId,
217
+ },
218
+ '*'
219
+ );
220
+
221
+ timeoutId = setTimeout(() => {
222
+ if (settled) return;
223
+ settled = true;
224
+ window.removeEventListener('message', handler);
225
+ resolve(null);
226
+ }, GameHub.PARENT_REQUEST_TIMEOUT_MS);
227
+ }
228
+ ).finally(() => {
229
+ S.bootstrapRequestPromise = null;
230
+ });
231
+
232
+ return S.bootstrapRequestPromise;
233
+ }
234
+
235
+ /**
236
+ * Ask the host for a fresh auth token. The host may also use the response to
237
+ * override league/match context — when it does, we prefer its values over
238
+ * whatever was on the URL.
239
+ */
240
+ export function getAuthTokenFromParent(): Promise<string | null> {
241
+ return new Promise((resolve) => {
242
+ if (window.parent === window) {
243
+ resolve(null);
244
+ return;
245
+ }
246
+
247
+ const S = GameHub.State;
248
+ const messageId = Date.now().toString();
249
+ let settled = false;
250
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
251
+
252
+ const handler = (event: MessageEvent) => {
253
+ if (
254
+ event.data &&
255
+ event.data.type === GameHub.MESSAGE_PREFIX + '_AUTH_RESPONSE' &&
256
+ event.data.messageId === messageId
257
+ ) {
258
+ if (settled) return;
259
+ settled = true;
260
+ window.removeEventListener('message', handler);
261
+ if (timeoutId) clearTimeout(timeoutId);
262
+ S.parentOrigin = event.origin;
263
+ // Host-supplied context wins over URL params.
264
+ if (event.data.leagueId) S.leagueId = event.data.leagueId;
265
+ if (event.data.gameId) S.gameId = event.data.gameId;
266
+ if (event.data.matchId) S.matchId = event.data.matchId;
267
+ if (event.data.participant1Id)
268
+ S.participant1Id = event.data.participant1Id;
269
+ if (event.data.participant2Id)
270
+ S.participant2Id = event.data.participant2Id;
271
+ if (Array.isArray(event.data.participant1MemberIds))
272
+ S.participant1MemberIds =
273
+ event.data.participant1MemberIds.filter(Boolean);
274
+ if (Array.isArray(event.data.participant2MemberIds))
275
+ S.participant2MemberIds =
276
+ event.data.participant2MemberIds.filter(Boolean);
277
+ resolve(event.data.token || null);
278
+ }
279
+ };
280
+
281
+ window.addEventListener('message', handler);
282
+ window.parent.postMessage(
283
+ { type: GameHub.MESSAGE_PREFIX + '_AUTH_REQUEST', messageId },
284
+ '*'
285
+ );
286
+
287
+ timeoutId = setTimeout(() => {
288
+ if (settled) return;
289
+ settled = true;
290
+ window.removeEventListener('message', handler);
291
+ resolve(null);
292
+ }, GameHub.PARENT_REQUEST_TIMEOUT_MS);
293
+ });
294
+ }
295
+
296
+ /**
297
+ * Fire a namespaced message up to the host window. Silently no-ops when we
298
+ * aren't inside an iframe.
299
+ */
300
+ export function sendToParent(type: string, data: Record<string, any>): void {
301
+ if (window.parent !== window) {
302
+ window.parent.postMessage(
303
+ {
304
+ type: GameHub.MESSAGE_PREFIX + '_' + type,
305
+ gameSlug: GameHub.State.gameSlug,
306
+ ...data,
307
+ },
308
+ GameHub.State.parentOrigin || '*'
309
+ );
310
+ }
311
+ }
312
+ }
@@ -0,0 +1,24 @@
1
+ namespace GameHub {
2
+ /**
3
+ * Bundle version reported by the SDK. Bumped at release time.
4
+ */
5
+ export const SDK_VERSION = '0.1.0';
6
+
7
+ /**
8
+ * Prefix applied to every cross-origin postMessage the SDK emits and accepts.
9
+ * Keeps our messages isolated from unrelated frames on the same page.
10
+ */
11
+ export const MESSAGE_PREFIX = 'GAMEHUB_SDK';
12
+
13
+ /** How long to wait for the host to reply to bootstrap/auth requests. */
14
+ export const PARENT_REQUEST_TIMEOUT_MS = 2000;
15
+
16
+ /** Maximum number of WebSocket reconnect attempts before giving up. */
17
+ export const MP_MAX_RECONNECT_ATTEMPTS = 5;
18
+
19
+ /** Hard cap on reconnect backoff. */
20
+ export const MP_MAX_RECONNECT_DELAY_MS = 10_000;
21
+
22
+ /** Upper bound used when the caller doesn't pass an explicit limit. */
23
+ export const QUESTIONS_LIMIT_CAP = 100;
24
+ }