@choksheak/react-utils 0.4.7 → 0.4.9

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 (109) hide show
  1. package/LICENSE +2 -0
  2. package/NoSSR.cjs +5 -2
  3. package/{NoSSR.mjs → NoSSR.js} +4 -1
  4. package/NoSSR.min.cjs +1 -1
  5. package/NoSSR.min.cjs.map +1 -1
  6. package/NoSSR.min.js +2 -0
  7. package/{NoSSR.min.mjs.map → NoSSR.min.js.map} +1 -1
  8. package/chunk-2VVAT5AA.cjs +599 -0
  9. package/chunk-5PDGU37E.cjs +104 -0
  10. package/{storage.mjs → chunk-7CPBZFDV.js} +5 -3
  11. package/{stringify.mjs → chunk-7XC6EVMX.js} +2 -0
  12. package/chunk-CW3XVEI4.min.cjs +2 -0
  13. package/chunk-CW3XVEI4.min.cjs.map +1 -0
  14. package/chunk-CYTO5EZE.cjs +34 -0
  15. package/chunk-GV7KUTU2.min.js +2 -0
  16. package/chunk-GV7KUTU2.min.js.map +1 -0
  17. package/{sharedState.mjs → chunk-H4OYYPJV.js} +29 -10
  18. package/chunk-IS3BZTWE.cjs +35 -0
  19. package/chunk-JOHZV3FD.min.cjs +2 -0
  20. package/chunk-JOHZV3FD.min.cjs.map +1 -0
  21. package/chunk-KGN4HQPP.min.cjs +2 -0
  22. package/chunk-KGN4HQPP.min.cjs.map +1 -0
  23. package/chunk-KXFV42DP.cjs +225 -0
  24. package/chunk-MBPSSROD.min.js +2 -0
  25. package/{useDeepMemo.min.mjs.map → chunk-MBPSSROD.min.js.map} +1 -1
  26. package/chunk-QASRLGQX.min.js +2 -0
  27. package/{storage.min.mjs.map → chunk-QASRLGQX.min.js.map} +1 -1
  28. package/chunk-SQX7XDQJ.min.cjs +2 -0
  29. package/chunk-SQX7XDQJ.min.cjs.map +1 -0
  30. package/chunk-TDP547RX.min.js +2 -0
  31. package/{stringify.min.mjs.map → chunk-TDP547RX.min.js.map} +1 -1
  32. package/{sharedQuery.mjs → chunk-TSVUVVWZ.js} +23 -8
  33. package/chunk-U67V476Y.js +35 -0
  34. package/chunk-UFJQLQFI.min.cjs +2 -0
  35. package/chunk-UFJQLQFI.min.cjs.map +1 -0
  36. package/chunk-UNSZMVZB.min.js +2 -0
  37. package/chunk-UNSZMVZB.min.js.map +1 -0
  38. package/chunk-WXLUEDBO.cjs +17 -0
  39. package/{useDeepMemo.mjs → chunk-YTXGK6BR.js} +2 -0
  40. package/chunk-ZCDXPV3A.min.cjs +2 -0
  41. package/chunk-ZCDXPV3A.min.cjs.map +1 -0
  42. package/chunk-ZCVFQ4FC.min.js +2 -0
  43. package/chunk-ZCVFQ4FC.min.js.map +1 -0
  44. package/dist-6EWLBMVU.min.js +2 -0
  45. package/dist-6EWLBMVU.min.js.map +1 -0
  46. package/dist-RQU6CWRG.js +545 -0
  47. package/dist-SEGTJ72R.min.cjs +2 -0
  48. package/dist-SEGTJ72R.min.cjs.map +1 -0
  49. package/dist-UKP7SPWZ.cjs +545 -0
  50. package/index.cjs +43 -5
  51. package/index.d.cts +3 -3
  52. package/index.d.ts +3 -3
  53. package/index.js +43 -0
  54. package/index.min.cjs +1 -1
  55. package/index.min.cjs.map +1 -1
  56. package/index.min.js +2 -0
  57. package/index.min.js.map +1 -0
  58. package/magic-string.es-FXUUD55Y.min.cjs +14 -0
  59. package/magic-string.es-FXUUD55Y.min.cjs.map +1 -0
  60. package/magic-string.es-HC5PDAU3.cjs +1308 -0
  61. package/magic-string.es-KDMUXKGI.js +1308 -0
  62. package/magic-string.es-W5QTEOCE.min.js +14 -0
  63. package/magic-string.es-W5QTEOCE.min.js.map +1 -0
  64. package/package.json +48 -8
  65. package/sharedQuery.cjs +8 -575
  66. package/sharedQuery.d.cts +7 -92
  67. package/sharedQuery.d.ts +7 -92
  68. package/sharedQuery.js +17 -0
  69. package/sharedQuery.min.cjs +1 -1
  70. package/sharedQuery.min.cjs.map +1 -1
  71. package/sharedQuery.min.js +2 -0
  72. package/sharedQuery.min.js.map +1 -0
  73. package/sharedState.cjs +11 -199
  74. package/sharedState.d.cts +12 -57
  75. package/sharedState.d.ts +12 -57
  76. package/sharedState.js +18 -0
  77. package/sharedState.min.cjs +1 -1
  78. package/sharedState.min.cjs.map +1 -1
  79. package/sharedState.min.js +2 -0
  80. package/sharedState.min.js.map +1 -0
  81. package/storage.cjs +7 -98
  82. package/storage.js +11 -0
  83. package/storage.min.cjs +1 -1
  84. package/storage.min.cjs.map +1 -1
  85. package/storage.min.js +2 -0
  86. package/storage.min.js.map +1 -0
  87. package/stringify.cjs +5 -30
  88. package/stringify.js +7 -0
  89. package/stringify.min.cjs +1 -1
  90. package/stringify.min.cjs.map +1 -1
  91. package/stringify.min.js +2 -0
  92. package/stringify.min.js.map +1 -0
  93. package/useDeepMemo.cjs +5 -13
  94. package/useDeepMemo.js +7 -0
  95. package/useDeepMemo.min.cjs +1 -1
  96. package/useDeepMemo.min.cjs.map +1 -1
  97. package/useDeepMemo.min.js +2 -0
  98. package/useDeepMemo.min.js.map +1 -0
  99. package/NoSSR.min.mjs +0 -2
  100. package/index.min.mjs +0 -2
  101. package/index.min.mjs.map +0 -1
  102. package/index.mjs +0 -5
  103. package/sharedQuery.min.mjs +0 -2
  104. package/sharedQuery.min.mjs.map +0 -1
  105. package/sharedState.min.mjs +0 -2
  106. package/sharedState.min.mjs.map +0 -1
  107. package/storage.min.mjs +0 -2
  108. package/stringify.min.mjs +0 -2
  109. package/useDeepMemo.min.mjs +0 -2
