@choksheak/react-utils 0.4.1 → 0.4.2

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 (95) hide show
  1. package/NoSSR.cjs +1 -1
  2. package/NoSSR.d.ts +7 -3
  3. package/NoSSR.min.cjs +1 -1
  4. package/NoSSR.min.mjs +1 -1
  5. package/NoSSR.mjs +1 -1
  6. package/{chunk-33UMQLKY.mjs → chunk-4235I4VO.mjs} +1 -10
  7. package/{chunk-GPV6JIQK.mjs → chunk-4J7TN5JN.mjs} +1 -1
  8. package/chunk-BBCGQMWI.min.cjs +2 -0
  9. package/chunk-BBCGQMWI.min.cjs.map +1 -0
  10. package/{chunk-5DO7KC3L.cjs → chunk-CYTO5EZE.cjs} +2 -11
  11. package/chunk-GKNOICX3.cjs +561 -0
  12. package/chunk-HRE7YPUJ.min.mjs +2 -0
  13. package/chunk-IS3BZTWE.cjs +35 -0
  14. package/chunk-JOHZV3FD.min.cjs +2 -0
  15. package/{chunk-F5L32IUC.min.cjs.map → chunk-JOHZV3FD.min.cjs.map} +1 -1
  16. package/chunk-KGN4HQPP.min.cjs +2 -0
  17. package/chunk-KGN4HQPP.min.cjs.map +1 -0
  18. package/chunk-NL4FU2MJ.min.mjs +2 -0
  19. package/chunk-NL4FU2MJ.min.mjs.map +1 -0
  20. package/chunk-R7POPVJR.mjs +35 -0
  21. package/chunk-TI3FMEYP.min.mjs +2 -0
  22. package/{chunk-RM4ZGGZ2.min.mjs.map → chunk-TI3FMEYP.min.mjs.map} +1 -1
  23. package/chunk-U7RD7B3N.min.mjs +2 -0
  24. package/chunk-U7RD7B3N.min.mjs.map +1 -0
  25. package/{chunk-WVLPJPWG.cjs → chunk-WXLUEDBO.cjs} +3 -3
  26. package/chunk-X6EKF4N7.mjs +561 -0
  27. package/chunk-ZCDXPV3A.min.cjs +2 -0
  28. package/chunk-ZCDXPV3A.min.cjs.map +1 -0
  29. package/dist-O6NNX4Y3.min.mjs +2 -0
  30. package/dist-O6NNX4Y3.min.mjs.map +1 -0
  31. package/dist-SEGTJ72R.min.cjs +2 -0
  32. package/dist-SEGTJ72R.min.cjs.map +1 -0
  33. package/dist-UKP7SPWZ.cjs +545 -0
  34. package/dist-YXYQDOH5.mjs +545 -0
  35. package/index.cjs +43 -0
  36. package/index.d.cts +8 -0
  37. package/index.d.ts +8 -0
  38. package/index.min.cjs +2 -0
  39. package/index.min.cjs.map +1 -0
  40. package/index.min.mjs +2 -0
  41. package/index.min.mjs.map +1 -0
  42. package/index.mjs +43 -0
  43. package/magic-string.es-5QZEPJXJ.min.mjs +14 -0
  44. package/magic-string.es-5QZEPJXJ.min.mjs.map +1 -0
  45. package/magic-string.es-EREYSDLL.mjs +1308 -0
  46. package/magic-string.es-FXUUD55Y.min.cjs +14 -0
  47. package/magic-string.es-FXUUD55Y.min.cjs.map +1 -0
  48. package/magic-string.es-HC5PDAU3.cjs +1308 -0
  49. package/package.json +71 -168
  50. package/sharedQuery.cjs +8 -555
  51. package/{sharedQuery.d.mts → sharedQuery.d.cts} +2 -2
  52. package/sharedQuery.d.ts +23 -17
  53. package/sharedQuery.min.cjs +1 -1
  54. package/sharedQuery.min.cjs.map +1 -1
  55. package/sharedQuery.min.mjs +1 -1
  56. package/sharedQuery.min.mjs.map +1 -1
  57. package/sharedQuery.mjs +9 -556
  58. package/sharedState.cjs +1 -1
  59. package/{sharedState.d.mts → sharedState.d.cts} +1 -1
  60. package/sharedState.d.ts +17 -11
  61. package/sharedState.min.cjs +1 -1
  62. package/sharedState.min.mjs +1 -1
  63. package/sharedState.mjs +1 -1
  64. package/storage.cjs +1 -1
  65. package/storage.d.ts +13 -9
  66. package/storage.min.cjs +1 -1
  67. package/storage.min.mjs +1 -1
  68. package/storage.mjs +1 -1
  69. package/stringify.cjs +3 -5
  70. package/stringify.d.ts +3 -1
  71. package/stringify.min.cjs +1 -1
  72. package/stringify.min.cjs.map +1 -1
  73. package/stringify.min.mjs +1 -1
  74. package/stringify.mjs +2 -4
  75. package/useDeepMemo.cjs +3 -3
  76. package/useDeepMemo.d.ts +3 -1
  77. package/useDeepMemo.min.cjs +1 -1
  78. package/useDeepMemo.min.mjs +1 -1
  79. package/useDeepMemo.mjs +2 -2
  80. package/chunk-74BS2FAO.cjs +0 -12
  81. package/chunk-F5L32IUC.min.cjs +0 -2
  82. package/chunk-KE3RXVMS.min.cjs +0 -2
  83. package/chunk-KE3RXVMS.min.cjs.map +0 -1
  84. package/chunk-MWDH7YON.min.mjs +0 -2
  85. package/chunk-RM4ZGGZ2.min.mjs +0 -2
  86. package/chunk-TEZPF6BG.min.cjs +0 -2
  87. package/chunk-TEZPF6BG.min.cjs.map +0 -1
  88. package/chunk-V7L3UICC.min.mjs +0 -2
  89. package/chunk-V7L3UICC.min.mjs.map +0 -1
  90. package/chunk-X6BYQHVC.mjs +0 -12
  91. /package/{NoSSR.d.mts → NoSSR.d.cts} +0 -0
  92. /package/{chunk-MWDH7YON.min.mjs.map → chunk-HRE7YPUJ.min.mjs.map} +0 -0
  93. /package/{storage.d.mts → storage.d.cts} +0 -0
  94. /package/{stringify.d.mts → stringify.d.cts} +0 -0
  95. /package/{useDeepMemo.d.mts → useDeepMemo.d.cts} +0 -0
