@blac/core 2.0.0 → 2.0.3

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 (60) hide show
  1. package/README.md +137 -177
  2. package/dist/StateContainerRegistry.cjs.map +1 -0
  3. package/dist/StateContainerRegistry.js.map +1 -0
  4. package/dist/debug.cjs +27 -0
  5. package/dist/debug.cjs.map +1 -0
  6. package/dist/debug.js +19 -0
  7. package/dist/debug.js.map +1 -0
  8. package/dist/dependency-manager.cjs.map +1 -0
  9. package/dist/dependency-manager.js.map +1 -0
  10. package/dist/index.cjs +346 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +794 -0
  13. package/dist/index.d.ts +675 -386
  14. package/dist/index.js +310 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/management.cjs.map +1 -0
  17. package/dist/management.js.map +1 -0
  18. package/dist/plugins.cjs +4 -0
  19. package/dist/plugins.js +3 -0
  20. package/dist/tracking/dependency-manager.d.ts +37 -0
  21. package/dist/tracking/index.d.ts +12 -0
  22. package/dist/tracking/path-utils.d.ts +52 -0
  23. package/dist/tracking/tracked.d.ts +70 -0
  24. package/dist/tracking/tracking-proxy.d.ts +197 -0
  25. package/dist/tracking-proxy.cjs.map +1 -0
  26. package/dist/tracking-proxy.js.map +1 -0
  27. package/dist/tracking.cjs +19 -0
  28. package/dist/tracking.d.cts +9 -0
  29. package/dist/tracking.d.ts +9 -0
  30. package/dist/tracking.js +4 -0
  31. package/dist/types.cjs +14 -0
  32. package/dist/types.cjs.map +1 -0
  33. package/dist/types.d.cts +8 -0
  34. package/dist/types.d.ts +8 -0
  35. package/dist/types.js +13 -0
  36. package/dist/types.js.map +1 -0
  37. package/dist/watch-entry.cjs +111 -0
  38. package/dist/watch-entry.cjs.map +1 -0
  39. package/dist/watch-entry.js +107 -0
  40. package/dist/watch-entry.js.map +1 -0
  41. package/dist/watch.cjs.map +1 -0
  42. package/dist/watch.js.map +1 -0
  43. package/package.json +122 -19
  44. package/dist/index.cjs.js +0 -2
  45. package/dist/index.cjs.js.map +0 -1
  46. package/dist/index.es.js +0 -670
  47. package/dist/index.es.js.map +0 -1
  48. package/src/Blac.ts +0 -483
  49. package/src/BlacEvent.ts +0 -5
  50. package/src/BlacObservable.ts +0 -88
  51. package/src/BlacObserver.ts +0 -129
  52. package/src/BlacPlugin.ts +0 -13
  53. package/src/Bloc.ts +0 -109
  54. package/src/BlocBase.ts +0 -248
  55. package/src/Cubit.ts +0 -69
  56. package/src/addons/BlacAddon.ts +0 -17
  57. package/src/addons/Persist.ts +0 -105
  58. package/src/addons/index.ts +0 -1
  59. package/src/index.ts +0 -8
  60. package/src/types.ts +0 -63
package/dist/index.d.ts CHANGED
@@ -1,505 +1,794 @@
1
+ export declare function acquire<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): InstanceType<T>;
2
+
1
3
  /**
2
- * Main Blac class that manages the state management system.
3
- * Implements a singleton pattern to ensure only one instance exists.
4
- * Handles bloc lifecycle, plugin management, and instance tracking.
4
+ * Decorator to configure StateContainer classes.
5
+ *
6
+ * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)
7
+ * ```ts
8
+ * @blac({ isolated: true })
9
+ * class FormBloc extends Cubit<FormState> {}
10
+ *
11
+ * @blac({ keepAlive: true })
12
+ * class AuthBloc extends Cubit<AuthState> {}
13
+ *
14
+ * @blac({ excludeFromDevTools: true })
15
+ * class InternalBloc extends Cubit<InternalState> {}
16
+ * ```
5
17
  *
6
- * Key responsibilities:
7
- * - Managing bloc instances (creation, disposal, lookup)
8
- * - Handling isolated and non-isolated blocs
9
- * - Managing plugins and lifecycle events
10
- * - Providing logging and debugging capabilities
18
+ * @example Function syntax (no decorator support needed)
19
+ * ```ts
20
+ * const FormBloc = blac({ isolated: true })(
21
+ * class extends Cubit<FormState> {}
22
+ * );
23
+ * ```
11
24
  */
