preact-sigma 1.0.0 → 2.0.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.
Files changed (5) hide show
  1. package/README.md +113 -467
  2. package/dist/index.d.mts +207 -193
  3. package/dist/index.mjs +593 -265
  4. package/llms.txt +354 -238
  5. package/package.json +1 -1
package/dist/index.d.mts CHANGED
@@ -1,215 +1,229 @@
1
- import { ReadonlySignal, Signal, batch, computed, untracked } from "@preact/signals";
2
- import { Immutable, Producer } from "immer";
1
+ import { ReadonlySignal, action, batch, computed, effect, untracked } from "@preact/signals";
2
+ import { Patch, freeze, immerable } from "immer";
3
3
 
4
- //#region src/internal.d.ts
5
- type Cleanup = () => void;
6
- type Disposable = {
7
- [Symbol.dispose](): void;
8
- };
9
- type OwnedResource = Cleanup | Disposable;
10
- type OwnedResources = OwnedResource | readonly OwnedResource[];
11
- declare class AnyStateHandle<TState = any, TEvents extends EventsDefinition = any> {
12
- private readonly state;
13
- /**
14
- * Emit a custom event with zero or one argument.
15
- */
16
- readonly emit: [TEvents] extends [{}] ? <TEvent extends string & keyof TEvents>(name: TEvent, ...args: TEvents[TEvent]) => void : never;
17
- /**
18
- * Attach cleanup functions or disposables to the managed state instance.
19
- */
20
- readonly own: (resources: OwnedResources) => void;
21
- constructor(state: Signal<Immutable<TState>>,
22
- /**
23
- * Emit a custom event with zero or one argument.
24
- */
25
-
26
- emit: [TEvents] extends [{}] ? <TEvent extends string & keyof TEvents>(name: TEvent, ...args: TEvents[TEvent]) => void : never,
27
- /**
28
- * Attach cleanup functions or disposables to the managed state instance.
29
- */
30
-
31
- own: (resources: OwnedResources) => void);
32
- /** Read the current immutable base state. This read is tracked. */
33
- get(): Immutable<TState>;
34
- /** Read the current immutable base state snapshot without tracking. */
35
- peek(): Immutable<TState>;
36
- /** Replace the base state, or update it with an Immer producer. */
37
- set(value: TState | Producer<TState>): void;
38
- }
39
- /** Check whether a value is a managed-state instance. */
40
- declare function isManagedState(value: unknown): value is AnyManagedState;
41
- //#endregion
42
- //#region src/framework.d.ts
43
- type EventsDefinition = Record<string, [any?]>;
44
- type FilterProperties$1<T extends object, U> = {} & { [P in { [K in keyof T]: [T[K]] extends [never] ? never : T[K] extends U ? K : never }[keyof T]]: T[P] };
45
- type InferActions$1<TProps extends object> = {} & FilterProperties$1<TProps, (...args: any[]) => any>;
46
- type InferManagedStates$1<TProps extends object> = {} & FilterProperties$1<TProps, AnyManagedState>;
47
- type InferPublicProps$1<TProps extends object> = InferActions$1<TProps> & InferManagedStates$1<TProps>;
48
- type OmitManagedStates<TState> = TState extends object ? Omit<TState, keyof InferManagedStates$1<TState>> : TState;
49
- type InferState$1<TProps extends object> = {} & Immutable<{ [K in keyof FilterProperties$1<TProps, ReadonlySignal | StateHandle<any, any> | Lens>]: TProps[K] extends ReadonlySignal<infer T> | StateHandle<infer T> | Lens<infer T> ? T : never }> & Readonly<InferManagedStates$1<TProps>>;
50
- type AnyManagedState<TState = any, TEvents extends EventsDefinition = any> = {
51
- /** Get the underlying signal for an exposed signal-backed public property. */get<K extends keyof OmitManagedStates<TState>>(key: K): ReadonlySignal<OmitManagedStates<TState>[K]>;
52
- get(): ReadonlySignal<TState>; /** Read the current immutable public state snapshot without tracking. */
53
- peek<K extends keyof OmitManagedStates<TState>>(key: K): OmitManagedStates<TState>[K];
54
- peek(): TState;
55
- /**
56
- * Subscribe to the current and future immutable values of one signal-backed
57
- * public property. Returns a function to unsubscribe.
58
- */
59
- subscribe<K extends keyof OmitManagedStates<TState>>(key: K, listener: (value: OmitManagedStates<TState>[K]) => void): () => void; /** Subscribe to the current and future immutable public state snapshots. */
60
- subscribe(listener: (value: TState) => void): () => void;
61
- /**
62
- * Subscribe to a custom event emitted by this managed state.
63
- *
64
- * Your listener receives the emitted argument directly, or no argument at all.
65
- */
66
- on<TEvent extends string & keyof TEvents>(name: TEvent, listener: (...args: TEvents[TEvent]) => void): () => void; /** Dispose this managed state instance and its owned resources. */
67
- dispose(): void;
68
- [Symbol.dispose](): void;
69
- };
4
+ //#region src/immer.d.ts
5
+ type PrimitiveType = number | string | boolean;
6
+ /** Object types that should never be mapped */
7
+ type AtomicObject = Function | Promise<any> | Date | RegExp | EventTarget | AnySigmaState;
70
8
  /**
71
- * Public instance shape produced by `defineManagedState()` and `useManagedState()`.
72
- *
73
- * Returned signals and top-level lenses are exposed as tracked getter
74
- * properties. Returning the `StateHandle` itself exposes the base state
75
- * directly as a reactive immutable property.
9
+ * If the lib "ES2015.Collection" is not included in tsconfig.json,
10
+ * types like ReadonlyArray, WeakMap etc. fall back to `any` (specified nowhere)
11
+ * or `{}` (from the node types), in both cases entering an infinite recursion in
12
+ * pattern matching type mappings
13
+ * This type can be used to cast these types to `void` in these cases.
76
14
  */