package/sharedState.d.cts CHANGED
@@ -1,63 +1,7 @@
1
+ import * as _choksheak_ts_utils_storageAdapter from '@choksheak/ts-utils/storageAdapter';
1
2
  import { SetStateAction, Dispatch } from 'react';
2
3
  import { StorageOptions } from './storage.cjs';
3
4
  import '@choksheak/ts-utils/duration';
4
- import '@choksheak/ts-utils/storageAdapter';
5
-
6
- /**
7
- * @packageDocumentation
8
- *
9
- * The "shared state" is a React state that shares the same value across the
10
- * entire app. Users declare a shared state constant that can be reused across
11
- * multiple components with the same underlying value.
12
- *
13
- * Shared states provide persistence to local storage and/or indexed DB out of
14
- * the box, by using "@choksheak/ts-utils". Note that no matter if the shared
15
- * state uses persistence or not, it will always maintain a copy of the state
16
- * in memory. Persisted values can be configured with an automatic expiration
17
- * duration.
18
- *
19
- * This module is largely similar to the open source "jotai" npm library. You
20
- * can use shared states to replace "jotai" in your code, and optionally make
21
- * use of the persistence mechanism. A quick migration guide from jotai is:
22
- *
23
- * ```
24
- * atom() --> sharedState()
25
- * useAtom() --> useSharedState()
26
- * useAtomValue() --> useSharedStateValue()
27
- * useSetAtom() --> useSharedStateSetter()
28
- * ```
29
- *
30
- * Example:
31
- * ```
32
- * import { sharedState, useSharedState } from "@choksheak/react-utils/sharedState";
33
- *
34
- * // Create a new shared state in the top level scope.
35
- * // The first argument is the default value, which is required.
36
- * // The second argument is an options object, and is optional (defaults
37
- * // to storing in memory only without any persistence).
38
- * const usersState = sharedState(
39
- * [], { store: { persistTo: "indexedDb", key: "users" }}
40
- * );
41
- *
42
- * export const UsersComponent: React.FC = () => {
43
- * // Get both the value and the setter.
44
- * const [users, setUsers] = useSharedState(usersState);
45
- * ...
46
- * };
47
- *
48
- * export const ReadOnlyComponent: React.FC = () => {
49
- * // Get the value only.
50
- * const users = useSharedStateValue(usersState);
51
- * ...
52
- * };
53
- *
54
- * export const WriteOnlyComponent: React.FC = () => {
55
- * // Get the setter only.
56
- * const setUsers = useSharedStateSetter(usersState);
57
- * ...
58
- * };
59
- * ```
60
- */
61
5
 
62
6
  /************************************************************************/
63
7
  /************************************************************************/
@@ -75,13 +19,20 @@ declare const SharedStateConfig: {
75
19
  * the top level scope when the shared state is defined.
76
20
  */
77
21
  lazyLoad: boolean;
22
+ /** Default to log to console. */
23
+ log: (...args: unknown[]) => void;
78
24
  };
79
25
  type SharedStateConfig = typeof SharedStateConfig;
80
26
  /** Convenience function to update global defaults. */
81
27
  declare function configureSharedState(config: Partial<SharedStateConfig>): void;
82
28
  /** Options to configure a shared state. */
83
29
  type SharedStateOptions<T> = {
30
+ /** Load from store only on first use of useSharedState(). */
84
31
  lazyLoad?: boolean;
32
+ /** Used for debug logging. */
33
+ name?: string;
34
+ /** Customize the logger. */
35
+ log?: (...args: unknown[]) => void;
85
36
  } & StorageOptions<T>;
86
37
  /**
87
38
  * Create a new shared state object. Put this code at the top level scope:
@@ -92,10 +43,14 @@ type SharedStateOptions<T> = {
92
43
  * ```
93
44
  */
