@choksheak/react-utils 0.4.7 → 0.4.8

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 (108) hide show
  1. package/NoSSR.cjs +5 -2
  2. package/{NoSSR.mjs → NoSSR.js} +4 -1
  3. package/NoSSR.min.cjs +14 -1
  4. package/NoSSR.min.cjs.map +1 -1
  5. package/NoSSR.min.js +15 -0
  6. package/{NoSSR.min.mjs.map → NoSSR.min.js.map} +1 -1
  7. package/chunk-4YV72T4D.min.js +105 -0
  8. package/{storage.min.mjs.map → chunk-4YV72T4D.min.js.map} +1 -1
  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-AXDXFCZV.min.js +35 -0
  13. package/{stringify.min.mjs.map → chunk-AXDXFCZV.min.js.map} +1 -1
  14. package/chunk-C6X4GPZ4.min.cjs +596 -0
  15. package/chunk-C6X4GPZ4.min.cjs.map +1 -0
  16. package/{sharedState.mjs → chunk-CIDQGOPA.js} +23 -8
  17. package/chunk-CYTO5EZE.cjs +34 -0
  18. package/chunk-HFIQE4XZ.cjs +595 -0
  19. package/chunk-IS3BZTWE.cjs +35 -0
  20. package/chunk-JYZY2SHD.min.js +596 -0
  21. package/chunk-JYZY2SHD.min.js.map +1 -0
  22. package/chunk-K2L3OVGY.min.cjs +18 -0
  23. package/chunk-K2L3OVGY.min.cjs.map +1 -0
  24. package/chunk-KGDXU6Q2.min.cjs +222 -0
  25. package/chunk-KGDXU6Q2.min.cjs.map +1 -0
  26. package/chunk-MNWSPF5J.min.js +18 -0
  27. package/{useDeepMemo.min.mjs.map → chunk-MNWSPF5J.min.js.map} +1 -1
  28. package/chunk-P2E73RBM.min.cjs +35 -0
  29. package/chunk-P2E73RBM.min.cjs.map +1 -0
  30. package/chunk-PCGGKBOL.min.js +222 -0
  31. package/chunk-PCGGKBOL.min.js.map +1 -0
  32. package/chunk-PHITDXZT.min.js +36 -0
  33. package/chunk-PHITDXZT.min.js.map +1 -0
  34. package/{sharedQuery.mjs → chunk-RFKUMDNU.js} +17 -6
  35. package/chunk-RRQBFF4W.min.cjs +105 -0
  36. package/chunk-RRQBFF4W.min.cjs.map +1 -0
  37. package/chunk-TST6JKQ5.min.cjs +36 -0
  38. package/chunk-TST6JKQ5.min.cjs.map +1 -0
  39. package/chunk-U67V476Y.js +35 -0
  40. package/chunk-UNDIVFP5.cjs +221 -0
  41. package/chunk-WXLUEDBO.cjs +17 -0
  42. package/{useDeepMemo.mjs → chunk-YTXGK6BR.js} +2 -0
  43. package/dist-4BDJ7HYS.min.js +546 -0
  44. package/dist-4BDJ7HYS.min.js.map +1 -0
  45. package/dist-HKOCAKHU.min.cjs +546 -0
  46. package/dist-HKOCAKHU.min.cjs.map +1 -0
  47. package/dist-RQU6CWRG.js +545 -0
  48. package/dist-UKP7SPWZ.cjs +545 -0
  49. package/index.cjs +43 -5
  50. package/index.d.cts +2 -2
  51. package/index.d.ts +2 -2
  52. package/index.js +43 -0
  53. package/index.min.cjs +43 -1
  54. package/index.min.cjs.map +1 -1
  55. package/index.min.js +44 -0
  56. package/index.min.js.map +1 -0
  57. package/magic-string.es-2AQNCEBL.min.js +1309 -0
  58. package/magic-string.es-2AQNCEBL.min.js.map +1 -0
  59. package/magic-string.es-HC5PDAU3.cjs +1308 -0
  60. package/magic-string.es-KDMUXKGI.js +1308 -0
  61. package/magic-string.es-XJ27RPMN.min.cjs +1309 -0
  62. package/magic-string.es-XJ27RPMN.min.cjs.map +1 -0
  63. package/package.json +48 -8
  64. package/sharedQuery.cjs +8 -575
  65. package/sharedQuery.d.cts +7 -92
  66. package/sharedQuery.d.ts +7 -92
  67. package/sharedQuery.js +17 -0
  68. package/sharedQuery.min.cjs +17 -1
  69. package/sharedQuery.min.cjs.map +1 -1
  70. package/sharedQuery.min.js +18 -0
  71. package/sharedQuery.min.js.map +1 -0
  72. package/sharedState.cjs +11 -199
  73. package/sharedState.d.cts +12 -57
  74. package/sharedState.d.ts +12 -57
  75. package/sharedState.js +18 -0
  76. package/sharedState.min.cjs +18 -1
  77. package/sharedState.min.cjs.map +1 -1
  78. package/sharedState.min.js +19 -0
  79. package/sharedState.min.js.map +1 -0
  80. package/storage.cjs +7 -98
  81. package/storage.js +11 -0
  82. package/storage.min.cjs +11 -1
  83. package/storage.min.cjs.map +1 -1
  84. package/storage.min.js +12 -0
  85. package/storage.min.js.map +1 -0
  86. package/stringify.cjs +5 -30
  87. package/stringify.js +7 -0
  88. package/stringify.min.cjs +7 -1
  89. package/stringify.min.cjs.map +1 -1
  90. package/stringify.min.js +8 -0
  91. package/stringify.min.js.map +1 -0
  92. package/useDeepMemo.cjs +5 -13
  93. package/useDeepMemo.js +7 -0
  94. package/useDeepMemo.min.cjs +7 -1
  95. package/useDeepMemo.min.cjs.map +1 -1
  96. package/useDeepMemo.min.js +8 -0
  97. package/useDeepMemo.min.js.map +1 -0
  98. package/NoSSR.min.mjs +0 -2
  99. package/index.min.mjs +0 -2
  100. package/index.min.mjs.map +0 -1
  101. package/index.mjs +0 -5
  102. package/sharedQuery.min.mjs +0 -2
  103. package/sharedQuery.min.mjs.map +0 -1
  104. package/sharedState.min.mjs +0 -2
  105. package/sharedState.min.mjs.map +0 -1
  106. package/storage.min.mjs +0 -2
  107. package/stringify.min.mjs +0 -2
  108. package/useDeepMemo.min.mjs +0 -2
