@blac/core 2.0.5 → 2.0.7

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 (55) hide show
  1. package/README.md +98 -129
  2. package/dist/StateContainerRegistry-COxgpYAw.cjs +601 -0
  3. package/dist/StateContainerRegistry-COxgpYAw.cjs.map +1 -0
  4. package/dist/StateContainerRegistry-DS_wyKck.js +566 -0
  5. package/dist/StateContainerRegistry-DS_wyKck.js.map +1 -0
  6. package/dist/branded-DndTHjv2.cjs +18 -0
  7. package/dist/branded-DndTHjv2.cjs.map +1 -0
  8. package/dist/branded-mwGzzPF1.js +13 -0
  9. package/dist/branded-mwGzzPF1.js.map +1 -0
  10. package/dist/config-BD9MkJ0k.js +42 -0
  11. package/dist/config-BD9MkJ0k.js.map +1 -0
  12. package/dist/config-DTuCbHcJ.cjs +101 -0
  13. package/dist/config-DTuCbHcJ.cjs.map +1 -0
  14. package/dist/constants.d.cts +73 -0
  15. package/dist/constants.d.ts +0 -8
  16. package/dist/core/Cubit.d.ts +0 -17
  17. package/dist/core/StateContainer.d.ts +37 -88
  18. package/dist/core/StateContainerRegistry.d.ts +2 -3
  19. package/dist/core/symbols.d.ts +2 -0
  20. package/dist/debug.cjs +12 -0
  21. package/dist/debug.d.cts +35 -0
  22. package/dist/debug.js +3 -0
  23. package/dist/decorators/blac.d.ts +3 -10
  24. package/dist/index.cjs +175 -1613
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +2 -4
  27. package/dist/index.d.ts +2 -4
  28. package/dist/index.js +142 -1564
  29. package/dist/index.js.map +1 -1
  30. package/dist/plugin/BlacPlugin.d.ts +34 -3
  31. package/dist/plugins.cjs +4 -0
  32. package/dist/plugins.d.cts +25 -0
  33. package/dist/plugins.js +2 -0
  34. package/dist/registry/management.d.ts +1 -1
  35. package/dist/resolve-dependencies-8xtWXd53.js +648 -0
  36. package/dist/resolve-dependencies-8xtWXd53.js.map +1 -0
  37. package/dist/resolve-dependencies-DJ2UBTq1.cjs +773 -0
  38. package/dist/resolve-dependencies-DJ2UBTq1.cjs.map +1 -0
  39. package/dist/tracked-12W-U7tq.js +181 -0
  40. package/dist/tracked-12W-U7tq.js.map +1 -0
  41. package/dist/tracked-DLnq137F.cjs +216 -0
  42. package/dist/tracked-DLnq137F.cjs.map +1 -0
  43. package/dist/tracking.cjs +18 -0
  44. package/dist/tracking.d.cts +9 -0
  45. package/dist/tracking.js +2 -0
  46. package/dist/types/utilities.d.ts +0 -1
  47. package/dist/types.cjs +3 -0
  48. package/dist/types.d.cts +8 -0
  49. package/dist/types.js +2 -0
  50. package/dist/utils/idGenerator.d.ts +0 -16
  51. package/dist/utils/static-props.d.ts +0 -7
  52. package/dist/watch-entry.cjs +7 -0
  53. package/dist/watch-entry.d.cts +26 -0
  54. package/dist/watch-entry.js +2 -0
  55. package/package.json +58 -3
package/dist/index.cjs CHANGED
@@ -1,4 +1,8 @@
1
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_StateContainerRegistry = require("./StateContainerRegistry-COxgpYAw.cjs");
3
+ const require_tracked = require("./tracked-DLnq137F.cjs");
4
+ const require_config = require("./config-DTuCbHcJ.cjs");
5
+ const require_branded = require("./branded-DndTHjv2.cjs");
2
6
  //#region src/utils/idGenerator.ts
