@blac/core 2.0.0-rc.1 → 2.0.0-rc.11

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 (121) hide show
  1. package/dist/index.cjs +2100 -38
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +1298 -0
  4. package/dist/index.d.ts +1298 -17
  5. package/dist/index.js +2028 -37
  6. package/dist/index.js.map +1 -1
  7. package/package.json +35 -13
  8. package/dist/.tsbuildinfo +0 -1
  9. package/dist/Blac.d.ts +0 -246
  10. package/dist/Blac.d.ts.map +0 -1
  11. package/dist/Blac.js +0 -624
  12. package/dist/Blac.js.map +0 -1
  13. package/dist/Bloc.d.ts +0 -41
  14. package/dist/Bloc.d.ts.map +0 -1
  15. package/dist/Bloc.js +0 -140
  16. package/dist/Bloc.js.map +0 -1
  17. package/dist/BlocBase.d.ts +0 -110
  18. package/dist/BlocBase.d.ts.map +0 -1
  19. package/dist/BlocBase.js +0 -287
  20. package/dist/BlocBase.js.map +0 -1
  21. package/dist/Cubit.d.ts +0 -25
  22. package/dist/Cubit.d.ts.map +0 -1
  23. package/dist/Cubit.js +0 -64
  24. package/dist/Cubit.js.map +0 -1
  25. package/dist/adapter/BlacAdapter.d.ts +0 -67
  26. package/dist/adapter/BlacAdapter.d.ts.map +0 -1
  27. package/dist/adapter/BlacAdapter.js +0 -263
  28. package/dist/adapter/BlacAdapter.js.map +0 -1
  29. package/dist/adapter/ProxyFactory.d.ts +0 -50
  30. package/dist/adapter/ProxyFactory.d.ts.map +0 -1
  31. package/dist/adapter/ProxyFactory.js +0 -150
  32. package/dist/adapter/ProxyFactory.js.map +0 -1
  33. package/dist/adapter/index.d.ts +0 -3
  34. package/dist/adapter/index.d.ts.map +0 -1
  35. package/dist/adapter/index.js +0 -19
  36. package/dist/adapter/index.js.map +0 -1
  37. package/dist/errors/BlacError.d.ts +0 -38
  38. package/dist/errors/BlacError.d.ts.map +0 -1
  39. package/dist/errors/BlacError.js +0 -55
  40. package/dist/errors/BlacError.js.map +0 -1
  41. package/dist/errors/ErrorManager.d.ts +0 -39
  42. package/dist/errors/ErrorManager.d.ts.map +0 -1
  43. package/dist/errors/ErrorManager.js +0 -91
  44. package/dist/errors/ErrorManager.js.map +0 -1
  45. package/dist/errors/handleError.d.ts +0 -24
  46. package/dist/errors/handleError.d.ts.map +0 -1
  47. package/dist/errors/handleError.js +0 -62
  48. package/dist/errors/handleError.js.map +0 -1
  49. package/dist/errors/index.d.ts +0 -5
  50. package/dist/errors/index.d.ts.map +0 -1
  51. package/dist/errors/index.js +0 -13
  52. package/dist/errors/index.js.map +0 -1
  53. package/dist/events.d.ts +0 -11
  54. package/dist/events.d.ts.map +0 -1
  55. package/dist/events.js +0 -17
  56. package/dist/events.js.map +0 -1
  57. package/dist/index.d.ts.map +0 -1
  58. package/dist/lifecycle/BlocLifecycle.d.ts +0 -51
  59. package/dist/lifecycle/BlocLifecycle.d.ts.map +0 -1
  60. package/dist/lifecycle/BlocLifecycle.js +0 -123
  61. package/dist/lifecycle/BlocLifecycle.js.map +0 -1
  62. package/dist/lifecycle/index.d.ts +0 -2
  63. package/dist/lifecycle/index.d.ts.map +0 -1
  64. package/dist/lifecycle/index.js +0 -18
  65. package/dist/lifecycle/index.js.map +0 -1
  66. package/dist/plugins/BlocPluginRegistry.d.ts +0 -58
  67. package/dist/plugins/BlocPluginRegistry.d.ts.map +0 -1
  68. package/dist/plugins/BlocPluginRegistry.js +0 -201
  69. package/dist/plugins/BlocPluginRegistry.js.map +0 -1
  70. package/dist/plugins/SystemPluginRegistry.d.ts +0 -79
  71. package/dist/plugins/SystemPluginRegistry.d.ts.map +0 -1
  72. package/dist/plugins/SystemPluginRegistry.js +0 -184
  73. package/dist/plugins/SystemPluginRegistry.js.map +0 -1
  74. package/dist/plugins/index.d.ts +0 -4
  75. package/dist/plugins/index.d.ts.map +0 -1
  76. package/dist/plugins/index.js +0 -26
  77. package/dist/plugins/index.js.map +0 -1
  78. package/dist/plugins/types.d.ts +0 -103
  79. package/dist/plugins/types.d.ts.map +0 -1
  80. package/dist/plugins/types.js +0 -3
  81. package/dist/plugins/types.js.map +0 -1
  82. package/dist/subscription/SubscriptionManager.d.ts +0 -67
  83. package/dist/subscription/SubscriptionManager.d.ts.map +0 -1
  84. package/dist/subscription/SubscriptionManager.js +0 -317
  85. package/dist/subscription/SubscriptionManager.js.map +0 -1
  86. package/dist/subscription/index.d.ts +0 -3
  87. package/dist/subscription/index.d.ts.map +0 -1
  88. package/dist/subscription/index.js +0 -19
  89. package/dist/subscription/index.js.map +0 -1
  90. package/dist/subscription/types.d.ts +0 -65
  91. package/dist/subscription/types.d.ts.map +0 -1
  92. package/dist/subscription/types.js +0 -3
  93. package/dist/subscription/types.js.map +0 -1
  94. package/dist/testing.d.ts +0 -33
  95. package/dist/testing.d.ts.map +0 -1
  96. package/dist/testing.js +0 -68
  97. package/dist/testing.js.map +0 -1
  98. package/dist/types.d.ts +0 -57
  99. package/dist/types.d.ts.map +0 -1
  100. package/dist/types.js +0 -3
  101. package/dist/types.js.map +0 -1
  102. package/dist/utils/BatchingManager.d.ts +0 -28
  103. package/dist/utils/BatchingManager.d.ts.map +0 -1
  104. package/dist/utils/BatchingManager.js +0 -48
  105. package/dist/utils/BatchingManager.js.map +0 -1
  106. package/dist/utils/RerenderLogger.d.ts +0 -60
  107. package/dist/utils/RerenderLogger.d.ts.map +0 -1
  108. package/dist/utils/RerenderLogger.js +0 -205
  109. package/dist/utils/RerenderLogger.js.map +0 -1
  110. package/dist/utils/generateInstanceId.d.ts +0 -11
  111. package/dist/utils/generateInstanceId.d.ts.map +0 -1
  112. package/dist/utils/generateInstanceId.js +0 -50
  113. package/dist/utils/generateInstanceId.js.map +0 -1
  114. package/dist/utils/shallowEqual.d.ts +0 -9
  115. package/dist/utils/shallowEqual.d.ts.map +0 -1
  116. package/dist/utils/shallowEqual.js +0 -35
  117. package/dist/utils/shallowEqual.js.map +0 -1
  118. package/dist/utils/uuid.d.ts +0 -10
  119. package/dist/utils/uuid.d.ts.map +0 -1
  120. package/dist/utils/uuid.js +0 -24
  121. package/dist/utils/uuid.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,38 +1,2029 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./Blac"), exports);