package/sharedState.cjs CHANGED
@@ -1,206 +1,18 @@
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');
2
- var _react = require('react');
3
- var _storage = require('./storage');
4
- const SharedStateConfig = {
5
- /**
6
- * Default duration for storage expiration in milliseconds. Initial value
7
- * is 30 days, but can be changed to anything.
8
- */
9
- storeExpiryMs: 30 * _timeConstants.MS_PER_DAY,
10
- /**
11
- * True to load from storage only on mount, false (default) to load in
12
- * the top level scope when the shared state is defined.
13
- */
14
- lazyLoad: false
15
- };
16
- function configureSharedState(config) {
17
- Object.assign(SharedStateConfig, config);
18
- }
19
- function createPubSubStore() {
20
- const dataByKey = /* @__PURE__ */ new Map();
21
- const subscribersByKey = /* @__PURE__ */ new Map();
22
- function notify(key, next, prev) {
23
- const subscribers = subscribersByKey.get(key);
24
- if (!subscribers) return;
25
- const copy = Array.from(subscribers.values());
26
- for (const subscriber of copy) {
27
- try {
28
- subscriber(next, prev);
29
- } catch (e) {
30
- console.error(`Error invoking subscriber:`, e);
31
- }
32
- }
33
- }
34
- return {
35
- // This could be undefined if T includes undefined, else it should never
36
- // return undefined because the user has to always specify the default value.
37
- get(key) {
38
- return dataByKey.get(key);
39
- },
40
- set(key, value) {
41
- const prev = dataByKey.get(key);
42
- if (prev === value) return;
43
- dataByKey.set(key, value);
44
- notify(key, value, prev);
45
- },
46
- delete(key) {
47
- dataByKey.delete(key);
48
- },
49
- setNoNotify(key, value) {
50
- dataByKey.set(key, value);
51
- },
52
- // Subscribe to changes of a specific key
53
- subscribe(key, subscriber) {
54
- let subscribers = subscribersByKey.get(key);
55
- if (!subscribers) {
56
- subscribers = /* @__PURE__ */ new Set();
57
- subscribersByKey.set(key, subscribers);
58
- }
59
- subscribers.add(subscriber);
60
- return () => {
61
- subscribers.delete(subscriber);
62
- if (subscribers.size === 0) subscribersByKey.delete(key);
63
- };
64
- }
65
- };
66
- }
67
- function getOrCreatePubSubStore() {
68
- if (typeof window !== "undefined") {
69
- const t = window.globalThis;
70
- return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
71
- }
72
- return createPubSubStore();
73
- }
74
- const pubSubStore = getOrCreatePubSubStore();
75
- const STORAGE_KEY = "state";
76
- let stateKey = 0;
77
- function getNextStateKey() {
78
- if (typeof window !== "undefined") {
79
- const t = window.globalThis;
80
- t.reactUtilsStateKey = (_nullishCoalesce(t.reactUtilsStateKey, () => ( 0))) + 1;
81
- return t.reactUtilsStateKey;
82
- }
83
- return ++stateKey;
84
- }
85
- function sharedState(defaultValue, options) {
86
- let readyResolve = () => {
87
- };
88
- const readyPromise = new Promise((resolve) => {
89
- readyResolve = resolve;
90
- });
91
- const resolveReadyPromise = readyResolve;
92
- const pubSubKey = String(getNextStateKey());
93
- const storageAdapter = _storage.getStorageAdapter.call(void 0,
94
- options,
95
- SharedStateConfig.storeExpiryMs
96
- );
97
- pubSubStore.setNoNotify(pubSubKey, defaultValue);
98
- const lazyLoad = _optionalChain([options, 'optionalAccess', _ => _.lazyLoad]);
99
- const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
100
- function completeInit(stored) {
101
- const value = stored !== void 0 ? stored : defaultValue;
102
- pubSubStore.set(pubSubKey, value);
103
- obj.initDone = true;
104
- resolveReadyPromise();
105
- }
106
- const obj = {
107
- defaultValue,
108
- /** Allow users to await for the completion of data init. */
109
- readyPromise,
110
- lazy,
111
- initStarted: false,
112
- initDone: false,
113
- /** `subscribe` function required by useSyncExternalStore. */
114
- subscribe(subscriber) {
115
- return pubSubStore.subscribe(pubSubKey, () => subscriber());
116
- },
117
- /** Returns true if there is a backing store. */
118
- hasStore() {
119
- return Boolean(storageAdapter);
120
- },
121
- /**
122
- * Set a value directly into the store. Does nothing if there is no
123
- * backing store.
124
- *
125
- * Warning: If you want to set the value properly, you should use
126
- * `setValue()` instead which also updates the in-memory copy.
127
- */
128
- setInStore(value) {
129
- return _optionalChain([storageAdapter, 'optionalAccess', _2 => _2.set, 'call', _3 => _3(STORAGE_KEY, value)]);
130
- },
131
- /**
132
- * Get a value directly from the store. Returns undefined if there is no
133
- * backing store.
134
- */
135
- getFromStore() {
136
- return _optionalChain([storageAdapter, 'optionalAccess', _4 => _4.get, 'call', _5 => _5(STORAGE_KEY)]);
137
- },
138
- /**
139
- * Get the value of the shared state.
140
- * `getSnapshot` function — must return same ref if value unchanged.
141
- * Note that this would return the default value if data init from store is
142
- * not completed yet.
143
- */
144
- getSnapshot() {
145
- return pubSubStore.get(pubSubKey);
146
- },
147
- /** Set the value of the shared state. */
148
- setValue(next) {
149
- if (typeof next === "function") {
150
- const prev = pubSubStore.get(pubSubKey);
151
- next = next(prev);
152
- }
153
- pubSubStore.set(pubSubKey, next);
154
- void obj.setInStore(next);
155
- },
156
- /**
157
- * Remove the value of the shared state. Actually this just sets the value
158
- * back to the given default value.
159
- */
160
- delete() {
161
- pubSubStore.set(pubSubKey, defaultValue);
162
- return _optionalChain([storageAdapter, 'optionalAccess', _6 => _6.set, 'call', _7 => _7(STORAGE_KEY, defaultValue)]);
163
- },
164
- /** Initial default handling. */
165
- initDefaultValueOnce() {
166
- if (obj.initDone || obj.initStarted) return;
167
- obj.initStarted = true;
168
- const maybePromise = obj.getFromStore();
169
- if (maybePromise instanceof Promise) {
170
- return maybePromise.then(completeInit);
171
- } else {
172
- const stored = maybePromise;
173
- completeInit(stored);
174
- }
175
- }
176
- };
177
- if (!lazy) {
178
- obj.initDefaultValueOnce();
179
- }
180
- return obj;
181
- }
182
- function useSharedState(state) {
183
- void state.initDefaultValueOnce();
184
- const value = _react.useSyncExternalStore.call(void 0,
185
- (onStoreChange) => state.subscribe(onStoreChange),
186
- () => state.getSnapshot(),
187
- // getServerSnapshot is needed to prevent SSR dev errors in nextjs.
188
- () => state.getSnapshot()
189
- );
190
- return [value, state.setValue];
191
- }
192
- function useSharedStateValue(state) {
193
- return useSharedState(state)[0];
194
- }
195
- function useSharedStateSetter(state) {
196
- void state.initDefaultValueOnce();
197
- return state.setValue;
198
- }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
199
2
 