94
45
  declare function sharedState<T>(defaultValue: T, options?: SharedStateOptions<T>): {
46
+ readonly name: string | undefined;
95
47
  readonly defaultValue: T;
48
+ readonly pubSubKey: string;
96
49
  /** Allow users to await for the completion of data init. */
97
50
  readonly readyPromise: Promise<void>;
51
+ readonly storeExpiryMs: number;
98
52
  readonly lazy: boolean;
53
+ readonly storageAdapter: _choksheak_ts_utils_storageAdapter.StorageAdapter<T> | null;
99
54
  readonly initStarted: false;
100
55
  readonly initDone: false;
101
56
  /** `subscribe` function required by useSyncExternalStore. */
package/sharedState.d.ts CHANGED
@@ -1,63 +1,7 @@
1
+ import * as _choksheak_ts_utils_storageAdapter from '@choksheak/ts-utils/storageAdapter';
1
2
  import { SetStateAction, Dispatch } from 'react';
2
3
  import { StorageOptions } from './storage.js';
3
4
  import '@choksheak/ts-utils/duration';
4
- import '@choksheak/ts-utils/storageAdapter';
5
-
6
- /**
7
- * @packageDocumentation
8
- *
9
- * The "shared state" is a React state that shares the same value across the
10
- * entire app. Users declare a shared state constant that can be reused across
11
- * multiple components with the same underlying value.
12
- *
13
- * Shared states provide persistence to local storage and/or indexed DB out of
14
- * the box, by using "@choksheak/ts-utils". Note that no matter if the shared
15
- * state uses persistence or not, it will always maintain a copy of the state
16
- * in memory. Persisted values can be configured with an automatic expiration
17
- * duration.
18
- *
19
- * This module is largely similar to the open source "jotai" npm library. You
20
- * can use shared states to replace "jotai" in your code, and optionally make
21
- * use of the persistence mechanism. A quick migration guide from jotai is:
22
- *
23
- * ```
24
- * atom() --> sharedState()
25
- * useAtom() --> useSharedState()
26
- * useAtomValue() --> useSharedStateValue()
27
- * useSetAtom() --> useSharedStateSetter()
28
- * ```
29
- *
30
- * Example:
31
- * ```
32
- * import { sharedState, useSharedState } from "@choksheak/react-utils/sharedState";
33
- *
34
- * // Create a new shared state in the top level scope.
35
- * // The first argument is the default value, which is required.
36
- * // The second argument is an options object, and is optional (defaults
37
- * // to storing in memory only without any persistence).
38
- * const usersState = sharedState(
39
- * [], { store: { persistTo: "indexedDb", key: "users" }}
40
- * );
41
- *
42
- * export const UsersComponent: React.FC = () => {
43
- * // Get both the value and the setter.
44
- * const [users, setUsers] = useSharedState(usersState);
45
- * ...
46
- * };
47
- *
48
- * export const ReadOnlyComponent: React.FC = () => {
49
- * // Get the value only.
50
- * const users = useSharedStateValue(usersState);
51
- * ...
52
- * };
53
- *
54
- * export const WriteOnlyComponent: React.FC = () => {
55
- * // Get the setter only.
56
- * const setUsers = useSharedStateSetter(usersState);
57
- * ...
58
- * };
59
- * ```
60
- */
61
5
 
62
6
  /************************************************************************/
63
7
  /************************************************************************/
@@ -75,13 +19,20 @@ declare const SharedStateConfig: {
75
19
  * the top level scope when the shared state is defined.
76
20
  */
77
21
  lazyLoad: boolean;
22
+ /** Default to log to console. */
23
+ log: (...args: unknown[]) => void;
78
24
  };
79
25
  type SharedStateConfig = typeof SharedStateConfig;
80
26
  /** Convenience function to update global defaults. */
81
27
  declare function configureSharedState(config: Partial<SharedStateConfig>): void;
82
28
  /** Options to configure a shared state. */
83
29
  type SharedStateOptions<T> = {
30
+ /** Load from store only on first use of useSharedState(). */
84
31
  lazyLoad?: boolean;
32
+ /** Used for debug logging. */
33
+ name?: string;
34
+ /** Customize the logger. */
35
+ log?: (...args: unknown[]) => void;
85
36
  } & StorageOptions<T>;
86
37
  /**
87
38
  * Create a new shared state object. Put this code at the top level scope:
@@ -92,10 +43,14 @@ type SharedStateOptions<T> = {
92
43
  * ```
93
44
  */
94
45
  declare function sharedState<T>(defaultValue: T, options?: SharedStateOptions<T>): {
46
+ readonly name: string | undefined;
95
47
  readonly defaultValue: T;
48
+ readonly pubSubKey: string;
96
49
  /** Allow users to await for the completion of data init. */
97
50
  readonly readyPromise: Promise<void>;
51
+ readonly storeExpiryMs: number;
98
52
  readonly lazy: boolean;
53
+ readonly storageAdapter: _choksheak_ts_utils_storageAdapter.StorageAdapter<T> | null;
99
54
  readonly initStarted: false;
100
55
  readonly initDone: false;
101
56
  /** `subscribe` function required by useSyncExternalStore. */
package/sharedState.js ADDED
@@ -0,0 +1,18 @@
1
+ import {
2
+ SharedStateConfig,
3
+ configureSharedState,
4
+ sharedState,
5
+ useSharedState,
6
+ useSharedStateSetter,
7
+ useSharedStateValue
8
+ } from "./chunk-H4OYYPJV.js";
9
+ import "./chunk-7CPBZFDV.js";
10
+ import "./chunk-U67V476Y.js";
11
+ export {
12
+ SharedStateConfig,
13
+ configureSharedState,
14
+ sharedState,
15
+ useSharedState,
16
+ useSharedStateSetter,
17
+ useSharedStateValue
18
+ };
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _timeConstants = require('@choksheak/ts-utils/timeConstants');var _react = require('react');var _storage = require('./storage');const p={storeExpiryMs:30*_timeConstants.MS_PER_DAY,lazyLoad:!1};function E(e){Object.assign(p,e)}function l(){const e=new Map,i=new Map;function S(o,n,t){const a=i.get(o);if(!a)return;const c=Array.from(a.values());for(const d of c)try{d(n,t)}catch(f){console.error("Error invoking subscriber:",f)}}return{get(o){return e.get(o)},set(o,n){const t=e.get(o);t!==n&&(e.set(o,n),S(o,n,t))},delete(o){e.delete(o)},setNoNotify(o,n){e.set(o,n)},subscribe(o,n){let t=i.get(o);return t||(t=new Set,i.set(o,t)),t.add(n),()=>{t.delete(n),t.size===0&&i.delete(o)}}}}function h(){if(typeof window<"u"){const e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=l())}return l()}const u=h(),T="state";let m=0;function P(){if(typeof window<"u"){const e=window.globalThis;return e.reactUtilsStateKey=(_nullishCoalesce(e.reactUtilsStateKey, () => (0)))+1,e.reactUtilsStateKey}return++m}function U(e,i){let S=()=>{};const o=new Promise(r=>{S=r}),n=S,t=String(P()),a=_storage.getStorageAdapter.call(void 0, i,p.storeExpiryMs);u.setNoNotify(t,e);const c=_optionalChain([i, 'optionalAccess', _ => _.lazyLoad]),d=c!==void 0?c:p.lazyLoad;function f(r){const b=r!==void 0?r:e;u.set(t,b),s.initDone=!0,n()}const s={defaultValue:e,readyPromise:o,lazy:d,initStarted:!1,initDone:!1,subscribe(r){return u.subscribe(t,()=>r())},hasStore(){return!!a},setInStore(r){return _optionalChain([a, 'optionalAccess', _2 => _2.set, 'call', _3 => _3(T,r)])},getFromStore(){return _optionalChain([a, 'optionalAccess', _4 => _4.get, 'call', _5 => _5(T)])},getSnapshot(){return u.get(t)},setValue(r){if(typeof r=="function"){const b=u.get(t);r=r(b)}u.set(t,r),s.setInStore(r)},delete(){return u.set(t,e),_optionalChain([a, 'optionalAccess', _6 => _6.set, 'call', _7 => _7(T,e)])},initDefaultValueOnce(){if(s.initDone||s.initStarted)return;s.initStarted=!0;const r=s.getFromStore();if(r instanceof Promise)return r.then(f);f(r)}};return d||s.initDefaultValueOnce(),s}function w(e){return e.initDefaultValueOnce(),[_react.useSyncExternalStore.call(void 0, S=>e.subscribe(S),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function R(e){return w(e)[0]}function C(e){return e.initDefaultValueOnce(),e.setValue}exports.SharedStateConfig = p; exports.configureSharedState = E; exports.sharedState = U; exports.useSharedState = w; exports.useSharedStateSetter = C; exports.useSharedStateValue = R;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkSQX7XDQJmincjs = require('./chunk-SQX7XDQJ.min.cjs');require('./chunk-UFJQLQFI.min.cjs');require('./chunk-ZCDXPV3A.min.cjs');exports.SharedStateConfig = _chunkSQX7XDQJmincjs.a; exports.configureSharedState = _chunkSQX7XDQJmincjs.b; exports.sharedState = _chunkSQX7XDQJmincjs.c; exports.useSharedState = _chunkSQX7XDQJmincjs.d; exports.useSharedStateSetter = _chunkSQX7XDQJmincjs.f; exports.useSharedStateValue = _chunkSQX7XDQJmincjs.e;
2
2
  //# sourceMappingURL=sharedState.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sharedState.ts"],"names":["SharedStateConfig","MS_PER_DAY","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","getNextStateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","pubSubKey","storageAdapter","getStorageAdapter","lazyLoad","lazy","completeInit","stored","obj","maybePromise","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"],"mappings":"AAwDA,mvBAA2B,8BACoC,oCAEb,MASrCA,CAAAA,CAAoB,CAK/B,aAAA,CAAe,EAAA,CAAKC,yBAAAA,CAMpB,QAAA,CAAU,CAAA,CACZ,CAAA,CAKO,SAASC,CAAAA,CAAqBC,CAAAA,CAAoC,CACvE,MAAA,CAAO,MAAA,CAAOH,CAAAA,CAAmBG,CAAM,CACzC,CAQA,SAASC,CAAAA,CAAAA,CAAoB,CAC3B,MAAMC,CAAAA,CAAY,IAAI,GAAA,CAChBC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAUC,CAAAA,CAAaC,CAAAA,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CAAE,CAAC,CAChC,CAUO,SAASI,CAAAA,CAAwBJ,CAAAA,CAAuB,CAC7D,OAAKA,CAAAA,CAAM,oBAAA,CAAqB,CAAA,CAEzBA,CAAAA,CAAM,QACf,CAAA,wLAAA","file":"/Users/choksheaklau/src/react-utils/dist/sharedState.min.cjs","sourcesContent":["/**\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\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as {\n reactUtilsPubSubStore?: ReturnType<typeof createPubSubStore>;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\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// Try to make this safe across hot reloads and bundling.\nfunction getNextStateKey() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as { reactUtilsStateKey?: number };\n t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;\n return t.reactUtilsStateKey;\n }\n return ++stateKey;\n}\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 // We'll make a new key with each hot reload, but that's ok.\n const pubSubKey = String(getNextStateKey());\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. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n function completeInit(stored: T | undefined) {\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\n const obj = {\n defaultValue,\n\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 setInStore(value: T): Promise<void> | void {\n return 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 getFromStore(): Promise<T | undefined> | T | undefined {\n return 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(): Promise<void> | void {\n pubSubStore.set(pubSubKey, defaultValue);\n return storageAdapter?.set(STORAGE_KEY, defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n const maybePromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (maybePromise instanceof Promise) {\n return maybePromise.then(completeInit);\n } else {\n const stored = maybePromise;\n completeInit(stored);\n }\n },\n } as const;\n\n if (!lazy) {\n 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"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/sharedState.min.cjs"],"names":[],"mappings":"AAAA,wIAAiD,oCAAiC,oCAAiC,sTAAiJ","file":"/Users/choksheaklau/src/react-utils/dist/sharedState.min.cjs"}
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f}from"./chunk-GV7KUTU2.min.js";import"./chunk-QASRLGQX.min.js";import"./chunk-UNSZMVZB.min.js";export{a as SharedStateConfig,b as configureSharedState,c as sharedState,d as useSharedState,f as useSharedStateSetter,e as useSharedStateValue};
2
+ //# sourceMappingURL=sharedState.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/storage.cjs CHANGED
@@ -1,102 +1,11 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _kvStore = require('@choksheak/ts-utils/kvStore');
2
- var _localStore = require('@choksheak/ts-utils/localStore');
3
- const IS_NOT_BROWSER = typeof window === "undefined";
4
- function getStorageAdapter(options, defaultStoreExpiryMs) {
5
- const { store } = _nullishCoalesce(options, () => ( {}));
6
- if (!store) {
7
- return null;
8
- }
9
- if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
10
- const expiryMs = store.expiryMs || defaultStoreExpiryMs;
11
- const config = { ...store, expiryMs };
12
- switch (store.persistTo) {
13
- case "localStorage":
14
- return localStoreAdapter(config);
15
- case "indexedDb":
16
- return kvStoreAdapter(config);
17
- default:
18
- store.persistTo;
19
- throw new Error(`Unknown store.adapter ${store.persistTo}`);
20
- }
21
- }
22
- return store;
23
- }
24
- function localStoreAdapter({
25
- key,
26
- expiryMs,
27
- isValid
28
- }) {
29
- const STORE_NAME = "react-utils";
30
- const adapter = _localStore.createLocalStore.call(void 0, STORE_NAME, {
31
- defaultExpiryMs: expiryMs
32
- });
33
- const keyPrefix = key + ":";
34
- return {
35
- set: (key2, value) => {
36
- if (IS_NOT_BROWSER) return;
37
- adapter.set(keyPrefix + key2, value);
38
- },
39
- get: (key2) => {
40
- if (IS_NOT_BROWSER) return void 0;
41
- const fullKey = keyPrefix + key2;
42
- const value = adapter.get(fullKey);
43
- if (value !== void 0 && isValid && !isValid(value)) {
44
- console.warn(
45
- `localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
46
- );
47
- adapter.delete(fullKey);
48
- return void 0;
49
- }
50
- return value;
51
- },
52
- delete: (key2) => {
53
- if (IS_NOT_BROWSER) return;
54
- adapter.delete(keyPrefix + key2);
55
- },
56
- /** Note that this will clear all keys in all shared states. */
57
- clear: () => {
58
- if (IS_NOT_BROWSER) return;
59
- adapter.clear();
60
- }
61
- };
62
- }
63
- function kvStoreAdapter({
64
- key,
65
- expiryMs,
66
- isValid
67
- }) {
68
- const keyPrefix = key + ":";
69
- return {
70
- set: async (key2, value) => {
71
- if (IS_NOT_BROWSER) return;
72
- await _kvStore.kvStore.set(keyPrefix + key2, value, expiryMs);
73
- },
74
- get: async (key2) => {
75
- if (IS_NOT_BROWSER) return void 0;
76
- const fullKey = keyPrefix + key2;
77
- const value = await _kvStore.kvStore.get(fullKey);
78
- if (value !== void 0 && isValid && !isValid(value)) {
79
- console.warn(
80
- `indexedDb adapter: Auto-discard invalid value for ${key2}:`,
81
- value
82
- );
83
- await _kvStore.kvStore.delete(fullKey);
84
- return void 0;
85
- }
86
- return value;
87
- },
88
- delete: async (key2) => {
89
- if (IS_NOT_BROWSER) return;
90
- await _kvStore.kvStore.delete(keyPrefix + key2);
91
- },
92
- clear: async () => {
93
- if (IS_NOT_BROWSER) return;
94
- await _kvStore.kvStore.clear();
95
- }
96
- };
97
- }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
98
2
 
99
3
 
100
4
 
5
+ var _chunk5PDGU37Ecjs = require('./chunk-5PDGU37E.cjs');
6
+ require('./chunk-IS3BZTWE.cjs');
101
7
 
102
- exports.getStorageAdapter = getStorageAdapter; exports.kvStoreAdapter = kvStoreAdapter; exports.localStoreAdapter = localStoreAdapter;
8
+
9
+
10
+
11
+ exports.getStorageAdapter = _chunk5PDGU37Ecjs.getStorageAdapter; exports.kvStoreAdapter = _chunk5PDGU37Ecjs.kvStoreAdapter; exports.localStoreAdapter = _chunk5PDGU37Ecjs.localStoreAdapter;
package/storage.js ADDED
@@ -0,0 +1,11 @@
1
+ import {
2
+ getStorageAdapter,
3
+ kvStoreAdapter,
4
+ localStoreAdapter
5
+ } from "./chunk-7CPBZFDV.js";
6
+ import "./chunk-U67V476Y.js";
7
+ export {
8
+ getStorageAdapter,
9
+ kvStoreAdapter,
10
+ localStoreAdapter
11
+ };
package/storage.min.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _kvStore = require('@choksheak/ts-utils/kvStore');var _localStore = require('@choksheak/ts-utils/localStore');const n=typeof window>"u";function v(s,a){const{store:e}=_nullishCoalesce(s, () => ({}));if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){const i=e.expiryMs||a,t={...e,expiryMs:i};switch(e.persistTo){case"localStorage":return c(t);case"indexedDb":return l(t);default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}function c({key:s,expiryMs:a,isValid:e}){const t=_localStore.createLocalStore.call(void 0, "react-utils",{defaultExpiryMs:a}),o=s+":";return{set:(r,d)=>{n||t.set(o+r,d)},get:r=>{if(n)return;const d=o+r,p=t.get(d);if(p!==void 0&&e&&!e(p)){console.warn(`localStorage adapter: Auto-discard invalid value for ${d}: ${JSON.stringify(p)}`),t.delete(d);return}return p},delete:r=>{n||t.delete(o+r)},clear:()=>{n||t.clear()}}}function l({key:s,expiryMs:a,isValid:e}){const i=s+":";return{set:async(t,o)=>{n||await _kvStore.kvStore.set(i+t,o,a)},get:async t=>{if(n)return;const o=i+t,r=await _kvStore.kvStore.get(o);if(r!==void 0&&e&&!e(r)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${t}:`,r),await _kvStore.kvStore.delete(o);return}return r},delete:async t=>{n||await _kvStore.kvStore.delete(i+t)},clear:async()=>{n||await _kvStore.kvStore.clear()}}}exports.getStorageAdapter = v; exports.kvStoreAdapter = l; exports.localStoreAdapter = c;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkUFJQLQFImincjs = require('./chunk-UFJQLQFI.min.cjs');require('./chunk-ZCDXPV3A.min.cjs');exports.getStorageAdapter = _chunkUFJQLQFImincjs.a; exports.kvStoreAdapter = _chunkUFJQLQFImincjs.c; exports.localStoreAdapter = _chunkUFJQLQFImincjs.b;
2
2
  //# sourceMappingURL=storage.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage.ts"],"names":["IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","config","localStoreAdapter","kvStoreAdapter"],"mappings":"AAYA,mOAAwB,4DACS,MAkC3BA,CAAAA,CAAiB,OAAO,MAAA,CAAW,GAAA,CAMlC,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CAC0B,CAC1B,KAAM,CAAE,KAAA,CAAAC,CAAM,CAAA,kBAAIF,CAAAA,SAAW,CAAC,GAAA,CAE9B,EAAA,CAAI,CAACE,CAAAA,CACH,OAAO,IAAA,CAGT,EAAA,CACE,WAAA,GAAeA,CAAAA,EACf,OAAOA,CAAAA,CAAM,SAAA,EAAc,QAAA,EAC3B,KAAA,GAASA,CAAAA,EACT,OAAOA,CAAAA,CAAM,GAAA,EAAQ,QAAA,CACrB,CACA,MAAMC,CAAAA,CAAWD,CAAAA,CAAM,QAAA,EAAYD,CAAAA,CAC7BG,CAAAA,CAAS,CAAE,GAAGF,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAA,CAEpC,MAAA,CAAQD,CAAAA,CAAM,SAAA,CAAW,CACvB,IAAK,cAAA,CACH,OAAOG,CAAAA,CAAqBD,CAAM,CAAA,CAEpC,IAAK,WAAA,CACH,OAAOE,CAAAA,CAAkBF,CAAM,CAAA,CAEjC,OAAA,CACE,MAAAF,CAAAA,CAAM,SAAA,CACA,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyBA,CAAAA,CAAM,SAAS,CAAA,CAAA","file":"/Users/choksheaklau/src/react-utils/dist/storage.min.cjs","sourcesContent":["/**\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 // Put everything in the same store so that we can GC properly.\n const STORE_NAME = \"react-utils\";\n\n const adapter = createLocalStore(STORE_NAME, {\n defaultExpiryMs: expiryMs,\n });\n\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\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(keyPrefix + key, value);\n },\n\n get: (key: string): T | undefined => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = adapter.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 `localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`,\n );\n adapter.delete(fullKey);\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(keyPrefix + key);\n },\n\n /** Note that this will clear all keys in all shared states. */\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"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/storage.min.cjs"],"names":[],"mappings":"AAAA,wIAA2C,oCAAiC,wJAA0E","file":"/Users/choksheaklau/src/react-utils/dist/storage.min.cjs"}
package/storage.min.js ADDED
@@ -0,0 +1,2 @@
1
+ import{a,b,c}from"./chunk-QASRLGQX.min.js";import"./chunk-UNSZMVZB.min.js";export{a as getStorageAdapter,c as kvStoreAdapter,b as localStoreAdapter};
2
+ //# sourceMappingURL=storage.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/stringify.cjs CHANGED
@@ -1,32 +1,7 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});function stringifyDeterministicForKeys(params) {
2
- const cache = /* @__PURE__ */ new Set();
3
- return JSON.stringify(params, (_, value) => {
4
- if (typeof value === "function") {
5
- throw new Error(`Functions should not be passed into query parameters`);
6
- }
7
- if (!value || typeof value !== "object" || Array.isArray(value)) {
8
- return value;
9
- }
10
- if (cache.has(value)) {
11
- return "[Circular]";
12
- }
13
- cache.add(value);
14
- if (value !== params) {
15
- try {
16
- JSON.stringify(value);
17
- } catch (e) {
18
- return "[Unserializable]";
19
- }
20
- }
21
- return Object.keys(value).sort().reduce(
22
- (result, key) => {
23
- result[key] = value[key];
24
- return result;
25
- },
26
- {}
27
- );
28
- });
29
- }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
30
2
 