77
- type ManagedState<TState, TEvents extends EventsDefinition = EventsDefinition, TProps extends object = Record<string, unknown>> = AnyManagedState<TState, TEvents> & Immutable<TState> & TProps;
15
+ type IfAvailable<T, Fallback = void> = true | false extends (T extends never ? true : false) ? Fallback : keyof T extends never ? Fallback : T;
78
16
  /**
79
- * Mark a constructor-returned method as a tracked query.
80
- *
81
- * Query methods wrap their body in `computed()`, so reads inside the method
82
- * participate in signal tracking even after the method is exposed publicly.
83
- * Query functions read from closed-over handles or signals and do not use an
84
- * instance receiver. Tagged query methods also skip the default `action()`
85
- * wrapping step.
17
+ * These should also never be mapped but must be tested after regular Map and
18
+ * Set
86
19
  */
87
- declare function query<TFunction extends (this: void, ...args: any[]) => any>(fn: TFunction): TFunction;
20
+ type WeakReferences = IfAvailable<WeakMap<any, any>> | IfAvailable<WeakSet<any>>;
21
+ type WritableDraft<T> = T extends any[] ? number extends T["length"] ? Draft<T[number]>[] : WritableNonArrayDraft<T> : WritableNonArrayDraft<T>;
22
+ type WritableNonArrayDraft<T> = { -readonly [K in keyof T]: T[K] extends infer V ? (V extends object ? Draft<V> : V) : never };
88
23
  /**
89
- * Constructor-local access to one top-level property of an object-shaped base
90
- * state.
24
+ * Convert a readonly type into a mutable type, if possible.
91
25
  *
92
- * Lenses only exist on `StateHandle`, and `get()` reads are tracked in the
93
- * same way as `StateHandle.get()`. `set()` accepts either a replacement value
94
- * or an Immer producer for that property value.
26
+ * Use this instead of `immer.Draft`
95
27
  */
