@blac/core 2.0.19 → 2.0.21

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 (236) hide show
  1. package/README.md +19 -29
  2. package/dist/{StateContainerRegistry-CSNm2Ws5.cjs → StateContainerRegistry-141uHhtF.cjs} +300 -397
  3. package/dist/StateContainerRegistry-141uHhtF.cjs.map +1 -0
  4. package/dist/{StateContainerRegistry-CvBOhAT2.js → StateContainerRegistry-vWgsD-RP.js} +277 -392
  5. package/dist/StateContainerRegistry-vWgsD-RP.js.map +1 -0
  6. package/dist/config.d.cts +2 -2
  7. package/dist/config.d.ts +2 -2
  8. package/dist/constants.d.cts +11 -20
  9. package/dist/constants.d.ts +11 -20
  10. package/dist/core/Cubit.d.ts +14 -10
  11. package/dist/core/StateContainer.d.ts +61 -4
  12. package/dist/core/StateContainerRegistry.d.ts +119 -16
  13. package/dist/core/meta.d.ts +5 -11
  14. package/dist/core/symbols.d.ts +24 -1
  15. package/dist/decorators/blac.d.ts +28 -26
  16. package/dist/{ensure-CQimeD0I.cjs → ensure-ORVw-WRE.cjs} +234 -40
  17. package/dist/ensure-ORVw-WRE.cjs.map +1 -0
  18. package/dist/{ensure-DTTTd2h8.js → ensure-k-6q7O25.js} +203 -39
  19. package/dist/ensure-k-6q7O25.js.map +1 -0
  20. package/dist/index.cjs +213 -32
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +6 -8
  23. package/dist/index.d.ts +6 -8
  24. package/dist/index.js +192 -12
  25. package/dist/index.js.map +1 -1
  26. package/dist/plugin/BlacPlugin.d.ts +14 -0
  27. package/dist/plugin/PluginManager.d.ts +23 -7
  28. package/dist/plugins.cjs +400 -3
  29. package/dist/plugins.cjs.map +1 -0
  30. package/dist/plugins.d.cts +6 -2
  31. package/dist/plugins.d.ts +6 -2
  32. package/dist/plugins.js +398 -1
  33. package/dist/plugins.js.map +1 -0
  34. package/dist/registry/acquire.d.ts +2 -2
  35. package/dist/registry/config.d.ts +9 -0
  36. package/dist/registry/management.d.ts +3 -0
  37. package/dist/registry/queries.d.ts +15 -0
  38. package/dist/registry/release.d.ts +3 -3
  39. package/dist/testing.cjs +13 -15
  40. package/dist/testing.cjs.map +1 -1
  41. package/dist/testing.d.cts +1 -1
  42. package/dist/testing.d.ts +1 -1
  43. package/dist/testing.js +2 -4
  44. package/dist/testing.js.map +1 -1
  45. package/dist/types/branded.d.ts +3 -3
  46. package/dist/types/utilities.d.ts +45 -18
  47. package/dist/utils/idGenerator.d.ts +0 -36
  48. package/dist/utils/static-props.d.ts +25 -1
  49. package/dist/utils/structural-key.d.ts +0 -7
  50. package/dist/watch/index.d.ts +1 -1
  51. package/dist/watch/watch.d.ts +22 -3
  52. package/package.json +17 -55
  53. package/dist/StateContainerRegistry-4Ljd9EJx.js +0 -1018
  54. package/dist/StateContainerRegistry-4Ljd9EJx.js.map +0 -1
  55. package/dist/StateContainerRegistry-B1GYx9Xo.js +0 -975
  56. package/dist/StateContainerRegistry-B1GYx9Xo.js.map +0 -1
  57. package/dist/StateContainerRegistry-B_ViBLvJ.js +0 -975
  58. package/dist/StateContainerRegistry-B_ViBLvJ.js.map +0 -1
  59. package/dist/StateContainerRegistry-C0dCNlTF.js +0 -1005
  60. package/dist/StateContainerRegistry-C0dCNlTF.js.map +0 -1
  61. package/dist/StateContainerRegistry-CEWpc1bj.cjs +0 -1113
  62. package/dist/StateContainerRegistry-CEWpc1bj.cjs.map +0 -1
  63. package/dist/StateContainerRegistry-CSNm2Ws5.cjs.map +0 -1
  64. package/dist/StateContainerRegistry-CchRjnjX.cjs +0 -1094
  65. package/dist/StateContainerRegistry-CchRjnjX.cjs.map +0 -1
  66. package/dist/StateContainerRegistry-CvBOhAT2.js.map +0 -1
  67. package/dist/StateContainerRegistry-D9BIRjwv.cjs +0 -1088
  68. package/dist/StateContainerRegistry-D9BIRjwv.cjs.map +0 -1
  69. package/dist/StateContainerRegistry-DJQqLrli.cjs +0 -1046
  70. package/dist/StateContainerRegistry-DJQqLrli.cjs.map +0 -1
  71. package/dist/StateContainerRegistry-DVIBTxGZ.js +0 -999
  72. package/dist/StateContainerRegistry-DVIBTxGZ.js.map +0 -1
  73. package/dist/StateContainerRegistry-Dj77cok9.js +0 -1005
  74. package/dist/StateContainerRegistry-Dj77cok9.js.map +0 -1
  75. package/dist/StateContainerRegistry-FWKzPfS-.cjs +0 -1046
  76. package/dist/StateContainerRegistry-FWKzPfS-.cjs.map +0 -1
  77. package/dist/StateContainerRegistry-lIwo-0m3.cjs +0 -1094
  78. package/dist/StateContainerRegistry-lIwo-0m3.cjs.map +0 -1
  79. package/dist/acquire-B1Wuqla6.cjs +0 -46
  80. package/dist/acquire-B1Wuqla6.cjs.map +0 -1
  81. package/dist/acquire-BP-ZfUH2.js +0 -35
  82. package/dist/acquire-BP-ZfUH2.js.map +0 -1
  83. package/dist/acquire-BRIJVJaA.js +0 -35
  84. package/dist/acquire-BRIJVJaA.js.map +0 -1
  85. package/dist/acquire-BZIs6tpN.cjs +0 -46
  86. package/dist/acquire-BZIs6tpN.cjs.map +0 -1
  87. package/dist/acquire-C3nOb3XR.cjs +0 -46
  88. package/dist/acquire-C3nOb3XR.cjs.map +0 -1
  89. package/dist/acquire-C4WAS13G.cjs +0 -46
  90. package/dist/acquire-C4WAS13G.cjs.map +0 -1
  91. package/dist/acquire-C7beGI55.cjs +0 -46
  92. package/dist/acquire-C7beGI55.cjs.map +0 -1
  93. package/dist/acquire-CbMz7gWs.cjs +0 -46
  94. package/dist/acquire-CbMz7gWs.cjs.map +0 -1
  95. package/dist/acquire-CwB083au.js +0 -35
  96. package/dist/acquire-CwB083au.js.map +0 -1
  97. package/dist/acquire-DHEOEVcj.cjs +0 -46
  98. package/dist/acquire-DHEOEVcj.cjs.map +0 -1
  99. package/dist/acquire-DXEQDZGr.js +0 -35
  100. package/dist/acquire-DXEQDZGr.js.map +0 -1
  101. package/dist/acquire-Dg-uXwjF.js +0 -35
  102. package/dist/acquire-Dg-uXwjF.js.map +0 -1
  103. package/dist/acquire-Don7499S.js +0 -35
  104. package/dist/acquire-Don7499S.js.map +0 -1
  105. package/dist/acquire-G8aB3GAx.js +0 -35
  106. package/dist/acquire-G8aB3GAx.js.map +0 -1
  107. package/dist/branded-BybA0_xw.cjs +0 -18
  108. package/dist/branded-BybA0_xw.cjs.map +0 -1
  109. package/dist/branded-DkbUzncc.js +0 -13
  110. package/dist/branded-DkbUzncc.js.map +0 -1
  111. package/dist/config-8pyOC5gv.js +0 -16
  112. package/dist/config-8pyOC5gv.js.map +0 -1
  113. package/dist/config-B1l8ZGlU.cjs +0 -32
  114. package/dist/config-B1l8ZGlU.cjs.map +0 -1
  115. package/dist/config-C7Ktkjh2.cjs +0 -32
  116. package/dist/config-C7Ktkjh2.cjs.map +0 -1
  117. package/dist/config-COT4Xkbc.js +0 -16
  118. package/dist/config-COT4Xkbc.js.map +0 -1
  119. package/dist/config-CzcoAvBo.js +0 -16
  120. package/dist/config-CzcoAvBo.js.map +0 -1
  121. package/dist/config-D6BoWWPv.js +0 -16
  122. package/dist/config-D6BoWWPv.js.map +0 -1
  123. package/dist/config-DVM_ESQt.js +0 -16
  124. package/dist/config-DVM_ESQt.js.map +0 -1
  125. package/dist/config-DVMnlHLv.cjs +0 -32
  126. package/dist/config-DVMnlHLv.cjs.map +0 -1
  127. package/dist/config-Dk1FxfXj.js +0 -16
  128. package/dist/config-Dk1FxfXj.js.map +0 -1
  129. package/dist/config-b2z51Y_C.cjs +0 -32
  130. package/dist/config-b2z51Y_C.cjs.map +0 -1
  131. package/dist/config-buwpT7l3.js +0 -16
  132. package/dist/config-buwpT7l3.js.map +0 -1
  133. package/dist/config-d9_U58ef.cjs +0 -32
  134. package/dist/config-d9_U58ef.cjs.map +0 -1
  135. package/dist/config-hWTayX76.cjs +0 -32
  136. package/dist/config-hWTayX76.cjs.map +0 -1
  137. package/dist/config-sCPKPYxZ.cjs +0 -32
  138. package/dist/config-sCPKPYxZ.cjs.map +0 -1
  139. package/dist/debug.cjs +0 -14
  140. package/dist/debug.d.cts +0 -34
  141. package/dist/debug.d.ts +0 -34
  142. package/dist/debug.js +0 -4
  143. package/dist/ensure-B1dEDsZV.cjs +0 -559
  144. package/dist/ensure-B1dEDsZV.cjs.map +0 -1
  145. package/dist/ensure-B9oOqpOB.cjs +0 -558
  146. package/dist/ensure-B9oOqpOB.cjs.map +0 -1
  147. package/dist/ensure-BfYnvAsI.js +0 -709
  148. package/dist/ensure-BfYnvAsI.js.map +0 -1
  149. package/dist/ensure-Bm91o37h.js +0 -536
  150. package/dist/ensure-Bm91o37h.js.map +0 -1
  151. package/dist/ensure-C1a8IFWy.js +0 -535
  152. package/dist/ensure-C1a8IFWy.js.map +0 -1
  153. package/dist/ensure-CLQEx0Nn.cjs +0 -528
  154. package/dist/ensure-CLQEx0Nn.cjs.map +0 -1
  155. package/dist/ensure-CPMiGvov.js +0 -493
  156. package/dist/ensure-CPMiGvov.js.map +0 -1
  157. package/dist/ensure-CQimeD0I.cjs.map +0 -1
  158. package/dist/ensure-DEXSmA-N.js +0 -526
  159. package/dist/ensure-DEXSmA-N.js.map +0 -1
  160. package/dist/ensure-DTTTd2h8.js.map +0 -1
  161. package/dist/ensure-Dx86f80B.cjs +0 -567
  162. package/dist/ensure-Dx86f80B.cjs.map +0 -1
  163. package/dist/ensure-DzqGej43.js +0 -526
  164. package/dist/ensure-DzqGej43.js.map +0 -1
  165. package/dist/ensure-VuiNPccZ.cjs +0 -559
  166. package/dist/ensure-VuiNPccZ.cjs.map +0 -1
  167. package/dist/ensure-_Oh8XPm4.cjs +0 -732
  168. package/dist/ensure-_Oh8XPm4.cjs.map +0 -1
  169. package/dist/ensure-fsQMjaQL.cjs +0 -567
  170. package/dist/ensure-fsQMjaQL.cjs.map +0 -1
  171. package/dist/ensure-vxAGa2v3.js +0 -536
  172. package/dist/ensure-vxAGa2v3.js.map +0 -1
  173. package/dist/management-14vsHr4t.cjs +0 -85
  174. package/dist/management-14vsHr4t.cjs.map +0 -1
  175. package/dist/management-444tdCBG.js +0 -38
  176. package/dist/management-444tdCBG.js.map +0 -1
  177. package/dist/management-7jLjVHJd.js +0 -38
  178. package/dist/management-7jLjVHJd.js.map +0 -1
  179. package/dist/management-AFuqQEwz.js +0 -38
  180. package/dist/management-AFuqQEwz.js.map +0 -1
  181. package/dist/management-BodVLAfJ.cjs +0 -85
  182. package/dist/management-BodVLAfJ.cjs.map +0 -1
  183. package/dist/management-BqGBdL01.js +0 -38
  184. package/dist/management-BqGBdL01.js.map +0 -1
  185. package/dist/management-BvUAjril.js +0 -38
  186. package/dist/management-BvUAjril.js.map +0 -1
  187. package/dist/management-C2wv4vGS.cjs +0 -85
  188. package/dist/management-C2wv4vGS.cjs.map +0 -1
  189. package/dist/management-D2pjr38g.js +0 -38
  190. package/dist/management-D2pjr38g.js.map +0 -1
  191. package/dist/management-D5WsZoTV.js +0 -38
  192. package/dist/management-D5WsZoTV.js.map +0 -1
  193. package/dist/management-DAV9sN-k.cjs +0 -85
  194. package/dist/management-DAV9sN-k.cjs.map +0 -1
  195. package/dist/management-Df7Y2sF1.cjs +0 -85
  196. package/dist/management-Df7Y2sF1.cjs.map +0 -1
  197. package/dist/management-DwO0nBzL.cjs +0 -85
  198. package/dist/management-DwO0nBzL.cjs.map +0 -1
  199. package/dist/management-GcnNJjnm.cjs +0 -85
  200. package/dist/management-GcnNJjnm.cjs.map +0 -1
  201. package/dist/types.cjs +0 -3
  202. package/dist/types.d.cts +0 -8
  203. package/dist/types.d.ts +0 -8
  204. package/dist/types.js +0 -2
  205. package/dist/watch-B91opmva.cjs +0 -70
  206. package/dist/watch-B91opmva.cjs.map +0 -1
  207. package/dist/watch-BHfCtbn1.cjs +0 -119
  208. package/dist/watch-BHfCtbn1.cjs.map +0 -1
  209. package/dist/watch-BmC-Tyqg.js +0 -59
  210. package/dist/watch-BmC-Tyqg.js.map +0 -1
  211. package/dist/watch-CKWt788i.cjs +0 -70
  212. package/dist/watch-CKWt788i.cjs.map +0 -1
  213. package/dist/watch-CfrSSrRY.js +0 -59
  214. package/dist/watch-CfrSSrRY.js.map +0 -1
  215. package/dist/watch-Cnh3PtQA.cjs +0 -70
  216. package/dist/watch-Cnh3PtQA.cjs.map +0 -1
  217. package/dist/watch-D01MdwKy.js +0 -108
  218. package/dist/watch-D01MdwKy.js.map +0 -1
  219. package/dist/watch-D8hwbFU1.js +0 -59
  220. package/dist/watch-D8hwbFU1.js.map +0 -1
  221. package/dist/watch-DPVUwPUY.js +0 -59
  222. package/dist/watch-DPVUwPUY.js.map +0 -1
  223. package/dist/watch-DVmvZBMD.cjs +0 -70
  224. package/dist/watch-DVmvZBMD.cjs.map +0 -1
  225. package/dist/watch-DkDGmGAx.cjs +0 -119
  226. package/dist/watch-DkDGmGAx.cjs.map +0 -1
  227. package/dist/watch-DztcJuUy.cjs +0 -119
  228. package/dist/watch-DztcJuUy.cjs.map +0 -1
  229. package/dist/watch-IrR8G28N.js +0 -108
  230. package/dist/watch-IrR8G28N.js.map +0 -1
  231. package/dist/watch-entry.cjs +0 -4
  232. package/dist/watch-entry.d.cts +0 -24
  233. package/dist/watch-entry.d.ts +0 -24
  234. package/dist/watch-entry.js +0 -2
  235. package/dist/watch-hx0r92Zc.js +0 -108
  236. package/dist/watch-hx0r92Zc.js.map +0 -1