3
+ var _chunkCYTO5EZEcjs = require('./chunk-CYTO5EZE.cjs');
4
+ require('./chunk-IS3BZTWE.cjs');
31
5
 
32
- exports.stringifyDeterministicForKeys = stringifyDeterministicForKeys;
6
+
7
+ exports.stringifyDeterministicForKeys = _chunkCYTO5EZEcjs.stringifyDeterministicForKeys;
package/stringify.js ADDED
@@ -0,0 +1,7 @@
1
+ import {
2
+ stringifyDeterministicForKeys
3
+ } from "./chunk-7XC6EVMX.js";
4
+ import "./chunk-U67V476Y.js";
5
+ export {
6
+ stringifyDeterministicForKeys
7
+ };
package/stringify.min.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});function e(n){const t=new Set;return JSON.stringify(n,(s,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(t.has(r))return"[Circular]";if(t.add(r),r!==n)try{JSON.stringify(r)}catch (e2){return"[Unserializable]"}return Object.keys(r).sort().reduce((i,o)=>(i[o]=r[o],i),{})})}exports.stringifyDeterministicForKeys = e;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkKGN4HQPPmincjs = require('./chunk-KGN4HQPP.min.cjs');require('./chunk-ZCDXPV3A.min.cjs');exports.stringifyDeterministicForKeys = _chunkKGN4HQPPmincjs.a;
2
2
  //# sourceMappingURL=stringify.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stringify.ts"],"names":["stringifyDeterministicForKeys","params","cache","_","value","result","key"],"mappings":"AAmBO,kFAASA,CAAAA,CAA8BC,CAAAA,CAAyB,CACrE,MAAMC,CAAAA,CAAQ,IAAI,GAAA,CAElB,OAAO,IAAA,CAAK,SAAA,CAAUD,CAAAA,CAAQ,CAACE,CAAAA,CAAGC,CAAAA,CAAAA,EAAU,CAC1C,EAAA,CAAI,OAAOA,CAAAA,EAAU,UAAA,CACnB,MAAM,IAAI,KAAA,CAAM,sDAAsD,CAAA,CAGxE,EAAA,CAAI,CAACA,CAAAA,EAAS,OAAOA,CAAAA,EAAU,QAAA,EAAY,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,CAC5D,OAAOA,CAAAA,CAGT,EAAA,CAAIF,CAAAA,CAAM,GAAA,CAAIE,CAAK,CAAA,CAEjB,MAAO,YAAA,CAOT,EAAA,CAJAF,CAAAA,CAAM,GAAA,CAAIE,CAAK,CAAA,CAIXA,CAAAA,GAAUH,CAAAA,CACZ,GAAI,CACF,IAAA,CAAK,SAAA,CAAUG,CAAK,CACtB,CAAA,UAAQ,CACN,MAAO,kBACT,CAGF,OAAO,MAAA,CAAO,IAAA,CAAKA,CAAK,CAAA,CACrB,IAAA,CAAK,CAAA,CACL,MAAA,CACC,CAACC,CAAAA,CAAiCC,CAAAA,CAAAA,EAAAA,CAChCD,CAAAA,CAAOC,CAAG,CAAA,CAAIF,CAAAA,CAAME,CAAG,CAAA,CAChBD,CAAAA,CAAAA,CAET,CAAC,CACH,CACJ,CAAC,CACH,CAAA,0CAAA","file":"/Users/choksheaklau/src/react-utils/dist/stringify.min.cjs","sourcesContent":["/**\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"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/stringify.min.cjs"],"names":[],"mappings":"AAAA,wIAAuC,oCAAiC,+DAA2C","file":"/Users/choksheaklau/src/react-utils/dist/stringify.min.cjs"}
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-TDP547RX.min.js";import"./chunk-UNSZMVZB.min.js";export{a as stringifyDeterministicForKeys};
2
+ //# sourceMappingURL=stringify.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/useDeepMemo.cjs CHANGED
@@ -1,15 +1,7 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _lodashes = require('lodash-es');
2
- var _react = require('react');
3
- function useDeepMemo(value) {
4
- const [state, setState] = _react.useState.call(void 0, value);
5
- return _react.useMemo.call(void 0, () => {
6
- if (_lodashes.isEqual.call(void 0, state, value)) {
7
- return state;
8
- }
9
- setState(value);
10
- return value;
11
- }, [state, value]);
12
- }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
13
2
 
