@blac/core 2.0.0-rc-13 → 2.0.0-rc-16

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 (54) hide show
  1. package/package.json +10 -15
  2. package/src/Blac.ts +38 -71
  3. package/src/Bloc.ts +8 -9
  4. package/src/BlocBase.ts +246 -540
  5. package/src/Cubit.ts +1 -16
  6. package/src/__tests__/Blac.config.test.ts +10 -17
  7. package/src/__tests__/Bloc.event.test.ts +27 -52
  8. package/src/__tests__/BlocBase.subscription.test.ts +349 -0
  9. package/src/__tests__/Cubit.test.ts +39 -50
  10. package/src/__tests__/memory-leaks.test.ts +383 -0
  11. package/src/__tests__/plugins.test.ts +107 -97
  12. package/src/adapter/BlacAdapter.ts +347 -207
  13. package/src/adapter/ProxyFactory.ts +196 -255
  14. package/src/adapter/__tests__/BlacAdapter.test.ts +71 -77
  15. package/src/adapter/__tests__/ProxyFactory.test.ts +1 -1
  16. package/src/adapter/index.ts +0 -1
  17. package/src/errors/BlacError.ts +69 -0
  18. package/src/errors/ErrorManager.ts +101 -0
  19. package/src/errors/handleError.ts +114 -0
  20. package/src/errors/index.ts +13 -0
  21. package/src/events.ts +7 -1
  22. package/src/index.ts +7 -1
  23. package/src/lifecycle/BlocLifecycle.ts +156 -0
  24. package/src/lifecycle/index.ts +1 -0
  25. package/src/plugins/BlocPluginRegistry.ts +71 -51
  26. package/src/plugins/SystemPluginRegistry.ts +63 -13
  27. package/src/plugins/__tests__/BlocPluginRegistry.test.ts +450 -0
  28. package/src/plugins/__tests__/SystemPluginRegistry.test.ts +404 -0
  29. package/src/plugins/types.ts +32 -3
  30. package/src/subscription/README.md +132 -0
  31. package/src/subscription/SubscriptionManager.ts +395 -0
  32. package/src/subscription/__tests__/SubscriptionManager.test.ts +355 -0
  33. package/src/subscription/index.ts +2 -0
  34. package/src/subscription/types.ts +90 -0
  35. package/src/testing.ts +31 -37
  36. package/src/types.ts +4 -21
  37. package/src/utils/BatchingManager.ts +59 -0
  38. package/src/utils/RerenderLogger.ts +265 -0
  39. package/src/utils/__tests__/generateInstanceId.test.ts +104 -0
  40. package/src/utils/__tests__/shallowEqual.test.ts +171 -0
  41. package/src/utils/__tests__/uuid.test.ts +144 -0
  42. package/src/utils/generateInstanceId.ts +54 -0
  43. package/src/utils/shallowEqual.ts +1 -1
  44. package/README.md +0 -329
  45. package/dist/index.cjs.js +0 -11
  46. package/dist/index.cjs.js.map +0 -1
  47. package/dist/index.d.ts +0 -1078
  48. package/dist/index.es.js +0 -1992
  49. package/dist/index.es.js.map +0 -1
  50. package/src/BlacObserver.ts +0 -189
  51. package/src/__tests__/BlocBase.lifecycle.test.ts +0 -441
  52. package/src/__tests__/props.test.ts +0 -256
  53. package/src/adapter/ConsumerTracker.ts +0 -241
  54. package/src/adapter/__tests__/ConsumerTracker.test.ts +0 -562
