@yoltra/core 0.2.0 → 0.4.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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Saving state, and starting from saved state.
3
+ *
4
+ * @remarks
5
+ * The two halves happen on opposite sides of the store's existence, which is why this is two
6
+ * functions rather than one. {@link hydrate} produces *initial slice state*, so the store is
7
+ * born hydrated; {@link persist} subscribes to a store that already exists.
8
+ *
9
+ * Restoring after construction is the obvious alternative and the wrong one. It means applying
10
+ * a whole-state snapshot to a live store, which emits a change across every path: a visible
11
+ * flash on boot, a burst of instrumentation entries describing changes nobody made, and
12
+ * effects observing a transition that never happened.
13
+ *
14
+ * @module @yoltra/core
15
+ */
16
+ /** Where persisted state lives. Bring your own; core imports no platform global. */
17
+ export interface PersistenceAdapter {
18
+ read(key: string): string | null | Promise<string | null>;
19
+ write(key: string, value: string): void | Promise<void>;
20
+ remove(key: string): void | Promise<void>;
21
+ }
22
+ /** Where a failure happened, so a handler can tell a bad write from a bad payload. */
23
+ export type PersistencePhase = "read" | "write" | "decode" | "migrate";
24
+ /** Shared configuration. */
25
+ export interface PersistOptions {
26
+ /** Storage key. */
27
+ readonly key: string;
28
+ readonly adapter: PersistenceAdapter;
29
+ /**
30
+ * Schema version of what is written.
31
+ *
32
+ * @remarks
33
+ * Compared on read. A mismatch is handed to {@link PersistOptions.migrate}, and without one
34
+ * the stored value is discarded rather than trusted — reducers change, and a snapshot
35
+ * written against an older shape is not merely stale, it may not be valid state at all.
36
+ */
37
+ readonly version: number;
38
+ /** Slices to persist. Every slice by default. */
39
+ readonly slices?: readonly string[];
40
+ /** Coalescing window for writes, in milliseconds. Defaults to 250. */
41
+ readonly throttleMs?: number;
42
+ /**
43
+ * Upgrades a payload written by an older version.
44
+ *
45
+ * @returns The slices to restore, or `null` to start fresh.
46
+ */
47
+ readonly migrate?: (persisted: unknown, from: number) => Record<string, unknown> | null;
48
+ /**
49
+ * Called on any failure.
50
+ *
51
+ * @remarks
52
+ * Persistence never throws into the application it is persisting. A store that will not
53
+ * start because storage holds stale JSON is worse than one that starts fresh, and a full
54
+ * disk should not take down a page.
55
+ */
56
+ readonly onError?: (error: unknown, phase: PersistencePhase) => void;
57
+ }
58
+ /** What {@link hydrate} recovered. */
59
+ export interface Hydration {
60
+ /** Slice states to start from. Empty when there was nothing usable to restore. */
61
+ readonly slices: Readonly<Record<string, unknown>>;
62
+ /** `true` when a payload was found, decoded and accepted. */
63
+ readonly restored: boolean;
64
+ }
65
+ /**
66
+ * Reads persisted state, ready to seed a store.
67
+ *
68
+ * @remarks
69
+ * Every read-side failure — missing, unparseable, wrong version with no migration, a
70
+ * migration that declines — resolves to "nothing to restore" and reports through
71
+ * {@link PersistOptions.onError}. Nothing throws.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const hydration = await hydrate({ key: 'app', adapter, version: 3 });
76
+ * const store = createStore({
77
+ * name: 'App',
78
+ * reducer: withHydration({ todos: todosSpec }, hydration),
79
+ * });
80
+ * ```
81
+ *
82
+ * @public
83
+ */
84
+ export declare function hydrate(options: PersistOptions & {
85
+ readonly source?: string;
86
+ }): Promise<Hydration>;
87
+ /** A reducer spec, as far as hydration cares: something carrying an initial `state`. */
88
+ interface HasState {
89
+ state: unknown;
90
+ }
91
+ /**
92
+ * Replaces each reducer's initial state with what was restored for it.
93
+ *
94
+ * @remarks
95
+ * Slices absent from the payload keep their declared defaults, so adding a reducer does not
96
+ * invalidate everything written before it existed.
97
+ *
98
+ * @public
99
+ */
100
+ export declare function withHydration<R extends Record<string, HasState>>(reducers: R, hydration: Hydration): R;
101
+ /** The store surface persistence needs, which is two methods wide. */
102
+ export interface PersistableStore {
103
+ getState(): unknown;
104
+ instrument(observer: (info: {
105
+ changedPaths?: readonly string[];
106
+ }) => void): () => void;
107
+ }
108
+ /**
109
+ * Writes state as it changes.
110
+ *
111
+ * @returns A function that stops persisting and flushes anything pending.
112
+ *
113
+ * @remarks
114
+ * Driven by `instrument` rather than the coarse subscription, so a change confined to a slice
115
+ * that is not persisted costs nothing at all. Writes are coalesced on the trailing edge.
116
+ *
117
+ * @public
118
+ */
119
+ export declare function persist(store: PersistableStore, options: PersistOptions): () => void;
120
+ /**
121
+ * Serializes a store for handoff, for example from a server render to the client.
122
+ *
123
+ * @public
124
+ */
125
+ export declare function dehydrate(store: Pick<PersistableStore, "getState">, options: Pick<PersistOptions, "version" | "slices">): string;
126
+ export {};
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Lossless encoding of store state for the wire.
3
+ *
4
+ * @remarks
5
+ * The wire is JSON, and `JSON.stringify` is not a safe way to put arbitrary state on it. It does
6
+ * not fail on the values it cannot represent — it quietly destroys them. A `Map` becomes `{}`, a
7
+ * `Set` becomes `{}`, a `Date` becomes a string, `undefined` disappears from objects entirely,
8
+ * and a `BigInt` or a cycle throws from inside a handler nobody awaits.
9
+ *
10
+ * Silent destruction is the dangerous half. The panel showed `{}` where a `Map` lived, which is
11
+ * merely wrong; but time-travel then sent that `{}` back and applied it to the running store,
12
+ * replacing a live `Map` with an empty object in the user's own application. A debugging tool
13
+ * corrupting the program it is inspecting is the worst failure available to it.
14
+ *
15
+ * Values are therefore tagged rather than coerced. Anything JSON can carry travels unchanged;
16
+ * anything it cannot is wrapped in a marker object that {@link decodeState} reverses exactly.
17
+ *
18
+ * @module
19
+ */
20
+ /** Options for {@link encodeState}. */
21
+ export interface EncodeOptions {
22
+ /**
23
+ * Redacts a value before it leaves the process.
24
+ *
25
+ * @remarks
26
+ * State frequently holds tokens, session material and personal data, and devtools traffic
27
+ * crosses a socket to another process. Return the replacement value, or the value itself to
28
+ * keep it. Applied before encoding, so a redacted value is encoded like any other.
29
+ */
30
+ readonly sanitize?: (path: string, value: unknown) => unknown;
31
+ /**
32
+ * Maximum number of nodes to encode. Beyond it, subtrees are replaced by a truncation marker.
33
+ *
34
+ * @remarks
35
+ * A snapshot larger than the hub's frame cap is rejected outright, which reads to the user as
36
+ * a panel that hangs. Truncating visibly is a better failure: the panel renders, and says
37
+ * where it stopped. Defaults to 100000.
38
+ */
39
+ readonly maxNodes?: number;
40
+ }
41
+ /** Reports what an encode had to compromise. Empty when nothing was lost. */
42
+ export interface EncodeReport {
43
+ /** Node budget was exhausted and some subtrees were replaced by markers. */
44
+ readonly truncated: boolean;
45
+ /** Values no JSON representation exists for, by path — functions, symbols, DOM nodes. */
46
+ readonly unsupported: readonly string[];
47
+ }
48
+ /** Result of {@link encodeState}. */
49
+ export interface EncodeResult {
50
+ readonly value: unknown;
51
+ readonly report: EncodeReport;
52
+ }
53
+ /**
54
+ * Encodes a value into something `JSON.stringify` can carry losslessly.
55
+ *
56
+ * @param input - Any value, including one holding `Map`, `Set`, `Date`, `BigInt` or cycles.
57
+ * @param options - Redaction and size limits.
58
+ * @returns The encoded value plus a report of anything that could not be represented.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * const { value } = encodeState({ index: new Map([['a', 1]]) });
63
+ * JSON.stringify(value); // safe, and decodeState restores the Map
64
+ * ```
65
+ *
66
+ * @public
67
+ */
68
+ export declare function encodeState(input: unknown, options?: EncodeOptions): EncodeResult;
69
+ /**
70
+ * Reverses {@link encodeState}.
71
+ *
72
+ * @param input - A value produced by `encodeState` (typically after a JSON round trip).
73
+ * @returns The original structure, with `Map`, `Set`, `Date` and friends restored.
74
+ *
75
+ * @remarks
76
+ * Unsupported markers decode to `undefined`: a function cannot be reconstructed, and inventing a
77
+ * placeholder would be worse than an absent value. Cycles are restored by resolving references
78
+ * after the tree is built, so a decoded structure is cyclic exactly where the original was.
79
+ *
80
+ * @public
81
+ */
82
+ export declare function decodeState(input: unknown): unknown;
83
+ /** Outcome of {@link encodeStateBounded}. */
84
+ export interface BoundedEncodeResult {
85
+ /** The encoded value, small enough to send. */
86
+ readonly value: unknown;
87
+ /** `true` when the state did not fit and parts were replaced by markers. */
88
+ readonly truncated: boolean;
89
+ /** Explains what was dropped, for display beside a partial tree. */
90
+ readonly note?: string;
91
+ }
92
+ /**
93
+ * Encodes a value, shrinking it until its serialized form fits within `maxBytes`.
94
+ *
95
+ * @param input - Any value.
96
+ * @param maxBytes - Byte budget for the serialized form.
97
+ * @param options - Passed through to {@link encodeState}.
98
+ *
99
+ * @returns The encoded value and whether anything had to be dropped.
100
+ *
101
+ * @remarks
102
+ * A frame larger than the hub's cap is not merely slow — it is rejected, and the connection with
103
+ * it, so the client reconnects, asks again, is refused again, and the panel sits waiting through
104
+ * a loop with nothing on screen to explain it. The size therefore has to be bounded before the
105
+ * frame is sent rather than discovered afterwards.
106
+ *
107
+ * Node count is a poor proxy for bytes: a hundred nodes holding base64 blobs outweigh a hundred
108
+ * thousand holding integers. So this measures the encoded output and, when it is too large,
109
+ * scales the node budget by how far over it went and measures again. Scaling by the overshoot
110
+ * rather than halving matters: from a default of a hundred thousand nodes, repeated halving
111
+ * needs a dozen rounds to reach the hundreds, so a state that could have been shown in part
112
+ * would have been abandoned instead.
113
+ *
114
+ * Truncation is reported rather than performed silently. A partial tree presented as the state is
115
+ * worse than no tree at all: a debugger that quietly lies about state is not a debugger.
116
+ *
117
+ * @public
118
+ */
119
+ export declare function encodeStateBounded(input: unknown, maxBytes: number, options?: EncodeOptions): BoundedEncodeResult;
@@ -1,4 +1,4 @@
1
- import { Event, EventMapBase, EventKey, EventUnion, Change, DeepReadonly, EffectSpec, MiddlewareFunction, ReducersMapAny, ReducerSpec, StateFromReducers, StoreInstance, StoreSpec, Unsubscribe, EMFromReducersStrict, Emit, EmitOptions, InstrumentationObserver, EventPhase, NarrowedEventHandler, When } from '../types';
1
+ import { Event, EventMapBase, EventKey, EventUnion, Change, DeepReadonly, EffectSpec, EventMeta, MiddlewareInput, ReducersMapAny, ReducerSpec, StateFromReducers, StoreInstance, StoreSpec, Unsubscribe, EMFromReducersStrict, Emit, EmitOptions, InstrumentationObserver, EventPhase, NarrowedEventHandler, When } from '../types';
2
2
  export declare class Store<EM extends EventMapBase, R extends string, S extends Record<R, any>> implements StoreInstance<R, S, EM> {
3
3
  /**
4
4
  * Store name (used by DevTools & diagnostics).
@@ -47,7 +47,7 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
47
47
  private readonly listeners;
48
48
  /**
49
49
  * Registered effect handlers keyed by `"channel::type"` for O(1) lookup.
50
- * Used for effects with explicit `keys` or legacy `events` targeting.
50
+ * Used for effects with explicit `keys` targeting.
51
51
  *
52
52
  * @internal
53
53
  */
@@ -102,12 +102,33 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
102
102
  * @internal
103
103
  */
104
104
  private readonly replayEnabled;
105
+ /**
106
+ * Produces the `id` for each emitted event. Defaults to `crypto.randomUUID()`; overridable
107
+ * via {@link StoreSpec.idFactory} for runtimes lacking it or for deterministic tests.
108
+ *
109
+ * @internal
110
+ */
111
+ private readonly idFactory;
105
112
  /**
106
113
  * Optional hook invoked when an effect throws/rejects. See
107
114
  * {@link StoreSpec.onEffectError}. `await emit()` never rejects on effect
108
115
  * failure — this is how callers observe effect errors.
109
116
  */
110
117
  private readonly onEffectError?;
118
+ /**
119
+ * Optional hook invoked when a reducer throws. See {@link StoreSpec.onReducerError}. The
120
+ * failing slice is isolated rather than the event being rolled back, so this is the only
121
+ * signal that a reducer misbehaved.
122
+ */
123
+ private readonly onReducerError?;
124
+ /**
125
+ * `slice:channel:type` combinations already warned about for payload aliasing.
126
+ *
127
+ * @remarks
128
+ * Development-only diagnostics have to stay quiet enough to be read. One warning names the
129
+ * pattern; repeating it once per event would bury it.
130
+ */
131
+ private readonly warnedPayloadAliases;
111
132
  /**
112
133
  * Pending events awaiting the **synchronous** reduce phase (middleware +
113
134
  * reducers + subscribers + coarse listeners). Drained by {@link drainReduce}.
@@ -327,6 +348,30 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
327
348
  *
328
349
  * @internal
329
350
  */
351
+ /**
352
+ * Reduces one slice and contains any error it raises.
353
+ *
354
+ * @returns `true` when the slice changed.
355
+ *
356
+ * @remarks
357
+ * The single funnel both dispatch paths go through, which is the point. Keyed reducers run
358
+ * through `reducerBus`, whose handler loop caught and logged; pattern reducers were called
359
+ * straight from the drain, so their errors escaped to the caller instead. The same bug in the
360
+ * same reducer therefore produced two different outcomes depending on how the slice happened
361
+ * to be targeted — a keyed reducer's throw let the event commit and its effects run, while a
362
+ * pattern reducer's throw aborted the commit and notified nobody, not even the uncommitted
363
+ * subscribers a veto would have reached.
364
+ *
365
+ * The semantics are now the same either way: **the failing slice is isolated.** Its state is
366
+ * unchanged, every other slice still reduces, and the event still commits if anything else
367
+ * changed. Rolling the whole event back would be tidier in principle, but fine-grained
368
+ * subscribers are notified inside `forwardEvent` as each slice commits, so an event that
369
+ * reverted afterwards would have already told components about a value that no longer exists.
370
+ * Isolation keeps every notification truthful.
371
+ *
372
+ * @internal
373
+ */
374
+ private forwardEventGuarded;
330
375
  private forwardEvent;
331
376
  /**
332
377
  * Returns a structured introspection snapshot for DevTools UIs.
@@ -400,6 +445,7 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
400
445
  type: string;
401
446
  payload: any;
402
447
  id: string;
448
+ meta?: EventMeta;
403
449
  }>): void;
404
450
  /**
405
451
  * Emits a typed event `(channel, type, payload)`.
@@ -605,13 +651,21 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
605
651
  /**
606
652
  * Registers a middleware (runs **before** reducers).
607
653
  *
608
- * @param mw - Middleware `(state, event, emit) => boolean|Promise<boolean>`.
609
- * Return `false` to cancel event propagation.
654
+ * @param mw - Middleware `(state, event, emit) => boolean`. Return `false` to cancel event
655
+ * propagation.
610
656
  * @returns Unsubscribe function that removes this middleware.
611
657
  *
658
+ * @remarks
659
+ * **Synchronous, and that is the contract.** The reduce phase completes before `emit()`
660
+ * returns, so the commit decision has to be available in the same tick. An `async` middleware
661
+ * returns a Promise, every Promise is truthy, and the veto would therefore never fire — the
662
+ * event would commit while the middleware was still deciding. The type rejects it; this note
663
+ * exists because the examples here used to teach it. Do authorization and validation here, and
664
+ * anything that needs to await in an effect.
665
+ *
612
666
  * @example Logging middleware
613
667
  * ```ts
614
- * const off = store.registerMiddleware(async (state, event) => {
668
+ * const off = store.registerMiddleware((state, event) => {
615
669
  * console.log('Event:', event.channel, event.type, event.payload);
616
670
  * return true; // allow
617
671
  * });
@@ -628,12 +682,12 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
628
682
  *
629
683
  * @public
630
684
  */
631
- registerMiddleware(mw: MiddlewareFunction<DeepReadonly<S>, EM>): Unsubscribe;
685
+ registerMiddleware(mw: MiddlewareInput<DeepReadonly<S>, EM>): Unsubscribe;
632
686
  /**
633
687
  * Dynamically **adds** a named slice reducer at runtime.
634
688
  *
635
689
  * @param name - New slice name (must not already exist).
636
- * @param spec - Reducer spec (state, events, reducer).
690
+ * @param spec - Reducer spec (state, when, reducer).
637
691
  * @returns Disposer function that **removes** the slice (and its state).
638
692
  *
639
693
  * @example
@@ -657,7 +711,7 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
657
711
  *
658
712
  * Effects are **keyed** by `(channel, type)` for O(1) lookup (no scanning all effects).
659
713
  *
660
- * @param spec - Effect specification with `events` (EventKeys) and `effect` (handler).
714
+ * @param spec - Effect specification with `when` targeting and `effect` (handler).
661
715
  * @returns Unsubscribe function.
662
716
  *
663
717
  * @example Logging effect
@@ -723,7 +777,7 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
723
777
  *
724
778
  * @public
725
779
  */
726
- replaceMiddleware(next: MiddlewareFunction<DeepReadonly<S>, EM>[]): void;
780
+ replaceMiddleware(next: MiddlewareInput<DeepReadonly<S>, EM>[]): void;
727
781
  /**
728
782
  * Replaces all registered **effects** (HMR-friendly).
729
783
  *
@@ -780,7 +834,7 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
780
834
  */
781
835
  hotReplace(partial: {
782
836
  reducer?: Record<R, ReducerSpec<S[R], EM>>;
783
- middleware?: MiddlewareFunction<DeepReadonly<S>, EM>[];
837
+ middleware?: MiddlewareInput<DeepReadonly<S>, EM>[];
784
838
  effects?: Array<EffectSpec<DeepReadonly<S>, EM>>;
785
839
  preserveState?: boolean;
786
840
  }): void;
@@ -789,7 +843,7 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
789
843
  * and wires `(channel, type)` listeners on the reducer bus.
790
844
  *
791
845
  * @param name - Slice name.
792
- * @param rSpec - Reducer spec (state, events, reducer).
846
+ * @param rSpec - Reducer spec (state, when, reducer).
793
847
  * @param opts - `{ preserveState: boolean }` whether to keep existing state.
794
848
  *
795
849
  * @internal
@@ -806,9 +860,9 @@ export declare class Store<EM extends EventMapBase, R extends string, S extends
806
860
  */
807
861
  private unmountSlice;
808
862
  /**
809
- * Normalizes event targeting from `when` or legacy `events` to an array of EventKeys.
863
+ * Normalizes event targeting from `when` to an array of EventKeys.
810
864
  *
811
- * @param spec - Object with optional `when` and/or `events` properties.
865
+ * @param spec - Object with an optional `when` matcher.
812
866
  * @returns Array of `[channel, type]` pairs.
813
867
  *
814
868
  * @internal
@@ -887,13 +941,15 @@ export declare function createStore<S extends Record<string, any>, EM extends Ev
887
941
  reducer?: {
888
942
  [K in keyof S]?: ReducerSpec<S[K], EM>;
889
943
  };
890
- middleware?: MiddlewareFunction<DeepReadonly<S>, EM>[];
944
+ middleware?: MiddlewareInput<DeepReadonly<S>, EM>[];
891
945
  effects?: Array<EffectSpec<DeepReadonly<S>, EM>>;
892
946
  dedupWindowMs?: number;
947
+ idFactory?: () => string;
893
948
  devtools?: {
894
949
  allowReplay?: boolean;
895
950
  };
896
951
  onEffectError?: (error: unknown, event: EventUnion<EM>) => void;
952
+ onReducerError?: (error: unknown, event: EventUnion<EM>, slice: string) => void;
897
953
  }): StoreInstance<keyof S & string, S, EM>;
898
954
  /**
899
955
  * Creates a store with types inferred from the reducers map.
@@ -926,13 +982,15 @@ export declare function createStore<S extends Record<string, any>, EM extends Ev
926
982
  export declare function createStore<RM extends ReducersMapAny>(cfg: {
927
983
  name: string;
928
984
  reducer: RM;
929
- middleware?: MiddlewareFunction<DeepReadonly<StateFromReducers<RM>>, EMFromReducersStrict<RM>>[];
985
+ middleware?: MiddlewareInput<DeepReadonly<StateFromReducers<RM>>, EMFromReducersStrict<RM>>[];
930
986
  effects?: Array<EffectSpec<DeepReadonly<StateFromReducers<RM>>, EMFromReducersStrict<RM>>>;
931
987
  dedupWindowMs?: number;
988
+ idFactory?: () => string;
932
989
  devtools?: {
933
990
  allowReplay?: boolean;
934
991
  };
935
992
  onEffectError?: (error: unknown, event: EventUnion<EMFromReducersStrict<RM>>) => void;
993
+ onReducerError?: (error: unknown, event: EventUnion<EMFromReducersStrict<RM>>, slice: string) => void;
936
994
  }): StoreInstance<keyof RM & string, StateFromReducers<RM>, EMFromReducersStrict<RM>>;
937
995
  /**
938
996
  * Utility to define **typed** `(channel, events[])` definitions for reducer specs.