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