@choksheak/react-utils 0.3.8 → 0.4.0

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 (87) hide show
  1. package/NoSSR.cjs +7 -30
  2. package/NoSSR.min.cjs +1 -1
  3. package/NoSSR.min.cjs.map +1 -1
  4. package/NoSSR.min.mjs +1 -1
  5. package/NoSSR.min.mjs.map +1 -1
  6. package/NoSSR.mjs +2 -0
  7. package/chunk-33UMQLKY.mjs +43 -0
  8. package/chunk-3V7WBGWQ.mjs +16 -0
  9. package/chunk-3X25NN6X.cjs +195 -0
  10. package/chunk-5DO7KC3L.cjs +43 -0
  11. package/chunk-5PDGU37E.cjs +104 -0
  12. package/chunk-6ZZ54XM5.min.mjs +2 -0
  13. package/chunk-6ZZ54XM5.min.mjs.map +1 -0
  14. package/chunk-74BS2FAO.cjs +12 -0
  15. package/chunk-F5L32IUC.min.cjs +2 -0
  16. package/chunk-F5L32IUC.min.cjs.map +1 -0
  17. package/chunk-GPV6JIQK.mjs +17 -0
  18. package/chunk-KE3RXVMS.min.cjs +2 -0
  19. package/chunk-KE3RXVMS.min.cjs.map +1 -0
  20. package/chunk-KILGR7YA.min.mjs +2 -0
  21. package/chunk-KILGR7YA.min.mjs.map +1 -0
  22. package/chunk-KRXENFK3.mjs +195 -0
  23. package/chunk-MWDH7YON.min.mjs +2 -0
  24. package/chunk-MWDH7YON.min.mjs.map +1 -0
  25. package/chunk-NTFFK7ZH.min.cjs +2 -0
  26. package/chunk-NTFFK7ZH.min.cjs.map +1 -0
  27. package/chunk-O3RBYG3W.min.cjs +2 -0
  28. package/chunk-O3RBYG3W.min.cjs.map +1 -0
  29. package/chunk-PHLY3LR4.mjs +104 -0
  30. package/chunk-RM4ZGGZ2.min.mjs +2 -0
  31. package/chunk-RM4ZGGZ2.min.mjs.map +1 -0
  32. package/chunk-TEZPF6BG.min.cjs +2 -0
  33. package/chunk-TEZPF6BG.min.cjs.map +1 -0
  34. package/chunk-UFJNJ3WV.cjs +16 -0
  35. package/chunk-UFJQLQFI.min.cjs +2 -0
  36. package/chunk-UFJQLQFI.min.cjs.map +1 -0
  37. package/chunk-V7L3UICC.min.mjs +2 -0
  38. package/chunk-V7L3UICC.min.mjs.map +1 -0
  39. package/chunk-VHMO75EY.min.mjs +2 -0
  40. package/chunk-VHMO75EY.min.mjs.map +1 -0
  41. package/chunk-WVLPJPWG.cjs +17 -0
  42. package/chunk-X6BYQHVC.mjs +12 -0
  43. package/fetcher.cjs +8 -50
  44. package/fetcher.d.mts +3 -3
  45. package/fetcher.d.ts +2 -2
  46. package/fetcher.min.cjs +1 -1
  47. package/fetcher.min.cjs.map +1 -1
  48. package/fetcher.min.mjs +1 -1
  49. package/fetcher.min.mjs.map +1 -1
  50. package/fetcher.mjs +5 -11
  51. package/package.json +124 -29
  52. package/sharedQuery.cjs +132 -392
  53. package/sharedQuery.d.mts +58 -13
  54. package/sharedQuery.d.ts +57 -12
  55. package/sharedQuery.min.cjs +1 -1
  56. package/sharedQuery.min.cjs.map +1 -1
  57. package/sharedQuery.min.mjs +1 -1
  58. package/sharedQuery.min.mjs.map +1 -1
  59. package/sharedQuery.mjs +94 -322
  60. package/sharedState.cjs +15 -304
  61. package/sharedState.d.mts +4 -4
  62. package/sharedState.d.ts +4 -4
  63. package/sharedState.min.cjs +1 -1
  64. package/sharedState.min.cjs.map +1 -1
  65. package/sharedState.min.mjs +1 -1
  66. package/sharedState.min.mjs.map +1 -1
  67. package/sharedState.mjs +10 -269
  68. package/storage.cjs +10 -123
  69. package/storage.d.mts +1 -0
  70. package/storage.d.ts +1 -0
  71. package/storage.min.cjs +1 -1
  72. package/storage.min.cjs.map +1 -1
  73. package/storage.min.mjs +1 -1
  74. package/storage.min.mjs.map +1 -1
  75. package/storage.mjs +6 -92
  76. package/stringify.cjs +8 -57
  77. package/stringify.min.cjs +1 -1
  78. package/stringify.min.cjs.map +1 -1
  79. package/stringify.min.mjs +1 -1
  80. package/stringify.min.mjs.map +1 -1
  81. package/stringify.mjs +6 -30
  82. package/useDeepMemo.cjs +6 -50
  83. package/useDeepMemo.min.cjs +1 -1
  84. package/useDeepMemo.min.cjs.map +1 -1
  85. package/useDeepMemo.min.mjs +1 -1
  86. package/useDeepMemo.min.mjs.map +1 -1
  87. package/useDeepMemo.mjs +4 -13
