@choksheak/react-utils 0.4.6 → 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.6",
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,384 +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 getNextStateKey() {
220
- if (typeof window !== "undefined") {
221
- const t = window.globalThis;
222
- t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;
223
- return t.reactUtilsStateKey;
224
- }
225
- return ++stateKey;
226
- }
227
- function sharedState(defaultValue, options) {
228
- let readyResolve = () => {
229
- };
230
- const readyPromise = new Promise((resolve) => {
231
- readyResolve = resolve;
232
- });
233
- const resolveReadyPromise = readyResolve;
234
- const pubSubKey = String(getNextStateKey());
235
- const storageAdapter = getStorageAdapter(
236
- options,
237
- SharedStateConfig.storeExpiryMs
238
- );
239
- pubSubStore.setNoNotify(pubSubKey, defaultValue);
240
- const lazyLoad = options?.lazyLoad;
241
- const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
242
- function completeInit(stored) {
243
- const value = stored !== void 0 ? stored : defaultValue;
244
- pubSubStore.set(pubSubKey, value);
245
- obj.initDone = true;
246
- resolveReadyPromise();
247
- }
248
- const obj = {
249
- defaultValue,
250
- /** Allow users to await for the completion of data init. */
251
- readyPromise,
252
- lazy,
253
- initStarted: false,
254
- initDone: false,
255
- /** `subscribe` function required by useSyncExternalStore. */
256
- subscribe(subscriber) {
257
- return pubSubStore.subscribe(pubSubKey, () => subscriber());
258
- },
259
- /** Returns true if there is a backing store. */
260
- hasStore() {
261
- return Boolean(storageAdapter);
262
- },
263
- /**
264
- * Set a value directly into the store. Does nothing if there is no
265
- * backing store.
266
- *
267
- * Warning: If you want to set the value properly, you should use
268
- * `setValue()` instead which also updates the in-memory copy.
269
- */
270
- setInStore(value) {
271
- return storageAdapter?.set(STORAGE_KEY, value);
272
- },
273
- /**
274
- * Get a value directly from the store. Returns undefined if there is no
275
- * backing store.
276
- */
277
- getFromStore() {
278
- return storageAdapter?.get(STORAGE_KEY);
279
- },
280
- /**
281
- * Get the value of the shared state.
282
- * `getSnapshot` function — must return same ref if value unchanged.
283
- * Note that this would return the default value if data init from store is
284
- * not completed yet.
285
- */
286
- getSnapshot() {
287
- return pubSubStore.get(pubSubKey);
288
- },
289
- /** Set the value of the shared state. */
290
- setValue(next) {
291
- if (typeof next === "function") {
292
- const prev = pubSubStore.get(pubSubKey);
293
- next = next(prev);
294
- }
295
- pubSubStore.set(pubSubKey, next);
296
- void obj.setInStore(next);
297
- },
298
- /**
299
- * Remove the value of the shared state. Actually this just sets the value
300
- * back to the given default value.
301
- */
302
- delete() {
303
- pubSubStore.set(pubSubKey, defaultValue);
304
- return storageAdapter?.set(STORAGE_KEY, defaultValue);
305
- },
306
- /** Initial default handling. */
307
- initDefaultValueOnce() {
308
- if (obj.initDone || obj.initStarted) return;
309
- obj.initStarted = true;
310
- const maybePromise = obj.getFromStore();
311
- if (maybePromise instanceof Promise) {
312
- return maybePromise.then(completeInit);
313
- } else {
314
- const stored = maybePromise;
315
- completeInit(stored);
316
- }
317
- }
318
- };
319
- if (!lazy) {
320
- obj.initDefaultValueOnce();
321
- }
322
- return obj;
323
- }
324
- function useSharedState(state) {
325
- void state.initDefaultValueOnce();
326
- const value = (0, import_react.useSyncExternalStore)(
327
- (onStoreChange) => state.subscribe(onStoreChange),
328
- () => state.getSnapshot(),
329
- // getServerSnapshot is needed to prevent SSR dev errors in nextjs.
330
- () => state.getSnapshot()
331
- );
332
- return [value, state.setValue];
333
- }
334
-
335
- // src/stringify.ts
336
- function stringifyDeterministicForKeys(params) {
337
- const cache = /* @__PURE__ */ new Set();
338
- return JSON.stringify(params, (_, value) => {
339
- if (typeof value === "function") {
340
- throw new Error(`Functions should not be passed into query parameters`);
341
- }
342
- if (!value || typeof value !== "object" || Array.isArray(value)) {
343
- return value;
344
- }
345
- if (cache.has(value)) {
346
- return "[Circular]";
347
- }
348
- cache.add(value);
349
- if (value !== params) {
350
- try {
351
- JSON.stringify(value);
352
- } catch {
353
- return "[Unserializable]";
354
- }
355
- }
356
- return Object.keys(value).sort().reduce(
357
- (result, key) => {
358
- result[key] = value[key];
359
- return result;
360
- },
361
- {}
362
- );
363
- });
364
- }
365
8
 