3
+ var _chunkWXLUEDBOcjs = require('./chunk-WXLUEDBO.cjs');
4
+ require('./chunk-IS3BZTWE.cjs');
14
5
 
15
- exports.useDeepMemo = useDeepMemo;
6
+
7
+ exports.useDeepMemo = _chunkWXLUEDBOcjs.useDeepMemo;
package/useDeepMemo.js ADDED
@@ -0,0 +1,7 @@
1
+ import {
2
+ useDeepMemo
3
+ } from "./chunk-YTXGK6BR.js";
4
+ import "./chunk-U67V476Y.js";
5
+ export {
6
+ useDeepMemo
7
+ };
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _lodashes = require('lodash-es');var _react = require('react');function f(t){const[e,r]=_react.useState.call(void 0, t);return _react.useMemo.call(void 0, ()=>_lodashes.isEqual.call(void 0, e,t)?e:(r(t),t),[e,t])}exports.useDeepMemo = f;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkJOHZV3FDmincjs = require('./chunk-JOHZV3FD.min.cjs');require('./chunk-ZCDXPV3A.min.cjs');exports.useDeepMemo = _chunkJOHZV3FDmincjs.a;
2
2
  //# sourceMappingURL=useDeepMemo.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/useDeepMemo.ts"],"names":["useDeepMemo","value","state","setState","useState","useMemo","isEqual"],"mappings":"AAYA,8GAAwB,8BACU,SAMlBA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,KAAM,CAACC,CAAAA,CAAOC,CAAQ,CAAA,CAAIC,6BAAAA,CAAiB,CAAA,CAE3C,OAAOC,4BAAAA,CAAQ,CAAA,EACTC,+BAAAA,CAAQJ,CAAOD,CAAK,CAAA,CACfC,CAAAA,CAAAA,CAKTC,CAAAA,CAASF,CAAK,CAAA,CAEPA,CAAAA,CAAAA,CACN,CAACC,CAAAA,CAAOD,CAAK,CAAC,CACnB,CAAA,wBAAA","file":"/Users/choksheaklau/src/react-utils/dist/useDeepMemo.min.cjs","sourcesContent":["/**\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-es\";\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"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/useDeepMemo.min.cjs"],"names":[],"mappings":"AAAA,wIAAuC,oCAAiC,6CAAyB","file":"/Users/choksheaklau/src/react-utils/dist/useDeepMemo.min.cjs"}
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-MBPSSROD.min.js";import"./chunk-UNSZMVZB.min.js";export{a as useDeepMemo};
2
+ //# sourceMappingURL=useDeepMemo.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/NoSSR.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- import{useEffect as r,useState as s}from"react";const l=({children:e,fallback:t})=>{const[o,c]=s(!1);return r(()=>{c(!0)},[]),o?e:t};export{l as NoSSR};
2
- //# sourceMappingURL=NoSSR.min.mjs.map
package/index.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- export*from"./sharedQuery";export*from"./sharedState";export*from"./storage";export*from"./useDeepMemo";export*from"./stringify";
2
- //# sourceMappingURL=index.min.mjs.map
package/index.min.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from \"./sharedQuery\";\nexport * from \"./sharedState\";\nexport * from \"./storage\";\nexport * from \"./useDeepMemo\";\nexport * from \"./stringify\";\n"],"mappings":"AAAA,WAAc,gBACd,WAAc,gBACd,WAAc,YACd,WAAc,gBACd,WAAc","names":[]}
package/index.mjs DELETED
@@ -1,5 +0,0 @@
1
- export * from "./sharedQuery";
2
- export * from "./sharedState";
3
- export * from "./storage";
4
- export * from "./useDeepMemo";
5
- export * from "./stringify";
@@ -1,2 +0,0 @@
1
- import{http as L,retries as j}from"@choksheak/ts-utils/http";import{nonNil as W}from"@choksheak/ts-utils/nonNil";import k from"object-sizeof";import{useCallback as P,useEffect as R,useMemo as v,useRef as K,useState as _}from"react";import X from"xxhashjs";import{sharedState as Y,useSharedState as H}from"./sharedState";import{stringifyDeterministicForKeys as I}from"./stringify";import{useDeepMemo as J}from"./useDeepMemo";const w={staleMs:0,expiryMs:30*864e5,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...t)=>console.log("[sharedQuery]",...t)};function ge(t){Object.assign(w,t)}const G=new Map;function Z(){if(typeof window<"u"){const t=window.globalThis;return t.reactUtilsQueryRegistry??=new Map}return G}function q(t){const D=Z(),i=t.queryName||t.url,y=D.get(i);if(y)return y;const T=ee(t);return D.set(i,T),T}function ee(t){const D=t.url||"",i=t.queryName||D;if(!i)throw new Error("Either queryName or url must be specified.");const y=new Map,T=new Map;let S;if(t.queryFn)S=t.queryFn;else if(D){const e=L.use(j());S=async(...r)=>{let a="";const n=r?.[0];if(n){if(typeof n=="string")a=n;else if(typeof n=="object"){const f=[];for(const[Q,M]of Object.entries(n))if(M!==void 0)if(Array.isArray(M))for(const x of M)x!==void 0&&f.push([Q,String(x)]);else f.push([Q,String(M)]);a=new URLSearchParams(f).toString()}a&&(D.includes("?")?a="&"+a:a="?"+a)}return await(await e.get(D+a)).json()}}else throw new Error("Either queryFn or url must be specified");const u=t.refetchFn,p=t?.staleMs??w.staleMs,b=t?.expiryMs??w.expiryMs,U=t?.refetchOnStale??w.refetchOnStale,A=t.store;if(A){if("persistTo"in A&&A.isValid){const e=A.isValid;t={...t,store:{...A,isValid:r=>{if(!r||typeof r!="object")return!1;for(const a of Object.values(r))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{const e=t.persistTo??w.persistTo;e&&(t={...t,store:{persistTo:e,key:i,expiryMs:b}})}const m=t?.maxSize??w.maxSize,o=t?.maxBytes??w.maxBytes,l=!!t?.keepLastNonEmptyData,s=t?.log??w.log,c=Y({},t);function B(e){return p===0?!0:Date.now()-e>p}function F(e){return b===0?!1:Date.now()-e>b}function O(){if(!m&&!o)return;const e=c.getSnapshot(),r=Object.keys(e).length;if(r<=1)return;const a=k(e);let n=m?r-m:0,d=o?a-o:0;if(n<=0&&d<=0){s(`No need to trim data for ${i}: size=${r} (limit=${m}), byteSize=${a.toLocaleString()} (limit=${o.toLocaleString()})`);return}s(`Need to trim ${i}: numToCut=${n}, bytesToCut=${d}`);const f={...e};let Q=!1;const M=(g,$)=>{if(T.has(g)){s(`Cannot clean up ${g} as it is mounted`);return}const N=k(g)+k(f[g]);s(`Cleaning up unmounted${$?", expired":""} ${g} (byteSize=${N.toLocaleString()})`),n--,d-=N,delete f[g],Q=!0};let x=Object.entries(f).sort((g,$)=>g[1].lastUpdatedMs-$[1].lastUpdatedMs);for(const[g]of x){if(!F(f[g].lastUpdatedMs))break;M(g,!0)}if(n>0||d>0){Q&&(x=Object.entries(f).sort((g,$)=>g[1].lastUpdatedMs-$[1].lastUpdatedMs));for(const[g]of x)if(M(g,!1),n<=0&&d<=0)break}if(!Q){s(`No trimmable entries found for ${i}: size=${r} (limit=${m}), byteSize=${a.toLocaleString()} (limit=${o.toLocaleString()})`);return}c.setValue(f),s(`Trimmed data for ${i}: size=[${r} -> ${Object.keys(f).length}] (limit=${m}), byteSize=[${a.toLocaleString()} -> ${k(f).toLocaleString()}] (limit=${o.toLocaleString()})`)}function V(e,r,a=Date.now()){const n={lastUpdatedMs:Date.now(),loading:!1,data:r,dataUpdatedMs:a};c.setValue(d=>({...d,[e]:n})),O()}async function E(e,r,a){s(`Start fetching ${e}, queryType=${r}`);try{const n=await(r==="refetch"&&u?u(...a):S(...a));return s(`Successfully fetched ${e}`),V(e,n,Date.now()),n}catch(n){throw s(`Failed to fetch ${e} for queryType=${r}: ${n}`),n}finally{y.delete(e)}}function C(e,r,...a){const n=y.get(e);if(n)return s(`Deduplicating inflight fetch for ${e}, queryType=${r}`),n.promise;const d=E(e,r,a),f=new AbortController;return y.set(e,{promise:d,abortController:f}),d}const h={queryName:i,queryFn:S,refetchFn:u,expiryMs:b,staleMs:p,refetchOnStale:U,maxSize:m,maxBytes:o,keepLastNonEmptyData:l,log:s,queryState:c,getQueryKey(e){let r=I(e);return r.length>30&&(r=X.h32(r,39406).toString(16).slice(2)),i+":"+r},getAbortController(e){const r=h.getQueryKey(e);return h.getAbortControllerByKey(r)},getAbortControllerByKey(e){return y.get(e)?.abortController??null},getAbortSignal(e){const r=h.getQueryKey(e);return h.getAbortSignalByKey(r)},getAbortSignalByKey(e){return h.getAbortControllerByKey(e)?.signal??null},async getCachedOrFetch(...e){const r=Date.now();await c.readyPromise;const a=Date.now()-r,n=h.getQueryKey(e),d=c.getSnapshot()?.[n];if(a&&s(`${n}: Waited for ${a}ms before data is ready`),d?.data&&!F(d.dataUpdatedMs??0))return B(d.dataUpdatedMs??0)?(U&&(s(`refetchOnStale for ${n}`),C(n,"query",...e)),s(`Returning stale data for ${n}`),d):(s(`Return fresh data ${n} from cache without fetching`),d);const f=await C(n,"query",...e),Q=Date.now();return{lastUpdatedMs:Q,loading:!1,data:f,dataUpdatedMs:Q}},getQueryValue(e){return c.getSnapshot()?.[e]},getData(e){const r=c.getSnapshot()?.[e];if(r?.lastUpdatedMs&&F(r.lastUpdatedMs)){h.deleteData(e);return}return r?.data},setData:V,async updateFromSource(...e){const r=h.getQueryKey(e);return await C(r,"query",...e)},async refetch(...e){const r=h.getQueryKey(e);return await C(r,"refetch",...e)},deleteData(e){const a={...c.getSnapshot()};delete a[e],c.setValue(a);const n=y.get(e);n&&(y.delete(e),n.abortController.abort("Deleted"))},clear(){c.delete();for(const{abortController:e}of Array.from(y.values()))e.abort("Cleared");y.clear()},mount(e){T.set(e,(T.get(e)??0)+1)},unmount(e){const r=T.get(e);r===1?T.delete(e):T.set(e,(r??0)-1)},enforceSizeLimit:O};return h}function ye(t){return q(t)}const z={lastUpdatedMs:0,loading:!0};function Te(t,...D){const i=J(D),[y,T]=H(t.queryState),S=K(!0),u=v(()=>t.getQueryKey(i),[t,i]),p=y[u]??z,b=P(o=>{T(l=>{const s={...l};return s[u]=typeof o=="function"?o(s[u]??z):o,s})},[u,T]),[U,A]=_();R(()=>{t.keepLastNonEmptyData&&p.data!==void 0&&A(p.data)},[t.keepLastNonEmptyData,p.data]);const m=P(async o=>{if(t.log(`Begin executing shared query ${u}, isRefetch=${o}`),!!S.current){b(l=>({...l,lastUpdatedMs:Date.now(),loading:!0}));try{let l;if(o){const s=await t.refetch(...i),c=Date.now();l={lastUpdatedMs:c,loading:!1,data:s,dataUpdatedMs:c}}else l=await t.getCachedOrFetch(...i);return S.current?(b({...l,loading:!1}),l.data):void 0}catch(l){if(!S.current)return;const s=Date.now();b(c=>({...c,lastUpdatedMs:s,loading:!1,error:l,errorUpdatedMs:s}))}}},[t,u,b,i]);return R(()=>(S.current=!0,t.mount(u),m(!1),()=>{S.current=!1,t.unmount(u)}),[m,t,u]),v(()=>({...p,data:p.data!==void 0?p.data:U,latestData:p.data,abortCurrentQuery:o=>{const l=t.getAbortControllerByKey(u);return l?.abort(o),!!l},getCachedOrFetch:async()=>{const o=await t.getCachedOrFetch(...i);return W(o.data,typeof o.error=="string"?o.error:JSON.stringify(o.error))},refetch:()=>m(!0),setData:(o,l)=>{t.setData(u,o,l)},deleteData:()=>{t.deleteData(u)}}),[m,U,t,u,p,i])}export{w as SharedQueryConfig,ge as configureSharedQuery,ye as sharedQuery,Te as useSharedQuery};
2
- //# sourceMappingURL=sharedQuery.min.mjs.map