96
- type Lens<TState = any> = {
97
- /** Read the current immutable property value. This read is tracked. */get: () => Immutable<TState>;
98
- /**
99
- * Replace the property value, or update it with an Immer producer for that
100
- * property value.
101
- */
102
- set: (value: TState | Producer<TState>) => void;
103
- };
28
+ type Draft<T> = T extends PrimitiveType ? T : T extends AtomicObject ? T : T extends ReadonlyMap<infer K, infer V> ? Map<Draft<K>, Draft<V>> : T extends ReadonlySet<infer V> ? Set<Draft<V>> : T extends WeakReferences ? T : T extends object ? WritableDraft<T> : T;
104
29
  /**
105
- * Constructor-local access to the base state.
30
+ * Convert a mutable type into a readonly type.
106
31
  *
107
- * `TState` may be any non-function value, including primitives.
108
- *
109
- * Return this handle from the constructor when you want to expose the base
110
- * state directly as a reactive immutable property on the managed state.
111
- *
112
- * When the base state is object-shaped, the handle also exposes a shallow
113
- * `Lens` for each top-level property key. Spreading an object-shaped handle
114
- * into the returned constructor object exposes those top-level lenses as
115
- * tracked public properties.
116
- *
117
- * For ordinary derived values, prefer external functions like
118
- * `getVisibleTodos(state)` so unused helpers can be tree-shaken. Reach for
119
- * `computed(() => derive(handle.get()))` only when you need memoized reactive
120
- * reads as a performance optimization.
32
+ * Use this instead of `immer.Immutable`
121
33
  */
