tsdf 8.0.0-beta.1 → 8.0.0-beta.2

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 +1 -0
  2. package/dist/main.d.ts +269 -0
  3. package/dist/main.js +1 -0
  4. package/package.json +4 -1
  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
@@ -1,272 +0,0 @@
1
- import produce from 'immer';
2
- import mitt from 'mitt';
3
- import { useCallback, useEffect } from 'react';
4
- import { Store, useSubscribeToStore } from 't-state';
5
- import {
6
- createFetchOrquestrator,
7
- FetchType,
8
- ScheduleFetchResults,
9
- FetchContext,
10
- } from './fetchOrquestrator';
11
- import { Status, ValidStoreState } from './storeShared';
12
- import { useEnsureIsLoaded } from './useEnsureIsLoaded';
13
- import { useOnMittEvent } from './utils/hooks';
14
-
15
- type DocumentStatus = Status | 'idle';
16
-
17
- export type TSDFDocumentStoreState<State extends ValidStoreState, NError> = {
18
- data: State | null;
19
- error: NError | null;
20
- status: DocumentStatus;
21
- refetchOnMount: false | FetchType;
22
- };
23
-
24
- export type TSDFUseDocumentReturn<Selected, NError> = {
25
- status: DocumentStatus;
26
- data: Selected;
27
- error: NError | null;
28
- isLoading: boolean;
29
- };
30
-
31
- export function newTSDFDocumentStore<State extends ValidStoreState, NError>({
32
- debugName,
33
- fetchFn,
34
- initialData,
35
- disableRefetchOnWindowFocus,
36
- disableRefetchOnMount: globalDisableRefetchOnMount,
37
- lowPriorityThrottleMs,
38
- mediumPriorityThrottleMs,
39
- dynamicRealtimeThrottleMs,
40
- errorNormalizer,
41
- }: {
42
- debugName?: string;
43
- fetchFn: () => Promise<State>;
44
- initialData?: State;
45
- errorNormalizer: (exception: unknown) => NError;
46
- disableRefetchOnWindowFocus?: boolean;
47
- disableRefetchOnMount?: boolean;
48
- lowPriorityThrottleMs?: number;
49
- mediumPriorityThrottleMs?: number;
50
- dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
51
- }) {
52
- type DocState = TSDFDocumentStoreState<State, NError>;
53
-
54
- const store = new Store<DocState>({
55
- debugName,
56
- state: {
57
- data: initialData ?? null,
58
- error: null,
59
- status: initialData ? 'success' : 'idle',
60
- refetchOnMount: false,
61
- },
62
- });
63
-
64
- async function fetch(fetchCtx: FetchContext, _: null): Promise<boolean> {
65
- store.setPartialState(
66
- {
67
- status: store.state.status === 'success' ? 'refetching' : 'loading',
68
- error: null,
69
- refetchOnMount: false,
70
- },
71
- {
72
- action:
73
- store.state.status === 'success'
74
- ? 'fetch-start-refetching'
75
- : 'fetch-start-loading',
76
- },
77
- );
78
-
79
- try {
80
- const data = await fetchFn();
81
-
82
- if (fetchCtx.shouldAbort()) return false;
83
-
84
- store.setPartialState(
85
- {
86
- data,
87
- status: 'success',
88
- },
89
- { action: 'fetch-success' },
90
- );
91
-
92
- return true;
93
- } catch (exception) {
94
- if (fetchCtx.shouldAbort()) return false;
95
-
96
- store.setPartialState(
97
- {
98
- error: errorNormalizer(exception),
99
- status: 'error',
100
- },
101
- { action: 'fetch-error' },
102
- );
103
-
104
- return false;
105
- }
106
- }
107
-
108
- const fetchOrquestrator = createFetchOrquestrator<null>({
109
- fetchFn: fetch,
110
- lowPriorityThrottleMs,
111
- dynamicRealtimeThrottleMs,
112
- mediumPriorityThrottleMs,
113
- });
114
-
115
- function scheduleFetch(fetchType: FetchType): ScheduleFetchResults {
116
- return fetchOrquestrator.scheduleFetch(fetchType, null);
117
- }
118
-
119
- async function awaitFetch(): Promise<
120
- { data: State; error: null } | { data: null; error: NError }
121
- > {
122
- const wasAborted = await fetchOrquestrator.awaitFetch(null);
123
-
124
- if (wasAborted) {
125
- return { data: null, error: errorNormalizer(new Error('Aborted')) };
126
- }
127
-
128
- if (!store.state.data) {
129
- return { data: null, error: errorNormalizer(new Error('No data')) };
130
- }
131
-
132
- return store.state.error
133
- ? { data: null, error: store.state.error }
134
- : { data: store.state.data, error: null };
135
- }
136
-
137
- const storeEvents = mitt<{ invalidateData: FetchType }>();
138
-
139
- let invalidationWasTriggered = false;
140
-
141
- function invalidateData(priority: FetchType = 'highPriority') {
142
- store.setKey('refetchOnMount', priority, { action: 'invalidate-data' });
143
- invalidationWasTriggered = false;
144
- storeEvents.emit('invalidateData', priority);
145
- }
146
-
147
- function useDocument<Selected = State | null>({
148
- selector,
149
- disabled,
150
- returnRefetchingStatus,
151
- disableRefetchOnMount = globalDisableRefetchOnMount,
152
- returnIdleStatus = !!disabled,
153
- ensureIsLoaded,
154
- }: {
155
- selector?: (data: State | null) => Selected;
156
- disabled?: boolean;
157
- disableRefetchOnMount?: boolean;
158
- returnIdleStatus?: boolean;
159
- ensureIsLoaded?: boolean;
160
- returnRefetchingStatus?: boolean;
161
- } = {}) {
162
- const storeStateSelector = useCallback(
163
- (state: DocState): TSDFUseDocumentReturn<Selected, NError> => {
164
- const { error } = state;
165
-
166
- const data = selector ? selector(state.data) : (state.data as Selected);
167
-
168
- let status = state.status;
169
-
170
- if (!returnIdleStatus && status === 'idle') {
171
- status = 'loading';
172
- }
173
-
174
- if (!returnRefetchingStatus && status === 'refetching') {
175
- status = 'success';
176
- }
177
-
178
- return {
179
- data,
180
- error,
181
- status,
182
- isLoading: status === 'loading',
183
- };
184
- },
185
- [returnRefetchingStatus, returnIdleStatus, selector],
186
- );
187
-
188
- const storeState = store.useSelector(storeStateSelector, {
189
- useExternalDeps: true,
190
- });
191
-
192
- useOnMittEvent(storeEvents, 'invalidateData', (priority) => {
193
- if (!invalidationWasTriggered) {
194
- scheduleFetch(priority);
195
- invalidationWasTriggered = true;
196
- }
197
- });
198
-
199
- useEffect(() => {
200
- if (disabled) return;
201
-
202
- if (disableRefetchOnMount) {
203
- const shouldFetch =
204
- store.state.refetchOnMount || store.state.status === 'idle';
205
-
206
- if (shouldFetch) {
207
- scheduleFetch(store.state.refetchOnMount || 'lowPriority');
208
- }
209
- } else {
210
- scheduleFetch('lowPriority');
211
- }
212
- }, [disableRefetchOnMount, disabled]);
213
-
214
- const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
215
- ensureIsLoaded,
216
- !disabled,
217
- () => {
218
- scheduleFetch('highPriority');
219
- },
220
- );
221
-
222
- useSubscribeToStore(store, ({ observe }) => {
223
- observe
224
- .ifSelector((state) => state.status)
225
- .change.then(({ current }) => {
226
- if (current === 'success' || current === 'error') {
227
- emitIsLoadedEvt('isLoaded', true);
228
- }
229
- });
230
- });
231
-
232
- return useModifyResult(storeState);
233
- }
234
-
235
- function updateState(
236
- produceNewData: (draftData: State) => State | void | undefined,
237
- ) {
238
- store.setKey(
239
- 'data',
240
- (current) => {
241
- if (!current) return current;
242
-
243
- return produce(current, produceNewData);
244
- },
245
- { action: 'update-state' },
246
- );
247
- }
248
-
249
- if (!disableRefetchOnWindowFocus) {
250
- function handleFocus() {
251
- invalidateData('lowPriority');
252
- }
253
-
254
- window.addEventListener('focus', handleFocus);
255
- window.addEventListener('visibilitychange', handleFocus);
256
- }
257
-
258
- return {
259
- store,
260
- awaitFetch,
261
- scheduleFetch,
262
- invalidateData,
263
- useDocument,
264
- updateState,
265
- startMutation: fetchOrquestrator.startMutation,
266
- };
267
- }
268
-
269
- export type TSDFDocumentStore<
270
- State extends ValidStoreState,
271
- NError,
272
- > = ReturnType<typeof newTSDFDocumentStore<State, NError>>;
@@ -1,335 +0,0 @@
1
- export type FetchContext = {
2
- shouldAbort: () => boolean;
3
- getStartTime: () => number;
4
- };
5
-
6
- export type FetchType = 'lowPriority' | 'highPriority' | 'realtimeUpdate';
7
-
8
- type Events = 'scheduled-fetch-started' | 'scheduled-rt-fetch-started';
9
-
10
- export type ScheduleFetchResults =
11
- | 'skipped'
12
- | 'started'
13
- | 'scheduled'
14
- | 'rt-scheduled';
15
-
16
- export type FetchOrquestrator<T> = ReturnType<
17
- typeof createFetchOrquestrator<T>
18
- >;
19
-
20
- export type CreateFetchOrquestratorOptions<T> = {
21
- fetchFn: (fetchContext: FetchContext, params: T) => Promise<boolean>;
22
- on?: (event: Events) => void;
23
- lowPriorityThrottleMs?: number;
24
- mediumPriorityThrottleMs?: number;
25
- dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
26
- };
27
-
28
- export function createFetchOrquestrator<T>({
29
- fetchFn,
30
- on,
31
- mediumPriorityThrottleMs = 10,
32
- lowPriorityThrottleMs = 200,
33
- dynamicRealtimeThrottleMs,
34
- }: CreateFetchOrquestratorOptions<T>) {
35
- const fetchs: {
36
- inProgress_: { startTime: number; onEnd: (() => void)[] } | null;
37
- scheduled_: { params: T } | null;
38
- realtimeScheduled_: { timeoutId: number } | null;
39
- } = {
40
- inProgress_: null,
41
- scheduled_: null,
42
- realtimeScheduled_: null,
43
- };
44
- let lastMutationIdStarted = 0;
45
- let lastFetchIdStarted = 0;
46
- let mutationIsInProgress = false;
47
- let lastFetchStartTime = 0;
48
- let lastFetchDuration = 0;
49
- let onMutationEnd: (() => void)[] = [];
50
- let lastFetchWasAborted = false;
51
- let abortFetchsBeforeOrEqual = 0;
52
-
53
- function setLastFetchDurantion(duration: number) {
54
- lastFetchDuration = duration;
55
- }
56
-
57
- function setLastFetchStartTime(startTime: number) {
58
- lastFetchStartTime = startTime;
59
- }
60
-
61
- function flushScheduledFetch() {
62
- if (fetchs.scheduled_) {
63
- on?.('scheduled-fetch-started');
64
- const params = fetchs.scheduled_.params;
65
- fetchs.scheduled_ = null;
66
- startFetch(params, Date.now());
67
- }
68
- }
69
-
70
- function startMutation() {
71
- mutationIsInProgress = true;
72
- abortFetchsBeforeOrEqual = lastFetchIdStarted;
73
- fetchs.inProgress_ = null;
74
-
75
- const id = getAutoIncrementId();
76
- lastMutationIdStarted = id;
77
-
78
- return () => endMutation(id);
79
- }
80
-
81
- function endMutation(id: number): boolean {
82
- if (id === lastMutationIdStarted) {
83
- mutationIsInProgress = false;
84
-
85
- if (onMutationEnd.length > 0) {
86
- onMutationEnd.forEach((cb) => cb());
87
- onMutationEnd = [];
88
- }
89
-
90
- flushScheduledFetch();
91
- return true;
92
- }
93
-
94
- return false;
95
- }
96
-
97
- function getFetchs() {
98
- return fetchs;
99
- }
100
-
101
- async function startFetch(params: T, startTime: number): Promise<boolean> {
102
- if (fetchs.inProgress_) {
103
- throw new Error('[tsdf] Fetch already in progress');
104
- }
105
-
106
- const id = getAutoIncrementId();
107
- lastFetchIdStarted = id;
108
-
109
- lastFetchWasAborted = false;
110
- fetchs.inProgress_ = { startTime, onEnd: [] };
111
- const prevFetchStartTime = lastFetchStartTime;
112
- lastFetchStartTime = startTime;
113
-
114
- function shouldAbort() {
115
- const abort =
116
- id !== lastFetchIdStarted ||
117
- mutationIsInProgress ||
118
- id <= abortFetchsBeforeOrEqual;
119
-
120
- lastFetchWasAborted = abort;
121
-
122
- return abort;
123
- }
124
-
125
- const success = await fetchFn(
126
- {
127
- shouldAbort,
128
- getStartTime: () => startTime,
129
- },
130
- params,
131
- );
132
-
133
- const currentFetchs = getFetchs();
134
-
135
- if (!currentFetchs.inProgress_) {
136
- lastFetchStartTime = prevFetchStartTime;
137
- return false;
138
- }
139
-
140
- if (success) {
141
- lastFetchDuration = Date.now() - startTime;
142
- }
143
-
144
- if (currentFetchs.realtimeScheduled_) {
145
- clearTimeout(currentFetchs.realtimeScheduled_.timeoutId);
146
- fetchs.realtimeScheduled_ = null;
147
- }
148
-
149
- const onEnd = currentFetchs.inProgress_.onEnd;
150
-
151
- currentFetchs.inProgress_ = null;
152
-
153
- if (onEnd.length > 0) {
154
- onEnd.forEach((cb) => cb());
155
- }
156
-
157
- flushScheduledFetch();
158
-
159
- return true;
160
- }
161
-
162
- function scheduleFetch(
163
- fetchType: FetchType,
164
- params: T,
165
- ): ScheduleFetchResults {
166
- const startTime = Date.now();
167
-
168
- if (dynamicRealtimeThrottleMs && fetchType === 'realtimeUpdate') {
169
- if (scheduleRTU(startTime, params)) {
170
- return 'rt-scheduled';
171
- }
172
- }
173
-
174
- if (shouldSkipFetch(fetchType, startTime)) {
175
- return 'skipped';
176
- }
177
-
178
- if (shouldScheduleFetch(fetchType, params)) {
179
- return 'scheduled';
180
- }
181
-
182
- startFetch(params, startTime);
183
-
184
- return 'started';
185
- }
186
-
187
- function shouldSkipFetch(fetchType: FetchType, startTime: number): boolean {
188
- if (fetchType === 'highPriority') {
189
- if (fetchs.inProgress_) {
190
- const timeSinceLastFetch = startTime - fetchs.inProgress_.startTime;
191
-
192
- if (timeSinceLastFetch < mediumPriorityThrottleMs) {
193
- return true;
194
- }
195
- }
196
- }
197
-
198
- if (fetchType === 'lowPriority') {
199
- if (fetchs.inProgress_ || fetchs.scheduled_ || mutationIsInProgress) {
200
- return true;
201
- }
202
-
203
- if (lastFetchStartTime) {
204
- const timeSinceLastFetch = startTime - lastFetchStartTime;
205
-
206
- if (timeSinceLastFetch < lowPriorityThrottleMs) {
207
- return true;
208
- }
209
- }
210
- }
211
-
212
- return false;
213
- }
214
-
215
- function shouldScheduleFetch(priority: FetchType, params: T): boolean {
216
- const shouldSchedule = (() => {
217
- if (priority === 'lowPriority') {
218
- return false;
219
- }
220
-
221
- return !!fetchs.inProgress_ || !!mutationIsInProgress;
222
- })();
223
-
224
- if (shouldSchedule) {
225
- fetchs.scheduled_ = { params };
226
- }
227
-
228
- return shouldSchedule;
229
- }
230
-
231
- function addDelayedRTU(startTime: number, params: T): boolean {
232
- if (!dynamicRealtimeThrottleMs) return false;
233
-
234
- const timeSinceLastFetch =
235
- startTime - (lastFetchStartTime + lastFetchDuration);
236
-
237
- const minimumRealtimeInterval =
238
- dynamicRealtimeThrottleMs(lastFetchDuration);
239
-
240
- if (timeSinceLastFetch >= minimumRealtimeInterval) return false;
241
-
242
- const delay = minimumRealtimeInterval - timeSinceLastFetch;
243
-
244
- fetchs.realtimeScheduled_ = {
245
- timeoutId: window.setTimeout(() => {
246
- fetchs.realtimeScheduled_ = null;
247
- on?.('scheduled-rt-fetch-started');
248
- startFetch(params, Date.now());
249
- }, delay),
250
- };
251
-
252
- return true;
253
- }
254
-
255
- function scheduleRTU(startTime: number, params: T): boolean {
256
- if (
257
- !lastFetchDuration ||
258
- !lastFetchStartTime ||
259
- !dynamicRealtimeThrottleMs
260
- ) {
261
- return false;
262
- }
263
-
264
- if (fetchs.realtimeScheduled_) {
265
- return true;
266
- }
267
-
268
- if (fetchs.inProgress_) {
269
- fetchs.inProgress_.onEnd.push(() => {
270
- addDelayedRTU(Date.now(), params);
271
- });
272
-
273
- return true;
274
- } else if (mutationIsInProgress) {
275
- onMutationEnd.push(() => {
276
- const added = addDelayedRTU(Date.now(), params);
277
-
278
- if (!added) {
279
- on?.('scheduled-rt-fetch-started');
280
- scheduleFetch('highPriority', params);
281
- }
282
- });
283
-
284
- return true;
285
- } else {
286
- if (!addDelayedRTU(startTime, params)) {
287
- return false;
288
- }
289
- }
290
-
291
- return true;
292
- }
293
-
294
- function addOnFetchEnd(cb: () => void) {
295
- if (fetchs.inProgress_) {
296
- fetchs.inProgress_.onEnd.push(cb);
297
- }
298
- }
299
-
300
- async function awaitFetch(params: T): Promise<boolean> {
301
- scheduleFetch('highPriority', params);
302
-
303
- if (fetchs.inProgress_) {
304
- await new Promise<true>((resolve) => {
305
- addOnFetchEnd(() => resolve(true));
306
- });
307
- }
308
-
309
- return lastFetchWasAborted;
310
- }
311
-
312
- return {
313
- scheduleFetch,
314
- awaitFetch,
315
- startMutation,
316
- get hasPendingFetch() {
317
- return (
318
- !!fetchs.inProgress_ || !!fetchs.scheduled_ || !!fetchs.realtimeScheduled_
319
- );
320
- },
321
- get fetchIsInProgress() {
322
- return !!fetchs.inProgress_;
323
- },
324
- get mutationIsInProgress() {
325
- return mutationIsInProgress;
326
- },
327
- setLastFetchDurantion,
328
- setLastFetchStartTime,
329
- };
330
- }
331
-
332
- let autoIncrementId = 0;
333
- export function getAutoIncrementId() {
334
- return ++autoIncrementId;
335
- }