package/NoSSR.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-74BS2FAO.cjs');
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-IS3BZTWE.cjs');
2
2
 
3
3
  // src/NoSSR.tsx
4
4
  var _react = require('react');
package/NoSSR.d.ts CHANGED
@@ -1,12 +1,14 @@
1
+ import React, { ReactNode } from 'react';
2
+
1
3
  /**
2
4
  * @packageDocumentation
3
5
  *
4
6
  * Wraps components in <NoSSR>...</NoSSR> to make sure they only render on the
5
7
  * client side, and not on the server side.
6
8
  */
7
- import React, { ReactNode } from "react";
9
+
8
10
  /** Props for the NoSSR component. */
9
- export type NoSSRProps = {
11
+ type NoSSRProps = {
10
12
  /** The content to render only on the client side. */
11
13
  children: ReactNode;
12
14
  /** A component to render during SSR or initial load. */
@@ -17,4 +19,6 @@ export type NoSSRProps = {
17
19
  * Server-Side Rendering (SSR). It renders a optional fallback during SSR, and
18
20
  * only renders its children after the component has mounted on the client.
19
21
  */
20
- export declare const NoSSR: React.FC<NoSSRProps>;
22
+ declare const NoSSR: React.FC<NoSSRProps>;
23
+
24
+ export { NoSSR, type NoSSRProps };
package/NoSSR.min.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-KE3RXVMS.min.cjs');var _react = require('react');var l=({children:e,fallback:t})=>{let[o,c]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>{c(!0)},[]),o?e:t};exports.NoSSR = l;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-ZCDXPV3A.min.cjs');var _react = require('react');var l=({children:e,fallback:t})=>{let[o,c]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>{c(!0)},[]),o?e:t};exports.NoSSR = l;
2
2
  //# sourceMappingURL=NoSSR.min.cjs.map
package/NoSSR.min.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunk-MWDH7YON.min.mjs";import{useEffect as r,useState as s}from"react";var l=({children:e,fallback:t})=>{let[o,c]=s(!1);return r(()=>{c(!0)},[]),o?e:t};export{l as NoSSR};
1
+ import"./chunk-HRE7YPUJ.min.mjs";import{useEffect as r,useState as s}from"react";var l=({children:e,fallback:t})=>{let[o,c]=s(!1);return r(()=>{c(!0)},[]),o?e:t};export{l as NoSSR};
2
2
  //# sourceMappingURL=NoSSR.min.mjs.map
package/NoSSR.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import "./chunk-X6BYQHVC.mjs";
1
+ import "./chunk-R7POPVJR.mjs";
2
2
 
3
3
  // src/NoSSR.tsx
4
4
  import { useEffect, useState } from "react";
@@ -1,7 +1,3 @@
1
- import {
2
- __esm
3
- } from "./chunk-X6BYQHVC.mjs";
4
-
5
1
  // src/stringify.ts
6
2
  function stringifyDeterministicForKeys(params) {
7
3
  const cache = /* @__PURE__ */ new Set();
@@ -32,12 +28,7 @@ function stringifyDeterministicForKeys(params) {
32
28
  );
33
29
  });
