dharma-core 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { SetState, StoreConfig } from "../types/types";
2
2
  export declare const createStorageAdapter: <TState, TActions>(config: StoreConfig<TState, TActions>, get: () => TState, set: SetState<TState>) => {
3
- onLoad: () => Promise<void>;
3
+ onLoad: () => void;
4
4
  onChange: (newState: TState) => Promise<void>;
5
5
  onAttach: () => void;
6
6
  onDetach: () => void;
@@ -12,24 +12,7 @@ const createStorageAdapter = (config, get, set) => {
12
12
  warn.warn("No storage provider found. If this happened during SSR, you can safely ignore this warning.");
13
13
  return null;
14
14
  }
15
- const { key, serializer = JSON, initialState } = config;
16
- const initKey = `init_${key}`;
17
- const onLoad = async () => {
18
- try {
19
- let initialStateSnapshot = storage.getItem(initKey);
20
- const initialStateString = serializer.stringify(initialState);
21
- if (initialStateSnapshot instanceof Promise) {
22
- initialStateSnapshot = await initialStateSnapshot;
23
- }
24
- if (initialStateSnapshot !== initialStateString) {
25
- storage.setItem(initKey, initialStateString);
26
- storage.removeItem(key);
27
- }
28
- }
29
- catch {
30
- warn.warn("Failed to initialize snapshots. If this happened during SSR, you can safely ignore this warning.");
31
- }
32
- };
15
+ const { key, serializer = JSON, syncWithStorageOn = "load" } = config;
33
16
  const syncWithSnapshot = async () => {
34
17
  try {
35
18
  let currentSnapshot = storage.getItem(key);
@@ -40,12 +23,20 @@ const createStorageAdapter = (config, get, set) => {
40
23
  set(serializer.parse(currentSnapshot));
41
24
  }
42
25
  }
43
- catch {
44
- warn.warn("Failed to update state from snapshot");
26
+ catch (e) {
27
+ warn.warn("Failed to sync state with snapshot. If this happened during SSR, you can safely ignore this warning.");
28
+ console.error(e);
29
+ }
30
+ };
31
+ const onLoad = () => {
32
+ if (syncWithStorageOn === "load") {
33
+ syncWithSnapshot();
45
34
  }
46
35
  };
47
36
  const onAttach = () => {
48
- syncWithSnapshot();
37
+ if (syncWithStorageOn === "attach") {
38
+ syncWithSnapshot();
39
+ }
49
40
  if (IS_BROWSER) {
50
41
  window.addEventListener("focus", syncWithSnapshot);
51
42
  }
@@ -61,8 +52,9 @@ const createStorageAdapter = (config, get, set) => {
61
52
  storage.setItem(key, newSnapshot);
62
53
  }
63
54
  }
64
- catch {
55
+ catch (e) {
65
56
  warn.warn("Failed to update snapshot");
57
+ console.error(e);
66
58
  }
67
59
  };
68
60
  const onDetach = () => {
@@ -1 +1 @@
1
- {"version":3,"file":"createStorageAdapter.js","sources":["../../../src/internal/createStorageAdapter.ts"],"sourcesContent":["import { SetState, StorageAPI, StoreConfig } from \"../types/types\";\nimport { warn } from \"./warn\";\n\nexport const createStorageAdapter = <TState, TActions>(\n config: StoreConfig<TState, TActions>,\n get: () => TState,\n set: SetState<TState>,\n) => {\n if (!config.persist) {\n return null;\n }\n\n const IS_BROWSER = typeof window !== \"undefined\";\n\n const storage =\n config.storage ?? (IS_BROWSER ? (localStorage as StorageAPI) : undefined);\n\n if (!storage) {\n warn(\n \"No storage provider found. If this happened during SSR, you can safely ignore this warning.\",\n );\n return null;\n }\n\n const { key, serializer = JSON, initialState } = config;\n const initKey = `init_${key}`;\n\n const onLoad = async () => {\n try {\n let initialStateSnapshot = storage.getItem(initKey);\n const initialStateString = serializer.stringify(initialState);\n\n if (initialStateSnapshot instanceof Promise) {\n initialStateSnapshot = await initialStateSnapshot;\n }\n\n if (initialStateSnapshot !== initialStateString) {\n storage.setItem(initKey, initialStateString);\n storage.removeItem(key);\n }\n } catch {\n warn(\n \"Failed to initialize snapshots. If this happened during SSR, you can safely ignore this warning.\",\n );\n }\n };\n\n const syncWithSnapshot = async () => {\n try {\n let currentSnapshot = storage.getItem(key);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (currentSnapshot && currentSnapshot !== serializer.stringify(get())) {\n set(serializer.parse(currentSnapshot));\n }\n } catch {\n warn(\"Failed to update state from snapshot\");\n }\n };\n\n const onAttach = () => {\n syncWithSnapshot();\n\n if (IS_BROWSER) {\n window.addEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n const onChange = async (newState: TState) => {\n try {\n let currentSnapshot = storage.getItem(key);\n const newSnapshot = serializer.stringify(newState);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (newSnapshot !== currentSnapshot) {\n storage.setItem(key, newSnapshot);\n }\n } catch {\n warn(\"Failed to update snapshot\");\n }\n };\n\n const onDetach = () => {\n if (IS_BROWSER) {\n window.removeEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n return {\n onLoad,\n onChange,\n onAttach,\n onDetach,\n };\n};\n"],"names":["warn"],"mappings":";;;;AAGO,MAAM,oBAAoB,GAAG,CAClC,MAAqC,EACrC,GAAiB,EACjB,GAAqB,KACnB;AACF,IAAA,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;AACnB,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,MAAM,UAAU,GAAG,OAAO,MAAM,KAAK,WAAW;AAEhD,IAAA,MAAM,OAAO,GACX,MAAM,CAAC,OAAO,KAAK,UAAU,GAAI,YAA2B,GAAG,SAAS,CAAC;IAE3E,IAAI,CAAC,OAAO,EAAE;QACZA,SAAI,CACF,6FAA6F,CAC9F;AACD,QAAA,OAAO,IAAI;IACb;IAEA,MAAM,EAAE,GAAG,EAAE,UAAU,GAAG,IAAI,EAAE,YAAY,EAAE,GAAG,MAAM;AACvD,IAAA,MAAM,OAAO,GAAG,CAAA,KAAA,EAAQ,GAAG,EAAE;AAE7B,IAAA,MAAM,MAAM,GAAG,YAAW;AACxB,QAAA,IAAI;YACF,IAAI,oBAAoB,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;YACnD,MAAM,kBAAkB,GAAG,UAAU,CAAC,SAAS,CAAC,YAAY,CAAC;AAE7D,YAAA,IAAI,oBAAoB,YAAY,OAAO,EAAE;gBAC3C,oBAAoB,GAAG,M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AC;YACnC;QACF;AAAE,QAAA,MAAM;YACNA,SAAI,CAAC,2BAA2B,CAAC;QACnC;AACF,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;QACpB,IAAI,UAAU,EAAE;AACd,YAAA,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,CAAC;QACvD;AACF,IAAA,CAAC;IAED,OAAO;QACL,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,QAAQ;KACT;AACH;;;;"}
1
+ {"version":3,"file":"createStorageAdapter.js","sources":["../../../src/internal/createStorageAdapter.ts"],"sourcesContent":["import { SetState, StorageAPI, StoreConfig } from \"../types/types\";\nimport { warn } from \"./warn\";\n\nexport const createStorageAdapter = <TState, TActions>(\n config: StoreConfig<TState, TActions>,\n get: () => TState,\n set: SetState<TState>,\n) => {\n if (!config.persist) {\n return null;\n }\n\n const IS_BROWSER = typeof window !== \"undefined\";\n\n const storage =\n config.storage ?? (IS_BROWSER ? (localStorage as StorageAPI) : undefined);\n\n if (!storage) {\n warn(\n \"No storage provider found. If this happened during SSR, you can safely ignore this warning.\",\n );\n return null;\n }\n\n const { key, serializer = JSON, syncWithStorageOn = \"load\" } = config;\n\n const syncWithSnapshot = async () => {\n try {\n let currentSnapshot = storage.getItem(key);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (currentSnapshot && currentSnapshot !== serializer.stringify(get())) {\n set(serializer.parse(currentSnapshot));\n }\n } catch (e) {\n warn(\n \"Failed to sync state with snapshot. If this happened during SSR, you can safely ignore this warning.\",\n );\n console.error(e);\n }\n };\n\n const onLoad = () => {\n if (syncWithStorageOn === \"load\") {\n syncWithSnapshot();\n }\n };\n\n const onAttach = () => {\n if (syncWithStorageOn === \"attach\") {\n syncWithSnapshot();\n }\n\n if (IS_BROWSER) {\n window.addEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n const onChange = async (newState: TState) => {\n try {\n let currentSnapshot = storage.getItem(key);\n const newSnapshot = serializer.stringify(newState);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (newSnapshot !== currentSnapshot) {\n storage.setItem(key, newSnapshot);\n }\n } catch (e) {\n warn(\"Failed to update snapshot\");\n console.error(e);\n }\n };\n\n const onDetach = () => {\n if (IS_BROWSER) {\n window.removeEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n return {\n onLoad,\n onChange,\n onAttach,\n onDetach,\n };\n};\n"],"names":["warn"],"mappings":";;;;AAGO,MAAM,oBAAoB,GAAG,CAClC,MAAqC,EACrC,GAAiB,EACjB,GAAqB,KACnB;AACF,IAAA,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;AACnB,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,MAAM,UAAU,GAAG,OAAO,MAAM,KAAK,WAAW;AAEhD,IAAA,MAAM,OAAO,GACX,MAAM,CAAC,OAAO,KAAK,UAAU,GAAI,YAA2B,GAAG,SAAS,CAAC;IAE3E,IAAI,CAAC,OAAO,EAAE;QACZA,SAAI,CACF,6FAA6F,CAC9F;AACD,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,MAAM,EAAE,GAAG,EAAE,UAAU,GAAG,IAAI,EAAE,iBAAiB,GAAG,MAAM,EAAE,GAAG,MAAM;AAErE,IAAA,MAAM,gBAAgB,GAAG,YAAW;AAClC,QAAA,IAAI;YACF,IAAI,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC;AAE1C,YAAA,IAAI,eAAe,YAAY,OAAO,EAAE;gBACtC,eAAe,GAAG,MAAM,eAAe;YACzC;AAEA,YAAA,IAAI,eAAe,IAAI,eAAe,KAAK,UAAU,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,EAAE;gBACtE,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;YACxC;QACF;QAAE,OAAO,CAAC,EAAE;YACVA,SAAI,CACF,sGAAsG,CACvG;AACD,YAAA,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAClB;AACF,IAAA,CAAC;IAED,MAAM,MAAM,GAAG,MAAK;AAClB,QAAA,IAAI,iBAAiB,KAAK,MAAM,EAAE;AAChC,YAAA,gBAAgB,EAAE;QACpB;AACF,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;AACpB,QAAA,IAAI,iBAAiB,KAAK,QAAQ,EAAE;AAClC,YAAA,gBAAgB,EAAE;QACpB;QAEA,IAAI,UAAU,EAAE;AACd,YAAA,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,CAAC;QACpD;AACF,IAAA,CAAC;AAED,IAAA,MAAM,QAAQ,GAAG,OAAO,QAAgB,KAAI;AAC1C,QAAA,IAAI;YACF,IAAI,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC;YAC1C,MAAM,WAAW,GAAG,UAAU,CAAC,SAAS,CAAC,QAAQ,CAAC;AAElD,YAAA,IAAI,eAAe,YAAY,OAAO,EAAE;gBACtC,eAAe,GAAG,MAAM,eAAe;YACzC;AAEA,YAAA,IAAI,WAAW,KAAK,eAAe,EAAE;AACnC,gBAAA,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,CAAC;YACnC;QACF;QAAE,OAAO,CAAC,EAAE;YACVA,SAAI,CAAC,2BAA2B,CAAC;AACjC,YAAA,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAClB;AACF,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;QACpB,IAAI,UAAU,EAAE;AACd,YAAA,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,CAAC;QACvD;AACF,IAAA,CAAC;IAED,OAAO;QACL,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,QAAQ;KACT;AACH;;;;"}
@@ -32,12 +32,17 @@ const createStore = (config) => {
32
32
  return state;
33
33
  };
34
34
  const listeners = new Set();
35
- const actions = config.actions?.({ set, get, reset });
35
+ const actions = config.actions?.({
36
+ set,
37
+ get,
38
+ reset,
39
+ initialState,
40
+ });
36
41
  const storageAdapter = createStorageAdapter.createStorageAdapter(config, get, set);
37
42
  const subscribe = (listener) => {
38
43
  if (listeners.size === 0) {
39
44
  storageAdapter?.onAttach();
40
- onAttach?.({ state, set, reset });
45
+ onAttach?.({ state, set, reset, initialState });
41
46
  }
42
47
  listener(state);
43
48
  listeners.add(listener);
@@ -45,7 +50,7 @@ const createStore = (config) => {
45
50
  listeners.delete(listener);
46
51
  if (listeners.size === 0) {
47
52
  storageAdapter?.onDetach();
48
- onDetach?.({ state, set, reset });
53
+ onDetach?.({ state, set, reset, initialState });
49
54
  }
50
55
  };
51
56
  };
@@ -55,15 +60,19 @@ const createStore = (config) => {
55
60
  state,
56
61
  set: setSilently,
57
62
  reset: resetSilently,
63
+ initialState,
58
64
  });
59
65
  listeners.forEach((listener) => listener(state));
60
66
  };
61
67
  storageAdapter?.onLoad();
62
- onLoad?.({ state, set, reset });
68
+ onLoad?.({ state, set, reset, initialState });
63
69
  return {
64
70
  get,
65
71
  subscribe,
66
72
  actions,
73
+ set,
74
+ reset,
75
+ initialState,
67
76
  };
68
77
  };