12
- export declare class Blac {
13
- /** The singleton instance of Blac */
14
- static instance: Blac;
15
- /** Timestamp when the instance was created */
16
- createdAt: number;
17
- static getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
18
- searchIsolated?: boolean;
19
- }) => InstanceType<B>[];
20
- static addPlugin: (plugin: BlacPlugin) => void;
21
- /** Map storing all registered bloc instances by their class name and ID */
22
- blocInstanceMap: Map<string, BlocBase<any>>;
23
- /** Map storing isolated bloc instances grouped by their constructor */
24
- isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<any>[]>;
25
- pluginList: BlacPlugin[];
26
- /** Flag to control whether changes should be posted to document */
27
- postChangesToDocument: boolean;
28
- /**
29
- * Creates a new Blac instance.
30
- * @param options - Configuration options including singleton control
31
- */
32
- constructor(options?: {
33
- __unsafe_ignore_singleton?: boolean;
34
- });
35
- /** Flag to enable/disable logging */
36
- static enableLog: boolean;
37
- /**
38
- * Logs messages to console when logging is enabled
39
- * @param args - Arguments to log
40
- */
41
- log: (...args: unknown[]) => void;
42
- static log: (...args: unknown[]) => void;
43
- /**
44
- * Gets the singleton instance of Blac
45
- * @returns The Blac instance
46
- */
47
- static getInstance(): Blac;
48
- /**
49
- * Logs a warning message
50
- * @param message - Warning message
51
- * @param args - Additional arguments
52
- */
53
- warn: (message: string, ...args: unknown[]) => void;
54
- static warn: (message: string, ...args: unknown[]) => void;
25
+ export declare function blac(options: BlacOptions): <T extends new (...args: any[]) => any>(target: T, _context?: ClassDecoratorContext) => T;
26
+
27
+ /**
28
+ * Configuration options for the @blac decorator.
29
+ * Only one option can be specified at a time (union type).
30
+ */
31
+ export declare type BlacOptions =
32
+ /** Mark bloc as isolated (each component gets its own instance) */
33
+ {
34
+ isolated: true;
35
+ }
36
+ /** Mark bloc to never be auto-disposed when ref count reaches 0 */
37
+ | {
38
+ keepAlive: true;
39
+ }
40
+ /** Exclude bloc from DevTools tracking (prevents infinite loops) */
41
+ | {
42
+ excludeFromDevTools: true;
43
+ };
44
+
45
+ /**
46
+ * Interface for plugins that extend BlaC functionality
47
+ */
48
+ export declare interface BlacPlugin {
49
+ /** Unique plugin identifier */
50
+ readonly name: string;
51
+ /** Plugin version identifier */
52
+ readonly version: string;
55
53
  /**
56
- * Logs an error message
57
- * @param message - Error message
58
- * @param args - Additional arguments
54
+ * Called when the plugin is installed (optional)
59
55
  */
60
- error: (message: string, ...args: unknown[]) => void;
61
- static error: (message: string, ...args: unknown[]) => void;
56
+ onInstall?(context: PluginContext): void;
62
57
  /**
63
- * Resets the Blac instance to a new one, disposing non-keepAlive blocs
64
- * from the old instance.
58
+ * Called when the plugin is uninstalled
65
59
  */
66
- resetInstance: () => void;
67
- static resetInstance: () => void;
60
+ onUninstall?(): void;
68
61
  /**
69
- * Adds a plugin to the Blac instance
70
- * @param plugin - The plugin to add
62
+ * Called when a state container instance is created
71
63
  */
72
- addPlugin: (plugin: BlacPlugin) => void;
64
+ onInstanceCreated?(instance: StateContainer<any>, context: PluginContext): void;
73
65
  /**
74
- * Dispatches a lifecycle event to all registered plugins
75
- * @param event - The lifecycle event to dispatch
76
- * @param bloc - The bloc instance involved in the event
77
- * @param params - Additional parameters for the event
66
+ * Called when state changes in a container instance
78
67
  */
79
- dispatchEventToPlugins: (event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown) => void;
68
+ onStateChanged?<S extends object = any>(instance: StateContainer<S>, previousState: S, currentState: S, callstack: string | undefined, context: PluginContext): void;
80
69
  /**
81
- * Dispatches a lifecycle event and handles related cleanup actions.
82
- * This method is responsible for:
83
- * - Logging the event
84
- * - Handling bloc disposal when needed
85
- * - Managing bloc consumer cleanup
86
- * - Forwarding the event to plugins
87
- *
88
- * @param event - The lifecycle event to dispatch
89
- * @param bloc - The bloc instance involved in the event
90
- * @param params - Additional parameters for the event
70
+ * Called when a state container instance is disposed
91
71
  */
92
- dispatchEvent: (event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown) => void;
72
+ onInstanceDisposed?(instance: StateContainer<any>, context: PluginContext): void;
73
+ }
74
+
75
+ /**
76
+ * Plugin interface variant that requires mandatory onInstall hook
77
+ */
78
+ export declare interface BlacPluginWithInit extends BlacPlugin {
93
79
  /**
94
- * Disposes of a bloc instance by removing it from the appropriate registry
95
- * @param bloc - The bloc instance to dispose
80
+ * Required initialization hook called when plugin is installed
96
81
  */
97
- disposeBloc: (bloc: BlocBase<any>) => void;
82
+ onInstall(context: PluginContext): void;
83
+ }
84
+
85
+ declare const BLOC_REF_MARKER: unique symbol;
86
+
87
+ /**
88
+ * Constructor type for StateContainer classes with static registry methods.
89
+ * Used for type-safe hook parameters.
90
+ * @template TBloc - The StateContainer instance type
91
+ */
92
+ export declare type BlocConstructor<S extends object = any, T extends new (...args: any[]) => StateContainer<S> = new (...args: any[]) => StateContainer<S>> = (new (...args: any[]) => InstanceType<T>) & {
93
+ acquire(instanceKey?: string, ...args: any[]): InstanceType<T>;
94
+ borrow(instanceKey?: string, ...args: any[]): InstanceType<T> | null;
95
+ borrowSafe(instanceKey?: string, ...args: any[]): {
96
+ error: Error;
97
+ instance: null;
98
+ } | {
99
+ error: null;
100
+ instance: InstanceType<T>;
101
+ };
102
+ ensure(instanceKey?: string): InstanceType<T>;
103
+ release(instanceKey?: string): void;
104
+ isolated?: boolean;
105
+ keepAlive?: boolean;
106
+ };
107
+
108
+ declare type BlocInput = StateContainerConstructor | BlocRef<StateContainerConstructor>;
109
+
110
+ /**
111
+ * Extract instance type from an abstract class constructor
112
+ * @template T - The abstract class constructor type
113
+ */
114
+ export declare type BlocInstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;
115
+
116
+ /**
117
+ * Reference to a specific bloc instance by class and instance ID.
118
+ */
119
+ export declare interface BlocRef<T extends StateContainerConstructor> {
120
+ [BLOC_REF_MARKER]: true;
121
+ blocClass: T;
122
+ instanceId: string;
123
+ }
124
+
125
+ export declare function borrow<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): InstanceType<T>;
126
+
127
+ export declare function borrowSafe<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): {
128
+ error: Error;
129
+ instance: null;
130
+ } | {
131
+ error: null;
132
+ instance: InstanceType<T>;
133
+ };
134
+
135
+ /* Excluded from this release type: capturePaths */
136
+
137
+ export declare function clear<T extends StateContainerConstructor>(BlocClass: T): void;
138
+
139
+ /* Excluded from this release type: clearActiveTracker */
140
+
141
+ export declare function clearAll(): void;
142
+
143
+ /* Excluded from this release type: clearExternalDependencies */
144
+
145
+ /* Excluded from this release type: commitTrackedGetters */
146
+
147
+ /* Excluded from this release type: createBlocProxy */
148
+
149
+ /* Excluded from this release type: createDependencyProxy */
150
+
151
+ /* Excluded from this release type: createDependencyState */
152
+
153
+ /* Excluded from this release type: createGetterState */
154
+
155
+ /**
156
+ * Simple state container with direct state emission.
157
+ * Extends StateContainer with public methods for emitting and updating state.
158
+ *
159
+ * @template S - State type
160
+ */
161
+ export declare abstract class Cubit<S extends object = any> extends StateContainer<S> {
162
+ constructor(initialState: S);
98
163
  /**
99
- * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
100
- * @param blocClassName - The name of the bloc class
101
- * @param id - The instance ID
102
- * @returns A unique key string in the format "className:id"
164
+ * Replace state with a new value and notify all listeners
165
+ * @param newState - The new state value
103
166
  */
104
- createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string;
167
+ emit(newState: S): void;
105
168
  /**
106
- * Unregister a bloc instance from the main registry
107
- * @param bloc - The bloc instance to unregister
169
+ * Transform current state using an updater function and emit the new state
170
+ * @param updater - Function that receives current state and returns new state
108
171
  */
109
- unregisterBlocInstance(bloc: BlocBase<any>): void;
172
+ update(updater: (current: S) => S): void;
110
173
  /**
111
- * Registers a bloc instance in the main registry
112
- * @param bloc - The bloc instance to register
174
+ * Merge partial state changes into current state (only for object states)
113
175
  */
114
- registerBlocInstance(bloc: BlocBase<any>): void;
176
+ patch: S extends object ? (partial: Partial<S>) => void : never;
177
+ }
178
+
179
+ /**
180
+ * Manages subscriptions to state container dependencies.
181
+ * Provides efficient sync mechanism to add/remove subscriptions
182
+ * as dependencies change between callback invocations.
183
+ */
184
+ export declare class DependencyManager {
185
+ private subscriptions;
186
+ private currentDeps;
115
187
  /**
116
- * Finds a registered bloc instance by its class and ID
117
- * @param blocClass - The bloc class to search for
118
- * @param id - The instance ID
119
- * @returns The found bloc instance or undefined if not found
188
+ * Sync subscriptions with a new set of dependencies.
189
+ * Adds subscriptions for new deps, removes subscriptions for stale deps.
190
+ *
191
+ * @param newDeps - The new set of dependencies to subscribe to
192
+ * @param onChange - Callback to invoke when any dependency changes
193
+ * @param exclude - Optional instance to exclude from subscriptions (e.g., primary bloc)
194
+ * @returns true if the dependency set changed, false if unchanged
120
195
  */
121
- findRegisteredBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
196
+ sync(newDeps: Set<StateContainerInstance>, onChange: () => void, exclude?: StateContainerInstance): boolean;
122
197
  /**
123
- * Registers an isolated bloc instance in the isolated registry
124
- * @param bloc - The isolated bloc instance to register
198
+ * Add a single dependency subscription.
125
199
  */
126
- registerIsolatedBlocInstance(bloc: BlocBase<any>): void;
200
+ add(dep: StateContainerInstance, onChange: () => void): void;
127
201
  /**
128
- * Unregister an isolated bloc instance from the isolated registry
129
- * @param bloc - The isolated bloc instance to unregister
202
+ * Check if a dependency is currently subscribed.
130
203
  */
131
- unregisterIsolatedBlocInstance(bloc: BlocBase<any>): void;
204
+ has(dep: StateContainerInstance): boolean;
132
205
  /**
133
- * Finds an isolated bloc instance by its class and ID
206
+ * Get the current set of dependencies.
134
207
  */
135
- findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
208
+ getDependencies(): Set<StateContainerInstance>;
136
209
  /**
137
- * Creates a new bloc instance and registers it in the appropriate registry
138
- * @param blocClass - The bloc class to instantiate
139
- * @param id - The instance ID
140
- * @param props - Properties to pass to the bloc constructor
141
- * @param instanceRef - Optional reference string for the instance
142
- * @returns The newly created bloc instance
210
+ * Clean up all active subscriptions.
143
211
  */
144
- createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
145
- /**
146
- * Gets or creates a bloc instance based on the provided class and options.
147
- * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
148
- *
149
- * @param blocClass - The bloc class to get or create
150
- * @param options - Options including:
151
- * - id: The instance ID (defaults to class name if not provided)
152
- * - props: Properties to pass to the bloc constructor
153
- * - instanceRef: Optional reference string for the instance
154
- * @returns The bloc instance
155
- */
156
- getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
157
- static getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
158
- /**
159
- * Gets a bloc instance or throws an error if it doesn't exist
160
- * @param blocClass - The bloc class to get
161
- * @param options - Options including:
162
- * - id: The instance ID (defaults to class name if not provided)
163
- * - props: Properties to pass to the bloc constructor
164
- * - instanceRef: Optional reference string for the instance
165
- */
166
- getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
167
- id?: BlocInstanceId;
168
- props?: InferPropsFromGeneric<B>;
169
- instanceRef?: string;
170
- }) => InstanceType<B>;
171
- static getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
172
- id?: BlocInstanceId;
173
- props?: InferPropsFromGeneric<B> | undefined;
174
- instanceRef?: string;
175
- }) => InstanceType<B>;
176
- /**
177
- * Gets all instances of a specific bloc class
178
- * @param blocClass - The bloc class to search for
179
- * @param options - Options including:
180
- * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
181
- * @returns Array of matching bloc instances
182
- */
183
- getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
184
- searchIsolated?: boolean;
185
- }) => InstanceType<B>[];
212
+ cleanup(): void;
213
+ private areSetsEqual;
186
214
  }
