tsdf 8.0.0-beta.1 → 8.0.0-beta.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.
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,296 +0,0 @@
1
- /* eslint-disable @typescript-eslint/ban-types */
2
- import produce from 'immer';
3
- import { randomInt } from '../utils/math';
4
- import { sleep } from '../utils/sleep';
5
- import { simplifyArraySnapshot } from '../utils/storeUtils';
6
-
7
- export function mockServerResource<Data, S = Data>({
8
- initialData,
9
- randomTimeout,
10
- logFetchs,
11
- fetchSelector = (data) => data as unknown as S,
12
- }: {
13
- initialData: Data;
14
- logFetchs?: boolean;
15
- randomTimeout?: [number, number] | true;
16
- fetchSelector?: (data: Data | null, params: string) => S | 'notFound';
17
- }) {
18
- type Timeout = number | [number, number] | ((param: string) => number);
19
-
20
- let data = initialData;
21
- let timeout: Timeout = randomTimeout ? [30, 100] : 30;
22
- let lastTimeout: Timeout = timeout;
23
- let lastTimeoutMs = 0;
24
- let error: Error | string | null = null;
25
- let numOfFetchs = 0;
26
- let waitNextFetchCompleteCall = 0;
27
- let onUpdateServerData:
28
- | ((prevAndData: { prev: Data; data: Data }) => void)
29
- | null = null;
30
- let fetchs: {
31
- result?: Data;
32
- error?: string;
33
- time: { start: number; end: number };
34
- params: string;
35
- started: number;
36
- duration: number;
37
- }[] = [];
38
-
39
- let startTime = Date.now();
40
-
41
- function reset() {
42
- data = initialData;
43
- timeout = randomTimeout ? [30, 100] : 30;
44
- lastTimeout = timeout;
45
- lastTimeoutMs = 0;
46
- fetchs = [];
47
- error = null;
48
- numOfFetchs = 0;
49
- startTime = Date.now();
50
- onUpdateServerData = null;
51
- waitNextFetchCompleteCall = 0;
52
- }
53
-
54
- const dbReadAt = 0.62;
55
-
56
- const fetchsInProgress = new Set<symbol>();
57
-
58
- async function fetch(params: string): Promise<S> {
59
- const fetchStartTime = Date.now() - startTime;
60
- const fetchId = Symbol();
61
-
62
- fetchsInProgress.add(fetchId);
63
-
64
- let duration = 0;
65
-
66
- if (Array.isArray(timeout)) {
67
- duration = randomInt(timeout[0], timeout[1]);
68
- } else if (typeof timeout === 'function') {
69
- duration = timeout(params);
70
- } else {
71
- duration = timeout;
72
- }
73
-
74
- if (logFetchs) {
75
- // eslint-disable-next-line no-console
76
- console.log(
77
- `${numOfFetchs} - fetch${params ? ` ${params}` : ''} - started ${
78
- Date.now() - startTime
79
- }ms - duration: ${duration}ms`,
80
- );
81
- }
82
-
83
- lastTimeoutMs = duration;
84
-
85
- await sleep(duration * dbReadAt);
86
-
87
- try {
88
- if (error) {
89
- throw typeof error === 'string' ? new Error(error) : error;
90
- }
91
-
92
- const response = fetchSelector(data, params);
93
-
94
- if (response === 'notFound') {
95
- throw new Error('Not found');
96
- }
97
-
98
- await sleep(duration * (1 - dbReadAt));
99
-
100
- if (!response) {
101
- throw new Error('No data');
102
- }
103
-
104
- fetchs.push({
105
- started: numOfFetchs,
106
- result: response as any,
107
- params,
108
- duration,
109
- time: { start: fetchStartTime, end: Date.now() - startTime },
110
- });
111
-
112
- return response;
113
- } catch (e) {
114
- fetchs.push({
115
- started: numOfFetchs,
116
- error: JSON.stringify(e),
117
- params,
118
- duration,
119
- time: { start: fetchStartTime, end: Date.now() - startTime },
120
- });
121
- throw e;
122
- } finally {
123
- fetchsInProgress.delete(fetchId);
124
- numOfFetchs += 1;
125
- }
126
- }
127
-
128
- async function fetchWitoutSelector() {
129
- return fetch('');
130
- }
131
-
132
- function mutateData(newData: Partial<Data>) {
133
- const prev = data;
134
- data = { ...data, ...newData };
135
- setTimeout(() => {
136
- onUpdateServerData?.({ prev, data });
137
- }, 8);
138
- }
139
-
140
- function produceData(recipe: (draft: Data) => void) {
141
- const prev = data;
142
- data = produce(data, recipe);
143
- setTimeout(() => {
144
- onUpdateServerData?.({ prev, data });
145
- }, 8);
146
- }
147
-
148
- function setFetchDuration(newTimeout: typeof timeout) {
149
- lastTimeout = timeout;
150
- timeout = newTimeout;
151
- }
152
-
153
- function undoTimeoutChange() {
154
- timeout = lastTimeout;
155
- }
156
-
157
- function setFetchError(newError: Error | string | null) {
158
- error = newError;
159
- }
160
-
161
- /** default duration: 60 */
162
- async function emulateMutation(
163
- newData: Partial<Data> | ((draft: Data) => void),
164
- {
165
- duration = 60,
166
- setDataAt = duration * 0.8,
167
- emulateError,
168
- }: {
169
- duration?: number;
170
- setDataAt?: number;
171
- emulateError?: Error | string;
172
- } = {},
173
- ) {
174
- if (logFetchs) {
175
- // eslint-disable-next-line no-console
176
- console.log(
177
- `mutation - started ${
178
- Date.now() - startTime
179
- }ms - duration: ${duration}ms`,
180
- );
181
- }
182
-
183
- await sleep(setDataAt);
184
-
185
- if (emulateError) {
186
- throw typeof emulateError === 'string'
187
- ? new Error(emulateError)
188
- : emulateError;
189
- }
190
-
191
- if (!data) {
192
- throw new Error('No data');
193
- }
194
-
195
- if (typeof newData === 'function') {
196
- produceData(newData);
197
- } else {
198
- mutateData(newData);
199
- }
200
-
201
- await sleep(duration - setDataAt);
202
-
203
- return data;
204
- }
205
-
206
- async function waitFetchIdle(extraWait = 0, maxWait = 1000) {
207
- waitNextFetchCompleteCall++;
208
- const startWaitTime = Date.now();
209
-
210
- const currentWaitNextFetchCompleteCall = waitNextFetchCompleteCall;
211
-
212
- function checkTimeout() {
213
- if (Date.now() - startWaitTime > maxWait) {
214
- throw new Error(
215
- `Wait for fetch idle ${currentWaitNextFetchCompleteCall} timeout`,
216
- );
217
- }
218
- }
219
-
220
- if (fetchsInProgress.size === 0) {
221
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
222
- while (fetchsInProgress.size === 0) {
223
- await sleep(5);
224
-
225
- checkTimeout();
226
- }
227
- }
228
-
229
- async function waitUntilFetchsInProgressSizeIsZero() {
230
- while (fetchsInProgress.size > 0) {
231
- await sleep(10);
232
-
233
- checkTimeout();
234
- }
235
- }
236
-
237
- await waitUntilFetchsInProgressSizeIsZero();
238
-
239
- await sleep(extraWait);
240
-
241
- if (fetchsInProgress.size > 0) {
242
- await waitUntilFetchsInProgressSizeIsZero();
243
- }
244
- }
245
-
246
- return {
247
- fetch,
248
- mutateData,
249
- fetchWitoutSelector,
250
- waitFetchIdle,
251
- produceData,
252
- setFetchDuration,
253
- get data() {
254
- return data;
255
- },
256
- reset,
257
- setFetchError,
258
- addOnUpdateServerData(
259
- listener: (prevAndData: { prev: Data; data: Data }) => void,
260
- ) {
261
- onUpdateServerData = listener;
262
- },
263
- emulateMutation,
264
- undoTimeoutChange,
265
- get fetchsCount() {
266
- return numOfFetchs;
267
- },
268
- get fetchDuration() {
269
- return lastTimeoutMs;
270
- },
271
- relativeTime() {
272
- return Date.now() - startTime;
273
- },
274
- numOfFetchsFromHere() {
275
- const currentNumOfFetchs = numOfFetchs;
276
- return () => numOfFetchs - currentNumOfFetchs;
277
- },
278
- fetchsSequence(
279
- simplifyArray: 'all' | { firstNItems: number } | 'length' = {
280
- firstNItems: 1,
281
- },
282
- ) {
283
- return simplifyArraySnapshot(
284
- fetchs.map(({ time, duration, ...item }) => ({
285
- ...item,
286
- })),
287
- simplifyArray,
288
- );
289
- },
290
- get fetchs() {
291
- return fetchs;
292
- },
293
- };
294
- }
295
-
296
- export type ServerMock<Data> = ReturnType<typeof mockServerResource<Data>>;
@@ -1,370 +0,0 @@
1
- import {
2
- createFetchOrquestrator,
3
- FetchType,
4
- FetchContext,
5
- } from '../../src/fetchOrquestrator';
6
- import { arrayWithPrev } from '../utils/arrayUtils';
7
- import { sleep } from '../utils/sleep';
8
-
9
- type Data = number | 'error' | null;
10
-
11
- type AddAction = (action: string, value?: Data) => void;
12
-
13
- function serverEmulator(initialData: Data, addAction: AddAction) {
14
- const serverDataHistory: Data[] = [initialData];
15
- /** default duration: 60 */
16
- async function mutateData(
17
- newData: Data,
18
- {
19
- duration = 60,
20
- setDataAt = duration * 0.7,
21
- onServerDataChange,
22
- addServerDataChangeAction,
23
- }: {
24
- duration?: number;
25
- setDataAt?: number;
26
- onServerDataChange?: () => void;
27
- addServerDataChangeAction?: boolean;
28
- } = {},
29
- ) {
30
- addAction(`mutation-started`, newData);
31
-
32
- await sleep(setDataAt);
33
-
34
- serverDataHistory.push(newData);
35
-
36
- if (addServerDataChangeAction) {
37
- addAction(`server-data-changed`, newData);
38
- }
39
-
40
- onServerDataChange?.();
41
-
42
- addAction(`mutation-finished`, newData);
43
-
44
- await sleep(duration - setDataAt);
45
- }
46
-
47
- return {
48
- mutateData,
49
- setData(value: Data) {
50
- addAction(`server-data-changed`, value);
51
- serverDataHistory.push(value);
52
- },
53
- get current() {
54
- return serverDataHistory.at(-1)!;
55
- },
56
- history: serverDataHistory,
57
- };
58
- }
59
-
60
- function uiEmulator(initialData: Data, addAction: AddAction) {
61
- const uiHistory: Data[] = [initialData];
62
-
63
- function setUi(value: number | 'error', reason: 'optimistic' | 'fetch') {
64
- uiHistory.push(value);
65
- addAction(`${reason}-ui-commit`, value);
66
- }
67
-
68
- return {
69
- setUi,
70
- history: uiHistory,
71
- get changesHistory() {
72
- const historyWithoutDuplicates: Data[] = [];
73
-
74
- for (const value of uiHistory) {
75
- if (value !== historyWithoutDuplicates.at(-1)) {
76
- historyWithoutDuplicates.push(value);
77
- }
78
- }
79
-
80
- return historyWithoutDuplicates;
81
- },
82
- get current() {
83
- return uiHistory.at(-1)!;
84
- },
85
- };
86
- }
87
-
88
- export function createTestStore(
89
- serverInitialData: Data,
90
- {
91
- uiInitialData = 0,
92
- }: {
93
- serverInitialData?: Data;
94
- uiInitialData?: Data;
95
- } = {},
96
- ) {
97
- const actionsHistory: {
98
- action: string;
99
- time: number;
100
- value: Data | undefined;
101
- }[] = [];
102
- const initialTime = Date.now();
103
-
104
- function getRelativeTime() {
105
- return Date.now() - initialTime;
106
- }
107
-
108
- const addAction: AddAction = (action, value) => {
109
- actionsHistory.push({
110
- action,
111
- time: getRelativeTime(),
112
- value,
113
- });
114
- };
115
-
116
- const server = serverEmulator(serverInitialData, addAction);
117
- const ui = uiEmulator(uiInitialData, addAction);
118
- let numOfFetchs = 0;
119
-
120
- const dbReadAt = 0.62;
121
-
122
- let fetchId = 0;
123
-
124
- async function mockFetch(fetchCtx: FetchContext, ms: number) {
125
- fetchId++;
126
-
127
- const fetchIdLocal = fetchId;
128
-
129
- await sleep(ms * dbReadAt);
130
-
131
- const serverResponse = server.current;
132
-
133
- await sleep(ms * (1 - dbReadAt));
134
-
135
- numOfFetchs++;
136
-
137
- if (serverResponse === 'error') {
138
- addAction(`fetch-error : ${fetchIdLocal}`);
139
- ui.setUi('error', 'fetch');
140
- return false;
141
- }
142
-
143
- if (fetchCtx.shouldAbort()) {
144
- addAction(`fetch-aborted : ${fetchIdLocal}`);
145
-
146
- return false;
147
- }
148
-
149
- addAction(`fetch-finished : ${fetchIdLocal}`, serverResponse);
150
- ui.setUi(serverResponse, 'fetch');
151
-
152
- return true;
153
- }
154
-
155
- async function waitForNoPendingRequests(chekcInterval = 10) {
156
- while (
157
- fetchOrquestrator.hasPendingFetch ||
158
- fetchOrquestrator.mutationIsInProgress
159
- ) {
160
- await sleep(chekcInterval);
161
- }
162
- }
163
-
164
- const fetchOrquestrator = createFetchOrquestrator({
165
- fetchFn: mockFetch,
166
- on(event) {
167
- if (event === 'scheduled-fetch-started') {
168
- addAction(`scheduled-fetch-started : ${fetchId + 1}`);
169
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
170
- } else if (event === 'scheduled-rt-fetch-started') {
171
- addAction(`scheduled-rt-fetch-started : ${fetchId + 1}`);
172
- } else {
173
- addAction(event);
174
- }
175
- },
176
- dynamicRealtimeThrottleMs: getDynamicRealtimeThrottleMs,
177
- });
178
-
179
- /** default duration = 40 */
180
- function fetch(fetchType: FetchType, duration = 40) {
181
- const result = fetchOrquestrator.scheduleFetch(fetchType, duration);
182
-
183
- if (result === 'started') {
184
- addAction(`fetch-started : ${fetchId}`);
185
- }
186
-
187
- if (result === 'skipped') {
188
- addAction('fetch-skipped');
189
- }
190
-
191
- if (result === 'scheduled') {
192
- addAction('fetch-scheduled');
193
- }
194
-
195
- if (result === 'rt-scheduled') {
196
- addAction('rt-fetch-scheduled');
197
- }
198
- }
199
-
200
- async function emulateExternalRTU(newServerValue: number, duration = 40) {
201
- server.setData(newServerValue);
202
-
203
- await sleep(5);
204
-
205
- fetch('realtimeUpdate', duration);
206
- }
207
-
208
- return {
209
- ui,
210
- server,
211
- timeline(groupByTime = 10, startAt = 0): string {
212
- return getTimeline(actionsHistory, groupByTime, startAt);
213
- },
214
- get actions() {
215
- return getActions(actionsHistory);
216
- },
217
- fetch,
218
- get numOfFetchs() {
219
- return numOfFetchs;
220
- },
221
- mutateData: server.mutateData,
222
- optimisticUpdate(value: number) {
223
- ui.setUi(value, 'optimistic');
224
- },
225
- errorInNextFetch() {
226
- server.setData('error');
227
- },
228
- waitForNoPendingRequests,
229
- addAction,
230
- emulateExternalRTU,
231
- startMutation: fetchOrquestrator.startMutation,
232
- };
233
- }
234
-
235
- export type TestStore = ReturnType<typeof createTestStore>;
236
-
237
- function getActions(
238
- actionsHistory: { action: string; time: number; value: Data | undefined }[],
239
- ) {
240
- let lastIdentation = '';
241
-
242
- return [
243
- '\n',
244
- actionsHistory
245
- .map(({ action, value }) => {
246
- if (value) {
247
- lastIdentation = stringFromLength(
248
- value === 'error' ? 0 : (value - 1) * 2,
249
- );
250
-
251
- return `${lastIdentation}${value} - ${action}`;
252
- } else {
253
- return `${lastIdentation}${action}`;
254
- }
255
- })
256
- .join('\n'),
257
- '\n',
258
- ].join('');
259
- }
260
-
261
- type Action = {
262
- action: string;
263
- time: number;
264
- value: Data | undefined;
265
- };
266
-
267
- function getTimeline(
268
- actionsHistory: Action[],
269
- groupByTime: number,
270
- startAt: number,
271
- ) {
272
- const timeline: string[] = [];
273
- let lastIdentation = '';
274
- let lastAction = '';
275
-
276
- const dividerText = '.';
277
-
278
- const actionsWithNormalizedTime: Action[] = [];
279
-
280
- actionsHistory.forEach((action) => {
281
- if (action.time < startAt) {
282
- return;
283
- }
284
-
285
- let time = action.time;
286
-
287
- time = time - (time % groupByTime);
288
-
289
- actionsWithNormalizedTime.push({
290
- ...action,
291
- time,
292
- });
293
- });
294
-
295
- for (const [{ action, time, value }, prev] of arrayWithPrev(
296
- actionsWithNormalizedTime,
297
- )) {
298
- if (prev) {
299
- const timeDiff = time - prev.time;
300
-
301
- if (timeDiff > 50) {
302
- timeline.push(dividerText);
303
- }
304
- }
305
-
306
- let actionText: string;
307
-
308
- if (value) {
309
- lastIdentation = stringFromLength(
310
- value === 'error' ? 0 : (value - 1) * 2,
311
- );
312
-
313
- actionText = `${lastIdentation}${value} - ${action}`;
314
- } else {
315
- actionText = `${lastIdentation}${action}`;
316
- }
317
-
318
- if (lastAction.startsWith(`${time}ms:`)) {
319
- lastAction = `${time}ms:--${actionText}`;
320
- } else {
321
- lastAction = `${time}ms: ${actionText}`;
322
- }
323
-
324
- timeline.push(lastAction);
325
- }
326
-
327
- const maxTimeLength = Math.max(
328
- ...timeline.map((action) =>
329
- action.includes(':') ? action.split(':')[0]!.length : 0,
330
- ),
331
- );
332
-
333
- const timelineWithBalancedStart = timeline.map((action) => {
334
- if (action.startsWith(dividerText)) {
335
- return `${stringFromLength(maxTimeLength)}-`;
336
- }
337
-
338
- const [time, actionType] = action.split(':');
339
-
340
- return `${stringFromLength(
341
- maxTimeLength - time!.length,
342
- )}${time}:${actionType}`;
343
- });
344
-
345
- return `\n${timelineWithBalancedStart
346
- .map((action) => {
347
- if (action.includes('--')) {
348
- const [time, actionType] = action.split(':--');
349
-
350
- return ` ${stringFromLength(time!.length - 1)}: ${actionType}`;
351
- }
352
-
353
- return action;
354
- })
355
- .join('\n')}\n`;
356
- }
357
-
358
- function stringFromLength(length: number, string = ' ') {
359
- return Array.from({ length })
360
- .map((_) => string)
361
- .join('');
362
- }
363
-
364
- function getDynamicRealtimeThrottleMs(lastDuration: number): number {
365
- if (lastDuration > 300) {
366
- return 300;
367
- }
368
-
369
- return 100;
370
- }