200
3
 
201
4
 
202
5
 
203
6
 
204
7
 
8
+ var _chunkUNDIVFP5cjs = require('./chunk-UNDIVFP5.cjs');
9
+ require('./chunk-5PDGU37E.cjs');
10
+ require('./chunk-IS3BZTWE.cjs');
205
11
 
206
- exports.SharedStateConfig = SharedStateConfig; exports.configureSharedState = configureSharedState; exports.sharedState = sharedState; exports.useSharedState = useSharedState; exports.useSharedStateSetter = useSharedStateSetter; exports.useSharedStateValue = useSharedStateValue;
12
+
13
+
14
+
15
+
16
+
17
+
18
+ exports.SharedStateConfig = _chunkUNDIVFP5cjs.SharedStateConfig; exports.configureSharedState = _chunkUNDIVFP5cjs.configureSharedState; exports.sharedState = _chunkUNDIVFP5cjs.sharedState; exports.useSharedState = _chunkUNDIVFP5cjs.useSharedState; exports.useSharedStateSetter = _chunkUNDIVFP5cjs.useSharedStateSetter; exports.useSharedStateValue = _chunkUNDIVFP5cjs.useSharedStateValue;
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-CIDQGOPA.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,19 @@
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});
2
+
3
+
4
+
5
+
6
+
7
+
8
+ var _chunkKGDXU6Q2mincjs = require('./chunk-KGDXU6Q2.min.cjs');
9
+ require('./chunk-RRQBFF4W.min.cjs');
10
+ require('./chunk-TST6JKQ5.min.cjs');
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+ exports.SharedStateConfig = _chunkKGDXU6Q2mincjs.SharedStateConfig; exports.configureSharedState = _chunkKGDXU6Q2mincjs.configureSharedState; exports.sharedState = _chunkKGDXU6Q2mincjs.sharedState; exports.useSharedState = _chunkKGDXU6Q2mincjs.useSharedState; exports.useSharedStateSetter = _chunkKGDXU6Q2mincjs.useSharedStateSetter; exports.useSharedStateValue = _chunkKGDXU6Q2mincjs.useSharedStateValue;
2
19
  //# 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,CAASC,CAAAA,CAAe,CACtD,MAAMC,CAAAA,CAAcL,CAAAA,CAAiB,GAAA,CAAIE,CAAG,CAAA,CAC5C,EAAA,CAAI,CAACG,CAAAA,CAAa,MAAA,CAGlB,MA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,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;AACE;AACA;AACA;AACA;AACA;AACA;AACF,+DAAiC;AACjC,oCAAiC;AACjC,oCAAiC;AACjC;AACE;AACA;AACA;AACA;AACA;AACA;AACF,qZAAC","file":"/Users/choksheaklau/src/react-utils/dist/sharedState.min.cjs"}