187
215
 
188
- declare type BlacAddon = {
189
- name: string;
190
- onInit?: BlacAddonInit;
191
- onEmit?: BlacAddonEmit;
216
+ /* Excluded from this release type: DependencyState */
217
+
218
+ export declare function ensure<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): InstanceType<T>;
219
+
220
+ /**
221
+ * Extract constructor argument types from a class
222
+ * @template T - The class type
223
+ */
224
+ export declare type ExtractConstructorArgs<T> = T extends new (...args: infer P) => any ? P : never[];
225
+
226
+ declare type ExtractInstance<T> = T extends BlocRef<infer C> ? InstanceType<C> : T extends StateContainerConstructor ? InstanceType<T> : never;
227
+
228
+ declare type ExtractInstances<T extends readonly BlocInput[]> = {
229
+ [K in keyof T]: ExtractInstance<T[K]>;
192
230
  };
193
231
 
194
- declare type BlacAddonEmit = (params: {
195
- oldState: unknown;
196
- newState: unknown;
197
- cubit: BlocBase<any>;
198
- }) => void;
232
+ /**
233
+ * Extract the state type from a StateContainer
234
+ * @template T - The StateContainer type
235
+ */
236
+ export declare type ExtractState<T> = T extends StateContainerConstructor<infer S> ? Readonly<S> : never;
237
+
238
+ export declare type ExtractStateMutable<T> = T extends StateContainerConstructor<infer S> ? S : never;
199
239
 
