@ksaa-nlp/gamehub-sdk 3.5.0 → 3.6.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 +7 -2
- package/SPEC.md +7 -3
- package/dist/gamehub-sdk.js +6 -2
- package/dist/gamehub-sdk.js.map +2 -2
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/main.d.ts +1 -1
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +6 -0
- package/dist/src/main.js.map +1 -1
- package/dist/types/session.d.ts +25 -2
- package/dist/types/session.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -152,9 +152,14 @@ sdk.logEvent('used_powerup', { kind: 'extra_time' }); // analytics breadcrumb
|
|
|
152
152
|
|
|
153
153
|
// Let the player flag the current question — the host opens a report dialog
|
|
154
154
|
sdk.reportQuestion({ questionId: q.id, prompt: q.prompt });
|
|
155
|
+
|
|
156
|
+
// …or let the player pick which question to report from a dropdown
|
|
157
|
+
sdk.reportQuestion({
|
|
158
|
+
questions: quiz.map((q) => ({ questionId: q.id, prompt: q.prompt })),
|
|
159
|
+
});
|
|
155
160
|
```
|
|
156
161
|
|
|
157
|
-
All of these are fire-and-forget — they just `postMessage` to the parent window. `reportQuestion` asks the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it).
|
|
162
|
+
All of these are fire-and-forget — they just `postMessage` to the parent window. `reportQuestion` asks the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it). Pass `questions` instead of a single `questionId` to have the host render a dropdown so the player chooses which question to report.
|
|
158
163
|
|
|
159
164
|
## Pause/resume from the host
|
|
160
165
|
|
|
@@ -222,7 +227,7 @@ sdk.getQuestions({ difficulty, category, limit }); // Promise<Question[]>
|
|
|
222
227
|
sdk.notifyComplete(data?); // void
|
|
223
228
|
sdk.requestClose(); // void
|
|
224
229
|
sdk.logEvent(name, data?); // void
|
|
225
|
-
sdk.reportQuestion({ questionId
|
|
230
|
+
sdk.reportQuestion({ questionId?, prompt?, message?, questions? }); // void
|
|
226
231
|
|
|
227
232
|
// Context
|
|
228
233
|
sdk.getGameSlug(); // string | null
|
package/SPEC.md
CHANGED
|
@@ -170,7 +170,7 @@ The SDK communicates with the host page through namespaced `postMessage` envelop
|
|
|
170
170
|
| SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
|
|
171
171
|
| SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
|
|
172
172
|
| SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
|
|
173
|
-
| SDK → host | `QUESTION_REPORT` | Fired by `sdk.reportQuestion(data)`. Carries `{ questionId
|
|
173
|
+
| SDK → host | `QUESTION_REPORT` | Fired by `sdk.reportQuestion(data)`. Carries `{ questionId?, prompt?, message?, questions? }`. With `questions` the host renders a question-picker dropdown; otherwise it reports the single `questionId`. |
|
|
174
174
|
| SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6. |
|
|
175
175
|
| host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6. |
|
|
176
176
|
|
|
@@ -505,9 +505,13 @@ interface SdkState {
|
|
|
505
505
|
| `notifyComplete(data?)` | `void` | `GAME_COMPLETE` |
|
|
506
506
|
| `requestClose()` | `void` | `REQUEST_CLOSE` |
|
|
507
507
|
| `logEvent(eventName, eventData?)` | `void` | `LOG_EVENT { event: eventName, data: eventData }` |
|
|
508
|
-
| `reportQuestion(data)` | `void` | `QUESTION_REPORT { questionId
|
|
508
|
+
| `reportQuestion(data)` | `void` | `QUESTION_REPORT { questionId?, prompt?, message?, questions? }` |
|
|
509
509
|
|
|
510
|
-
`reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog
|
|
510
|
+
`reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog. The host owns the dialog (the SDK renders no DOM — see §19.3) and submits the report, collecting the reason, an optional message, and — for guests — name/email. Like the other host signals it no-ops outside an iframe.
|
|
511
|
+
|
|
512
|
+
Two modes:
|
|
513
|
+
- **Single question** — pass `questionId` (and optionally `prompt`). The dialog reports that one question.
|
|
514
|
+
- **Pick from a list** — pass `questions: ReportableQuestion[]` (each `{ questionId, prompt? }`). The host renders a dropdown so the player chooses which question to report; `questionId`, when also supplied, pre-selects an entry. The `questions` array is forwarded verbatim (each entry normalised to `{ questionId, prompt }`) on the `QUESTION_REPORT` envelope.
|
|
511
515
|
|
|
512
516
|
### 14.7 Read-only context
|
|
513
517
|
|
package/dist/gamehub-sdk.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
(() => {
|
|
3
3
|
// src/constants.ts
|
|
4
|
-
var SDK_VERSION = "3.
|
|
4
|
+
var SDK_VERSION = "3.6.0";
|
|
5
5
|
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
6
|
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
7
|
var HOST_API_TIMEOUT_MS = 15e3;
|
|
@@ -634,7 +634,11 @@
|
|
|
634
634
|
sendToParent("QUESTION_REPORT", {
|
|
635
635
|
questionId: data.questionId,
|
|
636
636
|
prompt: data.prompt,
|
|
637
|
-
message: data.message
|
|
637
|
+
message: data.message,
|
|
638
|
+
questions: Array.isArray(data.questions) ? data.questions.map((q) => ({
|
|
639
|
+
questionId: q.questionId,
|
|
640
|
+
prompt: q.prompt
|
|
641
|
+
})) : void 0
|
|
638
642
|
});
|
|
639
643
|
},
|
|
640
644
|
logEvent(eventName, eventData = {}) {
|
package/dist/gamehub-sdk.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/constants.ts", "../src/state.ts", "../src/utils.ts", "../src/bridge.ts", "../src/api-client.ts", "../src/session.ts", "../src/init.ts", "../src/match-context.ts", "../src/main.ts", "../src/browser-entry.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Bundle version reported by the SDK. Bumped at release time.\n */\nexport const SDK_VERSION = '3.5.0';\n\n/**\n * Prefix applied to every cross-origin postMessage the SDK emits and accepts.\n * Keeps our messages isolated from unrelated frames on the same page.\n */\nexport const MESSAGE_PREFIX = 'GAMEHUB_SDK';\n\n/** How long to wait for the host to reply to bootstrap/auth requests. */\nexport const PARENT_REQUEST_TIMEOUT_MS = 2000;\n\n/**\n * How long to wait for the host to proxy an HTTP API request back to the\n * SDK. Larger than {@link PARENT_REQUEST_TIMEOUT_MS} because this round-trip\n * includes the host's real network call to the GameHub backend.\n */\nexport const HOST_API_TIMEOUT_MS = 15000;\n\n/** Upper bound on questions returned per `getQuestions` call. */\nexport const QUESTIONS_LIMIT_CAP = 100;\n", "/**\n * Centralised mutable state for the SDK singleton.\n *\n * Everything here lives on a single `state` object so feature modules\n * can mutate it (`state.foo = bar`). ES modules don't allow reassigning\n * imported `let` bindings from the consumer side, so a single shared\n * object is the cleanest replacement for the namespace + `export let`\n * pattern used in earlier SDK versions.\n */\n\nimport type {\n BootstrapConfig,\n BootstrapMultiplayer,\n} from '../types/bootstrap.js';\nimport type { MatchContext } from '../types/match.js';\nimport type { StartSessionResult } from '../types/session.js';\n\nexport interface SdkState {\n // --- API endpoint resolution -------------------------------------------\n sdkOrigin: string;\n sdkPathPrefix: string;\n runtimeBasePath: string;\n apiBase: string;\n\n // --- Game / league context ---------------------------------------------\n gameSlug: string | null;\n sessionToken: string | null;\n authToken: string | null;\n leagueId: string | null;\n gameId: string | null;\n matchId: string | null;\n\n // --- Free-form bootstrap fields (display only) -------------------------\n bootstrapMode: string | null;\n bootstrapPlayerName: string | null;\n bootstrapPlayerCount: string | null;\n bootstrapTeamOneName: string | null;\n bootstrapTeamTwoName: string | null;\n /** Player's pre-start profile choice; default for `getQuestions`. */\n bootstrapProfileId: string | null;\n\n // --- Multiplayer bootstrap ---------------------------------------------\n // Opaque to the SDK \u2014 exposed verbatim on `getBootstrap().multiplayer`\n // for games to feed into their realtime client (e.g. `@colyseus/sdk`'s\n // `client.reconnect(...)`). The SDK does not open or manage the socket.\n bootstrapMultiplayer: BootstrapMultiplayer | null;\n bootstrapReceived: boolean;\n\n // --- Initialisation lifecycle ------------------------------------------\n isInitialized: boolean;\n isAutoInitializing: boolean;\n autoInitPromise: Promise<boolean> | null;\n bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;\n parentOrigin: string | null;\n sessionStartPromise: Promise<StartSessionResult> | null;\n\n // --- League match context (HTTP) ---------------------------------------\n /** Cached league match context, loaded on demand. */\n matchContext: MatchContext | null;\n /** In-flight match-context fetch, deduped across callers. */\n matchContextPromise: Promise<MatchContext | null> | null;\n}\n\nexport const state: SdkState = {\n sdkOrigin: '',\n sdkPathPrefix: '',\n runtimeBasePath: '',\n apiBase: '',\n\n gameSlug: null,\n sessionToken: null,\n authToken: null,\n leagueId: null,\n gameId: null,\n matchId: null,\n\n bootstrapMode: null,\n bootstrapPlayerName: null,\n bootstrapPlayerCount: null,\n bootstrapTeamOneName: null,\n bootstrapTeamTwoName: null,\n bootstrapProfileId: null,\n\n bootstrapMultiplayer: null,\n bootstrapReceived: false,\n\n isInitialized: false,\n isAutoInitializing: false,\n autoInitPromise: null,\n bootstrapRequestPromise: null,\n parentOrigin: null,\n sessionStartPromise: null,\n\n matchContext: null,\n matchContextPromise: null,\n};\n", "import type { ApiResponse } from '../types/api.js';\n\n/**\n * True when running in a browser-like environment (has both `window` and\n * `document`). Used to short-circuit DOM-touching helpers so the package\n * can be imported under Node / Angular SSR without throwing.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Logs with a consistent `[GameHubSDK]` prefix so host-page developers can\n * easily filter SDK messages in their console.\n */\nexport function warn(message: string, ...rest: any[]): void {\n console.warn('[GameHubSDK] ' + message, ...rest);\n}\n\nexport function error(message: string, ...rest: any[]): void {\n console.error('[GameHubSDK] ' + message, ...rest);\n}\n\n/**\n * Flattens the standard `{ success, data }` envelope returned by the\n * GameHub REST API down to the inner `data` payload. Returns the raw\n * response when the envelope shape doesn't apply.\n */\nexport function unwrapResult(result: ApiResponse | null | undefined): any {\n if (!result) return null;\n if (result.success && result.data) return result.data;\n return result;\n}\n\n/**\n * Safely read a query-string parameter, falling back to a regex scan when\n * URLSearchParams is unavailable (very old browsers / odd runtimes).\n */\nexport function readQueryParam(name: string): string | null {\n try {\n const params = new URLSearchParams(window.location.search);\n return params.get(name);\n } catch {\n const match = window.location.search.match(\n new RegExp('[?&]' + name + '=([^&]+)')\n );\n return match ? decodeURIComponent(match[1]) : null;\n }\n}\n", "/**\n * Cross-origin communication layer between the game iframe and its host page.\n *\n * Messages are namespaced with `MESSAGE_PREFIX` so we don't pick up\n * unrelated postMessage traffic. The host implements a small protocol:\n * - `BOOTSTRAP_REQUEST` \u21C4 `BOOTSTRAP` (initial config + multiplayer)\n * - `AUTH_REQUEST` \u21C4 `AUTH_RESPONSE` (refresh the bearer token)\n * - `READY` / `INIT` / `SESSION_STARTED` / `SCORE_SUBMITTED` / etc.\n * (one-way SDK \u2192 host signals)\n */\n\nimport { state } from './state.js';\nimport {\n MESSAGE_PREFIX,\n PARENT_REQUEST_TIMEOUT_MS,\n HOST_API_TIMEOUT_MS,\n} from './constants.js';\nimport { isBrowser } from './utils.js';\nimport type {\n BootstrapConfig,\n BootstrapMultiplayer,\n} from '../types/bootstrap.js';\nimport type { ApiResponse, ApiRequestOptions } from '../types/api.js';\n\nfunction trimToNullable(value: unknown): string | null | undefined {\n if (value === null) return null;\n if (typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n return trimmed ? trimmed : null;\n}\n\nfunction parseMultiplayer(\n value: BootstrapConfig['multiplayer']\n): BootstrapMultiplayer | null | undefined {\n if (value === null) return null;\n if (!value || typeof value !== 'object') return undefined;\n const { reservation, wsEndpoint } = value;\n if (\n !reservation ||\n typeof reservation !== 'object' ||\n typeof (reservation as { name?: unknown }).name !== 'string' ||\n typeof (reservation as { sessionId?: unknown }).sessionId !== 'string' ||\n typeof (reservation as { roomId?: unknown }).roomId !== 'string' ||\n typeof wsEndpoint !== 'string'\n ) {\n return undefined;\n }\n return {\n reservation,\n wsEndpoint: wsEndpoint.trim(),\n };\n}\n\n/**\n * Fold a {@link BootstrapConfig} from the host into internal state. Accepts\n * partial configs: only fields the host explicitly set (including explicit\n * `null`s used to clear a value) are applied.\n */\nexport function mergeBootstrapConfig(config: BootstrapConfig = {}): void {\n if (!config || typeof config !== 'object') return;\n\n const apply = (\n key: 'gameSlug' | 'authToken' | 'leagueId' | 'gameId' | 'matchId',\n raw: unknown\n ) => {\n const next = trimToNullable(raw);\n if (next === undefined) return;\n state[key] = next;\n };\n\n apply('gameSlug', config.gameSlug);\n apply('authToken', config.authToken);\n apply('leagueId', config.leagueId);\n apply('gameId', config.gameId);\n apply('matchId', config.matchId);\n\n const applyBootstrap = (\n key:\n | 'bootstrapMode'\n | 'bootstrapPlayerName'\n | 'bootstrapPlayerCount'\n | 'bootstrapTeamOneName'\n | 'bootstrapTeamTwoName'\n | 'bootstrapProfileId',\n raw: unknown\n ) => {\n const next = trimToNullable(raw);\n if (next === undefined) return;\n state[key] = next;\n };\n\n applyBootstrap('bootstrapMode', config.mode);\n applyBootstrap('bootstrapPlayerName', config.playerName);\n applyBootstrap('bootstrapPlayerCount', config.playerCount);\n applyBootstrap('bootstrapTeamOneName', config.teamOneName);\n applyBootstrap('bootstrapTeamTwoName', config.teamTwoName);\n applyBootstrap('bootstrapProfileId', config.profileId);\n\n const mp = parseMultiplayer(config.multiplayer);\n if (mp !== undefined) {\n state.bootstrapMultiplayer = mp;\n }\n}\n\nfunction snapshotBootstrap(): BootstrapConfig {\n return {\n gameSlug: state.gameSlug,\n authToken: state.authToken,\n leagueId: state.leagueId,\n gameId: state.gameId,\n matchId: state.matchId,\n mode: state.bootstrapMode,\n playerName: state.bootstrapPlayerName,\n playerCount: state.bootstrapPlayerCount,\n teamOneName: state.bootstrapTeamOneName,\n teamTwoName: state.bootstrapTeamTwoName,\n profileId: state.bootstrapProfileId,\n multiplayer: state.bootstrapMultiplayer,\n };\n}\n\n/**\n * Ask the host for its bootstrap payload. Resolves `null` if the game is\n * standalone (no parent) or the host doesn't reply within the timeout.\n *\n * Subsequent calls after a successful bootstrap short-circuit to the\n * cached state snapshot.\n */\nexport function requestBootstrapFromParent(): Promise<BootstrapConfig | null> {\n if (!isBrowser() || window.parent === window) {\n return Promise.resolve(null);\n }\n\n if (state.bootstrapReceived) {\n return Promise.resolve(snapshotBootstrap());\n }\n\n if (state.bootstrapRequestPromise) {\n return state.bootstrapRequestPromise;\n }\n\n state.bootstrapRequestPromise = new Promise<BootstrapConfig | null>(\n (resolve) => {\n const messageId = Date.now().toString();\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const handler = (event: MessageEvent) => {\n if (\n event.data &&\n event.data.type === MESSAGE_PREFIX + '_BOOTSTRAP' &&\n event.data.payload\n ) {\n if (event.data.messageId && event.data.messageId !== messageId) {\n return;\n }\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n if (timeoutId) clearTimeout(timeoutId);\n state.parentOrigin = event.origin;\n state.bootstrapReceived = true;\n mergeBootstrapConfig(event.data.payload);\n resolve(event.data.payload);\n }\n };\n\n window.addEventListener('message', handler);\n window.parent.postMessage(\n {\n type: MESSAGE_PREFIX + '_BOOTSTRAP_REQUEST',\n messageId,\n },\n '*'\n );\n\n timeoutId = setTimeout(() => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n resolve(null);\n }, PARENT_REQUEST_TIMEOUT_MS);\n }\n ).finally(() => {\n state.bootstrapRequestPromise = null;\n });\n\n return state.bootstrapRequestPromise;\n}\n\n/**\n * Ask the host for a fresh auth token. The host may also use the response\n * to override league/match context \u2014 when it does, we prefer its values.\n */\nexport function getAuthTokenFromParent(): Promise<string | null> {\n return new Promise((resolve) => {\n if (!isBrowser() || window.parent === window) {\n resolve(null);\n return;\n }\n\n const messageId = Date.now().toString();\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const handler = (event: MessageEvent) => {\n if (\n event.data &&\n event.data.type === MESSAGE_PREFIX + '_AUTH_RESPONSE' &&\n event.data.messageId === messageId\n ) {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n if (timeoutId) clearTimeout(timeoutId);\n state.parentOrigin = event.origin;\n if (event.data.leagueId) state.leagueId = event.data.leagueId;\n if (event.data.gameId) state.gameId = event.data.gameId;\n if (event.data.matchId) state.matchId = event.data.matchId;\n resolve(event.data.token || null);\n }\n };\n\n window.addEventListener('message', handler);\n window.parent.postMessage(\n { type: MESSAGE_PREFIX + '_AUTH_REQUEST', messageId },\n '*'\n );\n\n timeoutId = setTimeout(() => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n resolve(null);\n }, PARENT_REQUEST_TIMEOUT_MS);\n });\n}\n\n/** Monotonic counter so concurrent API proxy requests get distinct ids. */\nlet apiRequestSeq = 0;\n\n/**\n * Proxy an HTTP request to the GameHub backend through the host page.\n *\n * The host frame is same-origin with the GameHub API, so it performs the\n * real `fetch` and posts the parsed JSON envelope back. This keeps the SDK\n * (and the game it lives in) from ever issuing a cross-origin request to the\n * backend \u2014 which would otherwise fail CORS when the game is served from a\n * different domain than GameHub.\n *\n * The protocol mirrors the bootstrap/auth handshakes: a `messageId`-keyed\n * `API_REQUEST` is answered by exactly one `API_RESPONSE`. Resolves with the\n * parsed {@link ApiResponse}; rejects on host-reported failure or timeout so\n * the existing per-call `try/catch` degradation paths fire unchanged.\n */\nexport function requestApiFromParent(\n endpoint: string,\n options: ApiRequestOptions = {}\n): Promise<ApiResponse> {\n return new Promise<ApiResponse>((resolve, reject) => {\n if (!isBrowser() || window.parent === window) {\n reject(new Error('Host bridge unavailable: not running in an iframe'));\n return;\n }\n\n const messageId = 'api_' + Date.now().toString() + '_' + ++apiRequestSeq;\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const handler = (event: MessageEvent) => {\n if (\n !event.data ||\n event.data.type !== MESSAGE_PREFIX + '_API_RESPONSE' ||\n event.data.messageId !== messageId\n ) {\n return;\n }\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n if (timeoutId) clearTimeout(timeoutId);\n state.parentOrigin = event.origin;\n if (event.data.ok) {\n resolve((event.data.result ?? {}) as ApiResponse);\n } else {\n reject(new Error(event.data.error || 'Host API request failed'));\n }\n };\n\n window.addEventListener('message', handler);\n window.parent.postMessage(\n {\n type: MESSAGE_PREFIX + '_API_REQUEST',\n messageId,\n endpoint,\n method: options.method || 'GET',\n body: options.body ?? null,\n },\n state.parentOrigin || '*'\n );\n\n timeoutId = setTimeout(() => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n reject(new Error('Host API request timed out'));\n }, HOST_API_TIMEOUT_MS);\n });\n}\n\n/**\n * Fire a namespaced message up to the host window. Silently no-ops when\n * we aren't inside an iframe.\n */\nexport function sendToParent(type: string, data: Record<string, any>): void {\n if (!isBrowser() || window.parent === window) return;\n window.parent.postMessage(\n {\n type: MESSAGE_PREFIX + '_' + type,\n gameSlug: state.gameSlug,\n ...data,\n },\n state.parentOrigin || '*'\n );\n}\n", "import { state } from './state.js';\nimport { isBrowser } from './utils.js';\nimport { requestApiFromParent } from './bridge.js';\nimport type { ApiResponse, ApiRequestOptions } from '../types/api.js';\n\n/**\n * Performs a request against the GameHub REST API and parses the JSON\n * response.\n *\n * Transport is chosen by context:\n * - **Inside the host iframe** the request is proxied through the host via\n * postMessage ({@link requestApiFromParent}). The host is same-origin\n * with the GameHub backend, so the game never issues a cross-origin call\n * itself \u2014 this is what keeps the SDK CORS-free when the game is served\n * from a different domain than GameHub.\n * - **Standalone** (dev harness / a game served from the GameHub origin)\n * the SDK calls the backend directly, prefixing the configured API base\n * and attaching the Bearer auth token when available.\n *\n * Throws whatever the transport throws (host failure/timeout, or\n * `fetch`/`JSON.parse`) \u2014 callers decide whether to retry, fall back, or\n * surface the error to the host.\n */\nexport async function apiRequest(\n endpoint: string,\n options: ApiRequestOptions = {}\n): Promise<ApiResponse> {\n // When embedded, let the host (same-origin with the API) make the call.\n if (isBrowser() && window.parent !== window) {\n return requestApiFromParent(endpoint, options);\n }\n\n const url = state.apiBase + endpoint;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers || {}),\n };\n\n if (state.authToken) {\n headers.Authorization = 'Bearer ' + state.authToken;\n }\n\n const response = await fetch(url, {\n ...options,\n credentials: options.credentials || 'same-origin',\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n });\n\n return response.json();\n}\n", "import { state } from './state.js';\nimport { QUESTIONS_LIMIT_CAP } from './constants.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult } from './utils.js';\nimport { sendToParent } from './bridge.js';\nimport { ensureInitialized } from './init.js';\nimport type {\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\nimport type { MatchResultPayload } from '../types/match.js';\n\n/**\n * Starts a new game session and caches the returned session token. Safe\n * to call multiple times \u2014 the cached token short-circuits subsequent\n * calls.\n *\n * Endpoint is selected from the active context:\n * - league + game + match \u2192 scoped match session\n * - league + game \u2192 scoped league session\n * - otherwise \u2192 standalone session (requires auth)\n */\nexport async function startSession(): Promise<StartSessionResult> {\n if (!state.gameSlug) return { success: false, error: 'Game slug not set' };\n\n const isLeagueMatchSession = Boolean(\n state.leagueId && state.gameId && state.matchId\n );\n if (!state.authToken && !isLeagueMatchSession) {\n return { success: false, error: 'User not authenticated' };\n }\n if (state.sessionToken) return { success: true, token: state.sessionToken };\n\n try {\n let endpoint = '/sessions/start';\n let body: Record<string, any> = { gameSlug: state.gameSlug };\n\n if (state.leagueId && state.gameId && state.matchId) {\n endpoint =\n '/leagues/' + state.leagueId + '/matches/' + state.matchId + '/session';\n body = { gameId: state.gameId };\n } else if (state.leagueId && state.gameId) {\n endpoint = '/leagues/' + state.leagueId + '/sessions';\n body = { gameId: state.gameId };\n }\n\n const result = await apiRequest(endpoint, {\n method: 'POST',\n body,\n });\n\n const data = unwrapResult(result);\n if (result.success || data?.token) {\n state.sessionToken = data?.token || result?.token || null;\n sendToParent('SESSION_STARTED', { token: state.sessionToken });\n return { success: true, token: state.sessionToken };\n }\n\n return {\n success: false,\n error: result.error?.message || 'Failed to start session',\n };\n } catch (err: any) {\n return { success: false, error: err.message };\n }\n}\n\n/**\n * Submit a score to the current session. If no session exists yet we try\n * to open one (re-using any in-flight start attempt).\n *\n * Multiplayer authority lives on the Colyseus server now \u2014 score\n * submission is no longer gated by a client-side host role. Games that\n * want only one peer to call this should make that decision based on\n * their room state (e.g. `room.state.hostPeerId === selfId`).\n */\nexport async function submitScore(\n score: number,\n meta: ScoreMetadata = {}\n): Promise<SubmitScoreResult> {\n await ensureInitialized();\n\n if (!state.isInitialized) {\n return {\n success: false,\n error: 'SDK could not initialize. Is game slug set?',\n };\n }\n\n if (!state.sessionToken) {\n if (state.sessionStartPromise) {\n await state.sessionStartPromise;\n } else {\n const sessionResult = await startSession();\n if (!sessionResult.success) {\n return {\n success: false,\n error: sessionResult.error || 'Could not start session',\n };\n }\n }\n }\n\n if (!state.sessionToken) {\n return {\n success: false,\n error: 'No active session. User may not be authenticated.',\n };\n }\n\n if (typeof score !== 'number' || score < 0) {\n return { success: false, error: 'Score must be a non-negative number' };\n }\n\n try {\n const result = await apiRequest('/sessions/submit', {\n method: 'POST',\n body: {\n token: state.sessionToken,\n score: Math.floor(score),\n meta,\n },\n });\n\n const data = unwrapResult(result);\n\n if (result.success || data?.accepted) {\n sendToParent('SCORE_SUBMITTED', {\n score,\n accepted: data?.accepted,\n timeTaken: data?.timeTaken,\n });\n return {\n success: true,\n accepted: data?.accepted,\n timeTaken: data?.timeTaken,\n };\n }\n\n return {\n success: false,\n error: result.error?.message || 'Score rejected',\n };\n } catch (err: any) {\n return { success: false, error: err.message };\n }\n}\n\n/**\n * Convenience wrapper that tags a score with the current league match\n * context. Fails early if there's no matchId \u2014 a plain `submitScore` is\n * the right call in that case.\n */\nexport async function submitMatchScore(\n score: number,\n meta: ScoreMetadata = {}\n): Promise<SubmitScoreResult> {\n if (!state.matchId) {\n return {\n success: false,\n error: 'No matchId found for this game session',\n };\n }\n\n return await submitScore(score, {\n ...(meta || {}),\n matchId: state.matchId,\n leagueId: state.leagueId || meta.leagueId,\n gameId: state.gameId || meta.gameId,\n });\n}\n\n/**\n * Submit a match result (winner, scores, etc.) with a zero placeholder\n * score \u2014 the server derives the real leaderboard entries from the result\n * payload.\n */\nexport async function submitMatchResult(\n result: MatchResultPayload = {}\n): Promise<SubmitScoreResult> {\n if (!result || typeof result !== 'object') {\n return { success: false, error: 'match result payload is required' };\n }\n\n return await submitMatchScore(0, { matchResult: result });\n}\n\n/**\n * Fetch questions for this game. Returns an empty array on any failure\n * or invalid input \u2014 callers can treat \"no questions\" as the degraded\n * state.\n */\nexport async function getQuestions(\n options: QuestionOptions = {}\n): Promise<Question[]> {\n await ensureInitialized();\n\n const gameIdentifier = state.gameId || state.gameSlug;\n if (!gameIdentifier) return [];\n\n const { difficulty, category, limit } = options;\n\n if (difficulty && !['easy', 'medium', 'hard'].includes(difficulty)) {\n return [];\n }\n\n if (limit !== undefined && (typeof limit !== 'number' || limit < 1)) {\n return [];\n }\n\n // Profile selection: explicit option wins, else the bootstrap-supplied\n // profileId (the player's pre-start picker choice). Omitted \u2192 resolver\n // falls back to the game's isDefault profile (identical to today).\n const profileId = options.profileId || state.bootstrapProfileId || '';\n\n try {\n const params = new URLSearchParams({\n limit: String(\n Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)\n ),\n random: 'true',\n });\n if (state.gameId) params.set('gameId', state.gameId);\n if (difficulty) params.set('difficulty', difficulty);\n if (category) params.set('category', String(category));\n if (profileId) params.set('profileId', profileId);\n\n const result = await apiRequest(\n '/games/' +\n encodeURIComponent(gameIdentifier) +\n '/questions?' +\n params.toString(),\n { method: 'GET' }\n );\n\n const data = unwrapResult(result);\n const raw: unknown[] = Array.isArray(data)\n ? data\n : Array.isArray(data?.questions)\n ? data.questions\n : [];\n // The Mongoose `Question.answer` field allows numeric values for\n // numeric-answer questions. Coerce to string at the API boundary so\n // the canonical `Question.answer: string` invariant holds everywhere\n // downstream (offline games, UGC bundles, scoring code).\n return raw.map(normalizeQuestion);\n } catch {\n return [];\n }\n}\n\nfunction normalizeQuestion(raw: unknown): Question {\n const q = raw as Question & { answer: string | number };\n const answer = typeof q.answer === 'number' ? String(q.answer) : q.answer;\n return { ...q, answer };\n}\n", "/**\n * SDK discovery + auto-initialisation.\n *\n * Detects the API base URL (from the `<script>` tag or the page location)\n * and the active game slug, then exchanges a few postMessages with the\n * host to pick up an auth token and the bootstrap payload before opening\n * a session.\n *\n * The SDK is transport-agnostic: when the bootstrap carries a\n * `multiplayer` block, the values are exposed on\n * `sdk.getBootstrap().multiplayer` for the game to open its own realtime\n * connection (e.g. `new Client(wsEndpoint).reconnect(reconnectionToken)`\n * via `@colyseus/sdk`). The SDK never opens a socket itself.\n */\n\nimport { state } from './state.js';\nimport { MESSAGE_PREFIX } from './constants.js';\nimport { isBrowser, readQueryParam, warn, error as logError } from './utils.js';\nimport {\n mergeBootstrapConfig,\n requestBootstrapFromParent,\n getAuthTokenFromParent,\n sendToParent,\n} from './bridge.js';\nimport * as Session from './session.js';\n\nlet environmentDetected = false;\nlet hostListenerInstalled = false;\n\n/**\n * One-off environment detection. Should be called exactly once at SDK\n * boot time, before any other init function. Idempotent and safe to call\n * outside a browser (no-op).\n */\nexport function detectEnvironment(): void {\n if (!isBrowser() || environmentDetected) return;\n environmentDetected = true;\n state.sdkOrigin = window.location.origin;\n\n // Detect when the game is being served under /games/<slug>/ or\n // /uploaded-games/<slug>/ \u2014 used to infer the slug AND the mount point\n // (which the API base URL is built from).\n const runtimePathMatch = window.location.pathname.match(\n /^(.*)\\/(?:uploaded-games|games)\\/([a-z0-9-]+)(?:\\/|$)/i\n );\n let detectedSlug: string | null = null;\n if (runtimePathMatch) {\n state.runtimeBasePath = runtimePathMatch[1] || '';\n detectedSlug = runtimePathMatch[2] || null;\n }\n\n // Pull league/match context off the URL if present. The host may still\n // override these later via postMessage.\n state.leagueId = readQueryParam('leagueId');\n state.gameId = readQueryParam('gameId');\n state.matchId = readQueryParam('matchId');\n\n // Locate our own <script> tag so we can honour `data-game-slug` and\n // resolve the path prefix (needed when served from a subpath like /app).\n const scripts = document.getElementsByTagName('script');\n for (let i = 0; i < scripts.length; i++) {\n const src = scripts[i].src;\n if (!src.includes('gamehub-sdk.js')) continue;\n\n try {\n const parsedSrc = new URL(src, window.location.origin);\n state.sdkOrigin = parsedSrc.origin;\n const match = parsedSrc.pathname.match(/(.*)\\/sdk\\/gamehub-sdk\\.js$/);\n state.sdkPathPrefix = match ? match[1] || '' : '';\n } catch {\n const match = src.match(/(.*)\\/sdk\\/gamehub-sdk\\.js/);\n if (match) {\n const fallbackUrl = new URL(match[1], window.location.origin);\n state.sdkOrigin = fallbackUrl.origin;\n state.sdkPathPrefix = fallbackUrl.pathname || '';\n }\n }\n\n const slugAttr = scripts[i].getAttribute('data-game-slug');\n if (slugAttr) detectedSlug = slugAttr;\n break;\n }\n\n if (!detectedSlug) {\n const pathMatch = window.location.pathname.match(\n /\\/(?:uploaded-games|games)\\/([a-z0-9-]+)\\//i\n );\n if (pathMatch) detectedSlug = pathMatch[1];\n }\n\n const effectiveBasePath = state.sdkPathPrefix || state.runtimeBasePath || '';\n state.apiBase = state.sdkOrigin + effectiveBasePath + '/api';\n state.gameSlug = detectedSlug;\n}\n\n/**\n * Orchestrates the full SDK boot sequence:\n * 1. Request bootstrap config from the host (seeds slug + context).\n * 2. Exchange for an auth token if we don't already have one.\n * 3. Notify the host that we've booted.\n * 4. Open a session if we can, and reconnect to the Colyseus room when\n * the host gave us a `multiplayer` block.\n *\n * Safe to call multiple times \u2014 concurrent callers share a single promise.\n */\nexport async function autoInit(): Promise<boolean> {\n if (!isBrowser()) return false;\n if (state.isInitialized || state.isAutoInitializing) {\n return state.autoInitPromise as Promise<boolean>;\n }\n\n detectEnvironment();\n installHostMessageListener();\n\n state.isAutoInitializing = true;\n\n state.autoInitPromise = (async () => {\n try {\n await requestBootstrapFromParent();\n\n if (!state.gameSlug) {\n warn(\n 'Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}.'\n );\n state.isAutoInitializing = false;\n return false;\n }\n\n if (!state.authToken) {\n state.authToken = await getAuthTokenFromParent();\n }\n state.isInitialized = true;\n state.isAutoInitializing = false;\n\n sendToParent('INIT', {\n slug: state.gameSlug,\n auto: true,\n });\n\n if (\n state.authToken ||\n (state.leagueId && state.gameId && state.matchId)\n ) {\n state.sessionStartPromise = Session.startSession();\n }\n\n return true;\n } catch (err) {\n logError('Auto-init failed:', err);\n state.isAutoInitializing = false;\n return false;\n }\n })();\n\n return state.autoInitPromise;\n}\n\n/**\n * Ensures init has at least started; callers `await` this before touching\n * any state that depends on bootstrap / auth having resolved.\n */\nexport async function ensureInitialized(): Promise<boolean> {\n if (state.isInitialized) return true;\n if (!isBrowser()) return false;\n if (state.autoInitPromise) return await state.autoInitPromise;\n return await autoInit();\n}\n\n/**\n * Wires up the ambient message listener the host uses to push updates\n * into the running SDK (fresh bootstrap, rotated auth, pause/resume).\n */\nexport function installHostMessageListener(): void {\n if (!isBrowser() || hostListenerInstalled) return;\n hostListenerInstalled = true;\n window.addEventListener('message', (event: MessageEvent) => {\n if (!event.data || !event.data.type) return;\n\n const type = event.data.type;\n\n if (type === MESSAGE_PREFIX + '_BOOTSTRAP' && event.data.payload) {\n state.parentOrigin = event.origin;\n state.bootstrapReceived = true;\n mergeBootstrapConfig(event.data.payload);\n }\n\n if (type === MESSAGE_PREFIX + '_SET_AUTH') {\n state.authToken = event.data.token;\n state.parentOrigin = event.origin;\n\n if (\n state.gameSlug &&\n !state.sessionToken &&\n !state.sessionStartPromise &&\n (state.authToken || (state.leagueId && state.gameId && state.matchId))\n ) {\n state.sessionStartPromise = Session.startSession();\n }\n }\n\n if (type === MESSAGE_PREFIX + '_COMMAND') {\n const command = event.data.command;\n const w = window as any;\n if (command === 'pause' && typeof w.onGameHubPause === 'function') {\n w.onGameHubPause();\n } else if (\n command === 'resume' &&\n typeof w.onGameHubResume === 'function'\n ) {\n w.onGameHubResume();\n }\n }\n });\n}\n", "import { state } from './state.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult } from './utils.js';\nimport type { MatchContext } from '../types/match.js';\n\n/**\n * Lazily load the match context for a league game. Results are cached on\n * `state.matchContext`; concurrent callers share a single in-flight request\n * via `state.matchContextPromise`.\n *\n * Resolves `null` when required context (league or match id) is missing, or\n * when the server returns an error \u2014 callers decide how to degrade.\n */\nexport async function fetchMatchContext(): Promise<MatchContext | null> {\n if (!state.leagueId || !state.matchId) return null;\n if (state.matchContext) return state.matchContext;\n if (state.matchContextPromise) return await state.matchContextPromise;\n\n state.matchContextPromise = apiRequest(\n '/leagues/' +\n encodeURIComponent(state.leagueId) +\n '/matches/' +\n encodeURIComponent(state.matchId),\n { method: 'GET' }\n )\n .then((result) => {\n const data = unwrapResult(result);\n if (result?.success && data) {\n state.matchContext = data as MatchContext;\n return state.matchContext;\n }\n return null;\n })\n .catch(() => null)\n .finally(() => {\n state.matchContextPromise = null;\n });\n\n return await state.matchContextPromise;\n}\n", "/**\n * Public SDK module entry. Exports `createSdk` (the factory) and every\n * public type.\n *\n * Importing this module has no side effects \u2014 it does not touch\n * `window`, `document`, or run any boot logic. For the legacy\n * `<script>`-tag distribution that auto-attaches `window.GameHubSDK`\n * and runs `autoInit()`, see `./browser-entry.ts`.\n *\n * The SDK is transport-agnostic. Games that need realtime multiplayer\n * read `sdk.getBootstrap().multiplayer` and open their own connection\n * (e.g. via `@colyseus/sdk`'s `client.reconnect(...)`).\n */\n\nimport { SDK_VERSION } from './constants.js';\nimport { state } from './state.js';\nimport { sendToParent } from './bridge.js';\nimport { ensureInitialized } from './init.js';\nimport { isBrowser } from './utils.js';\nimport * as Session from './session.js';\nimport * as MatchCtx from './match-context.js';\n\nimport type { BootstrapData } from '../types/bootstrap.js';\nimport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ReportQuestionData,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\nimport type {\n MatchContext,\n MatchParticipant,\n MatchParticipantMember,\n MatchResultPayload,\n} from '../types/match.js';\n\n// Re-export public types so consumers can `import type { Sdk, ... } from\n// '@ksaa-nlp/gamehub-sdk'` without reaching into module subpaths.\nexport type { ApiRequestOptions, ApiResponse } from '../types/api.js';\nexport type {\n BootstrapConfig,\n BootstrapData,\n BootstrapMultiplayer,\n} from '../types/bootstrap.js';\nexport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ReportQuestionData,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\nexport type {\n MatchContext,\n MatchParticipant,\n MatchParticipantMember,\n MatchResultPayload,\n} from '../types/match.js';\n\n/**\n * Public shape of `window.GameHubSDK` and the value returned by\n * `createSdk()`.\n *\n * Games that need realtime multiplayer read\n * `sdk.getBootstrap().multiplayer` and open their own socket \u2014 typically\n * via `new Client(wsEndpoint).reconnect(reconnectionToken)` from\n * `@colyseus/sdk`. The SDK itself has no realtime dependency.\n */\nexport interface Sdk {\n readonly version: string;\n\n /** @returns true after auto-init has resolved. */\n isInitialized(): boolean;\n /** @returns true when an auth token is currently known. */\n isAuthenticated(): boolean;\n /** @returns true when a live session token has been issued. */\n hasActiveSession(): boolean;\n\n /** Manually start a session (auto-init already attempts this). */\n startSession(): Promise<StartSessionResult>;\n\n /** Submit a final score for the current session. */\n submitScore(score: number, meta?: ScoreMetadata): Promise<SubmitScoreResult>;\n\n /** Submit a score attached to the active league match. */\n submitMatchScore(\n score: number,\n meta?: ScoreMetadata\n ): Promise<SubmitScoreResult>;\n\n /**\n * Submit a league-match result (winner, per-participant scores, etc.).\n * Use this instead of `submitMatchScore` for matches whose leaderboard\n * is derived from the result payload rather than a single score.\n */\n submitMatchResult(result?: MatchResultPayload): Promise<SubmitScoreResult>;\n\n /**\n * Fetch the league-match context for the current bootstrap (leagueId +\n * matchId). Memoised on first success; returns `null` outside a league\n * match context or on transport error.\n */\n getMatchContext(): Promise<MatchContext | null>;\n\n /** Tell the host the game has finished (shows completion UI). */\n notifyComplete(data?: GameCompleteData): void;\n\n /** Ask the host to close the game/iframe and return to the lobby. */\n requestClose(): void;\n\n /**\n * Ask the host to open the \"report this question\" dialog. The host collects\n * the reason, an optional message, and (for guests) name/email, then submits\n * the report to the platform. No-ops when the game runs outside the host\n * iframe.\n */\n reportQuestion(data: ReportQuestionData): void;\n\n /** Emit a custom analytics event to the host. */\n logEvent(eventName: string, eventData?: EventData): void;\n\n /** @returns the resolved game slug, or null if we never found one. */\n getGameSlug(): string | null;\n\n /** @returns whether the SDK is running inside an iframe. */\n isInIframe(): boolean;\n\n /** Awaitable barrier \u2014 resolves when the SDK has booted. */\n ready(): Promise<boolean>;\n\n /** @returns a snapshot of bootstrap-sourced state for debugging. */\n getBootstrap(): BootstrapData;\n\n /**\n * Fetch questions for quiz-style games. Returns [] on failure.\n * Pass `options.profileId` to select a game profile; if omitted, the\n * bootstrap-supplied `profileId` is used, else the game's default profile.\n */\n getQuestions(options?: QuestionOptions): Promise<Question[]>;\n}\n\n/**\n * Build the public API object. Methods are thin adapters that route to\n * the internal modules.\n */\nexport function createSdk(): Sdk {\n return {\n version: SDK_VERSION,\n\n isInitialized(): boolean {\n return state.isInitialized;\n },\n\n isAuthenticated(): boolean {\n return !!state.authToken;\n },\n\n hasActiveSession(): boolean {\n return !!state.sessionToken;\n },\n\n async startSession(): Promise<StartSessionResult> {\n await ensureInitialized();\n if (state.sessionStartPromise) return await state.sessionStartPromise;\n return await Session.startSession();\n },\n\n submitScore(\n score: number,\n meta: ScoreMetadata = {}\n ): Promise<SubmitScoreResult> {\n return Session.submitScore(score, meta);\n },\n\n submitMatchScore(\n score: number,\n meta: ScoreMetadata = {}\n ): Promise<SubmitScoreResult> {\n return Session.submitMatchScore(score, meta);\n },\n\n submitMatchResult(\n result: MatchResultPayload = {}\n ): Promise<SubmitScoreResult> {\n return Session.submitMatchResult(result);\n },\n\n async getMatchContext(): Promise<MatchContext | null> {\n await ensureInitialized();\n return await MatchCtx.fetchMatchContext();\n },\n\n notifyComplete(data: GameCompleteData = {}): void {\n sendToParent('GAME_COMPLETE', data);\n },\n\n requestClose(): void {\n sendToParent('REQUEST_CLOSE', {});\n },\n\n reportQuestion(data: ReportQuestionData): void {\n sendToParent('QUESTION_REPORT', {\n questionId: data.questionId,\n prompt: data.prompt,\n message: data.message,\n });\n },\n\n logEvent(eventName: string, eventData: EventData = {}): void {\n sendToParent('LOG_EVENT', {\n event: eventName,\n data: eventData,\n });\n },\n\n getGameSlug(): string | null {\n return state.gameSlug;\n },\n\n isInIframe(): boolean {\n return isBrowser() && window.parent !== window;\n },\n\n async ready(): Promise<boolean> {\n return await ensureInitialized();\n },\n\n getBootstrap(): BootstrapData {\n return {\n gameSlug: state.gameSlug,\n authToken: state.authToken,\n leagueId: state.leagueId,\n gameId: state.gameId,\n matchId: state.matchId,\n mode: state.bootstrapMode,\n playerName: state.bootstrapPlayerName,\n playerCount: state.bootstrapPlayerCount,\n teamOneName: state.bootstrapTeamOneName,\n teamTwoName: state.bootstrapTeamTwoName,\n profileId: state.bootstrapProfileId,\n multiplayer: state.bootstrapMultiplayer,\n isBootstrapped: state.bootstrapReceived,\n };\n },\n\n getQuestions(options: QuestionOptions = {}): Promise<Question[]> {\n return Session.getQuestions(options);\n },\n };\n}\n", "/**\n * Script-tag entry point.\n *\n * Bundled into the legacy `gamehub-sdk.js` UMD/IIFE artifact that GameHub-\n * hosted games drop in via `<script src=\"gamehub-sdk.js\">`. Importing this\n * module (which a bundler does once when producing that artifact) attaches\n * `window.GameHubSDK`, wires up the host message listener, and runs the\n * auto-init handshake.\n *\n * This file is the ONLY place in the SDK that performs side effects on\n * load. Module / npm consumers import from `./main` instead, which is pure.\n */\n\nimport { SDK_VERSION } from './constants.js';\nimport { state } from './state.js';\nimport { sendToParent } from './bridge.js';\nimport {\n autoInit,\n detectEnvironment,\n installHostMessageListener,\n} from './init.js';\nimport { isBrowser } from './utils.js';\nimport { createSdk, type Sdk } from './main.js';\n\ndeclare global {\n interface Window {\n GameHubSDK?: Sdk;\n }\n}\n\n(function bootstrapSdk(): void {\n 'use strict';\n\n // Defensive: if a bundler accidentally pulls this entry into a non-browser\n // build, exit cleanly instead of throwing on `window.location.origin`.\n if (!isBrowser()) return;\n\n detectEnvironment();\n installHostMessageListener();\n\n const sdk = createSdk();\n window.GameHubSDK = sdk;\n\n // Announce presence to the host as soon as the script runs.\n if (window.parent !== window) {\n sendToParent('READY', { version: SDK_VERSION });\n }\n\n // Kick off auto-init if we have any signal we're embedded in GameHub:\n // either we detected a slug locally, or we're inside an iframe that might\n // feed us one. Waits for DOMContentLoaded so script tags declared after\n // us are available for the slug-detection scan.\n const hasBootSignal = !!state.gameSlug || window.parent !== window;\n if (!hasBootSignal) return;\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n autoInit();\n });\n } else {\n autoInit();\n }\n})();\n"],
|
|
5
|
-
"mappings": ";;;AAGO,MAAM,cAAc;AAMpB,MAAM,iBAAiB;AAGvB,MAAM,4BAA4B;AAOlC,MAAM,sBAAsB;AAG5B,MAAM,sBAAsB;;;ACyC5B,MAAM,QAAkB;AAAA,IAC7B,WAAW;AAAA,IACX,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,SAAS;AAAA,IAET,UAAU;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,SAAS;AAAA,IAET,eAAe;AAAA,IACf,qBAAqB;AAAA,IACrB,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,UAAU,MAAM;AAAA,UAChB,WAAW,MAAM;AAAA,UACjB,UAAU,MAAM;AAAA,UAChB,QAAQ,MAAM;AAAA,UACd,SAAS,MAAM;AAAA,UACf,MAAM,MAAM;AAAA,UACZ,YAAY,MAAM;AAAA,UAClB,aAAa,MAAM;AAAA,UACnB,aAAa,MAAM;AAAA,UACnB,aAAa,MAAM;AAAA,UACnB,WAAW,MAAM;AAAA,UACjB,aAAa,MAAM;AAAA,UACnB,gBAAgB,MAAM;AAAA,QACxB;AAAA,MACF;AAAA,MAEA,aAAa,UAA2B,CAAC,GAAwB;AAC/D,eAAe,aAAa,OAAO;AAAA,MACrC;AAAA,IACF;AAAA,EACF;;;ACjOA,GAAC,SAAS,eAAqB;AAC7B;AAIA,QAAI,CAAC,UAAU,EAAG;AAElB,sBAAkB;AAClB,+BAA2B;AAE3B,UAAM,MAAM,UAAU;AACtB,WAAO,aAAa;AAGpB,QAAI,OAAO,WAAW,QAAQ;AAC5B,mBAAa,SAAS,EAAE,SAAS,YAAY,CAAC;AAAA,IAChD;AAMA,UAAM,gBAAgB,CAAC,CAAC,MAAM,YAAY,OAAO,WAAW;AAC5D,QAAI,CAAC,cAAe;AAEpB,QAAI,SAAS,eAAe,WAAW;AACrC,eAAS,iBAAiB,oBAAoB,MAAM;AAClD,iBAAS;AAAA,MACX,CAAC;AAAA,IACH,OAAO;AACL,eAAS;AAAA,IACX;AAAA,EACF,GAAG;",
|
|
4
|
+
"sourcesContent": ["/**\n * Bundle version reported by the SDK. Bumped at release time.\n */\nexport const SDK_VERSION = '3.6.0';\n\n/**\n * Prefix applied to every cross-origin postMessage the SDK emits and accepts.\n * Keeps our messages isolated from unrelated frames on the same page.\n */\nexport const MESSAGE_PREFIX = 'GAMEHUB_SDK';\n\n/** How long to wait for the host to reply to bootstrap/auth requests. */\nexport const PARENT_REQUEST_TIMEOUT_MS = 2000;\n\n/**\n * How long to wait for the host to proxy an HTTP API request back to the\n * SDK. Larger than {@link PARENT_REQUEST_TIMEOUT_MS} because this round-trip\n * includes the host's real network call to the GameHub backend.\n */\nexport const HOST_API_TIMEOUT_MS = 15000;\n\n/** Upper bound on questions returned per `getQuestions` call. */\nexport const QUESTIONS_LIMIT_CAP = 100;\n", "/**\n * Centralised mutable state for the SDK singleton.\n *\n * Everything here lives on a single `state` object so feature modules\n * can mutate it (`state.foo = bar`). ES modules don't allow reassigning\n * imported `let` bindings from the consumer side, so a single shared\n * object is the cleanest replacement for the namespace + `export let`\n * pattern used in earlier SDK versions.\n */\n\nimport type {\n BootstrapConfig,\n BootstrapMultiplayer,\n} from '../types/bootstrap.js';\nimport type { MatchContext } from '../types/match.js';\nimport type { StartSessionResult } from '../types/session.js';\n\nexport interface SdkState {\n // --- API endpoint resolution -------------------------------------------\n sdkOrigin: string;\n sdkPathPrefix: string;\n runtimeBasePath: string;\n apiBase: string;\n\n // --- Game / league context ---------------------------------------------\n gameSlug: string | null;\n sessionToken: string | null;\n authToken: string | null;\n leagueId: string | null;\n gameId: string | null;\n matchId: string | null;\n\n // --- Free-form bootstrap fields (display only) -------------------------\n bootstrapMode: string | null;\n bootstrapPlayerName: string | null;\n bootstrapPlayerCount: string | null;\n bootstrapTeamOneName: string | null;\n bootstrapTeamTwoName: string | null;\n /** Player's pre-start profile choice; default for `getQuestions`. */\n bootstrapProfileId: string | null;\n\n // --- Multiplayer bootstrap ---------------------------------------------\n // Opaque to the SDK \u2014 exposed verbatim on `getBootstrap().multiplayer`\n // for games to feed into their realtime client (e.g. `@colyseus/sdk`'s\n // `client.reconnect(...)`). The SDK does not open or manage the socket.\n bootstrapMultiplayer: BootstrapMultiplayer | null;\n bootstrapReceived: boolean;\n\n // --- Initialisation lifecycle ------------------------------------------\n isInitialized: boolean;\n isAutoInitializing: boolean;\n autoInitPromise: Promise<boolean> | null;\n bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;\n parentOrigin: string | null;\n sessionStartPromise: Promise<StartSessionResult> | null;\n\n // --- League match context (HTTP) ---------------------------------------\n /** Cached league match context, loaded on demand. */\n matchContext: MatchContext | null;\n /** In-flight match-context fetch, deduped across callers. */\n matchContextPromise: Promise<MatchContext | null> | null;\n}\n\nexport const state: SdkState = {\n sdkOrigin: '',\n sdkPathPrefix: '',\n runtimeBasePath: '',\n apiBase: '',\n\n gameSlug: null,\n sessionToken: null,\n authToken: null,\n leagueId: null,\n gameId: null,\n matchId: null,\n\n bootstrapMode: null,\n bootstrapPlayerName: null,\n bootstrapPlayerCount: null,\n bootstrapTeamOneName: null,\n bootstrapTeamTwoName: null,\n bootstrapProfileId: null,\n\n bootstrapMultiplayer: null,\n bootstrapReceived: false,\n\n isInitialized: false,\n isAutoInitializing: false,\n autoInitPromise: null,\n bootstrapRequestPromise: null,\n parentOrigin: null,\n sessionStartPromise: null,\n\n matchContext: null,\n matchContextPromise: null,\n};\n", "import type { ApiResponse } from '../types/api.js';\n\n/**\n * True when running in a browser-like environment (has both `window` and\n * `document`). Used to short-circuit DOM-touching helpers so the package\n * can be imported under Node / Angular SSR without throwing.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Logs with a consistent `[GameHubSDK]` prefix so host-page developers can\n * easily filter SDK messages in their console.\n */\nexport function warn(message: string, ...rest: any[]): void {\n console.warn('[GameHubSDK] ' + message, ...rest);\n}\n\nexport function error(message: string, ...rest: any[]): void {\n console.error('[GameHubSDK] ' + message, ...rest);\n}\n\n/**\n * Flattens the standard `{ success, data }` envelope returned by the\n * GameHub REST API down to the inner `data` payload. Returns the raw\n * response when the envelope shape doesn't apply.\n */\nexport function unwrapResult(result: ApiResponse | null | undefined): any {\n if (!result) return null;\n if (result.success && result.data) return result.data;\n return result;\n}\n\n/**\n * Safely read a query-string parameter, falling back to a regex scan when\n * URLSearchParams is unavailable (very old browsers / odd runtimes).\n */\nexport function readQueryParam(name: string): string | null {\n try {\n const params = new URLSearchParams(window.location.search);\n return params.get(name);\n } catch {\n const match = window.location.search.match(\n new RegExp('[?&]' + name + '=([^&]+)')\n );\n return match ? decodeURIComponent(match[1]) : null;\n }\n}\n", "/**\n * Cross-origin communication layer between the game iframe and its host page.\n *\n * Messages are namespaced with `MESSAGE_PREFIX` so we don't pick up\n * unrelated postMessage traffic. The host implements a small protocol:\n * - `BOOTSTRAP_REQUEST` \u21C4 `BOOTSTRAP` (initial config + multiplayer)\n * - `AUTH_REQUEST` \u21C4 `AUTH_RESPONSE` (refresh the bearer token)\n * - `READY` / `INIT` / `SESSION_STARTED` / `SCORE_SUBMITTED` / etc.\n * (one-way SDK \u2192 host signals)\n */\n\nimport { state } from './state.js';\nimport {\n MESSAGE_PREFIX,\n PARENT_REQUEST_TIMEOUT_MS,\n HOST_API_TIMEOUT_MS,\n} from './constants.js';\nimport { isBrowser } from './utils.js';\nimport type {\n BootstrapConfig,\n BootstrapMultiplayer,\n} from '../types/bootstrap.js';\nimport type { ApiResponse, ApiRequestOptions } from '../types/api.js';\n\nfunction trimToNullable(value: unknown): string | null | undefined {\n if (value === null) return null;\n if (typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n return trimmed ? trimmed : null;\n}\n\nfunction parseMultiplayer(\n value: BootstrapConfig['multiplayer']\n): BootstrapMultiplayer | null | undefined {\n if (value === null) return null;\n if (!value || typeof value !== 'object') return undefined;\n const { reservation, wsEndpoint } = value;\n if (\n !reservation ||\n typeof reservation !== 'object' ||\n typeof (reservation as { name?: unknown }).name !== 'string' ||\n typeof (reservation as { sessionId?: unknown }).sessionId !== 'string' ||\n typeof (reservation as { roomId?: unknown }).roomId !== 'string' ||\n typeof wsEndpoint !== 'string'\n ) {\n return undefined;\n }\n return {\n reservation,\n wsEndpoint: wsEndpoint.trim(),\n };\n}\n\n/**\n * Fold a {@link BootstrapConfig} from the host into internal state. Accepts\n * partial configs: only fields the host explicitly set (including explicit\n * `null`s used to clear a value) are applied.\n */\nexport function mergeBootstrapConfig(config: BootstrapConfig = {}): void {\n if (!config || typeof config !== 'object') return;\n\n const apply = (\n key: 'gameSlug' | 'authToken' | 'leagueId' | 'gameId' | 'matchId',\n raw: unknown\n ) => {\n const next = trimToNullable(raw);\n if (next === undefined) return;\n state[key] = next;\n };\n\n apply('gameSlug', config.gameSlug);\n apply('authToken', config.authToken);\n apply('leagueId', config.leagueId);\n apply('gameId', config.gameId);\n apply('matchId', config.matchId);\n\n const applyBootstrap = (\n key:\n | 'bootstrapMode'\n | 'bootstrapPlayerName'\n | 'bootstrapPlayerCount'\n | 'bootstrapTeamOneName'\n | 'bootstrapTeamTwoName'\n | 'bootstrapProfileId',\n raw: unknown\n ) => {\n const next = trimToNullable(raw);\n if (next === undefined) return;\n state[key] = next;\n };\n\n applyBootstrap('bootstrapMode', config.mode);\n applyBootstrap('bootstrapPlayerName', config.playerName);\n applyBootstrap('bootstrapPlayerCount', config.playerCount);\n applyBootstrap('bootstrapTeamOneName', config.teamOneName);\n applyBootstrap('bootstrapTeamTwoName', config.teamTwoName);\n applyBootstrap('bootstrapProfileId', config.profileId);\n\n const mp = parseMultiplayer(config.multiplayer);\n if (mp !== undefined) {\n state.bootstrapMultiplayer = mp;\n }\n}\n\nfunction snapshotBootstrap(): BootstrapConfig {\n return {\n gameSlug: state.gameSlug,\n authToken: state.authToken,\n leagueId: state.leagueId,\n gameId: state.gameId,\n matchId: state.matchId,\n mode: state.bootstrapMode,\n playerName: state.bootstrapPlayerName,\n playerCount: state.bootstrapPlayerCount,\n teamOneName: state.bootstrapTeamOneName,\n teamTwoName: state.bootstrapTeamTwoName,\n profileId: state.bootstrapProfileId,\n multiplayer: state.bootstrapMultiplayer,\n };\n}\n\n/**\n * Ask the host for its bootstrap payload. Resolves `null` if the game is\n * standalone (no parent) or the host doesn't reply within the timeout.\n *\n * Subsequent calls after a successful bootstrap short-circuit to the\n * cached state snapshot.\n */\nexport function requestBootstrapFromParent(): Promise<BootstrapConfig | null> {\n if (!isBrowser() || window.parent === window) {\n return Promise.resolve(null);\n }\n\n if (state.bootstrapReceived) {\n return Promise.resolve(snapshotBootstrap());\n }\n\n if (state.bootstrapRequestPromise) {\n return state.bootstrapRequestPromise;\n }\n\n state.bootstrapRequestPromise = new Promise<BootstrapConfig | null>(\n (resolve) => {\n const messageId = Date.now().toString();\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const handler = (event: MessageEvent) => {\n if (\n event.data &&\n event.data.type === MESSAGE_PREFIX + '_BOOTSTRAP' &&\n event.data.payload\n ) {\n if (event.data.messageId && event.data.messageId !== messageId) {\n return;\n }\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n if (timeoutId) clearTimeout(timeoutId);\n state.parentOrigin = event.origin;\n state.bootstrapReceived = true;\n mergeBootstrapConfig(event.data.payload);\n resolve(event.data.payload);\n }\n };\n\n window.addEventListener('message', handler);\n window.parent.postMessage(\n {\n type: MESSAGE_PREFIX + '_BOOTSTRAP_REQUEST',\n messageId,\n },\n '*'\n );\n\n timeoutId = setTimeout(() => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n resolve(null);\n }, PARENT_REQUEST_TIMEOUT_MS);\n }\n ).finally(() => {\n state.bootstrapRequestPromise = null;\n });\n\n return state.bootstrapRequestPromise;\n}\n\n/**\n * Ask the host for a fresh auth token. The host may also use the response\n * to override league/match context \u2014 when it does, we prefer its values.\n */\nexport function getAuthTokenFromParent(): Promise<string | null> {\n return new Promise((resolve) => {\n if (!isBrowser() || window.parent === window) {\n resolve(null);\n return;\n }\n\n const messageId = Date.now().toString();\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const handler = (event: MessageEvent) => {\n if (\n event.data &&\n event.data.type === MESSAGE_PREFIX + '_AUTH_RESPONSE' &&\n event.data.messageId === messageId\n ) {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n if (timeoutId) clearTimeout(timeoutId);\n state.parentOrigin = event.origin;\n if (event.data.leagueId) state.leagueId = event.data.leagueId;\n if (event.data.gameId) state.gameId = event.data.gameId;\n if (event.data.matchId) state.matchId = event.data.matchId;\n resolve(event.data.token || null);\n }\n };\n\n window.addEventListener('message', handler);\n window.parent.postMessage(\n { type: MESSAGE_PREFIX + '_AUTH_REQUEST', messageId },\n '*'\n );\n\n timeoutId = setTimeout(() => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n resolve(null);\n }, PARENT_REQUEST_TIMEOUT_MS);\n });\n}\n\n/** Monotonic counter so concurrent API proxy requests get distinct ids. */\nlet apiRequestSeq = 0;\n\n/**\n * Proxy an HTTP request to the GameHub backend through the host page.\n *\n * The host frame is same-origin with the GameHub API, so it performs the\n * real `fetch` and posts the parsed JSON envelope back. This keeps the SDK\n * (and the game it lives in) from ever issuing a cross-origin request to the\n * backend \u2014 which would otherwise fail CORS when the game is served from a\n * different domain than GameHub.\n *\n * The protocol mirrors the bootstrap/auth handshakes: a `messageId`-keyed\n * `API_REQUEST` is answered by exactly one `API_RESPONSE`. Resolves with the\n * parsed {@link ApiResponse}; rejects on host-reported failure or timeout so\n * the existing per-call `try/catch` degradation paths fire unchanged.\n */\nexport function requestApiFromParent(\n endpoint: string,\n options: ApiRequestOptions = {}\n): Promise<ApiResponse> {\n return new Promise<ApiResponse>((resolve, reject) => {\n if (!isBrowser() || window.parent === window) {\n reject(new Error('Host bridge unavailable: not running in an iframe'));\n return;\n }\n\n const messageId = 'api_' + Date.now().toString() + '_' + ++apiRequestSeq;\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const handler = (event: MessageEvent) => {\n if (\n !event.data ||\n event.data.type !== MESSAGE_PREFIX + '_API_RESPONSE' ||\n event.data.messageId !== messageId\n ) {\n return;\n }\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n if (timeoutId) clearTimeout(timeoutId);\n state.parentOrigin = event.origin;\n if (event.data.ok) {\n resolve((event.data.result ?? {}) as ApiResponse);\n } else {\n reject(new Error(event.data.error || 'Host API request failed'));\n }\n };\n\n window.addEventListener('message', handler);\n window.parent.postMessage(\n {\n type: MESSAGE_PREFIX + '_API_REQUEST',\n messageId,\n endpoint,\n method: options.method || 'GET',\n body: options.body ?? null,\n },\n state.parentOrigin || '*'\n );\n\n timeoutId = setTimeout(() => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n reject(new Error('Host API request timed out'));\n }, HOST_API_TIMEOUT_MS);\n });\n}\n\n/**\n * Fire a namespaced message up to the host window. Silently no-ops when\n * we aren't inside an iframe.\n */\nexport function sendToParent(type: string, data: Record<string, any>): void {\n if (!isBrowser() || window.parent === window) return;\n window.parent.postMessage(\n {\n type: MESSAGE_PREFIX + '_' + type,\n gameSlug: state.gameSlug,\n ...data,\n },\n state.parentOrigin || '*'\n );\n}\n", "import { state } from './state.js';\nimport { isBrowser } from './utils.js';\nimport { requestApiFromParent } from './bridge.js';\nimport type { ApiResponse, ApiRequestOptions } from '../types/api.js';\n\n/**\n * Performs a request against the GameHub REST API and parses the JSON\n * response.\n *\n * Transport is chosen by context:\n * - **Inside the host iframe** the request is proxied through the host via\n * postMessage ({@link requestApiFromParent}). The host is same-origin\n * with the GameHub backend, so the game never issues a cross-origin call\n * itself \u2014 this is what keeps the SDK CORS-free when the game is served\n * from a different domain than GameHub.\n * - **Standalone** (dev harness / a game served from the GameHub origin)\n * the SDK calls the backend directly, prefixing the configured API base\n * and attaching the Bearer auth token when available.\n *\n * Throws whatever the transport throws (host failure/timeout, or\n * `fetch`/`JSON.parse`) \u2014 callers decide whether to retry, fall back, or\n * surface the error to the host.\n */\nexport async function apiRequest(\n endpoint: string,\n options: ApiRequestOptions = {}\n): Promise<ApiResponse> {\n // When embedded, let the host (same-origin with the API) make the call.\n if (isBrowser() && window.parent !== window) {\n return requestApiFromParent(endpoint, options);\n }\n\n const url = state.apiBase + endpoint;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers || {}),\n };\n\n if (state.authToken) {\n headers.Authorization = 'Bearer ' + state.authToken;\n }\n\n const response = await fetch(url, {\n ...options,\n credentials: options.credentials || 'same-origin',\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n });\n\n return response.json();\n}\n", "import { state } from './state.js';\nimport { QUESTIONS_LIMIT_CAP } from './constants.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult } from './utils.js';\nimport { sendToParent } from './bridge.js';\nimport { ensureInitialized } from './init.js';\nimport type {\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\nimport type { MatchResultPayload } from '../types/match.js';\n\n/**\n * Starts a new game session and caches the returned session token. Safe\n * to call multiple times \u2014 the cached token short-circuits subsequent\n * calls.\n *\n * Endpoint is selected from the active context:\n * - league + game + match \u2192 scoped match session\n * - league + game \u2192 scoped league session\n * - otherwise \u2192 standalone session (requires auth)\n */\nexport async function startSession(): Promise<StartSessionResult> {\n if (!state.gameSlug) return { success: false, error: 'Game slug not set' };\n\n const isLeagueMatchSession = Boolean(\n state.leagueId && state.gameId && state.matchId\n );\n if (!state.authToken && !isLeagueMatchSession) {\n return { success: false, error: 'User not authenticated' };\n }\n if (state.sessionToken) return { success: true, token: state.sessionToken };\n\n try {\n let endpoint = '/sessions/start';\n let body: Record<string, any> = { gameSlug: state.gameSlug };\n\n if (state.leagueId && state.gameId && state.matchId) {\n endpoint =\n '/leagues/' + state.leagueId + '/matches/' + state.matchId + '/session';\n body = { gameId: state.gameId };\n } else if (state.leagueId && state.gameId) {\n endpoint = '/leagues/' + state.leagueId + '/sessions';\n body = { gameId: state.gameId };\n }\n\n const result = await apiRequest(endpoint, {\n method: 'POST',\n body,\n });\n\n const data = unwrapResult(result);\n if (result.success || data?.token) {\n state.sessionToken = data?.token || result?.token || null;\n sendToParent('SESSION_STARTED', { token: state.sessionToken });\n return { success: true, token: state.sessionToken };\n }\n\n return {\n success: false,\n error: result.error?.message || 'Failed to start session',\n };\n } catch (err: any) {\n return { success: false, error: err.message };\n }\n}\n\n/**\n * Submit a score to the current session. If no session exists yet we try\n * to open one (re-using any in-flight start attempt).\n *\n * Multiplayer authority lives on the Colyseus server now \u2014 score\n * submission is no longer gated by a client-side host role. Games that\n * want only one peer to call this should make that decision based on\n * their room state (e.g. `room.state.hostPeerId === selfId`).\n */\nexport async function submitScore(\n score: number,\n meta: ScoreMetadata = {}\n): Promise<SubmitScoreResult> {\n await ensureInitialized();\n\n if (!state.isInitialized) {\n return {\n success: false,\n error: 'SDK could not initialize. Is game slug set?',\n };\n }\n\n if (!state.sessionToken) {\n if (state.sessionStartPromise) {\n await state.sessionStartPromise;\n } else {\n const sessionResult = await startSession();\n if (!sessionResult.success) {\n return {\n success: false,\n error: sessionResult.error || 'Could not start session',\n };\n }\n }\n }\n\n if (!state.sessionToken) {\n return {\n success: false,\n error: 'No active session. User may not be authenticated.',\n };\n }\n\n if (typeof score !== 'number' || score < 0) {\n return { success: false, error: 'Score must be a non-negative number' };\n }\n\n try {\n const result = await apiRequest('/sessions/submit', {\n method: 'POST',\n body: {\n token: state.sessionToken,\n score: Math.floor(score),\n meta,\n },\n });\n\n const data = unwrapResult(result);\n\n if (result.success || data?.accepted) {\n sendToParent('SCORE_SUBMITTED', {\n score,\n accepted: data?.accepted,\n timeTaken: data?.timeTaken,\n });\n return {\n success: true,\n accepted: data?.accepted,\n timeTaken: data?.timeTaken,\n };\n }\n\n return {\n success: false,\n error: result.error?.message || 'Score rejected',\n };\n } catch (err: any) {\n return { success: false, error: err.message };\n }\n}\n\n/**\n * Convenience wrapper that tags a score with the current league match\n * context. Fails early if there's no matchId \u2014 a plain `submitScore` is\n * the right call in that case.\n */\nexport async function submitMatchScore(\n score: number,\n meta: ScoreMetadata = {}\n): Promise<SubmitScoreResult> {\n if (!state.matchId) {\n return {\n success: false,\n error: 'No matchId found for this game session',\n };\n }\n\n return await submitScore(score, {\n ...(meta || {}),\n matchId: state.matchId,\n leagueId: state.leagueId || meta.leagueId,\n gameId: state.gameId || meta.gameId,\n });\n}\n\n/**\n * Submit a match result (winner, scores, etc.) with a zero placeholder\n * score \u2014 the server derives the real leaderboard entries from the result\n * payload.\n */\nexport async function submitMatchResult(\n result: MatchResultPayload = {}\n): Promise<SubmitScoreResult> {\n if (!result || typeof result !== 'object') {\n return { success: false, error: 'match result payload is required' };\n }\n\n return await submitMatchScore(0, { matchResult: result });\n}\n\n/**\n * Fetch questions for this game. Returns an empty array on any failure\n * or invalid input \u2014 callers can treat \"no questions\" as the degraded\n * state.\n */\nexport async function getQuestions(\n options: QuestionOptions = {}\n): Promise<Question[]> {\n await ensureInitialized();\n\n const gameIdentifier = state.gameId || state.gameSlug;\n if (!gameIdentifier) return [];\n\n const { difficulty, category, limit } = options;\n\n if (difficulty && !['easy', 'medium', 'hard'].includes(difficulty)) {\n return [];\n }\n\n if (limit !== undefined && (typeof limit !== 'number' || limit < 1)) {\n return [];\n }\n\n // Profile selection: explicit option wins, else the bootstrap-supplied\n // profileId (the player's pre-start picker choice). Omitted \u2192 resolver\n // falls back to the game's isDefault profile (identical to today).\n const profileId = options.profileId || state.bootstrapProfileId || '';\n\n try {\n const params = new URLSearchParams({\n limit: String(\n Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)\n ),\n random: 'true',\n });\n if (state.gameId) params.set('gameId', state.gameId);\n if (difficulty) params.set('difficulty', difficulty);\n if (category) params.set('category', String(category));\n if (profileId) params.set('profileId', profileId);\n\n const result = await apiRequest(\n '/games/' +\n encodeURIComponent(gameIdentifier) +\n '/questions?' +\n params.toString(),\n { method: 'GET' }\n );\n\n const data = unwrapResult(result);\n const raw: unknown[] = Array.isArray(data)\n ? data\n : Array.isArray(data?.questions)\n ? data.questions\n : [];\n // The Mongoose `Question.answer` field allows numeric values for\n // numeric-answer questions. Coerce to string at the API boundary so\n // the canonical `Question.answer: string` invariant holds everywhere\n // downstream (offline games, UGC bundles, scoring code).\n return raw.map(normalizeQuestion);\n } catch {\n return [];\n }\n}\n\nfunction normalizeQuestion(raw: unknown): Question {\n const q = raw as Question & { answer: string | number };\n const answer = typeof q.answer === 'number' ? String(q.answer) : q.answer;\n return { ...q, answer };\n}\n", "/**\n * SDK discovery + auto-initialisation.\n *\n * Detects the API base URL (from the `<script>` tag or the page location)\n * and the active game slug, then exchanges a few postMessages with the\n * host to pick up an auth token and the bootstrap payload before opening\n * a session.\n *\n * The SDK is transport-agnostic: when the bootstrap carries a\n * `multiplayer` block, the values are exposed on\n * `sdk.getBootstrap().multiplayer` for the game to open its own realtime\n * connection (e.g. `new Client(wsEndpoint).reconnect(reconnectionToken)`\n * via `@colyseus/sdk`). The SDK never opens a socket itself.\n */\n\nimport { state } from './state.js';\nimport { MESSAGE_PREFIX } from './constants.js';\nimport { isBrowser, readQueryParam, warn, error as logError } from './utils.js';\nimport {\n mergeBootstrapConfig,\n requestBootstrapFromParent,\n getAuthTokenFromParent,\n sendToParent,\n} from './bridge.js';\nimport * as Session from './session.js';\n\nlet environmentDetected = false;\nlet hostListenerInstalled = false;\n\n/**\n * One-off environment detection. Should be called exactly once at SDK\n * boot time, before any other init function. Idempotent and safe to call\n * outside a browser (no-op).\n */\nexport function detectEnvironment(): void {\n if (!isBrowser() || environmentDetected) return;\n environmentDetected = true;\n state.sdkOrigin = window.location.origin;\n\n // Detect when the game is being served under /games/<slug>/ or\n // /uploaded-games/<slug>/ \u2014 used to infer the slug AND the mount point\n // (which the API base URL is built from).\n const runtimePathMatch = window.location.pathname.match(\n /^(.*)\\/(?:uploaded-games|games)\\/([a-z0-9-]+)(?:\\/|$)/i\n );\n let detectedSlug: string | null = null;\n if (runtimePathMatch) {\n state.runtimeBasePath = runtimePathMatch[1] || '';\n detectedSlug = runtimePathMatch[2] || null;\n }\n\n // Pull league/match context off the URL if present. The host may still\n // override these later via postMessage.\n state.leagueId = readQueryParam('leagueId');\n state.gameId = readQueryParam('gameId');\n state.matchId = readQueryParam('matchId');\n\n // Locate our own <script> tag so we can honour `data-game-slug` and\n // resolve the path prefix (needed when served from a subpath like /app).\n const scripts = document.getElementsByTagName('script');\n for (let i = 0; i < scripts.length; i++) {\n const src = scripts[i].src;\n if (!src.includes('gamehub-sdk.js')) continue;\n\n try {\n const parsedSrc = new URL(src, window.location.origin);\n state.sdkOrigin = parsedSrc.origin;\n const match = parsedSrc.pathname.match(/(.*)\\/sdk\\/gamehub-sdk\\.js$/);\n state.sdkPathPrefix = match ? match[1] || '' : '';\n } catch {\n const match = src.match(/(.*)\\/sdk\\/gamehub-sdk\\.js/);\n if (match) {\n const fallbackUrl = new URL(match[1], window.location.origin);\n state.sdkOrigin = fallbackUrl.origin;\n state.sdkPathPrefix = fallbackUrl.pathname || '';\n }\n }\n\n const slugAttr = scripts[i].getAttribute('data-game-slug');\n if (slugAttr) detectedSlug = slugAttr;\n break;\n }\n\n if (!detectedSlug) {\n const pathMatch = window.location.pathname.match(\n /\\/(?:uploaded-games|games)\\/([a-z0-9-]+)\\//i\n );\n if (pathMatch) detectedSlug = pathMatch[1];\n }\n\n const effectiveBasePath = state.sdkPathPrefix || state.runtimeBasePath || '';\n state.apiBase = state.sdkOrigin + effectiveBasePath + '/api';\n state.gameSlug = detectedSlug;\n}\n\n/**\n * Orchestrates the full SDK boot sequence:\n * 1. Request bootstrap config from the host (seeds slug + context).\n * 2. Exchange for an auth token if we don't already have one.\n * 3. Notify the host that we've booted.\n * 4. Open a session if we can, and reconnect to the Colyseus room when\n * the host gave us a `multiplayer` block.\n *\n * Safe to call multiple times \u2014 concurrent callers share a single promise.\n */\nexport async function autoInit(): Promise<boolean> {\n if (!isBrowser()) return false;\n if (state.isInitialized || state.isAutoInitializing) {\n return state.autoInitPromise as Promise<boolean>;\n }\n\n detectEnvironment();\n installHostMessageListener();\n\n state.isAutoInitializing = true;\n\n state.autoInitPromise = (async () => {\n try {\n await requestBootstrapFromParent();\n\n if (!state.gameSlug) {\n warn(\n 'Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}.'\n );\n state.isAutoInitializing = false;\n return false;\n }\n\n if (!state.authToken) {\n state.authToken = await getAuthTokenFromParent();\n }\n state.isInitialized = true;\n state.isAutoInitializing = false;\n\n sendToParent('INIT', {\n slug: state.gameSlug,\n auto: true,\n });\n\n if (\n state.authToken ||\n (state.leagueId && state.gameId && state.matchId)\n ) {\n state.sessionStartPromise = Session.startSession();\n }\n\n return true;\n } catch (err) {\n logError('Auto-init failed:', err);\n state.isAutoInitializing = false;\n return false;\n }\n })();\n\n return state.autoInitPromise;\n}\n\n/**\n * Ensures init has at least started; callers `await` this before touching\n * any state that depends on bootstrap / auth having resolved.\n */\nexport async function ensureInitialized(): Promise<boolean> {\n if (state.isInitialized) return true;\n if (!isBrowser()) return false;\n if (state.autoInitPromise) return await state.autoInitPromise;\n return await autoInit();\n}\n\n/**\n * Wires up the ambient message listener the host uses to push updates\n * into the running SDK (fresh bootstrap, rotated auth, pause/resume).\n */\nexport function installHostMessageListener(): void {\n if (!isBrowser() || hostListenerInstalled) return;\n hostListenerInstalled = true;\n window.addEventListener('message', (event: MessageEvent) => {\n if (!event.data || !event.data.type) return;\n\n const type = event.data.type;\n\n if (type === MESSAGE_PREFIX + '_BOOTSTRAP' && event.data.payload) {\n state.parentOrigin = event.origin;\n state.bootstrapReceived = true;\n mergeBootstrapConfig(event.data.payload);\n }\n\n if (type === MESSAGE_PREFIX + '_SET_AUTH') {\n state.authToken = event.data.token;\n state.parentOrigin = event.origin;\n\n if (\n state.gameSlug &&\n !state.sessionToken &&\n !state.sessionStartPromise &&\n (state.authToken || (state.leagueId && state.gameId && state.matchId))\n ) {\n state.sessionStartPromise = Session.startSession();\n }\n }\n\n if (type === MESSAGE_PREFIX + '_COMMAND') {\n const command = event.data.command;\n const w = window as any;\n if (command === 'pause' && typeof w.onGameHubPause === 'function') {\n w.onGameHubPause();\n } else if (\n command === 'resume' &&\n typeof w.onGameHubResume === 'function'\n ) {\n w.onGameHubResume();\n }\n }\n });\n}\n", "import { state } from './state.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult } from './utils.js';\nimport type { MatchContext } from '../types/match.js';\n\n/**\n * Lazily load the match context for a league game. Results are cached on\n * `state.matchContext`; concurrent callers share a single in-flight request\n * via `state.matchContextPromise`.\n *\n * Resolves `null` when required context (league or match id) is missing, or\n * when the server returns an error \u2014 callers decide how to degrade.\n */\nexport async function fetchMatchContext(): Promise<MatchContext | null> {\n if (!state.leagueId || !state.matchId) return null;\n if (state.matchContext) return state.matchContext;\n if (state.matchContextPromise) return await state.matchContextPromise;\n\n state.matchContextPromise = apiRequest(\n '/leagues/' +\n encodeURIComponent(state.leagueId) +\n '/matches/' +\n encodeURIComponent(state.matchId),\n { method: 'GET' }\n )\n .then((result) => {\n const data = unwrapResult(result);\n if (result?.success && data) {\n state.matchContext = data as MatchContext;\n return state.matchContext;\n }\n return null;\n })\n .catch(() => null)\n .finally(() => {\n state.matchContextPromise = null;\n });\n\n return await state.matchContextPromise;\n}\n", "/**\n * Public SDK module entry. Exports `createSdk` (the factory) and every\n * public type.\n *\n * Importing this module has no side effects \u2014 it does not touch\n * `window`, `document`, or run any boot logic. For the legacy\n * `<script>`-tag distribution that auto-attaches `window.GameHubSDK`\n * and runs `autoInit()`, see `./browser-entry.ts`.\n *\n * The SDK is transport-agnostic. Games that need realtime multiplayer\n * read `sdk.getBootstrap().multiplayer` and open their own connection\n * (e.g. via `@colyseus/sdk`'s `client.reconnect(...)`).\n */\n\nimport { SDK_VERSION } from './constants.js';\nimport { state } from './state.js';\nimport { sendToParent } from './bridge.js';\nimport { ensureInitialized } from './init.js';\nimport { isBrowser } from './utils.js';\nimport * as Session from './session.js';\nimport * as MatchCtx from './match-context.js';\n\nimport type { BootstrapData } from '../types/bootstrap.js';\nimport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ReportQuestionData,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\nimport type {\n MatchContext,\n MatchParticipant,\n MatchParticipantMember,\n MatchResultPayload,\n} from '../types/match.js';\n\n// Re-export public types so consumers can `import type { Sdk, ... } from\n// '@ksaa-nlp/gamehub-sdk'` without reaching into module subpaths.\nexport type { ApiRequestOptions, ApiResponse } from '../types/api.js';\nexport type {\n BootstrapConfig,\n BootstrapData,\n BootstrapMultiplayer,\n} from '../types/bootstrap.js';\nexport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ReportableQuestion,\n ReportQuestionData,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\nexport type {\n MatchContext,\n MatchParticipant,\n MatchParticipantMember,\n MatchResultPayload,\n} from '../types/match.js';\n\n/**\n * Public shape of `window.GameHubSDK` and the value returned by\n * `createSdk()`.\n *\n * Games that need realtime multiplayer read\n * `sdk.getBootstrap().multiplayer` and open their own socket \u2014 typically\n * via `new Client(wsEndpoint).reconnect(reconnectionToken)` from\n * `@colyseus/sdk`. The SDK itself has no realtime dependency.\n */\nexport interface Sdk {\n readonly version: string;\n\n /** @returns true after auto-init has resolved. */\n isInitialized(): boolean;\n /** @returns true when an auth token is currently known. */\n isAuthenticated(): boolean;\n /** @returns true when a live session token has been issued. */\n hasActiveSession(): boolean;\n\n /** Manually start a session (auto-init already attempts this). */\n startSession(): Promise<StartSessionResult>;\n\n /** Submit a final score for the current session. */\n submitScore(score: number, meta?: ScoreMetadata): Promise<SubmitScoreResult>;\n\n /** Submit a score attached to the active league match. */\n submitMatchScore(\n score: number,\n meta?: ScoreMetadata\n ): Promise<SubmitScoreResult>;\n\n /**\n * Submit a league-match result (winner, per-participant scores, etc.).\n * Use this instead of `submitMatchScore` for matches whose leaderboard\n * is derived from the result payload rather than a single score.\n */\n submitMatchResult(result?: MatchResultPayload): Promise<SubmitScoreResult>;\n\n /**\n * Fetch the league-match context for the current bootstrap (leagueId +\n * matchId). Memoised on first success; returns `null` outside a league\n * match context or on transport error.\n */\n getMatchContext(): Promise<MatchContext | null>;\n\n /** Tell the host the game has finished (shows completion UI). */\n notifyComplete(data?: GameCompleteData): void;\n\n /** Ask the host to close the game/iframe and return to the lobby. */\n requestClose(): void;\n\n /**\n * Ask the host to open the \"report this question\" dialog. The host collects\n * the reason, an optional message, and (for guests) name/email, then submits\n * the report to the platform. No-ops when the game runs outside the host\n * iframe.\n */\n reportQuestion(data: ReportQuestionData): void;\n\n /** Emit a custom analytics event to the host. */\n logEvent(eventName: string, eventData?: EventData): void;\n\n /** @returns the resolved game slug, or null if we never found one. */\n getGameSlug(): string | null;\n\n /** @returns whether the SDK is running inside an iframe. */\n isInIframe(): boolean;\n\n /** Awaitable barrier \u2014 resolves when the SDK has booted. */\n ready(): Promise<boolean>;\n\n /** @returns a snapshot of bootstrap-sourced state for debugging. */\n getBootstrap(): BootstrapData;\n\n /**\n * Fetch questions for quiz-style games. Returns [] on failure.\n * Pass `options.profileId` to select a game profile; if omitted, the\n * bootstrap-supplied `profileId` is used, else the game's default profile.\n */\n getQuestions(options?: QuestionOptions): Promise<Question[]>;\n}\n\n/**\n * Build the public API object. Methods are thin adapters that route to\n * the internal modules.\n */\nexport function createSdk(): Sdk {\n return {\n version: SDK_VERSION,\n\n isInitialized(): boolean {\n return state.isInitialized;\n },\n\n isAuthenticated(): boolean {\n return !!state.authToken;\n },\n\n hasActiveSession(): boolean {\n return !!state.sessionToken;\n },\n\n async startSession(): Promise<StartSessionResult> {\n await ensureInitialized();\n if (state.sessionStartPromise) return await state.sessionStartPromise;\n return await Session.startSession();\n },\n\n submitScore(\n score: number,\n meta: ScoreMetadata = {}\n ): Promise<SubmitScoreResult> {\n return Session.submitScore(score, meta);\n },\n\n submitMatchScore(\n score: number,\n meta: ScoreMetadata = {}\n ): Promise<SubmitScoreResult> {\n return Session.submitMatchScore(score, meta);\n },\n\n submitMatchResult(\n result: MatchResultPayload = {}\n ): Promise<SubmitScoreResult> {\n return Session.submitMatchResult(result);\n },\n\n async getMatchContext(): Promise<MatchContext | null> {\n await ensureInitialized();\n return await MatchCtx.fetchMatchContext();\n },\n\n notifyComplete(data: GameCompleteData = {}): void {\n sendToParent('GAME_COMPLETE', data);\n },\n\n requestClose(): void {\n sendToParent('REQUEST_CLOSE', {});\n },\n\n reportQuestion(data: ReportQuestionData): void {\n sendToParent('QUESTION_REPORT', {\n questionId: data.questionId,\n prompt: data.prompt,\n message: data.message,\n questions: Array.isArray(data.questions)\n ? data.questions.map((q) => ({\n questionId: q.questionId,\n prompt: q.prompt,\n }))\n : undefined,\n });\n },\n\n logEvent(eventName: string, eventData: EventData = {}): void {\n sendToParent('LOG_EVENT', {\n event: eventName,\n data: eventData,\n });\n },\n\n getGameSlug(): string | null {\n return state.gameSlug;\n },\n\n isInIframe(): boolean {\n return isBrowser() && window.parent !== window;\n },\n\n async ready(): Promise<boolean> {\n return await ensureInitialized();\n },\n\n getBootstrap(): BootstrapData {\n return {\n gameSlug: state.gameSlug,\n authToken: state.authToken,\n leagueId: state.leagueId,\n gameId: state.gameId,\n matchId: state.matchId,\n mode: state.bootstrapMode,\n playerName: state.bootstrapPlayerName,\n playerCount: state.bootstrapPlayerCount,\n teamOneName: state.bootstrapTeamOneName,\n teamTwoName: state.bootstrapTeamTwoName,\n profileId: state.bootstrapProfileId,\n multiplayer: state.bootstrapMultiplayer,\n isBootstrapped: state.bootstrapReceived,\n };\n },\n\n getQuestions(options: QuestionOptions = {}): Promise<Question[]> {\n return Session.getQuestions(options);\n },\n };\n}\n", "/**\n * Script-tag entry point.\n *\n * Bundled into the legacy `gamehub-sdk.js` UMD/IIFE artifact that GameHub-\n * hosted games drop in via `<script src=\"gamehub-sdk.js\">`. Importing this\n * module (which a bundler does once when producing that artifact) attaches\n * `window.GameHubSDK`, wires up the host message listener, and runs the\n * auto-init handshake.\n *\n * This file is the ONLY place in the SDK that performs side effects on\n * load. Module / npm consumers import from `./main` instead, which is pure.\n */\n\nimport { SDK_VERSION } from './constants.js';\nimport { state } from './state.js';\nimport { sendToParent } from './bridge.js';\nimport {\n autoInit,\n detectEnvironment,\n installHostMessageListener,\n} from './init.js';\nimport { isBrowser } from './utils.js';\nimport { createSdk, type Sdk } from './main.js';\n\ndeclare global {\n interface Window {\n GameHubSDK?: Sdk;\n }\n}\n\n(function bootstrapSdk(): void {\n 'use strict';\n\n // Defensive: if a bundler accidentally pulls this entry into a non-browser\n // build, exit cleanly instead of throwing on `window.location.origin`.\n if (!isBrowser()) return;\n\n detectEnvironment();\n installHostMessageListener();\n\n const sdk = createSdk();\n window.GameHubSDK = sdk;\n\n // Announce presence to the host as soon as the script runs.\n if (window.parent !== window) {\n sendToParent('READY', { version: SDK_VERSION });\n }\n\n // Kick off auto-init if we have any signal we're embedded in GameHub:\n // either we detected a slug locally, or we're inside an iframe that might\n // feed us one. Waits for DOMContentLoaded so script tags declared after\n // us are available for the slug-detection scan.\n const hasBootSignal = !!state.gameSlug || window.parent !== window;\n if (!hasBootSignal) return;\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n autoInit();\n });\n } else {\n autoInit();\n }\n})();\n"],
|
|
5
|
+
"mappings": ";;;AAGO,MAAM,cAAc;AAMpB,MAAM,iBAAiB;AAGvB,MAAM,4BAA4B;AAOlC,MAAM,sBAAsB;AAG5B,MAAM,sBAAsB;;;ACyC5B,MAAM,QAAkB;AAAA,IAC7B,WAAW;AAAA,IACX,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,SAAS;AAAA,IAET,UAAU;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,SAAS;AAAA,IAET,eAAe;AAAA,IACf,qBAAqB;AAAA,IACrB,sBAAsB;AAAA,IACtB,sBAAsB;AAAA,IACtB,sBAAsB;AAAA,IACtB,oBAAoB;AAAA,IAEpB,sBAAsB;AAAA,IACtB,mBAAmB;AAAA,IAEnB,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,IACjB,yBAAyB;AAAA,IACzB,cAAc;AAAA,IACd,qBAAqB;AAAA,IAErB,cAAc;AAAA,IACd,qBAAqB;AAAA,EACvB;;;ACxFO,WAAS,YAAqB;AACnC,WAAO,OAAO,WAAW,eAAe,OAAO,aAAa;A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a,MAAM;AAAA,UACnB,aAAa,MAAM;AAAA,UACnB,WAAW,MAAM;AAAA,UACjB,aAAa,MAAM;AAAA,UACnB,gBAAgB,MAAM;AAAA,QACxB;AAAA,MACF;AAAA,MAEA,aAAa,UAA2B,CAAC,GAAwB;AAC/D,eAAe,aAAa,OAAO;AAAA,MACrC;AAAA,IACF;AAAA,EACF;;;ACxOA,GAAC,SAAS,eAAqB;AAC7B;AAIA,QAAI,CAAC,UAAU,EAAG;AAElB,sBAAkB;AAClB,+BAA2B;AAE3B,UAAM,MAAM,UAAU;AACtB,WAAO,aAAa;AAGpB,QAAI,OAAO,WAAW,QAAQ;AAC5B,mBAAa,SAAS,EAAE,SAAS,YAAY,CAAC;AAAA,IAChD;AAMA,UAAM,gBAAgB,CAAC,CAAC,MAAM,YAAY,OAAO,WAAW;AAC5D,QAAI,CAAC,cAAe;AAEpB,QAAI,SAAS,eAAe,WAAW;AACrC,eAAS,iBAAiB,oBAAoB,MAAM;AAClD,iBAAS;AAAA,MACX,CAAC;AAAA,IACH,OAAO;AACL,eAAS;AAAA,IACX;AAAA,EACF,GAAG;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/src/constants.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Bundle version reported by the SDK. Bumped at release time.
|
|
3
3
|
*/
|
|
4
|
-
export declare const SDK_VERSION = "3.
|
|
4
|
+
export declare const SDK_VERSION = "3.6.0";
|
|
5
5
|
/**
|
|
6
6
|
* Prefix applied to every cross-origin postMessage the SDK emits and accepts.
|
|
7
7
|
* Keeps our messages isolated from unrelated frames on the same page.
|
package/dist/src/constants.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Bundle version reported by the SDK. Bumped at release time.
|
|
3
3
|
*/
|
|
4
|
-
export const SDK_VERSION = '3.
|
|
4
|
+
export const SDK_VERSION = '3.6.0';
|
|
5
5
|
/**
|
|
6
6
|
* Prefix applied to every cross-origin postMessage the SDK emits and accepts.
|
|
7
7
|
* Keeps our messages isolated from unrelated frames on the same page.
|
package/dist/src/main.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ import type { EventData, GameCompleteData, Question, QuestionOptions, ReportQues
|
|
|
16
16
|
import type { MatchContext, MatchResultPayload } from '../types/match.js';
|
|
17
17
|
export type { ApiRequestOptions, ApiResponse } from '../types/api.js';
|
|
18
18
|
export type { BootstrapConfig, BootstrapData, BootstrapMultiplayer, } from '../types/bootstrap.js';
|
|
19
|
-
export type { EventData, GameCompleteData, Question, QuestionOptions, ReportQuestionData, ScoreMetadata, StartSessionResult, SubmitScoreResult, } from '../types/session.js';
|
|
19
|
+
export type { EventData, GameCompleteData, Question, QuestionOptions, ReportableQuestion, ReportQuestionData, ScoreMetadata, StartSessionResult, SubmitScoreResult, } from '../types/session.js';
|
|
20
20
|
export type { MatchContext, MatchParticipant, MatchParticipantMember, MatchResultPayload, } from '../types/match.js';
|
|
21
21
|
/**
|
|
22
22
|
* Public shape of `window.GameHubSDK` and the value returned by
|
package/dist/src/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAUH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EACV,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EACV,YAAY,EAGZ,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAI3B,YAAY,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACtE,YAAY,EACV,eAAe,EACf,aAAa,EACb,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,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;CAC9D;AAED;;;GAGG;AACH,wBAAgB,SAAS,IAAI,GAAG,CA8G/B"}
|
package/dist/src/main.js
CHANGED
|
@@ -64,6 +64,12 @@ export function createSdk() {
|
|
|
64
64
|
questionId: data.questionId,
|
|
65
65
|
prompt: data.prompt,
|
|
66
66
|
message: data.message,
|
|
67
|
+
questions: Array.isArray(data.questions)
|
|
68
|
+
? data.questions.map((q) => ({
|
|
69
|
+
questionId: q.questionId,
|
|
70
|
+
prompt: q.prompt,
|
|
71
|
+
}))
|
|
72
|
+
: undefined,
|
|
67
73
|
});
|
|
68
74
|
},
|
|
69
75
|
logEvent(eventName, eventData = {}) {
|
package/dist/src/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","sourceRoot":"","sources":["../../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,KAAK,QAAQ,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"main.js","sourceRoot":"","sources":["../../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAA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AAC,kBAAkB;gBACnC,WAAW,EAAE,KAAK,CAAC,oBAAoB;gBACvC,cAAc,EAAE,KAAK,CAAC,iBAAiB;aACxC,CAAC;QACJ,CAAC;QAED,YAAY,CAAC,UAA2B,EAAE;YACxC,OAAO,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/types/session.d.ts
CHANGED
|
@@ -20,18 +20,41 @@ export interface EventData {
|
|
|
20
20
|
value?: number;
|
|
21
21
|
properties?: Record<string, any>;
|
|
22
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* A single question the host can offer in its report dialog's question
|
|
25
|
+
* picker. Supplied via {@link ReportQuestionData.questions}.
|
|
26
|
+
*/
|
|
27
|
+
export interface ReportableQuestion {
|
|
28
|
+
/** The `id` of the question (as returned by `getQuestions`). */
|
|
29
|
+
questionId: string;
|
|
30
|
+
/** Optional prompt label shown for this option in the picker. */
|
|
31
|
+
prompt?: string;
|
|
32
|
+
}
|
|
23
33
|
/**
|
|
24
34
|
* Payload passed to `sdk.reportQuestion`. Identifies the question the player
|
|
25
35
|
* wants to flag; the host renders the report dialog and collects the reason,
|
|
26
36
|
* optional message, and (for guests) name/email before submitting.
|
|
37
|
+
*
|
|
38
|
+
* For a single question, pass `questionId` (and optionally `prompt`). To let
|
|
39
|
+
* the player pick which question to report, pass `questions` — the host renders
|
|
40
|
+
* a dropdown of them; `questionId` then acts as the pre-selected option.
|
|
27
41
|
*/
|
|
28
42
|
export interface ReportQuestionData {
|
|
29
|
-
/**
|
|
30
|
-
|
|
43
|
+
/**
|
|
44
|
+
* The `id` of the question to report (as returned by `getQuestions`). May be
|
|
45
|
+
* omitted when `questions` is supplied, in which case it pre-selects an entry.
|
|
46
|
+
*/
|
|
47
|
+
questionId?: string;
|
|
31
48
|
/** Optional prompt snapshot so the host dialog can show what's being reported. */
|
|
32
49
|
prompt?: string;
|
|
33
50
|
/** Optional message to pre-fill in the dialog. */
|
|
34
51
|
message?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Optional list of questions for the host to render as a selectable dropdown,
|
|
54
|
+
* letting the player choose which question to report. When omitted, the dialog
|
|
55
|
+
* reports the single `questionId`.
|
|
56
|
+
*/
|
|
57
|
+
questions?: ReportableQuestion[];
|
|
35
58
|
}
|
|
36
59
|
/** Options accepted by `sdk.getQuestions`. */
|
|
37
60
|
export interface QuestionOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../types/session.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC7B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,6CAA6C;AAC7C,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC5B;AAED,uCAAuC;AACvC,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAClC;AAED
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../types/session.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG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;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wCAAwC;AACxC,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ksaa-nlp/gamehub-sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.0",
|
|
4
4
|
"description": "ESM SDK that lets GameHub-hosted games talk to the platform (auth, sessions, scores, bootstrap pipeline). Includes types and a Node-only dev harness for authoring UGC server bundles (`./server`, `./server/dev`). Transport-agnostic — games open their own realtime connection (e.g. via @colyseus/sdk).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/src/main.js",
|