@blac/core 2.0.0-rc.0 → 2.0.0-rc.10

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