200
- declare type BlacAddonInit = (bloc: BlocBase<any>) => void;
240
+ export declare function forEach<T extends StateContainerConstructor>(BlocClass: T, callback: (instance: InstanceReadonlyState<T>) => void): void;
201
241
 
202
242
  /**
203
- * Configuration options for the Blac instance
243
+ * Generate a unique isolated instance key
244
+ * Uses base36 encoding for compact, URL-safe identifiers
245
+ *
246
+ * Format: "isolated-{9-char-random-string}"
247
+ * Example: "isolated-k7x2m9p4q"
248
+ *
249
+ * @returns A unique isolated instance key
204
250
  */
205
- export declare interface BlacConfig {
206
- /** Whether to expose the Blac instance globally */
207
- exposeBlacInstance?: boolean;
251
+ export declare function generateIsolatedKey(): string;
252
+
253
+ export declare function getAll<T extends StateContainerConstructor>(BlocClass: T): InstanceReadonlyState<T>[];
254
+
255
+ /**
256
+ * Get the global plugin manager
257
+ */
258
+ export declare function getPluginManager(): any;
259
+
260
+ export declare function getRefCount<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): number;
261
+
262
+ /* Excluded from this release type: GetterState */
263
+
264
+ /**
265
+ * Global default registry instance
266
+ */
267
+ export declare const globalRegistry: StateContainerRegistry;
268
+
269
+ /* Excluded from this release type: hasDependencyChanges */
270
+
271
+ /* Excluded from this release type: hasGetterChanges */
272
+
273
+ export declare function hasInstance<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): boolean;
274
+
275
+ /* Excluded from this release type: hasTrackedData */
276
+
277
+ /**
278
+ * Create a reference to a specific bloc instance.
279
+ *
280
+ * @example
281
+ * ```ts
282
+ * watch(instance(UserBloc, 'user-123'), (userBloc) => {
283
+ * console.log(userBloc.state.name);
284
+ * });
285
+ * ```
286
+ */
287
+ export declare function instance<T extends StateContainerConstructor>(BlocClass: T, instanceId: string): BlocRef<T>;
288
+
289
+ /**
290
+ * Entry in the instance registry, tracking the instance and its reference count
291
+ * @template T - Instance type
292
+ */
293
+ export declare interface InstanceEntry<T = any> {
294
+ /** The state container instance */
295
+ instance: T;
296
+ /** Number of active references to this instance */
297
+ refCount: number;
208
298
  }
209
299
 
210
300
  /**
211
- * Enum representing different lifecycle events that can occur in the Blac system.
212
- * These events are used to track the lifecycle of blocs and their consumers.
301
+ * Metadata information about a state container instance for debugging and inspection
213
302
  */