package/sharedQuery.d.mts CHANGED
@@ -112,10 +112,11 @@ type QueryStateValue<TData> = Readonly<{
112
112
  /** Return type for useSharedQuery(). */
113
113
  type UseQueryResult<TData> = QueryStateValue<TData> & Readonly<{
114
114
  /**
115
- * Return the last non-empty data if you want to display the last loaded data
116
- * while waiting for the new data to load.
115
+ * Usually same as `data`, but if you specify `keepLastNonEmptyData: true`,
116
+ * then this will contain the latest data (undefined when args just changed)
117
+ * and data will contain the last non empty data.
117
118
  */
118
- lastNonEmptyData: TData | undefined;
119
+ latestData: TData | undefined;
119
120
  /**
120
121
  * Cancels the inflight query (if any). Returns true if canceled.
121
122
  */
@@ -136,8 +137,7 @@ type UseQueryResult<TData> = QueryStateValue<TData> & Readonly<{
136
137
  * query key to the state entry.
137
138
  */
138
139
  type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;
139
- /** Options to configure a shared query. */
140
- type SharedQueryOptions<TArgs extends unknown[], TData> = {
140
+ type QueryTargetWithFn<TArgs extends unknown[], TData> = {
141
141
  /**
142
142
  * The name could have been auto-generated, but we let the user give us a
143
143
  * human-readable name that can be identified quickly in the logs.
@@ -145,10 +145,41 @@ type SharedQueryOptions<TArgs extends unknown[], TData> = {
145
145
  * arguments.
146
146
  */
147
147
  queryName: string;
148
+ /** Function to fetch data. */
149
+ queryFn: QueryFn<TArgs, TData>;
150
+ };
151
+ type QueryTargetWithUrl = {
148
152
  /**
149
- * Function to fetch data.
153
+ * The queryName can optionally be specified, else we will fallback to use
154
+ * the url as the queryName.
150
155
  */
151
- queryFn: QueryFn<TArgs, TData>;
156
+ queryName?: string;
157
+ /**
158
+ * URL to fetch data using HTTP GET. Note that using this field will cause
159
+ * both TArgs and TData to be undefined (unknown). Therefore you can make up
160
+ * for this by specifying types with useSharedQuery, like this:
161
+ * ```
162
+ * const usersQuery = useSharedQuery<[{ userId?: string[] }], User[]>({
163
+ * url: "/api/list-users",
164
+ * });
165
+ * ```
166
+ *
167
+ * If `userId` were specified as ["u1", "u2"], the query url would be
168
+ * "/api/list-users?userId=u1&userId=u2".
169
+ *
170
+ * You can also pass the params as a string like "userId=u1&userId=u2".
171
+ * ```
172
+ * const usersQuery = useSharedQuery<[string], User[]>({
173
+ * url: "/api/list-users",
174
+ * });
175
+ * ```
176
+ */
177
+ url: string;
178
+ };
179
+ /** Specifies how to fetch the data. */
180
+ type QueryTarget<TArgs extends unknown[], TData> = QueryTargetWithFn<TArgs, TData> | QueryTargetWithUrl;
181
+ /** Options to configure a shared query. */
182
+ type SharedQueryOptions<TArgs extends unknown[], TData> = QueryTarget<TArgs, TData> & {
152
183
  /**
153
184
  * Function to re-fetch data. Usually this would just be the `queryFn`, but
154
185
  * if you need a different behavior for refetching, then specify this.
@@ -249,12 +280,12 @@ declare function sharedQuery<TArgs extends unknown[], TData>(options: SharedQuer
249
280
  readonly initDone: false;
250
281
  readonly subscribe: (subscriber: () => void) => () => void;
251
282
  readonly hasStore: () => boolean;
252
- readonly setInStore: (value: SharedQueryState<TData>) => Promise<void>;
253
- readonly getFromStore: () => Promise<SharedQueryState<TData> | undefined>;
283
+ readonly setInStore: (value: SharedQueryState<TData>) => Promise<void> | void;
284
+ readonly getFromStore: () => SharedQueryState<TData> | Promise<SharedQueryState<TData> | undefined> | undefined;
254
285
  readonly getSnapshot: () => SharedQueryState<TData>;
255
286
  readonly setValue: (next: SetStateAction<SharedQueryState<TData>>) => void;
256
- readonly delete: () => void;
257
- readonly initDefaultValueOnce: () => Promise<void>;
287
+ readonly delete: () => Promise<void> | void;
288
+ readonly initDefaultValueOnce: () => Promise<void> | void;
258
289
  };
259
290
  /** Returns a key to identify requests based on the given args. */
260
291
  readonly getQueryKey: (args: TArgs) => string;
@@ -270,7 +301,7 @@ declare function sharedQuery<TArgs extends unknown[], TData>(options: SharedQuer
270
301
  /**
271
302
  * Get the AbortSignal to check for query abortions.
272
303
  *
273
- * Example:
304
+ * Example using fetch:
274
305
  * ```
275
306
  * const getUserQuery = sharedQuery({
276
307
  * queryName: "getUser",
@@ -291,6 +322,20 @@ declare function sharedQuery<TArgs extends unknown[], TData>(options: SharedQuer
291
322
  * },
292
323
  * });
293
324
  * ```
325
+ *
326
+ * Example using `fetcher.ts`:
327
+ * ```
328
+ * const getUserQuery = sharedQuery({
329
+ * queryName: "getUser",
330
+ * queryFn: (userId: string) => {
331
+ * // Get the signal for this current execution.
332
+ * const signal = getUserQuery.getAbortSignal([userId]);
333
+ *
334
+ * // Pass the signal to fetch so that it can be aborted.
335
+ * return fetcher.url(`/users/${userId}`).options({ signal }).get().json();
336
+ * },
337
+ * });
338
+ * ```
294
339
  */
295
340
  readonly getAbortSignal: (args: TArgs) => AbortSignal | null;
296
341
  readonly getAbortSignalByKey: (queryKey: string) => AbortSignal | null;
@@ -341,4 +386,4 @@ type SharedQuery<TArgs extends unknown[], TData> = ReturnType<typeof sharedQuery
341
386
  */
342
387
  declare function useSharedQuery<TArgs extends unknown[], TData>(query: SharedQuery<TArgs, TData>, ...args: TArgs): UseQueryResult<TData>;
343
388
 
344
- export { type QueryFn, type QueryStateValue, type SharedQuery, SharedQueryConfig, type SharedQueryOptions, type SharedQueryState, type UseQueryResult, configureSharedQuery, sharedQuery, useSharedQuery };
389
+ export { type QueryFn, type QueryStateValue, type QueryTarget, type QueryTargetWithFn, type QueryTargetWithUrl, type SharedQuery, SharedQueryConfig, type SharedQueryOptions, type SharedQueryState, type UseQueryResult, configureSharedQuery, sharedQuery, useSharedQuery };
package/sharedQuery.d.ts CHANGED
@@ -108,10 +108,11 @@ export type QueryStateValue<TData> = Readonly<{
108
108
  /** Return type for useSharedQuery(). */
109
109
  export type UseQueryResult<TData> = QueryStateValue<TData> & Readonly<{
110
110
  /**
111
- * Return the last non-empty data if you want to display the last loaded data
112
- * while waiting for the new data to load.
111
+ * Usually same as `data`, but if you specify `keepLastNonEmptyData: true`,
112
+ * then this will contain the latest data (undefined when args just changed)
113
+ * and data will contain the last non empty data.
113
114
  */
114
- lastNonEmptyData: TData | undefined;
115
+ latestData: TData | undefined;
115
116
  /**
116
117
  * Cancels the inflight query (if any). Returns true if canceled.
117
118
  */
@@ -132,8 +133,7 @@ export type UseQueryResult<TData> = QueryStateValue<TData> & Readonly<{
132
133
  * query key to the state entry.
133
134
  */
134
135
  export type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;
135
- /** Options to configure a shared query. */
136
- export type SharedQueryOptions<TArgs extends unknown[], TData> = {
136
+ export type QueryTargetWithFn<TArgs extends unknown[], TData> = {
137
137
  /**
138
138
  * The name could have been auto-generated, but we let the user give us a
139
139
  * human-readable name that can be identified quickly in the logs.
@@ -141,10 +141,41 @@ export type SharedQueryOptions<TArgs extends unknown[], TData> = {
141
141
  * arguments.
142
142
  */
143
143
  queryName: string;
144
+ /** Function to fetch data. */
145
+ queryFn: QueryFn<TArgs, TData>;
146
+ };
147
+ export type QueryTargetWithUrl = {
144
148
  /**
145
- * Function to fetch data.
149
+ * The queryName can optionally be specified, else we will fallback to use
150
+ * the url as the queryName.
146
151
  */
147
- queryFn: QueryFn<TArgs, TData>;
152
+ queryName?: string;
153
+ /**
154
+ * URL to fetch data using HTTP GET. Note that using this field will cause
155
+ * both TArgs and TData to be undefined (unknown). Therefore you can make up
156
+ * for this by specifying types with useSharedQuery, like this:
157
+ * ```
158
+ * const usersQuery = useSharedQuery<[{ userId?: string[] }], User[]>({
159
+ * url: "/api/list-users",
160
+ * });
161
+ * ```
162
+ *
163
+ * If `userId` were specified as ["u1", "u2"], the query url would be
164
+ * "/api/list-users?userId=u1&userId=u2".
165
+ *
166
+ * You can also pass the params as a string like "userId=u1&userId=u2".
167
+ * ```
168
+ * const usersQuery = useSharedQuery<[string], User[]>({
169
+ * url: "/api/list-users",
170
+ * });
171
+ * ```
172
+ */
173
+ url: string;
174
+ };
175
+ /** Specifies how to fetch the data. */
176
+ export type QueryTarget<TArgs extends unknown[], TData> = QueryTargetWithFn<TArgs, TData> | QueryTargetWithUrl;
177
+ /** Options to configure a shared query. */
178
+ export type SharedQueryOptions<TArgs extends unknown[], TData> = QueryTarget<TArgs, TData> & {
148
179
  /**
149
180
  * Function to re-fetch data. Usually this would just be the `queryFn`, but
150
181
  * if you need a different behavior for refetching, then specify this.
@@ -245,12 +276,12 @@ export declare function sharedQuery<TArgs extends unknown[], TData>(options: Sha
245
276
  readonly initDone: false;
246
277
  readonly subscribe: (subscriber: () => void) => () => void;
247
278
  readonly hasStore: () => boolean;
248
- readonly setInStore: (value: SharedQueryState<TData>) => Promise<void>;
249
- readonly getFromStore: () => Promise<SharedQueryState<TData> | undefined>;
279
+ readonly setInStore: (value: SharedQueryState<TData>) => Promise<void> | void;
280
+ readonly getFromStore: () => SharedQueryState<TData> | Promise<SharedQueryState<TData> | undefined> | undefined;
250
281
  readonly getSnapshot: () => SharedQueryState<TData>;
251
282
  readonly setValue: (next: SetStateAction<SharedQueryState<TData>>) => void;
252
- readonly delete: () => void;
253
- readonly initDefaultValueOnce: () => Promise<void>;
283
+ readonly delete: () => Promise<void> | void;
284
+ readonly initDefaultValueOnce: () => Promise<void> | void;
254
285
  };
255
286
  /** Returns a key to identify requests based on the given args. */
256
287
  readonly getQueryKey: (args: TArgs) => string;
@@ -266,7 +297,7 @@ export declare function sharedQuery<TArgs extends unknown[], TData>(options: Sha
266
297
  /**
267
298
  * Get the AbortSignal to check for query abortions.
268
299
  *
269
- * Example:
300
+ * Example using fetch:
270
301
  * ```
271
302
  * const getUserQuery = sharedQuery({
272
303
  * queryName: "getUser",
@@ -287,6 +318,20 @@ export declare function sharedQuery<TArgs extends unknown[], TData>(options: Sha
287
318
  * },
288
319
  * });
289
320
  * ```
321
+ *
322
+ * Example using `fetcher.ts`:
323
+ * ```
324
+ * const getUserQuery = sharedQuery({
325
+ * queryName: "getUser",
326
+ * queryFn: (userId: string) => {
327
+ * // Get the signal for this current execution.
328
+ * const signal = getUserQuery.getAbortSignal([userId]);
329
+ *
330
+ * // Pass the signal to fetch so that it can be aborted.
331
+ * return fetcher.url(`/users/${userId}`).options({ signal }).get().json();
332
+ * },
333
+ * });
334
+ * ```
290
335
  */
291
336
  readonly getAbortSignal: (args: TArgs) => AbortSignal | null;
292
337
  readonly getAbortSignalByKey: (queryKey: string) => AbortSignal | null;
@@ -1,2 +1,2 @@
1
- "use strict";var ae=Object.create;var P=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty;var de=(e,o)=>{for(var n in o)P(e,n,{get:o[n],enumerable:!0})},K=(e,o,n,r)=>{if(o&&typeof o=="object"||typeof o=="function")for(let a of se(o))!ue.call(e,a)&&a!==n&&P(e,a,{get:()=>o[a],enumerable:!(r=oe(o,a))||r.enumerable});return e};var j=(e,o,n)=>(n=e!=null?ae(ie(e)):{},K(o||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),ce=e=>K(P({},"__esModule",{value:!0}),e);var me={};de(me,{SharedQueryConfig:()=>M,configureSharedQuery:()=>pe,sharedQuery:()=>ye,useSharedQuery:()=>Te});module.exports=ce(me);var re=require("@choksheak/ts-utils/timeConstants"),U=j(require("object-sizeof")),b=require("react");var J=require("@choksheak/ts-utils/timeConstants"),W=require("react");var O=require("@choksheak/ts-utils/kvStore"),_=require("@choksheak/ts-utils/localStore"),x=typeof window>"u";function Y(e,o){let{store:n}=e??{};if(!n)return null;if("persistTo"in n&&typeof n.persistTo=="string"&&"key"in n&&typeof n.key=="string"){let r=n.expiryMs||o,a={...n,expiryMs:r};switch(n.persistTo){case"localStorage":return le(a);case"indexedDb":return fe(a);default:throw n.persistTo,new Error(`Unknown store.adapter ${n.persistTo}`)}}return n}function le({key:e,expiryMs:o,isValid:n}){let r=(0,_.createLocalStore)(e,{defaultExpiryMs:o});return{set:(a,s)=>{x||r.set(a,s)},get:a=>{if(x)return;let s=r.get(a);if(n&&!n(s)){console.warn(`localStorage adapter: Auto-discard invalid value for ${a}: ${JSON.stringify(s)}`),r.delete(a);return}return s},delete:a=>{x||r.delete(a)},clear:()=>{x||r.clear()}}}function fe({key:e,expiryMs:o,isValid:n}){let r=e+":";return{set:async(a,s)=>{x||await O.kvStore.set(r+a,s,o)},get:async a=>{if(x)return;let s=r+a,u=await O.kvStore.get(s);if(u!==void 0&&n&&!n(u)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${a}:`,u),await O.kvStore.delete(s);return}return u},delete:async a=>{x||await O.kvStore.delete(r+a)},clear:async()=>{x||await O.kvStore.clear()}}}var I={storeExpiryMs:30*J.MS_PER_DAY,lazyLoad:!1};function ge(){let e=new Map,o=new Map;function n(r,a,s){let u=o.get(r);if(!u)return;let T=Array.from(u.values());for(let h of T)try{h(a,s)}catch(S){console.error("Error invoking subscriber:",S)}}return{get(r){return e.get(r)},set(r,a){let s=e.get(r);s!==a&&(e.set(r,a),n(r,a,s))},delete(r){e.delete(r)},setNoNotify(r,a){e.set(r,a)},subscribe(r,a){let s=o.get(r);return s||(s=new Set,o.set(r,s)),s.add(a),()=>{s.delete(a),s.size===0&&o.delete(r)}}}}var Q=ge(),z="state",Se=0;function G(e,o){let n=()=>{},r=new Promise(f=>{n=f}),a=n,s=String(Se++),u=Y(o,I.storeExpiryMs);Q.setNoNotify(s,e);let T=o?.lazyLoad,h=T!==void 0?T:I.lazyLoad,S={readyPromise:r,lazy:h,initStarted:!1,initDone:!1,subscribe(f){return Q.subscribe(s,()=>f())},hasStore(){return!!u},async setInStore(f){return await u?.set(z,f)},async getFromStore(){return await u?.get(z)},getSnapshot(){return Q.get(s)},setValue(f){if(typeof f=="function"){let p=Q.get(s);f=f(p)}Q.set(s,f),S.setInStore(f)},delete(){Q.set(s,e),u?.set(z,e)},async initDefaultValueOnce(){if(S.initDone||S.initStarted)return;S.initStarted=!0;let f=await S.getFromStore(),p=f!==void 0?f:e;Q.set(s,p),S.initDone=!0,a()}};return h||S.initDefaultValueOnce(),S}function H(e){return e.initDefaultValueOnce(),[(0,W.useSyncExternalStore)(n=>e.subscribe(n),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function X(e){let o=new Set;return JSON.stringify(e,(n,r)=>{if(typeof r=="function")throw new Error("Functions should not be passed into query parameters");if(!r||typeof r!="object"||Array.isArray(r))return r;if(o.has(r))return"[Circular]";if(o.add(r),r!==e)try{JSON.stringify(r)}catch{return"[Unserializable]"}return Object.keys(r).sort().reduce((a,s)=>(a[s]=r[s],a),{})})}var Z=j(require("lodash/isEqual")),E=require("react");function q(e){let[o,n]=(0,E.useState)(e);return(0,E.useMemo)(()=>(0,Z.default)(o,e)?o:(n(e),e),[o,e])}var M={staleMs:0,expiryMs:30*re.MS_PER_DAY,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...e)=>console.log("[sharedQuery]",...e)};function pe(e){Object.assign(M,e)}var ee=new Set;function ye(e){if(ee.has(e.queryName))throw new Error(`Duplicate shared query name "${e.queryName}"`);ee.add(e.queryName);let o=new Map,n=new Map,r=e.queryName,a=e.queryFn,s=e.refetchFn,u=e?.staleMs??M.staleMs,T=e?.expiryMs??M.expiryMs,h=e?.refetchOnStale??M.refetchOnStale,S=e.store;if(S){if("persistTo"in S&&S.isValid){let t=S.isValid;e={...e,store:{...S,isValid:i=>{if(!i||typeof i!="object")return!1;for(let l of Object.values(i))if(!l||typeof l!="object"||!("data"in l)||!("dataUpdatedMs"in l)||!("lastUpdatedMs"in l)||typeof l.dataUpdatedMs!="number"||typeof l.lastUpdatedMs!="number"||!t(l.data))return!1;return!0}}}}}else{let t=e.persistTo??M.persistTo;t&&(e={...e,store:{persistTo:t,key:r,expiryMs:T}})}let f=e?.maxSize??M.maxSize,p=e?.maxBytes??M.maxBytes,D=!!e?.keepLastNonEmptyData,d=e?.log??M.log,g=G({},e);function v(t){return u===0?!0:Date.now()-t>u}function N(t){return T===0?!1:Date.now()-t>T}function R(){if(!f&&!p)return;let t=g.getSnapshot(),i=Object.keys(t).length;if(i<=1)return;let l=(0,U.default)(t),c=f?i-f:0,y=p?l-p:0;if(c<=0&&y<=0){d(`No need to trim data for ${r}: size=${i} (limit=${f}), byteSize=${l.toLocaleString()} (limit=${p.toLocaleString()})`);return}d(`Need to trim ${r}: numToCut=${c}, bytesToCut=${y}`);let w={...t},$=!1,B=(m,C)=>{if(n.has(m)){d(`Cannot clean up ${m} as it is mounted`);return}let F=(0,U.default)(m)+(0,U.default)(w[m]);d(`Cleaning up unmounted${C?", expired":""} ${m} (byteSize=${F.toLocaleString()})`),c--,y-=F,delete w[m],$=!0},V=Object.entries(w).sort((m,C)=>m[1].lastUpdatedMs-C[1].lastUpdatedMs);for(let[m]of V){if(!N(w[m].lastUpdatedMs))break;B(m,!0)}if(c>0||y>0){$&&(V=Object.entries(w).sort((m,C)=>m[1].lastUpdatedMs-C[1].lastUpdatedMs));for(let[m]of V)if(B(m,!1),c<=0&&y<=0)break}if(!$){d(`No trimmable entries found for ${r}: size=${i} (limit=${f}), byteSize=${l.toLocaleString()} (limit=${p.toLocaleString()})`);return}g.setValue(w),d(`Trimmed data for ${r}: size=[${i} -> ${Object.keys(w).length}] (limit=${f}), byteSize=[${l.toLocaleString()} -> ${(0,U.default)(w).toLocaleString()}] (limit=${p.toLocaleString()})`)}function L(t,i,l=Date.now()){let c={lastUpdatedMs:Date.now(),loading:!1,data:i,dataUpdatedMs:l};g.setValue(y=>({...y,[t]:c})),R()}async function ne(t,i,l){d(`Start fetching ${t}, queryType=${i}`);try{let c=await(i==="refetch"&&s?s(...l):a(...l));return d(`Successfully fetched ${t}`),L(t,c,Date.now()),c}catch(c){throw d(`Failed to fetch ${t} for queryType=${i}: ${c}`),c}finally{o.delete(t)}}function k(t,i,...l){let c=o.get(t);if(c)return d(`Deduplicating inflight fetch for ${t}, queryType=${i}`),c.promise;let y=ne(t,i,l),w=new AbortController;return o.set(t,{promise:y,abortController:w}),y}let A={queryName:r,queryFn:a,refetchFn:s,expiryMs:T,staleMs:u,refetchOnStale:h,maxSize:f,maxBytes:p,keepLastNonEmptyData:D,log:d,queryState:g,getQueryKey(t){return r+":"+X(t)},getAbortController(t){let i=A.getQueryKey(t);return A.getAbortControllerByKey(i)},getAbortControllerByKey(t){return o.get(t)?.abortController??null},getAbortSignal(t){let i=A.getQueryKey(t);return A.getAbortSignalByKey(i)},getAbortSignalByKey(t){return A.getAbortControllerByKey(t)?.signal??null},async getCachedOrFetch(...t){let i=Date.now();await g.readyPromise;let l=Date.now()-i,c=A.getQueryKey(t),y=g.getSnapshot()?.[c];if(l&&d(`${c}: Waited for ${l}ms before data is ready`),y?.data&&!N(y.dataUpdatedMs??0))return v(y.dataUpdatedMs??0)?(h&&(d(`refetchOnStale for ${c}`),k(c,"query",...t)),d(`Returning stale data for ${c}`),y):(d(`Return fresh data ${c} from cache without fetching`),y);let w=await k(c,"query",...t),$=Date.now();return{lastUpdatedMs:$,loading:!1,data:w,dataUpdatedMs:$}},getQueryValue(t){return g.getSnapshot()?.[t]},getData(t){let i=g.getSnapshot()?.[t];if(i?.lastUpdatedMs&&N(i.lastUpdatedMs)){A.deleteData(t);return}return i?.data},setData:L,async updateFromSource(...t){let i=A.getQueryKey(t);return await k(i,"query",...t)},async refetch(...t){let i=A.getQueryKey(t);return await k(i,"refetch",...t)},deleteData(t){let l={...g.getSnapshot()};delete l[t],g.setValue(l);let c=o.get(t);c&&(o.delete(t),c.abortController.abort("Deleted"))},clear(){g.delete();for(let{abortController:t}of Array.from(o.values()))t.abort("Cleared");o.clear()},mount(t){n.set(t,(n.get(t)??0)+1)},unmount(t){let i=n.get(t);i===1?n.delete(t):n.set(t,(i??0)-1)},enforceSizeLimit:R};return A}var te={lastUpdatedMs:0,loading:!0};function Te(e,...o){let n=q(o),[r,a]=H(e.queryState),s=(0,b.useRef)(!0),u=(0,b.useMemo)(()=>e.getQueryKey(n),[e,n]),T=r[u]??te,h=(0,b.useCallback)(D=>{a(d=>{let g={...d};return g[u]=typeof D=="function"?D(g[u]??te):D,g})},[u,a]),[S,f]=(0,b.useState)();(0,b.useEffect)(()=>{e.keepLastNonEmptyData&&T.data!==void 0&&f(T.data)},[e.keepLastNonEmptyData,T.data]);let p=(0,b.useCallback)(async D=>{if(e.log(`Begin executing shared query ${u}, isRefetch=${D}`),!!s.current){h(d=>({...d,lastUpdatedMs:Date.now(),loading:!0}));try{let d;if(D){let g=await e.refetch(...n),v=Date.now();d={lastUpdatedMs:v,loading:!1,data:g,dataUpdatedMs:v}}else d=await e.getCachedOrFetch(...n);if(!s.current)return;h({...d,loading:!1})}catch(d){if(!s.current)return;let g=Date.now();h(v=>({...v,lastUpdatedMs:g,loading:!1,error:d,errorUpdatedMs:g}))}}},[e,u,h,n]);return(0,b.useEffect)(()=>(s.current=!0,e.mount(u),p(!1),()=>{s.current=!1,e.unmount(u)}),[p,e,u]),(0,b.useMemo)(()=>({...T,lastNonEmptyData:S,abortCurrentQuery:D=>{let d=e.getAbortControllerByKey(u);return d?.abort(D),!!d},refetch:()=>p(!0),setData:(D,d)=>{e.setData(u,D,d)},deleteData:()=>{e.deleteData(u)}}),[p,S,e,u,T])}0&&(module.exports={SharedQueryConfig,configureSharedQuery,sharedQuery,useSharedQuery});
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 _chunkO3RBYG3Wmincjs = require('./chunk-O3RBYG3W.min.cjs');var _chunkNTFFK7ZHmincjs = require('./chunk-NTFFK7ZH.min.cjs');require('./chunk-UFJQLQFI.min.cjs');var _chunkTEZPF6BGmincjs = require('./chunk-TEZPF6BG.min.cjs');var _chunkF5L32IUCmincjs = require('./chunk-F5L32IUC.min.cjs');require('./chunk-KE3RXVMS.min.cjs');var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);var _react = require('react');var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);_chunkTEZPF6BGmincjs.b.call(void 0, );var Q={staleMs:0,expiryMs:30*864e5,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...r)=>console.log("[sharedQuery]",...r)};function se(r){Object.assign(Q,r)}var W=new Set;function ie(r){let w=r.url||"",u=r.queryName||w;if(!u)throw new Error("Either queryName or url must be specified.");if(W.has(u))throw new Error(`Duplicate shared query name "${u}"`);W.add(u);let p=new Map,h=new Map,m;if(r.queryFn)m=r.queryFn;else if(w)m=(...e)=>{let t="",a=_optionalChain([e, 'optionalAccess', _2 => _2[0]]);if(a){if(typeof a=="string")t=a;else if(typeof a=="object"){let n=[];for(let[s,d]of Object.entries(a))if(d!==void 0)if(Array.isArray(d))for(let b of d)b!==void 0&&n.push([s,String(b)]);else n.push([s,String(d)]);t=new URLSearchParams(n).toString()}t&&(w.includes("?")?t="&"+t:t="?"+t)}return _chunkO3RBYG3Wmincjs.a.url(w+t).get().json()};else throw new Error("Either queryFn or url must be specified");let l=r.refetchFn,y=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _3 => _3.staleMs]), () => (Q.staleMs)),D=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _4 => _4.expiryMs]), () => (Q.expiryMs)),M=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _5 => _5.refetchOnStale]), () => (Q.refetchOnStale)),A=r.store;if(A){if("persistTo"in A&&A.isValid){let e=A.isValid;r={...r,store:{...A,isValid:t=>{if(!t||typeof t!="object")return!1;for(let a of Object.values(t))if(!a||typeof a!="object"||!("data"in a)||!("dataUpdatedMs"in a)||!("lastUpdatedMs"in a)||typeof a.dataUpdatedMs!="number"||typeof a.lastUpdatedMs!="number"||!e(a.data))return!1;return!0}}}}}else{let e=_nullishCoalesce(r.persistTo, () => (Q.persistTo));e&&(r={...r,store:{persistTo:e,key:u,expiryMs:D}})}let T=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _6 => _6.maxSize]), () => (Q.maxSize)),i=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _7 => _7.maxBytes]), () => (Q.maxBytes)),c=!!_optionalChain([r, 'optionalAccess', _8 => _8.keepLastNonEmptyData]),o=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _9 => _9.log]), () => (Q.log)),f=_chunkNTFFK7ZHmincjs.c.call(void 0, {},r);function _(e){return y===0?!0:Date.now()-e>y}function C(e){return D===0?!1:Date.now()-e>D}function k(){if(!T&&!i)return;let e=f.getSnapshot(),t=Object.keys(e).length;if(t<=1)return;let a=_objectsizeof2.default.call(void 0, e),n=T?t-T:0,s=i?a-i:0;if(n<=0&&s<=0){o(`No need to trim data for ${u}: size=${t} (limit=${T}), byteSize=${a.toLocaleString()} (limit=${i.toLocaleString()})`);return}o(`Need to trim ${u}: numToCut=${n}, bytesToCut=${s}`);let d={...e},b=!1,v=(g,$)=>{if(h.has(g)){o(`Cannot clean up ${g} as it is mounted`);return}let O=_objectsizeof2.default.call(void 0, g)+_objectsizeof2.default.call(void 0, d[g]);o(`Cleaning up unmounted${$?", expired":""} ${g} (byteSize=${O.toLocaleString()})`),n--,s-=O,delete d[g],b=!0},F=Object.entries(d).sort((g,$)=>g[1].lastUpdatedMs-$[1].lastUpdatedMs);for(let[g]of F){if(!C(d[g].lastUpdatedMs))break;v(g,!0)}if(n>0||s>0){b&&(F=Object.entries(d).sort((g,$)=>g[1].lastUpdatedMs-$[1].lastUpdatedMs));for(let[g]of F)if(v(g,!1),n<=0&&s<=0)break}if(!b){o(`No trimmable entries found for ${u}: size=${t} (limit=${T}), byteSize=${a.toLocaleString()} (limit=${i.toLocaleString()})`);return}f.setValue(d),o(`Trimmed data for ${u}: size=[${t} -> ${Object.keys(d).length}] (limit=${T}), byteSize=[${a.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, d).toLocaleString()}] (limit=${i.toLocaleString()})`)}function V(e,t,a=Date.now()){let n={lastUpdatedMs:Date.now(),loading:!1,data:t,dataUpdatedMs:a};f.setValue(s=>({...s,[e]:n})),k()}async function X(e,t,a){o(`Start fetching ${e}, queryType=${t}`);try{let n=await(t==="refetch"&&l?l(...a):m(...a));return o(`Successfully fetched ${e}`),V(e,n,Date.now()),n}catch(n){throw o(`Failed to fetch ${e} for queryType=${t}: ${n}`),n}finally{p.delete(e)}}function x(e,t,...a){let n=p.get(e);if(n)return o(`Deduplicating inflight fetch for ${e}, queryType=${t}`),n.promise;let s=X(e,t,a),d=new AbortController;return p.set(e,{promise:s,abortController:d}),s}let S={queryName:u,queryFn:m,refetchFn:l,expiryMs:D,staleMs:y,refetchOnStale:M,maxSize:T,maxBytes:i,keepLastNonEmptyData:c,log:o,queryState:f,getQueryKey(e){let t=_chunkTEZPF6BGmincjs.a.call(void 0, e);return t.length>30&&(t=_xxhashjs2.default.h32(t,39406).toString(16).slice(2)),u+":"+t},getAbortController(e){let t=S.getQueryKey(e);return S.getAbortControllerByKey(t)},getAbortControllerByKey(e){return _nullishCoalesce(_optionalChain([p, 'access', _10 => _10.get, 'call', _11 => _11(e), 'optionalAccess', _12 => _12.abortController]), () => (null))},getAbortSignal(e){let t=S.getQueryKey(e);return S.getAbortSignalByKey(t)},getAbortSignalByKey(e){return _nullishCoalesce(_optionalChain([S, 'access', _13 => _13.getAbortControllerByKey, 'call', _14 => _14(e), 'optionalAccess', _15 => _15.signal]), () => (null))},async getCachedOrFetch(...e){let t=Date.now();await f.readyPromise;let a=Date.now()-t,n=S.getQueryKey(e),s=_optionalChain([f, 'access', _16 => _16.getSnapshot, 'call', _17 => _17(), 'optionalAccess', _18 => _18[n]]);if(a&&o(`${n}: Waited for ${a}ms before data is ready`),_optionalChain([s, 'optionalAccess', _19 => _19.data])&&!C(_nullishCoalesce(s.dataUpdatedMs, () => (0))))return _(_nullishCoalesce(s.dataUpdatedMs, () => (0)))?(M&&(o(`refetchOnStale for ${n}`),x(n,"query",...e)),o(`Returning stale data for ${n}`),s):(o(`Return fresh data ${n} from cache without fetching`),s);let d=await x(n,"query",...e),b=Date.now();return{lastUpdatedMs:b,loading:!1,data:d,dataUpdatedMs:b}},getQueryValue(e){return _optionalChain([f, 'access', _20 => _20.getSnapshot, 'call', _21 => _21(), 'optionalAccess', _22 => _22[e]])},getData(e){let t=_optionalChain([f, 'access', _23 => _23.getSnapshot, 'call', _24 => _24(), 'optionalAccess', _25 => _25[e]]);if(_optionalChain([t, 'optionalAccess', _26 => _26.lastUpdatedMs])&&C(t.lastUpdatedMs)){S.deleteData(e);return}return _optionalChain([t, 'optionalAccess', _27 => _27.data])},setData:V,async updateFromSource(...e){let t=S.getQueryKey(e);return await x(t,"query",...e)},async refetch(...e){let t=S.getQueryKey(e);return await x(t,"refetch",...e)},deleteData(e){let a={...f.getSnapshot()};delete a[e],f.setValue(a);let n=p.get(e);n&&(p.delete(e),n.abortController.abort("Deleted"))},clear(){f.delete();for(let{abortController:e}of Array.from(p.values()))e.abort("Cleared");p.clear()},mount(e){h.set(e,(_nullishCoalesce(h.get(e), () => (0)))+1)},unmount(e){let t=h.get(e);t===1?h.delete(e):h.set(e,(_nullishCoalesce(t, () => (0)))-1)},enforceSizeLimit:k};return S}var K={lastUpdatedMs:0,loading:!0};function ue(r,...w){let u=_chunkF5L32IUCmincjs.a.call(void 0, w),[p,h]=_chunkNTFFK7ZHmincjs.d.call(void 0, r.queryState),m=_react.useRef.call(void 0, !0),l=_react.useMemo.call(void 0, ()=>r.getQueryKey(u),[r,u]),y=_nullishCoalesce(p[l], () => (K)),D=_react.useCallback.call(void 0, i=>{h(c=>{let o={...c};return o[l]=typeof i=="function"?i(_nullishCoalesce(o[l], () => (K))):i,o})},[l,h]),[M,A]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{r.keepLastNonEmptyData&&y.data!==void 0&&A(y.data)},[r.keepLastNonEmptyData,y.data]);let T=_react.useCallback.call(void 0, async i=>{if(r.log(`Begin executing shared query ${l}, isRefetch=${i}`),!!m.current){D(c=>({...c,lastUpdatedMs:Date.now(),loading:!0}));try{let c;if(i){let o=await r.refetch(...u),f=Date.now();c={lastUpdatedMs:f,loading:!1,data:o,dataUpdatedMs:f}}else c=await r.getCachedOrFetch(...u);if(!m.current)return;D({...c,loading:!1})}catch(c){if(!m.current)return;let o=Date.now();D(f=>({...f,lastUpdatedMs:o,loading:!1,error:c,errorUpdatedMs:o}))}}},[r,l,D,u]);return _react.useEffect.call(void 0, ()=>(m.current=!0,r.mount(l),T(!1),()=>{m.current=!1,r.unmount(l)}),[T,r,l]),_react.useMemo.call(void 0, ()=>({...y,data:y.data!==void 0?y.data:M,latestData:y.data,abortCurrentQuery:i=>{let c=r.getAbortControllerByKey(l);return _optionalChain([c, 'optionalAccess', _28 => _28.abort, 'call', _29 => _29(i)]),!!c},refetch:()=>T(!0),setData:(i,c)=>{r.setData(l,i,c)},deleteData:()=>{r.deleteData(l)}}),[T,M,r,l,y])}exports.SharedQueryConfig = Q; exports.configureSharedQuery = se; exports.sharedQuery = ie; exports.useSharedQuery = ue;
2
2
  //# sourceMappingURL=sharedQuery.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sharedQuery.ts","../src/sharedState.ts","../src/storage.ts","../src/stringify.ts","../src/useDeepMemo.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Think of shared queries as like the open source npm package \"react-query\",\n * but with strong type-checking and built-in support for persistence.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n * import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, userId);\n *\n * // You can check for user.loading and user.error if needed.\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { sharedState, SharedStateOptions, useSharedState } from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Return the last non-empty data if you want to display the last loaded data\n * while waiting for the new data to load.\n */\n lastNonEmptyData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => Promise<void>;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /**\n * Function to fetch data.\n */\n queryFn: QueryFn<TArgs, TData>;\n\n /**\n * Function to re-fetch data. Usually this would just be the `queryFn`, but\n * if you need a different behavior for refetching, then specify this.\n */\n refetchFn?: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * MS_PER_DAY,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Whether this is a normal query or an explicit refetch. */\ntype QueryType = \"query\" | \"refetch\";\n\n// Disallow duplicate query names.\nconst seenQueryNames = new Set<string>();\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is mainly used for logging and also\n * used as the storage key when you use the top-level `persistTo`.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n) {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query name \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n const inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n const mountedKeys = new Map<string, number>();\n\n const queryName = options.queryName;\n const queryFn = options.queryFn;\n const refetchFn = options.refetchFn;\n\n const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n const refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n const store = options.store;\n\n if (store) {\n // Wrap the isValid to account for the query state wrapper.\n if (\"persistTo\" in store && store.isValid) {\n const isValid = store.isValid;\n\n options = {\n ...options,\n store: {\n ...store,\n isValid: (u) => {\n // Supposed type of u: SharedQueryState<TData>\n if (!u || typeof u !== \"object\") {\n return false;\n }\n\n // Since each stored key could contain multiple values, and isValid\n // checks for each value, we need to check every value to make sure\n // they are valid.\n // Supposed type of v: QueryStateValue<TData>\n for (const v of Object.values(u)) {\n if (\n !v ||\n typeof v !== \"object\" ||\n !(\"data\" in v) ||\n !(\"dataUpdatedMs\" in v) ||\n !(\"lastUpdatedMs\" in v) ||\n typeof v.dataUpdatedMs !== \"number\" ||\n typeof v.lastUpdatedMs !== \"number\" ||\n !isValid(v.data)\n ) {\n return false;\n }\n }\n\n return true;\n },\n },\n };\n }\n } else {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options = {\n ...options,\n store: {\n persistTo,\n key: queryName,\n expiryMs,\n },\n };\n }\n }\n\n const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n const log = options?.log ?? SharedQueryConfig.log;\n\n const queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n\n function isStale(dataUpdatedMs: number): boolean {\n if (staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > staleMs;\n }\n\n function isExpired(dataUpdatedMs: number): boolean {\n if (expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > expiryMs;\n }\n\n function enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!maxSize && !maxBytes) {\n return;\n }\n\n const oldState = queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = maxSize ? oldSize - maxSize : 0;\n let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n log(\n `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n log(\n `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (mountedKeys.has(key)) {\n log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n log(\n `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n log(\n `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`,\n );\n }\n\n function setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n enforceSizeLimit();\n }\n\n async function startFetching(\n queryKey: string,\n queryType: QueryType,\n args: TArgs,\n ) {\n log(`Start fetching ${queryKey}, queryType=${queryType}`);\n\n try {\n const data = await (queryType === \"refetch\" && refetchFn\n ? refetchFn(...args)\n : queryFn(...args));\n\n log(`Successfully fetched ${queryKey}`);\n setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);\n throw e;\n } finally {\n inflightQueries.delete(queryKey);\n }\n }\n\n function dedupedFetch(\n queryKey: string,\n queryType: QueryType,\n ...args: TArgs\n ): Promise<TData> {\n const inflightQuery = inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests. Note that queries and refetches are\n // also deduped because they should technically be trying to fetch the same\n // data.\n if (inflightQuery) {\n log(\n `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`,\n );\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = startFetching(queryKey, queryType, args);\n const abortController = new AbortController();\n\n inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n const obj = {\n queryName,\n queryFn,\n refetchFn,\n expiryMs,\n staleMs,\n refetchOnStale,\n maxSize,\n maxBytes,\n keepLastNonEmptyData,\n log,\n queryState,\n\n /** Returns a key to identify requests based on the given args. */\n getQueryKey(args: TArgs): string {\n return queryName + \":\" + stringifyDeterministicForKeys(args);\n },\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n getAbortController(args: TArgs): AbortController | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortControllerByKey(queryKey);\n },\n\n getAbortControllerByKey(queryKey: string): AbortController | null {\n return inflightQueries.get(queryKey)?.abortController ?? null;\n },\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n */\n getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortSignalByKey(queryKey);\n },\n\n getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return obj.getAbortControllerByKey(queryKey)?.signal ?? null;\n },\n\n /** For cached data, we need to return the correct timestamps as well. */\n async getCachedOrFetch(...args: TArgs): Promise<QueryStateValue<TData>> {\n // Important: wait for data to be loaded from cache first before trying to\n // fetch from server. This fixes a bad bug where the data is big, and the\n // code here starts a server fetch before the cache data loaded.\n const startMs = Date.now();\n await queryState.readyPromise;\n const waitedMs = Date.now() - startMs;\n\n const queryKey = obj.getQueryKey(args);\n const cached = queryState.getSnapshot()?.[queryKey];\n\n if (waitedMs) {\n log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);\n }\n\n if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!isStale(cached.dataUpdatedMs ?? 0)) {\n log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached;\n }\n\n // If stale, optionally update the data in the background.\n if (refetchOnStale) {\n log(`refetchOnStale for ${queryKey}`);\n void dedupedFetch(queryKey, \"query\", ...args);\n }\n\n // Still return stale data immediately.\n log(`Returning stale data for ${queryKey}`);\n return cached;\n }\n\n const data = await dedupedFetch(queryKey, \"query\", ...args);\n const now = Date.now();\n\n return {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n },\n\n /** Get the entire stored entry for a query key. */\n getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return queryState.getSnapshot()?.[queryKey];\n },\n\n /** Get the current stored data for a query key. */\n getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (isExpired(stateValue.lastUpdatedMs)) {\n obj.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n },\n\n /** Set the data directly if the user obtained it from somewhere else. */\n setData,\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n async updateFromSource(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"query\", ...args);\n },\n\n /**\n * Perform an explicit refetch. If `options.refetchFn` was not specified,\n * then this would be identical to calling `obj.updateFromSource()`.\n */\n async refetch(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"refetch\", ...args);\n },\n\n /** Delete the cached data for one set of arguments. */\n deleteData(queryKey: string): void {\n const record = queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n queryState.setValue(clone);\n\n const inflight = inflightQueries.get(queryKey);\n if (inflight) {\n inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n },\n\n /** Delete all currently cached data & all inflight promises. */\n clear(): void {\n queryState.delete();\n\n for (const { abortController } of Array.from(inflightQueries.values())) {\n abortController.abort(\"Cleared\");\n }\n\n inflightQueries.clear();\n },\n\n /** Keep track of mounted keys. */\n mount(queryKey: string): void {\n mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);\n },\n\n /** Clean up mounted keys. */\n unmount(queryKey: string): void {\n const count = mountedKeys.get(queryKey);\n if (count === 1) {\n mountedKeys.delete(queryKey);\n } else {\n mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n },\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n enforceSizeLimit,\n } as const;\n\n return obj;\n}\n\nexport type SharedQuery<TArgs extends unknown[], TData> = ReturnType<\n typeof sharedQuery<TArgs, TData>\n>;\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (isRefetch: boolean) => {\n query.log(\n `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`,\n );\n\n if (!isMounted.current) return;\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n let state: QueryStateValue<TData>;\n\n if (isRefetch) {\n const data = await query.refetch(...stableArgs);\n const now = Date.now();\n\n state = {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n } else {\n state = await query.getCachedOrFetch(...stableArgs);\n }\n\n if (!isMounted.current) return;\n\n // Make sure to reset loading to false.\n setQueryStateValue({ ...state, loading: false });\n } catch (e) {\n if (!isMounted.current) return;\n\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [execute, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n lastNonEmptyData,\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown): boolean => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: (): Promise<void> => {\n return execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number): void => {\n query.setData(queryKey, data, dataUpdatedMs);\n },\n deleteData: (): void => {\n query.deleteData(queryKey);\n },\n } satisfies UseQueryResult<TData>;\n }, [execute, lastNonEmptyData, query, queryKey, queryStateValue]);\n}\n","/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\nconst pubSubStore = createPubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n const pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n const obj = {\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n lazy,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n async setInStore(value: T): Promise<void> {\n return await storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n async getFromStore(): Promise<T | undefined> {\n return await storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(pubSubKey, next);\n void obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete() {\n pubSubStore.set(pubSubKey, defaultValue);\n void storageAdapter?.set(STORAGE_KEY, defaultValue);\n },\n\n /** Initial default handling. */\n async initDefaultValueOnce() {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n const stored = await obj.getFromStore();\n const value = stored !== undefined ? stored : defaultValue;\n\n pubSubStore.set(pubSubKey, value);\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n },\n } as const;\n\n if (!lazy) {\n void obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n","/**\n * @packageDocumentation\n *\n * Backing storage implementation for the shared state. Note that this uses the\n * LocalStore and KvStore from package \"@choksheak/ts-utils\", but is customized\n * to be used for shared states.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\nimport { Duration } from \"@choksheak/ts-utils/duration\";\nimport { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { createLocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\n/** Options to configure a pre-built store adapter. */\nexport type StoreOptions = {\n /** Choose which pre-built store adapter to use. */\n persistTo: PersistTo;\n\n /** Storage key to act as a namespace to store the data. */\n key: string;\n\n /** How long to wait before the value is considered expired. */\n expiryMs?: number | Duration;\n\n /** Returns true if the given value supposed to be of type T is valid. */\n isValid?: (u: unknown) => boolean;\n};\n\nexport type StoreConstructorArgs = Omit<StoreOptions, \"persistTo\">;\n\n/** Either use a pre-built store, or a custom one you provide. */\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\n// In SSR (Server-Side Rendering) mode, we never want to use our storage\n// adapters for anything.\nconst IS_NOT_BROWSER = typeof window === \"undefined\";\n\n/**\n * Convert a StorageOptions<T> config object into an actual storage adapter, or\n * returns null if a storage adapter is not configured.\n */\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n const config = { ...store, expiryMs };\n\n switch (store.persistTo) {\n case \"localStorage\":\n return localStoreAdapter<T>(config);\n\n case \"indexedDb\":\n return kvStoreAdapter<T>(config);\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n\n/**\n * Create a new SSR-safe local store adapter, which allows users to reuse the\n * same adapter in multiple shared states or shared queries.\n */\nexport function localStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n const adapter = createLocalStore(key, { defaultExpiryMs: expiryMs });\n\n return {\n set: (key: string, value: T): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(key, value);\n },\n\n get: (key: string): T | undefined => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const value = adapter.get<T>(key);\n\n if (isValid && !isValid(value)) {\n console.warn(\n `localStorage adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`,\n );\n adapter.delete(key);\n return undefined;\n }\n\n return value;\n },\n\n delete: (key: string): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.delete(key);\n },\n\n clear: (): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.clear();\n },\n };\n}\n\n/**\n * Create a new SSR-safe indexed DB KV store adapter, which allows users to\n * reuse the same adapter in multiple shared states or shared queries.\n */\nexport function kvStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = await kvStore.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `indexedDb adapter: Auto-discard invalid value for ${key}:`,\n value,\n );\n await kvStore.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n delete: async (key: string): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.clear();\n },\n };\n}\n","/**\n * @packageDocumentation\n *\n * Implements special stringify for use in the shared queries. This will likely\n * not be reusable for your own use cases.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\n/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","/**\n * @packageDocumentation\n *\n * Provides a memoized value in React where the value is checked for deep\n * equality. If the value has changed, but is deeply equal to the previous\n * value, then useDeepMemo will return the same reference to the previous\n * value and ignore the latest value.\n *\n * This is mainly used in shared queries to check for changes in the query\n * arguments, but it might be useful for your own use cases.\n */\n\nimport isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/**\n * Provides a stable value for T based on deep equality. The deep equality is\n * determined by the `isEqual()` function in lodash.\n */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"skBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,uBAAAE,EAAA,yBAAAC,GAAA,gBAAAC,GAAA,mBAAAC,KAAA,eAAAC,GAAAN,IAqFA,IAAAO,GAA2B,6CAC3BC,EAAwB,4BACxBC,EAOO,iBCtCP,IAAAC,EAA2B,6CAC3BC,EAA+D,iBC7C/D,IAAAC,EAAwB,uCACxBC,EAAiC,0CAkC3BC,EAAiB,OAAO,OAAW,IAMlC,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAC7BG,EAAS,CAAE,GAAGF,EAAO,SAAAC,CAAS,EAEpC,OAAQD,EAAM,UAAW,CACvB,IAAK,eACH,OAAOG,GAAqBD,CAAM,EAEpC,IA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EAAaf,EAAM,wBAAwBvB,CAAQ,EACzD,OAAAsC,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,QAAS,IACAJ,EAAQ,EAAI,EAErB,QAAS,CAACjC,EAAapB,IAAiC,CACtD0C,EAAM,QAAQvB,EAAUC,EAAMpB,CAAa,CAC7C,EACA,WAAY,IAAY,CACtB0C,EAAM,WAAWvB,CAAQ,CAC3B,CACF,GACC,CAACkC,EAASF,EAAkBT,EAAOvB,EAAU6B,CAAe,CAAC,CAClE","names":["sharedQuery_exports","__export","SharedQueryConfig","configureSharedQuery","sharedQuery","useSharedQuery","__toCommonJS","import_timeConstants","import_object_sizeof","import_react","import_timeConstants","import_react","import_kvStore","import_localStore","IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","config","localStoreAdapter","kvStoreAdapter","key","isValid","adapter","value","keyPrefix","fullKey","SharedStateConfig","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","pubSubStore","STORAGE_KEY","stateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","pubSubKey","storageAdapter","getStorageAdapter","SharedStateConfig","lazyLoad","lazy","obj","stored","useSharedState","state","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","import_isEqual","import_react","useDeepMemo","value","state","setState","isEqual","SharedQueryConfig","args","configureSharedQuery","config","seenQueryNames","sharedQuery","options","inflightQueries","mountedKeys","queryName","queryFn","refetchFn","staleMs","expiryMs","refetchOnStale","store","isValid","u","v","persistTo","maxSize","maxBytes","keepLastNonEmptyData","log","queryState","sharedState","isStale","dataUpdatedMs","isExpired","enforceSizeLimit","oldState","oldSize","oldByteSize","getByteSize","numToCut","bytesToCut","newState","needUpdate","deleteKeyIfNotMounted","key","expired","byteSize","entriesByTimeAscending","entry1","entry2","setData","queryKey","data","entry","prev","startFetching","queryType","e","dedupedFetch","inflightQuery","promise","abortController","obj","stringifyDeterministicForKeys","startMs","waitedMs","cached","now","stateValue","clone","inflight","count","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","setQueryState","useSharedState","isMounted","queryStateValue","setQueryStateValue","next","lastNonEmptyData","setLastNonEmptyData","execute","isRefetch","state","reason","controller"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/sharedQuery.min.cjs","../src/sharedQuery.ts"],"names":["init_stringify","SharedQueryConfig","args","configureSharedQuery","config","seenQueryNames","sharedQuery","options","url","queryName","inflightQueries","mountedKeys","queryFn","params","firstArg","entries","k","v","item","fetcher","refetchFn","staleMs","expiryMs","refetchOnStale","store","isValid","u","persistTo","maxSize","maxBytes","keepLastNonEmptyData","log","queryState","sharedState","isStale","dataUpdatedMs","isExpired","enforceSizeLimit","oldState","oldSize","oldByteSize","getByteSize","numToCut","bytesToCut"],"mappings":"AAAA,g1BAA4C,+DAAoD,oCAAiC,+DAAoD,+DAA6C,oCAAiC,yGCqF3O,8BAQjB,wFACS,oCAKhBA,CAAAA,CA4KO,IAAMC,CAAAA,CAAoB,CAE/B,OAAA,CAAS,CAAA,CAGT,QAAA,CAAU,EAAA,CAAK,KAAA,CAGf,cAAA,CAAgB,CAAA,CAAA,CAGhB,SAAA,CAAW,KAAA,CAAA,CAGX,OAAA,CAAS,GAAA,CAGT,QAAA,CAAU,GAAA,CAGV,GAAA,CAAK,CAAA,GAAIC,CAAAA,CAAAA,EAAoB,OAAA,CAAQ,GAAA,CAAI,eAAA,CAAiB,GAAGA,CAAI,CACnE,CAAA,CAKO,SAASC,EAAAA,CAAqBC,CAAAA,CAAoC,CACvE,MAAA,CAAO,MAAA,CAAOH,CAAAA,CAAmBG,CAAM,CACzC,CAMA,IAAMC,CAAAA,CAAiB,IAAI,GAAA,CAoBpB,SAASC,EAAAA,CAGdC,CAAAA,CACA,CAEA,IAAMC,CAAAA,CAAOD,CAAAA,CAA+B,GAAA,EAAO,EAAA,CAC7CE,CAAAA,CAAYF,CAAAA,CAAQ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AA,GAAa,CAAA,CAAU,CAAA,CAAA,CAEb,IAAA,CAAK,GAAA,CAAI,CAAA,CAAIa,CAAAA,CACZb,CACjB,CAEA,SAASe,CAAAA,CAAAA,CAAyB,CAEhC,EAAA,CAAI,CAACT,CAAAA,EAAW,CAACC,CAAAA,CACf,MAAA,CAGF,IAAMS,CAAAA,CAAWN,CAAAA,CAAW,WAAA,CAAY,CAAA,CAClCO,CAAAA,CAAU,MAAA,CAAO,IAAA,CAAKD,CAAQ,CAAA,CAAE,MAAA,CAGtC,EAAA,CAAIC,CAAAA,EAAW,CAAA,CACb,MAAA,CAGF,IAAMC,CAAAA,CAAcC,oCAAAA,CAAoB,CAAA,CAEpCC,CAAAA,CAAWd,CAAAA,CAAUW,CAAAA,CAAUX,CAAAA,CAAU,CAAA,CACzCe,CAAAA,CAAad,CAAAA,CAAWW,CAAAA,CAAcX,CAAAA,CAAW,CAAA,CAGrD,EAAA,CAAIa,CAAAA,EAAY,CAAA,EAAKC,CAAAA,EAAc,CAAA,CAAG,CACpCZ,CAAAA,CACE,CAAA,yBAAA,EAA4BtB,CAAS,CAAA,OAAA,EAAU8B,CAAO,CAAA,QAAA,EAAWX,CAAO,CAAA,YAAA,EAAeY,CAAAA,CAAY,cAAA,CAAe,CAAC,CAAA,QAAA,EAAWX,CAAAA,CAAS,cAAA,CAAe,CAAC,CAAA,CAAA,CACzJ,CAAA,CACA,MACF,CAGAE,CAAAA,CACE,CAAA,aAAA,EAAgBtB,CAAS,CAAA,WAAA,EAAciC,CAAQ,CAAA,aAAA,EAAgBC,CAAU,CAAA,CAAA","file":"/Users/choksheaklau/src/react-utils/dist/sharedQuery.min.cjs","sourcesContent":[null,"/**\n * @packageDocumentation\n *\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Think of shared queries as like the open source npm package \"react-query\",\n * but with strong type-checking and built-in support for persistence.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n * import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, userId);\n *\n * // You can check for user.loading and user.error if needed.\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport XXH from \"xxhashjs\";\n\nimport { fetcher } from \"./fetcher\";\nimport { sharedState, SharedStateOptions, useSharedState } from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Usually same as `data`, but if you specify `keepLastNonEmptyData: true`,\n * then this will contain the latest data (undefined when args just changed)\n * and data will contain the last non empty data.\n */\n latestData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => Promise<void>;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\nexport type QueryTargetWithFn<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /** Function to fetch data. */\n queryFn: QueryFn<TArgs, TData>;\n};\n\nexport type QueryTargetWithUrl = {\n /**\n * The queryName can optionally be specified, else we will fallback to use\n * the url as the queryName.\n */\n queryName?: string;\n\n /**\n * URL to fetch data using HTTP GET. Note that using this field will cause\n * both TArgs and TData to be undefined (unknown). Therefore you can make up\n * for this by specifying types with useSharedQuery, like this:\n * ```\n * const usersQuery = useSharedQuery<[{ userId?: string[] }], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n *\n * If `userId` were specified as [\"u1\", \"u2\"], the query url would be\n * \"/api/list-users?userId=u1&userId=u2\".\n *\n * You can also pass the params as a string like \"userId=u1&userId=u2\".\n * ```\n * const usersQuery = useSharedQuery<[string], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n */\n url: string;\n};\n\n/** Specifies how to fetch the data. */\nexport type QueryTarget<TArgs extends unknown[], TData> =\n | QueryTargetWithFn<TArgs, TData>\n | QueryTargetWithUrl;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = QueryTarget<\n TArgs,\n TData\n> & {\n /**\n * Function to re-fetch data. Usually this would just be the `queryFn`, but\n * if you need a different behavior for refetching, then specify this.\n */\n refetchFn?: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * 86_400_000 /* MS_PER_DAY */,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Whether this is a normal query or an explicit refetch. */\ntype QueryType = \"query\" | \"refetch\";\n\n// Disallow duplicate query names.\nconst seenQueryNames = new Set<string>();\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is mainly used for logging and also\n * used as the storage key when you use the top-level `persistTo`.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n) {\n // If queryName is not specified, fallback to use url as the queryName.\n const url = (options as QueryTargetWithUrl).url || \"\";\n const queryName = options.queryName || url;\n\n if (!queryName) {\n throw new Error(`Either queryName or url must be specified.`);\n }\n\n if (seenQueryNames.has(queryName)) {\n throw new Error(`Duplicate shared query name \"${queryName}\"`);\n }\n seenQueryNames.add(queryName);\n\n const inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n const mountedKeys = new Map<string, number>();\n\n let queryFn: QueryFn<TArgs, TData>;\n\n if ((options as QueryTargetWithFn<TArgs, TData>).queryFn) {\n queryFn = (options as QueryTargetWithFn<TArgs, TData>).queryFn;\n } else if (url) {\n // Auto-generate the queryFn as a HTTP GET request using the url.\n queryFn = (...args: TArgs): Promise<TData> => {\n // If args are given, treat the first argument as a search param.\n let params = \"\";\n const firstArg = args?.[0];\n\n if (firstArg) {\n if (typeof firstArg === \"string\") {\n params = firstArg;\n } else if (typeof firstArg === \"object\") {\n const entries: [string, string][] = [];\n\n for (const [k, v] of Object.entries(firstArg)) {\n if (v === undefined) continue;\n\n // Allow the same param to be specified multiple times.\n if (Array.isArray(v)) {\n for (const item of v) {\n if (item === undefined) continue;\n\n // The field values can only be primitives, not objects.\n entries.push([k, String(item)]);\n }\n } else {\n // The field values can only be primitives, not objects.\n entries.push([k, String(v)]);\n }\n }\n\n params = new URLSearchParams(entries).toString();\n }\n\n if (params) {\n if (url.includes(\"?\")) {\n // Append more search params to existing ones.\n params = \"&\" + params;\n } else {\n // Set the full search params string.\n params = \"?\" + params;\n }\n }\n }\n\n return fetcher\n .url(url + params)\n .get()\n .json();\n };\n } else {\n throw new Error(`Either queryFn or url must be specified`);\n }\n\n const refetchFn = options.refetchFn;\n\n const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n const refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n const store = options.store;\n\n if (store) {\n // Wrap the isValid to account for the query state wrapper.\n if (\"persistTo\" in store && store.isValid) {\n const isValid = store.isValid;\n\n options = {\n ...options,\n store: {\n ...store,\n isValid: (u) => {\n // Supposed type of u: SharedQueryState<TData>\n if (!u || typeof u !== \"object\") {\n return false;\n }\n\n // Since each stored key could contain multiple values, and isValid\n // checks for each value, we need to check every value to make sure\n // they are valid.\n // Supposed type of v: QueryStateValue<TData>\n for (const v of Object.values(u)) {\n if (\n !v ||\n typeof v !== \"object\" ||\n !(\"data\" in v) ||\n !(\"dataUpdatedMs\" in v) ||\n !(\"lastUpdatedMs\" in v) ||\n typeof v.dataUpdatedMs !== \"number\" ||\n typeof v.lastUpdatedMs !== \"number\" ||\n !isValid(v.data)\n ) {\n return false;\n }\n }\n\n return true;\n },\n },\n };\n }\n } else {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options = {\n ...options,\n store: {\n persistTo,\n key: queryName,\n expiryMs,\n },\n };\n }\n }\n\n const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n const log = options?.log ?? SharedQueryConfig.log;\n\n const queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n\n function isStale(dataUpdatedMs: number): boolean {\n if (staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > staleMs;\n }\n\n function isExpired(dataUpdatedMs: number): boolean {\n if (expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > expiryMs;\n }\n\n function enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!maxSize && !maxBytes) {\n return;\n }\n\n const oldState = queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = maxSize ? oldSize - maxSize : 0;\n let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n log(\n `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n log(\n `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (mountedKeys.has(key)) {\n log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n log(\n `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n log(\n `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`,\n );\n }\n\n function setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n enforceSizeLimit();\n }\n\n async function startFetching(\n queryKey: string,\n queryType: QueryType,\n args: TArgs,\n ) {\n log(`Start fetching ${queryKey}, queryType=${queryType}`);\n\n try {\n const data = await (queryType === \"refetch\" && refetchFn\n ? refetchFn(...args)\n : queryFn(...args));\n\n log(`Successfully fetched ${queryKey}`);\n setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);\n throw e;\n } finally {\n inflightQueries.delete(queryKey);\n }\n }\n\n function dedupedFetch(\n queryKey: string,\n queryType: QueryType,\n ...args: TArgs\n ): Promise<TData> {\n const inflightQuery = inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests. Note that queries and refetches are\n // also deduped because they should technically be trying to fetch the same\n // data.\n if (inflightQuery) {\n log(\n `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`,\n );\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = startFetching(queryKey, queryType, args);\n const abortController = new AbortController();\n\n inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n const obj = {\n queryName,\n queryFn,\n refetchFn,\n expiryMs,\n staleMs,\n refetchOnStale,\n maxSize,\n maxBytes,\n keepLastNonEmptyData,\n log,\n queryState,\n\n /** Returns a key to identify requests based on the given args. */\n getQueryKey(args: TArgs): string {\n let s = stringifyDeterministicForKeys(args);\n\n // Ensure the query key is not too long.\n if (s.length > 30) {\n s = XXH.h32(s, 0x99ee).toString(16).slice(2); // remove \"0x\"\n }\n\n return queryName + \":\" + s;\n },\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n getAbortController(args: TArgs): AbortController | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortControllerByKey(queryKey);\n },\n\n getAbortControllerByKey(queryKey: string): AbortController | null {\n return inflightQueries.get(queryKey)?.abortController ?? null;\n },\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example using fetch:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n *\n * Example using `fetcher.ts`:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * return fetcher.url(`/users/${userId}`).options({ signal }).get().json();\n * },\n * });\n * ```\n */\n getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortSignalByKey(queryKey);\n },\n\n getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return obj.getAbortControllerByKey(queryKey)?.signal ?? null;\n },\n\n /** For cached data, we need to return the correct timestamps as well. */\n async getCachedOrFetch(...args: TArgs): Promise<QueryStateValue<TData>> {\n // Important: wait for data to be loaded from cache first before trying to\n // fetch from server. This fixes a bad bug where the data is big, and the\n // code here starts a server fetch before the cache data loaded.\n const startMs = Date.now();\n await queryState.readyPromise;\n const waitedMs = Date.now() - startMs;\n\n const queryKey = obj.getQueryKey(args);\n const cached = queryState.getSnapshot()?.[queryKey];\n\n if (waitedMs) {\n log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);\n }\n\n if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!isStale(cached.dataUpdatedMs ?? 0)) {\n log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached;\n }\n\n // If stale, optionally update the data in the background.\n if (refetchOnStale) {\n log(`refetchOnStale for ${queryKey}`);\n void dedupedFetch(queryKey, \"query\", ...args);\n }\n\n // Still return stale data immediately.\n log(`Returning stale data for ${queryKey}`);\n return cached;\n }\n\n const data = await dedupedFetch(queryKey, \"query\", ...args);\n const now = Date.now();\n\n return {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n },\n\n /** Get the entire stored entry for a query key. */\n getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return queryState.getSnapshot()?.[queryKey];\n },\n\n /** Get the current stored data for a query key. */\n getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (isExpired(stateValue.lastUpdatedMs)) {\n obj.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n },\n\n /** Set the data directly if the user obtained it from somewhere else. */\n setData,\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n async updateFromSource(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"query\", ...args);\n },\n\n /**\n * Perform an explicit refetch. If `options.refetchFn` was not specified,\n * then this would be identical to calling `obj.updateFromSource()`.\n */\n async refetch(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"refetch\", ...args);\n },\n\n /** Delete the cached data for one set of arguments. */\n deleteData(queryKey: string): void {\n const record = queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n queryState.setValue(clone);\n\n const inflight = inflightQueries.get(queryKey);\n if (inflight) {\n inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n },\n\n /** Delete all currently cached data & all inflight promises. */\n clear(): void {\n queryState.delete();\n\n for (const { abortController } of Array.from(inflightQueries.values())) {\n abortController.abort(\"Cleared\");\n }\n\n inflightQueries.clear();\n },\n\n /** Keep track of mounted keys. */\n mount(queryKey: string): void {\n mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);\n },\n\n /** Clean up mounted keys. */\n unmount(queryKey: string): void {\n const count = mountedKeys.get(queryKey);\n if (count === 1) {\n mountedKeys.delete(queryKey);\n } else {\n mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n },\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n enforceSizeLimit,\n } as const;\n\n return obj;\n}\n\nexport type SharedQuery<TArgs extends unknown[], TData> = ReturnType<\n typeof sharedQuery<TArgs, TData>\n>;\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (isRefetch: boolean) => {\n query.log(\n `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`,\n );\n\n if (!isMounted.current) return;\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n let state: QueryStateValue<TData>;\n\n if (isRefetch) {\n const data = await query.refetch(...stableArgs);\n const now = Date.now();\n\n state = {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n } else {\n state = await query.getCachedOrFetch(...stableArgs);\n }\n\n if (!isMounted.current) return;\n\n // Make sure to reset loading to false.\n setQueryStateValue({ ...state, loading: false });\n } catch (e) {\n if (!isMounted.current) return;\n\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [execute, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n\n // Fill with lastNonEmptyData when data is undefined.\n data:\n queryStateValue.data !== undefined\n ? queryStateValue.data\n : lastNonEmptyData,\n latestData: queryStateValue.data,\n\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown): boolean => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: (): Promise<void> => {\n return execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number): void => {\n query.setData(queryKey, data, dataUpdatedMs);\n },\n deleteData: (): void => {\n query.deleteData(queryKey);\n },\n } satisfies UseQueryResult<TData>;\n }, [execute, lastNonEmptyData, query, queryKey, queryStateValue]);\n}\n"]}