3
7
  /**
4
8
  * Generate simple ID with timestamp and random (no counter tracking)
@@ -18,608 +22,13 @@ function generateSimpleId(prefix, affix) {
18
22
  if (affix) return `${prefix}:${affix}`;
19
23
  return `${prefix}:${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
20
24
  }
21
- /**
22
- * Generate a unique isolated instance key
23
- * Uses base36 encoding for compact, URL-safe identifiers
24
- *
25
- * Format: "isolated-{9-char-random-string}"
26
- * Example: "isolated-k7x2m9p4q"
27
- *
28
- * @returns A unique isolated instance key
29
- */
30
- function generateIsolatedKey() {
31
- return `isolated-${Math.random().toString(36).slice(2, 11)}`;
32
- }
33
-
34
- //#endregion
35
- //#region src/constants.ts
36
- /**
37
- * Default configuration constants for BlaC
38
- *
39
- * Centralized location for all magic numbers and default values.
40
- */
41
- /**
42
- * Default configuration constants for BlaC
43
- */
44
- const BLAC_DEFAULTS = {
45
- DEFAULT_INSTANCE_KEY: "default",
46
- MAX_GETTER_DEPTH: 10,
47
- CLEANUP_INTERVAL_MS: 3e4,
48
- WEAKREF_CLEANUP_INTERVAL_MS: 1e4,
49
- MAX_SUBSCRIPTIONS: 1e3,
50
- MAX_SUBSCRIPTIONS_HIGH_PERF: 1e4,
51
- PIPELINE_TIMEOUT_MS: 5e3,
52
- CLEANUP_INTERVAL_HIGH_PERF_MS: 5e3,
53
- MAX_PIPELINE_STAGES: 30
54
- };
55
- /**
56
- * Static property names for StateContainer classes
57
- * Used for feature flags and configuration on bloc classes
58
- */
59
- const BLAC_STATIC_PROPS = {
60
- ISOLATED: "isolated",
61
- KEEP_ALIVE: "keepAlive",
62
- EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools"
63
- };
64
- /**
65
- * Standard error message prefix
66
- */
67
- const BLAC_ERROR_PREFIX = "[BlaC]";
68
-
69
- //#endregion
70
- //#region src/plugin/PluginManager.ts
71
- /**
72
- * Manages plugin lifecycle for the BlaC state management system.
73
- * Plugins receive notifications about state container lifecycle events.
74
- *
75
- * @example
76
- * ```ts
77
- * const manager = createPluginManager(registry);
78
- * manager.install(myPlugin, { environment: 'development' });
79
- * ```
80
- */
81
- var PluginManager = class {
82
- /**
83
- * Create a new PluginManager
84
- * @param registry - The StateContainerRegistry to monitor for lifecycle events
85
- */
86
- constructor(registry) {
87
- this.plugins = /* @__PURE__ */ new Map();
88
- this.registry = registry;
89
- this.setupLifecycleHooks();
90
- }
91
- /**
92
- * Install a plugin with optional configuration
93
- * @param plugin - The plugin to install
94
- * @param config - Optional plugin configuration
95
- * @throws Error if plugin is already installed
96
- */
97
- install(plugin, config = {}) {
98
- const effectiveConfig = {
99
- enabled: true,
100
- environment: "all",
101
- ...config
102
- };
103
- if (!this.shouldEnablePlugin(effectiveConfig)) {
104
- console.log(`[BlaC] Plugin "${plugin.name}" skipped (environment mismatch)`);
105
- return;
106
- }
107
- if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already installed`);
108
- const context = this.createPluginContext();
109
- this.plugins.set(plugin.name, {
110
- plugin,
111
- config: effectiveConfig,
112
- context
113
- });
114
- if (plugin.onInstall) try {
115
- plugin.onInstall(context);
116
- } catch (error) {
117
- console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error);
118
- this.plugins.delete(plugin.name);
119
- throw error;
120
- }
121
- console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
122
- }
123
- /**
124
- * Uninstall a plugin by name
125
- * @param pluginName - The name of the plugin to uninstall
126
- * @throws Error if plugin is not installed
127
- */
128
- uninstall(pluginName) {
129
- const installed = this.plugins.get(pluginName);
130
- if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
131
- if (installed.plugin.onUninstall) try {
132
- installed.plugin.onUninstall();
133
- } catch (error) {
134
- console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error);
135
- }
136
- this.plugins.delete(pluginName);
137
- console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
138
- }
139
- /**
140
- * Get an installed plugin by name
141
- * @param pluginName - The name of the plugin to retrieve
142
- * @returns The plugin instance or undefined if not found
143
- */
144
- getPlugin(pluginName) {
145
- return this.plugins.get(pluginName)?.plugin;
146
- }
147
- /**
148
- * Get all installed plugins
149
- * @returns Array of all installed plugins
150
- */
151
- getAllPlugins() {
152
- return Array.from(this.plugins.values()).map((p) => p.plugin);
153
- }
154
- /**
155
- * Check if a plugin is installed
156
- * @param pluginName - The name of the plugin to check
157
- * @returns true if the plugin is installed
158
- */
159
- hasPlugin(pluginName) {
160
- return this.plugins.has(pluginName);
161
- }
162
- /**
163
- * Uninstall all plugins
164
- */
165
- clear() {
166
- for (const name of this.plugins.keys()) this.uninstall(name);
167
- }
168
- /**
169
- * Setup lifecycle hooks to notify plugins
170
- */
171
- setupLifecycleHooks() {
172
- this.registry.on("created", (instance) => {
173
- this.notifyPlugins("onInstanceCreated", instance);
174
- });
175
- this.registry.on("stateChanged", (instance, previousState, currentState, callstack) => {
176
- this.notifyPlugins("onStateChanged", instance, previousState, currentState, callstack);
177
- });
178
- this.registry.on("disposed", (instance) => {
179
- this.notifyPlugins("onInstanceDisposed", instance);
180
- });
181
- }
182
- /**
183
- * Notify all plugins of a lifecycle event
184
- */
185
- notifyPlugins(hookName, ...args) {
186
- for (const { plugin, config, context } of this.plugins.values()) {
187
- if (!config.enabled) continue;
188
- const hook = plugin[hookName];
189
- if (typeof hook === "function") try {
190
- hook.apply(plugin, [...args, context]);
191
- } catch (error) {
192
- console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error);
193
- }
194
- }
195
- }
196
- /**
197
- * Create plugin context with safe API access
198
- */
199
- createPluginContext() {
200
- return {
201
- getInstanceMetadata: (instance) => {
202
- return {
203
- id: instance.instanceId,
204
- className: instance.constructor.name,
205
- isDisposed: instance.isDisposed,
206
- name: instance.name,
207
- lastStateChangeTimestamp: instance.lastUpdateTimestamp,
208
- createdAt: instance.createdAt,
209
- state: instance.state,
210
- isIsolated: instance.instanceId.startsWith("isolated-")
211
- };
212
- },
213
- getState: (instance) => {
214
- return instance.state;
215
- },
216
- queryInstances: (typeClass) => {
217
- return this.registry.getAll(typeClass);
218
- },
219
- getAllTypes: () => {
220
- return this.registry.getTypes();
221
- },
222
- getStats: () => {
223
- return this.registry.getStats();
224
- }
225
- };
226
- }
227
- /**
228
- * Check if plugin should be enabled based on environment
229
- */
230
- shouldEnablePlugin(config) {
231
- if (!config.enabled) return false;
232
- if (config.environment === "all") return true;
233
- return this.getCurrentEnvironment() === config.environment;
234
- }
235
- /**
236
- * Get current environment
237
- */
238
- getCurrentEnvironment() {
239
- if (typeof process !== "undefined") {
240
- if (process.env.NODE_ENV === "test") return "test";
241
- if (process.env.NODE_ENV === "production") return "production";
242
- return "development";
243
- }
244
- return "development";
245
- }
246
- };
247
- /**
248
- * Create a plugin manager instance
249
- * @param registry - The StateContainerRegistry to monitor for lifecycle events
250
- * @returns A new PluginManager instance
251
- */
252
- function createPluginManager(registry) {
253
- return new PluginManager(registry);
254
- }
255
-
256
- //#endregion
257
- //#region src/utils/static-props.ts
258
- /**
259
- * Utility functions for accessing static properties on StateContainer classes
260
- */
261
- /**
262
- * Get a static property from a class constructor
263
- * Type-safe helper that avoids (Type as any) casts
264
- *
265
- * @param Type - The class constructor
266
- * @param propName - The property name to access
267
- * @param defaultValue - Optional default value if property is undefined
268
- * @returns The property value or default
269
- */
270
- function getStaticProp(Type, propName, defaultValue) {
271
- return Type[propName] ?? defaultValue;
272
- }
273
- /**
274
- * Check if a class is marked as isolated.
275
- * Isolated classes create separate instances per component.
276
- * @param Type - The class constructor to check
277
- * @returns true if the class has `static isolated = true`
278
- */
279
- function isIsolatedClass(Type) {
280
- return getStaticProp(Type, BLAC_STATIC_PROPS.ISOLATED) === true;
281
- }
282
- /**
283
- * Check if a class is marked as keepAlive.
284
- * KeepAlive classes are never auto-disposed when ref count reaches 0.
285
- * @param Type - The class constructor to check
286
- * @returns true if the class has `static keepAlive = true`
287
- */
288
- function isKeepAliveClass(Type) {
289
- return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
290
- }
291
-
292
25
  //#endregion
293
- //#region src/core/StateContainerRegistry.ts
294
- /**
295
- * Central registry for managing StateContainer instances.
296
- * Handles instance lifecycle, ref counting, and lifecycle event emission.
297
- *
298
- * @example
299
- * ```ts
300
- * const registry = new StateContainerRegistry();
301
- * const instance = registry.acquire(MyBloc); // ownership, must release
302
- * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
303
- * registry.on('stateChanged', (container, prev, next) => {
304
- * console.log('State changed:', prev, '->', next);
305
- * });
306
- * ```
307
- */
308
- var StateContainerRegistry = class {
309
- constructor() {
310
- this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
311
- this.types = /* @__PURE__ */ new Set();
312
- this.typeConfigs = /* @__PURE__ */ new Map();
313
- this.listeners = /* @__PURE__ */ new Map();
314
- }
315
- /**
316
- * Register a type for lifecycle event tracking
317
- * @param constructor - The StateContainer class constructor
318
- */
319
- registerType(constructor) {
320
- this.types.add(constructor);
321
- }
322
- /**
323
- * Register a StateContainer class with configuration
324
- * @param constructor - The StateContainer class constructor
325
- * @param isolated - Whether instances should be isolated (component-scoped)
326
- * @throws Error if type is already registered
327
- */
328
- register(constructor, isolated = false) {
329
- const className = constructor.name;
330
- if (!isolated && isIsolatedClass(constructor)) isolated = true;
331
- if (this.typeConfigs.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
332
- this.typeConfigs.set(className, { isolated });
333
- this.registerType(constructor);
334
- }
335
- ensureInstancesMap(Type) {
336
- let instances = this.instancesByConstructor.get(Type);
337
- if (!instances) {
338
- instances = /* @__PURE__ */ new Map();
339
- this.instancesByConstructor.set(Type, instances);
340
- }
341
- return instances;
342
- }
343
- /**
344
- * Get the instances Map for a specific class (public API for stats/debugging)
345
- */
346
- getInstancesMap(Type) {
347
- return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
348
- }
349
- /**
350
- * Acquire an instance with ref counting (ownership semantics).
351
- * Creates a new instance if one doesn't exist, or returns existing and increments ref count.
352
- * You must call `release()` when done to decrement the ref count.
353
- * @param Type - The StateContainer class constructor
354
- * @param instanceKey - Instance key (defaults to 'default')
355
- * @param options - Acquisition options
356
- * @param options.canCreate - Whether to create new instance if not found (default: true)
357
- * @param options.countRef - Whether to increment ref count (default: true)
358
- * @returns The state container instance
359
- */
360
- acquire(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, options = {}) {
361
- const { canCreate = true, countRef = true } = options;
362
- const registryConfig = this.typeConfigs.get(Type.name);
363
- const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;
364
- const config = { instanceId: instanceKey };
365
- if (isolated && !canCreate) throw new Error(`${BLAC_ERROR_PREFIX} Cannot get isolated instance "${instanceKey}" of ${Type.name} when creation is disabled.`);
366
- if (isolated) {
367
- const instance = new Type();
368
- instance.initConfig(config);
369
- this.registerType(Type);
370
- return instance;
371
- }
372
- const instances = this.ensureInstancesMap(Type);
373
- let entry = instances.get(instanceKey);
374
- if (entry?.instance.isDisposed) {
375
- instances.delete(instanceKey);
376
- entry = void 0;
377
- }
378
- if (entry && countRef) entry.refCount++;
379
- if (entry) return entry.instance;
380
- if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${instanceKey}" not found and creation is disabled.`);
381
- const instance = new Type();
382
- instance.initConfig(config);
383
- instances.set(instanceKey, {
384
- instance,
385
- refCount: 1
386
- });
387
- this.registerType(Type);
388
- return instance;
389
- }
390
- /**
391
- * Borrow an existing instance without incrementing ref count (borrowing semantics).
392
- * Tracks cross-bloc dependency for reactive updates.
393
- * @param Type - The StateContainer class constructor
394
- * @param instanceKey - Instance key (defaults to 'default')
395
- * @returns The state container instance
396
- * @throws Error if instance doesn't exist
397
- */
398
- borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
399
- return this.acquire(Type, instanceKey, {
400
- canCreate: false,
401
- countRef: false
402
- });
403
- }
404
- /**
405
- * Safely borrow an existing instance (borrowing semantics with error handling).
406
- * Returns discriminated union for type-safe conditional access.
407
- * @param Type - The StateContainer class constructor
408
- * @param instanceKey - Instance key (defaults to 'default')
409
- * @returns Discriminated union with either the instance or an error
410
- */
411
- borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
412
- try {
413
- return {
414
- error: null,
415
- instance: this.borrow(Type, instanceKey)
416
- };
417
- } catch (error) {
418
- return {
419
- error,
420
- instance: null
421
- };
422
- }
423
- }
424
- /**
425
- * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
426
- * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.
427
- * Tracks cross-bloc dependency for reactive updates.
428
- *
429
- * Use this in bloc-to-bloc communication when you need to ensure an instance exists
430
- * but don't want to claim ownership (no ref count increment).
431
- * @param Type - The StateContainer class constructor
432
- * @param instanceKey - Instance key (defaults to 'default')
433
- * @returns The state container instance
434
- */
435
- ensure(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
436
- return this.acquire(Type, instanceKey, {
437
- canCreate: true,
438
- countRef: false
439
- });
440
- }
441
- /**
442
- * Release a reference to an instance.
443
- * Decrements ref count and disposes when it reaches 0 (unless keepAlive).
444
- * @param Type - The StateContainer class constructor
445
- * @param instanceKey - Instance key (defaults to 'default')
446
- * @param forceDispose - Force immediate disposal regardless of ref count
447
- */
448
- release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false) {
449
- const instances = this.ensureInstancesMap(Type);
450
- const entry = instances.get(instanceKey);
451
- if (!entry) return;
452
- if (forceDispose) {
453
- if (!entry.instance.isDisposed) entry.instance.dispose();
454
- instances.delete(instanceKey);
455
- return;
456
- }
457
- entry.refCount--;
458
- const keepAlive = isKeepAliveClass(Type);
459
- if (entry.refCount <= 0 && !keepAlive) {
460
- if (!entry.instance.isDisposed) entry.instance.dispose();
461
- instances.delete(instanceKey);
462
- }
463
- }
464
- /**
465
- * Get all instances of a specific type.
466
- * @param Type - The StateContainer class constructor
467
- * @returns Array of all instances
468
- */
469
- getAll(Type) {
470
- const instances = this.ensureInstancesMap(Type);
471
- const result = [];
472
- for (const entry of instances.values()) result.push(entry.instance);
473
- return result;
474
- }
475
- /**
476
- * Safely iterate over all instances of a type.
477
- * Skips disposed instances and catches callback errors.
478
- * @param Type - The StateContainer class constructor
479
- * @param callback - Function to call for each instance
480
- */
481
- forEach(Type, callback) {
482
- const instances = this.ensureInstancesMap(Type);
483
- for (const entry of instances.values()) {
484
- const instance = entry.instance;
485
- if (!instance.isDisposed) try {
486
- callback(instance);
487
- } catch (error) {
488
- console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error);
489
- }
490
- }
491
- }
492
- /**
493
- * Clear all instances of a specific type (disposes them).
494
- * @param Type - The StateContainer class constructor
495
- */
496
- clear(Type) {
497
- const instances = this.ensureInstancesMap(Type);
498
- for (const entry of instances.values()) if (!entry.instance.isDisposed) entry.instance.dispose();
499
- instances.clear();
500
- }
501
- /**
502
- * Get reference count for an instance.
503
- * @param Type - The StateContainer class constructor
504
- * @param instanceKey - Instance key (defaults to 'default')
505
- * @returns Current ref count (0 if instance doesn't exist)
506
- */
507
- getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
508
- return this.ensureInstancesMap(Type).get(instanceKey)?.refCount ?? 0;
509
- }
510
- /**
511
- * Check if an instance exists.
512
- * @param Type - The StateContainer class constructor
513
- * @param instanceKey - Instance key (defaults to 'default')
514
- * @returns true if instance exists
515
- */
516
- hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
517
- return this.ensureInstancesMap(Type).has(instanceKey);
518
- }
519
- /**
520
- * Clear all instances from all types (for testing)
521
- *
522
- * Iterates all registered types and clears their instances.
523
- * Also clears type tracking to reset the registry state.
524
- */
525
- clearAll() {
526
- for (const Type of this.types) this.clear(Type);
527
- this.types.clear();
528
- this.typeConfigs.clear();
529
- }
530
- /**
531
- * Get registry statistics for debugging.
532
- * @returns Object with registeredTypes, totalInstances, and typeBreakdown
533
- */
534
- getStats() {
535
- const typeBreakdown = {};
536
- let totalInstances = 0;
537
- for (const Type of this.types) {
538
- const typeName = Type.name;
539
- const count = this.getInstancesMap(Type).size;
540
- typeBreakdown[typeName] = count;
541
- totalInstances += count;
542
- }
543
- return {
544
- registeredTypes: this.types.size,
545
- totalInstances,
546
- typeBreakdown
547
- };
548
- }
549
- /**
550
- * Get all registered types (for plugin system).
551
- * @returns Array of all registered StateContainer class constructors
552
- */
553
- getTypes() {
554
- return Array.from(this.types);
555
- }
556
- /**
557
- * Subscribe to lifecycle events
558
- * @param event - The lifecycle event to listen for
559
- * @param listener - The listener function to call when the event occurs
560
- * @returns Unsubscribe function
561
- */
562
- on(event, listener) {
563
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
564
- const instance = this.listeners.get(event);
565
- if (!instance) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
566
- instance.add(listener);
567
- return () => {
568
- this.listeners.get(event)?.delete(listener);
569
- };
570
- }
571
- /**
572
- * Emit lifecycle event to all listeners
573
- * @internal - Called by StateContainer lifecycle methods
574
- */
575
- emit(event, ...args) {
576
- const listeners = this.listeners.get(event);
577
- if (!listeners || listeners.size === 0) return;
578
- for (const listener of listeners) try {
579
- listener(...args);
580
- } catch (error) {
581
- console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error);
582
- }
583
- }
584
- };
585
- /**
586
- * Global default registry instance
587
- */
588
- const globalRegistry = new StateContainerRegistry();
589
- /**
590
- * Global plugin manager (initialized lazily)
591
- */
592
- let _globalPluginManager = null;
593
- /**
594
- * Get the global plugin manager
595
- */
596
- function getPluginManager() {
597
- if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
598
- return _globalPluginManager;
599
- }
600
-
26
+ //#region src/core/symbols.ts
27
+ const EMIT = Symbol("blac.emit");
28
+ const UPDATE = Symbol("blac.update");
601
29
  //#endregion
