@diffenderfer-games/hub 0.0.0-stage → 2.0.0-next.1

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.
Files changed (164) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +191 -3
  4. package/dist/auto.d.ts +36 -0
  5. package/dist/auto.d.ts.map +1 -0
  6. package/dist/auto.js +27 -0
  7. package/dist/auto.js.map +1 -0
  8. package/dist/daily.d.ts +2 -0
  9. package/dist/daily.js +1 -0
  10. package/dist/doctor/cli.mjs +268 -0
  11. package/dist/doctor/cli.mjs.map +1 -0
  12. package/dist/index.d.ts +12 -0
  13. package/dist/index.js +6 -0
  14. package/dist/input.d.ts +2 -0
  15. package/dist/input.js +3 -0
  16. package/dist/mp.d.ts +4 -0
  17. package/dist/mp.js +1 -0
  18. package/dist/race.d.ts +4 -0
  19. package/dist/race.js +1 -0
  20. package/dist/rooms.d.ts +4 -0
  21. package/dist/rooms.js +1 -0
  22. package/dist/shared/bridge.js +209 -0
  23. package/dist/shared/bridge.js.map +1 -0
  24. package/dist/shared/client-version.gen.js +7 -0
  25. package/dist/shared/client-version.gen.js.map +1 -0
  26. package/dist/shared/daily.d.ts +123 -0
  27. package/dist/shared/daily.d.ts.map +1 -0
  28. package/dist/shared/daily.js +191 -0
  29. package/dist/shared/daily.js.map +1 -0
  30. package/dist/shared/dom.js +48 -0
  31. package/dist/shared/dom.js.map +1 -0
  32. package/dist/shared/globals.js +102 -0
  33. package/dist/shared/globals.js.map +1 -0
  34. package/dist/shared/index.d.ts +706 -0
  35. package/dist/shared/index.d.ts.map +1 -0
  36. package/dist/shared/input.d.ts +730 -0
  37. package/dist/shared/input.d.ts.map +1 -0
  38. package/dist/shared/input.js +2718 -0
  39. package/dist/shared/input.js.map +1 -0
  40. package/dist/shared/latest-state.js +17 -0
  41. package/dist/shared/latest-state.js.map +1 -0
  42. package/dist/shared/mp.d.ts +9 -0
  43. package/dist/shared/mp.d.ts.map +1 -0
  44. package/dist/shared/mp.js +30 -0
  45. package/dist/shared/mp.js.map +1 -0
  46. package/dist/shared/multiplayer-types.d.ts +47 -0
  47. package/dist/shared/multiplayer-types.d.ts.map +1 -0
  48. package/dist/shared/page-stack.js +207 -0
  49. package/dist/shared/page-stack.js.map +1 -0
  50. package/dist/shared/race-types.d.ts +126 -0
  51. package/dist/shared/race-types.d.ts.map +1 -0
  52. package/dist/shared/race.d.ts +9 -0
  53. package/dist/shared/race.d.ts.map +1 -0
  54. package/dist/shared/race.js +53 -0
  55. package/dist/shared/race.js.map +1 -0
  56. package/dist/shared/room-types.d.ts +125 -0
  57. package/dist/shared/room-types.d.ts.map +1 -0
  58. package/dist/shared/rooms.d.ts +9 -0
  59. package/dist/shared/rooms.d.ts.map +1 -0
  60. package/dist/shared/rooms.js +62 -0
  61. package/dist/shared/rooms.js.map +1 -0
  62. package/dist/shared/runtime-opener.js +84 -0
  63. package/dist/shared/runtime-opener.js.map +1 -0
  64. package/dist/shared/social.d.ts +148 -0
  65. package/dist/shared/social.d.ts.map +1 -0
  66. package/dist/shared/social.js +73 -0
  67. package/dist/shared/social.js.map +1 -0
  68. package/dist/shared/src.js +2164 -0
  69. package/dist/shared/src.js.map +1 -0
  70. package/dist/shared/wire-types.d.ts +51 -0
  71. package/dist/shared/wire-types.d.ts.map +1 -0
  72. package/dist/social.d.ts +6 -0
  73. package/dist/social.js +3 -0
  74. package/dist/types.d.ts +1 -0
  75. package/dist/types.js +0 -0
  76. package/package.json +89 -6
  77. package/src/auto.ts +39 -0
  78. package/src/core/connection.ts +299 -0
  79. package/src/core/errors.ts +147 -0
  80. package/src/core/game-data.ts +38 -0
  81. package/src/core/hub-economy.ts +179 -0
  82. package/src/core/hub-progress.ts +205 -0
  83. package/src/core/hub.ts +131 -0
  84. package/src/core/menu-control.ts +61 -0
  85. package/src/core/offline/events.ts +50 -0
  86. package/src/core/offline/favorites.ts +21 -0
  87. package/src/core/offline/local-store.ts +261 -0
  88. package/src/core/offline/queue.ts +171 -0
  89. package/src/core/page.ts +74 -0
  90. package/src/core/rest/endpoint-types.ts +22 -0
  91. package/src/core/rest/rest-client.ts +152 -0
  92. package/src/core/rest/routes.gen.ts +90 -0
  93. package/src/core/storage/json-guards.ts +74 -0
  94. package/src/core/storage/key-value.ts +66 -0
  95. package/src/core/ticket.ts +43 -0
  96. package/src/core/types.ts +134 -0
  97. package/src/core/version/client-version.gen.ts +3 -0
  98. package/src/core/version/hub-version.ts +62 -0
  99. package/src/core/version/semver.ts +97 -0
  100. package/src/daily/daily-system.ts +161 -0
  101. package/src/daily/page-daily.ts +36 -0
  102. package/src/daily/types.ts +67 -0
  103. package/src/daily.ts +10 -0
  104. package/src/doctor/checks.ts +78 -0
  105. package/src/doctor/cli.ts +98 -0
  106. package/src/doctor/hub-version-fetch.ts +43 -0
  107. package/src/doctor/tsconfig.json +12 -0
  108. package/src/globals.ts +115 -0
  109. package/src/index.ts +50 -0
  110. package/src/input/device-state.ts +146 -0
  111. package/src/input/edges.ts +55 -0
  112. package/src/input/gamepad.ts +61 -0
  113. package/src/input/input-events.ts +32 -0
  114. package/src/input/input-registry.ts +164 -0
  115. package/src/input/input-system.ts +393 -0
  116. package/src/input/legacy-controls.ts +64 -0
  117. package/src/input/nav-state.ts +191 -0
  118. package/src/input/navigator.ts +171 -0
  119. package/src/input/on-screen-controls.ts +101 -0
  120. package/src/input/page-control.ts +43 -0
  121. package/src/input/page-input.ts +193 -0
  122. package/src/input/player-remaps.ts +77 -0
  123. package/src/input/source-values.ts +116 -0
  124. package/src/input/spatial.ts +47 -0
  125. package/src/input/types.ts +331 -0
  126. package/src/input/zero-config.ts +177 -0
  127. package/src/input.ts +22 -0
  128. package/src/mp.ts +10 -0
  129. package/src/overlay/controls-panel.ts +163 -0
  130. package/src/overlay/dom.ts +46 -0
  131. package/src/overlay/layout-clusters.ts +162 -0
  132. package/src/overlay/layout-geometry.ts +136 -0
  133. package/src/overlay/layout.ts +203 -0
  134. package/src/overlay/listener-scope.ts +23 -0
  135. package/src/overlay/on-screen-keyboard.ts +137 -0
  136. package/src/overlay/overlay.ts +208 -0
  137. package/src/overlay/styles.ts +54 -0
  138. package/src/overlay/virtual-controls.ts +262 -0
  139. package/src/race.ts +10 -0
  140. package/src/realtime/bridge.ts +121 -0
  141. package/src/realtime/cross-bundle.ts +29 -0
  142. package/src/realtime/fallback-notice.ts +48 -0
  143. package/src/realtime/hub-link.ts +65 -0
  144. package/src/realtime/latest-state.ts +33 -0
  145. package/src/realtime/multiplayer-forwarder.ts +28 -0
  146. package/src/realtime/multiplayer-types.ts +52 -0
  147. package/src/realtime/page-runtime.ts +60 -0
  148. package/src/realtime/race-forwarder.ts +59 -0
  149. package/src/realtime/race-types.ts +132 -0
  150. package/src/realtime/room-types.ts +125 -0
  151. package/src/realtime/rooms-forwarder.ts +79 -0
  152. package/src/realtime/runtime-api.ts +49 -0
  153. package/src/realtime/runtime-opener.ts +61 -0
  154. package/src/realtime/social-forwarder.ts +72 -0
  155. package/src/realtime/social-types.ts +78 -0
  156. package/src/realtime/types.ts +53 -0
  157. package/src/realtime/wire-types.ts +72 -0
  158. package/src/rooms.ts +10 -0
  159. package/src/social.ts +18 -0
  160. package/src/types.ts +13 -0
  161. package/src/uistack/page-stack.ts +45 -0
  162. package/src/uistack/play-suspension.ts +82 -0
  163. package/src/uistack/types.ts +76 -0
  164. package/src/uistack/ui-stack.ts +144 -0
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The `Hub` client: every REST method (in `hub-progress.ts` and
3
+ * `hub-economy.ts`), the hub's version, and the page-wide namespaces as lazy
4
+ * getters (`hub.input`, `hub.daily`, `hub.social`, `hub.mp`, `hub.rooms`,
5
+ * `hub.race`, ...), so v1 code such as `hub.input.define(...)` works unchanged.
6
+ */
7
+ import type { HubVersion } from '@diffenderfer-games/hub-contract';
8
+ import { getDaily, type DailyHost, type DailySystem } from '../daily';
9
+ import { getInput, getUiStack, type InputSystem } from '../input';
10
+ import { mp } from '../mp';
11
+ import { race } from '../race';
12
+ import { rooms } from '../rooms';
13
+ import { linkRealtimeToHub, notify, presence, social } from '../social';
14
+ import { OfflineError, toHubError } from './errors';
15
+ import { HubEconomy } from './hub-economy';
16
+ import { hubMenu, type HubMenuControl } from './menu-control';
17
+ import { emitWindowEvent } from './page';
18
+ import { fetchGameServerTicket } from './ticket';
19
+ import { clientSupport, readHubVersion, type ClientSupport } from './version/hub-version';
20
+ import { HUB_CLIENT_VERSION } from './version/client-version.gen';
21
+ import type { HubOptions } from './types';
22
+
23
+ /** The hub client. Use the ready-made {@link hub}, or `createHub()` for another slug or API base. */
24
+ export class Hub extends HubEconomy {
25
+ /** This client's package version (sent as `x-hub-client`). */
26
+ readonly clientVersion: string = HUB_CLIENT_VERSION;
27
+
28
+ /**
29
+ * The hub's version and the client versions it supports (`GET /_api/version`),
30
+ * read once per page. `null` for a hub from before versioning.
31
+ */
32
+ hubVersion(): Promise<HubVersion | null> {
33
+ return readHubVersion(this.rest);
34
+ }
35
+
36
+ /** How the hub regards this client: `supported`, `deprecated`, `unsupported`, or `unknown` (an older hub). */
37
+ async clientSupport(): Promise<ClientSupport> {
38
+ return clientSupport(await this.hubVersion());
39
+ }
40
+
41
+ /**
42
+ * The input system (keyboard, touch and gamepad): `hub.input.define({ ... })`,
43
+ * `hub.input.value('jump')`. Page-wide; remaps are saved locally and to the
44
+ * reserved `__controls` save slot.
45
+ */
46
+ get input(): InputSystem {
47
+ return getInput({
48
+ slug: this.slug,
49
+ saveToCloud: (overrides) => {
50
+ void this.putSave('__controls', overrides).catch(() => undefined);
51
+ },
52
+ });
53
+ }
54
+
55
+ /** Hub UI covering the game (menu, dialogs, chat): open/close events and `autoPause`. Page-wide. */
56
+ get overlay(): ReturnType<typeof getUiStack> {
57
+ return getUiStack();
58
+ }
59
+
60
+ /** Show or hide the injected hub menu button (page-wide). */
61
+ get menu(): HubMenuControl {
62
+ return hubMenu;
63
+ }
64
+
65
+ /**
66
+ * Daily challenges: call `hub.daily.define({ play })` once at load and
67
+ * `hub.daily.complete({ ... })` on finish. Page-wide, shared with the
68
+ * injected menu, which can start a clicked day on the same instance.
69
+ */
70
+ get daily(): DailySystem {
71
+ return getDaily(this.dailyHost());
72
+ }
73
+
74
+ /** Tell friends what the player is doing in this game. */
75
+ get presence(): typeof presence {
76
+ return presence;
77
+ }
78
+
79
+ /** Friends, players and the hub's social dialogs. */
80
+ get social(): typeof social {
81
+ return social;
82
+ }
83
+
84
+ /** Invites, launches, the leave guard and own-server tickets. */
85
+ get mp(): typeof mp {
86
+ return mp;
87
+ }
88
+
89
+ /** Hub relay rooms, for games without a server. */
90
+ get rooms(): typeof rooms {
91
+ return rooms;
92
+ }
93
+
94
+ /** Toast behaviour during intense play. */
95
+ get notify(): typeof notify {
96
+ return notify;
97
+ }
98
+
99
+ /** Races: a single-player game becomes multiplayer by racing. */
100
+ get race(): typeof race {
101
+ return race;
102
+ }
103
+
104
+ /** What the daily system needs from this client: its REST calls and window events. */
105
+ private dailyHost(): DailyHost {
106
+ return {
107
+ slug: this.slug,
108
+ status: () => this.rest.call('getGameDailyChallenges', this.gameFields()),
109
+ all: () => this.rest.call('listDailyChallengesForAllGames'),
110
+ start: (day) => this.rest.call('startDailyChallenge', { ...this.gameFields(), day }),
111
+ complete: (day, token, meta) => this.rest.call('completeDailyChallenge', { ...this.gameFields(), day, token, meta }),
112
+ emit: (eventName, detail) => {
113
+ emitWindowEvent(eventName, detail);
114
+ },
115
+ };
116
+ }
117
+ }
118
+
119
+ linkRealtimeToHub({
120
+ toHubError,
121
+ createOfflineError: (message) => new OfflineError(message),
122
+ getGameServerTicket: fetchGameServerTicket,
123
+ });
124
+
125
+ /** A ready-to-use client, with the slug and API base detected from the page. */
126
+ export const hub: Hub = new Hub();
127
+
128
+ /** Create a client for another slug or API base, or with other offline behaviour. */
129
+ export function createHub(options: HubOptions = {}): Hub {
130
+ return new Hub(options);
131
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `hub.menu`: show or hide the injected hub menu button. The menu
3
+ * (`/_hub/menu.js`) may load before or after the game, and the game may
4
+ * bundle its own client copy, so the shared state is a window global and a
5
+ * window event rather than an object:
6
+ *
7
+ * - `window.__HUB_MENU_VISIBLE__` (boolean; absent means visible);
8
+ * - `hub:menu-visibility` (`CustomEvent`, detail `{ visible }`).
9
+ *
10
+ * The menu reads the global on boot and listens for the event.
11
+ */
12
+ import { emitWindowEvent, isBrowserPage } from './page';
13
+
14
+ declare global {
15
+ interface Window {
16
+ /** The last requested menu-button visibility (absent: visible). */
17
+ __HUB_MENU_VISIBLE__?: boolean;
18
+ }
19
+ }
20
+
21
+ /** Control over the injected hub menu button. */
22
+ export interface HubMenuControl {
23
+ /**
24
+ * Show (`true`) or hide (`false`) the menu button. Hidden means faded out,
25
+ * not focusable and `aria-hidden`; an open drawer stays open until closed,
26
+ * and the gamepad Select button still opens it. A small corner hotspot
27
+ * peeks it back for a few seconds on hover or tap, so players can always
28
+ * reach it.
29
+ */
30
+ setVisible(isVisible: boolean): void;
31
+ /** Show the menu button. */
32
+ show(): void;
33
+ /** Hide the menu button. */
34
+ hide(): void;
35
+ /** The last requested visibility (`true` unless a game hid it). */
36
+ readonly visible: boolean;
37
+ }
38
+
39
+ /** The page's menu control (one per page; every client copy shares the window state). */
40
+ export const hubMenu: HubMenuControl = {
41
+ setVisible(isVisible: boolean): void {
42
+ if (!isBrowserPage()) {
43
+ return;
44
+ }
45
+ const wasVisible = window.__HUB_MENU_VISIBLE__;
46
+ if (wasVisible === isVisible || (wasVisible === undefined && isVisible)) {
47
+ return;
48
+ }
49
+ window.__HUB_MENU_VISIBLE__ = isVisible;
50
+ emitWindowEvent('hub:menu-visibility', { visible: isVisible });
51
+ },
52
+ show(): void {
53
+ hubMenu.setVisible(true);
54
+ },
55
+ hide(): void {
56
+ hubMenu.setVisible(false);
57
+ },
58
+ get visible(): boolean {
59
+ return !isBrowserPage() || window.__HUB_MENU_VISIBLE__ !== false;
60
+ },
61
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Analytics events recorded while offline (`play`, `heartbeat`, custom
3
+ * events), kept under `hub:<slug>:events` and sent when the hub is back.
4
+ * The buffer is capped; heartbeats are dropped first, then the oldest.
5
+ */
6
+ import { isRecord, optionalNumber, optionalString } from '../storage/json-guards';
7
+
8
+ /** The most events kept while offline. */
9
+ export const EVENT_BUFFER_CAP = 100;
10
+
11
+ /** One buffered event. */
12
+ export interface BufferedEvent {
13
+ /** The event type, as `recordGameEvent` sends it. */
14
+ readonly type: string;
15
+ /** When it happened (epoch ms). */
16
+ readonly ts: number;
17
+ }
18
+
19
+ /** The well-formed events of a stored buffer. */
20
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a buffer read back from localStorage (possibly written by a v1 client)
21
+ export function readEvents(stored: unknown): BufferedEvent[] {
22
+ if (!Array.isArray(stored)) {
23
+ return [];
24
+ }
25
+ return stored.flatMap((entry): BufferedEvent[] => {
26
+ if (!isRecord(entry)) {
27
+ return [];
28
+ }
29
+ const type = optionalString(entry.type);
30
+ const ts = optionalNumber(entry.ts);
31
+ return type === undefined || ts === undefined ? [] : [{ type, ts }];
32
+ });
33
+ }
34
+
35
+ /** The buffer with one more event, trimmed to {@link EVENT_BUFFER_CAP}: oldest heartbeats go first, then the oldest events. */
36
+ export function appendEvent(events: readonly BufferedEvent[], incoming: BufferedEvent): BufferedEvent[] {
37
+ let buffered = [...events, incoming];
38
+ let excess = buffered.length - EVENT_BUFFER_CAP;
39
+ if (excess <= 0) {
40
+ return buffered;
41
+ }
42
+ buffered = buffered.filter((event) => {
43
+ if (excess > 0 && event.type === 'heartbeat') {
44
+ excess -= 1;
45
+ return false;
46
+ }
47
+ return true;
48
+ });
49
+ return buffered.length > EVENT_BUFFER_CAP ? buffered.slice(buffered.length - EVENT_BUFFER_CAP) : buffered;
50
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Starred games are site-wide, not per game, so they live under one global
3
+ * key (`hub:favorites`, the v1 client's) rather than in a game's cache. The
4
+ * list mirrors the hub's so the menu still shows it offline.
5
+ */
6
+ import { parseJsonText, stringsIn } from '../storage/json-guards';
7
+ import { createPageStore } from '../storage/key-value';
8
+
9
+ /** The key of the mirrored favorites list. */
10
+ export const FAVORITES_KEY = 'hub:favorites';
11
+
12
+ /** The mirrored favorite slugs (empty when none or unreadable). */
13
+ export function readLocalFavorites(): string[] {
14
+ const text = createPageStore().read(FAVORITES_KEY);
15
+ return text === null ? [] : stringsIn(parseJsonText(text));
16
+ }
17
+
18
+ /** Mirror the hub's favorites list. */
19
+ export function writeLocalFavorites(games: readonly string[]): void {
20
+ createPageStore().write(FAVORITES_KEY, JSON.stringify(games));
21
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * The offline cache: what the client serves when the hub can't be reached,
3
+ * and where queued writes and buffered events wait. Keys are the v1 client's
4
+ * (`hub:user`, `hub:<slug>:save:<slot>`, `hub:<slug>:queue`, ...), so a page
5
+ * upgraded from a vendored copy keeps that copy's cache and queues.
6
+ */
7
+ import type { Board, Json, SortDir, Stats } from '@diffenderfer-games/hub-contract';
8
+ import { isJson, isNullableString, isNumberRecord, isRecord, optionalNumber, optionalString, parseJsonText } from '../storage/json-guards';
9
+ import { createPageStore, type KeyValueStore } from '../storage/key-value';
10
+ import type { Profile, Save, SaveMeta, SnapshotResponse, User } from '../types';
11
+ import { appendEvent, readEvents, type BufferedEvent } from './events';
12
+ import { betterScore, enqueueOp, readQueue, type QueueOp, type QueueOpInput, type QueuedScoreOptions } from './queue';
13
+
14
+ /** The key of the locally known user, shared by every game (like the real session). */
15
+ export const USER_KEY = 'hub:user';
16
+
17
+ /** A board this player has a local best on. */
18
+ export interface LocalBoard {
19
+ /** The board. */
20
+ readonly board: Board;
21
+ /** This player's best score. */
22
+ readonly best: number;
23
+ }
24
+
25
+ /** How a stat update combines with the stored value. */
26
+ export type StatUpdateMode = 'set' | 'incr' | 'max';
27
+
28
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached user read back from localStorage
29
+ function readUser(stored: unknown): User | null {
30
+ if (!isRecord(stored)) {
31
+ return null;
32
+ }
33
+ const id = optionalNumber(stored.id);
34
+ const username = optionalString(stored.username);
35
+ if (id === undefined || username === undefined) {
36
+ return null;
37
+ }
38
+ return typeof stored.guest === 'boolean' ? { id, username, guest: stored.guest } : { id, username };
39
+ }
40
+
41
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached save read back from localStorage
42
+ function readSave(stored: unknown): Save | null {
43
+ if (!isRecord(stored)) {
44
+ return null;
45
+ }
46
+ const slot = optionalString(stored.slot);
47
+ const updatedAt = optionalNumber(stored.updatedAt);
48
+ if (slot === undefined || updatedAt === undefined || !isNullableString(stored.label) || !isJson(stored.data)) {
49
+ return null;
50
+ }
51
+ return { slot, label: stored.label, data: stored.data, updatedAt };
52
+ }
53
+
54
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached profile read back from localStorage
55
+ function readProfile(stored: unknown): Profile | null {
56
+ if (!isRecord(stored)) {
57
+ return null;
58
+ }
59
+ const game = optionalString(stored.game);
60
+ const updatedAt = optionalNumber(stored.updatedAt);
61
+ if (game === undefined || updatedAt === undefined || !isNullableString(stored.displayName) || !isJson(stored.data)) {
62
+ return null;
63
+ }
64
+ return { game, displayName: stored.displayName, data: stored.data, updatedAt };
65
+ }
66
+
67
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached board read back from localStorage
68
+ function readLocalBoard(stored: unknown): LocalBoard | null {
69
+ if (!isRecord(stored) || !isRecord(stored.board)) {
70
+ return null;
71
+ }
72
+ const key = optionalString(stored.board.key);
73
+ const title = optionalString(stored.board.title);
74
+ const sortDir = stored.board.sortDir === 'asc' || stored.board.sortDir === 'desc' ? stored.board.sortDir : undefined;
75
+ const best = optionalNumber(stored.best);
76
+ if (key === undefined || title === undefined || sortDir === undefined || best === undefined) {
77
+ return null;
78
+ }
79
+ return { board: { key, title, sortDir }, best };
80
+ }
81
+
82
+ /** One game's offline cache, queue and event buffer. */
83
+ export class LocalStore {
84
+ private readonly prefix: string;
85
+ private readonly store: KeyValueStore;
86
+ private sequence = 0;
87
+
88
+ /** The cache for game `slug` in `store` (default: `localStorage`, or memory without it). */
89
+ constructor(slug: string, store: KeyValueStore = createPageStore()) {
90
+ this.prefix = `hub:${slug}:`;
91
+ this.store = store;
92
+ }
93
+
94
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: JSON read back from storage, checked by each caller's guard
95
+ private readStored(key: string): unknown {
96
+ const text = this.store.read(key);
97
+ return text === null ? undefined : parseJsonText(text);
98
+ }
99
+
100
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: any JSON-serializable value the cache stores
101
+ private writeStored(key: string, stored: unknown): void {
102
+ this.store.write(key, JSON.stringify(stored));
103
+ }
104
+
105
+ /** The locally known user. */
106
+ getUser(): User | null {
107
+ return readUser(this.readStored(USER_KEY));
108
+ }
109
+
110
+ /** Remember the user (offline sign-in, or a snapshot). */
111
+ setUser(user: User): void {
112
+ this.writeStored(USER_KEY, user);
113
+ }
114
+
115
+ /** Forget the user (offline sign-out). */
116
+ clearUser(): void {
117
+ this.store.remove(USER_KEY);
118
+ }
119
+
120
+ /** This game's cached profile. */
121
+ getProfile(): Profile | null {
122
+ return readProfile(this.readStored(`${this.prefix}profile`));
123
+ }
124
+
125
+ /** Store this game's profile and return it. */
126
+ setProfile(game: string, displayName: string | null, profileData: Json): Profile {
127
+ const profile: Profile = { game, displayName, data: profileData, updatedAt: Date.now() };
128
+ this.writeStored(`${this.prefix}profile`, profile);
129
+ return profile;
130
+ }
131
+
132
+ /** Every cached save's metadata, newest first. */
133
+ listSaves(): SaveMeta[] {
134
+ return this.store.keys()
135
+ .filter((key) => key.startsWith(`${this.prefix}save:`))
136
+ .flatMap((key) => {
137
+ const save = readSave(this.readStored(key));
138
+ return save === null ? [] : [{ slot: save.slot, label: save.label, updatedAt: save.updatedAt }];
139
+ })
140
+ .sort((first, second) => second.updatedAt - first.updatedAt);
141
+ }
142
+
143
+ /** One cached save, or `null`. */
144
+ getSave(slot: string): Save | null {
145
+ return readSave(this.readStored(`${this.prefix}save:${slot}`));
146
+ }
147
+
148
+ /** Store a save and return its `updatedAt`. */
149
+ putSave(slot: string, saveData: Json, label: string | null): number {
150
+ const updatedAt = Date.now();
151
+ this.writeStored(`${this.prefix}save:${slot}`, { slot, label, data: saveData, updatedAt });
152
+ return updatedAt;
153
+ }
154
+
155
+ /** Forget a save. */
156
+ deleteSave(slot: string): void {
157
+ this.store.remove(`${this.prefix}save:${slot}`);
158
+ }
159
+
160
+ /** This game's cached stats. */
161
+ getStats(): Stats {
162
+ const stored = this.readStored(`${this.prefix}stats`);
163
+ return isNumberRecord(stored) ? { ...stored } : {};
164
+ }
165
+
166
+ /** Apply one stat update and return the stat's new value. */
167
+ updateStat(key: string, amount: number, mode: StatUpdateMode): number {
168
+ const stats = this.getStats();
169
+ const current = stats[key] ?? 0;
170
+ const updated = mode === 'incr' ? current + amount : mode === 'max' ? Math.max(current, amount) : amount;
171
+ this.writeStored(`${this.prefix}stats`, { ...stats, [key]: updated });
172
+ return updated;
173
+ }
174
+
175
+ /** The boards this player has a local best on (offline boards only know the player's own best). */
176
+ listBoards(): Board[] {
177
+ return this.store.keys()
178
+ .filter((key) => key.startsWith(`${this.prefix}lb:`))
179
+ .flatMap((key) => {
180
+ const local = readLocalBoard(this.readStored(key));
181
+ return local === null ? [] : [local.board];
182
+ });
183
+ }
184
+
185
+ /** One board's local best, or `null`. */
186
+ getBoard(key: string): LocalBoard | null {
187
+ return readLocalBoard(this.readStored(`${this.prefix}lb:${key}`));
188
+ }
189
+
190
+ /** Record a score locally, keeping the best one; returns the board and best. */
191
+ submitScore(key: string, score: number, options: QueuedScoreOptions): LocalBoard {
192
+ const existing = this.getBoard(key);
193
+ const sortDir: SortDir = existing?.board.sortDir ?? (options.sort === 'asc' ? 'asc' : 'desc');
194
+ const board: Board = existing?.board ?? { key, title: options.title !== undefined && options.title !== '' ? options.title : key, sortDir };
195
+ const best = existing === null ? score : betterScore(existing.best, score, sortDir);
196
+ this.writeStored(`${this.prefix}lb:${key}`, { board, best });
197
+ return { board, best };
198
+ }
199
+
200
+ /** The queued writes, oldest first. */
201
+ getQueue(): QueueOp[] {
202
+ return readQueue(this.readStored(`${this.prefix}queue`));
203
+ }
204
+
205
+ /** Replace the queue. */
206
+ setQueue(queue: readonly QueueOp[]): void {
207
+ this.writeStored(`${this.prefix}queue`, queue);
208
+ }
209
+
210
+ /** How many writes are queued. */
211
+ queueLength(): number {
212
+ return this.getQueue().length;
213
+ }
214
+
215
+ /** Queue a write, collapsing it with a compatible queued one. */
216
+ enqueue(input: QueueOpInput): void {
217
+ this.sequence += 1;
218
+ const now = Date.now();
219
+ this.setQueue(enqueueOp(this.getQueue(), { ...input, id: `${String(now)}-${String(this.sequence)}`, ts: now }));
220
+ }
221
+
222
+ /** The buffered analytics events, oldest first. */
223
+ getEvents(): BufferedEvent[] {
224
+ return readEvents(this.readStored(`${this.prefix}events`));
225
+ }
226
+
227
+ /** Replace the event buffer. */
228
+ setEvents(events: readonly BufferedEvent[]): void {
229
+ this.writeStored(`${this.prefix}events`, events);
230
+ }
231
+
232
+ /** Buffer one event (capped; heartbeats are dropped first). */
233
+ bufferEvent(type: string): void {
234
+ this.setEvents(appendEvent(this.getEvents(), { type, ts: Date.now() }));
235
+ }
236
+
237
+ /** Fan a `/me/snapshot` reply out across every game's cache keys. */
238
+ hydrate(snapshot: SnapshotResponse): void {
239
+ if (snapshot.user !== null) {
240
+ this.writeStored(USER_KEY, snapshot.user);
241
+ }
242
+ for (const [slug, game] of Object.entries(snapshot.games)) {
243
+ const gamePrefix = `hub:${slug}:`;
244
+ if (game.profile !== null) {
245
+ this.writeStored(`${gamePrefix}profile`, game.profile);
246
+ }
247
+ for (const save of game.saves) {
248
+ this.writeStored(`${gamePrefix}save:${save.slot}`, save);
249
+ }
250
+ this.writeStored(`${gamePrefix}stats`, game.stats);
251
+ this.writeStored(`${gamePrefix}inventory`, game.inventory);
252
+ }
253
+ for (const gameRecords of snapshot.records) {
254
+ for (const record of gameRecords.records) {
255
+ this.writeStored(`hub:${gameRecords.slug}:lb:${record.key}`, { board: { key: record.key, title: record.title, sortDir: record.sortDir }, best: record.score });
256
+ }
257
+ }
258
+ this.writeStored('hub:records', snapshot.records);
259
+ this.writeStored('hub:leaderboards', snapshot.leaderboards);
260
+ }
261
+ }