@choksheak/react-utils 0.4.5 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@choksheak/react-utils",
3
3
  "license": "The Unlicense",
4
- "version": "0.4.5",
4
+ "version": "0.4.7",
5
5
  "description": "Miscellaneous React+TypeScript utilities with support for full tree-shaking.",
6
6
  "private": false,
7
7
  "sideEffects": false,
package/sharedQuery.cjs CHANGED
@@ -1,376 +1,18 @@
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
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
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);
29
4
 
30
- // src/sharedQuery.ts
31
- var sharedQuery_exports = {};
32
- __export(sharedQuery_exports, {
33
- SharedQueryConfig: () => SharedQueryConfig,
34
- configureSharedQuery: () => configureSharedQuery,
35
- sharedQuery: () => sharedQuery,
36
- useSharedQuery: () => useSharedQuery
37
- });
38
- module.exports = __toCommonJS(sharedQuery_exports);
39
- var import_http = require("@choksheak/ts-utils/http");
40
- var import_nonNil = require("@choksheak/ts-utils/nonNil");
41
- var import_object_sizeof = __toESM(require("object-sizeof"), 1);
42
- var import_react3 = require("react");
43
- var import_xxhashjs = __toESM(require("xxhashjs"), 1);
44
5
 
45
- // src/sharedState.ts
46
- var import_timeConstants = require("@choksheak/ts-utils/timeConstants");
47
- var import_react = require("react");
48
6
 