602
30
  //#region src/core/StateContainer.ts
603
31
  const EMPTY_DEPS = /* @__PURE__ */ new Map();
604
- /**
605
- * Abstract base class for all state containers in BlaC.
606
- * Provides lifecycle management, subscription handling, ref counting,
607
- * and integration with the global registry.
608
- *
609
- * @template S - State type managed by this container
610
- *
611
- * @example
612
- * ```ts
613
- * class CounterBloc extends StateContainer<{ count: number }> {
614
- * constructor() {
615
- * super({ count: 0 });
616
- * }
617
- * increment() {
618
- * this.emit({ count: this.state.count + 1 });
619
- * }
620
- * }
621
- * ```
622
- */
623
32
  var StateContainer = class StateContainer {
624
33
  static {
625
34
  this.__excludeFromDevTools = false;
@@ -632,25 +41,29 @@ var StateContainer = class StateContainer {
632
41
  }
633
42
  depend(Type, instanceKey) {
634
43
  if (!this._dependencies) this._dependencies = /* @__PURE__ */ new Map();
635
- this._dependencies.set(Type, instanceKey ?? BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY);
636
- return () => globalRegistry.ensure(Type, instanceKey);
44
+ this._dependencies.set(Type, instanceKey ?? require_StateContainerRegistry.BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY);
45
+ return () => require_StateContainerRegistry.globalRegistry.ensure(Type, instanceKey);
637
46
  }
638
47
  constructor(initialState) {
639
- this.listeners = /* @__PURE__ */ new Set();
48
+ this._listeners = /* @__PURE__ */ new Set();
640
49
  this._disposed = false;
641
- this.config = {};
642
- this.systemEventHandlers = /* @__PURE__ */ new Map();
50
+ this._hydrationStatus = "idle";
51
+ this._changedWhileHydrating = false;
52
+ this._hydrationPromise = null;
53
+ this._hydrationPromiseSettled = false;
54
+ this._config = {};
55
+ this._systemEventHandlers = /* @__PURE__ */ new Map();
56
+ this._dependencies = null;
643
57
  this.name = this.constructor.name;
644
58
  this.debug = false;
645
59
  this.instanceId = generateSimpleId(this.constructor.name, "main");
646
60
  this.createdAt = Date.now();
647
- this._dependencies = null;
648
61
  this.lastUpdateTimestamp = Date.now();
649
62
  this.onSystemEvent = (event, handler) => {
650
- let handlers = this.systemEventHandlers.get(event);
63
+ let handlers = this._systemEventHandlers.get(event);
651
64
  if (!handlers) {
652
65
  handlers = /* @__PURE__ */ new Set();
653
- this.systemEventHandlers.set(event, handlers);
66
+ this._systemEventHandlers.set(event, handlers);
654
67
  }
655
68
  handlers.add(handler);
656
69
  return () => {
@@ -659,72 +72,89 @@ var StateContainer = class StateContainer {
659
72
  };
660
73
  this._state = initialState;
661
74
  }
662
- /**
663
- * Initialize configuration for this instance.
664
- * Called by the registry after construction.
665
- * @param config - Configuration options
666
- */
667
75
  initConfig(config) {
668
- this.config = { ...config };
669
- this.name = this.config.name || this.constructor.name;
670
- this.debug = this.config.debug ?? false;
671
- this.instanceId = generateSimpleId(this.constructor.name, this.config.instanceId);
672
- globalRegistry.emit("created", this);
76
+ this._config = { ...config };
77
+ this.name = this._config.name || this.constructor.name;
78
+ this.debug = this._config.debug ?? false;
79
+ this.instanceId = generateSimpleId(this.constructor.name, this._config.instanceId);
80
+ require_StateContainerRegistry.globalRegistry.emit("created", this);
673
81
  }
674
- /** Current state value */
675
82
  get state() {
676
83
  return this._state;
677
84
  }
678
- /** Whether this instance has been disposed */
679
85
  get isDisposed() {
680
86
  return this._disposed;
681
87
  }
682
- /**
683
- * Subscribe to state changes
684
- * @param listener - Function called when state changes
685
- * @returns Unsubscribe function
686
- */
88
+ get hydrationStatus() {
89
+ return this._hydrationStatus;
90
+ }
91
+ get hydrationError() {
92
+ return this._hydrationError;
93
+ }
94
+ get isHydrated() {
95
+ return this._hydrationStatus === "hydrated";
96
+ }
97
+ get changedWhileHydrating() {
98
+ return this._changedWhileHydrating;
99
+ }
687
100
  subscribe(listener) {
688
101
  if (this._disposed) throw new Error(`Cannot subscribe to disposed container ${this.name}`);
689
- this.listeners.add(listener);
690
- return () => this.listeners.delete(listener);
102
+ this._listeners.add(listener);
103
+ return () => this._listeners.delete(listener);
691
104
  }
692
- /**
693
- * Dispose this instance and clean up resources.
694
- * Clears all listeners and emits the 'dispose' system event.
695
- */
696
105
  dispose() {
697
106
  if (this._disposed) return;
698
107
  if (this.debug) console.log(`[${this.name}] Disposing...`);
699
108
  this._disposed = true;
109
+ if (this._hydrationStatus === "hydrating") this.failHydration(/* @__PURE__ */ new Error(`Hydration cancelled because ${this.name} was disposed`));
700
110
  this.emitSystemEvent("dispose", void 0);
701
- this.listeners.clear();
702
- this.systemEventHandlers.clear();
703
- globalRegistry.emit("disposed", this);
111
+ this._listeners.clear();
112
+ this._systemEventHandlers.clear();
113
+ require_StateContainerRegistry.globalRegistry.emit("disposed", this);
704
114
  if (this.debug) console.log(`[${this.name}] Disposed successfully`);
705
115
  }
706
- /**
707
- * Emit a new state value and notify all listeners.
708
- * @param newState - The new state value
709
- * @protected
710
- */
711
- emit(newState) {
712
- if (this._disposed) throw new Error(`Cannot emit state from disposed container ${this.name}`);
713
- if (this._state === newState) return;
714
- const previousState = this._state;
715
- this._state = newState;
716
- this.emitSystemEvent("stateChanged", {
717
- state: newState,
718
- previousState
719
- });
720
- for (const listener of this.listeners) try {
721
- listener(newState);
722
- } catch (error) {
723
- console.error(`[${this.name}] Error in listener:`, error);
116
+ [EMIT](newState) {
117
+ this.applyState(newState, "default");
118
+ }
119
+ [UPDATE](updater) {
120
+ if (this._disposed) throw new Error(`Cannot update state from disposed container ${this.name}`);
121
+ this[EMIT](updater(this._state));
122
+ }
123
+ beginHydration() {
124
+ if (this._disposed) throw new Error(`Cannot begin hydration for disposed container ${this.name}`);
125
+ this._changedWhileHydrating = false;
126
+ this._hydrationError = void 0;
127
+ this._hydrationPromise = null;
128
+ this._resolveHydrationPromise = void 0;
129
+ this._rejectHydrationPromise = void 0;
130
+ this._hydrationPromiseSettled = false;
131
+ this.ensureHydrationPromise();
132
+ this.setHydrationStatus("hydrating");
133
+ }
134
+ applyHydratedState(newState) {
135
+ if (this._disposed) return false;
136
+ if (this._hydrationStatus !== "hydrating" || this._changedWhileHydrating) return false;
137
+ this.applyState(newState, "hydration");
138
+ return true;
139
+ }
140
+ finishHydration() {
141
+ if (this._hydrationStatus !== "hydrating") {
142
+ if (this._hydrationStatus === "hydrated") return;
143
+ if (this._hydrationStatus === "error") this.ensureHydrationPromise();
724
144
  }
725
- const stackTrace = this.captureStackTrace();
726
- globalRegistry.emit("stateChanged", this, previousState, newState, stackTrace);
727
- this.lastUpdateTimestamp = Date.now();
145
+ this.setHydrationStatus("hydrated");
146
+ this.resolveHydration();
147
+ }
148
+ failHydration(error) {
149
+ const err = error instanceof Error ? error : /* @__PURE__ */ new Error(`Hydration failed: ${error}`);
150
+ this._hydrationError = err;
151
+ this.setHydrationStatus("error", err);
152
+ this.rejectHydration(err);
153
+ }
154
+ waitForHydration() {
155
+ if (this._hydrationStatus === "idle" || this._hydrationStatus === "hydrated") return Promise.resolve();
156
+ if (this._hydrationStatus === "error") return Promise.reject(this._hydrationError ?? /* @__PURE__ */ new Error(`Hydration failed for container ${this.name}`));
157
+ return this.ensureHydrationPromise();
728
158
  }
729
159
  captureStackTrace() {
730
160
  if (!StateContainer.enableStackTrace || typeof process !== "undefined" && process.env?.NODE_ENV === "production") return "";
@@ -733,7 +163,7 @@ var StateContainer = class StateContainer {
733
163
  const formattedLines = [];
734
164
  for (const line of relevantLines) {
735
165
  if (!line.trim()) continue;
736
- if (line.includes("StateContainer.emit") || line.includes("StateContainer.update") || line.includes("StateContainer.captureStackTrace") || line.includes("Cubit.patch")) continue;
166
+ if (line.includes("StateContainer.emit") || line.includes("StateContainer.update") || line.includes("StateContainer.captureStackTrace") || line.includes("[blac.emit]") || line.includes("[blac.update]") || line.includes("Cubit.patch")) continue;
737
167
  if (line.includes("node_modules") || line.includes("react-dom") || line.includes("react_jsx") || line.includes(".vite/deps") || line.includes("executeDispatch") || line.includes("runWithFiber") || line.includes("invokeGuarded") || line.includes("callCallback") || line.includes("processDispatchQueue") || line.includes("dispatchEvent") || line.includes("batchedUpdates")) continue;
738
168
  const formatted = this.formatStackLine(line);
739
169
  if (formatted) formattedLines.push(formatted);
@@ -764,17 +194,65 @@ var StateContainer = class StateContainer {
764
194
  if (segments.length > 3) path = segments.slice(-3).join("/");
765
195
  return path;
766
196
  }
767
- /**
768
- * Update state using a transform function.
769
- * @param updater - Function that receives current state and returns new state
770
- * @protected
771
- */
772
- update(updater) {
773
- if (this._disposed) throw new Error(`Cannot update state from disposed container ${this.name}`);
774
- this.emit(updater(this._state));
197
+ applyState(newState, source) {
198
+ if (this._disposed) throw new Error(`Cannot emit state from disposed container ${this.name}`);
199
+ if (this._state === newState) return;
200
+ if (this._hydrationStatus === "hydrating" && source !== "hydration") this._changedWhileHydrating = true;
201
+ const previousState = this._state;
202
+ this._state = newState;
203
+ this.emitSystemEvent("stateChanged", {
204
+ state: newState,
205
+ previousState
206
+ });
207
+ const listeners = Array.from(this._listeners);
208
+ for (const listener of listeners) try {
209
+ listener(newState);
210
+ } catch (error) {
211
+ console.error(`[${this.name}] Error in listener:`, error);
212
+ }
213
+ const stackTrace = this.captureStackTrace();
214
+ require_StateContainerRegistry.globalRegistry.emit("stateChanged", this, previousState, newState, stackTrace);
215
+ this.lastUpdateTimestamp = Date.now();
216
+ }
217
+ setHydrationStatus(status, error) {
218
+ const previousStatus = this._hydrationStatus;
219
+ this._hydrationStatus = status;
220
+ this._hydrationError = error;
221
+ this.emitSystemEvent("hydrationChanged", {
222
+ status,
223
+ previousStatus,
224
+ error,
225
+ changedWhileHydrating: this._changedWhileHydrating
226
+ });
227
+ }
228
+ ensureHydrationPromise() {
229
+ if (!this._hydrationPromise || this._hydrationPromiseSettled) {
230
+ this._hydrationPromiseSettled = false;
231
+ this._hydrationPromise = new Promise((resolve, reject) => {
232
+ this._resolveHydrationPromise = () => {
233
+ if (this._hydrationPromiseSettled) return;
234
+ this._hydrationPromiseSettled = true;
235
+ resolve();
236
+ };
237
+ this._rejectHydrationPromise = (error) => {
238
+ if (this._hydrationPromiseSettled) return;
239
+ this._hydrationPromiseSettled = true;
240
+ reject(error);
241
+ };
242
+ });
243
+ this._hydrationPromise.catch(() => {});
244
+ }
245
+ return this._hydrationPromise;
246
+ }
247
+ resolveHydration() {
248
+ this._resolveHydrationPromise?.();
249
+ }
250
+ rejectHydration(error) {
251
+ this.ensureHydrationPromise();
252
+ this._rejectHydrationPromise?.(error);
775
253
  }
776
254
  emitSystemEvent(event, payload) {
777
- const handlers = this.systemEventHandlers.get(event);
255
+ const handlers = this._systemEventHandlers.get(event);
778
256
  if (!handlers) return;
779
257
  for (const handler of handlers) try {
780
258
  handler(payload);
@@ -783,15 +261,8 @@ var StateContainer = class StateContainer {
783
261
  }
784
262
  }
785
263
  };
786
-
787
264
  //#endregion
788
265
  //#region src/core/Cubit.ts
789
- /**
790
- * Simple state container with direct state emission.
791
- * Extends StateContainer with public methods for emitting and updating state.
792
- *
793
- * @template S - State type
794
- */
795
266
  var Cubit = class extends StateContainer {
796
267
  constructor(initialState) {
797
268
  super(initialState);
@@ -809,93 +280,34 @@ var Cubit = class extends StateContainer {
809
280
  }));
810
281
  });
811
282
  }
812
- /**
813
- * Replace state with a new value and notify all listeners
814
- * @param newState - The new state value
815
- */
816
283
  emit(newState) {
817
- super["emit"](newState);
284
+ this[EMIT](newState);
818
285
  }
819
- /**
820
- * Transform current state using an updater function and emit the new state
821
- * @param updater - Function that receives current state and returns new state
822
- */
823
286
  update(updater) {
824
- super["update"](updater);
287
+ this[UPDATE](updater);
825
288
  }
826
289
  };
827
-
828
290
  //#endregion
829
291
  //#region src/registry/acquire.ts
830
292
  function acquire(BlocClass, instanceKey) {
831
- return globalRegistry.acquire(BlocClass, instanceKey, {
293
+ return require_StateContainerRegistry.globalRegistry.acquire(BlocClass, instanceKey, {
832
294
  canCreate: true,
833
295
  countRef: true
834
296
  });
835
297
  }
836
-
837
298
  //#endregion
838
299
  //#region src/registry/borrow.ts
839
300
  function borrow(BlocClass, instanceKey) {
840
- return globalRegistry.borrow(BlocClass, instanceKey);
301
+ return require_StateContainerRegistry.globalRegistry.borrow(BlocClass, instanceKey);
841
302
  }
842
303
  function borrowSafe(BlocClass, instanceKey) {
843
- return globalRegistry.borrowSafe(BlocClass, instanceKey);
844
- }
845
-
846
- //#endregion
847
- //#region src/registry/ensure.ts
848
- function ensure(BlocClass, instanceKey) {
849
- return globalRegistry.ensure(BlocClass, instanceKey);
304
+ return require_StateContainerRegistry.globalRegistry.borrowSafe(BlocClass, instanceKey);
850
305
  }
851
-
852
306
  //#endregion
853
307
  //#region src/registry/release.ts
854
308
  function release(BlocClass, instanceKey, forceDispose = false) {
855
- globalRegistry.release(BlocClass, instanceKey, forceDispose);
856
- }
857
-
858
- //#endregion
859
- //#region src/registry/queries.ts
860
- function hasInstance(BlocClass, instanceKey) {
861
- return globalRegistry.hasInstance(BlocClass, instanceKey);
862
- }
863
- function getRefCount(BlocClass, instanceKey) {
864
- return globalRegistry.getRefCount(BlocClass, instanceKey);
865
- }
866
- function getAll(BlocClass) {
867
- return globalRegistry.getAll(BlocClass);
868
- }
869
- function forEach(BlocClass, callback) {
870
- globalRegistry.forEach(BlocClass, callback);
871
- }
872
-
873
- //#endregion
874
- //#region src/registry/management.ts
875
- function clear(BlocClass) {
876
- globalRegistry.clear(BlocClass);
877
- }
878
- function clearAll() {
879
- globalRegistry.clearAll();
880
- }
881
- function register(BlocClass, isolated = false) {
882
- globalRegistry.register(BlocClass, isolated);
883
- }
884
-
885
- //#endregion
886
- //#region src/registry/config.ts
887
- let _registry = globalRegistry;
888
- function getRegistry() {
889
- return _registry;
890
- }
891
- function setRegistry(registry) {
892
- _registry.clearAll();
893
- _registry = registry;
894
- }
895
- function getStats() {
896
- return _registry.getStats();
309
+ require_StateContainerRegistry.globalRegistry.release(BlocClass, instanceKey, forceDispose);
897
310
  }
898
-
899
311
  //#endregion
900
312
  //#region src/decorators/blac.ts
901
313
  /**
@@ -903,9 +315,6 @@ function getStats() {
903
315
  *
904
316
  * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)
905
317
  * ```ts
906
- * @blac({ isolated: true })
907
- * class FormBloc extends Cubit<FormState> {}
908
- *
909
318
  * @blac({ keepAlive: true })
910
319
  * class AuthBloc extends Cubit<AuthState> {}
911
320
  *
@@ -915,894 +324,47 @@ function getStats() {
915
324
  *
916
325
  * @example Function syntax (no decorator support needed)
917
326
  * ```ts
918
- * const FormBloc = blac({ isolated: true })(
919
- * class extends Cubit<FormState> {}
327
+ * const AuthBloc = blac({ keepAlive: true })(
328
+ * class extends Cubit<AuthState> {}
920
329
  * );
921
330
  * ```
922
331
  */
923
332
  function blac(options) {
924
333
  return function(target, _context) {
925
- if ("isolated" in options && options.isolated) target[BLAC_STATIC_PROPS.ISOLATED] = true;
926
- if ("keepAlive" in options && options.keepAlive) target[BLAC_STATIC_PROPS.KEEP_ALIVE] = true;
927
- if ("excludeFromDevTools" in options && options.excludeFromDevTools) target[BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] = true;
334
+ if ("keepAlive" in options && options.keepAlive) target[require_StateContainerRegistry.BLAC_STATIC_PROPS.KEEP_ALIVE] = true;
335
+ if ("excludeFromDevTools" in options && options.excludeFromDevTools) target[require_StateContainerRegistry.BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] = true;
928
336
  return target;
929
337
  };
930
338
  }
931
-
932
- //#endregion
933
- //#region src/tracking/path-utils.ts
934
- /**
935
- * Path utilities for dependency tracking
936
- *
937
- * Provides utilities for parsing property paths and extracting values
938
- * from nested objects using path strings.
939
- *
940
- * @internal
941
- */
942
- /**
943
- * Parse a property path string into an array of segments
944
- *
945
- * @internal
946
- *
947
- * Handles both dot notation (a.b.c) and bracket notation (a[0].b)
948
- *
949
- * @example
950
- * ```ts
951
- * parsePath('user.name') // ['user', 'name']
952
- * parsePath('items[0].name') // ['items', '0', 'name']
953
- * parsePath('data.users[2].address.city') // ['data', 'users', '2', 'address', 'city']
954
- * ```
955
- */
956
- function parsePath(path) {
957
- const segments = [];
958
- let current = "";
959
- let i = 0;
960
- while (i < path.length) {
961
- const char = path[i];
962
- if (char === ".") {
963
- if (current) segments.push(current);
964
- current = "";
965
- } else if (char === "[") {
966
- if (current) segments.push(current);
967
- current = "";
968
- i++;
969
- while (i < path.length && path[i] !== "]") current += path[i++];
970
- if (current) segments.push(current);
971
- current = "";
972
- } else current += char;
973
- i++;
974
- }
975
- if (current) segments.push(current);
976
- return segments;
977
- }
978
- /**
979
- * Get a value from an object using a path of segments
980
- *
981
- * @example
982
- * ```ts
983
- * const obj = { user: { name: 'Alice', age: 30 } }
984
- * getValueAtPath(obj, ['user', 'name']) // 'Alice'
985
- * getValueAtPath(obj, ['user', 'age']) // 30
986
- * getValueAtPath(obj, ['user', 'missing']) // undefined
987
- * ```
988
- *
989
- * @internal
990
- */
991
- function getValueAtPath(obj, segments) {
992
- if (obj == null) return void 0;
993
- let current = obj;
994
- for (let i = 0; i < segments.length; i++) {
995
- current = current[segments[i]];
996
- if (current == null) return void 0;
997
- }
998
- return current;
999
- }
1000
- /**
1001
- * Shallow equality comparison for arrays
1002
- *
1003
- * Compares two arrays element-by-element using Object.is
1004
- *
1005
- * @example
1006
- * ```ts
1007
- * shallowEqual([1, 2, 3], [1, 2, 3]) // true
1008
- * shallowEqual([1, 2, 3], [1, 2, 4]) // false
1009
- * shallowEqual([1, 2], [1, 2, 3]) // false
1010
- * ```
1011
- *
1012
- * @internal
1013
- */
1014
- function shallowEqual(arr1, arr2) {
1015
- if (arr1.length !== arr2.length) return false;
1016
- for (let i = 0; i < arr1.length; i++) if (!Object.is(arr1[i], arr2[i])) return false;
1017
- return true;
1018
- }
1019
-
1020
- //#endregion
1021
- //#region src/tracking/tracking-proxy.ts
1022
- /**
1023
- * Consolidated Tracking System
1024
- *
1025
- * This module provides all dependency and getter tracking functionality:
1026
- * - Proxy creation for automatic property access tracking
1027
- * - Dependency path tracking and change detection
1028
- * - Getter execution tracking for computed properties
1029
- * - Combined tracking proxy for watch/waitUntil use cases
1030
- */
1031
- /**
1032
- * Check if a value can be proxied
1033
- * Returns true for plain objects and arrays only.
1034
- * @internal
1035
- */
1036
- function isProxyable(value) {
1037
- if (typeof value !== "object" || value === null) return false;
1038
- const proto = Object.getPrototypeOf(value);
1039
- return proto === Object.prototype || proto === Array.prototype;
1040
- }
1041
- /**
1042
- * Create a new proxy tracker state
1043
- * @internal
1044
- */
1045
- function createProxyState() {
1046
- return {
1047
- trackedPaths: /* @__PURE__ */ new Set(),
1048
- isTracking: false,
1049
- proxyCache: /* @__PURE__ */ new WeakMap(),
1050
- boundFunctionsCache: null,
1051
- lastProxiedState: null,
1052
- lastProxy: null,
1053
- maxDepth: 10
1054
- };
1055
- }
1056
- /**
1057
- * Start tracking property accesses
1058
- * @internal
1059
- */
1060
- function startProxy(state) {
1061
- state.isTracking = true;
1062
- state.trackedPaths.clear();
1063
- }
1064
- /**
1065
- * Stop tracking and return the tracked paths
1066
- * @internal
1067
- */
1068
- function stopProxy(state) {
1069
- state.isTracking = false;
1070
- return new Set(state.trackedPaths);
1071
- }
1072
- /**
1073
- * Create a proxy for an array with property access tracking
1074
- * @internal
1075
- */
1076
- function createArrayProxy(state, target, path, depth = 0) {
1077
- const proxy = new Proxy(target, { get: (arr, prop) => {
1078
- if (typeof prop === "symbol") return Reflect.get(arr, prop);
1079
- const value = Reflect.get(arr, prop);
1080
- if (typeof value === "function") {
1081
- if (!state.boundFunctionsCache) state.boundFunctionsCache = /* @__PURE__ */ new WeakMap();
1082
- const cached = state.boundFunctionsCache.get(value);
1083
- if (cached) return cached;
1084
- const bound = value.bind(arr);
1085
- state.boundFunctionsCache.set(value, bound);
1086
- return bound;
1087
- }
1088
- if (prop === "length") {
1089
- if (state.isTracking) {
1090
- const fullPath = path ? `${path}.length` : "length";
1091
- state.trackedPaths.add(fullPath);
1092
- }
1093
- return value;
1094
- }
1095
- let fullPath;
1096
- if (typeof prop === "string") {
1097
- const index = Number(prop);
1098
- if (!isNaN(index) && index >= 0) fullPath = path ? `${path}[${index}]` : `[${index}]`;
1099
- else fullPath = path ? `${path}.${prop}` : prop;
1100
- } else return value;
1101
- if (isProxyable(value)) return createInternal(state, value, fullPath, depth + 1);
1102
- if (state.isTracking) state.trackedPaths.add(fullPath);
1103
- return value;
1104
- } });
1105
- state.proxyCache.set(target, proxy);
1106
- return proxy;
1107
- }
1108
- /**
1109
- * Create a proxy for an object with property access tracking
1110
- * @internal
1111
- */
1112
- function createInternal(state, target, path = "", depth = 0) {
1113
- if (!state.isTracking || !isProxyable(target)) return target;
1114
- if (depth >= state.maxDepth) return target;
1115
- if (state.proxyCache.has(target)) return state.proxyCache.get(target);
1116
- if (Array.isArray(target)) return createArrayProxy(state, target, path, depth);
1117
- const proxy = new Proxy(target, {
1118
- get: (obj, prop) => {
1119
- if (typeof prop === "symbol") return Reflect.get(obj, prop);
1120
- const value = Reflect.get(obj, prop);
1121
- if (typeof value === "function") {
1122
- if (!state.boundFunctionsCache) state.boundFunctionsCache = /* @__PURE__ */ new WeakMap();
1123
- const cached = state.boundFunctionsCache.get(value);
1124
- if (cached) return cached;
1125
- const bound = value.bind(obj);
1126
- state.boundFunctionsCache.set(value, bound);
1127
- return bound;
1128
- }
1129
- const fullPath = path ? `${path}.${String(prop)}` : String(prop);
1130
- if (typeof prop === "string" && state.isTracking) {
1131
- if (!prop.startsWith("_") && !prop.startsWith("$$")) state.trackedPaths.add(fullPath);
1132
- }
1133
- if (isProxyable(value)) return createInternal(state, value, fullPath, depth + 1);
1134
- return value;
1135
- },
1136
- has: (obj, prop) => {
1137
- if (typeof prop === "string" && state.isTracking) {
1138
- const fullPath = path ? `${path}.${prop}` : prop;
1139
- state.trackedPaths.add(fullPath);
1140
- }
1141
- return Reflect.has(obj, prop);
1142
- },
1143
- ownKeys: (obj) => {
1144
- if (state.isTracking && path) state.trackedPaths.add(path);
1145
- return Reflect.ownKeys(obj);
1146
- }
1147
- });
1148
- state.proxyCache.set(target, proxy);
1149
- return proxy;
1150
- }
1151
- /**
1152
- * Create a proxy for a target with caching
1153
- * @internal
1154
- */
1155
- function createForTarget(state, target) {
1156
- if (state.lastProxiedState === target && state.lastProxy) return state.lastProxy;
1157
- state.proxyCache = /* @__PURE__ */ new WeakMap();
1158
- state.boundFunctionsCache = null;
1159
- const proxy = createInternal(state, target, "", 0);
1160
- state.lastProxiedState = target;
1161
- state.lastProxy = proxy;
1162
- return proxy;
1163
- }
1164
- function isChildPath(child, parent) {
1165
- if (child === parent) return false;
1166
- return child.startsWith(parent + ".") || child.startsWith(parent + "[");
1167
- }
1168
- function getArrayParentPath(path) {
1169
- if (path.endsWith(".length")) return path.slice(0, -7);
1170
- const arrayIndexMatch = path.match(/^(.+?)\[\d+\]/);
1171
- if (arrayIndexMatch) return arrayIndexMatch[1];
1172
- return null;
1173
- }
1174
- /**
1175
- * @internal
1176
- */
1177
- function optimizeTrackedPaths(paths) {
1178
- if (paths.size === 0) return /* @__PURE__ */ new Set();
1179
- if (paths.size === 1) return new Set(paths);
1180
- const sortedPaths = Array.from(paths).sort((a, b) => b.length - a.length);
1181
- const optimized = /* @__PURE__ */ new Set();
1182
- for (const path of sortedPaths) {
1183
- let hasMoreSpecificChild = false;
1184
- for (const optimizedPath of optimized) if (isChildPath(optimizedPath, path)) {
1185
- hasMoreSpecificChild = true;
1186
- break;
1187
- }
1188
- if (!hasMoreSpecificChild) optimized.add(path);
1189
- }
1190
- const arrayParents = /* @__PURE__ */ new Set();
1191
- for (const path of optimized) {
1192
- const arrayParent = getArrayParentPath(path);
1193
- if (arrayParent) arrayParents.add(arrayParent);
1194
- }
1195
- for (const arrayParent of arrayParents) optimized.add(arrayParent);
1196
- return optimized;
1197
- }
1198
- /**
1199
- * @internal
1200
- */
1201
- function createDependencyState() {
1202
- return {
1203
- proxyState: createProxyState(),
1204
- previousRenderPaths: /* @__PURE__ */ new Set(),
1205
- currentRenderPaths: /* @__PURE__ */ new Set(),
1206
- pathCache: /* @__PURE__ */ new Map(),
1207
- lastCheckedState: null,
1208
- lastCheckedValues: /* @__PURE__ */ new Map()
1209
- };
1210
- }
1211
- /**
1212
- * @internal
1213
- */
1214
- function startDependency(tracker) {
1215
- startProxy(tracker.proxyState);
1216
- }
1217
- /**
1218
- * @internal
1219
- */
1220
- function createDependencyProxy(tracker, state) {
1221
- return createForTarget(tracker.proxyState, state);
1222
- }
1223
- /**
1224
- * @internal
1225
- */
1226
- function capturePaths(tracker, state) {
1227
- tracker.previousRenderPaths = tracker.currentRenderPaths;
1228
- tracker.currentRenderPaths = optimizeTrackedPaths(stopProxy(tracker.proxyState));
1229
- if (tracker.previousRenderPaths.size === 0 && tracker.currentRenderPaths.size === 0) return;
1230
- const trackedPathsUnion = new Set(tracker.previousRenderPaths);
1231
- for (const path of tracker.currentRenderPaths) trackedPathsUnion.add(path);
1232
- const canReuseCache = tracker.lastCheckedState === state;
1233
- for (const path of trackedPathsUnion) if (!tracker.pathCache.has(path)) {
1234
- const segments = parsePath(path);
1235
- const value = canReuseCache && tracker.lastCheckedValues.has(path) ? tracker.lastCheckedValues.get(path) : getValueAtPath(state, segments);
1236
- tracker.pathCache.set(path, {
1237
- segments,
1238
- value
1239
- });
1240
- } else {
1241
- const info = tracker.pathCache.get(path);
1242
- info.value = canReuseCache && tracker.lastCheckedValues.has(path) ? tracker.lastCheckedValues.get(path) : getValueAtPath(state, info.segments);
1243
- }
1244
- tracker.lastCheckedValues.clear();
1245
- }
1246
- /**
1247
- * @internal
1248
- */
1249
- function hasDependencyChanges(tracker, state) {
1250
- if (tracker.pathCache.size === 0) return true;
1251
- tracker.lastCheckedValues.clear();
1252
- for (const [path, info] of tracker.pathCache.entries()) {
1253
- const currentValue = getValueAtPath(state, info.segments);
1254
- tracker.lastCheckedValues.set(path, currentValue);
1255
- if (!Object.is(currentValue, info.value)) {
1256
- tracker.lastCheckedState = state;
1257
- return true;
1258
- }
1259
- }
1260
- tracker.lastCheckedState = state;
1261
- return false;
1262
- }
1263
- /**
1264
- * @internal
1265
- */
1266
- function hasTrackedData(tracker) {
1267
- return tracker.proxyState.trackedPaths.size > 0 || tracker.pathCache.size > 0 || tracker.previousRenderPaths.size > 0;
1268
- }
1269
- const descriptorCache = /* @__PURE__ */ new WeakMap();
1270
- const blocProxyCache = /* @__PURE__ */ new WeakMap();
1271
- const activeTrackerMap = /* @__PURE__ */ new WeakMap();
1272
- const MAX_GETTER_DEPTH = BLAC_DEFAULTS.MAX_GETTER_DEPTH;
1273
- /**
1274
- * @internal
1275
- */
1276
- function getDescriptor(obj, prop) {
1277
- const constructor = obj.constructor;
1278
- let constructorCache = descriptorCache.get(constructor);
1279
- if (constructorCache?.has(prop)) return constructorCache.get(prop);
1280
- let current = obj;
1281
- let descriptor;
1282
- while (current && current !== Object.prototype) {
1283
- descriptor = Object.getOwnPropertyDescriptor(current, prop);
1284
- if (descriptor) break;
1285
- current = Object.getPrototypeOf(current);
1286
- }
1287
- if (!constructorCache) {
1288
- constructorCache = /* @__PURE__ */ new Map();
1289
- descriptorCache.set(constructor, constructorCache);
1290
- }
1291
- constructorCache.set(prop, descriptor);
1292
- return descriptor;
1293
- }
1294
- /**
1295
- * @internal
1296
- */
1297
- function isGetter(obj, prop) {
1298
- return getDescriptor(obj, prop)?.get !== void 0;
1299
- }
1300
- /**
1301
- * @internal
1302
- */
1303
- function createGetterState() {
1304
- return {
1305
- trackedValues: /* @__PURE__ */ new Map(),
1306
- currentlyAccessing: /* @__PURE__ */ new Set(),
1307
- trackedGetters: /* @__PURE__ */ new Set(),
1308
- isTracking: false,
1309
- renderCache: /* @__PURE__ */ new Map(),
1310
- cacheValid: false,
1311
- depth: 0,
1312
- visitedBlocs: /* @__PURE__ */ new Set()
1313
- };
1314
- }
1315
- /**
1316
- * @internal
1317
- */
1318
- function setActiveTracker(bloc, tracker) {
1319
- activeTrackerMap.set(bloc, tracker);
1320
- }
1321
- /**
1322
- * @internal
1323
- */
1324
- function clearActiveTracker(bloc) {
1325
- activeTrackerMap.delete(bloc);
1326
- }
1327
- /**
1328
- * @internal
1329
- */
1330
- function commitTrackedGetters(tracker) {
1331
- if (tracker.currentlyAccessing.size > 0) tracker.trackedGetters = new Set(tracker.currentlyAccessing);
1332
- tracker.currentlyAccessing.clear();
1333
- }
1334
- /**
1335
- * Execute a tracked getter with depth/circular dependency checks and context management.
1336
- * @internal
1337
- */
1338
- function executeTrackedGetter(target, prop, tracker) {
1339
- tracker.currentlyAccessing.add(prop);
1340
- if (tracker.cacheValid && tracker.renderCache.has(prop)) {
1341
- const cachedValue = tracker.renderCache.get(prop);
1342
- tracker.trackedValues.set(prop, cachedValue);
1343
- return cachedValue;
1344
- }
1345
- if (tracker.depth >= MAX_GETTER_DEPTH) {
1346
- console.warn(`${BLAC_ERROR_PREFIX} Maximum getter depth (${MAX_GETTER_DEPTH}) exceeded. Possible circular dependency in getter "${String(prop)}" on ${target.constructor.name}.`);
1347
- return;
1348
- }
1349
- if (tracker.visitedBlocs.has(target)) {
1350
- console.warn(`${BLAC_ERROR_PREFIX} Circular dependency detected: getter "${String(prop)}" on ${target.constructor.name}.`);
1351
- return;
1352
- }
1353
- const prevDepth = tracker.depth;
1354
- const prevVisited = new Set(tracker.visitedBlocs);
1355
- tracker.depth++;
1356
- tracker.visitedBlocs.add(target);
1357
- try {
1358
- const value = getDescriptor(target, prop).get.call(target);
1359
- tracker.trackedValues.set(prop, value);
1360
- return value;
1361
- } catch (error) {
1362
- tracker.currentlyAccessing.delete(prop);
1363
- throw error;
1364
- } finally {
1365
- tracker.depth = prevDepth;
1366
- tracker.visitedBlocs = prevVisited;
1367
- }
1368
- }
1369
- /**
1370
- * @internal
1371
- */
1372
- function createBlocProxy(bloc) {
1373
- const cached = blocProxyCache.get(bloc);
1374
- if (cached) return cached;
1375
- const proxy = new Proxy(bloc, { get(target, prop, receiver) {
1376
- const tracker = activeTrackerMap.get(target);
1377
- if (tracker?.isTracking && isGetter(target, prop)) return executeTrackedGetter(target, prop, tracker);
1378
- return Reflect.get(target, prop, receiver);
1379
- } });
1380
- blocProxyCache.set(bloc, proxy);
1381
- return proxy;
1382
- }
1383
- /**
1384
- * @internal
1385
- */
1386
- function hasGetterChanges(bloc, tracker) {
1387
- if (!tracker || tracker.trackedGetters.size === 0) return false;
1388
- tracker.renderCache.clear();
1389
- let hasAnyChange = false;
1390
- for (const prop of tracker.trackedGetters) try {
1391
- const descriptor = getDescriptor(bloc, prop);
1392
- if (!descriptor?.get) continue;
1393
- const newValue = descriptor.get.call(bloc);
1394
- const oldValue = tracker.trackedValues.get(prop);
1395
- tracker.renderCache.set(prop, newValue);
1396
- tracker.trackedValues.set(prop, newValue);
1397
- if (!Object.is(newValue, oldValue)) hasAnyChange = true;
1398
- } catch (error) {
1399
- console.warn(`${BLAC_ERROR_PREFIX} Getter "${String(prop)}" threw error during change detection. Stopping tracking for this getter.`, error);
1400
- tracker.trackedGetters.delete(prop);
1401
- tracker.trackedValues.delete(prop);
1402
- tracker.cacheValid = false;
1403
- return true;
1404
- }
1405
- tracker.cacheValid = true;
1406
- return hasAnyChange;
1407
- }
1408
- /**
1409
- * @internal
1410
- */
1411
- function invalidateRenderCache(tracker) {
1412
- tracker.cacheValid = false;
1413
- }
1414
- /**
1415
- * Create a new tracking proxy state.
1416
- */
1417
- function createState() {
1418
- return {
1419
- dependencyState: createDependencyState(),
1420
- getterState: createGetterState(),
1421
- dependencies: /* @__PURE__ */ new Set(),
1422
- isTracking: false
1423
- };
1424
- }
1425
- /**
1426
- * Start tracking on a tracking proxy.
1427
- */
1428
- function startTracking(tracker) {
1429
- tracker.isTracking = true;
1430
- tracker.dependencies.clear();
1431
- tracker.getterState.isTracking = true;
1432
- startDependency(tracker.dependencyState);
1433
- }
1434
- /**
1435
- * Stop tracking and collect all dependencies.
1436
- */
1437
- function stopTracking(tracker, bloc) {
1438
- tracker.isTracking = false;
1439
- tracker.getterState.isTracking = false;
1440
- capturePaths(tracker.dependencyState, bloc.state);
1441
- commitTrackedGetters(tracker.getterState);
1442
- return new Set(tracker.dependencies);
1443
- }
1444
- /**
1445
- * Check if tracked state or getters have changed.
1446
- */
1447
- function hasChanges(tracker, bloc) {
1448
- invalidateRenderCache(tracker.getterState);
1449
- const stateChanged = hasDependencyChanges(tracker.dependencyState, bloc.state);
1450
- const getterChanged = hasGetterChanges(bloc, tracker.getterState);
1451
- return stateChanged || getterChanged;
1452
- }
1453
- /**
1454
- * Create a tracking proxy for a bloc instance.
1455
- * Tracks both state property access and getter access.
1456
- */
1457
- function createTrackingProxy(bloc, tracker) {
1458
- tracker.dependencies.add(bloc);
1459
- const stateProxyCache = /* @__PURE__ */ new WeakMap();
1460
- return new Proxy(bloc, { get(target, prop, receiver) {
1461
- if (prop === "state") {
1462
- if (!tracker.isTracking) return target.state;
1463
- const rawState = target.state;
1464
- if (rawState === null || typeof rawState !== "object") return rawState;
1465
- if (stateProxyCache.has(rawState)) return stateProxyCache.get(rawState);
1466
- const stateProxy = createDependencyProxy(tracker.dependencyState, rawState);
1467
- stateProxyCache.set(rawState, stateProxy);
1468
- return stateProxy;
1469
- }
1470
- if (typeof prop === "symbol") return Reflect.get(target, prop, receiver);
1471
- const value = Reflect.get(target, prop, receiver);
1472
- if (typeof value === "function") return value.bind(target);
1473
- if (tracker.isTracking && isGetter(target, prop)) return executeTrackedGetter(target, prop, tracker.getterState);
1474
- return value;
1475
- } });
1476
- }
1477
-
1478
- //#endregion
1479
- //#region src/tracking/dependency-manager.ts
1480
- /**
1481
- * Manages subscriptions to state container dependencies.
1482
- * Provides efficient sync mechanism to add/remove subscriptions
1483
- * as dependencies change between callback invocations.
1484
- */
1485
- var DependencyManager = class {
1486
- constructor() {
1487
- this.subscriptions = /* @__PURE__ */ new Map();
1488
- this.currentDeps = /* @__PURE__ */ new Set();
1489
- }
1490
- /**
1491
- * Sync subscriptions with a new set of dependencies.
1492
- * Adds subscriptions for new deps, removes subscriptions for stale deps.
1493
- *
1494
- * @param newDeps - The new set of dependencies to subscribe to
1495
- * @param onChange - Callback to invoke when any dependency changes
1496
- * @param exclude - Optional instance to exclude from subscriptions (e.g., primary bloc)
1497
- * @returns true if the dependency set changed, false if unchanged
1498
- */
1499
- sync(newDeps, onChange, exclude) {
1500
- const filteredNewDeps = /* @__PURE__ */ new Set();
1501
- for (const dep of newDeps) if (dep !== exclude && !dep.isDisposed) filteredNewDeps.add(dep);
1502
- if (this.areSetsEqual(this.currentDeps, filteredNewDeps)) return false;
1503
- for (const dep of this.currentDeps) if (!filteredNewDeps.has(dep)) {
1504
- const unsub = this.subscriptions.get(dep);
1505
- if (unsub) {
1506
- unsub();
1507
- this.subscriptions.delete(dep);
1508
- }
1509
- }
1510
- for (const dep of filteredNewDeps) if (!this.currentDeps.has(dep) && !this.subscriptions.has(dep)) {
1511
- const unsub = dep.subscribe(onChange);
1512
- this.subscriptions.set(dep, unsub);
1513
- }
1514
- this.currentDeps = filteredNewDeps;
1515
- return true;
1516
- }
1517
- /**
1518
- * Add a single dependency subscription.
1519
- */
1520
- add(dep, onChange) {
1521
- if (this.subscriptions.has(dep) || dep.isDisposed) return;
1522
- const unsub = dep.subscribe(onChange);
1523
- this.subscriptions.set(dep, unsub);
1524
- this.currentDeps.add(dep);
1525
- }
1526
- /**
1527
- * Check if a dependency is currently subscribed.
1528
- */
1529
- has(dep) {
1530
- return this.currentDeps.has(dep);
1531
- }
1532
- /**
1533
- * Get the current set of dependencies.
1534
- */
1535
- getDependencies() {
1536
- return new Set(this.currentDeps);
1537
- }
1538
- /**
1539
- * Clean up all active subscriptions.
1540
- */
1541
- cleanup() {
1542
- for (const unsub of this.subscriptions.values()) unsub();
1543
- this.subscriptions.clear();
1544
- this.currentDeps.clear();
1545
- }
1546
- areSetsEqual(a, b) {
1547
- if (a.size !== b.size) return false;
1548
- for (const item of a) if (!b.has(item)) return false;
1549
- return true;
1550
- }
1551
- };
1552
-
1553
- //#endregion
1554
- //#region src/tracking/resolve-dependencies.ts
1555
- /**
1556
- * Resolve all transitive dependencies of a bloc via BFS over `dependencies` maps.
1557
- * Uses cycle detection to avoid infinite loops.
1558
- * @internal
1559
- */
1560
- function resolveDependencies(bloc) {
1561
- const result = /* @__PURE__ */ new Set();
1562
- const visited = /* @__PURE__ */ new Set();
1563
- const queue = [bloc];
1564
- while (queue.length > 0) {
1565
- const current = queue.shift();
1566
- for (const [Type, key] of current.dependencies) {
1567
- if (visited.has(Type)) continue;
1568
- visited.add(Type);
1569
- const dep = globalRegistry.ensure(Type, key);
1570
- result.add(dep);
1571
- if (dep.dependencies.size > 0) queue.push(dep);
1572
- }
1573
- }
1574
- result.delete(bloc);
1575
- return result;
1576
- }
1577
-
1578
- //#endregion
1579
- //#region src/watch/watch.ts
1580
- const STOP = Symbol("watch.STOP");
1581
- const BLOC_REF_MARKER = Symbol("BlocRef");
1582
- /**
1583
- * Create a reference to a specific bloc instance.
1584
- *
1585
- * @example
1586
- * ```ts
1587
- * watch(instance(UserBloc, 'user-123'), (userBloc) => {
1588
- * console.log(userBloc.state.name);
1589
- * });
1590
- * ```
1591
- */
1592
- function instance(BlocClass, instanceId) {
1593
- return {
1594
- [BLOC_REF_MARKER]: true,
1595
- blocClass: BlocClass,
1596
- instanceId
1597
- };
1598
- }
1599
- function isBlocRef(input) {
1600
- return typeof input === "object" && input !== null && BLOC_REF_MARKER in input;
1601
- }
1602
- function resolveBloc(input) {
1603
- if (isBlocRef(input)) return ensure(input.blocClass, input.instanceId);
1604
- return ensure(input, BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY);
1605
- }
1606
- function isArray(input) {
1607
- return Array.isArray(input);
1608
- }
1609
- function watchImpl(blocsOrBloc, callback) {
1610
- const isSingle = !isArray(blocsOrBloc);
1611
- const instances = (isSingle ? [blocsOrBloc] : blocsOrBloc).map(resolveBloc);
1612
- const tracker = createState();
1613
- const proxiedInstances = instances.map((inst) => createTrackingProxy(inst, tracker));
1614
- const externalDepsManager = new DependencyManager();
1615
- let disposed = false;
1616
- const primarySubscriptions = [];
1617
- const cleanup = () => {
1618
- if (disposed) return;
1619
- disposed = true;
1620
- primarySubscriptions.forEach((unsub) => unsub());
1621
- externalDepsManager.cleanup();
1622
- };
1623
- const runCallback = () => {
1624
- if (disposed) return;
1625
- startTracking(tracker);
1626
- let result;
1627
- try {
1628
- result = callback(isSingle ? proxiedInstances[0] : proxiedInstances);
1629
- } finally {
1630
- const externalDeps = /* @__PURE__ */ new Set();
1631
- for (const inst of instances) {
1632
- const deps = stopTracking(tracker, inst);
1633
- for (const dep of deps) externalDeps.add(dep);
1634
- for (const dep of resolveDependencies(inst)) externalDeps.add(dep);
1635
- }
1636
- for (const inst of instances) externalDeps.delete(inst);
1637
- externalDepsManager.sync(externalDeps, runCallback);
1638
- }
1639
- if (result === STOP) cleanup();
1640
- };
1641
- const onChange = () => {
1642
- if (disposed) return;
1643
- runCallback();
1644
- };
1645
- for (const inst of instances) primarySubscriptions.push(inst.subscribe(onChange));
1646
- runCallback();
1647
- return cleanup;
1648
- }
1649
- const watch = Object.assign(watchImpl, { STOP });
1650
-
1651
- //#endregion
1652
- //#region src/tracking/tracked.ts
1653
- /**
1654
- * Run a callback while tracking all bloc dependencies accessed.
1655
- * Returns both the result and the set of discovered dependencies.
1656
- *
1657
- * @example
1658
- * ```ts
1659
- * const { result, dependencies } = tracked(() => {
1660
- * const user = ensure(UserBloc);
1661
- * return user.fullName; // getter that may access other blocs
1662
- * });
1663
- * // dependencies contains UserBloc + any blocs accessed in fullName getter
1664
- * ```
1665
- */
1666
- function tracked(callback, options) {
1667
- const tracker = createState();
1668
- startTracking(tracker);
1669
- let result;
1670
- try {
1671
- result = callback();
1672
- } finally {
1673
- stopTracking(tracker, { state: null });
1674
- }
1675
- const dependencies = new Set(tracker.dependencies);
1676
- if (options?.exclude) dependencies.delete(options.exclude);
1677
- return {
1678
- result,
1679
- dependencies
1680
- };
1681
- }
1682
- /**
1683
- * Context for running tracked callbacks with bloc proxies.
1684
- * Provides methods to create proxies and check for changes.
1685
- */
1686
- var TrackedContext = class {
1687
- constructor() {
1688
- this.proxiedBlocs = /* @__PURE__ */ new WeakMap();
1689
- this.primaryBlocs = /* @__PURE__ */ new Set();
1690
- this.tracker = createState();
1691
- }
1692
- /**
1693
- * Get a tracking proxy for a bloc instance.
1694
- * The proxy will track state and getter accesses.
1695
- */
1696
- proxy(bloc) {
1697
- const cached = this.proxiedBlocs.get(bloc);
1698
- if (cached) return cached;
1699
- const proxied = createTrackingProxy(bloc, this.tracker);
1700
- this.proxiedBlocs.set(bloc, proxied);
1701
- this.primaryBlocs.add(bloc);
1702
- return proxied;
1703
- }
1704
- /**
1705
- * Start tracking for a new callback execution.
1706
- */
1707
- start() {
1708
- startTracking(this.tracker);
1709
- }
1710
- /**
1711
- * Stop tracking and get discovered dependencies.
1712
- * Excludes primary blocs (those explicitly proxied via proxy()).
1713
- */
1714
- stop() {
1715
- const allDeps = /* @__PURE__ */ new Set();
1716
- for (const bloc of this.primaryBlocs) {
1717
- const deps = stopTracking(this.tracker, bloc);
1718
- for (const dep of deps) if (!this.primaryBlocs.has(dep)) allDeps.add(dep);
1719
- }
1720
- return allDeps;
1721
- }
1722
- /**
1723
- * Check if any tracked state or getters have changed.
1724
- */
1725
- changed() {
1726
- for (const bloc of this.primaryBlocs) if (hasChanges(this.tracker, bloc)) return true;
1727
- return false;
1728
- }
1729
- /**
1730
- * Get all primary blocs (those explicitly proxied).
1731
- */
1732
- getPrimaryBlocs() {
1733
- return new Set(this.primaryBlocs);
1734
- }
1735
- /**
1736
- * Reset the context for reuse.
1737
- */
1738
- reset() {
1739
- this.tracker = createState();
1740
- this.proxiedBlocs = /* @__PURE__ */ new WeakMap();
1741
- this.primaryBlocs.clear();
1742
- }
1743
- };
1744
- /**
1745
- * Create a new tracked context for manual control over tracking.
1746
- */
1747
- function createTrackedContext() {
1748
- return new TrackedContext();
1749
- }
1750
-
1751
- //#endregion
1752
- //#region src/types/branded.ts
1753
- /**
1754
- * Create a branded InstanceId from a string
1755
- * @param id - The string ID to brand
1756
- * @returns Branded InstanceId
1757
- */
1758
- function instanceId(id) {
1759
- return id;
1760
- }
1761
-
1762
339
  //#endregion
1763
340
  exports.Cubit = Cubit;
1764
- exports.DependencyManager = DependencyManager;
1765
- exports.PluginManager = PluginManager;
341
+ exports.EMIT = EMIT;
342
+ exports.PluginManager = require_StateContainerRegistry.PluginManager;
1766
343
  exports.StateContainer = StateContainer;
1767
- exports.TrackedContext = TrackedContext;
344
+ exports.TrackedContext = require_tracked.TrackedContext;
345
+ exports.UPDATE = UPDATE;
1768
346
  exports.acquire = acquire;
1769
347
  exports.blac = blac;
1770
348
  exports.borrow = borrow;
1771
349
  exports.borrowSafe = borrowSafe;
1772
- exports.capturePaths = capturePaths;
1773
- exports.clear = clear;
1774
- exports.clearActiveTracker = clearActiveTracker;
1775
- exports.clearAll = clearAll;
1776
- exports.commitTrackedGetters = commitTrackedGetters;
1777
- exports.createBlocProxy = createBlocProxy;
1778
- exports.createDependencyProxy = createDependencyProxy;
1779
- exports.createDependencyState = createDependencyState;
1780
- exports.createGetterState = createGetterState;
1781
- exports.createTrackedContext = createTrackedContext;
1782
- exports.ensure = ensure;
1783
- exports.forEach = forEach;
1784
- exports.generateIsolatedKey = generateIsolatedKey;
1785
- exports.getAll = getAll;
1786
- exports.getPluginManager = getPluginManager;
1787
- exports.getRefCount = getRefCount;
1788
- exports.getRegistry = getRegistry;
1789
- exports.getStats = getStats;
1790
- exports.globalRegistry = globalRegistry;
1791
- exports.hasDependencyChanges = hasDependencyChanges;
1792
- exports.hasGetterChanges = hasGetterChanges;
1793
- exports.hasInstance = hasInstance;
1794
- exports.hasTrackedData = hasTrackedData;
1795
- exports.instance = instance;
1796
- exports.instanceId = instanceId;
1797
- exports.invalidateRenderCache = invalidateRenderCache;
1798
- exports.isIsolatedClass = isIsolatedClass;
1799
- exports.register = register;
350
+ exports.clear = require_config.clear;
351
+ exports.clearAll = require_config.clearAll;
352
+ exports.createTrackedContext = require_tracked.createTrackedContext;
353
+ exports.ensure = require_tracked.ensure;
354
+ exports.forEach = require_config.forEach;
355
+ exports.getAll = require_config.getAll;
356
+ exports.getPluginManager = require_StateContainerRegistry.getPluginManager;
357
+ exports.getRefCount = require_config.getRefCount;
358
+ exports.getRegistry = require_config.getRegistry;
359
+ exports.getStats = require_config.getStats;
360
+ exports.globalRegistry = require_StateContainerRegistry.globalRegistry;
361
+ exports.hasInstance = require_config.hasInstance;
362
+ exports.instance = require_tracked.instance;
363
+ exports.instanceId = require_branded.instanceId;
364
+ exports.register = require_config.register;
1800
365
  exports.release = release;
1801
- exports.resolveDependencies = resolveDependencies;
1802
- exports.setActiveTracker = setActiveTracker;
1803
- exports.setRegistry = setRegistry;
1804
- exports.shallowEqual = shallowEqual;
1805
- exports.startDependency = startDependency;
1806
- exports.tracked = tracked;
1807
- exports.watch = watch;
366
+ exports.setRegistry = require_config.setRegistry;
367
+ exports.tracked = require_tracked.tracked;
368
+ exports.watch = require_tracked.watch;
369
+
1808
370
  //# sourceMappingURL=index.cjs.map