69
78
 
@@ -1 +1 @@
1
- {"version":3,"file":"createStore.js","sources":["../../../src/lib/createStore.ts"],"sourcesContent":["import { createStorageAdapter } from \"../internal/createStorageAdapter\";\nimport { Listener, StateModifier, Store, StoreConfig } from \"../types/types\";\nimport { merge } from \"./merge\";\n\n/**\n * Creates a store with an initial state and actions that can modify the state.\n *\n * @param {StoreConfig<TState, TActions>} [config] - The configuration for the store.\n *\n * @returns {Store<TState, TActions>} The created store with state management methods.\n *\n * @see {@link https://dharma.fransek.dev/core/createstore/}\n */\nexport const createStore = <TState, TActions = undefined>(\n config: StoreConfig<TState, TActions>,\n): Store<TState, TActions> => {\n const { initialState, onLoad, onAttach, onDetach, onChange } = config;\n\n let state = initialState;\n\n const get = () => state;\n\n const setSilently = (stateModifier: StateModifier<TState>) => {\n state = merge(state, stateModifier);\n return state;\n };\n\n const set = (stateModifier: StateModifier<TState>) => {\n setSilently(stateModifier);\n dispatch();\n return state;\n };\n\n const resetSilently = () => setSilently(initialState);\n\n const reset = () => {\n resetSilently();\n dispatch();\n return state;\n };\n\n const listeners = new Set<Listener<TState>>();\n const actions = config.actions?.({ set, get, reset }) as TActions;\n const storageAdapter = createStorageAdapter(config, get, set);\n\n const subscribe = (listener: Listener<TState>) => {\n if (listeners.size === 0) {\n storageAdapter?.onAttach();\n onAttach?.({ state, set, reset });\n }\n\n listener(state);\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n storageAdapter?.onDetach();\n onDetach?.({ state, set, reset });\n }\n };\n };\n\n const dispatch = () => {\n storageAdapter?.onChange(state);\n onChange?.({\n state,\n set: setSilently,\n reset: resetSilently,\n });\n listeners.forEach((listener) => listener(state));\n };\n\n storageAdapter?.onLoad();\n onLoad?.({ state, set, reset });\n\n return {\n get,\n subscribe,\n actions,\n };\n};\n"],"names":["merge","createStorageAdapter"],"mappings":";;;;;AAIA;;;;;;;;AAQG;AACI,MAAM,WAAW,GAAG,CACzB,MAAqC,KACV;AAC3B,IAAA,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,MAAM;IAErE,IAAI,KAAK,GAAG,YAAY;AAExB,IAAA,MAAM,GAAG,GAAG,MAAM,KAAK;AAEvB,IAAA,MAAM,WAAW,GAAG,CAAC,aAAoC,KAAI;AAC3D,QAAA,KAAK,GAAGA,WAAK,CAAC,KAAK,EAAE,aAAa,CAAC;AACnC,QAAA,OAAO,KAAK;AACd,IAAA,CAAC;AAED,IAAA,MAAM,GAAG,GAAG,CAAC,aAAoC,KAAI;QACnD,WAAW,CAAC,aAAa,CAAC;AAC1B,QAAA,QAAQ,EAAE;AACV,QAAA,OAAO,KAAK;AACd,IAAA,CAAC;IAED,MAAM,aAAa,GAAG,MAAM,WAAW,CAAC,YAAY,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,EAAE;IACxB,MAAM,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;IAE/B,OAAO;QACL,GAAG;QACH,SAAS;QACT,OAAO;KACR;AACH;;;;"}
1
+ {"version":3,"file":"createStore.js","sources":["../../../src/lib/createStore.ts"],"sourcesContent":["import { createStorageAdapter } from \"../internal/createStorageAdapter\";\nimport { Listener, StateModifier, Store, StoreConfig } from \"../types/types\";\nimport { merge } from \"./merge\";\n\n/**\n * Creates a store with an initial state and actions that can modify the state.\n *\n * @param {StoreConfig<TState, TActions>} [config] - The configuration for the store.\n *\n * @returns {Store<TState, TActions>} The created store with state management methods.\n *\n * @see {@link https://dharma.fransek.dev/core/createstore/}\n */\nexport const createStore = <TState, TActions = undefined>(\n config: StoreConfig<TState, TActions>,\n): Store<TState, TActions> => {\n const { initialState, onLoad, onAttach, onDetach, onChange } = config;\n\n let state = initialState;\n\n const get = () => state;\n\n const setSilently = (stateModifier: StateModifier<TState>) => {\n state = merge(state, stateModifier);\n return state;\n };\n\n const set = (stateModifier: StateModifier<TState>) => {\n setSilently(stateModifier);\n dispatch();\n return state;\n };\n\n const resetSilently = () => setSilently(initialState);\n\n const reset = () => {\n resetSilently();\n dispatch();\n return state;\n };\n\n const listeners = new Set<Listener<TState>>();\n const actions = config.actions?.({\n set,\n get,\n reset,\n initialState,\n }) as TActions;\n const storageAdapter = createStorageAdapter(config, get, set);\n\n const subscribe = (listener: Listener<TState>) => {\n if (listeners.size === 0) {\n storageAdapter?.onAttach();\n onAttach?.({ state, set, reset, initialState });\n }\n\n listener(state);\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n storageAdapter?.onDetach();\n onDetach?.({ state, set, reset, initialState });\n }\n };\n };\n\n const dispatch = () => {\n storageAdapter?.onChange(state);\n onChange?.({\n state,\n set: setSilently,\n reset: resetSilently,\n initialState,\n });\n listeners.forEach((listener) => listener(state));\n };\n\n storageAdapter?.onLoad();\n onLoad?.({ state, set, reset, initialState });\n\n return {\n get,\n subscribe,\n actions,\n set,\n reset,\n initialState,\n };\n};\n"],"names":["merge","createStorageAdapter"],"mappings":";;;;;AAIA;;;;;;;;AAQG;AACI,MAAM,WAAW,GAAG,CACzB,MAAqC,KACV;AAC3B,IAAA,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,MAAM;IAErE,IAAI,KAAK,GAAG,YAAY;AAExB,IAAA,MAAM,GAAG,GAAG,MAAM,KAAK;AAEvB,IAAA,MAAM,WAAW,GAAG,CAAC,aAAoC,KAAI;AAC3D,QAAA,KAAK,GAAGA,WAAK,CAAC,KAAK,EAAE,aAAa,CAAC;AACnC,QAAA,OAAO,KAAK;AACd,IAAA,CAAC;AAED,IAAA,MAAM,GAAG,GAAG,CAAC,aAAoC,KAAI;QACnD,WAAW,CAAC,aAAa,CAAC;AAC1B,QAAA,QAAQ,EAAE;AACV,QAAA,OAAO,KAAK;AACd,IAAA,CAAC;IAED,MAAM,aAAa,GAAG,MAAM,WAAW,CAAC,YAAY,CAAC;IAErD,MAAM,KAAK,GAAG,MAAK;AACjB,QAAA,aAAa,EAAE;AACf,QAAA,QAAQ,EAAE;AACV,QAAA,OAAO,KAAK;AACd,IAAA,CAAC;AAED,IAAA,MAAM,SAAS,GAAG,IAAI,GAAG,EAAoB;AAC7C,IAAA,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,GAAG;QAC/B,GAAG;QACH,GAAG;QACH,KAAK;QACL,YAAY;AACb,KAAA,CAAa;IACd,MAAM,cAAc,GAAGC,yCAAoB,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG,CAAC;AAE7D,IAAA,MAAM,SAAS,GAAG,CAAC,QAA0B,KAAI;AAC/C,QAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;YACxB,cAAc,EAAE,QAAQ,EAAE;AAC1B,YAAA,QAAQ,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;QACjD;QAEA,QAAQ,CAAC,KAAK,CAAC;AACf,QAAA,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAEvB,QAAA,OAAO,MAAK;AACV,YAAA,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC;AAE1B,YAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;gBACxB,cAAc,EAAE,QAAQ,EAAE;AAC1B,gBAAA,QAAQ,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;YACjD;AACF,QAAA,CAAC;AACH,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;AACpB,QAAA,cAAc,EAAE,QAAQ,CAAC,KAAK,CAAC;AAC/B,QAAA,QAAQ,GAAG;YACT,KAAK;AACL,YAAA,GAAG,EAAE,WAAW;AAChB,YAAA,KAAK,EAAE,aAAa;YACpB,YAAY;AACb,SAAA,CAAC;AACF,QAAA,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC;AAClD,IAAA,CAAC;IAED,cAAc,EAAE,MAAM,EAAE;AACxB,IAAA,MAAM,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;IAE7C,OAAO;QACL,GAAG;QACH,SAAS;QACT,OAAO;QACP,GAAG;QACH,KAAK;QACL,YAAY;KACb;AACH;;;;"}
@@ -66,10 +66,8 @@ const derive = (store, deriveFn, dependencyFn) => {
66
66
  return {
67
67
  get,
68
68
  subscribe,
69
- actions: {
70
- mount,
71
- unmount,
72
- },
69
+ mount,
70
+ unmount,
73
71
  };
74
72
  };