122
- type StateHandle<TState, TEvents extends EventsDefinition = never> = AnyStateHandle<TState, TEvents> & (TState extends object ? TState extends ((...args: any[]) => any) | readonly any[] | ReadonlyMap<any, any> | ReadonlySet<any> ? {} : { readonly [K in keyof TState]: Lens<TState[K]> } : {});
123
- /**
124
- * Pure constructor function for a managed state definition.
125
- *
126
- * The first parameter should be explicitly typed as `StateHandle<...>`. The
127
- * library infers the internal state and event types from that parameter type.
128
- *
129
- * Return only methods, signals, top-level `Lens` values from the provided
130
- * `StateHandle`, the provided `StateHandle`, or a managed state instance.
131
- * Returned signals and lenses become tracked getter properties, returning the
132
- * handle exposes the base state directly as a reactive immutable property, and
133
- * managed state instances are passed through unchanged.
134
- */
135
- type StateConstructor<TState, TEvents extends EventsDefinition, TParams extends any[], TProps extends object = {}> = (handle: StateHandle<TState, TEvents>, ...params: TParams) => TProps & {
136
- [key: string]: ((...args: any[]) => any) | AnyManagedState | Lens | ReadonlySignal | StateHandle<any, any>;
34
+ type Immutable<T> = T extends PrimitiveType ? T : T extends AtomicObject ? T : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Immutable<K>, Immutable<V>> : T extends ReadonlySet<infer V> ? ReadonlySet<Immutable<V>> : T extends WeakReferences ? T : T extends object ? { readonly [K in keyof T]: Immutable<T[K]> } : T;
35
+ //#endregion
36
+ //#region src/internal/symbols.d.ts
37
+ declare const sigmaStateBrand: unique symbol;
38
+ declare const sigmaEventsBrand: unique symbol;
39
+ //#endregion
40
+ //#region src/internal/types.d.ts
41
+ type AnyFunction = (...args: any[]) => any;
42
+ type Cleanup = () => void;
43
+ type DefaultStateInitializer<TValue> = (this: void) => TValue;
44
+ type DefaultStateValue<TValue> = TValue | DefaultStateInitializer<TValue>;
45
+ type Disposable = {
46
+ [Symbol.dispose](): void;
137
47
  };
138
- /**
139
- * Define a managed state class with a private mutable implementation and an
140
- * immutable public surface.
141
- *
142
- * `TState` may be any non-function value, including primitives.
143
- *
144
- * The constructor function's explicitly typed `StateHandle` parameter is what
145
- * the library uses to infer the internal state and event types.
146
- *
147
- * Methods are automatically wrapped with `action()` from `@preact/signals`, so
148
- * they are untracked and batched unless you opt into tracked reads with
149
- * `query()`.
150
- *
151
- * The state constructor must return an object with properties that are either:
152
- * - A function (to expose methods)
153
- * - A signal (to expose derived state)
154
- * - A top-level lens from the state handle (to expose one reactive property)
155
- * - The state handle (to expose the reactive immutable base state directly)
156
- * - A managed state instance (to compose another managed state as a property)
157
- *
158
- * Returned signals and top-level lenses are turned into getter properties, so
159
- * reads are tracked by the `@preact/signals` runtime. When the base state is
160
- * object-shaped, spreading the `StateHandle` into the returned object exposes
161
- * its current top-level lenses at once.
162
- *
163
- * Events can carry at most one argument.
164
- *
165
- * The state constructor should be side-effect free.
166
- */
167
- declare function defineManagedState<TState, TEvents extends EventsDefinition, TParams extends any[], TProps extends object = {}, TInitialState extends TState = TState>(constructor: StateConstructor<TState, TEvents, TParams, TProps>, initialState: TInitialState): new (...params: TParams) => ManagedState<InferState$1<TProps>, TEvents, InferPublicProps$1<TProps>>;
48
+ /** The event map shape used by sigma types. */
49
+ type AnyEvents = Record<string, object | void>;
50
+ /** The top-level state object shape used by sigma types. */
51
+ type AnyState = Record<string, unknown>;
52
+ /** The object accepted by `.defaultState(...)`. */
53
+ type AnyDefaultState<TState extends AnyState> = { [K in keyof TState]?: DefaultStateValue<TState[K]> };
54
+ /** A cleanup resource supported by `.setup(...)`. */
55
+ type AnyResource = Cleanup | Disposable | AbortController;
56
+ type ComputedValues<TComputeds extends object | undefined> = [undefined] extends [TComputeds] ? never : { readonly [K in keyof TComputeds]: TComputeds[K] extends AnyFunction ? Immutable<ReturnType<TComputeds[K]>> : never };
57
+ type ComputedContext<TState extends AnyState, TComputeds extends object> = Immutable<TState> & ComputedValues<TComputeds>;
58
+ type QueryMethods<TQueries extends object | undefined> = [undefined] extends [TQueries] ? never : { [K in keyof TQueries]: TQueries[K] extends AnyFunction ? (...args: Parameters<TQueries[K]>) => ReturnType<TQueries[K]> : never };
59
+ type ActionMethods<TActions extends object | undefined> = [undefined] extends [TActions] ? never : { [K in keyof TActions]: TActions[K] extends AnyFunction ? (...args: Parameters<TActions[K]>) => ReturnType<TActions[K]> : never };
60
+ type EventMethods<TEvents extends AnyEvents | undefined> = [undefined] extends [TEvents] ? never : {
61
+ readonly [sigmaEventsBrand]: TEvents;
62
+ on<TEvent extends string & keyof TEvents>(name: TEvent, listener: [TEvents[TEvent]] extends [void] ? () => void : (payload: TEvents[TEvent]) => void): Cleanup;
63
+ };
64
+ type SetupMethods<TSetupArgs extends any[] | undefined> = [TSetupArgs] extends [undefined] ? never : {
65
+ setup(...args: Extract<TSetupArgs, any[]>): Cleanup;
66
+ };
67
+ type ReadonlyContext<TState extends AnyState, TComputeds extends object, TQueries extends object> = Immutable<TState> & ComputedValues<TComputeds> & QueryMethods<TQueries>;
68
+ type Emit<TEvents extends AnyEvents> = <TEvent extends string & keyof TEvents>(name: TEvent, ...args: [TEvents[TEvent]] extends [void] ? [] : [payload: TEvents[TEvent]]) => void;
69
+ type ActionContext<TState extends AnyState, TEvents extends AnyEvents, TComputeds extends object, TQueries extends object, TActions extends object> = Draft<TState> & ComputedValues<TComputeds> & QueryMethods<TQueries> & ActionMethods<TActions> & {
70
+ /** Publishes the current action draft immediately so later boundaries use committed state. */commit(): void;
71
+ emit: Emit<TEvents>;
72
+ };
73
+ /** The public shape shared by all sigma-state instances. */
74
+ interface AnySigmaState extends EventTarget {
75
+ readonly [sigmaStateBrand]: true;
76
+ }
77
+ /** A sigma-state instance with a typed event map. */
78
+ type AnySigmaStateWithEvents<TEvents extends AnyEvents> = AnySigmaState & {
79
+ readonly [sigmaEventsBrand]: TEvents;
80
+ };
81
+ /** Options accepted by `.observe(...)`. */
82
+ type SigmaObserveOptions = {
83
+ patches?: boolean;
84
+ };
85
+ /** The change object delivered to `.observe(...)` listeners. */
86
+ type SigmaObserveChange<TState extends AnyState, TWithPatches extends boolean = false> = {
87
+ readonly newState: Immutable<TState>;
88
+ readonly oldState: Immutable<TState>;
89
+ } & (TWithPatches extends true ? {
90
+ readonly inversePatches: readonly Patch[];
91
+ readonly patches: readonly Patch[];
92
+ } : {});
93
+ type SigmaDefinition = {
94
+ state: AnyState;
95
+ events?: AnyEvents;
96
+ computeds?: object;
97
+ queries?: object;
98
+ actions?: object;
99
+ setupArgs?: any[];
100
+ };
101
+ interface SignalAccessors<T extends object> {
102
+ get<K extends keyof T>(key: K): ReadonlySignal<T[K]>;
103
+ }
104
+ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
105
+ type Simplify<T> = {} & { [K in keyof T]: T[K] };
106
+ type MapSigmaDefinition<T extends SigmaDefinition> = keyof T extends infer K ? K extends "state" ? Immutable<T[K]> & SignalAccessors<Immutable<T[K]>> : K extends "computeds" ? ComputedValues<T[K]> & SignalAccessors<ComputedValues<T[K]>> : K extends "queries" ? QueryMethods<T[K]> : K extends "actions" ? ActionMethods<T[K]> : K extends "events" ? EventMethods<T[K]> : K extends "setupArgs" ? SetupMethods<T[K]> : never : never;
107
+ /** The public instance shape produced by a configured sigma type. */
108
+ type SigmaState<T extends SigmaDefinition = SigmaDefinition> = AnySigmaState & Simplify<UnionToIntersection<MapSigmaDefinition<T>>>;
109
+ type SetupContext<T extends SigmaDefinition> = SigmaState<T> & {
110
+ emit: T["events"] extends object ? Emit<T["events"]> : never;
111
+ };
112
+ type MergeObjects<TLeft extends object, TRight> = [TRight] extends [object] ? Extract<Simplify<Omit<TLeft, keyof TRight> & TRight>, TLeft> : TLeft;
113
+ type RequiredKeys<TObject extends object> = { [K in keyof TObject]-?: {} extends Pick<TObject, K> ? never : K }[keyof TObject];
114
+ type MissingInitialKeys<TState extends AnyState, TDefaults extends AnyDefaultState<TState> | undefined> = Exclude<RequiredKeys<TState>, keyof NonNullable<TDefaults>>;
115
+ type InitialStateInput<TState extends AnyState, TDefaults extends AnyDefaultState<TState> | undefined> = [MissingInitialKeys<TState, TDefaults>] extends [never] ? [initialState?: Partial<TState>] : [initialState: Pick<TState, MissingInitialKeys<TState, TDefaults>> & Partial<TState>];
116
+ type Omit<T, K> = {} & { [P in Exclude<keyof T, K>]: T[P] };
117
+ type OmitEmpty<T extends object> = {} & Omit<T, { [K in keyof T]: [undefined] extends [T[K]] ? K : [{}] extends [T[K]] ? K : never }[keyof T]>;
118
+ /** Infers the `setup(...)` argument list for a sigma-state instance. */
119
+ type InferSetupArgs<T extends AnySigmaState> = T extends {
120
+ setup(...args: infer TArgs extends any[]): Cleanup;
121
+ } ? TArgs : never;
168
122
  //#endregion
169
- //#region src/hooks.d.ts
170
- type FilterProperties<T extends object, U> = {} & { [P in { [K in keyof T]: [T[K]] extends [never] ? never : T[K] extends U ? K : never }[keyof T]]: T[P] };
171
- type InferActions<TProps extends object> = {} & FilterProperties<TProps, (...args: any[]) => any>;
172
- type InferManagedStates<TProps extends object> = {} & FilterProperties<TProps, AnyManagedState>;
173
- type InferPublicProps<TProps extends object> = InferActions<TProps> & InferManagedStates<TProps>;
174
- type InferState<TProps extends object> = {} & Immutable<{ [K in keyof FilterProperties<TProps, ReadonlySignal | StateHandle<any, any> | Lens>]: TProps[K] extends ReadonlySignal<infer T> | StateHandle<infer T> | Lens<infer T> ? T : never }> & Readonly<InferManagedStates<TProps>>;
123
+ //#region src/internal/runtime.d.ts
124
+ /** Controls whether sigma deep-freezes published public state. Auto-freezing starts enabled. */
125
+ declare function setAutoFreeze(autoFreeze: boolean): void;
175
126
  /**
176
- * Clean encapsulation of complex UI state.
127
+ * Returns a shallow snapshot of an instance's committed public state.
177
128
  *
178
- * Use this when a component needs the same managed-state API without defining a
179
- * separate class. The constructor follows the same rules as
180
- * `defineManagedState()`, including explicit typing of the `StateHandle`
181
- * parameter for state and event inference.
182
- */
183
- declare function useManagedState<TState, TEvents extends EventsDefinition, TProps extends object = {}, TInitialState extends TState = TState>(constructor: StateConstructor<TState, TEvents, [], TProps>, initialState: TInitialState | (() => TInitialState)): ManagedState<InferState<TProps>, TEvents, InferPublicProps<TProps>>;
184
- /**
185
- * Any subscribable source, including a managed state or any Preact signal.
129
+ * The snapshot includes one own property for each top-level state key and reads
130
+ * the current committed value for that key. Its type is inferred from the
131
+ * instance's sigma-state definition.
186
132
  */
187
- type SubscribeTarget<T> = {
188
- subscribe: (listener: (value: T) => void) => () => void;
189
- };
133
+ declare function snapshot<T extends AnySigmaState>(publicInstance: T): T extends SigmaState<infer TDefinition> ? Immutable<TDefinition["state"]> : never;
190
134
  /**
191
- * Subscribe to future values from a subscribable source inside `useEffect`.
135
+ * Replaces an instance's committed public state from a snapshot object.
192
136
  *
193
- * The listener is kept fresh automatically, so a dependency array is not part
194
- * of this API. The listener receives the current value immediately and then
195
- * future updates. Pass `null` to disable the subscription temporarily.
137
+ * The replacement snapshot must be a plain object with exactly the instance's
138
+ * top-level state keys. Its type is inferred from the instance's sigma-state
139
+ * definition.
196
140
  */
197
- declare function useSubscribe<T>(target: SubscribeTarget<T> | null, listener: (value: T) => void): void;
198
- type InferEvent<T extends EventTarget | AnyManagedState> = T extends AnyManagedState<any, infer TEvents extends EventsDefinition> ? string & keyof TEvents : T extends {
199
- addEventListener: (name: infer TEvent) => any;
200
- } ? string & TEvent : string;
201
- type InferEventListener<T extends EventTarget | AnyManagedState, TEvent extends string = any> = T extends AnyManagedState<any, infer TEvents extends EventsDefinition> ? TEvent extends string & keyof TEvents ? (...args: TEvents[TEvent]) => void : never : T extends {
202
- addEventListener: (name: TEvent, listener: infer TListener extends (event: any) => any) => any;
203
- } ? TListener : (event: Event) => void;
141
+ declare function replaceState<T extends AnySigmaState>(publicInstance: T, nextState: T extends SigmaState<infer TDefinition> ? Immutable<TDefinition["state"]> : never): void;
142
+ //#endregion
143
+ //#region src/framework.d.ts
144
+ /** Checks whether a value is a sigma-state instance. */
145
+ declare function isSigmaState(value: unknown): value is AnySigmaState;
146
+ /** Creates a standalone tracked query function with the same signature as `fn`. */
147
+ declare function query<TArgs extends any[], TResult>(fn: (this: void, ...args: TArgs) => TResult): typeof fn;
204
148
  /**
205
- * Subscribe to events from an `EventTarget` or managed state inside `useEffect`.
206
- *
207
- * The listener is kept fresh automatically, so a dependency array is not part
208
- * of this API. Pass `null` to disable the subscription temporarily.
209
- *
210
- * For managed-state events, your listener receives the emitted argument
211
- * directly, or no argument at all.
149
+ * Builds sigma-state constructors by accumulating default state, computeds, queries,
150
+ * observers, actions, and setup handlers.
212
151
  */
213
- declare function useEventTarget<T extends EventTarget | AnyManagedState, TEvent extends InferEvent<T>>(target: T | null, name: TEvent, listener: InferEventListener<T, TEvent>): void;
152
+ declare class SigmaType<TState extends AnyState, TEvents extends AnyEvents = {}, TDefaults extends AnyDefaultState<TState> = {}, TComputeds extends object = {}, TQueries extends object = {}, TActions extends object = {}, TSetupArgs extends any[] = never> extends Function {
153
+ constructor(name?: string);
154
+ }
155
+ /** The constructor shape exposed by a configured sigma type. */
156
+ interface SigmaType<TState extends AnyState, TEvents extends AnyEvents, TDefaults extends AnyDefaultState<TState>, TComputeds extends object, TQueries extends object, TActions extends object, TSetupArgs extends any[]> {
157
+ new (...args: InitialStateInput<TState, TDefaults>): SigmaState<Extract<OmitEmpty<{
158
+ state: TState;
159
+ events: TEvents;
160
+ computeds: TComputeds;
161
+ queries: TQueries;
162
+ actions: TActions;
163
+ setupArgs: TSetupArgs;
164
+ }>, SigmaDefinition>>;
165
+ /** Does not exist at runtime, only for type inference. */
166
+ get Instance(): SigmaState<Extract<OmitEmpty<{
167
+ state: TState;
168
+ events: TEvents;
169
+ computeds: TComputeds;
170
+ queries: TQueries;
171
+ actions: TActions;
172
+ setupArgs: TSetupArgs;
173
+ }>, SigmaDefinition>>;
174
+ defaultState<TNextDefaults extends AnyDefaultState<TState>>(defaultState: TNextDefaults): SigmaType<TState, TEvents, MergeObjects<TDefaults, TNextDefaults>, TComputeds, TQueries, TActions, TSetupArgs>;
175
+ computed<TNextComputeds extends object>(computeds: TNextComputeds & ThisType<ComputedContext<TState, MergeObjects<TComputeds, TNextComputeds>>>): SigmaType<TState, TEvents, TDefaults, MergeObjects<TComputeds, TNextComputeds>, TQueries, TActions, TSetupArgs>;
176
+ queries<TNextQueries extends object>(queries: TNextQueries & ThisType<ReadonlyContext<TState, TComputeds, MergeObjects<TQueries, TNextQueries>>>): SigmaType<TState, TEvents, TDefaults, TComputeds, MergeObjects<TQueries, TNextQueries>, TActions, TSetupArgs>;
177
+ observe(listener: (this: ReadonlyContext<TState, TComputeds, TQueries>, change: SigmaObserveChange<TState>) => void, options?: SigmaObserveOptions & {
178
+ patches?: false | undefined;
179
+ }): this;
180
+ observe(listener: (this: ReadonlyContext<TState, TComputeds, TQueries>, change: SigmaObserveChange<TState, true>) => void, options: SigmaObserveOptions & {
181
+ patches: true;
182
+ }): this;
183
+ /**
184
+ * Adds action methods whose `this` receives draft state, typed events, `commit()`,
185
+ * and the computeds, queries, and actions already defined on the builder.
186
+ *
187
+ * Actions create drafts lazily as they need them. Sync actions on the same
188
+ * instance reuse the current draft, so they can compose and publish once when
189
+ * the outer action returns. Declared async actions publish their initial
190
+ * synchronous work on return, then require `this.commit()` to publish later
191
+ * writes made after `await`. Non-async actions stay synchronous; if one
192
+ * returns a promise, sigma throws so async boundaries stay explicit.
193
+ */
194
+ actions<TNextActions extends object>(actions: TNextActions & ThisType<ActionContext<TState, TEvents, TComputeds, TQueries, MergeObjects<TActions, TNextActions>>>): SigmaType<TState, TEvents, TDefaults, TComputeds, TQueries, MergeObjects<TActions, TNextActions>, TSetupArgs>;
195
+ setup<TNextSetupArgs extends ([TSetupArgs] extends [never] ? any[] : NonNullable<TSetupArgs>)>(setup: (this: SetupContext<{
196
+ state: TState;
197
+ events: TEvents;
198
+ computeds: TComputeds;
199
+ queries: TQueries;
200
+ actions: TActions;
201
+ setupArgs: TNextSetupArgs;
202
+ }>, ...args: TNextSetupArgs) => readonly AnyResource[]): SigmaType<TState, TEvents, TDefaults, TComputeds, TQueries, TActions, TNextSetupArgs>;
203
+ }
204
+ //#endregion
205
+ //#region src/listener.d.ts
206
+ type TryGet<T, K extends PropertyKey, TCatch = never> = K extends keyof T ? T[K] : TCatch;
207
+ type TypedEventListener<TEventMap, TEvent extends string, TCurrentTarget extends EventTarget> = ((event: TryGet<TEventMap, string extends TEvent ? keyof TEventMap : TEvent, CustomEvent> & {
208
+ readonly currentTarget: TCurrentTarget;
209
+ }) => void) & {
210
+ __eventType?: string extends TEvent ? keyof TEventMap : TEvent;
211
+ };
212
+ /** Infers the supported event names for a listener target. */
213
+ type InferEventType<TTarget extends EventTarget> = (InferListener<TTarget> extends {
214
+ __eventType?: infer TEvent;
215
+ } ? string & TEvent : never) | (string & {});
216
+ /** Infers the listener function signature for a target and event name. */
217
+ type InferListener<TTarget extends EventTarget, TEvent extends string = string> = TTarget extends AnySigmaStateWithEvents<infer TEvents> ? TEvent extends keyof TEvents ? (event: TEvents[TEvent]) => void : never : TTarget extends Window ? TypedEventListener<WindowEventMap, TEvent, TTarget> : TTarget extends Document ? TypedEventListener<DocumentEventMap, TEvent, TTarget> : TTarget extends HTMLBodyElement ? TypedEventListener<HTMLBodyElementEventMap, TEvent, TTarget> : TTarget extends HTMLMediaElement ? TypedEventListener<HTMLMediaElementEventMap, TEvent, TTarget> : TTarget extends HTMLElement ? TypedEventListener<HTMLElementEventMap, TEvent, TTarget> : TTarget extends SVGSVGElement ? TypedEventListener<SVGSVGElementEventMap, TEvent, TTarget> : TTarget extends SVGElement ? TypedEventListener<SVGElementEventMap, TEvent, TTarget> : (event: Event & {
218
+ readonly currentTarget: TTarget;
219
+ }) => void;
220
+ /** Adds an event listener and returns a cleanup function that removes it. */
221
+ declare function listen<TTarget extends EventTarget, TEvent extends InferEventType<TTarget>>(target: TTarget, name: TEvent, fn: InferListener<TTarget, TEvent>): () => void;
222
+ //#endregion
223
+ //#region src/hooks.d.ts
224
+ /** Creates one sigma-state instance for a component and manages its setup cleanup. */
225
+ declare function useSigma<T extends AnySigmaState>(create: () => T, setupArgs?: InferSetupArgs<T>): T;
226
+ /** Attaches an event listener in a component and cleans it up when dependencies change. */
227
+ declare function useListener<TTarget extends EventTarget | AnySigmaState, TEvent extends InferEventType<TTarget>>(target: TTarget | null, name: TEvent, listener: InferListener<TTarget, TEvent>): void;
214
228
  //#endregion
215
- export { AnyManagedState, EventsDefinition, Lens, ManagedState, StateConstructor, StateHandle, SubscribeTarget, batch, computed, defineManagedState, isManagedState, query, untracked, useEventTarget, useManagedState, useSubscribe };
229
+ export { type AnyDefaultState, type AnyEvents, type AnyResource, type AnySigmaState, type AnySigmaStateWithEvents, type AnyState, InferEventType, InferListener, type InferSetupArgs, type SigmaObserveChange, type SigmaObserveOptions, type SigmaState, SigmaType, action, batch, computed, effect, freeze, immerable, isSigmaState, listen, query, replaceState, setAutoFreeze, snapshot, untracked, useListener, useSigma };