@ksaa-nlp/gamehub-sdk 0.4.0 → 0.5.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/CHANGELOG.md +83 -0
- package/dist/gamehub-sdk.js +16 -8
- 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 +12 -5
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js.map +1 -1
- package/dist/src/multiplayer.d.ts +9 -3
- package/dist/src/multiplayer.d.ts.map +1 -1
- package/dist/src/multiplayer.js +29 -7
- package/dist/src/multiplayer.js.map +1 -1
- package/dist/types/multiplayer.d.ts +31 -0
- package/dist/types/multiplayer.d.ts.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,88 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0 — 2026-04-30
|
|
4
|
+
|
|
5
|
+
Adds **retained ("sticky") multiplayer events** so peers that join or reconnect mid-match automatically receive the latest authoritative state before any live traffic — without games having to write a custom resync intent.
|
|
6
|
+
|
|
7
|
+
### Why
|
|
8
|
+
|
|
9
|
+
Every multiplayer game using the SDK has the same gap: when a guest peer drops and reconnects (or a viewer joins late), they have no idea what `match_start` said, which cells/turns/positions are filled, or whose turn it is. Today the only fix is per-game: a custom `request_state_sync` intent and a `state_snapshot` response, with all the bespoke serialisation and dedupe logic that implies. The SDK couldn't ship the upcoming `multiplayer.match` reducer's "transparent reconnect" guarantee without solving this.
|
|
10
|
+
|
|
11
|
+
Retained frames put the fix at the transport layer where it belongs. The host pins the latest broadcast for a given key; the realtime server replays the pinned set to every newcomer in original insertion order, before any live frame for that key reaches the new socket. Borrowed semantics from MQTT retained messages — a small, well-understood primitive.
|
|
12
|
+
|
|
13
|
+
### What changed
|
|
14
|
+
|
|
15
|
+
- **`SendOptions { retain?: boolean; retainKey?: string }`** is a new optional third argument on `multiplayer.send` and `multiplayer.broadcast`. Defaults preserve the old behaviour exactly.
|
|
16
|
+
- **`MpMessage.retained?: boolean`** marks frames replayed by the server. Game code can usually treat retained and live frames identically (apply both via the same handler); games that play sounds or animations on a state change typically suppress them when `retained` is true.
|
|
17
|
+
- **Per-peer seq dedupe now skips retained frames** and does not advance the per-peer high-water mark when one arrives. Replays carry their original `seq` (intentionally older than any live frame the receiver may already have seen), so the dedupe at [src/multiplayer.ts](./src/multiplayer.ts) would otherwise drop them. Live ordering is unaffected because `mpLastSeqByPeer` continues to advance only on live frames.
|
|
18
|
+
- **`SendOptions` is re-exported** from the package entry alongside the other multiplayer types.
|
|
19
|
+
|
|
20
|
+
### Wire format
|
|
21
|
+
|
|
22
|
+
Outbound (sender → server):
|
|
23
|
+
|
|
24
|
+
```jsonc
|
|
25
|
+
{
|
|
26
|
+
"eventName": "link:match_start",
|
|
27
|
+
"payload": { ... },
|
|
28
|
+
"retain": true, // host-only on the server side
|
|
29
|
+
"retainKey": "match_start" // optional; defaults to eventName
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Inbound (server → all peers, replay or live):
|
|
34
|
+
|
|
35
|
+
```jsonc
|
|
36
|
+
{
|
|
37
|
+
"type": "game_event",
|
|
38
|
+
"roomCode": "...",
|
|
39
|
+
"fromPeerId": "...",
|
|
40
|
+
"eventName": "...",
|
|
41
|
+
"payload": { ... },
|
|
42
|
+
"seq": 7,
|
|
43
|
+
"sentAt": 1714378900000,
|
|
44
|
+
"retained": true // present on replays only
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Server requirements
|
|
49
|
+
|
|
50
|
+
This release pairs with realtime-server changes that:
|
|
51
|
+
|
|
52
|
+
- Store retained frames per room (memory + MongoDB), capped at 64 keys per room with FIFO eviction at the cap.
|
|
53
|
+
- Replay them to every new socket immediately after `room_joined` and before any live frame can reach that socket.
|
|
54
|
+
- Drop the `retain` flag silently from non-host senders so a guest can't forge long-lived state for late joiners.
|
|
55
|
+
- TTL retained docs in MongoDB at 24 hours (orphan cleanup for rooms closed via the HTTP API rather than via host disconnect).
|
|
56
|
+
|
|
57
|
+
The wire format is a strict superset of v0.4 — older clients connecting to a server with retain support keep working unchanged (they just don't see the new fields). Older servers connecting from v0.5 clients ignore the `retain`/`retainKey` fields harmlessly.
|
|
58
|
+
|
|
59
|
+
### How games use it
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// Host-authoritative match start — replays for every reconnecting peer
|
|
63
|
+
sdk.multiplayer.broadcast('link:match_start', payload, {
|
|
64
|
+
retain: true,
|
|
65
|
+
retainKey: 'match_start',
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// Per-cell board state, replayed cell-by-cell on reconnect
|
|
69
|
+
sdk.multiplayer.broadcast('link:answer_resolved', payload, {
|
|
70
|
+
retain: true,
|
|
71
|
+
retainKey: `cell:${payload.cellId}`,
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Game-side dedupe (e.g. an `appliedEventKeys` set keyed by the same logical id) is still required: the same logical event can arrive once live and once retained on a reconnect-during-match. The upcoming `multiplayer.match` reducer formalises this via its `idKey` callback.
|
|
76
|
+
|
|
77
|
+
### Unchanged
|
|
78
|
+
|
|
79
|
+
- Public `Sdk` interface beyond the new `SendOptions` parameter.
|
|
80
|
+
- `BootstrapData` shape.
|
|
81
|
+
- `MpMessage` for live frames (the `retained` flag is opt-in and absent on every existing path).
|
|
82
|
+
- All other multiplayer methods (`createRoom`, `joinRoom`, `leaveRoom`, `getRoom`, `getPeers`, …).
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
3
86
|
## 0.4.0 — 2026-04-28
|
|
4
87
|
|
|
5
88
|
ESM-only npm package shape with proper `exports`, retired hand-written shim, and a separate IIFE bundle for the `<script>`-tag flow. The package now installs cleanly and imports correctly under Node's native ESM loader, Angular, Vite, webpack, and esbuild — no bundler-specific workarounds.
|
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 = "0.
|
|
4
|
+
var SDK_VERSION = "0.5.0";
|
|
5
5
|
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
6
|
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
7
|
var MP_MAX_RECONNECT_ATTEMPTS = 5;
|
|
@@ -416,7 +416,8 @@
|
|
|
416
416
|
return;
|
|
417
417
|
}
|
|
418
418
|
if (message.type === "game_event") {
|
|
419
|
-
|
|
419
|
+
const isRetained = message.retained === true;
|
|
420
|
+
if (!isRetained && typeof message.seq === "number" && typeof message.fromPeerId === "string") {
|
|
420
421
|
const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;
|
|
421
422
|
if (message.seq <= last) return;
|
|
422
423
|
state.mpLastSeqByPeer.set(message.fromPeerId, message.seq);
|
|
@@ -427,14 +428,16 @@
|
|
|
427
428
|
eventName: message.eventName,
|
|
428
429
|
payload: message.payload,
|
|
429
430
|
seq: message.seq,
|
|
430
|
-
sentAt: message.sentAt
|
|
431
|
+
sentAt: message.sentAt,
|
|
432
|
+
retained: isRetained
|
|
431
433
|
});
|
|
432
434
|
emit(message.eventName, {
|
|
433
435
|
roomCode: message.roomCode,
|
|
434
436
|
fromPeerId: message.fromPeerId,
|
|
435
437
|
payload: message.payload,
|
|
436
438
|
seq: message.seq,
|
|
437
|
-
sentAt: message.sentAt
|
|
439
|
+
sentAt: message.sentAt,
|
|
440
|
+
retained: isRetained
|
|
438
441
|
});
|
|
439
442
|
}
|
|
440
443
|
};
|
|
@@ -628,7 +631,7 @@
|
|
|
628
631
|
state.mpViewerOverride = false;
|
|
629
632
|
emit("room_left", { reason });
|
|
630
633
|
}
|
|
631
|
-
function send(eventName, payload = {}) {
|
|
634
|
+
function send(eventName, payload = {}, options = {}) {
|
|
632
635
|
if (state.mpViewerOverride) {
|
|
633
636
|
warn("multiplayer.send ignored: peer is a viewer");
|
|
634
637
|
return false;
|
|
@@ -637,15 +640,20 @@
|
|
|
637
640
|
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
638
641
|
return false;
|
|
639
642
|
}
|
|
640
|
-
|
|
643
|
+
const frame = { eventName, payload };
|
|
644
|
+
if (options.retain) {
|
|
645
|
+
frame.retain = true;
|
|
646
|
+
if (options.retainKey) frame.retainKey = options.retainKey;
|
|
647
|
+
}
|
|
648
|
+
socket.send(JSON.stringify(frame));
|
|
641
649
|
return true;
|
|
642
650
|
}
|
|
643
|
-
function broadcast(eventName, payload = {}) {
|
|
651
|
+
function broadcast(eventName, payload = {}, options = {}) {
|
|
644
652
|
if (!isHost()) {
|
|
645
653
|
warn("multiplayer.broadcast ignored: peer is not the host");
|
|
646
654
|
return false;
|
|
647
655
|
}
|
|
648
|
-
return send(eventName, payload);
|
|
656
|
+
return send(eventName, payload, options);
|
|
649
657
|
}
|
|
650
658
|
function getRole() {
|
|
651
659
|
return state.mpRoom ? state.mpRoom.role : null;
|
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/multiplayer.ts", "../src/match-context.ts", "../src/session.ts", "../src/init.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 = '0.4.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/** Maximum number of WebSocket reconnect attempts before giving up. */\nexport const MP_MAX_RECONNECT_ATTEMPTS = 5;\n\n/** Hard cap on reconnect backoff. */\nexport const MP_MAX_RECONNECT_DELAY_MS = 10_000;\n\n/** Upper bound used when the caller doesn't pass an explicit limit. */\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 the various feature\n * modules can mutate it (`state.foo = bar`). ES modules don't allow\n * reassigning imported `let` bindings from the consumer side, so a single\n * shared object is the cleanest replacement for the previous namespace-with-\n * `export let` pattern.\n */\n\nimport type { MatchContext } from '../types/match.js';\nimport type { BootstrapConfig } from '../types/bootstrap.js';\nimport type { StartSessionResult } from '../types/session.js';\nimport type {\n MpRoom,\n MpJoinRequest,\n Peer,\n MpEventHandler,\n} from '../types/multiplayer.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 participant1Id: string | null;\n participant2Id: string | null;\n participant1MemberIds: string[];\n participant2MemberIds: string[];\n\n // --- Match metadata (fetched lazily from the API) ----------------------\n matchContext: MatchContext | null;\n matchContextPromise: Promise<MatchContext | null> | null;\n\n // --- Bootstrap payload from host ---------------------------------------\n bootstrapShareId: string | null;\n bootstrapRoomCode: string | null;\n bootstrapRoomRole: string | null;\n bootstrapRoomToken: string | null;\n bootstrapWsUrl: string | null;\n bootstrapPlayerName: string | null;\n bootstrapPeerId: string | null;\n bootstrapMaxPlayers: number | 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 lastAutoJoinShareId: string | null;\n lastAutoJoinRoomCode: string | null;\n\n // --- Multiplayer runtime ------------------------------------------------\n mpSocket: WebSocket | null;\n mpReconnectTimer: ReturnType<typeof setTimeout> | null;\n mpReconnectAttempts: number;\n mpExpectedClose: boolean;\n mpRoom: MpRoom | null;\n mpLastJoinRequest: MpJoinRequest | null;\n readonly mpPeers: Map<string, Peer>;\n readonly mpHandlers: Map<string, Set<MpEventHandler>>;\n /**\n * Highest `seq` we've already delivered to game code, per sending peer.\n * Used to drop late/duplicate `game_event` frames so a reconnect or a\n * buffered message can't double-advance game state.\n */\n readonly mpLastSeqByPeer: Map<string, number>;\n /**\n * Local override for view-only guests. The server doesn't know about\n * viewers \u2014 this is a client-side flag the SDK flips when the game joins\n * with `{ asViewer: true }`. It gates outbound `send` / `broadcast` and\n * score submission.\n */\n mpViewerOverride: boolean;\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 participant1Id: null,\n participant2Id: null,\n participant1MemberIds: [],\n participant2MemberIds: [],\n\n matchContext: null,\n matchContextPromise: null,\n\n bootstrapShareId: null,\n bootstrapRoomCode: null,\n bootstrapRoomRole: null,\n bootstrapRoomToken: null,\n bootstrapWsUrl: null,\n bootstrapPlayerName: null,\n bootstrapPeerId: null,\n bootstrapMaxPlayers: null,\n bootstrapReceived: false,\n\n isInitialized: false,\n isAutoInitializing: false,\n autoInitPromise: null,\n bootstrapRequestPromise: null,\n parentOrigin: null,\n sessionStartPromise: null,\n lastAutoJoinShareId: null,\n lastAutoJoinRoomCode: null,\n\n mpSocket: null,\n mpReconnectTimer: null,\n mpReconnectAttempts: 0,\n mpExpectedClose: false,\n mpRoom: null,\n mpLastJoinRequest: null,\n mpPeers: new Map(),\n mpHandlers: new Map(),\n mpLastSeqByPeer: new Map(),\n mpViewerOverride: false,\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 our REST API\n * down to the inner `data` payload, or returns the raw response if it isn't\n * shaped that way.\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 * Extracts a share ID from either:\n * - a full multiplayer URL (`/join?mp=<shareId>`), or\n * - a short path where the last segment is the share ID itself.\n * Returns null if the link can't be parsed.\n */\nexport function extractShareIdFromLink(link: string): string | null {\n try {\n const parsed = new URL(link, window.location.origin);\n const mp = parsed.searchParams.get('mp');\n if (mp) return mp;\n return parsed.pathname.split('/').pop() || null;\n } catch {\n return null;\n }\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/**\n * Reads a CSV query parameter and returns the trimmed, non-empty values.\n */\nexport function readCsvQueryParam(name: string): string[] {\n const raw = readQueryParam(name) || '';\n return raw\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean);\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 unrelated\n * postMessage traffic. The host is expected to implement a small protocol\n * (BOOTSTRAP_REQUEST / BOOTSTRAP, AUTH_REQUEST / AUTH_RESPONSE, etc.).\n */\n\nimport { state } from './state.js';\nimport { MESSAGE_PREFIX, PARENT_REQUEST_TIMEOUT_MS } from './constants.js';\nimport { isBrowser } from './utils.js';\nimport type { BootstrapConfig } from '../types/bootstrap.js';\n\n/**\n * Fold a {@link BootstrapConfig} from the host into internal state. Accepts\n * partial configs: only the fields that are explicitly set (including\n * explicit `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 if (typeof config.gameSlug === 'string' && config.gameSlug.trim()) {\n state.gameSlug = config.gameSlug.trim();\n }\n\n if (typeof config.authToken === 'string') {\n state.authToken = config.authToken;\n } else if (config.authToken === null) {\n state.authToken = null;\n }\n\n if (typeof config.leagueId === 'string' && config.leagueId.trim()) {\n state.leagueId = config.leagueId.trim();\n } else if (config.leagueId === null) {\n state.leagueId = null;\n }\n\n if (typeof config.gameId === 'string' && config.gameId.trim()) {\n state.gameId = config.gameId.trim();\n } else if (config.gameId === null) {\n state.gameId = null;\n }\n\n if (typeof config.matchId === 'string' && config.matchId.trim()) {\n state.matchId = config.matchId.trim();\n } else if (config.matchId === null) {\n state.matchId = null;\n }\n\n if (\n typeof config.participant1Id === 'string' &&\n config.participant1Id.trim()\n ) {\n state.participant1Id = config.participant1Id.trim();\n } else if (config.participant1Id === null) {\n state.participant1Id = null;\n }\n\n if (\n typeof config.participant2Id === 'string' &&\n config.participant2Id.trim()\n ) {\n state.participant2Id = config.participant2Id.trim();\n } else if (config.participant2Id === null) {\n state.participant2Id = null;\n }\n\n if (Array.isArray(config.participant1MemberIds)) {\n state.participant1MemberIds = config.participant1MemberIds.filter(Boolean);\n }\n\n if (Array.isArray(config.participant2MemberIds)) {\n state.participant2MemberIds = config.participant2MemberIds.filter(Boolean);\n }\n\n if (typeof config.playerName === 'string' && config.playerName.trim()) {\n state.bootstrapPlayerName = config.playerName.trim();\n } else if (config.playerName === null) {\n state.bootstrapPlayerName = null;\n }\n\n if (typeof config.peerId === 'string' && config.peerId.trim()) {\n state.bootstrapPeerId = config.peerId.trim();\n } else if (config.peerId === null) {\n state.bootstrapPeerId = null;\n }\n\n // `room` is an object on the wire so roomCode/shareId/maxPlayers and\n // optional live join credentials stay grouped \u2014 but SDK state keeps them\n // flat to avoid allocating a fresh object on every merge and to keep\n // URL-seeded values (e.g. from `?roomCode=`) in the same place.\n if (config.room && typeof config.room === 'object') {\n const room = config.room;\n\n if (typeof room.roomCode === 'string' && room.roomCode.trim()) {\n state.bootstrapRoomCode = room.roomCode.trim().toUpperCase();\n } else if (room.roomCode === null) {\n state.bootstrapRoomCode = null;\n }\n\n if (typeof room.shareId === 'string' && room.shareId.trim()) {\n state.bootstrapShareId = room.shareId.trim();\n } else if (room.shareId === null) {\n state.bootstrapShareId = null;\n }\n\n if (\n typeof room.maxPlayers === 'number' &&\n Number.isFinite(room.maxPlayers)\n ) {\n state.bootstrapMaxPlayers = room.maxPlayers;\n } else if (room.maxPlayers === null) {\n state.bootstrapMaxPlayers = null;\n }\n\n if (typeof room.role === 'string' && room.role.trim()) {\n state.bootstrapRoomRole = room.role.trim();\n } else if (room.role === null) {\n state.bootstrapRoomRole = null;\n }\n\n if (typeof room.roomToken === 'string' && room.roomToken.trim()) {\n state.bootstrapRoomToken = room.roomToken.trim();\n } else if (room.roomToken === null) {\n state.bootstrapRoomToken = null;\n }\n\n if (typeof room.wsUrl === 'string' && room.wsUrl.trim()) {\n state.bootstrapWsUrl = room.wsUrl.trim();\n } else if (room.wsUrl === null) {\n state.bootstrapWsUrl = null;\n }\n } else if (config.room === null) {\n state.bootstrapRoomCode = null;\n state.bootstrapShareId = null;\n state.bootstrapMaxPlayers = null;\n state.bootstrapRoomRole = null;\n state.bootstrapRoomToken = null;\n state.bootstrapWsUrl = null;\n }\n}\n\n/**\n * Ask the host for its bootstrap payload. Resolves `null` if the game is\n * standalone (no parent), if the host doesn't reply within the timeout, or\n * if we're not in an iframe.\n *\n * Subsequent calls after a successful bootstrap short-circuit to the cached\n * 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({\n gameSlug: state.gameSlug,\n authToken: state.authToken,\n leagueId: state.leagueId,\n gameId: state.gameId,\n matchId: state.matchId,\n participant1Id: state.participant1Id,\n participant2Id: state.participant2Id,\n participant1MemberIds: state.participant1MemberIds,\n participant2MemberIds: state.participant2MemberIds,\n playerName: state.bootstrapPlayerName,\n peerId: state.bootstrapPeerId,\n room: state.bootstrapRoomCode\n ? {\n roomCode: state.bootstrapRoomCode,\n shareId: state.bootstrapShareId,\n maxPlayers: state.bootstrapMaxPlayers,\n role: state.bootstrapRoomRole,\n roomToken: state.bootstrapRoomToken,\n wsUrl: state.bootstrapWsUrl,\n }\n : null,\n });\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\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 to\n * override league/match context \u2014 when it does, we prefer its values over\n * whatever was on the URL.\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 // Host-supplied context wins over URL params.\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 if (event.data.participant1Id)\n state.participant1Id = event.data.participant1Id;\n if (event.data.participant2Id)\n state.participant2Id = event.data.participant2Id;\n if (Array.isArray(event.data.participant1MemberIds))\n state.participant1MemberIds =\n event.data.participant1MemberIds.filter(Boolean);\n if (Array.isArray(event.data.participant2MemberIds))\n state.participant2MemberIds =\n event.data.participant2MemberIds.filter(Boolean);\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/**\n * Fire a namespaced message up to the host window. Silently no-ops when we\n * 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 type { ApiResponse, ApiRequestOptions } from '../types/api.js';\n\n/**\n * Performs a request against the GameHub REST API, prefixing the configured\n * API base, attaching the Bearer auth token when available, and parsing the\n * JSON response.\n *\n * Throws whatever `fetch`/`JSON.parse` throw \u2014 callers decide whether to\n * retry, fall back, or surface the error to the host.\n */\nexport async function apiRequest(\n endpoint: string,\n options: ApiRequestOptions = {}\n): Promise<ApiResponse> {\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", "/**\n * Multiplayer layer: room creation/join, WebSocket connection management,\n * reconnection, and an event emitter for game code to listen on.\n */\n\nimport { state } from './state.js';\nimport {\n MP_MAX_RECONNECT_ATTEMPTS,\n MP_MAX_RECONNECT_DELAY_MS,\n} from './constants.js';\nimport { apiRequest } from './api-client.js';\nimport {\n warn,\n error as logError,\n extractShareIdFromLink,\n unwrapResult,\n} from './utils.js';\nimport { ensureInitialized } from './init.js';\nimport type {\n CreateRoomResult,\n JoinInfo,\n JoinOptions,\n JoinRoomResult,\n MpEventHandler,\n Peer,\n RoomInfo,\n RoomOptions,\n} from '../types/multiplayer.js';\n\n// --- Event emitter -------------------------------------------------------\n\n/**\n * Dispatch an event to per-name listeners and the wildcard (`'*'`) listeners.\n * Handler errors are caught and logged so a buggy listener can't break the\n * socket loop.\n */\nexport function emit(eventName: string, payload: any): void {\n const handlers = state.mpHandlers.get(eventName);\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(payload);\n } catch (err) {\n logError('Multiplayer handler error:', err);\n }\n });\n }\n\n const allHandlers = state.mpHandlers.get('*');\n if (allHandlers) {\n allHandlers.forEach((handler) => {\n try {\n handler({ eventName, payload });\n } catch (err) {\n logError('Multiplayer * handler error:', err);\n }\n });\n }\n}\n\n// --- Connection lifecycle ------------------------------------------------\n\n/**\n * Detach listeners from the current socket and close it. Idempotent.\n * The caller is responsible for clearing `state.mpRoom` and related state \u2014\n * this function only touches the transport.\n */\nexport function clearSocket(): void {\n if (state.mpReconnectTimer) {\n clearTimeout(state.mpReconnectTimer);\n state.mpReconnectTimer = null;\n }\n\n if (state.mpSocket) {\n try {\n state.mpSocket.onopen = null;\n state.mpSocket.onclose = null;\n state.mpSocket.onmessage = null;\n state.mpSocket.onerror = null;\n state.mpSocket.close();\n } catch {\n // ignore\n }\n }\n\n state.mpSocket = null;\n}\n\n/**\n * Open a WebSocket for the given join info and wire up the message/close\n * handlers. Automatically reconnects with exponential backoff up to\n * `MP_MAX_RECONNECT_ATTEMPTS` attempts.\n */\nexport function connect(joinInfo: JoinInfo): void {\n clearSocket();\n\n const wsBase = joinInfo.wsUrl.replace(/\\/+$/, '');\n const wsUrl =\n wsBase +\n '?roomToken=' +\n encodeURIComponent(joinInfo.roomToken) +\n '&gameSlug=' +\n encodeURIComponent(joinInfo.gameSlug) +\n '&sdk=2.x';\n\n state.mpExpectedClose = false;\n state.mpSocket = new WebSocket(wsUrl);\n\n state.mpSocket.onopen = () => {\n state.mpReconnectAttempts = 0;\n emit('connected', {\n roomCode: joinInfo.roomCode,\n peerId: joinInfo.peerId,\n });\n };\n\n state.mpSocket.onmessage = (event: MessageEvent) => {\n let message: any = null;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n\n if (!message || !message.type) return;\n\n if (message.type === 'system') {\n if (message.eventName === 'room_joined') {\n state.mpPeers.clear();\n const peers: Peer[] = message.payload?.peers || [];\n peers.forEach((peer) => {\n if (peer && peer.peerId) state.mpPeers.set(peer.peerId, peer);\n });\n }\n\n if (message.eventName === 'peer_joined' && message.payload?.peerId) {\n state.mpPeers.set(message.payload.peerId, message.payload);\n }\n\n if (message.eventName === 'peer_left' && message.payload?.peerId) {\n state.mpPeers.delete(message.payload.peerId);\n }\n\n if (message.eventName === 'room_closed') {\n emit('room_left', { reason: 'room_closed' });\n clearSocket();\n }\n\n emit(message.eventName, message.payload || {});\n return;\n }\n\n if (message.type === 'game_event') {\n // Reentrancy guard: drop late / duplicate frames from the same peer so\n // a reconnect-replay or an out-of-order delivery can't double-advance\n // game state. The server stamps a strictly-monotonic `seq` per sender.\n if (\n typeof message.seq === 'number' &&\n typeof message.fromPeerId === 'string'\n ) {\n const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;\n if (message.seq <= last) return;\n state.mpLastSeqByPeer.set(message.fromPeerId, message.seq);\n }\n\n emit('message', {\n roomCode: message.roomCode,\n fromPeerId: message.fromPeerId,\n eventName: message.eventName,\n payload: message.payload,\n seq: message.seq,\n sentAt: message.sentAt,\n });\n\n // Also fan out to per-eventName subscribers so game code can do\n // `multiplayer.on('player_move', handler)` directly instead of\n // filtering inside a single `message` listener.\n emit(message.eventName, {\n roomCode: message.roomCode,\n fromPeerId: message.fromPeerId,\n payload: message.payload,\n seq: message.seq,\n sentAt: message.sentAt,\n });\n }\n };\n\n state.mpSocket.onclose = () => {\n emit('disconnected', { roomCode: joinInfo.roomCode });\n if (state.mpExpectedClose || !state.mpLastJoinRequest) return;\n if (state.mpReconnectAttempts >= MP_MAX_RECONNECT_ATTEMPTS) return;\n\n state.mpReconnectAttempts += 1;\n const delay = Math.min(\n 1000 * Math.pow(2, state.mpReconnectAttempts - 1),\n MP_MAX_RECONNECT_DELAY_MS\n );\n emit('reconnecting', {\n attempts: state.mpReconnectAttempts,\n delayMs: delay,\n });\n\n state.mpReconnectTimer = setTimeout(() => {\n if (!state.mpLastJoinRequest) return;\n connect(state.mpLastJoinRequest);\n }, delay);\n };\n\n state.mpSocket.onerror = () => {\n // The `onclose` handler owns reconnect logic; we only avoid\n // double-triggering it here.\n };\n}\n\n// --- High-level room actions --------------------------------------------\n\n/**\n * Create a room for the current game and connect as the host.\n */\nexport async function createRoom(\n options: RoomOptions = {}\n): Promise<CreateRoomResult> {\n await ensureInitialized();\n\n if (!state.gameSlug) {\n return { success: false, error: 'Game slug is required' };\n }\n\n const result = await apiRequest('/multiplayer/rooms/create', {\n method: 'POST',\n body: {\n gameSlug: state.gameSlug,\n maxPlayers: options.maxPlayers,\n passcode: options.passcode,\n },\n });\n\n const data = unwrapResult(result);\n if (!result.success || !data?.roomToken) {\n return {\n success: false,\n error: result.error?.message || 'Failed to create room',\n };\n }\n\n state.mpRoom = {\n roomCode: data.roomCode,\n shareId: data.shareId,\n shareUrl: data.shareUrl,\n peerId: data.peerId,\n role: data.role,\n gameSlug: data.gameSlug,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n };\n\n state.mpLastJoinRequest = {\n roomCode: data.roomCode,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n gameSlug: data.gameSlug,\n peerId: data.peerId,\n };\n\n connect(state.mpLastJoinRequest);\n\n return {\n success: true,\n roomCode: data.roomCode,\n shareId: data.shareId,\n shareUrl: data.shareUrl,\n peerId: data.peerId,\n roomToken: data.roomToken,\n };\n}\n\n/**\n * Join an existing room by its short alphanumeric code.\n */\nexport async function joinRoom(\n roomCode: string,\n options: JoinOptions = {}\n): Promise<JoinRoomResult> {\n await ensureInitialized();\n\n if (!state.gameSlug) {\n return { success: false, error: 'Game slug is required' };\n }\n\n const result = await apiRequest('/multiplayer/rooms/join-token', {\n method: 'POST',\n body: {\n gameSlug: state.gameSlug,\n roomCode,\n passcode: options.passcode,\n displayName: options.displayName,\n },\n });\n\n const data = unwrapResult(result);\n if (!result.success || !data?.roomToken) {\n return {\n success: false,\n error: result.error?.message || 'Failed to join room',\n };\n }\n\n const resolvedRole =\n options.asViewer && data.role !== 'host' ? 'viewer' : data.role;\n state.mpViewerOverride = resolvedRole === 'viewer';\n\n state.mpRoom = {\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n role: resolvedRole,\n gameSlug: data.gameSlug,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n };\n\n state.mpLastJoinRequest = {\n roomCode: data.roomCode,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n gameSlug: data.gameSlug,\n peerId: data.peerId,\n };\n\n connect(state.mpLastJoinRequest);\n\n return {\n success: true,\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n roomToken: data.roomToken,\n };\n}\n\n/**\n * Join an existing room by its share ID or full share URL.\n */\nexport async function joinRoomByLink(\n link: string,\n options: JoinOptions = {}\n): Promise<JoinRoomResult> {\n await ensureInitialized();\n\n if (!state.gameSlug) {\n return { success: false, error: 'Game slug is required' };\n }\n\n const shareId = extractShareIdFromLink(link);\n if (!shareId) {\n return { success: false, error: 'Invalid multiplayer link' };\n }\n\n const result = await apiRequest('/multiplayer/rooms/join-token', {\n method: 'POST',\n body: {\n gameSlug: state.gameSlug,\n shareId,\n passcode: options.passcode,\n displayName: options.displayName,\n },\n });\n\n const data = unwrapResult(result);\n if (!result.success || !data?.roomToken) {\n return {\n success: false,\n error: result.error?.message || 'Failed to join room by link',\n };\n }\n\n const resolvedRole =\n options.asViewer && data.role !== 'host' ? 'viewer' : data.role;\n state.mpViewerOverride = resolvedRole === 'viewer';\n\n state.mpRoom = {\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n role: resolvedRole,\n gameSlug: data.gameSlug,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n };\n\n state.mpLastJoinRequest = {\n roomCode: data.roomCode,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n gameSlug: data.gameSlug,\n peerId: data.peerId,\n };\n\n connect(state.mpLastJoinRequest);\n\n return {\n success: true,\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n roomToken: data.roomToken,\n };\n}\n\n/**\n * Disconnect from the current room. If we're the host, also ask the server\n * to close the room so stragglers get booted cleanly.\n */\nexport async function leaveRoom(reason: string = 'left'): Promise<void> {\n if (state.mpRoom && state.mpRoom.role === 'host' && state.mpRoom.roomToken) {\n try {\n await apiRequest(\n '/multiplayer/rooms/' +\n encodeURIComponent(state.mpRoom.roomCode) +\n '/close',\n {\n method: 'POST',\n body: { roomToken: state.mpRoom.roomToken },\n }\n );\n } catch {\n // ignore\n }\n }\n\n state.mpExpectedClose = true;\n clearSocket();\n state.mpRoom = null;\n state.mpLastJoinRequest = null;\n state.mpPeers.clear();\n state.mpLastSeqByPeer.clear();\n state.mpViewerOverride = false;\n emit('room_left', { reason });\n}\n\n/**\n * Send a custom game event to every other peer in the room. Returns false\n * when the socket isn't open or the current peer is a view-only guest.\n */\nexport function send(\n eventName: string,\n payload: Record<string, any> = {}\n): boolean {\n if (state.mpViewerOverride) {\n warn('multiplayer.send ignored: peer is a viewer');\n return false;\n }\n const socket = state.mpSocket;\n if (!socket || socket.readyState !== WebSocket.OPEN) {\n return false;\n }\n socket.send(JSON.stringify({ eventName, payload }));\n return true;\n}\n\n/**\n * Host-only variant of `send`. Silently no-ops (and logs a warning) if the\n * current peer isn't the host. Use this for authoritative state updates \u2014\n * grid shuffles, turn advances, round resolution \u2014 so a guest that\n * accidentally calls it can't corrupt the match.\n */\nexport function broadcast(\n eventName: string,\n payload: Record<string, any> = {}\n): boolean {\n if (!isHost()) {\n warn('multiplayer.broadcast ignored: peer is not the host');\n return false;\n }\n return send(eventName, payload);\n}\n\n/** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */\nexport function getRole(): string | null {\n return state.mpRoom ? state.mpRoom.role : null;\n}\n\n/** @returns true when the current peer is the room's authoritative host. */\nexport function isHost(): boolean {\n return state.mpRoom?.role === 'host';\n}\n\n/** @returns true when the current peer joined with `{ asViewer: true }`. */\nexport function isViewer(): boolean {\n return state.mpViewerOverride === true;\n}\n\n/**\n * Returns the peerId of the current player (self), or null if not joined.\n * Convenience for filtering self-originated echoes inside a `message`\n * listener: `if (msg.fromPeerId === selfId()) return;`.\n */\nexport function selfId(): string | null {\n return state.mpRoom ? state.mpRoom.peerId : null;\n}\n\n/**\n * Subscribe to a multiplayer event. Use `'*'` to receive every event.\n * Returns an unsubscribe function.\n */\nexport function on(eventName: string, handler: MpEventHandler): () => void {\n const handlers = state.mpHandlers;\n if (!handlers.has(eventName)) {\n handlers.set(eventName, new Set());\n }\n handlers.get(eventName)!.add(handler);\n return () => {\n const set = handlers.get(eventName);\n if (!set) return;\n set.delete(handler);\n if (set.size === 0) handlers.delete(eventName);\n };\n}\n\n/** @returns a copy of the current room descriptor, or null if not in one. */\nexport function getRoom(): RoomInfo | null {\n return state.mpRoom ? { ...state.mpRoom } : null;\n}\n\n/** @returns every peer currently in the room (self included). */\nexport function getPeers(): Peer[] {\n return Array.from(state.mpPeers.values());\n}\n\n/** @returns whether the WebSocket is currently open. */\nexport function isConnected(): boolean {\n const s = state.mpSocket;\n return Boolean(s && s.readyState === WebSocket.OPEN);\n}\n", "import { state } from './state.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult } from './utils.js';\nimport type { MatchContext, MatchParticipantMember } 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 state.participant1Id =\n data.participant1?.participantId || state.participant1Id;\n state.participant2Id =\n data.participant2?.participantId || state.participant2Id;\n state.participant1MemberIds = Array.isArray(data.participant1?.members)\n ? data.participant1.members\n .map((member: MatchParticipantMember) => member?.leaguePlayerId)\n .filter(Boolean)\n : state.participant1MemberIds;\n state.participant2MemberIds = Array.isArray(data.participant2?.members)\n ? data.participant2.members\n .map((member: MatchParticipantMember) => member?.leaguePlayerId)\n .filter(Boolean)\n : state.participant2MemberIds;\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", "import { state } from './state.js';\nimport { QUESTIONS_LIMIT_CAP } from './constants.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult, warn } from './utils.js';\nimport { sendToParent } from './bridge.js';\nimport { ensureInitialized } from './init.js';\nimport type { MatchResultPayload } from '../types/match.js';\nimport type {\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\n\n/**\n * Starts a new game session and caches the returned session token. Safe to\n * call multiple times \u2014 the cached token short-circuits subsequent 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/' +\n state.leagueId +\n '/matches/' +\n state.matchId +\n '/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 to\n * open one (re-using any in-flight start attempt).\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 // Online-mode gate: when the SDK is joined to a multiplayer room, only the\n // host is allowed to submit. Guests and viewers short-circuit with\n // `{ skipped: true }` so games can call `submitScore` from shared code\n // without double-counting the match.\n if (state.mpRoom && state.mpRoom.role !== 'host') {\n warn('submitScore skipped: only the multiplayer host may submit scores');\n return { success: true, skipped: true };\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 the\n * 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 or\n * invalid input \u2014 callers can treat \"no questions\" as the degraded 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 try {\n const params = new URLSearchParams({\n limit: String(Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)),\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\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 if (Array.isArray(data)) return data;\n if (!data || !Array.isArray(data.questions)) return [];\n return data.questions;\n } catch {\n return [];\n }\n}\n", "/**\n * SDK discovery + auto-initialisation.\n *\n * Detects the API base URL (from the `<script>` tag or the page location),\n * the active game slug, and the league/match context from the URL. Then\n * exchanges a few postMessages with the host to pick up an auth token and the\n * full bootstrap payload before opening a session and auto-joining any\n * pending multiplayer room.\n */\n\nimport { state } from './state.js';\nimport { MESSAGE_PREFIX } from './constants.js';\nimport {\n isBrowser,\n readQueryParam,\n readCsvQueryParam,\n warn,\n error as logError,\n} from './utils.js';\nimport {\n mergeBootstrapConfig,\n requestBootstrapFromParent,\n getAuthTokenFromParent,\n sendToParent,\n} from './bridge.js';\nimport * as Multiplayer from './multiplayer.js';\nimport * as MatchCtx from './match-context.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 boot\n * time, before any other Init function. Must run in a browser \u2014 calling it\n * server-side is a no-op. Idempotent: subsequent calls return immediately.\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 this lets us infer both the slug and the\n // mount point (which we use to build the API base URL).\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 state.participant1Id = readQueryParam('participant1Id');\n state.participant2Id = readQueryParam('participant2Id');\n state.participant1MemberIds = readCsvQueryParam('participant1MemberIds');\n state.participant2MemberIds = readCsvQueryParam('participant2MemberIds');\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 // Final fallback: look for a games slug in the path even if we didn't\n // match the full pattern earlier.\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 * Returns the share ID we should auto-join on boot, if any. Bootstrap takes\n * priority over URL params so hosts can override a stale link.\n */\nfunction getPendingShareId(): string | null {\n if (state.bootstrapShareId) return state.bootstrapShareId;\n return readQueryParam('mp');\n}\n\n/** Same as {@link getPendingShareId} but for room codes. */\nfunction getPendingRoomCode(): string | null {\n if (state.bootstrapRoomCode) return state.bootstrapRoomCode;\n const roomCode = readQueryParam('roomCode');\n return roomCode ? roomCode.trim().toUpperCase() : null;\n}\n\nfunction getPendingRoomRole(): string | null {\n if (state.bootstrapRoomRole) return state.bootstrapRoomRole;\n const role = readQueryParam('roomRole');\n return role ? role.trim() : null;\n}\n\nfunction getPendingRoomToken(): string | null {\n if (state.bootstrapRoomToken) return state.bootstrapRoomToken;\n const roomToken = readQueryParam('roomToken');\n return roomToken ? roomToken.trim() : null;\n}\n\nfunction getPendingWsUrl(): string | null {\n if (state.bootstrapWsUrl) return state.bootstrapWsUrl;\n const wsUrl = readQueryParam('wsUrl');\n return wsUrl ? wsUrl.trim() : null;\n}\n\n/** Same as {@link getPendingShareId} but for the host-preferred display name. */\nfunction getPendingPlayerName(): string | undefined {\n if (state.bootstrapPlayerName) return state.bootstrapPlayerName;\n const playerName = readQueryParam('playerName');\n return playerName ? playerName.trim() : undefined;\n}\n\n/**\n * Resolve the peerId for \"this player\" \u2014 bootstrap wins over the URL so the\n * host can correct a stale link. Populated opportunistically so games know\n * their assigned peerId before the multiplayer WS has joined.\n */\nfunction seedPeerIdFromUrl(): void {\n if (state.bootstrapPeerId) return;\n const fromUrl = readQueryParam('peerId');\n if (fromUrl) state.bootstrapPeerId = fromUrl.trim();\n}\n\nfunction resumePendingRoomFromBootstrap(): boolean {\n const roomCode = getPendingRoomCode();\n const roomToken = getPendingRoomToken();\n const wsUrl = getPendingWsUrl();\n const peerId =\n state.bootstrapPeerId ||\n readQueryParam('peerId')?.trim() ||\n null;\n\n if (!state.gameSlug || !roomCode || !roomToken || !wsUrl || !peerId) {\n return false;\n }\n\n const role = getPendingRoomRole() || 'player';\n state.mpViewerOverride = role === 'viewer';\n state.mpRoom = {\n roomCode,\n shareId: state.bootstrapShareId || '',\n peerId,\n role,\n gameSlug: state.gameSlug,\n roomToken,\n wsUrl,\n };\n state.mpLastJoinRequest = {\n roomCode,\n roomToken,\n wsUrl,\n gameSlug: state.gameSlug,\n peerId,\n };\n\n Multiplayer.connect(state.mpLastJoinRequest);\n return true;\n}\n\nasync function autoJoinPendingShare(): Promise<void> {\n const shareId = getPendingShareId();\n if (!shareId) return;\n if (state.lastAutoJoinShareId === shareId) return;\n\n try {\n state.lastAutoJoinShareId = shareId;\n await Multiplayer.joinRoomByLink(shareId, {\n displayName: getPendingPlayerName(),\n });\n } catch (err: any) {\n state.lastAutoJoinShareId = null;\n warn('Auto join by link failed: ' + (err?.message || err));\n }\n}\n\nasync function autoJoinPendingRoomCode(): Promise<void> {\n const roomCode = getPendingRoomCode();\n if (!roomCode) return;\n if (state.lastAutoJoinRoomCode === roomCode) return;\n\n try {\n state.lastAutoJoinRoomCode = roomCode;\n if (resumePendingRoomFromBootstrap()) {\n return;\n }\n await Multiplayer.joinRoom(roomCode, {\n displayName: getPendingPlayerName(),\n });\n } catch (err: any) {\n state.lastAutoJoinRoomCode = null;\n warn('Auto join by room code failed: ' + (err?.message || err));\n }\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, then fetch match context.\n * 4. Open a session if we can, and auto-join any pending multiplayer room.\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 // Module consumers (e.g. Angular services) call `createSdk()` directly\n // without going through the script-tag entry, so they may not have run\n // these themselves. Both functions are idempotent \u2014 safe to call again\n // when the script-tag entry has already invoked them.\n detectEnvironment();\n installHostMessageListener();\n\n state.isAutoInitializing = true;\n\n state.autoInitPromise = (async () => {\n try {\n await requestBootstrapFromParent();\n seedPeerIdFromUrl();\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 await MatchCtx.fetchMatchContext();\n\n if (\n state.authToken ||\n (state.leagueId && state.gameId && state.matchId)\n ) {\n state.sessionStartPromise = Session.startSession();\n }\n\n await autoJoinPendingShare();\n await autoJoinPendingRoomCode();\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 into\n * the running SDK (fresh bootstrap, rotated auth, pause/resume commands).\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 if (state.isInitialized && state.bootstrapShareId && !state.mpRoom) {\n autoJoinPendingShare();\n }\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", "/**\n * Public SDK module entry. Exports `createSdk` (the factory) and every\n * public type. Importing this module has no side effects \u2014 it does not\n * touch `window`, `document`, or run any boot logic.\n *\n * For the legacy `<script>`-tag distribution that auto-attaches\n * `window.GameHubSDK` and runs `autoInit()`, see `./browser-entry.ts`.\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';\nimport * as Multiplayer from './multiplayer.js';\n\nimport type { BootstrapData } from '../types/bootstrap.js';\nimport type { MatchContext, MatchResultPayload } from '../types/match.js';\nimport type {\n CreateRoomResult,\n JoinOptions,\n JoinRoomResult,\n MpEventHandler,\n Peer,\n RoomInfo,\n RoomOptions,\n} from '../types/multiplayer.js';\nimport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\n\n// Re-export the 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 BootstrapRoom,\n} from '../types/bootstrap.js';\nexport type {\n MatchContext,\n MatchParticipant,\n MatchParticipantMember,\n MatchResultPayload,\n} from '../types/match.js';\nexport type {\n CreateRoomResult,\n JoinInfo,\n JoinOptions,\n JoinRoomResult,\n MpEventHandler,\n MpJoinRequest,\n MpMessage,\n MpRoom,\n Peer,\n RoomInfo,\n RoomOptions,\n} from '../types/multiplayer.js';\nexport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\n\n/**\n * Shape of `window.GameHubSDK`. Documented separately from the\n * implementation so the public API is easy to scan.\n */\nexport interface Sdk {\n readonly version: string;\n\n /** @returns true after auto-init has successfully 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 /** Submit a full match result (winner, scores, etc.). */\n submitMatchResult(result?: MatchResultPayload): Promise<SubmitScoreResult>;\n\n /** Signal the host that the game is ready to begin another round. */\n playAgain(): Promise<{ success: boolean; token: string | 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 /** 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 /** Fetch the match context (lazy; cached after first success). */\n getMatchContext(): Promise<MatchContext | null>;\n\n /** Fetch questions for quiz-style games. Returns [] on failure. */\n getQuestions(options?: QuestionOptions): Promise<Question[]>;\n\n /** Multiplayer sub-API. */\n multiplayer: {\n createRoom(options?: RoomOptions): Promise<CreateRoomResult>;\n joinRoom(\n roomCode: string,\n options?: JoinOptions\n ): Promise<JoinRoomResult>;\n joinRoomByLink(\n link: string,\n options?: JoinOptions\n ): Promise<JoinRoomResult>;\n leaveRoom(reason?: string): Promise<void>;\n /** Send a custom event to every peer in the room. Blocked for viewers. */\n send(eventName: string, payload?: Record<string, any>): boolean;\n /**\n * Host-only send. No-ops for guests and viewers. Use this for\n * authoritative state updates (grid shuffles, turn changes, round end).\n */\n broadcast(eventName: string, payload?: Record<string, any>): boolean;\n on(eventName: string, handler: MpEventHandler): () => void;\n getRoom(): RoomInfo | null;\n getPeers(): Peer[];\n isConnected(): boolean;\n /** @returns the peer's role (`host`, `player`, `viewer`) or null. */\n getRole(): string | null;\n /** @returns true if this peer is the authoritative host. */\n isHost(): boolean;\n /** @returns true if this peer joined as a view-only guest. */\n isViewer(): boolean;\n /** @returns the peerId of the local player (self), or null. */\n selfId(): string | null;\n };\n}\n\n/**\n * Assemble the public API object. Methods are thin adapters that route to\n * the internal modules \u2014 keeping the surface area small and the internals\n * freely refactorable.\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 playAgain(): Promise<{ success: boolean; token: string | null }> {\n // Same session \u2014 each play is appended as a new record in plays[].\n return { success: true, token: state.sessionToken };\n },\n\n notifyComplete(data: GameCompleteData = {}): void {\n sendToParent('GAME_COMPLETE', data);\n },\n\n requestClose(): void {\n sendToParent('REQUEST_CLOSE', {});\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 match: state.matchContext,\n participant1Id: state.participant1Id,\n participant2Id: state.participant2Id,\n participant1MemberIds: state.participant1MemberIds,\n participant2MemberIds: state.participant2MemberIds,\n playerName: state.bootstrapPlayerName,\n peerId: state.bootstrapPeerId,\n room: state.bootstrapRoomCode\n ? {\n roomCode: state.bootstrapRoomCode,\n shareId: state.bootstrapShareId,\n maxPlayers: state.bootstrapMaxPlayers,\n role: state.bootstrapRoomRole,\n roomToken: state.bootstrapRoomToken,\n wsUrl: state.bootstrapWsUrl,\n }\n : null,\n isBootstrapped: state.bootstrapReceived,\n };\n },\n\n async getMatchContext(): Promise<MatchContext | null> {\n await ensureInitialized();\n return await MatchCtx.fetchMatchContext();\n },\n\n getQuestions(options: QuestionOptions = {}): Promise<Question[]> {\n return Session.getQuestions(options);\n },\n\n multiplayer: {\n createRoom: Multiplayer.createRoom,\n joinRoom: Multiplayer.joinRoom,\n joinRoomByLink: Multiplayer.joinRoomByLink,\n leaveRoom: Multiplayer.leaveRoom,\n send: Multiplayer.send,\n broadcast: Multiplayer.broadcast,\n on: Multiplayer.on,\n getRoom: Multiplayer.getRoom,\n getPeers: Multiplayer.getPeers,\n isConnected: Multiplayer.isConnected,\n getRole: Multiplayer.getRole,\n isHost: Multiplayer.isHost,\n isViewer: Multiplayer.isViewer,\n selfId: Multiplayer.selfId,\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;AAGlC,MAAM,4BAA4B;AAGlC,MAAM,4BAA4B;AAGlC,MAAM,sBAAsB;;;ACmE5B,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,IACT,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,uBAAuB,CAAC;AAAA,IACxB,uBAAuB,CAAC;AAAA,IAExB,cAAc;AAAA,IACd,qBAAqB;AAAA,IAErB,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,gBAAgB;AAAA,IAChB,qBAAqB;AAAA,IACrB,iBAAiB;AAAA,IACjB,qBAAqB;AAAA,IACrB,mBAA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;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 = '0.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/** Maximum number of WebSocket reconnect attempts before giving up. */\nexport const MP_MAX_RECONNECT_ATTEMPTS = 5;\n\n/** Hard cap on reconnect backoff. */\nexport const MP_MAX_RECONNECT_DELAY_MS = 10_000;\n\n/** Upper bound used when the caller doesn't pass an explicit limit. */\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 the various feature\n * modules can mutate it (`state.foo = bar`). ES modules don't allow\n * reassigning imported `let` bindings from the consumer side, so a single\n * shared object is the cleanest replacement for the previous namespace-with-\n * `export let` pattern.\n */\n\nimport type { MatchContext } from '../types/match.js';\nimport type { BootstrapConfig } from '../types/bootstrap.js';\nimport type { StartSessionResult } from '../types/session.js';\nimport type {\n MpRoom,\n MpJoinRequest,\n Peer,\n MpEventHandler,\n} from '../types/multiplayer.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 participant1Id: string | null;\n participant2Id: string | null;\n participant1MemberIds: string[];\n participant2MemberIds: string[];\n\n // --- Match metadata (fetched lazily from the API) ----------------------\n matchContext: MatchContext | null;\n matchContextPromise: Promise<MatchContext | null> | null;\n\n // --- Bootstrap payload from host ---------------------------------------\n bootstrapShareId: string | null;\n bootstrapRoomCode: string | null;\n bootstrapRoomRole: string | null;\n bootstrapRoomToken: string | null;\n bootstrapWsUrl: string | null;\n bootstrapPlayerName: string | null;\n bootstrapPeerId: string | null;\n bootstrapMaxPlayers: number | 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 lastAutoJoinShareId: string | null;\n lastAutoJoinRoomCode: string | null;\n\n // --- Multiplayer runtime ------------------------------------------------\n mpSocket: WebSocket | null;\n mpReconnectTimer: ReturnType<typeof setTimeout> | null;\n mpReconnectAttempts: number;\n mpExpectedClose: boolean;\n mpRoom: MpRoom | null;\n mpLastJoinRequest: MpJoinRequest | null;\n readonly mpPeers: Map<string, Peer>;\n readonly mpHandlers: Map<string, Set<MpEventHandler>>;\n /**\n * Highest `seq` we've already delivered to game code, per sending peer.\n * Used to drop late/duplicate `game_event` frames so a reconnect or a\n * buffered message can't double-advance game state.\n */\n readonly mpLastSeqByPeer: Map<string, number>;\n /**\n * Local override for view-only guests. The server doesn't know about\n * viewers \u2014 this is a client-side flag the SDK flips when the game joins\n * with `{ asViewer: true }`. It gates outbound `send` / `broadcast` and\n * score submission.\n */\n mpViewerOverride: boolean;\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 participant1Id: null,\n participant2Id: null,\n participant1MemberIds: [],\n participant2MemberIds: [],\n\n matchContext: null,\n matchContextPromise: null,\n\n bootstrapShareId: null,\n bootstrapRoomCode: null,\n bootstrapRoomRole: null,\n bootstrapRoomToken: null,\n bootstrapWsUrl: null,\n bootstrapPlayerName: null,\n bootstrapPeerId: null,\n bootstrapMaxPlayers: null,\n bootstrapReceived: false,\n\n isInitialized: false,\n isAutoInitializing: false,\n autoInitPromise: null,\n bootstrapRequestPromise: null,\n parentOrigin: null,\n sessionStartPromise: null,\n lastAutoJoinShareId: null,\n lastAutoJoinRoomCode: null,\n\n mpSocket: null,\n mpReconnectTimer: null,\n mpReconnectAttempts: 0,\n mpExpectedClose: false,\n mpRoom: null,\n mpLastJoinRequest: null,\n mpPeers: new Map(),\n mpHandlers: new Map(),\n mpLastSeqByPeer: new Map(),\n mpViewerOverride: false,\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 our REST API\n * down to the inner `data` payload, or returns the raw response if it isn't\n * shaped that way.\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 * Extracts a share ID from either:\n * - a full multiplayer URL (`/join?mp=<shareId>`), or\n * - a short path where the last segment is the share ID itself.\n * Returns null if the link can't be parsed.\n */\nexport function extractShareIdFromLink(link: string): string | null {\n try {\n const parsed = new URL(link, window.location.origin);\n const mp = parsed.searchParams.get('mp');\n if (mp) return mp;\n return parsed.pathname.split('/').pop() || null;\n } catch {\n return null;\n }\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/**\n * Reads a CSV query parameter and returns the trimmed, non-empty values.\n */\nexport function readCsvQueryParam(name: string): string[] {\n const raw = readQueryParam(name) || '';\n return raw\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean);\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 unrelated\n * postMessage traffic. The host is expected to implement a small protocol\n * (BOOTSTRAP_REQUEST / BOOTSTRAP, AUTH_REQUEST / AUTH_RESPONSE, etc.).\n */\n\nimport { state } from './state.js';\nimport { MESSAGE_PREFIX, PARENT_REQUEST_TIMEOUT_MS } from './constants.js';\nimport { isBrowser } from './utils.js';\nimport type { BootstrapConfig } from '../types/bootstrap.js';\n\n/**\n * Fold a {@link BootstrapConfig} from the host into internal state. Accepts\n * partial configs: only the fields that are explicitly set (including\n * explicit `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 if (typeof config.gameSlug === 'string' && config.gameSlug.trim()) {\n state.gameSlug = config.gameSlug.trim();\n }\n\n if (typeof config.authToken === 'string') {\n state.authToken = config.authToken;\n } else if (config.authToken === null) {\n state.authToken = null;\n }\n\n if (typeof config.leagueId === 'string' && config.leagueId.trim()) {\n state.leagueId = config.leagueId.trim();\n } else if (config.leagueId === null) {\n state.leagueId = null;\n }\n\n if (typeof config.gameId === 'string' && config.gameId.trim()) {\n state.gameId = config.gameId.trim();\n } else if (config.gameId === null) {\n state.gameId = null;\n }\n\n if (typeof config.matchId === 'string' && config.matchId.trim()) {\n state.matchId = config.matchId.trim();\n } else if (config.matchId === null) {\n state.matchId = null;\n }\n\n if (\n typeof config.participant1Id === 'string' &&\n config.participant1Id.trim()\n ) {\n state.participant1Id = config.participant1Id.trim();\n } else if (config.participant1Id === null) {\n state.participant1Id = null;\n }\n\n if (\n typeof config.participant2Id === 'string' &&\n config.participant2Id.trim()\n ) {\n state.participant2Id = config.participant2Id.trim();\n } else if (config.participant2Id === null) {\n state.participant2Id = null;\n }\n\n if (Array.isArray(config.participant1MemberIds)) {\n state.participant1MemberIds = config.participant1MemberIds.filter(Boolean);\n }\n\n if (Array.isArray(config.participant2MemberIds)) {\n state.participant2MemberIds = config.participant2MemberIds.filter(Boolean);\n }\n\n if (typeof config.playerName === 'string' && config.playerName.trim()) {\n state.bootstrapPlayerName = config.playerName.trim();\n } else if (config.playerName === null) {\n state.bootstrapPlayerName = null;\n }\n\n if (typeof config.peerId === 'string' && config.peerId.trim()) {\n state.bootstrapPeerId = config.peerId.trim();\n } else if (config.peerId === null) {\n state.bootstrapPeerId = null;\n }\n\n // `room` is an object on the wire so roomCode/shareId/maxPlayers and\n // optional live join credentials stay grouped \u2014 but SDK state keeps them\n // flat to avoid allocating a fresh object on every merge and to keep\n // URL-seeded values (e.g. from `?roomCode=`) in the same place.\n if (config.room && typeof config.room === 'object') {\n const room = config.room;\n\n if (typeof room.roomCode === 'string' && room.roomCode.trim()) {\n state.bootstrapRoomCode = room.roomCode.trim().toUpperCase();\n } else if (room.roomCode === null) {\n state.bootstrapRoomCode = null;\n }\n\n if (typeof room.shareId === 'string' && room.shareId.trim()) {\n state.bootstrapShareId = room.shareId.trim();\n } else if (room.shareId === null) {\n state.bootstrapShareId = null;\n }\n\n if (\n typeof room.maxPlayers === 'number' &&\n Number.isFinite(room.maxPlayers)\n ) {\n state.bootstrapMaxPlayers = room.maxPlayers;\n } else if (room.maxPlayers === null) {\n state.bootstrapMaxPlayers = null;\n }\n\n if (typeof room.role === 'string' && room.role.trim()) {\n state.bootstrapRoomRole = room.role.trim();\n } else if (room.role === null) {\n state.bootstrapRoomRole = null;\n }\n\n if (typeof room.roomToken === 'string' && room.roomToken.trim()) {\n state.bootstrapRoomToken = room.roomToken.trim();\n } else if (room.roomToken === null) {\n state.bootstrapRoomToken = null;\n }\n\n if (typeof room.wsUrl === 'string' && room.wsUrl.trim()) {\n state.bootstrapWsUrl = room.wsUrl.trim();\n } else if (room.wsUrl === null) {\n state.bootstrapWsUrl = null;\n }\n } else if (config.room === null) {\n state.bootstrapRoomCode = null;\n state.bootstrapShareId = null;\n state.bootstrapMaxPlayers = null;\n state.bootstrapRoomRole = null;\n state.bootstrapRoomToken = null;\n state.bootstrapWsUrl = null;\n }\n}\n\n/**\n * Ask the host for its bootstrap payload. Resolves `null` if the game is\n * standalone (no parent), if the host doesn't reply within the timeout, or\n * if we're not in an iframe.\n *\n * Subsequent calls after a successful bootstrap short-circuit to the cached\n * 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({\n gameSlug: state.gameSlug,\n authToken: state.authToken,\n leagueId: state.leagueId,\n gameId: state.gameId,\n matchId: state.matchId,\n participant1Id: state.participant1Id,\n participant2Id: state.participant2Id,\n participant1MemberIds: state.participant1MemberIds,\n participant2MemberIds: state.participant2MemberIds,\n playerName: state.bootstrapPlayerName,\n peerId: state.bootstrapPeerId,\n room: state.bootstrapRoomCode\n ? {\n roomCode: state.bootstrapRoomCode,\n shareId: state.bootstrapShareId,\n maxPlayers: state.bootstrapMaxPlayers,\n role: state.bootstrapRoomRole,\n roomToken: state.bootstrapRoomToken,\n wsUrl: state.bootstrapWsUrl,\n }\n : null,\n });\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\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 to\n * override league/match context \u2014 when it does, we prefer its values over\n * whatever was on the URL.\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 // Host-supplied context wins over URL params.\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 if (event.data.participant1Id)\n state.participant1Id = event.data.participant1Id;\n if (event.data.participant2Id)\n state.participant2Id = event.data.participant2Id;\n if (Array.isArray(event.data.participant1MemberIds))\n state.participant1MemberIds =\n event.data.participant1MemberIds.filter(Boolean);\n if (Array.isArray(event.data.participant2MemberIds))\n state.participant2MemberIds =\n event.data.participant2MemberIds.filter(Boolean);\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/**\n * Fire a namespaced message up to the host window. Silently no-ops when we\n * 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 type { ApiResponse, ApiRequestOptions } from '../types/api.js';\n\n/**\n * Performs a request against the GameHub REST API, prefixing the configured\n * API base, attaching the Bearer auth token when available, and parsing the\n * JSON response.\n *\n * Throws whatever `fetch`/`JSON.parse` throw \u2014 callers decide whether to\n * retry, fall back, or surface the error to the host.\n */\nexport async function apiRequest(\n endpoint: string,\n options: ApiRequestOptions = {}\n): Promise<ApiResponse> {\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", "/**\n * Multiplayer layer: room creation/join, WebSocket connection management,\n * reconnection, and an event emitter for game code to listen on.\n */\n\nimport { state } from './state.js';\nimport {\n MP_MAX_RECONNECT_ATTEMPTS,\n MP_MAX_RECONNECT_DELAY_MS,\n} from './constants.js';\nimport { apiRequest } from './api-client.js';\nimport {\n warn,\n error as logError,\n extractShareIdFromLink,\n unwrapResult,\n} from './utils.js';\nimport { ensureInitialized } from './init.js';\nimport type {\n CreateRoomResult,\n JoinInfo,\n JoinOptions,\n JoinRoomResult,\n MpEventHandler,\n Peer,\n RoomInfo,\n RoomOptions,\n SendOptions,\n} from '../types/multiplayer.js';\n\n// --- Event emitter -------------------------------------------------------\n\n/**\n * Dispatch an event to per-name listeners and the wildcard (`'*'`) listeners.\n * Handler errors are caught and logged so a buggy listener can't break the\n * socket loop.\n */\nexport function emit(eventName: string, payload: any): void {\n const handlers = state.mpHandlers.get(eventName);\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(payload);\n } catch (err) {\n logError('Multiplayer handler error:', err);\n }\n });\n }\n\n const allHandlers = state.mpHandlers.get('*');\n if (allHandlers) {\n allHandlers.forEach((handler) => {\n try {\n handler({ eventName, payload });\n } catch (err) {\n logError('Multiplayer * handler error:', err);\n }\n });\n }\n}\n\n// --- Connection lifecycle ------------------------------------------------\n\n/**\n * Detach listeners from the current socket and close it. Idempotent.\n * The caller is responsible for clearing `state.mpRoom` and related state \u2014\n * this function only touches the transport.\n */\nexport function clearSocket(): void {\n if (state.mpReconnectTimer) {\n clearTimeout(state.mpReconnectTimer);\n state.mpReconnectTimer = null;\n }\n\n if (state.mpSocket) {\n try {\n state.mpSocket.onopen = null;\n state.mpSocket.onclose = null;\n state.mpSocket.onmessage = null;\n state.mpSocket.onerror = null;\n state.mpSocket.close();\n } catch {\n // ignore\n }\n }\n\n state.mpSocket = null;\n}\n\n/**\n * Open a WebSocket for the given join info and wire up the message/close\n * handlers. Automatically reconnects with exponential backoff up to\n * `MP_MAX_RECONNECT_ATTEMPTS` attempts.\n */\nexport function connect(joinInfo: JoinInfo): void {\n clearSocket();\n\n const wsBase = joinInfo.wsUrl.replace(/\\/+$/, '');\n const wsUrl =\n wsBase +\n '?roomToken=' +\n encodeURIComponent(joinInfo.roomToken) +\n '&gameSlug=' +\n encodeURIComponent(joinInfo.gameSlug) +\n '&sdk=2.x';\n\n state.mpExpectedClose = false;\n state.mpSocket = new WebSocket(wsUrl);\n\n state.mpSocket.onopen = () => {\n state.mpReconnectAttempts = 0;\n emit('connected', {\n roomCode: joinInfo.roomCode,\n peerId: joinInfo.peerId,\n });\n };\n\n state.mpSocket.onmessage = (event: MessageEvent) => {\n let message: any = null;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n\n if (!message || !message.type) return;\n\n if (message.type === 'system') {\n if (message.eventName === 'room_joined') {\n state.mpPeers.clear();\n const peers: Peer[] = message.payload?.peers || [];\n peers.forEach((peer) => {\n if (peer && peer.peerId) state.mpPeers.set(peer.peerId, peer);\n });\n }\n\n if (message.eventName === 'peer_joined' && message.payload?.peerId) {\n state.mpPeers.set(message.payload.peerId, message.payload);\n }\n\n if (message.eventName === 'peer_left' && message.payload?.peerId) {\n state.mpPeers.delete(message.payload.peerId);\n }\n\n if (message.eventName === 'room_closed') {\n emit('room_left', { reason: 'room_closed' });\n clearSocket();\n }\n\n emit(message.eventName, message.payload || {});\n return;\n }\n\n if (message.type === 'game_event') {\n const isRetained = message.retained === true;\n\n // Reentrancy guard: drop late / duplicate frames from the same peer so\n // an out-of-order delivery can't double-advance game state. The server\n // stamps a strictly-monotonic `seq` per sender.\n //\n // Retained frames are replays of older state \u2014 their `seq` is\n // intentionally older than any live frame the receiver may already\n // have observed, so they bypass the dedupe and don't update the\n // per-peer high-water mark. Game code is expected to apply retained\n // frames idempotently (typically via a domain-level id key).\n if (\n !isRetained &&\n typeof message.seq === 'number' &&\n typeof message.fromPeerId === 'string'\n ) {\n const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;\n if (message.seq <= last) return;\n state.mpLastSeqByPeer.set(message.fromPeerId, message.seq);\n }\n\n emit('message', {\n roomCode: message.roomCode,\n fromPeerId: message.fromPeerId,\n eventName: message.eventName,\n payload: message.payload,\n seq: message.seq,\n sentAt: message.sentAt,\n retained: isRetained,\n });\n\n // Also fan out to per-eventName subscribers so game code can do\n // `multiplayer.on('player_move', handler)` directly instead of\n // filtering inside a single `message` listener.\n emit(message.eventName, {\n roomCode: message.roomCode,\n fromPeerId: message.fromPeerId,\n payload: message.payload,\n seq: message.seq,\n sentAt: message.sentAt,\n retained: isRetained,\n });\n }\n };\n\n state.mpSocket.onclose = () => {\n emit('disconnected', { roomCode: joinInfo.roomCode });\n if (state.mpExpectedClose || !state.mpLastJoinRequest) return;\n if (state.mpReconnectAttempts >= MP_MAX_RECONNECT_ATTEMPTS) return;\n\n state.mpReconnectAttempts += 1;\n const delay = Math.min(\n 1000 * Math.pow(2, state.mpReconnectAttempts - 1),\n MP_MAX_RECONNECT_DELAY_MS\n );\n emit('reconnecting', {\n attempts: state.mpReconnectAttempts,\n delayMs: delay,\n });\n\n state.mpReconnectTimer = setTimeout(() => {\n if (!state.mpLastJoinRequest) return;\n connect(state.mpLastJoinRequest);\n }, delay);\n };\n\n state.mpSocket.onerror = () => {\n // The `onclose` handler owns reconnect logic; we only avoid\n // double-triggering it here.\n };\n}\n\n// --- High-level room actions --------------------------------------------\n\n/**\n * Create a room for the current game and connect as the host.\n */\nexport async function createRoom(\n options: RoomOptions = {}\n): Promise<CreateRoomResult> {\n await ensureInitialized();\n\n if (!state.gameSlug) {\n return { success: false, error: 'Game slug is required' };\n }\n\n const result = await apiRequest('/multiplayer/rooms/create', {\n method: 'POST',\n body: {\n gameSlug: state.gameSlug,\n maxPlayers: options.maxPlayers,\n passcode: options.passcode,\n },\n });\n\n const data = unwrapResult(result);\n if (!result.success || !data?.roomToken) {\n return {\n success: false,\n error: result.error?.message || 'Failed to create room',\n };\n }\n\n state.mpRoom = {\n roomCode: data.roomCode,\n shareId: data.shareId,\n shareUrl: data.shareUrl,\n peerId: data.peerId,\n role: data.role,\n gameSlug: data.gameSlug,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n };\n\n state.mpLastJoinRequest = {\n roomCode: data.roomCode,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n gameSlug: data.gameSlug,\n peerId: data.peerId,\n };\n\n connect(state.mpLastJoinRequest);\n\n return {\n success: true,\n roomCode: data.roomCode,\n shareId: data.shareId,\n shareUrl: data.shareUrl,\n peerId: data.peerId,\n roomToken: data.roomToken,\n };\n}\n\n/**\n * Join an existing room by its short alphanumeric code.\n */\nexport async function joinRoom(\n roomCode: string,\n options: JoinOptions = {}\n): Promise<JoinRoomResult> {\n await ensureInitialized();\n\n if (!state.gameSlug) {\n return { success: false, error: 'Game slug is required' };\n }\n\n const result = await apiRequest('/multiplayer/rooms/join-token', {\n method: 'POST',\n body: {\n gameSlug: state.gameSlug,\n roomCode,\n passcode: options.passcode,\n displayName: options.displayName,\n },\n });\n\n const data = unwrapResult(result);\n if (!result.success || !data?.roomToken) {\n return {\n success: false,\n error: result.error?.message || 'Failed to join room',\n };\n }\n\n const resolvedRole =\n options.asViewer && data.role !== 'host' ? 'viewer' : data.role;\n state.mpViewerOverride = resolvedRole === 'viewer';\n\n state.mpRoom = {\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n role: resolvedRole,\n gameSlug: data.gameSlug,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n };\n\n state.mpLastJoinRequest = {\n roomCode: data.roomCode,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n gameSlug: data.gameSlug,\n peerId: data.peerId,\n };\n\n connect(state.mpLastJoinRequest);\n\n return {\n success: true,\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n roomToken: data.roomToken,\n };\n}\n\n/**\n * Join an existing room by its share ID or full share URL.\n */\nexport async function joinRoomByLink(\n link: string,\n options: JoinOptions = {}\n): Promise<JoinRoomResult> {\n await ensureInitialized();\n\n if (!state.gameSlug) {\n return { success: false, error: 'Game slug is required' };\n }\n\n const shareId = extractShareIdFromLink(link);\n if (!shareId) {\n return { success: false, error: 'Invalid multiplayer link' };\n }\n\n const result = await apiRequest('/multiplayer/rooms/join-token', {\n method: 'POST',\n body: {\n gameSlug: state.gameSlug,\n shareId,\n passcode: options.passcode,\n displayName: options.displayName,\n },\n });\n\n const data = unwrapResult(result);\n if (!result.success || !data?.roomToken) {\n return {\n success: false,\n error: result.error?.message || 'Failed to join room by link',\n };\n }\n\n const resolvedRole =\n options.asViewer && data.role !== 'host' ? 'viewer' : data.role;\n state.mpViewerOverride = resolvedRole === 'viewer';\n\n state.mpRoom = {\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n role: resolvedRole,\n gameSlug: data.gameSlug,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n };\n\n state.mpLastJoinRequest = {\n roomCode: data.roomCode,\n roomToken: data.roomToken,\n wsUrl: data.wsUrl,\n gameSlug: data.gameSlug,\n peerId: data.peerId,\n };\n\n connect(state.mpLastJoinRequest);\n\n return {\n success: true,\n roomCode: data.roomCode,\n shareId: data.shareId,\n peerId: data.peerId,\n roomToken: data.roomToken,\n };\n}\n\n/**\n * Disconnect from the current room. If we're the host, also ask the server\n * to close the room so stragglers get booted cleanly.\n */\nexport async function leaveRoom(reason: string = 'left'): Promise<void> {\n if (state.mpRoom && state.mpRoom.role === 'host' && state.mpRoom.roomToken) {\n try {\n await apiRequest(\n '/multiplayer/rooms/' +\n encodeURIComponent(state.mpRoom.roomCode) +\n '/close',\n {\n method: 'POST',\n body: { roomToken: state.mpRoom.roomToken },\n }\n );\n } catch {\n // ignore\n }\n }\n\n state.mpExpectedClose = true;\n clearSocket();\n state.mpRoom = null;\n state.mpLastJoinRequest = null;\n state.mpPeers.clear();\n state.mpLastSeqByPeer.clear();\n state.mpViewerOverride = false;\n emit('room_left', { reason });\n}\n\n/**\n * Send a custom game event to every other peer in the room. Returns false\n * when the socket isn't open or the current peer is a view-only guest.\n *\n * Pass `{ retain: true }` (host-only on the server) to pin the latest frame\n * for `retainKey` so it's replayed to peers that join/reconnect afterwards.\n */\nexport function send(\n eventName: string,\n payload: Record<string, any> = {},\n options: SendOptions = {}\n): boolean {\n if (state.mpViewerOverride) {\n warn('multiplayer.send ignored: peer is a viewer');\n return false;\n }\n const socket = state.mpSocket;\n if (!socket || socket.readyState !== WebSocket.OPEN) {\n return false;\n }\n const frame: Record<string, any> = { eventName, payload };\n if (options.retain) {\n frame.retain = true;\n if (options.retainKey) frame.retainKey = options.retainKey;\n }\n socket.send(JSON.stringify(frame));\n return true;\n}\n\n/**\n * Host-only variant of `send`. Silently no-ops (and logs a warning) if the\n * current peer isn't the host. Use this for authoritative state updates \u2014\n * grid shuffles, turn advances, round resolution \u2014 so a guest that\n * accidentally calls it can't corrupt the match.\n *\n * Pair with `{ retain: true, retainKey }` so late joiners and reconnecting\n * peers receive the latest authoritative state automatically.\n */\nexport function broadcast(\n eventName: string,\n payload: Record<string, any> = {},\n options: SendOptions = {}\n): boolean {\n if (!isHost()) {\n warn('multiplayer.broadcast ignored: peer is not the host');\n return false;\n }\n return send(eventName, payload, options);\n}\n\n/** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */\nexport function getRole(): string | null {\n return state.mpRoom ? state.mpRoom.role : null;\n}\n\n/** @returns true when the current peer is the room's authoritative host. */\nexport function isHost(): boolean {\n return state.mpRoom?.role === 'host';\n}\n\n/** @returns true when the current peer joined with `{ asViewer: true }`. */\nexport function isViewer(): boolean {\n return state.mpViewerOverride === true;\n}\n\n/**\n * Returns the peerId of the current player (self), or null if not joined.\n * Convenience for filtering self-originated echoes inside a `message`\n * listener: `if (msg.fromPeerId === selfId()) return;`.\n */\nexport function selfId(): string | null {\n return state.mpRoom ? state.mpRoom.peerId : null;\n}\n\n/**\n * Subscribe to a multiplayer event. Use `'*'` to receive every event.\n * Returns an unsubscribe function.\n */\nexport function on(eventName: string, handler: MpEventHandler): () => void {\n const handlers = state.mpHandlers;\n if (!handlers.has(eventName)) {\n handlers.set(eventName, new Set());\n }\n handlers.get(eventName)!.add(handler);\n return () => {\n const set = handlers.get(eventName);\n if (!set) return;\n set.delete(handler);\n if (set.size === 0) handlers.delete(eventName);\n };\n}\n\n/** @returns a copy of the current room descriptor, or null if not in one. */\nexport function getRoom(): RoomInfo | null {\n return state.mpRoom ? { ...state.mpRoom } : null;\n}\n\n/** @returns every peer currently in the room (self included). */\nexport function getPeers(): Peer[] {\n return Array.from(state.mpPeers.values());\n}\n\n/** @returns whether the WebSocket is currently open. */\nexport function isConnected(): boolean {\n const s = state.mpSocket;\n return Boolean(s && s.readyState === WebSocket.OPEN);\n}\n", "import { state } from './state.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult } from './utils.js';\nimport type { MatchContext, MatchParticipantMember } 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 state.participant1Id =\n data.participant1?.participantId || state.participant1Id;\n state.participant2Id =\n data.participant2?.participantId || state.participant2Id;\n state.participant1MemberIds = Array.isArray(data.participant1?.members)\n ? data.participant1.members\n .map((member: MatchParticipantMember) => member?.leaguePlayerId)\n .filter(Boolean)\n : state.participant1MemberIds;\n state.participant2MemberIds = Array.isArray(data.participant2?.members)\n ? data.participant2.members\n .map((member: MatchParticipantMember) => member?.leaguePlayerId)\n .filter(Boolean)\n : state.participant2MemberIds;\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", "import { state } from './state.js';\nimport { QUESTIONS_LIMIT_CAP } from './constants.js';\nimport { apiRequest } from './api-client.js';\nimport { unwrapResult, warn } from './utils.js';\nimport { sendToParent } from './bridge.js';\nimport { ensureInitialized } from './init.js';\nimport type { MatchResultPayload } from '../types/match.js';\nimport type {\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\n\n/**\n * Starts a new game session and caches the returned session token. Safe to\n * call multiple times \u2014 the cached token short-circuits subsequent 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/' +\n state.leagueId +\n '/matches/' +\n state.matchId +\n '/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 to\n * open one (re-using any in-flight start attempt).\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 // Online-mode gate: when the SDK is joined to a multiplayer room, only the\n // host is allowed to submit. Guests and viewers short-circuit with\n // `{ skipped: true }` so games can call `submitScore` from shared code\n // without double-counting the match.\n if (state.mpRoom && state.mpRoom.role !== 'host') {\n warn('submitScore skipped: only the multiplayer host may submit scores');\n return { success: true, skipped: true };\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 the\n * 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 or\n * invalid input \u2014 callers can treat \"no questions\" as the degraded 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 try {\n const params = new URLSearchParams({\n limit: String(Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)),\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\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 if (Array.isArray(data)) return data;\n if (!data || !Array.isArray(data.questions)) return [];\n return data.questions;\n } catch {\n return [];\n }\n}\n", "/**\n * SDK discovery + auto-initialisation.\n *\n * Detects the API base URL (from the `<script>` tag or the page location),\n * the active game slug, and the league/match context from the URL. Then\n * exchanges a few postMessages with the host to pick up an auth token and the\n * full bootstrap payload before opening a session and auto-joining any\n * pending multiplayer room.\n */\n\nimport { state } from './state.js';\nimport { MESSAGE_PREFIX } from './constants.js';\nimport {\n isBrowser,\n readQueryParam,\n readCsvQueryParam,\n warn,\n error as logError,\n} from './utils.js';\nimport {\n mergeBootstrapConfig,\n requestBootstrapFromParent,\n getAuthTokenFromParent,\n sendToParent,\n} from './bridge.js';\nimport * as Multiplayer from './multiplayer.js';\nimport * as MatchCtx from './match-context.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 boot\n * time, before any other Init function. Must run in a browser \u2014 calling it\n * server-side is a no-op. Idempotent: subsequent calls return immediately.\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 this lets us infer both the slug and the\n // mount point (which we use to build the API base URL).\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 state.participant1Id = readQueryParam('participant1Id');\n state.participant2Id = readQueryParam('participant2Id');\n state.participant1MemberIds = readCsvQueryParam('participant1MemberIds');\n state.participant2MemberIds = readCsvQueryParam('participant2MemberIds');\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 // Final fallback: look for a games slug in the path even if we didn't\n // match the full pattern earlier.\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 * Returns the share ID we should auto-join on boot, if any. Bootstrap takes\n * priority over URL params so hosts can override a stale link.\n */\nfunction getPendingShareId(): string | null {\n if (state.bootstrapShareId) return state.bootstrapShareId;\n return readQueryParam('mp');\n}\n\n/** Same as {@link getPendingShareId} but for room codes. */\nfunction getPendingRoomCode(): string | null {\n if (state.bootstrapRoomCode) return state.bootstrapRoomCode;\n const roomCode = readQueryParam('roomCode');\n return roomCode ? roomCode.trim().toUpperCase() : null;\n}\n\nfunction getPendingRoomRole(): string | null {\n if (state.bootstrapRoomRole) return state.bootstrapRoomRole;\n const role = readQueryParam('roomRole');\n return role ? role.trim() : null;\n}\n\nfunction getPendingRoomToken(): string | null {\n if (state.bootstrapRoomToken) return state.bootstrapRoomToken;\n const roomToken = readQueryParam('roomToken');\n return roomToken ? roomToken.trim() : null;\n}\n\nfunction getPendingWsUrl(): string | null {\n if (state.bootstrapWsUrl) return state.bootstrapWsUrl;\n const wsUrl = readQueryParam('wsUrl');\n return wsUrl ? wsUrl.trim() : null;\n}\n\n/** Same as {@link getPendingShareId} but for the host-preferred display name. */\nfunction getPendingPlayerName(): string | undefined {\n if (state.bootstrapPlayerName) return state.bootstrapPlayerName;\n const playerName = readQueryParam('playerName');\n return playerName ? playerName.trim() : undefined;\n}\n\n/**\n * Resolve the peerId for \"this player\" \u2014 bootstrap wins over the URL so the\n * host can correct a stale link. Populated opportunistically so games know\n * their assigned peerId before the multiplayer WS has joined.\n */\nfunction seedPeerIdFromUrl(): void {\n if (state.bootstrapPeerId) return;\n const fromUrl = readQueryParam('peerId');\n if (fromUrl) state.bootstrapPeerId = fromUrl.trim();\n}\n\nfunction resumePendingRoomFromBootstrap(): boolean {\n const roomCode = getPendingRoomCode();\n const roomToken = getPendingRoomToken();\n const wsUrl = getPendingWsUrl();\n const peerId =\n state.bootstrapPeerId ||\n readQueryParam('peerId')?.trim() ||\n null;\n\n if (!state.gameSlug || !roomCode || !roomToken || !wsUrl || !peerId) {\n return false;\n }\n\n const role = getPendingRoomRole() || 'player';\n state.mpViewerOverride = role === 'viewer';\n state.mpRoom = {\n roomCode,\n shareId: state.bootstrapShareId || '',\n peerId,\n role,\n gameSlug: state.gameSlug,\n roomToken,\n wsUrl,\n };\n state.mpLastJoinRequest = {\n roomCode,\n roomToken,\n wsUrl,\n gameSlug: state.gameSlug,\n peerId,\n };\n\n Multiplayer.connect(state.mpLastJoinRequest);\n return true;\n}\n\nasync function autoJoinPendingShare(): Promise<void> {\n const shareId = getPendingShareId();\n if (!shareId) return;\n if (state.lastAutoJoinShareId === shareId) return;\n\n try {\n state.lastAutoJoinShareId = shareId;\n await Multiplayer.joinRoomByLink(shareId, {\n displayName: getPendingPlayerName(),\n });\n } catch (err: any) {\n state.lastAutoJoinShareId = null;\n warn('Auto join by link failed: ' + (err?.message || err));\n }\n}\n\nasync function autoJoinPendingRoomCode(): Promise<void> {\n const roomCode = getPendingRoomCode();\n if (!roomCode) return;\n if (state.lastAutoJoinRoomCode === roomCode) return;\n\n try {\n state.lastAutoJoinRoomCode = roomCode;\n if (resumePendingRoomFromBootstrap()) {\n return;\n }\n await Multiplayer.joinRoom(roomCode, {\n displayName: getPendingPlayerName(),\n });\n } catch (err: any) {\n state.lastAutoJoinRoomCode = null;\n warn('Auto join by room code failed: ' + (err?.message || err));\n }\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, then fetch match context.\n * 4. Open a session if we can, and auto-join any pending multiplayer room.\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 // Module consumers (e.g. Angular services) call `createSdk()` directly\n // without going through the script-tag entry, so they may not have run\n // these themselves. Both functions are idempotent \u2014 safe to call again\n // when the script-tag entry has already invoked them.\n detectEnvironment();\n installHostMessageListener();\n\n state.isAutoInitializing = true;\n\n state.autoInitPromise = (async () => {\n try {\n await requestBootstrapFromParent();\n seedPeerIdFromUrl();\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 await MatchCtx.fetchMatchContext();\n\n if (\n state.authToken ||\n (state.leagueId && state.gameId && state.matchId)\n ) {\n state.sessionStartPromise = Session.startSession();\n }\n\n await autoJoinPendingShare();\n await autoJoinPendingRoomCode();\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 into\n * the running SDK (fresh bootstrap, rotated auth, pause/resume commands).\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 if (state.isInitialized && state.bootstrapShareId && !state.mpRoom) {\n autoJoinPendingShare();\n }\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", "/**\n * Public SDK module entry. Exports `createSdk` (the factory) and every\n * public type. Importing this module has no side effects \u2014 it does not\n * touch `window`, `document`, or run any boot logic.\n *\n * For the legacy `<script>`-tag distribution that auto-attaches\n * `window.GameHubSDK` and runs `autoInit()`, see `./browser-entry.ts`.\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';\nimport * as Multiplayer from './multiplayer.js';\n\nimport type { BootstrapData } from '../types/bootstrap.js';\nimport type { MatchContext, MatchResultPayload } from '../types/match.js';\nimport type {\n CreateRoomResult,\n JoinOptions,\n JoinRoomResult,\n MpEventHandler,\n Peer,\n RoomInfo,\n RoomOptions,\n SendOptions,\n} from '../types/multiplayer.js';\nimport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\n\n// Re-export the 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 BootstrapRoom,\n} from '../types/bootstrap.js';\nexport type {\n MatchContext,\n MatchParticipant,\n MatchParticipantMember,\n MatchResultPayload,\n} from '../types/match.js';\nexport type {\n CreateRoomResult,\n JoinInfo,\n JoinOptions,\n JoinRoomResult,\n MpEventHandler,\n MpJoinRequest,\n MpMessage,\n MpRoom,\n Peer,\n RoomInfo,\n RoomOptions,\n SendOptions,\n} from '../types/multiplayer.js';\nexport type {\n EventData,\n GameCompleteData,\n Question,\n QuestionOptions,\n ScoreMetadata,\n StartSessionResult,\n SubmitScoreResult,\n} from '../types/session.js';\n\n/**\n * Shape of `window.GameHubSDK`. Documented separately from the\n * implementation so the public API is easy to scan.\n */\nexport interface Sdk {\n readonly version: string;\n\n /** @returns true after auto-init has successfully 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 /** Submit a full match result (winner, scores, etc.). */\n submitMatchResult(result?: MatchResultPayload): Promise<SubmitScoreResult>;\n\n /** Signal the host that the game is ready to begin another round. */\n playAgain(): Promise<{ success: boolean; token: string | 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 /** 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 /** Fetch the match context (lazy; cached after first success). */\n getMatchContext(): Promise<MatchContext | null>;\n\n /** Fetch questions for quiz-style games. Returns [] on failure. */\n getQuestions(options?: QuestionOptions): Promise<Question[]>;\n\n /** Multiplayer sub-API. */\n multiplayer: {\n createRoom(options?: RoomOptions): Promise<CreateRoomResult>;\n joinRoom(\n roomCode: string,\n options?: JoinOptions\n ): Promise<JoinRoomResult>;\n joinRoomByLink(\n link: string,\n options?: JoinOptions\n ): Promise<JoinRoomResult>;\n leaveRoom(reason?: string): Promise<void>;\n /**\n * Send a custom event to every peer in the room. Blocked for viewers.\n * Pass `{ retain: true, retainKey }` (host only on the server side) to\n * pin the latest frame so peers joining/reconnecting later receive it\n * before live traffic.\n */\n send(\n eventName: string,\n payload?: Record<string, any>,\n options?: SendOptions\n ): boolean;\n /**\n * Host-only send. No-ops for guests and viewers. Use this for\n * authoritative state updates (grid shuffles, turn changes, round end).\n * Pair with `{ retain: true, retainKey }` to make the latest snapshot\n * automatically replay to late joiners and reconnecting peers.\n */\n broadcast(\n eventName: string,\n payload?: Record<string, any>,\n options?: SendOptions\n ): boolean;\n on(eventName: string, handler: MpEventHandler): () => void;\n getRoom(): RoomInfo | null;\n getPeers(): Peer[];\n isConnected(): boolean;\n /** @returns the peer's role (`host`, `player`, `viewer`) or null. */\n getRole(): string | null;\n /** @returns true if this peer is the authoritative host. */\n isHost(): boolean;\n /** @returns true if this peer joined as a view-only guest. */\n isViewer(): boolean;\n /** @returns the peerId of the local player (self), or null. */\n selfId(): string | null;\n };\n}\n\n/**\n * Assemble the public API object. Methods are thin adapters that route to\n * the internal modules \u2014 keeping the surface area small and the internals\n * freely refactorable.\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 playAgain(): Promise<{ success: boolean; token: string | null }> {\n // Same session \u2014 each play is appended as a new record in plays[].\n return { success: true, token: state.sessionToken };\n },\n\n notifyComplete(data: GameCompleteData = {}): void {\n sendToParent('GAME_COMPLETE', data);\n },\n\n requestClose(): void {\n sendToParent('REQUEST_CLOSE', {});\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 match: state.matchContext,\n participant1Id: state.participant1Id,\n participant2Id: state.participant2Id,\n participant1MemberIds: state.participant1MemberIds,\n participant2MemberIds: state.participant2MemberIds,\n playerName: state.bootstrapPlayerName,\n peerId: state.bootstrapPeerId,\n room: state.bootstrapRoomCode\n ? {\n roomCode: state.bootstrapRoomCode,\n shareId: state.bootstrapShareId,\n maxPlayers: state.bootstrapMaxPlayers,\n role: state.bootstrapRoomRole,\n roomToken: state.bootstrapRoomToken,\n wsUrl: state.bootstrapWsUrl,\n }\n : null,\n isBootstrapped: state.bootstrapReceived,\n };\n },\n\n async getMatchContext(): Promise<MatchContext | null> {\n await ensureInitialized();\n return await MatchCtx.fetchMatchContext();\n },\n\n getQuestions(options: QuestionOptions = {}): Promise<Question[]> {\n return Session.getQuestions(options);\n },\n\n multiplayer: {\n createRoom: Multiplayer.createRoom,\n joinRoom: Multiplayer.joinRoom,\n joinRoomByLink: Multiplayer.joinRoomByLink,\n leaveRoom: Multiplayer.leaveRoom,\n send: Multiplayer.send,\n broadcast: Multiplayer.broadcast,\n on: Multiplayer.on,\n getRoom: Multiplayer.getRoom,\n getPeers: Multiplayer.getPeers,\n isConnected: Multiplayer.isConnected,\n getRole: Multiplayer.getRole,\n isHost: Multiplayer.isHost,\n isViewer: Multiplayer.isViewer,\n selfId: Multiplayer.selfId,\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;AAGlC,MAAM,4BAA4B;AAGlC,MAAM,4BAA4B;AAGlC,MAAM,sBAAsB;;;ACmE5B,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,IACT,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,uBAAuB,CAAC;AAAA,IACxB,uBAAuB,CAAC;AAAA,IAExB,cAAc;AAAA,IACd,qBAAqB;AAAA,IAErB,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,gBAAgB;AAAA,IAChB,qBAAqB;AAAA,IACrB,iBA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A;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;;;ACjSA,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 = "0.
|
|
4
|
+
export declare const SDK_VERSION = "0.5.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 = '0.
|
|
4
|
+
export const SDK_VERSION = '0.5.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
|
@@ -8,12 +8,12 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { BootstrapData } from '../types/bootstrap.js';
|
|
10
10
|
import type { MatchContext, MatchResultPayload } from '../types/match.js';
|
|
11
|
-
import type { CreateRoomResult, JoinOptions, JoinRoomResult, MpEventHandler, Peer, RoomInfo, RoomOptions } from '../types/multiplayer.js';
|
|
11
|
+
import type { CreateRoomResult, JoinOptions, JoinRoomResult, MpEventHandler, Peer, RoomInfo, RoomOptions, SendOptions } from '../types/multiplayer.js';
|
|
12
12
|
import type { EventData, GameCompleteData, Question, QuestionOptions, ScoreMetadata, StartSessionResult, SubmitScoreResult } from '../types/session.js';
|
|
13
13
|
export type { ApiRequestOptions, ApiResponse } from '../types/api.js';
|
|
14
14
|
export type { BootstrapConfig, BootstrapData, BootstrapRoom, } from '../types/bootstrap.js';
|
|
15
15
|
export type { MatchContext, MatchParticipant, MatchParticipantMember, MatchResultPayload, } from '../types/match.js';
|
|
16
|
-
export type { CreateRoomResult, JoinInfo, JoinOptions, JoinRoomResult, MpEventHandler, MpJoinRequest, MpMessage, MpRoom, Peer, RoomInfo, RoomOptions, } from '../types/multiplayer.js';
|
|
16
|
+
export type { CreateRoomResult, JoinInfo, JoinOptions, JoinRoomResult, MpEventHandler, MpJoinRequest, MpMessage, MpRoom, Peer, RoomInfo, RoomOptions, SendOptions, } from '../types/multiplayer.js';
|
|
17
17
|
export type { EventData, GameCompleteData, Question, QuestionOptions, ScoreMetadata, StartSessionResult, SubmitScoreResult, } from '../types/session.js';
|
|
18
18
|
/**
|
|
19
19
|
* Shape of `window.GameHubSDK`. Documented separately from the
|
|
@@ -64,13 +64,20 @@ export interface Sdk {
|
|
|
64
64
|
joinRoom(roomCode: string, options?: JoinOptions): Promise<JoinRoomResult>;
|
|
65
65
|
joinRoomByLink(link: string, options?: JoinOptions): Promise<JoinRoomResult>;
|
|
66
66
|
leaveRoom(reason?: string): Promise<void>;
|
|
67
|
-
/**
|
|
68
|
-
|
|
67
|
+
/**
|
|
68
|
+
* Send a custom event to every peer in the room. Blocked for viewers.
|
|
69
|
+
* Pass `{ retain: true, retainKey }` (host only on the server side) to
|
|
70
|
+
* pin the latest frame so peers joining/reconnecting later receive it
|
|
71
|
+
* before live traffic.
|
|
72
|
+
*/
|
|
73
|
+
send(eventName: string, payload?: Record<string, any>, options?: SendOptions): boolean;
|
|
69
74
|
/**
|
|
70
75
|
* Host-only send. No-ops for guests and viewers. Use this for
|
|
71
76
|
* authoritative state updates (grid shuffles, turn changes, round end).
|
|
77
|
+
* Pair with `{ retain: true, retainKey }` to make the latest snapshot
|
|
78
|
+
* automatically replay to late joiners and reconnecting peers.
|
|
72
79
|
*/
|
|
73
|
-
broadcast(eventName: string, payload?: Record<string, any
|
|
80
|
+
broadcast(eventName: string, payload?: Record<string, any>, options?: SendOptions): boolean;
|
|
74
81
|
on(eventName: string, handler: MpEventHandler): () => void;
|
|
75
82
|
getRoom(): RoomInfo | null;
|
|
76
83
|
getPeers(): Peer[];
|
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;;;;;;;GAOG;AAWH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,KAAK,EACV,gBAAgB,EAChB,WAAW,EACX,cAAc,EACd,cAAc,EACd,IAAI,EACJ,QAAQ,EACR,WAAW,EACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EACV,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,eAAe,EACf,aAAa,EACb,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,qBAAqB,CAAC;AAI7B,YAAY,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACtE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AM,EAAE,WAAW,CAAC,MAAM;YAC1B,QAAQ,EAAE,WAAW,CAAC,QAAQ;YAC9B,MAAM,EAAE,WAAW,CAAC,MAAM;SAC3B;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Multiplayer layer: room creation/join, WebSocket connection management,
|
|
3
3
|
* reconnection, and an event emitter for game code to listen on.
|
|
4
4
|
*/
|
|
5
|
-
import type { CreateRoomResult, JoinInfo, JoinOptions, JoinRoomResult, MpEventHandler, Peer, RoomInfo, RoomOptions } from '../types/multiplayer.js';
|
|
5
|
+
import type { CreateRoomResult, JoinInfo, JoinOptions, JoinRoomResult, MpEventHandler, Peer, RoomInfo, RoomOptions, SendOptions } from '../types/multiplayer.js';
|
|
6
6
|
/**
|
|
7
7
|
* Dispatch an event to per-name listeners and the wildcard (`'*'`) listeners.
|
|
8
8
|
* Handler errors are caught and logged so a buggy listener can't break the
|
|
@@ -41,15 +41,21 @@ export declare function leaveRoom(reason?: string): Promise<void>;
|
|
|
41
41
|
/**
|
|
42
42
|
* Send a custom game event to every other peer in the room. Returns false
|
|
43
43
|
* when the socket isn't open or the current peer is a view-only guest.
|
|
44
|
+
*
|
|
45
|
+
* Pass `{ retain: true }` (host-only on the server) to pin the latest frame
|
|
46
|
+
* for `retainKey` so it's replayed to peers that join/reconnect afterwards.
|
|
44
47
|
*/
|
|
45
|
-
export declare function send(eventName: string, payload?: Record<string, any
|
|
48
|
+
export declare function send(eventName: string, payload?: Record<string, any>, options?: SendOptions): boolean;
|
|
46
49
|
/**
|
|
47
50
|
* Host-only variant of `send`. Silently no-ops (and logs a warning) if the
|
|
48
51
|
* current peer isn't the host. Use this for authoritative state updates —
|
|
49
52
|
* grid shuffles, turn advances, round resolution — so a guest that
|
|
50
53
|
* accidentally calls it can't corrupt the match.
|
|
54
|
+
*
|
|
55
|
+
* Pair with `{ retain: true, retainKey }` so late joiners and reconnecting
|
|
56
|
+
* peers receive the latest authoritative state automatically.
|
|
51
57
|
*/
|
|
52
|
-
export declare function broadcast(eventName: string, payload?: Record<string, any
|
|
58
|
+
export declare function broadcast(eventName: string, payload?: Record<string, any>, options?: SendOptions): boolean;
|
|
53
59
|
/** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */
|
|
54
60
|
export declare function getRole(): string | null;
|
|
55
61
|
/** @returns true when the current peer is the room's authoritative host. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multiplayer.d.ts","sourceRoot":"","sources":["../../src/multiplayer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAeH,OAAO,KAAK,EACV,gBAAgB,EAChB,QAAQ,EACR,WAAW,EACX,cAAc,EACd,cAAc,EACd,IAAI,EACJ,QAAQ,EACR,WAAW,EACZ,MAAM,yBAAyB,CAAC;AAIjC;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,IAAI,CAsB1D;AAID;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,IAAI,CAmBlC;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"multiplayer.d.ts","sourceRoot":"","sources":["../../src/multiplayer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAeH,OAAO,KAAK,EACV,gBAAgB,EAChB,QAAQ,EACR,WAAW,EACX,cAAc,EACd,cAAc,EACd,IAAI,EACJ,QAAQ,EACR,WAAW,EACX,WAAW,EACZ,MAAM,yBAAyB,CAAC;AAIjC;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,IAAI,CAsB1D;AAID;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,IAAI,CAmBlC;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAkIhD;AAID;;GAEG;AACH,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AgB,WAAW,IAAI,OAAO,CAGrC"}
|
package/dist/src/multiplayer.js
CHANGED
|
@@ -118,10 +118,18 @@ export function connect(joinInfo) {
|
|
|
118
118
|
return;
|
|
119
119
|
}
|
|
120
120
|
if (message.type === 'game_event') {
|
|
121
|
+
const isRetained = message.retained === true;
|
|
121
122
|
// Reentrancy guard: drop late / duplicate frames from the same peer so
|
|
122
|
-
//
|
|
123
|
-
//
|
|
124
|
-
|
|
123
|
+
// an out-of-order delivery can't double-advance game state. The server
|
|
124
|
+
// stamps a strictly-monotonic `seq` per sender.
|
|
125
|
+
//
|
|
126
|
+
// Retained frames are replays of older state — their `seq` is
|
|
127
|
+
// intentionally older than any live frame the receiver may already
|
|
128
|
+
// have observed, so they bypass the dedupe and don't update the
|
|
129
|
+
// per-peer high-water mark. Game code is expected to apply retained
|
|
130
|
+
// frames idempotently (typically via a domain-level id key).
|
|
131
|
+
if (!isRetained &&
|
|
132
|
+
typeof message.seq === 'number' &&
|
|
125
133
|
typeof message.fromPeerId === 'string') {
|
|
126
134
|
const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;
|
|
127
135
|
if (message.seq <= last)
|
|
@@ -135,6 +143,7 @@ export function connect(joinInfo) {
|
|
|
135
143
|
payload: message.payload,
|
|
136
144
|
seq: message.seq,
|
|
137
145
|
sentAt: message.sentAt,
|
|
146
|
+
retained: isRetained,
|
|
138
147
|
});
|
|
139
148
|
// Also fan out to per-eventName subscribers so game code can do
|
|
140
149
|
// `multiplayer.on('player_move', handler)` directly instead of
|
|
@@ -145,6 +154,7 @@ export function connect(joinInfo) {
|
|
|
145
154
|
payload: message.payload,
|
|
146
155
|
seq: message.seq,
|
|
147
156
|
sentAt: message.sentAt,
|
|
157
|
+
retained: isRetained,
|
|
148
158
|
});
|
|
149
159
|
}
|
|
150
160
|
};
|
|
@@ -358,8 +368,11 @@ export async function leaveRoom(reason = 'left') {
|
|
|
358
368
|
/**
|
|
359
369
|
* Send a custom game event to every other peer in the room. Returns false
|
|
360
370
|
* when the socket isn't open or the current peer is a view-only guest.
|
|
371
|
+
*
|
|
372
|
+
* Pass `{ retain: true }` (host-only on the server) to pin the latest frame
|
|
373
|
+
* for `retainKey` so it's replayed to peers that join/reconnect afterwards.
|
|
361
374
|
*/
|
|
362
|
-
export function send(eventName, payload = {}) {
|
|
375
|
+
export function send(eventName, payload = {}, options = {}) {
|
|
363
376
|
if (state.mpViewerOverride) {
|
|
364
377
|
warn('multiplayer.send ignored: peer is a viewer');
|
|
365
378
|
return false;
|
|
@@ -368,7 +381,13 @@ export function send(eventName, payload = {}) {
|
|
|
368
381
|
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
369
382
|
return false;
|
|
370
383
|
}
|
|
371
|
-
|
|
384
|
+
const frame = { eventName, payload };
|
|
385
|
+
if (options.retain) {
|
|
386
|
+
frame.retain = true;
|
|
387
|
+
if (options.retainKey)
|
|
388
|
+
frame.retainKey = options.retainKey;
|
|
389
|
+
}
|
|
390
|
+
socket.send(JSON.stringify(frame));
|
|
372
391
|
return true;
|
|
373
392
|
}
|
|
374
393
|
/**
|
|
@@ -376,13 +395,16 @@ export function send(eventName, payload = {}) {
|
|
|
376
395
|
* current peer isn't the host. Use this for authoritative state updates —
|
|
377
396
|
* grid shuffles, turn advances, round resolution — so a guest that
|
|
378
397
|
* accidentally calls it can't corrupt the match.
|
|
398
|
+
*
|
|
399
|
+
* Pair with `{ retain: true, retainKey }` so late joiners and reconnecting
|
|
400
|
+
* peers receive the latest authoritative state automatically.
|
|
379
401
|
*/
|
|
380
|
-
export function broadcast(eventName, payload = {}) {
|
|
402
|
+
export function broadcast(eventName, payload = {}, options = {}) {
|
|
381
403
|
if (!isHost()) {
|
|
382
404
|
warn('multiplayer.broadcast ignored: peer is not the host');
|
|
383
405
|
return false;
|
|
384
406
|
}
|
|
385
|
-
return send(eventName, payload);
|
|
407
|
+
return send(eventName, payload, options);
|
|
386
408
|
}
|
|
387
409
|
/** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */
|
|
388
410
|
export function getRole() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multiplayer.js","sourceRoot":"","sources":["../../src/multiplayer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EACL,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EACL,IAAI,EACJ,KAAK,IAAI,QAAQ,EACjB,sBAAsB,EACtB,YAAY,GACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAY9C,4EAA4E;AAE5E;;;;GAIG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,OAAY;IAClD,MAAM,QAAQ,GAAG,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACjD,IAAI,QAAQ,EAAE,CAAC;QACb,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC3B,IAAI,CAAC;gBACH,OAAO,CAAC,OAAO,CAAC,CAAC;YACnB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,QAAQ,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAC;YAC9C,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC9C,IAAI,WAAW,EAAE,CAAC;QAChB,WAAW,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC9B,IAAI,CAAC;gBACH,OAAO,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC;YAClC,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,QAAQ,CAAC,8BAA8B,EAAE,GAAG,CAAC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AU,KAAK,SAAS,CAAC,IAAI,CAAC,CAAC;AACvD,CAAC"}
|
|
@@ -74,6 +74,28 @@ export interface JoinOptions {
|
|
|
74
74
|
*/
|
|
75
75
|
asViewer?: boolean;
|
|
76
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Options accepted by `multiplayer.send` / `multiplayer.broadcast`.
|
|
79
|
+
*/
|
|
80
|
+
export interface SendOptions {
|
|
81
|
+
/**
|
|
82
|
+
* When true, the server keeps the latest frame for `retainKey` (or the
|
|
83
|
+
* event name if no key is given) and replays it to every peer that joins
|
|
84
|
+
* the room afterwards — before any live traffic reaches that peer's
|
|
85
|
+
* socket. Mirrors MQTT retained messages.
|
|
86
|
+
*
|
|
87
|
+
* Only the room's host may retain frames; the server silently drops the
|
|
88
|
+
* `retain` flag from non-host senders.
|
|
89
|
+
*/
|
|
90
|
+
retain?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Identifier under which the server stores the retained frame. Sending
|
|
93
|
+
* another retained frame with the same key overwrites the previous value
|
|
94
|
+
* but keeps its position in replay order. Defaults to the event name.
|
|
95
|
+
* Must match `^[a-zA-Z0-9_.:-]{1,64}$`.
|
|
96
|
+
*/
|
|
97
|
+
retainKey?: string;
|
|
98
|
+
}
|
|
77
99
|
/**
|
|
78
100
|
* Shape of the `message` event emitted for every peer-originated game event.
|
|
79
101
|
*/
|
|
@@ -84,6 +106,15 @@ export interface MpMessage<T = any> {
|
|
|
84
106
|
payload: T;
|
|
85
107
|
seq: number;
|
|
86
108
|
sentAt: number;
|
|
109
|
+
/**
|
|
110
|
+
* True when the frame is a server-replayed retained ("sticky") snapshot
|
|
111
|
+
* delivered on join/reconnect. Game code can usually treat retained and
|
|
112
|
+
* live frames identically — apply both via the same handler. Idempotent
|
|
113
|
+
* appliers don't need to special-case this flag, but games that play
|
|
114
|
+
* sounds/animations on a state change typically suppress them when
|
|
115
|
+
* `retained` is true.
|
|
116
|
+
*/
|
|
117
|
+
retained?: boolean;
|
|
87
118
|
}
|
|
88
119
|
/** Result returned by `multiplayer.createRoom`. */
|
|
89
120
|
export interface CreateRoomResult {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multiplayer.d.ts","sourceRoot":"","sources":["../../types/multiplayer.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,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,WAAW,SAAS,CAAC,CAAC,GAAG,GAAG;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,CAAC,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,mDAAmD;AACnD,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,oEAAoE;AACpE,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,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": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "ESM SDK that lets GameHub-hosted games talk to the platform (auth, sessions, scores, multiplayer). Drops into Node, Angular, browsers, or a `<script>` tag.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/src/main.js",
|