214
- export declare enum BlacLifecycleEvent {
215
- BLOC_DISPOSED = "BLOC_DISPOSED",
216
- BLOC_CREATED = "BLOC_CREATED",
217
- LISTENER_REMOVED = "LISTENER_REMOVED",
218
- LISTENER_ADDED = "LISTENER_ADDED",
219
- STATE_CHANGED = "STATE_CHANGED",
220
- BLOC_CONSUMER_REMOVED = "BLOC_CONSUMER_REMOVED",
221
- BLOC_CONSUMER_ADDED = "BLOC_CONSUMER_ADDED"
303
+ export declare interface InstanceMetadata {
304
+ /** Unique instance identifier */
305
+ id: string;
306
+ /** Name of the state container class */
307
+ className: string;
308
+ /** Whether the instance has been disposed */
309
+ isDisposed: boolean;
310
+ /** Display name for the instance */
311
+ name: string;
312
+ /** When state last changed (milliseconds) */
313
+ lastStateChangeTimestamp: number;
314
+ /** Current state value */
315
+ state: any;
316
+ /** Timestamp when instance was created (milliseconds) */
317
+ createdAt: number;
318
+ /** Whether this is an isolated (component-scoped) instance */
319
+ isIsolated: boolean;
320
+ /** Stack trace from when instance was created (for debugging) */
321
+ callstack?: string;
322
+ /** Previous state value */
323
+ previousState?: any;
324
+ /** Current state value */
325
+ currentState?: any;
222
326
  }
223
327
 
328
+ export declare type InstanceReadonlyState<T extends StateContainerConstructor = any> = Omit<InstanceType<T>, 'state'> & {
329
+ state: ExtractState<T>;
330
+ };
331
+
332
+ export declare type InstanceState<T extends StateContainerConstructor = any> = Omit<InstanceType<T>, 'state'> & {
333
+ state: ExtractStateMutable<T>;
334
+ };
335
+
336
+ /* Excluded from this release type: invalidateRenderCache */
337
+
224
338
  /**
225
- * A class that manages observers for a Bloc's state changes
226
- * @template S - The type of state being observed
339
+ * Check if a class is marked as isolated.
340
+ * Isolated classes create separate instances per component.
341
+ * @param Type - The class constructor to check
342
+ * @returns true if the class has `static isolated = true`
227
343
  */
228
- export declare class BlacObservable<S = unknown> {
229
- /** The Bloc instance this observable is associated with */
230
- bloc: BlocBase<S>;
231
- /**
232
- * Creates a new BlacObservable instance
233
- * @param bloc - The Bloc instance to observe
234
- */
235
- constructor(bloc: BlocBase<S>);
236
- private _observers;
237
- /**
238
- * Gets the number of active observers
239
- * @returns The number of observers currently subscribed
240
- */
241
- get size(): number;
344
+ export declare function isIsolatedClass<T extends StateContainerConstructor>(Type: T): boolean;
345
+
346
+ /**
347
+ * Lifecycle events emitted by the registry
348
+ */
349
+ export declare type LifecycleEvent = 'created' | 'stateChanged' | 'disposed';
350
+
351
+ /**
352
+ * Listener function type for each lifecycle event
353
+ * @template E - The lifecycle event type
354
+ */
355
+ export declare type LifecycleListener<E extends LifecycleEvent> = E extends 'created' ? (container: StateContainer<any>) => void : E extends 'stateChanged' ? (container: StateContainer<any>, previousState: any, currentState: any, callstack?: string) => void : E extends 'disposed' ? (container: StateContainer<any>) => void : never;
356
+
357
+ /* Excluded from this release type: PathInfo */
358
+
359
+ /**
360
+ * Configuration options for plugin installation
361
+ */
362
+ export declare interface PluginConfig {
363
+ /** Enable or disable the plugin */
364
+ enabled?: boolean;
365
+ /** Environments where plugin runs */
366
+ environment?: 'development' | 'production' | 'test' | 'all';
367
+ }
368
+
369
+ /**
370
+ * Safe context API provided to plugins for accessing registry data
371
+ */
372
+ export declare interface PluginContext {
242
373
  /**
243
- * Gets the set of all observers
244
- * @returns The Set of all BlacObserver instances
374
+ * Get metadata for a specific instance
245
375
  */
246
- get observers(): Set<BlacObserver<S>>;
376
+ getInstanceMetadata(instance: StateContainer<any>): InstanceMetadata;
247
377
  /**
248
- * Subscribes an observer to state changes
249
- * @param observer - The observer to subscribe
250
- * @returns A function that can be called to unsubscribe the observer
378
+ * Get current state from a container
251
379
  */
252
- subscribe(observer: BlacObserver<S>): () => void;
380
+ getState<S extends object = any>(instance: StateContainer<S>): S;
253
381
  /**
254
- * Unsubscribes an observer from state changes
255
- * @param observer - The observer to unsubscribe
382
+ * Get all instances of a specific type
256
383
  */
257
- unsubscribe(observer: BlacObserver<S>): void;
384
+ queryInstances<T extends StateContainer<any>>(typeClass: new (...args: any[]) => T): T[];
258
385
  /**
259
- * Notifies all observers of a state change
260
- * @param newState - The new state value
261
- * @param oldState - The previous state value
262
- * @param action - Optional action that triggered the state change
386
+ * Get all registered state container types
263
387
  */
264
- notify(newState: S, oldState: S, action?: unknown): void;
388
+ getAllTypes(): Array<new (...args: any[]) => StateContainer<any>>;
265
389
  /**
266
- * Disposes of all observers and clears the observer set
390
+ * Get registry statistics
267
391
  */
268
- dispose(): void;
392
+ getStats(): {
393
+ registeredTypes: number;
394
+ totalInstances: number;
395
+ typeBreakdown: Record<string, number>;
396
+ };
269
397
  }
270
398
 
271
399
  /**
272
- * Represents an observer that can subscribe to state changes in a Bloc
273
- * @template S - The type of state being observed
400
+ * Manages plugin lifecycle for the BlaC state management system.
401
+ * Plugins receive notifications about state container lifecycle events.
402
+ *
403
+ * @example
404
+ * ```ts
405
+ * const manager = createPluginManager(registry);
406
+ * manager.install(myPlugin, { environment: 'development' });
407
+ * ```
274
408
  */
275
- export declare type BlacObserver<S> = {
276
- /** Function to be called when state changes */
277
- fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;
278
- /** Optional function to determine if the observer should be notified of state changes */
279
- dependencyArray?: BlocHookDependencyArrayFn<S>;
280
- /** Dispose function for the observer */
281
- dispose?: () => void;
282
- /** Cached state values used for dependency comparison */
283
- lastState?: unknown[][];
284
- /** Unique identifier for the observer */
285
- id: string;
286
- };
287
-
288
- export declare interface BlacPlugin {
289
- name: string;
290
- onEvent(event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown): void;
291
- }
292
-
293
- export declare abstract class Bloc<S, // State type
294
- A extends object, // Base Action/Event type, constrained to object
295
- P = unknown> extends BlocBase<S, P> {
296
- readonly eventHandlers: Map<new (...args: any[]) => A, (event: A, emit: (newState: S) => void) => void | Promise<void>>;
409
+ export declare class PluginManager {
410
+ private plugins;
411
+ private registry;
297
412
  /**
298
- * Registers an event handler for a specific event type.
299
- * This method is typically called in the constructor of a derived Bloc class.
300
- * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).
301
- * @param handler A function that processes the event and can emit new states.
302
- * The 'event' parameter in the handler will be typed to the specific eventConstructor.
413
+ * Create a new PluginManager
414
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
303
415
  */
304
- protected on<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
416
+ constructor(registry: StateContainerRegistry);
305
417
  /**
306
- * Dispatches an action/event to the Bloc.
307
- * If a handler is registered for this specific event type (via 'on'), it will be invoked.
308
- * Asynchronous handlers are awaited.
309
- * @param action The action/event instance to be processed.
418
+ * Install a plugin with optional configuration
419
+ * @param plugin - The plugin to install
420
+ * @param config - Optional plugin configuration
421
+ * @throws Error if plugin is already installed
310
422
  */
311
- add: (action: A) => Promise<void>;
312
- }
313
-
314
- /**
315
- * Base class for both Blocs and Cubits that provides core state management functionality.
316
- * Handles state transitions, observer notifications, lifecycle management, and addon integration.
317
- *
318
- * @abstract This class should be extended, not instantiated directly
319
- * @template S The type of state managed by this Bloc
320
- * @template P The type of props that can be passed during instance creation (optional)
321
- */
322
- export declare abstract class BlocBase<S, P = unknown> {
423
+ install(plugin: BlacPlugin, config?: PluginConfig): void;
323
424
  /**
324
- * When true, every consumer will receive its own unique instance of this Bloc.
325
- * Use this when state should not be shared between components.
326
- * @default false
425
+ * Uninstall a plugin by name
426
+ * @param pluginName - The name of the plugin to uninstall
427
+ * @throws Error if plugin is not installed
327
428
  */
328
- static isolated: boolean;
329
- get isIsolated(): boolean;
429
+ uninstall(pluginName: string): void;
330
430
  /**
331
- * When true, the Bloc instance persists even when there are no active consumers.
332
- * Useful for maintaining state between component unmount/remount cycles.
333
- * @default false
431
+ * Get an installed plugin by name
432
+ * @param pluginName - The name of the plugin to retrieve
433
+ * @returns The plugin instance or undefined if not found
334
434
  */
335
- static keepAlive: boolean;
336
- get isKeepAlive(): boolean;
435
+ getPlugin(pluginName: string): BlacPlugin | undefined;
337
436
  /**
338
- * Defines how dependencies are selected from the state for efficient updates.
339
- * When provided, observers will only be notified when selected dependencies change.
437
+ * Get all installed plugins
438
+ * @returns Array of all installed plugins
340
439
  */
341
- defaultDependencySelector: DependencySelector<S> | undefined;
342
- /* Excluded from this release type: _addons */
343
- /* Excluded from this release type: _isolated */
344
- /* Excluded from this release type: _observer */
345
- /* Excluded from this release type: _blac */
440
+ getAllPlugins(): BlacPlugin[];
346
441
  /**
347
- * The unique identifier for this Bloc instance.
348
- * Defaults to the class name, but can be customized.
442
+ * Check if a plugin is installed
443
+ * @param pluginName - The name of the plugin to check
444
+ * @returns true if the plugin is installed
349
445
  */
350
- _id: BlocInstanceId;
351
- /* Excluded from this release type: _instanceRef */
352
- /* Excluded from this release type: _keepAlive */
446
+ hasPlugin(pluginName: string): boolean;
353
447
  /**
354
- * @readonly
355
- * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.
448
+ * Uninstall all plugins
356
449
  */
357
- readonly _createdAt: number;
358
- /* Excluded from this release type: _state */
359
- /* Excluded from this release type: _oldState */
450
+ clear(): void;
360
451
  /**
361
- * Props passed during Bloc instance creation.
362
- * Can be used to configure or parameterize the Bloc's behavior.
452
+ * Setup lifecycle hooks to notify plugins
363
453
  */
364
- props: P | null;
454
+ private setupLifecycleHooks;
365
455
  /**
366
- * Creates a new BlocBase instance with the given initial state.
367
- * Sets up the observer, registers with the Blac manager, and initializes addons.
368
- *
369
- * @param initialState The initial state value for this Bloc
456
+ * Notify all plugins of a lifecycle event
370
457
  */
371
- constructor(initialState: S);
458
+ private notifyPlugins;
459
+ /**
460
+ * Create plugin context with safe API access
461
+ */
462
+ private createPluginContext;
463
+ /**
464
+ * Check if plugin should be enabled based on environment
465
+ */
466
+ private shouldEnablePlugin;
372
467
  /**
373
- * Returns the current state of the Bloc.
374
- * Use this getter to access the state in a read-only manner.
375
- */
376
- get state(): S;
377
- /* Excluded from this release type: _name */
378
- /* Excluded from this release type: _updateId */
379
- /* Excluded from this release type: _dispose */
380
- /* Excluded from this release type: onDispose */
381
- /* Excluded from this release type: _consumers */
382
- /* Excluded from this release type: _addConsumer */
383
- /* Excluded from this release type: _removeConsumer */
384
- /* Excluded from this release type: _connectAddons */
385
- lastUpdate: number;
386
- /* Excluded from this release type: _pushState */
468
+ * Get current environment
469
+ */
470
+ private getCurrentEnvironment;
387
471
  }
388
472
 
389
- /**
390
- * Represents the abstract base types for Bloc and Cubit
391
- */
392
- export declare type BlocBaseAbstract = typeof Bloc<any, any, any> | typeof Cubit<any, any>;
473
+ /* Excluded from this release type: ProxyState */
393
474
 
394
- /**
395
- * Represents a constructor type for a Bloc that takes no parameters
396
- * @template B - The type of the Bloc instance
397
- */
398
- export declare type BlocClassNoParams<B> = new (args: never[]) => B;
475
+ export declare function release<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string, forceDispose?: boolean): void;
399
476
 
400
- /**
401
- * Represents a constructor type for a Bloc that can take any parameters
402
- * @template B - The type of the Bloc instance
403
- */
404
- export declare type BlocConstructor<B> = new (...args: any) => B;
405
-
406
- /**
407
- * Extracts the constructor parameters type from a BlocBase
408
- * @template B - The BlocBase type to extract the constructor parameters from
409
- */
410
- export declare type BlocConstructorParameters<B extends BlocBase<any>> = BlocConstructor<B> extends new (...args: infer P) => B ? P : never;
411
-
412
- /**
413
- * Represents a function type for determining hook dependencies based on state changes
414
- * @template B - The BlocGeneric type
415
- */
416
- export declare type BlocHookDependencyArrayFn<S> = (newState: S, oldState: S) => unknown[][];
477
+ /* Excluded from this release type: setActiveTracker */
417
478
 
418
- export declare type BlocInstanceId = string | number | undefined;
479
+ /* Excluded from this release type: shallowEqual */
419
480
 
420
- /**
421
- * Extracts the state type from either a Bloc or Cubit
422
- * @template T - The Bloc or Cubit type to extract the state from
423
- */
424
- export declare type BlocState<T> = T extends BlocBase<infer S> ? S : never;
481
+ /* Excluded from this release type: startDependency */
425
482
 
426
483
  /**
427
- * A Cubit is a simpler version of a Bloc that doesn't handle events.
428
- * It manages state and provides methods to update it.
429
- * @template S - The type of state this Cubit manages
430
- * @template P - The type of parameters (optional, defaults to null)
484
+ * Abstract base class for all state containers in BlaC.
485
+ * Provides lifecycle management, subscription handling, ref counting,
486
+ * and integration with the global registry.
487
+ *
488
+ * @template S - State type managed by this container
489
+ *
490
+ * @example
491
+ * ```ts
492
+ * class CounterBloc extends StateContainer<{ count: number }> {
493
+ * constructor() {
494
+ * super({ count: 0 });
495
+ * }
496
+ * increment() {
497
+ * this.emit({ count: this.state.count + 1 });
498
+ * }
499
+ * }
500
+ * ```
431
501
  */
432
- export declare abstract class Cubit<S, P = null> extends BlocBase<S, P> {
502
+ export declare abstract class StateContainer<S extends object = any> {
503
+ static __excludeFromDevTools: boolean;
504
+ static enableStackTrace: boolean;
505
+ private _state;
506
+ private readonly listeners;
507
+ private _disposed;
508
+ private config;
509
+ private readonly systemEventHandlers;
510
+ /** Display name for this instance */
511
+ name: string;
512
+ /** Whether debug logging is enabled */
513
+ debug: boolean;
514
+ /** Unique identifier for this instance */
515
+ instanceId: string;
516
+ /** Timestamp when this instance was created */
517
+ createdAt: number;
518
+ constructor(initialState: S);
433
519
  /**
434
- * Updates the current state and notifies all observers of the change.
435
- * If the new state is identical to the current state (using Object.is),
436
- * no update will occur.
437
- * @param state - The new state to set
520
+ * Initialize configuration for this instance.
521
+ * Called by the registry after construction.
522
+ * @param config - Configuration options
438
523
  */
439
- emit(state: S): void;
524
+ initConfig(config: StateContainerConfig): void;
525
+ /** Current state value */
526
+ get state(): Readonly<S>;
527
+ /** Whether this instance has been disposed */
528
+ get isDisposed(): boolean;
440
529
  /**
441
- * Partially updates the current state by merging it with the provided state patch.
442
- * This method is only applicable when the state is an object type.
443
- *
444
- * @param statePatch - A partial state object containing only the properties to update
445
- * @param ignoreChangeCheck - If true, skips checking if the state has actually changed
446
- * @throws {TypeError} If the state is not an object type
530
+ * Subscribe to state changes
531
+ * @param listener - Function called when state changes
532
+ * @returns Unsubscribe function
533
+ */
534
+ subscribe(listener: StateListener<S>): () => void;
535
+ /**
536
+ * Dispose this instance and clean up resources.
537
+ * Clears all listeners and emits the 'dispose' system event.
538
+ */
539
+ dispose(): void;
540
+ /**
541
+ * Emit a new state value and notify all listeners.
542
+ * @param newState - The new state value
543
+ * @protected
447
544
  */
448
- patch(statePatch: S extends object ? Partial<S> : S, ignoreChangeCheck?: boolean): void;
545
+ protected emit(newState: S): void;
546
+ private captureStackTrace;
547
+ private formatStackLine;
548
+ private cleanFilePath;
549
+ /** Timestamp of the last state update */
550
+ lastUpdateTimestamp: number;
551
+ /**
552
+ * Update state using a transform function.
553
+ * @param updater - Function that receives current state and returns new state
554
+ * @protected
555
+ */
556
+ protected update(updater: (current: S) => S): void;
557
+ /**
558
+ * Subscribe to system lifecycle events.
559
+ * @param event - The event type to listen for
560
+ * @param handler - Handler function called when event occurs
561
+ * @returns Unsubscribe function
562
+ * @protected
563
+ */
564
+ protected onSystemEvent: <E extends SystemEvent>(event: E, handler: SystemEventHandler<S, E>) => (() => void);
565
+ private emitSystemEvent;
449
566
  }
450
567
 
451
- declare type DependencySelector<S> = (newState: S, oldState?: S) => unknown[][];
452
-
453
- export declare interface GetBlocOptions<B extends BlocBase<any>> {
454
- id?: string;
455
- dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;
456
- props?: InferPropsFromGeneric<B>;
457
- onMount?: (bloc: B) => void;
458
- instanceRef?: string;
568
+ /**
569
+ * Configuration options for initializing a StateContainer instance
570
+ */
571
+ export declare interface StateContainerConfig {
572
+ /** Display name for the instance (defaults to class name) */
573
+ name?: string;
574
+ /** Enable debug logging for this instance */
575
+ debug?: boolean;
576
+ /** Custom instance identifier */
577
+ instanceId?: string;
459
578
  }
460
579
 
461
580
  /**
462
- * Extracts the props type from either a Bloc or Cubit
463
- * @template T - The Bloc or Cubit type to extract the props from
581
+ * Constructor type for StateContainer classes
582
+ * @template S - State type managed by the container
464
583
  */
465
- export declare type InferPropsFromGeneric<T> = T extends Bloc<any, any, infer P> ? P : T extends Cubit<any, infer P> ? P : never;
584
+ export declare type StateContainerConstructor<S extends object = any> = new (...args: any[]) => StateContainer<S>;
585
+
586
+ export declare type StateContainerInstance<S extends object = any> = Omit<StateContainer<S>, 'state'> & {
587
+ state: Readonly<S>;
588
+ };
466
589
 
467
590
  /**
468
- * Persist addon
591
+ * Central registry for managing StateContainer instances.
592
+ * Handles instance lifecycle, ref counting, and lifecycle event emission.
469
593
  *
470
- * @param options
471
- * @returns BlacAddon
594
+ * @example
595
+ * ```ts
596
+ * const registry = new StateContainerRegistry();
597
+ * const instance = registry.acquire(MyBloc); // ownership, must release
598
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
599
+ * registry.on('stateChanged', (container, prev, next) => {
600
+ * console.log('State changed:', prev, '->', next);
601
+ * });
602
+ * ```
472
603
  */
473
- export declare function Persist(options?: {
604
+ declare class StateContainerRegistry {
605
+ private readonly instancesByConstructor;
606
+ private readonly types;
607
+ private readonly typeConfigs;
608
+ private readonly listeners;
609
+ /**
610
+ * Register a type for lifecycle event tracking
611
+ * @param constructor - The StateContainer class constructor
612
+ */
613
+ registerType<T extends StateContainerConstructor>(constructor: T): void;
614
+ /**
615
+ * Register a StateContainer class with configuration
616
+ * @param constructor - The StateContainer class constructor
617
+ * @param isolated - Whether instances should be isolated (component-scoped)
618
+ * @throws Error if type is already registered
619
+ */
620
+ register<T extends StateContainerConstructor>(constructor: T, isolated?: boolean): void;
621
+ private ensureInstancesMap;
622
+ /**
623
+ * Get the instances Map for a specific class (public API for stats/debugging)
624
+ */
625
+ getInstancesMap<T extends StateContainerConstructor>(Type: T): Map<string, InstanceEntry>;
626
+ private trackExecutionContext;
627
+ /**
628
+ * Acquire an instance with ref counting (ownership semantics).
629
+ * Creates a new instance if one doesn't exist, or returns existing and increments ref count.
630
+ * You must call `release()` when done to decrement the ref count.
631
+ * @param Type - The StateContainer class constructor
632
+ * @param instanceKey - Instance key (defaults to 'default')
633
+ * @param options - Acquisition options
634
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
635
+ * @param options.countRef - Whether to increment ref count (default: true)
636
+ * @param options.trackExecutionContext - Whether to track cross-bloc dependency (default: false)
637
+ * @returns The state container instance
638
+ */
639
+ acquire<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string, options?: {
640
+ canCreate?: boolean;
641
+ countRef?: boolean;
642
+ trackExecutionContext?: boolean;
643
+ }): InstanceType<T>;
644
+ /**
645
+ * Borrow an existing instance without incrementing ref count (borrowing semantics).
646
+ * Tracks cross-bloc dependency for reactive updates.
647
+ * @param Type - The StateContainer class constructor
648
+ * @param instanceKey - Instance key (defaults to 'default')
649
+ * @returns The state container instance
650
+ * @throws Error if instance doesn't exist
651
+ */
652
+ borrow<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): InstanceType<T>;
653
+ /**
654
+ * Safely borrow an existing instance (borrowing semantics with error handling).
655
+ * Returns discriminated union for type-safe conditional access.
656
+ * @param Type - The StateContainer class constructor
657
+ * @param instanceKey - Instance key (defaults to 'default')
658
+ * @returns Discriminated union with either the instance or an error
659
+ */
660
+ borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): {
661
+ error: Error;
662
+ instance: null;
663
+ } | {
664
+ error: null;
665
+ instance: InstanceType<T>;
666
+ };
667
+ /**
668
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
669
+ * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.
670
+ * Tracks cross-bloc dependency for reactive updates.
671
+ *
672
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
673
+ * but don't want to claim ownership (no ref count increment).
674
+ * @param Type - The StateContainer class constructor
675
+ * @param instanceKey - Instance key (defaults to 'default')
676
+ * @returns The state container instance
677
+ */
678
+ ensure<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): InstanceType<T>;
679
+ /**
680
+ * Release a reference to an instance.
681
+ * Decrements ref count and disposes when it reaches 0 (unless keepAlive).
682
+ * @param Type - The StateContainer class constructor
683
+ * @param instanceKey - Instance key (defaults to 'default')
684
+ * @param forceDispose - Force immediate disposal regardless of ref count
685
+ */
686
+ release<T extends StateContainerConstructor>(Type: T, instanceKey?: string, forceDispose?: boolean): void;
474
687
  /**
475
- * @default 'blac'
688
+ * Get all instances of a specific type.
689
+ * @param Type - The StateContainer class constructor
690
+ * @returns Array of all instances
476
691
  */
477
- keyPrefix?: string;
692
+ getAll<T extends StateContainerConstructor>(Type: T): InstanceReadonlyState<T>[];
478
693
  /**
479
- * @default the bloc's id
694
+ * Safely iterate over all instances of a type.
695
+ * Skips disposed instances and catches callback errors.
696
+ * @param Type - The StateContainer class constructor
697
+ * @param callback - Function to call for each instance
480
698
  */
481
- keyName?: string;
699
+ forEach<T extends StateContainerConstructor>(Type: T, callback: (instance: InstanceReadonlyState<T>) => void): void;
482
700
  /**
483
- * Used when the value is not found in storage
701
+ * Clear all instances of a specific type (disposes them).
702
+ * @param Type - The StateContainer class constructor
484
703
  */
485
- defaultValue?: unknown;
704
+ clear<T extends StateContainerConstructor>(Type: T): void;
486
705
  /**
487
- * @default 'localStorage'
488
- * @see StorageType
706
+ * Get reference count for an instance.
707
+ * @param Type - The StateContainer class constructor
708
+ * @param instanceKey - Instance key (defaults to 'default')
709
+ * @returns Current ref count (0 if instance doesn't exist)
489
710
  */
490
- storageType?: StorageType;
711
+ getRefCount<T extends StateContainerConstructor>(Type: T, instanceKey?: string): number;
491
712
  /**
492
- * @default false
713
+ * Check if an instance exists.
714
+ * @param Type - The StateContainer class constructor
715
+ * @param instanceKey - Instance key (defaults to 'default')
716
+ * @returns true if instance exists
493
717
  */
494
- onError?: (e: unknown) => void;
495
- }): BlacAddon;
718
+ hasInstance<T extends StateContainerConstructor>(Type: T, instanceKey?: string): boolean;
719
+ /**
720
+ * Clear all instances from all types (for testing)
721
+ *
722
+ * Iterates all registered types and clears their instances.
723
+ * Also clears type tracking to reset the registry state.
724
+ */
725
+ clearAll(): void;
726
+ /**
727
+ * Get registry statistics for debugging.
728
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
729
+ */
730
+ getStats(): {
731
+ registeredTypes: number;
732
+ totalInstances: number;
733
+ typeBreakdown: Record<string, number>;
734
+ };
735
+ /**
736
+ * Get all registered types (for plugin system).
737
+ * @returns Array of all registered StateContainer class constructors
738
+ */
739
+ getTypes(): StateContainerConstructor[];
740
+ /**
741
+ * Subscribe to lifecycle events
742
+ * @param event - The lifecycle event to listen for
743
+ * @param listener - The listener function to call when the event occurs
744
+ * @returns Unsubscribe function
745
+ */
746
+ on<E extends LifecycleEvent>(event: E, listener: LifecycleListener<E>): () => void;
747
+ /* Excluded from this release type: emit */
748
+ }
749
+
750
+ /* Excluded from this release type: StateListener */
751
+
752
+ declare const STOP: unique symbol;
753
+
754
+ declare type StopSymbol = typeof STOP;
496
755
 
