@oxog/state 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,27 +2,6 @@
2
2
 
3
3
  var react = require('react');
4
4
 
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
-
26
5
  // src/utils/deep-clone.ts
27
6
  function deepClone(value, seen) {
28
7
  if (value === null || typeof value !== "object") {
@@ -50,7 +29,7 @@ function deepClone(value, seen) {
50
29
  const cloned = {};
51
30
  seen.set(value, cloned);
52
31
  for (const key in value) {
53
- if (Object.prototype.hasOwnProperty.call(value, key)) {
32
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(value, key)) {
54
33
  cloned[key] = deepClone(value[key], seen);
55
34
  }
56
35
  }
@@ -58,10 +37,6 @@ function deepClone(value, seen) {
58
37
  }
59
38
  return value;
60
39
  }
61
- var init_deep_clone = __esm({
62
- "src/utils/deep-clone.ts"() {
63
- }
64
- });
65
40
 
66
41
  // src/utils/deep-equal.ts
67
42
  function deepEqual(a, b) {
@@ -98,10 +73,6 @@ function deepEqual(a, b) {
98
73
  }
99
74
  return true;
100
75
  }
101
- var init_deep_equal = __esm({
102
- "src/utils/deep-equal.ts"() {
103
- }
104
- });
105
76
 
106
77
  // src/utils/shallow-equal.ts
107
78
  function shallowEqual(a, b) {
@@ -123,10 +94,6 @@ function shallowEqual(a, b) {
123
94
  }
124
95
  return true;
125
96
  }
126
- var init_shallow_equal = __esm({
127
- "src/utils/shallow-equal.ts"() {
128
- }
129
- });
130
97
 
131
98
  // src/utils/deep-merge.ts
132
99
  function deepMerge(target, source) {
@@ -138,14 +105,14 @@ function deepMerge(target, source) {
138
105
  }
139
106
  const output = deepClone(target);
140
107
  for (const key in source) {
141
- if (Object.prototype.hasOwnProperty.call(source, key)) {
108
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(source, key)) {
142
109
  const sourceValue = source[key];
143
110
  const targetValue = output[key];
144
111
  if (sourceValue instanceof Date) {
145
112
  output[key] = new Date(sourceValue.getTime());
146
113
  continue;
147
114
  }
148
- if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date)) {
115
+ if (Object.prototype.hasOwnProperty.call(output, key) && sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date)) {
149
116
  output[key] = deepMerge(targetValue, sourceValue);
150
117
  } else {
151
118
  output[key] = cloneValue(sourceValue);
@@ -167,7 +134,7 @@ function cloneValue(value) {
167
134
  if (value.constructor === Object) {
168
135
  const cloned = {};
169
136
  for (const key in value) {
170
- if (Object.prototype.hasOwnProperty.call(value, key)) {
137
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(value, key)) {
171
138
  cloned[key] = cloneValue(value[key]);
172
139
  }
173
140
  }
@@ -175,20 +142,11 @@ function cloneValue(value) {
175
142
  }
176
143
  return value;
177
144
  }
178
- var init_deep_merge = __esm({
179
- "src/utils/deep-merge.ts"() {
180
- init_deep_clone();
181
- }
182
- });
183
145
 
184
146
  // src/utils/is-function.ts
185
147
  function isFunction(value) {
186
148
  return typeof value === "function";
187
149
  }
188
- var init_is_function = __esm({
189
- "src/utils/is-function.ts"() {
190
- }
191
- });
192
150
 
193
151
  // src/utils/pick.ts
194
152
  function pick(obj, keys) {
@@ -200,10 +158,6 @@ function pick(obj, keys) {
200
158
  }
201
159
  return result;
202
160
  }
203
- var init_pick = __esm({
204
- "src/utils/pick.ts"() {
205
- }
206
- });
207
161
 
208
162
  // src/utils/omit.ts
209
163
  function omit(obj, keys) {
@@ -213,251 +167,227 @@ function omit(obj, keys) {
213
167
  }
214
168
  return result;
215
169
  }
216
- var init_omit = __esm({
217
- "src/utils/omit.ts"() {
218
- }
219
- });
220
170
 
221
171
  // src/utils/identity.ts
222
172
  function identity(value) {
223
173
  return value;
224
174
  }
225
- var init_identity = __esm({
226
- "src/utils/identity.ts"() {
227
- }
228
- });
229
-
230
- // src/utils/index.ts
231
- var init_utils = __esm({
232
- "src/utils/index.ts"() {
233
- init_deep_clone();
234
- init_deep_equal();
235
- init_shallow_equal();
236
- init_deep_merge();
237
- init_is_function();
238
- init_pick();
239
- init_omit();
240
- init_identity();
241
- }
242
- });
243
175
 
244
176
  // src/kernel.ts
245
- function createKernel(config) {
246
- return new Kernel(config);
247
- }
248
- var EventBus, Kernel;
249
- var init_kernel = __esm({
250
- "src/kernel.ts"() {
251
- EventBus = class {
252
- listeners = /* @__PURE__ */ new Map();
253
- /**
254
- * Subscribe to an event.
255
- *
256
- * @param event - Event name
257
- * @param handler - Event handler
258
- * @returns Unsubscribe function
259
- */
260
- on(event, handler) {
261
- if (!this.listeners.has(event)) {
262
- this.listeners.set(event, /* @__PURE__ */ new Set());
263
- }
264
- this.listeners.get(event).add(handler);
265
- return () => {
266
- this.listeners.get(event)?.delete(handler);
267
- };
268
- }
269
- /**
270
- * Emit an event to all subscribers.
271
- *
272
- * @param event - Event name
273
- * @param data - Event data
274
- */
275
- emit(event, data) {
276
- const handlers = this.listeners.get(event);
277
- if (handlers) {
278
- for (const handler of handlers) {
279
- try {
280
- handler(data);
281
- } catch (error) {
282
- console.error(`Error in ${event} handler:`, error);
283
- }
284
- }
285
- }
286
- }
287
- /** Clear all listeners. */
288
- destroy() {
289
- this.listeners.clear();
290
- }
177
+ var EventBus = class {
178
+ listeners = /* @__PURE__ */ new Map();
179
+ /**
180
+ * Subscribe to an event.
181
+ *
182
+ * @param event - Event name
183
+ * @param handler - Event handler
184
+ * @returns Unsubscribe function
185
+ */
186
+ on(event, handler) {
187
+ if (!this.listeners.has(event)) {
188
+ this.listeners.set(event, /* @__PURE__ */ new Set());
189
+ }
190
+ this.listeners.get(event).add(handler);
191
+ return () => {
192
+ this.listeners.get(event)?.delete(handler);
291
193
  };
292
- Kernel = class {
293
- plugins = /* @__PURE__ */ new Map();
294
- eventBus = new EventBus();
295
- config;
296
- errorHandlers = /* @__PURE__ */ new Set();
297
- initializing = false;
298
- constructor(config) {
299
- this.config = config || {};
300
- }
301
- /**
302
- * Register a plugin.
303
- *
304
- * @param plugin - The plugin to register
305
- * @param options - Plugin options
306
- * @param store - The store instance
307
- * @throws {Error} If plugin already registered or dependencies missing
308
- */
309
- register(plugin, options, store) {
310
- if (!plugin.name || !plugin.version || typeof plugin.install !== "function") {
311
- throw new Error("Invalid plugin: must have name, version, and install function");
312
- }
313
- if (this.plugins.has(plugin.name)) {
314
- throw new Error(`Plugin '${plugin.name}' is already registered`);
315
- }
316
- if (plugin.dependencies) {
317
- for (const dep of plugin.dependencies) {
318
- if (!this.plugins.has(dep)) {
319
- throw new Error(
320
- `Plugin '${plugin.name}' requires '${dep}' to be registered first`
321
- );
322
- }
323
- }
324
- }
325
- const instance = {
326
- plugin,
327
- options
328
- };
194
+ }
195
+ /**
196
+ * Emit an event to all subscribers.
197
+ *
198
+ * @param event - Event name
199
+ * @param data - Event data
200
+ */
201
+ emit(event, data) {
202
+ const handlers = this.listeners.get(event);
203
+ if (handlers) {
204
+ for (const handler of handlers) {
329
205
  try {
330
- plugin.install(store, options);
206
+ handler(data);
331
207
  } catch (error) {
332
- throw new Error(`Failed to install plugin '${plugin.name}': ${error}`);
333
- }
334
- this.plugins.set(plugin.name, instance);
335
- if (!this.initializing && plugin.onInit) {
336
- this.runOnInit(plugin, store);
208
+ console.error(`Error in ${event} handler:`, error);
337
209
  }
338
210
  }
339
- /**
340
- * Initialize all plugins.
341
- *
342
- * @param store - The store instance
343
- */
344
- async initializeAll(store) {
345
- this.initializing = true;
346
- const plugins = Array.from(this.plugins.values());
347
- for (const { plugin } of plugins) {
348
- if (plugin.onInit) {
349
- await this.runOnInit(plugin, store);
350
- }
211
+ }
212
+ }
213
+ /** Clear all listeners. */
214
+ destroy() {
215
+ this.listeners.clear();
216
+ }
217
+ };
218
+ var Kernel = class {
219
+ plugins = /* @__PURE__ */ new Map();
220
+ eventBus = new EventBus();
221
+ config;
222
+ errorHandlers = /* @__PURE__ */ new Set();
223
+ initializing = false;
224
+ constructor(config) {
225
+ this.config = config || {};
226
+ }
227
+ /**
228
+ * Register a plugin.
229
+ *
230
+ * @param plugin - The plugin to register
231
+ * @param options - Plugin options
232
+ * @param store - The store instance
233
+ * @throws {Error} If plugin already registered or dependencies missing
234
+ */
235
+ register(plugin, options, store) {
236
+ if (!plugin.name || !plugin.version || typeof plugin.install !== "function") {
237
+ throw new Error("Invalid plugin: must have name, version, and install function");
238
+ }
239
+ if (this.plugins.has(plugin.name)) {
240
+ throw new Error(`Plugin '${plugin.name}' is already registered`);
241
+ }
242
+ if (plugin.dependencies) {
243
+ for (const dep of plugin.dependencies) {
244
+ if (!this.plugins.has(dep)) {
245
+ throw new Error(
246
+ `Plugin '${plugin.name}' requires '${dep}' to be registered first`
247
+ );
351
248
  }
352
- this.initializing = false;
353
249
  }
354
- /**
355
- * Run plugin's onInit safely.
356
- */
357
- async runOnInit(plugin, store) {
250
+ }
251
+ const instance = {
252
+ plugin,
253
+ options
254
+ };
255
+ try {
256
+ plugin.install(store, options);
257
+ } catch (error) {
258
+ throw new Error(`Failed to install plugin '${plugin.name}': ${error}`);
259
+ }
260
+ this.plugins.set(plugin.name, instance);
261
+ if (!this.initializing && plugin.onInit) {
262
+ this.runOnInit(plugin, store);
263
+ }
264
+ }
265
+ /**
266
+ * Initialize all plugins.
267
+ *
268
+ * @param store - The store instance
269
+ */
270
+ async initializeAll(store) {
271
+ this.initializing = true;
272
+ const plugins = Array.from(this.plugins.values());
273
+ for (const { plugin } of plugins) {
274
+ if (plugin.onInit) {
275
+ await this.runOnInit(plugin, store);
276
+ }
277
+ }
278
+ this.initializing = false;
279
+ }
280
+ /**
281
+ * Run plugin's onInit safely.
282
+ */
283
+ async runOnInit(plugin, store) {
284
+ try {
285
+ await plugin.onInit(store);
286
+ } catch (error) {
287
+ console.error(`Error in ${plugin.name} onInit:`, error);
288
+ }
289
+ }
290
+ /**
291
+ * Unregister a plugin.
292
+ *
293
+ * @param name - Plugin name
294
+ */
295
+ async unregister(name) {
296
+ const instance = this.plugins.get(name);
297
+ if (!instance) {
298
+ return;
299
+ }
300
+ if (instance.plugin.onDestroy) {
301
+ try {
302
+ await instance.plugin.onDestroy();
303
+ } catch (error) {
304
+ console.error(`Error in ${name} onDestroy:`, error);
305
+ }
306
+ }
307
+ this.plugins.delete(name);
308
+ }
309
+ /**
310
+ * Emit a state change event.
311
+ *
312
+ * @param state - New state
313
+ * @param prevState - Previous state
314
+ */
315
+ emitStateChange(state, prevState) {
316
+ this.eventBus.emit("stateChange", { state, prevState });
317
+ for (const { plugin } of this.plugins.values()) {
318
+ if (plugin.onStateChange) {
358
319
  try {
359
- await plugin.onInit(store);
320
+ plugin.onStateChange(state, prevState);
360
321
  } catch (error) {
361
- console.error(`Error in ${plugin.name} onInit:`, error);
362
- }
363
- }
364
- /**
365
- * Unregister a plugin.
366
- *
367
- * @param name - Plugin name
368
- */
369
- async unregister(name) {
370
- const instance = this.plugins.get(name);
371
- if (!instance) {
372
- return;
373
- }
374
- if (instance.plugin.onDestroy) {
375
- try {
376
- await instance.plugin.onDestroy();
377
- } catch (error) {
378
- console.error(`Error in ${name} onDestroy:`, error);
379
- }
380
- }
381
- this.plugins.delete(name);
382
- }
383
- /**
384
- * Emit a state change event.
385
- *
386
- * @param state - New state
387
- * @param prevState - Previous state
388
- */
389
- emitStateChange(state, prevState) {
390
- this.eventBus.emit("stateChange", { state, prevState });
391
- for (const { plugin } of this.plugins.values()) {
392
- if (plugin.onStateChange) {
393
- try {
394
- plugin.onStateChange(state, prevState);
395
- } catch (error) {
396
- console.error(`Error in ${plugin.name} onStateChange:`, error);
397
- }
398
- }
322
+ console.error(`Error in ${plugin.name} onStateChange:`, error);
399
323
  }
400
324
  }
401
- /**
402
- * Emit an error event.
403
- *
404
- * @param error - The error
405
- */
406
- emitError(error) {
407
- this.eventBus.emit("error", error);
408
- for (const { plugin } of this.plugins.values()) {
409
- if (plugin.onError) {
410
- try {
411
- plugin.onError(error);
412
- } catch (err) {
413
- console.error(`Error in ${plugin.name} onError:`, err);
414
- }
415
- }
416
- }
417
- for (const handler of this.errorHandlers) {
418
- try {
419
- handler(error);
420
- } catch (err) {
421
- console.error("Error in error handler:", err);
422
- }
325
+ }
326
+ }
327
+ /**
328
+ * Emit an error event.
329
+ *
330
+ * @param error - The error
331
+ */
332
+ emitError(error) {
333
+ this.eventBus.emit("error", error);
334
+ for (const { plugin } of this.plugins.values()) {
335
+ if (plugin.onError) {
336
+ try {
337
+ plugin.onError(error);
338
+ } catch (err) {
339
+ console.error(`Error in ${plugin.name} onError:`, err);
423
340
  }
424
341
  }
425
- /**
426
- * Add an error handler.
427
- *
428
- * @param handler - Error handler function
429
- * @returns Unsubscribe function
430
- */
431
- onError(handler) {
432
- this.errorHandlers.add(handler);
433
- return () => {
434
- this.errorHandlers.delete(handler);
435
- };
436
- }
437
- /**
438
- * Subscribe to an event.
439
- *
440
- * @param event - Event name
441
- * @param handler - Event handler
442
- * @returns Unsubscribe function
443
- */
444
- on(event, handler) {
445
- return this.eventBus.on(event, handler);
446
- }
447
- /** Destroy the kernel and cleanup. */
448
- async destroy() {
449
- const pluginNames = Array.from(this.plugins.keys());
450
- for (const name of pluginNames) {
451
- await this.unregister(name);
452
- }
453
- this.eventBus.destroy();
454
- this.errorHandlers.clear();
342
+ }
343
+ for (const handler of this.errorHandlers) {
344
+ try {
345
+ handler(error);
346
+ } catch (err) {
347
+ console.error("Error in error handler:", err);
455
348
  }
349
+ }
350
+ }
351
+ /**
352
+ * Add an error handler.
353
+ *
354
+ * @param handler - Error handler function
355
+ * @returns Unsubscribe function
356
+ */
357
+ onError(handler) {
358
+ this.errorHandlers.add(handler);
359
+ return () => {
360
+ this.errorHandlers.delete(handler);
456
361
  };
457
362
  }
458
- });
363
+ /**
364
+ * Subscribe to an event.
365
+ *
366
+ * @param event - Event name
367
+ * @param handler - Event handler
368
+ * @returns Unsubscribe function
369
+ */
370
+ on(event, handler) {
371
+ return this.eventBus.on(event, handler);
372
+ }
373
+ /** Destroy the kernel and cleanup. */
374
+ async destroy() {
375
+ const pluginNames = Array.from(this.plugins.keys());
376
+ for (const name of pluginNames) {
377
+ await this.unregister(name);
378
+ }
379
+ this.eventBus.destroy();
380
+ this.errorHandlers.clear();
381
+ }
382
+ };
383
+ function createKernel(config) {
384
+ return new Kernel(config);
385
+ }
459
386
 
460
387
  // src/batch-context.ts
388
+ var batchDepth = 0;
389
+ var batchStores = /* @__PURE__ */ new Set();
390
+ var batchManagedStores = /* @__PURE__ */ new Set();
461
391
  function isBatching() {
462
392
  return batchDepth > 0;
463
393
  }
@@ -486,125 +416,418 @@ function addManagedStore(store) {
486
416
  function isStoreManaged(store) {
487
417
  return batchManagedStores.has(store);
488
418
  }
489
- var batchDepth, batchStores, batchManagedStores, sharedBatchContext;
490
- var init_batch_context = __esm({
491
- "src/batch-context.ts"() {
492
- batchDepth = 0;
493
- batchStores = /* @__PURE__ */ new Set();
494
- batchManagedStores = /* @__PURE__ */ new Set();
495
- sharedBatchContext = {
496
- get depth() {
497
- return batchDepth;
498
- },
499
- get stores() {
500
- return batchStores;
501
- },
502
- get managedStores() {
503
- return batchManagedStores;
504
- },
505
- isBatching,
506
- batch(store, fn) {
507
- const wasAlreadyBatching = isStoreManaged(store);
508
- incrementBatchDepth();
509
- addBatchStore(store);
510
- if (!wasAlreadyBatching && "beginBatch" in store) {
511
- store.beginBatch();
512
- addManagedStore(store);
513
- }
514
- try {
515
- const result = fn();
516
- decrementBatchDepth();
517
- if (getBatchDepth() === 0) {
518
- for (const s of getBatchManagedStores()) {
519
- if ("flushNotifications" in s) {
520
- s.flushNotifications();
521
- }
522
- if ("endBatch" in s) {
523
- s.endBatch();
524
- }
525
- }
526
- clearBatchStores();
419
+ var sharedBatchContext = {
420
+ get depth() {
421
+ return batchDepth;
422
+ },
423
+ get stores() {
424
+ return batchStores;
425
+ },
426
+ get managedStores() {
427
+ return batchManagedStores;
428
+ },
429
+ isBatching,
430
+ batch(store, fn) {
431
+ const wasAlreadyBatching = isStoreManaged(store);
432
+ incrementBatchDepth();
433
+ addBatchStore(store);
434
+ if (!wasAlreadyBatching && "beginBatch" in store) {
435
+ store.beginBatch();
436
+ addManagedStore(store);
437
+ }
438
+ try {
439
+ const result = fn();
440
+ decrementBatchDepth();
441
+ if (getBatchDepth() === 0) {
442
+ for (const s of getBatchManagedStores()) {
443
+ if ("flushNotifications" in s) {
444
+ s.flushNotifications();
527
445
  }
528
- return result;
529
- } catch (error) {
530
- decrementBatchDepth();
531
- if (getBatchDepth() === 0) {
532
- for (const s of getBatchManagedStores()) {
533
- if ("endBatch" in s) {
534
- s.endBatch();
535
- }
536
- }
537
- clearBatchStores();
446
+ if ("endBatch" in s) {
447
+ s.endBatch();
538
448
  }
539
- throw error;
540
449
  }
450
+ clearBatchStores();
541
451
  }
542
- };
452
+ return result;
453
+ } catch (error) {
454
+ decrementBatchDepth();
455
+ if (getBatchDepth() === 0) {
456
+ for (const s of getBatchManagedStores()) {
457
+ if ("endBatch" in s) {
458
+ s.endBatch();
459
+ }
460
+ }
461
+ clearBatchStores();
462
+ }
463
+ throw error;
464
+ }
543
465
  }
544
- });
466
+ };
545
467
 
546
468
  // src/types.ts
547
- exports.StoreErrorCode = void 0; exports.StoreError = void 0;
548
- var init_types = __esm({
549
- "src/types.ts"() {
550
- exports.StoreErrorCode = /* @__PURE__ */ ((StoreErrorCode2) => {
551
- StoreErrorCode2["STORE_DESTROYED"] = "STORE_DESTROYED";
552
- StoreErrorCode2["PLUGIN_EXISTS"] = "PLUGIN_EXISTS";
553
- StoreErrorCode2["PLUGIN_DEPENDENCY_MISSING"] = "PLUGIN_DEPENDENCY_MISSING";
554
- StoreErrorCode2["INVALID_STATE_UPDATE"] = "INVALID_STATE_UPDATE";
555
- StoreErrorCode2["ACTION_ERROR"] = "ACTION_ERROR";
556
- return StoreErrorCode2;
557
- })(exports.StoreErrorCode || {});
558
- exports.StoreError = class extends Error {
559
- constructor(code, message) {
560
- super(message);
561
- this.code = code;
562
- this.name = "StoreError";
469
+ var StoreErrorCode = /* @__PURE__ */ ((StoreErrorCode2) => {
470
+ StoreErrorCode2["STORE_DESTROYED"] = "STORE_DESTROYED";
471
+ StoreErrorCode2["PLUGIN_EXISTS"] = "PLUGIN_EXISTS";
472
+ StoreErrorCode2["PLUGIN_DEPENDENCY_MISSING"] = "PLUGIN_DEPENDENCY_MISSING";
473
+ StoreErrorCode2["INVALID_STATE_UPDATE"] = "INVALID_STATE_UPDATE";
474
+ StoreErrorCode2["ACTION_ERROR"] = "ACTION_ERROR";
475
+ return StoreErrorCode2;
476
+ })(StoreErrorCode || {});
477
+ var StoreError = class extends Error {
478
+ constructor(code, message) {
479
+ super(message);
480
+ this.code = code;
481
+ this.name = "StoreError";
482
+ }
483
+ };
484
+
485
+ // src/batch.ts
486
+ function batch(fn) {
487
+ incrementBatchDepth();
488
+ try {
489
+ const result = fn();
490
+ decrementBatchDepth();
491
+ if (getBatchDepth() === 0) {
492
+ const storesArray = Array.from(getBatchManagedStores());
493
+ for (const s of storesArray) {
494
+ if ("flushNotifications" in s) {
495
+ s.flushNotifications();
496
+ }
563
497
  }
564
- };
498
+ clearBatchStores();
499
+ }
500
+ return result;
501
+ } catch (error) {
502
+ decrementBatchDepth();
503
+ const storesArray = Array.from(getBatchManagedStores());
504
+ for (const s of storesArray) {
505
+ if ("flushNotifications" in s) {
506
+ s.flushNotifications();
507
+ }
508
+ }
509
+ clearBatchStores();
510
+ throw error;
565
511
  }
566
- });
512
+ }
567
513
 
568
514
  // src/store.ts
569
- var store_exports = {};
570
- __export(store_exports, {
571
- StoreError: () => exports.StoreError,
572
- StoreErrorCode: () => exports.StoreErrorCode,
573
- StoreImpl: () => StoreImpl,
574
- batch: () => batch,
575
- createStore: () => createStore
576
- });
577
- function createStore(initialState, actions) {
578
- const kernel = createKernel({ name: "store" });
579
- const state = { ...initialState };
580
- const extractedActions = {};
581
- for (const key in state) {
582
- if (isFunction(state[key]) && key.startsWith("$")) {
583
- extractedActions[key.substring(1)] = state[key];
584
- delete state[key];
515
+ var StoreImpl = class {
516
+ state;
517
+ initialState;
518
+ listeners = /* @__PURE__ */ new Set();
519
+ selectorSubscriptions = /* @__PURE__ */ new Set();
520
+ kernel;
521
+ destroyed = false;
522
+ batchDepth = 0;
523
+ pendingNotify = false;
524
+ queuedState = null;
525
+ queuedPrevState = null;
526
+ actions = {};
527
+ /** Incremented on every state change. */
528
+ version = 0;
529
+ /** True while listeners are being notified. */
530
+ notifying = false;
531
+ /** Notifications raised by listeners while notifying; delivered in order. */
532
+ notifyQueue = [];
533
+ constructor(initialState, kernel) {
534
+ this.state = deepClone(initialState);
535
+ this.initialState = deepClone(initialState);
536
+ this.kernel = kernel;
537
+ this.kernel.onError((error) => {
538
+ console.error("Store error:", error);
539
+ });
540
+ }
541
+ /** Get current state snapshot. */
542
+ getState() {
543
+ this.checkNotDestroyed();
544
+ return this.state;
545
+ }
546
+ /** Update state with partial object or function. */
547
+ setState(partial) {
548
+ this.checkNotDestroyed();
549
+ const prevState = this.state;
550
+ const update = typeof partial === "function" ? partial(this.state) : partial;
551
+ if (update === null || update === void 0) {
552
+ return;
553
+ }
554
+ this.state = { ...this.state, ...withoutProtoKey(update) };
555
+ this.notifyOrQueue(this.state, prevState);
556
+ }
557
+ /** Deep merge state. */
558
+ merge(partial) {
559
+ this.checkNotDestroyed();
560
+ const prevState = this.state;
561
+ this.state = deepMerge(this.state, partial);
562
+ this.notifyOrQueue(this.state, prevState);
563
+ }
564
+ /** Reset to initial state. */
565
+ reset() {
566
+ this.checkNotDestroyed();
567
+ const prevState = this.state;
568
+ this.state = deepClone(this.initialState);
569
+ this.notifyOrQueue(this.state, prevState);
570
+ }
571
+ subscribe(arg1, arg2, arg3) {
572
+ this.checkNotDestroyed();
573
+ if (arg2 === void 0 && typeof arg1 === "function") {
574
+ const subscription2 = { listener: arg1, since: this.version };
575
+ this.listeners.add(subscription2);
576
+ return () => {
577
+ this.listeners.delete(subscription2);
578
+ };
585
579
  }
580
+ const subscription = {
581
+ selector: arg1,
582
+ listener: arg2,
583
+ equalityFn: arg3 || shallowEqual,
584
+ value: arg1(this.state)
585
+ };
586
+ this.selectorSubscriptions.add(subscription);
587
+ return () => {
588
+ this.selectorSubscriptions.delete(subscription);
589
+ };
586
590
  }
587
- const allActions = { ...extractedActions, ...actions };
588
- const builder = new StoreBuilderImpl(state, kernel);
589
- if (allActions) {
590
- for (const [name, fn] of Object.entries(allActions)) {
591
- builder.addAction(name, fn);
591
+ /** Register a plugin. */
592
+ use(plugin, options) {
593
+ this.checkNotDestroyed();
594
+ this.kernel.register(plugin, options, this);
595
+ return this;
596
+ }
597
+ /** Destroy store and cleanup. */
598
+ destroy() {
599
+ if (this.destroyed) {
600
+ return;
601
+ }
602
+ this.destroyed = true;
603
+ this.kernel.destroy().catch((error) => {
604
+ console.error("Error destroying store plugins:", error);
605
+ });
606
+ this.listeners.clear();
607
+ this.selectorSubscriptions.clear();
608
+ this.notifyQueue = [];
609
+ this.actions = {};
610
+ }
611
+ /** Add an action (for fluent builder pattern). */
612
+ addAction(name, fn) {
613
+ this.actions[name] = fn;
614
+ return this;
615
+ }
616
+ /**
617
+ * Expose a bound action on the state object (and on the initial state, so
618
+ * `reset()` keeps it). Construction-time only: no notification is sent.
619
+ */
620
+ exposeAction(name, fn) {
621
+ if (name === "__proto__") return;
622
+ this.state = { ...this.state, [name]: fn };
623
+ this.initialState = { ...this.initialState, [name]: fn };
624
+ }
625
+ /** Get all actions. */
626
+ getActions() {
627
+ return this.actions;
628
+ }
629
+ /** Check if store is destroyed. */
630
+ checkNotDestroyed() {
631
+ if (this.destroyed) {
632
+ throw new Error("Cannot use destroyed store");
633
+ }
634
+ }
635
+ /** Notify listeners or queue if batching. */
636
+ notifyOrQueue(state, prevState) {
637
+ this.version++;
638
+ const inGlobalBatch = sharedBatchContext.isBatching();
639
+ if (inGlobalBatch) {
640
+ const managedStores = sharedBatchContext.managedStores;
641
+ if (!managedStores.has(this)) {
642
+ managedStores.add(this);
643
+ }
644
+ }
645
+ if (this.batchDepth > 0 || inGlobalBatch) {
646
+ this.queuedState = state;
647
+ if (!this.pendingNotify) {
648
+ this.queuedPrevState = prevState;
649
+ }
650
+ this.pendingNotify = true;
651
+ } else {
652
+ this.notify(state, prevState);
653
+ }
654
+ }
655
+ /**
656
+ * Notify all listeners.
657
+ *
658
+ * Re-entrant updates (a listener calling setState) are queued and delivered
659
+ * after the current pass, so every listener sees changes in order and ends
660
+ * on the latest state.
661
+ */
662
+ notify(state, prevState) {
663
+ this.notifyQueue.push({ state, prevState, version: this.version });
664
+ if (this.notifying) {
665
+ return;
666
+ }
667
+ this.notifying = true;
668
+ try {
669
+ let next;
670
+ while ((next = this.notifyQueue.shift()) !== void 0) {
671
+ this.deliver(next);
672
+ }
673
+ } finally {
674
+ this.notifying = false;
675
+ this.notifyQueue = [];
676
+ }
677
+ }
678
+ /** Deliver one notification to plugins and listeners. */
679
+ deliver({ state, prevState, version }) {
680
+ this.kernel.emitStateChange(state, prevState);
681
+ for (const subscription of Array.from(this.listeners)) {
682
+ if (!this.listeners.has(subscription) || subscription.since >= version) {
683
+ continue;
684
+ }
685
+ try {
686
+ subscription.listener(state, prevState);
687
+ } catch (error) {
688
+ this.kernel.emitError(error);
689
+ }
690
+ }
691
+ for (const subscription of Array.from(this.selectorSubscriptions)) {
692
+ if (!this.selectorSubscriptions.has(subscription)) {
693
+ continue;
694
+ }
695
+ try {
696
+ const newValue = subscription.selector(state);
697
+ if (subscription.equalityFn(newValue, subscription.value)) {
698
+ continue;
699
+ }
700
+ const prevValue = subscription.value;
701
+ subscription.value = newValue;
702
+ subscription.listener(newValue, prevValue);
703
+ } catch (error) {
704
+ this.kernel.emitError(error);
705
+ }
706
+ }
707
+ }
708
+ /** Flush pending notifications (end of batch). */
709
+ flushNotifications() {
710
+ if (this.pendingNotify) {
711
+ const state = this.queuedState;
712
+ const prevState = this.queuedPrevState;
713
+ this.pendingNotify = false;
714
+ this.queuedState = null;
715
+ this.queuedPrevState = null;
716
+ if (!this.destroyed) {
717
+ this.notify(state, prevState);
718
+ }
719
+ }
720
+ }
721
+ /** Start batching. */
722
+ beginBatch() {
723
+ this.batchDepth++;
724
+ }
725
+ /** End batching. */
726
+ endBatch() {
727
+ this.batchDepth--;
728
+ if (this.batchDepth === 0) {
729
+ this.flushNotifications();
730
+ }
731
+ }
732
+ };
733
+ function withoutProtoKey(update) {
734
+ if (update !== null && typeof update === "object" && Object.prototype.hasOwnProperty.call(update, "__proto__")) {
735
+ const copy = {};
736
+ for (const key of Object.keys(update)) {
737
+ if (key !== "__proto__") copy[key] = update[key];
738
+ }
739
+ return copy;
740
+ }
741
+ return update;
742
+ }
743
+ var StoreBuilderImpl = class {
744
+ store;
745
+ constructor(initialState, kernel) {
746
+ this.store = new StoreImpl(initialState, kernel);
747
+ }
748
+ getState() {
749
+ return this.store.getState();
750
+ }
751
+ setState(partial) {
752
+ this.store.setState(partial);
753
+ }
754
+ merge(partial) {
755
+ this.store.merge(partial);
756
+ }
757
+ reset() {
758
+ this.store.reset();
759
+ }
760
+ subscribe(arg1, arg2, arg3) {
761
+ if (arg2 === void 0) {
762
+ return this.store.subscribe(arg1);
763
+ } else {
764
+ return this.store.subscribe(arg1, arg2, arg3);
592
765
  }
593
766
  }
594
- const actionList = builder.getActions();
595
- for (const [name, fn] of Object.entries(actionList)) {
596
- builder[name] = (...args) => {
597
- const currentState = builder.getState();
598
- const result = fn(currentState, ...args);
767
+ use(plugin, options) {
768
+ this.store.use(plugin, options);
769
+ return this;
770
+ }
771
+ destroy() {
772
+ this.store.destroy();
773
+ }
774
+ action(name, fn) {
775
+ this.store.addAction(name, fn);
776
+ const bound = (...args) => {
777
+ const result = fn(this.getState(), ...args);
599
778
  if (result instanceof Promise) {
600
779
  return result.then((partial) => {
601
- builder.setState(partial);
780
+ this.setState(partial);
602
781
  return partial;
603
782
  });
604
783
  }
605
- builder.setState(result);
784
+ this.setState(result);
606
785
  return result;
607
786
  };
787
+ Object.defineProperty(bound, "name", { value: name, configurable: true });
788
+ this[name] = bound;
789
+ this.store.exposeAction(name, bound);
790
+ return this;
791
+ }
792
+ /** Add action (internal use). */
793
+ addAction(name, fn) {
794
+ this.store.addAction(name, fn);
795
+ return this;
796
+ }
797
+ /** Get actions (internal use). */
798
+ getActions() {
799
+ return this.store.getActions();
800
+ }
801
+ /** Start batching. */
802
+ beginBatch() {
803
+ this.store.beginBatch();
804
+ }
805
+ /** End batching. */
806
+ endBatch() {
807
+ this.store.endBatch();
808
+ }
809
+ /** Flush pending notifications. */
810
+ flushNotifications() {
811
+ this.store.flushNotifications();
812
+ }
813
+ };
814
+ function createStore(initialState, actions) {
815
+ const kernel = createKernel({ name: "store" });
816
+ const state = {};
817
+ const extractedActions = {};
818
+ for (const key of Object.keys(initialState)) {
819
+ const value = initialState[key];
820
+ if (key === "__proto__") continue;
821
+ if (isFunction(value) && key.startsWith("$")) {
822
+ extractedActions[key.substring(1)] = value;
823
+ } else {
824
+ state[key] = value;
825
+ }
826
+ }
827
+ const allActions = { ...extractedActions, ...actions };
828
+ const builder = new StoreBuilderImpl(state, kernel);
829
+ for (const [name, fn] of Object.entries(allActions)) {
830
+ builder.action(name, fn);
608
831
  }
609
832
  kernel.initializeAll(builder).catch((error) => {
610
833
  console.error("Error initializing plugins:", error);
@@ -637,321 +860,55 @@ function createStore(initialState, actions) {
637
860
  }
638
861
  });
639
862
  }
640
- function batch(fn) {
641
- return fn();
642
- }
643
- var StoreImpl, StoreBuilderImpl;
644
- var init_store = __esm({
645
- "src/store.ts"() {
646
- init_utils();
647
- init_kernel();
648
- init_batch_context();
649
- init_types();
650
- StoreImpl = class {
651
- state;
652
- initialState;
653
- listeners = /* @__PURE__ */ new Set();
654
- selectorSubscriptions = /* @__PURE__ */ new Map();
655
- kernel;
656
- destroyed = false;
657
- batchDepth = 0;
658
- pendingNotify = false;
659
- queuedState = null;
660
- queuedPrevState = null;
661
- actions = {};
662
- constructor(initialState, kernel) {
663
- this.state = deepClone(initialState);
664
- this.initialState = deepClone(initialState);
665
- this.kernel = kernel;
666
- this.kernel.onError((error) => {
667
- console.error("Store error:", error);
668
- });
669
- }
670
- /** Get current state snapshot. */
671
- getState() {
672
- this.checkNotDestroyed();
673
- return this.state;
674
- }
675
- /** Update state with partial object or function. */
676
- setState(partial) {
677
- this.checkNotDestroyed();
678
- const prevState = this.state;
679
- const update = typeof partial === "function" ? partial(this.state) : partial;
680
- this.state = { ...this.state, ...update };
681
- this.notifyOrQueue(this.state, prevState);
682
- }
683
- /** Deep merge state. */
684
- merge(partial) {
685
- this.checkNotDestroyed();
686
- const prevState = this.state;
687
- this.state = deepMerge(this.state, partial);
688
- this.notifyOrQueue(this.state, prevState);
689
- }
690
- /** Reset to initial state. */
691
- reset() {
692
- this.checkNotDestroyed();
693
- const prevState = this.state;
694
- this.state = deepClone(this.initialState);
695
- this.notifyOrQueue(this.state, prevState);
696
- }
697
- subscribe(arg1, arg2, arg3) {
698
- this.checkNotDestroyed();
699
- if (arg2 === void 0 && typeof arg1 === "function") {
700
- const listener2 = arg1;
701
- this.listeners.add(listener2);
702
- return () => {
703
- this.listeners.delete(listener2);
704
- };
705
- }
706
- const selector2 = arg1;
707
- const listener = arg2;
708
- const equalityFn = arg3 || shallowEqual;
709
- let subscription = this.selectorSubscriptions.get(selector2);
710
- if (!subscription) {
711
- const initialValue = selector2(this.state);
712
- subscription = {
713
- value: initialValue,
714
- listeners: /* @__PURE__ */ new Set(),
715
- selector: selector2,
716
- equalityFn
717
- };
718
- this.selectorSubscriptions.set(selector2, subscription);
719
- }
720
- subscription.listeners.add(listener);
721
- return () => {
722
- const sub = this.selectorSubscriptions.get(selector2);
723
- if (sub) {
724
- sub.listeners.delete(listener);
725
- if (sub.listeners.size === 0) {
726
- this.selectorSubscriptions.delete(selector2);
727
- }
728
- }
729
- };
730
- }
731
- /** Register a plugin. */
732
- use(plugin, options) {
733
- this.checkNotDestroyed();
734
- this.kernel.register(plugin, options, this);
735
- return this;
736
- }
737
- /** Destroy store and cleanup. */
738
- destroy() {
739
- if (this.destroyed) {
740
- return;
741
- }
742
- this.destroyed = true;
743
- this.kernel.destroy();
744
- this.listeners.clear();
745
- this.selectorSubscriptions.clear();
746
- this.actions = {};
747
- }
748
- /** Add an action (for fluent builder pattern). */
749
- addAction(name, fn) {
750
- this.actions[name] = fn;
751
- return this;
752
- }
753
- /** Get all actions. */
754
- getActions() {
755
- return this.actions;
756
- }
757
- /** Check if store is destroyed. */
758
- checkNotDestroyed() {
759
- if (this.destroyed) {
760
- throw new Error("Cannot use destroyed store");
761
- }
762
- }
763
- /** Notify listeners or queue if batching. */
764
- notifyOrQueue(state, prevState) {
765
- const inGlobalBatch = sharedBatchContext.isBatching();
766
- if (inGlobalBatch) {
767
- const managedStores = sharedBatchContext.managedStores;
768
- if (!managedStores.has(this)) {
769
- managedStores.add(this);
770
- }
771
- }
772
- if (this.batchDepth > 0 || inGlobalBatch) {
773
- this.queuedState = state;
774
- if (!this.pendingNotify) {
775
- this.queuedPrevState = prevState;
776
- }
777
- this.pendingNotify = true;
778
- } else {
779
- this.notify(state, prevState);
780
- }
781
- }
782
- /** Notify all listeners. */
783
- notify(state, prevState) {
784
- this.kernel.emitStateChange(state, prevState);
785
- for (const listener of this.listeners) {
786
- try {
787
- listener(state, prevState);
788
- } catch (error) {
789
- this.kernel.emitError(error);
790
- }
791
- }
792
- for (const subscription of this.selectorSubscriptions.values()) {
793
- const newValue = subscription.selector(state);
794
- if (!subscription.equalityFn(newValue, subscription.value)) {
795
- const prevValue = subscription.value;
796
- subscription.value = newValue;
797
- for (const listener of subscription.listeners) {
798
- try {
799
- listener(newValue, prevValue);
800
- } catch (error) {
801
- this.kernel.emitError(error);
802
- }
803
- }
804
- }
805
- }
806
- }
807
- /** Flush pending notifications (end of batch). */
808
- flushNotifications() {
809
- if (this.pendingNotify) {
810
- this.notify(this.queuedState, this.queuedPrevState);
811
- this.pendingNotify = false;
812
- this.queuedState = null;
813
- this.queuedPrevState = null;
814
- }
815
- }
816
- /** Start batching. */
817
- beginBatch() {
818
- this.batchDepth++;
819
- }
820
- /** End batching. */
821
- endBatch() {
822
- this.batchDepth--;
823
- if (this.batchDepth === 0) {
824
- this.flushNotifications();
825
- }
826
- }
827
- };
828
- StoreBuilderImpl = class {
829
- store;
830
- constructor(initialState, kernel) {
831
- this.store = new StoreImpl(initialState, kernel);
832
- }
833
- getState() {
834
- return this.store.getState();
835
- }
836
- setState(partial) {
837
- this.store.setState(partial);
838
- }
839
- merge(partial) {
840
- this.store.merge(partial);
841
- }
842
- reset() {
843
- this.store.reset();
844
- }
845
- subscribe(arg1, arg2, arg3) {
846
- if (arg2 === void 0) {
847
- return this.store.subscribe(arg1);
848
- } else {
849
- return this.store.subscribe(arg1, arg2, arg3);
850
- }
851
- }
852
- use(plugin, options) {
853
- this.store.use(plugin, options);
854
- return this;
855
- }
856
- destroy() {
857
- this.store.destroy();
858
- }
859
- action(name, fn) {
860
- this.store.addAction(name, fn);
861
- this[name] = (...args) => {
862
- const currentState = this.getState();
863
- const result = fn(currentState, ...args);
864
- if (result instanceof Promise) {
865
- return result.then((partial) => {
866
- this.setState(partial);
867
- return partial;
868
- });
869
- }
870
- this.setState(result);
871
- return result;
872
- };
873
- return this;
874
- }
875
- /** Add action (internal use). */
876
- addAction(name, fn) {
877
- this.store.addAction(name, fn);
878
- return this;
879
- }
880
- /** Get actions (internal use). */
881
- getActions() {
882
- return this.store.getActions();
883
- }
884
- /** Start batching. */
885
- beginBatch() {
886
- this.store.beginBatch();
887
- }
888
- /** End batching. */
889
- endBatch() {
890
- this.store.endBatch();
891
- }
892
- /** Flush pending notifications. */
893
- flushNotifications() {
894
- this.store.flushNotifications();
895
- }
896
- };
897
- }
898
- });
899
-
900
- // src/index.ts
901
- init_store();
902
-
903
- // src/react.ts
904
- init_identity();
905
- init_shallow_equal();
906
- init_store();
907
863
  function useStore(store, selector2 = identity, equalityFn = shallowEqual) {
908
864
  const selectorRef = react.useRef(selector2);
909
865
  const equalityFnRef = react.useRef(equalityFn);
910
- const storeRef = react.useRef(store);
911
- if (selectorRef.current !== selector2) {
912
- selectorRef.current = selector2;
913
- }
914
- if (equalityFnRef.current !== equalityFn) {
915
- equalityFnRef.current = equalityFn;
916
- }
917
- if (storeRef.current !== store) {
918
- storeRef.current = store;
919
- }
920
- const getSnapshot = () => {
921
- const state = storeRef.current.getState();
922
- return selectorRef.current(state);
923
- };
924
- const getServerSnapshot = getSnapshot;
925
- const subscribe = (callback) => {
926
- const unsubscribe = storeRef.current.subscribe(
927
- (state) => selectorRef.current(state),
928
- (value, prevValue) => {
929
- if (!equalityFnRef.current(value, prevValue)) {
930
- callback();
931
- }
932
- },
933
- equalityFnRef.current
934
- );
935
- return unsubscribe;
936
- };
937
- const selectedState = react.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
866
+ selectorRef.current = selector2;
867
+ equalityFnRef.current = equalityFn;
868
+ const cacheRef = react.useRef(null);
869
+ const getSnapshot = react.useCallback(() => {
870
+ const state = store.getState();
871
+ const currentSelector = selectorRef.current;
872
+ const cache = cacheRef.current;
873
+ if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {
874
+ return cache.selected;
875
+ }
876
+ const next = currentSelector(state);
877
+ if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {
878
+ cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };
879
+ return cache.selected;
880
+ }
881
+ cacheRef.current = { store, state, selector: currentSelector, selected: next };
882
+ return next;
883
+ }, [store]);
884
+ const subscribe = react.useCallback((callback) => store.subscribe(() => callback()), [store]);
885
+ const selectedState = react.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
938
886
  react.useDebugValue(selectedState);
939
887
  return selectedState;
940
888
  }
941
889
  function useCreateStore(initialState) {
942
890
  const storeRef = react.useRef();
891
+ const pendingDestroyRef = react.useRef(null);
943
892
  if (storeRef.current === void 0) {
944
893
  storeRef.current = createStore(initialState);
945
894
  }
895
+ const store = storeRef.current;
946
896
  react.useEffect(() => {
897
+ pendingDestroyRef.current = null;
947
898
  return () => {
948
- if (storeRef.current) {
949
- storeRef.current.destroy();
950
- storeRef.current = void 0;
951
- }
899
+ const token = {};
900
+ pendingDestroyRef.current = token;
901
+ queueMicrotask(() => {
902
+ if (pendingDestroyRef.current === token) {
903
+ store.destroy();
904
+ if (storeRef.current === store) {
905
+ storeRef.current = void 0;
906
+ }
907
+ }
908
+ });
952
909
  };
953
- }, []);
954
- return storeRef.current;
910
+ }, [store]);
911
+ return store;
955
912
  }
956
913
  function useAction(store, actionName) {
957
914
  const storeRef = react.useRef(store);
@@ -1011,51 +968,49 @@ function useStoreActions(store, ...actionNames) {
1011
968
  return result;
1012
969
  }
1013
970
  function useStoreSelector(store, selectors) {
1014
- const selectorsRef = react.useRef(selectors);
1015
- const keysRef = react.useRef(Object.keys(selectors));
1016
971
  const prevResultRef = react.useRef(null);
1017
- if (selectorsRef.current !== selectors) {
1018
- selectorsRef.current = selectors;
1019
- keysRef.current = Object.keys(selectors);
1020
- }
1021
972
  const combinedSelector = react.useCallback((state) => {
1022
- const keys = keysRef.current;
1023
- const currentSelectors = selectorsRef.current;
973
+ const keys = Object.keys(selectors);
1024
974
  const result = {};
1025
975
  for (const key of keys) {
1026
- const selector2 = currentSelectors[key];
976
+ const selector2 = selectors[key];
1027
977
  if (selector2) {
1028
978
  result[key] = selector2(state);
1029
979
  }
1030
980
  }
1031
- if (prevResultRef.current !== null) {
981
+ const prev = prevResultRef.current;
982
+ if (prev !== null && Object.keys(prev).length === keys.length) {
1032
983
  let isEqual = true;
1033
984
  for (const key of keys) {
1034
- if (!shallowEqual(prevResultRef.current[key], result[key])) {
985
+ if (!(key in prev) || !shallowEqual(prev[key], result[key])) {
1035
986
  isEqual = false;
1036
987
  break;
1037
988
  }
1038
989
  }
1039
990
  if (isEqual) {
1040
- return prevResultRef.current;
991
+ return prev;
1041
992
  }
1042
993
  }
1043
994
  prevResultRef.current = result;
1044
995
  return result;
1045
- }, []);
996
+ }, [selectors]);
1046
997
  return useStore(store, combinedSelector);
1047
998
  }
1048
999
  function useTransientSubscribe(store, selector2, callback, equalityFn = shallowEqual) {
1049
1000
  const callbackRef = react.useRef(callback);
1001
+ const selectorRef = react.useRef(selector2);
1002
+ const equalityFnRef = react.useRef(equalityFn);
1050
1003
  callbackRef.current = callback;
1004
+ selectorRef.current = selector2;
1005
+ equalityFnRef.current = equalityFn;
1051
1006
  react.useEffect(() => {
1052
1007
  const unsubscribe = store.subscribe(
1053
- selector2,
1008
+ (state) => selectorRef.current(state),
1054
1009
  (value, prevValue) => callbackRef.current(value, prevValue),
1055
- equalityFn
1010
+ (a, b) => equalityFnRef.current(a, b)
1056
1011
  );
1057
1012
  return unsubscribe;
1058
- }, [store, selector2, equalityFn]);
1013
+ }, [store]);
1059
1014
  }
1060
1015
  function useSetState(store) {
1061
1016
  const storeRef = react.useRef(store);
@@ -1069,7 +1024,6 @@ function useSetState(store) {
1069
1024
  }
1070
1025
 
1071
1026
  // src/subscribe.ts
1072
- init_utils();
1073
1027
  function createDebounced(fn, delay2) {
1074
1028
  let timeoutId = null;
1075
1029
  const debounced = ((...args) => {
@@ -1214,28 +1168,34 @@ function subscribeToMany(store, selectors, listener, options = {}) {
1214
1168
  }
1215
1169
  function subscribeOnce(store, selector2, listener, options = {}) {
1216
1170
  let unsubscribe = null;
1171
+ let fired = false;
1217
1172
  const onceListener = (value, prevValue) => {
1173
+ if (fired) return;
1174
+ fired = true;
1218
1175
  listener(value, prevValue);
1219
1176
  if (unsubscribe) {
1220
1177
  unsubscribe();
1221
1178
  }
1222
1179
  };
1223
1180
  unsubscribe = subscribeWithOptions(store, selector2, onceListener, options);
1181
+ if (fired) {
1182
+ unsubscribe();
1183
+ }
1224
1184
  return unsubscribe;
1225
1185
  }
1226
1186
 
1227
1187
  // src/computed.ts
1228
- init_utils();
1229
1188
  function computed(store, selector2, options = {}) {
1230
1189
  const { equals = shallowEqual, lazy = false, cacheSize = 1 } = options;
1231
1190
  const cache = [];
1232
1191
  let currentValue;
1192
+ let notifiedValue;
1193
+ let computedFrom;
1233
1194
  let isInitialized = false;
1234
1195
  let isDestroyed = false;
1235
1196
  const listeners = /* @__PURE__ */ new Set();
1236
1197
  let unsubscribe = null;
1237
- const compute = () => {
1238
- const state = store.getState();
1198
+ const compute = (state) => {
1239
1199
  for (const entry of cache) {
1240
1200
  if (entry.input === state || shallowEqual(entry.input, state)) {
1241
1201
  return entry.output;
@@ -1248,23 +1208,36 @@ function computed(store, selector2, options = {}) {
1248
1208
  }
1249
1209
  return newValue;
1250
1210
  };
1211
+ const refresh = () => {
1212
+ const state = store.getState();
1213
+ if (isInitialized && state === computedFrom) return;
1214
+ const newValue = compute(state);
1215
+ if (!isInitialized || !equals(newValue, currentValue)) {
1216
+ currentValue = newValue;
1217
+ }
1218
+ computedFrom = state;
1219
+ };
1220
+ const emit = () => {
1221
+ const prevValue = notifiedValue;
1222
+ const value = currentValue;
1223
+ if (equals(value, prevValue)) return;
1224
+ notifiedValue = value;
1225
+ for (const listener of Array.from(listeners)) {
1226
+ try {
1227
+ listener(value, prevValue);
1228
+ } catch (error) {
1229
+ console.error("Computed listener error:", error);
1230
+ }
1231
+ }
1232
+ };
1251
1233
  const initialize = () => {
1252
1234
  if (isInitialized || isDestroyed) return;
1235
+ refresh();
1253
1236
  isInitialized = true;
1254
- currentValue = compute();
1255
- unsubscribe = store.subscribe((state, prevState) => {
1256
- const prevValue = currentValue;
1257
- const newValue = compute();
1258
- if (!equals(newValue, prevValue)) {
1259
- currentValue = newValue;
1260
- for (const listener of listeners) {
1261
- try {
1262
- listener(newValue, prevValue);
1263
- } catch (error) {
1264
- console.error("Computed listener error:", error);
1265
- }
1266
- }
1267
- }
1237
+ notifiedValue = currentValue;
1238
+ unsubscribe = store.subscribe(() => {
1239
+ refresh();
1240
+ emit();
1268
1241
  });
1269
1242
  };
1270
1243
  if (!lazy) {
@@ -1276,6 +1249,8 @@ function computed(store, selector2, options = {}) {
1276
1249
  }
1277
1250
  if (!isInitialized) {
1278
1251
  initialize();
1252
+ } else {
1253
+ refresh();
1279
1254
  }
1280
1255
  return currentValue;
1281
1256
  };
@@ -1283,17 +1258,13 @@ function computed(store, selector2, options = {}) {
1283
1258
  if (isDestroyed) return;
1284
1259
  cache.length = 0;
1285
1260
  if (isInitialized) {
1286
- const prevValue = currentValue;
1287
- currentValue = compute();
1288
- if (!equals(currentValue, prevValue)) {
1289
- for (const listener of listeners) {
1290
- try {
1291
- listener(currentValue, prevValue);
1292
- } catch (error) {
1293
- console.error("Computed listener error:", error);
1294
- }
1295
- }
1261
+ const state = store.getState();
1262
+ const newValue = compute(state);
1263
+ computedFrom = state;
1264
+ if (!equals(newValue, currentValue)) {
1265
+ currentValue = newValue;
1296
1266
  }
1267
+ emit();
1297
1268
  }
1298
1269
  };
1299
1270
  const subscribe = (listener) => {
@@ -1321,6 +1292,8 @@ function computed(store, selector2, options = {}) {
1321
1292
  listeners.clear();
1322
1293
  cache.length = 0;
1323
1294
  currentValue = void 0;
1295
+ notifiedValue = void 0;
1296
+ computedFrom = void 0;
1324
1297
  };
1325
1298
  const computedFn = get;
1326
1299
  computedFn.get = get;
@@ -1341,25 +1314,33 @@ function combineComputed(computeds, combiner, options = {}) {
1341
1314
  const values = computeds.map((c) => c());
1342
1315
  return combiner(values);
1343
1316
  };
1317
+ let notifiedValue;
1318
+ const refresh = () => {
1319
+ const newValue = compute();
1320
+ if (!equals(newValue, currentValue)) {
1321
+ currentValue = newValue;
1322
+ cache.unshift(newValue);
1323
+ while (cache.length > cacheSize) {
1324
+ cache.pop();
1325
+ }
1326
+ }
1327
+ };
1344
1328
  currentValue = compute();
1345
1329
  cache.push(currentValue);
1330
+ notifiedValue = currentValue;
1346
1331
  for (const computed2 of computeds) {
1347
1332
  const unsub = computed2.subscribe(() => {
1348
1333
  if (isDestroyed) return;
1349
- const prevValue = currentValue;
1350
- const newValue = compute();
1351
- if (!equals(newValue, prevValue)) {
1352
- currentValue = newValue;
1353
- cache.unshift(newValue);
1354
- while (cache.length > cacheSize) {
1355
- cache.pop();
1356
- }
1357
- for (const listener of listeners) {
1358
- try {
1359
- listener(newValue, prevValue);
1360
- } catch (error) {
1361
- console.error("Combined computed listener error:", error);
1362
- }
1334
+ refresh();
1335
+ const prevValue = notifiedValue;
1336
+ const value = currentValue;
1337
+ if (equals(value, prevValue)) return;
1338
+ notifiedValue = value;
1339
+ for (const listener of Array.from(listeners)) {
1340
+ try {
1341
+ listener(value, prevValue);
1342
+ } catch (error) {
1343
+ console.error("Combined computed listener error:", error);
1363
1344
  }
1364
1345
  }
1365
1346
  });
@@ -1369,6 +1350,7 @@ function combineComputed(computeds, combiner, options = {}) {
1369
1350
  if (isDestroyed) {
1370
1351
  throw new Error("Cannot access destroyed computed value");
1371
1352
  }
1353
+ refresh();
1372
1354
  return currentValue;
1373
1355
  };
1374
1356
  const invalidate = () => {
@@ -1420,7 +1402,15 @@ function memoizeSelector(selector2, equals = shallowEqual) {
1420
1402
  }
1421
1403
 
1422
1404
  // src/slices.ts
1423
- init_store();
1405
+ var sliceRegistry = /* @__PURE__ */ new WeakMap();
1406
+ function registerSlice(store, name, data) {
1407
+ let slices = sliceRegistry.get(store);
1408
+ if (!slices) {
1409
+ slices = /* @__PURE__ */ new Map();
1410
+ sliceRegistry.set(store, slices);
1411
+ }
1412
+ slices.set(name, data);
1413
+ }
1424
1414
  function createSlice(name, creator) {
1425
1415
  return { name, creator };
1426
1416
  }
@@ -1454,15 +1444,19 @@ function combineSlices(...slices) {
1454
1444
  destroy: () => {
1455
1445
  }
1456
1446
  };
1447
+ const sliceData = /* @__PURE__ */ new Map();
1457
1448
  for (const slice of slices) {
1458
1449
  const sliceResult = slice.creator(set, get, placeholderStore);
1450
+ const data = {};
1459
1451
  for (const [key, value] of Object.entries(sliceResult)) {
1460
1452
  if (typeof value === "function") {
1461
1453
  actions[key] = value;
1462
1454
  } else {
1463
1455
  initialState[key] = value;
1456
+ data[key] = value;
1464
1457
  }
1465
1458
  }
1459
+ sliceData.set(slice.name, data);
1466
1460
  }
1467
1461
  tempStore = createStore(initialState);
1468
1462
  for (const slice of slices) {
@@ -1483,6 +1477,9 @@ function combineSlices(...slices) {
1483
1477
  }
1484
1478
  }
1485
1479
  }
1480
+ for (const [name, data] of sliceData) {
1481
+ registerSlice(tempStore, name, data);
1482
+ }
1486
1483
  const store = tempStore;
1487
1484
  for (const [name, action] of Object.entries(actions)) {
1488
1485
  store[name] = action;
@@ -1490,7 +1487,7 @@ function combineSlices(...slices) {
1490
1487
  return store;
1491
1488
  }
1492
1489
  function createNamespacedSlice(namespace, creator) {
1493
- return createSlice(namespace, (set, get, store) => {
1490
+ return createSlice(namespace, (set, get) => {
1494
1491
  const namespacedSet = (partial) => {
1495
1492
  const current = get()[namespace] || {};
1496
1493
  const update = typeof partial === "function" ? partial(current) : partial;
@@ -1527,13 +1524,16 @@ function extendStore(store, ...slices) {
1527
1524
  const get = () => store.getState();
1528
1525
  for (const slice of slices) {
1529
1526
  const sliceResult = slice.creator(set, get, store);
1527
+ const data = {};
1530
1528
  for (const [key, value] of Object.entries(sliceResult)) {
1531
1529
  if (typeof value === "function") {
1532
1530
  actions[key] = value;
1533
1531
  } else {
1534
1532
  store.setState({ [key]: value });
1533
+ data[key] = value;
1535
1534
  }
1536
1535
  }
1536
+ registerSlice(store, slice.name, data);
1537
1537
  }
1538
1538
  const extendedStore = store;
1539
1539
  for (const [name, action] of Object.entries(actions)) {
@@ -1542,8 +1542,24 @@ function extendStore(store, ...slices) {
1542
1542
  return extendedStore;
1543
1543
  }
1544
1544
  function resetSlices(store, ...sliceNames) {
1545
- console.warn("resetSlices: Use store.reset() to reset all state");
1546
- store.reset();
1545
+ const slices = sliceRegistry.get(store);
1546
+ if (!slices) {
1547
+ console.warn("resetSlices: store was not created with combineSlices/extendStore; resetting all state");
1548
+ store.reset();
1549
+ return;
1550
+ }
1551
+ const update = {};
1552
+ for (const name of sliceNames) {
1553
+ const data = slices.get(name);
1554
+ if (!data) {
1555
+ console.warn(`resetSlices: unknown slice '${name}'`);
1556
+ continue;
1557
+ }
1558
+ Object.assign(update, data);
1559
+ }
1560
+ if (Object.keys(update).length > 0) {
1561
+ store.setState(deepClone(update));
1562
+ }
1547
1563
  }
1548
1564
 
1549
1565
  // src/federation.ts
@@ -1686,6 +1702,15 @@ function createFederation(stores, options = {}) {
1686
1702
  getStore(storeName) {
1687
1703
  return stores[storeName];
1688
1704
  },
1705
+ subscribeStore(storeName, listener) {
1706
+ const store = stores[storeName];
1707
+ if (!store) {
1708
+ throw new Error(`Unknown store '${String(storeName)}' in federation '${name}'`);
1709
+ }
1710
+ const unsubscribe = store.subscribe(listener);
1711
+ unsubscribers.push(unsubscribe);
1712
+ return unsubscribe;
1713
+ },
1689
1714
  destroy() {
1690
1715
  log("Destroying federation");
1691
1716
  for (const unsubscribe of unsubscribers) {
@@ -1752,7 +1777,6 @@ function waitForFederated(federation, predicate, timeout) {
1752
1777
  }
1753
1778
 
1754
1779
  // src/plugins/persist.ts
1755
- init_utils();
1756
1780
  var defaultStorage = {
1757
1781
  getItem: (key) => {
1758
1782
  if (typeof window === "undefined") return null;
@@ -1764,10 +1788,7 @@ var defaultStorage = {
1764
1788
  },
1765
1789
  setItem: (key, value) => {
1766
1790
  if (typeof window === "undefined") return;
1767
- try {
1768
- window.localStorage.setItem(key, value);
1769
- } catch {
1770
- }
1791
+ window.localStorage.setItem(key, value);
1771
1792
  },
1772
1793
  /* c8 ignore next 3 */
1773
1794
  removeItem: () => {
@@ -1784,10 +1805,7 @@ var sessionStorage = {
1784
1805
  },
1785
1806
  setItem: (key, value) => {
1786
1807
  if (typeof window === "undefined") return;
1787
- try {
1788
- window.sessionStorage.setItem(key, value);
1789
- } catch {
1790
- }
1808
+ window.sessionStorage.setItem(key, value);
1791
1809
  },
1792
1810
  removeItem: (key) => {
1793
1811
  if (typeof window === "undefined") return;
@@ -1942,7 +1960,9 @@ function getDevtools() {
1942
1960
  function devtools(options = {}) {
1943
1961
  const { name = "OxogState Store", enabled = true, maxAge = 50 } = options;
1944
1962
  let connection = null;
1945
- let history2 = [];
1963
+ let unsubscribeStore = null;
1964
+ let unsubscribeDevtools = null;
1965
+ let states = [];
1946
1966
  return {
1947
1967
  name: "devtools",
1948
1968
  version: "1.0.0",
@@ -1952,55 +1972,79 @@ function devtools(options = {}) {
1952
1972
  }
1953
1973
  const extension = getDevtools();
1954
1974
  if (!extension) return;
1955
- connection = extension.connect({ name });
1956
- connection.init(store.getState());
1957
- store.subscribe((state, prevState) => {
1958
- if (!connection) return;
1959
- history2.push({ state, action: "UPDATE" });
1960
- if (history2.length > maxAge) {
1961
- history2.shift();
1975
+ const conn = extension.connect({ name });
1976
+ connection = conn;
1977
+ conn.init(store.getState());
1978
+ states = [store.getState()];
1979
+ let applyingFromDevtools = false;
1980
+ const apply = (fn) => {
1981
+ applyingFromDevtools = true;
1982
+ try {
1983
+ fn();
1984
+ } finally {
1985
+ applyingFromDevtools = false;
1986
+ }
1987
+ };
1988
+ unsubscribeStore = store.subscribe((state, prevState) => {
1989
+ if (!connection || applyingFromDevtools) return;
1990
+ states.push(state);
1991
+ if (states.length > maxAge + 1) {
1992
+ states.shift();
1962
1993
  }
1963
1994
  connection.send({ type: "UPDATE", prev: prevState }, state);
1964
1995
  });
1965
- connection.subscribe((message) => {
1966
- if (message.type === "DISPATCH" && message.payload) {
1967
- switch (message.payload.type) {
1968
- case "JUMP_TO_STATE":
1969
- case "JUMP_TO_ACTION": {
1970
- const index = message.payload.type === "JUMP_TO_ACTION" ? history2.findIndex((h) => h.action === message.payload.action) : message.payload.index;
1971
- if (index >= 0 && index < history2.length) {
1972
- const entry = history2[index];
1973
- if (entry) {
1974
- store.setState(entry.state);
1975
- }
1976
- }
1977
- break;
1978
- }
1979
- case "COMMIT": {
1980
- connection.init(store.getState());
1981
- history2 = [];
1982
- break;
1983
- }
1984
- case "ROLLBACK": {
1985
- if (history2.length > 1) {
1986
- const previous = history2[history2.length - 2];
1987
- if (previous) {
1988
- store.setState(previous.state);
1989
- }
1990
- }
1991
- break;
1996
+ const parseState = (message) => {
1997
+ if (typeof message.state !== "string") return void 0;
1998
+ try {
1999
+ return JSON.parse(message.state);
2000
+ } catch {
2001
+ return void 0;
2002
+ }
2003
+ };
2004
+ const unsubscribe = conn.subscribe((message) => {
2005
+ if (message?.type !== "DISPATCH" || !message.payload) return;
2006
+ switch (message.payload.type) {
2007
+ case "JUMP_TO_STATE":
2008
+ case "JUMP_TO_ACTION": {
2009
+ const target = parseState(message) ?? states[message.payload.index];
2010
+ if (target !== void 0) {
2011
+ apply(() => store.setState(target));
1992
2012
  }
1993
- case "RESET": {
1994
- store.reset();
1995
- break;
2013
+ break;
2014
+ }
2015
+ case "COMMIT": {
2016
+ conn.init(store.getState());
2017
+ states = [store.getState()];
2018
+ break;
2019
+ }
2020
+ case "ROLLBACK": {
2021
+ const target = parseState(message) ?? states[0];
2022
+ if (target !== void 0) {
2023
+ apply(() => store.setState(target));
1996
2024
  }
2025
+ conn.init(store.getState());
2026
+ states = [store.getState()];
2027
+ break;
2028
+ }
2029
+ case "RESET": {
2030
+ apply(() => store.reset());
2031
+ conn.init(store.getState());
2032
+ states = [store.getState()];
2033
+ break;
1997
2034
  }
1998
2035
  }
1999
2036
  });
2037
+ if (typeof unsubscribe === "function") {
2038
+ unsubscribeDevtools = unsubscribe;
2039
+ }
2000
2040
  },
2001
2041
  onDestroy() {
2042
+ unsubscribeStore?.();
2043
+ unsubscribeStore = null;
2044
+ unsubscribeDevtools?.();
2045
+ unsubscribeDevtools = null;
2002
2046
  connection = null;
2003
- history2 = [];
2047
+ states = [];
2004
2048
  }
2005
2049
  };
2006
2050
  }
@@ -2010,6 +2054,7 @@ function history(options = {}) {
2010
2054
  const { limit = 50, keys } = options;
2011
2055
  let historyState = null;
2012
2056
  let isInternalUpdate = false;
2057
+ let internalState = null;
2013
2058
  return {
2014
2059
  name: "history",
2015
2060
  version: "1.0.0",
@@ -2021,6 +2066,11 @@ function history(options = {}) {
2021
2066
  };
2022
2067
  store.subscribe((state) => {
2023
2068
  if (!historyState || isInternalUpdate) return;
2069
+ if (internalState !== null && state === internalState) {
2070
+ internalState = null;
2071
+ return;
2072
+ }
2073
+ internalState = null;
2024
2074
  const previousPresent = historyState.present;
2025
2075
  const newPresent = state;
2026
2076
  let hasChanged = true;
@@ -2045,8 +2095,12 @@ function history(options = {}) {
2045
2095
  historyState.future.push(historyState.present);
2046
2096
  historyState.present = previous;
2047
2097
  isInternalUpdate = true;
2048
- store.setState(previous);
2049
- isInternalUpdate = false;
2098
+ try {
2099
+ store.setState(previous);
2100
+ internalState = store.getState();
2101
+ } finally {
2102
+ isInternalUpdate = false;
2103
+ }
2050
2104
  };
2051
2105
  store.redo = () => {
2052
2106
  if (!historyState || historyState.future.length === 0) return;
@@ -2054,8 +2108,12 @@ function history(options = {}) {
2054
2108
  historyState.past.push(historyState.present);
2055
2109
  historyState.present = next;
2056
2110
  isInternalUpdate = true;
2057
- store.setState(next);
2058
- isInternalUpdate = false;
2111
+ try {
2112
+ store.setState(next);
2113
+ internalState = store.getState();
2114
+ } finally {
2115
+ isInternalUpdate = false;
2116
+ }
2059
2117
  };
2060
2118
  store.clearHistory = () => {
2061
2119
  if (!historyState) return;
@@ -2083,7 +2141,16 @@ function sync(options = {}) {
2083
2141
  const { channel = "oxog-state" } = options;
2084
2142
  let broadcastChannel = null;
2085
2143
  let currentStore = null;
2086
- let isLocalUpdate = false;
2144
+ let unsubscribe = null;
2145
+ let applyingRemote = false;
2146
+ const broadcast = (state, errorMessage) => {
2147
+ if (!broadcastChannel) return;
2148
+ try {
2149
+ broadcastChannel.postMessage(toMessage(state));
2150
+ } catch (error) {
2151
+ console.error(errorMessage, error);
2152
+ }
2153
+ };
2087
2154
  return {
2088
2155
  name: "sync",
2089
2156
  version: "1.0.0",
@@ -2095,28 +2162,34 @@ function sync(options = {}) {
2095
2162
  }
2096
2163
  broadcastChannel = new BroadcastChannel(channel);
2097
2164
  broadcastChannel.onmessage = (event) => {
2098
- if (!isLocalUpdate) {
2099
- try {
2100
- store.setState(event.data);
2101
- } catch (error) {
2102
- console.error("Error applying sync state:", error);
2103
- }
2165
+ if (!currentStore) return;
2166
+ applyingRemote = true;
2167
+ try {
2168
+ currentStore.setState(event.data);
2169
+ } catch (error) {
2170
+ console.error("Error applying sync state:", error);
2171
+ } finally {
2172
+ applyingRemote = false;
2104
2173
  }
2105
2174
  };
2175
+ unsubscribe = store.subscribe((state) => {
2176
+ if (!applyingRemote) {
2177
+ broadcast(state, "Error broadcasting state:");
2178
+ }
2179
+ });
2106
2180
  },
2107
2181
  onInit() {
2108
- if (broadcastChannel && currentStore) {
2109
- isLocalUpdate = true;
2110
- try {
2111
- broadcastChannel.postMessage(currentStore.getState());
2112
- } catch (error) {
2113
- console.error("Error broadcasting initial state:", error);
2114
- }
2115
- isLocalUpdate = false;
2182
+ if (currentStore) {
2183
+ broadcast(currentStore.getState(), "Error broadcasting initial state:");
2116
2184
  }
2117
2185
  },
2118
2186
  onDestroy() {
2187
+ if (unsubscribe) {
2188
+ unsubscribe();
2189
+ unsubscribe = null;
2190
+ }
2119
2191
  if (broadcastChannel) {
2192
+ broadcastChannel.onmessage = null;
2120
2193
  broadcastChannel.close();
2121
2194
  broadcastChannel = null;
2122
2195
  }
@@ -2124,82 +2197,166 @@ function sync(options = {}) {
2124
2197
  }
2125
2198
  };
2126
2199
  }
2200
+ function toMessage(state) {
2201
+ if (state === null || typeof state !== "object") return state;
2202
+ const data = {};
2203
+ for (const key of Object.keys(state)) {
2204
+ const value = state[key];
2205
+ if (typeof value !== "function") {
2206
+ data[key] = value;
2207
+ }
2208
+ }
2209
+ return data;
2210
+ }
2127
2211
  function triggerSync(store, channel = "oxog-state") {
2128
2212
  if (typeof BroadcastChannel === "undefined") {
2129
2213
  console.warn("BroadcastChannel is not supported in this environment");
2130
2214
  return;
2131
2215
  }
2132
2216
  const broadcastChannel = new BroadcastChannel(channel);
2133
- broadcastChannel.postMessage(store.getState());
2217
+ broadcastChannel.postMessage(toMessage(store.getState()));
2134
2218
  broadcastChannel.close();
2135
2219
  }
2136
2220
 
2137
2221
  // src/plugins/immer.ts
2138
- function createProxy(base, copies) {
2139
- return new Proxy(base || {}, {
2140
- get(target, key) {
2141
- const value = target[key];
2142
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
2143
- if (copies.has(value)) {
2144
- return createProxy(copies.get(value), copies);
2145
- }
2146
- return createProxy(value, copies);
2147
- }
2148
- return value;
2222
+ var DRAFT_STATE = /* @__PURE__ */ Symbol("oxog-state.draft");
2223
+ function isDraftable(value) {
2224
+ if (value === null || typeof value !== "object") return false;
2225
+ if (Array.isArray(value)) return true;
2226
+ const proto = Object.getPrototypeOf(value);
2227
+ return proto === Object.prototype || proto === null;
2228
+ }
2229
+ function getDraftState(value) {
2230
+ if (value === null || typeof value !== "object") return void 0;
2231
+ return value[DRAFT_STATE];
2232
+ }
2233
+ function latest(state) {
2234
+ return state.copy ?? state.base;
2235
+ }
2236
+ function hasOwn(target, key) {
2237
+ return Object.prototype.hasOwnProperty.call(target, key);
2238
+ }
2239
+ function shallowCopy(base) {
2240
+ if (Array.isArray(base)) return base.slice();
2241
+ return Object.getPrototypeOf(base) === null ? Object.assign(/* @__PURE__ */ Object.create(null), base) : { ...base };
2242
+ }
2243
+ function markChanged(state) {
2244
+ if (state.copy === null) {
2245
+ state.copy = shallowCopy(state.base);
2246
+ if (state.parent) markChanged(state.parent);
2247
+ }
2248
+ }
2249
+ function createDraft(base, parent) {
2250
+ const state = {
2251
+ base,
2252
+ copy: null,
2253
+ parent,
2254
+ children: /* @__PURE__ */ new Map(),
2255
+ proxy: null,
2256
+ finalized: false,
2257
+ result: void 0
2258
+ };
2259
+ const target = Array.isArray(base) ? [] : {};
2260
+ state.proxy = new Proxy(target, {
2261
+ get(_target, prop) {
2262
+ if (prop === DRAFT_STATE) return state;
2263
+ const source = latest(state);
2264
+ const value = Reflect.get(source, prop, state.proxy);
2265
+ if (!hasOwn(source, prop) || !isDraftable(value)) return value;
2266
+ if (value !== state.base[prop]) return value;
2267
+ let child = state.children.get(prop);
2268
+ if (!child) {
2269
+ child = createDraft(value, state);
2270
+ state.children.set(prop, child);
2271
+ }
2272
+ return child.proxy;
2149
2273
  },
2150
- set(target, key, value) {
2151
- if (!copies.has(target)) {
2152
- copies.set(target, { ...target });
2153
- }
2154
- const copy = copies.get(target);
2155
- copy[key] = value;
2274
+ set(_target, prop, value) {
2275
+ if (prop === "__proto__") return true;
2276
+ const source = latest(state);
2277
+ if (hasOwn(source, prop) && Object.is(source[prop], value)) return true;
2278
+ markChanged(state);
2279
+ state.copy[prop] = value;
2280
+ state.children.delete(prop);
2156
2281
  return true;
2157
2282
  },
2158
- deleteProperty(target, key) {
2159
- if (!copies.has(target)) {
2160
- copies.set(target, { ...target });
2161
- }
2162
- const copy = copies.get(target);
2163
- delete copy[key];
2283
+ deleteProperty(_target, prop) {
2284
+ if (!hasOwn(latest(state), prop)) return true;
2285
+ markChanged(state);
2286
+ delete state.copy[prop];
2287
+ state.children.delete(prop);
2288
+ return true;
2289
+ },
2290
+ has(_target, prop) {
2291
+ return prop in latest(state);
2292
+ },
2293
+ ownKeys() {
2294
+ return Reflect.ownKeys(latest(state));
2295
+ },
2296
+ getOwnPropertyDescriptor(_target, prop) {
2297
+ const source = latest(state);
2298
+ const descriptor = Reflect.getOwnPropertyDescriptor(source, prop);
2299
+ if (!descriptor) return void 0;
2300
+ if (Array.isArray(source) && prop === "length") return descriptor;
2301
+ return { ...descriptor, configurable: true };
2302
+ },
2303
+ defineProperty(_target, prop, descriptor) {
2304
+ markChanged(state);
2305
+ Object.defineProperty(state.copy, prop, { ...descriptor, configurable: true });
2164
2306
  return true;
2307
+ },
2308
+ getPrototypeOf() {
2309
+ return Object.getPrototypeOf(state.base);
2310
+ },
2311
+ setPrototypeOf() {
2312
+ return false;
2165
2313
  }
2166
2314
  });
2315
+ return state;
2316
+ }
2317
+ function finalizeValue(value, seen) {
2318
+ const draft = getDraftState(value);
2319
+ if (draft) return finalizeDraft(draft, seen);
2320
+ if (!isDraftable(value) || seen.has(value)) return value;
2321
+ seen.add(value);
2322
+ for (const key of Object.keys(value)) {
2323
+ const item = value[key];
2324
+ const finalized = finalizeValue(item, seen);
2325
+ if (finalized !== item) value[key] = finalized;
2326
+ }
2327
+ return value;
2167
2328
  }
2168
- function finalize(base, copies) {
2169
- if (!copies.has(base)) {
2170
- return deepClone2(base);
2329
+ function finalizeDraft(state, seen) {
2330
+ if (state.finalized) return state.result;
2331
+ state.finalized = true;
2332
+ if (state.copy === null) {
2333
+ state.result = state.base;
2334
+ return state.result;
2171
2335
  }
2172
- const copy = copies.get(base);
2173
- for (const key in copy) {
2174
- if (Object.prototype.hasOwnProperty.call(copy, key)) {
2175
- const value = copy[key];
2176
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
2177
- copy[key] = finalize(value, copies);
2178
- }
2336
+ const copy = state.copy;
2337
+ state.result = copy;
2338
+ for (const key of Object.keys(copy)) {
2339
+ const value = copy[key];
2340
+ const child = state.children.get(key);
2341
+ if (child && value === child.base) {
2342
+ copy[key] = finalizeDraft(child, seen);
2343
+ } else if (value !== state.base[key]) {
2344
+ copy[key] = finalizeValue(value, seen);
2179
2345
  }
2180
2346
  }
2181
2347
  return copy;
2182
2348
  }
2183
- function deepClone2(value) {
2184
- if (value === null || typeof value !== "object") {
2185
- return value;
2186
- }
2187
- if (Array.isArray(value)) {
2188
- return value.map((v) => deepClone2(v));
2349
+ function produce(base, recipe) {
2350
+ if (!isDraftable(base)) {
2351
+ const result2 = recipe(base);
2352
+ return result2 === void 0 ? base : result2;
2189
2353
  }
2190
- const cloned = {};
2191
- for (const key in value) {
2192
- if (Object.prototype.hasOwnProperty.call(value, key)) {
2193
- cloned[key] = deepClone2(value[key]);
2194
- }
2354
+ const root = createDraft(base, null);
2355
+ const result = recipe(root.proxy);
2356
+ if (result !== null && typeof result === "object" && result !== root.proxy) {
2357
+ return finalizeValue(result, /* @__PURE__ */ new Set());
2195
2358
  }
2196
- return cloned;
2197
- }
2198
- function produce(base, recipe) {
2199
- const copies = /* @__PURE__ */ new Map();
2200
- const draft = createProxy(base, copies);
2201
- recipe(draft);
2202
- return finalize(base, copies);
2359
+ return finalizeDraft(root, /* @__PURE__ */ new Set());
2203
2360
  }
2204
2361
  function immer() {
2205
2362
  return {
@@ -2209,8 +2366,10 @@ function immer() {
2209
2366
  const originalSetState = store.setState.bind(store);
2210
2367
  store.setState = (update) => {
2211
2368
  if (typeof update === "function") {
2212
- const newState = produce(store.getState(), update);
2213
- originalSetState(newState);
2369
+ const current = store.getState();
2370
+ const next = produce(current, update);
2371
+ if (next === current) return;
2372
+ originalSetState(next);
2214
2373
  } else {
2215
2374
  originalSetState(update);
2216
2375
  }
@@ -2227,28 +2386,43 @@ function selector(options) {
2227
2386
  version: "1.0.0",
2228
2387
  install(store) {
2229
2388
  const originalGetState = store.getState.bind(store);
2230
- const cache = /* @__PURE__ */ new Map();
2231
- const computedState = new Proxy({}, {
2232
- get(_, prop) {
2233
- const selectorFn = selectors[prop];
2234
- if (selectorFn) {
2235
- const currentState = originalGetState();
2236
- const cacheKey = prop;
2237
- const cached = cache.get(cacheKey);
2238
- if (cached && cached.state === currentState) {
2239
- return cached.value;
2389
+ let lastState;
2390
+ let lastSnapshot;
2391
+ const createSnapshot = (state) => {
2392
+ if (state === null || typeof state !== "object") return state;
2393
+ const cache = /* @__PURE__ */ new Map();
2394
+ return new Proxy(state, {
2395
+ get(target, prop, receiver) {
2396
+ const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop) ? selectors[prop] : void 0;
2397
+ if (selectorFn) {
2398
+ if (!cache.has(prop)) {
2399
+ cache.set(prop, selectorFn(state));
2400
+ }
2401
+ return cache.get(prop);
2240
2402
  }
2241
- const value = selectorFn(currentState);
2242
- cache.set(cacheKey, { value, state: currentState });
2243
- return value;
2403
+ return Reflect.get(target, prop, receiver);
2404
+ },
2405
+ getOwnPropertyDescriptor(target, prop) {
2406
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
2407
+ const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop) ? selectors[prop] : void 0;
2408
+ if (descriptor && selectorFn && "value" in descriptor && descriptor.configurable) {
2409
+ if (!cache.has(prop)) {
2410
+ cache.set(prop, selectorFn(state));
2411
+ }
2412
+ return { ...descriptor, value: cache.get(prop) };
2413
+ }
2414
+ return descriptor;
2244
2415
  }
2245
- return originalGetState()[prop];
2416
+ });
2417
+ };
2418
+ store.getState = () => {
2419
+ const state = originalGetState();
2420
+ if (state !== lastState || lastSnapshot === void 0) {
2421
+ lastState = state;
2422
+ lastSnapshot = createSnapshot(state);
2246
2423
  }
2247
- });
2248
- store.getState = () => computedState;
2249
- store.subscribe(() => {
2250
- cache.clear();
2251
- });
2424
+ return lastSnapshot;
2425
+ };
2252
2426
  }
2253
2427
  };
2254
2428
  }
@@ -2410,7 +2584,6 @@ function createLogger(defaultOptions = {}) {
2410
2584
  }
2411
2585
 
2412
2586
  // src/plugins/effects.ts
2413
- init_utils();
2414
2587
  function createDebounced3(fn, delay2) {
2415
2588
  let timeoutId = null;
2416
2589
  const debounced = ((...args) => {
@@ -2432,12 +2605,20 @@ function createDebounced3(fn, delay2) {
2432
2605
  }
2433
2606
  function effects(options) {
2434
2607
  const { effects: effectDefs, onError } = options;
2608
+ let destroyAll = null;
2435
2609
  return {
2436
2610
  name: "effects",
2437
2611
  version: "1.0.0",
2438
2612
  install(store) {
2439
2613
  const cleanups = [];
2440
- const effectCleanups = /* @__PURE__ */ new Map();
2614
+ let destroyed = false;
2615
+ const report = (error, name) => {
2616
+ if (onError) {
2617
+ onError(error, name);
2618
+ } else {
2619
+ console.error(`Effect error${name ? ` in '${name}'` : ""}:`, error);
2620
+ }
2621
+ };
2441
2622
  for (let i = 0; i < effectDefs.length; i++) {
2442
2623
  const def = effectDefs[i];
2443
2624
  if (!def) continue;
@@ -2449,85 +2630,101 @@ function effects(options) {
2449
2630
  debounce,
2450
2631
  name
2451
2632
  } = def;
2452
- let isActive = true;
2453
- let prevValue = selector2(store.getState());
2454
- const createUtils = () => ({
2455
- getState: () => store.getState(),
2456
- setState: (partial) => store.setState(partial),
2457
- isActive: () => isActive,
2458
- cancel: () => {
2459
- isActive = false;
2460
- },
2461
- onlyIfActive: (fn) => {
2462
- if (isActive) {
2463
- return fn();
2464
- }
2465
- return void 0;
2633
+ let currentRun = null;
2634
+ let currentCleanup = null;
2635
+ const runCleanup = (cleanup) => {
2636
+ if (!cleanup) return;
2637
+ try {
2638
+ cleanup();
2639
+ } catch (error) {
2640
+ report(error, name);
2466
2641
  }
2467
- });
2642
+ };
2643
+ const deactivate = (run) => {
2644
+ if (run && run.active) {
2645
+ run.active = false;
2646
+ run.controller.abort();
2647
+ }
2648
+ };
2468
2649
  const runEffect = async (value, prev) => {
2469
- const prevCleanup = effectCleanups.get(i);
2470
- if (prevCleanup) {
2471
- try {
2472
- prevCleanup();
2473
- } catch (e) {
2650
+ if (destroyed) return;
2651
+ deactivate(currentRun);
2652
+ const previousCleanup = currentCleanup;
2653
+ currentCleanup = null;
2654
+ runCleanup(previousCleanup);
2655
+ const run = { active: true, controller: new AbortController() };
2656
+ currentRun = run;
2657
+ const utils = {
2658
+ getState: () => store.getState(),
2659
+ setState: (partial) => {
2660
+ if (run.active) store.setState(partial);
2661
+ },
2662
+ isActive: () => run.active,
2663
+ cancel: () => deactivate(run),
2664
+ onlyIfActive: (fn) => run.active ? fn() : void 0,
2665
+ signal: run.controller.signal
2666
+ };
2667
+ const settle = (result) => {
2668
+ if (typeof result !== "function") return;
2669
+ if (run.active) {
2670
+ currentCleanup = result;
2671
+ } else {
2672
+ runCleanup(result);
2474
2673
  }
2475
- effectCleanups.delete(i);
2476
- }
2477
- isActive = true;
2674
+ };
2675
+ const fail = (error) => {
2676
+ if (!(run.controller.signal.aborted && error?.name === "AbortError")) {
2677
+ report(error, name);
2678
+ }
2679
+ };
2478
2680
  try {
2479
- const result = effect(value, prev, createUtils());
2681
+ const result = effect(value, prev, utils);
2480
2682
  if (result instanceof Promise) {
2481
- const cleanup = await result;
2482
- if (cleanup && isActive) {
2483
- effectCleanups.set(i, cleanup);
2683
+ try {
2684
+ settle(await result);
2685
+ } catch (error) {
2686
+ fail(error);
2484
2687
  }
2485
- } else if (result) {
2486
- effectCleanups.set(i, result);
2487
- }
2488
- } catch (error) {
2489
- if (onError) {
2490
- onError(error, name);
2491
2688
  } else {
2492
- console.error(`Effect error${name ? ` in '${name}'` : ""}:`, error);
2689
+ settle(result);
2493
2690
  }
2691
+ } catch (error) {
2692
+ fail(error);
2494
2693
  }
2495
2694
  };
2496
- const effectFn = debounce && debounce > 0 ? createDebounced3(runEffect, debounce) : runEffect;
2695
+ const debounced = debounce && debounce > 0 ? createDebounced3(runEffect, debounce) : null;
2696
+ const effectFn = debounced ?? runEffect;
2497
2697
  if (fireImmediately) {
2498
- effectFn(prevValue, prevValue);
2698
+ const initial = selector2(store.getState());
2699
+ void effectFn(initial, initial);
2499
2700
  }
2500
2701
  const unsubscribe = store.subscribe(
2501
2702
  selector2,
2502
2703
  (value, prev) => {
2503
- if (!equalityFn(value, prev)) {
2504
- prevValue = value;
2505
- effectFn(value, prev);
2506
- }
2704
+ void effectFn(value, prev);
2507
2705
  },
2508
2706
  equalityFn
2509
2707
  );
2510
2708
  cleanups.push(() => {
2511
2709
  unsubscribe();
2512
- isActive = false;
2513
- if ("cancel" in effectFn) {
2514
- effectFn.cancel();
2515
- }
2516
- const cleanup = effectCleanups.get(i);
2517
- if (cleanup) {
2518
- try {
2519
- cleanup();
2520
- } catch {
2521
- }
2522
- }
2710
+ debounced?.cancel();
2711
+ deactivate(currentRun);
2712
+ const cleanup = currentCleanup;
2713
+ currentCleanup = null;
2714
+ runCleanup(cleanup);
2523
2715
  });
2524
2716
  }
2525
- store.__effectsCleanup = () => {
2717
+ destroyAll = () => {
2718
+ if (destroyed) return;
2719
+ destroyed = true;
2526
2720
  for (const cleanup of cleanups) {
2527
2721
  cleanup();
2528
2722
  }
2529
- effectCleanups.clear();
2530
2723
  };
2724
+ store.__effectsCleanup = destroyAll;
2725
+ },
2726
+ onDestroy() {
2727
+ destroyAll?.();
2531
2728
  }
2532
2729
  };
2533
2730
  }
@@ -2733,12 +2930,7 @@ function createAsyncValidator(validator) {
2733
2930
  };
2734
2931
  }
2735
2932
 
2736
- // src/index.ts
2737
- init_utils();
2738
-
2739
2933
  // src/testing.ts
2740
- init_store();
2741
- init_utils();
2742
2934
  function createMockStorage() {
2743
2935
  const storage = /* @__PURE__ */ new Map();
2744
2936
  return {
@@ -2953,7 +3145,7 @@ function toMiddlewareApi(store) {
2953
3145
  destroy: () => store.destroy()
2954
3146
  };
2955
3147
  }
2956
- function middlewareCompat(middleware, options) {
3148
+ function middlewareCompat(middleware, _options) {
2957
3149
  return {
2958
3150
  name: "middleware-compat",
2959
3151
  version: "1.0.0",
@@ -2986,7 +3178,6 @@ function middlewareCompat(middleware, options) {
2986
3178
  };
2987
3179
  }
2988
3180
  function createWithMiddleware(creator) {
2989
- const { createStore: createStore2 } = (init_store(), __toCommonJS(store_exports));
2990
3181
  let currentState = null;
2991
3182
  let storeRef = null;
2992
3183
  const set = (partial, replace) => {
@@ -3024,7 +3215,7 @@ function createWithMiddleware(creator) {
3024
3215
  }
3025
3216
  };
3026
3217
  currentState = creator(set, get, placeholderApi);
3027
- storeRef = createStore2(currentState);
3218
+ storeRef = createStore(currentState);
3028
3219
  const api = {
3029
3220
  setState: (partial, replace) => {
3030
3221
  if (typeof partial === "function") {
@@ -3065,6 +3256,8 @@ function compose(...middlewares) {
3065
3256
  };
3066
3257
  }
3067
3258
 
3259
+ exports.StoreError = StoreError;
3260
+ exports.StoreErrorCode = StoreErrorCode;
3068
3261
  exports.assertState = assertState;
3069
3262
  exports.batch = batch;
3070
3263
  exports.combineComputed = combineComputed;