@oxog/state 1.0.0 → 1.3.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.
package/dist/index.cjs CHANGED
@@ -29,7 +29,7 @@ function deepClone(value, seen) {
29
29
  const cloned = {};
30
30
  seen.set(value, cloned);
31
31
  for (const key in value) {
32
- if (Object.prototype.hasOwnProperty.call(value, key)) {
32
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(value, key)) {
33
33
  cloned[key] = deepClone(value[key], seen);
34
34
  }
35
35
  }
@@ -105,14 +105,14 @@ function deepMerge(target, source) {
105
105
  }
106
106
  const output = deepClone(target);
107
107
  for (const key in source) {
108
- if (Object.prototype.hasOwnProperty.call(source, key)) {
108
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(source, key)) {
109
109
  const sourceValue = source[key];
110
110
  const targetValue = output[key];
111
111
  if (sourceValue instanceof Date) {
112
112
  output[key] = new Date(sourceValue.getTime());
113
113
  continue;
114
114
  }
115
- if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date)) {
115
+ if (Object.prototype.hasOwnProperty.call(output, key) && sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date)) {
116
116
  output[key] = deepMerge(targetValue, sourceValue);
117
117
  } else {
118
118
  output[key] = cloneValue(sourceValue);
@@ -134,7 +134,7 @@ function cloneValue(value) {
134
134
  if (value.constructor === Object) {
135
135
  const cloned = {};
136
136
  for (const key in value) {
137
- if (Object.prototype.hasOwnProperty.call(value, key)) {
137
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(value, key)) {
138
138
  cloned[key] = cloneValue(value[key]);
139
139
  }
140
140
  }
@@ -482,12 +482,41 @@ var StoreError = class extends Error {
482
482
  }
483
483
  };
484
484
 
485
+ // src/batch.ts
486
+ function batch(fn) {
487
+ incrementBatchDepth();
488
+ try {
489
+ const result = fn();
490
+ decrementBatchDepth();
491
+ if (getBatchDepth() === 0) {
492
+ const storesArray = Array.from(getBatchManagedStores());
493
+ for (const s of storesArray) {
494
+ if ("flushNotifications" in s) {
495
+ s.flushNotifications();
496
+ }
497
+ }
498
+ clearBatchStores();
499
+ }
500
+ return result;
501
+ } catch (error) {
502
+ decrementBatchDepth();
503
+ const storesArray = Array.from(getBatchManagedStores());
504
+ for (const s of storesArray) {
505
+ if ("flushNotifications" in s) {
506
+ s.flushNotifications();
507
+ }
508
+ }
509
+ clearBatchStores();
510
+ throw error;
511
+ }
512
+ }
513
+
485
514
  // src/store.ts
486
515
  var StoreImpl = class {
487
516
  state;
488
517
  initialState;
489
518
  listeners = /* @__PURE__ */ new Set();
490
- selectorSubscriptions = /* @__PURE__ */ new Map();
519
+ selectorSubscriptions = /* @__PURE__ */ new Set();
491
520
  kernel;
492
521
  destroyed = false;
493
522
  batchDepth = 0;
@@ -495,6 +524,12 @@ var StoreImpl = class {
495
524
  queuedState = null;
496
525
  queuedPrevState = null;
497
526
  actions = {};
527
+ /** Incremented on every state change. */
528
+ version = 0;
529
+ /** True while listeners are being notified. */
530
+ notifying = false;
531
+ /** Notifications raised by listeners while notifying; delivered in order. */
532
+ notifyQueue = [];
498
533
  constructor(initialState, kernel) {
499
534
  this.state = deepClone(initialState);
500
535
  this.initialState = deepClone(initialState);
@@ -513,7 +548,10 @@ var StoreImpl = class {
513
548
  this.checkNotDestroyed();
514
549
  const prevState = this.state;
515
550
  const update = typeof partial === "function" ? partial(this.state) : partial;
516
- this.state = { ...this.state, ...update };
551
+ if (update === null || update === void 0) {
552
+ return;
553
+ }
554
+ this.state = { ...this.state, ...withoutProtoKey(update) };
517
555
  this.notifyOrQueue(this.state, prevState);
518
556
  }
519
557
  /** Deep merge state. */
@@ -533,35 +571,21 @@ var StoreImpl = class {
533
571
  subscribe(arg1, arg2, arg3) {
534
572
  this.checkNotDestroyed();
535
573
  if (arg2 === void 0 && typeof arg1 === "function") {
536
- const listener2 = arg1;
537
- this.listeners.add(listener2);
574
+ const subscription2 = { listener: arg1, since: this.version };
575
+ this.listeners.add(subscription2);
538
576
  return () => {
539
- this.listeners.delete(listener2);
540
- };
541
- }
542
- const selector2 = arg1;
543
- const listener = arg2;
544
- const equalityFn = arg3 || shallowEqual;
545
- let subscription = this.selectorSubscriptions.get(selector2);
546
- if (!subscription) {
547
- const initialValue = selector2(this.state);
548
- subscription = {
549
- value: initialValue,
550
- listeners: /* @__PURE__ */ new Set(),
551
- selector: selector2,
552
- equalityFn
577
+ this.listeners.delete(subscription2);
553
578
  };
554
- this.selectorSubscriptions.set(selector2, subscription);
555
579
  }
556
- subscription.listeners.add(listener);
580
+ const subscription = {
581
+ selector: arg1,
582
+ listener: arg2,
583
+ equalityFn: arg3 || shallowEqual,
584
+ value: arg1(this.state)
585
+ };
586
+ this.selectorSubscriptions.add(subscription);
557
587
  return () => {
558
- const sub = this.selectorSubscriptions.get(selector2);
559
- if (sub) {
560
- sub.listeners.delete(listener);
561
- if (sub.listeners.size === 0) {
562
- this.selectorSubscriptions.delete(selector2);
563
- }
564
- }
588
+ this.selectorSubscriptions.delete(subscription);
565
589
  };
566
590
  }
567
591
  /** Register a plugin. */
@@ -576,9 +600,12 @@ var StoreImpl = class {
576
600
  return;
577
601
  }
578
602
  this.destroyed = true;
579
- this.kernel.destroy();
603
+ this.kernel.destroy().catch((error) => {
604
+ console.error("Error destroying store plugins:", error);
605
+ });
580
606
  this.listeners.clear();
581
607
  this.selectorSubscriptions.clear();
608
+ this.notifyQueue = [];
582
609
  this.actions = {};
583
610
  }
584
611
  /** Add an action (for fluent builder pattern). */
@@ -586,6 +613,15 @@ var StoreImpl = class {
586
613
  this.actions[name] = fn;
587
614
  return this;
588
615
  }
616
+ /**
617
+ * Expose a bound action on the state object (and on the initial state, so
618
+ * `reset()` keeps it). Construction-time only: no notification is sent.
619
+ */
620
+ exposeAction(name, fn) {
621
+ if (name === "__proto__") return;
622
+ this.state = { ...this.state, [name]: fn };
623
+ this.initialState = { ...this.initialState, [name]: fn };
624
+ }
589
625
  /** Get all actions. */
590
626
  getActions() {
591
627
  return this.actions;
@@ -598,6 +634,7 @@ var StoreImpl = class {
598
634
  }
599
635
  /** Notify listeners or queue if batching. */
600
636
  notifyOrQueue(state, prevState) {
637
+ this.version++;
601
638
  const inGlobalBatch = sharedBatchContext.isBatching();
602
639
  if (inGlobalBatch) {
603
640
  const managedStores = sharedBatchContext.managedStores;
@@ -615,38 +652,70 @@ var StoreImpl = class {
615
652
  this.notify(state, prevState);
616
653
  }
617
654
  }
618
- /** Notify all listeners. */
655
+ /**
656
+ * Notify all listeners.
657
+ *
658
+ * Re-entrant updates (a listener calling setState) are queued and delivered
659
+ * after the current pass, so every listener sees changes in order and ends
660
+ * on the latest state.
661
+ */
619
662
  notify(state, prevState) {
663
+ this.notifyQueue.push({ state, prevState, version: this.version });
664
+ if (this.notifying) {
665
+ return;
666
+ }
667
+ this.notifying = true;
668
+ try {
669
+ let next;
670
+ while ((next = this.notifyQueue.shift()) !== void 0) {
671
+ this.deliver(next);
672
+ }
673
+ } finally {
674
+ this.notifying = false;
675
+ this.notifyQueue = [];
676
+ }
677
+ }
678
+ /** Deliver one notification to plugins and listeners. */
679
+ deliver({ state, prevState, version }) {
620
680
  this.kernel.emitStateChange(state, prevState);
621
- for (const listener of this.listeners) {
681
+ for (const subscription of Array.from(this.listeners)) {
682
+ if (!this.listeners.has(subscription) || subscription.since >= version) {
683
+ continue;
684
+ }
622
685
  try {
623
- listener(state, prevState);
686
+ subscription.listener(state, prevState);
624
687
  } catch (error) {
625
688
  this.kernel.emitError(error);
626
689
  }
627
690
  }
628
- for (const subscription of this.selectorSubscriptions.values()) {
629
- const newValue = subscription.selector(state);
630
- if (!subscription.equalityFn(newValue, subscription.value)) {
691
+ for (const subscription of Array.from(this.selectorSubscriptions)) {
692
+ if (!this.selectorSubscriptions.has(subscription)) {
693
+ continue;
694
+ }
695
+ try {
696
+ const newValue = subscription.selector(state);
697
+ if (subscription.equalityFn(newValue, subscription.value)) {
698
+ continue;
699
+ }
631
700
  const prevValue = subscription.value;
632
701
  subscription.value = newValue;
633
- for (const listener of subscription.listeners) {
634
- try {
635
- listener(newValue, prevValue);
636
- } catch (error) {
637
- this.kernel.emitError(error);
638
- }
639
- }
702
+ subscription.listener(newValue, prevValue);
703
+ } catch (error) {
704
+ this.kernel.emitError(error);
640
705
  }
641
706
  }
642
707
  }
643
708
  /** Flush pending notifications (end of batch). */
644
709
  flushNotifications() {
645
710
  if (this.pendingNotify) {
646
- this.notify(this.queuedState, this.queuedPrevState);
711
+ const state = this.queuedState;
712
+ const prevState = this.queuedPrevState;
647
713
  this.pendingNotify = false;
648
714
  this.queuedState = null;
649
715
  this.queuedPrevState = null;
716
+ if (!this.destroyed) {
717
+ this.notify(state, prevState);
718
+ }
650
719
  }
651
720
  }
652
721
  /** Start batching. */
@@ -661,6 +730,16 @@ var StoreImpl = class {
661
730
  }
662
731
  }
663
732
  };
733
+ function withoutProtoKey(update) {
734
+ if (update !== null && typeof update === "object" && Object.prototype.hasOwnProperty.call(update, "__proto__")) {
735
+ const copy = {};
736
+ for (const key of Object.keys(update)) {
737
+ if (key !== "__proto__") copy[key] = update[key];
738
+ }
739
+ return copy;
740
+ }
741
+ return update;
742
+ }
664
743
  var StoreBuilderImpl = class {
665
744
  store;
666
745
  constructor(initialState, kernel) {
@@ -694,9 +773,8 @@ var StoreBuilderImpl = class {
694
773
  }
695
774
  action(name, fn) {
696
775
  this.store.addAction(name, fn);
697
- this[name] = (...args) => {
698
- const currentState = this.getState();
699
- const result = fn(currentState, ...args);
776
+ const bound = (...args) => {
777
+ const result = fn(this.getState(), ...args);
700
778
  if (result instanceof Promise) {
701
779
  return result.then((partial) => {
702
780
  this.setState(partial);
@@ -706,6 +784,9 @@ var StoreBuilderImpl = class {
706
784
  this.setState(result);
707
785
  return result;
708
786
  };
787
+ Object.defineProperty(bound, "name", { value: name, configurable: true });
788
+ this[name] = bound;
789
+ this.store.exposeAction(name, bound);
709
790
  return this;
710
791
  }
711
792
  /** Add action (internal use). */
@@ -732,35 +813,21 @@ var StoreBuilderImpl = class {
732
813
  };
733
814
  function createStore(initialState, actions) {
734
815
  const kernel = createKernel({ name: "store" });
735
- const state = { ...initialState };
816
+ const state = {};
736
817
  const extractedActions = {};
737
- for (const key in state) {
738
- if (isFunction(state[key]) && key.startsWith("$")) {
739
- extractedActions[key.substring(1)] = state[key];
740
- delete state[key];
818
+ for (const key of Object.keys(initialState)) {
819
+ const value = initialState[key];
820
+ if (key === "__proto__") continue;
821
+ if (isFunction(value) && key.startsWith("$")) {
822
+ extractedActions[key.substring(1)] = value;
823
+ } else {
824
+ state[key] = value;
741
825
  }
742
826
  }
743
827
  const allActions = { ...extractedActions, ...actions };
744
828
  const builder = new StoreBuilderImpl(state, kernel);
745
- if (allActions) {
746
- for (const [name, fn] of Object.entries(allActions)) {
747
- builder.addAction(name, fn);
748
- }
749
- }
750
- const actionList = builder.getActions();
751
- for (const [name, fn] of Object.entries(actionList)) {
752
- builder[name] = (...args) => {
753
- const currentState = builder.getState();
754
- const result = fn(currentState, ...args);
755
- if (result instanceof Promise) {
756
- return result.then((partial) => {
757
- builder.setState(partial);
758
- return partial;
759
- });
760
- }
761
- builder.setState(result);
762
- return result;
763
- };
829
+ for (const [name, fn] of Object.entries(allActions)) {
830
+ builder.action(name, fn);
764
831
  }
765
832
  kernel.initializeAll(builder).catch((error) => {
766
833
  console.error("Error initializing plugins:", error);
@@ -793,57 +860,55 @@ function createStore(initialState, actions) {
793
860
  }
794
861
  });
795
862
  }
796
- function batch(fn) {
797
- return fn();
798
- }
799
863
  function useStore(store, selector2 = identity, equalityFn = shallowEqual) {
800
864
  const selectorRef = react.useRef(selector2);
801
865
  const equalityFnRef = react.useRef(equalityFn);
802
- const storeRef = react.useRef(store);
803
- if (selectorRef.current !== selector2) {
804
- selectorRef.current = selector2;
805
- }
806
- if (equalityFnRef.current !== equalityFn) {
807
- equalityFnRef.current = equalityFn;
808
- }
809
- if (storeRef.current !== store) {
810
- storeRef.current = store;
811
- }
812
- const getSnapshot = () => {
813
- const state = storeRef.current.getState();
814
- return selectorRef.current(state);
815
- };
816
- const getServerSnapshot = getSnapshot;
817
- const subscribe = (callback) => {
818
- const unsubscribe = storeRef.current.subscribe(
819
- (state) => selectorRef.current(state),
820
- (value, prevValue) => {
821
- if (!equalityFnRef.current(value, prevValue)) {
822
- callback();
823
- }
824
- },
825
- equalityFnRef.current
826
- );
827
- return unsubscribe;
828
- };
829
- const selectedState = react.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
866
+ selectorRef.current = selector2;
867
+ equalityFnRef.current = equalityFn;
868
+ const cacheRef = react.useRef(null);
869
+ const getSnapshot = react.useCallback(() => {
870
+ const state = store.getState();
871
+ const currentSelector = selectorRef.current;
872
+ const cache = cacheRef.current;
873
+ if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {
874
+ return cache.selected;
875
+ }
876
+ const next = currentSelector(state);
877
+ if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {
878
+ cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };
879
+ return cache.selected;
880
+ }
881
+ cacheRef.current = { store, state, selector: currentSelector, selected: next };
882
+ return next;
883
+ }, [store]);
884
+ const subscribe = react.useCallback((callback) => store.subscribe(() => callback()), [store]);
885
+ const selectedState = react.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
830
886
  react.useDebugValue(selectedState);
831
887
  return selectedState;
832
888
  }
833
889
  function useCreateStore(initialState) {
834
890
  const storeRef = react.useRef();
891
+ const pendingDestroyRef = react.useRef(null);
835
892
  if (storeRef.current === void 0) {
836
893
  storeRef.current = createStore(initialState);
837
894
  }
895
+ const store = storeRef.current;
838
896
  react.useEffect(() => {
897
+ pendingDestroyRef.current = null;
839
898
  return () => {
840
- if (storeRef.current) {
841
- storeRef.current.destroy();
842
- storeRef.current = void 0;
843
- }
899
+ const token = {};
900
+ pendingDestroyRef.current = token;
901
+ queueMicrotask(() => {
902
+ if (pendingDestroyRef.current === token) {
903
+ store.destroy();
904
+ if (storeRef.current === store) {
905
+ storeRef.current = void 0;
906
+ }
907
+ }
908
+ });
844
909
  };
845
- }, []);
846
- return storeRef.current;
910
+ }, [store]);
911
+ return store;
847
912
  }
848
913
  function useAction(store, actionName) {
849
914
  const storeRef = react.useRef(store);
@@ -857,159 +922,1129 @@ function useAction(store, actionName) {
857
922
  }
858
923
  return actionRef.current;
859
924
  }
925
+ function useShallow(selector2) {
926
+ const prev = react.useRef();
927
+ return (state) => {
928
+ const next = selector2(state);
929
+ if (prev.current === void 0) {
930
+ prev.current = next;
931
+ return next;
932
+ }
933
+ if (shallowCompareObjects(prev.current, next)) {
934
+ return prev.current;
935
+ }
936
+ prev.current = next;
937
+ return next;
938
+ };
939
+ }
940
+ function shallowCompareObjects(a, b) {
941
+ if (a === b) return true;
942
+ if (typeof a !== "object" || typeof b !== "object") return false;
943
+ if (a === null || b === null) return false;
944
+ const keysA = Object.keys(a);
945
+ const keysB = Object.keys(b);
946
+ if (keysA.length !== keysB.length) return false;
947
+ for (const key of keysA) {
948
+ if (a[key] !== b[key]) {
949
+ return false;
950
+ }
951
+ }
952
+ return true;
953
+ }
954
+ function useStoreActions(store, ...actionNames) {
955
+ const storeRef = react.useRef(store);
956
+ const actionsRef = react.useRef({});
957
+ if (storeRef.current !== store) {
958
+ storeRef.current = store;
959
+ actionsRef.current = {};
960
+ }
961
+ const result = {};
962
+ for (const name of actionNames) {
963
+ if (!actionsRef.current[name]) {
964
+ actionsRef.current[name] = storeRef.current[name];
965
+ }
966
+ result[name] = actionsRef.current[name];
967
+ }
968
+ return result;
969
+ }
970
+ function useStoreSelector(store, selectors) {
971
+ const prevResultRef = react.useRef(null);
972
+ const combinedSelector = react.useCallback((state) => {
973
+ const keys = Object.keys(selectors);
974
+ const result = {};
975
+ for (const key of keys) {
976
+ const selector2 = selectors[key];
977
+ if (selector2) {
978
+ result[key] = selector2(state);
979
+ }
980
+ }
981
+ const prev = prevResultRef.current;
982
+ if (prev !== null && Object.keys(prev).length === keys.length) {
983
+ let isEqual = true;
984
+ for (const key of keys) {
985
+ if (!(key in prev) || !shallowEqual(prev[key], result[key])) {
986
+ isEqual = false;
987
+ break;
988
+ }
989
+ }
990
+ if (isEqual) {
991
+ return prev;
992
+ }
993
+ }
994
+ prevResultRef.current = result;
995
+ return result;
996
+ }, [selectors]);
997
+ return useStore(store, combinedSelector);
998
+ }
999
+ function useTransientSubscribe(store, selector2, callback, equalityFn = shallowEqual) {
1000
+ const callbackRef = react.useRef(callback);
1001
+ const selectorRef = react.useRef(selector2);
1002
+ const equalityFnRef = react.useRef(equalityFn);
1003
+ callbackRef.current = callback;
1004
+ selectorRef.current = selector2;
1005
+ equalityFnRef.current = equalityFn;
1006
+ react.useEffect(() => {
1007
+ const unsubscribe = store.subscribe(
1008
+ (state) => selectorRef.current(state),
1009
+ (value, prevValue) => callbackRef.current(value, prevValue),
1010
+ (a, b) => equalityFnRef.current(a, b)
1011
+ );
1012
+ return unsubscribe;
1013
+ }, [store]);
1014
+ }
1015
+ function useSetState(store) {
1016
+ const storeRef = react.useRef(store);
1017
+ if (storeRef.current !== store) {
1018
+ storeRef.current = store;
1019
+ }
1020
+ const setStateRef = react.useRef((partial) => {
1021
+ storeRef.current.setState(partial);
1022
+ });
1023
+ return setStateRef.current;
1024
+ }
860
1025
 
861
- // src/plugins/persist.ts
862
- var defaultStorage = {
863
- getItem: (key) => {
864
- if (typeof window === "undefined") return null;
865
- try {
866
- return window.localStorage.getItem(key);
867
- } catch {
868
- return null;
1026
+ // src/subscribe.ts
1027
+ function createDebounced(fn, delay2) {
1028
+ let timeoutId = null;
1029
+ const debounced = ((...args) => {
1030
+ if (timeoutId) {
1031
+ clearTimeout(timeoutId);
869
1032
  }
870
- },
871
- setItem: (key, value) => {
872
- if (typeof window === "undefined") return;
873
- try {
874
- window.localStorage.setItem(key, value);
875
- } catch {
1033
+ timeoutId = setTimeout(() => {
1034
+ fn(...args);
1035
+ timeoutId = null;
1036
+ }, delay2);
1037
+ });
1038
+ debounced.cancel = () => {
1039
+ if (timeoutId) {
1040
+ clearTimeout(timeoutId);
1041
+ timeoutId = null;
1042
+ }
1043
+ };
1044
+ return debounced;
1045
+ }
1046
+ function createThrottled(fn, delay2) {
1047
+ let lastCall = 0;
1048
+ let timeoutId = null;
1049
+ let lastArgs = null;
1050
+ const throttled = ((...args) => {
1051
+ const now = Date.now();
1052
+ const remaining = delay2 - (now - lastCall);
1053
+ lastArgs = args;
1054
+ if (remaining <= 0) {
1055
+ if (timeoutId) {
1056
+ clearTimeout(timeoutId);
1057
+ timeoutId = null;
1058
+ }
1059
+ lastCall = now;
1060
+ fn(...args);
1061
+ } else if (!timeoutId) {
1062
+ timeoutId = setTimeout(() => {
1063
+ lastCall = Date.now();
1064
+ timeoutId = null;
1065
+ if (lastArgs) {
1066
+ fn(...lastArgs);
1067
+ }
1068
+ }, remaining);
1069
+ }
1070
+ });
1071
+ throttled.cancel = () => {
1072
+ if (timeoutId) {
1073
+ clearTimeout(timeoutId);
1074
+ timeoutId = null;
1075
+ }
1076
+ lastArgs = null;
1077
+ };
1078
+ return throttled;
1079
+ }
1080
+ function subscribeWithOptions(store, selector2, listener, options = {}) {
1081
+ const {
1082
+ equalityFn = shallowEqual,
1083
+ fireImmediately = false,
1084
+ debounce,
1085
+ throttle,
1086
+ when
1087
+ } = options;
1088
+ if (debounce !== void 0 && throttle !== void 0) {
1089
+ throw new Error("Cannot use both debounce and throttle options");
1090
+ }
1091
+ let wrappedListener = listener;
1092
+ let cleanup = null;
1093
+ if (debounce !== void 0 && debounce > 0) {
1094
+ const debouncedListener = createDebounced(listener, debounce);
1095
+ wrappedListener = debouncedListener;
1096
+ cleanup = () => debouncedListener.cancel();
1097
+ } else if (throttle !== void 0 && throttle > 0) {
1098
+ const throttledListener = createThrottled(listener, throttle);
1099
+ wrappedListener = throttledListener;
1100
+ cleanup = () => throttledListener.cancel();
1101
+ }
1102
+ let finalListener;
1103
+ let prevState = store.getState();
1104
+ if (when) {
1105
+ finalListener = (value, prevValue) => {
1106
+ const currentState = store.getState();
1107
+ if (when(currentState, prevState)) {
1108
+ wrappedListener(value, prevValue);
1109
+ }
1110
+ prevState = currentState;
1111
+ };
1112
+ } else {
1113
+ finalListener = wrappedListener;
1114
+ }
1115
+ if (fireImmediately) {
1116
+ const currentValue = selector2(store.getState());
1117
+ finalListener(currentValue, currentValue);
1118
+ }
1119
+ const unsubscribe = store.subscribe(selector2, finalListener, equalityFn);
1120
+ return () => {
1121
+ unsubscribe();
1122
+ if (cleanup) {
1123
+ cleanup();
1124
+ }
1125
+ };
1126
+ }
1127
+ function createSubscriber(defaultOptions = {}) {
1128
+ return (store, selector2, listener, options = {}) => {
1129
+ return subscribeWithOptions(store, selector2, listener, {
1130
+ ...defaultOptions,
1131
+ ...options
1132
+ });
1133
+ };
1134
+ }
1135
+ function subscribeToMany(store, selectors, listener, options = {}) {
1136
+ const keys = Object.keys(selectors);
1137
+ const state = store.getState();
1138
+ for (const key of keys) {
1139
+ const selector2 = selectors[key];
1140
+ if (selector2) {
1141
+ selector2(state);
876
1142
  }
877
- },
878
- /* c8 ignore next 3 */
879
- removeItem: () => {
880
1143
  }
881
- };
882
- var sessionStorage = {
883
- getItem: (key) => {
884
- if (typeof window === "undefined") return null;
885
- try {
886
- return window.sessionStorage.getItem(key);
887
- } catch {
888
- return null;
1144
+ const combinedSelector = (state2) => {
1145
+ const result = {};
1146
+ for (const key of keys) {
1147
+ const selector2 = selectors[key];
1148
+ if (selector2) {
1149
+ result[key] = selector2(state2);
1150
+ }
889
1151
  }
890
- },
891
- setItem: (key, value) => {
892
- if (typeof window === "undefined") return;
893
- try {
894
- window.sessionStorage.setItem(key, value);
895
- } catch {
1152
+ return result;
1153
+ };
1154
+ const combinedEqualityFn = (a, b) => {
1155
+ for (const key of keys) {
1156
+ if (!shallowEqual(a[key], b[key])) {
1157
+ return false;
1158
+ }
896
1159
  }
897
- },
898
- removeItem: (key) => {
899
- if (typeof window === "undefined") return;
900
- try {
901
- window.sessionStorage.removeItem(key);
902
- } catch {
1160
+ return true;
1161
+ };
1162
+ return subscribeWithOptions(
1163
+ store,
1164
+ combinedSelector,
1165
+ listener,
1166
+ { ...options, equalityFn: combinedEqualityFn }
1167
+ );
1168
+ }
1169
+ function subscribeOnce(store, selector2, listener, options = {}) {
1170
+ let unsubscribe = null;
1171
+ let fired = false;
1172
+ const onceListener = (value, prevValue) => {
1173
+ if (fired) return;
1174
+ fired = true;
1175
+ listener(value, prevValue);
1176
+ if (unsubscribe) {
1177
+ unsubscribe();
903
1178
  }
1179
+ };
1180
+ unsubscribe = subscribeWithOptions(store, selector2, onceListener, options);
1181
+ if (fired) {
1182
+ unsubscribe();
904
1183
  }
905
- };
906
- function persist(options) {
907
- const { key, storage = defaultStorage, whitelist, blacklist } = options;
908
- return {
909
- name: "persist",
910
- version: "1.0.0",
911
- install(store) {
1184
+ return unsubscribe;
1185
+ }
1186
+
1187
+ // src/computed.ts
1188
+ function computed(store, selector2, options = {}) {
1189
+ const { equals = shallowEqual, lazy = false, cacheSize = 1 } = options;
1190
+ const cache = [];
1191
+ let currentValue;
1192
+ let notifiedValue;
1193
+ let computedFrom;
1194
+ let isInitialized = false;
1195
+ let isDestroyed = false;
1196
+ const listeners = /* @__PURE__ */ new Set();
1197
+ let unsubscribe = null;
1198
+ const compute = (state) => {
1199
+ for (const entry of cache) {
1200
+ if (entry.input === state || shallowEqual(entry.input, state)) {
1201
+ return entry.output;
1202
+ }
1203
+ }
1204
+ const newValue = selector2(state);
1205
+ cache.unshift({ input: state, output: newValue });
1206
+ while (cache.length > cacheSize) {
1207
+ cache.pop();
1208
+ }
1209
+ return newValue;
1210
+ };
1211
+ const refresh = () => {
1212
+ const state = store.getState();
1213
+ if (isInitialized && state === computedFrom) return;
1214
+ const newValue = compute(state);
1215
+ if (!isInitialized || !equals(newValue, currentValue)) {
1216
+ currentValue = newValue;
1217
+ }
1218
+ computedFrom = state;
1219
+ };
1220
+ const emit = () => {
1221
+ const prevValue = notifiedValue;
1222
+ const value = currentValue;
1223
+ if (equals(value, prevValue)) return;
1224
+ notifiedValue = value;
1225
+ for (const listener of Array.from(listeners)) {
912
1226
  try {
913
- const saved = storage.getItem(key);
914
- if (saved) {
915
- const parsed = JSON.parse(saved);
916
- store.merge(parsed);
917
- }
1227
+ listener(value, prevValue);
918
1228
  } catch (error) {
919
- console.error(`Failed to hydrate state from '${key}':`, error);
1229
+ console.error("Computed listener error:", error);
920
1230
  }
921
- store.subscribe((state) => {
1231
+ }
1232
+ };
1233
+ const initialize = () => {
1234
+ if (isInitialized || isDestroyed) return;
1235
+ refresh();
1236
+ isInitialized = true;
1237
+ notifiedValue = currentValue;
1238
+ unsubscribe = store.subscribe(() => {
1239
+ refresh();
1240
+ emit();
1241
+ });
1242
+ };
1243
+ if (!lazy) {
1244
+ initialize();
1245
+ }
1246
+ const get = () => {
1247
+ if (isDestroyed) {
1248
+ throw new Error("Cannot access destroyed computed value");
1249
+ }
1250
+ if (!isInitialized) {
1251
+ initialize();
1252
+ } else {
1253
+ refresh();
1254
+ }
1255
+ return currentValue;
1256
+ };
1257
+ const invalidate = () => {
1258
+ if (isDestroyed) return;
1259
+ cache.length = 0;
1260
+ if (isInitialized) {
1261
+ const state = store.getState();
1262
+ const newValue = compute(state);
1263
+ computedFrom = state;
1264
+ if (!equals(newValue, currentValue)) {
1265
+ currentValue = newValue;
1266
+ }
1267
+ emit();
1268
+ }
1269
+ };
1270
+ const subscribe = (listener) => {
1271
+ if (isDestroyed) {
1272
+ throw new Error("Cannot subscribe to destroyed computed value");
1273
+ }
1274
+ if (!isInitialized) {
1275
+ initialize();
1276
+ }
1277
+ listeners.add(listener);
1278
+ return () => {
1279
+ listeners.delete(listener);
1280
+ };
1281
+ };
1282
+ const getHistory = () => {
1283
+ return cache.map((entry) => entry.output);
1284
+ };
1285
+ const destroy = () => {
1286
+ if (isDestroyed) return;
1287
+ isDestroyed = true;
1288
+ if (unsubscribe) {
1289
+ unsubscribe();
1290
+ unsubscribe = null;
1291
+ }
1292
+ listeners.clear();
1293
+ cache.length = 0;
1294
+ currentValue = void 0;
1295
+ notifiedValue = void 0;
1296
+ computedFrom = void 0;
1297
+ };
1298
+ const computedFn = get;
1299
+ computedFn.get = get;
1300
+ computedFn.invalidate = invalidate;
1301
+ computedFn.subscribe = subscribe;
1302
+ computedFn.getHistory = getHistory;
1303
+ computedFn.destroy = destroy;
1304
+ return computedFn;
1305
+ }
1306
+ function combineComputed(computeds, combiner, options = {}) {
1307
+ const { equals = shallowEqual, cacheSize = 1 } = options;
1308
+ let currentValue;
1309
+ let isDestroyed = false;
1310
+ const listeners = /* @__PURE__ */ new Set();
1311
+ const unsubscribes = [];
1312
+ const cache = [];
1313
+ const compute = () => {
1314
+ const values = computeds.map((c) => c());
1315
+ return combiner(values);
1316
+ };
1317
+ let notifiedValue;
1318
+ const refresh = () => {
1319
+ const newValue = compute();
1320
+ if (!equals(newValue, currentValue)) {
1321
+ currentValue = newValue;
1322
+ cache.unshift(newValue);
1323
+ while (cache.length > cacheSize) {
1324
+ cache.pop();
1325
+ }
1326
+ }
1327
+ };
1328
+ currentValue = compute();
1329
+ cache.push(currentValue);
1330
+ notifiedValue = currentValue;
1331
+ for (const computed2 of computeds) {
1332
+ const unsub = computed2.subscribe(() => {
1333
+ if (isDestroyed) return;
1334
+ refresh();
1335
+ const prevValue = notifiedValue;
1336
+ const value = currentValue;
1337
+ if (equals(value, prevValue)) return;
1338
+ notifiedValue = value;
1339
+ for (const listener of Array.from(listeners)) {
922
1340
  try {
923
- let toSave = state;
924
- if (whitelist) {
925
- toSave = pick(state, whitelist);
926
- } else if (blacklist) {
927
- toSave = omit(state, blacklist);
928
- }
929
- storage.setItem(key, JSON.stringify(toSave));
1341
+ listener(value, prevValue);
930
1342
  } catch (error) {
931
- console.error(`Failed to persist state to '${key}':`, error);
1343
+ console.error("Combined computed listener error:", error);
932
1344
  }
933
- });
934
- },
935
- onDestroy() {
1345
+ }
1346
+ });
1347
+ unsubscribes.push(unsub);
1348
+ }
1349
+ const get = () => {
1350
+ if (isDestroyed) {
1351
+ throw new Error("Cannot access destroyed computed value");
1352
+ }
1353
+ refresh();
1354
+ return currentValue;
1355
+ };
1356
+ const invalidate = () => {
1357
+ if (isDestroyed) return;
1358
+ for (const computed2 of computeds) {
1359
+ computed2.invalidate();
1360
+ }
1361
+ };
1362
+ const subscribe = (listener) => {
1363
+ if (isDestroyed) {
1364
+ throw new Error("Cannot subscribe to destroyed computed value");
1365
+ }
1366
+ listeners.add(listener);
1367
+ return () => listeners.delete(listener);
1368
+ };
1369
+ const getHistory = () => [...cache];
1370
+ const destroy = () => {
1371
+ if (isDestroyed) return;
1372
+ isDestroyed = true;
1373
+ for (const unsub of unsubscribes) {
1374
+ unsub();
936
1375
  }
1376
+ listeners.clear();
1377
+ cache.length = 0;
937
1378
  };
1379
+ const combinedFn = get;
1380
+ combinedFn.get = get;
1381
+ combinedFn.invalidate = invalidate;
1382
+ combinedFn.subscribe = subscribe;
1383
+ combinedFn.getHistory = getHistory;
1384
+ combinedFn.destroy = destroy;
1385
+ return combinedFn;
938
1386
  }
939
- function createStorage(storage) {
940
- return storage;
1387
+ function memoizeSelector(selector2, equals = shallowEqual) {
1388
+ let lastState;
1389
+ let lastResult;
1390
+ let isInitialized = false;
1391
+ return (state) => {
1392
+ if (!isInitialized || lastState !== state) {
1393
+ const newResult = selector2(state);
1394
+ if (!isInitialized || !equals(newResult, lastResult)) {
1395
+ lastResult = newResult;
1396
+ }
1397
+ lastState = state;
1398
+ isInitialized = true;
1399
+ }
1400
+ return lastResult;
1401
+ };
941
1402
  }
942
1403
 
943
- // src/plugins/devtools.ts
944
- function hasDevtools() {
945
- return typeof window !== "undefined" && !!window.__REDUX_DEVTOOLS_EXTENSION__;
1404
+ // src/slices.ts
1405
+ var sliceRegistry = /* @__PURE__ */ new WeakMap();
1406
+ function registerSlice(store, name, data) {
1407
+ let slices = sliceRegistry.get(store);
1408
+ if (!slices) {
1409
+ slices = /* @__PURE__ */ new Map();
1410
+ sliceRegistry.set(store, slices);
1411
+ }
1412
+ slices.set(name, data);
946
1413
  }
947
- function getDevtools() {
948
- if (typeof window === "undefined") return null;
949
- return window.__REDUX_DEVTOOLS_EXTENSION__ || null;
1414
+ function createSlice(name, creator) {
1415
+ return { name, creator };
950
1416
  }
951
- function devtools(options = {}) {
952
- const { name = "OxogState Store", enabled = true, maxAge = 50 } = options;
953
- let connection = null;
954
- let history2 = [];
955
- return {
956
- name: "devtools",
957
- version: "1.0.0",
1417
+ function combineSlices(...slices) {
1418
+ const initialState = {};
1419
+ const actions = {};
1420
+ let tempStore = null;
1421
+ const set = (partial) => {
1422
+ if (tempStore) {
1423
+ if (typeof partial === "function") {
1424
+ tempStore.setState(partial);
1425
+ } else {
1426
+ tempStore.setState(partial);
1427
+ }
1428
+ }
1429
+ };
1430
+ const get = () => {
1431
+ return tempStore ? tempStore.getState() : initialState;
1432
+ };
1433
+ const placeholderStore = {
1434
+ getState: () => initialState,
1435
+ setState: () => {
1436
+ },
1437
+ subscribe: () => () => {
1438
+ },
1439
+ merge: () => {
1440
+ },
1441
+ reset: () => {
1442
+ },
1443
+ use: () => placeholderStore,
1444
+ destroy: () => {
1445
+ }
1446
+ };
1447
+ const sliceData = /* @__PURE__ */ new Map();
1448
+ for (const slice of slices) {
1449
+ const sliceResult = slice.creator(set, get, placeholderStore);
1450
+ const data = {};
1451
+ for (const [key, value] of Object.entries(sliceResult)) {
1452
+ if (typeof value === "function") {
1453
+ actions[key] = value;
1454
+ } else {
1455
+ initialState[key] = value;
1456
+ data[key] = value;
1457
+ }
1458
+ }
1459
+ sliceData.set(slice.name, data);
1460
+ }
1461
+ tempStore = createStore(initialState);
1462
+ for (const slice of slices) {
1463
+ const sliceResult = slice.creator(
1464
+ (partial) => {
1465
+ if (typeof partial === "function") {
1466
+ tempStore.setState(partial);
1467
+ } else {
1468
+ tempStore.setState(partial);
1469
+ }
1470
+ },
1471
+ () => tempStore.getState(),
1472
+ tempStore
1473
+ );
1474
+ for (const [key, value] of Object.entries(sliceResult)) {
1475
+ if (typeof value === "function") {
1476
+ actions[key] = value;
1477
+ }
1478
+ }
1479
+ }
1480
+ for (const [name, data] of sliceData) {
1481
+ registerSlice(tempStore, name, data);
1482
+ }
1483
+ const store = tempStore;
1484
+ for (const [name, action] of Object.entries(actions)) {
1485
+ store[name] = action;
1486
+ }
1487
+ return store;
1488
+ }
1489
+ function createNamespacedSlice(namespace, creator) {
1490
+ return createSlice(namespace, (set, get) => {
1491
+ const namespacedSet = (partial) => {
1492
+ const current = get()[namespace] || {};
1493
+ const update = typeof partial === "function" ? partial(current) : partial;
1494
+ set({ [namespace]: { ...current, ...update } });
1495
+ };
1496
+ const namespacedGet = () => {
1497
+ return get()[namespace] || {};
1498
+ };
1499
+ const sliceResult = creator(namespacedSet, namespacedGet);
1500
+ const state = {};
1501
+ const actions = {};
1502
+ for (const [key, value] of Object.entries(sliceResult)) {
1503
+ if (typeof value === "function") {
1504
+ actions[key] = value;
1505
+ } else {
1506
+ state[key] = value;
1507
+ }
1508
+ }
1509
+ return {
1510
+ [namespace]: state,
1511
+ ...actions
1512
+ };
1513
+ });
1514
+ }
1515
+ function extendStore(store, ...slices) {
1516
+ const actions = {};
1517
+ const set = (partial) => {
1518
+ if (typeof partial === "function") {
1519
+ store.setState(partial);
1520
+ } else {
1521
+ store.setState(partial);
1522
+ }
1523
+ };
1524
+ const get = () => store.getState();
1525
+ for (const slice of slices) {
1526
+ const sliceResult = slice.creator(set, get, store);
1527
+ const data = {};
1528
+ for (const [key, value] of Object.entries(sliceResult)) {
1529
+ if (typeof value === "function") {
1530
+ actions[key] = value;
1531
+ } else {
1532
+ store.setState({ [key]: value });
1533
+ data[key] = value;
1534
+ }
1535
+ }
1536
+ registerSlice(store, slice.name, data);
1537
+ }
1538
+ const extendedStore = store;
1539
+ for (const [name, action] of Object.entries(actions)) {
1540
+ extendedStore[name] = action;
1541
+ }
1542
+ return extendedStore;
1543
+ }
1544
+ function resetSlices(store, ...sliceNames) {
1545
+ const slices = sliceRegistry.get(store);
1546
+ if (!slices) {
1547
+ console.warn("resetSlices: store was not created with combineSlices/extendStore; resetting all state");
1548
+ store.reset();
1549
+ return;
1550
+ }
1551
+ const update = {};
1552
+ for (const name of sliceNames) {
1553
+ const data = slices.get(name);
1554
+ if (!data) {
1555
+ console.warn(`resetSlices: unknown slice '${name}'`);
1556
+ continue;
1557
+ }
1558
+ Object.assign(update, data);
1559
+ }
1560
+ if (Object.keys(update).length > 0) {
1561
+ store.setState(deepClone(update));
1562
+ }
1563
+ }
1564
+
1565
+ // src/federation.ts
1566
+ function createFederation(stores, options = {}) {
1567
+ const { name = "federation", debug = false } = options;
1568
+ const listeners = /* @__PURE__ */ new Set();
1569
+ const unsubscribers = [];
1570
+ let isInTransaction = false;
1571
+ let transactionChanges = [];
1572
+ let previousStates = null;
1573
+ const getState = () => {
1574
+ const state = {};
1575
+ for (const key in stores) {
1576
+ const store = stores[key];
1577
+ if (store) {
1578
+ state[key] = store.getState();
1579
+ }
1580
+ }
1581
+ return state;
1582
+ };
1583
+ const notify = (changedStore) => {
1584
+ if (isInTransaction) {
1585
+ if (!transactionChanges.includes(changedStore)) {
1586
+ transactionChanges.push(changedStore);
1587
+ }
1588
+ return;
1589
+ }
1590
+ const state = getState();
1591
+ const prevState = previousStates || state;
1592
+ for (const listener of listeners) {
1593
+ try {
1594
+ listener(state, prevState, changedStore);
1595
+ } catch (error) {
1596
+ console.error(`Federation listener error:`, error);
1597
+ }
1598
+ }
1599
+ previousStates = state;
1600
+ };
1601
+ for (const key in stores) {
1602
+ const store = stores[key];
1603
+ if (store) {
1604
+ const unsubscribe = store.subscribe(() => {
1605
+ notify(key);
1606
+ });
1607
+ unsubscribers.push(unsubscribe);
1608
+ }
1609
+ }
1610
+ previousStates = getState();
1611
+ const log = (message, ...args) => {
1612
+ if (debug) {
1613
+ console.log(`[${name}] ${message}`, ...args);
1614
+ }
1615
+ };
1616
+ return {
1617
+ stores,
1618
+ getState,
1619
+ subscribe(listener) {
1620
+ listeners.add(listener);
1621
+ return () => {
1622
+ listeners.delete(listener);
1623
+ };
1624
+ },
1625
+ transaction(fn) {
1626
+ if (isInTransaction) {
1627
+ fn(stores);
1628
+ return;
1629
+ }
1630
+ isInTransaction = true;
1631
+ transactionChanges = [];
1632
+ const snapshotStates = getState();
1633
+ log("Transaction started");
1634
+ try {
1635
+ const result = fn(stores);
1636
+ if (result instanceof Promise) {
1637
+ throw new Error(
1638
+ "Async operations in transaction() are not supported. Use transactionAsync() instead."
1639
+ );
1640
+ }
1641
+ isInTransaction = false;
1642
+ if (transactionChanges.length > 0) {
1643
+ log("Transaction committed, changed stores:", transactionChanges);
1644
+ const state = getState();
1645
+ for (const listener of listeners) {
1646
+ try {
1647
+ listener(state, snapshotStates, transactionChanges[0]);
1648
+ } catch (error) {
1649
+ console.error(`Federation listener error:`, error);
1650
+ }
1651
+ }
1652
+ previousStates = state;
1653
+ }
1654
+ } catch (error) {
1655
+ isInTransaction = false;
1656
+ log("Transaction failed, rolling back");
1657
+ for (const key in stores) {
1658
+ const store = stores[key];
1659
+ if (store) {
1660
+ store.setState(snapshotStates[key]);
1661
+ }
1662
+ }
1663
+ throw error;
1664
+ }
1665
+ },
1666
+ async transactionAsync(fn) {
1667
+ if (isInTransaction) {
1668
+ await fn(stores);
1669
+ return;
1670
+ }
1671
+ isInTransaction = true;
1672
+ transactionChanges = [];
1673
+ const snapshotStates = getState();
1674
+ log("Async transaction started");
1675
+ try {
1676
+ await fn(stores);
1677
+ isInTransaction = false;
1678
+ if (transactionChanges.length > 0) {
1679
+ log("Async transaction committed, changed stores:", transactionChanges);
1680
+ const state = getState();
1681
+ for (const listener of listeners) {
1682
+ try {
1683
+ listener(state, snapshotStates, transactionChanges[0]);
1684
+ } catch (error) {
1685
+ console.error(`Federation listener error:`, error);
1686
+ }
1687
+ }
1688
+ previousStates = state;
1689
+ }
1690
+ } catch (error) {
1691
+ isInTransaction = false;
1692
+ log("Async transaction failed, rolling back");
1693
+ for (const key in stores) {
1694
+ const store = stores[key];
1695
+ if (store) {
1696
+ store.setState(snapshotStates[key]);
1697
+ }
1698
+ }
1699
+ throw error;
1700
+ }
1701
+ },
1702
+ getStore(storeName) {
1703
+ return stores[storeName];
1704
+ },
1705
+ subscribeStore(storeName, listener) {
1706
+ const store = stores[storeName];
1707
+ if (!store) {
1708
+ throw new Error(`Unknown store '${String(storeName)}' in federation '${name}'`);
1709
+ }
1710
+ const unsubscribe = store.subscribe(listener);
1711
+ unsubscribers.push(unsubscribe);
1712
+ return unsubscribe;
1713
+ },
1714
+ destroy() {
1715
+ log("Destroying federation");
1716
+ for (const unsubscribe of unsubscribers) {
1717
+ unsubscribe();
1718
+ }
1719
+ listeners.clear();
1720
+ }
1721
+ };
1722
+ }
1723
+ function createFederatedSelector(federation, selector2) {
1724
+ return () => selector2(federation.getState());
1725
+ }
1726
+ function createFederatedComputed(federation, selector2, equalityFn = Object.is) {
1727
+ let cachedValue = selector2(federation.getState());
1728
+ const listeners = /* @__PURE__ */ new Set();
1729
+ federation.subscribe((state) => {
1730
+ const newValue = selector2(state);
1731
+ if (!equalityFn(newValue, cachedValue)) {
1732
+ const prevValue = cachedValue;
1733
+ cachedValue = newValue;
1734
+ for (const listener of listeners) {
1735
+ listener(newValue, prevValue);
1736
+ }
1737
+ }
1738
+ });
1739
+ return {
1740
+ get() {
1741
+ return cachedValue;
1742
+ },
1743
+ subscribe(listener) {
1744
+ listeners.add(listener);
1745
+ return () => {
1746
+ listeners.delete(listener);
1747
+ };
1748
+ }
1749
+ };
1750
+ }
1751
+ function waitForFederated(federation, predicate, timeout) {
1752
+ return new Promise((resolve, reject) => {
1753
+ const state = federation.getState();
1754
+ if (predicate(state)) {
1755
+ resolve(state);
1756
+ return;
1757
+ }
1758
+ let timeoutId;
1759
+ let unsubscribe;
1760
+ const cleanup = () => {
1761
+ if (timeoutId) clearTimeout(timeoutId);
1762
+ if (unsubscribe) unsubscribe();
1763
+ };
1764
+ if (timeout) {
1765
+ timeoutId = setTimeout(() => {
1766
+ cleanup();
1767
+ reject(new Error(`waitForFederated timed out after ${timeout}ms`));
1768
+ }, timeout);
1769
+ }
1770
+ unsubscribe = federation.subscribe((state2) => {
1771
+ if (predicate(state2)) {
1772
+ cleanup();
1773
+ resolve(state2);
1774
+ }
1775
+ });
1776
+ });
1777
+ }
1778
+
1779
+ // src/plugins/persist.ts
1780
+ var defaultStorage = {
1781
+ getItem: (key) => {
1782
+ if (typeof window === "undefined") return null;
1783
+ try {
1784
+ return window.localStorage.getItem(key);
1785
+ } catch {
1786
+ return null;
1787
+ }
1788
+ },
1789
+ setItem: (key, value) => {
1790
+ if (typeof window === "undefined") return;
1791
+ window.localStorage.setItem(key, value);
1792
+ },
1793
+ /* c8 ignore next 3 */
1794
+ removeItem: () => {
1795
+ }
1796
+ };
1797
+ var sessionStorage = {
1798
+ getItem: (key) => {
1799
+ if (typeof window === "undefined") return null;
1800
+ try {
1801
+ return window.sessionStorage.getItem(key);
1802
+ } catch {
1803
+ return null;
1804
+ }
1805
+ },
1806
+ setItem: (key, value) => {
1807
+ if (typeof window === "undefined") return;
1808
+ window.sessionStorage.setItem(key, value);
1809
+ },
1810
+ removeItem: (key) => {
1811
+ if (typeof window === "undefined") return;
1812
+ try {
1813
+ window.sessionStorage.removeItem(key);
1814
+ } catch {
1815
+ }
1816
+ }
1817
+ };
1818
+ function createDebounced2(fn, delay2) {
1819
+ let timeoutId = null;
1820
+ const debounced = ((...args) => {
1821
+ if (timeoutId) {
1822
+ clearTimeout(timeoutId);
1823
+ }
1824
+ timeoutId = setTimeout(() => {
1825
+ fn(...args);
1826
+ timeoutId = null;
1827
+ }, delay2);
1828
+ });
1829
+ debounced.cancel = () => {
1830
+ if (timeoutId) {
1831
+ clearTimeout(timeoutId);
1832
+ timeoutId = null;
1833
+ }
1834
+ };
1835
+ return debounced;
1836
+ }
1837
+ function persist(options) {
1838
+ const {
1839
+ key,
1840
+ storage = defaultStorage,
1841
+ whitelist,
1842
+ blacklist,
1843
+ partialize,
1844
+ merge: customMerge,
1845
+ version = 0,
1846
+ migrate,
1847
+ serialize = JSON.stringify,
1848
+ deserialize = JSON.parse,
1849
+ encrypt,
1850
+ decrypt,
1851
+ writeDebounce,
1852
+ onRehydrateStorage,
1853
+ onHydrationComplete,
1854
+ onPersistError
1855
+ } = options;
1856
+ let cancelDebounce = null;
1857
+ return {
1858
+ name: "persist",
1859
+ version: "1.0.0",
1860
+ install(store) {
1861
+ try {
1862
+ let saved = storage.getItem(key);
1863
+ if (saved && decrypt) {
1864
+ try {
1865
+ saved = decrypt(saved);
1866
+ } catch {
1867
+ saved = null;
1868
+ }
1869
+ }
1870
+ if (saved) {
1871
+ let parsed;
1872
+ let persistedVersion = 0;
1873
+ try {
1874
+ const data = deserialize(saved);
1875
+ if (data && typeof data === "object" && "state" in data && "version" in data) {
1876
+ parsed = data.state;
1877
+ persistedVersion = data.version;
1878
+ } else {
1879
+ parsed = data;
1880
+ }
1881
+ } catch {
1882
+ parsed = deserialize(saved);
1883
+ }
1884
+ if (onRehydrateStorage) {
1885
+ onRehydrateStorage(parsed);
1886
+ }
1887
+ if (migrate && persistedVersion < version) {
1888
+ parsed = migrate(parsed, persistedVersion);
1889
+ }
1890
+ if (customMerge) {
1891
+ const currentState = store.getState();
1892
+ const mergedState = customMerge(parsed, currentState);
1893
+ store.setState(mergedState);
1894
+ } else {
1895
+ store.merge(parsed);
1896
+ }
1897
+ if (onHydrationComplete) {
1898
+ onHydrationComplete(store.getState());
1899
+ }
1900
+ }
1901
+ } catch (error) {
1902
+ if (onPersistError) {
1903
+ onPersistError(error);
1904
+ } else {
1905
+ console.error(`Failed to hydrate state from '${key}':`, error);
1906
+ }
1907
+ }
1908
+ const persistState = (state) => {
1909
+ try {
1910
+ let toSave = state;
1911
+ if (partialize) {
1912
+ toSave = partialize(state);
1913
+ } else if (whitelist) {
1914
+ toSave = pick(state, whitelist);
1915
+ } else if (blacklist) {
1916
+ toSave = omit(state, blacklist);
1917
+ }
1918
+ const dataToStore = {
1919
+ state: toSave,
1920
+ version
1921
+ };
1922
+ let serialized = serialize(dataToStore);
1923
+ if (encrypt) {
1924
+ serialized = encrypt(serialized);
1925
+ }
1926
+ storage.setItem(key, serialized);
1927
+ } catch (error) {
1928
+ if (onPersistError) {
1929
+ onPersistError(error);
1930
+ } else {
1931
+ console.error(`Failed to persist state to '${key}':`, error);
1932
+ }
1933
+ }
1934
+ };
1935
+ const debouncedPersist = writeDebounce && writeDebounce > 0 ? createDebounced2(persistState, writeDebounce) : persistState;
1936
+ if (writeDebounce && writeDebounce > 0) {
1937
+ cancelDebounce = () => debouncedPersist.cancel?.();
1938
+ }
1939
+ store.subscribe(debouncedPersist);
1940
+ },
1941
+ onDestroy() {
1942
+ if (cancelDebounce) {
1943
+ cancelDebounce();
1944
+ }
1945
+ }
1946
+ };
1947
+ }
1948
+ function createStorage(storage) {
1949
+ return storage;
1950
+ }
1951
+
1952
+ // src/plugins/devtools.ts
1953
+ function hasDevtools() {
1954
+ return typeof window !== "undefined" && !!window.__REDUX_DEVTOOLS_EXTENSION__;
1955
+ }
1956
+ function getDevtools() {
1957
+ if (typeof window === "undefined") return null;
1958
+ return window.__REDUX_DEVTOOLS_EXTENSION__ || null;
1959
+ }
1960
+ function devtools(options = {}) {
1961
+ const { name = "OxogState Store", enabled = true, maxAge = 50 } = options;
1962
+ let connection = null;
1963
+ let unsubscribeStore = null;
1964
+ let unsubscribeDevtools = null;
1965
+ let states = [];
1966
+ return {
1967
+ name: "devtools",
1968
+ version: "1.0.0",
958
1969
  install(store) {
959
1970
  if (!enabled || !hasDevtools()) {
960
1971
  return;
961
1972
  }
962
1973
  const extension = getDevtools();
963
1974
  if (!extension) return;
964
- connection = extension.connect({ name });
965
- connection.init(store.getState());
966
- store.subscribe((state, prevState) => {
967
- if (!connection) return;
968
- history2.push({ state, action: "UPDATE" });
969
- if (history2.length > maxAge) {
970
- history2.shift();
1975
+ const conn = extension.connect({ name });
1976
+ connection = conn;
1977
+ conn.init(store.getState());
1978
+ states = [store.getState()];
1979
+ let applyingFromDevtools = false;
1980
+ const apply = (fn) => {
1981
+ applyingFromDevtools = true;
1982
+ try {
1983
+ fn();
1984
+ } finally {
1985
+ applyingFromDevtools = false;
1986
+ }
1987
+ };
1988
+ unsubscribeStore = store.subscribe((state, prevState) => {
1989
+ if (!connection || applyingFromDevtools) return;
1990
+ states.push(state);
1991
+ if (states.length > maxAge + 1) {
1992
+ states.shift();
971
1993
  }
972
1994
  connection.send({ type: "UPDATE", prev: prevState }, state);
973
1995
  });
974
- connection.subscribe((message) => {
975
- if (message.type === "DISPATCH" && message.payload) {
976
- switch (message.payload.type) {
977
- case "JUMP_TO_STATE":
978
- case "JUMP_TO_ACTION": {
979
- const index = message.payload.type === "JUMP_TO_ACTION" ? history2.findIndex((h) => h.action === message.payload.action) : message.payload.index;
980
- if (index >= 0 && index < history2.length) {
981
- const entry = history2[index];
982
- if (entry) {
983
- store.setState(entry.state);
984
- }
985
- }
986
- break;
987
- }
988
- case "COMMIT": {
989
- connection.init(store.getState());
990
- history2 = [];
991
- break;
992
- }
993
- case "ROLLBACK": {
994
- if (history2.length > 1) {
995
- const previous = history2[history2.length - 2];
996
- if (previous) {
997
- store.setState(previous.state);
998
- }
999
- }
1000
- break;
1996
+ const parseState = (message) => {
1997
+ if (typeof message.state !== "string") return void 0;
1998
+ try {
1999
+ return JSON.parse(message.state);
2000
+ } catch {
2001
+ return void 0;
2002
+ }
2003
+ };
2004
+ const unsubscribe = conn.subscribe((message) => {
2005
+ if (message?.type !== "DISPATCH" || !message.payload) return;
2006
+ switch (message.payload.type) {
2007
+ case "JUMP_TO_STATE":
2008
+ case "JUMP_TO_ACTION": {
2009
+ const target = parseState(message) ?? states[message.payload.index];
2010
+ if (target !== void 0) {
2011
+ apply(() => store.setState(target));
1001
2012
  }
1002
- case "RESET": {
1003
- store.reset();
1004
- break;
2013
+ break;
2014
+ }
2015
+ case "COMMIT": {
2016
+ conn.init(store.getState());
2017
+ states = [store.getState()];
2018
+ break;
2019
+ }
2020
+ case "ROLLBACK": {
2021
+ const target = parseState(message) ?? states[0];
2022
+ if (target !== void 0) {
2023
+ apply(() => store.setState(target));
1005
2024
  }
2025
+ conn.init(store.getState());
2026
+ states = [store.getState()];
2027
+ break;
2028
+ }
2029
+ case "RESET": {
2030
+ apply(() => store.reset());
2031
+ conn.init(store.getState());
2032
+ states = [store.getState()];
2033
+ break;
1006
2034
  }
1007
2035
  }
1008
2036
  });
2037
+ if (typeof unsubscribe === "function") {
2038
+ unsubscribeDevtools = unsubscribe;
2039
+ }
1009
2040
  },
1010
2041
  onDestroy() {
2042
+ unsubscribeStore?.();
2043
+ unsubscribeStore = null;
2044
+ unsubscribeDevtools?.();
2045
+ unsubscribeDevtools = null;
1011
2046
  connection = null;
1012
- history2 = [];
2047
+ states = [];
1013
2048
  }
1014
2049
  };
1015
2050
  }
@@ -1019,6 +2054,7 @@ function history(options = {}) {
1019
2054
  const { limit = 50, keys } = options;
1020
2055
  let historyState = null;
1021
2056
  let isInternalUpdate = false;
2057
+ let internalState = null;
1022
2058
  return {
1023
2059
  name: "history",
1024
2060
  version: "1.0.0",
@@ -1030,6 +2066,11 @@ function history(options = {}) {
1030
2066
  };
1031
2067
  store.subscribe((state) => {
1032
2068
  if (!historyState || isInternalUpdate) return;
2069
+ if (internalState !== null && state === internalState) {
2070
+ internalState = null;
2071
+ return;
2072
+ }
2073
+ internalState = null;
1033
2074
  const previousPresent = historyState.present;
1034
2075
  const newPresent = state;
1035
2076
  let hasChanged = true;
@@ -1054,8 +2095,12 @@ function history(options = {}) {
1054
2095
  historyState.future.push(historyState.present);
1055
2096
  historyState.present = previous;
1056
2097
  isInternalUpdate = true;
1057
- store.setState(previous);
1058
- isInternalUpdate = false;
2098
+ try {
2099
+ store.setState(previous);
2100
+ internalState = store.getState();
2101
+ } finally {
2102
+ isInternalUpdate = false;
2103
+ }
1059
2104
  };
1060
2105
  store.redo = () => {
1061
2106
  if (!historyState || historyState.future.length === 0) return;
@@ -1063,8 +2108,12 @@ function history(options = {}) {
1063
2108
  historyState.past.push(historyState.present);
1064
2109
  historyState.present = next;
1065
2110
  isInternalUpdate = true;
1066
- store.setState(next);
1067
- isInternalUpdate = false;
2111
+ try {
2112
+ store.setState(next);
2113
+ internalState = store.getState();
2114
+ } finally {
2115
+ isInternalUpdate = false;
2116
+ }
1068
2117
  };
1069
2118
  store.clearHistory = () => {
1070
2119
  if (!historyState) return;
@@ -1092,7 +2141,16 @@ function sync(options = {}) {
1092
2141
  const { channel = "oxog-state" } = options;
1093
2142
  let broadcastChannel = null;
1094
2143
  let currentStore = null;
1095
- let isLocalUpdate = false;
2144
+ let unsubscribe = null;
2145
+ let applyingRemote = false;
2146
+ const broadcast = (state, errorMessage) => {
2147
+ if (!broadcastChannel) return;
2148
+ try {
2149
+ broadcastChannel.postMessage(toMessage(state));
2150
+ } catch (error) {
2151
+ console.error(errorMessage, error);
2152
+ }
2153
+ };
1096
2154
  return {
1097
2155
  name: "sync",
1098
2156
  version: "1.0.0",
@@ -1104,28 +2162,34 @@ function sync(options = {}) {
1104
2162
  }
1105
2163
  broadcastChannel = new BroadcastChannel(channel);
1106
2164
  broadcastChannel.onmessage = (event) => {
1107
- if (!isLocalUpdate) {
1108
- try {
1109
- store.setState(event.data);
1110
- } catch (error) {
1111
- console.error("Error applying sync state:", error);
1112
- }
2165
+ if (!currentStore) return;
2166
+ applyingRemote = true;
2167
+ try {
2168
+ currentStore.setState(event.data);
2169
+ } catch (error) {
2170
+ console.error("Error applying sync state:", error);
2171
+ } finally {
2172
+ applyingRemote = false;
1113
2173
  }
1114
2174
  };
2175
+ unsubscribe = store.subscribe((state) => {
2176
+ if (!applyingRemote) {
2177
+ broadcast(state, "Error broadcasting state:");
2178
+ }
2179
+ });
1115
2180
  },
1116
2181
  onInit() {
1117
- if (broadcastChannel && currentStore) {
1118
- isLocalUpdate = true;
1119
- try {
1120
- broadcastChannel.postMessage(currentStore.getState());
1121
- } catch (error) {
1122
- console.error("Error broadcasting initial state:", error);
1123
- }
1124
- isLocalUpdate = false;
2182
+ if (currentStore) {
2183
+ broadcast(currentStore.getState(), "Error broadcasting initial state:");
1125
2184
  }
1126
2185
  },
1127
2186
  onDestroy() {
2187
+ if (unsubscribe) {
2188
+ unsubscribe();
2189
+ unsubscribe = null;
2190
+ }
1128
2191
  if (broadcastChannel) {
2192
+ broadcastChannel.onmessage = null;
1129
2193
  broadcastChannel.close();
1130
2194
  broadcastChannel = null;
1131
2195
  }
@@ -1133,82 +2197,166 @@ function sync(options = {}) {
1133
2197
  }
1134
2198
  };
1135
2199
  }
2200
+ function toMessage(state) {
2201
+ if (state === null || typeof state !== "object") return state;
2202
+ const data = {};
2203
+ for (const key of Object.keys(state)) {
2204
+ const value = state[key];
2205
+ if (typeof value !== "function") {
2206
+ data[key] = value;
2207
+ }
2208
+ }
2209
+ return data;
2210
+ }
1136
2211
  function triggerSync(store, channel = "oxog-state") {
1137
2212
  if (typeof BroadcastChannel === "undefined") {
1138
2213
  console.warn("BroadcastChannel is not supported in this environment");
1139
2214
  return;
1140
2215
  }
1141
2216
  const broadcastChannel = new BroadcastChannel(channel);
1142
- broadcastChannel.postMessage(store.getState());
2217
+ broadcastChannel.postMessage(toMessage(store.getState()));
1143
2218
  broadcastChannel.close();
1144
2219
  }
1145
2220
 
1146
2221
  // src/plugins/immer.ts
1147
- function createProxy(base, copies) {
1148
- return new Proxy(base || {}, {
1149
- get(target, key) {
1150
- const value = target[key];
1151
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
1152
- if (copies.has(value)) {
1153
- return createProxy(copies.get(value), copies);
1154
- }
1155
- return createProxy(value, copies);
2222
+ var DRAFT_STATE = /* @__PURE__ */ Symbol("oxog-state.draft");
2223
+ function isDraftable(value) {
2224
+ if (value === null || typeof value !== "object") return false;
2225
+ if (Array.isArray(value)) return true;
2226
+ const proto = Object.getPrototypeOf(value);
2227
+ return proto === Object.prototype || proto === null;
2228
+ }
2229
+ function getDraftState(value) {
2230
+ if (value === null || typeof value !== "object") return void 0;
2231
+ return value[DRAFT_STATE];
2232
+ }
2233
+ function latest(state) {
2234
+ return state.copy ?? state.base;
2235
+ }
2236
+ function hasOwn(target, key) {
2237
+ return Object.prototype.hasOwnProperty.call(target, key);
2238
+ }
2239
+ function shallowCopy(base) {
2240
+ if (Array.isArray(base)) return base.slice();
2241
+ return Object.getPrototypeOf(base) === null ? Object.assign(/* @__PURE__ */ Object.create(null), base) : { ...base };
2242
+ }
2243
+ function markChanged(state) {
2244
+ if (state.copy === null) {
2245
+ state.copy = shallowCopy(state.base);
2246
+ if (state.parent) markChanged(state.parent);
2247
+ }
2248
+ }
2249
+ function createDraft(base, parent) {
2250
+ const state = {
2251
+ base,
2252
+ copy: null,
2253
+ parent,
2254
+ children: /* @__PURE__ */ new Map(),
2255
+ proxy: null,
2256
+ finalized: false,
2257
+ result: void 0
2258
+ };
2259
+ const target = Array.isArray(base) ? [] : {};
2260
+ state.proxy = new Proxy(target, {
2261
+ get(_target, prop) {
2262
+ if (prop === DRAFT_STATE) return state;
2263
+ const source = latest(state);
2264
+ const value = Reflect.get(source, prop, state.proxy);
2265
+ if (!hasOwn(source, prop) || !isDraftable(value)) return value;
2266
+ if (value !== state.base[prop]) return value;
2267
+ let child = state.children.get(prop);
2268
+ if (!child) {
2269
+ child = createDraft(value, state);
2270
+ state.children.set(prop, child);
1156
2271
  }
1157
- return value;
2272
+ return child.proxy;
1158
2273
  },
1159
- set(target, key, value) {
1160
- if (!copies.has(target)) {
1161
- copies.set(target, { ...target });
1162
- }
1163
- const copy = copies.get(target);
1164
- copy[key] = value;
2274
+ set(_target, prop, value) {
2275
+ if (prop === "__proto__") return true;
2276
+ const source = latest(state);
2277
+ if (hasOwn(source, prop) && Object.is(source[prop], value)) return true;
2278
+ markChanged(state);
2279
+ state.copy[prop] = value;
2280
+ state.children.delete(prop);
1165
2281
  return true;
1166
2282
  },
1167
- deleteProperty(target, key) {
1168
- if (!copies.has(target)) {
1169
- copies.set(target, { ...target });
1170
- }
1171
- const copy = copies.get(target);
1172
- delete copy[key];
2283
+ deleteProperty(_target, prop) {
2284
+ if (!hasOwn(latest(state), prop)) return true;
2285
+ markChanged(state);
2286
+ delete state.copy[prop];
2287
+ state.children.delete(prop);
1173
2288
  return true;
2289
+ },
2290
+ has(_target, prop) {
2291
+ return prop in latest(state);
2292
+ },
2293
+ ownKeys() {
2294
+ return Reflect.ownKeys(latest(state));
2295
+ },
2296
+ getOwnPropertyDescriptor(_target, prop) {
2297
+ const source = latest(state);
2298
+ const descriptor = Reflect.getOwnPropertyDescriptor(source, prop);
2299
+ if (!descriptor) return void 0;
2300
+ if (Array.isArray(source) && prop === "length") return descriptor;
2301
+ return { ...descriptor, configurable: true };
2302
+ },
2303
+ defineProperty(_target, prop, descriptor) {
2304
+ markChanged(state);
2305
+ Object.defineProperty(state.copy, prop, { ...descriptor, configurable: true });
2306
+ return true;
2307
+ },
2308
+ getPrototypeOf() {
2309
+ return Object.getPrototypeOf(state.base);
2310
+ },
2311
+ setPrototypeOf() {
2312
+ return false;
1174
2313
  }
1175
2314
  });
2315
+ return state;
1176
2316
  }
1177
- function finalize(base, copies) {
1178
- if (!copies.has(base)) {
1179
- return deepClone2(base);
2317
+ function finalizeValue(value, seen) {
2318
+ const draft = getDraftState(value);
2319
+ if (draft) return finalizeDraft(draft, seen);
2320
+ if (!isDraftable(value) || seen.has(value)) return value;
2321
+ seen.add(value);
2322
+ for (const key of Object.keys(value)) {
2323
+ const item = value[key];
2324
+ const finalized = finalizeValue(item, seen);
2325
+ if (finalized !== item) value[key] = finalized;
1180
2326
  }
1181
- const copy = copies.get(base);
1182
- for (const key in copy) {
1183
- if (Object.prototype.hasOwnProperty.call(copy, key)) {
1184
- const value = copy[key];
1185
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
1186
- copy[key] = finalize(value, copies);
1187
- }
2327
+ return value;
2328
+ }
2329
+ function finalizeDraft(state, seen) {
2330
+ if (state.finalized) return state.result;
2331
+ state.finalized = true;
2332
+ if (state.copy === null) {
2333
+ state.result = state.base;
2334
+ return state.result;
2335
+ }
2336
+ const copy = state.copy;
2337
+ state.result = copy;
2338
+ for (const key of Object.keys(copy)) {
2339
+ const value = copy[key];
2340
+ const child = state.children.get(key);
2341
+ if (child && value === child.base) {
2342
+ copy[key] = finalizeDraft(child, seen);
2343
+ } else if (value !== state.base[key]) {
2344
+ copy[key] = finalizeValue(value, seen);
1188
2345
  }
1189
2346
  }
1190
2347
  return copy;
1191
2348
  }
1192
- function deepClone2(value) {
1193
- if (value === null || typeof value !== "object") {
1194
- return value;
1195
- }
1196
- if (Array.isArray(value)) {
1197
- return value.map((v) => deepClone2(v));
2349
+ function produce(base, recipe) {
2350
+ if (!isDraftable(base)) {
2351
+ const result2 = recipe(base);
2352
+ return result2 === void 0 ? base : result2;
1198
2353
  }
1199
- const cloned = {};
1200
- for (const key in value) {
1201
- if (Object.prototype.hasOwnProperty.call(value, key)) {
1202
- cloned[key] = deepClone2(value[key]);
1203
- }
2354
+ const root = createDraft(base, null);
2355
+ const result = recipe(root.proxy);
2356
+ if (result !== null && typeof result === "object" && result !== root.proxy) {
2357
+ return finalizeValue(result, /* @__PURE__ */ new Set());
1204
2358
  }
1205
- return cloned;
1206
- }
1207
- function produce(base, recipe) {
1208
- const copies = /* @__PURE__ */ new Map();
1209
- const draft = createProxy(base, copies);
1210
- recipe(draft);
1211
- return finalize(base, copies);
2359
+ return finalizeDraft(root, /* @__PURE__ */ new Set());
1212
2360
  }
1213
2361
  function immer() {
1214
2362
  return {
@@ -1218,8 +2366,10 @@ function immer() {
1218
2366
  const originalSetState = store.setState.bind(store);
1219
2367
  store.setState = (update) => {
1220
2368
  if (typeof update === "function") {
1221
- const newState = produce(store.getState(), update);
1222
- originalSetState(newState);
2369
+ const current = store.getState();
2370
+ const next = produce(current, update);
2371
+ if (next === current) return;
2372
+ originalSetState(next);
1223
2373
  } else {
1224
2374
  originalSetState(update);
1225
2375
  }
@@ -1236,57 +2386,948 @@ function selector(options) {
1236
2386
  version: "1.0.0",
1237
2387
  install(store) {
1238
2388
  const originalGetState = store.getState.bind(store);
1239
- const cache = /* @__PURE__ */ new Map();
1240
- const computedState = new Proxy({}, {
1241
- get(_, prop) {
1242
- const selectorFn = selectors[prop];
1243
- if (selectorFn) {
1244
- const currentState = originalGetState();
1245
- const cacheKey = prop;
1246
- const cached = cache.get(cacheKey);
1247
- if (cached && cached.state === currentState) {
1248
- return cached.value;
2389
+ let lastState;
2390
+ let lastSnapshot;
2391
+ const createSnapshot = (state) => {
2392
+ if (state === null || typeof state !== "object") return state;
2393
+ const cache = /* @__PURE__ */ new Map();
2394
+ return new Proxy(state, {
2395
+ get(target, prop, receiver) {
2396
+ const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop) ? selectors[prop] : void 0;
2397
+ if (selectorFn) {
2398
+ if (!cache.has(prop)) {
2399
+ cache.set(prop, selectorFn(state));
2400
+ }
2401
+ return cache.get(prop);
2402
+ }
2403
+ return Reflect.get(target, prop, receiver);
2404
+ },
2405
+ getOwnPropertyDescriptor(target, prop) {
2406
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
2407
+ const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop) ? selectors[prop] : void 0;
2408
+ if (descriptor && selectorFn && "value" in descriptor && descriptor.configurable) {
2409
+ if (!cache.has(prop)) {
2410
+ cache.set(prop, selectorFn(state));
2411
+ }
2412
+ return { ...descriptor, value: cache.get(prop) };
1249
2413
  }
1250
- const value = selectorFn(currentState);
1251
- cache.set(cacheKey, { value, state: currentState });
1252
- return value;
2414
+ return descriptor;
1253
2415
  }
1254
- return originalGetState()[prop];
2416
+ });
2417
+ };
2418
+ store.getState = () => {
2419
+ const state = originalGetState();
2420
+ if (state !== lastState || lastSnapshot === void 0) {
2421
+ lastState = state;
2422
+ lastSnapshot = createSnapshot(state);
2423
+ }
2424
+ return lastSnapshot;
2425
+ };
2426
+ }
2427
+ };
2428
+ }
2429
+
2430
+ // src/plugins/logger.ts
2431
+ var LOG_LEVELS = {
2432
+ debug: 0,
2433
+ info: 1,
2434
+ warn: 2,
2435
+ error: 3
2436
+ };
2437
+ var COLORS = {
2438
+ title: "#9E9E9E",
2439
+ prevState: "#9E9E9E",
2440
+ action: "#03A9F4",
2441
+ nextState: "#4CAF50",
2442
+ diff: {
2443
+ changed: "#2196F3"
2444
+ }
2445
+ };
2446
+ function formatTime(date) {
2447
+ const hours = date.getHours().toString().padStart(2, "0");
2448
+ const minutes = date.getMinutes().toString().padStart(2, "0");
2449
+ const seconds = date.getSeconds().toString().padStart(2, "0");
2450
+ const ms = date.getMilliseconds().toString().padStart(3, "0");
2451
+ return `${hours}:${minutes}:${seconds}.${ms}`;
2452
+ }
2453
+ function calculateDiff(prevState, nextState) {
2454
+ const diff = {};
2455
+ if (typeof prevState !== "object" || typeof nextState !== "object") {
2456
+ if (prevState !== nextState) {
2457
+ diff["value"] = { prev: prevState, next: nextState };
2458
+ }
2459
+ return diff;
2460
+ }
2461
+ if (prevState === null || nextState === null) {
2462
+ if (prevState !== nextState) {
2463
+ diff["value"] = { prev: prevState, next: nextState };
2464
+ }
2465
+ return diff;
2466
+ }
2467
+ const allKeys = /* @__PURE__ */ new Set([
2468
+ ...Object.keys(prevState),
2469
+ ...Object.keys(nextState)
2470
+ ]);
2471
+ for (const key of allKeys) {
2472
+ const prev = prevState[key];
2473
+ const next = nextState[key];
2474
+ if (prev !== next) {
2475
+ diff[key] = { prev, next };
2476
+ }
2477
+ }
2478
+ return diff;
2479
+ }
2480
+ function isBrowser() {
2481
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
2482
+ }
2483
+ function logger(options = {}) {
2484
+ const {
2485
+ level = "debug",
2486
+ logger: customLogger = console,
2487
+ collapsed = true,
2488
+ diff = true,
2489
+ colors = isBrowser(),
2490
+ timestamp = true,
2491
+ filter,
2492
+ stateTransformer,
2493
+ actionName = "STATE_CHANGE",
2494
+ name = "Store",
2495
+ enabled = true
2496
+ } = options;
2497
+ const minLevel = LOG_LEVELS[level];
2498
+ return {
2499
+ name: "logger",
2500
+ version: "1.0.0",
2501
+ install(store) {
2502
+ if (!enabled) return;
2503
+ store.subscribe((state, prevState) => {
2504
+ if (filter && !filter(state, prevState)) {
2505
+ return;
2506
+ }
2507
+ if (LOG_LEVELS.info < minLevel) {
2508
+ return;
2509
+ }
2510
+ const now = /* @__PURE__ */ new Date();
2511
+ const action = typeof actionName === "function" ? actionName(state, prevState) : actionName;
2512
+ const displayPrevState = stateTransformer ? stateTransformer(prevState) : prevState;
2513
+ const displayNextState = stateTransformer ? stateTransformer(state) : state;
2514
+ const timeStr = timestamp ? ` @ ${formatTime(now)}` : "";
2515
+ const title = `${name} ${action}${timeStr}`;
2516
+ if (colors && isBrowser()) {
2517
+ logWithColors(
2518
+ customLogger,
2519
+ title,
2520
+ displayPrevState,
2521
+ displayNextState,
2522
+ collapsed,
2523
+ diff ? calculateDiff(prevState, state) : void 0
2524
+ );
2525
+ } else {
2526
+ logPlain(
2527
+ customLogger,
2528
+ title,
2529
+ displayPrevState,
2530
+ displayNextState,
2531
+ collapsed,
2532
+ diff ? calculateDiff(prevState, state) : void 0
2533
+ );
1255
2534
  }
1256
2535
  });
1257
- store.getState = () => computedState;
1258
- store.subscribe(() => {
1259
- cache.clear();
2536
+ }
2537
+ };
2538
+ }
2539
+ function logWithColors(log, title, prevState, nextState, collapsed, diff) {
2540
+ const titleStyle = `color: ${COLORS.title}; font-weight: lighter;`;
2541
+ const groupMethod = collapsed ? "groupCollapsed" : "group";
2542
+ log[groupMethod](`%c${title}`, titleStyle);
2543
+ log.log("%cprev state", `color: ${COLORS.prevState}; font-weight: bold;`, prevState);
2544
+ log.log("%cnext state", `color: ${COLORS.nextState}; font-weight: bold;`, nextState);
2545
+ if (diff && Object.keys(diff).length > 0) {
2546
+ log.log("%cdiff", `color: ${COLORS.action}; font-weight: bold;`);
2547
+ for (const [key, { prev, next }] of Object.entries(diff)) {
2548
+ log.log(
2549
+ ` %c${key}:`,
2550
+ `color: ${COLORS.diff.changed};`,
2551
+ prev,
2552
+ "\u2192",
2553
+ next
2554
+ );
2555
+ }
2556
+ }
2557
+ log.groupEnd();
2558
+ }
2559
+ function logPlain(log, title, prevState, nextState, collapsed, diff) {
2560
+ const hasGroupCollapsed = typeof log.groupCollapsed === "function";
2561
+ const groupMethod = collapsed && hasGroupCollapsed ? "groupCollapsed" : "group";
2562
+ const hasGroup = typeof log[groupMethod] === "function";
2563
+ if (hasGroup) {
2564
+ log[groupMethod](title);
2565
+ } else {
2566
+ log.log(`=== ${title} ===`);
2567
+ }
2568
+ log.log("prev state:", prevState);
2569
+ log.log("next state:", nextState);
2570
+ if (diff && Object.keys(diff).length > 0) {
2571
+ log.log("diff:");
2572
+ for (const [key, { prev, next }] of Object.entries(diff)) {
2573
+ log.log(` ${key}:`, prev, "\u2192", next);
2574
+ }
2575
+ }
2576
+ if (hasGroup) {
2577
+ log.groupEnd();
2578
+ } else {
2579
+ log.log("===");
2580
+ }
2581
+ }
2582
+ function createLogger(defaultOptions = {}) {
2583
+ return (options = {}) => logger({ ...defaultOptions, ...options });
2584
+ }
2585
+
2586
+ // src/plugins/effects.ts
2587
+ function createDebounced3(fn, delay2) {
2588
+ let timeoutId = null;
2589
+ const debounced = ((...args) => {
2590
+ if (timeoutId) {
2591
+ clearTimeout(timeoutId);
2592
+ }
2593
+ timeoutId = setTimeout(() => {
2594
+ fn(...args);
2595
+ timeoutId = null;
2596
+ }, delay2);
2597
+ });
2598
+ debounced.cancel = () => {
2599
+ if (timeoutId) {
2600
+ clearTimeout(timeoutId);
2601
+ timeoutId = null;
2602
+ }
2603
+ };
2604
+ return debounced;
2605
+ }
2606
+ function effects(options) {
2607
+ const { effects: effectDefs, onError } = options;
2608
+ let destroyAll = null;
2609
+ return {
2610
+ name: "effects",
2611
+ version: "1.0.0",
2612
+ install(store) {
2613
+ const cleanups = [];
2614
+ let destroyed = false;
2615
+ const report = (error, name) => {
2616
+ if (onError) {
2617
+ onError(error, name);
2618
+ } else {
2619
+ console.error(`Effect error${name ? ` in '${name}'` : ""}:`, error);
2620
+ }
2621
+ };
2622
+ for (let i = 0; i < effectDefs.length; i++) {
2623
+ const def = effectDefs[i];
2624
+ if (!def) continue;
2625
+ const {
2626
+ selector: selector2,
2627
+ effect,
2628
+ equalityFn = shallowEqual,
2629
+ fireImmediately = false,
2630
+ debounce,
2631
+ name
2632
+ } = def;
2633
+ let currentRun = null;
2634
+ let currentCleanup = null;
2635
+ const runCleanup = (cleanup) => {
2636
+ if (!cleanup) return;
2637
+ try {
2638
+ cleanup();
2639
+ } catch (error) {
2640
+ report(error, name);
2641
+ }
2642
+ };
2643
+ const deactivate = (run) => {
2644
+ if (run && run.active) {
2645
+ run.active = false;
2646
+ run.controller.abort();
2647
+ }
2648
+ };
2649
+ const runEffect = async (value, prev) => {
2650
+ if (destroyed) return;
2651
+ deactivate(currentRun);
2652
+ const previousCleanup = currentCleanup;
2653
+ currentCleanup = null;
2654
+ runCleanup(previousCleanup);
2655
+ const run = { active: true, controller: new AbortController() };
2656
+ currentRun = run;
2657
+ const utils = {
2658
+ getState: () => store.getState(),
2659
+ setState: (partial) => {
2660
+ if (run.active) store.setState(partial);
2661
+ },
2662
+ isActive: () => run.active,
2663
+ cancel: () => deactivate(run),
2664
+ onlyIfActive: (fn) => run.active ? fn() : void 0,
2665
+ signal: run.controller.signal
2666
+ };
2667
+ const settle = (result) => {
2668
+ if (typeof result !== "function") return;
2669
+ if (run.active) {
2670
+ currentCleanup = result;
2671
+ } else {
2672
+ runCleanup(result);
2673
+ }
2674
+ };
2675
+ const fail = (error) => {
2676
+ if (!(run.controller.signal.aborted && error?.name === "AbortError")) {
2677
+ report(error, name);
2678
+ }
2679
+ };
2680
+ try {
2681
+ const result = effect(value, prev, utils);
2682
+ if (result instanceof Promise) {
2683
+ try {
2684
+ settle(await result);
2685
+ } catch (error) {
2686
+ fail(error);
2687
+ }
2688
+ } else {
2689
+ settle(result);
2690
+ }
2691
+ } catch (error) {
2692
+ fail(error);
2693
+ }
2694
+ };
2695
+ const debounced = debounce && debounce > 0 ? createDebounced3(runEffect, debounce) : null;
2696
+ const effectFn = debounced ?? runEffect;
2697
+ if (fireImmediately) {
2698
+ const initial = selector2(store.getState());
2699
+ void effectFn(initial, initial);
2700
+ }
2701
+ const unsubscribe = store.subscribe(
2702
+ selector2,
2703
+ (value, prev) => {
2704
+ void effectFn(value, prev);
2705
+ },
2706
+ equalityFn
2707
+ );
2708
+ cleanups.push(() => {
2709
+ unsubscribe();
2710
+ debounced?.cancel();
2711
+ deactivate(currentRun);
2712
+ const cleanup = currentCleanup;
2713
+ currentCleanup = null;
2714
+ runCleanup(cleanup);
2715
+ });
2716
+ }
2717
+ destroyAll = () => {
2718
+ if (destroyed) return;
2719
+ destroyed = true;
2720
+ for (const cleanup of cleanups) {
2721
+ cleanup();
2722
+ }
2723
+ };
2724
+ store.__effectsCleanup = destroyAll;
2725
+ },
2726
+ onDestroy() {
2727
+ destroyAll?.();
2728
+ }
2729
+ };
2730
+ }
2731
+ function createEffect(name, selector2, effect, options = {}) {
2732
+ return {
2733
+ name,
2734
+ selector: selector2,
2735
+ effect,
2736
+ ...options
2737
+ };
2738
+ }
2739
+ function createSimpleEffect(effect, options = {}) {
2740
+ return {
2741
+ selector: (s) => s,
2742
+ effect,
2743
+ equalityFn: () => false,
2744
+ // Always run
2745
+ ...options
2746
+ };
2747
+ }
2748
+ function combineEffects(...effectDefs) {
2749
+ return {
2750
+ effects: effectDefs
2751
+ };
2752
+ }
2753
+ function createDebouncedEffect(delay2, selector2, effect, options = {}) {
2754
+ return {
2755
+ selector: selector2,
2756
+ effect,
2757
+ debounce: delay2,
2758
+ ...options
2759
+ };
2760
+ }
2761
+
2762
+ // src/plugins/validate.ts
2763
+ function isZodLike(schema) {
2764
+ return typeof schema === "object" && schema !== null && "safeParse" in schema && typeof schema.safeParse === "function";
2765
+ }
2766
+ function isYupLike(schema) {
2767
+ return typeof schema === "object" && schema !== null && "validateSync" in schema && typeof schema.validateSync === "function";
2768
+ }
2769
+ function extractPaths(state, paths) {
2770
+ const result = {};
2771
+ for (const path of paths) {
2772
+ if (path in state) {
2773
+ result[path] = state[path];
2774
+ }
2775
+ }
2776
+ return result;
2777
+ }
2778
+ function validateState(state, schema, paths) {
2779
+ const stateToValidate = paths ? extractPaths(state, paths) : state;
2780
+ if (typeof schema === "function") {
2781
+ const result = schema(stateToValidate);
2782
+ if (typeof result === "boolean") {
2783
+ return {
2784
+ valid: result,
2785
+ errors: result ? [] : [{ path: [], message: "Validation failed" }]
2786
+ };
2787
+ }
2788
+ if ("valid" in result && "errors" in result) {
2789
+ return result;
2790
+ }
2791
+ if (Array.isArray(result)) {
2792
+ return {
2793
+ valid: result.length === 0,
2794
+ errors: result
2795
+ };
2796
+ }
2797
+ return { valid: true, errors: [] };
2798
+ }
2799
+ if (isZodLike(schema)) {
2800
+ const result = schema.safeParse(stateToValidate);
2801
+ if (result.success) {
2802
+ return { valid: true, errors: [] };
2803
+ }
2804
+ const errors = (result.error?.issues || []).map((issue) => ({
2805
+ path: issue.path.map(String),
2806
+ message: issue.message,
2807
+ rule: issue.code
2808
+ }));
2809
+ return { valid: false, errors };
2810
+ }
2811
+ if (isYupLike(schema)) {
2812
+ try {
2813
+ schema.validateSync(stateToValidate, { abortEarly: false });
2814
+ return { valid: true, errors: [] };
2815
+ } catch (error) {
2816
+ const errors = [];
2817
+ if (error.inner && Array.isArray(error.inner)) {
2818
+ for (const err of error.inner) {
2819
+ errors.push({
2820
+ path: err.path ? err.path.split(".") : [],
2821
+ message: err.message,
2822
+ rule: err.type,
2823
+ value: err.value
2824
+ });
2825
+ }
2826
+ } else {
2827
+ errors.push({
2828
+ path: error.path ? error.path.split(".") : [],
2829
+ message: error.message || "Validation failed",
2830
+ rule: error.type
2831
+ });
2832
+ }
2833
+ return { valid: false, errors };
2834
+ }
2835
+ }
2836
+ return { valid: true, errors: [] };
2837
+ }
2838
+ function validate(options) {
2839
+ const {
2840
+ schema,
2841
+ on = "change",
2842
+ onError,
2843
+ throwOnError = false,
2844
+ paths,
2845
+ name = "validate"
2846
+ } = options;
2847
+ return {
2848
+ name,
2849
+ version: "1.0.0",
2850
+ install(store) {
2851
+ let currentErrors = [];
2852
+ const doValidate = () => {
2853
+ const state = store.getState();
2854
+ const result = validateState(state, schema, paths);
2855
+ currentErrors = result.errors;
2856
+ if (!result.valid) {
2857
+ if (onError) {
2858
+ onError(result.errors);
2859
+ }
2860
+ if (throwOnError) {
2861
+ const errorMessages = result.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");
2862
+ throw new Error(`Validation failed: ${errorMessages}`);
2863
+ }
2864
+ }
2865
+ return result;
2866
+ };
2867
+ if (on === "change") {
2868
+ store.subscribe(() => {
2869
+ doValidate();
2870
+ });
2871
+ }
2872
+ const validationAPI = {
2873
+ validate: doValidate,
2874
+ isValid: () => currentErrors.length === 0,
2875
+ getErrors: () => [...currentErrors],
2876
+ clearErrors: () => {
2877
+ currentErrors = [];
2878
+ }
2879
+ };
2880
+ Object.assign(store, validationAPI);
2881
+ }
2882
+ };
2883
+ }
2884
+ function createValidator(predicate, message) {
2885
+ return (state) => {
2886
+ const valid = predicate(state);
2887
+ return {
2888
+ valid,
2889
+ errors: valid ? [] : [{ path: [], message }]
2890
+ };
2891
+ };
2892
+ }
2893
+ function combineValidators(...validators) {
2894
+ return (state) => {
2895
+ const allErrors = [];
2896
+ for (const validator of validators) {
2897
+ const result = validator(state);
2898
+ if (typeof result === "boolean") {
2899
+ if (!result) {
2900
+ allErrors.push({ path: [], message: "Validation failed" });
2901
+ }
2902
+ } else if ("valid" in result && "errors" in result) {
2903
+ allErrors.push(...result.errors);
2904
+ } else if (Array.isArray(result)) {
2905
+ allErrors.push(...result);
2906
+ }
2907
+ }
2908
+ return {
2909
+ valid: allErrors.length === 0,
2910
+ errors: allErrors
2911
+ };
2912
+ };
2913
+ }
2914
+ function createFieldValidator(field, predicate, message) {
2915
+ return (state) => {
2916
+ const valid = predicate(state[field], state);
2917
+ return {
2918
+ valid,
2919
+ errors: valid ? [] : [{ path: [String(field)], message, value: state[field] }]
2920
+ };
2921
+ };
2922
+ }
2923
+ function createAsyncValidator(validator) {
2924
+ return async (state) => {
2925
+ const errors = await validator(state);
2926
+ return {
2927
+ valid: errors.length === 0,
2928
+ errors
2929
+ };
2930
+ };
2931
+ }
2932
+
2933
+ // src/testing.ts
2934
+ function createMockStorage() {
2935
+ const storage = /* @__PURE__ */ new Map();
2936
+ return {
2937
+ getItem(key) {
2938
+ return storage.get(key) ?? null;
2939
+ },
2940
+ setItem(key, value) {
2941
+ storage.set(key, value);
2942
+ },
2943
+ removeItem(key) {
2944
+ storage.delete(key);
2945
+ },
2946
+ clear() {
2947
+ storage.clear();
2948
+ },
2949
+ getAll() {
2950
+ const result = {};
2951
+ for (const [key, value] of storage) {
2952
+ result[key] = value;
2953
+ }
2954
+ return result;
2955
+ }
2956
+ };
2957
+ }
2958
+ function spyOnStore(store) {
2959
+ const changes = [];
2960
+ const waiters = [];
2961
+ const unsubscribe = store.subscribe((state, prevState) => {
2962
+ changes.push({
2963
+ state,
2964
+ prevState,
2965
+ timestamp: Date.now()
2966
+ });
2967
+ for (let i = waiters.length - 1; i >= 0; i--) {
2968
+ const waiter = waiters[i];
2969
+ if (waiter && waiter.predicate(state)) {
2970
+ waiter.resolve(state);
2971
+ waiters.splice(i, 1);
2972
+ }
2973
+ }
2974
+ });
2975
+ return {
2976
+ changes,
2977
+ lastChange: () => changes[changes.length - 1],
2978
+ lastState: () => changes[changes.length - 1]?.state,
2979
+ reset: () => {
2980
+ changes.length = 0;
2981
+ },
2982
+ unsubscribe,
2983
+ waitFor: (predicate, timeout = 5e3) => {
2984
+ return new Promise((resolve, reject) => {
2985
+ const current = store.getState();
2986
+ if (predicate(current)) {
2987
+ resolve(current);
2988
+ return;
2989
+ }
2990
+ const waiter = { resolve, predicate };
2991
+ waiters.push(waiter);
2992
+ const timeoutId = setTimeout(() => {
2993
+ const index = waiters.indexOf(waiter);
2994
+ if (index >= 0) {
2995
+ waiters.splice(index, 1);
2996
+ reject(new Error(`waitFor timeout after ${timeout}ms`));
2997
+ }
2998
+ }, timeout);
2999
+ const originalResolve = waiter.resolve;
3000
+ waiter.resolve = (state) => {
3001
+ clearTimeout(timeoutId);
3002
+ originalResolve(state);
3003
+ };
1260
3004
  });
3005
+ },
3006
+ waitForChanges: (count, timeout = 5e3) => {
3007
+ return new Promise((resolve, reject) => {
3008
+ const startCount = changes.length;
3009
+ const check = () => {
3010
+ if (changes.length >= startCount + count) {
3011
+ return changes.slice(startCount, startCount + count);
3012
+ }
3013
+ return null;
3014
+ };
3015
+ const immediate = check();
3016
+ if (immediate) {
3017
+ resolve(immediate);
3018
+ return;
3019
+ }
3020
+ const intervalId = setInterval(() => {
3021
+ const result = check();
3022
+ if (result) {
3023
+ clearInterval(intervalId);
3024
+ clearTimeout(timeoutId);
3025
+ resolve(result);
3026
+ }
3027
+ }, 10);
3028
+ const timeoutId = setTimeout(() => {
3029
+ clearInterval(intervalId);
3030
+ reject(new Error(`waitForChanges timeout after ${timeout}ms`));
3031
+ }, timeout);
3032
+ });
3033
+ }
3034
+ };
3035
+ }
3036
+ function assertState(store) {
3037
+ return {
3038
+ toEqual: (expected) => {
3039
+ const state = store.getState();
3040
+ for (const [key, value] of Object.entries(expected)) {
3041
+ if (state[key] !== value) {
3042
+ throw new Error(
3043
+ `Expected state.${key} to be ${JSON.stringify(value)}, but got ${JSON.stringify(state[key])}`
3044
+ );
3045
+ }
3046
+ }
3047
+ },
3048
+ toHaveSelected: (selector2, expected) => {
3049
+ const actual = selector2(store.getState());
3050
+ if (!shallowEqual(actual, expected)) {
3051
+ throw new Error(
3052
+ `Expected selector to return ${JSON.stringify(expected)}, but got ${JSON.stringify(actual)}`
3053
+ );
3054
+ }
3055
+ },
3056
+ toMatch: (predicate) => {
3057
+ const state = store.getState();
3058
+ if (!predicate(state)) {
3059
+ throw new Error(
3060
+ `State did not match predicate: ${JSON.stringify(state)}`
3061
+ );
3062
+ }
1261
3063
  }
1262
3064
  };
1263
3065
  }
3066
+ function createTestStore(options) {
3067
+ const { initialState, spy: enableSpy = true } = options;
3068
+ const store = createStore(initialState);
3069
+ const spy = enableSpy ? spyOnStore(store) : void 0;
3070
+ const assert = assertState(store);
3071
+ return {
3072
+ store,
3073
+ spy,
3074
+ assert,
3075
+ reset: () => {
3076
+ store.reset();
3077
+ spy?.reset();
3078
+ },
3079
+ destroy: () => {
3080
+ spy?.unsubscribe();
3081
+ store.destroy();
3082
+ }
3083
+ };
3084
+ }
3085
+ function delay(ms) {
3086
+ return new Promise((resolve) => setTimeout(resolve, ms));
3087
+ }
3088
+ async function flushMicrotasks(fn) {
3089
+ if (fn) {
3090
+ fn();
3091
+ }
3092
+ await Promise.resolve();
3093
+ }
3094
+ function mockAction(fn) {
3095
+ const calls = [];
3096
+ const mocked = ((...args) => {
3097
+ calls.push(args);
3098
+ return fn(...args);
3099
+ });
3100
+ Object.defineProperty(mocked, "callCount", {
3101
+ get: () => calls.length
3102
+ });
3103
+ mocked.calls = calls;
3104
+ mocked.reset = () => {
3105
+ calls.length = 0;
3106
+ };
3107
+ return mocked;
3108
+ }
3109
+ function snapshot(store) {
3110
+ return JSON.parse(JSON.stringify(store.getState()));
3111
+ }
3112
+ function stateDiff(before, after) {
3113
+ const diff = {};
3114
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
3115
+ for (const key of allKeys) {
3116
+ if (!shallowEqual(before[key], after[key])) {
3117
+ diff[key] = { before: before[key], after: after[key] };
3118
+ }
3119
+ }
3120
+ return diff;
3121
+ }
3122
+
3123
+ // src/compat/middleware.ts
3124
+ function toMiddlewareApi(store) {
3125
+ return {
3126
+ setState: (partial, replace) => {
3127
+ if (typeof partial === "function") {
3128
+ const currentState = store.getState();
3129
+ const newPartial = partial(currentState);
3130
+ if (replace) {
3131
+ store.setState(newPartial);
3132
+ } else {
3133
+ store.merge(newPartial);
3134
+ }
3135
+ } else {
3136
+ if (replace) {
3137
+ store.setState(partial);
3138
+ } else {
3139
+ store.merge(partial);
3140
+ }
3141
+ }
3142
+ },
3143
+ getState: () => store.getState(),
3144
+ subscribe: (listener) => store.subscribe(listener),
3145
+ destroy: () => store.destroy()
3146
+ };
3147
+ }
3148
+ function middlewareCompat(middleware, _options) {
3149
+ return {
3150
+ name: "middleware-compat",
3151
+ version: "1.0.0",
3152
+ install(store) {
3153
+ const api = toMiddlewareApi(store);
3154
+ const stateCreator = (set, get) => {
3155
+ return get();
3156
+ };
3157
+ const enhancedCreator = middleware(stateCreator);
3158
+ const enhancedState = enhancedCreator(api.setState, api.getState, api);
3159
+ if (enhancedState && typeof enhancedState === "object") {
3160
+ const currentState = store.getState();
3161
+ const stateOnly = {};
3162
+ for (const key in enhancedState) {
3163
+ const value = enhancedState[key];
3164
+ if (typeof value !== "function") {
3165
+ stateOnly[key] = value;
3166
+ }
3167
+ }
3168
+ if (Object.keys(stateOnly).length > 0) {
3169
+ const hasChanges = Object.keys(stateOnly).some(
3170
+ (key) => currentState[key] !== stateOnly[key]
3171
+ );
3172
+ if (hasChanges) {
3173
+ store.merge(stateOnly);
3174
+ }
3175
+ }
3176
+ }
3177
+ }
3178
+ };
3179
+ }
3180
+ function createWithMiddleware(creator) {
3181
+ let currentState = null;
3182
+ let storeRef = null;
3183
+ const set = (partial, replace) => {
3184
+ if (!storeRef) {
3185
+ throw new Error("Store not initialized");
3186
+ }
3187
+ if (typeof partial === "function") {
3188
+ const newPartial = partial(storeRef.getState());
3189
+ if (replace) {
3190
+ storeRef.setState(newPartial);
3191
+ } else {
3192
+ storeRef.merge(newPartial);
3193
+ }
3194
+ } else {
3195
+ if (replace) {
3196
+ storeRef.setState(partial);
3197
+ } else {
3198
+ storeRef.merge(partial);
3199
+ }
3200
+ }
3201
+ };
3202
+ const get = () => {
3203
+ if (storeRef) {
3204
+ return storeRef.getState();
3205
+ }
3206
+ if (currentState) {
3207
+ return currentState;
3208
+ }
3209
+ throw new Error("Store not initialized");
3210
+ };
3211
+ const placeholderApi = {
3212
+ setState: set,
3213
+ getState: get,
3214
+ subscribe: () => () => {
3215
+ }
3216
+ };
3217
+ currentState = creator(set, get, placeholderApi);
3218
+ storeRef = createStore(currentState);
3219
+ const api = {
3220
+ setState: (partial, replace) => {
3221
+ if (typeof partial === "function") {
3222
+ const newPartial = partial(storeRef.getState());
3223
+ if (replace) {
3224
+ storeRef.setState(newPartial);
3225
+ } else {
3226
+ storeRef.merge(newPartial);
3227
+ }
3228
+ } else {
3229
+ if (replace) {
3230
+ storeRef.setState(partial);
3231
+ } else {
3232
+ storeRef.merge(partial);
3233
+ }
3234
+ }
3235
+ },
3236
+ getState: () => storeRef.getState(),
3237
+ subscribe: (listener) => storeRef.subscribe(listener),
3238
+ destroy: () => storeRef.destroy(),
3239
+ use: (plugin) => {
3240
+ storeRef.use(plugin);
3241
+ return api;
3242
+ }
3243
+ };
3244
+ return api;
3245
+ }
3246
+ function createSimpleMiddleware(name, enhancer) {
3247
+ const middleware = enhancer;
3248
+ Object.defineProperty(middleware, "name", { value: name });
3249
+ return middleware;
3250
+ }
3251
+ function compose(...middlewares) {
3252
+ return (creator) => {
3253
+ return middlewares.reduceRight((acc, middleware) => {
3254
+ return middleware(acc);
3255
+ }, creator);
3256
+ };
3257
+ }
1264
3258
 
1265
3259
  exports.StoreError = StoreError;
1266
3260
  exports.StoreErrorCode = StoreErrorCode;
3261
+ exports.assertState = assertState;
1267
3262
  exports.batch = batch;
3263
+ exports.combineComputed = combineComputed;
3264
+ exports.combineEffects = combineEffects;
3265
+ exports.combineSlices = combineSlices;
3266
+ exports.combineValidators = combineValidators;
3267
+ exports.compose = compose;
3268
+ exports.computed = computed;
3269
+ exports.createAsyncValidator = createAsyncValidator;
3270
+ exports.createDebouncedEffect = createDebouncedEffect;
3271
+ exports.createEffect = createEffect;
3272
+ exports.createFederatedComputed = createFederatedComputed;
3273
+ exports.createFederatedSelector = createFederatedSelector;
3274
+ exports.createFederation = createFederation;
3275
+ exports.createFieldValidator = createFieldValidator;
3276
+ exports.createLogger = createLogger;
3277
+ exports.createMockStorage = createMockStorage;
3278
+ exports.createNamespacedSlice = createNamespacedSlice;
3279
+ exports.createSimpleEffect = createSimpleEffect;
3280
+ exports.createSimpleMiddleware = createSimpleMiddleware;
3281
+ exports.createSlice = createSlice;
1268
3282
  exports.createStorage = createStorage;
1269
3283
  exports.createStore = createStore;
3284
+ exports.createSubscriber = createSubscriber;
3285
+ exports.createTestStore = createTestStore;
3286
+ exports.createValidator = createValidator;
3287
+ exports.createWithMiddleware = createWithMiddleware;
1270
3288
  exports.deepClone = deepClone;
1271
3289
  exports.deepEqual = deepEqual;
1272
3290
  exports.deepMerge = deepMerge;
3291
+ exports.delay = delay;
1273
3292
  exports.devtools = devtools;
3293
+ exports.effects = effects;
3294
+ exports.extendStore = extendStore;
3295
+ exports.flushMicrotasks = flushMicrotasks;
1274
3296
  exports.hasHistory = hasHistory;
1275
3297
  exports.history = history;
1276
3298
  exports.identity = identity;
1277
3299
  exports.immer = immer;
1278
3300
  exports.isFunction = isFunction;
3301
+ exports.logger = logger;
3302
+ exports.memoizeSelector = memoizeSelector;
3303
+ exports.middlewareCompat = middlewareCompat;
3304
+ exports.mockAction = mockAction;
1279
3305
  exports.omit = omit;
1280
3306
  exports.persist = persist;
1281
3307
  exports.pick = pick;
1282
3308
  exports.produce = produce;
3309
+ exports.resetSlices = resetSlices;
1283
3310
  exports.selector = selector;
1284
3311
  exports.sessionStorage = sessionStorage;
1285
3312
  exports.shallowEqual = shallowEqual;
3313
+ exports.snapshot = snapshot;
3314
+ exports.spyOnStore = spyOnStore;
3315
+ exports.stateDiff = stateDiff;
3316
+ exports.subscribeOnce = subscribeOnce;
3317
+ exports.subscribeToMany = subscribeToMany;
3318
+ exports.subscribeWithOptions = subscribeWithOptions;
1286
3319
  exports.sync = sync;
3320
+ exports.toMiddlewareApi = toMiddlewareApi;
1287
3321
  exports.triggerSync = triggerSync;
1288
3322
  exports.useAction = useAction;
1289
3323
  exports.useCreateStore = useCreateStore;
3324
+ exports.useSetState = useSetState;
3325
+ exports.useShallow = useShallow;
1290
3326
  exports.useStore = useStore;
3327
+ exports.useStoreActions = useStoreActions;
3328
+ exports.useStoreSelector = useStoreSelector;
3329
+ exports.useTransientSubscribe = useTransientSubscribe;
3330
+ exports.validate = validate;
3331
+ exports.waitForFederated = waitForFederated;
1291
3332
  //# sourceMappingURL=index.cjs.map
1292
3333
  //# sourceMappingURL=index.cjs.map