@diffenderfer-games/hub 2.0.0-next.0 → 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 (98) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -21
  3. package/README.md +191 -139
  4. package/dist/doctor/cli.mjs +49 -19
  5. package/dist/doctor/cli.mjs.map +1 -1
  6. package/dist/shared/client-version.gen.js +1 -1
  7. package/dist/shared/daily.js +1 -1
  8. package/dist/shared/globals.js +8 -3
  9. package/dist/shared/globals.js.map +1 -1
  10. package/dist/shared/index.d.ts +1 -1
  11. package/package.json +89 -89
  12. package/src/auto.ts +39 -39
  13. package/src/core/connection.ts +299 -299
  14. package/src/core/errors.ts +147 -147
  15. package/src/core/game-data.ts +38 -38
  16. package/src/core/hub-economy.ts +179 -179
  17. package/src/core/hub-progress.ts +205 -205
  18. package/src/core/hub.ts +131 -131
  19. package/src/core/menu-control.ts +61 -61
  20. package/src/core/offline/events.ts +50 -50
  21. package/src/core/offline/favorites.ts +21 -21
  22. package/src/core/offline/local-store.ts +261 -261
  23. package/src/core/offline/queue.ts +171 -171
  24. package/src/core/page.ts +74 -74
  25. package/src/core/rest/endpoint-types.ts +22 -22
  26. package/src/core/rest/rest-client.ts +152 -152
  27. package/src/core/storage/json-guards.ts +74 -74
  28. package/src/core/storage/key-value.ts +66 -66
  29. package/src/core/ticket.ts +43 -43
  30. package/src/core/types.ts +134 -134
  31. package/src/core/version/client-version.gen.ts +1 -1
  32. package/src/core/version/hub-version.ts +62 -62
  33. package/src/core/version/semver.ts +97 -97
  34. package/src/daily/daily-system.ts +161 -161
  35. package/src/daily/page-daily.ts +36 -36
  36. package/src/daily/types.ts +67 -67
  37. package/src/daily.ts +10 -10
  38. package/src/doctor/checks.ts +78 -76
  39. package/src/doctor/cli.ts +98 -106
  40. package/src/doctor/hub-version-fetch.ts +43 -0
  41. package/src/doctor/tsconfig.json +12 -12
  42. package/src/globals.ts +115 -110
  43. package/src/index.ts +50 -50
  44. package/src/input/device-state.ts +146 -146
  45. package/src/input/edges.ts +55 -55
  46. package/src/input/gamepad.ts +61 -61
  47. package/src/input/input-events.ts +32 -32
  48. package/src/input/input-registry.ts +164 -164
  49. package/src/input/input-system.ts +393 -393
  50. package/src/input/legacy-controls.ts +64 -64
  51. package/src/input/nav-state.ts +191 -191
  52. package/src/input/navigator.ts +171 -171
  53. package/src/input/on-screen-controls.ts +101 -101
  54. package/src/input/page-control.ts +43 -43
  55. package/src/input/page-input.ts +193 -193
  56. package/src/input/player-remaps.ts +77 -77
  57. package/src/input/source-values.ts +116 -116
  58. package/src/input/spatial.ts +47 -47
  59. package/src/input/types.ts +331 -331
  60. package/src/input/zero-config.ts +177 -177
  61. package/src/input.ts +22 -22
  62. package/src/mp.ts +10 -10
  63. package/src/overlay/controls-panel.ts +163 -163
  64. package/src/overlay/dom.ts +46 -46
  65. package/src/overlay/layout-clusters.ts +162 -162
  66. package/src/overlay/layout-geometry.ts +136 -136
  67. package/src/overlay/layout.ts +203 -203
  68. package/src/overlay/listener-scope.ts +23 -23
  69. package/src/overlay/on-screen-keyboard.ts +137 -137
  70. package/src/overlay/overlay.ts +208 -208
  71. package/src/overlay/styles.ts +9 -9
  72. package/src/overlay/virtual-controls.ts +262 -262
  73. package/src/race.ts +10 -10
  74. package/src/realtime/bridge.ts +121 -121
  75. package/src/realtime/cross-bundle.ts +29 -29
  76. package/src/realtime/fallback-notice.ts +48 -48
  77. package/src/realtime/hub-link.ts +65 -65
  78. package/src/realtime/latest-state.ts +33 -33
  79. package/src/realtime/multiplayer-forwarder.ts +28 -28
  80. package/src/realtime/multiplayer-types.ts +52 -52
  81. package/src/realtime/page-runtime.ts +60 -60
  82. package/src/realtime/race-forwarder.ts +59 -59
  83. package/src/realtime/race-types.ts +132 -132
  84. package/src/realtime/room-types.ts +125 -125
  85. package/src/realtime/rooms-forwarder.ts +79 -79
  86. package/src/realtime/runtime-api.ts +49 -49
  87. package/src/realtime/runtime-opener.ts +61 -61
  88. package/src/realtime/social-forwarder.ts +72 -72
  89. package/src/realtime/social-types.ts +78 -78
  90. package/src/realtime/types.ts +53 -53
  91. package/src/realtime/wire-types.ts +72 -72
  92. package/src/rooms.ts +10 -10
  93. package/src/social.ts +18 -18
  94. package/src/types.ts +13 -13
  95. package/src/uistack/page-stack.ts +45 -45
  96. package/src/uistack/play-suspension.ts +82 -82
  97. package/src/uistack/types.ts +76 -76
  98. package/src/uistack/ui-stack.ts +144 -144
