@hadoku/prefs-client 1.1.23 → 1.1.25
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 +2 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.js +104 -55
- package/dist/react.d.ts +1 -1
- package/dist/{types-DCldC4WA.d.ts → types-r2SIOIuu.d.ts} +45 -7
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,7 +57,8 @@ function Settings() {
|
|
|
57
57
|
|
|
58
58
|
- **Cache**: localStorage at `prefs-cache:{userId}:{appId}`. Stale-while-revalidate.
|
|
59
59
|
- **Writes**: 1s-debounced PUT. Multiple `save()` calls within the window coalesce into one network call.
|
|
60
|
-
- **Conflicts**: API-Always-Wins. On a 409 the SDK adopts the server blob and re-renders; the local patch is discarded
|
|
60
|
+
- **Conflicts**: API-Always-Wins. On a 409 the SDK adopts the server blob and re-renders; the local patch is discarded, and the `save()` (with an explicit `expectedVersion`) or `flush()` waiting on it rejects with `PrefsConflictError`.
|
|
61
|
+
- **`expectedVersion`**: by default the SDK sends the last version it has seen (0 before the first read). `save(patch, { expectedVersion: n })` sends `n`; `{ expectedVersion: null }` sends none — last write wins. Both send at once rather than debounced.
|
|
61
62
|
- **Cross-tab**: BroadcastChannel keyed by `prefs:{userId}:{appId}` propagates saves between tabs without a server roundtrip.
|
|
62
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.
|
|
63
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.
|
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-
|
|
3
|
-
export { b as
|
|
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';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* createPrefsClient — vanilla (no React) client for the prefs-api.
|
|
@@ -15,9 +15,10 @@ export { b as PrefsMigration, c as PrefsRow, S as SaveOptions, d as Scope, e as
|
|
|
15
15
|
* save(patch)
|
|
16
16
|
* ├─ merge patch into in-memory current blob
|
|
17
17
|
* ├─ update cache + notify listeners synchronously (optimistic UI)
|
|
18
|
-
* ├─ debounce 1s, then PUT
|
|
18
|
+
* ├─ debounce 1s, then PUT (an explicit expectedVersion sends at once)
|
|
19
19
|
* └─ on 409: adopt server blob from response, overwrite cache, notify
|
|
20
|
-
* (API-Always-Wins per docs/planning/unified-prefs-2026-05-20.md)
|
|
20
|
+
* (API-Always-Wins per docs/planning/unified-prefs-2026-05-20.md),
|
|
21
|
+
* and reject the save()/flush() waiting on that patch
|
|
21
22
|
*
|
|
22
23
|
* subscribe(listener)
|
|
23
24
|
* ├─ stash listener in a Set
|
package/dist/index.js
CHANGED
|
@@ -105,6 +105,20 @@ function isUuid(s) {
|
|
|
105
105
|
return UUID_RE.test(s);
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
// src/types.ts
|
|
109
|
+
var PrefsConflictError = class extends Error {
|
|
110
|
+
constructor(patch, scope, serverVersion) {
|
|
111
|
+
super(`prefs-api refused a ${scope}-scope save with 409 (server version ${serverVersion})`);
|
|
112
|
+
this.patch = patch;
|
|
113
|
+
this.scope = scope;
|
|
114
|
+
this.serverVersion = serverVersion;
|
|
115
|
+
}
|
|
116
|
+
patch;
|
|
117
|
+
scope;
|
|
118
|
+
serverVersion;
|
|
119
|
+
name = "PrefsConflictError";
|
|
120
|
+
};
|
|
121
|
+
|
|
108
122
|
// src/whoami.ts
|
|
109
123
|
var ANON_USER_ID = "anon";
|
|
110
124
|
var WHOAMI_GLOBAL = "__hadokuWhoami";
|
|
@@ -131,22 +145,28 @@ function adaptWhoami(body) {
|
|
|
131
145
|
}
|
|
132
146
|
return { userId: UNSCOPED_ID, userType, name, scope: "none", ...verified };
|
|
133
147
|
}
|
|
148
|
+
var WHOAMI_TIMEOUT_MS = 3e3;
|
|
134
149
|
async function fetchWhoamiRaw(url, userKey) {
|
|
135
150
|
const headers = {};
|
|
136
151
|
if (userKey) {
|
|
137
152
|
headers["X-User-Key"] = userKey;
|
|
138
153
|
}
|
|
154
|
+
const ctrl = new AbortController();
|
|
155
|
+
const timer = setTimeout(() => ctrl.abort(), WHOAMI_TIMEOUT_MS);
|
|
139
156
|
try {
|
|
140
157
|
const resp = await fetch(url, {
|
|
141
158
|
method: "GET",
|
|
142
159
|
headers,
|
|
143
160
|
credentials: "include",
|
|
144
|
-
cache: "no-store"
|
|
161
|
+
cache: "no-store",
|
|
162
|
+
signal: ctrl.signal
|
|
145
163
|
});
|
|
146
164
|
if (!resp.ok) return null;
|
|
147
165
|
return await resp.json();
|
|
148
166
|
} catch {
|
|
149
167
|
return null;
|
|
168
|
+
} finally {
|
|
169
|
+
clearTimeout(timer);
|
|
150
170
|
}
|
|
151
171
|
}
|
|
152
172
|
function defaultWhoamiUrl() {
|
|
@@ -188,11 +208,11 @@ function createPrefsClient(opts) {
|
|
|
188
208
|
let currentBlob = null;
|
|
189
209
|
let userVersion = 0;
|
|
190
210
|
let deviceVersion = 0;
|
|
191
|
-
let
|
|
192
|
-
|
|
211
|
+
let queued = [];
|
|
212
|
+
const unsettled = /* @__PURE__ */ new Set();
|
|
213
|
+
let sendChain = Promise.resolve();
|
|
193
214
|
const dirtyFields = /* @__PURE__ */ new Set();
|
|
194
215
|
let saveTimer = null;
|
|
195
|
-
let savePromise = null;
|
|
196
216
|
let initPromise = null;
|
|
197
217
|
let bcast = null;
|
|
198
218
|
let destroyed = false;
|
|
@@ -371,60 +391,77 @@ function createPrefsClient(opts) {
|
|
|
371
391
|
notify(currentBlob);
|
|
372
392
|
broadcast(currentBlob);
|
|
373
393
|
}
|
|
394
|
+
function newBatch(scope, expected, patch = {}) {
|
|
395
|
+
let settle;
|
|
396
|
+
const done = new Promise((resolve) => {
|
|
397
|
+
settle = resolve;
|
|
398
|
+
});
|
|
399
|
+
const batch = { patch, scope, expected, done, settle };
|
|
400
|
+
unsettled.add(batch);
|
|
401
|
+
return batch;
|
|
402
|
+
}
|
|
374
403
|
function scheduleFlush() {
|
|
375
404
|
if (saveTimer) clearTimeout(saveTimer);
|
|
376
|
-
saveTimer = setTimeout(
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
}
|
|
380
|
-
async function flushPending() {
|
|
381
|
-
if (Object.keys(pendingPatch).length === 0) return;
|
|
382
|
-
if (savePromise) {
|
|
383
|
-
await savePromise;
|
|
384
|
-
}
|
|
385
|
-
const patchSnapshot = pendingPatch;
|
|
386
|
-
const scopeSnapshot = pendingScope;
|
|
387
|
-
pendingPatch = {};
|
|
405
|
+
saveTimer = setTimeout(dispatchQueued, SAVE_DEBOUNCE_MS);
|
|
406
|
+
}
|
|
407
|
+
function dispatchQueued() {
|
|
388
408
|
if (saveTimer) {
|
|
389
409
|
clearTimeout(saveTimer);
|
|
390
410
|
saveTimer = null;
|
|
391
411
|
}
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
412
|
+
const batches = queued;
|
|
413
|
+
queued = [];
|
|
414
|
+
for (const batch of batches) {
|
|
415
|
+
sendChain = sendChain.then(() => send(batch));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function clearDirty(patch) {
|
|
419
|
+
for (const key of Object.keys(patch)) {
|
|
420
|
+
let stillPending = false;
|
|
421
|
+
for (const other of unsettled) {
|
|
422
|
+
if (key in other.patch) stillPending = true;
|
|
395
423
|
}
|
|
424
|
+
if (!stillPending) dirtyFields.delete(key);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
async function send(batch) {
|
|
428
|
+
if (!canSync()) {
|
|
429
|
+
unsettled.delete(batch);
|
|
430
|
+
clearDirty(batch.patch);
|
|
431
|
+
batch.settle(null);
|
|
396
432
|
return;
|
|
397
433
|
}
|
|
398
|
-
const expectedVersion =
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
await refreshFromServer();
|
|
409
|
-
} else {
|
|
410
|
-
if (scopeSnapshot === "user") {
|
|
411
|
-
userVersion = result.conflict.version;
|
|
412
|
-
} else {
|
|
413
|
-
deviceVersion = result.conflict.version;
|
|
414
|
-
}
|
|
415
|
-
await refreshFromServer();
|
|
416
|
-
}
|
|
417
|
-
for (const key of Object.keys(patchSnapshot)) {
|
|
418
|
-
if (!(key in pendingPatch)) dirtyFields.delete(key);
|
|
419
|
-
}
|
|
420
|
-
} catch {
|
|
421
|
-
pendingPatch = { ...patchSnapshot, ...pendingPatch };
|
|
422
|
-
pendingScope = scopeSnapshot;
|
|
423
|
-
} finally {
|
|
424
|
-
savePromise = null;
|
|
434
|
+
const expectedVersion = batch.expected === void 0 ? batch.scope === "user" ? userVersion : deviceVersion : batch.expected ?? void 0;
|
|
435
|
+
let conflict = null;
|
|
436
|
+
try {
|
|
437
|
+
const result = await putToServer(batch.scope, batch.patch, expectedVersion);
|
|
438
|
+
const version = result.ok ? result.row.version : result.conflict.version;
|
|
439
|
+
if ((result.ok ? result.scope : batch.scope) === "user") {
|
|
440
|
+
userVersion = version;
|
|
441
|
+
} else {
|
|
442
|
+
deviceVersion = version;
|
|
425
443
|
}
|
|
426
|
-
|
|
427
|
-
|
|
444
|
+
if (!result.ok) {
|
|
445
|
+
conflict = new PrefsConflictError(batch.patch, batch.scope, version);
|
|
446
|
+
}
|
|
447
|
+
} catch {
|
|
448
|
+
unsettled.delete(batch);
|
|
449
|
+
const front = queued[0];
|
|
450
|
+
if (front && front.scope === batch.scope && front.expected === batch.expected) {
|
|
451
|
+
front.patch = { ...batch.patch, ...front.patch };
|
|
452
|
+
} else {
|
|
453
|
+
queued.unshift(newBatch(batch.scope, batch.expected, batch.patch));
|
|
454
|
+
}
|
|
455
|
+
batch.settle(null);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
unsettled.delete(batch);
|
|
459
|
+
clearDirty(batch.patch);
|
|
460
|
+
try {
|
|
461
|
+
await refreshFromServer();
|
|
462
|
+
} catch {
|
|
463
|
+
}
|
|
464
|
+
batch.settle(conflict);
|
|
428
465
|
}
|
|
429
466
|
const client = {
|
|
430
467
|
appId: opts.appId,
|
|
@@ -458,14 +495,21 @@ function createPrefsClient(opts) {
|
|
|
458
495
|
mirrorBootstrap(nextBlob);
|
|
459
496
|
notify(nextBlob);
|
|
460
497
|
broadcast(nextBlob);
|
|
461
|
-
|
|
462
|
-
|
|
498
|
+
const expected = saveOpts?.expectedVersion;
|
|
499
|
+
const last = queued[queued.length - 1];
|
|
500
|
+
let batch;
|
|
501
|
+
if (last && last.scope === scope && last.expected === void 0 && expected === void 0) {
|
|
502
|
+
batch = last;
|
|
503
|
+
} else {
|
|
504
|
+
batch = newBatch(scope, expected);
|
|
505
|
+
queued.push(batch);
|
|
463
506
|
}
|
|
464
|
-
|
|
465
|
-
pendingScope = scope;
|
|
507
|
+
batch.patch = { ...batch.patch, ...patch };
|
|
466
508
|
for (const key of Object.keys(patch)) dirtyFields.add(key);
|
|
467
|
-
if (
|
|
468
|
-
|
|
509
|
+
if (expected !== void 0) {
|
|
510
|
+
dispatchQueued();
|
|
511
|
+
const conflict = await batch.done;
|
|
512
|
+
if (conflict) throw conflict;
|
|
469
513
|
} else {
|
|
470
514
|
scheduleFlush();
|
|
471
515
|
}
|
|
@@ -500,7 +544,11 @@ function createPrefsClient(opts) {
|
|
|
500
544
|
await storage.remove(anonKey);
|
|
501
545
|
},
|
|
502
546
|
async flush() {
|
|
503
|
-
|
|
547
|
+
const waiting = [...unsettled];
|
|
548
|
+
dispatchQueued();
|
|
549
|
+
const conflicts = await Promise.all(waiting.map((b) => b.done));
|
|
550
|
+
const conflict = conflicts.find((c) => c !== null);
|
|
551
|
+
if (conflict) throw conflict;
|
|
504
552
|
},
|
|
505
553
|
destroy() {
|
|
506
554
|
if (destroyed) return;
|
|
@@ -517,6 +565,7 @@ export {
|
|
|
517
565
|
CACHE_KEY_PREFIX,
|
|
518
566
|
DEVICE_ID_KEY,
|
|
519
567
|
PREFS_API_BASE,
|
|
568
|
+
PrefsConflictError,
|
|
520
569
|
SAVE_DEBOUNCE_MS,
|
|
521
570
|
capacitorStorage,
|
|
522
571
|
createPrefsClient,
|
package/dist/react.d.ts
CHANGED
|
@@ -136,11 +136,40 @@ interface SaveOptions {
|
|
|
136
136
|
/** Default: 'user'. Use 'device' for per-device-only fields like theme. */
|
|
137
137
|
scope?: Scope;
|
|
138
138
|
/**
|
|
139
|
-
* Override the auto-managed expectedVersion
|
|
140
|
-
*
|
|
141
|
-
*
|
|
139
|
+
* Override the auto-managed expectedVersion for THIS patch.
|
|
140
|
+
*
|
|
141
|
+
* Left undefined, the SDK sends the last server version it has seen for the
|
|
142
|
+
* scope — 0 on a client that has not read the row yet, which prefs-api
|
|
143
|
+
* answers with 409 for any row that exists.
|
|
144
|
+
*
|
|
145
|
+
* - a number is sent as-is (`0` writes only if the row does not exist yet);
|
|
146
|
+
* - `null` sends no version at all: last write wins, prefs-api's contract
|
|
147
|
+
* for an omitted version. Use it for a pick the user just made on a page
|
|
148
|
+
* that need not have read the row first.
|
|
149
|
+
*
|
|
150
|
+
* Either way the patch is sent on its own and at once — never coalesced with
|
|
151
|
+
* a debounced batch — and save() rejects with {@link PrefsConflictError} if
|
|
152
|
+
* prefs-api refused it with 409.
|
|
142
153
|
*/
|
|
143
|
-
expectedVersion?: number;
|
|
154
|
+
expectedVersion?: number | null;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* A patch prefs-api refused with 409 because the row's version had moved. The
|
|
158
|
+
* client has already adopted the server's row (the API-wins rule) and dropped
|
|
159
|
+
* the patch; this tells the caller the save did not happen.
|
|
160
|
+
*/
|
|
161
|
+
declare class PrefsConflictError extends Error {
|
|
162
|
+
/** The patch that was dropped. */
|
|
163
|
+
readonly patch: Record<string, unknown>;
|
|
164
|
+
readonly scope: Scope;
|
|
165
|
+
/** The row's version on the server, which the client now holds. */
|
|
166
|
+
readonly serverVersion: number;
|
|
167
|
+
readonly name = "PrefsConflictError";
|
|
168
|
+
constructor(
|
|
169
|
+
/** The patch that was dropped. */
|
|
170
|
+
patch: Record<string, unknown>, scope: Scope,
|
|
171
|
+
/** The row's version on the server, which the client now holds. */
|
|
172
|
+
serverVersion: number);
|
|
144
173
|
}
|
|
145
174
|
/**
|
|
146
175
|
* `T` is the app's prefs blob (a `z.infer` of its schema). It is intentionally
|
|
@@ -162,7 +191,10 @@ interface PrefsClient<T> {
|
|
|
162
191
|
read(): Promise<T>;
|
|
163
192
|
/**
|
|
164
193
|
* Apply a partial patch. Coalesced via a 1s debounce so a slider that
|
|
165
|
-
* fires 30 onChange events in two seconds only PUTs twice.
|
|
194
|
+
* fires 30 onChange events in two seconds only PUTs twice. Resolves once
|
|
195
|
+
* the patch is applied locally; with an explicit `expectedVersion` it
|
|
196
|
+
* instead waits for the PUT and rejects with {@link PrefsConflictError} on
|
|
197
|
+
* a 409.
|
|
166
198
|
*/
|
|
167
199
|
save(patch: Partial<T>, opts?: SaveOptions): Promise<void>;
|
|
168
200
|
/** Subscribe to changes (incl. cross-tab via BroadcastChannel). */
|
|
@@ -181,10 +213,16 @@ interface PrefsClient<T> {
|
|
|
181
213
|
* unconditionally on sign-in; it decides for itself.
|
|
182
214
|
*/
|
|
183
215
|
promoteAnonPrefsToUser(): Promise<void>;
|
|
184
|
-
/**
|
|
216
|
+
/**
|
|
217
|
+
* Send every queued patch now and wait for it, and for any already in
|
|
218
|
+
* flight, to settle. Rejects with {@link PrefsConflictError} if prefs-api
|
|
219
|
+
* refused one of them with 409 (its fields now show the server's value). A
|
|
220
|
+
* network failure does not reject: that patch stays queued for the next
|
|
221
|
+
* save. For beforeunload, call it as `void client.flush().catch(...)`.
|
|
222
|
+
*/
|
|
185
223
|
flush(): Promise<void>;
|
|
186
224
|
/** Tear down (cancels timers, closes BroadcastChannel). */
|
|
187
225
|
destroy(): void;
|
|
188
226
|
}
|
|
189
227
|
|
|
190
|
-
export { type AsyncStorage as A, type PrefsClientOptions as P, type SaveOptions as S, type PrefsClient as a, type PrefsMigration as
|
|
228
|
+
export { type AsyncStorage as A, type PrefsClientOptions as P, type SaveOptions as S, type PrefsClient as a, PrefsConflictError as b, type PrefsMigration as c, type PrefsRow as d, type Scope as e, type ServerReadResult as f, capacitorStorage as g, detectStorage as h, localStorageAdapter as l, memoryStorage as m, sessionStorageWrite as s };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/prefs-client",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "1.1.25",
|
|
4
|
+
"gitHead": "155e8fbf36a57da2948b06923ae8dba64a88e09c",
|
|
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).",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/index.js",
|