tsdf 8.0.0-beta.1 → 8.0.0-beta.10

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 (57) hide show
  1. package/dist/main.cjs +1846 -0
  2. package/dist/main.d.ts +291 -0
  3. package/dist/main.js +1811 -0
  4. package/package.json +6 -2
  5. package/.eslintignore +0 -3
  6. package/.eslintrc.cjs +0 -119
  7. package/.gitattributes +0 -22
  8. package/.prettierrc +0 -6
  9. package/.vscode/settings.json +0 -3
  10. package/.vscode/tasks.json +0 -35
  11. package/fetch-orquestrator-scenarios.excalidraw +0 -10115
  12. package/scripts/check-if-is-sync.sh +0 -6
  13. package/src/collectionFetchOrquestrator.ts +0 -23
  14. package/src/collectionStore.ts +0 -608
  15. package/src/documentStore.ts +0 -272
  16. package/src/fetchOrquestrator.ts +0 -335
  17. package/src/listQueryStore.ts +0 -1190
  18. package/src/main.ts +0 -22
  19. package/src/storeShared.ts +0 -5
  20. package/src/useEnsureIsLoaded.ts +0 -50
  21. package/src/utils/filterAndMap.ts +0 -20
  22. package/src/utils/getCacheId.ts +0 -19
  23. package/src/utils/hooks.ts +0 -110
  24. package/src/utils/isObject.ts +0 -3
  25. package/src/utils/math.ts +0 -7
  26. package/src/utils/serializableClone.ts +0 -3
  27. package/src/utils/useLatestValue.ts +0 -16
  28. package/test/__snapshots__/listQueryStore.test.ts.snap +0 -146
  29. package/test/__snapshots__/listQueryStoreHooks.test.ts.snap +0 -9
  30. package/test/collectionStore.test.ts +0 -523
  31. package/test/collectionStoreHooks.test.tsx +0 -651
  32. package/test/documentStore.test.ts +0 -183
  33. package/test/documentStoreHooks.test.tsx +0 -857
  34. package/test/fetchOrquestrator.test.ts +0 -913
  35. package/test/listQueryStore.test.ts +0 -1158
  36. package/test/listQueryStoreHooks.test.tsx +0 -662
  37. package/test/listQueryStoreHooks2.test.tsx +0 -483
  38. package/test/listQueryStoreHooksMutations.test.tsx +0 -764
  39. package/test/mocks/fetchMock.ts +0 -296
  40. package/test/mocks/fetchOrquestratorEnv.ts +0 -370
  41. package/test/setup/setup.ts +0 -109
  42. package/test/testHelpers.test.ts +0 -88
  43. package/test/utils/RenderObjValues.tsx +0 -23
  44. package/test/utils/arrayUtils.ts +0 -13
  45. package/test/utils/createDefaultListQueryStore.ts +0 -275
  46. package/test/utils/createOrVariations.ts +0 -48
  47. package/test/utils/dedent.ts +0 -50
  48. package/test/utils/delayCall.ts +0 -25
  49. package/test/utils/math.ts +0 -3
  50. package/test/utils/objectUtils.ts +0 -18
  51. package/test/utils/range.ts +0 -19
  52. package/test/utils/sleep.ts +0 -3
  53. package/test/utils/storeUtils.ts +0 -460
  54. package/tsconfig.json +0 -24
  55. package/tsconfig.prod.json +0 -9
  56. package/tsup.config.ts +0 -12
  57. package/vitest.config.ts +0 -10