@@ -1,299 +1,299 @@
1
- /**
2
- * The machinery under every `Hub` call: reaching the REST API, falling back
3
- * to the offline cache, queueing writes made offline and replaying them,
4
- * buffering analytics, warming the cache for every game, and reporting
5
- * online/offline/sync status (to `onStatus` listeners and as `hub:*` window
6
- * events, which the injected menu listens for).
7
- */
8
- import { HubError } from './errors';
9
- import { LocalStore } from './offline/local-store';
10
- import type { QueueOp, QueueOpInput } from './offline/queue';
11
- import { absoluteApiBase, detectApiBase, detectSlug, emitWindowEvent, isBrowserPage } from './page';
12
- import { createRestClient, type RestClient } from './rest/rest-client';
13
- import type { HubOptions, HubStatus, SnapshotResponse } from './types';
14
-
15
- /** How long `prefetchAll()` waits between snapshots unless forced. */
16
- const PREFETCH_INTERVAL_MS = 30_000;
17
-
18
- /** A queued write the hub refused during a sync: dropped, with the hub's message. */
19
- export interface SyncConflict {
20
- /** The refused op. */
21
- readonly op: QueueOp;
22
- /** The hub's message. */
23
- readonly error?: string;
24
- }
25
-
26
- /** What one `sync()` did. */
27
- export interface SyncResult {
28
- /** Queued writes the hub accepted. */
29
- readonly flushed: number;
30
- /** Queued writes the hub refused (and that were dropped). */
31
- readonly conflicts: SyncConflict[];
32
- }
33
-
34
- /** Whether a failure means "the hub can't be reached" (rather than a refusal). */
35
- // eslint-disable-next-line no-restricted-syntax -- trust boundary: whatever a call threw
36
- function isTransportFailure(failure: unknown): boolean {
37
- return failure instanceof HubError && failure.isOffline;
38
- }
39
-
40
- /** The game slug's path field, or a {@link HubError} when the slug is unknown. */
41
- export interface GameFields {
42
- /** The game's slug. */
43
- readonly slug: string;
44
- }
45
-
46
- /** The connection, offline cache and sync machinery shared by every `Hub` method. */
47
- export class HubConnection {
48
- /** This client's game slug (`null` when it could not be determined). */
49
- readonly slug: string | null;
50
- /** The absolute API base, e.g. `https://diffenderfer.games/_api`. */
51
- readonly apiBase: string;
52
- /** Typed REST calls to {@link apiBase}. */
53
- protected readonly rest: RestClient;
54
- /** This game's offline cache, queue and event buffer. */
55
- protected readonly store: LocalStore;
56
- private readonly offlineMode: NonNullable<HubOptions['offline']>;
57
- private isReachable = true;
58
- private isSyncing = false;
59
- private lastPrefetchAt = 0;
60
- private readonly statusListeners = new Set<(status: HubStatus) => void>();
61
-
62
- /** A connection for `options` (slug and API base default to the page's). */
63
- constructor(options: HubOptions = {}) {
64
- this.slug = options.slug ?? detectSlug();
65
- this.apiBase = options.apiBase === undefined ? detectApiBase() : absoluteApiBase(options.apiBase);
66
- this.offlineMode = options.offline ?? 'auto';
67
- this.rest = createRestClient({
68
- apiBase: this.apiBase,
69
- fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
70
- onReachable: () => {
71
- this.setReachable(true);
72
- },
73
- });
74
- this.store = new LocalStore(this.slug ?? 'app');
75
- if (typeof navigator !== 'undefined' && 'onLine' in navigator) {
76
- this.isReachable = navigator.onLine;
77
- }
78
- if (isBrowserPage()) {
79
- window.addEventListener('online', () => {
80
- this.setReachable(true);
81
- });
82
- window.addEventListener('offline', () => {
83
- this.setReachable(false);
84
- });
85
- }
86
- }
87
-
88
- /** `true` when calls are being served from the offline cache rather than the hub. */
89
- get isOffline(): boolean {
90
- return this.offlineMode === 'always' || (this.offlineMode === 'auto' && !this.isReachable);
91
- }
92
-
93
- /** `true` while the hub is reachable. */
94
- get isOnline(): boolean {
95
- return this.isReachable;
96
- }
97
-
98
- /** Queued writes plus buffered analytics events waiting to sync. */
99
- pending(): number {
100
- return this.store.queueLength() + this.store.getEvents().length;
101
- }
102
-
103
- /** Subscribe to connection and sync status changes; returns the unsubscribe function. */
104
- onStatus(listener: (status: HubStatus) => void): () => void {
105
- this.statusListeners.add(listener);
106
- return () => {
107
- this.statusListeners.delete(listener);
108
- };
109
- }
110
-
111
- /** Tell `onStatus` listeners and the page (`hub:status`) the current status. */
112
- protected notifyStatus(): void {
113
- const status: HubStatus = { online: this.isReachable, offline: this.isOffline, pending: this.pending() };
114
- for (const listener of this.statusListeners) {
115
- try {
116
- listener(status);
117
- } catch {
118
- // A listener's failure must not stop the others.
119
- }
120
- }
121
- emitWindowEvent('hub:status', status);
122
- }
123
-
124
- /** Record reachability; coming back online syncs the queue and re-warms the cache. */
125
- protected setReachable(isReachableNow: boolean): void {
126
- if (isReachableNow === this.isReachable) {
127
- return;
128
- }
129
- this.isReachable = isReachableNow;
130
- emitWindowEvent(isReachableNow ? 'hub:online' : 'hub:offline', { pending: this.pending() });
131
- this.notifyStatus();
132
- if (isReachableNow) {
133
- void this.sync();
134
- void this.prefetchAll().catch(() => undefined);
135
- }
136
- }
137
-
138
- /** `{ slug }` for this game's endpoints; throws when the slug is unknown. */
139
- protected gameFields(): GameFields {
140
- if (this.slug === null) {
141
- throw new HubError('Hub: could not determine the game slug.');
142
- }
143
- return { slug: this.slug };
144
- }
145
-
146
- /**
147
- * Run the network call, falling back to the offline answer when the hub
148
- * can't be reached (per the offline mode). Real API errors (with an HTTP
149
- * status) always reach the caller.
150
- */
151
- protected async withFallback<Reply>(networkCall: () => Promise<Reply>, offlineAnswer: () => Reply): Promise<Reply> {
152
- if (this.isOffline) {
153
- return offlineAnswer();
154
- }
155
- try {
156
- return await networkCall();
157
- } catch (failure) {
158
- if (!isTransportFailure(failure) || this.offlineMode === 'never') {
159
- throw failure;
160
- }
161
- this.setReachable(false);
162
- return offlineAnswer();
163
- }
164
- }
165
-
166
- /** Send one queued write. */
167
- private async sendOp(op: QueueOpInput): Promise<void> {
168
- const game = this.gameFields();
169
- switch (op.kind) {
170
- case 'putSave':
171
- await this.rest.call('writeSave', { ...game, slot: op.slot, data: op.data, label: op.label });
172
- return;
173
- case 'deleteSave':
174
- await this.rest.call('deleteSave', { ...game, slot: op.slot });
175
- return;
176
- case 'setStat':
177
- await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.value, mode: 'set' });
178
- return;
179
- case 'maxStat':
180
- await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.value, mode: 'max' });
181
- return;
182
- case 'incrStat':
183
- await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.amount, mode: 'incr' });
184
- return;
185
- case 'submitScore':
186
- await this.rest.call('submitScore', { ...game, key: op.key, score: op.score, ...op.opts });
187
- return;
188
- case 'setProfile':
189
- await this.rest.call('setGameProfile', { ...game, ...op.patch });
190
- return;
191
- }
192
- }
193
-
194
- /**
195
- * Apply a write to the offline cache at once, then send it now (online
196
- * with an empty queue) or queue it behind the others. Resolves with the
197
- * local answer; a real API error on the direct path reaches the caller and
198
- * is not queued.
199
- */
200
- protected async mutateQueued<Reply>(input: QueueOpInput, localAnswer: () => Reply): Promise<Reply> {
201
- const answer = localAnswer();
202
- if (this.isOffline || this.store.queueLength() > 0) {
203
- this.store.enqueue(input);
204
- this.notifyStatus();
205
- if (!this.isOffline) {
206
- void this.sync();
207
- }
208
- return answer;
209
- }
210
- try {
211
- await this.sendOp(input);
212
- return answer;
213
- } catch (failure) {
214
- if (!isTransportFailure(failure)) {
215
- throw failure;
216
- }
217
- this.setReachable(false);
218
- this.store.enqueue(input);
219
- this.notifyStatus();
220
- return answer;
221
- }
222
- }
223
-
224
- /**
225
- * Replay the queue, then the buffered events, in order. Stops at the first
226
- * transport failure (offline again: the rest stays queued); a write the hub
227
- * refuses is dropped and reported as a conflict.
228
- */
229
- async sync(): Promise<SyncResult> {
230
- if (this.isSyncing || this.isOffline || this.slug === null) {
231
- return { flushed: 0, conflicts: [] };
232
- }
233
- this.isSyncing = true;
234
- let flushed = 0;
235
- const conflicts: SyncConflict[] = [];
236
- try {
237
- let queue = this.store.getQueue();
238
- for (let op = queue[0]; op !== undefined; op = queue[0]) {
239
- try {
240
- await this.sendOp(op);
241
- flushed += 1;
242
- } catch (failure) {
243
- if (isTransportFailure(failure)) {
244
- break;
245
- }
246
- conflicts.push({ op, error: failure instanceof Error ? failure.message : String(failure) });
247
- }
248
- queue = queue.slice(1);
249
- this.store.setQueue(queue);
250
- }
251
- await this.flushEvents();
252
- } finally {
253
- this.isSyncing = false;
254
- }
255
- emitWindowEvent('hub:sync', { pending: this.pending(), flushed, conflicts });
256
- this.notifyStatus();
257
- return { flushed, conflicts };
258
- }
259
-
260
- /** Send the buffered analytics events; a refused one is dropped (telemetry never blocks). */
261
- private async flushEvents(): Promise<void> {
262
- let events = this.store.getEvents();
263
- for (let event = events[0]; event !== undefined; event = events[0]) {
264
- try {
265
- await this.rest.call('recordGameEvent', { ...this.gameFields(), type: event.type });
266
- } catch (failure) {
267
- if (isTransportFailure(failure)) {
268
- return;
269
- }
270
- }
271
- events = events.slice(1);
272
- this.store.setEvents(events);
273
- }
274
- }
275
-
276
- /**
277
- * Warm the offline cache for every game the player has touched, in one
278
- * request, so going offline later still shows complete progress.
279
- * Throttled to once per 30 s unless `isForced`; `null` when offline or throttled.
280
- */
281
- async prefetchAll(isForced = false): Promise<SnapshotResponse | null> {
282
- if (this.isOffline || (!isForced && Date.now() - this.lastPrefetchAt < PREFETCH_INTERVAL_MS)) {
283
- return null;
284
- }
285
- let snapshot: SnapshotResponse;
286
- try {
287
- snapshot = await this.rest.call('getMyOfflineSnapshot');
288
- } catch (failure) {
289
- if (isTransportFailure(failure)) {
290
- return null;
291
- }
292
- throw failure;
293
- }
294
- this.lastPrefetchAt = Date.now();
295
- this.store.hydrate(snapshot);
296
- emitWindowEvent('hub:prefetch', { games: Object.keys(snapshot.games).length });
297
- return snapshot;
298
- }
299
- }
1
+ /**
2
+ * The machinery under every `Hub` call: reaching the REST API, falling back
3
+ * to the offline cache, queueing writes made offline and replaying them,
4
+ * buffering analytics, warming the cache for every game, and reporting
5
+ * online/offline/sync status (to `onStatus` listeners and as `hub:*` window
6
+ * events, which the injected menu listens for).
7
+ */
8
+ import { HubError } from './errors';
9
+ import { LocalStore } from './offline/local-store';
10
+ import type { QueueOp, QueueOpInput } from './offline/queue';
11
+ import { absoluteApiBase, detectApiBase, detectSlug, emitWindowEvent, isBrowserPage } from './page';
12
+ import { createRestClient, type RestClient } from './rest/rest-client';
13
+ import type { HubOptions, HubStatus, SnapshotResponse } from './types';
14
+
15
+ /** How long `prefetchAll()` waits between snapshots unless forced. */
16
+ const PREFETCH_INTERVAL_MS = 30_000;
17
+
18
+ /** A queued write the hub refused during a sync: dropped, with the hub's message. */
19
+ export interface SyncConflict {
20
+ /** The refused op. */
21
+ readonly op: QueueOp;
22
+ /** The hub's message. */
23
+ readonly error?: string;
24
+ }
25
+
26
+ /** What one `sync()` did. */
27
+ export interface SyncResult {
28
+ /** Queued writes the hub accepted. */
29
+ readonly flushed: number;
30
+ /** Queued writes the hub refused (and that were dropped). */
31
+ readonly conflicts: SyncConflict[];
32
+ }
33
+
34
+ /** Whether a failure means "the hub can't be reached" (rather than a refusal). */
35
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: whatever a call threw
36
+ function isTransportFailure(failure: unknown): boolean {
37
+ return failure instanceof HubError && failure.isOffline;
38
+ }
39
+
40
+ /** The game slug's path field, or a {@link HubError} when the slug is unknown. */
41
+ export interface GameFields {
42
+ /** The game's slug. */
43
+ readonly slug: string;
44
+ }
45
+
46
+ /** The connection, offline cache and sync machinery shared by every `Hub` method. */
47
+ export class HubConnection {
48
+ /** This client's game slug (`null` when it could not be determined). */
49
+ readonly slug: string | null;
50
+ /** The absolute API base, e.g. `https://diffenderfer.games/_api`. */
51
+ readonly apiBase: string;
52
+ /** Typed REST calls to {@link apiBase}. */
53
+ protected readonly rest: RestClient;
54
+ /** This game's offline cache, queue and event buffer. */
55
+ protected readonly store: LocalStore;
56
+ private readonly offlineMode: NonNullable<HubOptions['offline']>;
57
+ private isReachable = true;
58
+ private isSyncing = false;
59
+ private lastPrefetchAt = 0;
60
+ private readonly statusListeners = new Set<(status: HubStatus) => void>();
61
+
62
+ /** A connection for `options` (slug and API base default to the page's). */
63
+ constructor(options: HubOptions = {}) {
64
+ this.slug = options.slug ?? detectSlug();
65
+ this.apiBase = options.apiBase === undefined ? detectApiBase() : absoluteApiBase(options.apiBase);
66
+ this.offlineMode = options.offline ?? 'auto';
67
+ this.rest = createRestClient({
68
+ apiBase: this.apiBase,
69
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
70
+ onReachable: () => {
71
+ this.setReachable(true);
72
+ },
73
+ });
74
+ this.store = new LocalStore(this.slug ?? 'app');
75
+ if (typeof navigator !== 'undefined' && 'onLine' in navigator) {
76
+ this.isReachable = navigator.onLine;
77
+ }
78
+ if (isBrowserPage()) {
79
+ window.addEventListener('online', () => {
80
+ this.setReachable(true);
81
+ });
82
+ window.addEventListener('offline', () => {
83
+ this.setReachable(false);
84
+ });
85
+ }
86
+ }
87
+
88
+ /** `true` when calls are being served from the offline cache rather than the hub. */
89
+ get isOffline(): boolean {
90
+ return this.offlineMode === 'always' || (this.offlineMode === 'auto' && !this.isReachable);
91
+ }
92
+
93
+ /** `true` while the hub is reachable. */
94
+ get isOnline(): boolean {
95
+ return this.isReachable;
96
+ }
97
+
98
+ /** Queued writes plus buffered analytics events waiting to sync. */
99
+ pending(): number {
100
+ return this.store.queueLength() + this.store.getEvents().length;
101
+ }
102
+
103
+ /** Subscribe to connection and sync status changes; returns the unsubscribe function. */
104
+ onStatus(listener: (status: HubStatus) => void): () => void {
105
+ this.statusListeners.add(listener);
106
+ return () => {
107
+ this.statusListeners.delete(listener);
108
+ };
109
+ }
110
+
111
+ /** Tell `onStatus` listeners and the page (`hub:status`) the current status. */
112
+ protected notifyStatus(): void {
113
+ const status: HubStatus = { online: this.isReachable, offline: this.isOffline, pending: this.pending() };
114
+ for (const listener of this.statusListeners) {
115
+ try {
116
+ listener(status);
117
+ } catch {
118
+ // A listener's failure must not stop the others.
119
+ }
120
+ }
121
+ emitWindowEvent('hub:status', status);
122
+ }
123
+
124
+ /** Record reachability; coming back online syncs the queue and re-warms the cache. */
125
+ protected setReachable(isReachableNow: boolean): void {
126
+ if (isReachableNow === this.isReachable) {
127
+ return;
128
+ }
129
+ this.isReachable = isReachableNow;
130
+ emitWindowEvent(isReachableNow ? 'hub:online' : 'hub:offline', { pending: this.pending() });
131
+ this.notifyStatus();
132
+ if (isReachableNow) {
133
+ void this.sync();
134
+ void this.prefetchAll().catch(() => undefined);
135
+ }
136
+ }
137
+
138
+ /** `{ slug }` for this game's endpoints; throws when the slug is unknown. */
139
+ protected gameFields(): GameFields {
140
+ if (this.slug === null) {
141
+ throw new HubError('Hub: could not determine the game slug.');
142
+ }
143
+ return { slug: this.slug };
144
+ }
145
+
146
+ /**
147
+ * Run the network call, falling back to the offline answer when the hub
148
+ * can't be reached (per the offline mode). Real API errors (with an HTTP
149
+ * status) always reach the caller.
150
+ */
151
+ protected async withFallback<Reply>(networkCall: () => Promise<Reply>, offlineAnswer: () => Reply): Promise<Reply> {
152
+ if (this.isOffline) {
153
+ return offlineAnswer();
154
+ }
155
+ try {
156
+ return await networkCall();
157
+ } catch (failure) {
158
+ if (!isTransportFailure(failure) || this.offlineMode === 'never') {
159
+ throw failure;
160
+ }
161
+ this.setReachable(false);
162
+ return offlineAnswer();
163
+ }
164
+ }
165
+
166
+ /** Send one queued write. */
167
+ private async sendOp(op: QueueOpInput): Promise<void> {
168
+ const game = this.gameFields();
169
+ switch (op.kind) {
170
+ case 'putSave':
171
+ await this.rest.call('writeSave', { ...game, slot: op.slot, data: op.data, label: op.label });
172
+ return;
173
+ case 'deleteSave':
174
+ await this.rest.call('deleteSave', { ...game, slot: op.slot });
175
+ return;
176
+ case 'setStat':
177
+ await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.value, mode: 'set' });
178
+ return;
179
+ case 'maxStat':
180
+ await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.value, mode: 'max' });
181
+ return;
182
+ case 'incrStat':
183
+ await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.amount, mode: 'incr' });
184
+ return;
185
+ case 'submitScore':
186
+ await this.rest.call('submitScore', { ...game, key: op.key, score: op.score, ...op.opts });
187
+ return;
188
+ case 'setProfile':
189
+ await this.rest.call('setGameProfile', { ...game, ...op.patch });
190
+ return;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Apply a write to the offline cache at once, then send it now (online
196
+ * with an empty queue) or queue it behind the others. Resolves with the
197
+ * local answer; a real API error on the direct path reaches the caller and
198
+ * is not queued.
199
+ */
200
+ protected async mutateQueued<Reply>(input: QueueOpInput, localAnswer: () => Reply): Promise<Reply> {
201
+ const answer = localAnswer();
202
+ if (this.isOffline || this.store.queueLength() > 0) {
203
+ this.store.enqueue(input);
204
+ this.notifyStatus();
205
+ if (!this.isOffline) {
206
+ void this.sync();
207
+ }
208
+ return answer;
209
+ }
210
+ try {
211
+ await this.sendOp(input);
212
+ return answer;
213
+ } catch (failure) {
214
+ if (!isTransportFailure(failure)) {
215
+ throw failure;
216
+ }
217
+ this.setReachable(false);
218
+ this.store.enqueue(input);
219
+ this.notifyStatus();
220
+ return answer;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Replay the queue, then the buffered events, in order. Stops at the first
226
+ * transport failure (offline again: the rest stays queued); a write the hub
227
+ * refuses is dropped and reported as a conflict.
228
+ */
229
+ async sync(): Promise<SyncResult> {
230
+ if (this.isSyncing || this.isOffline || this.slug === null) {
231
+ return { flushed: 0, conflicts: [] };
232
+ }
233
+ this.isSyncing = true;
234
+ let flushed = 0;
235
+ const conflicts: SyncConflict[] = [];
236
+ try {
237
+ let queue = this.store.getQueue();
238
+ for (let op = queue[0]; op !== undefined; op = queue[0]) {
239
+ try {
240
+ await this.sendOp(op);
241
+ flushed += 1;
242
+ } catch (failure) {
243
+ if (isTransportFailure(failure)) {
244
+ break;
245
+ }
246
+ conflicts.push({ op, error: failure instanceof Error ? failure.message : String(failure) });
247
+ }
248
+ queue = queue.slice(1);
249
+ this.store.setQueue(queue);
250
+ }
251
+ await this.flushEvents();
252
+ } finally {
253
+ this.isSyncing = false;
254
+ }
255
+ emitWindowEvent('hub:sync', { pending: this.pending(), flushed, conflicts });
256
+ this.notifyStatus();
257
+ return { flushed, conflicts };
258
+ }
259
+
260
+ /** Send the buffered analytics events; a refused one is dropped (telemetry never blocks). */
261
+ private async flushEvents(): Promise<void> {
262
+ let events = this.store.getEvents();
263
+ for (let event = events[0]; event !== undefined; event = events[0]) {
264
+ try {
265
+ await this.rest.call('recordGameEvent', { ...this.gameFields(), type: event.type });
266
+ } catch (failure) {
267
+ if (isTransportFailure(failure)) {
268
+ return;
269
+ }
270
+ }
271
+ events = events.slice(1);
272
+ this.store.setEvents(events);
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Warm the offline cache for every game the player has touched, in one
278
+ * request, so going offline later still shows complete progress.
279
+ * Throttled to once per 30 s unless `isForced`; `null` when offline or throttled.
280
+ */
281
+ async prefetchAll(isForced = false): Promise<SnapshotResponse | null> {
282
+ if (this.isOffline || (!isForced && Date.now() - this.lastPrefetchAt < PREFETCH_INTERVAL_MS)) {
283
+ return null;
284
+ }
285
+ let snapshot: SnapshotResponse;
286
+ try {
287
+ snapshot = await this.rest.call('getMyOfflineSnapshot');
288
+ } catch (failure) {
289
+ if (isTransportFailure(failure)) {
290
+ return null;
291
+ }
292
+ throw failure;
293
+ }
294
+ this.lastPrefetchAt = Date.now();
295
+ this.store.hydrate(snapshot);
296
+ emitWindowEvent('hub:prefetch', { games: Object.keys(snapshot.games).length });
297
+ return snapshot;
298
+ }
299
+ }