@oxog/state 1.3.0 → 1.3.1

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