local-replica 0.0.0 → 0.0.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 +152 -2
- package/dist/createReplicaEngine-CdR-URHo.js +2018 -0
- package/dist/createReplicaEngine-CdR-URHo.js.map +1 -0
- package/dist/index-DsElitHD.d.ts +856 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +281 -0
- package/dist/index.js.map +1 -0
- package/dist/zustand/index.d.ts +353 -1
- package/dist/zustand/index.js +641 -0
- package/dist/zustand/index.js.map +1 -0
- package/package.json +10 -1
package/dist/zustand/index.js
CHANGED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
import { S as stableQueryKey, t as createReplicaEngine, v as isReplicaSyncKey, y as replicaKeys } from "../createReplicaEngine-CdR-URHo.js";
|
|
2
|
+
import { useEffect, useLayoutEffect, useRef } from "react";
|
|
3
|
+
// src/zustand/errors.ts
|
|
4
|
+
/** `slice.fetch` was asked to fetch for a scope that is no longer active. */
|
|
5
|
+
var ReplicaScopeChangedError = class extends Error {
|
|
6
|
+
constructor(name, scope) {
|
|
7
|
+
super(`[replica] ${name}: scope ${scope} is no longer active`);
|
|
8
|
+
this.name = "ReplicaScopeChangedError";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
// src/zustand/lens.ts
|
|
12
|
+
/**
|
|
13
|
+
* Apply every view write as ONE host update, so subscribers never observe a
|
|
14
|
+
* view out of step with its bookkeeping. Consecutive key writes go through
|
|
15
|
+
* the lens' `setMany` when it has one, so seeding N rows clones the backing
|
|
16
|
+
* field once instead of N times.
|
|
17
|
+
*/
|
|
18
|
+
const applyLensWrites = (view, state, writes) => {
|
|
19
|
+
let patch = {};
|
|
20
|
+
let current = state;
|
|
21
|
+
let pending = [];
|
|
22
|
+
const flush = () => {
|
|
23
|
+
if (pending.length === 0) return;
|
|
24
|
+
const entries = pending;
|
|
25
|
+
pending = [];
|
|
26
|
+
if (view.setMany && entries.length > 1) {
|
|
27
|
+
const next = view.setMany(current, entries);
|
|
28
|
+
patch = {
|
|
29
|
+
...patch,
|
|
30
|
+
...next
|
|
31
|
+
};
|
|
32
|
+
current = {
|
|
33
|
+
...current,
|
|
34
|
+
...next
|
|
35
|
+
};
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
for (const entry of entries) {
|
|
39
|
+
const next = view.set(current, entry.key, entry.data);
|
|
40
|
+
patch = {
|
|
41
|
+
...patch,
|
|
42
|
+
...next
|
|
43
|
+
};
|
|
44
|
+
current = {
|
|
45
|
+
...current,
|
|
46
|
+
...next
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
for (const write of writes) if ("type" in write) {
|
|
51
|
+
flush();
|
|
52
|
+
const next = view.clear(current);
|
|
53
|
+
patch = {
|
|
54
|
+
...patch,
|
|
55
|
+
...next
|
|
56
|
+
};
|
|
57
|
+
current = {
|
|
58
|
+
...current,
|
|
59
|
+
...next
|
|
60
|
+
};
|
|
61
|
+
} else pending.push({
|
|
62
|
+
data: write.data,
|
|
63
|
+
key: write.key
|
|
64
|
+
});
|
|
65
|
+
flush();
|
|
66
|
+
return patch;
|
|
67
|
+
};
|
|
68
|
+
/** Lens for the common case: a `Record<key, TData>` field on the store. */
|
|
69
|
+
const recordLens = (field) => ({
|
|
70
|
+
clear: () => ({ [field]: {} }),
|
|
71
|
+
get: (state, key) => state[field]?.[key],
|
|
72
|
+
keys: (state) => Object.keys(state[field] ?? {}),
|
|
73
|
+
set: (state, key, data) => {
|
|
74
|
+
const next = { ...state[field] };
|
|
75
|
+
if (data === void 0) delete next[key];
|
|
76
|
+
else next[key] = data;
|
|
77
|
+
return { [field]: next };
|
|
78
|
+
},
|
|
79
|
+
setMany: (state, entries) => {
|
|
80
|
+
const next = { ...state[field] };
|
|
81
|
+
for (const { key, data } of entries) if (data === void 0) delete next[key];
|
|
82
|
+
else next[key] = data;
|
|
83
|
+
return { [field]: next };
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
/**
|
|
87
|
+
* Lens for a paged view split across store fields: the rows stay where
|
|
88
|
+
* existing readers expect them (`itemsField[key]`, a plain array), the paging
|
|
89
|
+
* bookkeeping lives in `metaField[key]`, and `derive` recomputes fields built
|
|
90
|
+
* from the rows (e.g. a parsed display list) in the same commit — so a derived
|
|
91
|
+
* field is never one frame behind its rows.
|
|
92
|
+
*
|
|
93
|
+
* Rows seeded without bookkeeping (by code outside the replica) read as a
|
|
94
|
+
* single head page.
|
|
95
|
+
*/
|
|
96
|
+
const splitPagedLens = ({ clearDerived, derive, itemsField, metaField }) => {
|
|
97
|
+
const NO_META = {};
|
|
98
|
+
const views = /* @__PURE__ */ new WeakMap();
|
|
99
|
+
const remember = (items, meta, view) => {
|
|
100
|
+
let byMeta = views.get(items);
|
|
101
|
+
if (!byMeta) views.set(items, byMeta = /* @__PURE__ */ new WeakMap());
|
|
102
|
+
byMeta.set(meta, view);
|
|
103
|
+
return view;
|
|
104
|
+
};
|
|
105
|
+
const rowsOf = (state) => state[itemsField] ?? {};
|
|
106
|
+
const metaOf = (state) => state[metaField] ?? {};
|
|
107
|
+
return {
|
|
108
|
+
clear: () => ({
|
|
109
|
+
[itemsField]: {},
|
|
110
|
+
[metaField]: {},
|
|
111
|
+
...clearDerived?.()
|
|
112
|
+
}),
|
|
113
|
+
get: (state, key) => {
|
|
114
|
+
const items = rowsOf(state)[key];
|
|
115
|
+
if (!items) return void 0;
|
|
116
|
+
const meta = metaOf(state)[key] ?? NO_META;
|
|
117
|
+
const cached = views.get(items)?.get(meta);
|
|
118
|
+
if (cached) return cached;
|
|
119
|
+
const view = meta === NO_META ? {
|
|
120
|
+
currentPage: 0,
|
|
121
|
+
hasMore: true,
|
|
122
|
+
items,
|
|
123
|
+
pageSize: items.length
|
|
124
|
+
} : {
|
|
125
|
+
...meta,
|
|
126
|
+
items
|
|
127
|
+
};
|
|
128
|
+
return remember(items, meta, view);
|
|
129
|
+
},
|
|
130
|
+
keys: (state) => Object.keys(rowsOf(state)),
|
|
131
|
+
set: (state, key, data) => {
|
|
132
|
+
const rows = { ...rowsOf(state) };
|
|
133
|
+
const metas = { ...metaOf(state) };
|
|
134
|
+
if (data === void 0) {
|
|
135
|
+
delete rows[key];
|
|
136
|
+
delete metas[key];
|
|
137
|
+
} else {
|
|
138
|
+
const { items, ...meta } = data;
|
|
139
|
+
rows[key] = items;
|
|
140
|
+
metas[key] = meta;
|
|
141
|
+
remember(items, meta, data);
|
|
142
|
+
}
|
|
143
|
+
const next = {
|
|
144
|
+
...state,
|
|
145
|
+
[itemsField]: rows,
|
|
146
|
+
[metaField]: metas
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
[itemsField]: rows,
|
|
150
|
+
[metaField]: metas,
|
|
151
|
+
...derive?.(next, key, data?.items)
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
// src/zustand/requests.ts
|
|
157
|
+
/** Request id of a sync key in a scope: requests of the same id dedupe and supersede. */
|
|
158
|
+
const replicaRequestId = (scope, syncKey) => `${scope}\u0000${stableQueryKey(syncKey)}`;
|
|
159
|
+
/**
|
|
160
|
+
* Lifecycle bookkeeping of head requests: capture (`begin`), send and track in
|
|
161
|
+
* flight, retire older requests once a newer response applied, and settle each
|
|
162
|
+
* request exactly once. What settling *does* is the slice's `fold`; this only
|
|
163
|
+
* guarantees every path — a mounted `useSync`, or `fetch` with no view mounted
|
|
164
|
+
* — goes through it the same way.
|
|
165
|
+
*/
|
|
166
|
+
const createRequests = ({ clearGeneration, fetcher, fold, removalGeneration, resource }) => {
|
|
167
|
+
let requestSeq = 0;
|
|
168
|
+
/**
|
|
169
|
+
* Requests whose start order is at or below this number are retired, per
|
|
170
|
+
* request id: a newer response already applied, or a `fresh` fetch started
|
|
171
|
+
* after them. Their late response would repaint an older value.
|
|
172
|
+
*
|
|
173
|
+
* An entry only matters while a request it retires is still unsettled:
|
|
174
|
+
* every request started later has a higher sequence, so a missing entry
|
|
175
|
+
* (read as 0) admits exactly the same responses. Entries are pruned as soon
|
|
176
|
+
* as no sent request at or below them is pending, so the map holds only the
|
|
177
|
+
* ids with an older request in flight.
|
|
178
|
+
*/
|
|
179
|
+
const retiredThrough = /* @__PURE__ */ new Map();
|
|
180
|
+
/** Sequences of the sent requests that have not settled yet, per request id. */
|
|
181
|
+
const unsettled = /* @__PURE__ */ new Map();
|
|
182
|
+
/** Drop the retirement of `requestId` once no request it retires is pending. */
|
|
183
|
+
const pruneRetired = (requestId) => {
|
|
184
|
+
const through = retiredThrough.get(requestId);
|
|
185
|
+
if (through === void 0) return;
|
|
186
|
+
for (const seq of unsettled.get(requestId) ?? []) if (seq <= through) return;
|
|
187
|
+
retiredThrough.delete(requestId);
|
|
188
|
+
};
|
|
189
|
+
const retire = (requestId, seq) => {
|
|
190
|
+
if ((retiredThrough.get(requestId) ?? 0) < seq) retiredThrough.set(requestId, seq);
|
|
191
|
+
pruneRetired(requestId);
|
|
192
|
+
};
|
|
193
|
+
/** A newer response already applied, or a `fresh` fetch started after it. */
|
|
194
|
+
const isRetired = ({ requestId, seq }) => seq <= (retiredThrough.get(requestId) ?? 0);
|
|
195
|
+
const trackUnsettled = ({ requestId, seq }) => {
|
|
196
|
+
const pending = unsettled.get(requestId) ?? /* @__PURE__ */ new Set();
|
|
197
|
+
unsettled.set(requestId, pending);
|
|
198
|
+
pending.add(seq);
|
|
199
|
+
};
|
|
200
|
+
const untrackUnsettled = ({ requestId, seq }) => {
|
|
201
|
+
const pending = unsettled.get(requestId);
|
|
202
|
+
if (!pending?.delete(seq)) return;
|
|
203
|
+
if (pending.size === 0) unsettled.delete(requestId);
|
|
204
|
+
pruneRetired(requestId);
|
|
205
|
+
};
|
|
206
|
+
/** The latest request in flight per id, which a non-`fresh` `fetch` joins. */
|
|
207
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
208
|
+
/** `useSync` requests in flight per id (`fetch` seeds the driver only while none is). */
|
|
209
|
+
const syncInflight = /* @__PURE__ */ new Map();
|
|
210
|
+
/**
|
|
211
|
+
* `useSync` request each sync id last started, settled by the driver's
|
|
212
|
+
* callback. The driver settles one request per key at a time (a newer
|
|
213
|
+
* request supersedes the older one), so the latest start is the one that
|
|
214
|
+
* settles.
|
|
215
|
+
*/
|
|
216
|
+
const syncRequests = /* @__PURE__ */ new Map();
|
|
217
|
+
const syncKeyOf = (params, scope, key) => resource.syncKey?.(params) ?? replicaKeys.sync(resource.name, resource.version, scope, key, params);
|
|
218
|
+
/** Capture what a head request for `params` started under. */
|
|
219
|
+
const begin = (params, scope, source) => {
|
|
220
|
+
const key = resource.key(params);
|
|
221
|
+
const syncKey = syncKeyOf(params, scope, key);
|
|
222
|
+
return {
|
|
223
|
+
clearGeneration: clearGeneration(scope),
|
|
224
|
+
key,
|
|
225
|
+
params,
|
|
226
|
+
queryKey: resource.storageKey(params),
|
|
227
|
+
removalGeneration: removalGeneration(scope, key),
|
|
228
|
+
requestId: replicaRequestId(scope, syncKey),
|
|
229
|
+
scope,
|
|
230
|
+
seq: ++requestSeq,
|
|
231
|
+
source,
|
|
232
|
+
syncKey
|
|
233
|
+
};
|
|
234
|
+
};
|
|
235
|
+
/** Send the request and track it in flight until it settles. */
|
|
236
|
+
const send = (request) => {
|
|
237
|
+
const { requestId } = request;
|
|
238
|
+
const sent = fetcher(request.params, void 0);
|
|
239
|
+
const promise = Promise.resolve(sent);
|
|
240
|
+
request.promise = promise;
|
|
241
|
+
trackUnsettled(request);
|
|
242
|
+
inflight.set(requestId, request);
|
|
243
|
+
if (request.source === "sync") syncInflight.set(requestId, (syncInflight.get(requestId) ?? 0) + 1);
|
|
244
|
+
const done = () => {
|
|
245
|
+
if (inflight.get(requestId) === request) inflight.delete(requestId);
|
|
246
|
+
if (request.source !== "sync") return;
|
|
247
|
+
const count = syncInflight.get(requestId) - 1;
|
|
248
|
+
if (count > 0) syncInflight.set(requestId, count);
|
|
249
|
+
else syncInflight.delete(requestId);
|
|
250
|
+
};
|
|
251
|
+
promise.then(done, done);
|
|
252
|
+
if (request.source === "sync") promise.then((data) => settle(request, { data }), (error) => settle(request, { error }));
|
|
253
|
+
return sent;
|
|
254
|
+
};
|
|
255
|
+
/**
|
|
256
|
+
* Fold a settled head request into the replica (see the slice's `fold`). A
|
|
257
|
+
* request is settled once: a `fetch` that joined a `useSync` request shares
|
|
258
|
+
* its result.
|
|
259
|
+
*/
|
|
260
|
+
const settle = (request, outcome) => {
|
|
261
|
+
if (request.settled) return request.settled;
|
|
262
|
+
request.settledWith = "error" in outcome ? outcome.error : outcome.data;
|
|
263
|
+
request.settled = fold(request, outcome);
|
|
264
|
+
untrackUnsettled(request);
|
|
265
|
+
if (request.source === "sync") releaseSyncRequest(request);
|
|
266
|
+
return request.settled;
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* Drop a settled `useSync` request's record once its driver callback had its
|
|
270
|
+
* chance to read it. The record is normally taken by that callback, but the
|
|
271
|
+
* driver skips it when the hook changed key, unmounted or was superseded —
|
|
272
|
+
* the request still settles on its own promise, and its record (holding the
|
|
273
|
+
* response) must not stay behind. A driver runs the callback in the same
|
|
274
|
+
* turn the response resolves (SWR does, in microtasks), so a macrotask later
|
|
275
|
+
* the record is only a leak.
|
|
276
|
+
*/
|
|
277
|
+
const releaseSyncRequest = (request) => {
|
|
278
|
+
setTimeout(() => {
|
|
279
|
+
if (syncRequests.get(request.requestId) === request) syncRequests.delete(request.requestId);
|
|
280
|
+
}, 0);
|
|
281
|
+
};
|
|
282
|
+
/** Start a `useSync` request and record it for the driver's callback. */
|
|
283
|
+
const startSync = (params, scope) => {
|
|
284
|
+
const request = begin(params, scope, "sync");
|
|
285
|
+
syncRequests.set(request.requestId, request);
|
|
286
|
+
return send(request);
|
|
287
|
+
};
|
|
288
|
+
/**
|
|
289
|
+
* The `useSync` request settling now: the one `requestId` last started. A
|
|
290
|
+
* response the driver settles without having run our fetcher (a
|
|
291
|
+
* cache-shared key), or one the recorded request did not produce, is
|
|
292
|
+
* captured now: nothing it started under is known.
|
|
293
|
+
*/
|
|
294
|
+
const takeSyncRequest = (requestId, response, params, scope) => {
|
|
295
|
+
const request = syncRequests.get(requestId);
|
|
296
|
+
syncRequests.delete(requestId);
|
|
297
|
+
if (request && (!request.settled || request.settledWith === response)) return request;
|
|
298
|
+
return begin(params, scope, "sync");
|
|
299
|
+
};
|
|
300
|
+
return {
|
|
301
|
+
begin,
|
|
302
|
+
/** Records of `useSync` requests not yet released (leak checks in tests). */
|
|
303
|
+
debugPendingSyncRequests: () => syncRequests.size,
|
|
304
|
+
/** Retirement records still held (leak checks in tests). */
|
|
305
|
+
debugRetiredRequests: () => retiredThrough.size,
|
|
306
|
+
/** The request in flight for `requestId`, which a non-`fresh` `fetch` joins. */
|
|
307
|
+
inflight: (requestId) => inflight.get(requestId),
|
|
308
|
+
isRetired,
|
|
309
|
+
/** Whether a `useSync` request of `requestId` is in flight. */
|
|
310
|
+
isSyncInflight: (requestId) => syncInflight.has(requestId),
|
|
311
|
+
retire,
|
|
312
|
+
send,
|
|
313
|
+
settle,
|
|
314
|
+
startSync,
|
|
315
|
+
syncKeyOf,
|
|
316
|
+
takeSyncRequest
|
|
317
|
+
};
|
|
318
|
+
};
|
|
319
|
+
// src/zustand/useSync.ts
|
|
320
|
+
/**
|
|
321
|
+
* Hydrates the persisted row once per scope/key/query, then lets the driver
|
|
322
|
+
* fetch and revalidate the head. Read the data from the store.
|
|
323
|
+
*/
|
|
324
|
+
const createUseSync = ({ driver, engine: { ensureScope, fetcher, hydrate, retain }, get, headQuery, requests, resource, view }) => {
|
|
325
|
+
/**
|
|
326
|
+
* Entries (`scope` + key) whose one-shot hydration actually painted a
|
|
327
|
+
* persisted row. The hydration query settles `true` on a cache miss too, so
|
|
328
|
+
* a reactivated key may only replay `onHydrated` when its row really came from
|
|
329
|
+
* storage — not off a provisional seed or another source that happens to sit
|
|
330
|
+
* in the view.
|
|
331
|
+
*/
|
|
332
|
+
const hydratedEntries = /* @__PURE__ */ new Set();
|
|
333
|
+
const hydratedEntryId = (scope, key) => `${scope}\u0000${key}`;
|
|
334
|
+
const useSync = (params, { enabled = true, onError, onHydrated, onSuccess, ...schedule } = {}) => {
|
|
335
|
+
const scope = resource.scope.use();
|
|
336
|
+
const key = params ? resource.key(params) : void 0;
|
|
337
|
+
const active = enabled && !!params && key !== void 0;
|
|
338
|
+
const queryKey = params ? resource.storageKey(params) : void 0;
|
|
339
|
+
useLayoutEffect(() => {
|
|
340
|
+
if (active) ensureScope(scope);
|
|
341
|
+
}, [active, scope]);
|
|
342
|
+
useLayoutEffect(() => {
|
|
343
|
+
if (active && key !== void 0 && queryKey !== void 0) headQuery.set(key, queryKey);
|
|
344
|
+
}, [
|
|
345
|
+
active,
|
|
346
|
+
key,
|
|
347
|
+
queryKey
|
|
348
|
+
]);
|
|
349
|
+
useLayoutEffect(() => {
|
|
350
|
+
if (active && key !== void 0 && queryKey !== void 0) return retain(key, queryKey);
|
|
351
|
+
}, [
|
|
352
|
+
active,
|
|
353
|
+
key,
|
|
354
|
+
queryKey
|
|
355
|
+
]);
|
|
356
|
+
const activeKey = useRef(void 0);
|
|
357
|
+
const hydratedKey = useRef(void 0);
|
|
358
|
+
useLayoutEffect(() => {
|
|
359
|
+
activeKey.current = active ? key : void 0;
|
|
360
|
+
hydratedKey.current = void 0;
|
|
361
|
+
}, [
|
|
362
|
+
active,
|
|
363
|
+
key,
|
|
364
|
+
scope
|
|
365
|
+
]);
|
|
366
|
+
const hydration = driver.useQuery(active && resource.persisted && resource.persistKey(key) ? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params)) : null, async () => {
|
|
367
|
+
const didHydrate = await hydrate(params, scope);
|
|
368
|
+
if (didHydrate) hydratedEntries.add(hydratedEntryId(scope, key));
|
|
369
|
+
if (activeKey.current !== key) return true;
|
|
370
|
+
hydratedKey.current = hydratedEntryId(scope, key);
|
|
371
|
+
if (didHydrate) {
|
|
372
|
+
const hydrated = view.get(get(), key);
|
|
373
|
+
if (hydrated !== void 0) onHydrated?.(hydrated);
|
|
374
|
+
}
|
|
375
|
+
return true;
|
|
376
|
+
}, { once: true });
|
|
377
|
+
useEffect(() => {
|
|
378
|
+
if (!active || key === void 0 || hydration.data !== true) return;
|
|
379
|
+
const entry = hydratedEntryId(scope, key);
|
|
380
|
+
if (hydratedKey.current === entry) return;
|
|
381
|
+
hydratedKey.current = entry;
|
|
382
|
+
const current = view.get(get(), key);
|
|
383
|
+
if (current !== void 0) {
|
|
384
|
+
if (hydratedEntries.has(entry)) onHydrated?.(current);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
hydrate(params, scope).then((didHydrate) => {
|
|
388
|
+
if (!didHydrate) return;
|
|
389
|
+
hydratedEntries.add(entry);
|
|
390
|
+
if (activeKey.current !== key || resource.scope.get() !== scope) return;
|
|
391
|
+
const hydrated = view.get(get(), key);
|
|
392
|
+
if (hydrated !== void 0) onHydrated?.(hydrated);
|
|
393
|
+
});
|
|
394
|
+
}, [
|
|
395
|
+
active,
|
|
396
|
+
key,
|
|
397
|
+
scope,
|
|
398
|
+
hydration.data
|
|
399
|
+
]);
|
|
400
|
+
const syncKey = active && fetcher ? requests.syncKeyOf(params, scope, key) : null;
|
|
401
|
+
/** The request settling now: the one this sync id last started. */
|
|
402
|
+
const takeRequest = (response) => requests.takeSyncRequest(replicaRequestId(scope, syncKey), response, params, scope);
|
|
403
|
+
const sync = driver.useQuery(syncKey, () => requests.startSync(params, scope), {
|
|
404
|
+
...schedule,
|
|
405
|
+
onError: (error) => {
|
|
406
|
+
const settled = requests.settle(takeRequest(error), { error });
|
|
407
|
+
if (settled.current) onError?.(error, {
|
|
408
|
+
isActive: settled.isActive,
|
|
409
|
+
key,
|
|
410
|
+
scope
|
|
411
|
+
});
|
|
412
|
+
},
|
|
413
|
+
onSuccess: (data) => {
|
|
414
|
+
const settled = requests.settle(takeRequest(data), { data });
|
|
415
|
+
if (!settled.current || !settled.isActive) return;
|
|
416
|
+
if (activeKey.current !== key) return;
|
|
417
|
+
onSuccess?.(data);
|
|
418
|
+
}
|
|
419
|
+
});
|
|
420
|
+
return {
|
|
421
|
+
error: sync.error,
|
|
422
|
+
isHydrated: key === void 0 || !resource.persisted || !resource.persistKey(key) || hydration.data === true,
|
|
423
|
+
isValidating: sync.isValidating,
|
|
424
|
+
revalidate: () => sync.mutate()
|
|
425
|
+
};
|
|
426
|
+
};
|
|
427
|
+
return useSync;
|
|
428
|
+
};
|
|
429
|
+
// src/zustand/createReplicaSlice.ts
|
|
430
|
+
/**
|
|
431
|
+
* Bind a replica to a domain Zustand store.
|
|
432
|
+
*
|
|
433
|
+
* The domain store stays the only UI source of truth: components read the
|
|
434
|
+
* `view` location through their usual selectors. The engine owns every
|
|
435
|
+
* transition of that location; this slice adds the Zustand port and a
|
|
436
|
+
* `useSync` hook that only orchestrates fetching — data never flows through
|
|
437
|
+
* its return value.
|
|
438
|
+
*/
|
|
439
|
+
const createReplicaSlice = (resource, { driver, effects, get, set, stateKey, view, ...options }) => {
|
|
440
|
+
const revalidate = (key) => driver.revalidate((queryKey) => isReplicaSyncKey(queryKey, resource.name, {
|
|
441
|
+
key,
|
|
442
|
+
scope: resource.scope.get()
|
|
443
|
+
}));
|
|
444
|
+
const engine = createReplicaEngine(resource, {
|
|
445
|
+
...options,
|
|
446
|
+
port: {
|
|
447
|
+
commit: (writes, state, label) => set({
|
|
448
|
+
...applyLensWrites(view, get(), writes),
|
|
449
|
+
[stateKey]: state
|
|
450
|
+
}, false, label),
|
|
451
|
+
getState: () => get()[stateKey],
|
|
452
|
+
keys: view.keys && (() => view.keys(get())),
|
|
453
|
+
read: (key) => view.get(get(), key)
|
|
454
|
+
},
|
|
455
|
+
revalidate
|
|
456
|
+
});
|
|
457
|
+
const { applyHead, clearGeneration, fetcher, isMissingHead, removalGeneration } = engine;
|
|
458
|
+
/**
|
|
459
|
+
* Row key of the head query each entry last asked for. One entry backs a
|
|
460
|
+
* single view, so a response that belongs to a query the entry has already
|
|
461
|
+
* moved past must not repaint it — it would show a superseded query, and a
|
|
462
|
+
* view gated on the current query would then wait forever. Making this an
|
|
463
|
+
* invariant of the slice (not of one driver) keeps it true for drivers that
|
|
464
|
+
* leave a request's own callback live after the query changed.
|
|
465
|
+
*/
|
|
466
|
+
const headQuery = /* @__PURE__ */ new Map();
|
|
467
|
+
const requests = createRequests({
|
|
468
|
+
clearGeneration,
|
|
469
|
+
fetcher,
|
|
470
|
+
fold: (request, outcome) => fold(request, outcome),
|
|
471
|
+
removalGeneration,
|
|
472
|
+
resource
|
|
473
|
+
});
|
|
474
|
+
/**
|
|
475
|
+
* Whether the request still answers the query its entry shows. A `useSync`
|
|
476
|
+
* request must match the query the entry last asked for (see `headQuery`). A
|
|
477
|
+
* `fetch` may also land with no view mounted, but never over a view that
|
|
478
|
+
* shows another query of the key.
|
|
479
|
+
*/
|
|
480
|
+
const isActiveQuery = ({ key, queryKey, source }) => {
|
|
481
|
+
const head = headQuery.get(key);
|
|
482
|
+
return source === "sync" ? head === queryKey : head === void 0 || head === queryKey;
|
|
483
|
+
};
|
|
484
|
+
/**
|
|
485
|
+
* Fold a settled head request into the replica: apply every guard, then
|
|
486
|
+
* `replace` / remove a terminal absence (in the captured scope) / purge one
|
|
487
|
+
* captured off-scope, then run the resource effects.
|
|
488
|
+
*/
|
|
489
|
+
const fold = (request, outcome) => {
|
|
490
|
+
const { key, params, scope } = request;
|
|
491
|
+
/**
|
|
492
|
+
* Whether the entry is still on the scope the request was captured under.
|
|
493
|
+
*
|
|
494
|
+
* A response can settle after an identity/workspace switch. `replace` drops
|
|
495
|
+
* it — the engine refuses off-scope actions — but no side effect may run
|
|
496
|
+
* either: it carries the previous identity's state (onboarding redirect,
|
|
497
|
+
* display snapshot, analytics identify, settings writes). The captured
|
|
498
|
+
* key/scope is not enough on its own, because a switch to a scope that
|
|
499
|
+
* reads the same key/query satisfies the other guards.
|
|
500
|
+
*/
|
|
501
|
+
const isActive = resource.scope.get() === scope;
|
|
502
|
+
const dropped = {
|
|
503
|
+
applied: false,
|
|
504
|
+
current: false,
|
|
505
|
+
isActive,
|
|
506
|
+
missing: false
|
|
507
|
+
};
|
|
508
|
+
if (request.clearGeneration !== clearGeneration(scope) || request.removalGeneration !== removalGeneration(scope, key) || requests.isRetired(request) || !isActiveQuery(request)) return dropped;
|
|
509
|
+
if ("error" in outcome) {
|
|
510
|
+
effects?.onError?.(outcome.error, params, {
|
|
511
|
+
isActive,
|
|
512
|
+
key,
|
|
513
|
+
scope
|
|
514
|
+
});
|
|
515
|
+
return {
|
|
516
|
+
...dropped,
|
|
517
|
+
current: true
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
if (!isActive) {
|
|
521
|
+
const missing = isMissingHead(outcome.data);
|
|
522
|
+
if (missing) {
|
|
523
|
+
remove(key, scope);
|
|
524
|
+
effects?.onPurge?.(params, {
|
|
525
|
+
key,
|
|
526
|
+
scope,
|
|
527
|
+
source: request.source
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
...dropped,
|
|
532
|
+
current: true,
|
|
533
|
+
missing
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
requests.retire(request.requestId, request.seq - 1);
|
|
537
|
+
const { outcome: folded } = applyHead(params, outcome.data, scope);
|
|
538
|
+
const context = {
|
|
539
|
+
key,
|
|
540
|
+
scope,
|
|
541
|
+
source: request.source
|
|
542
|
+
};
|
|
543
|
+
if (folded === "replaced") effects?.onApplied?.(outcome.data, params, context);
|
|
544
|
+
else if (folded === "missing") effects?.onMissing?.(params, context);
|
|
545
|
+
return {
|
|
546
|
+
applied: folded !== "dropped",
|
|
547
|
+
current: true,
|
|
548
|
+
isActive,
|
|
549
|
+
missing: folded === "missing"
|
|
550
|
+
};
|
|
551
|
+
};
|
|
552
|
+
/**
|
|
553
|
+
* Fetch the head of an entry now and settle it like a `useSync` response —
|
|
554
|
+
* for stores that need the data while no view is mounted (a hover prefetch,
|
|
555
|
+
* a refresh after a mutation on a route without the list). `revalidate` only
|
|
556
|
+
* re-runs mounted queries.
|
|
557
|
+
*
|
|
558
|
+
* Joins a request in flight for the same entry unless `fresh`. Resolves with
|
|
559
|
+
* what was fetched and whether it was applied; rejects when the request
|
|
560
|
+
* fails, after routing the failure through `effects.onError`.
|
|
561
|
+
*/
|
|
562
|
+
const fetch = async (params, { fresh = false, scope = resource.scope.get() } = {}) => {
|
|
563
|
+
if (!fetcher) throw new Error(`[replica] ${resource.name} has no fetcher`);
|
|
564
|
+
if (scope !== resource.scope.get()) throw new ReplicaScopeChangedError(resource.name, scope);
|
|
565
|
+
let request = requests.begin(params, scope, "fetch");
|
|
566
|
+
const joined = fresh ? void 0 : requests.inflight(request.requestId);
|
|
567
|
+
if (joined) request = joined;
|
|
568
|
+
else {
|
|
569
|
+
if (fresh) requests.retire(request.requestId, request.seq - 1);
|
|
570
|
+
requests.send(request);
|
|
571
|
+
}
|
|
572
|
+
let data;
|
|
573
|
+
try {
|
|
574
|
+
data = await request.promise;
|
|
575
|
+
} catch (error) {
|
|
576
|
+
requests.settle(request, { error });
|
|
577
|
+
throw error;
|
|
578
|
+
}
|
|
579
|
+
const settled = requests.settle(request, { data });
|
|
580
|
+
if (settled.applied && request.source === "fetch" && !requests.isSyncInflight(request.requestId)) driver.seed?.(request.syncKey, data);
|
|
581
|
+
return {
|
|
582
|
+
applied: settled.applied,
|
|
583
|
+
data,
|
|
584
|
+
missing: settled.missing
|
|
585
|
+
};
|
|
586
|
+
};
|
|
587
|
+
/**
|
|
588
|
+
* Forget the key's head query as well as the entry. A `useSync` request
|
|
589
|
+
* already in flight for it would otherwise pass the settle guards (the
|
|
590
|
+
* marker still matches), `replace` the entry and persist pre-mutation rows
|
|
591
|
+
* back over an invalidation that has already completed. (The engine's
|
|
592
|
+
* removal generation drops a `fetch` captured before the removal.)
|
|
593
|
+
*/
|
|
594
|
+
const remove = (key, scope) => {
|
|
595
|
+
if (scope === void 0 || scope === resource.scope.get()) headQuery.delete(key);
|
|
596
|
+
return engine.remove(key, scope);
|
|
597
|
+
};
|
|
598
|
+
const useSync = createUseSync({
|
|
599
|
+
driver,
|
|
600
|
+
engine,
|
|
601
|
+
get,
|
|
602
|
+
headQuery,
|
|
603
|
+
requests,
|
|
604
|
+
resource,
|
|
605
|
+
view
|
|
606
|
+
});
|
|
607
|
+
return {
|
|
608
|
+
...engine,
|
|
609
|
+
/** @internal Records of `useSync` requests not yet released (leak checks in tests). */
|
|
610
|
+
debugPendingSyncRequests: requests.debugPendingSyncRequests,
|
|
611
|
+
/** @internal Retirement records still held (leak checks in tests). */
|
|
612
|
+
debugRetiredRequests: requests.debugRetiredRequests,
|
|
613
|
+
fetch,
|
|
614
|
+
remove,
|
|
615
|
+
useSync
|
|
616
|
+
};
|
|
617
|
+
};
|
|
618
|
+
// src/zustand/driver.ts
|
|
619
|
+
/**
|
|
620
|
+
* Driver over SWR. Pass the app's own hook and scoped `mutate` when it wraps
|
|
621
|
+
* SWR (custom cache provider, key augmentation, retry policy).
|
|
622
|
+
*/
|
|
623
|
+
const createSWRDriver = ({ mutate, useSWR }) => ({
|
|
624
|
+
revalidate: (match) => mutate(match),
|
|
625
|
+
seed: (key, data) => {
|
|
626
|
+
mutate(key, data, { revalidate: false }).catch(() => void 0);
|
|
627
|
+
},
|
|
628
|
+
useQuery: (key, fetcher, { once, onError, onSuccess, ...schedule }) => useSWR(key, fetcher, {
|
|
629
|
+
...Object.fromEntries(Object.entries(schedule).filter(([, value]) => value !== void 0)),
|
|
630
|
+
...once && {
|
|
631
|
+
revalidateIfStale: false,
|
|
632
|
+
revalidateOnFocus: false,
|
|
633
|
+
revalidateOnReconnect: false
|
|
634
|
+
},
|
|
635
|
+
...onError && { onError: (error) => onError(error) },
|
|
636
|
+
...onSuccess && { onSuccess: (data) => onSuccess(data) }
|
|
637
|
+
})
|
|
638
|
+
});
|
|
639
|
+
export { ReplicaScopeChangedError, createReplicaSlice, createSWRDriver, recordLens, splitPagedLens };
|
|
640
|
+
|
|
641
|
+
//# sourceMappingURL=index.js.map
|