366
- // src/useDeepMemo.ts
367
- var import_lodash_es = require("lodash-es");
368
- var import_react2 = require("react");
369
- function useDeepMemo(value) {
370
- const [state, setState] = (0, import_react2.useState)(value);
371
- return (0, import_react2.useMemo)(() => {
372
- if ((0, import_lodash_es.isEqual)(state, value)) {
373
- return state;
374
- }
375
- setState(value);
376
- return value;
377
- }, [state, value]);
378
- }
379
9
 
380
- // src/sharedQuery.ts
381
- 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 = {
382
16
  /** Refetch on every page load. */
383
17
  staleMs: 0,
384
18
  /** Keep in cache for a long time. */
@@ -397,7 +31,7 @@ var SharedQueryConfig = {
397
31
  function configureSharedQuery(config) {
398
32
  Object.assign(SharedQueryConfig, config);
399
33
  }
400
- var moduleQueryRegistry = /* @__PURE__ */ new Map();
34
+ const moduleQueryRegistry = /* @__PURE__ */ new Map();
401
35
  function getOrCreateQueryRegistry() {
402
36
  if (typeof window !== "undefined") {
403
37
  const g = window.globalThis;
@@ -428,10 +62,10 @@ function sharedQuery2(options) {
428
62
  if (options.queryFn) {
429
63
  queryFn = options.queryFn;
430
64
  } else if (url) {
431
- const fetcher = import_http.http.use((0, import_http.retries)());
65
+ const fetcher = _http.http.use(_http.retries.call(void 0, ));
432
66
  queryFn = async (...args) => {
433
67
  let params = "";
434
- const firstArg = args?.[0];
68
+ const firstArg = _optionalChain([args, 'optionalAccess', _ => _[0]]);
435
69
  if (firstArg) {
436
70
  if (typeof firstArg === "string") {
437
71
  params = firstArg;
@@ -465,9 +99,9 @@ function sharedQuery2(options) {
465
99
  throw new Error(`Either queryFn or url must be specified`);
466
100
  }
467
101
  const refetchFn = options.refetchFn;
468
- const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;
469
- const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;
470
- 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));
471
105
  const store = options.store;
472
106
  if (store) {
473
107
  if ("persistTo" in store && store.isValid) {
@@ -491,7 +125,7 @@ function sharedQuery2(options) {
491
125
  };
492
126
  }
493
127
  } else {
494
- const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;
128
+ const persistTo = _nullishCoalesce(options.persistTo, () => ( SharedQueryConfig.persistTo));
495
129
  if (persistTo) {
496
130
  options = {
497
131
  ...options,
@@ -503,11 +137,11 @@ function sharedQuery2(options) {
503
137
  };
504
138
  }
505
139
  }
506
- const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;
507
- const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
508
- const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
509
- const log = options?.log ?? SharedQueryConfig.log;
510
- 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,
511
145
  {},
512
146
  // defaultValue
513
147
  options
@@ -531,7 +165,7 @@ function sharedQuery2(options) {
531
165
  if (oldSize <= 1) {
532
166
  return;
533
167
  }
534
- const oldByteSize = (0, import_object_sizeof.default)(oldState);
168
+ const oldByteSize = _objectsizeof2.default.call(void 0, oldState);
535
169
  let numToCut = maxSize ? oldSize - maxSize : 0;
536
170
  let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
537
171
  if (numToCut <= 0 && bytesToCut <= 0) {
@@ -550,7 +184,7 @@ function sharedQuery2(options) {
550
184
  log(`Cannot clean up ${key} as it is mounted`);
551
185
  return;
552
186
  }
553
- 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]);
554
188
  log(
555
189
  `Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
556
190
  );
@@ -589,7 +223,7 @@ function sharedQuery2(options) {
589
223
  }
590
224
  queryState.setValue(newState);
591
225
  log(
592
- `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()})`
593
227
  );
594
228
  }
595
229
  function setData(queryKey, data, dataUpdatedMs = Date.now()) {
@@ -643,9 +277,9 @@ function sharedQuery2(options) {
643
277
  queryState,
644
278
  /** Returns a key to identify requests based on the given args. */
645
279
  getQueryKey(args) {
646
- let s = stringifyDeterministicForKeys(args);
280
+ let s = _stringify.stringifyDeterministicForKeys.call(void 0, args);
647
281
  if (s.length > 30) {
648
- s = import_xxhashjs.default.h32(s, 39406).toString(16).slice(2);
282
+ s = _xxhashjs2.default.h32(s, 39406).toString(16).slice(2);
649
283
  }
650
284
  return queryName + ":" + s;
651
285
  },
@@ -661,7 +295,7 @@ function sharedQuery2(options) {
661
295
  return obj.getAbortControllerByKey(queryKey);
662
296
  },
663
297
  getAbortControllerByKey(queryKey) {
664
- return inflightQueries.get(queryKey)?.abortController ?? null;
298
+ return _nullishCoalesce(_optionalChain([inflightQueries, 'access', _9 => _9.get, 'call', _10 => _10(queryKey), 'optionalAccess', _11 => _11.abortController]), () => ( null));
665
299
  },
666
300
  /**
667
301
  * Get the AbortSignal to check for query abortions.
@@ -708,7 +342,7 @@ function sharedQuery2(options) {
708
342
  return obj.getAbortSignalByKey(queryKey);
709
343
  },
710
344
  getAbortSignalByKey(queryKey) {
711
- return obj.getAbortControllerByKey(queryKey)?.signal ?? null;
345
+ return _nullishCoalesce(_optionalChain([obj, 'access', _12 => _12.getAbortControllerByKey, 'call', _13 => _13(queryKey), 'optionalAccess', _14 => _14.signal]), () => ( null));
712
346
  },
713
347
  /** For cached data, we need to return the correct timestamps as well. */
714
348
  async getCachedOrFetch(...args) {
@@ -716,12 +350,12 @@ function sharedQuery2(options) {
716
350
  await queryState.readyPromise;
717
351
  const waitedMs = Date.now() - startMs;
718
352
  const queryKey = obj.getQueryKey(args);
719
- const cached = queryState.getSnapshot()?.[queryKey];
353
+ const cached = _optionalChain([queryState, 'access', _15 => _15.getSnapshot, 'call', _16 => _16(), 'optionalAccess', _17 => _17[queryKey]]);
720
354
  if (waitedMs) {
721
355
  log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
722
356
  }
723
- if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {
724
- 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)))) {
725
359
  log(`Return fresh data ${queryKey} from cache without fetching`);
726
360
  return cached;
727
361
  }
@@ -744,18 +378,18 @@ function sharedQuery2(options) {
744
378
  },
745
379
  /** Get the entire stored entry for a query key. */
746
380
  getQueryValue(queryKey) {
747
- return queryState.getSnapshot()?.[queryKey];
381
+ return _optionalChain([queryState, 'access', _19 => _19.getSnapshot, 'call', _20 => _20(), 'optionalAccess', _21 => _21[queryKey]]);
748
382
  },
749
383
  /** Get the current stored data for a query key. */
750
384
  getData(queryKey) {
751
- const stateValue = queryState.getSnapshot()?.[queryKey];
752
- 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])) {
753
387
  if (isExpired(stateValue.lastUpdatedMs)) {
754
388
  obj.deleteData(queryKey);
755
389
  return void 0;
756
390
  }
757
391
  }
758
- return stateValue?.data;
392
+ return _optionalChain([stateValue, 'optionalAccess', _26 => _26.data]);
759
393
  },
760
394
  /** Set the data directly if the user obtained it from somewhere else. */
761
395
  setData,
@@ -797,7 +431,7 @@ function sharedQuery2(options) {
797
431
  },
798
432
  /** Keep track of mounted keys. */
799
433
  mount(queryKey) {
800
- mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);
434
+ mountedKeys.set(queryKey, (_nullishCoalesce(mountedKeys.get(queryKey), () => ( 0))) + 1);
801
435
  },
802
436
  /** Clean up mounted keys. */
803
437
  unmount(queryKey) {
@@ -805,7 +439,7 @@ function sharedQuery2(options) {
805
439
  if (count === 1) {
806
440
  mountedKeys.delete(queryKey);
807
441
  } else {
808
- mountedKeys.set(queryKey, (count ?? 0) - 1);
442
+ mountedKeys.set(queryKey, (_nullishCoalesce(count, () => ( 0))) - 1);
809
443
  }
810
444
  },
811
445
  /**
@@ -819,36 +453,36 @@ function sharedQuery2(options) {
819
453
  function sharedQuery(options) {
820
454
  return sharedQuery1(options);
821
455
  }
822
- var DEFAULT_QUERY_STATE_ENTRY = {
456
+ const DEFAULT_QUERY_STATE_ENTRY = {
823
457
  lastUpdatedMs: 0,
824
458
  loading: true
825
459
  };
826
460
  function useSharedQuery(query, ...args) {
827
- const stableArgs = useDeepMemo(args);
828
- const [queryState, setQueryState] = useSharedState(query.queryState);
829
- const isMounted = (0, import_react3.useRef)(true);
830
- 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,
831
465
  () => query.getQueryKey(stableArgs),
832
466
  [query, stableArgs]
833
467
  );
834
- const queryStateValue = queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;
835
- const setQueryStateValue = (0, import_react3.useCallback)(
468
+ const queryStateValue = _nullishCoalesce(queryState[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY));
469
+ const setQueryStateValue = _react.useCallback.call(void 0,
836
470
  (next) => {
837
471
  setQueryState((prev) => {
838
472
  const clone = { ...prev };
839
- 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;
840
474
  return clone;
841
475
  });
842
476
  },
843
477
  [queryKey, setQueryState]
844
478
  );
845
- const [lastNonEmptyData, setLastNonEmptyData] = (0, import_react3.useState)();
846
- (0, import_react3.useEffect)(() => {
479
+ const [lastNonEmptyData, setLastNonEmptyData] = _react.useState.call(void 0, );
480
+ _react.useEffect.call(void 0, () => {
847
481
  if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
848
482
  setLastNonEmptyData(queryStateValue.data);
849
483
  }
850
484
  }, [query.keepLastNonEmptyData, queryStateValue.data]);
851
- const executeQuery = (0, import_react3.useCallback)(
485
+ const executeQuery = _react.useCallback.call(void 0,
852
486
  async (isRefetch) => {
853
487
  query.log(
854
488
  `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
@@ -893,7 +527,7 @@ function useSharedQuery(query, ...args) {
893
527
  },
894
528
  [query, queryKey, setQueryStateValue, stableArgs]
895
529
  );
896
- (0, import_react3.useEffect)(() => {
530
+ _react.useEffect.call(void 0, () => {
897
531
  isMounted.current = true;
898
532
  query.mount(queryKey);
899
533
  void executeQuery(false);
@@ -902,7 +536,7 @@ function useSharedQuery(query, ...args) {
902
536
  query.unmount(queryKey);
903
537
  };
904
538
  }, [executeQuery, query, queryKey]);
905
- return (0, import_react3.useMemo)(() => {
539
+ return _react.useMemo.call(void 0, () => {
906
540
  return {
907
541
  ...queryStateValue,
908
542
  // Fill with lastNonEmptyData when data is undefined.
@@ -913,12 +547,12 @@ function useSharedQuery(query, ...args) {
913
547
  // abort the running queryFn.
914
548
  abortCurrentQuery: (reason) => {
915
549
  const controller = query.getAbortControllerByKey(queryKey);
916
- controller?.abort(reason);
550
+ _optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
917
551
  return Boolean(controller);
918
552
  },
919
553
  getCachedOrFetch: async () => {
920
554
  const data = await query.getCachedOrFetch(...stableArgs);
921
- return (0, import_nonNil.nonNil)(
555
+ return _nonNil.nonNil.call(void 0,
922
556
  data.data,
923
557
  typeof data.error === "string" ? data.error : JSON.stringify(data.error)
924
558
  );
@@ -942,10 +576,9 @@ function useSharedQuery(query, ...args) {
942
576
  stableArgs
943
577
  ]);
944
578
  }
945
- // Annotate the CommonJS export names for ESM import in node:
946
- 0 && (module.exports = {
947
- SharedQueryConfig,
948
- configureSharedQuery,
949
- sharedQuery,
950
- useSharedQuery
951
- });
579
+
580
+
581
+
582
+
583
+
584
+ exports.SharedQueryConfig = SharedQueryConfig; exports.configureSharedQuery = configureSharedQuery; exports.sharedQuery = sharedQuery; exports.useSharedQuery = useSharedQuery;