@yoltra/core 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1744 +0,0 @@
1
- /*!
2
- * @yoltra/core v0.3.0
3
- * (c) 2026 Manu Ramirez <@pixerael>
4
- * License: MIT
5
- * Homepage: https://yoltra.dev
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree
9
- */
10
- var P = Object.defineProperty;
11
- var z = (a, e, t) => e in a ? P(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
12
- var d = (a, e, t) => z(a, typeof e != "symbol" ? e + "" : e, t);
13
- class O {
14
- constructor() {
15
- /**
16
- * Internal registry: `channel → type → Set<handler>`.
17
- * @internal
18
- */
19
- d(this, "handlers", /* @__PURE__ */ new Map());
20
- }
21
- /**
22
- * Subscribes a handler to an exact `(channel, type)`.
23
- *
24
- * @typeParam C - Channel key (must be a string key of `EM`).
25
- * @typeParam T - Type key within channel `C` (must be a string key of `EM[C]`).
26
- * @param channel - Channel name to subscribe to.
27
- * @param type - Event type within the channel.
28
- * @param handler - Function invoked with the payload type `EM[C][T]`.
29
- * @returns An **unsubscribe** function that removes this handler.
30
- *
31
- * @example
32
- * ```ts
33
- * const off = bus.on('data', 'loaded', ({ items }) => {
34
- * console.log('Loaded', items.length, 'items');
35
- * });
36
- *
37
- * // Later, stop listening:
38
- * off();
39
- * ```
40
- *
41
- * @public
42
- */
43
- on(e, t, r) {
44
- let n = this.handlers.get(e);
45
- n || (n = /* @__PURE__ */ new Map(), this.handlers.set(e, n));
46
- let s = n.get(t);
47
- return s || (s = /* @__PURE__ */ new Set(), n.set(t, s)), s.add(r), () => this.off(e, t, r);
48
- }
49
- /**
50
- * Removes a specific handler previously added with {@link EventBus.on | `on`}.
51
- *
52
- * @typeParam C - Channel key (string key of `EM`).
53
- * @typeParam T - Type key within channel `C` (string key of `EM[C]`).
54
- * @param channel - Channel name of the subscription to remove.
55
- * @param type - Event type of the subscription to remove.
56
- * @param handler - The same handler reference that was passed to `on`.
57
- *
58
- * @example
59
- * ```ts
60
- * const h = (n: number) => console.log('inc', n);
61
- * bus.on('math', 'inc', h);
62
- *
63
- * // Explicitly remove this handler:
64
- * bus.off('math', 'inc', h);
65
- * ```
66
- *
67
- * @public
68
- */
69
- off(e, t, r) {
70
- const n = this.handlers.get(e);
71
- if (!n) return;
72
- const s = n.get(t);
73
- s && (s.delete(r), s.size === 0 && n.delete(t), n.size === 0 && this.handlers.delete(e));
74
- }
75
- /**
76
- * Emits an event to all subscribers of the exact `(channel, type)`.
77
- *
78
- * Handlers are invoked **synchronously**. Any exception thrown by a handler is
79
- * caught and logged, and other handlers still run.
80
- *
81
- * @typeParam C - Channel key (string key of `EM`).
82
- * @typeParam T - Type key within channel `C` (string key of `EM[C]`).
83
- * @param channel - Channel name to emit on.
84
- * @param type - Event type to emit.
85
- * @param payload - Payload matching `EM[C][T]`.
86
- *
87
- * @example
88
- * ```ts
89
- * bus.emit('ui', 'toggle', false);
90
- * ```
91
- *
92
- * @public
93
- */
94
- emit(e, t, r) {
95
- const n = this.handlers.get(e);
96
- if (!n) return;
97
- const s = n.get(t);
98
- if (!(!s || s.size === 0))
99
- for (const c of [...s])
100
- try {
101
- c(r);
102
- } catch (i) {
103
- console.error("EventBus handler error:", i);
104
- }
105
- }
106
- /**
107
- * Clears **all** listeners across all channels/types.
108
- *
109
- * Useful for tests or during HMR teardown to avoid duplicate handlers.
110
- *
111
- * @example
112
- * ```ts
113
- * // In a test teardown:
114
- * afterEach(() => bus.clear());
115
- * ```
116
- *
117
- * @public
118
- */
119
- clear() {
120
- this.handlers.clear();
121
- }
122
- }
123
- class k {
124
- constructor() {
125
- /**
126
- * Exact handlers: `channel → type → [handlers]`.
127
- * @internal
128
- */
129
- d(this, "handlers", /* @__PURE__ */ new Map());
130
- /**
131
- * Pattern handlers with `*` and `**`: `channel → pattern(string) → [handlers]`.
132
- * @internal
133
- */
134
- d(this, "patternHandlers", /* @__PURE__ */ new Map());
135
- }
136
- /**
137
- * Subscribes a handler to either an **exact** type or a **pattern**.
138
- *
139
- * @param channel - Channel to subscribe on.
140
- * @param type - Exact event type (e.g. `"a.b"`) or pattern (contains `*`/`**`).
141
- * @param handler - Function invoked with the emitted payload.
142
- * @returns An **unsubscribe** function that removes this handler.
143
- *
144
- * @remarks
145
- * - Exact subscriptions are stored under a **normalized** key (leading `.` removed).
146
- * - Pattern subscriptions are stored **as provided**; matching normalizes the subject.
147
- *
148
- * @example Exact subscription
149
- * ```ts
150
- * const off = bus.on('data', 'items.loaded', ({ count }) => {
151
- * console.log('Loaded', count);
152
- * });
153
- * // Later
154
- * off();
155
- * ```
156
- *
157
- * @example Pattern subscription
158
- * ```ts
159
- * // Match any single sub-event: 'panel.open', 'panel.close', etc.
160
- * const offStar = bus.on('ui', 'panel.*', () => {});
161
- *
162
- * // Match any depth: 'panel.open', 'panel.items.add', 'panel', etc.
163
- * const offGlob = bus.on('ui', 'panel.**', () => {});
164
- * ```
165
- *
166
- * @public
167
- */
168
- on(e, t, r) {
169
- const n = String(t);
170
- if (this.isPattern(n)) {
171
- const s = n;
172
- this.patternHandlers.has(e) || this.patternHandlers.set(e, /* @__PURE__ */ new Map());
173
- const c = this.patternHandlers.get(e);
174
- return c.has(s) || c.set(s, []), c.get(s).push(r), () => this.offPattern(e, s, r);
175
- } else {
176
- const s = this.normalizeTypeKey(n);
177
- this.handlers.has(e) || this.handlers.set(e, /* @__PURE__ */ new Map());
178
- const c = this.handlers.get(e);
179
- return c.has(s) || c.set(s, []), c.get(s).push(r), () => this.offExactNormalized(e, s, r);
180
- }
181
- }
182
- /**
183
- * Unsubscribes an **exact** handler. The `type` key is normalized internally,
184
- * so callers can pass `"foo"` or `".foo"` interchangeably.
185
- *
186
- * @param channel - Channel name.
187
- * @param type - Exact event type key to remove (normalization applied).
188
- * @param handler - The same handler reference previously passed to {@link LooseEventBus.on | `on`}.
189
- *
190
- * @example
191
- * ```ts
192
- * const h = () => {};
193
- * bus.on('ui', 'panel.open', h);
194
- * // Remove it (with or without leading dot)
195
- * bus.off('ui', '.panel.open', h);
196
- * ```
197
- *
198
- * @public
199
- */
200
- off(e, t, r) {
201
- const n = this.normalizeTypeKey(String(t));
202
- this.offExactNormalized(e, n, r);
203
- }
204
- /**
205
- * Internal exact unsubscription using an already **normalized** type key.
206
- *
207
- * @param channel - Channel name.
208
- * @param normalizedType - Event type key with leading dot removed.
209
- * @param handler - Handler to remove.
210
- * @internal
211
- */
212
- offExactNormalized(e, t, r) {
213
- const n = this.handlers.get(e);
214
- if (!n) return;
215
- const s = n.get(t);
216
- if (!s) return;
217
- const c = s.indexOf(r);
218
- c !== -1 && s.splice(c, 1), s.length === 0 && n.delete(t), n.size === 0 && this.handlers.delete(e);
219
- }
220
- /**
221
- * Internal removal for a **pattern** subscription. No-ops if missing.
222
- *
223
- * @param channel - Channel name.
224
- * @param pattern - Pattern string as originally subscribed.
225
- * @param handler - Handler to remove.
226
- * @internal
227
- */
228
- offPattern(e, t, r) {
229
- const n = this.patternHandlers.get(e);
230
- if (!n) return;
231
- const s = n.get(t);
232
- if (!s) return;
233
- const c = s.indexOf(r);
234
- c !== -1 && s.splice(c, 1), s.length === 0 && n.delete(t), n.size === 0 && this.patternHandlers.delete(e);
235
- }
236
- /**
237
- * Emits an event to all exact subscribers first, then to **matching pattern** subscribers.
238
- * Duplicate handler references are called **once** (de-duped).
239
- *
240
- * @param channel - Channel to emit on.
241
- * @param type - Event type (subject). A leading dot is ignored for matching.
242
- * @param payload - Payload delivered to handlers.
243
- *
244
- * @example
245
- * ```ts
246
- * // Suppose:
247
- * // - on('ui', 'panel.open', h)
248
- * // - on('ui', 'panel.*', h) // same handler ref!
249
- * // - on('ui', 'panel.**', other)
250
- * bus.emit('ui', 'panel.open', { id: 1 });
251
- * // => 'h' runs once (de-duped), then 'other'
252
- * ```
253
- *
254
- * @public
255
- */
256
- emit(e, t, r) {
257
- const n = String(t), s = this.normalizeTypeKey(n), c = this.handlers.get(e)?.get(s) ?? [], i = this.patternHandlers.get(e), o = [];
258
- if (i && i.size) {
259
- const l = this.normalizeTypeKey(n);
260
- for (const [u, p] of i.entries())
261
- this.matchPattern(u, l) && o.push(p);
262
- }
263
- const f = /* @__PURE__ */ new Set(), h = (l) => {
264
- for (const u of [...l])
265
- if (!f.has(u)) {
266
- f.add(u);
267
- try {
268
- u(r);
269
- } catch (p) {
270
- console.error(p);
271
- continue;
272
- }
273
- }
274
- };
275
- h(c);
276
- for (const l of o) h(l);
277
- }
278
- /**
279
- * Determines if a string is a **pattern** (contains `*`).
280
- * @param s - Event type or pattern string.
281
- * @returns `true` if it contains at least one `*`, else `false`.
282
- * @internal
283
- */
284
- isPattern(e) {
285
- return e.includes("*");
286
- }
287
- /**
288
- * Normalizes event type keys for exact matching by stripping a **single** leading dot.
289
- *
290
- * @param s - Event type key.
291
- * @returns Normalized key without a leading dot.
292
- * @example
293
- * ```ts
294
- * normalizeTypeKey('.a.b') // 'a.b'
295
- * normalizeTypeKey('a.b') // 'a.b'
296
- * ```
297
- * @internal
298
- */
299
- normalizeTypeKey(e) {
300
- return e.replace(/^\./, "");
301
- }
302
- /**
303
- * Splits a path into dot-separated segments after normalization and removes empties.
304
- * @param p - Event type or pattern string.
305
- * @internal
306
- */
307
- splitPath(e) {
308
- return this.normalizeTypeKey(e).split(".").filter(Boolean);
309
- }
310
- /**
311
- * Pattern matcher over dot-separated segments.
312
- *
313
- * Rules:
314
- * - **literal**: exact match.
315
- * - `*` : matches exactly **one** segment.
316
- * - `**` : matches **zero or more** remaining segments (including empty).
317
- *
318
- * @param pattern - Pattern (may include `*`/`**`).
319
- * @param path - Subject event type key to test.
320
- * @returns `true` if the pattern matches the path; otherwise `false`.
321
- *
322
- * @example
323
- * ```ts
324
- * matchPattern('a.*', 'a.b') // true
325
- * matchPattern('a.*', 'a.b.c') // false
326
- * matchPattern('a.**', 'a') // true
327
- * matchPattern('a.**', 'a.b.c') // true
328
- * matchPattern('**.end', 'x.y.end') // true
329
- * ```
330
- *
331
- * @internal
332
- */
333
- matchPattern(e, t) {
334
- const r = this.splitPath(e), n = this.splitPath(t);
335
- let s = 0, c = 0, i = -1, o = 0;
336
- for (; c < n.length; )
337
- if (s < r.length && (r[s] === "*" || r[s] === n[c]))
338
- s++, c++;
339
- else if (s < r.length && r[s] === "**")
340
- i = s, o = c, s++;
341
- else if (i !== -1)
342
- s = i + 1, c = ++o;
343
- else
344
- return !1;
345
- for (; s < r.length && r[s] === "**"; ) s++;
346
- return s === r.length;
347
- }
348
- /**
349
- * Removes **all** listeners (exact and pattern). Useful for tests/HMR teardown.
350
- *
351
- * @example
352
- * ```ts
353
- * afterEach(() => bus.clear());
354
- * ```
355
- *
356
- * @public
357
- */
358
- clear() {
359
- this.handlers.clear(), this.patternHandlers.clear();
360
- }
361
- /**
362
- * Returns a snapshot of all registered subscriptions for DevTools introspection.
363
- *
364
- * @returns An array of `{ channel, type, count }` entries for each distinct
365
- * (channel, type/pattern) pair with at least one handler.
366
- *
367
- * @internal
368
- */
369
- __introspect() {
370
- const e = [];
371
- for (const [t, r] of this.handlers)
372
- for (const [n, s] of r)
373
- s.length > 0 && e.push({ channel: t, type: n, count: s.length });
374
- for (const [t, r] of this.patternHandlers)
375
- for (const [n, s] of r)
376
- s.length > 0 && e.push({ channel: t, type: n, count: s.length });
377
- return e;
378
- }
379
- }
380
- class _ {
381
- /**
382
- * Creates a new {@link Reducer} from a pure reducer function.
383
- *
384
- * @param reduce - A function `(state, event) => nextState` that implements your update logic.
385
- *
386
- * @example
387
- * ```ts
388
- * const reducer = new Reducer<MyState, MyEM>((state, event) => {
389
- * // implement your transitions here
390
- * return state;
391
- * });
392
- * ```
393
- *
394
- * @public
395
- */
396
- constructor(e) {
397
- /**
398
- * The underlying pure reducer function.
399
- * @internal
400
- */
401
- d(this, "_reduce");
402
- this._reduce = e;
403
- }
404
- /**
405
- * Applies the reducer to produce the next state.
406
- *
407
- * @param state - Current state.
408
- * @param event - An event drawn from {@link EventUnion | `EventUnion<EM>`}.
409
- * @returns The next state produced by the underlying reducer function.
410
- *
411
- * @example
412
- * ```ts
413
- * const next = reducer.reduce(curr, someEvent as EventUnion<MyEM>);
414
- * ```
415
- *
416
- * @public
417
- */
418
- reduce(e, t) {
419
- return this._reduce(e, t);
420
- }
421
- }
422
- function g(a, e, t = "", r = /* @__PURE__ */ new Map()) {
423
- if (a === e) return [];
424
- if (typeof a != "object" || typeof e != "object" || a === null || e === null)
425
- return typeof a == "number" && Number.isNaN(a) && Number.isNaN(e) ? [] : [t];
426
- if (a instanceof Date && e instanceof Date)
427
- return a.getTime() === e.getTime() ? [] : [t];
428
- if (a instanceof RegExp && e instanceof RegExp)
429
- return a.source === e.source && e.flags === a.flags ? [] : [t];
430
- const n = a, s = e, c = r.get(n);
431
- if (c?.has(s)) return [];
432
- const i = c ?? /* @__PURE__ */ new Set();
433
- i.add(s), c || r.set(n, i);
434
- try {
435
- const o = Array.isArray(a), f = Array.isArray(e);
436
- if (o !== f) return [t];
437
- const h = [];
438
- if (o) {
439
- const u = a, p = e;
440
- if (u.length !== p.length) return [t];
441
- for (let y = 0; y < u.length; y++) {
442
- const m = t ? `${t}.${y}` : `${y}`;
443
- h.push(...g(u[y], p[y], m, r));
444
- }
445
- return h.filter(Boolean);
446
- }
447
- const l = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(e)]);
448
- for (const u of l) {
449
- const p = t ? `${t}.${u}` : u, y = Object.prototype.hasOwnProperty.call(a, u), m = Object.prototype.hasOwnProperty.call(e, u);
450
- if (!y || !m) {
451
- h.push(p);
452
- continue;
453
- }
454
- h.push(...g(a[u], e[u], p, r));
455
- }
456
- return h.filter(Boolean);
457
- } finally {
458
- i.delete(s), i.size === 0 && r.delete(n);
459
- }
460
- }
461
- function E(a, e = /* @__PURE__ */ new WeakSet()) {
462
- if (a === null || typeof a != "object" || e.has(a) || Object.isFrozen(a)) return a;
463
- if (e.add(a), Array.isArray(a)) {
464
- const t = a;
465
- for (let r = 0; r < t.length; r++)
466
- t[r] = E(t[r], e);
467
- return Object.freeze(t);
468
- }
469
- for (const t of Object.getOwnPropertyNames(a)) {
470
- const r = Object.getOwnPropertyDescriptor(a, t);
471
- !r || !("value" in r) || (a[t] = E(a[t], e));
472
- }
473
- for (const t of Object.getOwnPropertySymbols(a)) {
474
- const r = Object.getOwnPropertyDescriptor(a, t);
475
- !r || !("value" in r) || (a[t] = E(a[t], e));
476
- }
477
- return Object.freeze(a);
478
- }
479
- function b(a) {
480
- return process.env.NODE_ENV === "production" ? a : E(a);
481
- }
482
- const w = 100, S = () => typeof performance < "u" && typeof performance.now == "function" ? performance.now() : Date.now();
483
- class v {
484
- /**
485
- * Creates a store from a {@link StoreSpec}.
486
- *
487
- * @param spec - Store configuration (name, reducers, middleware, optional effects).
488
- *
489
- * @public
490
- */
491
- constructor(e) {
492
- /**
493
- * Store name (used by DevTools & diagnostics).
494
- *
495
- * @public
496
- */
497
- d(this, "name");
498
- /**
499
- * Registered middleware pipeline (run **before** reducers).
500
- * Stores either raw functions (legacy) or MiddlewareSpec objects.
501
- * Return `false` from the middleware function to stop propagation.
502
- *
503
- * @internal
504
- */
505
- d(this, "middleware");
506
- /**
507
- * Installed slice reducers keyed by slice name.
508
- *
509
- * @internal
510
- */
511
- d(this, "reducers");
512
- /**
513
- * Current immutable snapshot of the store state.
514
- * This reference changes whenever any slice changes (shallow immutability).
515
- *
516
- * @internal
517
- */
518
- d(this, "state");
519
- /**
520
- * Bus for reducer wiring (emit by `(channel, type)`).
521
- *
522
- * @internal
523
- */
524
- d(this, "reducerBus");
525
- /**
526
- * Bus for **granular** connector events (emit by **dotted path** inside a slice).
527
- *
528
- * @internal
529
- */
530
- d(this, "connectorBus");
531
- /**
532
- * Coarse-grained listeners (called once per committed event, only if state changed).
533
- *
534
- * @internal
535
- */
536
- d(this, "listeners", /* @__PURE__ */ new Set());
537
- /**
538
- * Registered effect handlers keyed by `"channel::type"` for O(1) lookup.
539
- * Used for effects with explicit `keys` or legacy `events` targeting.
540
- *
541
- * @internal
542
- */
543
- d(this, "effects", /* @__PURE__ */ new Map());
544
- /**
545
- * Pattern-based effects that need runtime matching.
546
- * Used for effects with `when: { any }`, `{ channel }`, or `{ channels }`.
547
- * Stores tuples of [effect function, when matcher].
548
- *
549
- * @internal
550
- */
551
- d(this, "patternEffects", /* @__PURE__ */ new Set());
552
- /**
553
- * Committed event subscribers keyed by `"channel::type"` for O(1) lookup.
554
- * Notified after reducers, before effects, for events that passed middleware.
555
- *
556
- * @internal
557
- */
558
- d(this, "committedEventSubscribers", /* @__PURE__ */ new Map());
559
- /**
560
- * Uncommitted event subscribers keyed by `"channel::type"` for O(1) lookup.
561
- * Notified when middleware rejects an event.
562
- *
563
- * @internal
564
- */
565
- d(this, "uncommittedEventSubscribers", /* @__PURE__ */ new Map());
566
- /**
567
- * All-events subscribers keyed by `"channel::type"` for O(1) lookup.
568
- * Notified for both committed and uncommitted events with phase parameter.
569
- *
570
- * @internal
571
- */
572
- d(this, "allEventSubscribers", /* @__PURE__ */ new Map());
573
- /**
574
- * Track reducerBus unsubs per slice for HMR/register/unregister.
575
- *
576
- * @internal
577
- */
578
- d(this, "sliceUnsubs", /* @__PURE__ */ new Map());
579
- /**
580
- * Pattern-based reducers that need runtime matching.
581
- * Used for reducers with `when: { any }`, `{ channel }`, or `{ channels }`.
582
- * Maps slice name to the `when` matcher.
583
- *
584
- * @internal
585
- */
586
- d(this, "patternReducers", /* @__PURE__ */ new Map());
587
- /**
588
- * Whether `__replayEvents()` is allowed.
589
- * Set from `spec.devtools.allowReplay`.
590
- *
591
- * @internal
592
- */
593
- d(this, "replayEnabled");
594
- /**
595
- * Optional hook invoked when an effect throws/rejects. See
596
- * {@link StoreSpec.onEffectError}. `await emit()` never rejects on effect
597
- * failure — this is how callers observe effect errors.
598
- */
599
- d(this, "onEffectError");
600
- /**
601
- * Pending events awaiting the **synchronous** reduce phase (middleware +
602
- * reducers + subscribers + coarse listeners). Drained by {@link drainReduce}.
603
- *
604
- * @internal
605
- */
606
- d(this, "reduceQueue", []);
607
- /**
608
- * Re-entrancy guard for the synchronous reduce phase.
609
- *
610
- * @internal
611
- */
612
- d(this, "isReducing", !1);
613
- /**
614
- * Registered instrumentation observers (DevTools seam). See {@link instrument}.
615
- *
616
- * @internal
617
- */
618
- d(this, "instrumentObservers", /* @__PURE__ */ new Set());
619
- /**
620
- * Scratch array collecting slice-prefixed changed leaf paths during an
621
- * instrumented reduce. Set by {@link drainReduce} while observers are active;
622
- * appended to by {@link forwardEvent}. `null` when not instrumenting.
623
- *
624
- * @internal
625
- */
626
- d(this, "changedPathSink", null);
627
- /**
628
- * Count of effect tasks currently in flight; surfaced as queue depth by
629
- * {@link __devtoolsIntrospect}.
630
- *
631
- * @internal
632
- */
633
- d(this, "inFlightEffects", 0);
634
- /**
635
- * Tracks processed events by fingerprint with timestamps for TTL-based deduplication.
636
- *
637
- * **Deduplication Behavior:**
638
- * - Events are fingerprinted using `channel::type::JSON(payload)`
639
- * - If an identical fingerprint is seen within the dedup window, it's skipped
640
- * - The window is 50ms in development, 100ms in production
641
- *
642
- * **Limitations:**
643
- * - Non-serializable payloads (functions, symbols, circular refs) get unique
644
- * fingerprints and won't be deduplicated
645
- * - Legitimate rapid-fire identical events may be incorrectly deduplicated
646
- * - The cache is bounded to 1000 entries with lazy pruning
647
- *
648
- * @internal
649
- */
650
- d(this, "processedEvents", /* @__PURE__ */ new Map());
651
- /**
652
- * Lifetime count of events suppressed by the deduplication cache.
653
- * Exposed via {@link __devtoolsIntrospect} so the DevTools agent can
654
- * surface it in the STORE_METRICS response without further core changes.
655
- *
656
- * @internal
657
- */
658
- d(this, "dedupCount", 0);
659
- /**
660
- * Store-owned metadata for registered effects, keyed by the effect function.
661
- * Kept **off** the caller's function object: mutating a user-owned function
662
- * (the old `fn.__quoMeta`) bled metadata across stores that share a handler
663
- * and left it attached after unregister. Cleared on {@link dispose}.
664
- *
665
- * @internal
666
- */
667
- d(this, "effectMeta", /* @__PURE__ */ new WeakMap());
668
- /**
669
- * Configuration for event deduplication.
670
- * @internal
671
- */
672
- d(this, "dedupConfig");
673
- /**
674
- * Timer for periodic cleanup of processed events.
675
- *
676
- * @internal
677
- */
678
- d(this, "eventCleanupTimer", null);
679
- if (this.name = e.name ?? "yoltra Store", this.reducerBus = new O(), this.connectorBus = new k(), this.middleware = [...e.middleware ?? []], this.reducers = {}, this.state = {}, this.replayEnabled = e.devtools?.allowReplay ?? !1, this.onEffectError = e.onEffectError, this.dedupConfig = {
680
- windowMs: e.dedupWindowMs ?? 0,
681
- maxCacheSize: 1e3
682
- }, Object.entries(e.reducer).forEach(([t, r]) => {
683
- this.mountSlice(t, r, { preserveState: !1 });
684
- }), e.effects?.length)
685
- for (const t of e.effects)
686
- this.registerEffect(t);
687
- this.dispose = this.dispose.bind(this), this.notifyEffects = this.notifyEffects.bind(this), this.forwardEvent = this.forwardEvent.bind(this), this.__applyExternalState = this.__applyExternalState.bind(this), this.__replayEvents = this.__replayEvents.bind(this), this.__devtoolsIntrospect = this.__devtoolsIntrospect.bind(this), this.mountSlice = this.mountSlice.bind(this), this.unmountSlice = this.unmountSlice.bind(this), this.getAtPath = this.getAtPath.bind(this), this.emit = this.emit.bind(this), this.subscribe = this.subscribe.bind(this), this.connect = this.connect.bind(this), this.onEffect = this.onEffect.bind(this), this.onEvent = this.onEvent.bind(this), this.getState = this.getState.bind(this), this.registerEffect = this.registerEffect.bind(this), this.registerMiddleware = this.registerMiddleware.bind(this), this.registerReducer = this.registerReducer.bind(this), this.replaceMiddleware = this.replaceMiddleware.bind(this), this.replaceEffects = this.replaceEffects.bind(this), this.replaceReducers = this.replaceReducers.bind(this), this.hotReplace = this.hotReplace.bind(this);
688
- }
689
- /**
690
- * Cleanup resources (timers, etc.) when disposing the store.
691
- * Call this if you're dynamically creating/destroying stores.
692
- *
693
- * @example
694
- * ```ts
695
- * const store = createStore({ ... });
696
- * // later
697
- * store.dispose();
698
- * ```
699
- *
700
- * @public
701
- */
702
- dispose() {
703
- this.eventCleanupTimer && (clearInterval(this.eventCleanupTimer), this.eventCleanupTimer = null), this.processedEvents.clear(), this.effects.clear(), this.patternEffects.clear(), this.effectMeta = /* @__PURE__ */ new WeakMap(), this.listeners.clear(), this.committedEventSubscribers.clear(), this.uncommittedEventSubscribers.clear(), this.allEventSubscribers.clear(), this.instrumentObservers.clear(), this.connectorBus.clear(), this.reducerBus.clear(), this.patternReducers.clear(), this.sliceUnsubs.clear(), this.changedPathSink = null;
704
- }
705
- /**
706
- * Generates a fingerprint for an event for deduplication purposes.
707
- * Falls back gracefully for non-serializable payloads.
708
- *
709
- * @param channel - Event channel.
710
- * @param type - Event type.
711
- * @param payload - Event payload.
712
- * @returns A string fingerprint for the event.
713
- *
714
- * @internal
715
- */
716
- fingerprint(e, t, r) {
717
- const n = `${e}::${t}`;
718
- try {
719
- if (r == null)
720
- return `${n}::null`;
721
- if (typeof r != "object")
722
- return `${n}::${String(r)}`;
723
- const s = JSON.stringify(r);
724
- return `${n}::${s}`;
725
- } catch {
726
- return `${n}::${Date.now()}::${Math.random()}`;
727
- }
728
- }
729
- /**
730
- * Checks if an event should be deduplicated.
731
- * Returns true if this is a duplicate that should be skipped.
732
- *
733
- * @param fp - Event fingerprint.
734
- * @returns `true` if duplicate (should skip), `false` otherwise.
735
- *
736
- * @internal
737
- */
738
- shouldDedupe(e, t) {
739
- const r = Date.now(), n = this.processedEvents.get(e);
740
- return n !== void 0 && r - n < t ? (this.dedupCount++, !0) : (this.processedEvents.set(e, r), this.ensureCleanupTimer(), this.processedEvents.size > this.dedupConfig.maxCacheSize && this.pruneProcessedEvents(r), !1);
741
- }
742
- /**
743
- * Starts the periodic prune interval if it isn't already running. Called when
744
- * the first entry is cached so the timer's lifetime tracks actual dedup use
745
- * (content window or identity `dedupKey`), independent of `dedupWindowMs`.
746
- *
747
- * @internal
748
- */
749
- ensureCleanupTimer() {
750
- this.eventCleanupTimer === null && (this.eventCleanupTimer = setInterval(() => {
751
- this.pruneProcessedEvents(Date.now());
752
- }, 5e3), this.eventCleanupTimer.unref?.());
753
- }
754
- /**
755
- * Removes expired entries from the processed events cache.
756
- *
757
- * @param now - Current timestamp.
758
- *
759
- * @internal
760
- */
761
- pruneProcessedEvents(e) {
762
- const t = Math.max(this.dedupConfig.windowMs, w), r = e - t * 2;
763
- for (const [n, s] of this.processedEvents)
764
- s < r && this.processedEvents.delete(n);
765
- this.processedEvents.size === 0 && this.eventCleanupTimer !== null && (clearInterval(this.eventCleanupTimer), this.eventCleanupTimer = null);
766
- }
767
- /**
768
- * Checks if an event matches a `When` matcher.
769
- *
770
- * @param when - The When matcher (or undefined for "all events").
771
- * @param event - The event to check.
772
- * @returns `true` if the event matches, `false` otherwise.
773
- *
774
- * @remarks
775
- * - `undefined` or missing `when` matches ALL events.
776
- * - `{ any: true }` matches ALL events.
777
- * - `{ keys: [...] }` matches if event's `[channel, type]` is in the array.
778
- * - `{ channel: 'x' }` matches if event's channel equals 'x'.
779
- * - `{ channels: ['x', 'y'] }` matches if event's channel is in the array.
780
- *
781
- * @internal
782
- */
783
- matchesWhen(e, t) {
784
- return !e || "any" in e && e.any === !0 ? !0 : "keys" in e ? e.keys.some(
785
- ([r, n]) => t.channel === r && t.type === n
786
- ) : "channel" in e ? t.channel === e.channel : "channels" in e ? e.channels.includes(t.channel) : !1;
787
- }
788
- /**
789
- * Extracts the middleware function from a MiddlewareInput.
790
- * Handles both raw functions (legacy) and MiddlewareSpec objects.
791
- *
792
- * @param input - MiddlewareInput (function or spec).
793
- * @returns The middleware function.
794
- *
795
- * @internal
796
- */
797
- getMiddlewareFunction(e) {
798
- return typeof e == "function" ? e : e.middleware;
799
- }
800
- /**
801
- * Gets the `when` matcher from a MiddlewareInput.
802
- *
803
- * @param input - MiddlewareInput (function or spec).
804
- * @returns The `when` matcher, or `undefined` for raw functions (match all).
805
- *
806
- * @internal
807
- */
808
- getMiddlewareWhen(e) {
809
- if (typeof e != "function")
810
- return e.when;
811
- }
812
- /**
813
- * Invokes all registered **effects** for a given event.
814
- * Handles both key-based effects (O(1) lookup) and pattern-based effects (runtime matching).
815
- * Errors are caught and logged.
816
- *
817
- * @param event - The event that was reduced.
818
- * @internal
819
- */
820
- async notifyEffects(e) {
821
- const t = `${String(e.channel)}::${String(e.type)}`, r = this.effects.get(t);
822
- if (r && r.size > 0)
823
- for (const n of [...r])
824
- try {
825
- await n(e, this.getState, this.emit);
826
- } catch (s) {
827
- console.error("Effect error:", s), this.onEffectError?.(s, e);
828
- }
829
- for (const { effect: n, when: s } of this.patternEffects)
830
- if (this.matchesWhen(s, e))
831
- try {
832
- await n(e, this.getState, this.emit);
833
- } catch (c) {
834
- console.error("Effect error:", c), this.onEffectError?.(c, e);
835
- }
836
- }
837
- /**
838
- * Notifies event subscribers for a specific phase.
839
- *
840
- * Calls both phase-specific subscribers and 'all' subscribers.
841
- * Errors are caught and logged, allowing other subscribers to continue.
842
- *
843
- * @param event - The event to notify about.
844
- * @param phase - The phase ('committed' or 'uncommitted').
845
- * @internal
846
- */
847
- notifyEventSubscribers(e, t) {
848
- const r = `${String(e.channel)}::${String(e.type)}`, s = (t === "committed" ? this.committedEventSubscribers : this.uncommittedEventSubscribers).get(r);
849
- if (s?.size)
850
- for (const i of [...s]) this.invokeEventSubscriber(i, e, t);
851
- const c = this.allEventSubscribers.get(r);
852
- if (c?.size)
853
- for (const i of [...c]) this.invokeEventSubscriber(i, e, t);
854
- }
855
- /**
856
- * Invokes a single event-subscription handler **fire-and-forget**: synchronous
857
- * throws and async rejections are logged but never block the emit pipeline.
858
- * Event subscribers are notifications, not part of the committed reduce result.
859
- *
860
- * @internal
861
- */
862
- invokeEventSubscriber(e, t, r) {
863
- try {
864
- const n = e(t, this.getState, this.emit, r);
865
- n && typeof n.then == "function" && n.catch((s) => console.error("Event subscription error:", s));
866
- } catch (n) {
867
- console.error("Event subscription error:", n);
868
- }
869
- }
870
- /**
871
- * Applies a reduced event to a slice and emits **precise** connector events.
872
- *
873
- * For each changed **leaf path** (via {@link detectChangedProps}), emits that leaf and
874
- * all of its **ancestors** once (e.g., `"data"`, `"data.123"`, `"data.123.title"`).
875
- *
876
- * **State Immutability**: When a slice changes, a new state object is created via
877
- * shallow spread: `{ ...this.state, [sliceName]: newSlice }`. This ensures that
878
- * `this.state` reference changes, enabling efficient change detection via `===`.
879
- *
880
- * @param rName - Slice name being updated.
881
- * @param event - Reduced event with typed payload.
882
- * @returns `true` if the slice actually changed, `false` otherwise.
883
- *
884
- * @internal
885
- */
886
- forwardEvent(e, t) {
887
- const r = this.state[e], n = this.reducers[e].reduce(r, t);
888
- if (r === n) return !1;
889
- const s = g(r, n).filter(Boolean);
890
- if (s.length === 0) return !1;
891
- const c = b(n);
892
- if (this.state = { ...this.state, [e]: c }, this.changedPathSink)
893
- for (const o of s)
894
- this.changedPathSink.push(o ? `${e}.${o}` : e);
895
- const i = /* @__PURE__ */ new Set();
896
- for (const o of s)
897
- for (const f of v.buildAncestorPaths(o)) i.add(f);
898
- for (const o of i) {
899
- const f = this.getAtPath(r, o), h = this.getAtPath(c, o);
900
- this.connectorBus.emit(e, o, { oldValue: f, newValue: h, path: o });
901
- }
902
- return !0;
903
- }
904
- /**
905
- * Returns a structured introspection snapshot for DevTools UIs.
906
- *
907
- * @remarks
908
- * Reads the internal middleware, effects, reducers, and subscriber
909
- * registries and returns a plain-object summary matching the
910
- * `STORE_SUBSCRIPTIONS` protocol message shape.
911
- *
912
- * @public
913
- */
914
- __devtoolsIntrospect() {
915
- const e = Object.keys(this.reducers).map((i) => {
916
- const o = this.patternReducers.get(i);
917
- return { name: i, when: o };
918
- }), t = [];
919
- for (const [i, o] of this.effects) {
920
- if (o.size === 0) continue;
921
- const [f, h] = i.split("::");
922
- for (const l of o) {
923
- const u = this.effectMeta.get(l);
924
- t.push({ channel: f, type: h, name: u?.name, description: u?.description });
925
- }
926
- }
927
- for (const i of this.patternEffects) {
928
- const o = this.effectMeta.get(i.effect);
929
- t.push({
930
- channel: "*",
931
- type: "*",
932
- name: o?.name,
933
- description: o?.description
934
- });
935
- }
936
- const r = [];
937
- for (const i of this.middleware)
938
- typeof i == "function" ? r.push({ name: i.name || void 0 }) : r.push({
939
- name: i.meta?.name,
940
- description: i.meta?.description,
941
- when: i.when
942
- });
943
- const n = [];
944
- for (const i of this.connectorBus.__introspect())
945
- for (let o = 0; o < i.count; o++)
946
- n.push({ reducer: i.channel, property: i.type });
947
- const s = [];
948
- for (const [i, o] of this.committedEventSubscribers) {
949
- if (o.size === 0) continue;
950
- const [f, h] = i.split("::");
951
- for (let l = 0; l < o.size; l++)
952
- s.push({ channel: f, type: h, phase: "committed" });
953
- }
954
- for (const [i, o] of this.uncommittedEventSubscribers) {
955
- if (o.size === 0) continue;
956
- const [f, h] = i.split("::");
957
- for (let l = 0; l < o.size; l++)
958
- s.push({ channel: f, type: h, phase: "uncommitted" });
959
- }
960
- for (const [i, o] of this.allEventSubscribers) {
961
- if (o.size === 0) continue;
962
- const [f, h] = i.split("::");
963
- for (let l = 0; l < o.size; l++)
964
- s.push({ channel: f, type: h, phase: "all" });
965
- }
966
- const c = this.listeners.size;
967
- return {
968
- reducers: e,
969
- effects: t,
970
- middleware: r,
971
- atomic: n,
972
- event: s,
973
- coarse: c,
974
- dedupHits: this.dedupCount,
975
- queueDepth: this.reduceQueue.length + this.inFlightEffects
976
- };
977
- }
978
- /**
979
- * Applies an externally provided **whole-state** (e.g., DevTools time travel) and emits
980
- * fine-grained path changes for each slice.
981
- *
982
- * **State Immutability**: If any slices change, a new state object is created via
983
- * shallow spread. This ensures consistent immutability with {@link forwardEvent}.
984
- *
985
- * **Missing slices**: the snapshot should contain every slice. A slice absent
986
- * from `nextPlain` is **retained at its current value** (not blanked to
987
- * `undefined`, which would make `getState().<slice>` throw on next access).
988
- *
989
- * @param nextPlain - Plain JS object to become the new state.
990
- *
991
- * @internal
992
- */
993
- __applyExternalState(e) {
994
- if (!this.replayEnabled) {
995
- console.warn(
996
- "[yoltra] External state apply (time-travel) is disabled. Enable it with createStore({ devtools: { allowReplay: true } })"
997
- );
998
- return;
999
- }
1000
- const t = this.state, r = e, n = { ...this.state };
1001
- let s = !1;
1002
- Object.keys(this.reducers).forEach((c) => {
1003
- const i = t?.[c], o = r?.[c];
1004
- if (o === void 0) {
1005
- process.env.NODE_ENV !== "production" && console.warn(
1006
- `[yoltra] External state is missing slice "${String(
1007
- c
1008
- )}"; retaining its current value. Time-travel snapshots should contain all slices.`
1009
- );
1010
- return;
1011
- }
1012
- if (i === o) return;
1013
- const f = b(o);
1014
- n[c] = f, s = !0;
1015
- const h = g(i, o).filter(Boolean);
1016
- if (h.length === 0) return;
1017
- const l = /* @__PURE__ */ new Set();
1018
- for (const u of h) for (const p of v.buildAncestorPaths(u)) l.add(p);
1019
- for (const u of l) {
1020
- const p = this.getAtPath(i, u), y = this.getAtPath(f, u);
1021
- this.connectorBus.emit(c, u, { oldValue: p, newValue: y, path: u });
1022
- }
1023
- }), s && (this.state = n), s && this.listeners.forEach((c) => c());
1024
- }
1025
- /**
1026
- * Replays a sequence of events from a snapshot through reducers and event
1027
- * subscribers ONLY. Skips dedup, middleware, and effects.
1028
- *
1029
- * This method is gated by the `devtools.allowReplay` runtime config.
1030
- * If replay is not enabled, this method throws.
1031
- *
1032
- * @param snapshot - The state snapshot to restore before replaying.
1033
- * @param events - Array of events to replay (in order).
1034
- *
1035
- * @internal
1036
- */
1037
- __replayEvents(e, t) {
1038
- if (!this.replayEnabled)
1039
- throw new Error(
1040
- "[yoltra] Event replay is disabled. Enable it with createStore({ devtools: { allowReplay: true } })"
1041
- );
1042
- this.__applyExternalState(e);
1043
- for (const r of t) {
1044
- const n = r, s = this.state;
1045
- this.reducerBus.emit(n.channel, n.type, n.payload);
1046
- for (const [o, f] of this.patternReducers)
1047
- this.matchesWhen(f, n) && this.forwardEvent(o, n);
1048
- const c = this.state, i = s !== c;
1049
- this.notifyEventSubscribers(n, "committed"), i && this.listeners.forEach((o) => o());
1050
- }
1051
- }
1052
- /**
1053
- * Emits a typed event `(channel, type, payload)`.
1054
- * Events are queued and processed **sequentially** (FIFO).
1055
- *
1056
- * **Pipeline per event:** the *reduce phase* (steps 1-4) runs **synchronously**,
1057
- * so `getState()` reflects the change as soon as `emit()` returns; the *effect
1058
- * phase* (step 5) runs afterwards, asynchronously.
1059
- * 1. **Deduplication** (opt-in) - Skip when content-dedup is enabled (`dedupWindowMs > 0`) or a matching `dedupKey` recurs; off by default
1060
- * 2. **Middleware** (sync) - Pre-reducer hooks; may cancel by returning `false`
1061
- * 3. **Reducers** (sync) - state updates + fine-grained path notifications
1062
- * 4. **Subscribers + coarse** (sync) - event subscribers (fire-and-forget) then coarse listeners (only if state changed)
1063
- * 5. **Effects** (async) - side-effects keyed by `(channel, type)`; the returned promise resolves once they complete
1064
- *
1065
- * **Change Detection**: Uses reference equality (`===`) on `this.state` to determine
1066
- * if any slice changed. Works because {@link forwardEvent} creates a new state reference
1067
- * via shallow spread when any slice changes.
1068
- *
1069
- * @typeParam C - Channel key in `EM`.
1070
- * @typeParam T - Type key within channel `C`.
1071
- * @param channel - Channel name.
1072
- * @param type - Event type name.
1073
- * @param payload - Payload typed as `EM[C][T]`.
1074
- * @param opts - Optional per-emit options (e.g. `dedupKey` for identity-based dedup).
1075
- * @returns A promise that resolves once this event's effects have finished.
1076
- * State is already updated synchronously before `emit()` returns.
1077
- *
1078
- * @example Basic usage
1079
- * ```ts
1080
- * await store.emit('ui', 'increment', 1);
1081
- * ```
1082
- *
1083
- * @example With middleware cancellation
1084
- * ```ts
1085
- * store.registerMiddleware((state, event) => {
1086
- * if (event.type === 'dangerous') return false; // cancel
1087
- * return true; // allow
1088
- * });
1089
- *
1090
- * await store.emit('ui', 'dangerous', null); // cancelled, no state change
1091
- * ```
1092
- *
1093
- * @public
1094
- */
1095
- async emit(e, t, r, n) {
1096
- const s = n?.dedupKey, c = this.dedupConfig.windowMs;
1097
- if (c > 0 || s !== void 0) {
1098
- const h = s !== void 0 && c <= 0 ? w : c, l = s !== void 0 ? `${e}::${t}::#${s}` : this.fingerprint(e, t, r);
1099
- if (this.shouldDedupe(l, h))
1100
- return;
1101
- }
1102
- const i = crypto.randomUUID();
1103
- let o;
1104
- const f = new Promise((h) => {
1105
- o = h;
1106
- });
1107
- return this.reduceQueue.push({
1108
- channel: e,
1109
- type: t,
1110
- payload: r,
1111
- id: i,
1112
- resolve: o
1113
- }), this.drainReduce(), f;
1114
- }
1115
- /**
1116
- * Drains the reduce queue **synchronously**. For each event it runs middleware,
1117
- * reducers, event subscribers, and coarse listeners in the same tick, so
1118
- * `getState()` reflects the change the moment {@link emit} returns. Re-entrant
1119
- * emits (from middleware or subscribers) are appended and drained in the same
1120
- * pass — preserving FIFO order without interleaving reducers. Each committed
1121
- * event's effects then run in an independent task (see {@link runEventEffects}).
1122
- *
1123
- * @internal
1124
- */
1125
- drainReduce() {
1126
- if (!this.isReducing) {
1127
- this.isReducing = !0;
1128
- try {
1129
- for (; this.reduceQueue.length > 0; ) {
1130
- const { channel: e, type: t, payload: r, id: n, resolve: s } = this.reduceQueue.shift(), c = { channel: e, type: t, payload: r, id: n }, i = this.instrumentObservers.size > 0, o = i ? this.state : void 0, f = [];
1131
- i && (this.changedPathSink = f);
1132
- const h = i ? S() : 0;
1133
- let l = !1;
1134
- try {
1135
- l = this.applyEventSync(c);
1136
- } catch (u) {
1137
- console.error("Emit reduce error:", u);
1138
- } finally {
1139
- i && (this.changedPathSink = null);
1140
- }
1141
- i && this.emitInstrumentation(
1142
- c,
1143
- l,
1144
- f,
1145
- o,
1146
- S() - h
1147
- ), this.runEventEffects(c, l, s);
1148
- }
1149
- } finally {
1150
- this.isReducing = !1;
1151
- }
1152
- }
1153
- }
1154
- /**
1155
- * Runs the **synchronous** part of the pipeline for a single event: middleware
1156
- * (may veto), key- and pattern-based reducers, committed/uncommitted event
1157
- * subscribers (fire-and-forget), and coarse listeners.
1158
- *
1159
- * @returns `true` if the event was committed (passed middleware), `false` if a
1160
- * middleware vetoed it.
1161
- *
1162
- * @internal
1163
- */
1164
- applyEventSync(e) {
1165
- for (const n of this.middleware) {
1166
- const s = this.getMiddlewareWhen(n);
1167
- if (!this.matchesWhen(s, e)) continue;
1168
- const c = this.getMiddlewareFunction(n);
1169
- let i;
1170
- try {
1171
- i = c(this.state, e, this.emit);
1172
- } catch (o) {
1173
- console.error("Middleware error:", o), i = !1;
1174
- }
1175
- if (!i)
1176
- return this.notifyEventSubscribers(e, "uncommitted"), !1;
1177
- }
1178
- const t = this.state;
1179
- this.reducerBus.emit(e.channel, e.type, e.payload);
1180
- for (const [n, s] of this.patternReducers)
1181
- this.matchesWhen(s, e) && this.forwardEvent(n, e);
1182
- const r = t !== this.state;
1183
- return this.notifyEventSubscribers(e, "committed"), r && this.listeners.forEach((n) => n()), !0;
1184
- }
1185
- /**
1186
- * Runs a single committed event's effects as an **independent async task**,
1187
- * then resolves that event's completion deferred so `await emit(...)` settles
1188
- * once its effects finish. Per-event tasks (rather than one shared serialized
1189
- * loop) let an effect `await` a re-entrant emit without deadlocking.
1190
- *
1191
- * @internal
1192
- */
1193
- async runEventEffects(e, t, r) {
1194
- this.inFlightEffects++;
1195
- try {
1196
- t && await this.notifyEffects(e);
1197
- } catch (n) {
1198
- console.error("Effect error:", n);
1199
- } finally {
1200
- this.inFlightEffects--, r();
1201
- }
1202
- }
1203
- /**
1204
- * Registers an instrumentation observer. See {@link StoreInstance.instrument}.
1205
- *
1206
- * @public
1207
- */
1208
- instrument(e) {
1209
- return this.instrumentObservers.add(e), () => {
1210
- this.instrumentObservers.delete(e);
1211
- };
1212
- }
1213
- /**
1214
- * Builds an {@link InstrumentedEvent} from the reduce result and notifies
1215
- * observers. `changedPaths` are the exact slice-prefixed leaf paths recorded
1216
- * by {@link forwardEvent} during this reduce, so DevTools patches need no
1217
- * re-diff.
1218
- *
1219
- * @internal
1220
- */
1221
- emitInstrumentation(e, t, r, n, s) {
1222
- const c = {}, i = {};
1223
- for (const f of r)
1224
- c[f] = this.getAtPath(n, f), i[f] = this.getAtPath(this.state, f);
1225
- const o = {
1226
- event: {
1227
- id: e.id,
1228
- channel: e.channel,
1229
- type: e.type,
1230
- payload: e.payload
1231
- },
1232
- committed: t,
1233
- changedPaths: r,
1234
- prevValues: c,
1235
- nextValues: i,
1236
- reduceTimeMs: s
1237
- };
1238
- for (const f of [...this.instrumentObservers])
1239
- try {
1240
- f(o);
1241
- } catch (h) {
1242
- console.error("Instrumentation observer error:", h);
1243
- }
1244
- }
1245
- /**
1246
- * Connects a **fine-grained** listener to a dotted path under a slice.
1247
- *
1248
- * @param spec - `{ reducer, property }` where `property` is a dotted path (e.g., `"items.0.title"`).
1249
- * Supports wildcards: `*` (one segment) and `**` (zero or more segments).
1250
- * @param h - Handler receiving a {@link Change} with `{ oldValue, newValue, path }`.
1251
- * @returns Unsubscribe function.
1252
- *
1253
- * @example Exact path
1254
- * ```ts
1255
- * const off = store.connect(
1256
- * { reducer: 'todos', property: 'items.0.title' },
1257
- * (chg) => console.log('title changed:', chg.newValue)
1258
- * );
1259
- * off();
1260
- * ```
1261
- *
1262
- * @example Wildcard pattern
1263
- * ```ts
1264
- * // Listen to any item title change
1265
- * const off = store.connect(
1266
- * { reducer: 'todos', property: 'items.*.title' },
1267
- * (chg) => console.log('some title changed')
1268
- * );
1269
- * ```
1270
- *
1271
- * @public
1272
- */
1273
- connect(e, t) {
1274
- return this.connectorBus.on(e.reducer, e.property, t);
1275
- }
1276
- /**
1277
- * Subscribe to events by channel and type.
1278
- *
1279
- * Event subscriptions are intended for the View layer (e.g., React components)
1280
- * to react to events without affecting the event flow. They are fire-and-forget
1281
- * and cannot cancel event propagation.
1282
- *
1283
- * **Phases:**
1284
- * - `'committed'` (default): Events that passed middleware and reached reducers.
1285
- * Notified after reducers, before effects.
1286
- * - `'uncommitted'`: Events rejected by middleware. Notified immediately after rejection.
1287
- * - `'all'`: Both committed and uncommitted events. Handler receives the phase parameter
1288
- * to distinguish between the two.
1289
- *
1290
- * @typeParam C - Channel key within `EM`.
1291
- * @typeParam T - Event type key within channel `C`.
1292
- * @param channel - Channel to subscribe to.
1293
- * @param type - Event type to subscribe to.
1294
- * @param handler - Handler function `(event, getState, emit, phase)`.
1295
- * @param phase - Event phase to subscribe to (default: `'committed'`).
1296
- * @returns Unsubscribe function.
1297
- *
1298
- * @example Committed events (default)
1299
- * ```ts
1300
- * const off = store.onEvent('ui', 'save', (event, getState, emit, phase) => {
1301
- * console.log('Save committed:', event.payload);
1302
- * });
1303
- * off();
1304
- * ```
1305
- *
1306
- * @example Uncommitted (rejected) events
1307
- * ```ts
1308
- * store.onEvent('ui', 'delete', (event, getState, emit, phase) => {
1309
- * console.log('Delete was rejected by middleware');
1310
- * }, 'uncommitted');
1311
- * ```
1312
- *
1313
- * @example All events
1314
- * ```ts
1315
- * store.onEvent('ui', 'action', (event, getState, emit, phase) => {
1316
- * console.log('Action:', phase); // 'committed' or 'uncommitted'
1317
- * }, 'all');
1318
- * ```
1319
- *
1320
- * @public
1321
- */
1322
- onEvent(e, t, r, n = "committed") {
1323
- const s = `${e}::${String(t)}`, c = n === "committed" ? this.committedEventSubscribers : n === "uncommitted" ? this.uncommittedEventSubscribers : this.allEventSubscribers;
1324
- return c.has(s) || c.set(s, /* @__PURE__ */ new Set()), c.get(s).add(r), () => {
1325
- const i = c.get(s);
1326
- i && (i.delete(r), i.size === 0 && c.delete(s));
1327
- };
1328
- }
1329
- /**
1330
- * Subscribes to **coarse-grained** commits (called once per successful event, only if state changed).
1331
- *
1332
- * **Use Case**: React's `useSyncExternalStore` or similar external store integrations.
1333
- *
1334
- * @param fn - Listener invoked after reducers/effects have run and state has changed.
1335
- * @returns Unsubscribe function.
1336
- *
1337
- * @example
1338
- * ```ts
1339
- * const off = store.subscribe(() => console.log('state committed'));
1340
- * // Later:
1341
- * off();
1342
- * ```
1343
- *
1344
- * @public
1345
- */
1346
- subscribe(e) {
1347
- return this.listeners.add(e), () => this.listeners.delete(e);
1348
- }
1349
- /**
1350
- * Returns the current immutable state snapshot.
1351
- *
1352
- * @returns Deep-readonly state object.
1353
- *
1354
- * @example
1355
- * ```ts
1356
- * const state = store.getState();
1357
- * console.log(state.counter.value);
1358
- * ```
1359
- *
1360
- * @public
1361
- */
1362
- getState() {
1363
- return this.state;
1364
- }
1365
- /**
1366
- * Registers a middleware (runs **before** reducers).
1367
- *
1368
- * @param mw - Middleware `(state, event, emit) => boolean|Promise<boolean>`.
1369
- * Return `false` to cancel event propagation.
1370
- * @returns Unsubscribe function that removes this middleware.
1371
- *
1372
- * @example Logging middleware
1373
- * ```ts
1374
- * const off = store.registerMiddleware(async (state, event) => {
1375
- * console.log('Event:', event.channel, event.type, event.payload);
1376
- * return true; // allow
1377
- * });
1378
- * off();
1379
- * ```
1380
- *
1381
- * @example Cancellation middleware
1382
- * ```ts
1383
- * store.registerMiddleware((state, event) => {
1384
- * if (event.type === 'forbidden') return false; // cancel
1385
- * return true;
1386
- * });
1387
- * ```
1388
- *
1389
- * @public
1390
- */
1391
- registerMiddleware(e) {
1392
- return this.middleware.push(e), () => {
1393
- const t = this.middleware.indexOf(e);
1394
- t !== -1 && this.middleware.splice(t, 1);
1395
- };
1396
- }
1397
- /**
1398
- * Dynamically **adds** a named slice reducer at runtime.
1399
- *
1400
- * @param name - New slice name (must not already exist).
1401
- * @param spec - Reducer spec (state, events, reducer).
1402
- * @returns Disposer function that **removes** the slice (and its state).
1403
- *
1404
- * @example
1405
- * ```ts
1406
- * const dispose = store.registerReducer('filters', {
1407
- * state: { q: '' },
1408
- * events: [['ui', 'setQuery']],
1409
- * reducer(s, evt) {
1410
- * return evt.type === 'setQuery' ? { q: evt.payload } : s;
1411
- * }
1412
- * });
1413
- * // Later:
1414
- * dispose();
1415
- * ```
1416
- *
1417
- * @public
1418
- */
1419
- registerReducer(e, t) {
1420
- if (e in this.reducers) throw new Error(`Reducer ${e} already exists`);
1421
- return this.mountSlice(e, t, {
1422
- preserveState: !1
1423
- }), this.listeners.forEach((r) => r()), () => {
1424
- this.unmountSlice(e, { deleteState: !0 }), this.listeners.forEach((r) => r());
1425
- };
1426
- }
1427
- /**
1428
- * Registers an **effect** (stateless async event consumer) that runs after reducers.
1429
- *
1430
- * Effects are **keyed** by `(channel, type)` for O(1) lookup (no scanning all effects).
1431
- *
1432
- * @param spec - Effect specification with `events` (EventKeys) and `effect` (handler).
1433
- * @returns Unsubscribe function.
1434
- *
1435
- * @example Logging effect
1436
- * ```ts
1437
- * const off = store.registerEffect({
1438
- * events: [['ui', 'increment']],
1439
- * effect: async (evt, getState, emit) => {
1440
- * console.log('increment', evt.payload, getState().counter.value);
1441
- * }
1442
- * });
1443
- * off();
1444
- * ```
1445
- *
1446
- * @example Multi-event effect
1447
- * ```ts
1448
- * store.registerEffect({
1449
- * events: [['ui', 'increment'], ['ui', 'decrement']],
1450
- * effect: async (evt, getState, emit) => {
1451
- * // Runs for both increment and decrement
1452
- * await saveToServer(getState());
1453
- * }
1454
- * });
1455
- * ```
1456
- *
1457
- * @public
1458
- */
1459
- registerEffect(e) {
1460
- const { effect: t, meta: r, when: n } = e, s = [];
1461
- if (r && this.effectMeta.set(t, r), n && ("any" in n && n.any === !0 || "channel" in n || "channels" in n)) {
1462
- const o = { effect: t, when: n };
1463
- return this.patternEffects.add(o), () => {
1464
- this.patternEffects.delete(o);
1465
- };
1466
- }
1467
- const i = this.normalizeEventKeys(e);
1468
- if (i.length === 0 && !n && !e.events) {
1469
- const o = { effect: t, when: { any: !0 } };
1470
- return this.patternEffects.add(o), () => {
1471
- this.patternEffects.delete(o);
1472
- };
1473
- }
1474
- for (const [o, f] of i) {
1475
- const h = `${String(o)}::${String(f)}`;
1476
- this.effects.has(h) || this.effects.set(h, /* @__PURE__ */ new Set()), this.effects.get(h).add(t), s.push(() => {
1477
- const l = this.effects.get(h);
1478
- l && (l.delete(t), l.size === 0 && this.effects.delete(h));
1479
- });
1480
- }
1481
- return () => {
1482
- for (const o of s) o();
1483
- };
1484
- }
1485
- /**
1486
- * Convenience helper to register an **effect** filtered by a single `(channel, type)` pair.
1487
- *
1488
- * @typeParam C - Channel key within `EM`.
1489
- * @typeParam T - Event type key within channel `C`.
1490
- * @param channel - Channel to filter.
1491
- * @param type - Event type to filter.
1492
- * @param handler - Effect handler `(payload, getState, emit, event)`.
1493
- * @returns Unsubscribe/teardown function.
1494
- *
1495
- * @example
1496
- * ```ts
1497
- * const off = store.onEffect('ui', 'increment', async (n, get, emit) => {
1498
- * if (n > 10) await emit('ui', 'increment', -10);
1499
- * });
1500
- * // later
1501
- * off();
1502
- * ```
1503
- *
1504
- * @public
1505
- */
1506
- onEffect(e, t, r) {
1507
- const n = async (s, c, i) => {
1508
- if (s.channel !== e || s.type !== t) return;
1509
- const o = s;
1510
- return r(o.payload, c, i, o);
1511
- };
1512
- return this.registerEffect({
1513
- events: [[e, t]],
1514
- effect: n
1515
- });
1516
- }
1517
- /**
1518
- * Replaces the **entire** middleware pipeline (HMR-friendly).
1519
- *
1520
- * @param next - New middleware array.
1521
- *
1522
- * @example Hot module replacement
1523
- * ```ts
1524
- * if (import.meta.hot) {
1525
- * import.meta.hot.accept('./middleware', (newModule) => {
1526
- * store.replaceMiddleware(newModule.middleware);
1527
- * });
1528
- * }
1529
- * ```
1530
- *
1531
- * @public
1532
- */
1533
- replaceMiddleware(e) {
1534
- this.middleware.length = 0;
1535
- for (const t of e) this.middleware.push(t);
1536
- }
1537
- /**
1538
- * Replaces all registered **effects** (HMR-friendly).
1539
- *
1540
- * @param next - New effects array (as EffectSpecs).
1541
- *
1542
- * @example Hot module replacement
1543
- * ```ts
1544
- * if (import.meta.hot) {
1545
- * import.meta.hot.accept('./effects', (newModule) => {
1546
- * store.replaceEffects(newModule.effects);
1547
- * });
1548
- * }
1549
- * ```
1550
- *
1551
- * @public
1552
- */
1553
- replaceEffects(e) {
1554
- this.effects.clear(), this.patternEffects.clear();
1555
- for (const t of e)
1556
- this.registerEffect(t);
1557
- }
1558
- /**
1559
- * Replaces the entire **reducer set** (HMR-friendly).
1560
- *
1561
- * @param next - Map of slice specs keyed by slice name.
1562
- * @param opts - `{ preserveState?: boolean }` (default `true`).
1563
- *
1564
- * @example Hot module replacement
1565
- * ```ts
1566
- * if (import.meta.hot) {
1567
- * import.meta.hot.accept('./reducers', (newModule) => {
1568
- * store.replaceReducers(newModule.reducers, { preserveState: true });
1569
- * });
1570
- * }
1571
- * ```
1572
- *
1573
- * @public
1574
- */
1575
- replaceReducers(e, t = {}) {
1576
- const r = t.preserveState !== !1, n = new Set(Object.keys(this.reducers)), s = Object.entries(e), c = new Set(s.map(([i]) => i));
1577
- for (const i of n)
1578
- c.has(i) || this.unmountSlice(i, { deleteState: !0 });
1579
- for (const [i, o] of s)
1580
- n.has(i) ? (this.unmountSlice(i, { deleteState: !1 }), this.mountSlice(i, o, { preserveState: r })) : this.mountSlice(i, o, { preserveState: !1 });
1581
- }
1582
- /**
1583
- * Convenience API to replace **any subset** of store parts (HMR patterns).
1584
- *
1585
- * @param partial - Partial replacement set.
1586
- *
1587
- * @example Replace everything
1588
- * ```ts
1589
- * store.hotReplace({
1590
- * reducer: newReducers,
1591
- * middleware: newMiddleware,
1592
- * effects: newEffects,
1593
- * preserveState: true
1594
- * });
1595
- * ```
1596
- *
1597
- * @public
1598
- */
1599
- hotReplace(e) {
1600
- e.middleware && this.replaceMiddleware(e.middleware), e.effects && this.replaceEffects(e.effects), e.reducer && this.replaceReducers(e.reducer, { preserveState: e.preserveState });
1601
- }
1602
- /**
1603
- * Mounts a slice: installs reducer, initializes state (unless preserved),
1604
- * and wires `(channel, type)` listeners on the reducer bus.
1605
- *
1606
- * @param name - Slice name.
1607
- * @param rSpec - Reducer spec (state, events, reducer).
1608
- * @param opts - `{ preserveState: boolean }` whether to keep existing state.
1609
- *
1610
- * @internal
1611
- */
1612
- mountSlice(e, t, r) {
1613
- const n = e, { events: s, reducer: c, state: i, when: o } = t;
1614
- if (this.reducers[e] = new _(c), (!r.preserveState || this.state[n] === void 0) && (this.state[n] = b(structuredClone(i))), o && ("any" in o && o.any === !0 || "channel" in o || "channels" in o)) {
1615
- this.patternReducers.set(e, o), this.sliceUnsubs.set(n, []);
1616
- return;
1617
- }
1618
- const h = this.normalizeEventKeys(t);
1619
- if (h.length === 0 && !o && !s) {
1620
- this.patternReducers.set(e, { any: !0 }), this.sliceUnsubs.set(n, []);
1621
- return;
1622
- }
1623
- const l = [];
1624
- for (const [u, p] of h) {
1625
- const y = this.reducerBus.on(u, p, (m) => {
1626
- const M = { channel: u, type: p, payload: m, id: crypto.randomUUID() };
1627
- this.forwardEvent(e, M);
1628
- });
1629
- l.push(y);
1630
- }
1631
- this.sliceUnsubs.set(n, l);
1632
- }
1633
- /**
1634
- * Unmounts a slice: disposes reducer-bus listeners, removes reducer,
1635
- * and optionally deletes the slice state.
1636
- *
1637
- * @param name - Slice name.
1638
- * @param opts - `{ deleteState: boolean }`.
1639
- *
1640
- * @internal
1641
- */
1642
- unmountSlice(e, t) {
1643
- const r = e;
1644
- this.patternReducers.delete(e);
1645
- const n = this.sliceUnsubs.get(r);
1646
- if (n) {
1647
- for (const s of n)
1648
- try {
1649
- s();
1650
- } catch (c) {
1651
- console.error(`[Store error]: ${c}`);
1652
- }
1653
- this.sliceUnsubs.delete(r);
1654
- }
1655
- delete this.reducers[e], t.deleteState && delete this.state[r];
1656
- }
1657
- /**
1658
- * Normalizes event targeting from `when` or legacy `events` to an array of EventKeys.
1659
- *
1660
- * @param spec - Object with optional `when` and/or `events` properties.
1661
- * @returns Array of `[channel, type]` pairs.
1662
- *
1663
- * @internal
1664
- */
1665
- normalizeEventKeys(e) {
1666
- if (e.when) {
1667
- const t = e.when;
1668
- if ("any" in t && t.any === !0)
1669
- return [];
1670
- if ("keys" in t)
1671
- return t.keys;
1672
- if ("channel" in t)
1673
- return [];
1674
- if ("channels" in t)
1675
- return [];
1676
- }
1677
- return e.events ? e.events : [];
1678
- }
1679
- /**
1680
- * Reads a dotted path from an object (supports numeric array indices via string keys).
1681
- *
1682
- * @param obj - Root object (slice or value).
1683
- * @param path - Dotted path; leading dot is ignored.
1684
- * @returns The value at the path, or `undefined`.
1685
- *
1686
- * @internal
1687
- */
1688
- getAtPath(e, t) {
1689
- if (!t) return e;
1690
- const n = (t[0] === "." ? t.slice(1) : t).split(".");
1691
- let s = e;
1692
- for (const c of n) {
1693
- if (s == null) return;
1694
- s = s[c];
1695
- }
1696
- return s;
1697
- }
1698
- /**
1699
- * Builds ancestor paths for a dotted path.
1700
- *
1701
- * For `"a.b.c"`, returns `["a", "a.b", "a.b.c"]`. Leading dots are trimmed.
1702
- *
1703
- * @param path - Dotted path string.
1704
- * @returns Array of ancestor paths.
1705
- *
1706
- * @example
1707
- * ```ts
1708
- * Store.buildAncestorPaths('x.y.z'); // ['x','x.y','x.y.z']
1709
- * ```
1710
- *
1711
- * @public
1712
- */
1713
- static buildAncestorPaths(e) {
1714
- if (!e) return [];
1715
- const r = (e[0] === "." ? e.slice(1) : e).split("."), n = [];
1716
- for (let s = 0; s < r.length; s++)
1717
- n.push(r.slice(0, s + 1).join("."));
1718
- return n;
1719
- }
1720
- }
1721
- function R(a) {
1722
- return new v({
1723
- name: a.name,
1724
- reducer: a.reducer ?? {},
1725
- middleware: a.middleware ?? [],
1726
- effects: a.effects ?? [],
1727
- dedupWindowMs: a.dedupWindowMs,
1728
- devtools: a.devtools,
1729
- onEffectError: a.onEffectError
1730
- });
1731
- }
1732
- const $ = (a) => (e, t) => t.map((r) => [e, r]), B = () => (a) => a;
1733
- export {
1734
- O as EventBus,
1735
- k as LooseEventBus,
1736
- _ as Reducer,
1737
- v as Store,
1738
- R as createStore,
1739
- g as detectChangedProps,
1740
- B as eventKeys,
1741
- E as freezeState,
1742
- $ as typedEvents
1743
- };
1744
- //# sourceMappingURL=yoltra.esm.js.map