34
30
  }
35
- var init_stringify = __esm({
36
- "src/stringify.ts"() {
37
- }
38
- });
39
31
 
40
32
  export {
41
- stringifyDeterministicForKeys,
42
- init_stringify
33
+ stringifyDeterministicForKeys
43
34
  };
@@ -1,5 +1,5 @@
1
1
  // src/useDeepMemo.ts
2
- import isEqual from "lodash/isEqual";
2
+ import { isEqual } from "lodash-es";
3
3
  import { useMemo, useState } from "react";
4
4
  function useDeepMemo(value) {
5
5
  const [state, setState] = useState(value);
@@ -0,0 +1,2 @@
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 _chunkNTFFK7ZHmincjs = require('./chunk-NTFFK7ZH.min.cjs');var _chunkKGN4HQPPmincjs = require('./chunk-KGN4HQPP.min.cjs');var _chunkJOHZV3FDmincjs = require('./chunk-JOHZV3FD.min.cjs');var _http = require('@choksheak/ts-utils/http');var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);var _react = require('react');var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);var Q={staleMs:0,expiryMs:30*864e5,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...a)=>console.log("[sharedQuery]",...a)};function se(a){Object.assign(Q,a)}var j=new Set;function ie(a){let M=a.url||"",i=a.queryName||M;if(!i)throw new Error("Either queryName or url must be specified.");if(j.has(i))throw new Error(`Duplicate shared query name "${i}"`);j.add(i);let T=new Map,h=new Map,m;if(a.queryFn)m=a.queryFn;else if(M){let e=_http.http.use(_http.retries.call(void 0, ));m=async(...t)=>{let r="",n=_optionalChain([t, 'optionalAccess', _2 => _2[0]]);if(n){if(typeof n=="string")r=n;else if(typeof n=="object"){let f=[];for(let[b,w]of Object.entries(n))if(w!==void 0)if(Array.isArray(w))for(let $ of w)$!==void 0&&f.push([b,String($)]);else f.push([b,String(w)]);r=new URLSearchParams(f).toString()}r&&(M.includes("?")?r="&"+r:r="?"+r)}return await(await e.get(M+r)).json()}}else throw new Error("Either queryFn or url must be specified");let u=a.refetchFn,y=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _3 => _3.staleMs]), () => (Q.staleMs)),D=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _4 => _4.expiryMs]), () => (Q.expiryMs)),x=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _5 => _5.refetchOnStale]), () => (Q.refetchOnStale)),A=a.store;if(A){if("persistTo"in A&&A.isValid){let e=A.isValid;a={...a,store:{...A,isValid:t=>{if(!t||typeof t!="object")return!1;for(let r of Object.values(t))if(!r||typeof r!="object"||!("data"in r)||!("dataUpdatedMs"in r)||!("lastUpdatedMs"in r)||typeof r.dataUpdatedMs!="number"||typeof r.lastUpdatedMs!="number"||!e(r.data))return!1;return!0}}}}}else{let e=_nullishCoalesce(a.persistTo, () => (Q.persistTo));e&&(a={...a,store:{persistTo:e,key:i,expiryMs:D}})}let p=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _6 => _6.maxSize]), () => (Q.maxSize)),s=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _7 => _7.maxBytes]), () => (Q.maxBytes)),d=!!_optionalChain([a, 'optionalAccess', _8 => _8.keepLastNonEmptyData]),o=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _9 => _9.log]), () => (Q.log)),c=_chunkNTFFK7ZHmincjs.c.call(void 0, {},a);function K(e){return y===0?!0:Date.now()-e>y}function k(e){return D===0?!1:Date.now()-e>D}function V(){if(!p&&!s)return;let e=c.getSnapshot(),t=Object.keys(e).length;if(t<=1)return;let r=_objectsizeof2.default.call(void 0, e),n=p?t-p:0,l=s?r-s:0;if(n<=0&&l<=0){o(`No need to trim data for ${i}: size=${t} (limit=${p}), byteSize=${r.toLocaleString()} (limit=${s.toLocaleString()})`);return}o(`Need to trim ${i}: numToCut=${n}, bytesToCut=${l}`);let f={...e},b=!1,w=(g,U)=>{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, f[g]);o(`Cleaning up unmounted${U?", expired":""} ${g} (byteSize=${O.toLocaleString()})`),n--,l-=O,delete f[g],b=!0},$=Object.entries(f).sort((g,U)=>g[1].lastUpdatedMs-U[1].lastUpdatedMs);for(let[g]of $){if(!k(f[g].lastUpdatedMs))break;w(g,!0)}if(n>0||l>0){b&&($=Object.entries(f).sort((g,U)=>g[1].lastUpdatedMs-U[1].lastUpdatedMs));for(let[g]of $)if(w(g,!1),n<=0&&l<=0)break}if(!b){o(`No trimmable entries found for ${i}: size=${t} (limit=${p}), byteSize=${r.toLocaleString()} (limit=${s.toLocaleString()})`);return}c.setValue(f),o(`Trimmed data for ${i}: size=[${t} -> ${Object.keys(f).length}] (limit=${p}), byteSize=[${r.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, f).toLocaleString()}] (limit=${s.toLocaleString()})`)}function v(e,t,r=Date.now()){let n={lastUpdatedMs:Date.now(),loading:!1,data:t,dataUpdatedMs:r};c.setValue(l=>({...l,[e]:n})),V()}async function _(e,t,r){o(`Start fetching ${e}, queryType=${t}`);try{let n=await(t==="refetch"&&u?u(...r):m(...r));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{T.delete(e)}}function C(e,t,...r){let n=T.get(e);if(n)return o(`Deduplicating inflight fetch for ${e}, queryType=${t}`),n.promise;let l=_(e,t,r),f=new AbortController;return T.set(e,{promise:l,abortController:f}),l}let S={queryName:i,queryFn:m,refetchFn:u,expiryMs:D,staleMs:y,refetchOnStale:x,maxSize:p,maxBytes:s,keepLastNonEmptyData:d,log:o,queryState:c,getQueryKey(e){let t=_chunkKGN4HQPPmincjs.a.call(void 0, e);return t.length>30&&(t=_xxhashjs2.default.h32(t,39406).toString(16).slice(2)),i+":"+t},getAbortController(e){let t=S.getQueryKey(e);return S.getAbortControllerByKey(t)},getAbortControllerByKey(e){return _nullishCoalesce(_optionalChain([T, '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 c.readyPromise;let r=Date.now()-t,n=S.getQueryKey(e),l=_optionalChain([c, 'access', _16 => _16.getSnapshot, 'call', _17 => _17(), 'optionalAccess', _18 => _18[n]]);if(r&&o(`${n}: Waited for ${r}ms before data is ready`),_optionalChain([l, 'optionalAccess', _19 => _19.data])&&!k(_nullishCoalesce(l.dataUpdatedMs, () => (0))))return K(_nullishCoalesce(l.dataUpdatedMs, () => (0)))?(x&&(o(`refetchOnStale for ${n}`),C(n,"query",...e)),o(`Returning stale data for ${n}`),l):(o(`Return fresh data ${n} from cache without fetching`),l);let f=await C(n,"query",...e),b=Date.now();return{lastUpdatedMs:b,loading:!1,data:f,dataUpdatedMs:b}},getQueryValue(e){return _optionalChain([c, 'access', _20 => _20.getSnapshot, 'call', _21 => _21(), 'optionalAccess', _22 => _22[e]])},getData(e){let t=_optionalChain([c, 'access', _23 => _23.getSnapshot, 'call', _24 => _24(), 'optionalAccess', _25 => _25[e]]);if(_optionalChain([t, 'optionalAccess', _26 => _26.lastUpdatedMs])&&k(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 C(t,"query",...e)},async refetch(...e){let t=S.getQueryKey(e);return await C(t,"refetch",...e)},deleteData(e){let r={...c.getSnapshot()};delete r[e],c.setValue(r);let n=T.get(e);n&&(T.delete(e),n.abortController.abort("Deleted"))},clear(){c.delete();for(let{abortController:e}of Array.from(T.values()))e.abort("Cleared");T.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:V};return S}var W={lastUpdatedMs:0,loading:!0};function ue(a,...M){let i=_chunkJOHZV3FDmincjs.a.call(void 0, M),[T,h]=_chunkNTFFK7ZHmincjs.d.call(void 0, a.queryState),m=_react.useRef.call(void 0, !0),u=_react.useMemo.call(void 0, ()=>a.getQueryKey(i),[a,i]),y=_nullishCoalesce(T[u], () => (W)),D=_react.useCallback.call(void 0, s=>{h(d=>{let o={...d};return o[u]=typeof s=="function"?s(_nullishCoalesce(o[u], () => (W))):s,o})},[u,h]),[x,A]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{a.keepLastNonEmptyData&&y.data!==void 0&&A(y.data)},[a.keepLastNonEmptyData,y.data]);let p=_react.useCallback.call(void 0, async s=>{if(a.log(`Begin executing shared query ${u}, isRefetch=${s}`),!!m.current){D(d=>({...d,lastUpdatedMs:Date.now(),loading:!0}));try{let d;if(s){let o=await a.refetch(...i),c=Date.now();d={lastUpdatedMs:c,loading:!1,data:o,dataUpdatedMs:c}}else d=await a.getCachedOrFetch(...i);if(!m.current)return;D({...d,loading:!1})}catch(d){if(!m.current)return;let o=Date.now();D(c=>({...c,lastUpdatedMs:o,loading:!1,error:d,errorUpdatedMs:o}))}}},[a,u,D,i]);return _react.useEffect.call(void 0, ()=>(m.current=!0,a.mount(u),p(!1),()=>{m.current=!1,a.unmount(u)}),[p,a,u]),_react.useMemo.call(void 0, ()=>({...y,data:y.data!==void 0?y.data:x,latestData:y.data,abortCurrentQuery:s=>{let d=a.getAbortControllerByKey(u);return _optionalChain([d, 'optionalAccess', _28 => _28.abort, 'call', _29 => _29(s)]),!!d},refetch:()=>p(!0),setData:(s,d)=>{a.setData(u,s,d)},deleteData:()=>{a.deleteData(u)}}),[p,x,a,u,y])}exports.a = Q; exports.b = se; exports.c = ie; exports.d = ue;
2
+ //# sourceMappingURL=chunk-BBCGQMWI.min.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-BBCGQMWI.min.cjs","../src/sharedQuery.ts"],"names":["SharedQueryConfig","args","configureSharedQuery","config","seenQueryNames","sharedQuery","options","url","queryName","inflightQueries","mountedKeys","queryFn","fetcher","http","retries","params","firstArg","entries","k","v","item","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,g1BAAmD,+DAA6C,+DAA6C,gDCqF/G,yGACN,8BAQjB,wFACS,IAgLHA,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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AAS,cAAA,CAAe,CAAC,CAAA,CAAA,CACzJ,CAAA,CACA,MACF,CAGAE,CAAAA,CACE,CAAA,aAAA,EAAgBxB,CAAS,CAAA,WAAA,EAAcmC,CAAQ,CAAA,aAAA,EAAgBC,CAAU,CAAA,CAAA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-BBCGQMWI.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 { http, retries } from \"@choksheak/ts-utils/http\";\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 { 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 const fetcher = http.use(retries());\n\n // Auto-generate the queryFn as a HTTP GET request using the url.\n queryFn = async (...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 const response = await fetcher.get(url + params);\n\n return await response.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 `http.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 * const response = await http.get(`/users/${userId}`, { signal });\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\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"]}
@@ -1,8 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
- var _chunk74BS2FAOcjs = require('./chunk-74BS2FAO.cjs');
4
-
5
- // src/stringify.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/stringify.ts
6
2
  function stringifyDeterministicForKeys(params) {
7
3
  const cache = /* @__PURE__ */ new Set();
8
4
  return JSON.stringify(params, (_, value) => {
@@ -32,12 +28,7 @@ function stringifyDeterministicForKeys(params) {
32
28
  );
33
29
  });
34
30
  }
35
- var init_stringify = _chunk74BS2FAOcjs.__esm.call(void 0, {
36
- "src/stringify.ts"() {
37
- }
38
- });
39
-
40
31
 
41
32
 
42
33
 
43
- exports.stringifyDeterministicForKeys = stringifyDeterministicForKeys; exports.init_stringify = init_stringify;
34
+ exports.stringifyDeterministicForKeys = stringifyDeterministicForKeys;