49
- // src/storage.ts
50
- var import_kvStore = require("@choksheak/ts-utils/kvStore");
51
- var import_localStore = require("@choksheak/ts-utils/localStore");
52
- var IS_NOT_BROWSER = typeof window === "undefined";
53
- function getStorageAdapter(options, defaultStoreExpiryMs) {
54
- const { store } = options ?? {};
55
- if (!store) {
56
- return null;
57
- }
58
- if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
59
- const expiryMs = store.expiryMs || defaultStoreExpiryMs;
60
- const config = { ...store, expiryMs };
61
- switch (store.persistTo) {
62
- case "localStorage":
63
- return localStoreAdapter(config);
64
- case "indexedDb":
65
- return kvStoreAdapter(config);
66
- default:
67
- store.persistTo;
68
- throw new Error(`Unknown store.adapter ${store.persistTo}`);
69
- }
70
- }
71
- return store;
72
- }
73
- function localStoreAdapter({
74
- key,
75
- expiryMs,
76
- isValid
77
- }) {
78
- const STORE_NAME = "react-utils";
79
- const adapter = (0, import_localStore.createLocalStore)(STORE_NAME, {
80
- defaultExpiryMs: expiryMs
81
- });
82
- const keyPrefix = key + ":";
83
- return {
84
- set: (key2, value) => {
85
- if (IS_NOT_BROWSER) return;
86
- adapter.set(keyPrefix + key2, value);
87
- },
88
- get: (key2) => {
89
- if (IS_NOT_BROWSER) return void 0;
90
- const fullKey = keyPrefix + key2;
91
- const value = adapter.get(fullKey);
92
- if (value !== void 0 && isValid && !isValid(value)) {
93
- console.warn(
94
- `localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
95
- );
96
- adapter.delete(fullKey);
97
- return void 0;
98
- }
99
- return value;
100
- },
101
- delete: (key2) => {
102
- if (IS_NOT_BROWSER) return;
103
- adapter.delete(keyPrefix + key2);
104
- },
105
- /** Note that this will clear all keys in all shared states. */
106
- clear: () => {
107
- if (IS_NOT_BROWSER) return;
108
- adapter.clear();
109
- }
110
- };
111
- }
112
- function kvStoreAdapter({
113
- key,
114
- expiryMs,
115
- isValid
116
- }) {
117
- const keyPrefix = key + ":";
118
- return {
119
- set: async (key2, value) => {
120
- if (IS_NOT_BROWSER) return;
121
- await import_kvStore.kvStore.set(keyPrefix + key2, value, expiryMs);
122
- },
123
- get: async (key2) => {
124
- if (IS_NOT_BROWSER) return void 0;
125
- const fullKey = keyPrefix + key2;
126
- const value = await import_kvStore.kvStore.get(fullKey);
127
- if (value !== void 0 && isValid && !isValid(value)) {
128
- console.warn(
129
- `indexedDb adapter: Auto-discard invalid value for ${key2}:`,
130
- value
131
- );
132
- await import_kvStore.kvStore.delete(fullKey);
133
- return void 0;
134
- }
135
- return value;
136
- },
137
- delete: async (key2) => {
138
- if (IS_NOT_BROWSER) return;
139
- await import_kvStore.kvStore.delete(keyPrefix + key2);
140
- },
141
- clear: async () => {
142
- if (IS_NOT_BROWSER) return;
143
- await import_kvStore.kvStore.clear();
144
- }
145
- };
146
- }
147
7
 
148
- // src/sharedState.ts
149
- var SharedStateConfig = {
150
- /**
151
- * Default duration for storage expiration in milliseconds. Initial value
152
- * is 30 days, but can be changed to anything.
153
- */
154
- storeExpiryMs: 30 * import_timeConstants.MS_PER_DAY,
155
- /**
156
- * True to load from storage only on mount, false (default) to load in
157
- * the top level scope when the shared state is defined.
158
- */
159
- lazyLoad: false
160
- };
161
- function createPubSubStore() {
162
- const dataByKey = /* @__PURE__ */ new Map();
163
- const subscribersByKey = /* @__PURE__ */ new Map();
164
- function notify(key, next, prev) {
165
- const subscribers = subscribersByKey.get(key);
166
- if (!subscribers) return;
167
- const copy = Array.from(subscribers.values());
168
- for (const subscriber of copy) {
169
- try {
170
- subscriber(next, prev);
171
- } catch (e) {
172
- console.error(`Error invoking subscriber:`, e);
173
- }
174
- }
175
- }
176
- return {
177
- // This could be undefined if T includes undefined, else it should never
178
- // return undefined because the user has to always specify the default value.
179
- get(key) {
180
- return dataByKey.get(key);
181
- },
182
- set(key, value) {
183
- const prev = dataByKey.get(key);
184
- if (prev === value) return;
185
- dataByKey.set(key, value);
186
- notify(key, value, prev);
187
- },
188
- delete(key) {
189
- dataByKey.delete(key);
190
- },
191
- setNoNotify(key, value) {
192
- dataByKey.set(key, value);
193
- },
194
- // Subscribe to changes of a specific key
195
- subscribe(key, subscriber) {
196
- let subscribers = subscribersByKey.get(key);
197
- if (!subscribers) {
198
- subscribers = /* @__PURE__ */ new Set();
199
- subscribersByKey.set(key, subscribers);
200
- }
201
- subscribers.add(subscriber);
202
- return () => {
203
- subscribers.delete(subscriber);
204
- if (subscribers.size === 0) subscribersByKey.delete(key);
205
- };
206
- }
207
- };
208
- }
209
- function getOrCreatePubSubStore() {
210
- if (typeof window !== "undefined") {
211
- const t = window.globalThis;
212
- return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
213
- }
214
- return createPubSubStore();
215
- }
216
- var pubSubStore = getOrCreatePubSubStore();
217
- var STORAGE_KEY = "state";
218
- var stateKey = 0;
219
- function sharedState(defaultValue, options) {
220
- let readyResolve = () => {
221
- };
222
- const readyPromise = new Promise((resolve) => {
223
- readyResolve = resolve;
224
- });
225
- const resolveReadyPromise = readyResolve;
226
- const pubSubKey = String(stateKey++);
227
- const storageAdapter = getStorageAdapter(
228
- options,
229
- SharedStateConfig.storeExpiryMs
230
- );
231
- pubSubStore.setNoNotify(pubSubKey, defaultValue);
232
- const lazyLoad = options?.lazyLoad;
233
- const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
234
- function completeInit(stored) {
235
- const value = stored !== void 0 ? stored : defaultValue;
236
- pubSubStore.set(pubSubKey, value);
237
- obj.initDone = true;
238
- resolveReadyPromise();
239
- }
240
- const obj = {
241
- defaultValue,
242
- /** Allow users to await for the completion of data init. */
243
- readyPromise,
244
- lazy,
245
- initStarted: false,
246
- initDone: false,
247
- /** `subscribe` function required by useSyncExternalStore. */
248
- subscribe(subscriber) {
249
- return pubSubStore.subscribe(pubSubKey, () => subscriber());
250
- },
251
- /** Returns true if there is a backing store. */
252
- hasStore() {
253
- return Boolean(storageAdapter);
254
- },
255
- /**
256
- * Set a value directly into the store. Does nothing if there is no
257
- * backing store.
258
- *
259
- * Warning: If you want to set the value properly, you should use
260
- * `setValue()` instead which also updates the in-memory copy.
261
- */
262
- setInStore(value) {
263
- return storageAdapter?.set(STORAGE_KEY, value);
264
- },
265
- /**
266
- * Get a value directly from the store. Returns undefined if there is no
267
- * backing store.
268
- */
269
- getFromStore() {
270
- return storageAdapter?.get(STORAGE_KEY);
271
- },
272
- /**
273
- * Get the value of the shared state.
274
- * `getSnapshot` function — must return same ref if value unchanged.
275
- * Note that this would return the default value if data init from store is
276
- * not completed yet.
277
- */
278
- getSnapshot() {
279
- return pubSubStore.get(pubSubKey);
280
- },
281
- /** Set the value of the shared state. */
282
- setValue(next) {
283
- if (typeof next === "function") {
284
- const prev = pubSubStore.get(pubSubKey);
285
- next = next(prev);
286
- }
287
- pubSubStore.set(pubSubKey, next);
288
- void obj.setInStore(next);
289
- },
290
- /**
291
- * Remove the value of the shared state. Actually this just sets the value
292
- * back to the given default value.
293
- */
294
- delete() {
295
- pubSubStore.set(pubSubKey, defaultValue);
296
- return storageAdapter?.set(STORAGE_KEY, defaultValue);
297
- },
298
- /** Initial default handling. */
299
- initDefaultValueOnce() {
300
- if (obj.initDone || obj.initStarted) return;
301
- obj.initStarted = true;
302
- const maybePromise = obj.getFromStore();
303
- if (maybePromise instanceof Promise) {
304
- return maybePromise.then(completeInit);
305
- } else {
306
- const stored = maybePromise;
307
- completeInit(stored);
308
- }
309
- }
310
- };
311
- if (!lazy) {
312
- obj.initDefaultValueOnce();
313
- }
314
- return obj;
315
- }
316
- function useSharedState(state) {
317
- void state.initDefaultValueOnce();
318
- const value = (0, import_react.useSyncExternalStore)(
319
- (onStoreChange) => state.subscribe(onStoreChange),
320
- () => state.getSnapshot(),
321
- // getServerSnapshot is needed to prevent SSR dev errors in nextjs.
322
- () => state.getSnapshot()
323
- );
324
- return [value, state.setValue];
325
- }
326
-
327
- // src/stringify.ts
328
- function stringifyDeterministicForKeys(params) {
329
- const cache = /* @__PURE__ */ new Set();
330
- return JSON.stringify(params, (_, value) => {
331
- if (typeof value === "function") {
332
- throw new Error(`Functions should not be passed into query parameters`);
333
- }
334
- if (!value || typeof value !== "object" || Array.isArray(value)) {
335
- return value;
336
- }
337
- if (cache.has(value)) {
338
- return "[Circular]";
339
- }
340
- cache.add(value);
341
- if (value !== params) {
342
- try {
343
- JSON.stringify(value);
344
- } catch {
345
- return "[Unserializable]";
346
- }
347
- }
348
- return Object.keys(value).sort().reduce(
349
- (result, key) => {
350
- result[key] = value[key];
351
- return result;
352
- },
353
- {}
354
- );
355
- });
356
- }
357
8
 
358
- // src/useDeepMemo.ts
359
- var import_lodash_es = require("lodash-es");
360
- var import_react2 = require("react");
361
- function useDeepMemo(value) {
362
- const [state, setState] = (0, import_react2.useState)(value);
363
- return (0, import_react2.useMemo)(() => {
364
- if ((0, import_lodash_es.isEqual)(state, value)) {
365
- return state;
366
- }
367
- setState(value);
368
- return value;
369
- }, [state, value]);
370
- }
371
9
 
372
- // src/sharedQuery.ts
373
- var SharedQueryConfig = {
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 = {
374
16
  /** Refetch on every page load. */
375
17
  staleMs: 0,
376
18
  /** Keep in cache for a long time. */
@@ -389,7 +31,7 @@ var SharedQueryConfig = {
389
31
  function configureSharedQuery(config) {
390
32
  Object.assign(SharedQueryConfig, config);
391
33
  }
392
- var moduleQueryRegistry = /* @__PURE__ */ new Map();
34
+ const moduleQueryRegistry = /* @__PURE__ */ new Map();
393
35
  function getOrCreateQueryRegistry() {
394
36
  if (typeof window !== "undefined") {
395
37
  const g = window.globalThis;
@@ -400,9 +42,7 @@ function getOrCreateQueryRegistry() {
400
42
  function sharedQuery1(options) {
401
43
  const registry = getOrCreateQueryRegistry();
402
44
  const key = options.queryName || options.url;
403
- const existing = registry.get(
404
- options.queryName || options.url
405
- );
45
+ const existing = registry.get(key);
406
46
  if (existing) {
407
47
  return existing;
408
48
  }
@@ -422,10 +62,10 @@ function sharedQuery2(options) {
422
62
  if (options.queryFn) {
423
63
  queryFn = options.queryFn;
424
64
  } else if (url) {
425
- const fetcher = import_http.http.use((0, import_http.retries)());
65
+ const fetcher = _http.http.use(_http.retries.call(void 0, ));
426
66
  queryFn = async (...args) => {
427
67
  let params = "";
428
- const firstArg = args?.[0];
68
+ const firstArg = _optionalChain([args, 'optionalAccess', _ => _[0]]);
429
69
  if (firstArg) {
430
70
  if (typeof firstArg === "string") {
431
71
  params = firstArg;
@@ -459,9 +99,9 @@ function sharedQuery2(options) {
459
99
  throw new Error(`Either queryFn or url must be specified`);
460
100
  }
461
101
  const refetchFn = options.refetchFn;
462
- const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;
463
- const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;
464
- const refetchOnStale = options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;
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));
465
105
  const store = options.store;
466
106
  if (store) {
467
107
  if ("persistTo" in store && store.isValid) {
@@ -485,7 +125,7 @@ function sharedQuery2(options) {
485
125
  };
486
126
  }
487
127
  } else {
488
- const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;
128
+ const persistTo = _nullishCoalesce(options.persistTo, () => ( SharedQueryConfig.persistTo));
489
129
  if (persistTo) {
490
130
  options = {
491
131
  ...options,
@@ -497,11 +137,11 @@ function sharedQuery2(options) {
497
137
  };
498
138
  }
499
139
  }
500
- const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;
501
- const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
502
- const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
503
- const log = options?.log ?? SharedQueryConfig.log;
504
- const queryState = sharedState(
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,
505
145
  {},
506
146
  // defaultValue
507
147
  options
@@ -525,7 +165,7 @@ function sharedQuery2(options) {
525
165
  if (oldSize <= 1) {
526
166
  return;
527
167
  }
528
- const oldByteSize = (0, import_object_sizeof.default)(oldState);
168
+ const oldByteSize = _objectsizeof2.default.call(void 0, oldState);
529
169
  let numToCut = maxSize ? oldSize - maxSize : 0;
530
170
  let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
531
171
  if (numToCut <= 0 && bytesToCut <= 0) {
@@ -544,7 +184,7 @@ function sharedQuery2(options) {
544
184
  log(`Cannot clean up ${key} as it is mounted`);
545
185
  return;
546
186
  }
547
- const byteSize = (0, import_object_sizeof.default)(key) + (0, import_object_sizeof.default)(newState[key]);
187
+ const byteSize = _objectsizeof2.default.call(void 0, key) + _objectsizeof2.default.call(void 0, newState[key]);
548
188
  log(
549
189
  `Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
550
190
  );
@@ -583,7 +223,7 @@ function sharedQuery2(options) {
583
223
  }
584
224
  queryState.setValue(newState);
585
225
  log(
586
- `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${(0, import_object_sizeof.default)(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
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()})`
587
227
  );
588
228
  }
589
229
  function setData(queryKey, data, dataUpdatedMs = Date.now()) {
@@ -637,9 +277,9 @@ function sharedQuery2(options) {
637
277
  queryState,
638
278
  /** Returns a key to identify requests based on the given args. */
639
279
  getQueryKey(args) {
640
- let s = stringifyDeterministicForKeys(args);
280
+ let s = _stringify.stringifyDeterministicForKeys.call(void 0, args);
641
281
  if (s.length > 30) {
642
- s = import_xxhashjs.default.h32(s, 39406).toString(16).slice(2);
282
+ s = _xxhashjs2.default.h32(s, 39406).toString(16).slice(2);
643
283
  }
644
284
  return queryName + ":" + s;
645
285
  },
@@ -655,7 +295,7 @@ function sharedQuery2(options) {
655
295
  return obj.getAbortControllerByKey(queryKey);
656
296
  },
657
297
  getAbortControllerByKey(queryKey) {
658
- return inflightQueries.get(queryKey)?.abortController ?? null;
298
+ return _nullishCoalesce(_optionalChain([inflightQueries, 'access', _9 => _9.get, 'call', _10 => _10(queryKey), 'optionalAccess', _11 => _11.abortController]), () => ( null));
659
299
  },
660
300
  /**
661
301
  * Get the AbortSignal to check for query abortions.
@@ -702,7 +342,7 @@ function sharedQuery2(options) {
702
342
  return obj.getAbortSignalByKey(queryKey);
703
343
  },
704
344
  getAbortSignalByKey(queryKey) {
705
- return obj.getAbortControllerByKey(queryKey)?.signal ?? null;
345
+ return _nullishCoalesce(_optionalChain([obj, 'access', _12 => _12.getAbortControllerByKey, 'call', _13 => _13(queryKey), 'optionalAccess', _14 => _14.signal]), () => ( null));
706
346
  },
707
347
  /** For cached data, we need to return the correct timestamps as well. */
708
348
  async getCachedOrFetch(...args) {
@@ -710,12 +350,12 @@ function sharedQuery2(options) {
710
350
  await queryState.readyPromise;
711
351
  const waitedMs = Date.now() - startMs;
712
352
  const queryKey = obj.getQueryKey(args);
713
- const cached = queryState.getSnapshot()?.[queryKey];
353
+ const cached = _optionalChain([queryState, 'access', _15 => _15.getSnapshot, 'call', _16 => _16(), 'optionalAccess', _17 => _17[queryKey]]);
714
354
  if (waitedMs) {
715
355
  log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
716
356
  }
717
- if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {
718
- if (!isStale(cached.dataUpdatedMs ?? 0)) {
357
+ if (_optionalChain([cached, 'optionalAccess', _18 => _18.data]) && !isExpired(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
358
+ if (!isStale(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
719
359
  log(`Return fresh data ${queryKey} from cache without fetching`);
720
360
  return cached;
721
361
  }
@@ -738,18 +378,18 @@ function sharedQuery2(options) {
738
378
  },
739
379
  /** Get the entire stored entry for a query key. */
740
380
  getQueryValue(queryKey) {
741
- return queryState.getSnapshot()?.[queryKey];
381
+ return _optionalChain([queryState, 'access', _19 => _19.getSnapshot, 'call', _20 => _20(), 'optionalAccess', _21 => _21[queryKey]]);
742
382
  },
743
383
  /** Get the current stored data for a query key. */
744
384
  getData(queryKey) {
745
- const stateValue = queryState.getSnapshot()?.[queryKey];
746
- if (stateValue?.lastUpdatedMs) {
385
+ const stateValue = _optionalChain([queryState, 'access', _22 => _22.getSnapshot, 'call', _23 => _23(), 'optionalAccess', _24 => _24[queryKey]]);
386
+ if (_optionalChain([stateValue, 'optionalAccess', _25 => _25.lastUpdatedMs])) {
747
387
  if (isExpired(stateValue.lastUpdatedMs)) {
748
388
  obj.deleteData(queryKey);
749
389
  return void 0;
750
390
  }
751
391
  }
752
- return stateValue?.data;
392
+ return _optionalChain([stateValue, 'optionalAccess', _26 => _26.data]);
753
393
  },
754
394
  /** Set the data directly if the user obtained it from somewhere else. */
755
395
  setData,
@@ -791,7 +431,7 @@ function sharedQuery2(options) {
791
431
  },
792
432
  /** Keep track of mounted keys. */
793
433
  mount(queryKey) {
794
- mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);
434
+ mountedKeys.set(queryKey, (_nullishCoalesce(mountedKeys.get(queryKey), () => ( 0))) + 1);
795
435
  },
796
436
  /** Clean up mounted keys. */
797
437
  unmount(queryKey) {
@@ -799,7 +439,7 @@ function sharedQuery2(options) {
799
439
  if (count === 1) {
800
440
  mountedKeys.delete(queryKey);
801
441
  } else {
802
- mountedKeys.set(queryKey, (count ?? 0) - 1);
442
+ mountedKeys.set(queryKey, (_nullishCoalesce(count, () => ( 0))) - 1);
803
443
  }
804
444
  },
805
445
  /**
@@ -813,36 +453,36 @@ function sharedQuery2(options) {
813
453
  function sharedQuery(options) {
814
454
  return sharedQuery1(options);
815
455
  }
816
- var DEFAULT_QUERY_STATE_ENTRY = {
456
+ const DEFAULT_QUERY_STATE_ENTRY = {
817
457
  lastUpdatedMs: 0,
818
458
  loading: true
819
459
  };
820
460
  function useSharedQuery(query, ...args) {
821
- const stableArgs = useDeepMemo(args);
822
- const [queryState, setQueryState] = useSharedState(query.queryState);
823
- const isMounted = (0, import_react3.useRef)(true);
824
- const queryKey = (0, import_react3.useMemo)(
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,
825
465
  () => query.getQueryKey(stableArgs),
826
466
  [query, stableArgs]
827
467
  );
828
- const queryStateValue = queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;
829
- const setQueryStateValue = (0, import_react3.useCallback)(
468
+ const queryStateValue = _nullishCoalesce(queryState[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY));
469
+ const setQueryStateValue = _react.useCallback.call(void 0,
830
470
  (next) => {
831
471
  setQueryState((prev) => {
832
472
  const clone = { ...prev };
833
- clone[queryKey] = typeof next === "function" ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY) : next;
473
+ clone[queryKey] = typeof next === "function" ? next(_nullishCoalesce(clone[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY))) : next;
834
474
  return clone;
835
475
  });
836
476
  },
837
477
  [queryKey, setQueryState]
838
478
  );
839
- const [lastNonEmptyData, setLastNonEmptyData] = (0, import_react3.useState)();
840
- (0, import_react3.useEffect)(() => {
479
+ const [lastNonEmptyData, setLastNonEmptyData] = _react.useState.call(void 0, );
480
+ _react.useEffect.call(void 0, () => {
841
481
  if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
842
482
  setLastNonEmptyData(queryStateValue.data);
843
483
  }
844
484
  }, [query.keepLastNonEmptyData, queryStateValue.data]);
845
- const executeQuery = (0, import_react3.useCallback)(
485
+ const executeQuery = _react.useCallback.call(void 0,
846
486
  async (isRefetch) => {
847
487
  query.log(
848
488
  `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
@@ -887,7 +527,7 @@ function useSharedQuery(query, ...args) {
887
527
  },
888
528
  [query, queryKey, setQueryStateValue, stableArgs]
889
529
  );
890
- (0, import_react3.useEffect)(() => {
530
+ _react.useEffect.call(void 0, () => {
891
531
  isMounted.current = true;
892
532
  query.mount(queryKey);
893
533
  void executeQuery(false);
@@ -896,7 +536,7 @@ function useSharedQuery(query, ...args) {
896
536
  query.unmount(queryKey);
897
537
  };
898
538
  }, [executeQuery, query, queryKey]);
899
- return (0, import_react3.useMemo)(() => {
539
+ return _react.useMemo.call(void 0, () => {
900
540
  return {
901
541
  ...queryStateValue,
902
542
  // Fill with lastNonEmptyData when data is undefined.
@@ -907,12 +547,12 @@ function useSharedQuery(query, ...args) {
907
547
  // abort the running queryFn.
908
548
  abortCurrentQuery: (reason) => {
909
549
  const controller = query.getAbortControllerByKey(queryKey);
910
- controller?.abort(reason);
550
+ _optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
911
551
  return Boolean(controller);
912
552
  },
913
553
  getCachedOrFetch: async () => {
914
554
  const data = await query.getCachedOrFetch(...stableArgs);
915
- return (0, import_nonNil.nonNil)(
555
+ return _nonNil.nonNil.call(void 0,
916
556
  data.data,
917
557
  typeof data.error === "string" ? data.error : JSON.stringify(data.error)
918
558
  );
@@ -936,10 +576,9 @@ function useSharedQuery(query, ...args) {
936
576
  stableArgs
937
577
  ]);
938
578
  }
939
- // Annotate the CommonJS export names for ESM import in node:
940
- 0 && (module.exports = {
941
- SharedQueryConfig,
942
- configureSharedQuery,
943
- sharedQuery,
944
- useSharedQuery
945
- });
579
+
580
+
581
+
582
+
583
+
584
+ exports.SharedQueryConfig = SharedQueryConfig; exports.configureSharedQuery = configureSharedQuery; exports.sharedQuery = sharedQuery; exports.useSharedQuery = useSharedQuery;