@choksheak/react-utils 0.4.7 → 0.4.8

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 (108) hide show
  1. package/NoSSR.cjs +5 -2
  2. package/{NoSSR.mjs → NoSSR.js} +4 -1
  3. package/NoSSR.min.cjs +14 -1
  4. package/NoSSR.min.cjs.map +1 -1
  5. package/NoSSR.min.js +15 -0
  6. package/{NoSSR.min.mjs.map → NoSSR.min.js.map} +1 -1
  7. package/chunk-4YV72T4D.min.js +105 -0
  8. package/{storage.min.mjs.map → chunk-4YV72T4D.min.js.map} +1 -1
  9. package/chunk-5PDGU37E.cjs +104 -0
  10. package/{storage.mjs → chunk-7CPBZFDV.js} +5 -3
  11. package/{stringify.mjs → chunk-7XC6EVMX.js} +2 -0
  12. package/chunk-AXDXFCZV.min.js +35 -0
  13. package/{stringify.min.mjs.map → chunk-AXDXFCZV.min.js.map} +1 -1
  14. package/chunk-C6X4GPZ4.min.cjs +596 -0
  15. package/chunk-C6X4GPZ4.min.cjs.map +1 -0
  16. package/{sharedState.mjs → chunk-CIDQGOPA.js} +23 -8
  17. package/chunk-CYTO5EZE.cjs +34 -0
  18. package/chunk-HFIQE4XZ.cjs +595 -0
  19. package/chunk-IS3BZTWE.cjs +35 -0
  20. package/chunk-JYZY2SHD.min.js +596 -0
  21. package/chunk-JYZY2SHD.min.js.map +1 -0
  22. package/chunk-K2L3OVGY.min.cjs +18 -0
  23. package/chunk-K2L3OVGY.min.cjs.map +1 -0
  24. package/chunk-KGDXU6Q2.min.cjs +222 -0
  25. package/chunk-KGDXU6Q2.min.cjs.map +1 -0
  26. package/chunk-MNWSPF5J.min.js +18 -0
  27. package/{useDeepMemo.min.mjs.map → chunk-MNWSPF5J.min.js.map} +1 -1
  28. package/chunk-P2E73RBM.min.cjs +35 -0
  29. package/chunk-P2E73RBM.min.cjs.map +1 -0
  30. package/chunk-PCGGKBOL.min.js +222 -0
  31. package/chunk-PCGGKBOL.min.js.map +1 -0
  32. package/chunk-PHITDXZT.min.js +36 -0
  33. package/chunk-PHITDXZT.min.js.map +1 -0
  34. package/{sharedQuery.mjs → chunk-RFKUMDNU.js} +17 -6
  35. package/chunk-RRQBFF4W.min.cjs +105 -0
  36. package/chunk-RRQBFF4W.min.cjs.map +1 -0
  37. package/chunk-TST6JKQ5.min.cjs +36 -0
  38. package/chunk-TST6JKQ5.min.cjs.map +1 -0
  39. package/chunk-U67V476Y.js +35 -0
  40. package/chunk-UNDIVFP5.cjs +221 -0
  41. package/chunk-WXLUEDBO.cjs +17 -0
  42. package/{useDeepMemo.mjs → chunk-YTXGK6BR.js} +2 -0
  43. package/dist-4BDJ7HYS.min.js +546 -0
  44. package/dist-4BDJ7HYS.min.js.map +1 -0
  45. package/dist-HKOCAKHU.min.cjs +546 -0
  46. package/dist-HKOCAKHU.min.cjs.map +1 -0
  47. package/dist-RQU6CWRG.js +545 -0
  48. package/dist-UKP7SPWZ.cjs +545 -0
  49. package/index.cjs +43 -5
  50. package/index.d.cts +2 -2
  51. package/index.d.ts +2 -2
  52. package/index.js +43 -0
  53. package/index.min.cjs +43 -1
  54. package/index.min.cjs.map +1 -1
  55. package/index.min.js +44 -0
  56. package/index.min.js.map +1 -0
  57. package/magic-string.es-2AQNCEBL.min.js +1309 -0
  58. package/magic-string.es-2AQNCEBL.min.js.map +1 -0
  59. package/magic-string.es-HC5PDAU3.cjs +1308 -0
  60. package/magic-string.es-KDMUXKGI.js +1308 -0
  61. package/magic-string.es-XJ27RPMN.min.cjs +1309 -0
  62. package/magic-string.es-XJ27RPMN.min.cjs.map +1 -0
  63. package/package.json +48 -8
  64. package/sharedQuery.cjs +8 -575
  65. package/sharedQuery.d.cts +7 -92
  66. package/sharedQuery.d.ts +7 -92
  67. package/sharedQuery.js +17 -0
  68. package/sharedQuery.min.cjs +17 -1
  69. package/sharedQuery.min.cjs.map +1 -1
  70. package/sharedQuery.min.js +18 -0
  71. package/sharedQuery.min.js.map +1 -0
  72. package/sharedState.cjs +11 -199
  73. package/sharedState.d.cts +12 -57
  74. package/sharedState.d.ts +12 -57
  75. package/sharedState.js +18 -0
  76. package/sharedState.min.cjs +18 -1
  77. package/sharedState.min.cjs.map +1 -1
  78. package/sharedState.min.js +19 -0
  79. package/sharedState.min.js.map +1 -0
  80. package/storage.cjs +7 -98
  81. package/storage.js +11 -0
  82. package/storage.min.cjs +11 -1
  83. package/storage.min.cjs.map +1 -1
  84. package/storage.min.js +12 -0
  85. package/storage.min.js.map +1 -0
  86. package/stringify.cjs +5 -30
  87. package/stringify.js +7 -0
  88. package/stringify.min.cjs +7 -1
  89. package/stringify.min.cjs.map +1 -1
  90. package/stringify.min.js +8 -0
  91. package/stringify.min.js.map +1 -0
  92. package/useDeepMemo.cjs +5 -13
  93. package/useDeepMemo.js +7 -0
  94. package/useDeepMemo.min.cjs +7 -1
  95. package/useDeepMemo.min.cjs.map +1 -1
  96. package/useDeepMemo.min.js +8 -0
  97. package/useDeepMemo.min.js.map +1 -0
  98. package/NoSSR.min.mjs +0 -2
  99. package/index.min.mjs +0 -2
  100. package/index.min.mjs.map +0 -1
  101. package/index.mjs +0 -5
  102. package/sharedQuery.min.mjs +0 -2
  103. package/sharedQuery.min.mjs.map +0 -1
  104. package/sharedState.min.mjs +0 -2
  105. package/sharedState.min.mjs.map +0 -1
  106. package/storage.min.mjs +0 -2
  107. package/stringify.min.mjs +0 -2
  108. package/useDeepMemo.min.mjs +0 -2