@@ -0,0 +1,19 @@
1
+ import {
2
+ SharedStateConfig,
3
+ configureSharedState,
4
+ sharedState,
5
+ useSharedState,
6
+ useSharedStateSetter,
7
+ useSharedStateValue
8
+ } from "./chunk-PCGGKBOL.min.js";
9
+ import "./chunk-4YV72T4D.min.js";
10
+ import "./chunk-PHITDXZT.min.js";
11
+ export {
12
+ SharedStateConfig,
13
+ configureSharedState,
14
+ sharedState,
15
+ useSharedState,
16
+ useSharedStateSetter,
17
+ useSharedStateValue
18
+ };
19
+ //# 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,12 @@
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});
2
+
3
+
4
+
5
+ var _chunkRRQBFF4Wmincjs = require('./chunk-RRQBFF4W.min.cjs');
6
+ require('./chunk-TST6JKQ5.min.cjs');
7
+
8
+
9
+
10
+
11
+ exports.getStorageAdapter = _chunkRRQBFF4Wmincjs.getStorageAdapter; exports.kvStoreAdapter = _chunkRRQBFF4Wmincjs.kvStoreAdapter; exports.localStoreAdapter = _chunkRRQBFF4Wmincjs.localStoreAdapter;
2
12
  //# sourceMappingURL=storage.min.cjs.map