@ksaa-nlp/gamehub-sdk 4.0.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -1
- package/SPEC.md +95 -6
- package/dist/gamehub-sdk.js +154 -11
- package/dist/gamehub-sdk.js.map +4 -4
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +32 -1
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/init.js +1 -1
- package/dist/src/init.js.map +1 -1
- package/dist/src/main.d.ts +13 -7
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +12 -1
- package/dist/src/main.js.map +1 -1
- package/dist/src/multiplayer.d.ts +4 -0
- package/dist/src/multiplayer.d.ts.map +1 -0
- package/dist/src/multiplayer.js +91 -0
- package/dist/src/multiplayer.js.map +1 -0
- package/dist/src/server-entry.d.ts +15 -5
- package/dist/src/server-entry.d.ts.map +1 -1
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +2 -0
- package/dist/src/session.js.map +1 -1
- package/dist/src/settings.d.ts +7 -0
- package/dist/src/settings.d.ts.map +1 -0
- package/dist/src/settings.js +49 -0
- package/dist/src/settings.js.map +1 -0
- package/dist/src/state.d.ts +5 -1
- package/dist/src/state.d.ts.map +1 -1
- package/dist/src/state.js +4 -0
- package/dist/src/state.js.map +1 -1
- package/dist/types/bootstrap.d.ts +39 -0
- package/dist/types/bootstrap.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -237,7 +237,7 @@ sdk.reportWord({
|
|
|
237
237
|
});
|
|
238
238
|
```
|
|
239
239
|
|
|
240
|
-
All of these are fire-and-forget — they just signal the host (over whichever transport is active). `reportQuestion` / `reportWord` ask the host to open its report dialog (the host collects the reason + optional message
|
|
240
|
+
All of these are fire-and-forget — they just signal the host (over whichever transport is active). `reportQuestion` / `reportWord` ask the host to open its report dialog (the host collects the reason + optional message for logged-in users and submits it; guests see a login prompt). Pass `questions` / `words` instead of a single id to have the host render a dropdown so the player chooses which item to report.
|
|
241
241
|
|
|
242
242
|
## Pause/resume from the host
|
|
243
243
|
|
|
@@ -382,3 +382,44 @@ See [SPEC.md §21bis](./SPEC.md#21bis-ugc-server-bundle-subpath) for the full co
|
|
|
382
382
|
## License
|
|
383
383
|
|
|
384
384
|
ISC.
|
|
385
|
+
|
|
386
|
+
## Account-wide game settings
|
|
387
|
+
|
|
388
|
+
Music is **off by default**, including guests and older hosts. GameHub delivers
|
|
389
|
+
saved account preferences in bootstrap and pushes updates in the current host.
|
|
390
|
+
The SDK provides settings; your game implements the audio behavior.
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
await sdk.ready();
|
|
394
|
+
const initialSettings = sdk.getSettings(); // { musicEnabled: false } by default
|
|
395
|
+
const unsubscribe = sdk.onSettingsChange(({ musicEnabled }) => {
|
|
396
|
+
// Apply to current AND future background music; keep your local mute too.
|
|
397
|
+
audio.setMusicAllowed(musicEnabled);
|
|
398
|
+
});
|
|
399
|
+
// On game teardown:
|
|
400
|
+
unsubscribe();
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
Callbacks immediately receive a snapshot and subsequently receive changes.
|
|
404
|
+
You can subscribe before `ready()` to keep music off during startup. Settings
|
|
405
|
+
are also available as `sdk.getBootstrap().settings`. Enabling music permits
|
|
406
|
+
playback subject to browser autoplay and the game's local mute; it must not
|
|
407
|
+
unmute sound effects or speech. Existing games need an integration update.
|
|
408
|
+
|
|
409
|
+
For a runnable reference game, serve the repository root with an HTTP static
|
|
410
|
+
server and open `packages/gamehub-sdk/demos/game-settings/index.html`.
|
|
411
|
+
The example host toggles music during gameplay; the game uses a separate gain
|
|
412
|
+
node for background music so sound effects remain independent. This is a
|
|
413
|
+
local integration demo; the GameHub profile is the production preference editor.
|
|
414
|
+
|
|
415
|
+
## Multiplayer v2 (SDK 4.2)
|
|
416
|
+
|
|
417
|
+
Use `await sdk.ready()` before reading `sdk.getBootstrap().multiplayerLaunch`.
|
|
418
|
+
`requestMultiplayerLaunch()` requests only that already-bound launch from a
|
|
419
|
+
capable trusted host and accepts no room/game override. It returns reserved,
|
|
420
|
+
recoverable or terminal. The SDK owns no realtime connection or persistent token.
|
|
421
|
+
Use [@ksaa-nlp/gamehub-multiplayer](../gamehub-multiplayer/README.md) for socket,
|
|
422
|
+
state, clock and recovery lifecycle. The [Take Twenty-One starter](../../examples/take-twenty-one/README.md)
|
|
423
|
+
contains a complete authoring/build/upload example. V1 bootstrap is unchanged;
|
|
424
|
+
unsupported/native hosts do not advertise v2. Server-authoritative v2 rounds use
|
|
425
|
+
ctx.endMatch version 2 instead of browser submitScore/submitMatchResult.
|
package/SPEC.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# GameHub SDK — Specification
|
|
2
2
|
|
|
3
|
-
Version: 4.
|
|
3
|
+
Version: 4.2.0
|
|
4
4
|
Status: Authoritative. Supersedes README/MIGRATION/CHANGELOG where they conflict.
|
|
5
5
|
|
|
6
6
|
This document is the single source of truth for the GameHub SDK. Code, tests, and consumer docs follow this spec; if a behaviour is observed in code but not described here, treat it as undocumented and revisit before relying on it.
|
|
@@ -9,12 +9,13 @@ This document is the single source of truth for the GameHub SDK. Code, tests, an
|
|
|
9
9
|
|
|
10
10
|
## 1. Purpose
|
|
11
11
|
|
|
12
|
-
The GameHub SDK is the client library that GameHub-hosted games use to talk to the GameHub platform. It is a thin, transport-agnostic adapter providing
|
|
12
|
+
The GameHub SDK is the client library that GameHub-hosted games use to talk to the GameHub platform. It is a thin, transport-agnostic adapter providing five capabilities:
|
|
13
13
|
|
|
14
14
|
1. **Bootstrap pipeline.** A cross-origin `postMessage` handshake with the host page to discover the active game, the user's auth context, and (when applicable) a multiplayer reconnection token.
|
|
15
15
|
2. **Sessions and scoring.** HTTP wrappers that open a session token and submit scores, with auto-init of the session when a submit is the first call.
|
|
16
16
|
3. **Questions.** HTTP wrapper for the questions endpoint, used by quiz-style games.
|
|
17
17
|
4. **League-match HTTP.** Wrappers for the league-match context fetch and the match-result submit endpoint.
|
|
18
|
+
5. **Game settings.** Read account-wide preferences and subscribe to trusted host updates; games implement their own audio behavior.
|
|
18
19
|
|
|
19
20
|
The SDK is not coupled to any realtime transport. When the host attaches a multiplayer room, the SDK exposes the connection parameters verbatim and the game opens its own socket.
|
|
20
21
|
|
|
@@ -61,6 +62,7 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
|
|
|
61
62
|
| `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`, `getWords`. |
|
|
62
63
|
| `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
|
|
63
64
|
| `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
|
|
65
|
+
| `src/settings.ts` | Settings snapshots, validated merge and isolated subscriptions. |
|
|
64
66
|
| `src/state.ts` | `SdkState` interface + the singleton `state` object. All mutable state lives here. |
|
|
65
67
|
| `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`, `WORDS_LIMIT_CAP`. |
|
|
66
68
|
| `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
|
|
@@ -234,13 +236,42 @@ On the **native** transport there is no web origin: inbound `HostMessage.origin`
|
|
|
234
236
|
|
|
235
237
|
This lets the host clear fields explicitly (via `null`) without overwriting unset fields.
|
|
236
238
|
|
|
239
|
+
### 6.4a Account-wide game settings
|
|
240
|
+
|
|
241
|
+
`GameSettings` is `{ readonly musicEnabled: boolean }`. The effective default is
|
|
242
|
+
`false` for guests, standalone execution, old hosts, missing/invalid initial
|
|
243
|
+
preferences and legacy accounts. No setting enables sound implicitly.
|
|
244
|
+
|
|
245
|
+
`BootstrapConfig.settings` is optional. Omission preserves current settings;
|
|
246
|
+
explicit `null` resets music to false. A non-array object with a boolean
|
|
247
|
+
`musicEnabled` applies that value and strips unknown fields. Every other shape
|
|
248
|
+
is ignored. `BootstrapData.settings` always contains a detached snapshot.
|
|
249
|
+
Settings use the existing correlated `BOOTSTRAP` and subsequent unsolicited
|
|
250
|
+
`BOOTSTRAP` protocol, with exactly the existing parent/origin/native trust rules.
|
|
251
|
+
No new message type, storage or realtime transport is introduced.
|
|
252
|
+
|
|
253
|
+
`getSettings()` synchronously returns a detached snapshot. It does not wait for
|
|
254
|
+
initialization. `onSettingsChange(listener)` installs the ambient host listener,
|
|
255
|
+
registers a callback, immediately delivers a fresh snapshot, and returns an
|
|
256
|
+
idempotent unsubscribe function. Subscribing before `ready()` is supported.
|
|
257
|
+
Subsequent callbacks run synchronously only when the effective value changes.
|
|
258
|
+
Each registration is independent, including repeated registrations of the same
|
|
259
|
+
function. Listener exceptions cannot escape or prevent delivery to other
|
|
260
|
+
listeners; consumer mutation never changes SDK state. Callbacks are local and
|
|
261
|
+
emit no telemetry. `ready()` can still be awaited before reading settings.
|
|
262
|
+
|
|
263
|
+
Games must apply `false` to all current and future background music. `true`
|
|
264
|
+
permits music subject to their own mute and browser autoplay rules; it does not
|
|
265
|
+
force playback. Sound effects, speech and instructional audio are unaffected.
|
|
266
|
+
The SDK does not control HTML media, Web Audio, game engines or DOM elements.
|
|
267
|
+
|
|
237
268
|
### 6.5 Bootstrap lifecycle
|
|
238
269
|
|
|
239
270
|
1. **Idle.** `state.bootstrapReceived = false`.
|
|
240
271
|
2. **Request.** First call to `requestBootstrapFromParent()` posts `BOOTSTRAP_REQUEST` and starts the timeout.
|
|
241
272
|
3. **Response.** Host replies with `BOOTSTRAP` carrying the matching `messageId`. `state.bootstrapReceived = true`; the direct parent's non-opaque origin is pinned.
|
|
242
273
|
4. **Cache.** Subsequent calls return `snapshotBootstrap()` synchronously (wrapped in a resolved promise).
|
|
243
|
-
5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing callers do not get re-notified.
|
|
274
|
+
5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing bootstrap callers do not get re-notified; settings subscriptions are notified when the effective settings change.
|
|
244
275
|
|
|
245
276
|
A standalone (non-iframe) game has no parent; `requestBootstrapFromParent()` resolves `null` immediately, and `state.bootstrapReceived` stays `false`. `autoInit()` still runs the slug-only path.
|
|
246
277
|
|
|
@@ -492,7 +523,7 @@ Full field tables in `types/word.ts` and `specs/words-bank-feature.md` §3.
|
|
|
492
523
|
Mirrors `reportQuestion`: fires the `WORD_REPORT` postMessage with
|
|
493
524
|
`{ wordId?, lemma?, message?, words? }` for the host to render its
|
|
494
525
|
`ReportWordDialog`. No-ops outside the host iframe (the SDK never calls the
|
|
495
|
-
report endpoint itself). See §6.1.
|
|
526
|
+
report endpoint itself). The host requires login, using the same guest/expired-session login prompt as question reports. This is host/API behavior only; the SDK message contract and version are unchanged. See §6.1.
|
|
496
527
|
|
|
497
528
|
## 12. Host command channel
|
|
498
529
|
|
|
@@ -557,6 +588,10 @@ interface SdkState {
|
|
|
557
588
|
}
|
|
558
589
|
```
|
|
559
590
|
|
|
591
|
+
The singleton also owns `gameSettings` (initial `{ musicEnabled: false }`) and
|
|
592
|
+
`settingsListeners` (initial empty Set). Settings mutate only via the validated
|
|
593
|
+
bootstrap merge; subscriptions hold callbacks only in memory.
|
|
594
|
+
|
|
560
595
|
### 13.1 Invariants
|
|
561
596
|
|
|
562
597
|
- `apiBase` is set exactly once, by `detectEnvironment()`, before any HTTP request. It is never mutated afterwards.
|
|
@@ -621,13 +656,20 @@ interface SdkState {
|
|
|
621
656
|
| `logEvent(eventName, eventData?)` | `void` | `LOG_EVENT { event: eventName, data: eventData }` |
|
|
622
657
|
| `reportQuestion(data)` | `void` | `QUESTION_REPORT { questionId?, prompt?, message?, questions? }` |
|
|
623
658
|
|
|
624
|
-
`reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog. The host owns the dialog (the SDK renders no DOM — see §19.3) and submits the report, collecting the reason
|
|
659
|
+
`reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog. The host owns the dialog (the SDK renders no DOM — see §19.3) and submits the report, collecting the reason and an optional message for logged-in users. Guests receive a login prompt from the host; report endpoints require a verified account token. A host submission returning `401` also shows the login prompt. Like the other host signals it no-ops outside an iframe.
|
|
625
660
|
|
|
626
661
|
Two modes:
|
|
627
662
|
|
|
628
663
|
- **Single question** — pass `questionId` (and optionally `prompt`). The dialog reports that one question.
|
|
629
664
|
- **Pick from a list** — pass `questions: ReportableQuestion[]` (each `{ questionId, prompt? }`). The host renders a dropdown so the player chooses which question to report; `questionId`, when also supplied, pre-selects an entry. The `questions` array is forwarded verbatim (each entry normalised to `{ questionId, prompt }`) on the `QUESTION_REPORT` envelope.
|
|
630
665
|
|
|
666
|
+
### 14.7a Game settings
|
|
667
|
+
|
|
668
|
+
| Method | Returns | Notes |
|
|
669
|
+
| --- | --- | --- |
|
|
670
|
+
| `getSettings()` | `GameSettings` | Detached effective snapshot; default music off. |
|
|
671
|
+
| `onSettingsChange(listener)` | `() => void` | Immediate snapshot, then changes; unsubscribe on game teardown. |
|
|
672
|
+
|
|
631
673
|
### 14.7 Read-only context
|
|
632
674
|
|
|
633
675
|
| Method | Returns | Notes |
|
|
@@ -661,7 +703,12 @@ interface BootstrapMultiplayer {
|
|
|
661
703
|
connectionScope?: string;
|
|
662
704
|
}
|
|
663
705
|
|
|
706
|
+
interface GameSettings {
|
|
707
|
+
readonly musicEnabled: boolean;
|
|
708
|
+
}
|
|
709
|
+
|
|
664
710
|
interface BootstrapConfig {
|
|
711
|
+
settings?: GameSettings | null;
|
|
665
712
|
gameSlug?: string | null;
|
|
666
713
|
authToken?: string | null;
|
|
667
714
|
leagueId?: string | null;
|
|
@@ -678,6 +725,7 @@ interface BootstrapConfig {
|
|
|
678
725
|
}
|
|
679
726
|
|
|
680
727
|
interface BootstrapData {
|
|
728
|
+
settings: GameSettings;
|
|
681
729
|
gameSlug: string | null;
|
|
682
730
|
authToken: string | null;
|
|
683
731
|
leagueId: string | null;
|
|
@@ -924,7 +972,7 @@ These rules exist because of a real prior regression where transport-related cle
|
|
|
924
972
|
|
|
925
973
|
### 20.3 Bundle budget
|
|
926
974
|
|
|
927
|
-
The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **
|
|
975
|
+
The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **44 KiB raw** and **10 KiB gzip**, the latter being the figure that matters most on the wire. The raw budget was historically 25 KB; native transport and the reliable multi-round lifecycle deliberately exceed that historical target. SDK 4.2.0 combines account music settings and multiplayer v2: **43,567 bytes raw / 9,804 bytes gzip**. The merged features deliberately raise the raw limit from 42 KiB to 44 KiB while retaining the 10 KiB gzip limit. Further growth requires a deliberate release review.
|
|
928
976
|
|
|
929
977
|
### 20.4 No runtime dependencies
|
|
930
978
|
|
|
@@ -1016,6 +1064,13 @@ or capability. Their existing Usage Intelligence feature IDs and accepted-only
|
|
|
1016
1064
|
server-operation observation remain authoritative; no scanner/report inventory
|
|
1017
1065
|
version change is required for this release.
|
|
1018
1066
|
|
|
1067
|
+
Version 4.1.0 adds `getSettings` and `onSettingsChange`, both static-only in the
|
|
1068
|
+
Usage Intelligence Report: a host delivering preferences proves neither their
|
|
1069
|
+
consumption nor audio compliance. Scanner version 2, admin Arabic labels,
|
|
1070
|
+
filters/CSV and fixtures are synchronized. Runtime aggregation excludes these
|
|
1071
|
+
local APIs. The example in `demos/game-settings/` is a reference game and
|
|
1072
|
+
host for manual testing of global/local mute and live preference updates.
|
|
1073
|
+
|
|
1019
1074
|
## 21bis. UGC server bundle subpath
|
|
1020
1075
|
|
|
1021
1076
|
The `./server` and `./server/dev` subpaths are separate from the browser SDK. Importing them has **no overlap** with the iframe runtime — they target the colyseus UGC sandbox, not the browser host.
|
|
@@ -1083,3 +1138,37 @@ expect(room.outbox).toContainEqual({
|
|
|
1083
1138
|
- **Host.** The GameHub-served page that frames the game in an iframe. Owns auth, matchmaking, and the bootstrap pipeline.
|
|
1084
1139
|
- **Game.** The iframe-hosted application that consumes this SDK.
|
|
1085
1140
|
- **Standalone.** A game loaded outside an iframe. `isInIframe()` returns false; the bootstrap pipeline is skipped.
|
|
1141
|
+
|
|
1142
|
+
## Launch v2 (4.2.0)
|
|
1143
|
+
|
|
1144
|
+
The authoritative cross-package contract is [multiplayer v2](../../specs/multiplayer.md).
|
|
1145
|
+
Optional bootstrap `capabilities` and `multiplayerLaunch` are separate from the
|
|
1146
|
+
unchanged required v1 `multiplayer.reservation` shape. `requestMultiplayerLaunch()`
|
|
1147
|
+
is a no-argument, single-flight request to the trusted host for its already-bound
|
|
1148
|
+
round. It validates bounded replies and fences a changed launch context. It owns
|
|
1149
|
+
no socket or persistent storage. Old/native hosts do not advertise v2 and return
|
|
1150
|
+
`PROTOCOL_UNSUPPORTED`; no fallback room is chosen.
|
|
1151
|
+
|
|
1152
|
+
`ready()` completes bootstrap before a module consumer reads its launch. V2
|
|
1153
|
+
bootstrap suppresses unrelated client-scored session creation; the host permits
|
|
1154
|
+
only the bound launch request and the backend rejects browser ownership of
|
|
1155
|
+
server-multiplayer PlayerSessions. Solo and legacy HTTP methods retain their
|
|
1156
|
+
existing semantics. The separate `@ksaa-nlp/gamehub-multiplayer` package owns
|
|
1157
|
+
Colyseus state, clock and recovery tokens.
|
|
1158
|
+
|
|
1159
|
+
Server `EndMatchPayload` adds optional version 2, per-seat scores, winner seat IDs
|
|
1160
|
+
and bounded metadata. The v2 room requires the v2 result shape and enriches it
|
|
1161
|
+
with trusted provenance. `ctx.endMatch` is a proposal, not a saved acknowledgement.
|
|
1162
|
+
Legacy endMatch payloads remain valid in legacy rooms.
|
|
1163
|
+
|
|
1164
|
+
SDK_VERSION, npm version and served JS/map are 4.2.0. The distribution gate is
|
|
1165
|
+
44 KiB raw / 10 KiB gzip (the raw increase covers v2 validation and game settings); runtime
|
|
1166
|
+
dependencies remain empty. Scanner version 3 includes requestMultiplayerLaunch,
|
|
1167
|
+
endMatch, seededPlayers and the static-only game-settings APIs; version-2 scans
|
|
1168
|
+
are stale after rebasing onto the game-settings release. A launch request
|
|
1169
|
+
observation is not successful admission; see the
|
|
1170
|
+
[usage report](../../specs/sdk-usage-report.md).
|
|
1171
|
+
|
|
1172
|
+
## Seeded participants (4.2.0)
|
|
1173
|
+
|
|
1174
|
+
`SeededPlayer` adds optional `kind: human|bot`, `seatId` and `peerId`. Missing kind means human for legacy hosts. V2 always supplies these fields; userId/seatId/peerId are the same opaque stable seat ID, never a bot/account credential. Bots do not connect or receive `onJoin`; the UGC bundle owns their legal moves using normal state/rules and `ctx.setTimeout`. All roster players, including bots, belong in endMatch scores. No realtime dependency is introduced. SDK Usage scanner 3 represents the widened data capability as `seededPlayers`: static identifiers are possible evidence; a trusted first UGC round-start acknowledgement confirms roster delivery. It does not prove a game consumed the field or that its bot algorithm acted. See the report specification.
|
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 = "4.
|
|
4
|
+
var SDK_VERSION = "4.2.0";
|
|
5
5
|
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
6
|
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
7
|
var HOST_API_TIMEOUT_MS = 15e3;
|
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
|
|
11
11
|
// src/state.ts
|
|
12
12
|
var state = {
|
|
13
|
+
gameSettings: { musicEnabled: false },
|
|
14
|
+
settingsListeners: /* @__PURE__ */ new Set(),
|
|
15
|
+
bootstrapLaunch: null,
|
|
16
|
+
bootstrapCapabilities: [],
|
|
13
17
|
sdkOrigin: "",
|
|
14
18
|
sdkPathPrefix: "",
|
|
15
19
|
runtimeBasePath: "",
|
|
@@ -41,6 +45,43 @@
|
|
|
41
45
|
matchContextPromise: null
|
|
42
46
|
};
|
|
43
47
|
|
|
48
|
+
// src/settings.ts
|
|
49
|
+
function getSettings() {
|
|
50
|
+
return { ...state.gameSettings };
|
|
51
|
+
}
|
|
52
|
+
function notify(listener) {
|
|
53
|
+
try {
|
|
54
|
+
listener(getSettings());
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function onSettingsChange(listener) {
|
|
59
|
+
if (typeof listener !== "function") return () => {
|
|
60
|
+
};
|
|
61
|
+
const subscription = (settings) => listener(settings);
|
|
62
|
+
state.settingsListeners.add(subscription);
|
|
63
|
+
notify(subscription);
|
|
64
|
+
return () => {
|
|
65
|
+
state.settingsListeners.delete(subscription);
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function mergeSettings(value) {
|
|
69
|
+
if (value === void 0) return;
|
|
70
|
+
let musicEnabled;
|
|
71
|
+
if (value === null) {
|
|
72
|
+
musicEnabled = false;
|
|
73
|
+
} else if (typeof value === "object" && !Array.isArray(value) && typeof value.musicEnabled === "boolean") {
|
|
74
|
+
musicEnabled = value.musicEnabled;
|
|
75
|
+
} else {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (musicEnabled === state.gameSettings.musicEnabled) return;
|
|
79
|
+
state.gameSettings = { musicEnabled };
|
|
80
|
+
for (const listener of [...state.settingsListeners]) {
|
|
81
|
+
if (state.settingsListeners.has(listener)) notify(listener);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
44
85
|
// src/utils.ts
|
|
45
86
|
function isBrowser() {
|
|
46
87
|
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
@@ -208,7 +249,8 @@
|
|
|
208
249
|
};
|
|
209
250
|
}
|
|
210
251
|
function mergeBootstrapConfig(config = {}) {
|
|
211
|
-
if (!config || typeof config !== "object") return;
|
|
252
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) return;
|
|
253
|
+
mergeSettings(config.settings);
|
|
212
254
|
const apply = (key, raw) => {
|
|
213
255
|
const next = trimToNullable(raw);
|
|
214
256
|
if (next === void 0) return;
|
|
@@ -235,6 +277,20 @@
|
|
|
235
277
|
applyBootstrap("bootstrapTeamOneName", config.teamOneName);
|
|
236
278
|
applyBootstrap("bootstrapTeamTwoName", config.teamTwoName);
|
|
237
279
|
applyBootstrap("bootstrapProfileId", config.profileId);
|
|
280
|
+
if (Array.isArray(config.capabilities))
|
|
281
|
+
state.bootstrapCapabilities = config.capabilities.filter((c) => typeof c === "string" && c.length <= 100).slice(0, 32);
|
|
282
|
+
const launch = config.multiplayerLaunch;
|
|
283
|
+
if (launch === null) state.bootstrapLaunch = null;
|
|
284
|
+
else if (launch && launch.version === 2 && (launch.recoveryGraceMs === void 0 || Number.isSafeInteger(launch.recoveryGraceMs) && launch.recoveryGraceMs >= 1e3 && launch.recoveryGraceMs <= 12e4) && [
|
|
285
|
+
"multiplayerSessionId",
|
|
286
|
+
"roundId",
|
|
287
|
+
"attemptId",
|
|
288
|
+
"seatId",
|
|
289
|
+
"hostInstanceId"
|
|
290
|
+
].every(
|
|
291
|
+
(k) => typeof launch[k] === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(String(launch[k]))
|
|
292
|
+
) && typeof launch.gameUrl === "string" && launch.gameUrl.startsWith("/games/") && launch.gameUrl.length < 2048 && ["server", "unverified"].includes(launch.scoreAuthority))
|
|
293
|
+
state.bootstrapLaunch = { ...launch };
|
|
238
294
|
const mp = parseMultiplayer(config.multiplayer);
|
|
239
295
|
if (mp !== void 0) {
|
|
240
296
|
state.bootstrapMultiplayer = mp;
|
|
@@ -242,6 +298,7 @@
|
|
|
242
298
|
}
|
|
243
299
|
function snapshotBootstrap() {
|
|
244
300
|
return {
|
|
301
|
+
settings: getSettings(),
|
|
245
302
|
gameSlug: state.gameSlug,
|
|
246
303
|
authToken: state.authToken,
|
|
247
304
|
leagueId: state.leagueId,
|
|
@@ -254,7 +311,9 @@
|
|
|
254
311
|
teamOneName: state.bootstrapTeamOneName,
|
|
255
312
|
teamTwoName: state.bootstrapTeamTwoName,
|
|
256
313
|
profileId: state.bootstrapProfileId,
|
|
257
|
-
multiplayer: state.bootstrapMultiplayer
|
|
314
|
+
multiplayer: state.bootstrapMultiplayer,
|
|
315
|
+
multiplayerLaunch: state.bootstrapLaunch,
|
|
316
|
+
capabilities: state.bootstrapCapabilities
|
|
258
317
|
};
|
|
259
318
|
}
|
|
260
319
|
function requestBootstrapFromParent() {
|
|
@@ -594,6 +653,8 @@
|
|
|
594
653
|
}
|
|
595
654
|
}
|
|
596
655
|
async function startSession() {
|
|
656
|
+
if (state.bootstrapLaunch)
|
|
657
|
+
return { success: false, error: "Multiplayer rounds own their results" };
|
|
597
658
|
if (state.sessionToken) return { success: true, token: state.sessionToken };
|
|
598
659
|
if (state.sessionStartPromise) return await state.sessionStartPromise;
|
|
599
660
|
const promise = performStartSession();
|
|
@@ -654,14 +715,14 @@
|
|
|
654
715
|
}
|
|
655
716
|
return failedResult(code, message, code === "SERVER_ERROR");
|
|
656
717
|
}
|
|
657
|
-
async function performSubmission(
|
|
718
|
+
async function performSubmission(pending2) {
|
|
658
719
|
let outcome;
|
|
659
720
|
try {
|
|
660
721
|
const response = await apiRequest("/sessions/submit", {
|
|
661
722
|
method: "POST",
|
|
662
|
-
body:
|
|
723
|
+
body: pending2.body
|
|
663
724
|
});
|
|
664
|
-
outcome = normalizeSubmissionResult(response,
|
|
725
|
+
outcome = normalizeSubmissionResult(response, pending2.token);
|
|
665
726
|
} catch (err) {
|
|
666
727
|
outcome = failedResult(
|
|
667
728
|
"TRANSPORT_ERROR",
|
|
@@ -671,7 +732,7 @@
|
|
|
671
732
|
}
|
|
672
733
|
if (outcome.success) {
|
|
673
734
|
sendToParent("SCORE_SUBMITTED", {
|
|
674
|
-
score:
|
|
735
|
+
score: pending2.body.score,
|
|
675
736
|
sessionId: outcome.sessionId,
|
|
676
737
|
status: outcome.status,
|
|
677
738
|
terminal: outcome.terminal,
|
|
@@ -717,8 +778,8 @@
|
|
|
717
778
|
}
|
|
718
779
|
const prepared = prepareSubmission(state.sessionToken, score, meta);
|
|
719
780
|
if (!prepared.ok) return prepared.result;
|
|
720
|
-
const
|
|
721
|
-
if (
|
|
781
|
+
const pending2 = state.pendingSubmission;
|
|
782
|
+
if (pending2 && (pending2.token !== state.sessionToken || pending2.canonicalPayload !== prepared.canonicalPayload)) {
|
|
722
783
|
return failedResult(
|
|
723
784
|
"CONCURRENT_SUBMISSION_CONFLICT",
|
|
724
785
|
"A different payload is already bound to the active session",
|
|
@@ -726,7 +787,7 @@
|
|
|
726
787
|
);
|
|
727
788
|
}
|
|
728
789
|
if (state.submissionPromise) return await state.submissionPromise;
|
|
729
|
-
const activePending =
|
|
790
|
+
const activePending = pending2 ?? {
|
|
730
791
|
token: state.sessionToken,
|
|
731
792
|
canonicalPayload: prepared.canonicalPayload,
|
|
732
793
|
body: prepared.body
|
|
@@ -907,7 +968,7 @@
|
|
|
907
968
|
state.isAutoInitializing = false;
|
|
908
969
|
return false;
|
|
909
970
|
}
|
|
910
|
-
if (!state.authToken) {
|
|
971
|
+
if (!state.authToken && !state.bootstrapLaunch) {
|
|
911
972
|
state.authToken = await getAuthTokenFromParent();
|
|
912
973
|
}
|
|
913
974
|
state.isInitialized = true;
|
|
@@ -968,6 +1029,79 @@
|
|
|
968
1029
|
});
|
|
969
1030
|
}
|
|
970
1031
|
|
|
1032
|
+
// src/multiplayer.ts
|
|
1033
|
+
var pending = null;
|
|
1034
|
+
function requestMultiplayerLaunch() {
|
|
1035
|
+
if (!state.bootstrapLaunch || !state.bootstrapCapabilities.includes("multiplayer.launch.v2"))
|
|
1036
|
+
return Promise.resolve({
|
|
1037
|
+
status: "terminal",
|
|
1038
|
+
error: {
|
|
1039
|
+
code: "PROTOCOL_UNSUPPORTED",
|
|
1040
|
+
message: "This host does not support multiplayer launch v2",
|
|
1041
|
+
retryable: false
|
|
1042
|
+
}
|
|
1043
|
+
});
|
|
1044
|
+
if (pending) return pending;
|
|
1045
|
+
const launch = state.bootstrapLaunch;
|
|
1046
|
+
const operation = (async () => {
|
|
1047
|
+
try {
|
|
1048
|
+
const response = await requestApiFromParent("/multiplayer/launch", {
|
|
1049
|
+
method: "POST",
|
|
1050
|
+
body: {}
|
|
1051
|
+
});
|
|
1052
|
+
if (state.bootstrapLaunch !== launch)
|
|
1053
|
+
return {
|
|
1054
|
+
status: "terminal",
|
|
1055
|
+
error: {
|
|
1056
|
+
code: "STALE_ATTEMPT",
|
|
1057
|
+
message: "Launch context changed",
|
|
1058
|
+
retryable: false
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
const data = response.data;
|
|
1062
|
+
if (response.success && data) {
|
|
1063
|
+
if (data.status === "reserved" && data.launch && [
|
|
1064
|
+
"multiplayerSessionId",
|
|
1065
|
+
"roundId",
|
|
1066
|
+
"attemptId",
|
|
1067
|
+
"seatId",
|
|
1068
|
+
"hostInstanceId"
|
|
1069
|
+
].every(
|
|
1070
|
+
(k) => data.launch[k] === launch[k]
|
|
1071
|
+
) && data.reservation && ["name", "roomId", "sessionId"].every(
|
|
1072
|
+
(k) => typeof data.reservation[k] === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(
|
|
1073
|
+
String(data.reservation[k])
|
|
1074
|
+
)
|
|
1075
|
+
) && /^wss?:\/\//.test(data.wsEndpoint) && data.wsEndpoint.length < 2048 && Number.isSafeInteger(data.generation) && data.generation > 0 && Number.isSafeInteger(data.expiresAt))
|
|
1076
|
+
return data;
|
|
1077
|
+
if ((data.status === "recoverable" || data.status === "terminal") && data.error && typeof data.error.code === "string" && data.error.code.length <= 100 && typeof data.error.message === "string" && data.error.message.length <= 1e3 && typeof data.error.retryable === "boolean")
|
|
1078
|
+
return data;
|
|
1079
|
+
}
|
|
1080
|
+
return {
|
|
1081
|
+
status: "recoverable",
|
|
1082
|
+
error: {
|
|
1083
|
+
code: response.error?.code ?? "UNAVAILABLE",
|
|
1084
|
+
message: response.error?.message ?? "Launch unavailable",
|
|
1085
|
+
retryable: true
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
} catch {
|
|
1089
|
+
return {
|
|
1090
|
+
status: "recoverable",
|
|
1091
|
+
error: {
|
|
1092
|
+
code: "UNAVAILABLE",
|
|
1093
|
+
message: "Launch request failed; retry",
|
|
1094
|
+
retryable: true
|
|
1095
|
+
}
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
})().finally(() => {
|
|
1099
|
+
if (pending === operation) pending = null;
|
|
1100
|
+
});
|
|
1101
|
+
pending = operation;
|
|
1102
|
+
return operation;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
971
1105
|
// src/match-context.ts
|
|
972
1106
|
async function fetchMatchContext() {
|
|
973
1107
|
if (!state.leagueId || !state.matchId) return null;
|
|
@@ -1002,6 +1136,7 @@
|
|
|
1002
1136
|
hasActiveSession() {
|
|
1003
1137
|
return !!state.sessionToken;
|
|
1004
1138
|
},
|
|
1139
|
+
requestMultiplayerLaunch,
|
|
1005
1140
|
async startSession() {
|
|
1006
1141
|
await ensureInitialized();
|
|
1007
1142
|
if (state.sessionStartPromise) return await state.sessionStartPromise;
|
|
@@ -1063,8 +1198,14 @@
|
|
|
1063
1198
|
async ready() {
|
|
1064
1199
|
return await ensureInitialized();
|
|
1065
1200
|
},
|
|
1201
|
+
getSettings,
|
|
1202
|
+
onSettingsChange(listener) {
|
|
1203
|
+
installHostMessageListener();
|
|
1204
|
+
return onSettingsChange(listener);
|
|
1205
|
+
},
|
|
1066
1206
|
getBootstrap() {
|
|
1067
1207
|
return {
|
|
1208
|
+
settings: getSettings(),
|
|
1068
1209
|
gameSlug: state.gameSlug,
|
|
1069
1210
|
authToken: state.authToken,
|
|
1070
1211
|
leagueId: state.leagueId,
|
|
@@ -1078,6 +1219,8 @@
|
|
|
1078
1219
|
teamTwoName: state.bootstrapTeamTwoName,
|
|
1079
1220
|
profileId: state.bootstrapProfileId,
|
|
1080
1221
|
multiplayer: state.bootstrapMultiplayer,
|
|
1222
|
+
multiplayerLaunch: state.bootstrapLaunch,
|
|
1223
|
+
capabilities: [...state.bootstrapCapabilities],
|
|
1081
1224
|
isBootstrapped: state.bootstrapReceived
|
|
1082
1225
|
};
|
|
1083
1226
|
},
|