@hadoku/prefs-client 1.2.1 → 1.2.3

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 CHANGED
@@ -62,6 +62,8 @@ function Settings() {
62
62
  - **Cross-tab**: BroadcastChannel keyed by `prefs:{userId}:{appId}` propagates saves between tabs without a server roundtrip.
63
63
  - **Anon → authed**: call `client.promoteAnonPrefsToUser()` after sign-in. If the server already has user-scope prefs (signed in on another device first), the server wins.
64
64
  - **Dirty-field protection**: a background refresh (or an incoming cross-tab broadcast) never overwrites a field with a save still pending/in-flight — it merges the server/remote blob with your unconfirmed local value instead. Otherwise a refresh landing between an optimistic write and its debounced PUT would visibly revert the change.
65
+ - **`peek()`**: the prefs the client holds right now, synchronously, or `null` before the first read settles. `usePrefs` renders from it, so a component mounted after the client has read starts from the held value rather than `null`.
66
+ - **`reset()`**: forgets everything the client holds in memory (prefs, versions, resolved identity) so the next `read()` starts over; storage is left alone. Unsent saves are dropped and a request already in flight is not adopted. For a module-level client that needs a clean start without a new module graph, such as each test of an app that imports one: clear storage, then `client.reset()`.
65
67
  - **FOUC bootstrap**: `bootstrapToSessionStorage` mirrors specific fields to sessionStorage so the inline `<head>` script can apply theme before React mounts. Mirroring only happens on an explicit local `save()` by default — never on read/hydrate/refresh/broadcast-receive — so an app embedded under a host that owns the same sessionStorage key can't clobber it just by booting. Pass `mirrorBootstrapOnRead: true` to restore the old every-read mirroring for a key nothing else writes to.
66
68
 
67
69
  ## Capacitor (native APK)
package/dist/games.d.ts CHANGED
@@ -163,10 +163,16 @@ interface StatsFilter {
163
163
  /** Only the matches whose scalar match attr is one of the values: `{ format: ['standard', 'modern'] }`. */
164
164
  match?: Readonly<Record<string, readonly string[]>>;
165
165
  }
166
+ /**
167
+ * One rating pool, or several: a read given several spans any of them, and a
168
+ * profile answers one `ratings` row per pool the player has. Needs a prefs-api
169
+ * (or game-stats) that reads `mode` repeated; one older answers the first only.
170
+ */
171
+ type ModeScope = string | readonly string[];
166
172
  /** `player` is a registry name; omit it for the caller. */
167
173
  interface PlayerScope extends StatsFilter {
168
174
  player?: string;
169
- mode?: string;
175
+ mode?: ModeScope;
170
176
  }
171
177
  declare function createGameStatsClient(opts: GameStatsClientOptions): {
172
178
  profile: (s?: PlayerScope) => Promise<ProfileView>;
@@ -175,9 +181,10 @@ declare function createGameStatsClient(opts: GameStatsClientOptions): {
175
181
  before?: number;
176
182
  }) => Promise<MatchPage>;
177
183
  match: (matchId: string) => Promise<MatchView>;
184
+ /** The rating board is one pool; an outcome board (`games`, `wins`, …) may span several. */
178
185
  leaderboard: (s?: {
179
186
  by?: LeaderboardBy;
180
- mode?: string;
187
+ mode?: ModeScope;
181
188
  limit?: number;
182
189
  }) => Promise<{
183
190
  by: LeaderboardBy;
@@ -202,4 +209,4 @@ interface RecordMatchOptions extends GameStatsClientOptions {
202
209
  /** Server-side: report one finished match. Safe to retry with the same matchId. */
203
210
  declare function recordMatch(opts: RecordMatchOptions, report: MatchReport): Promise<RecordMatchResult>;
204
211
 
205
- export { type BreakdownRow, type CounterTotals, DEFAULT_MODE, GAME_ID_PATTERN, type GameStatsClient, type GameStatsClientOptions, GameStatsError, type LeaderboardBy, type LeaderboardRow, MATCH_ID_PATTERN, type MatchPage, type MatchReport, type MatchSeatReport, type MatchView, type OutcomeTotals, type PlayerScope, type ProfileView, type RecordMatchOptions, type RecordMatchResult, STARTING_RATING, STAT_KEY_PATTERN, STAT_LIMITS, type SeatKind, type SeatOutcome, type SeatView, type StatAttr, type StatAttrs, type StatCounters, type StatsFilter, createGameStatsClient, outcomesFor, recordMatch, winRate };
212
+ export { type BreakdownRow, type CounterTotals, DEFAULT_MODE, GAME_ID_PATTERN, type GameStatsClient, type GameStatsClientOptions, GameStatsError, type LeaderboardBy, type LeaderboardRow, MATCH_ID_PATTERN, type MatchPage, type MatchReport, type MatchSeatReport, type MatchView, type ModeScope, type OutcomeTotals, type PlayerScope, type ProfileView, type RecordMatchOptions, type RecordMatchResult, STARTING_RATING, STAT_KEY_PATTERN, STAT_LIMITS, type SeatKind, type SeatOutcome, type SeatView, type StatAttr, type StatAttrs, type StatCounters, type StatsFilter, createGameStatsClient, outcomesFor, recordMatch, winRate };
package/dist/games.js CHANGED
@@ -49,7 +49,8 @@ function query({
49
49
  const q = new URLSearchParams();
50
50
  for (const [k, v] of Object.entries(params)) {
51
51
  if (v === void 0 || v === false) continue;
52
- q.set(k, v === true ? "1" : String(v));
52
+ if (typeof v === "object") for (const each of v) q.append(k, each);
53
+ else q.set(k, v === true ? "1" : String(v));
53
54
  }
54
55
  for (const [k, values] of Object.entries(match ?? {})) {
55
56
  for (const v of values) q.append(`match.${k}`, v);
@@ -65,6 +66,7 @@ function createGameStatsClient(opts) {
65
66
  profile: (s = {}) => get(`/profile${query({ ...s })}`),
66
67
  matches: (s = {}) => get(`/matches${query({ ...s })}`),
67
68
  match: (matchId) => get(`/matches/${encodeURIComponent(matchId)}`),
69
+ /** The rating board is one pool; an outcome board (`games`, `wins`, …) may span several. */
68
70
  leaderboard: (s = {}) => get(`/leaderboard${query({ ...s })}`),
69
71
  /**
70
72
  * Outcome totals grouped by one attr. `player: '*'` spans everyone.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
- import { P as PrefsClientOptions, a as PrefsClient, A as AsyncStorage } from './types-r2SIOIuu.js';
3
- export { b as PrefsConflictError, c as PrefsMigration, d as PrefsRow, S as SaveOptions, e as Scope, f as ServerReadResult, g as capacitorStorage, h as detectStorage, l as localStorageAdapter, m as memoryStorage, s as sessionStorageWrite } from './types-r2SIOIuu.js';
2
+ import { P as PrefsClientOptions, a as PrefsClient, A as AsyncStorage } from './types-DiRaemLm.js';
3
+ export { b as PrefsConflictError, c as PrefsMigration, d as PrefsRow, S as SaveOptions, e as Scope, f as ServerReadResult, g as capacitorStorage, h as detectStorage, l as localStorageAdapter, m as memoryStorage, s as sessionStorageWrite } from './types-DiRaemLm.js';
4
4
 
5
5
  /**
6
6
  * createPrefsClient — vanilla (no React) client for the prefs-api.
package/dist/index.js CHANGED
@@ -216,9 +216,11 @@ function createPrefsClient(opts) {
216
216
  let initPromise = null;
217
217
  let bcast = null;
218
218
  let destroyed = false;
219
+ let epoch = 0;
219
220
  const broadcastId = `${Math.random().toString(36).slice(2)}-${Date.now()}`;
220
221
  function ensureInit() {
221
222
  if (initPromise) return initPromise;
223
+ const started = epoch;
222
224
  initPromise = (async () => {
223
225
  const who = await whoami({
224
226
  userKey: opts.userKey,
@@ -227,12 +229,16 @@ function createPrefsClient(opts) {
227
229
  // browser — rather than pinning the hadoku.me constant (#419).
228
230
  ...opts.apiBase ? { whoamiUrl: `${opts.apiBase.replace(/\/prefs$/, "")}/session/whoami` } : {}
229
231
  });
232
+ if (epoch !== started) return;
230
233
  userId = who.userId;
231
234
  identityScope = who.scope;
232
235
  if (!deviceId) {
233
- deviceId = await getDeviceId(storage);
236
+ const id = await getDeviceId(storage);
237
+ if (epoch !== started) return;
238
+ deviceId = id;
234
239
  }
235
240
  const cached = await readCache();
241
+ if (epoch !== started) return;
236
242
  if (cached) {
237
243
  userVersion = cached.userVersion;
238
244
  deviceVersion = cached.deviceVersion;
@@ -376,7 +382,9 @@ function createPrefsClient(opts) {
376
382
  }
377
383
  return;
378
384
  }
385
+ const started = epoch;
379
386
  const server = await fetchFromServer();
387
+ if (epoch !== started) return;
380
388
  userVersion = server.user?.version ?? 0;
381
389
  deviceVersion = server.device?.version ?? 0;
382
390
  const merged = reconcileDirty(server.merged ?? {});
@@ -433,8 +441,10 @@ function createPrefsClient(opts) {
433
441
  }
434
442
  const expectedVersion = batch.expected === void 0 ? batch.scope === "user" ? userVersion : deviceVersion : batch.expected ?? void 0;
435
443
  let conflict = null;
444
+ const started = epoch;
436
445
  try {
437
446
  const result = await putToServer(batch.scope, batch.patch, expectedVersion);
447
+ if (epoch !== started) return;
438
448
  const version = result.ok ? result.row.version : result.conflict.version;
439
449
  if ((result.ok ? result.scope : batch.scope) === "user") {
440
450
  userVersion = version;
@@ -445,6 +455,7 @@ function createPrefsClient(opts) {
445
455
  conflict = new PrefsConflictError(batch.patch, batch.scope, version);
446
456
  }
447
457
  } catch {
458
+ if (epoch !== started) return;
448
459
  unsettled.delete(batch);
449
460
  const front = queued[0];
450
461
  if (front && front.scope === batch.scope && front.expected === batch.expected) {
@@ -514,6 +525,9 @@ function createPrefsClient(opts) {
514
525
  scheduleFlush();
515
526
  }
516
527
  },
528
+ peek() {
529
+ return currentBlob;
530
+ },
517
531
  subscribe(listener) {
518
532
  listeners.add(listener);
519
533
  return () => {
@@ -550,6 +564,26 @@ function createPrefsClient(opts) {
550
564
  const conflict = conflicts.find((c) => c !== null);
551
565
  if (conflict) throw conflict;
552
566
  },
567
+ reset() {
568
+ epoch++;
569
+ if (saveTimer) clearTimeout(saveTimer);
570
+ saveTimer = null;
571
+ for (const batch of unsettled) batch.settle(null);
572
+ unsettled.clear();
573
+ queued = [];
574
+ dirtyFields.clear();
575
+ sendChain = Promise.resolve();
576
+ if (bcast) bcast.close();
577
+ bcast = null;
578
+ initPromise = null;
579
+ userId = null;
580
+ identityScope = "anon";
581
+ wroteWhileAnon = false;
582
+ deviceId = opts.deviceId ?? null;
583
+ currentBlob = null;
584
+ userVersion = 0;
585
+ deviceVersion = 0;
586
+ },
553
587
  destroy() {
554
588
  if (destroyed) return;
555
589
  destroyed = true;
package/dist/react.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as PrefsClient } from './types-r2SIOIuu.js';
1
+ import { a as PrefsClient } from './types-DiRaemLm.js';
2
2
  import 'zod';
3
3
 
4
4
  interface UsePrefsResult<T extends Record<string, unknown>> {
package/dist/react.js CHANGED
@@ -27,23 +27,9 @@ var storeCache = /* @__PURE__ */ new WeakMap();
27
27
  function useStoreFromClient(client) {
28
28
  const cached = storeCache.get(client);
29
29
  if (cached) return cached;
30
- let snapshot = null;
31
- const onChangeListeners = /* @__PURE__ */ new Set();
32
- const unsubscribe = client.subscribe((next) => {
33
- snapshot = next;
34
- for (const l of onChangeListeners) l();
35
- });
36
30
  const store = {
37
- subscribe: (onChange) => {
38
- onChangeListeners.add(onChange);
39
- return () => {
40
- onChangeListeners.delete(onChange);
41
- if (onChangeListeners.size === 0) {
42
- void unsubscribe;
43
- }
44
- };
45
- },
46
- getSnapshot: () => snapshot,
31
+ subscribe: (onChange) => client.subscribe(() => onChange()),
32
+ getSnapshot: () => client.peek(),
47
33
  getServerSnapshot: () => null
48
34
  };
49
35
  storeCache.set(client, store);
@@ -197,6 +197,12 @@ interface PrefsClient<T> {
197
197
  * a 409.
198
198
  */
199
199
  save(patch: Partial<T>, opts?: SaveOptions): Promise<void>;
200
+ /**
201
+ * The prefs this client holds right now, or null before its first read
202
+ * settles (and after reset()). Synchronous and never fetches: the same
203
+ * value until the next change a subscriber is told about.
204
+ */
205
+ peek(): T | null;
200
206
  /** Subscribe to changes (incl. cross-tab via BroadcastChannel). */
201
207
  subscribe(listener: (prefs: T) => void): () => void;
202
208
  /**
@@ -221,6 +227,18 @@ interface PrefsClient<T> {
221
227
  * save. For beforeunload, call it as `void client.flush().catch(...)`.
222
228
  */
223
229
  flush(): Promise<void>;
230
+ /**
231
+ * Forget everything this client holds in memory, as if it had just been
232
+ * created: the prefs it read or saved, the versions it knows, the identity
233
+ * it resolved. The next read() starts again from whoami and storage, which
234
+ * reset() leaves untouched. Unsent saves are dropped (their flush() resolves),
235
+ * and a request already in flight is let finish without its answer being
236
+ * adopted. Subscribers stay subscribed.
237
+ *
238
+ * For a module-level client whose owner needs a clean start without a new
239
+ * module graph, such as each test of an app that imports one.
240
+ */
241
+ reset(): void;
224
242
  /** Tear down (cancels timers, closes BroadcastChannel). */
225
243
  destroy(): void;
226
244
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/prefs-client",
3
- "version": "1.2.1",
4
- "gitHead": "807de8b6e80b27f2a14c7347df6b7d013b8fd6bd",
3
+ "version": "1.2.3",
4
+ "gitHead": "755e0d4de5670334fb73f8cbbc3f0a07f1907614",
5
5
  "description": "Client SDK for the hadoku unified preferences store. Wraps /prefs/api/v1/* with localStorage caching, debounced writes, Zod-validated reads, and a usePrefs() React hook, plus match history, ratings and leaderboards for every game (./games), the one resolved avatar per user (./avatar), and the avatar cosmetics renderer (./cosmetics), and room history (./rooms).",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",