@diffenderfer-games/hub 2.0.0-next.0 → 2.0.0-next.2

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 (154) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +21 -21
  3. package/README.md +206 -139
  4. package/dist/auto.d.ts +6 -6
  5. package/dist/auto.js +2 -2
  6. package/dist/doctor/cli.mjs +62 -25
  7. package/dist/doctor/cli.mjs.map +1 -1
  8. package/dist/index.d.ts +6 -6
  9. package/dist/index.js +2 -2
  10. package/dist/mp.d.ts +3 -3
  11. package/dist/race.d.ts +1 -1
  12. package/dist/rooms.d.ts +3 -3
  13. package/dist/shared/bridge.js +9 -3
  14. package/dist/shared/bridge.js.map +1 -1
  15. package/dist/shared/client-version.gen.js +1 -1
  16. package/dist/shared/daily.d.ts +10 -4
  17. package/dist/shared/daily.d.ts.map +1 -1
  18. package/dist/shared/daily.js +12 -2
  19. package/dist/shared/daily.js.map +1 -1
  20. package/dist/shared/globals.js +8 -3
  21. package/dist/shared/globals.js.map +1 -1
  22. package/dist/shared/index.d.ts +314 -35
  23. package/dist/shared/index.d.ts.map +1 -1
  24. package/dist/shared/input.js +7 -2
  25. package/dist/shared/input.js.map +1 -1
  26. package/dist/shared/latest-state.js +1 -1
  27. package/dist/shared/mp.js +10 -2
  28. package/dist/shared/mp.js.map +1 -1
  29. package/dist/shared/multiplayer-types.d.ts +15 -2
  30. package/dist/shared/multiplayer-types.d.ts.map +1 -1
  31. package/dist/shared/race-types.d.ts +1 -1
  32. package/dist/shared/race.js +1 -1
  33. package/dist/shared/room-types.d.ts +28 -3
  34. package/dist/shared/room-types.d.ts.map +1 -1
  35. package/dist/shared/rooms.d.ts.map +1 -1
  36. package/dist/shared/rooms.js +10 -2
  37. package/dist/shared/rooms.js.map +1 -1
  38. package/dist/shared/runtime-opener.js +1 -1
  39. package/dist/shared/social.d.ts +23 -8
  40. package/dist/shared/social.d.ts.map +1 -1
  41. package/dist/shared/social.js +6 -1
  42. package/dist/shared/social.js.map +1 -1
  43. package/dist/shared/src.js +1588 -388
  44. package/dist/shared/src.js.map +1 -1
  45. package/dist/shared/wire-types.d.ts +6 -2
  46. package/dist/shared/wire-types.d.ts.map +1 -1
  47. package/dist/social.d.ts +5 -5
  48. package/dist/social.js +1 -1
  49. package/package.json +89 -89
  50. package/src/auto.ts +39 -39
  51. package/src/core/connection.ts +394 -299
  52. package/src/core/errors.ts +147 -147
  53. package/src/core/game-data.ts +40 -38
  54. package/src/core/hub-economy.ts +216 -179
  55. package/src/core/hub-progress.ts +202 -205
  56. package/src/core/hub.ts +133 -131
  57. package/src/core/menu-control.ts +61 -61
  58. package/src/core/offline/events.ts +50 -50
  59. package/src/core/offline/favorites.ts +21 -21
  60. package/src/core/offline/hub-kinds/daily-kind.ts +68 -0
  61. package/src/core/offline/hub-kinds/economy-kinds.ts +86 -0
  62. package/src/core/offline/hub-kinds/game-fields.ts +2 -0
  63. package/src/core/offline/hub-kinds/index.ts +35 -0
  64. package/src/core/offline/hub-kinds/legacy-ops.ts +37 -0
  65. package/src/core/offline/hub-kinds/progress-kinds.ts +148 -0
  66. package/src/core/offline/kind-adapters.ts +48 -0
  67. package/src/core/offline/local-inventory.ts +64 -0
  68. package/src/core/offline/local-store.ts +259 -261
  69. package/src/core/offline/offline-api.ts +65 -0
  70. package/src/core/offline/outbox-entry.ts +59 -0
  71. package/src/core/offline/outbox-kinds.ts +78 -0
  72. package/src/core/offline/outbox-merge.ts +39 -0
  73. package/src/core/offline/outbox-replayer.ts +141 -0
  74. package/src/core/offline/outbox-store.ts +85 -0
  75. package/src/core/offline/outbox.ts +232 -0
  76. package/src/core/offline/queue.ts +126 -171
  77. package/src/core/offline/replay-lease.ts +87 -0
  78. package/src/core/offline/replay-policy.ts +52 -0
  79. package/src/core/page.ts +74 -74
  80. package/src/core/rest/endpoint-types.ts +22 -22
  81. package/src/core/rest/rest-client.ts +163 -152
  82. package/src/core/rest/routes.gen.ts +108 -87
  83. package/src/core/storage/json-guards.ts +80 -74
  84. package/src/core/storage/key-value.ts +66 -66
  85. package/src/core/ticket.ts +43 -43
  86. package/src/core/types.ts +134 -134
  87. package/src/core/version/client-version.gen.ts +1 -1
  88. package/src/core/version/hub-version.ts +62 -62
  89. package/src/core/version/semver.ts +97 -97
  90. package/src/daily/daily-system.ts +168 -161
  91. package/src/daily/page-daily.ts +36 -36
  92. package/src/daily/types.ts +68 -67
  93. package/src/daily.ts +10 -10
  94. package/src/doctor/checks.ts +86 -76
  95. package/src/doctor/cli.ts +98 -106
  96. package/src/doctor/hub-version-fetch.ts +43 -0
  97. package/src/doctor/tsconfig.json +12 -12
  98. package/src/globals.ts +115 -110
  99. package/src/index.ts +55 -50
  100. package/src/input/device-state.ts +146 -146
  101. package/src/input/edges.ts +55 -55
  102. package/src/input/gamepad.ts +61 -61
  103. package/src/input/input-events.ts +32 -32
  104. package/src/input/input-registry.ts +171 -164
  105. package/src/input/input-system.ts +393 -393
  106. package/src/input/legacy-controls.ts +64 -64
  107. package/src/input/nav-state.ts +191 -191
  108. package/src/input/navigator.ts +171 -171
  109. package/src/input/on-screen-controls.ts +101 -101
  110. package/src/input/page-control.ts +43 -43
  111. package/src/input/page-input.ts +193 -193
  112. package/src/input/player-remaps.ts +77 -77
  113. package/src/input/source-values.ts +116 -116
  114. package/src/input/spatial.ts +47 -47
  115. package/src/input/types.ts +331 -331
  116. package/src/input/zero-config.ts +177 -177
  117. package/src/input.ts +22 -22
  118. package/src/mp.ts +10 -10
  119. package/src/overlay/controls-panel.ts +163 -163
  120. package/src/overlay/dom.ts +46 -46
  121. package/src/overlay/layout-clusters.ts +162 -162
  122. package/src/overlay/layout-geometry.ts +136 -136
  123. package/src/overlay/layout.ts +203 -203
  124. package/src/overlay/listener-scope.ts +23 -23
  125. package/src/overlay/on-screen-keyboard.ts +137 -137
  126. package/src/overlay/overlay.ts +208 -208
  127. package/src/overlay/styles.ts +9 -9
  128. package/src/overlay/virtual-controls.ts +262 -262
  129. package/src/race.ts +10 -10
  130. package/src/realtime/bridge.ts +126 -121
  131. package/src/realtime/cross-bundle.ts +29 -29
  132. package/src/realtime/fallback-notice.ts +48 -48
  133. package/src/realtime/hub-link.ts +65 -65
  134. package/src/realtime/latest-state.ts +33 -33
  135. package/src/realtime/multiplayer-forwarder.ts +40 -28
  136. package/src/realtime/multiplayer-types.ts +66 -52
  137. package/src/realtime/page-runtime.ts +60 -60
  138. package/src/realtime/race-forwarder.ts +59 -59
  139. package/src/realtime/race-types.ts +132 -132
  140. package/src/realtime/room-types.ts +151 -125
  141. package/src/realtime/rooms-forwarder.ts +91 -79
  142. package/src/realtime/runtime-api.ts +60 -49
  143. package/src/realtime/runtime-opener.ts +61 -61
  144. package/src/realtime/social-forwarder.ts +77 -72
  145. package/src/realtime/social-types.ts +86 -78
  146. package/src/realtime/types.ts +53 -53
  147. package/src/realtime/wire-types.ts +79 -72
  148. package/src/rooms.ts +10 -10
  149. package/src/social.ts +18 -18
  150. package/src/types.ts +13 -13
  151. package/src/uistack/page-stack.ts +45 -45
  152. package/src/uistack/play-suspension.ts +82 -82
  153. package/src/uistack/types.ts +76 -76
  154. package/src/uistack/ui-stack.ts +144 -144