497
- declare type StorageType = 'localStorage' | 'sessionStorage';
756
+ /**
757
+ * System events emitted by StateContainer lifecycle
758
+ */
759
+ export declare type SystemEvent = 'stateChanged' | 'dispose';
760
+
761
+ /* Excluded from this release type: SystemEventHandler */
498
762
 
499
763
  /**
500
- * Extracts the state type from a BlocBase instance
501
- * @template B - The BlocBase type to extract the state from
764
+ * Payload types for each system event
765
+ * @template S - State type
502
766
  */
503
- export declare type ValueType<B extends BlocBase<any>> = B extends BlocBase<infer U> ? U : never;
767
+ export declare interface SystemEventPayloads<S> {
768
+ /** Emitted when state changes via emit() or update() */
769
+ stateChanged: {
770
+ state: S;
771
+ previousState: S;
772
+ };
773
+ /** Emitted when the instance is disposed */
774
+ dispose: void;
775
+ }
776
+
777
+ export declare const watch: WatchFn;
778
+
779
+ /**
780
+ * Combined watch function type.
781
+ */
782
+ export declare interface WatchFn extends WatchSingleFn {
783
+ <T extends readonly BlocInput[]>(blocs: T, callback: (blocs: ExtractInstances<T>) => void | StopSymbol): () => void;
784
+ }
785
+
786
+ /**
787
+ * Watch function signature for single bloc.
788
+ */
789
+ declare interface WatchSingleFn {
790
+ <T extends StateContainerConstructor>(bloc: T | BlocRef<T>, callback: (bloc: InstanceType<T>) => void | StopSymbol): () => void;
791
+ STOP: StopSymbol;
792
+ }
504
793
 
505
794
  export { }