package/sharedQuery.cjs CHANGED
@@ -1,584 +1,17 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _http = require('@choksheak/ts-utils/http');
2
- var _nonNil = require('@choksheak/ts-utils/nonNil');
3
- var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
4
2
 
5
3
 
6
4
 
7
5
 
6
+ var _chunkHFIQE4XZcjs = require('./chunk-HFIQE4XZ.cjs');
7
+ require('./chunk-UNDIVFP5.cjs');
8
+ require('./chunk-5PDGU37E.cjs');
9
+ require('./chunk-CYTO5EZE.cjs');
10
+ require('./chunk-WXLUEDBO.cjs');
11
+ require('./chunk-IS3BZTWE.cjs');
8
12
 
9
13
 
10
- var _react = require('react');
11
- var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);
12
- var _sharedState = require('./sharedState');
13
- var _stringify = require('./stringify');
14
- var _useDeepMemo = require('./useDeepMemo');
15
- const SharedQueryConfig = {
16
- /** Refetch on every page load. */
17
- staleMs: 0,
18
- /** Keep in cache for a long time. */
19
- expiryMs: 30 * 864e5,
20
- /** Always refetch automatically if the data is stale. */
21
- refetchOnStale: true,
22
- /** No default persistence configured. */
23
- persistTo: void 0,
24
- /** 100 is not too large, but please tweak accordingly. */
25
- maxSize: 100,
26
- /** 100kb limit before discarding old records. */
27
- maxBytes: 1e5,
28
- /** Default to log to console. */
29
- log: (...args) => console.log("[sharedQuery]", ...args)
30
- };
31
- function configureSharedQuery(config) {
32
- Object.assign(SharedQueryConfig, config);
33
- }
34
- const moduleQueryRegistry = /* @__PURE__ */ new Map();
35
- function getOrCreateQueryRegistry() {
36
- if (typeof window !== "undefined") {
37
- const g = window.globalThis;
38
- return g.reactUtilsQueryRegistry ??= /* @__PURE__ */ new Map();
39
- }
40
- return moduleQueryRegistry;
41
- }
42
- function sharedQuery1(options) {
43
- const registry = getOrCreateQueryRegistry();
44
- const key = options.queryName || options.url;
45
- const existing = registry.get(key);
46
- if (existing) {
47
- return existing;
48
- }
49
- const obj = sharedQuery2(options);
50
- registry.set(key, obj);
51
- return obj;
52
- }
53
- function sharedQuery2(options) {
54
- const url = options.url || "";
55
- const queryName = options.queryName || url;
56
- if (!queryName) {
57
- throw new Error(`Either queryName or url must be specified.`);
58
- }
59
- const inflightQueries = /* @__PURE__ */ new Map();
60
- const mountedKeys = /* @__PURE__ */ new Map();
61
- let queryFn;
62
- if (options.queryFn) {
63
- queryFn = options.queryFn;
64
- } else if (url) {
65
- const fetcher = _http.http.use(_http.retries.call(void 0, ));
66
- queryFn = async (...args) => {
67
- let params = "";
68
- const firstArg = _optionalChain([args, 'optionalAccess', _ => _[0]]);
69
- if (firstArg) {
70
- if (typeof firstArg === "string") {
71
- params = firstArg;
72
- } else if (typeof firstArg === "object") {
73
- const entries = [];
74
- for (const [k, v] of Object.entries(firstArg)) {
75
- if (v === void 0) continue;
76
- if (Array.isArray(v)) {
77
- for (const item of v) {
78
- if (item === void 0) continue;
79
- entries.push([k, String(item)]);
80
- }
81
- } else {
82
- entries.push([k, String(v)]);
83
- }
84
- }
85
- params = new URLSearchParams(entries).toString();
86
- }
87
- if (params) {
88
- if (url.includes("?")) {
89
- params = "&" + params;
90
- } else {
91
- params = "?" + params;
92
- }
93
- }
94
- }
95
- const response = await fetcher.get(url + params);
96
- return await response.json();
97
- };
98
- } else {
99
- throw new Error(`Either queryFn or url must be specified`);
100
- }
101
- const refetchFn = options.refetchFn;
102
- const staleMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.staleMs]), () => ( SharedQueryConfig.staleMs));
103
- const expiryMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.expiryMs]), () => ( SharedQueryConfig.expiryMs));
104
- const refetchOnStale = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.refetchOnStale]), () => ( SharedQueryConfig.refetchOnStale));
105
- const store = options.store;
106
- if (store) {
107
- if ("persistTo" in store && store.isValid) {
108
- const isValid = store.isValid;
109
- options = {
110
- ...options,
111
- store: {
112
- ...store,
113
- isValid: (u) => {
114
- if (!u || typeof u !== "object") {
115
- return false;
116
- }
117
- for (const v of Object.values(u)) {
118
- if (!v || typeof v !== "object" || !("data" in v) || !("dataUpdatedMs" in v) || !("lastUpdatedMs" in v) || typeof v.dataUpdatedMs !== "number" || typeof v.lastUpdatedMs !== "number" || !isValid(v.data)) {
119
- return false;
120
- }
121
- }
122
- return true;
123
- }
124
- }
125
- };
126
- }
127
- } else {
128
- const persistTo = _nullishCoalesce(options.persistTo, () => ( SharedQueryConfig.persistTo));
129
- if (persistTo) {
130
- options = {
131
- ...options,
132
- store: {
133
- persistTo,
134
- key: queryName,
135
- expiryMs
136
- }
137
- };
138
- }
139
- }
140
- const maxSize = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _5 => _5.maxSize]), () => ( SharedQueryConfig.maxSize));
141
- const maxBytes = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _6 => _6.maxBytes]), () => ( SharedQueryConfig.maxBytes));
142
- const keepLastNonEmptyData = Boolean(_optionalChain([options, 'optionalAccess', _7 => _7.keepLastNonEmptyData]));
143
- const log = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.log]), () => ( SharedQueryConfig.log));
144
- const queryState = _sharedState.sharedState.call(void 0,
145
- {},
146
- // defaultValue
147
- options
148
- );
149
- function isStale(dataUpdatedMs) {
150
- if (staleMs === 0) return true;
151
- const ageMs = Date.now() - dataUpdatedMs;
152
- return ageMs > staleMs;
153
- }
154
- function isExpired(dataUpdatedMs) {
155
- if (expiryMs === 0) return false;
156
- const ageMs = Date.now() - dataUpdatedMs;
157
- return ageMs > expiryMs;
158
- }
159
- function enforceSizeLimit() {
160
- if (!maxSize && !maxBytes) {
161
- return;
162
- }
163
- const oldState = queryState.getSnapshot();
164
- const oldSize = Object.keys(oldState).length;
165
- if (oldSize <= 1) {
166
- return;
167
- }
168
- const oldByteSize = _objectsizeof2.default.call(void 0, oldState);
169
- let numToCut = maxSize ? oldSize - maxSize : 0;
170
- let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
171
- if (numToCut <= 0 && bytesToCut <= 0) {
172
- log(
173
- `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
174
- );
175
- return;
176
- }
177
- log(
178
- `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
179
- );
180
- const newState = { ...oldState };
181
- let needUpdate = false;
182
- const deleteKeyIfNotMounted = (key, expired) => {
183
- if (mountedKeys.has(key)) {
184
- log(`Cannot clean up ${key} as it is mounted`);
185
- return;
186
- }
187
- const byteSize = _objectsizeof2.default.call(void 0, key) + _objectsizeof2.default.call(void 0, newState[key]);
188
- log(
189
- `Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
190
- );
191
- numToCut--;
192
- bytesToCut -= byteSize;
193
- delete newState[key];
194
- needUpdate = true;
195
- };
196
- let entriesByTimeAscending = Object.entries(newState).sort(
197
- (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
198
- );
199
- for (const [key] of entriesByTimeAscending) {
200
- if (!isExpired(newState[key].lastUpdatedMs)) {
201
- break;
202
- }
203
- deleteKeyIfNotMounted(key, true);
204
- }
205
- if (numToCut > 0 || bytesToCut > 0) {
206
- if (needUpdate) {
207
- entriesByTimeAscending = Object.entries(newState).sort(
208
- (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
209
- );
210
- }
211
- for (const [key] of entriesByTimeAscending) {
212
- deleteKeyIfNotMounted(key, false);
213
- if (numToCut <= 0 && bytesToCut <= 0) {
214
- break;
215
- }
216
- }
217
- }
218
- if (!needUpdate) {
219
- log(
220
- `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
221
- );
222
- return;
223
- }
224
- queryState.setValue(newState);
225
- log(
226
- `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
227
- );
228
- }
229
- function setData(queryKey, data, dataUpdatedMs = Date.now()) {
230
- const entry = {
231
- lastUpdatedMs: Date.now(),
232
- loading: false,
233
- data,
234
- dataUpdatedMs
235
- };
236
- queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
237
- enforceSizeLimit();
238
- }
239
- async function startFetching(queryKey, queryType, args) {
240
- log(`Start fetching ${queryKey}, queryType=${queryType}`);
241
- try {
242
- const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
243
- log(`Successfully fetched ${queryKey}`);
244
- setData(queryKey, data, Date.now());
245
- return data;
246
- } catch (e) {
247
- log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
248
- throw e;
249
- } finally {
250
- inflightQueries.delete(queryKey);
251
- }
252
- }
253
- function dedupedFetch(queryKey, queryType, ...args) {
254
- const inflightQuery = inflightQueries.get(queryKey);
255
- if (inflightQuery) {
256
- log(
257
- `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
258
- );
259
- return inflightQuery.promise;
260
- }
261
- const promise = startFetching(queryKey, queryType, args);
262
- const abortController = new AbortController();
263
- inflightQueries.set(queryKey, { promise, abortController });
264
- return promise;
265
- }
266
- const obj = {
267
- queryName,
268
- queryFn,
269
- refetchFn,
270
- expiryMs,
271
- staleMs,
272
- refetchOnStale,
273
- maxSize,
274
- maxBytes,
275
- keepLastNonEmptyData,
276
- log,
277
- queryState,
278
- /** Returns a key to identify requests based on the given args. */
279
- getQueryKey(args) {
280
- let s = _stringify.stringifyDeterministicForKeys.call(void 0, args);
281
- if (s.length > 30) {
282
- s = _xxhashjs2.default.h32(s, 39406).toString(16).slice(2);
283
- }
284
- return queryName + ":" + s;
285
- },
286
- /**
287
- * Get the AbortController to abort the inflight query (if any).
288
- *
289
- * Note that once you get the controller, you can also get the signal easily
290
- * using `controller.signal`. So if you need both the controller and the
291
- * signal, just use this function.
292
- */
293
- getAbortController(args) {
294
- const queryKey = obj.getQueryKey(args);
295
- return obj.getAbortControllerByKey(queryKey);
296
- },
297
- getAbortControllerByKey(queryKey) {
298
- return _nullishCoalesce(_optionalChain([inflightQueries, 'access', _9 => _9.get, 'call', _10 => _10(queryKey), 'optionalAccess', _11 => _11.abortController]), () => ( null));
299
- },
300
- /**
301
- * Get the AbortSignal to check for query abortions.
302
- *
303
- * Example using fetch:
304
- * ```
305
- * const getUserQuery = sharedQuery({
306
- * queryName: "getUser",
307
- * queryFn: (userId: string) => {
308
- * // Get the signal for this current execution.
309
- * const signal = getUserQuery.getAbortSignal([userId]);
310
- *
311
- * // Pass the signal to fetch so that it can be aborted.
312
- * const response = await fetch(`/users/${userId}`, { signal });
313
- *
314
- * // Check for errors.
315
- * if (!response.ok) {
316
- * throw new Error(response.statusText);
317
- * }
318
- *
319
- * // Return the data.
320
- * return await response.json();
321
- * },
322
- * });
323
- * ```
324
- *
325
- * Example using `http.ts`:
326
- * ```
327
- * const getUserQuery = sharedQuery({
328
- * queryName: "getUser",
329
- * queryFn: (userId: string) => {
330
- * // Get the signal for this current execution.
331
- * const signal = getUserQuery.getAbortSignal([userId]);
332
- *
333
- * // Pass the signal to fetch so that it can be aborted.
334
- * const response = await http.get(`/users/${userId}`, { signal });
335
- * return await response.json();
336
- * },
337
- * });
338
- * ```
339
- */
340
- getAbortSignal(args) {
341
- const queryKey = obj.getQueryKey(args);
342
- return obj.getAbortSignalByKey(queryKey);
343
- },
344
- getAbortSignalByKey(queryKey) {
345
- return _nullishCoalesce(_optionalChain([obj, 'access', _12 => _12.getAbortControllerByKey, 'call', _13 => _13(queryKey), 'optionalAccess', _14 => _14.signal]), () => ( null));
346
- },
347
- /** For cached data, we need to return the correct timestamps as well. */
348
- async getCachedOrFetch(...args) {
349
- const startMs = Date.now();
350
- await queryState.readyPromise;
351
- const waitedMs = Date.now() - startMs;
352
- const queryKey = obj.getQueryKey(args);
353
- const cached = _optionalChain([queryState, 'access', _15 => _15.getSnapshot, 'call', _16 => _16(), 'optionalAccess', _17 => _17[queryKey]]);
354
- if (waitedMs) {
355
- log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
356
- }
357
- if (_optionalChain([cached, 'optionalAccess', _18 => _18.data]) && !isExpired(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
358
- if (!isStale(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
359
- log(`Return fresh data ${queryKey} from cache without fetching`);
360
- return cached;
361
- }
362
- if (refetchOnStale) {
363
- log(`refetchOnStale for ${queryKey}`);
364
- void dedupedFetch(queryKey, "query", ...args);
365
- }
366
- log(`Returning stale data for ${queryKey}`);
367
- return cached;
368
- }
369
- const data = await dedupedFetch(queryKey, "query", ...args);
370
- const now = Date.now();
371
- return {
372
- // Don't keep old error.
373
- lastUpdatedMs: now,
374
- loading: false,
375
- data,
376
- dataUpdatedMs: now
377
- };
378
- },
379
- /** Get the entire stored entry for a query key. */
380
- getQueryValue(queryKey) {
381
- return _optionalChain([queryState, 'access', _19 => _19.getSnapshot, 'call', _20 => _20(), 'optionalAccess', _21 => _21[queryKey]]);
382
- },
383
- /** Get the current stored data for a query key. */
384
- getData(queryKey) {
385
- const stateValue = _optionalChain([queryState, 'access', _22 => _22.getSnapshot, 'call', _23 => _23(), 'optionalAccess', _24 => _24[queryKey]]);
386
- if (_optionalChain([stateValue, 'optionalAccess', _25 => _25.lastUpdatedMs])) {
387
- if (isExpired(stateValue.lastUpdatedMs)) {
388
- obj.deleteData(queryKey);
389
- return void 0;
390
- }
391
- }
392
- return _optionalChain([stateValue, 'optionalAccess', _26 => _26.data]);
393
- },
394
- /** Set the data directly if the user obtained it from somewhere else. */
395
- setData,
396
- /**
397
- * Do a new fetch even when the data is already cached, but don't fetch if
398
- * another fetch is already inflight.
399
- */
400
- async updateFromSource(...args) {
401
- const key = obj.getQueryKey(args);
402
- return await dedupedFetch(key, "query", ...args);
403
- },
404
- /**
405
- * Perform an explicit refetch. If `options.refetchFn` was not specified,
406
- * then this would be identical to calling `obj.updateFromSource()`.
407
- */
408
- async refetch(...args) {
409
- const key = obj.getQueryKey(args);
410
- return await dedupedFetch(key, "refetch", ...args);
411
- },
412
- /** Delete the cached data for one set of arguments. */
413
- deleteData(queryKey) {
414
- const record = queryState.getSnapshot();
415
- const clone = { ...record };
416
- delete clone[queryKey];
417
- queryState.setValue(clone);
418
- const inflight = inflightQueries.get(queryKey);
419
- if (inflight) {
420
- inflightQueries.delete(queryKey);
421
- inflight.abortController.abort("Deleted");
422
- }
423
- },
424
- /** Delete all currently cached data & all inflight promises. */
425
- clear() {
426
- queryState.delete();
427
- for (const { abortController } of Array.from(inflightQueries.values())) {
428
- abortController.abort("Cleared");
429
- }
430
- inflightQueries.clear();
431
- },
432
- /** Keep track of mounted keys. */
433
- mount(queryKey) {
434
- mountedKeys.set(queryKey, (_nullishCoalesce(mountedKeys.get(queryKey), () => ( 0))) + 1);
435
- },
436
- /** Clean up mounted keys. */
437
- unmount(queryKey) {
438
- const count = mountedKeys.get(queryKey);
439
- if (count === 1) {
440
- mountedKeys.delete(queryKey);
441
- } else {
442
- mountedKeys.set(queryKey, (_nullishCoalesce(count, () => ( 0))) - 1);
443
- }
444
- },
445
- /**
446
- * Discard the oldest entries if the size exceeds the limit. The last
447
- * remaining record cannot be deleted no matter what the limit is.
448
- */
449
- enforceSizeLimit
450
- };
451
- return obj;
452
- }
453
- function sharedQuery(options) {
454
- return sharedQuery1(options);
455
- }
456
- const DEFAULT_QUERY_STATE_ENTRY = {
457
- lastUpdatedMs: 0,
458
- loading: true
459
- };
460
- function useSharedQuery(query, ...args) {
461
- const stableArgs = _useDeepMemo.useDeepMemo.call(void 0, args);
462
- const [queryState, setQueryState] = _sharedState.useSharedState.call(void 0, query.queryState);
463
- const isMounted = _react.useRef.call(void 0, true);
464
- const queryKey = _react.useMemo.call(void 0,
465
- () => query.getQueryKey(stableArgs),
466
- [query, stableArgs]
467
- );
468
- const queryStateValue = _nullishCoalesce(queryState[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY));
469
- const setQueryStateValue = _react.useCallback.call(void 0,
470
- (next) => {
471
- setQueryState((prev) => {
472
- const clone = { ...prev };
473
- clone[queryKey] = typeof next === "function" ? next(_nullishCoalesce(clone[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY))) : next;
474
- return clone;
475
- });
476
- },
477
- [queryKey, setQueryState]
478
- );
479
- const [lastNonEmptyData, setLastNonEmptyData] = _react.useState.call(void 0, );
480
- _react.useEffect.call(void 0, () => {
481
- if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
482
- setLastNonEmptyData(queryStateValue.data);
483
- }
484
- }, [query.keepLastNonEmptyData, queryStateValue.data]);
485
- const executeQuery = _react.useCallback.call(void 0,
486
- async (isRefetch) => {
487
- query.log(
488
- `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
489
- );
490
- if (!isMounted.current) return;
491
- setQueryStateValue((prev) => ({
492
- // Keep old data and error.
493
- ...prev,
494
- lastUpdatedMs: Date.now(),
495
- loading: true
496
- }));
497
- try {
498
- let state;
499
- if (isRefetch) {
500
- const data = await query.refetch(...stableArgs);
501
- const now = Date.now();
502
- state = {
503
- // Don't keep old error.
504
- lastUpdatedMs: now,
505
- loading: false,
506
- data,
507
- dataUpdatedMs: now
508
- };
509
- } else {
510
- state = await query.getCachedOrFetch(...stableArgs);
511
- }
512
- if (!isMounted.current) return;
513
- setQueryStateValue({ ...state, loading: false });
514
- return state.data;
515
- } catch (e) {
516
- if (!isMounted.current) return;
517
- const now = Date.now();
518
- setQueryStateValue((prev) => ({
519
- // Keep old data.
520
- ...prev,
521
- lastUpdatedMs: now,
522
- loading: false,
523
- error: e,
524
- errorUpdatedMs: now
525
- }));
526
- }
527
- },
528
- [query, queryKey, setQueryStateValue, stableArgs]
529
- );
530
- _react.useEffect.call(void 0, () => {
531
- isMounted.current = true;
532
- query.mount(queryKey);
533
- void executeQuery(false);
534
- return () => {
535
- isMounted.current = false;
536
- query.unmount(queryKey);
537
- };
538
- }, [executeQuery, query, queryKey]);
539
- return _react.useMemo.call(void 0, () => {
540
- return {
541
- ...queryStateValue,
542
- // Fill with lastNonEmptyData when data is undefined.
543
- data: queryStateValue.data !== void 0 ? queryStateValue.data : lastNonEmptyData,
544
- latestData: queryStateValue.data,
545
- // This works only if the user-given queryFn supports abort. If not,
546
- // this function doesn't do anything, since we don't have any means to
547
- // abort the running queryFn.
548
- abortCurrentQuery: (reason) => {
549
- const controller = query.getAbortControllerByKey(queryKey);
550
- _optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
551
- return Boolean(controller);
552
- },
553
- getCachedOrFetch: async () => {
554
- const data = await query.getCachedOrFetch(...stableArgs);
555
- return _nonNil.nonNil.call(void 0,
556
- data.data,
557
- typeof data.error === "string" ? data.error : JSON.stringify(data.error)
558
- );
559
- },
560
- refetch: () => {
561
- return executeQuery(true);
562
- },
563
- setData: (data, dataUpdatedMs) => {
564
- query.setData(queryKey, data, dataUpdatedMs);
565
- },
566
- deleteData: () => {
567
- query.deleteData(queryKey);
568
- }
569
- };
570
- }, [
571
- executeQuery,
572
- lastNonEmptyData,
573
- query,
574
- queryKey,
575
- queryStateValue,
576
- stableArgs
577
- ]);
578
- }
579
14
 
580
15
 
581
16
 
582
-
583
-
584
- exports.SharedQueryConfig = SharedQueryConfig; exports.configureSharedQuery = configureSharedQuery; exports.sharedQuery = sharedQuery; exports.useSharedQuery = useSharedQuery;
17
+ exports.SharedQueryConfig = _chunkHFIQE4XZcjs.SharedQueryConfig; exports.configureSharedQuery = _chunkHFIQE4XZcjs.configureSharedQuery; exports.sharedQuery = _chunkHFIQE4XZcjs.sharedQuery; exports.useSharedQuery = _chunkHFIQE4XZcjs.useSharedQuery;