package/dist/index.d.ts DELETED
@@ -1,1078 +0,0 @@
1
- import { BlacPlugin as BlacPlugin_2 } from '../core/types';
2
- import { BlocPlugin as BlocPlugin_2 } from '../core/types';
3
- import { ErrorContext as ErrorContext_2 } from '../core/types';
4
- import { PluginMetrics as PluginMetrics_2 } from '../core/types';
5
- import { PluginRegistry as PluginRegistry_2 } from '../core/types';
6
-
7
- export declare interface AdapterOptions<B extends BlocBase<any>> {
8
- id?: string;
9
- dependencies?: (bloc: B) => unknown[];
10
- props?: any;
11
- onMount?: (bloc: B) => void;
12
- onUnmount?: (bloc: B) => void;
13
- }
14
-
15
- /**
16
- * Main Blac class that manages the state management system.
17
- * Can work with singleton pattern or dependency injection.
18
- * Handles bloc lifecycle, and instance tracking.
19
- *
20
- * Key responsibilities:
21
- * - Managing bloc instances (creation, disposal, lookup)
22
- * - Handling isolated and non-isolated blocs
23
- * - Providing logging and debugging capabilities
24
- */
25
- export declare class Blac {
26
- static get instance(): Blac;
27
- /** Timestamp when the instance was created */
28
- createdAt: number;
29
- static get getAllBlocs(): <B extends BlocConstructor<any>>(blocClass: B, options?: {
30
- searchIsolated?: boolean;
31
- }) => InstanceType<B>[];
32
- /** Private static configuration */
33
- private static _config;
34
- /** Get current configuration */
35
- static get config(): Readonly<BlacConfig>;
36
- /**
37
- * Set or update Blac configuration
38
- * @param config - Partial configuration to merge with existing config
39
- * @throws Error if configuration is invalid
40
- */
41
- static setConfig(config: Partial<BlacConfig>): void;
42
- /** Map storing all registered bloc instances by their class name and ID */
43
- blocInstanceMap: Map<string, BlocBase<unknown>>;
44
- /** Map storing isolated bloc instances grouped by their constructor */
45
- isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<unknown>[]>;
46
- /** Map for O(1) lookup of isolated blocs by UID */
47
- isolatedBlocIndex: Map<string, BlocBase<unknown>>;
48
- /** Map tracking UIDs to prevent memory leaks */
49
- uidRegistry: Map<string, BlocBase<unknown>>;
50
- /** Set of keep-alive blocs for controlled cleanup */
51
- keepAliveBlocs: Set<BlocBase<unknown>>;
52
- /** Flag to control whether changes should be posted to document */
53
- postChangesToDocument: boolean;
54
- /** System plugin registry */
55
- readonly plugins: SystemPluginRegistry;
56
- /**
57
- * Creates a new Blac instance.
58
- * @param options - Configuration options including singleton control
59
- */
60
- constructor(options?: {
61
- __unsafe_ignore_singleton?: boolean;
62
- });
63
- /** Flag to enable/disable logging */
64
- static enableLog: boolean;
65
- static logLevel: 'warn' | 'log';
66
- static logSpy: ((...args: unknown[]) => void) | null;
67
- /**
68
- * Logs messages to console when logging is enabled
69
- * @param args - Arguments to log
70
- */
71
- log: (...args: unknown[]) => void;
72
- static get log(): (...args: unknown[]) => void;
73
- /**
74
- * Gets the current Blac instance
75
- * @returns The Blac instance
76
- */
77
- static getInstance(): Blac;
78
- /**
79
- * Logs a warning message
80
- * @param message - Warning message
81
- * @param args - Additional arguments
82
- */
83
- warn: (message: string, ...args: unknown[]) => void;
84
- static get warn(): (message: string, ...args: unknown[]) => void;
85
- /**
86
- * Logs an error message
87
- * @param message - Error message
88
- * @param args - Additional arguments
89
- */
90
- error: (message: string, ...args: unknown[]) => void;
91
- static get error(): (message: string, ...args: unknown[]) => void;
92
- /**
93
- * Resets the Blac instance to a new one, disposing non-keepAlive blocs
94
- * from the old instance.
95
- */
96
- resetInstance: () => void;
97
- static resetInstance: () => void;
98
- /**
99
- * Disposes of a bloc instance by removing it from the appropriate registry
100
- * @param bloc - The bloc instance to dispose
101
- */
102
- disposeBloc: (bloc: BlocBase<unknown>) => void;
103
- static get disposeBloc(): (bloc: BlocBase<unknown>) => void;
104
- /**
105
- * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
106
- * @param blocClassName - The name of the bloc class
107
- * @param id - The instance ID
108
- * @returns A unique key string in the format "className:id"
109
- */
110
- createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string;
111
- /**
112
- * Unregister a bloc instance from the main registry
113
- * @param bloc - The bloc instance to unregister
114
- */
115
- unregisterBlocInstance(bloc: BlocBase<unknown>): void;
116
- /**
117
- * Registers a bloc instance in the main registry
118
- * @param bloc - The bloc instance to register
119
- */
120
- registerBlocInstance(bloc: BlocBase<unknown>): void;
121
- /**
122
- * Finds a registered bloc instance by its class and ID
123
- * @param blocClass - The bloc class to search for
124
- * @param id - The instance ID
125
- * @returns The found bloc instance or undefined if not found
126
- */
127
- findRegisteredBlocInstance<B extends BlocConstructor<any>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
128
- /**
129
- * Registers an isolated bloc instance in the isolated registry
130
- * @param bloc - The isolated bloc instance to register
131
- */
132
- registerIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
133
- /**
134
- * Unregister an isolated bloc instance from the isolated registry
135
- * @param bloc - The isolated bloc instance to unregister
136
- */
137
- unregisterIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
138
- /**
139
- * Finds an isolated bloc instance by its class and ID (O(n) lookup)
140
- */
141
- findIsolatedBlocInstance<B extends BlocConstructor<any>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
142
- /**
143
- * Finds an isolated bloc instance by UID (O(1) lookup)
144
- */
145
- findIsolatedBlocInstanceByUid<B extends BlocBase<unknown>>(uid: string): B | undefined;
146
- /**
147
- * Creates a new bloc instance and registers it in the appropriate registry
148
- * @param blocClass - The bloc class to instantiate
149
- * @param id - The instance ID
150
- * @param props - Properties to pass to the bloc constructor
151
- * @param instanceRef - Optional reference string for the instance
152
- * @returns The newly created bloc instance
153
- */
154
- createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
155
- activateBloc: (bloc: BlocBase<unknown>) => void;
156
- static get activateBloc(): (bloc: BlocBase<unknown>) => void;
157
- /**
158
- * Gets or creates a bloc instance based on the provided class and options.
159
- * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
160
- *
161
- * @param blocClass - The bloc class to get or create
162
- * @param options - Options including:
163
- * - id: The instance ID (defaults to class name if not provided)
164
- * - props: Properties to pass to the bloc constructor
165
- * - instanceRef: Optional reference string for the instance
166
- * @returns The bloc instance
167
- */
168
- getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
169
- static get getBloc(): <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
170
- /**
171
- * Gets a bloc instance or throws an error if it doesn't exist
172
- * @param blocClass - The bloc class to get
173
- * @param options - Options including:
174
- * - id: The instance ID (defaults to class name if not provided)
175
- * - props: Properties to pass to the bloc constructor
176
- * - instanceRef: Optional reference string for the instance
177
- */
178
- getBlocOrThrow: <B extends BlocConstructor<any>>(blocClass: B, options?: {
179
- id?: BlocInstanceId;
180
- props?: InferPropsFromGeneric<B>;
181
- instanceRef?: string;
182
- }) => InstanceType<B>;
183
- static get getBlocOrThrow(): <B extends BlocConstructor<any>>(blocClass: B, options?: {
184
- id?: BlocInstanceId;
185
- props?: InferPropsFromGeneric<B> | undefined;
186
- instanceRef?: string;
187
- }) => InstanceType<B>;
188
- /**
189
- * Gets all instances of a specific bloc class
190
- * @param blocClass - The bloc class to search for
191
- * @param options - Options including:
192
- * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
193
- * @returns Array of matching bloc instances
194
- */
195
- getAllBlocs: <B extends BlocConstructor<any>>(blocClass: B, options?: {
196
- searchIsolated?: boolean;
197
- }) => InstanceType<B>[];
198
- /**
199
- * Disposes all keep-alive blocs of a specific type
200
- * @param blocClass - The bloc class to dispose
201
- */
202
- disposeKeepAliveBlocs: <B extends BlocConstructor<any>>(blocClass?: B) => void;
203
- static get disposeKeepAliveBlocs(): <B extends BlocConstructor<any>>(blocClass?: B | undefined) => void;
204
- /**
205
- * Disposes all blocs matching a pattern
206
- * @param predicate - Function to test each bloc for disposal
207
- */
208
- disposeBlocs: (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
209
- static get disposeBlocs(): (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
210
- /**
211
- * Gets memory usage statistics for debugging
212
- */
213
- getMemoryStats: () => {
214
- totalBlocs: number;
215
- registeredBlocs: number;
216
- isolatedBlocs: number;
217
- keepAliveBlocs: number;
218
- isolatedBlocTypes: number;
219
- };
220
- static get getMemoryStats(): () => {
221
- totalBlocs: number;
222
- registeredBlocs: number;
223
- isolatedBlocs: number;
224
- keepAliveBlocs: number;
225
- isolatedBlocTypes: number;
226
- };
227
- /**
228
- * Validates consumer references and cleans up orphaned consumers
229
- */
230
- validateConsumers: () => void;
231
- static get validateConsumers(): () => void;
232
- /**
233
- * Bootstrap the Blac instance and all plugins
234
- */
235
- bootstrap(): void;
236
- /**
237
- * Shutdown the Blac instance and all plugins
238
- */
239
- shutdown(): void;
240
- }
241
-
242
- /**
243
- * BlacAdapter orchestrates the connection between Bloc instances and React components.
244
- * It manages dependency tracking, lifecycle hooks, and proxy creation.
245
- */
246
- export declare class BlacAdapter<B extends BlocConstructor<BlocBase<any>>> {
247
- readonly id: string;
248
- readonly blocConstructor: B;
249
- readonly componentRef: {
250
- current: object;
251
- };
252
- blocInstance: InstanceType<B>;
253
- private consumerTracker;
254
- private static propsOwners;
255
- private lastProps?;
256
- unmountTime: number;
257
- mountTime: number;
258
- private dependencyValues?;
259
- private isUsingDependencies;
260
- private hasMounted;
261
- private mountCount;
262
- options?: AdapterOptions<InstanceType<B>>;
263
- constructor(instanceProps: {
264
- componentRef: {
265
- current: object;
266
- };
267
- blocConstructor: B;
268
- }, options?: typeof BlacAdapter.options);
269
- trackAccess(consumerRef: object, type: 'state' | 'class', path: string, value?: any): void;
270
- getConsumerDependencies(consumerRef: object): DependencyArray | null;
271
- shouldNotifyConsumer(consumerRef: object, changedPaths: Set<string>): boolean;
272
- updateLastNotified(consumerRef: object): void;
273
- resetConsumerTracking(): void;
274
- createStateProxy: <T extends object>(props: {
275
- target: T;
276
- }) => T;
277
- createClassProxy: <T extends object>(props: {
278
- target: T;
279
- }) => T;
280
- updateBlocInstance(): InstanceType<B>;
281
- createSubscription: (options: {
282
- onChange: () => void;
283
- }) => () => void;
284
- mount: () => void;
285
- unmount: () => void;
286
- getProxyState: (state: BlocState<InstanceType<B>>) => BlocState<InstanceType<B>>;
287
- getProxyBlocInstance: () => InstanceType<B>;
288
- get calledOnMount(): boolean;
289
- updateProps(props: any): void;
290
- private hasDependencyValuesChanged;
291
- }
292
-
293
- /**
294
- * Configuration options for the Blac instance
295
- */
296
- export declare interface BlacConfig {
297
- /** Whether to expose the Blac instance globally */
298
- exposeBlacInstance?: boolean;
299
- /**
300
- * Whether to enable proxy dependency tracking for automatic re-render optimization.
301
- * When false, state changes always cause re-renders unless dependencies are manually specified.
302
- * Default: true
303
- */
304
- proxyDependencyTracking?: boolean;
305
- }
306
-
307
- /**
308
- * Interface for Blac instance management
309
- */
310
- export declare interface BlacInstanceManager {
311
- getInstance(): Blac;
312
- setInstance(instance: Blac): void;
313
- resetInstance(): void;
314
- }
315
-
316
- /**
317
- * A class that manages observers for a Bloc's state changes
318
- * @template S - The type of state being observed
319
- */
320
- export declare class BlacObservable<S = unknown> {
321
- /** The Bloc instance this observable is associated with */
322
- bloc: BlocBase<S>;
323
- /**
324
- * Creates a new BlacObservable instance
325
- * @param bloc - The Bloc instance to observe
326
- */
327
- constructor(bloc: BlocBase<S>);
328
- private _observers;
329
- /**
330
- * Gets the number of active observers
331
- * @returns The number of observers currently subscribed
332
- */
333
- get size(): number;
334
- /**
335
- * Gets the set of all observers
336
- * @returns The Set of all BlacObserver instances
337
- */
338
- get observers(): Set<BlacObserver<S>>;
339
- /**
340
- * Subscribes an observer to state changes
341
- * @param observer - The observer to subscribe
342
- * @returns A function that can be called to unsubscribe the observer
343
- */
344
- subscribe(observer: BlacObserver<S>): () => void;
345
- /**
346
- * Unsubscribes an observer from state changes
347
- * @param observer - The observer to unsubscribe
348
- */
349
- unsubscribe(observer: BlacObserver<S>): void;
350
- /**
351
- * Notifies all observers of a state change
352
- * @param newState - The new state value
353
- * @param oldState - The previous state value
354
- * @param action - Optional action that triggered the state change
355
- */
356
- notify(newState: S, oldState: S, action?: unknown): void;
357
- /**
358
- * Clears the observer set
359
- */
360
- clear(): void;
361
- }
362
-
363
- /**
364
- * Represents an observer that can subscribe to state changes in a Bloc
365
- * @template S - The type of state being observed
366
- */
367
- export declare type BlacObserver<S> = {
368
- /** Function to be called when state changes */
369
- fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;
370
- /** Optional function to determine if the observer should be notified of state changes */
371
- dependencyArray?: BlocHookDependencyArrayFn<S>;
372
- /** Dispose function for the observer */
373
- dispose?: () => void;
374
- /** Cached state values used for dependency comparison */
375
- lastState?: unknown[];
376
- /** Unique identifier for the observer */
377
- id: string;
378
- };
379
-
380
- /**
381
- * System-wide plugin that observes all blocs
382
- */
383
- export declare interface BlacPlugin extends Plugin_2 {
384
- beforeBootstrap?(): void;
385
- afterBootstrap?(): void;
386
- beforeShutdown?(): void;
387
- afterShutdown?(): void;
388
- onBlocCreated?(bloc: BlocBase<any>): void;
389
- onBlocDisposed?(bloc: BlocBase<any>): void;
390
- onStateChanged?(bloc: BlocBase<any>, previousState: any, currentState: any): void;
391
- onEventAdded?(bloc: Bloc<any, any>, event: any): void;
392
- onError?(error: Error, bloc: BlocBase<unknown>, context: ErrorContext): void;
393
- }
394
-
395
- export declare abstract class Bloc<S, // State type
396
- A extends BlocEventConstraint = BlocEventConstraint, // Base Action/Event type with proper constraints
397
- P = unknown> extends BlocBase<S, P> {
398
- readonly eventHandlers: Map<new (...args: any[]) => A, (event: A, emit: (newState: S) => void) => void | Promise<void>>;
399
- /* Excluded from this release type: _eventQueue */
400
- /* Excluded from this release type: _isProcessingEvent */
401
- /**
402
- * Registers an event handler for a specific event type.
403
- * This method is typically called in the constructor of a derived Bloc class.
404
- * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).
405
- * @param handler A function that processes the event and can emit new states.
406
- * The 'event' parameter in the handler will be typed to the specific eventConstructor.
407
- */
408
- protected on<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
409
- /**
410
- * Dispatches an action/event to the Bloc.
411
- * Events are queued and processed sequentially to prevent race conditions.
412
- * @param action The action/event instance to be processed.
413
- */
414
- add: (action: A) => Promise<void>;
415
- /* Excluded from this release type: _processEventQueue */
416
- /* Excluded from this release type: _processEvent */
417
- }
418
-
419
- /**
420
- * Base class for both Blocs and Cubits that provides core state management functionality.
421
- * Handles state transitions, observer notifications, lifecycle management, and addon integration.
422
- *
423
- * @abstract This class should be extended, not instantiated directly
424
- * @template S The type of state managed by this Bloc
425
- * @template P The type of props that can be passed during instance creation (optional)
426
- */
427
- export declare abstract class BlocBase<S, P = unknown> {
428
- uid: string;
429
- /**
430
- * When true, every consumer will receive its own unique instance of this Bloc.
431
- * Use this when state should not be shared between components.
432
- * @default false
433
- */
434
- static isolated: boolean;
435
- get isIsolated(): boolean;
436
- /**
437
- * When true, the Bloc instance persists even when there are no active consumers.
438
- * Useful for maintaining state between component unmount/remount cycles.
439
- * @default false
440
- */
441
- static keepAlive: boolean;
442
- get isKeepAlive(): boolean;
443
- /**
444
- * Defines how dependencies are selected from the state for efficient updates.
445
- * When provided, observers will only be notified when selected dependencies change.
446
- */
447
- defaultDependencySelector: DependencySelector<S> | undefined;
448
- /* Excluded from this release type: _isolated */
449
- /* Excluded from this release type: _observer */
450
- /**
451
- * The unique identifier for this Bloc instance.
452
- * Defaults to the class name, but can be customized.
453
- */
454
- _id: BlocInstanceId;
455
- /* Excluded from this release type: _instanceRef */
456
- /* Excluded from this release type: _keepAlive */
457
- /**
458
- * @readonly
459
- * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.
460
- */
461
- readonly _createdAt: number;
462
- /* Excluded from this release type: _disposalState */
463
- /* Excluded from this release type: _disposalRequestTime */
464
- /* Excluded from this release type: _state */
465
- /* Excluded from this release type: _oldState */
466
- /**
467
- * Props passed during Bloc instance creation.
468
- * Can be used to configure or parameterize the Bloc's behavior.
469
- */
470
- props: P | null;
471
- /* Excluded from this release type: _batchingLock */
472
- /* Excluded from this release type: _pendingUpdates */
473
- /* Excluded from this release type: _consumerRefs */
474
- /**
475
- * Plugin registry for this bloc instance
476
- */
477
- protected _plugins: BlocPluginRegistry<S, any>;
478
- /* Excluded from this release type: _validateConsumers */
479
- /**
480
- * Creates a new BlocBase instance with the given initial state.
481
- * Sets up the observer, registers with the Blac manager, and initializes addons.
482
- *
483
- * @param initialState The initial state value for this Bloc
484
- */
485
- constructor(initialState: S);
486
- /**
487
- * Returns the current state of the Bloc.
488
- * Use this getter to access the state in a read-only manner.
489
- * Returns the state even during transitional lifecycle states for React compatibility.
490
- */
491
- get state(): S;
492
- /**
493
- * Returns whether this Bloc instance has been disposed.
494
- * @returns true if the bloc is in DISPOSED state
495
- */
496
- get isDisposed(): boolean;
497
- /* Excluded from this release type: _name */
498
- /* Excluded from this release type: _updateId */
499
- /* Excluded from this release type: _atomicStateTransition */
500
- /* Excluded from this release type: _dispose */
501
- /* Excluded from this release type: onDispose */
502
- /* Excluded from this release type: _consumers */
503
- /* Excluded from this release type: _addConsumer */
504
- /* Excluded from this release type: _removeConsumer */
505
- /* Excluded from this release type: _disposalHandler */
506
- /* Excluded from this release type: _setDisposalHandler */
507
- /* Excluded from this release type: _scheduleDisposal */
508
- lastUpdate: number;
509
- /* Excluded from this release type: _batchingEnabled */
510
- /* Excluded from this release type: _pushState */
511
- /* Excluded from this release type: _notifyObservers */
512
- /**
513
- * Enables batching for multiple state updates
514
- * @param batchFn Function to execute with batching enabled
515
- */
516
- batch: <T>(batchFn: () => T) => T;
517
- /**
518
- * Add a plugin to this bloc instance
519
- */
520
- addPlugin(plugin: BlocPlugin<S, any>): void;
521
- /**
522
- * Remove a plugin from this bloc instance
523
- */
524
- removePlugin(pluginName: string): boolean;
525
- /**
526
- * Get a plugin by name
527
- */
528
- getPlugin(pluginName: string): BlocPlugin<S, any> | undefined;
529
- /**
530
- * Get all plugins
531
- */
532
- getPlugins(): ReadonlyArray<BlocPlugin<S, any>>;
533
- /* Excluded from this release type: _activatePlugins */
534
- }
535
-
536
- /**
537
- * Represents the abstract base types for Bloc and Cubit
538
- */
539
- export declare type BlocBaseAbstract = typeof Bloc<any, any, any> | typeof Cubit<any, any>;
540
-
541
- /**
542
- * Represents a constructor type for a Bloc that takes no parameters
543
- * @template B - The type of the Bloc instance
544
- */
545
- export declare type BlocClassNoParams<B> = new (args: never[]) => B;
546
-
547
- /**
548
- * Represents a constructor type for a Bloc that can take any parameters
549
- * @template B - The type of the Bloc instance
550
- */
551
- export declare type BlocConstructor<B> = (new (...args: any) => B) & {
552
- isolated?: boolean;
553
- keepAlive?: boolean;
554
- };
555
-
556
- /**
557
- * Extracts the constructor parameters type from a BlocBase
558
- * @template B - The BlocBase type to extract the constructor parameters from
559
- */
560
- export declare type BlocConstructorParameters<B extends BlocBase<any>> = BlocConstructor<B> extends new (...args: infer P) => B ? P : never;
561
-
562
- /**
563
- * Error boundary interface for Bloc error handling
564
- */
565
- export declare interface BlocErrorBoundary<S, A extends BlocEventConstraint> {
566
- onError: (error: Error, event: A, currentState: S, bloc: {
567
- name: string;
568
- id: string;
569
- }) => void | Promise<void>;
570
- shouldRethrow?: (error: Error, event: A) => boolean;
571
- }
572
-
573
- /**
574
- * Enhanced constraint for Bloc events - must be objects with proper constructor
575
- */
576
- export declare type BlocEventConstraint = object;
577
-
578
- /**
579
- * Function type for determining dependencies that trigger re-renders
580
- * Similar to React's useEffect dependency array - if any dependency changes, a re-render is triggered
581
- * @template S The state type
582
- * @template I The bloc instance type
583
- * @param currentState The current state
584
- * @param previousState The previous state (undefined on first call)
585
- * @param instance The bloc instance
586
- * @returns Array of dependencies - if any dependency changes, a re-render is triggered
587
- */
588
- export declare type BlocHookDependencyArrayFn<S, I = any> = (currentState: S, previousState: S | undefined, instance: I) => unknown[];
589
-
590
- export declare type BlocInstanceId = string | number | undefined;
591
-
592
- /**
593
- * Enum representing the lifecycle states of a Bloc instance
594
- * Used for atomic state transitions to prevent race conditions
595
- */
596
- export declare enum BlocLifecycleState {
597
- ACTIVE = "active",
598
- DISPOSAL_REQUESTED = "disposal_requested",
599
- DISPOSING = "disposing",
600
- DISPOSED = "disposed"
601
- }
602
-
603
- /**
604
- * Bloc-specific plugin that can transform behavior
605
- */
606
- export declare interface BlocPlugin<TState = any, TEvent = never> extends Plugin_2 {
607
- transformState?(previousState: TState, nextState: TState): TState;
608
- transformEvent?(event: TEvent): TEvent | null;
609
- onAttach?(bloc: BlocBase<TState, any>): void;
610
- onDetach?(): void;
611
- onStateChange?(previousState: TState, currentState: TState): void;
612
- onEvent?(event: TEvent): void;
613
- onError?(error: Error, context: ErrorContext): void;
614
- }
615
-
616
- /**
617
- * Registry for bloc-specific plugins
618
- */
619
- export declare class BlocPluginRegistry<TState, TEvent = never> implements PluginRegistry_2<BlocPlugin_2<TState, TEvent>> {
620
- private plugins;
621
- private executionOrder;
622
- private attached;
623
- /**
624
- * Add a bloc plugin
625
- */
626
- add(plugin: BlocPlugin_2<TState, TEvent>): void;
627
- /**
628
- * Remove a bloc plugin
629
- */
630
- remove(pluginName: string): boolean;
631
- /**
632
- * Get a plugin by name
633
- */
634
- get(pluginName: string): BlocPlugin_2<TState, TEvent> | undefined;
635
- /**
636
- * Get all plugins in execution order
637
- */
638
- getAll(): ReadonlyArray<BlocPlugin_2<TState, TEvent>>;
639
- /**
640
- * Clear all plugins
641
- */
642
- clear(): void;
643
- /**
644
- * Attach all plugins to a bloc
645
- */
646
- attach(bloc: any): void;
647
- /**
648
- * Transform state through all plugins
649
- */
650
- transformState(previousState: TState, nextState: TState): TState;
651
- /**
652
- * Transform event through all plugins
653
- */
654
- transformEvent(event: TEvent): TEvent | null;
655
- /**
656
- * Notify plugins of state change
657
- */
658
- notifyStateChange(previousState: TState, currentState: TState): void;
659
- /**
660
- * Notify plugins of event
661
- */
662
- notifyEvent(event: TEvent): void;
663
- /**
664
- * Notify plugins of error
665
- */
666
- notifyError(error: Error, context: ErrorContext_2): void;
667
- private validateCapabilities;
668
- private canReadState;
669
- private canTransformState;
670
- private canInterceptEvents;
671
- }
672
-
673
- /**
674
- * Extracts the state type from either a Bloc or Cubit
675
- * @template T - The Bloc or Cubit type to extract the state from
676
- */
677
- export declare type BlocState<T> = T extends BlocBase<infer S> ? S : never;
678
-
679
- /**
680
- * Test utilities for Blac state management
681
- */
682
- export declare class BlocTest {
683
- private static originalInstance;
684
- /**
685
- * Sets up a clean test environment
686
- */
687
- static setUp(): void;
688
- /**
689
- * Tears down the test environment and restores original state
690
- */
691
- static tearDown(): void;
692
- /**
693
- * Creates a test bloc with automatic cleanup
694
- */
695
- static createBloc<T extends BlocBase<any>>(BlocClass: new (...args: any[]) => T, ...args: any[]): T;
696
- /**
697
- * Waits for a bloc to emit a specific state
698
- */
699
- static waitForState<T extends BlocBase<S>, S>(bloc: T, predicate: (state: S) => boolean, timeout?: number): Promise<S>;
700
- /**
701
- * Expects a bloc to emit specific states in order
702
- */
703
- static expectStates<T extends BlocBase<S>, S>(bloc: T, expectedStates: S[], timeout?: number): Promise<void>;
704
- }
705
-
706
- export declare interface ConsumerInfo {
707
- id: string;
708
- lastNotified: number;
709
- hasRendered: boolean;
710
- stateAccesses: Set<string>;
711
- classAccesses: Set<string>;
712
- stateValues: Map<string, TrackedValue>;
713
- classValues: Map<string, TrackedValue>;
714
- accessCount: number;
715
- lastAccessTime: number;
716
- firstAccessTime: number;
717
- }
718
-
719
- /**
720
- * ConsumerTracker manages both consumer registration and dependency tracking.
721
- * It uses a WeakMap for automatic garbage collection when consumers are no longer referenced.
722
- */
723
- export declare class ConsumerTracker {
724
- private consumers;
725
- private registrationCount;
726
- private activeConsumers;
727
- register(consumerRef: object, consumerId: string): void;
728
- unregister(consumerRef: object): void;
729
- trackAccess(consumerRef: object, type: 'state' | 'class', path: string, value?: any): void;
730
- resetTracking(consumerRef: object): void;
731
- getDependencies(consumerRef: object): DependencyArray | null;
732
- hasValuesChanged(consumerRef: object, newState: any, newBlocInstance: any): boolean;
733
- shouldNotifyConsumer(consumerRef: object, changedPaths: Set<string>): boolean;
734
- updateLastNotified(consumerRef: object): void;
735
- getConsumerInfo(consumerRef: object): ConsumerInfo | undefined;
736
- setHasRendered(consumerRef: object, hasRendered: boolean): void;
737
- hasConsumer(consumerRef: object): boolean;
738
- getStats(): {
739
- totalRegistrations: number;
740
- activeConsumers: number;
741
- };
742
- private getValueAtPath;
743
- }
744
-
745
- declare interface ConsumerTracker_2 {
746
- trackAccess: (consumerRef: object, type: 'state' | 'class', path: string, value?: any) => void;
747
- }
748
-
749
- /**
750
- * A Cubit is a simpler version of a Bloc that doesn't handle events.
751
- * It manages state and provides methods to update it.
752
- * @template S - The type of state this Cubit manages
753
- * @template P - The type of parameters (optional, defaults to null)
754
- */
755
- export declare abstract class Cubit<S, P = null> extends BlocBase<S, P> {
756
- /* Excluded from this release type: _updateProps */
757
- /**
758
- * Optional override for props handling
759
- */
760
- protected onPropsChanged?(oldProps: P | undefined, newProps: P): void;
761
- /**
762
- * Updates the current state and notifies all observers of the change.
763
- * If the new state is identical to the current state (using Object.is),
764
- * no update will occur.
765
- * @param state - The new state to set
766
- */
767
- emit(state: S): void;
768
- /**
769
- * Partially updates the current state by merging it with the provided state patch.
770
- * This method is only applicable when the state is an object type.
771
- *
772
- * @param statePatch - A partial state object containing only the properties to update
773
- * @param ignoreChangeCheck - If true, skips checking if the state has actually changed
774
- * @throws {TypeError} If the state is not an object type
775
- */
776
- patch(statePatch: S extends object ? Partial<S> : S, ignoreChangeCheck?: boolean): void;
777
- }
778
-
779
- export declare interface DependencyArray {
780
- statePaths: string[];
781
- classPaths: string[];
782
- }
783
-
784
- declare type DependencySelector<S> = (currentState: S, previousState: S | undefined, instance: any) => unknown[];
785
-
786
- /**
787
- * Error context provided to error handlers
788
- */
789
- export declare interface ErrorContext {
790
- readonly phase: 'initialization' | 'state-change' | 'event-processing' | 'disposal';
791
- readonly operation: string;
792
- readonly metadata?: Record<string, unknown>;
793
- }
794
-
795
- /**
796
- * Cross-platform UUID v4 generator that works in all environments including React Native/Hermes
797
- * Falls back to crypto.randomUUID() when available, otherwise uses Math.random()
798
- */
799
- /**
800
- * Generates a UUID v4 string compatible with all JavaScript environments
801
- * @returns A UUID v4 string in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
802
- */
803
- export declare function generateUUID(): string;
804
-
805
- export declare interface GetBlocOptions<B extends BlocBase<unknown>> {
806
- id?: string;
807
- selector?: BlocHookDependencyArrayFn<BlocState<B>>;
808
- props?: InferPropsFromGeneric<B>;
809
- onMount?: (bloc: B) => void;
810
- instanceRef?: string;
811
- throwIfNotFound?: boolean;
812
- /** Force creation of a new instance for isolated blocs, bypassing instance lookup */
813
- forceNewInstance?: boolean;
814
- }
815
-
816
- /**
817
- * Extracts the props type from either a Bloc or Cubit
818
- * @template T - The Bloc or Cubit type to extract the props from
819
- */
820
- export declare type InferPropsFromGeneric<T> = T extends Bloc<any, any, infer P> ? P : T extends Cubit<any, infer P> ? P : never;
821
-
822
- /**
823
- * Memory leak detector for tests
824
- */
825
- export declare class MemoryLeakDetector {
826
- private initialStats;
827
- constructor();
828
- /**
829
- * Check for memory leaks and return a report
830
- */
831
- checkForLeaks(): {
832
- hasLeaks: boolean;
833
- report: string;
834
- stats: ReturnType<typeof Blac.getMemoryStats>;
835
- };
836
- }
837
-
838
- /**
839
- * Mock Bloc for testing
840
- */
841
- export declare class MockBloc<S, A extends BlocEventConstraint = BlocEventConstraint> extends Bloc<S, A> {
842
- private mockHandlers;
843
- constructor(initialState: S);
844
- /**
845
- * Mock an event handler for testing
846
- */
847
- mockEventHandler<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
848
- /**
849
- * Get the number of registered handlers
850
- */
851
- getHandlerCount(): number;
852
- /**
853
- * Check if a handler is registered for an event type
854
- */
855
- hasHandler(eventConstructor: new (...args: any[]) => A): boolean;
856
- }
857
-
858
- /**
859
- * Mock Cubit for testing
860
- */
861
- export declare class MockCubit<S> extends Cubit<S> {
862
- private stateHistory;
863
- constructor(initialState: S);
864
- /**
865
- * Override emit to track state history
866
- */
867
- emit(newState: S): void;
868
- /**
869
- * Get the history of all states
870
- */
871
- getStateHistory(): S[];
872
- /**
873
- * Clear state history
874
- */
875
- clearStateHistory(): void;
876
- }
877
-
878
- /**
879
- * Base interface for all plugins
880
- */
881
- declare interface Plugin_2 {
882
- readonly name: string;
883
- readonly version: string;
884
- readonly capabilities?: PluginCapabilities;
885
- }
886
- export { Plugin_2 as Plugin }
887
-
888
- /**
889
- * Plugin capabilities for security model
890
- */
891
- export declare interface PluginCapabilities {
892
- readonly readState: boolean;
893
- readonly transformState: boolean;
894
- readonly interceptEvents: boolean;
895
- readonly persistData: boolean;
896
- readonly accessMetadata: boolean;
897
- }
898
-
899
- /**
900
- * Plugin execution context for performance monitoring
901
- */
902
- export declare interface PluginExecutionContext {
903
- readonly pluginName: string;
904
- readonly hookName: string;
905
- readonly startTime: number;
906
- readonly blocName?: string;
907
- readonly blocId?: string;
908
- }
909
-
910
- /**
911
- * Plugin metrics for monitoring
912
- */
913
- export declare interface PluginMetrics {
914
- readonly executionTime: number;
915
- readonly executionCount: number;
916
- readonly errorCount: number;
917
- readonly lastError?: Error;
918
- readonly lastExecutionTime?: number;
919
- }
920
-
921
- /**
922
- * Plugin registry interface
923
- */
924
- export declare interface PluginRegistry<T extends Plugin_2> {
925
- add(plugin: T): void;
926
- remove(pluginName: string): boolean;
927
- get(pluginName: string): T | undefined;
928
- getAll(): ReadonlyArray<T>;
929
- clear(): void;
930
- }
931
-
932
- export declare class PropsUpdated<P = any> {
933
- readonly props: P;
934
- constructor(props: P);
935
- }
936
-
937
- export declare class ProxyFactory {
938
- static createStateProxy<T extends object>(options: {
939
- target: T;
940
- consumerRef: object;
941
- consumerTracker: ConsumerTracker_2;
942
- path?: string;
943
- }): T;
944
- static createClassProxy<T extends object>(options: {
945
- target: T;
946
- consumerRef: object;
947
- consumerTracker: ConsumerTracker_2;
948
- }): T;
949
- static getProxyState<B extends BlocBase<any>>(options: {
950
- state: BlocState<B>;
951
- consumerRef: object;
952
- consumerTracker: ConsumerTracker_2;
953
- }): BlocState<B>;
954
- static getProxyBlocInstance<B extends BlocBase<any>>(options: {
955
- blocInstance: B;
956
- consumerRef: object;
957
- consumerTracker: ConsumerTracker_2;
958
- }): B;
959
- static getStats(): {
960
- totalProxies: number;
961
- cacheEfficiency: string;
962
- lifetime: string;
963
- proxiesPerSecond: string;
964
- stateProxiesCreated: number;
965
- classProxiesCreated: number;
966
- cacheHits: number;
967
- cacheMisses: number;
968
- propertyAccesses: number;
969
- nestedProxiesCreated: number;
970
- totalProxiesCreated: number;
971
- createdAt: number;
972
- };
973
- static resetStats(): void;
974
- }
975
-
976
- /**
977
- * Sets a custom instance manager (useful for testing or advanced patterns)
978
- */
979
- export declare function setBlacInstanceManager(manager: BlacInstanceManager): void;
980
-
981
- /**
982
- * Performs a shallow equality comparison between two values.
983
- * For objects, it checks if all top-level properties are equal using Object.is.
984
- * @param a First value to compare
985
- * @param b Second value to compare
986
- * @returns true if values are shallowly equal, false otherwise
987
- */
988
- export declare function shallowEqual(a: any, b: any): boolean;
989
-
990
- /**
991
- * Result of an atomic state transition operation
992
- */
993
- export declare interface StateTransitionResult {
994
- success: boolean;
995
- currentState: BlocLifecycleState;
996
- previousState: BlocLifecycleState;
997
- }
998
-
999
- /**
1000
- * Registry for system-wide plugins
1001
- */
1002
- export declare class SystemPluginRegistry implements PluginRegistry_2<BlacPlugin_2> {
1003
- private plugins;
1004
- private metrics;
1005
- private executionOrder;
1006
- /**
1007
- * Add a system plugin
1008
- */
1009
- add(plugin: BlacPlugin_2): void;
1010
- /**
1011
- * Remove a system plugin
1012
- */
1013
- remove(pluginName: string): boolean;
1014
- /**
1015
- * Get a plugin by name
1016
- */
1017
- get(pluginName: string): BlacPlugin_2 | undefined;
1018
- /**
1019
- * Get all plugins in execution order
1020
- */
1021
- getAll(): ReadonlyArray<BlacPlugin_2>;
1022
- /**
1023
- * Clear all plugins
1024
- */
1025
- clear(): void;
1026
- /**
1027
- * Execute a hook on all plugins
1028
- */
1029
- executeHook(hookName: keyof BlacPlugin_2, args: unknown[], errorHandler?: (error: Error, plugin: BlacPlugin_2) => void): void;
1030
- /**
1031
- * Bootstrap all plugins
1032
- */
1033
- bootstrap(): void;
1034
- /**
1035
- * Shutdown all plugins
1036
- */
1037
- shutdown(): void;
1038
- /**
1039
- * Notify plugins of bloc creation
1040
- */
1041
- notifyBlocCreated(bloc: BlocBase<any>): void;
1042
- /**
1043
- * Notify plugins of bloc disposal
1044
- */
1045
- notifyBlocDisposed(bloc: BlocBase<any>): void;
1046
- /**
1047
- * Notify plugins of state change
1048
- */
1049
- notifyStateChanged(bloc: BlocBase<any>, previousState: any, currentState: any): void;
1050
- /**
1051
- * Notify plugins of event addition
1052
- */
1053
- notifyEventAdded(bloc: Bloc<any, any>, event: any): void;
1054
- /**
1055
- * Notify plugins of errors
1056
- */
1057
- notifyError(error: Error, bloc: BlocBase<unknown>, context: ErrorContext_2): void;
1058
- /**
1059
- * Get metrics for a plugin
1060
- */
1061
- getMetrics(pluginName: string): Map<string, PluginMetrics_2> | undefined;
1062
- private initializeMetrics;
1063
- private recordSuccess;
1064
- private recordError;
1065
- }
1066
-
1067
- export declare interface TrackedValue {
1068
- value: any;
1069
- lastAccessTime: number;
1070
- }
1071
-
1072
- /**
1073
- * Extracts the state type from a BlocBase instance
1074
- * @template B - The BlocBase type to extract the state from
1075
- */
1076
- export declare type ValueType<B extends BlocBase<any>> = B extends BlocBase<infer U> ? U : never;
1077
-
1078
- export { }