package/dist/main.cjs ADDED
@@ -0,0 +1,1846 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/main.ts
27
+ var main_exports = {};
28
+ __export(main_exports, {
29
+ newTSDFCollectionStore: () => newTSDFCollectionStore,
30
+ newTSDFDocumentStore: () => newTSDFDocumentStore,
31
+ newTSDFListQueryStore: () => newTSDFListQueryStore
32
+ });
33
+ module.exports = __toCommonJS(main_exports);
34
+
35
+ // src/documentStore.ts
36
+ var import_immer = require("immer");
37
+ var import_mitt2 = __toESM(require("mitt"), 1);
38
+ var import_react3 = require("react");
39
+ var import_t_state2 = require("t-state");
40
+
41
+ // src/fetchOrquestrator.ts
42
+ function createFetchOrquestrator({
43
+ fetchFn,
44
+ on,
45
+ mediumPriorityThrottleMs = 10,
46
+ lowPriorityThrottleMs = 200,
47
+ dynamicRealtimeThrottleMs
48
+ }) {
49
+ const fetchs = {
50
+ a: null,
51
+ c: null,
52
+ b: null
53
+ };
54
+ let lastMutationIdStarted = 0;
55
+ let lastFetchIdStarted = 0;
56
+ let mutationIsInProgress = false;
57
+ let lastFetchStartTime = 0;
58
+ let lastFetchDuration = 0;
59
+ let onMutationEnd = [];
60
+ let lastFetchWasAborted = false;
61
+ let abortFetchsBeforeOrEqual = 0;
62
+ function setLastFetchDurantion(duration) {
63
+ lastFetchDuration = duration;
64
+ }
65
+ function setLastFetchStartTime(startTime) {
66
+ lastFetchStartTime = startTime;
67
+ }
68
+ function flushScheduledFetch() {
69
+ if (fetchs.c) {
70
+ on?.("scheduled-fetch-started");
71
+ const params = fetchs.c.params;
72
+ fetchs.c = null;
73
+ startFetch(params, Date.now());
74
+ }
75
+ }
76
+ function startMutation() {
77
+ mutationIsInProgress = true;
78
+ abortFetchsBeforeOrEqual = lastFetchIdStarted;
79
+ fetchs.a = null;
80
+ const id = getAutoIncrementId();
81
+ lastMutationIdStarted = id;
82
+ return () => endMutation(id);
83
+ }
84
+ function endMutation(id) {
85
+ if (id === lastMutationIdStarted) {
86
+ mutationIsInProgress = false;
87
+ if (onMutationEnd.length > 0) {
88
+ onMutationEnd.forEach((cb) => cb());
89
+ onMutationEnd = [];
90
+ }
91
+ flushScheduledFetch();
92
+ return true;
93
+ }
94
+ return false;
95
+ }
96
+ function getFetchs() {
97
+ return fetchs;
98
+ }
99
+ async function startFetch(params, startTime) {
100
+ if (fetchs.a) {
101
+ throw new Error("[tsdf] Fetch already in progress");
102
+ }
103
+ const id = getAutoIncrementId();
104
+ lastFetchIdStarted = id;
105
+ lastFetchWasAborted = false;
106
+ fetchs.a = { startTime, onEnd: [] };
107
+ const prevFetchStartTime = lastFetchStartTime;
108
+ lastFetchStartTime = startTime;
109
+ function shouldAbort() {
110
+ const abort = id !== lastFetchIdStarted || mutationIsInProgress || id <= abortFetchsBeforeOrEqual;
111
+ lastFetchWasAborted = abort;
112
+ return abort;
113
+ }
114
+ const success = await fetchFn(
115
+ {
116
+ shouldAbort,
117
+ getStartTime: () => startTime
118
+ },
119
+ params
120
+ );
121
+ const currentFetchs = getFetchs();
122
+ if (!currentFetchs.a) {
123
+ lastFetchStartTime = prevFetchStartTime;
124
+ return false;
125
+ }
126
+ if (success) {
127
+ lastFetchDuration = Date.now() - startTime;
128
+ }
129
+ if (currentFetchs.b) {
130
+ clearTimeout(currentFetchs.b.timeoutId);
131
+ fetchs.b = null;
132
+ }
133
+ const onEnd = currentFetchs.a.onEnd;
134
+ currentFetchs.a = null;
135
+ if (onEnd.length > 0) {
136
+ onEnd.forEach((cb) => cb());
137
+ }
138
+ flushScheduledFetch();
139
+ return true;
140
+ }
141
+ function scheduleFetch(fetchType, params) {
142
+ const startTime = Date.now();
143
+ if (dynamicRealtimeThrottleMs && fetchType === "realtimeUpdate") {
144
+ if (scheduleRTU(startTime, params)) {
145
+ return "rt-scheduled";
146
+ }
147
+ }
148
+ if (shouldSkipFetch(fetchType, startTime)) {
149
+ return "skipped";
150
+ }
151
+ if (shouldScheduleFetch(fetchType, params)) {
152
+ return "scheduled";
153
+ }
154
+ startFetch(params, startTime);
155
+ return "started";
156
+ }
157
+ function shouldSkipFetch(fetchType, startTime) {
158
+ if (fetchType === "highPriority") {
159
+ if (fetchs.a) {
160
+ const timeSinceLastFetch = startTime - fetchs.a.startTime;
161
+ if (timeSinceLastFetch < mediumPriorityThrottleMs) {
162
+ return true;
163
+ }
164
+ }
165
+ }
166
+ if (fetchType === "lowPriority") {
167
+ if (fetchs.a || fetchs.c || mutationIsInProgress) {
168
+ return true;
169
+ }
170
+ if (lastFetchStartTime) {
171
+ const timeSinceLastFetch = startTime - lastFetchStartTime;
172
+ if (timeSinceLastFetch < lowPriorityThrottleMs) {
173
+ return true;
174
+ }
175
+ }
176
+ }
177
+ return false;
178
+ }
179
+ function shouldScheduleFetch(priority, params) {
180
+ const shouldSchedule = (() => {
181
+ if (priority === "lowPriority") {
182
+ return false;
183
+ }
184
+ return !!fetchs.a || !!mutationIsInProgress;
185
+ })();
186
+ if (shouldSchedule) {
187
+ fetchs.c = { params };
188
+ }
189
+ return shouldSchedule;
190
+ }
191
+ function addDelayedRTU(startTime, params) {
192
+ if (!dynamicRealtimeThrottleMs)
193
+ return false;
194
+ const timeSinceLastFetch = startTime - (lastFetchStartTime + lastFetchDuration);
195
+ const minimumRealtimeInterval = dynamicRealtimeThrottleMs(lastFetchDuration);
196
+ if (timeSinceLastFetch >= minimumRealtimeInterval)
197
+ return false;
198
+ const delay = minimumRealtimeInterval - timeSinceLastFetch;
199
+ fetchs.b = {
200
+ timeoutId: window.setTimeout(() => {
201
+ fetchs.b = null;
202
+ on?.("scheduled-rt-fetch-started");
203
+ startFetch(params, Date.now());
204
+ }, delay)
205
+ };
206
+ return true;
207
+ }
208
+ function scheduleRTU(startTime, params) {
209
+ if (!lastFetchDuration || !lastFetchStartTime || !dynamicRealtimeThrottleMs) {
210
+ return false;
211
+ }
212
+ if (fetchs.b) {
213
+ return true;
214
+ }
215
+ if (fetchs.a) {
216
+ fetchs.a.onEnd.push(() => {
217
+ addDelayedRTU(Date.now(), params);
218
+ });
219
+ return true;
220
+ } else if (mutationIsInProgress) {
221
+ onMutationEnd.push(() => {
222
+ const added = addDelayedRTU(Date.now(), params);
223
+ if (!added) {
224
+ on?.("scheduled-rt-fetch-started");
225
+ scheduleFetch("highPriority", params);
226
+ }
227
+ });
228
+ return true;
229
+ } else {
230
+ if (!addDelayedRTU(startTime, params)) {
231
+ return false;
232
+ }
233
+ }
234
+ return true;
235
+ }
236
+ function addOnFetchEnd(cb) {
237
+ if (fetchs.a) {
238
+ fetchs.a.onEnd.push(cb);
239
+ }
240
+ }
241
+ async function awaitFetch(params) {
242
+ scheduleFetch("highPriority", params);
243
+ if (fetchs.a) {
244
+ await new Promise((resolve) => {
245
+ addOnFetchEnd(() => resolve(true));
246
+ });
247
+ }
248
+ return lastFetchWasAborted;
249
+ }
250
+ return {
251
+ scheduleFetch,
252
+ awaitFetch,
253
+ startMutation,
254
+ get hasPendingFetch() {
255
+ return !!fetchs.a || !!fetchs.c || !!fetchs.b;
256
+ },
257
+ get fetchIsInProgress() {
258
+ return !!fetchs.a;
259
+ },
260
+ get mutationIsInProgress() {
261
+ return mutationIsInProgress;
262
+ },
263
+ setLastFetchDurantion,
264
+ setLastFetchStartTime
265
+ };
266
+ }
267
+ var autoIncrementId = 0;
268
+ function getAutoIncrementId() {
269
+ return ++autoIncrementId;
270
+ }
271
+
272
+ // src/useEnsureIsLoaded.ts
273
+ var import_mitt = __toESM(require("mitt"), 1);
274
+ var import_react2 = require("react");
275
+
276
+ // src/utils/hooks.ts
277
+ var import_react = require("react");
278
+ var import_t_state = require("t-state");
279
+ function useDeepCompareMemoize(value, equalityFn = import_t_state.deepEqual) {
280
+ const ref = (0, import_react.useRef)();
281
+ const signalRef = (0, import_react.useRef)(0);
282
+ if (!equalityFn(value, ref.current)) {
283
+ ref.current = value;
284
+ signalRef.current += 1;
285
+ }
286
+ return [signalRef.current];
287
+ }
288
+ function useDeepMemo(callback, deeps) {
289
+ return (0, import_react.useMemo)(callback, useDeepCompareMemoize(deeps));
290
+ }
291
+ function useLatestValue(value) {
292
+ const ref = (0, import_react.useRef)({ insideEffect: value, insideMemo: value });
293
+ ref.current.insideMemo = value;
294
+ (0, import_react.useLayoutEffect)(() => {
295
+ ref.current.insideEffect = value;
296
+ });
297
+ return ref.current;
298
+ }
299
+ function useOnMittEvent(mitt5, event, callback) {
300
+ const latestCallback = useLatestValue(callback);
301
+ (0, import_react.useLayoutEffect)(() => {
302
+ const cb = (payload) => {
303
+ latestCallback.insideEffect(payload);
304
+ };
305
+ mitt5.on(event, cb);
306
+ return () => {
307
+ mitt5.off(event, cb);
308
+ };
309
+ }, [mitt5, event, latestCallback]);
310
+ }
311
+ function usePrevious(value, initial) {
312
+ const ref = (0, import_react.useRef)(initial);
313
+ (0, import_react.useEffect)(() => {
314
+ ref.current = value;
315
+ });
316
+ return ref.current;
317
+ }
318
+ function useOnChange(value, callBack, {
319
+ equalityFn: areEqual = import_t_state.shallowEqual,
320
+ callOnMount,
321
+ layoutEffect
322
+ } = {}) {
323
+ const useEffectFn = layoutEffect ? import_react.useLayoutEffect : import_react.useEffect;
324
+ const prev = usePrevious(value, !callOnMount ? value : void 0);
325
+ useEffectFn(() => {
326
+ if (!areEqual(value, prev)) {
327
+ return callBack({ prev, current: value });
328
+ }
329
+ });
330
+ }
331
+ function useConst(getValue) {
332
+ const store = (0, import_react.useRef)();
333
+ if (store.current === void 0) {
334
+ store.current = getValue();
335
+ }
336
+ return store.current;
337
+ }
338
+
339
+ // src/useEnsureIsLoaded.ts
340
+ function useEnsureIsLoaded(ensureIsLoaded, enabled, forceFetch) {
341
+ const isLoadedEvtEmitter = useConst(() => (0, import_mitt.default)());
342
+ const [isForceLoading, setIsForceLoading] = (0, import_react2.useState)(true);
343
+ useOnChange(
344
+ ensureIsLoaded && isForceLoading && enabled,
345
+ ({ current }) => {
346
+ if (current) {
347
+ forceFetch();
348
+ }
349
+ },
350
+ { callOnMount: true }
351
+ );
352
+ useOnMittEvent(isLoadedEvtEmitter, "isLoaded", (isLoaded) => {
353
+ if (ensureIsLoaded && enabled && isLoaded) {
354
+ setIsForceLoading(false);
355
+ }
356
+ });
357
+ function useModifyResult(result) {
358
+ return (0, import_react2.useMemo)(() => {
359
+ if (ensureIsLoaded) {
360
+ const newStatus = enabled && isForceLoading ? "loading" : result.status;
361
+ return {
362
+ ...result,
363
+ isLoading: newStatus === "loading",
364
+ status: newStatus
365
+ };
366
+ }
367
+ return result;
368
+ }, [ensureIsLoaded, isForceLoading, result]);
369
+ }
370
+ return [useModifyResult, isLoadedEvtEmitter.emit];
371
+ }
372
+
373
+ // src/documentStore.ts
374
+ function newTSDFDocumentStore({
375
+ debugName,
376
+ fetchFn,
377
+ initialData,
378
+ disableRefetchOnWindowFocus,
379
+ disableRefetchOnMount: globalDisableRefetchOnMount,
380
+ lowPriorityThrottleMs,
381
+ mediumPriorityThrottleMs,
382
+ dynamicRealtimeThrottleMs,
383
+ disableInitialDataInvalidation,
384
+ errorNormalizer
385
+ }) {
386
+ const store = new import_t_state2.Store({
387
+ debugName,
388
+ state: {
389
+ data: initialData ?? null,
390
+ error: null,
391
+ status: initialData ? "success" : "idle",
392
+ refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
393
+ }
394
+ });
395
+ async function fetch(fetchCtx, _) {
396
+ store.setPartialState(
397
+ {
398
+ status: store.state.status === "success" ? "refetching" : "loading",
399
+ error: null,
400
+ refetchOnMount: false
401
+ },
402
+ {
403
+ equalityCheck: import_t_state2.deepEqual,
404
+ action: store.state.status === "success" ? "fetch-start-refetching" : "fetch-start-loading"
405
+ }
406
+ );
407
+ try {
408
+ const data = await fetchFn();
409
+ if (fetchCtx.shouldAbort())
410
+ return false;
411
+ store.setPartialState(
412
+ {
413
+ data,
414
+ status: "success"
415
+ },
416
+ { action: "fetch-success", equalityCheck: import_t_state2.deepEqual }
417
+ );
418
+ return true;
419
+ } catch (exception) {
420
+ if (fetchCtx.shouldAbort())
421
+ return false;
422
+ store.setPartialState(
423
+ {
424
+ error: errorNormalizer(exception),
425
+ status: "error"
426
+ },
427
+ { action: "fetch-error" }
428
+ );
429
+ return false;
430
+ }
431
+ }
432
+ const fetchOrquestrator = createFetchOrquestrator({
433
+ fetchFn: fetch,
434
+ lowPriorityThrottleMs,
435
+ dynamicRealtimeThrottleMs,
436
+ mediumPriorityThrottleMs
437
+ });
438
+ function scheduleFetch(fetchType) {
439
+ return fetchOrquestrator.scheduleFetch(fetchType, null);
440
+ }
441
+ async function awaitFetch() {
442
+ const wasAborted = await fetchOrquestrator.awaitFetch(null);
443
+ if (wasAborted) {
444
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
445
+ }
446
+ if (!store.state.data) {
447
+ return { data: null, error: errorNormalizer(new Error("No data")) };
448
+ }
449
+ return store.state.error ? { data: null, error: store.state.error } : { data: store.state.data, error: null };
450
+ }
451
+ const storeEvents = (0, import_mitt2.default)();
452
+ let invalidationWasTriggered = false;
453
+ function invalidateData(priority = "highPriority") {
454
+ store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
455
+ invalidationWasTriggered = false;
456
+ storeEvents.emit("invalidateData", priority);
457
+ }
458
+ function useDocument({
459
+ selector,
460
+ disabled,
461
+ returnRefetchingStatus,
462
+ disableRefetchOnMount = globalDisableRefetchOnMount,
463
+ returnIdleStatus = !!disabled,
464
+ ensureIsLoaded
465
+ } = {}) {
466
+ const storeStateSelector = (0, import_react3.useCallback)(
467
+ (state) => {
468
+ const { error } = state;
469
+ const data = selector ? selector(state.data) : state.data;
470
+ let status = state.status;
471
+ if (!returnIdleStatus && status === "idle") {
472
+ status = "loading";
473
+ }
474
+ if (!returnRefetchingStatus && status === "refetching") {
475
+ status = "success";
476
+ }
477
+ return {
478
+ data,
479
+ error,
480
+ status,
481
+ isLoading: status === "loading"
482
+ };
483
+ },
484
+ [returnRefetchingStatus, returnIdleStatus, selector]
485
+ );
486
+ const storeState = store.useSelector(storeStateSelector, {
487
+ useExternalDeps: true
488
+ });
489
+ useOnMittEvent(storeEvents, "invalidateData", (priority) => {
490
+ if (!invalidationWasTriggered) {
491
+ scheduleFetch(priority);
492
+ invalidationWasTriggered = true;
493
+ }
494
+ });
495
+ (0, import_react3.useEffect)(() => {
496
+ if (disabled)
497
+ return;
498
+ if (disableRefetchOnMount) {
499
+ const shouldFetch = store.state.refetchOnMount || store.state.status === "idle";
500
+ if (shouldFetch) {
501
+ scheduleFetch(store.state.refetchOnMount || "lowPriority");
502
+ }
503
+ } else {
504
+ scheduleFetch("lowPriority");
505
+ }
506
+ }, [disableRefetchOnMount, disabled]);
507
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
508
+ ensureIsLoaded,
509
+ !disabled,
510
+ () => {
511
+ scheduleFetch("highPriority");
512
+ }
513
+ );
514
+ (0, import_t_state2.useSubscribeToStore)(store, ({ observe }) => {
515
+ observe.ifSelector((state) => state.status).change.then(({ current }) => {
516
+ if (current === "success" || current === "error") {
517
+ emitIsLoadedEvt("isLoaded", true);
518
+ }
519
+ });
520
+ });
521
+ return useModifyResult(storeState);
522
+ }
523
+ function updateState(produceNewData) {
524
+ store.setKey(
525
+ "data",
526
+ (current) => {
527
+ if (!current)
528
+ return current;
529
+ return (0, import_immer.produce)(current, produceNewData);
530
+ },
531
+ { action: "update-state" }
532
+ );
533
+ }
534
+ if (!disableRefetchOnWindowFocus) {
535
+ let handleFocus2 = function() {
536
+ invalidateData("lowPriority");
537
+ };
538
+ var handleFocus = handleFocus2;
539
+ window.addEventListener("focus", handleFocus2);
540
+ window.addEventListener("visibilitychange", handleFocus2);
541
+ }
542
+ return {
543
+ store,
544
+ awaitFetch,
545
+ scheduleFetch,
546
+ invalidateData,
547
+ useDocument,
548
+ updateState,
549
+ startMutation: fetchOrquestrator.startMutation
550
+ };
551
+ }
552
+
553
+ // src/collectionStore.ts
554
+ var import_mitt3 = __toESM(require("mitt"), 1);
555
+ var import_react4 = require("react");
556
+ var import_t_state3 = require("t-state");
557
+
558
+ // src/collectionFetchOrquestrator.ts
559
+ function createCollectionFetchOrquestrator(props) {
560
+ const fetchOrquestrators = /* @__PURE__ */ new Map();
561
+ function getFetchOrquestrator(key) {
562
+ if (!fetchOrquestrators.has(key)) {
563
+ fetchOrquestrators.set(key, createFetchOrquestrator(props));
564
+ }
565
+ return fetchOrquestrators.get(key);
566
+ }
567
+ return {
568
+ get: getFetchOrquestrator
569
+ };
570
+ }
571
+
572
+ // src/utils/filterAndMap.ts
573
+ var ignore = Symbol();
574
+ function filterAndMap(arr, fn) {
575
+ const result = [];
576
+ let i = 0;
577
+ for (const item of arr) {
578
+ const mappedItem = fn(item, ignore, i);
579
+ if (mappedItem !== ignore) {
580
+ result.push(mappedItem);
581
+ }
582
+ i++;
583
+ }
584
+ return result;
585
+ }
586
+
587
+ // src/utils/isObject.ts
588
+ function isObject(value) {
589
+ return typeof value === "object" && value !== null && !Array.isArray(value);
590
+ }
591
+
592
+ // src/utils/getCacheId.ts
593
+ function getCacheId(input) {
594
+ return typeof input === "string" || typeof input === "number" ? String(input) : JSON.stringify(input && isObject(input) ? orderedProps(input) : input);
595
+ }
596
+ function orderedProps(obj) {
597
+ return filterAndMap(Object.keys(obj).sort(), (k, ignore2) => {
598
+ const value = obj[k];
599
+ if (value === void 0)
600
+ return ignore2;
601
+ return { [k]: obj[k] };
602
+ });
603
+ }
604
+
605
+ // src/collectionStore.ts
606
+ var import_json = require("klona/json");
607
+ function newTSDFCollectionStore({
608
+ debugName,
609
+ fetchFn,
610
+ disableRefetchOnWindowFocus,
611
+ lowPriorityThrottleMs,
612
+ errorNormalizer,
613
+ disableInitialDataInvalidation,
614
+ mediumPriorityThrottleMs,
615
+ initialStateItems,
616
+ disableRefetchOnMount: globalDisableRefetchOnMount,
617
+ dynamicRealtimeThrottleMs,
618
+ getCollectionItemKey: filterCollectionItemObjKey
619
+ }) {
620
+ const initialState = {};
621
+ if (initialStateItems) {
622
+ for (const item of initialStateItems) {
623
+ const itemKey = getItemKey(item.payload);
624
+ initialState[itemKey] = {
625
+ data: item.data,
626
+ error: null,
627
+ status: "success",
628
+ payload: item.payload,
629
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
630
+ wasLoaded: true
631
+ };
632
+ }
633
+ }
634
+ const store = new import_t_state3.Store({
635
+ debugName,
636
+ state: initialState
637
+ });
638
+ function getItemKey(params) {
639
+ return getCacheId(
640
+ filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params
641
+ );
642
+ }
643
+ async function fetch(fetchCtx, itemPayload) {
644
+ const itemId = getItemKey(itemPayload);
645
+ const payload = (0, import_json.klona)(itemPayload);
646
+ const itemState = store.state[itemId];
647
+ store.produceState(
648
+ (draft) => {
649
+ const item = draft[itemId];
650
+ if (!item) {
651
+ draft[itemId] = {
652
+ data: null,
653
+ error: null,
654
+ status: "loading",
655
+ payload,
656
+ refetchOnMount: false,
657
+ wasLoaded: false
658
+ };
659
+ return;
660
+ }
661
+ item.status = item.data !== null ? "refetching" : "loading";
662
+ item.payload = payload;
663
+ item.error = null;
664
+ item.refetchOnMount = false;
665
+ },
666
+ {
667
+ equalityCheck: import_t_state3.deepEqual,
668
+ action: {
669
+ type: !itemState?.data ? "fetch-start-loading" : "fetch-start-refetching",
670
+ payload
671
+ }
672
+ }
673
+ );
674
+ try {
675
+ const data = await fetchFn(payload);
676
+ if (fetchCtx.shouldAbort())
677
+ return false;
678
+ store.produceState(
679
+ (draft) => {
680
+ const item = draft[itemId];
681
+ if (!item)
682
+ return;
683
+ item.data = data;
684
+ item.status = "success";
685
+ item.wasLoaded = true;
686
+ },
687
+ {
688
+ action: { type: "fetch-success", payload },
689
+ equalityCheck: import_t_state3.deepEqual
690
+ }
691
+ );
692
+ return true;
693
+ } catch (exception) {
694
+ if (fetchCtx.shouldAbort())
695
+ return false;
696
+ const error = errorNormalizer(exception);
697
+ store.produceState(
698
+ (draft) => {
699
+ const item = draft[itemId];
700
+ if (!item)
701
+ return;
702
+ item.error = error;
703
+ item.status = "error";
704
+ },
705
+ { action: { type: "fetch-error", payload, error } }
706
+ );
707
+ return false;
708
+ }
709
+ }
710
+ const fetchOrquestrator = createCollectionFetchOrquestrator({
711
+ fetchFn: fetch,
712
+ lowPriorityThrottleMs,
713
+ dynamicRealtimeThrottleMs,
714
+ mediumPriorityThrottleMs
715
+ });
716
+ function scheduleFetch(fetchType, payload) {
717
+ const multiplePayloads = Array.isArray(payload);
718
+ const payloads = multiplePayloads ? payload : [payload];
719
+ const results = [];
720
+ for (const param of payloads) {
721
+ const itemKey = getItemKey(param);
722
+ results.push(
723
+ fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param)
724
+ );
725
+ }
726
+ return multiplePayloads ? results : results[0];
727
+ }
728
+ async function awaitFetch(params) {
729
+ const itemId = getItemKey(params);
730
+ const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
731
+ if (wasAborted) {
732
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
733
+ }
734
+ const item = store.state[itemId];
735
+ if (!item?.data) {
736
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
737
+ }
738
+ return item.error ? { data: null, error: item.error } : { data: item.data, error: null };
739
+ }
740
+ function getItemsKeyArray(params) {
741
+ const items = store.state;
742
+ if (Array.isArray(params)) {
743
+ return params.map(getItemKey);
744
+ } else if (typeof params === "function") {
745
+ return filterAndMap(Object.entries(items), ([itemKey, item], ignore2) => {
746
+ return item && params(item.payload, item.data) ? itemKey : ignore2;
747
+ });
748
+ } else {
749
+ return [getItemKey(params)];
750
+ }
751
+ }
752
+ const storeEvents = (0, import_mitt3.default)();
753
+ const invalidationWasTriggered = /* @__PURE__ */ new Set();
754
+ function invalidateItem(itemPayload, priority = "highPriority") {
755
+ const itemsKey = getItemsKeyArray(itemPayload);
756
+ for (const itemKey of itemsKey) {
757
+ store.produceState(
758
+ (draft) => {
759
+ const item = draft[itemKey];
760
+ if (!item)
761
+ return;
762
+ item.refetchOnMount = priority;
763
+ },
764
+ { action: { type: "invalidate-data", itemKey } }
765
+ );
766
+ invalidationWasTriggered.delete(itemKey);
767
+ storeEvents.emit("invalidateData", { priority, itemKey });
768
+ }
769
+ }
770
+ function getItemState(params) {
771
+ if (typeof params === "function" || Array.isArray(params)) {
772
+ const itemsId = getItemsKeyArray(params);
773
+ return filterAndMap(itemsId, (itemId, ignore2) => {
774
+ return store.state[itemId] || ignore2;
775
+ });
776
+ }
777
+ return store.state[getItemKey(params)];
778
+ }
779
+ function useMultipleItems(queries, {
780
+ selector,
781
+ omitPayload,
782
+ returnIdleStatus,
783
+ returnRefetchingStatus,
784
+ disableRefetchOnMount = globalDisableRefetchOnMount
785
+ } = {}) {
786
+ const queriesWithId = useDeepMemo(() => {
787
+ return queries.map((payload) => {
788
+ return { itemKey: getItemKey(payload), payload };
789
+ });
790
+ }, [queries]);
791
+ const dataSelector = (0, import_react4.useCallback)((itemState) => {
792
+ if (selector)
793
+ return selector(itemState);
794
+ return itemState;
795
+ }, []);
796
+ const resultSelector = (0, import_react4.useCallback)(
797
+ (state) => {
798
+ return queriesWithId.map(
799
+ ({
800
+ itemKey,
801
+ payload
802
+ }) => {
803
+ const item = state[itemKey];
804
+ if (item === null) {
805
+ return {
806
+ itemStateKey: itemKey,
807
+ status: "deleted",
808
+ data: dataSelector(null),
809
+ error: null,
810
+ payload: omitPayload ? void 0 : payload,
811
+ isLoading: false
812
+ };
813
+ }
814
+ if (!item) {
815
+ return {
816
+ itemStateKey: itemKey,
817
+ status: returnIdleStatus ? "idle" : "loading",
818
+ data: dataSelector(null),
819
+ error: null,
820
+ payload: omitPayload ? void 0 : payload,
821
+ isLoading: returnIdleStatus ? false : true
822
+ };
823
+ }
824
+ let status = item.status;
825
+ if (!returnRefetchingStatus && item.status === "refetching") {
826
+ status = "success";
827
+ }
828
+ return {
829
+ itemStateKey: itemKey,
830
+ status,
831
+ data: dataSelector(item.data),
832
+ error: item.error,
833
+ isLoading: status === "loading",
834
+ payload: omitPayload ? void 0 : item.payload
835
+ };
836
+ }
837
+ );
838
+ },
839
+ [
840
+ dataSelector,
841
+ omitPayload,
842
+ queriesWithId,
843
+ returnIdleStatus,
844
+ returnRefetchingStatus
845
+ ]
846
+ );
847
+ const storeState = store.useSelector(resultSelector, {
848
+ equalityFn: import_t_state3.deepEqual,
849
+ useExternalDeps: true
850
+ });
851
+ useOnMittEvent(storeEvents, "invalidateData", (event) => {
852
+ for (const { itemKey, payload } of queriesWithId) {
853
+ if (itemKey !== event.itemKey)
854
+ continue;
855
+ if (!invalidationWasTriggered.has(itemKey)) {
856
+ scheduleFetch(event.priority, payload);
857
+ invalidationWasTriggered.add(itemKey);
858
+ }
859
+ }
860
+ });
861
+ (0, import_react4.useEffect)(() => {
862
+ for (const { itemKey: itemId, payload } of queriesWithId) {
863
+ if (itemId) {
864
+ if (disableRefetchOnMount) {
865
+ const itemState = getItemState(payload);
866
+ const shouldFetch = !itemState?.wasLoaded || itemState.refetchOnMount;
867
+ if (shouldFetch) {
868
+ scheduleFetch(
869
+ itemState?.refetchOnMount || "lowPriority",
870
+ payload
871
+ );
872
+ return;
873
+ }
874
+ } else {
875
+ scheduleFetch("lowPriority", payload);
876
+ }
877
+ }
878
+ }
879
+ }, [disableRefetchOnMount, queriesWithId]);
880
+ return storeState;
881
+ }
882
+ function useItem(payload, options = {}) {
883
+ const { selector, ensureIsLoaded } = options;
884
+ const query = (0, import_react4.useMemo)(
885
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
886
+ [payload]
887
+ );
888
+ const item = useMultipleItems(query, options);
889
+ const result = (0, import_react4.useMemo)(
890
+ () => item[0] ?? {
891
+ payload: void 0,
892
+ data: selector ? selector(null) : null,
893
+ error: null,
894
+ status: "idle",
895
+ itemStateKey: "",
896
+ isLoading: false
897
+ },
898
+ [item]
899
+ );
900
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
901
+ ensureIsLoaded,
902
+ !!payload,
903
+ () => {
904
+ if (payload) {
905
+ scheduleFetch("highPriority", payload);
906
+ }
907
+ }
908
+ );
909
+ (0, import_t_state3.useSubscribeToStore)(store, ({ observe }) => {
910
+ if (!ensureIsLoaded)
911
+ return;
912
+ observe.ifSelector((state) => state[result.itemStateKey]?.status).change.then(({ current }) => {
913
+ if (current === "success" || current === "error") {
914
+ emitIsLoadedEvt("isLoaded", true);
915
+ }
916
+ });
917
+ });
918
+ return useModifyResult(result);
919
+ }
920
+ function startMutation(fetchParams) {
921
+ const itemKeys = getItemsKeyArray(fetchParams);
922
+ const endMutations = [];
923
+ for (const itemKey of itemKeys) {
924
+ endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
925
+ }
926
+ return () => {
927
+ for (const endMutation of endMutations) {
928
+ endMutation();
929
+ }
930
+ };
931
+ }
932
+ function addItemToState(fetchParams, data) {
933
+ const itemKey = getItemKey(fetchParams);
934
+ store.produceState(
935
+ (draftState) => {
936
+ draftState[itemKey] = {
937
+ data,
938
+ status: "success",
939
+ wasLoaded: true,
940
+ refetchOnMount: false,
941
+ error: null,
942
+ payload: (0, import_json.klona)(fetchParams)
943
+ };
944
+ },
945
+ { action: { type: "create-item-state", payload: fetchParams } }
946
+ );
947
+ }
948
+ function deleteItemState(fetchParams) {
949
+ const itemKeys = getItemsKeyArray(fetchParams);
950
+ store.produceState(
951
+ (draftState) => {
952
+ for (const itemKey of itemKeys) {
953
+ draftState[itemKey] = null;
954
+ }
955
+ },
956
+ { action: { type: "delete-item-state", payload: fetchParams } }
957
+ );
958
+ }
959
+ function updateItemState(fetchParams, produceNewData, ifNothingWasUpdated) {
960
+ const itemKeys = getItemsKeyArray(fetchParams);
961
+ let someItemWasUpdated = false;
962
+ store.batch(
963
+ () => {
964
+ store.produceState((draftState) => {
965
+ for (const itemKey of itemKeys) {
966
+ const item = draftState[itemKey];
967
+ if (!item)
968
+ continue;
969
+ if (item.data) {
970
+ someItemWasUpdated = true;
971
+ const newData = produceNewData(item.data, item);
972
+ if (newData) {
973
+ item.data = newData;
974
+ }
975
+ }
976
+ }
977
+ });
978
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
979
+ ifNothingWasUpdated();
980
+ }
981
+ },
982
+ { type: "update-item-state", item: itemKeys }
983
+ );
984
+ return someItemWasUpdated;
985
+ }
986
+ if (!disableRefetchOnWindowFocus) {
987
+ let handleFocus2 = function() {
988
+ invalidateItem(() => true, "lowPriority");
989
+ };
990
+ var handleFocus = handleFocus2;
991
+ window.addEventListener("focus", handleFocus2);
992
+ window.addEventListener("visibilitychange", handleFocus2);
993
+ }
994
+ return {
995
+ store,
996
+ scheduleFetch,
997
+ awaitFetch,
998
+ useMultipleItems,
999
+ useItem,
1000
+ getItemKey,
1001
+ getItemState,
1002
+ startMutation,
1003
+ invalidateItem,
1004
+ updateItemState,
1005
+ addItemToState,
1006
+ deleteItemState
1007
+ };
1008
+ }
1009
+
1010
+ // src/listQueryStore.ts
1011
+ var import_mitt4 = __toESM(require("mitt"), 1);
1012
+ var import_react5 = require("react");
1013
+ var import_t_state4 = require("t-state");
1014
+ var import_json2 = require("klona/json");
1015
+ var noFetchFnError = "No fetchItemFn was provided";
1016
+ function newTSDFListQueryStore({
1017
+ debugName,
1018
+ fetchListFn,
1019
+ fetchItemFn,
1020
+ errorNormalizer,
1021
+ defaultQuerySize = 50,
1022
+ initialData,
1023
+ disableRefetchOnWindowFocus,
1024
+ disableRefetchOnMount: globalDisableRefetchOnMount,
1025
+ lowPriorityThrottleMs,
1026
+ disableInitialDataInvalidation,
1027
+ mediumPriorityThrottleMs,
1028
+ dynamicRealtimeThrottleMs,
1029
+ syncMutationsAndInvalidations
1030
+ }) {
1031
+ const initialState = { items: {}, queries: {}, itemQueries: {} };
1032
+ if (initialData) {
1033
+ for (const { payload, data } of initialData.items) {
1034
+ const itemKey = getItemKey(payload);
1035
+ initialState.items[itemKey] = data;
1036
+ initialState.itemQueries[itemKey] = {
1037
+ error: null,
1038
+ status: "success",
1039
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1040
+ wasLoaded: true,
1041
+ payload
1042
+ };
1043
+ }
1044
+ for (const { payload, items, hasMore } of initialData.queries) {
1045
+ const queryKey = getQueryKey(payload);
1046
+ initialState.queries[queryKey] = {
1047
+ error: null,
1048
+ status: "success",
1049
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1050
+ wasLoaded: true,
1051
+ payload,
1052
+ items: items.map(getItemKey),
1053
+ hasMore
1054
+ };
1055
+ }
1056
+ }
1057
+ const store = new import_t_state4.Store({
1058
+ debugName,
1059
+ state: initialState
1060
+ });
1061
+ function getQueryKey(params) {
1062
+ return getCacheId(params);
1063
+ }
1064
+ function getItemKey(params) {
1065
+ return getCacheId(params);
1066
+ }
1067
+ async function fetchQuery(fetchCtx, [fetchType, queryPayload, size = defaultQuerySize]) {
1068
+ const payload = (0, import_json2.klona)(queryPayload);
1069
+ const queryKey = getQueryKey(payload);
1070
+ const queryState = store.state.queries[queryKey];
1071
+ const isLoading = !queryState?.wasLoaded;
1072
+ store.produceState(
1073
+ (draft) => {
1074
+ const query = draft.queries[queryKey];
1075
+ if (!query) {
1076
+ draft.queries[queryKey] = {
1077
+ error: null,
1078
+ status: "loading",
1079
+ wasLoaded: false,
1080
+ payload,
1081
+ refetchOnMount: false,
1082
+ hasMore: false,
1083
+ items: []
1084
+ };
1085
+ return;
1086
+ }
1087
+ query.status = query.wasLoaded ? fetchType === "loadMore" ? "loadingMore" : "refetching" : "loading";
1088
+ query.error = null;
1089
+ query.refetchOnMount = false;
1090
+ },
1091
+ {
1092
+ equalityCheck: import_t_state4.deepEqual,
1093
+ action: {
1094
+ type: isLoading ? "fetch-query-start-loading" : fetchType === "loadMore" ? "fetch-query-loading-more" : "refetching-query-start",
1095
+ payload
1096
+ }
1097
+ }
1098
+ );
1099
+ const currentQuerySize = queryState?.items.length ?? 0;
1100
+ const querySize = (() => {
1101
+ if (fetchType === "loadMore") {
1102
+ return currentQuerySize + size;
1103
+ }
1104
+ if (isLoading)
1105
+ return size;
1106
+ return Math.max(currentQuerySize, size);
1107
+ })();
1108
+ try {
1109
+ const { items, hasMore } = await fetchListFn(payload, querySize);
1110
+ if (fetchCtx.shouldAbort())
1111
+ return false;
1112
+ store.produceState(
1113
+ (draft) => {
1114
+ const query = draft.queries[queryKey];
1115
+ if (!query)
1116
+ return;
1117
+ query.status = "success";
1118
+ query.wasLoaded = true;
1119
+ query.hasMore = hasMore;
1120
+ query.items = [];
1121
+ for (const { data, itemPayload } of items) {
1122
+ const itemKey = getItemKey(itemPayload);
1123
+ draft.items[itemKey] = data;
1124
+ query.items.push(String(itemKey));
1125
+ const itemQuery = draft.itemQueries[itemKey];
1126
+ if (!itemQuery || itemQuery.status !== "loading" && itemQuery.status !== "refetching") {
1127
+ draft.itemQueries[itemKey] = {
1128
+ error: null,
1129
+ refetchOnMount: false,
1130
+ status: "success",
1131
+ wasLoaded: true,
1132
+ payload: itemPayload
1133
+ };
1134
+ }
1135
+ }
1136
+ },
1137
+ {
1138
+ equalityCheck: import_t_state4.deepEqual,
1139
+ action: { type: "fetch-query-success", payload }
1140
+ }
1141
+ );
1142
+ for (const { itemPayload: id } of items) {
1143
+ const itemFetchOrquestrator = fetchItemOrquestrator?.get(String(id));
1144
+ if (itemFetchOrquestrator) {
1145
+ itemFetchOrquestrator.setLastFetchStartTime(fetchCtx.getStartTime());
1146
+ }
1147
+ }
1148
+ return true;
1149
+ } catch (exception) {
1150
+ if (fetchCtx.shouldAbort())
1151
+ return false;
1152
+ const error = errorNormalizer(exception);
1153
+ store.produceState(
1154
+ (draft) => {
1155
+ const query = draft.queries[queryKey];
1156
+ if (!query)
1157
+ return;
1158
+ query.status = "error";
1159
+ query.error = error;
1160
+ },
1161
+ {
1162
+ action: { type: "fetch-query-error", payload, error }
1163
+ }
1164
+ );
1165
+ return false;
1166
+ }
1167
+ }
1168
+ function getQueryState(params) {
1169
+ return store.state.queries[getQueryKey(params)];
1170
+ }
1171
+ function getItemState(itemPayload) {
1172
+ if (typeof itemPayload === "function" || Array.isArray(itemPayload)) {
1173
+ const itemsId = getItemsKeyArray(itemPayload);
1174
+ return filterAndMap(itemsId, ({ itemKey }, ignore2) => {
1175
+ const item = store.state.items[itemKey];
1176
+ const payload = store.state.itemQueries[itemKey]?.payload;
1177
+ return !item || !payload ? ignore2 : { payload, data: item };
1178
+ });
1179
+ }
1180
+ return store.state.items[getItemKey(itemPayload)];
1181
+ }
1182
+ const fetchQueryOrquestrator = createCollectionFetchOrquestrator({
1183
+ fetchFn: fetchQuery,
1184
+ lowPriorityThrottleMs,
1185
+ dynamicRealtimeThrottleMs,
1186
+ mediumPriorityThrottleMs
1187
+ });
1188
+ function scheduleListQueryFetch(fetchType, payload, size) {
1189
+ const multiplePayloads = Array.isArray(payload);
1190
+ const payloads = multiplePayloads ? payload : [payload];
1191
+ const results = payloads.map((param) => {
1192
+ return fetchQueryOrquestrator.get(getQueryKey(param)).scheduleFetch(fetchType, ["load", param, size]);
1193
+ });
1194
+ return multiplePayloads ? results : results[0];
1195
+ }
1196
+ function loadMore(params, size) {
1197
+ const queryState = getQueryState(params);
1198
+ if (!queryState || !queryState.hasMore)
1199
+ return "skipped";
1200
+ return fetchQueryOrquestrator.get(getQueryKey(params)).scheduleFetch("highPriority", ["loadMore", params, size]);
1201
+ }
1202
+ function getQueryItems(query, itemDataSelector) {
1203
+ return filterAndMap(query.items, (itemKey, ignore2) => {
1204
+ const item = store.state.items[itemKey];
1205
+ return item ? itemDataSelector(item, itemKey) : ignore2;
1206
+ });
1207
+ }
1208
+ async function awaitListQueryFetch(params, size = defaultQuerySize) {
1209
+ const queryKey = getQueryKey(params);
1210
+ const wasAborted = await fetchQueryOrquestrator.get(queryKey).awaitFetch(["load", params, size]);
1211
+ if (wasAborted) {
1212
+ return {
1213
+ items: [],
1214
+ error: errorNormalizer(new Error("Aborted")),
1215
+ hasMore: false
1216
+ };
1217
+ }
1218
+ const query = store.state.queries[queryKey];
1219
+ if (!query) {
1220
+ return {
1221
+ items: [],
1222
+ error: errorNormalizer(new Error("Not found")),
1223
+ hasMore: false
1224
+ };
1225
+ }
1226
+ return query.error ? { items: [], error: query.error, hasMore: query.hasMore } : {
1227
+ items: getQueryItems(query, (data, itemKey) => ({ data, itemKey })),
1228
+ error: null,
1229
+ hasMore: query.hasMore
1230
+ };
1231
+ }
1232
+ async function awaitItemFetch(itemPayload) {
1233
+ if (!fetchItemOrquestrator)
1234
+ throw new Error(noFetchFnError);
1235
+ const itemKey = getItemKey(itemPayload);
1236
+ const wasAborted = await fetchItemOrquestrator.get(itemKey).awaitFetch(itemPayload);
1237
+ if (wasAborted) {
1238
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
1239
+ }
1240
+ const item = store.state.items[itemKey];
1241
+ const itemQuery = store.state.itemQueries[itemKey];
1242
+ if (!itemQuery || !item) {
1243
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
1244
+ }
1245
+ return itemQuery.error ? { data: null, error: itemQuery.error } : { data: item, error: null };
1246
+ }
1247
+ function getQueriesKeyArray(payloads) {
1248
+ if (Array.isArray(payloads)) {
1249
+ return payloads.map((payload) => ({
1250
+ key: getQueryKey(payload),
1251
+ payload
1252
+ }));
1253
+ } else if (typeof payloads === "function") {
1254
+ return filterAndMap(
1255
+ Object.entries(store.state.queries),
1256
+ ([queryKey, query], ignore2) => {
1257
+ return payloads(query.payload, query, queryKey) ? {
1258
+ key: queryKey,
1259
+ payload: query.payload
1260
+ } : ignore2;
1261
+ }
1262
+ );
1263
+ } else {
1264
+ return [{ key: getQueryKey(payloads), payload: payloads }];
1265
+ }
1266
+ }
1267
+ const storeEvents = (0, import_mitt4.default)();
1268
+ const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1269
+ function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1270
+ const queriesKey = getQueriesKeyArray(queryPayload);
1271
+ for (const { key } of queriesKey) {
1272
+ store.produceState(
1273
+ (draft) => {
1274
+ const query = draft.queries[key];
1275
+ if (!query)
1276
+ return;
1277
+ query.refetchOnMount = priority;
1278
+ },
1279
+ { action: { type: "invalidate-data", key } }
1280
+ );
1281
+ queryInvalidationWasTriggered.delete(key);
1282
+ storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1283
+ }
1284
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1285
+ invalidateItem(
1286
+ (itemPayload) => queriesKey.some(({ payload }) => {
1287
+ return syncMutationsAndInvalidations.syncItemAndQuery(
1288
+ itemPayload,
1289
+ payload
1290
+ );
1291
+ }),
1292
+ priority,
1293
+ true
1294
+ );
1295
+ invalidateQuery(
1296
+ (queryToInvalidatePayload, _, queryToInvalidateKey) => queriesKey.some((alreadyInvalidatedQueryPayload) => {
1297
+ return queryToInvalidateKey !== alreadyInvalidatedQueryPayload.key && syncMutationsAndInvalidations.syncQueries(
1298
+ alreadyInvalidatedQueryPayload.payload,
1299
+ queryToInvalidatePayload
1300
+ );
1301
+ }),
1302
+ priority,
1303
+ true
1304
+ );
1305
+ }
1306
+ }
1307
+ function defaultItemSelector(data, id) {
1308
+ return { id, data };
1309
+ }
1310
+ function useMultipleListQueries(queries, {
1311
+ itemSelector = defaultItemSelector,
1312
+ omitPayload,
1313
+ returnIdleStatus,
1314
+ returnRefetchingStatus,
1315
+ loadSize,
1316
+ disableRefetchOnMount = globalDisableRefetchOnMount
1317
+ } = {}) {
1318
+ const queriesWithId = useDeepMemo(() => {
1319
+ return queries.map((payload) => {
1320
+ return {
1321
+ key: getQueryKey(payload),
1322
+ payload
1323
+ };
1324
+ });
1325
+ }, [queries]);
1326
+ const dataSelector = (0, import_react5.useCallback)(itemSelector, []);
1327
+ const resultSelector = (0, import_react5.useCallback)(
1328
+ (state) => {
1329
+ return queriesWithId.map(
1330
+ ({
1331
+ key: queryKey,
1332
+ payload
1333
+ }) => {
1334
+ const query = state.queries[queryKey];
1335
+ if (!query) {
1336
+ return {
1337
+ queryKey,
1338
+ status: returnIdleStatus ? "idle" : "loading",
1339
+ items: [],
1340
+ error: null,
1341
+ hasMore: false,
1342
+ payload: omitPayload ? void 0 : payload,
1343
+ isLoading: returnIdleStatus ? false : true
1344
+ };
1345
+ }
1346
+ let status = query.status;
1347
+ if (!returnRefetchingStatus && query.status === "refetching") {
1348
+ status = "success";
1349
+ }
1350
+ return {
1351
+ queryKey,
1352
+ status,
1353
+ items: getQueryItems(query, dataSelector),
1354
+ error: query.error,
1355
+ hasMore: query.hasMore,
1356
+ isLoading: status === "loading",
1357
+ payload: omitPayload ? void 0 : query.payload
1358
+ };
1359
+ }
1360
+ );
1361
+ },
1362
+ [
1363
+ dataSelector,
1364
+ omitPayload,
1365
+ queriesWithId,
1366
+ returnIdleStatus,
1367
+ returnRefetchingStatus
1368
+ ]
1369
+ );
1370
+ const storeState = store.useSelector(resultSelector, {
1371
+ equalityFn: import_t_state4.deepEqual,
1372
+ useExternalDeps: true
1373
+ });
1374
+ useOnMittEvent(storeEvents, "invalidateQuery", (event) => {
1375
+ for (const { key, payload } of queriesWithId) {
1376
+ if (key !== event.queryKey)
1377
+ continue;
1378
+ if (!queryInvalidationWasTriggered.has(key)) {
1379
+ scheduleListQueryFetch(event.priority, payload);
1380
+ queryInvalidationWasTriggered.add(key);
1381
+ }
1382
+ }
1383
+ });
1384
+ const loadSizeConst = useConst(() => loadSize);
1385
+ (0, import_react5.useEffect)(() => {
1386
+ for (const { key: itemId, payload: fetchParams } of queriesWithId) {
1387
+ if (itemId) {
1388
+ if (disableRefetchOnMount) {
1389
+ const itemState = getQueryState(fetchParams);
1390
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1391
+ if (shouldFetch) {
1392
+ scheduleListQueryFetch(
1393
+ itemState?.refetchOnMount || "lowPriority",
1394
+ fetchParams,
1395
+ loadSizeConst
1396
+ );
1397
+ return;
1398
+ }
1399
+ } else {
1400
+ scheduleListQueryFetch("lowPriority", fetchParams, loadSizeConst);
1401
+ }
1402
+ }
1403
+ }
1404
+ }, [disableRefetchOnMount, loadSizeConst, queriesWithId]);
1405
+ return storeState;
1406
+ }
1407
+ function useListQuery(payload, options = {}) {
1408
+ const { ensureIsLoaded } = options;
1409
+ const query = (0, import_react5.useMemo)(
1410
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
1411
+ [payload]
1412
+ );
1413
+ const queryResult = useMultipleListQueries(query, options);
1414
+ const result = (0, import_react5.useMemo)(
1415
+ () => queryResult[0] ?? {
1416
+ payload: void 0,
1417
+ error: null,
1418
+ hasMore: false,
1419
+ isLoading: false,
1420
+ status: "idle",
1421
+ queryKey: "",
1422
+ items: []
1423
+ },
1424
+ [queryResult]
1425
+ );
1426
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1427
+ ensureIsLoaded,
1428
+ !!payload,
1429
+ () => {
1430
+ if (payload) {
1431
+ scheduleListQueryFetch("highPriority", payload);
1432
+ }
1433
+ }
1434
+ );
1435
+ (0, import_t_state4.useSubscribeToStore)(store, ({ observe }) => {
1436
+ if (!ensureIsLoaded)
1437
+ return;
1438
+ observe.ifSelector((state) => state.queries[result.queryKey]?.status).change.then(({ current }) => {
1439
+ if (current === "success" || current === "error") {
1440
+ emitIsLoadedEvt("isLoaded", true);
1441
+ }
1442
+ });
1443
+ });
1444
+ return useModifyResult(result);
1445
+ }
1446
+ async function fetchItem(fetchCtx, itemPayload) {
1447
+ if (!fetchItemOrquestrator) {
1448
+ throw new Error(noFetchFnError);
1449
+ }
1450
+ const itemKey = getCacheId(itemPayload);
1451
+ const isLoaded = !store.state.itemQueries[itemKey]?.wasLoaded;
1452
+ store.produceState(
1453
+ (draft) => {
1454
+ const itemQuery = draft.itemQueries[itemKey];
1455
+ if (!itemQuery) {
1456
+ draft.itemQueries[itemKey] = {
1457
+ status: "loading",
1458
+ error: null,
1459
+ wasLoaded: false,
1460
+ refetchOnMount: false,
1461
+ payload: (0, import_json2.klona)(itemPayload)
1462
+ };
1463
+ return;
1464
+ }
1465
+ itemQuery.status = itemQuery.wasLoaded ? "refetching" : "loading";
1466
+ itemQuery.error = null;
1467
+ itemQuery.refetchOnMount = false;
1468
+ },
1469
+ {
1470
+ equalityCheck: import_t_state4.deepEqual,
1471
+ action: {
1472
+ type: isLoaded ? "fetch-item-start" : "fetch-item-refetch-start",
1473
+ itemPayload
1474
+ }
1475
+ }
1476
+ );
1477
+ try {
1478
+ const item = await fetchItemFn(itemPayload);
1479
+ if (fetchCtx.shouldAbort())
1480
+ return false;
1481
+ store.produceState(
1482
+ (draft) => {
1483
+ const itemQuery = draft.itemQueries[itemKey];
1484
+ if (!itemQuery)
1485
+ return;
1486
+ itemQuery.status = "success";
1487
+ itemQuery.wasLoaded = true;
1488
+ draft.items[itemKey] = item;
1489
+ },
1490
+ {
1491
+ equalityCheck: import_t_state4.deepEqual,
1492
+ action: { type: "fetch-item-success", itemPayload }
1493
+ }
1494
+ );
1495
+ return true;
1496
+ } catch (exception) {
1497
+ if (fetchCtx.shouldAbort())
1498
+ return false;
1499
+ const error = errorNormalizer(exception);
1500
+ store.produceState(
1501
+ (draft) => {
1502
+ const itemQuery = draft.itemQueries[itemKey];
1503
+ if (!itemQuery)
1504
+ return;
1505
+ itemQuery.status = "error";
1506
+ itemQuery.error = error;
1507
+ },
1508
+ {
1509
+ action: { type: "fetch-item-error", itemPayload }
1510
+ }
1511
+ );
1512
+ return false;
1513
+ }
1514
+ }
1515
+ const fetchItemOrquestrator = fetchItemFn && createCollectionFetchOrquestrator({
1516
+ fetchFn: fetchItem,
1517
+ lowPriorityThrottleMs,
1518
+ dynamicRealtimeThrottleMs,
1519
+ mediumPriorityThrottleMs
1520
+ });
1521
+ function scheduleItemFetch(fetchType, itemPayload) {
1522
+ if (!fetchItemOrquestrator) {
1523
+ throw new Error(noFetchFnError);
1524
+ }
1525
+ const fetchMultiple = Array.isArray(itemPayload);
1526
+ const itemsId = fetchMultiple ? itemPayload : [itemPayload];
1527
+ const results = itemsId.map((payload) => {
1528
+ const itemKey = getCacheId(payload);
1529
+ return fetchItemOrquestrator.get(itemKey).scheduleFetch(fetchType, payload);
1530
+ });
1531
+ return fetchMultiple ? results : results[0];
1532
+ }
1533
+ function getItemsKeyArray(itemsPayload) {
1534
+ if (Array.isArray(itemsPayload)) {
1535
+ return itemsPayload.map((payload) => ({
1536
+ itemKey: getItemKey(payload),
1537
+ payload
1538
+ }));
1539
+ }
1540
+ if (typeof itemsPayload === "function") {
1541
+ return filterAndMap(
1542
+ Object.entries(store.state.items),
1543
+ ([itemKey, item], ignore2) => {
1544
+ const payload = store.state.itemQueries[itemKey]?.payload;
1545
+ if (item === null || !payload)
1546
+ return ignore2;
1547
+ return itemsPayload(payload, item) ? { itemKey, payload } : ignore2;
1548
+ }
1549
+ );
1550
+ }
1551
+ return [{ payload: itemsPayload, itemKey: getItemKey(itemsPayload) }];
1552
+ }
1553
+ const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
1554
+ function invalidateItem(itemId, priority = "highPriority", ignoreInvalidationSync = false) {
1555
+ if (!fetchItemOrquestrator) {
1556
+ throw new Error(noFetchFnError);
1557
+ }
1558
+ const itemsKey = getItemsKeyArray(itemId);
1559
+ for (const { itemKey } of itemsKey) {
1560
+ store.produceState(
1561
+ (draft) => {
1562
+ const query = draft.itemQueries[itemKey];
1563
+ if (!query)
1564
+ return;
1565
+ query.refetchOnMount = priority;
1566
+ },
1567
+ { action: { type: "invalidate-item", queryKey: itemKey } }
1568
+ );
1569
+ itemInvalidationWasTriggered.delete(itemKey);
1570
+ storeEvents.emit("invalidateItem", { priority, itemKey });
1571
+ }
1572
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1573
+ invalidateQuery(
1574
+ (query) => itemsKey.some(
1575
+ ({ payload }) => syncMutationsAndInvalidations.syncItemAndQuery(payload, query)
1576
+ ),
1577
+ priority,
1578
+ true
1579
+ );
1580
+ }
1581
+ }
1582
+ function startItemMutation(itemId) {
1583
+ if (!fetchItemOrquestrator)
1584
+ throw new Error(noFetchFnError);
1585
+ const itemsKey = getItemsKeyArray(itemId);
1586
+ const endMutations = [];
1587
+ for (const { itemKey, payload } of itemsKey) {
1588
+ endMutations.push(fetchItemOrquestrator.get(itemKey).startMutation());
1589
+ if (syncMutationsAndInvalidations) {
1590
+ for (const [queryKey, query] of Object.entries(store.state.queries)) {
1591
+ if (syncMutationsAndInvalidations.syncItemAndQuery(
1592
+ payload,
1593
+ query.payload
1594
+ )) {
1595
+ endMutations.push(
1596
+ fetchQueryOrquestrator.get(queryKey).startMutation()
1597
+ );
1598
+ }
1599
+ }
1600
+ }
1601
+ }
1602
+ return () => {
1603
+ for (const endMutation of endMutations) {
1604
+ endMutation();
1605
+ }
1606
+ };
1607
+ }
1608
+ function defaultItemDataSelector(data) {
1609
+ return data;
1610
+ }
1611
+ function useMultipleItems(itemsPayload_, {
1612
+ selector = defaultItemDataSelector,
1613
+ returnIdleStatus,
1614
+ returnRefetchingStatus,
1615
+ disableRefetchOnMount
1616
+ } = {}) {
1617
+ const dataSelector = (0, import_react5.useCallback)(selector, []);
1618
+ const memoizedItemKeys = useDeepMemo(
1619
+ () => itemsPayload_.map(
1620
+ (itemPayload) => ({
1621
+ payload: itemPayload,
1622
+ itemKey: getItemKey(itemPayload)
1623
+ })
1624
+ ),
1625
+ [itemsPayload_]
1626
+ );
1627
+ const resultSelector = (0, import_react5.useCallback)(
1628
+ (state) => {
1629
+ return memoizedItemKeys.map(
1630
+ ({
1631
+ itemKey,
1632
+ payload
1633
+ }) => {
1634
+ const itemQuery = state.itemQueries[itemKey];
1635
+ const itemState = state.items[itemKey];
1636
+ if (itemQuery === null) {
1637
+ return {
1638
+ status: "deleted",
1639
+ error: null,
1640
+ isLoading: false,
1641
+ payload,
1642
+ data: dataSelector(null, itemKey)
1643
+ };
1644
+ }
1645
+ if (!itemQuery) {
1646
+ return {
1647
+ status: returnIdleStatus ? "idle" : "loading",
1648
+ error: null,
1649
+ isLoading: returnIdleStatus ? false : true,
1650
+ payload,
1651
+ data: dataSelector(null, itemKey)
1652
+ };
1653
+ }
1654
+ let status = itemQuery.status;
1655
+ if (!returnRefetchingStatus && itemQuery.status === "refetching") {
1656
+ status = "success";
1657
+ }
1658
+ return {
1659
+ status,
1660
+ error: itemQuery.error,
1661
+ isLoading: status === "loading",
1662
+ data: dataSelector(itemState ?? null, itemKey),
1663
+ payload
1664
+ };
1665
+ }
1666
+ );
1667
+ },
1668
+ [
1669
+ dataSelector,
1670
+ memoizedItemKeys,
1671
+ returnIdleStatus,
1672
+ returnRefetchingStatus
1673
+ ]
1674
+ );
1675
+ const storeState = store.useSelector(resultSelector, {
1676
+ equalityFn: import_t_state4.deepEqual,
1677
+ useExternalDeps: true
1678
+ });
1679
+ useOnMittEvent(storeEvents, "invalidateItem", (event) => {
1680
+ for (const { payload, itemKey } of memoizedItemKeys) {
1681
+ if (itemKey !== event.itemKey)
1682
+ continue;
1683
+ if (!itemInvalidationWasTriggered.has(itemKey)) {
1684
+ scheduleItemFetch(event.priority, payload);
1685
+ itemInvalidationWasTriggered.add(itemKey);
1686
+ }
1687
+ }
1688
+ });
1689
+ (0, import_react5.useEffect)(() => {
1690
+ for (const { payload, itemKey } of memoizedItemKeys) {
1691
+ if (itemKey) {
1692
+ if (disableRefetchOnMount) {
1693
+ const itemState = store.state.itemQueries[itemKey];
1694
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1695
+ if (shouldFetch) {
1696
+ scheduleItemFetch(
1697
+ itemState?.refetchOnMount || "lowPriority",
1698
+ payload
1699
+ );
1700
+ return;
1701
+ }
1702
+ } else {
1703
+ scheduleItemFetch("lowPriority", payload);
1704
+ }
1705
+ }
1706
+ }
1707
+ }, [disableRefetchOnMount, memoizedItemKeys]);
1708
+ return storeState;
1709
+ }
1710
+ function useItem(itemPayload, options = {}) {
1711
+ const { ensureIsLoaded } = options;
1712
+ const query = (0, import_react5.useMemo)(
1713
+ () => itemPayload === false || itemPayload === null || itemPayload === void 0 ? [] : [itemPayload],
1714
+ [itemPayload]
1715
+ );
1716
+ const queryResult = useMultipleItems(query, options);
1717
+ const memoizedSelector = (0, import_react5.useCallback)(
1718
+ options.selector ?? defaultItemDataSelector,
1719
+ []
1720
+ );
1721
+ const result = (0, import_react5.useMemo)(
1722
+ () => queryResult[0] ?? {
1723
+ error: null,
1724
+ isLoading: false,
1725
+ status: "idle",
1726
+ data: memoizedSelector(null, ""),
1727
+ payload: itemPayload || null
1728
+ },
1729
+ [itemPayload, memoizedSelector, queryResult]
1730
+ );
1731
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1732
+ ensureIsLoaded,
1733
+ !!itemPayload,
1734
+ () => {
1735
+ if (itemPayload) {
1736
+ scheduleItemFetch("highPriority", itemPayload);
1737
+ }
1738
+ }
1739
+ );
1740
+ (0, import_t_state4.useSubscribeToStore)(store, ({ observe }) => {
1741
+ if (!ensureIsLoaded || !itemPayload)
1742
+ return;
1743
+ observe.ifSelector((state) => state.itemQueries[itemPayload]?.status).change.then(({ current }) => {
1744
+ if (current === "success" || current === "error") {
1745
+ emitIsLoadedEvt("isLoaded", true);
1746
+ }
1747
+ });
1748
+ });
1749
+ return useModifyResult(result);
1750
+ }
1751
+ function updateItemState(itemIds, produceNewData, ifNothingWasUpdated) {
1752
+ const itemKeys = getItemsKeyArray(itemIds);
1753
+ let someItemWasUpdated = false;
1754
+ store.batch(
1755
+ () => {
1756
+ store.produceState((draftState) => {
1757
+ for (const { itemKey, payload } of itemKeys) {
1758
+ const item = draftState.items[itemKey];
1759
+ if (!item)
1760
+ continue;
1761
+ someItemWasUpdated = true;
1762
+ const newData = produceNewData(item, payload);
1763
+ if (newData) {
1764
+ draftState.items[itemKey] = newData;
1765
+ }
1766
+ }
1767
+ });
1768
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
1769
+ ifNothingWasUpdated();
1770
+ }
1771
+ },
1772
+ { type: "update-item-state", item: itemKeys }
1773
+ );
1774
+ return someItemWasUpdated;
1775
+ }
1776
+ function addItemToState(itemPayload, data) {
1777
+ const itemKey = getItemKey(itemPayload);
1778
+ store.produceState(
1779
+ (draftState) => {
1780
+ draftState.items[itemKey] = data;
1781
+ draftState.itemQueries[itemKey] = {
1782
+ status: "success",
1783
+ wasLoaded: true,
1784
+ refetchOnMount: false,
1785
+ error: null,
1786
+ payload: (0, import_json2.klona)(itemPayload)
1787
+ };
1788
+ },
1789
+ { action: { type: "create-item-state", itemPayload } }
1790
+ );
1791
+ }
1792
+ function deleteItemState(itemId) {
1793
+ const itemsId = getItemsKeyArray(itemId);
1794
+ store.produceState(
1795
+ (draftState) => {
1796
+ for (const { itemKey } of itemsId) {
1797
+ draftState.items[itemKey] = null;
1798
+ draftState.itemQueries[itemKey] = null;
1799
+ for (const query of Object.values(draftState.queries)) {
1800
+ if (query.items.includes(itemKey)) {
1801
+ query.items = query.items.filter((i) => i !== itemKey);
1802
+ }
1803
+ }
1804
+ }
1805
+ },
1806
+ { action: { type: "delete-item-state", itemId } }
1807
+ );
1808
+ }
1809
+ if (!disableRefetchOnWindowFocus) {
1810
+ let handleFocus2 = function() {
1811
+ invalidateQuery(() => true, "lowPriority");
1812
+ invalidateItem(() => true, "lowPriority");
1813
+ };
1814
+ var handleFocus = handleFocus2;
1815
+ window.addEventListener("focus", handleFocus2);
1816
+ window.addEventListener("visibilitychange", handleFocus2);
1817
+ }
1818
+ return {
1819
+ store,
1820
+ scheduleListQueryFetch,
1821
+ getQueryState,
1822
+ getQueryKey,
1823
+ deleteItemState,
1824
+ getItemState,
1825
+ loadMore,
1826
+ invalidateQuery,
1827
+ invalidateItem,
1828
+ scheduleItemFetch,
1829
+ awaitItemFetch,
1830
+ awaitListQueryFetch,
1831
+ useMultipleListQueries,
1832
+ useListQuery,
1833
+ getItemKey,
1834
+ useItem,
1835
+ useMultipleItems,
1836
+ addItemToState,
1837
+ updateItemState,
1838
+ startItemMutation
1839
+ };
1840
+ }
1841
+ // Annotate the CommonJS export names for ESM import in node:
1842
+ 0 && (module.exports = {
1843
+ newTSDFCollectionStore,
1844
+ newTSDFDocumentStore,
1845
+ newTSDFListQueryStore
1846
+ });