18
- __exportStar(require("./Bloc"), exports);
19
- __exportStar(require("./BlocBase"), exports);
20
- __exportStar(require("./Cubit"), exports);
21
- __exportStar(require("./types"), exports);
22
- __exportStar(require("./events"), exports);
23
- __exportStar(require("./subscription"), exports);
24
- __exportStar(require("./lifecycle"), exports);
25
- // Utilities
26
- __exportStar(require("./utils/uuid"), exports);
27
- __exportStar(require("./utils/shallowEqual"), exports);
28
- __exportStar(require("./utils/generateInstanceId"), exports);
29
- __exportStar(require("./utils/RerenderLogger"), exports);
30
- // Test utilities
31
- __exportStar(require("./testing"), exports);
32
- // Adapter
33
- __exportStar(require("./adapter"), exports);
34
- // Plugins
35
- __exportStar(require("./plugins"), exports);
36
- // Error handling
37
- __exportStar(require("./errors"), exports);
1
+ //#region src/utils/idGenerator.ts
2
+ /**
3
+ * Centralized ID Generation
4
+ *
5
+ * Provides consistent, collision-resistant ID generation for all BlaC subsystems.
6
+ * Uses timestamp + counter + random suffix for uniqueness.
7
+ */
8
+ const globalCounters = /* @__PURE__ */ new Map();
9
+ /**
10
+ * Creates an ID generator with isolated counter state
11
+ *
12
+ * @param prefix - Prefix for generated IDs
13
+ * @returns Object with next(), nextSimple(), and reset() methods
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const generator = createIdGenerator('sub');
18
+ * const id1 = generator.next(); // "sub:1698765432100_1_a3k9d7f2q"
19
+ * const id2 = generator.next(); // "sub:1698765432101_2_b4n8e9g3r"
20
+ * ```
21
+ */
22
+ function createIdGenerator(prefix) {
23
+ let counter = 0;
24
+ return {
25
+ next: () => `${prefix}:${Date.now()}_${++counter}_${Math.random().toString(36).substring(2, 11)}`,
26
+ nextSimple: () => `${prefix}:${++counter}`,
27
+ reset: () => {
28
+ counter = 0;
29
+ }
30
+ };
31
+ }
32
+ /**
33
+ * Generate ID with timestamp, counter, and random suffix (tree-shakeable)
34
+ *
35
+ * Format: `${prefix}:${timestamp}_${counter}_${random}`
36
+ *
37
+ * @param prefix - Prefix for the ID (e.g., 'sub', 'consumer', 'stage')
38
+ * @returns Branded ID string
39
+ *
40
+ * @example
41
+ * const id = generateId('sub');
42
+ * // Returns: "sub:1698765432100_1_a3k9d7f2q"
43
+ */
44
+ function generateId(prefix) {
45
+ const counter = (globalCounters.get(prefix) ?? 0) + 1;
46
+ globalCounters.set(prefix, counter);
47
+ return `${prefix}:${Date.now()}_${counter}_${Math.random().toString(36).substring(2, 11)}`;
48
+ }
49
+ /**
50
+ * Generate simple ID with timestamp and random (no counter tracking)
51
+ *
52
+ * Format: `${prefix}:${timestamp}_${random}`
53
+ *
54
+ * @param prefix - Prefix for the ID
55
+ * @returns Branded ID string
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const id = generateSimpleId('CounterBloc');
60
+ * // Returns: "CounterBloc:1698765432100_a3k9d7f2q"
61
+ * ```
62
+ */
63
+ function generateSimpleId(prefix, affix) {
64
+ if (affix) return `${prefix}:${affix}`;
65
+ return `${prefix}:${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
66
+ }
67
+ /**
68
+ * Reset all counters for testing purposes
69
+ * @internal
70
+ */
71
+ function __resetIdCounters() {
72
+ globalCounters.clear();
73
+ }
74
+ /**
75
+ * Generate a unique isolated instance key
76
+ * Uses base36 encoding for compact, URL-safe identifiers
77
+ *
78
+ * Format: "isolated-{9-char-random-string}"
79
+ * Example: "isolated-k7x2m9p4q"
80
+ *
81
+ * @returns A unique isolated instance key
82
+ */
83
+ function generateIsolatedKey() {
84
+ return `isolated-${Math.random().toString(36).slice(2, 11)}`;
85
+ }
86
+ /**
87
+ * Check if a key is an isolated instance key
88
+ * @param key - The instance key to check
89
+ * @returns true if the key is an isolated instance key
90
+ */
91
+ function isIsolatedKey(key) {
92
+ return key.startsWith("isolated-");
93
+ }
94
+
95
+ //#endregion
96
+ //#region src/plugin/PluginManager.ts
97
+ /**
98
+ * Manages plugin lifecycle for the BlaC state management system.
99
+ * Plugins receive notifications about state container lifecycle events.
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * const manager = createPluginManager(registry);
104
+ * manager.install(myPlugin, { environment: 'development' });
105
+ * ```
106
+ */
107
+ var PluginManager = class {
108
+ /**
109
+ * Create a new PluginManager
110
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
111
+ */
112
+ constructor(registry) {
113
+ this.plugins = /* @__PURE__ */ new Map();
114
+ this.registry = registry;
115
+ this.setupLifecycleHooks();
116
+ }
117
+ /**
118
+ * Install a plugin with optional configuration
119
+ * @param plugin - The plugin to install
120
+ * @param config - Optional plugin configuration
121
+ * @throws Error if plugin is already installed
122
+ */
123
+ install(plugin, config = {}) {
124
+ const effectiveConfig = {
125
+ enabled: true,
126
+ environment: "all",
127
+ ...config
128
+ };
129
+ if (!this.shouldEnablePlugin(effectiveConfig)) {
130
+ console.log(`[BlaC] Plugin "${plugin.name}" skipped (environment mismatch)`);
131
+ return;
132
+ }
133
+ if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already installed`);
134
+ const context = this.createPluginContext();
135
+ this.plugins.set(plugin.name, {
136
+ plugin,
137
+ config: effectiveConfig,
138
+ context
139
+ });
140
+ if (plugin.onInstall) try {
141
+ plugin.onInstall(context);
142
+ } catch (error$1) {
143
+ console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error$1);
144
+ this.plugins.delete(plugin.name);
145
+ throw error$1;
146
+ }
147
+ console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
148
+ }
149
+ /**
150
+ * Uninstall a plugin by name
151
+ * @param pluginName - The name of the plugin to uninstall
152
+ * @throws Error if plugin is not installed
153
+ */
154
+ uninstall(pluginName) {
155
+ const installed = this.plugins.get(pluginName);
156
+ if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
157
+ if (installed.plugin.onUninstall) try {
158
+ installed.plugin.onUninstall();
159
+ } catch (error$1) {
160
+ console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error$1);
161
+ }
162
+ this.plugins.delete(pluginName);
163
+ console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
164
+ }
165
+ /**
166
+ * Get an installed plugin by name
167
+ * @param pluginName - The name of the plugin to retrieve
168
+ * @returns The plugin instance or undefined if not found
169
+ */
170
+ getPlugin(pluginName) {
171
+ return this.plugins.get(pluginName)?.plugin;
172
+ }
173
+ /**
174
+ * Get all installed plugins
175
+ * @returns Array of all installed plugins
176
+ */
177
+ getAllPlugins() {
178
+ return Array.from(this.plugins.values()).map((p) => p.plugin);
179
+ }
180
+ /**
181
+ * Check if a plugin is installed
182
+ * @param pluginName - The name of the plugin to check
183
+ * @returns true if the plugin is installed
184
+ */
185
+ hasPlugin(pluginName) {
186
+ return this.plugins.has(pluginName);
187
+ }
188
+ /**
189
+ * Uninstall all plugins
190
+ */
191
+ clear() {
192
+ for (const name of this.plugins.keys()) this.uninstall(name);
193
+ }
194
+ /**
195
+ * Setup lifecycle hooks to notify plugins
196
+ */
197
+ setupLifecycleHooks() {
198
+ this.registry.on("created", (instance) => {
199
+ this.notifyPlugins("onInstanceCreated", instance);
200
+ });
201
+ this.registry.on("stateChanged", (instance, previousState, currentState, callstack) => {
202
+ this.notifyPlugins("onStateChanged", instance, previousState, currentState, callstack);
203
+ });
204
+ this.registry.on("eventAdded", (vertex, event) => {
205
+ this.notifyPlugins("onEventAdded", vertex, event);
206
+ });
207
+ this.registry.on("disposed", (instance) => {
208
+ this.notifyPlugins("onInstanceDisposed", instance);
209
+ });
210
+ }
211
+ /**
212
+ * Notify all plugins of a lifecycle event
213
+ */
214
+ notifyPlugins(hookName, ...args) {
215
+ for (const { plugin, config, context } of this.plugins.values()) {
216
+ if (!config.enabled) continue;
217
+ const hook = plugin[hookName];
218
+ if (typeof hook === "function") try {
219
+ hook.apply(plugin, [...args, context]);
220
+ } catch (error$1) {
221
+ console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error$1);
222
+ }
223
+ }
224
+ }
225
+ /**
226
+ * Create plugin context with safe API access
227
+ */
228
+ createPluginContext() {
229
+ return {
230
+ getInstanceMetadata: (instance) => {
231
+ return {
232
+ id: instance.instanceId,
233
+ className: instance.constructor.name,
234
+ isDisposed: instance.isDisposed,
235
+ name: instance.name,
236
+ lastStateChangeTimestamp: instance.lastUpdateTimestamp,
237
+ createdAt: instance.createdAt,
238
+ state: instance.state,
239
+ isIsolated: instance.instanceId.startsWith("isolated-")
240
+ };
241
+ },
242
+ getState: (instance) => {
243
+ return instance.state;
244
+ },
245
+ queryInstances: (typeClass) => {
246
+ return typeClass.getAll();
247
+ },
248
+ getAllTypes: () => {
249
+ return this.registry.getTypes();
250
+ },
251
+ getStats: () => {
252
+ return this.registry.getStats();
253
+ }
254
+ };
255
+ }
256
+ /**
257
+ * Check if plugin should be enabled based on environment
258
+ */
259
+ shouldEnablePlugin(config) {
260
+ if (!config.enabled) return false;
261
+ if (config.environment === "all") return true;
262
+ return this.getCurrentEnvironment() === config.environment;
263
+ }
264
+ /**
265
+ * Get current environment
266
+ */
267
+ getCurrentEnvironment() {
268
+ if (typeof process !== "undefined") {
269
+ if (process.env.NODE_ENV === "test") return "test";
270
+ if (process.env.NODE_ENV === "production") return "production";
271
+ return "development";
272
+ }
273
+ return "development";
274
+ }
275
+ };
276
+ /**
277
+ * Create a plugin manager instance
278
+ */
279
+ function createPluginManager(registry) {
280
+ return new PluginManager(registry);
281
+ }
282
+
283
+ //#endregion
284
+ //#region src/constants.ts
285
+ /**
286
+ * Default configuration constants for BlaC
287
+ *
288
+ * Centralized location for all magic numbers and default values.
289
+ */
290
+ /**
291
+ * Default configuration constants for BlaC
292
+ */
293
+ const BLAC_DEFAULTS = {
294
+ DEFAULT_INSTANCE_KEY: "default",
295
+ MAX_GETTER_DEPTH: 10,
296
+ CLEANUP_INTERVAL_MS: 3e4,
297
+ WEAKREF_CLEANUP_INTERVAL_MS: 1e4,
298
+ MAX_SUBSCRIPTIONS: 1e3,
299
+ MAX_SUBSCRIPTIONS_HIGH_PERF: 1e4,
300
+ PIPELINE_TIMEOUT_MS: 5e3,
301
+ CLEANUP_INTERVAL_HIGH_PERF_MS: 5e3,
302
+ MAX_PIPELINE_STAGES: 30
303
+ };
304
+ /**
305
+ * Static property names for StateContainer classes
306
+ * Used for feature flags and configuration on bloc classes
307
+ */
308
+ const BLAC_STATIC_PROPS = {
309
+ ISOLATED: "isolated",
310
+ KEEP_ALIVE: "keepAlive",
311
+ EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools"
312
+ };
313
+ /**
314
+ * ID generation patterns and constants
315
+ */
316
+ const BLAC_ID_PATTERNS = {
317
+ ISOLATED_PREFIX: "isolated-",
318
+ ID_LENGTH: 9
319
+ };
320
+ /**
321
+ * Standard error message prefix
322
+ */
323
+ const BLAC_ERROR_PREFIX = "[BlaC]";
324
+
325
+ //#endregion
326
+ //#region src/tracking/getter-tracker.ts
327
+ const descriptorCache = /* @__PURE__ */ new WeakMap();
328
+ const blocProxyCache = /* @__PURE__ */ new WeakMap();
329
+ const activeTrackerMap = /* @__PURE__ */ new WeakMap();
330
+ const getterExecutionContext = {
331
+ tracker: null,
332
+ currentBloc: null,
333
+ depth: 0,
334
+ visitedBlocs: /* @__PURE__ */ new Set()
335
+ };
336
+ const MAX_GETTER_DEPTH = BLAC_DEFAULTS.MAX_GETTER_DEPTH;
337
+ /**
338
+ * @internal
339
+ */
340
+ function getGetterExecutionContext() {
341
+ return getterExecutionContext;
342
+ }
343
+ /**
344
+ * @internal
345
+ */
346
+ function getDescriptor(obj, prop) {
347
+ const constructor = obj.constructor;
348
+ let constructorCache = descriptorCache.get(constructor);
349
+ if (constructorCache?.has(prop)) return constructorCache.get(prop);
350
+ let current = obj;
351
+ let descriptor;
352
+ while (current && current !== Object.prototype) {
353
+ descriptor = Object.getOwnPropertyDescriptor(current, prop);
354
+ if (descriptor) break;
355
+ current = Object.getPrototypeOf(current);
356
+ }
357
+ if (!constructorCache) {
358
+ constructorCache = /* @__PURE__ */ new Map();
359
+ descriptorCache.set(constructor, constructorCache);
360
+ }
361
+ constructorCache.set(prop, descriptor);
362
+ return descriptor;
363
+ }
364
+ /**
365
+ * @internal
366
+ */
367
+ function isGetter(obj, prop) {
368
+ return getDescriptor(obj, prop)?.get !== void 0;
369
+ }
370
+ /**
371
+ * @internal
372
+ */
373
+ function createGetterTracker() {
374
+ return {
375
+ trackedValues: /* @__PURE__ */ new Map(),
376
+ currentlyAccessing: /* @__PURE__ */ new Set(),
377
+ trackedGetters: /* @__PURE__ */ new Set(),
378
+ isTracking: false,
379
+ renderCache: /* @__PURE__ */ new Map(),
380
+ cacheValid: false,
381
+ externalDependencies: /* @__PURE__ */ new Set()
382
+ };
383
+ }
384
+ /**
385
+ * @internal
386
+ */
387
+ function setActiveTracker(bloc, tracker) {
388
+ activeTrackerMap.set(bloc, tracker);
389
+ }
390
+ /**
391
+ * @internal
392
+ */
393
+ function clearActiveTracker(bloc) {
394
+ activeTrackerMap.delete(bloc);
395
+ }
396
+ /**
397
+ * @internal
398
+ */
399
+ function getActiveTracker(bloc) {
400
+ return activeTrackerMap.get(bloc);
401
+ }
402
+ /**
403
+ * @internal
404
+ */
405
+ function commitTrackedGetters(tracker) {
406
+ if (tracker.currentlyAccessing.size > 0) tracker.trackedGetters = new Set(tracker.currentlyAccessing);
407
+ tracker.currentlyAccessing.clear();
408
+ }
409
+ /**
410
+ * @internal
411
+ */
412
+ function createBlocProxy(bloc) {
413
+ const cached = blocProxyCache.get(bloc);
414
+ if (cached) return cached;
415
+ const proxy = new Proxy(bloc, { get(target, prop, receiver) {
416
+ const tracker = activeTrackerMap.get(target);
417
+ if (tracker?.isTracking && isGetter(target, prop)) {
418
+ tracker.currentlyAccessing.add(prop);
419
+ if (tracker.cacheValid && tracker.renderCache.has(prop)) {
420
+ const cachedValue = tracker.renderCache.get(prop);
421
+ tracker.trackedValues.set(prop, cachedValue);
422
+ return cachedValue;
423
+ }
424
+ if (getterExecutionContext.depth >= MAX_GETTER_DEPTH) {
425
+ console.warn(`${BLAC_ERROR_PREFIX} Maximum getter depth (${MAX_GETTER_DEPTH}) exceeded. Possible circular dependency in getter "${String(prop)}" on ${target.constructor.name}. Returning undefined to prevent stack overflow.`);
426
+ return;
427
+ }
428
+ if (getterExecutionContext.visitedBlocs.has(target)) {
429
+ console.warn(`${BLAC_ERROR_PREFIX} Circular dependency detected: getter "${String(prop)}" on ${target.constructor.name} is calling back into itself. Returning undefined to prevent infinite recursion.`);
430
+ return;
431
+ }
432
+ const prevContext = {
433
+ tracker: getterExecutionContext.tracker,
434
+ currentBloc: getterExecutionContext.currentBloc,
435
+ depth: getterExecutionContext.depth,
436
+ visitedBlocs: new Set(getterExecutionContext.visitedBlocs)
437
+ };
438
+ getterExecutionContext.tracker = tracker;
439
+ getterExecutionContext.currentBloc = target;
440
+ getterExecutionContext.depth++;
441
+ getterExecutionContext.visitedBlocs.add(target);
442
+ try {
443
+ const value = getDescriptor(target, prop).get.call(target);
444
+ tracker.trackedValues.set(prop, value);
445
+ return value;
446
+ } catch (error$1) {
447
+ tracker.currentlyAccessing.delete(prop);
448
+ throw error$1;
449
+ } finally {
450
+ getterExecutionContext.tracker = prevContext.tracker;
451
+ getterExecutionContext.currentBloc = prevContext.currentBloc;
452
+ getterExecutionContext.depth = prevContext.depth;
453
+ getterExecutionContext.visitedBlocs = prevContext.visitedBlocs;
454
+ }
455
+ }
456
+ return Reflect.get(target, prop, receiver);
457
+ } });
458
+ blocProxyCache.set(bloc, proxy);
459
+ return proxy;
460
+ }
461
+ /**
462
+ * @internal
463
+ */
464
+ function hasGetterChanges(bloc, tracker) {
465
+ if (!tracker || tracker.trackedGetters.size === 0) return false;
466
+ tracker.renderCache.clear();
467
+ let hasAnyChange = false;
468
+ for (const prop of tracker.trackedGetters) try {
469
+ const descriptor = getDescriptor(bloc, prop);
470
+ if (!descriptor?.get) continue;
471
+ const newValue = descriptor.get.call(bloc);
472
+ const oldValue = tracker.trackedValues.get(prop);
473
+ tracker.renderCache.set(prop, newValue);
474
+ tracker.trackedValues.set(prop, newValue);
475
+ if (!Object.is(newValue, oldValue)) hasAnyChange = true;
476
+ } catch (error$1) {
477
+ console.warn(`${BLAC_ERROR_PREFIX} Getter "${String(prop)}" threw error during change detection. Stopping tracking for this getter.`, error$1);
478
+ tracker.trackedGetters.delete(prop);
479
+ tracker.trackedValues.delete(prop);
480
+ tracker.cacheValid = false;
481
+ return true;
482
+ }
483
+ tracker.cacheValid = true;
484
+ return hasAnyChange;
485
+ }
486
+ /**
487
+ * @internal
488
+ */
489
+ function invalidateRenderCache(tracker) {
490
+ tracker.cacheValid = false;
491
+ }
492
+ /**
493
+ * @internal
494
+ */
495
+ function clearExternalDependencies(tracker) {
496
+ tracker.externalDependencies.clear();
497
+ }
498
+ /**
499
+ * @internal
500
+ */
501
+ function resetGetterTracker(tracker) {
502
+ tracker.trackedValues.clear();
503
+ tracker.currentlyAccessing.clear();
504
+ tracker.trackedGetters.clear();
505
+ tracker.renderCache.clear();
506
+ tracker.cacheValid = false;
507
+ tracker.isTracking = false;
508
+ tracker.externalDependencies.clear();
509
+ }
510
+
511
+ //#endregion
512
+ //#region src/utils/static-props.ts
513
+ /**
514
+ * Utility functions for accessing static properties on StateContainer classes
515
+ */
516
+ /**
517
+ * Get a static property from a class constructor
518
+ * Type-safe helper that avoids (Type as any) casts
519
+ *
520
+ * @param Type - The class constructor
521
+ * @param propName - The property name to access
522
+ * @param defaultValue - Optional default value if property is undefined
523
+ * @returns The property value or default
524
+ */
525
+ function getStaticProp(Type, propName, defaultValue) {
526
+ return Type[propName] ?? defaultValue;
527
+ }
528
+ /**
529
+ * Check if a class is marked as isolated
530
+ * Isolated classes create separate instances per component
531
+ */
532
+ function isIsolatedClass(Type) {
533
+ return getStaticProp(Type, BLAC_STATIC_PROPS.ISOLATED) === true;
534
+ }
535
+ /**
536
+ * Check if a class is marked as keepAlive
537
+ * KeepAlive classes are never auto-disposed when ref count reaches 0
538
+ */
539
+ function isKeepAliveClass(Type) {
540
+ return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
541
+ }
542
+ /**
543
+ * Check if a class should be excluded from DevTools
544
+ * Used to prevent infinite loops when DevTools tracks itself
545
+ */
546
+ function isExcludedFromDevTools(Type) {
547
+ return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
548
+ }
549
+
550
+ //#endregion
551
+ //#region src/core/StateContainerRegistry.ts
552
+ /**
553
+ * Central registry for managing StateContainer instances.
554
+ * Handles instance lifecycle, ref counting, and lifecycle event emission.
555
+ *
556
+ * @example
557
+ * ```ts
558
+ * const registry = new StateContainerRegistry();
559
+ * const instance = registry.resolve(MyBloc);
560
+ * registry.on('stateChanged', (container, prev, next) => {
561
+ * console.log('State changed:', prev, '->', next);
562
+ * });
563
+ * ```
564
+ */
565
+ var StateContainerRegistry = class {
566
+ constructor() {
567
+ this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
568
+ this.types = /* @__PURE__ */ new Set();
569
+ this.typeConfigs = /* @__PURE__ */ new Map();
570
+ this.listeners = /* @__PURE__ */ new Map();
571
+ }
572
+ /**
573
+ * Register a type for lifecycle event tracking
574
+ * @param constructor - The StateContainer class constructor
575
+ */
576
+ registerType(constructor) {
577
+ this.types.add(constructor);
578
+ }
579
+ /**
580
+ * Register a StateContainer class with configuration
581
+ * @param constructor - The StateContainer class constructor
582
+ * @param isolated - Whether instances should be isolated (component-scoped)
583
+ * @throws Error if type is already registered
584
+ */
585
+ register(constructor, isolated = false) {
586
+ const className = constructor.name;
587
+ if (!isolated && isIsolatedClass(constructor)) isolated = true;
588
+ if (this.typeConfigs.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
589
+ this.typeConfigs.set(className, { isolated });
590
+ this.registerType(constructor);
591
+ }
592
+ ensureInstancesMap(Type) {
593
+ let instances = this.instancesByConstructor.get(Type);
594
+ if (!instances) {
595
+ instances = /* @__PURE__ */ new Map();
596
+ this.instancesByConstructor.set(Type, instances);
597
+ }
598
+ return instances;
599
+ }
600
+ /**
601
+ * Get the instances Map for a specific class (public API for stats/debugging)
602
+ */
603
+ getInstancesMap(Type) {
604
+ return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
605
+ }
606
+ /**
607
+ * Resolve an instance with ref counting (ownership semantics)
608
+ */
609
+ resolve(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, constructorArgs) {
610
+ const registryConfig = this.typeConfigs.get(Type.name);
611
+ const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;
612
+ const config = { instanceId: instanceKey };
613
+ if (isolated) {
614
+ const instance$1 = new Type(constructorArgs);
615
+ instance$1.initConfig(config);
616
+ this.registerType(Type);
617
+ return instance$1;
618
+ }
619
+ const instances = this.ensureInstancesMap(Type);
620
+ const entry = instances.get(instanceKey);
621
+ if (entry) {
622
+ entry.refCount++;
623
+ return entry.instance;
624
+ }
625
+ const instance = new Type(constructorArgs);
626
+ instance.initConfig(config);
627
+ instances.set(instanceKey, {
628
+ instance,
629
+ refCount: 1
630
+ });
631
+ this.registerType(Type);
632
+ return instance;
633
+ }
634
+ /**
635
+ * Get an existing instance without ref counting (borrowing semantics)
636
+ * @throws Error if instance doesn't exist
637
+ */
638
+ get(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
639
+ const entry = this.ensureInstancesMap(Type).get(instanceKey);
640
+ if (!entry) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${instanceKey}" not found.\nUse .resolve() to create and claim ownership, or .getSafe() for conditional access.`);
641
+ const context = getGetterExecutionContext();
642
+ if (context.tracker && context.currentBloc && context.currentBloc !== entry.instance) context.tracker.externalDependencies.add(entry.instance);
643
+ return entry.instance;
644
+ }
645
+ /**
646
+ * Safely get an existing instance (borrowing semantics with error handling)
647
+ * Returns discriminated union for type-safe conditional access
648
+ */
649
+ getSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
650
+ const entry = this.ensureInstancesMap(Type).get(instanceKey);
651
+ if (!entry) return {
652
+ error: /* @__PURE__ */ new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${instanceKey}" not found`),
653
+ instance: null
654
+ };
655
+ const context = getGetterExecutionContext();
656
+ if (context.tracker && context.currentBloc && context.currentBloc !== entry.instance) context.tracker.externalDependencies.add(entry.instance);
657
+ return {
658
+ error: null,
659
+ instance: entry.instance
660
+ };
661
+ }
662
+ /**
663
+ * Connect to an instance with borrowing semantics (for B2B communication)
664
+ * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.
665
+ * Tracks cross-bloc dependency for reactive updates.
666
+ *
667
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
668
+ * but don't want to claim ownership (no ref count increment).
669
+ *
670
+ * @param Type - The bloc class constructor
671
+ * @param instanceKey - Optional instance key (defaults to 'default')
672
+ * @param constructorArgs - Constructor arguments (only used if creating new instance)
673
+ * @returns The bloc instance
674
+ */
675
+ connect(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, constructorArgs) {
676
+ const registryConfig = this.typeConfigs.get(Type.name);
677
+ if (isIsolatedClass(Type) || registryConfig?.isolated === true) throw new Error(`${BLAC_ERROR_PREFIX} Cannot use .connect() with isolated bloc "${Type.name}".\nIsolated blocs are component-scoped. Use .resolve() in components instead.`);
678
+ const instances = this.ensureInstancesMap(Type);
679
+ let entry = instances.get(instanceKey);
680
+ if (!entry) {
681
+ const instance = new Type(constructorArgs);
682
+ const config = { instanceId: instanceKey };
683
+ instance.initConfig(config);
684
+ entry = {
685
+ instance,
686
+ refCount: 1
687
+ };
688
+ instances.set(instanceKey, entry);
689
+ this.registerType(Type);
690
+ }
691
+ const context = getGetterExecutionContext();
692
+ if (context.tracker && context.currentBloc && context.currentBloc !== entry.instance) context.tracker.externalDependencies.add(entry.instance);
693
+ return entry.instance;
694
+ }
695
+ /**
696
+ * Release a reference to an instance
697
+ */
698
+ release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false) {
699
+ const instances = this.ensureInstancesMap(Type);
700
+ const entry = instances.get(instanceKey);
701
+ if (!entry) return;
702
+ if (forceDispose) {
703
+ if (!entry.instance.isDisposed) entry.instance.dispose();
704
+ instances.delete(instanceKey);
705
+ return;
706
+ }
707
+ entry.refCount--;
708
+ const keepAlive = isKeepAliveClass(Type);
709
+ if (entry.refCount <= 0 && !keepAlive) {
710
+ if (!entry.instance.isDisposed) entry.instance.dispose();
711
+ instances.delete(instanceKey);
712
+ }
713
+ }
714
+ /**
715
+ * Get all instances of a specific type
716
+ */
717
+ getAll(Type) {
718
+ const instances = this.ensureInstancesMap(Type);
719
+ const result = [];
720
+ for (const entry of instances.values()) result.push(entry.instance);
721
+ return result;
722
+ }
723
+ /**
724
+ * Safely iterate over all instances of a type
725
+ */
726
+ forEach(Type, callback) {
727
+ const instances = this.ensureInstancesMap(Type);
728
+ for (const entry of instances.values()) {
729
+ const instance = entry.instance;
730
+ if (!instance.isDisposed) try {
731
+ callback(instance);
732
+ } catch (error$1) {
733
+ console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error$1);
734
+ }
735
+ }
736
+ }
737
+ /**
738
+ * Clear all instances of a specific type
739
+ */
740
+ clear(Type) {
741
+ const instances = this.ensureInstancesMap(Type);
742
+ for (const entry of instances.values()) if (!entry.instance.isDisposed) entry.instance.dispose();
743
+ instances.clear();
744
+ }
745
+ /**
746
+ * Get reference count for an instance
747
+ */
748
+ getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
749
+ return this.ensureInstancesMap(Type).get(instanceKey)?.refCount ?? 0;
750
+ }
751
+ /**
752
+ * Check if an instance exists
753
+ */
754
+ hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
755
+ return this.ensureInstancesMap(Type).has(instanceKey);
756
+ }
757
+ /**
758
+ * Clear all instances from all types (for testing)
759
+ *
760
+ * Iterates all registered types and clears their instances.
761
+ * Also clears type tracking to reset the registry state.
762
+ */
763
+ clearAll() {
764
+ for (const Type of this.types) this.clear(Type);
765
+ this.types.clear();
766
+ this.typeConfigs.clear();
767
+ }
768
+ /**
769
+ * Get registry statistics (for debugging)
770
+ */
771
+ getStats() {
772
+ const typeBreakdown = {};
773
+ let totalInstances = 0;
774
+ for (const Type of this.types) {
775
+ const typeName = Type.name;
776
+ const count = this.getInstancesMap(Type).size;
777
+ typeBreakdown[typeName] = count;
778
+ totalInstances += count;
779
+ }
780
+ return {
781
+ registeredTypes: this.types.size,
782
+ totalInstances,
783
+ typeBreakdown
784
+ };
785
+ }
786
+ /**
787
+ * Get all registered types (for plugin system)
788
+ */
789
+ getTypes() {
790
+ return Array.from(this.types);
791
+ }
792
+ /**
793
+ * Subscribe to lifecycle events
794
+ * @param event - The lifecycle event to listen for
795
+ * @param listener - The listener function to call when the event occurs
796
+ * @returns Unsubscribe function
797
+ */
798
+ on(event, listener) {
799
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
800
+ this.listeners.get(event).add(listener);
801
+ return () => {
802
+ this.listeners.get(event)?.delete(listener);
803
+ };
804
+ }
805
+ /**
806
+ * Emit lifecycle event to all listeners
807
+ * @internal - Called by StateContainer/Vertex lifecycle methods
808
+ */
809
+ emit(event, ...args) {
810
+ const listeners = this.listeners.get(event);
811
+ if (!listeners || listeners.size === 0) return;
812
+ for (const listener of listeners) try {
813
+ listener(...args);
814
+ } catch (error$1) {
815
+ console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error$1);
816
+ }
817
+ }
818
+ };
819
+ /**
820
+ * Global default registry instance
821
+ */
822
+ const globalRegistry = new StateContainerRegistry();
823
+ /**
824
+ * Global plugin manager (initialized lazily)
825
+ */
826
+ let _globalPluginManager = null;
827
+ /**
828
+ * Get the global plugin manager
829
+ */
830
+ function getPluginManager() {
831
+ if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
832
+ return _globalPluginManager;
833
+ }
834
+
835
+ //#endregion
836
+ //#region src/core/StateContainer.ts
837
+ /**
838
+ * Abstract base class for all state containers in BlaC.
839
+ * Provides lifecycle management, subscription handling, ref counting,
840
+ * and integration with the global registry.
841
+ *
842
+ * @template S - State type managed by this container
843
+ * @template P - Props type passed to the container (optional)
844
+ *
845
+ * @example
846
+ * ```ts
847
+ * class CounterBloc extends StateContainer<number> {
848
+ * constructor() {
849
+ * super(0);
850
+ * }
851
+ * increment() {
852
+ * this.emit(this.state + 1);
853
+ * }
854
+ * }
855
+ * ```
856
+ */
857
+ var StateContainer = class StateContainer {
858
+ static {
859
+ this.__excludeFromDevTools = false;
860
+ }
861
+ static {
862
+ this._registry = globalRegistry;
863
+ }
864
+ /**
865
+ * Get the global StateContainerRegistry
866
+ * @returns The registry managing all state container instances
867
+ */
868
+ static getRegistry() {
869
+ return StateContainer._registry;
870
+ }
871
+ /**
872
+ * Replace the global registry (clears existing instances)
873
+ * @param registry - The new registry to use
874
+ */
875
+ static setRegistry(registry) {
876
+ StateContainer._registry.clearAll();
877
+ StateContainer._registry = registry;
878
+ }
879
+ /**
880
+ * Register this class with the global registry
881
+ * @param isolated - Whether instances should be isolated (component-scoped)
882
+ */
883
+ static register(isolated = false) {
884
+ StateContainer._registry.register(this, isolated);
885
+ }
886
+ /**
887
+ * Resolve an instance with ref counting (ownership semantics).
888
+ * Creates a new instance if one doesn't exist, or returns existing and increments ref count.
889
+ * @param instanceKey - Optional instance key (defaults to 'default')
890
+ * @param constructorArgs - Arguments to pass to constructor if creating new instance
891
+ * @returns The state container instance
892
+ */
893
+ static resolve(instanceKey, constructorArgs) {
894
+ return StateContainer._registry.resolve(this, instanceKey, constructorArgs);
895
+ }
896
+ /**
897
+ * Get an existing instance without incrementing ref count (borrowing semantics).
898
+ * @param instanceKey - Optional instance key (defaults to 'default')
899
+ * @returns The state container instance
900
+ * @throws Error if instance doesn't exist
901
+ */
902
+ static get(instanceKey) {
903
+ return StateContainer._registry.get(this, instanceKey);
904
+ }
905
+ /**
906
+ * Safely get an existing instance with error handling.
907
+ * @param instanceKey - Optional instance key (defaults to 'default')
908
+ * @returns Discriminated union with either the instance or an error
909
+ */
910
+ static getSafe(instanceKey) {
911
+ return StateContainer._registry.getSafe(this, instanceKey);
912
+ }
913
+ /**
914
+ * Connect to an instance for bloc-to-bloc communication (borrowing semantics).
915
+ * Gets or creates instance without incrementing ref count.
916
+ * @param instanceKey - Optional instance key (defaults to 'default')
917
+ * @param constructorArgs - Arguments to pass to constructor if creating new instance
918
+ * @returns The state container instance
919
+ */
920
+ static connect(instanceKey, constructorArgs) {
921
+ return StateContainer._registry.connect(this, instanceKey, constructorArgs);
922
+ }
923
+ /**
924
+ * Release a reference to an instance.
925
+ * Decrements ref count and disposes when it reaches 0 (unless keepAlive).
926
+ * @param instanceKey - Optional instance key (defaults to 'default')
927
+ * @param forceDispose - Force immediate disposal regardless of ref count
928
+ */
929
+ static release(instanceKey, forceDispose = false) {
930
+ StateContainer._registry.release(this, instanceKey, forceDispose);
931
+ }
932
+ /**
933
+ * Get all instances of this class
934
+ * @returns Array of all instances
935
+ */
936
+ static getAll() {
937
+ return StateContainer._registry.getAll(this);
938
+ }
939
+ /**
940
+ * Iterate over all instances of this class
941
+ * @param callback - Function to call for each instance
942
+ */
943
+ static forEach(callback) {
944
+ StateContainer._registry.forEach(this, callback);
945
+ }
946
+ /**
947
+ * Clear all instances of this class (disposes them)
948
+ */
949
+ static clear() {
950
+ StateContainer._registry.clear(this);
951
+ }
952
+ /**
953
+ * Clear all instances from all registered types
954
+ */
955
+ static clearAllInstances() {
956
+ StateContainer._registry.clearAll();
957
+ }
958
+ /**
959
+ * Get registry statistics for debugging
960
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
961
+ */
962
+ static getStats() {
963
+ return StateContainer._registry.getStats();
964
+ }
965
+ /**
966
+ * Get reference count for an instance
967
+ * @param instanceKey - Optional instance key (defaults to 'default')
968
+ * @returns Current ref count (0 if instance doesn't exist)
969
+ */
970
+ static getRefCount(instanceKey) {
971
+ return StateContainer._registry.getRefCount(this, instanceKey);
972
+ }
973
+ /**
974
+ * Check if an instance exists
975
+ * @param instanceKey - Optional instance key (defaults to 'default')
976
+ * @returns true if instance exists
977
+ */
978
+ static hasInstance(instanceKey) {
979
+ return StateContainer._registry.hasInstance(this, instanceKey);
980
+ }
981
+ /** Current props value passed to this container */
982
+ get props() {
983
+ return this._props;
984
+ }
985
+ constructor(initialState) {
986
+ this.listeners = /* @__PURE__ */ new Set();
987
+ this._disposed = false;
988
+ this.config = {};
989
+ this._props = void 0;
990
+ this.systemEventHandlers = /* @__PURE__ */ new Map();
991
+ this.name = this.constructor.name;
992
+ this.debug = false;
993
+ this.instanceId = generateSimpleId(this.constructor.name, "main");
994
+ this.createdAt = Date.now();
995
+ this.lastUpdateTimestamp = Date.now();
996
+ this.onSystemEvent = (event, handler) => {
997
+ let handlers = this.systemEventHandlers.get(event);
998
+ if (!handlers) {
999
+ handlers = /* @__PURE__ */ new Set();
1000
+ this.systemEventHandlers.set(event, handlers);
1001
+ }
1002
+ handlers.add(handler);
1003
+ return () => {
1004
+ handlers?.delete(handler);
1005
+ };
1006
+ };
1007
+ this._state = initialState;
1008
+ }
1009
+ /**
1010
+ * Initialize configuration for this instance.
1011
+ * Called by the registry after construction.
1012
+ * @param config - Configuration options
1013
+ */
1014
+ initConfig(config) {
1015
+ this.config = { ...config };
1016
+ this.name = this.config.name || this.constructor.name;
1017
+ this.debug = this.config.debug ?? false;
1018
+ this.instanceId = generateSimpleId(this.constructor.name, this.config.instanceId);
1019
+ StateContainer._registry.emit("created", this);
1020
+ }
1021
+ /** Current state value */
1022
+ get state() {
1023
+ return this._state;
1024
+ }
1025
+ /** Whether this instance has been disposed */
1026
+ get isDisposed() {
1027
+ return this._disposed;
1028
+ }
1029
+ /**
1030
+ * Subscribe to state changes
1031
+ * @param listener - Function called when state changes
1032
+ * @returns Unsubscribe function
1033
+ */
1034
+ subscribe(listener) {
1035
+ if (this._disposed) throw new Error(`Cannot subscribe to disposed container ${this.name}`);
1036
+ this.listeners.add(listener);
1037
+ return () => this.listeners.delete(listener);
1038
+ }
1039
+ /**
1040
+ * Dispose this instance and clean up resources.
1041
+ * Clears all listeners and emits the 'dispose' system event.
1042
+ */
1043
+ dispose() {
1044
+ if (this._disposed) return;
1045
+ if (this.debug) console.log(`[${this.name}] Disposing...`);
1046
+ this._disposed = true;
1047
+ this.emitSystemEvent("dispose", void 0);
1048
+ this.listeners.clear();
1049
+ this.systemEventHandlers.clear();
1050
+ StateContainer._registry.emit("disposed", this);
1051
+ if (this.debug) console.log(`[${this.name}] Disposed successfully`);
1052
+ }
1053
+ /**
1054
+ * Emit a new state value and notify all listeners.
1055
+ * @param newState - The new state value
1056
+ * @protected
1057
+ */
1058
+ emit(newState) {
1059
+ if (this._disposed) throw new Error(`Cannot emit state from disposed container ${this.name}`);
1060
+ if (this._state === newState) return;
1061
+ const previousState = this._state;
1062
+ this._state = newState;
1063
+ this.emitSystemEvent("stateChanged", {
1064
+ state: newState,
1065
+ previousState
1066
+ });
1067
+ for (const listener of this.listeners) try {
1068
+ listener(newState);
1069
+ } catch (error$1) {
1070
+ console.error(`[${this.name}] Error in listener:`, error$1);
1071
+ }
1072
+ const stackTrace = this.captureStackTrace();
1073
+ StateContainer._registry.emit("stateChanged", this, previousState, newState, stackTrace);
1074
+ this.lastUpdateTimestamp = Date.now();
1075
+ }
1076
+ static {
1077
+ this.enableStackTrace = true;
1078
+ }
1079
+ captureStackTrace() {
1080
+ if (!StateContainer.enableStackTrace || typeof process !== "undefined" && process.env?.NODE_ENV === "production") return "";
1081
+ try {
1082
+ const relevantLines = ((/* @__PURE__ */ new Error()).stack || "").split("\n").slice(1);
1083
+ const formattedLines = [];
1084
+ for (const line of relevantLines) {
1085
+ if (!line.trim()) continue;
1086
+ if (line.includes("StateContainer.emit") || line.includes("StateContainer.update") || line.includes("StateContainer.captureStackTrace") || line.includes("Cubit.patch") || line.includes("Vertex.")) continue;
1087
+ 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;
1088
+ const formatted = this.formatStackLine(line);
1089
+ if (formatted) formattedLines.push(formatted);
1090
+ }
1091
+ return formattedLines.join("\n");
1092
+ } catch {
1093
+ return "";
1094
+ }
1095
+ }
1096
+ formatStackLine(line) {
1097
+ const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
1098
+ if (!match) {
1099
+ const simpleMatch = line.match(/at\s+(.+?):(\d+):(\d+)/);
1100
+ if (simpleMatch) {
1101
+ const [, url$1, lineNum$1, col$1] = simpleMatch;
1102
+ return ` at ${this.cleanFilePath(url$1)}:${lineNum$1}:${col$1}`;
1103
+ }
1104
+ return null;
1105
+ }
1106
+ const [, functionName, url, lineNum, col] = match;
1107
+ return ` at ${functionName} (${this.cleanFilePath(url)}:${lineNum}:${col})`;
1108
+ }
1109
+ cleanFilePath(url) {
1110
+ let path = url.replace(/http:\/\/localhost:\d+\/@fs/, "").replace(/http:\/\/localhost:\d+\//, "").replace(/\?t=\d+/, "").replace(/\?v=[a-f0-9]+/, "");
1111
+ const projectMatch = path.match(/\/Projects\/blac\/(.+)/);
1112
+ if (projectMatch) path = projectMatch[1];
1113
+ const segments = path.split("/");
1114
+ if (segments.length > 3) path = segments.slice(-3).join("/");
1115
+ return path;
1116
+ }
1117
+ /**
1118
+ * Update state using a transform function.
1119
+ * @param updater - Function that receives current state and returns new state
1120
+ * @protected
1121
+ */
1122
+ update(updater) {
1123
+ if (this._disposed) throw new Error(`Cannot update state from disposed container ${this.name}`);
1124
+ this.emit(updater(this._state));
1125
+ }
1126
+ emitSystemEvent(event, payload) {
1127
+ const handlers = this.systemEventHandlers.get(event);
1128
+ if (!handlers) return;
1129
+ for (const handler of handlers) try {
1130
+ handler(payload);
1131
+ } catch (error$1) {
1132
+ console.error(`[${this.name}] Error in system event handler:`, error$1);
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Update the props for this container.
1137
+ * Emits the 'propsUpdated' system event.
1138
+ * @param newProps - The new props value
1139
+ */
1140
+ updateProps(newProps) {
1141
+ if (this._disposed) throw new Error(`Cannot update props on disposed container ${this.name}`);
1142
+ const previousProps = this._props;
1143
+ this._props = newProps;
1144
+ this.emitSystemEvent("propsUpdated", {
1145
+ props: newProps,
1146
+ previousProps
1147
+ });
1148
+ if (this.debug) console.log(`[${this.name}] Props updated:`, {
1149
+ newProps,
1150
+ previousProps
1151
+ });
1152
+ }
1153
+ };
1154
+
1155
+ //#endregion
1156
+ //#region src/core/Cubit.ts
1157
+ /**
1158
+ * Simple state container with direct state emission.
1159
+ * Extends StateContainer with public methods for emitting and updating state.
1160
+ *
1161
+ * @template S - State type
1162
+ * @template P - Props type (optional)
1163
+ */
1164
+ var Cubit = class extends StateContainer {
1165
+ constructor(initialState) {
1166
+ super(initialState);
1167
+ this.patch = ((partial) => {
1168
+ if (typeof this.state !== "object" || this.state === null) throw new Error("patch() is only available for object state types");
1169
+ this.update((current) => ({
1170
+ ...current,
1171
+ ...partial
1172
+ }));
1173
+ });
1174
+ }
1175
+ /**
1176
+ * Replace state with a new value and notify all listeners
1177
+ * @param newState - The new state value
1178
+ */
1179
+ emit(newState) {
1180
+ super["emit"](newState);
1181
+ }
1182
+ /**
1183
+ * Transform current state using an updater function and emit the new state
1184
+ * @param updater - Function that receives current state and returns new state
1185
+ */
1186
+ update(updater) {
1187
+ super["update"](updater);
1188
+ }
1189
+ };
1190
+
1191
+ //#endregion
1192
+ //#region src/core/Vertex.ts
1193
+ /**
1194
+ * Event-driven state container that processes events to update state.
1195
+ * Use with event handlers registered via the on() method.
1196
+ *
1197
+ * @template S - State type
1198
+ * @template E - Event type (extends BaseEvent)
1199
+ * @template P - Props type (optional)
1200
+ */
1201
+ var Vertex = class extends StateContainer {
1202
+ constructor(initialState) {
1203
+ super(initialState);
1204
+ this.eventHandlers = /* @__PURE__ */ new Map();
1205
+ this.isProcessing = false;
1206
+ this.eventQueue = [];
1207
+ this.on = (EventClass, handler) => {
1208
+ const className = EventClass.name;
1209
+ const registrations = this.eventHandlers.get(className) || [];
1210
+ registrations.push({
1211
+ eventClass: EventClass,
1212
+ handler
1213
+ });
1214
+ this.eventHandlers.set(className, registrations);
1215
+ };
1216
+ this.add = (event) => {
1217
+ StateContainer._registry.emit("eventAdded", this, event);
1218
+ this.processEvent(event);
1219
+ };
1220
+ }
1221
+ processEvent(event) {
1222
+ if (this.isProcessing) {
1223
+ this.eventQueue.push(event);
1224
+ return;
1225
+ }
1226
+ this.isProcessing = true;
1227
+ try {
1228
+ this.handleEvent(event);
1229
+ while (this.eventQueue.length > 0) {
1230
+ const nextEvent = this.eventQueue.shift();
1231
+ this.handleEvent(nextEvent);
1232
+ }
1233
+ } finally {
1234
+ this.isProcessing = false;
1235
+ }
1236
+ }
1237
+ handleEvent(event) {
1238
+ const className = event.constructor.name;
1239
+ const registrations = this.eventHandlers.get(className);
1240
+ if (!registrations || registrations.length === 0) {
1241
+ if (this.debug) console.warn(`No handler registered for event: ${className}`);
1242
+ return;
1243
+ }
1244
+ const emitFn = (state) => {
1245
+ this.emit(state);
1246
+ };
1247
+ for (const registration of registrations) try {
1248
+ registration.handler(event, emitFn);
1249
+ } catch (error$1) {
1250
+ if (this.debug) console.error(`Error handling event ${className}:`, error$1);
1251
+ this.onEventError(event, error$1);
1252
+ }
1253
+ }
1254
+ /**
1255
+ * Handle errors that occur during event processing.
1256
+ * Override this method to implement custom error handling.
1257
+ * @param _event - The event that caused the error
1258
+ * @param _error - The error that occurred
1259
+ */
1260
+ onEventError(_event, _error) {}
1261
+ };
1262
+
1263
+ //#endregion
1264
+ //#region src/plugin/BlacPlugin.ts
1265
+ /**
1266
+ * Type guard to check if a plugin has a required onInstall hook
1267
+ * @param plugin - The plugin to check
1268
+ * @returns true if the plugin implements BlacPluginWithInit
1269
+ */
1270
+ function hasInitHook(plugin) {
1271
+ return typeof plugin.onInstall === "function";
1272
+ }
1273
+
1274
+ //#endregion
1275
+ //#region src/tracking/proxy-tracker.ts
1276
+ /**
1277
+ * Functional proxy tracker for automatic dependency tracking
1278
+ *
1279
+ * This module provides a functional approach to proxy-based dependency tracking.
1280
+ * Unlike the class-based ProxyTracker, this uses a state object pattern that's
1281
+ * easier to integrate with functional programming patterns and framework hooks.
1282
+ *
1283
+ * @internal
1284
+ */
1285
+ /**
1286
+ * Check if a value can be proxied
1287
+ *
1288
+ * Returns true for plain objects and arrays only.
1289
+ * Excludes built-in objects like Date, Map, Set, etc.
1290
+ *
1291
+ * @internal
1292
+ */
1293
+ function isProxyable(value) {
1294
+ if (typeof value !== "object" || value === null) return false;
1295
+ const proto = Object.getPrototypeOf(value);
1296
+ return proto === Object.prototype || proto === Array.prototype;
1297
+ }
1298
+ /**
1299
+ * Create a new proxy tracker state
1300
+ *
1301
+ * @example
1302
+ * const state = createProxyTrackerState<MyState>();
1303
+ * startProxyTracking(state);
1304
+ * const proxy = createProxyForTarget(state, myObject);
1305
+ * // ... use proxy ...
1306
+ * const paths = stopProxyTracking(state);
1307
+ *
1308
+ * @internal
1309
+ */
1310
+ function createProxyTrackerState() {
1311
+ return {
1312
+ trackedPaths: /* @__PURE__ */ new Set(),
1313
+ isTracking: false,
1314
+ proxyCache: /* @__PURE__ */ new WeakMap(),
1315
+ boundFunctionsCache: null,
1316
+ lastProxiedState: null,
1317
+ lastProxy: null,
1318
+ maxDepth: 10
1319
+ };
1320
+ }
1321
+ /**
1322
+ * Start tracking property accesses
1323
+ *
1324
+ * Clears previous tracked paths and enables tracking mode.
1325
+ *
1326
+ * @internal
1327
+ */
1328
+ function startProxyTracking(state) {
1329
+ state.isTracking = true;
1330
+ state.trackedPaths.clear();
1331
+ }
1332
+ /**
1333
+ * Stop tracking and return the tracked paths
1334
+ *
1335
+ * Returns a new Set containing all tracked paths.
1336
+ *
1337
+ * @internal
1338
+ */
1339
+ function stopProxyTracking(state) {
1340
+ state.isTracking = false;
1341
+ return new Set(state.trackedPaths);
1342
+ }
1343
+ /**
1344
+ * Create a proxy for an array with property access tracking
1345
+ *
1346
+ * Tracks:
1347
+ * - Array element access (arr[0])
1348
+ * - Length access (arr.length)
1349
+ * - Array method calls (arr.map, arr.filter, etc.)
1350
+ *
1351
+ * @internal
1352
+ */
1353
+ function createArrayProxy(state, target, path, depth = 0) {
1354
+ const proxy = new Proxy(target, { get: (arr, prop) => {
1355
+ if (typeof prop === "symbol") return Reflect.get(arr, prop);
1356
+ const value = Reflect.get(arr, prop);
1357
+ if (typeof value === "function") {
1358
+ if (!state.boundFunctionsCache) state.boundFunctionsCache = /* @__PURE__ */ new WeakMap();
1359
+ const cached = state.boundFunctionsCache.get(value);
1360
+ if (cached) return cached;
1361
+ const bound = value.bind(arr);
1362
+ state.boundFunctionsCache.set(value, bound);
1363
+ return bound;
1364
+ }
1365
+ if (prop === "length") {
1366
+ if (state.isTracking) {
1367
+ const fullPath$1 = path ? `${path}.length` : "length";
1368
+ state.trackedPaths.add(fullPath$1);
1369
+ }
1370
+ return value;
1371
+ }
1372
+ let fullPath;
1373
+ if (typeof prop === "string") {
1374
+ const index = Number(prop);
1375
+ if (!isNaN(index) && index >= 0) fullPath = path ? `${path}[${index}]` : `[${index}]`;
1376
+ else fullPath = path ? `${path}.${prop}` : prop;
1377
+ } else return value;
1378
+ if (isProxyable(value)) return createProxyInternal(state, value, fullPath, depth + 1);
1379
+ if (state.isTracking) state.trackedPaths.add(fullPath);
1380
+ return value;
1381
+ } });
1382
+ state.proxyCache.set(target, proxy);
1383
+ return proxy;
1384
+ }
1385
+ /**
1386
+ * Create a proxy for an object with property access tracking
1387
+ *
1388
+ * This is the core proxy creation function that recursively creates proxies
1389
+ * for nested objects and arrays.
1390
+ *
1391
+ * Tracks:
1392
+ * - Property access (obj.prop)
1393
+ * - Nested property access (obj.nested.prop)
1394
+ * - 'in' operator usage ('prop' in obj)
1395
+ * - Object.keys, Object.entries, etc.
1396
+ *
1397
+ * @internal
1398
+ */
1399
+ function createProxyInternal(state, target, path = "", depth = 0) {
1400
+ if (!state.isTracking || !isProxyable(target)) return target;
1401
+ if (depth >= state.maxDepth) return target;
1402
+ if (state.proxyCache.has(target)) return state.proxyCache.get(target);
1403
+ if (Array.isArray(target)) return createArrayProxy(state, target, path, depth);
1404
+ const proxy = new Proxy(target, {
1405
+ get: (obj, prop) => {
1406
+ if (typeof prop === "symbol") return Reflect.get(obj, prop);
1407
+ const value = Reflect.get(obj, prop);
1408
+ if (typeof value === "function") {
1409
+ if (!state.boundFunctionsCache) state.boundFunctionsCache = /* @__PURE__ */ new WeakMap();
1410
+ const cached = state.boundFunctionsCache.get(value);
1411
+ if (cached) return cached;
1412
+ const bound = value.bind(obj);
1413
+ state.boundFunctionsCache.set(value, bound);
1414
+ return bound;
1415
+ }
1416
+ const fullPath = path ? `${path}.${String(prop)}` : String(prop);
1417
+ if (typeof prop === "string" && state.isTracking) {
1418
+ if (!prop.startsWith("_") && !prop.startsWith("$$")) state.trackedPaths.add(fullPath);
1419
+ }
1420
+ if (isProxyable(value)) return createProxyInternal(state, value, fullPath, depth + 1);
1421
+ return value;
1422
+ },
1423
+ has: (obj, prop) => {
1424
+ if (typeof prop === "string" && state.isTracking) {
1425
+ const fullPath = path ? `${path}.${prop}` : prop;
1426
+ state.trackedPaths.add(fullPath);
1427
+ }
1428
+ return Reflect.has(obj, prop);
1429
+ },
1430
+ ownKeys: (obj) => {
1431
+ if (state.isTracking && path) state.trackedPaths.add(path);
1432
+ return Reflect.ownKeys(obj);
1433
+ }
1434
+ });
1435
+ state.proxyCache.set(target, proxy);
1436
+ return proxy;
1437
+ }
1438
+ /**
1439
+ * Create a proxy for a target with caching
1440
+ *
1441
+ * If the target hasn't changed since the last call, returns the cached proxy.
1442
+ * Otherwise, creates a new proxy and caches it.
1443
+ *
1444
+ * This is the main entry point for creating tracked proxies.
1445
+ *
1446
+ * @internal
1447
+ */
1448
+ function createProxyForTarget(state, target) {
1449
+ if (state.lastProxiedState === target && state.lastProxy) return state.lastProxy;
1450
+ state.proxyCache = /* @__PURE__ */ new WeakMap();
1451
+ state.boundFunctionsCache = null;
1452
+ const proxy = createProxyInternal(state, target, "", 0);
1453
+ state.lastProxiedState = target;
1454
+ state.lastProxy = proxy;
1455
+ return proxy;
1456
+ }
1457
+
1458
+ //#endregion
1459
+ //#region src/tracking/path-utils.ts
1460
+ /**
1461
+ * Path utilities for dependency tracking
1462
+ *
1463
+ * Provides utilities for parsing property paths and extracting values
1464
+ * from nested objects using path strings.
1465
+ *
1466
+ * @internal
1467
+ */
1468
+ /**
1469
+ * Parse a property path string into an array of segments
1470
+ *
1471
+ * @internal
1472
+ *
1473
+ * Handles both dot notation (a.b.c) and bracket notation (a[0].b)
1474
+ *
1475
+ * @example
1476
+ * ```ts
1477
+ * parsePath('user.name') // ['user', 'name']
1478
+ * parsePath('items[0].name') // ['items', '0', 'name']
1479
+ * parsePath('data.users[2].address.city') // ['data', 'users', '2', 'address', 'city']
1480
+ * ```
1481
+ */
1482
+ function parsePath(path) {
1483
+ const segments = [];
1484
+ let current = "";
1485
+ let i = 0;
1486
+ while (i < path.length) {
1487
+ const char = path[i];
1488
+ if (char === ".") {
1489
+ if (current) segments.push(current);
1490
+ current = "";
1491
+ } else if (char === "[") {
1492
+ if (current) segments.push(current);
1493
+ current = "";
1494
+ i++;
1495
+ while (i < path.length && path[i] !== "]") current += path[i++];
1496
+ if (current) segments.push(current);
1497
+ current = "";
1498
+ } else current += char;
1499
+ i++;
1500
+ }
1501
+ if (current) segments.push(current);
1502
+ return segments;
1503
+ }
1504
+ /**
1505
+ * Get a value from an object using a path of segments
1506
+ *
1507
+ * @example
1508
+ * ```ts
1509
+ * const obj = { user: { name: 'Alice', age: 30 } }
1510
+ * getValueAtPath(obj, ['user', 'name']) // 'Alice'
1511
+ * getValueAtPath(obj, ['user', 'age']) // 30
1512
+ * getValueAtPath(obj, ['user', 'missing']) // undefined
1513
+ * ```
1514
+ *
1515
+ * @internal
1516
+ */
1517
+ function getValueAtPath(obj, segments) {
1518
+ if (obj == null) return void 0;
1519
+ let current = obj;
1520
+ for (let i = 0; i < segments.length; i++) {
1521
+ current = current[segments[i]];
1522
+ if (current == null) return void 0;
1523
+ }
1524
+ return current;
1525
+ }
1526
+ /**
1527
+ * Shallow equality comparison for arrays
1528
+ *
1529
+ * Compares two arrays element-by-element using Object.is
1530
+ *
1531
+ * @example
1532
+ * ```ts
1533
+ * shallowEqual([1, 2, 3], [1, 2, 3]) // true
1534
+ * shallowEqual([1, 2, 3], [1, 2, 4]) // false
1535
+ * shallowEqual([1, 2], [1, 2, 3]) // false
1536
+ * ```
1537
+ *
1538
+ * @internal
1539
+ */
1540
+ function shallowEqual(arr1, arr2) {
1541
+ if (arr1.length !== arr2.length) return false;
1542
+ for (let i = 0; i < arr1.length; i++) if (!Object.is(arr1[i], arr2[i])) return false;
1543
+ return true;
1544
+ }
1545
+
1546
+ //#endregion
1547
+ //#region src/tracking/dependency-tracker.ts
1548
+ function isChildPath(child, parent) {
1549
+ if (child === parent) return false;
1550
+ return child.startsWith(parent + ".") || child.startsWith(parent + "[");
1551
+ }
1552
+ /**
1553
+ * Extract the parent array path from an array child path
1554
+ * Examples:
1555
+ * 'messages.length' -> 'messages'
1556
+ * 'messages[0]' -> 'messages'
1557
+ * 'messages[0].text' -> 'messages'
1558
+ * 'data.items[0]' -> 'data.items'
1559
+ */
1560
+ function getArrayParentPath(path) {
1561
+ if (path.endsWith(".length")) return path.slice(0, -7);
1562
+ const arrayIndexMatch = path.match(/^(.+?)\[\d+\]/);
1563
+ if (arrayIndexMatch) return arrayIndexMatch[1];
1564
+ return null;
1565
+ }
1566
+ /**
1567
+ * @internal
1568
+ */
1569
+ function optimizeTrackedPaths(paths) {
1570
+ if (paths.size === 0) return /* @__PURE__ */ new Set();
1571
+ if (paths.size === 1) return new Set(paths);
1572
+ const sortedPaths = Array.from(paths).sort((a, b) => b.length - a.length);
1573
+ const optimized = /* @__PURE__ */ new Set();
1574
+ for (const path of sortedPaths) {
1575
+ let hasMoreSpecificChild = false;
1576
+ for (const optimizedPath of optimized) if (isChildPath(optimizedPath, path)) {
1577
+ hasMoreSpecificChild = true;
1578
+ break;
1579
+ }
1580
+ if (!hasMoreSpecificChild) optimized.add(path);
1581
+ }
1582
+ const arrayParents = /* @__PURE__ */ new Set();
1583
+ for (const path of optimized) {
1584
+ const arrayParent = getArrayParentPath(path);
1585
+ if (arrayParent) arrayParents.add(arrayParent);
1586
+ }
1587
+ for (const arrayParent of arrayParents) optimized.add(arrayParent);
1588
+ return optimized;
1589
+ }
1590
+ /**
1591
+ * @internal
1592
+ */
1593
+ function createTrackerState() {
1594
+ return {
1595
+ proxyTrackerState: createProxyTrackerState(),
1596
+ previousRenderPaths: /* @__PURE__ */ new Set(),
1597
+ currentRenderPaths: /* @__PURE__ */ new Set(),
1598
+ pathCache: /* @__PURE__ */ new Map(),
1599
+ lastCheckedState: null,
1600
+ lastCheckedValues: /* @__PURE__ */ new Map()
1601
+ };
1602
+ }
1603
+ /**
1604
+ * @internal
1605
+ */
1606
+ function startTracking(tracker) {
1607
+ startProxyTracking(tracker.proxyTrackerState);
1608
+ }
1609
+ /**
1610
+ * @internal
1611
+ */
1612
+ function createProxy(tracker, state) {
1613
+ return createProxyForTarget(tracker.proxyTrackerState, state);
1614
+ }
1615
+ /**
1616
+ * @internal
1617
+ */
1618
+ function captureTrackedPaths(tracker, state) {
1619
+ tracker.previousRenderPaths = tracker.currentRenderPaths;
1620
+ tracker.currentRenderPaths = optimizeTrackedPaths(stopProxyTracking(tracker.proxyTrackerState));
1621
+ if (tracker.previousRenderPaths.size === 0 && tracker.currentRenderPaths.size === 0) return;
1622
+ const trackedPathsUnion = new Set(tracker.previousRenderPaths);
1623
+ for (const path of tracker.currentRenderPaths) trackedPathsUnion.add(path);
1624
+ const canReuseCache = tracker.lastCheckedState === state;
1625
+ for (const path of trackedPathsUnion) if (!tracker.pathCache.has(path)) {
1626
+ const segments = parsePath(path);
1627
+ const value = canReuseCache && tracker.lastCheckedValues.has(path) ? tracker.lastCheckedValues.get(path) : getValueAtPath(state, segments);
1628
+ tracker.pathCache.set(path, {
1629
+ segments,
1630
+ value
1631
+ });
1632
+ } else {
1633
+ const info$1 = tracker.pathCache.get(path);
1634
+ info$1.value = canReuseCache && tracker.lastCheckedValues.has(path) ? tracker.lastCheckedValues.get(path) : getValueAtPath(state, info$1.segments);
1635
+ }
1636
+ tracker.lastCheckedValues.clear();
1637
+ }
1638
+ /**
1639
+ * @internal
1640
+ */
1641
+ function hasChanges(tracker, state) {
1642
+ if (tracker.pathCache.size === 0) return true;
1643
+ tracker.lastCheckedValues.clear();
1644
+ for (const [path, info$1] of tracker.pathCache.entries()) {
1645
+ const currentValue = getValueAtPath(state, info$1.segments);
1646
+ tracker.lastCheckedValues.set(path, currentValue);
1647
+ if (!Object.is(currentValue, info$1.value)) {
1648
+ tracker.lastCheckedState = state;
1649
+ return true;
1650
+ }
1651
+ }
1652
+ tracker.lastCheckedState = state;
1653
+ return false;
1654
+ }
1655
+ /**
1656
+ * @internal
1657
+ */
1658
+ function hasTrackedData(tracker) {
1659
+ return tracker.proxyTrackerState.trackedPaths.size > 0 || tracker.pathCache.size > 0 || tracker.previousRenderPaths.size > 0;
1660
+ }
1661
+
1662
+ //#endregion
1663
+ //#region src/adapter/framework-adapter.ts
1664
+ /**
1665
+ * Manages subscriptions to external bloc dependencies for getter tracking.
1666
+ * When a getter accesses another bloc's state, this manager ensures
1667
+ * re-renders occur when those external dependencies change.
1668
+ */
1669
+ var ExternalDependencyManager = class {
1670
+ constructor() {
1671
+ this.subscriptions = [];
1672
+ this.previousDeps = /* @__PURE__ */ new Set();
1673
+ }
1674
+ areDependenciesEqual(oldDeps, newDeps) {
1675
+ if (oldDeps.size !== newDeps.size) return false;
1676
+ for (const dep of newDeps) if (!oldDeps.has(dep)) return false;
1677
+ return true;
1678
+ }
1679
+ /**
1680
+ * Update subscriptions to external bloc dependencies.
1681
+ * Creates subscriptions to blocs accessed via getters.
1682
+ * @param getterTracker - The getter tracker state with external dependencies
1683
+ * @param rawInstance - The primary bloc instance (excluded from subscriptions)
1684
+ * @param onGetterChange - Callback to invoke when external dependency changes
1685
+ * @returns true if subscriptions were updated, false if unchanged
1686
+ */
1687
+ updateSubscriptions(getterTracker, rawInstance, onGetterChange) {
1688
+ if (!getterTracker?.externalDependencies) return false;
1689
+ const currentDeps = getterTracker.externalDependencies;
1690
+ if (this.areDependenciesEqual(this.previousDeps, currentDeps)) {
1691
+ clearExternalDependencies(getterTracker);
1692
+ return false;
1693
+ }
1694
+ this.cleanup();
1695
+ for (const externalBloc of currentDeps) {
1696
+ if (externalBloc === rawInstance) continue;
1697
+ const unsub = externalBloc.subscribe(() => {
1698
+ invalidateRenderCache(getterTracker);
1699
+ if (hasGetterChanges(rawInstance, getterTracker)) onGetterChange();
1700
+ });
1701
+ this.subscriptions.push(unsub);
1702
+ }
1703
+ this.previousDeps = new Set(currentDeps);
1704
+ clearExternalDependencies(getterTracker);
1705
+ return true;
1706
+ }
1707
+ /**
1708
+ * Clean up all active subscriptions
1709
+ */
1710
+ cleanup() {
1711
+ this.subscriptions.forEach((unsub) => unsub());
1712
+ this.subscriptions = [];
1713
+ }
1714
+ };
1715
+ /**
1716
+ * Create a subscribe function for auto-tracking mode.
1717
+ * Only triggers callback when tracked properties change.
1718
+ * @param instance - The state container instance
1719
+ * @param adapterState - The adapter state for tracking
1720
+ * @returns Subscribe function for use with useSyncExternalStore
1721
+ */
1722
+ function createAutoTrackSubscribe(instance, adapterState) {
1723
+ return (callback) => {
1724
+ return instance.subscribe(() => {
1725
+ const tracker = adapterState.tracker || (adapterState.tracker = createTrackerState());
1726
+ const hasStateDeps = tracker.pathCache && tracker.pathCache.size > 0;
1727
+ const hasGetterDeps = adapterState.getterTracker && adapterState.getterTracker.trackedGetters.size > 0;
1728
+ const isPrimitiveState = instance.state !== null && typeof instance.state !== "object" && typeof instance.state !== "function";
1729
+ if (!hasStateDeps && !hasGetterDeps && !isPrimitiveState) return;
1730
+ let stateChanged = hasChanges(tracker, instance.state);
1731
+ if (!hasStateDeps && hasGetterDeps) stateChanged = false;
1732
+ if (stateChanged) {
1733
+ callback();
1734
+ return;
1735
+ }
1736
+ if (hasGetterChanges(instance, adapterState.getterTracker)) callback();
1737
+ });
1738
+ };
1739
+ }
1740
+ /**
1741
+ * Create a subscribe function for manual dependency tracking mode.
1742
+ * Only triggers callback when dependencies array changes.
1743
+ * @param instance - The state container instance
1744
+ * @param adapterState - The adapter state for caching
1745
+ * @param config - Configuration with dependencies function
1746
+ * @returns Subscribe function for use with useSyncExternalStore
1747
+ */
1748
+ function createManualDepsSubscribe(instance, adapterState, config) {
1749
+ return (callback) => {
1750
+ return instance.subscribe(() => {
1751
+ const newDeps = config.dependencies(instance.state, instance);
1752
+ if (!adapterState.manualDepsCache || !shallowEqual(adapterState.manualDepsCache, newDeps)) {
1753
+ adapterState.manualDepsCache = newDeps;
1754
+ callback();
1755
+ }
1756
+ });
1757
+ };
1758
+ }
1759
+ /**
1760
+ * Create a subscribe function for no-tracking mode.
1761
+ * Triggers callback on every state change.
1762
+ * @param instance - The state container instance
1763
+ * @returns Subscribe function for use with useSyncExternalStore
1764
+ */
1765
+ function createNoTrackSubscribe(instance) {
1766
+ return (callback) => instance.subscribe(callback);
1767
+ }
1768
+ /**
1769
+ * Create a snapshot function for auto-tracking mode.
1770
+ * Returns a proxied state that tracks property access.
1771
+ * @param instance - The state container instance
1772
+ * @param adapterState - The adapter state for tracking
1773
+ * @returns Snapshot function for use with useSyncExternalStore
1774
+ */
1775
+ function createAutoTrackSnapshot(instance, adapterState) {
1776
+ return () => {
1777
+ const tracker = adapterState.tracker || (adapterState.tracker = createTrackerState());
1778
+ if (hasTrackedData(tracker)) captureTrackedPaths(tracker, instance.state);
1779
+ if (adapterState.getterTracker) {
1780
+ invalidateRenderCache(adapterState.getterTracker);
1781
+ commitTrackedGetters(adapterState.getterTracker);
1782
+ adapterState.getterTracker.isTracking = true;
1783
+ setActiveTracker(instance, adapterState.getterTracker);
1784
+ }
1785
+ startTracking(tracker);
1786
+ return createProxy(tracker, instance.state);
1787
+ };
1788
+ }
1789
+ /**
1790
+ * Create a snapshot function for manual dependency tracking mode.
1791
+ * Caches dependencies for comparison on next render.
1792
+ * @param instance - The state container instance
1793
+ * @param adapterState - The adapter state for caching
1794
+ * @param config - Configuration with dependencies function
1795
+ * @returns Snapshot function for use with useSyncExternalStore
1796
+ */
1797
+ function createManualDepsSnapshot(instance, adapterState, config) {
1798
+ return () => {
1799
+ adapterState.manualDepsCache = config.dependencies(instance.state, instance);
1800
+ return instance.state;
1801
+ };
1802
+ }
1803
+ /**
1804
+ * Create a snapshot function for no-tracking mode.
1805
+ * Returns the raw state directly.
1806
+ * @param instance - The state container instance
1807
+ * @returns Snapshot function for use with useSyncExternalStore
1808
+ */
1809
+ function createNoTrackSnapshot(instance) {
1810
+ return () => instance.state;
1811
+ }
1812
+ /**
1813
+ * Initialize adapter state for auto-tracking mode.
1814
+ * Creates getter tracker and proxied bloc instance.
1815
+ * @param instance - The state container instance
1816
+ * @returns Initialized adapter state
1817
+ */
1818
+ function initAutoTrackState(instance) {
1819
+ return {
1820
+ tracker: null,
1821
+ manualDepsCache: null,
1822
+ getterTracker: createGetterTracker(),
1823
+ proxiedBloc: createBlocProxy(instance)
1824
+ };
1825
+ }
1826
+ /**
1827
+ * Initialize adapter state for manual dependency tracking mode.
1828
+ * No proxy is created; bloc is used directly.
1829
+ * @param instance - The state container instance
1830
+ * @returns Initialized adapter state
1831
+ */
1832
+ function initManualDepsState(instance) {
1833
+ return {
1834
+ tracker: null,
1835
+ manualDepsCache: null,
1836
+ getterTracker: null,
1837
+ proxiedBloc: instance
1838
+ };
1839
+ }
1840
+ /**
1841
+ * Initialize adapter state for no-tracking mode.
1842
+ * No tracking or proxy is created.
1843
+ * @param instance - The state container instance
1844
+ * @returns Initialized adapter state
1845
+ */
1846
+ function initNoTrackState(instance) {
1847
+ return {
1848
+ tracker: null,
1849
+ manualDepsCache: null,
1850
+ getterTracker: null,
1851
+ proxiedBloc: instance
1852
+ };
1853
+ }
1854
+ /**
1855
+ * Disable getter tracking after render phase completes.
1856
+ * Clears the active tracker to prevent tracking outside of render.
1857
+ * @param adapterState - The adapter state
1858
+ * @param rawInstance - The raw bloc instance
1859
+ */
1860
+ function disableGetterTracking(adapterState, rawInstance) {
1861
+ if (adapterState.getterTracker) {
1862
+ adapterState.getterTracker.isTracking = false;
1863
+ clearActiveTracker(rawInstance);
1864
+ }
1865
+ }
1866
+
1867
+ //#endregion
1868
+ //#region src/logging/Logger.ts
1869
+ /**
1870
+ * Log severity levels (lower number = higher severity)
1871
+ */
1872
+ let LogLevel = /* @__PURE__ */ function(LogLevel$1) {
1873
+ /** Critical errors that may cause application failure */
1874
+ LogLevel$1[LogLevel$1["ERROR"] = 0] = "ERROR";
1875
+ /** Warning conditions that should be addressed */
1876
+ LogLevel$1[LogLevel$1["WARN"] = 1] = "WARN";
1877
+ /** Informational messages about application state */
1878
+ LogLevel$1[LogLevel$1["INFO"] = 2] = "INFO";
1879
+ /** Detailed debugging information */
1880
+ LogLevel$1[LogLevel$1["DEBUG"] = 3] = "DEBUG";
1881
+ return LogLevel$1;
1882
+ }({});
1883
+ /**
1884
+ * Creates a logger instance with given configuration
1885
+ *
1886
+ * @param config - Logger configuration
1887
+ * @returns Logger instance with debug, info, warn, error, and configure methods
1888
+ *
1889
+ * @example
1890
+ * ```ts
1891
+ * const logger = createLogger({
1892
+ * enabled: true,
1893
+ * level: LogLevel.DEBUG,
1894
+ * output: (entry) => console.log(JSON.stringify(entry))
1895
+ * });
1896
+ * logger.debug('MyComponent', 'Rendering', { props: { foo: 'bar' } });
1897
+ * ```
1898
+ */
1899
+ function createLogger(config) {
1900
+ const shouldLog = (level) => {
1901
+ return config.enabled && config.level >= level;
1902
+ };
1903
+ const log = (level, context, message, data) => {
1904
+ try {
1905
+ const entry = {
1906
+ level,
1907
+ context,
1908
+ message,
1909
+ timestamp: Date.now(),
1910
+ ...data !== void 0 && { data: serialize(data) }
1911
+ };
1912
+ config.output(entry);
1913
+ } catch (e) {
1914
+ console.error("[BlacLogger] Error logging:", e);
1915
+ }
1916
+ };
1917
+ const serialize = (data) => {
1918
+ try {
1919
+ return JSON.parse(JSON.stringify(data));
1920
+ } catch {
1921
+ return String(data);
1922
+ }
1923
+ };
1924
+ return {
1925
+ debug: (context, message, data) => {
1926
+ if (shouldLog(LogLevel.DEBUG)) log("DEBUG", context, message, data);
1927
+ },
1928
+ info: (context, message, data) => {
1929
+ if (shouldLog(LogLevel.INFO)) log("INFO", context, message, data);
1930
+ },
1931
+ warn: (context, message, data) => {
1932
+ if (shouldLog(LogLevel.WARN)) log("WARN", context, message, data);
1933
+ },
1934
+ error: (context, message, data) => {
1935
+ if (shouldLog(LogLevel.ERROR)) log("ERROR", context, message, data);
1936
+ },
1937
+ configure: (opts) => {
1938
+ Object.assign(config, opts);
1939
+ }
1940
+ };
1941
+ }
1942
+ let currentConfig = {
1943
+ enabled: false,
1944
+ level: LogLevel.INFO,
1945
+ output: (entry) => console.log(JSON.stringify(entry))
1946
+ };
1947
+ let defaultLogger = createLogger(currentConfig);
1948
+ /**
1949
+ * Log a debug message (tree-shakeable export)
1950
+ * @param context - Context identifier (module or component name)
1951
+ * @param message - Log message
1952
+ * @param data - Optional structured data
1953
+ */
1954
+ const debug = (context, message, data) => defaultLogger.debug(context, message, data);
1955
+ /**
1956
+ * Log an info message (tree-shakeable export)
1957
+ * @param context - Context identifier (module or component name)
1958
+ * @param message - Log message
1959
+ * @param data - Optional structured data
1960
+ */
1961
+ const info = (context, message, data) => defaultLogger.info(context, message, data);
1962
+ /**
1963
+ * Log a warning message (tree-shakeable export)
1964
+ * @param context - Context identifier (module or component name)
1965
+ * @param message - Log message
1966
+ * @param data - Optional structured data
1967
+ */
1968
+ const warn = (context, message, data) => defaultLogger.warn(context, message, data);
1969
+ /**
1970
+ * Log an error message (tree-shakeable export)
1971
+ * @param context - Context identifier (module or component name)
1972
+ * @param message - Log message
1973
+ * @param data - Optional structured data
1974
+ */
1975
+ const error = (context, message, data) => defaultLogger.error(context, message, data);
1976
+ /**
1977
+ * Configuration function that recreates the default logger
1978
+ *
1979
+ * @param opts - Partial logger configuration
1980
+ *
1981
+ * @example
1982
+ * ```ts
1983
+ * configureLogger({ enabled: true, level: LogLevel.DEBUG });
1984
+ * ```
1985
+ */
1986
+ function configureLogger(opts) {
1987
+ currentConfig = {
1988
+ ...currentConfig,
1989
+ ...opts
1990
+ };
1991
+ defaultLogger = createLogger(currentConfig);
1992
+ }
1993
+
1994
+ //#endregion
1995
+ //#region src/decorators/blac.ts
1996
+ /**
1997
+ * Decorator to configure StateContainer classes.
1998
+ *
1999
+ * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)
2000
+ * ```ts
2001
+ * @blac({ isolated: true })
2002
+ * class FormBloc extends Cubit<FormState> {}
2003
+ *
2004
+ * @blac({ keepAlive: true })
2005
+ * class AuthBloc extends Cubit<AuthState> {}
2006
+ *
2007
+ * @blac({ excludeFromDevTools: true })
2008
+ * class InternalBloc extends Cubit<InternalState> {}
2009
+ * ```
2010
+ *
2011
+ * @example Function syntax (no decorator support needed)
2012
+ * ```ts
2013
+ * const FormBloc = blac({ isolated: true })(
2014
+ * class extends Cubit<FormState> {}
2015
+ * );
2016
+ * ```
2017
+ */
2018
+ function blac(options) {
2019
+ return function(target, _context) {
2020
+ if ("isolated" in options && options.isolated) target[BLAC_STATIC_PROPS.ISOLATED] = true;
2021
+ if ("keepAlive" in options && options.keepAlive) target[BLAC_STATIC_PROPS.KEEP_ALIVE] = true;
2022
+ if ("excludeFromDevTools" in options && options.excludeFromDevTools) target[BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] = true;
2023
+ return target;
2024
+ };
2025
+ }
2026
+
2027
+ //#endregion
2028
+ export { BLAC_DEFAULTS, BLAC_ERROR_PREFIX, BLAC_ID_PATTERNS, BLAC_STATIC_PROPS, Cubit, ExternalDependencyManager, LogLevel, PluginManager, StateContainer, StateContainerRegistry, Vertex, __resetIdCounters, blac, captureTrackedPaths, clearActiveTracker, clearExternalDependencies, commitTrackedGetters, configureLogger, createArrayProxy, createAutoTrackSnapshot, createAutoTrackSubscribe, createBlocProxy, createGetterTracker, createIdGenerator, createLogger, createManualDepsSnapshot, createManualDepsSubscribe, createNoTrackSnapshot, createNoTrackSubscribe, createPluginManager, createProxy, createProxyForTarget, createProxyInternal, createProxyTrackerState, createTrackerState, debug, disableGetterTracking, error, generateId, generateIsolatedKey, generateSimpleId, getActiveTracker, getDescriptor, getGetterExecutionContext, getPluginManager, getStaticProp, getValueAtPath, globalRegistry, hasChanges, hasGetterChanges, hasInitHook, hasTrackedData, info, initAutoTrackState, initManualDepsState, initNoTrackState, invalidateRenderCache, isExcludedFromDevTools, isGetter, isIsolatedClass, isIsolatedKey, isKeepAliveClass, isProxyable, parsePath, resetGetterTracker, setActiveTracker, shallowEqual, startProxyTracking, startTracking, stopProxyTracking, warn };
38
2029
  //# sourceMappingURL=index.js.map