75
73
 
@@ -1 +1 @@
1
- {"version":3,"file":"derive.js","sources":["../../../src/lib/derive.ts"],"sourcesContent":["import { DerivedStore, Listener, Store } from \"../types/types\";\nimport { deeplyEquals } from \"./deeplyEquals\";\n\n/**\n * Creates a derived store from an existing store.\n *\n * A derived store computes its state based on the original store's state using a derive function.\n * The derived store's value is memoized and only recomputed when requested.\n *\n * @param store - The original store to derive from\n * @param deriveFn - A function that computes the derived state from the original state\n * @param dependencyFn - Optional function that returns an array of dependencies. If provided, the derived state will only be recomputed when these dependencies change\n *\n * @returns A new store containing the derived state\n *\n * @see {@link https://dharma.fransek.dev/core/derive/}\n */\nexport const derive = <TState, TActions, TDerived>(\n store: Store<TState, TActions>,\n deriveFn: (state: TState) => TDerived,\n dependencyFn?: (state: TState) => unknown[],\n): DerivedStore<TDerived> => {\n let memo: TDerived | undefined;\n let prev: unknown[] | undefined;\n let isStale = true;\n let unsubscribe: (() => void) | undefined;\n const listeners = new Set<Listener<TDerived>>();\n\n const compute = () => {\n memo = deriveFn(store.get());\n isStale = false;\n return memo;\n };\n\n const get = () => {\n const next = dependencyFn?.(store.get());\n isStale &&= !prev || !deeplyEquals(prev, next);\n\n if (isStale) {\n prev = next;\n return compute();\n }\n\n return memo as TDerived;\n };\n\n const subscribe = (listener: Listener<TDerived>) => {\n if (listeners.size === 0) {\n mount();\n }\n\n listener(get());\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n unmount();\n }\n };\n };\n\n const listener = () => {\n isStale = true;\n listeners.forEach((listener) => listener(get()));\n };\n\n const mount = () => {\n if (!unsubscribe) {\n unsubscribe = store.subscribe(listener);\n }\n return unmount;\n };\n\n const unmount = () => {\n unsubscribe?.();\n unsubscribe = undefined;\n };\n\n return {\n get,\n subscribe,\n actions: {\n mount,\n unmount,\n },\n };\n};\n"],"names":["deeplyEquals"],"mappings":";;;;AAGA;;;;;;;;;;;;;AAaG;AACI,MAAM,MAAM,GAAG,CACpB,KAA8B,EAC9B,QAAqC,EACrC,YAA2C,KACjB;AAC1B,IAAA,IAAI,IAA0B;AAC9B,IAAA,IAAI,IAA2B;IAC/B,IAAI,OAAO,GAAG,IAAI;AAClB,IAAA,IAAI,WAAqC;AACzC,IAAA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AC;IAED,MAAM,OAAO,GAAG,MAAK;QACnB,WAAW,IAAI;QACf,WAAW,GAAG,SAAS;AACzB,IAAA,CAAC;IAED,OAAO;QACL,GAAG;QACH,SAAS;AACT,QAAA,OAAO,EAAE;YACP,KAAK;YACL,OAAO;AACR,SAAA;KACF;AACH;;;;"}
1
+ {"version":3,"file":"derive.js","sources":["../../../src/lib/derive.ts"],"sourcesContent":["import { DerivedStore, Listener, Store } from \"../types/types\";\nimport { deeplyEquals } from \"./deeplyEquals\";\n\n/**\n * Creates a derived store from an existing store.\n *\n * A derived store computes its state based on the original store's state using a derive function.\n * The derived store's value is memoized and only recomputed when requested.\n *\n * @param store - The original store to derive from\n * @param deriveFn - A function that computes the derived state from the original state\n * @param dependencyFn - Optional function that returns an array of dependencies. If provided, the derived state will only be recomputed when these dependencies change\n *\n * @returns A new store containing the derived state\n *\n * @see {@link https://dharma.fransek.dev/core/derive/}\n */\nexport const derive = <TState, TActions, TDerived>(\n store: Store<TState, TActions>,\n deriveFn: (state: TState) => TDerived,\n dependencyFn?: (state: TState) => unknown[],\n): DerivedStore<TDerived> => {\n let memo: TDerived | undefined;\n let prev: unknown[] | undefined;\n let isStale = true;\n let unsubscribe: (() => void) | undefined;\n const listeners = new Set<Listener<TDerived>>();\n\n const compute = () => {\n memo = deriveFn(store.get());\n isStale = false;\n return memo;\n };\n\n const get = () => {\n const next = dependencyFn?.(store.get());\n isStale &&= !prev || !deeplyEquals(prev, next);\n\n if (isStale) {\n prev = next;\n return compute();\n }\n\n return memo as TDerived;\n };\n\n const subscribe = (listener: Listener<TDerived>) => {\n if (listeners.size === 0) {\n mount();\n }\n\n listener(get());\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n unmount();\n }\n };\n };\n\n const listener = () => {\n isStale = true;\n listeners.forEach((listener) => listener(get()));\n };\n\n const mount = () => {\n if (!unsubscribe) {\n unsubscribe = store.subscribe(listener);\n }\n return unmount;\n };\n\n const unmount = () => {\n un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,QAAQ,GAAG,MAAK;QACpB,OAAO,GAAG,IAAI;AACd,QAAA,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC;AAClD,IAAA,CAAC;IAED,MAAM,KAAK,GAAG,MAAK;QACjB,IAAI,CAAC,WAAW,EAAE;AAChB,YAAA,WAAW,GAAG,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC;QACzC;AACA,QAAA,OAAO,OAAO;AAChB,IAAA,CAAC;IAED,MAAM,OAAO,GAAG,MAAK;QACnB,WAAW,IAAI;QACf,WAAW,GAAG,SAAS;AACzB,IAAA,CAAC;IAED,OAAO;QACL,GAAG;QACH,SAAS;QACT,KAAK;QACL,OAAO;KACR;AACH;;;;"}
@@ -7,14 +7,23 @@ export type Store<TState, TActions> = {
7
7
  actions: TActions;
8
8
  /** Subscribes to changes in the state of the store. Returns an unsubscribe function. */
9
9
  subscribe: (listener: Listener<TState>) => () => void;
10
+ /** Sets the state of the store. */
11
+ set: SetState<TState>;
12
+ /** Resets the state of the store to its initial value. */
13
+ reset: () => TState;
14
+ /** The initial state of the store. */
15
+ initialState: TState;
10
16
  };
11
- export type DerivedStoreActions = {
17
+ export type DerivedStore<TState> = {
18
+ /** Returns the current state of the store. */
19
+ get: () => TState;
20
+ /** Subscribes to changes in the state of the store. Returns an unsubscribe function. */
21
+ subscribe: (listener: Listener<TState>) => () => void;
12
22
  /** Start listening to changes in the original store. Called automatically on the first subscription. */
13
23
  mount: () => () => void;
14
24
  /** Stop listening to changes in the original store. Called automatically when there are no more subscribers. */
15
25
  unmount: () => void;
16
26
  };
17
- export type DerivedStore<TState> = Store<TState, DerivedStoreActions>;
18
27
  export type Effect = {
19
28
  /** Start listening to changes in the original store. */
20
29
  mount: () => () => void;
@@ -24,6 +33,8 @@ export type Effect = {
24
33
  export type StoreEventContext<TState> = {
25
34
  /** The current state of the store. */
26
35
  state: TState;
36
+ /** The initial state of the store. */
37
+ initialState: TState;
27
38
  /** Sets the state of the store. */
28
39
  set: SetState<TState>;
29
40
  /** Resets the state of the store to its initial value. */
@@ -38,6 +49,8 @@ export type ActionContext<TState> = {
38
49
  set: SetState<TState>;
39
50
  /** Resets the state of the store to its initial value. */
40
51
  reset: () => TState;
52
+ /** The initial state of the store. */
53
+ initialState: TState;
41
54
  };
42
55
  export type StoreActions<TState, TActions> = (context: ActionContext<TState>) => TActions;
43
56
  export type BaseConfig<TState, TActions> = {
@@ -58,7 +71,6 @@ export type MaybePromise<T> = T | Promise<T>;
58
71
  export type StorageAPI = {
59
72
  getItem: (key: string) => MaybePromise<string | null>;
60
73
  setItem: (key: string, value: string) => MaybePromise<void>;
61
- removeItem: (key: string) => MaybePromise<void>;
62
74
  };
63
75
  export type Serializer<T = any> = {
64
76
  stringify: (value: T) => string;
@@ -77,5 +89,11 @@ export type PersistConfig<TState> = {
77
89
  storage?: StorageAPI;
78
90
  /** The serializer to use for storing the state. Defaults to JSON. */
79
91
  serializer?: Serializer<TState>;
92
+ /**
93
+ * When to initially synchronize the store's state with the storage. Defaults to "load".
94
+ *
95
+ * Set to "attach" when using SSR to avoid hydration errors.
96
+ */
97
+ syncWithStorageOn?: "load" | "attach";
80
98
  };
81
99
  export type StoreConfig<TState, TActions> = BaseConfig<TState, TActions> & (PersistConfig<TState> | NoPersistConfig);
@@ -1,6 +1,6 @@
1
1
  import { SetState, StoreConfig } from "../types/types";
2
2
  export declare const createStorageAdapter: <TState, TActions>(config: StoreConfig<TState, TActions>, get: () => TState, set: SetState<TState>) => {
3
- onLoad: () => Promise<void>;
3
+ onLoad: () => void;
4
4
  onChange: (newState: TState) => Promise<void>;
5
5
  onAttach: () => void;
6
6
  onDetach: () => void;
@@ -10,24 +10,7 @@ const createStorageAdapter = (config, get, set) => {
10
10
  warn("No storage provider found. If this happened during SSR, you can safely ignore this warning.");
11
11
  return null;
12
12
  }
13
- const { key, serializer = JSON, initialState } = config;
14
- const initKey = `init_${key}`;
15
- const onLoad = async () => {
16
- try {
17
- let initialStateSnapshot = storage.getItem(initKey);
18
- const initialStateString = serializer.stringify(initialState);
19
- if (initialStateSnapshot instanceof Promise) {
20
- initialStateSnapshot = await initialStateSnapshot;
21
- }
22
- if (initialStateSnapshot !== initialStateString) {
23
- storage.setItem(initKey, initialStateString);
24
- storage.removeItem(key);
25
- }
26
- }
27
- catch {
28
- warn("Failed to initialize snapshots. If this happened during SSR, you can safely ignore this warning.");
29
- }
30
- };
13
+ const { key, serializer = JSON, syncWithStorageOn = "load" } = config;
31
14
  const syncWithSnapshot = async () => {
32
15
  try {
33
16
  let currentSnapshot = storage.getItem(key);
@@ -38,12 +21,20 @@ const createStorageAdapter = (config, get, set) => {
38
21
  set(serializer.parse(currentSnapshot));
39
22
  }
40
23
  }
41
- catch {
42
- warn("Failed to update state from snapshot");
24
+ catch (e) {
25
+ warn("Failed to sync state with snapshot. If this happened during SSR, you can safely ignore this warning.");
26
+ console.error(e);
27
+ }
28
+ };
29
+ const onLoad = () => {
30
+ if (syncWithStorageOn === "load") {
31
+ syncWithSnapshot();
43
32
  }
44
33
  };
45
34
  const onAttach = () => {
46
- syncWithSnapshot();
35
+ if (syncWithStorageOn === "attach") {
36
+ syncWithSnapshot();
37
+ }
47
38
  if (IS_BROWSER) {
48
39
  window.addEventListener("focus", syncWithSnapshot);
49
40
  }
@@ -59,8 +50,9 @@ const createStorageAdapter = (config, get, set) => {
59
50
  storage.setItem(key, newSnapshot);
60
51
  }
61
52
  }
62
- catch {
53
+ catch (e) {
63
54
  warn("Failed to update snapshot");
55
+ console.error(e);
64
56
  }
65
57
  };
66
58
  const onDetach = () => {
@@ -1 +1 @@
1
- {"version":3,"file":"createStorageAdapter.js","sources":["../../../src/internal/createStorageAdapter.ts"],"sourcesContent":["import { SetState, StorageAPI, StoreConfig } from \"../types/types\";\nimport { warn } from \"./warn\";\n\nexport const createStorageAdapter = <TState, TActions>(\n config: StoreConfig<TState, TActions>,\n get: () => TState,\n set: SetState<TState>,\n) => {\n if (!config.persist) {\n return null;\n }\n\n const IS_BROWSER = typeof window !== \"undefined\";\n\n const storage =\n config.storage ?? (IS_BROWSER ? (localStorage as StorageAPI) : undefined);\n\n if (!storage) {\n warn(\n \"No storage provider found. If this happened during SSR, you can safely ignore this warning.\",\n );\n return null;\n }\n\n const { key, serializer = JSON, initialState } = config;\n const initKey = `init_${key}`;\n\n const onLoad = async () => {\n try {\n let initialStateSnapshot = storage.getItem(initKey);\n const initialStateString = serializer.stringify(initialState);\n\n if (initialStateSnapshot instanceof Promise) {\n initialStateSnapshot = await initialStateSnapshot;\n }\n\n if (initialStateSnapshot !== initialStateString) {\n storage.setItem(initKey, initialStateString);\n storage.removeItem(key);\n }\n } catch {\n warn(\n \"Failed to initialize snapshots. If this happened during SSR, you can safely ignore this warning.\",\n );\n }\n };\n\n const syncWithSnapshot = async () => {\n try {\n let currentSnapshot = storage.getItem(key);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (currentSnapshot && currentSnapshot !== serializer.stringify(get())) {\n set(serializer.parse(currentSnapshot));\n }\n } catch {\n warn(\"Failed to update state from snapshot\");\n }\n };\n\n const onAttach = () => {\n syncWithSnapshot();\n\n if (IS_BROWSER) {\n window.addEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n const onChange = async (newState: TState) => {\n try {\n let currentSnapshot = storage.getItem(key);\n const newSnapshot = serializer.stringify(newState);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (newSnapshot !== currentSnapshot) {\n storage.setItem(key, newSnapshot);\n }\n } catch {\n warn(\"Failed to update snapshot\");\n }\n };\n\n const onDetach = () => {\n if (IS_BROWSER) {\n window.removeEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n return {\n onLoad,\n onChange,\n onAttach,\n onDetach,\n };\n};\n"],"names":[],"mappings":";;AAGO,MAAM,oBAAoB,GAAG,CAClC,MAAqC,EACrC,GAAiB,EACjB,GAAqB,KACnB;AACF,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CAAC,EAAE;gBACtE,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;YACxC;QACF;AAAE,QAAA,MAAM;YACN,IAAI,CAAC,sCAAsC,CAAC;QAC9C;AACF,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;AACpB,QAAA,gBAAgB,EAAE;QAElB,IAAI,UAAU,EAAE;AACd,YAAA,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,CAAC;QACpD;AACF,IAAA,CAAC;AAED,IAAA,MAAM,QAAQ,GAAG,OAAO,QAAgB,KAAI;AAC1C,QAAA,IAAI;YACF,IAAI,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC;YAC1C,MAAM,WAAW,GAAG,UAAU,CAAC,SAAS,CAAC,QAAQ,CAAC;AAElD,YAAA,IAAI,eAAe,YAAY,OAAO,EAAE;gBACtC,eAAe,GAAG,MAAM,eAAe;YACzC;AAEA,YAAA,IAAI,WAAW,KAAK,eAAe,EAAE;AACnC,gBAAA,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,CAAC;YACnC;QACF;AAAE,QAAA,MAAM;YACN,IAAI,CAAC,2BAA2B,CAAC;QACnC;AACF,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;QACpB,IAAI,UAAU,EAAE;AACd,YAAA,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,CAAC;QACvD;AACF,IAAA,CAAC;IAED,OAAO;QACL,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,QAAQ;KACT;AACH;;;;"}
1
+ {"version":3,"file":"createStorageAdapter.js","sources":["../../../src/internal/createStorageAdapter.ts"],"sourcesContent":["import { SetState, StorageAPI, StoreConfig } from \"../types/types\";\nimport { warn } from \"./warn\";\n\nexport const createStorageAdapter = <TState, TActions>(\n config: StoreConfig<TState, TActions>,\n get: () => TState,\n set: SetState<TState>,\n) => {\n if (!config.persist) {\n return null;\n }\n\n const IS_BROWSER = typeof window !== \"undefined\";\n\n const storage =\n config.storage ?? (IS_BROWSER ? (localStorage as StorageAPI) : undefined);\n\n if (!storage) {\n warn(\n \"No storage provider found. If this happened during SSR, you can safely ignore this warning.\",\n );\n return null;\n }\n\n const { key, serializer = JSON, syncWithStorageOn = \"load\" } = config;\n\n const syncWithSnapshot = async () => {\n try {\n let currentSnapshot = storage.getItem(key);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (currentSnapshot && currentSnapshot !== serializer.stringify(get())) {\n set(serializer.parse(currentSnapshot));\n }\n } catch (e) {\n warn(\n \"Failed to sync state with snapshot. If this happened during SSR, you can safely ignore this warning.\",\n );\n console.error(e);\n }\n };\n\n const onLoad = () => {\n if (syncWithStorageOn === \"load\") {\n syncWithSnapshot();\n }\n };\n\n const onAttach = () => {\n if (syncWithStorageOn === \"attach\") {\n syncWithSnapshot();\n }\n\n if (IS_BROWSER) {\n window.addEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n const onChange = async (newState: TState) => {\n try {\n let currentSnapshot = storage.getItem(key);\n const newSnapshot = serializer.stringify(newState);\n\n if (currentSnapshot instanceof Promise) {\n currentSnapshot = await currentSnapshot;\n }\n\n if (newSnapshot !== currentSnapshot) {\n storage.setItem(key, newSnapshot);\n }\n } catch (e) {\n warn(\"Failed to update snapshot\");\n console.error(e);\n }\n };\n\n const onDetach = () => {\n if (IS_BROWSER) {\n window.removeEventListener(\"focus\", syncWithSnapshot);\n }\n };\n\n return {\n onLoad,\n onChange,\n onAttach,\n onDetach,\n };\n};\n"],"names":[],"mappings":";;AAGO,MAAM,oBAAoB,GAAG,CAClC,MAAqC,EACrC,GAAiB,EACjB,GAAqB,KACnB;AACF,IAAA,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;AACnB,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,MAAM,UAAU,GAAG,OAAO,MAAM,KAAK,WAAW;AAEhD,IAAA,MAAM,OAAO,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,UAAU,CAAC,SAAS,CAAC,QAAQ,CAAC;AAElD,YAAA,IAAI,eAAe,YAAY,OAAO,EAAE;gBACtC,eAAe,GAAG,MAAM,eAAe;YACzC;AAEA,YAAA,IAAI,WAAW,KAAK,eAAe,EAAE;AACnC,gBAAA,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,CAAC;YACnC;QACF;QAAE,OAAO,CAAC,EAAE;YACV,IAAI,CAAC,2BAA2B,CAAC;AACjC,YAAA,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAClB;AACF,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;QACpB,IAAI,UAAU,EAAE;AACd,YAAA,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,CAAC;QACvD;AACF,IAAA,CAAC;IAED,OAAO;QACL,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,QAAQ;KACT;AACH;;;;"}
@@ -30,12 +30,17 @@ const createStore = (config) => {
30
30
  return state;
31
31
  };
32
32
  const listeners = new Set();
33
- const actions = config.actions?.({ set, get, reset });
33
+ const actions = config.actions?.({
34
+ set,
35
+ get,
36
+ reset,
37
+ initialState,
38
+ });
34
39
  const storageAdapter = createStorageAdapter(config, get, set);
35
40
  const subscribe = (listener) => {
36
41
  if (listeners.size === 0) {
37
42
  storageAdapter?.onAttach();
38
- onAttach?.({ state, set, reset });
43
+ onAttach?.({ state, set, reset, initialState });
39
44
  }
40
45
  listener(state);
41
46
  listeners.add(listener);
@@ -43,7 +48,7 @@ const createStore = (config) => {
43
48
  listeners.delete(listener);
44
49
  if (listeners.size === 0) {
45
50
  storageAdapter?.onDetach();
46
- onDetach?.({ state, set, reset });
51
+ onDetach?.({ state, set, reset, initialState });
47
52
  }
48
53
  };
49
54
  };
@@ -53,15 +58,19 @@ const createStore = (config) => {
53
58
  state,
54
59
  set: setSilently,
55
60
  reset: resetSilently,
61
+ initialState,
56
62
  });
57
63
  listeners.forEach((listener) => listener(state));
58
64
  };
59
65
  storageAdapter?.onLoad();
60
- onLoad?.({ state, set, reset });
66
+ onLoad?.({ state, set, reset, initialState });
61
67
  return {
62
68
  get,
63
69
  subscribe,
64
70
  actions,
71
+ set,
72
+ reset,
73
+ initialState,
65
74
  };
66
75
  };
67
76
 
@@ -1 +1 @@
1
- {"version":3,"file":"createStore.js","sources":["../../../src/lib/createStore.ts"],"sourcesContent":["import { createStorageAdapter } from \"../internal/createStorageAdapter\";\nimport { Listener, StateModifier, Store, StoreConfig } from \"../types/types\";\nimport { merge } from \"./merge\";\n\n/**\n * Creates a store with an initial state and actions that can modify the state.\n *\n * @param {StoreConfig<TState, TActions>} [config] - The configuration for the store.\n *\n * @returns {Store<TState, TActions>} The created store with state management methods.\n *\n * @see {@link https://dharma.fransek.dev/core/createstore/}\n */\nexport const createStore = <TState, TActions = undefined>(\n config: StoreConfig<TState, TActions>,\n): Store<TState, TActions> => {\n const { initialState, onLoad, onAttach, onDetach, onChange } = config;\n\n let state = initialState;\n\n const get = () => state;\n\n const setSilently = (stateModifier: StateModifier<TState>) => {\n state = merge(state, stateModifier);\n return state;\n };\n\n const set = (stateModifier: StateModifier<TState>) => {\n setSilently(stateModifier);\n dispatch();\n return state;\n };\n\n const resetSilently = () => setSilently(initialState);\n\n const reset = () => {\n resetSilently();\n dispatch();\n return state;\n };\n\n const listeners = new Set<Listener<TState>>();\n const actions = config.actions?.({ set, get, reset }) as TActions;\n const storageAdapter = createStorageAdapter(config, get, set);\n\n const subscribe = (listener: Listener<TState>) => {\n if (listeners.size === 0) {\n storageAdapter?.onAttach();\n onAttach?.({ state, set, reset });\n }\n\n listener(state);\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n storageAdapter?.onDetach();\n onDetach?.({ state, set, reset });\n }\n };\n };\n\n const dispatch = () => {\n storageAdapter?.onChange(state);\n onChange?.({\n state,\n set: setSilently,\n reset: resetSilently,\n });\n listeners.forEach((listener) => listener(state));\n };\n\n storageAdapter?.onLo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AAC,KAAK,CAAC;AACf,QAAA,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAEvB,QAAA,OAAO,MAAK;AACV,YAAA,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC;AAE1B,YAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;gBACxB,cAAc,EAAE,QAAQ,EAAE;gBAC1B,QAAQ,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;YACnC;AACF,QAAA,CAAC;AACH,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;AACpB,QAAA,cAAc,EAAE,QAAQ,CAAC,KAAK,CAAC;AAC/B,QAAA,QAAQ,GAAG;YACT,KAAK;AACL,YAAA,GAAG,EAAE,WAAW;AAChB,YAAA,KAAK,EAAE,aAAa;AACrB,SAAA,CAAC;AACF,QAAA,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC;AAClD,IAAA,CAAC;IAED,cAAc,EAAE,MAAM,EAAE;IACxB,MAAM,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;IAE/B,OAAO;QACL,GAAG;QACH,SAAS;QACT,OAAO;KACR;AACH;;;;"}
1
+ {"version":3,"file":"createStore.js","sources":["../../../src/lib/createStore.ts"],"sourcesContent":["import { createStorageAdapter } from \"../internal/createStorageAdapter\";\nimport { Listener, StateModifier, Store, StoreConfig } from \"../types/types\";\nimport { merge } from \"./merge\";\n\n/**\n * Creates a store with an initial state and actions that can modify the state.\n *\n * @param {StoreConfig<TState, TActions>} [config] - The configuration for the store.\n *\n * @returns {Store<TState, TActions>} The created store with state management methods.\n *\n * @see {@link https://dharma.fransek.dev/core/createstore/}\n */\nexport const createStore = <TState, TActions = undefined>(\n config: StoreConfig<TState, TActions>,\n): Store<TState, TActions> => {\n const { initialState, onLoad, onAttach, onDetach, onChange } = config;\n\n let state = initialState;\n\n const get = () => state;\n\n const setSilently = (stateModifier: StateModifier<TState>) => {\n state = merge(state, stateModifier);\n return state;\n };\n\n const set = (stateModifier: StateModifier<TState>) => {\n setSilently(stateModifier);\n dispatch();\n return state;\n };\n\n const resetSilently = () => setSilently(initialState);\n\n const reset = () => {\n resetSilently();\n dispatch();\n return state;\n };\n\n const listeners = new Set<Listener<TState>>();\n const actions = config.actions?.({\n set,\n get,\n reset,\n initialState,\n }) as TActions;\n const storageAdapter = createStorageAdapter(config, get, set);\n\n const subscribe = (listener: Listener<TState>) => {\n if (listeners.size === 0) {\n storageAdapter?.onAttach();\n onAttach?.({ state, set, reset, initialState });\n }\n\n listener(state);\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n storageAdapter?.onDetach();\n onDetach?.({ state, set, reset, initialState });\n }\n };\n };\n\n const dispatch = () => {\n storageAdapter?.onChange(state);\n onChange?.({\n state,\n set: setSilently,\n reset: resetSilently,\n initialState,\n });\n listeners.forEach((listener) => listener(state));\n };\n\n storageAdapter?.onLoad();\n onLoad?.({ state, set, reset, initialState });\n\n return {\n get,\n subscribe,\n actions,\n set,\n reset,\n initialState,\n };\n};\n"],"names":[],"mappings":";;;AAIA;;;;;;;;AAQG;AACI,MAAM,WAAW,GAAG,CACzB,MAAqC,KACV;AAC3B,IAAA,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,MAAM;IAErE,IAAI,KAAK,GAAG,YAAY;AAExB,IAAA,MAAM,GAAG,GAAG,MAAM,KAAK;AAEvB,IAAA,MAAM,WAAW,GAAG,CAAC,aAAoC,KAAI;AAC3D,QAAA,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,aAAa,CAAC;AACnC,QAAA,OAAO,KAAK;AACd,IAAA,CAAC;AAED,IAAA,MAAM,GAAG,GAAG,CAAC,aAAoC,KAAI;QACnD,WAAW,CAAC,aAAa,CAAC;AAC1B,QAAA,QAAQ,EAAE;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AY;AACb,SAAA,CAAC;AACF,QAAA,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC;AAClD,IAAA,CAAC;IAED,cAAc,EAAE,MAAM,EAAE;AACxB,IAAA,MAAM,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;IAE7C,OAAO;QACL,GAAG;QACH,SAAS;QACT,OAAO;QACP,GAAG;QACH,KAAK;QACL,YAAY;KACb;AACH;;;;"}
@@ -64,10 +64,8 @@ const derive = (store, deriveFn, dependencyFn) => {
64
64
  return {
65
65
  get,
66
66
  subscribe,
67
- actions: {
68
- mount,
69
- unmount,
70
- },
67
+ mount,
68
+ unmount,
71
69
  };
72
70
  };
73
71
 
@@ -1 +1 @@
1
- {"version":3,"file":"derive.js","sources":["../../../src/lib/derive.ts"],"sourcesContent":["import { DerivedStore, Listener, Store } from \"../types/types\";\nimport { deeplyEquals } from \"./deeplyEquals\";\n\n/**\n * Creates a derived store from an existing store.\n *\n * A derived store computes its state based on the original store's state using a derive function.\n * The derived store's value is memoized and only recomputed when requested.\n *\n * @param store - The original store to derive from\n * @param deriveFn - A function that computes the derived state from the original state\n * @param dependencyFn - Optional function that returns an array of dependencies. If provided, the derived state will only be recomputed when these dependencies change\n *\n * @returns A new store containing the derived state\n *\n * @see {@link https://dharma.fransek.dev/core/derive/}\n */\nexport const derive = <TState, TActions, TDerived>(\n store: Store<TState, TActions>,\n deriveFn: (state: TState) => TDerived,\n dependencyFn?: (state: TState) => unknown[],\n): DerivedStore<TDerived> => {\n let memo: TDerived | undefined;\n let prev: unknown[] | undefined;\n let isStale = true;\n let unsubscribe: (() => void) | undefined;\n const listeners = new Set<Listener<TDerived>>();\n\n const compute = () => {\n memo = deriveFn(store.get());\n isStale = false;\n return memo;\n };\n\n const get = () => {\n const next = dependencyFn?.(store.get());\n isStale &&= !prev || !deeplyEquals(prev, next);\n\n if (isStale) {\n prev = next;\n return compute();\n }\n\n return memo as TDerived;\n };\n\n const subscribe = (listener: Listener<TDerived>) => {\n if (listeners.size === 0) {\n mount();\n }\n\n listener(get());\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n unmount();\n }\n };\n };\n\n const listener = () => {\n isStale = true;\n listeners.forEach((listener) => listener(get()));\n };\n\n const mount = () => {\n if (!unsubscribe) {\n unsubscribe = store.subscribe(listener);\n }\n return unmount;\n };\n\n const unmount = () => {\n unsubscribe?.();\n unsubscribe = undefined;\n };\n\n return {\n get,\n subscribe,\n actions: {\n mount,\n unmount,\n },\n };\n};\n"],"names":[],"mappings":";;AAGA;;;;;;;;;;;;;AAaG;AACI,MAAM,MAAM,GAAG,CACpB,KAA8B,EAC9B,QAAqC,EACrC,YAA2C,KACjB;AAC1B,IAAA,IAAI,IAA0B;AAC9B,IAAA,IAAI,IAA2B;IAC/B,IAAI,OAAO,GAAG,IAAI;AAClB,IAAA,IAAI,WAAqC;AACzC,IAAA,MAAM,SAAS,GAAG,IAAI,GAAG,EAAsB;IAE/C,MAAM,OAAO,GAAG,MAAK;QACnB,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QAC5B,OAAO,GAAG,KAAK;AACf,QAAA,OAAO,IAAI;AACb,IAAA,CAAC;IAED,MAAM,GAAG,GAAG,MAAK;QACf,MAAM,IAAI,GAAG,YAAY,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC;QAE9C,IAAI,OAAO,EAAE;YACX,IAAI,GAAG,IAAI;YACX,OAAO,OAAO,EAAE;QAClB;AAEA,QAAA,OAAO,IAAgB;AACzB,IAAA,CAAC;AAED,IAAA,MAAM,SAAS,GAAG,CAAC,QAA4B,KAAI;AACjD,QAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;AACxB,YAAA,KAAK,EAAE;QACT;AAEA,QAAA,QAAQ,CAAC,GAAG,EAAE,CAAC;AACf,QAAA,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAEvB,QAAA,OAAO,MAAK;AACV,YAAA,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC;AAE1B,YAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;AACxB,gBAAA,OAAO,EAAE;YACX;AACF,QAAA,CAAC;AACH,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;QACpB,OAAO,GAAG,IAAI;AACd,QAAA,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC;AAClD,IAAA,CAAC;IAED,MAAM,KAAK,GAAG,MAAK;QACjB,IAAI,CAAC,WAAW,EAAE;AAChB,YAAA,WAAW,GAAG,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC;QACzC;AACA,QAAA,OAAO,OAAO;AAChB,IAAA,CAAC;IAED,MAAM,OAAO,GAAG,MAAK;QACnB,WAAW,IAAI;QACf,WAAW,GAAG,SAAS;AACzB,IAAA,CAAC;IAED,OAAO;QACL,GAAG;QACH,SAAS;AACT,QAAA,OAAO,EAAE;YACP,KAAK;YACL,OAAO;AACR,SAAA;KACF;AACH;;;;"}
1
+ {"version":3,"file":"derive.js","sources":["../../../src/lib/derive.ts"],"sourcesContent":["import { DerivedStore, Listener, Store } from \"../types/types\";\nimport { deeplyEquals } from \"./deeplyEquals\";\n\n/**\n * Creates a derived store from an existing store.\n *\n * A derived store computes its state based on the original store's state using a derive function.\n * The derived store's value is memoized and only recomputed when requested.\n *\n * @param store - The original store to derive from\n * @param deriveFn - A function that computes the derived state from the original state\n * @param dependencyFn - Optional function that returns an array of dependencies. If provided, the derived state will only be recomputed when these dependencies change\n *\n * @returns A new store containing the derived state\n *\n * @see {@link https://dharma.fransek.dev/core/derive/}\n */\nexport const derive = <TState, TActions, TDerived>(\n store: Store<TState, TActions>,\n deriveFn: (state: TState) => TDerived,\n dependencyFn?: (state: TState) => unknown[],\n): DerivedStore<TDerived> => {\n let memo: TDerived | undefined;\n let prev: unknown[] | undefined;\n let isStale = true;\n let unsubscribe: (() => void) | undefined;\n const listeners = new Set<Listener<TDerived>>();\n\n const compute = () => {\n memo = deriveFn(store.get());\n isStale = false;\n return memo;\n };\n\n const get = () => {\n const next = dependencyFn?.(store.get());\n isStale &&= !prev || !deeplyEquals(prev, next);\n\n if (isStale) {\n prev = next;\n return compute();\n }\n\n return memo as TDerived;\n };\n\n const subscribe = (listener: Listener<TDerived>) => {\n if (listeners.size === 0) {\n mount();\n }\n\n listener(get());\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n\n if (listeners.size === 0) {\n unmount();\n }\n };\n };\n\n const listener = () => {\n isStale = true;\n listeners.forEach((listener) => listener(get()));\n };\n\n const mount = () => {\n if (!unsubscribe) {\n unsubscribe = store.subscribe(listener);\n }\n return unmount;\n };\n\n const unmount = () => {\n unsubscribe?.();\n unsubscribe = undefined;\n };\n\n return {\n get,\n subscribe,\n mount,\n unmount,\n };\n};\n"],"names":[],"mappings":";;AAGA;;;;;;;;;;;;;AAaG;AACI,MAAM,MAAM,GAAG,CACpB,KAA8B,EAC9B,QAAqC,EACrC,YAA2C,KACjB;AAC1B,IAAA,IAAI,IAA0B;AAC9B,IAAA,IAAI,IAA2B;IAC/B,IAAI,OAAO,GAAG,IAAI;AAClB,IAAA,IAAI,WAAqC;AACzC,IAAA,MAAM,SAAS,GAAG,IAAI,GAAG,EAAsB;IAE/C,MAAM,OAAO,GAAG,MAAK;QACnB,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QAC5B,OAAO,GAAG,KAAK;AACf,QAAA,OAAO,IAAI;AACb,IAAA,CAAC;IAED,MAAM,GAAG,GAAG,MAAK;QACf,MAAM,IAAI,GAAG,YAAY,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC;QAE9C,IAAI,OAAO,EAAE;YACX,IAAI,GAAG,IAAI;YACX,OAAO,OAAO,EAAE;QAClB;AAEA,QAAA,OAAO,IAAgB;AACzB,IAAA,CAAC;AAED,IAAA,MAAM,SAAS,GAAG,CAAC,QAA4B,KAAI;AACjD,QAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;AACxB,YAAA,KAAK,EAAE;QACT;AAEA,QAAA,QAAQ,CAAC,GAAG,EAAE,CAAC;AACf,QAAA,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAEvB,QAAA,OAAO,MAAK;AACV,YAAA,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC;AAE1B,YAAA,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;AACxB,gBAAA,OAAO,EAAE;YACX;AACF,QAAA,CAAC;AACH,IAAA,CAAC;IAED,MAAM,QAAQ,GAAG,MAAK;QACpB,OAAO,GAAG,IAAI;AACd,QAAA,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC;AAClD,IAAA,CAAC;IAED,MAAM,KAAK,GAAG,MAAK;QACjB,IAAI,CAAC,WAAW,EAAE;AAChB,YAAA,WAAW,GAAG,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC;QACzC;AACA,QAAA,OAAO,OAAO;AAChB,IAAA,CAAC;IAED,MAAM,OAAO,GAAG,MAAK;QACnB,WAAW,IAAI;QACf,WAAW,GAAG,SAAS;AACzB,IAAA,CAAC;IAED,OAAO;QACL,GAAG;QACH,SAAS;QACT,KAAK;QACL,OAAO;KACR;AACH;;;;"}
@@ -7,14 +7,23 @@ export type Store<TState, TActions> = {
7
7
  actions: TActions;
8
8
  /** Subscribes to changes in the state of the store. Returns an unsubscribe function. */
9
9
  subscribe: (listener: Listener<TState>) => () => void;
10
+ /** Sets the state of the store. */
11
+ set: SetState<TState>;
12
+ /** Resets the state of the store to its initial value. */
13
+ reset: () => TState;
14
+ /** The initial state of the store. */
15
+ initialState: TState;
10
16
  };
11
- export type DerivedStoreActions = {
17
+ export type DerivedStore<TState> = {
18
+ /** Returns the current state of the store. */
19
+ get: () => TState;
20
+ /** Subscribes to changes in the state of the store. Returns an unsubscribe function. */
21
+ subscribe: (listener: Listener<TState>) => () => void;
12
22
  /** Start listening to changes in the original store. Called automatically on the first subscription. */
13
23
  mount: () => () => void;
14
24
  /** Stop listening to changes in the original store. Called automatically when there are no more subscribers. */
15
25
  unmount: () => void;
16
26
  };
17
- export type DerivedStore<TState> = Store<TState, DerivedStoreActions>;
18
27
  export type Effect = {
19
28
  /** Start listening to changes in the original store. */
20
29
  mount: () => () => void;
@@ -24,6 +33,8 @@ export type Effect = {
24
33
  export type StoreEventContext<TState> = {
25
34
  /** The current state of the store. */
26
35
  state: TState;
36
+ /** The initial state of the store. */
37
+ initialState: TState;
27
38
  /** Sets the state of the store. */
28
39
  set: SetState<TState>;
29
40
  /** Resets the state of the store to its initial value. */
@@ -38,6 +49,8 @@ export type ActionContext<TState> = {
38
49
  set: SetState<TState>;
39
50
  /** Resets the state of the store to its initial value. */
40
51
  reset: () => TState;
52
+ /** The initial state of the store. */
53
+ initialState: TState;
41
54
  };
42
55
  export type StoreActions<TState, TActions> = (context: ActionContext<TState>) => TActions;
43
56
  export type BaseConfig<TState, TActions> = {
@@ -58,7 +71,6 @@ export type MaybePromise<T> = T | Promise<T>;
58
71
  export type StorageAPI = {
59
72
  getItem: (key: string) => MaybePromise<string | null>;
60
73
  setItem: (key: string, value: string) => MaybePromise<void>;
61
- removeItem: (key: string) => MaybePromise<void>;
62
74
  };
63
75
  export type Serializer<T = any> = {
64
76
  stringify: (value: T) => string;
@@ -77,5 +89,11 @@ export type PersistConfig<TState> = {
77
89
  storage?: StorageAPI;
78
90
  /** The serializer to use for storing the state. Defaults to JSON. */
79
91
  serializer?: Serializer<TState>;
92
+ /**
93
+ * When to initially synchronize the store's state with the storage. Defaults to "load".
94
+ *
95
+ * Set to "attach" when using SSR to avoid hydration errors.
96
+ */
97
+ syncWithStorageOn?: "load" | "attach";
80
98
  };
81
99
  export type StoreConfig<TState, TActions> = BaseConfig<TState, TActions> & (PersistConfig<TState> | NoPersistConfig);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dharma-core",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "author": "Frans Ekman <fransedvinekman@gmail.com>",
5
5
  "license": "MIT",
6
6
  "description": "A simple and lightweight state management solution for JavaScript and TypeScript applications.",