@@ -1,1094 +0,0 @@
1
- let _dirtytalk_structural = require("@dirtytalk/structural");
2
- //#region src/config.ts
3
- /**
4
- * Default equality: shallow per-key `Object.is` comparison.
5
- * Falls through to `false` for primitives/null so reference-only state still
6
- * behaves correctly.
7
- */
8
- const shallowEqualState = (prev, next) => {
9
- if (Object.is(prev, next)) return true;
10
- if (typeof prev !== "object" || prev === null) return false;
11
- if (typeof next !== "object" || next === null) return false;
12
- const prevKeys = Object.keys(prev);
13
- if (prevKeys.length !== Object.keys(next).length) return false;
14
- for (let i = 0; i < prevKeys.length; i++) {
15
- const key = prevKeys[i];
16
- if (!Object.is(prev[key], next[key])) return false;
17
- }
18
- return true;
19
- };
20
- const defaultConfig = {
21
- equality: shallowEqualState,
22
- maxInstancesPerType: 1e5,
23
- maxRefsPerInstance: 1e5,
24
- maxEmitsPerSecond: 1e3
25
- };
26
- let globalConfig = { ...defaultConfig };
27
- /**
28
- * Configure global defaults for @blac/core.
29
- *
30
- * @example
31
- * ```ts
32
- * import { configureBlac, shallowEqualState } from '@blac/core';
33
- *
34
- * // Swap in a deep-equality check for all blocs
35
- * configureBlac({ equality: myDeepEqual });
36
- * ```
37
- */
38
- function configureBlac(config) {
39
- globalConfig = {
40
- ...globalConfig,
41
- ...config
42
- };
43
- }
44
- /**
45
- * Get the current global configuration.
46
- * @internal
47
- */
48
- function getBlacConfig() {
49
- return globalConfig;
50
- }
51
- /**
52
- * Reset configuration to defaults (useful for testing).
53
- * @internal
54
- */
55
- function resetBlacConfig() {
56
- globalConfig = { ...defaultConfig };
57
- }
58
- //#endregion
59
- //#region src/plugin/PluginManager.ts
60
- /**
61
- * Manages plugin lifecycle for the BlaC state management system.
62
- *
63
- * The manager hooks into two surfaces:
64
- *
65
- * 1. **Registry lifecycle events** (`created`, `disposed`, `refAcquired`,
66
- * `refReleased`, `depsChanged`) — synchronous, fired by the registry.
67
- *
68
- * 2. **Per-container channel flushes** — microtask-coalesced. For each
69
- * container, the manager subscribes once at create-time with
70
- * `ALL_PATHS` interest and stashes `prevState`. On every flush it
71
- * captures the new state + the changed `PathSet` and dispatches
72
- * `onStateChange(ctx, prev, next, paths)` to every enabled plugin.
73
- *
74
- * The `ALL_PATHS` subscription cost: plugins counted as a consumer with
75
- * `ALL_PATHS` interest will defeat the single-consumer-skip optimization
76
- * in `StructuralContainer`. This is the intended trade-off — devtools /
77
- * persist plugins genuinely want every change, and stateful plugins
78
- * (logging) can decode `paths` via `container.interner.lookup(id)` to log
79
- * only relevant fields. Plugins that want low overhead should remain
80
- * uninstalled or environment-gated.
81
- *
82
- * @example
83
- * ```ts
84
- * const manager = createPluginManager(registry);
85
- * manager.install(myPlugin, { environment: 'development' });
86
- * ```
87
- */
88
- var PluginManager = class {
89
- /**
90
- * Create a new PluginManager
91
- * @param registry - The StateContainerRegistry to monitor for lifecycle events
92
- */
93
- constructor(registry) {
94
- this.plugins = /* @__PURE__ */ new Map();
95
- this.lifecycleUnsubscribers = [];
96
- this.containerBridges = /* @__PURE__ */ new WeakMap();
97
- this.registry = registry;
98
- this.setupLifecycleHooks();
99
- }
100
- /**
101
- * Install a plugin with optional configuration
102
- * @param plugin - The plugin to install
103
- * @param config - Optional plugin configuration
104
- * @throws Error if plugin is already installed
105
- */
106
- install(plugin, config = {}) {
107
- const effectiveConfig = {
108
- enabled: true,
109
- environment: "all",
110
- ...config
111
- };
112
- if (!this.shouldEnablePlugin(effectiveConfig)) {
113
- console.log(`[BlaC] Plugin "${plugin.name}" skipped (environment mismatch)`);
114
- return;
115
- }
116
- if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already installed`);
117
- const installContext = this.buildContext(void 0);
118
- this.plugins.set(plugin.name, {
119
- plugin,
120
- config: effectiveConfig,
121
- installContext
122
- });
123
- if (plugin.onInstall) try {
124
- plugin.onInstall(installContext);
125
- } catch (error) {
126
- console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error);
127
- this.plugins.delete(plugin.name);
128
- throw error;
129
- }
130
- console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
131
- }
132
- /**
133
- * Uninstall a plugin by name
134
- * @param pluginName - The name of the plugin to uninstall
135
- * @throws Error if plugin is not installed
136
- */
137
- uninstall(pluginName) {
138
- const installed = this.plugins.get(pluginName);
139
- if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
140
- if (installed.plugin.onUninstall) try {
141
- installed.plugin.onUninstall();
142
- } catch (error) {
143
- console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error);
144
- }
145
- this.plugins.delete(pluginName);
146
- console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
147
- }
148
- /**
149
- * Get an installed plugin by name
150
- * @param pluginName - The name of the plugin to retrieve
151
- * @returns The plugin instance or undefined if not found
152
- */
153
- getPlugin(pluginName) {
154
- return this.plugins.get(pluginName)?.plugin;
155
- }
156
- /**
157
- * Get all installed plugins
158
- * @returns Array of all installed plugins
159
- */
160
- getAllPlugins() {
161
- return Array.from(this.plugins.values()).map((p) => p.plugin);
162
- }
163
- /**
164
- * Check if a plugin is installed
165
- * @param pluginName - The name of the plugin to check
166
- * @returns true if the plugin is installed
167
- */
168
- hasPlugin(pluginName) {
169
- return this.plugins.has(pluginName);
170
- }
171
- /**
172
- * Uninstall all plugins
173
- */
174
- clear() {
175
- for (const name of this.plugins.keys()) this.uninstall(name);
176
- }
177
- destroy() {
178
- this.clear();
179
- for (const unsub of this.lifecycleUnsubscribers) unsub();
180
- this.lifecycleUnsubscribers = [];
181
- }
182
- /**
183
- * Wire registry lifecycle events into plugin dispatch.
184
- *
185
- * `onStateChange` is NOT wired through `registry.on('stateChanged', …)` —
186
- * that event lacks the `PathSet` payload. Instead, on each `created` we
187
- * subscribe to the container's channel directly so we get
188
- * `(paths)` and capture `(prev, next)` via the per-container snapshot.
189
- */
190
- setupLifecycleHooks() {
191
- this.lifecycleUnsubscribers = [
192
- this.registry.on("created", (instance) => {
193
- this.attachStateBridge(instance);
194
- this.notifyPlugins("onCreated", instance);
195
- }),
196
- this.registry.on("disposed", (instance) => {
197
- this.notifyPlugins("onDestroyed", instance);
198
- this.detachStateBridge(instance);
199
- }),
200
- this.registry.on("refAcquired", (instance, refId) => {
201
- this.notifyPlugins("onRefAcquired", instance, refId);
202
- }),
203
- this.registry.on("refReleased", (instance, refId) => {
204
- this.notifyPlugins("onRefReleased", instance, refId);
205
- }),
206
- this.registry.on("depsChanged", (instance, previousDeps, currentDeps) => {
207
- this.notifyPlugins("onDepsChanged", instance, previousDeps, currentDeps);
208
- }),
209
- this.registry.on("hydrationChanged", (instance, status, previousStatus) => {
210
- this.notifyPlugins("onHydrationChange", instance, status, previousStatus);
211
- })
212
- ];
213
- }
214
- /**
215
- * Subscribe to the container's channel with `ALL_PATHS` interest, so we
216
- * fire on every flush. Capture `prev` from the snapshot taken on the
217
- * previous flush (or at create-time for the first flush) and pass the
218
- * channel's `paths` argument straight through to plugins.
219
- *
220
- * Per-container bookkeeping is stored in a `WeakMap` keyed by the
221
- * container itself, so a disposed/GC'd container drops cleanly.
222
- */
223
- attachStateBridge(container) {
224
- if (this.containerBridges.has(container)) return;
225
- const bridge = {
226
- unsub: () => {},
227
- prevState: container.state
228
- };
229
- this.containerBridges.set(container, bridge);
230
- bridge.unsub = container.channel.subscribe(() => _dirtytalk_structural.ALL_PATHS, (paths) => this.dispatchStateChange(container, paths));
231
- }
232
- detachStateBridge(container) {
233
- const bridge = this.containerBridges.get(container);
234
- if (!bridge) return;
235
- bridge.unsub();
236
- this.containerBridges.delete(container);
237
- }
238
- /**
239
- * Channel-flush callback. Snapshots `next`, hands `(prev, next, paths)`
240
- * to every enabled plugin's `onStateChange`, then updates `prevState`
241
- * for the next flush.
242
- *
243
- * Note: `prev` is captured once and reused across plugins — every
244
- * plugin sees the same `prev`/`next`/`paths` regardless of dispatch
245
- * order, matching the "snapshot prev once per flush" invariant.
246
- */
247
- dispatchStateChange(container, paths) {
248
- const bridge = this.containerBridges.get(container);
249
- if (!bridge) return;
250
- const prev = bridge.prevState;
251
- const next = container.state;
252
- bridge.prevState = next;
253
- let ctx;
254
- for (const { plugin, config } of this.plugins.values()) {
255
- if (!config.enabled) continue;
256
- const hook = plugin.onStateChange;
257
- if (typeof hook !== "function") continue;
258
- try {
259
- ctx ??= this.buildContext(container);
260
- hook.call(plugin, ctx, prev, next, paths);
261
- } catch (error) {
262
- console.error(`[BlaC] Error in plugin "${plugin.name}" onStateChange:`, error);
263
- }
264
- }
265
- }
266
- /**
267
- * Notify all plugins of a lifecycle event.
268
- *
269
- * Builds a fresh `PluginContext` per dispatch (instance becomes
270
- * `ctx.container`), so plugins can reach the focal bloc through
271
- * `ctx.container`. The context is built lazily on the first matching
272
- * hook and reused for every other plugin in this dispatch — zero
273
- * builds if no enabled plugin implements `hookName`.
274
- */
275
- notifyPlugins(hookName, instance, ...extraArgs) {
276
- let ctx;
277
- for (const { plugin, config } of this.plugins.values()) {
278
- if (!config.enabled) continue;
279
- const hook = plugin[hookName];
280
- if (typeof hook !== "function") continue;
281
- try {
282
- ctx ??= this.buildContext(instance);
283
- hook.call(plugin, ctx, ...extraArgs);
284
- } catch (error) {
285
- console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error);
286
- }
287
- }
288
- }
289
- /**
290
- * Build a `PluginContext` for a given focal container. The context is
291
- * cheap to build — its methods close over `this.registry` directly —
292
- * so we create one per dispatch rather than caching per container.
293
- * This sidesteps the lifetime question of "when do we evict a cached
294
- * context?" and keeps `paths`-vs-`container` lifetimes cleanly
295
- * separated.
296
- */
297
- buildContext(container) {
298
- const registry = this.registry;
299
- return {
300
- container,
301
- getInstanceMetadata: (instance) => {
302
- return {
303
- id: instance.$blac.id,
304
- className: instance.constructor.name,
305
- isDisposed: instance.$blac.disposed,
306
- name: instance.$blac.name,
307
- createdAt: instance.$blac.createdAt,
308
- state: instance.state,
309
- hydrationStatus: instance.$blac.hydration.status,
310
- isHydrated: instance.$blac.hydration.isHydrated,
311
- hydrationError: instance.$blac.hydration.error,
312
- changedWhileHydrating: instance.$blac.hydration.changedWhileHydrating,
313
- args: instance.args
314
- };
315
- },
316
- getState: (instance) => {
317
- return instance.state;
318
- },
319
- getHydrationStatus: (instance) => {
320
- return instance.$blac.hydration.status;
321
- },
322
- startHydration: (instance) => {
323
- instance.$blac.hydration.begin();
324
- },
325
- applyHydratedState: (instance, state) => {
326
- return instance.$blac.hydration.apply(state);
327
- },
328
- finishHydration: (instance) => {
329
- instance.$blac.hydration.finish();
330
- },
331
- failHydration: (instance, error) => {
332
- instance.$blac.hydration.fail(error);
333
- },
334
- waitForHydration: (instance) => {
335
- return instance.$blac.hydration.wait();
336
- },
337
- queryInstances: (typeClass) => {
338
- return registry.getAll(typeClass);
339
- },
340
- getAllTypes: () => {
341
- return registry.getTypes();
342
- },
343
- getStats: () => {
344
- return registry.getStats();
345
- },
346
- getRefIds: (instanceId) => {
347
- for (const Type of registry.getTypes()) {
348
- const map = registry.getInstancesMap(Type);
349
- for (const [, entry] of map) if (entry.instance.$blac.id === instanceId) return Array.from(entry.refs.keys());
350
- }
351
- return [];
352
- }
353
- };
354
- }
355
- /**
356
- * Check if plugin should be enabled based on environment
357
- */
358
- shouldEnablePlugin(config) {
359
- if (!config.enabled) return false;
360
- if (config.environment === "all") return true;
361
- return this.getCurrentEnvironment() === config.environment;
362
- }
363
- /**
364
- * Get current environment
365
- */
366
- getCurrentEnvironment() {
367
- if (typeof process !== "undefined") {
368
- if (process.env.NODE_ENV === "test") return "test";
369
- if (process.env.NODE_ENV === "production") return "production";
370
- return "development";
371
- }
372
- return "development";
373
- }
374
- };
375
- /**
376
- * Create a plugin manager instance
377
- * @param registry - The StateContainerRegistry to monitor for lifecycle events
378
- * @returns A new PluginManager instance
379
- */
380
- function createPluginManager(registry) {
381
- return new PluginManager(registry);
382
- }
383
- //#endregion
384
- //#region src/constants.ts
385
- /**
386
- * Default configuration constants for BlaC
387
- *
388
- * Centralized location for all magic numbers and default values.
389
- */
390
- /**
391
- * Default configuration constants for BlaC
392
- */
393
- const BLAC_DEFAULTS = {
394
- /**
395
- * Default instance key for shared instances
396
- */
397
- DEFAULT_INSTANCE_KEY: "default",
398
- /**
399
- * Maximum getter nesting depth (prevents infinite recursion)
400
- */
401
- MAX_GETTER_DEPTH: 10
402
- };
403
- /**
404
- * Static property names for StateContainer classes
405
- * Used for feature flags and configuration on bloc classes
406
- */
407
- const BLAC_STATIC_PROPS = {
408
- /**
409
- * Mark a bloc to never be auto-disposed (kept alive permanently)
410
- */
411
- KEEP_ALIVE: "keepAlive",
412
- /**
413
- * Exclude a bloc from DevTools reporting (prevents infinite loops)
414
- */
415
- EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools",
416
- /**
417
- * Per-class equality function used to short-circuit `emit`/`patch` when the
418
- * new state is structurally equal to the previous state. Falls back to the
419
- * global `configureBlac({ equality })` value when unset.
420
- */
421
- EQUALITY: "__equality",
422
- /**
423
- * Per-class key function: `static key = (args) => string`.
424
- * When set, the registry calls `Type.key(args)` to derive the instance key
425
- * instead of using a structural hash of `args`. Allows blocs to ignore
426
- * non-identity fields (e.g., `readonly` flags) while still keying by id.
427
- */
428
- KEY: "key"
429
- };
430
- /**
431
- * Standard error message prefix
432
- */
433
- const BLAC_ERROR_PREFIX = "[BlaC]";
434
- //#endregion
435
- //#region src/utils/static-props.ts
436
- /**
437
- * Utility functions for accessing static properties on StateContainer classes
438
- */
439
- /**
440
- * Get a static property from a class constructor
441
- * Type-safe helper that avoids (Type as any) casts
442
- *
443
- * @param Type - The class constructor
444
- * @param propName - The property name to access
445
- * @param defaultValue - Optional default value if property is undefined
446
- * @returns The property value or default
447
- */
448
- function getStaticProp(Type, propName, defaultValue) {
449
- return Type[propName] ?? defaultValue;
450
- }
451
- /**
452
- * Check if a class is marked as keepAlive.
453
- * KeepAlive classes are never auto-disposed when ref count reaches 0.
454
- * @param Type - The class constructor to check
455
- * @returns true if the class has `static keepAlive = true`
456
- */
457
- function isKeepAliveClass(Type) {
458
- return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
459
- }
460
- /**
461
- * Check if a class should be excluded from DevTools.
462
- * Used to prevent infinite loops when DevTools tracks itself.
463
- * @param Type - The class constructor to check
464
- * @returns true if the class has `static __excludeFromDevTools = true`
465
- */
466
- function isExcludedFromDevTools(Type) {
467
- return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
468
- }
469
- /**
470
- * Get the per-class equality function set via `@blac({ equality })`, if any.
471
- * @param Type - The class constructor to check
472
- * @returns the equality function or `undefined`
473
- */
474
- function getClassEquality(Type) {
475
- const fn = getStaticProp(Type, BLAC_STATIC_PROPS.EQUALITY);
476
- return typeof fn === "function" ? fn : void 0;
477
- }
478
- /**
479
- * Get the per-class key function set via `@blac({ key })` or `static key = …`, if any.
480
- * Used by the registry to derive a stable instance key from `args`.
481
- * @param Type - The class constructor to check
482
- * @returns the key function or `undefined`
483
- */
484
- function getClassKey(Type) {
485
- const fn = getStaticProp(Type, BLAC_STATIC_PROPS.KEY, void 0);
486
- return typeof fn === "function" ? fn : void 0;
487
- }
488
- //#endregion
489
- //#region src/utils/structural-key.ts
490
- /**
491
- * Deterministic, order-independent hash of serializable args.
492
- * Sorts object keys so {a,b} === {b,a}.
493
- * Throws (dev) if it encounters a function or non-plain object — those belong in `deps`.
494
- */
495
- const DEFAULT_STRUCTURAL_KEY = "default";
496
- /**
497
- * Produce a stable string key for serializable args.
498
- * - `undefined` / `void` args → `'default'` sentinel (no-args blocs stay on the default key).
499
- * - Object keys are sorted for order-independence.
500
- * - Arrays keep their insertion order.
501
- * - Functions throw — they must be passed via `deps`, not `args`.
502
- */
503
- function structuralKey(args) {
504
- if (args === void 0 || args === null) return DEFAULT_STRUCTURAL_KEY;
505
- return JSON.stringify(args, function(_k, v) {
506
- if (typeof v === "function") throw new Error("[blac] args must be serializable; put refs/callbacks in `deps`");
507
- if (v && typeof v === "object" && !Array.isArray(v)) return Object.keys(v).sort().reduce((o, k) => {
508
- o[k] = v[k];
509
- return o;
510
- }, {});
511
- return v;
512
- });
513
- }
514
- //#endregion
515
- //#region src/core/symbols.ts
516
- /**
517
- * @internal Apply one owner's (consumer's) deps slice to an instance.
518
- * Called by framework adapters (e.g. @blac/react useBloc) — not public API.
519
- */
520
- const APPLY_DEPS = Symbol("blac.applyDeps");
521
- /**
522
- * @internal Withdraw one owner's entire deps slice (consumer unmounted).
523
- * Called by framework adapters — not public API.
524
- */
525
- const REMOVE_DEPS_OWNER = Symbol("blac.removeDepsOwner");
526
- /**
527
- * @internal Symbol-keyed configuration entry point on `StateContainer`.
528
- * Writes the instance's identity fields (`_name`/`_debug`/`_instanceId`),
529
- * resolves per-class equality, emits the registry `created` event, and runs
530
- * `init()` once.
531
- *
532
- * Framework-only — the registry (`StateContainerRegistry.ensure`) and testing
533
- * helpers are the sole callers, mirroring the `APPLY_DEPS` precedent.
534
- */
535
- const INIT_CONFIG = Symbol("blac.initConfig");
536
- //#endregion
537
- //#region src/core/StateContainerRegistry.ts
538
- /**
539
- * Central registry for managing StateContainer instances.
540
- * Handles instance lifecycle, named ref tracking, and lifecycle event emission.
541
- *
542
- * @example
543
- * ```ts
544
- * const registry = new StateContainerRegistry();
545
- * const instance = registry.acquire(MyBloc); // ownership, must release
546
- * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
547
- * registry.on('stateChanged', (container, prev, next) => {
548
- * console.log('State changed:', prev, '->', next);
549
- * });
550
- * ```
551
- */
552
- var StateContainerRegistry = class {
553
- constructor() {
554
- this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
555
- this.types = /* @__PURE__ */ new Set();
556
- this.registeredTypeNames = /* @__PURE__ */ new Set();
557
- this.listeners = /* @__PURE__ */ new Map();
558
- this._stateChangedListenerCount = 0;
559
- this._pendingStateChanges = null;
560
- this._autoRefIdCounter = 0;
561
- }
562
- get hasStateChangedListeners() {
563
- return this._stateChangedListenerCount > 0;
564
- }
565
- /**
566
- * Register a type for lifecycle event tracking
567
- * @param constructor - The StateContainer class constructor
568
- */
569
- registerType(constructor) {
570
- this.types.add(constructor);
571
- }
572
- /**
573
- * Register a StateContainer class with configuration
574
- * @param constructor - The StateContainer class constructor
575
- * @throws Error if type is already registered
576
- */
577
- register(constructor) {
578
- const className = constructor.name;
579
- if (this.registeredTypeNames.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
580
- this.registeredTypeNames.add(className);
581
- this.registerType(constructor);
582
- }
583
- ensureInstancesMap(Type) {
584
- let instances = this.instancesByConstructor.get(Type);
585
- if (!instances) {
586
- instances = /* @__PURE__ */ new Map();
587
- this.instancesByConstructor.set(Type, instances);
588
- }
589
- return instances;
590
- }
591
- /**
592
- * Get the instances Map for a specific class (public API for stats/debugging)
593
- */
594
- getInstancesMap(Type) {
595
- return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
596
- }
597
- /**
598
- * Directly insert an instance entry into the registry without going through
599
- * acquire/release. Creates the internal WeakMap bucket for the constructor if
600
- * it does not exist yet. Replaces any existing entry for the same key.
601
- *
602
- * The provided instance is NOT configured or disposed here — callers are
603
- * responsible for any initConfig / dispose calls. Intended for testing
604
- * helpers that create stubs outside the normal acquisition path.
605
- *
606
- * @internal Used by testing helpers only.
607
- */
608
- insertInstance(Type, instanceKey, instance, refs = /* @__PURE__ */ new Map()) {
609
- const instances = this.ensureInstancesMap(Type);
610
- const existingEntry = instances.get(instanceKey);
611
- if (existingEntry && existingEntry.instance !== instance && !existingEntry.instance.$blac.disposed) existingEntry.instance.dispose();
612
- instances.set(instanceKey, {
613
- instance,
614
- refs
615
- });
616
- }
617
- /**
618
- * Resolve the storage key for an instance. This is the single source of truth
619
- * for keying — `acquire` and `release` MUST agree, otherwise a ref taken under
620
- * an args-derived key is never dropped (instance leaks).
621
- *
622
- * Resolution order (explicit beats derived):
623
- * explicit key > `static key(args)` > structural hash of args > default sentinel.
624
- *
625
- * @param Type - The StateContainer class constructor
626
- * @param instanceKey - Explicit key, or undefined to derive from args
627
- * @param args - Construction args used for structural/`static key` derivation
628
- */
629
- resolveKey(Type, instanceKey, args) {
630
- if (instanceKey !== void 0) return instanceKey;
631
- const keyFn = getClassKey(Type);
632
- if (keyFn) return keyFn(args);
633
- if (args !== void 0) return structuralKey(args);
634
- return DEFAULT_STRUCTURAL_KEY;
635
- }
636
- /**
637
- * Circuit breaker for runaway instance creation. Throws when a single
638
- * constructor would exceed `maxInstancesPerType` live instances — almost
639
- * always an unstable instance key (e.g. a new object/array passed as `args`
640
- * every render, or a missing `static key`) leaking an instance per render.
641
- */
642
- assertInstanceLimit(Type, currentCount) {
643
- const limit = getBlacConfig().maxInstancesPerType;
644
- if (limit > 0 && currentCount >= limit) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} exceeded the maximum of ${limit} live instances. This usually means the instance key is unstable — e.g. \`args\` that change identity every render, or a missing \`static key\` — so a new instance is created and never disposed (memory leak). Stabilize the key, add a \`static key(args)\`, or raise \`configureBlac({ maxInstancesPerType })\`.`);
645
- }
646
- /**
647
- * Circuit breaker for runaway reference growth. Throws when one instance
648
- * accumulates more than `maxRefsPerInstance` distinct live refs — almost
649
- * always consumer cleanup (e.g. `useBloc`'s unmount `release`) never firing.
650
- */
651
- assertRefLimit(Type, resolvedKey, refCount) {
652
- const limit = getBlacConfig().maxRefsPerInstance;
653
- if (limit > 0 && refCount > limit) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${resolvedKey}" exceeded the maximum of ${limit} live references. This usually means references are acquired without a matching release (e.g. a consumer that never unmounts/cleans up), leaking refs that keep the instance alive forever. Ensure every acquire is paired with a release, or raise \`configureBlac({ maxRefsPerInstance })\`.`);
654
- }
655
- /**
656
- * Acquire an instance with ref tracking (ownership semantics).
657
- * Creates a new instance if one doesn't exist, or returns existing and adds a ref.
658
- * You must call `release()` with the same refId when done.
659
- *
660
- * @internal Internal key tier. Public callers use the args-based `acquire`
661
- * wrapper; `useBloc` and `watch` address a pre-resolved key here.
662
- * @param Type - The StateContainer class constructor
663
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
664
- * @param options - Acquisition options
665
- * @param options.canCreate - Whether to create new instance if not found (default: true)
666
- * @param options.countRef - Whether to add a reference (default: true)
667
- * @param options.refId - Named reference ID for debugging; auto-generated if omitted
668
- * @returns The state container instance
669
- */
670
- acquire(Type, instanceKey, options = {}) {
671
- const { canCreate = true, countRef = true } = options;
672
- const args = options.args;
673
- const resolvedKey = this.resolveKey(Type, instanceKey, args);
674
- const config = {
675
- instanceId: resolvedKey,
676
- args
677
- };
678
- const instances = this.ensureInstancesMap(Type);
679
- let entry = instances.get(resolvedKey);
680
- if (entry?.instance.$blac.disposed) {
681
- instances.delete(resolvedKey);
682
- entry = void 0;
683
- }
684
- if (entry) {
685
- if (process.env.NODE_ENV !== "production" && args !== void 0 && entry.args !== void 0) {
686
- const incomingKey = structuralKey(args);
687
- const storedKey = structuralKey(entry.args);
688
- if (incomingKey !== storedKey) console.warn(`${BLAC_ERROR_PREFIX} ${Type.name} instance key "${resolvedKey}" was acquired with different args. Existing args: ${storedKey}, new args: ${incomingKey}. The existing instance will be reused. If distinct args should produce distinct instances, either remove the explicit instanceKey or provide a \`static key\` function that reflects the difference.`);
689
- }
690
- if (countRef) {
691
- const refId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
692
- entry.refs.set(refId, (entry.refs.get(refId) ?? 0) + 1);
693
- this.assertRefLimit(Type, resolvedKey, entry.refs.size);
694
- this.emit("refAcquired", entry.instance, refId);
695
- }
696
- return entry.instance;
697
- }
698
- if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${resolvedKey}" not found and creation is disabled.`);
699
- this.assertInstanceLimit(Type, instances.size);
700
- const instance = new Type();
701
- instance[INIT_CONFIG](config);
702
- const initialRefs = /* @__PURE__ */ new Map();
703
- let initialRefId;
704
- if (countRef) {
705
- initialRefId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
706
- initialRefs.set(initialRefId, 1);
707
- }
708
- instances.set(resolvedKey, {
709
- instance,
710
- refs: initialRefs,
711
- args
712
- });
713
- this.registerType(Type);
714
- if (initialRefId) this.emit("refAcquired", instance, initialRefId);
715
- return instance;
716
- }
717
- /**
718
- * Borrow an existing instance without adding a ref (borrowing semantics).
719
- * Tracks cross-bloc dependency for reactive updates.
720
- *
721
- * @internal Internal key tier; public callers use the args-based `borrow`.
722
- * @param Type - The StateContainer class constructor
723
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
724
- * @returns The state container instance
725
- * @throws Error if instance doesn't exist
726
- */
727
- borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
728
- return this.acquire(Type, instanceKey, {
729
- canCreate: false,
730
- countRef: false
731
- });
732
- }
733
- /**
734
- * Safely borrow an existing instance (borrowing semantics with error handling).
735
- * Returns discriminated union for type-safe conditional access.
736
- *
737
- * @internal Internal key tier; public callers use the args-based `borrowSafe`.
738
- * @param Type - The StateContainer class constructor
739
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
740
- * @returns Discriminated union with either the instance or an error
741
- */
742
- borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
743
- try {
744
- return {
745
- error: null,
746
- instance: this.borrow(Type, instanceKey)
747
- };
748
- } catch (error) {
749
- return {
750
- error,
751
- instance: null
752
- };
753
- }
754
- }
755
- /**
756
- * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
757
- * Gets existing instance OR creates it if it doesn't exist, without adding a ref.
758
- * Tracks cross-bloc dependency for reactive updates.
759
- *
760
- * Use this in bloc-to-bloc communication when you need to ensure an instance exists
761
- * but don't want to claim ownership (no ref added).
762
- *
763
- * @internal Internal key tier; public callers use the args-based `ensure`.
764
- * @param Type - The StateContainer class constructor
765
- * @param instanceKey - Pre-resolved instance key, or undefined to derive from `args`
766
- * (`static key(args)` / structural hash), matching `acquire`.
767
- * @param args - Construction args; used for keying when no explicit key is given
768
- * @returns The state container instance
769
- */
770
- ensure(Type, instanceKey, args) {
771
- return this.acquire(Type, instanceKey, {
772
- canCreate: true,
773
- countRef: false,
774
- args
775
- });
776
- }
777
- /**
778
- * Release a reference to an instance.
779
- * Removes the ref and disposes when refs is empty (unless keepAlive).
780
- * Releasing an already-removed refId is a no-op (idempotent).
781
- *
782
- * @internal Internal key tier; public callers use the args-based `release`.
783
- * @param Type - The StateContainer class constructor
784
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
785
- * @param forceDispose - Force immediate disposal regardless of refs
786
- * @param refId - The specific ref to remove; removes one arbitrary ref if omitted
787
- */
788
- release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false, refId) {
789
- const instances = this.ensureInstancesMap(Type);
790
- const entry = instances.get(instanceKey);
791
- if (!entry) return;
792
- if (forceDispose) {
793
- if (!entry.instance.$blac.disposed) entry.instance.dispose();
794
- instances.delete(instanceKey);
795
- return;
796
- }
797
- let releasedRefId;
798
- if (refId !== void 0) {
799
- const count = entry.refs.get(refId) ?? 0;
800
- if (count <= 1) entry.refs.delete(refId);
801
- else entry.refs.set(refId, count - 1);
802
- releasedRefId = refId;
803
- } else {
804
- const firstKey = entry.refs.keys().next().value;
805
- if (firstKey !== void 0) {
806
- const count = entry.refs.get(firstKey) ?? 0;
807
- if (count <= 1) entry.refs.delete(firstKey);
808
- else entry.refs.set(firstKey, count - 1);
809
- releasedRefId = firstKey;
810
- }
811
- }
812
- if (releasedRefId) this.emit("refReleased", entry.instance, releasedRefId);
813
- const keepAlive = isKeepAliveClass(Type);
814
- if (entry.refs.size === 0 && !keepAlive) {
815
- const deps = entry.instance.$blac.dependencies;
816
- if (!entry.instance.$blac.disposed) entry.instance.dispose();
817
- instances.delete(instanceKey);
818
- for (const [DepType, depKey] of deps) {
819
- const depInstances = this.ensureInstancesMap(DepType);
820
- const depEntry = depInstances.get(depKey);
821
- if (depEntry && depEntry.refs.size === 0 && !isKeepAliveClass(DepType) && !depEntry.instance.$blac.disposed) {
822
- depEntry.instance.dispose();
823
- depInstances.delete(depKey);
824
- }
825
- }
826
- }
827
- }
828
- /**
829
- * Get all instances of a specific type.
830
- * @param Type - The StateContainer class constructor
831
- * @returns Array of all instances
832
- */
833
- getAll(Type) {
834
- const instances = this.ensureInstancesMap(Type);
835
- const result = [];
836
- for (const entry of instances.values()) result.push(entry.instance);
837
- return result;
838
- }
839
- /**
840
- * Safely iterate over all instances of a type.
841
- * Skips disposed instances and catches callback errors.
842
- * @param Type - The StateContainer class constructor
843
- * @param callback - Function to call for each instance
844
- */
845
- forEach(Type, callback) {
846
- const instances = this.ensureInstancesMap(Type);
847
- for (const entry of instances.values()) {
848
- const instance = entry.instance;
849
- if (!instance.$blac.disposed) try {
850
- callback(instance);
851
- } catch (error) {
852
- console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error);
853
- }
854
- }
855
- }
856
- /**
857
- * Clear all instances of a specific type (disposes them).
858
- * @param Type - The StateContainer class constructor
859
- */
860
- clear(Type) {
861
- const instances = this.ensureInstancesMap(Type);
862
- for (const entry of instances.values()) if (!entry.instance.$blac.disposed) entry.instance.dispose();
863
- instances.clear();
864
- }
865
- /**
866
- * Get reference count for an instance (number of active refs).
867
- *
868
- * @internal Internal key tier; public callers use the args-based `getRefCount`.
869
- * @param Type - The StateContainer class constructor
870
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
871
- * @returns Current ref count (0 if instance doesn't exist)
872
- */
873
- getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
874
- return this.ensureInstancesMap(Type).get(instanceKey)?.refs.size ?? 0;
875
- }
876
- /**
877
- * Get all active reference IDs for an instance.
878
- *
879
- * @internal Internal key tier; public callers use the args-based `getRefIds`.
880
- * @param Type - The StateContainer class constructor
881
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
882
- * @returns Array of ref ID strings (empty if instance doesn't exist)
883
- */
884
- getRefIds(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
885
- const instances = this.instancesByConstructor.get(Type);
886
- if (!instances) return [];
887
- const entry = instances.get(instanceKey);
888
- return entry ? Array.from(entry.refs.keys()) : [];
889
- }
890
- /**
891
- * Check if an instance exists.
892
- *
893
- * @internal Internal key tier; public callers use the args-based `hasInstance`.
894
- * @param Type - The StateContainer class constructor
895
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
896
- * @returns true if instance exists
897
- */
898
- hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
899
- return this.ensureInstancesMap(Type).has(instanceKey);
900
- }
901
- /**
902
- * Clear all instances from all types (for testing)
903
- *
904
- * Iterates all registered types and clears their instances.
905
- * Also clears type tracking to reset the registry state.
906
- */
907
- clearAll() {
908
- for (const Type of this.types) this.clear(Type);
909
- this.types.clear();
910
- this.registeredTypeNames.clear();
911
- }
912
- /**
913
- * Get registry statistics for debugging.
914
- * @returns Object with registeredTypes, totalInstances, and typeBreakdown
915
- */
916
- getStats() {
917
- const typeBreakdown = {};
918
- let totalInstances = 0;
919
- for (const Type of this.types) {
920
- const typeName = Type.name;
921
- const count = this.getInstancesMap(Type).size;
922
- typeBreakdown[typeName] = count;
923
- totalInstances += count;
924
- }
925
- return {
926
- registeredTypes: this.types.size,
927
- totalInstances,
928
- typeBreakdown
929
- };
930
- }
931
- /**
932
- * Get all registered types (for plugin system).
933
- * @returns Array of all registered StateContainer class constructors
934
- */
935
- getTypes() {
936
- return Array.from(this.types);
937
- }
938
- /**
939
- * Subscribe to lifecycle events
940
- * @param event - The lifecycle event to listen for
941
- * @param listener - The listener function to call when the event occurs
942
- * @returns Unsubscribe function
943
- */
944
- on(event, listener) {
945
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
946
- const instance = this.listeners.get(event);
947
- if (!instance) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
948
- instance.add(listener);
949
- if (event === "stateChanged") this._stateChangedListenerCount++;
950
- return () => {
951
- if (this.listeners.get(event)?.delete(listener) && event === "stateChanged") this._stateChangedListenerCount--;
952
- };
953
- }
954
- emit(event, ...args) {
955
- const listeners = this.listeners.get(event);
956
- if (!listeners || listeners.size === 0) return;
957
- for (const listener of listeners) try {
958
- listener(...args);
959
- } catch (error) {
960
- console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error);
961
- }
962
- }
963
- /**
964
- * Schedule a deferred stateChanged notification via microtask.
965
- * Skips entirely when no stateChanged listeners are registered.
966
- * @internal - Called by StateContainer.applyState
967
- */
968
- notifyStateChanged(container, previousState, newState) {
969
- if (this._stateChangedListenerCount === 0) return;
970
- if (!this._pendingStateChanges) {
971
- this._pendingStateChanges = [];
972
- queueMicrotask(() => this.flushStateChanged());
973
- }
974
- this._pendingStateChanges.push([
975
- container,
976
- previousState,
977
- newState
978
- ]);
979
- }
980
- flushStateChanged() {
981
- const pending = this._pendingStateChanges;
982
- this._pendingStateChanges = null;
983
- if (!pending) return;
984
- for (const [container, prev, next] of pending) this.emit("stateChanged", container, prev, next);
985
- }
986
- };
987
- /**
988
- * Global default registry instance
989
- */
990
- const globalRegistry = new StateContainerRegistry();
991
- /**
992
- * Global plugin manager (initialized lazily)
993
- */
994
- let _globalPluginManager = null;
995
- /**
996
- * Get the global plugin manager
997
- */
998
- function getPluginManager() {
999
- if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
1000
- return _globalPluginManager;
1001
- }
1002
- //#endregion
1003
- Object.defineProperty(exports, "APPLY_DEPS", {
1004
- enumerable: true,
1005
- get: function() {
1006
- return APPLY_DEPS;
1007
- }
1008
- });
1009
- Object.defineProperty(exports, "BLAC_STATIC_PROPS", {
1010
- enumerable: true,
1011
- get: function() {
1012
- return BLAC_STATIC_PROPS;
1013
- }
1014
- });
1015
- Object.defineProperty(exports, "INIT_CONFIG", {
1016
- enumerable: true,
1017
- get: function() {
1018
- return INIT_CONFIG;
1019
- }
1020
- });
1021
- Object.defineProperty(exports, "PluginManager", {
1022
- enumerable: true,
1023
- get: function() {
1024
- return PluginManager;
1025
- }
1026
- });
1027
- Object.defineProperty(exports, "REMOVE_DEPS_OWNER", {
1028
- enumerable: true,
1029
- get: function() {
1030
- return REMOVE_DEPS_OWNER;
1031
- }
1032
- });
1033
- Object.defineProperty(exports, "StateContainerRegistry", {
1034
- enumerable: true,
1035
- get: function() {
1036
- return StateContainerRegistry;
1037
- }
1038
- });
1039
- Object.defineProperty(exports, "configureBlac", {
1040
- enumerable: true,
1041
- get: function() {
1042
- return configureBlac;
1043
- }
1044
- });
1045
- Object.defineProperty(exports, "getBlacConfig", {
1046
- enumerable: true,
1047
- get: function() {
1048
- return getBlacConfig;
1049
- }
1050
- });
1051
- Object.defineProperty(exports, "getClassEquality", {
1052
- enumerable: true,
1053
- get: function() {
1054
- return getClassEquality;
1055
- }
1056
- });
1057
- Object.defineProperty(exports, "getPluginManager", {
1058
- enumerable: true,
1059
- get: function() {
1060
- return getPluginManager;
1061
- }
1062
- });
1063
- Object.defineProperty(exports, "globalRegistry", {
1064
- enumerable: true,
1065
- get: function() {
1066
- return globalRegistry;
1067
- }
1068
- });
1069
- Object.defineProperty(exports, "isExcludedFromDevTools", {
1070
- enumerable: true,
1071
- get: function() {
1072
- return isExcludedFromDevTools;
1073
- }
1074
- });
1075
- Object.defineProperty(exports, "isKeepAliveClass", {
1076
- enumerable: true,
1077
- get: function() {
1078
- return isKeepAliveClass;
1079
- }
1080
- });
1081
- Object.defineProperty(exports, "resetBlacConfig", {
1082
- enumerable: true,
1083
- get: function() {
1084
- return resetBlacConfig;
1085
- }
1086
- });
1087
- Object.defineProperty(exports, "shallowEqualState", {
1088
- enumerable: true,
1089
- get: function() {
1090
- return shallowEqualState;
1091
- }
1092
- });
1093
-
1094
- //# sourceMappingURL=StateContainerRegistry-lIwo-0m3.cjs.map