@@ -1,261 +1,259 @@
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
- }
1
+ /**
2
+ * The offline cache: what the client serves when the hub can't be reached,
3
+ * and where buffered analytics events wait (queued writes live in the
4
+ * outbox, `outbox.ts`). Keys are the v1 client's (`hub:user`,
5
+ * `hub:<slug>:save:<slot>`, `hub:<slug>:events`, ...), so a page upgraded
6
+ * from a vendored copy keeps that copy's cache, and its `hub:<slug>:queue`
7
+ * moves into the outbox.
8
+ */
9
+ import type { Board, Inventory, Json, SortDir, Stats } from '@diffenderfer-games/hub-contract';
10
+ import { isJson, isNullableString, isNumberRecord, isRecord, optionalNumber, optionalString, parseJsonText } from '../storage/json-guards';
11
+ import { createPageStore, type KeyValueStore } from '../storage/key-value';
12
+ import type { Profile, Save, SaveMeta, SnapshotResponse, User } from '../types';
13
+ import { appendEvent, readEvents, type BufferedEvent } from './events';
14
+ import { EMPTY_INVENTORY, readInventory } from './local-inventory';
15
+ import { betterScore, readQueue, type QueueOp, type QueuedScoreOptions } from './queue';
16
+
17
+ /** The key of the locally known user, shared by every game (like the real session). */
18
+ export const USER_KEY = 'hub:user';
19
+
20
+ /** A board this player has a local best on. */
21
+ export interface LocalBoard {
22
+ /** The board. */
23
+ readonly board: Board;
24
+ /** This player's best score. */
25
+ readonly best: number;
26
+ }
27
+
28
+ /** How a stat update combines with the stored value. */
29
+ export type StatUpdateMode = 'set' | 'incr' | 'max';
30
+
31
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached user read back from localStorage
32
+ function readUser(stored: unknown): User | null {
33
+ if (!isRecord(stored)) {
34
+ return null;
35
+ }
36
+ const id = optionalNumber(stored.id);
37
+ const username = optionalString(stored.username);
38
+ if (id === undefined || username === undefined) {
39
+ return null;
40
+ }
41
+ return typeof stored.guest === 'boolean' ? { id, username, guest: stored.guest } : { id, username };
42
+ }
43
+
44
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached save read back from localStorage
45
+ function readSave(stored: unknown): Save | null {
46
+ if (!isRecord(stored)) {
47
+ return null;
48
+ }
49
+ const slot = optionalString(stored.slot);
50
+ const updatedAt = optionalNumber(stored.updatedAt);
51
+ if (slot === undefined || updatedAt === undefined || !isNullableString(stored.label) || !isJson(stored.data)) {
52
+ return null;
53
+ }
54
+ return { slot, label: stored.label, data: stored.data, updatedAt };
55
+ }
56
+
57
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached profile read back from localStorage
58
+ function readProfile(stored: unknown): Profile | null {
59
+ if (!isRecord(stored)) {
60
+ return null;
61
+ }
62
+ const game = optionalString(stored.game);
63
+ const updatedAt = optionalNumber(stored.updatedAt);
64
+ if (game === undefined || updatedAt === undefined || !isNullableString(stored.displayName) || !isJson(stored.data)) {
65
+ return null;
66
+ }
67
+ return { game, displayName: stored.displayName, data: stored.data, updatedAt };
68
+ }
69
+
70
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a cached board read back from localStorage
71
+ function readLocalBoard(stored: unknown): LocalBoard | null {
72
+ if (!isRecord(stored) || !isRecord(stored.board)) {
73
+ return null;
74
+ }
75
+ const key = optionalString(stored.board.key);
76
+ const title = optionalString(stored.board.title);
77
+ const sortDir = stored.board.sortDir === 'asc' || stored.board.sortDir === 'desc' ? stored.board.sortDir : undefined;
78
+ const best = optionalNumber(stored.best);
79
+ if (key === undefined || title === undefined || sortDir === undefined || best === undefined) {
80
+ return null;
81
+ }
82
+ return { board: { key, title, sortDir }, best };
83
+ }
84
+
85
+ /** One game's offline cache, queue and event buffer. */
86
+ export class LocalStore {
87
+ private readonly prefix: string;
88
+ private readonly store: KeyValueStore;
89
+
90
+ /** The cache for game `slug` in `store` (default: `localStorage`, or memory without it). */
91
+ constructor(slug: string, store: KeyValueStore = createPageStore()) {
92
+ this.prefix = `hub:${slug}:`;
93
+ this.store = store;
94
+ }
95
+
96
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: JSON read back from storage, checked by each caller's guard
97
+ private readStored(key: string): unknown {
98
+ const text = this.store.read(key);
99
+ return text === null ? undefined : parseJsonText(text);
100
+ }
101
+
102
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: any JSON-serializable value the cache stores
103
+ private writeStored(key: string, stored: unknown): void {
104
+ this.store.write(key, JSON.stringify(stored));
105
+ }
106
+
107
+ /** The locally known user. */
108
+ getUser(): User | null {
109
+ return readUser(this.readStored(USER_KEY));
110
+ }
111
+
112
+ /** Remember the user (offline sign-in, or a snapshot). */
113
+ setUser(user: User): void {
114
+ this.writeStored(USER_KEY, user);
115
+ }
116
+
117
+ /** Forget the user (offline sign-out). */
118
+ clearUser(): void {
119
+ this.store.remove(USER_KEY);
120
+ }
121
+
122
+ /** This game's cached profile. */
123
+ getProfile(): Profile | null {
124
+ return readProfile(this.readStored(`${this.prefix}profile`));
125
+ }
126
+
127
+ /** Store this game's profile and return it. */
128
+ setProfile(game: string, displayName: string | null, profileData: Json): Profile {
129
+ const profile: Profile = { game, displayName, data: profileData, updatedAt: Date.now() };
130
+ this.writeStored(`${this.prefix}profile`, profile);
131
+ return profile;
132
+ }
133
+
134
+ /** Every cached save's metadata, newest first. */
135
+ listSaves(): SaveMeta[] {
136
+ return this.store.keys()
137
+ .filter((key) => key.startsWith(`${this.prefix}save:`))
138
+ .flatMap((key) => {
139
+ const save = readSave(this.readStored(key));
140
+ return save === null ? [] : [{ slot: save.slot, label: save.label, updatedAt: save.updatedAt }];
141
+ })
142
+ .sort((first, second) => second.updatedAt - first.updatedAt);
143
+ }
144
+
145
+ /** One cached save, or `null`. */
146
+ getSave(slot: string): Save | null {
147
+ return readSave(this.readStored(`${this.prefix}save:${slot}`));
148
+ }
149
+
150
+ /** Store a save and return its `updatedAt`. */
151
+ putSave(slot: string, saveData: Json, label: string | null): number {
152
+ const updatedAt = Date.now();
153
+ this.writeStored(`${this.prefix}save:${slot}`, { slot, label, data: saveData, updatedAt });
154
+ return updatedAt;
155
+ }
156
+
157
+ /** Forget a save. */
158
+ deleteSave(slot: string): void {
159
+ this.store.remove(`${this.prefix}save:${slot}`);
160
+ }
161
+
162
+ /** This game's cached stats. */
163
+ getStats(): Stats {
164
+ const stored = this.readStored(`${this.prefix}stats`);
165
+ return isNumberRecord(stored) ? { ...stored } : {};
166
+ }
167
+
168
+ /** Apply one stat update and return the stat's new value. */
169
+ updateStat(key: string, amount: number, mode: StatUpdateMode): number {
170
+ const stats = this.getStats();
171
+ const current = stats[key] ?? 0;
172
+ const updated = mode === 'incr' ? current + amount : mode === 'max' ? Math.max(current, amount) : amount;
173
+ this.writeStored(`${this.prefix}stats`, { ...stats, [key]: updated });
174
+ return updated;
175
+ }
176
+
177
+ /** The boards this player has a local best on (offline boards only know the player's own best). */
178
+ listBoards(): Board[] {
179
+ return this.store.keys()
180
+ .filter((key) => key.startsWith(`${this.prefix}lb:`))
181
+ .flatMap((key) => {
182
+ const local = readLocalBoard(this.readStored(key));
183
+ return local === null ? [] : [local.board];
184
+ });
185
+ }
186
+
187
+ /** One board's local best, or `null`. */
188
+ getBoard(key: string): LocalBoard | null {
189
+ return readLocalBoard(this.readStored(`${this.prefix}lb:${key}`));
190
+ }
191
+
192
+ /** Record a score locally, keeping the best one; returns the board and best. */
193
+ submitScore(key: string, score: number, options: QueuedScoreOptions): LocalBoard {
194
+ const existing = this.getBoard(key);
195
+ const sortDir: SortDir = existing?.board.sortDir ?? (options.sort === 'asc' ? 'asc' : 'desc');
196
+ const board: Board = existing?.board ?? { key, title: options.title !== undefined && options.title !== '' ? options.title : key, sortDir };
197
+ const best = existing === null ? score : betterScore(existing.best, score, sortDir);
198
+ this.writeStored(`${this.prefix}lb:${key}`, { board, best });
199
+ return { board, best };
200
+ }
201
+
202
+ /** The v1 client's queued writes, removed from storage (the caller moves them into the outbox). */
203
+ takeLegacyQueue(): QueueOp[] {
204
+ const queue = readQueue(this.readStored(`${this.prefix}queue`));
205
+ this.store.remove(`${this.prefix}queue`);
206
+ return queue;
207
+ }
208
+
209
+ /** This game's cached inventory (empty when none is cached). */
210
+ getInventory(): Inventory {
211
+ return readInventory(this.readStored(`${this.prefix}inventory`)) ?? EMPTY_INVENTORY;
212
+ }
213
+
214
+ /** Store this game's inventory and return it. */
215
+ setInventory(inventory: Inventory): Inventory {
216
+ this.writeStored(`${this.prefix}inventory`, inventory);
217
+ return inventory;
218
+ }
219
+
220
+ /** The buffered analytics events, oldest first. */
221
+ getEvents(): BufferedEvent[] {
222
+ return readEvents(this.readStored(`${this.prefix}events`));
223
+ }
224
+
225
+ /** Replace the event buffer. */
226
+ setEvents(events: readonly BufferedEvent[]): void {
227
+ this.writeStored(`${this.prefix}events`, events);
228
+ }
229
+
230
+ /** Buffer one event (capped; heartbeats are dropped first). */
231
+ bufferEvent(type: string): void {
232
+ this.setEvents(appendEvent(this.getEvents(), { type, ts: Date.now() }));
233
+ }
234
+
235
+ /** Fan a `/me/snapshot` reply out across every game's cache keys. */
236
+ hydrate(snapshot: SnapshotResponse): void {
237
+ if (snapshot.user !== null) {
238
+ this.writeStored(USER_KEY, snapshot.user);
239
+ }
240
+ for (const [slug, game] of Object.entries(snapshot.games)) {
241
+ const gamePrefix = `hub:${slug}:`;
242
+ if (game.profile !== null) {
243
+ this.writeStored(`${gamePrefix}profile`, game.profile);
244
+ }
245
+ for (const save of game.saves) {
246
+ this.writeStored(`${gamePrefix}save:${save.slot}`, save);
247
+ }
248
+ this.writeStored(`${gamePrefix}stats`, game.stats);
249
+ this.writeStored(`${gamePrefix}inventory`, game.inventory);
250
+ }
251
+ for (const gameRecords of snapshot.records) {
252
+ for (const record of gameRecords.records) {
253
+ this.writeStored(`hub:${gameRecords.slug}:lb:${record.key}`, { board: { key: record.key, title: record.title, sortDir: record.sortDir }, best: record.score });
254
+ }
255
+ }
256
+ this.writeStored('hub:records', snapshot.records);
257
+ this.writeStored('hub:leaderboards', snapshot.leaderboards);
258
+ }
259
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `hub.offline`: the outbox, opened to games. A game defines its own kinds
3
+ * (a handler per kind, which may make several dependent calls) and enqueues
4
+ * operations of them; the hub queues them in order, replays them when it is
5
+ * reachable, and reports what happened.
6
+ */
7
+ import { toStoredJson, type GamePayload } from '../game-data';
8
+ import { HubError } from '../errors';
9
+ import { gameKind } from './kind-adapters';
10
+ import type { OfflineEventName, OfflineListener, OfflineOp, Outbox } from './outbox';
11
+ import { HUB_KIND_PREFIX, type OfflineHandler, type OfflineKindDefinition } from './outbox-kinds';
12
+
13
+ /** What `hub.offline` drives. */
14
+ export interface OfflineHost {
15
+ /** The game's outbox. */
16
+ readonly outbox: Outbox;
17
+ /** Replay now when the hub is reachable (and nothing else is replaying). */
18
+ requestSync(): void;
19
+ }
20
+
21
+ /** The game-facing outbox API. */
22
+ export class OfflineApi {
23
+ private readonly host: OfflineHost;
24
+
25
+ /** The API over `host`. */
26
+ constructor(host: OfflineHost) {
27
+ this.host = host;
28
+ }
29
+
30
+ /**
31
+ * Define what an operation of `kind` does when it replays. Define every
32
+ * kind at load, before or after enqueueing: waiting ops of an undefined
33
+ * kind hold the queue until it is defined. `hub.*` kinds are the hub's own.
34
+ */
35
+ define<Payload extends GamePayload>(kind: string, definition: OfflineHandler<Payload> | OfflineKindDefinition<Payload>): void {
36
+ if (kind.startsWith(HUB_KIND_PREFIX) || kind === '') {
37
+ throw new HubError(`Offline kinds starting with "${HUB_KIND_PREFIX}" are the hub's own; name yours after your game.`);
38
+ }
39
+ this.host.outbox.define(kind, gameKind(definition));
40
+ this.host.requestSync();
41
+ }
42
+
43
+ /**
44
+ * Queue an operation of `kind` and replay it as soon as the hub is
45
+ * reachable (at once when online). Resolves the queued op; its outcome
46
+ * arrives as a `replayed` or `failed` event. Throws a `HubError` (code
47
+ * `offline_queue_full`) when the outbox is full.
48
+ */
49
+ enqueue(kind: string, payload: GamePayload): OfflineOp {
50
+ const op = this.host.outbox.stamp(kind, toStoredJson(payload));
51
+ this.host.outbox.add(op);
52
+ this.host.requestSync();
53
+ return op;
54
+ }
55
+
56
+ /** The waiting operations (the hub's and the game's), oldest first. */
57
+ pending(): OfflineOp[] {
58
+ return this.host.outbox.pending();
59
+ }
60
+
61
+ /** Listen for `queued`, `replayed` or `failed`; returns the unsubscribe function. */
62
+ on<Name extends OfflineEventName>(name: Name, listener: OfflineListener<Name>): () => void {
63
+ return this.host.outbox.on(name, listener);
64
+ }
65
+ }