@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,1046 +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: 1e3,
23
- maxRefsPerInstance: 1e3,
24
- maxEmitsPerSecond: 100
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
- ];
210
- }
211
- /**
212
- * Subscribe to the container's channel with `ALL_PATHS` interest, so we
213
- * fire on every flush. Capture `prev` from the snapshot taken on the
214
- * previous flush (or at create-time for the first flush) and pass the
215
- * channel's `paths` argument straight through to plugins.
216
- *
217
- * Per-container bookkeeping is stored in a `WeakMap` keyed by the
218
- * container itself, so a disposed/GC'd container drops cleanly.
219
- */
220
- attachStateBridge(container) {
221
- if (this.containerBridges.has(container)) return;
222
- const bridge = {
223
- unsub: () => {},
224
- prevState: container.state
225
- };
226
- this.containerBridges.set(container, bridge);
227
- bridge.unsub = container.channel.subscribe(() => _dirtytalk_structural.ALL_PATHS, (paths) => this.dispatchStateChange(container, paths));
228
- }
229
- detachStateBridge(container) {
230
- const bridge = this.containerBridges.get(container);
231
- if (!bridge) return;
232
- bridge.unsub();
233
- this.containerBridges.delete(container);
234
- }
235
- /**
236
- * Channel-flush callback. Snapshots `next`, hands `(prev, next, paths)`
237
- * to every enabled plugin's `onStateChange`, then updates `prevState`
238
- * for the next flush.
239
- *
240
- * Note: `prev` is captured once and reused across plugins — every
241
- * plugin sees the same `prev`/`next`/`paths` regardless of dispatch
242
- * order, matching the "snapshot prev once per flush" invariant called
243
- * out in the C2 spec pitfalls.
244
- */
245
- dispatchStateChange(container, paths) {
246
- const bridge = this.containerBridges.get(container);
247
- if (!bridge) return;
248
- const prev = bridge.prevState;
249
- const next = container.state;
250
- bridge.prevState = next;
251
- for (const { plugin, config } of this.plugins.values()) {
252
- if (!config.enabled) continue;
253
- const hook = plugin.onStateChange;
254
- if (typeof hook !== "function") continue;
255
- try {
256
- hook.call(plugin, this.buildContext(container), prev, next, paths);
257
- } catch (error) {
258
- console.error(`[BlaC] Error in plugin "${plugin.name}" onStateChange:`, error);
259
- }
260
- }
261
- }
262
- /**
263
- * Notify all plugins of a lifecycle event.
264
- *
265
- * Builds a fresh `PluginContext` per dispatch (instance becomes
266
- * `ctx.container`), so plugins can reach the focal bloc through
267
- * `ctx.container` per Decision 6.
268
- */
269
- notifyPlugins(hookName, instance, ...extraArgs) {
270
- for (const { plugin, config } of this.plugins.values()) {
271
- if (!config.enabled) continue;
272
- const hook = plugin[hookName];
273
- if (typeof hook !== "function") continue;
274
- try {
275
- hook.call(plugin, this.buildContext(instance), ...extraArgs);
276
- } catch (error) {
277
- console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error);
278
- }
279
- }
280
- }
281
- /**
282
- * Build a `PluginContext` for a given focal container. The context is
283
- * cheap to build — its methods close over `this.registry` directly —
284
- * so we create one per dispatch rather than caching per container.
285
- * This sidesteps the lifetime question of "when do we evict a cached
286
- * context?" and keeps `paths`-vs-`container` lifetimes cleanly
287
- * separated per the C2 spec.
288
- */
289
- buildContext(container) {
290
- const registry = this.registry;
291
- return {
292
- container,
293
- getInstanceMetadata: (instance) => {
294
- return {
295
- id: instance.instanceId,
296
- className: instance.constructor.name,
297
- isDisposed: instance.isDisposed,
298
- name: instance.name,
299
- createdAt: instance.createdAt,
300
- state: instance.state,
301
- hydrationStatus: instance.hydrationStatus,
302
- isHydrated: instance.isHydrated,
303
- hydrationError: instance.hydrationError,
304
- changedWhileHydrating: instance.changedWhileHydrating,
305
- args: instance.args
306
- };
307
- },
308
- getState: (instance) => {
309
- return instance.state;
310
- },
311
- getHydrationStatus: (instance) => {
312
- return instance.hydrationStatus;
313
- },
314
- startHydration: (instance) => {
315
- instance.beginHydration();
316
- },
317
- applyHydratedState: (instance, state) => {
318
- return instance.applyHydratedState(state);
319
- },
320
- finishHydration: (instance) => {
321
- instance.finishHydration();
322
- },
323
- failHydration: (instance, error) => {
324
- instance.failHydration(error);
325
- },
326
- waitForHydration: (instance) => {
327
- return instance.waitForHydration();
328
- },
329
- queryInstances: (typeClass) => {
330
- return registry.getAll(typeClass);
331
- },
332
- getAllTypes: () => {
333
- return registry.getTypes();
334
- },
335
- getStats: () => {
336
- return registry.getStats();
337
- },
338
- getRefIds: (instanceId) => {
339
- for (const Type of registry.getTypes()) {
340
- const map = registry.getInstancesMap(Type);
341
- for (const [, entry] of map) if (entry.instance.instanceId === instanceId) return Array.from(entry.refs.keys());
342
- }
343
- return [];
344
- }
345
- };
346
- }
347
- /**
348
- * Check if plugin should be enabled based on environment
349
- */
350
- shouldEnablePlugin(config) {
351
- if (!config.enabled) return false;
352
- if (config.environment === "all") return true;
353
- return this.getCurrentEnvironment() === config.environment;
354
- }
355
- /**
356
- * Get current environment
357
- */
358
- getCurrentEnvironment() {
359
- if (typeof process !== "undefined") {
360
- if (process.env.NODE_ENV === "test") return "test";
361
- if (process.env.NODE_ENV === "production") return "production";
362
- return "development";
363
- }
364
- return "development";
365
- }
366
- };
367
- /**
368
- * Create a plugin manager instance
369
- * @param registry - The StateContainerRegistry to monitor for lifecycle events
370
- * @returns A new PluginManager instance
371
- */
372
- function createPluginManager(registry) {
373
- return new PluginManager(registry);
374
- }
375
- //#endregion
376
- //#region src/constants.ts
377
- /**
378
- * Default configuration constants for BlaC
379
- *
380
- * Centralized location for all magic numbers and default values.
381
- */
382
- /**
383
- * Default configuration constants for BlaC
384
- */
385
- const BLAC_DEFAULTS = {
386
- /**
387
- * Default instance key for shared instances
388
- */
389
- DEFAULT_INSTANCE_KEY: "default",
390
- /**
391
- * Maximum getter nesting depth (prevents infinite recursion)
392
- */
393
- MAX_GETTER_DEPTH: 10
394
- };
395
- /**
396
- * Static property names for StateContainer classes
397
- * Used for feature flags and configuration on bloc classes
398
- */
399
- const BLAC_STATIC_PROPS = {
400
- /**
401
- * Mark a bloc to never be auto-disposed (kept alive permanently)
402
- */
403
- KEEP_ALIVE: "keepAlive",
404
- /**
405
- * Exclude a bloc from DevTools reporting (prevents infinite loops)
406
- */
407
- EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools",
408
- /**
409
- * Per-class equality function used to short-circuit `emit`/`patch` when the
410
- * new state is structurally equal to the previous state. Falls back to the
411
- * global `configureBlac({ equality })` value when unset.
412
- */
413
- EQUALITY: "__equality",
414
- /**
415
- * Per-class key function: `static key = (args) => string`.
416
- * When set, the registry calls `Type.key(args)` to derive the instance key
417
- * instead of using a structural hash of `args`. Allows blocs to ignore
418
- * non-identity fields (e.g., `readonly` flags) while still keying by id.
419
- */
420
- KEY: "key"
421
- };
422
- /**
423
- * Standard error message prefix
424
- */
425
- const BLAC_ERROR_PREFIX = "[BlaC]";
426
- //#endregion
427
- //#region src/utils/static-props.ts
428
- /**
429
- * Utility functions for accessing static properties on StateContainer classes
430
- */
431
- /**
432
- * Get a static property from a class constructor
433
- * Type-safe helper that avoids (Type as any) casts
434
- *
435
- * @param Type - The class constructor
436
- * @param propName - The property name to access
437
- * @param defaultValue - Optional default value if property is undefined
438
- * @returns The property value or default
439
- */
440
- function getStaticProp(Type, propName, defaultValue) {
441
- return Type[propName] ?? defaultValue;
442
- }
443
- /**
444
- * Check if a class is marked as keepAlive.
445
- * KeepAlive classes are never auto-disposed when ref count reaches 0.
446
- * @param Type - The class constructor to check
447
- * @returns true if the class has `static keepAlive = true`
448
- */
449
- function isKeepAliveClass(Type) {
450
- return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
451
- }
452
- /**
453
- * Check if a class should be excluded from DevTools.
454
- * Used to prevent infinite loops when DevTools tracks itself.
455
- * @param Type - The class constructor to check
456
- * @returns true if the class has `static __excludeFromDevTools = true`
457
- */
458
- function isExcludedFromDevTools(Type) {
459
- return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
460
- }
461
- /**
462
- * Get the per-class equality function set via `@blac({ equality })`, if any.
463
- * @param Type - The class constructor to check
464
- * @returns the equality function or `undefined`
465
- */
466
- function getClassEquality(Type) {
467
- const fn = getStaticProp(Type, BLAC_STATIC_PROPS.EQUALITY);
468
- return typeof fn === "function" ? fn : void 0;
469
- }
470
- /**
471
- * Get the per-class key function set via `@blac({ key })` or `static key = …`, if any.
472
- * Used by the registry to derive a stable instance key from `args`.
473
- * @param Type - The class constructor to check
474
- * @returns the key function or `undefined`
475
- */
476
- function getClassKey(Type) {
477
- const fn = getStaticProp(Type, BLAC_STATIC_PROPS.KEY, void 0);
478
- return typeof fn === "function" ? fn : void 0;
479
- }
480
- //#endregion
481
- //#region src/utils/structural-key.ts
482
- /**
483
- * Deterministic, order-independent hash of serializable args.
484
- * Sorts object keys so {a,b} === {b,a}.
485
- * Throws (dev) if it encounters a function or non-plain object — those belong in `deps`.
486
- */
487
- const DEFAULT_STRUCTURAL_KEY = "default";
488
- /**
489
- * Produce a stable string key for serializable args.
490
- * - `undefined` / `void` args → `'default'` sentinel (no-args blocs stay on the default key).
491
- * - Object keys are sorted for order-independence.
492
- * - Arrays keep their insertion order.
493
- * - Functions throw — they must be passed via `deps`, not `args`.
494
- */
495
- function structuralKey(args) {
496
- if (args === void 0 || args === null) return DEFAULT_STRUCTURAL_KEY;
497
- return JSON.stringify(args, function(_k, v) {
498
- if (typeof v === "function") throw new Error("[blac] args must be serializable; put refs/callbacks in `deps`");
499
- if (v && typeof v === "object" && !Array.isArray(v)) return Object.keys(v).sort().reduce((o, k) => {
500
- o[k] = v[k];
501
- return o;
502
- }, {});
503
- return v;
504
- });
505
- }
506
- //#endregion
507
- //#region src/core/StateContainerRegistry.ts
508
- /**
509
- * Central registry for managing StateContainer instances.
510
- * Handles instance lifecycle, named ref tracking, and lifecycle event emission.
511
- *
512
- * @example
513
- * ```ts
514
- * const registry = new StateContainerRegistry();
515
- * const instance = registry.acquire(MyBloc); // ownership, must release
516
- * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
517
- * registry.on('stateChanged', (container, prev, next) => {
518
- * console.log('State changed:', prev, '->', next);
519
- * });
520
- * ```
521
- */
522
- var StateContainerRegistry = class {
523
- constructor() {
524
- this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
525
- this.types = /* @__PURE__ */ new Set();
526
- this.registeredTypeNames = /* @__PURE__ */ new Set();
527
- this.listeners = /* @__PURE__ */ new Map();
528
- this._stateChangedListenerCount = 0;
529
- this._pendingStateChanges = null;
530
- this._autoRefIdCounter = 0;
531
- }
532
- get hasStateChangedListeners() {
533
- return this._stateChangedListenerCount > 0;
534
- }
535
- /**
536
- * Register a type for lifecycle event tracking
537
- * @param constructor - The StateContainer class constructor
538
- */
539
- registerType(constructor) {
540
- this.types.add(constructor);
541
- }
542
- /**
543
- * Register a StateContainer class with configuration
544
- * @param constructor - The StateContainer class constructor
545
- * @throws Error if type is already registered
546
- */
547
- register(constructor) {
548
- const className = constructor.name;
549
- if (this.registeredTypeNames.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
550
- this.registeredTypeNames.add(className);
551
- this.registerType(constructor);
552
- }
553
- ensureInstancesMap(Type) {
554
- let instances = this.instancesByConstructor.get(Type);
555
- if (!instances) {
556
- instances = /* @__PURE__ */ new Map();
557
- this.instancesByConstructor.set(Type, instances);
558
- }
559
- return instances;
560
- }
561
- /**
562
- * Get the instances Map for a specific class (public API for stats/debugging)
563
- */
564
- getInstancesMap(Type) {
565
- return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
566
- }
567
- /**
568
- * Directly insert an instance entry into the registry without going through
569
- * acquire/release. Creates the internal WeakMap bucket for the constructor if
570
- * it does not exist yet. Replaces any existing entry for the same key.
571
- *
572
- * The provided instance is NOT configured or disposed here — callers are
573
- * responsible for any initConfig / dispose calls. Intended for testing
574
- * helpers that create stubs outside the normal acquisition path.
575
- *
576
- * @internal Used by testing helpers only.
577
- */
578
- insertInstance(Type, instanceKey, instance, refs = /* @__PURE__ */ new Map()) {
579
- const instances = this.ensureInstancesMap(Type);
580
- const existingEntry = instances.get(instanceKey);
581
- if (existingEntry && existingEntry.instance !== instance && !existingEntry.instance.isDisposed) existingEntry.instance.dispose();
582
- instances.set(instanceKey, {
583
- instance,
584
- refs
585
- });
586
- }
587
- /**
588
- * Resolve the storage key for an instance. This is the single source of truth
589
- * for keying — `acquire` and `release` MUST agree, otherwise a ref taken under
590
- * an args-derived key is never dropped (instance leaks).
591
- *
592
- * Resolution order (explicit beats derived):
593
- * explicit key > `static key(args)` > structural hash of args > default sentinel.
594
- *
595
- * @param Type - The StateContainer class constructor
596
- * @param instanceKey - Explicit key, or undefined to derive from args
597
- * @param args - Construction args used for structural/`static key` derivation
598
- */
599
- resolveKey(Type, instanceKey, args) {
600
- if (instanceKey !== void 0) return instanceKey;
601
- const keyFn = getClassKey(Type);
602
- if (keyFn) return keyFn(args);
603
- if (args !== void 0) return structuralKey(args);
604
- return DEFAULT_STRUCTURAL_KEY;
605
- }
606
- /**
607
- * Circuit breaker for runaway instance creation. Throws when a single
608
- * constructor would exceed `maxInstancesPerType` live instances — almost
609
- * always an unstable instance key (e.g. a new object/array passed as `args`
610
- * every render, or a missing `static key`) leaking an instance per render.
611
- */
612
- assertInstanceLimit(Type, currentCount) {
613
- const limit = getBlacConfig().maxInstancesPerType;
614
- 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 })\`.`);
615
- }
616
- /**
617
- * Circuit breaker for runaway reference growth. Throws when one instance
618
- * accumulates more than `maxRefsPerInstance` distinct live refs — almost
619
- * always consumer cleanup (e.g. `useBloc`'s unmount `release`) never firing.
620
- */
621
- assertRefLimit(Type, resolvedKey, refCount) {
622
- const limit = getBlacConfig().maxRefsPerInstance;
623
- 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 })\`.`);
624
- }
625
- /**
626
- * Acquire an instance with ref tracking (ownership semantics).
627
- * Creates a new instance if one doesn't exist, or returns existing and adds a ref.
628
- * You must call `release()` with the same refId when done.
629
- *
630
- * @internal Internal key tier. Public callers use the args-based `acquire`
631
- * wrapper; `useBloc`/`compat`/`watch` address a pre-resolved key here.
632
- * @param Type - The StateContainer class constructor
633
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
634
- * @param options - Acquisition options
635
- * @param options.canCreate - Whether to create new instance if not found (default: true)
636
- * @param options.countRef - Whether to add a reference (default: true)
637
- * @param options.refId - Named reference ID for debugging; auto-generated if omitted
638
- * @returns The state container instance
639
- */
640
- acquire(Type, instanceKey = void 0, options = {}) {
641
- const { canCreate = true, countRef = true } = options;
642
- const args = options.args;
643
- const resolvedKey = this.resolveKey(Type, instanceKey, args);
644
- const config = {
645
- instanceId: resolvedKey,
646
- args
647
- };
648
- const instances = this.ensureInstancesMap(Type);
649
- let entry = instances.get(resolvedKey);
650
- if (entry?.instance.isDisposed) {
651
- instances.delete(resolvedKey);
652
- entry = void 0;
653
- }
654
- if (entry) {
655
- if (process.env.NODE_ENV !== "production" && args !== void 0 && entry.args !== void 0) {
656
- const incomingKey = structuralKey(args);
657
- const storedKey = structuralKey(entry.args);
658
- 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.`);
659
- }
660
- if (countRef) {
661
- const refId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
662
- entry.refs.set(refId, (entry.refs.get(refId) ?? 0) + 1);
663
- this.assertRefLimit(Type, resolvedKey, entry.refs.size);
664
- this.emit("refAcquired", entry.instance, refId);
665
- }
666
- return entry.instance;
667
- }
668
- if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${resolvedKey}" not found and creation is disabled.`);
669
- this.assertInstanceLimit(Type, instances.size);
670
- const instance = new Type();
671
- instance.initConfig(config);
672
- const initialRefs = /* @__PURE__ */ new Map();
673
- let initialRefId;
674
- if (countRef) {
675
- initialRefId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
676
- initialRefs.set(initialRefId, 1);
677
- }
678
- instances.set(resolvedKey, {
679
- instance,
680
- refs: initialRefs,
681
- args
682
- });
683
- this.registerType(Type);
684
- if (initialRefId) this.emit("refAcquired", instance, initialRefId);
685
- return instance;
686
- }
687
- /**
688
- * Borrow an existing instance without adding a ref (borrowing semantics).
689
- * Tracks cross-bloc dependency for reactive updates.
690
- *
691
- * @internal Internal key tier; public callers use the args-based `borrow`.
692
- * @param Type - The StateContainer class constructor
693
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
694
- * @returns The state container instance
695
- * @throws Error if instance doesn't exist
696
- */
697
- borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
698
- return this.acquire(Type, instanceKey, {
699
- canCreate: false,
700
- countRef: false
701
- });
702
- }
703
- /**
704
- * Safely borrow an existing instance (borrowing semantics with error handling).
705
- * Returns discriminated union for type-safe conditional access.
706
- *
707
- * @internal Internal key tier; public callers use the args-based `borrowSafe`.
708
- * @param Type - The StateContainer class constructor
709
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
710
- * @returns Discriminated union with either the instance or an error
711
- */
712
- borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
713
- try {
714
- return {
715
- error: null,
716
- instance: this.borrow(Type, instanceKey)
717
- };
718
- } catch (error) {
719
- return {
720
- error,
721
- instance: null
722
- };
723
- }
724
- }
725
- /**
726
- * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
727
- * Gets existing instance OR creates it if it doesn't exist, without adding a ref.
728
- * Tracks cross-bloc dependency for reactive updates.
729
- *
730
- * Use this in bloc-to-bloc communication when you need to ensure an instance exists
731
- * but don't want to claim ownership (no ref added).
732
- *
733
- * @internal Internal key tier; public callers use the args-based `ensure`.
734
- * @param Type - The StateContainer class constructor
735
- * @param instanceKey - Pre-resolved instance key, or undefined to derive from `args`
736
- * (`static key(args)` / structural hash), matching `acquire`.
737
- * @param args - Construction args; used for keying when no explicit key is given
738
- * @returns The state container instance
739
- */
740
- ensure(Type, instanceKey = void 0, args) {
741
- return this.acquire(Type, instanceKey, {
742
- canCreate: true,
743
- countRef: false,
744
- args
745
- });
746
- }
747
- /**
748
- * Release a reference to an instance.
749
- * Removes the ref and disposes when refs is empty (unless keepAlive).
750
- * Releasing an already-removed refId is a no-op (idempotent).
751
- *
752
- * @internal Internal key tier; public callers use the args-based `release`.
753
- * @param Type - The StateContainer class constructor
754
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
755
- * @param forceDispose - Force immediate disposal regardless of refs
756
- * @param refId - The specific ref to remove; removes one arbitrary ref if omitted
757
- */
758
- release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false, refId) {
759
- const instances = this.ensureInstancesMap(Type);
760
- const entry = instances.get(instanceKey);
761
- if (!entry) return;
762
- if (forceDispose) {
763
- if (!entry.instance.isDisposed) entry.instance.dispose();
764
- instances.delete(instanceKey);
765
- return;
766
- }
767
- let releasedRefId;
768
- if (refId !== void 0) {
769
- const count = entry.refs.get(refId) ?? 0;
770
- if (count <= 1) entry.refs.delete(refId);
771
- else entry.refs.set(refId, count - 1);
772
- releasedRefId = refId;
773
- } else {
774
- const firstKey = entry.refs.keys().next().value;
775
- if (firstKey !== void 0) {
776
- const count = entry.refs.get(firstKey) ?? 0;
777
- if (count <= 1) entry.refs.delete(firstKey);
778
- else entry.refs.set(firstKey, count - 1);
779
- releasedRefId = firstKey;
780
- }
781
- }
782
- if (releasedRefId) this.emit("refReleased", entry.instance, releasedRefId);
783
- const keepAlive = isKeepAliveClass(Type);
784
- if (entry.refs.size === 0 && !keepAlive) {
785
- const deps = entry.instance.dependencies;
786
- if (!entry.instance.isDisposed) entry.instance.dispose();
787
- instances.delete(instanceKey);
788
- for (const [DepType, depKey] of deps) {
789
- const depInstances = this.ensureInstancesMap(DepType);
790
- const depEntry = depInstances.get(depKey);
791
- if (depEntry && depEntry.refs.size === 0 && !isKeepAliveClass(DepType) && !depEntry.instance.isDisposed) {
792
- depEntry.instance.dispose();
793
- depInstances.delete(depKey);
794
- }
795
- }
796
- }
797
- }
798
- /**
799
- * Get all instances of a specific type.
800
- * @param Type - The StateContainer class constructor
801
- * @returns Array of all instances
802
- */
803
- getAll(Type) {
804
- const instances = this.ensureInstancesMap(Type);
805
- const result = [];
806
- for (const entry of instances.values()) result.push(entry.instance);
807
- return result;
808
- }
809
- /**
810
- * Safely iterate over all instances of a type.
811
- * Skips disposed instances and catches callback errors.
812
- * @param Type - The StateContainer class constructor
813
- * @param callback - Function to call for each instance
814
- */
815
- forEach(Type, callback) {
816
- const instances = this.ensureInstancesMap(Type);
817
- for (const entry of instances.values()) {
818
- const instance = entry.instance;
819
- if (!instance.isDisposed) try {
820
- callback(instance);
821
- } catch (error) {
822
- console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error);
823
- }
824
- }
825
- }
826
- /**
827
- * Clear all instances of a specific type (disposes them).
828
- * @param Type - The StateContainer class constructor
829
- */
830
- clear(Type) {
831
- const instances = this.ensureInstancesMap(Type);
832
- for (const entry of instances.values()) if (!entry.instance.isDisposed) entry.instance.dispose();
833
- instances.clear();
834
- }
835
- /**
836
- * Get reference count for an instance (number of active refs).
837
- *
838
- * @internal Internal key tier; public callers use the args-based `getRefCount`.
839
- * @param Type - The StateContainer class constructor
840
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
841
- * @returns Current ref count (0 if instance doesn't exist)
842
- */
843
- getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
844
- return this.ensureInstancesMap(Type).get(instanceKey)?.refs.size ?? 0;
845
- }
846
- /**
847
- * Get all active reference IDs for an instance.
848
- *
849
- * @internal Internal key tier; public callers use the args-based `getRefIds`.
850
- * @param Type - The StateContainer class constructor
851
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
852
- * @returns Array of ref ID strings (empty if instance doesn't exist)
853
- */
854
- getRefIds(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
855
- const instances = this.instancesByConstructor.get(Type);
856
- if (!instances) return [];
857
- const entry = instances.get(instanceKey);
858
- return entry ? Array.from(entry.refs.keys()) : [];
859
- }
860
- /**
861
- * Check if an instance exists.
862
- *
863
- * @internal Internal key tier; public callers use the args-based `hasInstance`.
864
- * @param Type - The StateContainer class constructor
865
- * @param instanceKey - Pre-resolved instance key (defaults to 'default')
866
- * @returns true if instance exists
867
- */
868
- hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
869
- return this.ensureInstancesMap(Type).has(instanceKey);
870
- }
871
- /**
872
- * Clear all instances from all types (for testing)
873
- *
874
- * Iterates all registered types and clears their instances.
875
- * Also clears type tracking to reset the registry state.
876
- */
877
- clearAll() {
878
- for (const Type of this.types) this.clear(Type);
879
- this.types.clear();
880
- this.registeredTypeNames.clear();
881
- }
882
- /**
883
- * Get registry statistics for debugging.
884
- * @returns Object with registeredTypes, totalInstances, and typeBreakdown
885
- */
886
- getStats() {
887
- const typeBreakdown = {};
888
- let totalInstances = 0;
889
- for (const Type of this.types) {
890
- const typeName = Type.name;
891
- const count = this.getInstancesMap(Type).size;
892
- typeBreakdown[typeName] = count;
893
- totalInstances += count;
894
- }
895
- return {
896
- registeredTypes: this.types.size,
897
- totalInstances,
898
- typeBreakdown
899
- };
900
- }
901
- /**
902
- * Get all registered types (for plugin system).
903
- * @returns Array of all registered StateContainer class constructors
904
- */
905
- getTypes() {
906
- return Array.from(this.types);
907
- }
908
- /**
909
- * Subscribe to lifecycle events
910
- * @param event - The lifecycle event to listen for
911
- * @param listener - The listener function to call when the event occurs
912
- * @returns Unsubscribe function
913
- */
914
- on(event, listener) {
915
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
916
- const instance = this.listeners.get(event);
917
- if (!instance) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
918
- instance.add(listener);
919
- if (event === "stateChanged") this._stateChangedListenerCount++;
920
- return () => {
921
- if (this.listeners.get(event)?.delete(listener) && event === "stateChanged") this._stateChangedListenerCount--;
922
- };
923
- }
924
- emit(event, ...args) {
925
- const listeners = this.listeners.get(event);
926
- if (!listeners || listeners.size === 0) return;
927
- for (const listener of listeners) try {
928
- listener(...args);
929
- } catch (error) {
930
- console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error);
931
- }
932
- }
933
- /**
934
- * Schedule a deferred stateChanged notification via microtask.
935
- * Skips entirely when no stateChanged listeners are registered.
936
- * @internal - Called by StateContainer.applyState
937
- */
938
- notifyStateChanged(container, previousState, newState) {
939
- if (this._stateChangedListenerCount === 0) return;
940
- if (!this._pendingStateChanges) {
941
- this._pendingStateChanges = [];
942
- queueMicrotask(() => this.flushStateChanged());
943
- }
944
- this._pendingStateChanges.push([
945
- container,
946
- previousState,
947
- newState
948
- ]);
949
- }
950
- flushStateChanged() {
951
- const pending = this._pendingStateChanges;
952
- this._pendingStateChanges = null;
953
- if (!pending) return;
954
- for (const [container, prev, next] of pending) this.emit("stateChanged", container, prev, next);
955
- }
956
- };
957
- /**
958
- * Global default registry instance
959
- */
960
- const globalRegistry = new StateContainerRegistry();
961
- /**
962
- * Global plugin manager (initialized lazily)
963
- */
964
- let _globalPluginManager = null;
965
- /**
966
- * Get the global plugin manager
967
- */
968
- function getPluginManager() {
969
- if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
970
- return _globalPluginManager;
971
- }
972
- //#endregion
973
- Object.defineProperty(exports, "BLAC_STATIC_PROPS", {
974
- enumerable: true,
975
- get: function() {
976
- return BLAC_STATIC_PROPS;
977
- }
978
- });
979
- Object.defineProperty(exports, "PluginManager", {
980
- enumerable: true,
981
- get: function() {
982
- return PluginManager;
983
- }
984
- });
985
- Object.defineProperty(exports, "StateContainerRegistry", {
986
- enumerable: true,
987
- get: function() {
988
- return StateContainerRegistry;
989
- }
990
- });
991
- Object.defineProperty(exports, "configureBlac", {
992
- enumerable: true,
993
- get: function() {
994
- return configureBlac;
995
- }
996
- });
997
- Object.defineProperty(exports, "getBlacConfig", {
998
- enumerable: true,
999
- get: function() {
1000
- return getBlacConfig;
1001
- }
1002
- });
1003
- Object.defineProperty(exports, "getClassEquality", {
1004
- enumerable: true,
1005
- get: function() {
1006
- return getClassEquality;
1007
- }
1008
- });
1009
- Object.defineProperty(exports, "getPluginManager", {
1010
- enumerable: true,
1011
- get: function() {
1012
- return getPluginManager;
1013
- }
1014
- });
1015
- Object.defineProperty(exports, "globalRegistry", {
1016
- enumerable: true,
1017
- get: function() {
1018
- return globalRegistry;
1019
- }
1020
- });
1021
- Object.defineProperty(exports, "isExcludedFromDevTools", {
1022
- enumerable: true,
1023
- get: function() {
1024
- return isExcludedFromDevTools;
1025
- }
1026
- });
1027
- Object.defineProperty(exports, "isKeepAliveClass", {
1028
- enumerable: true,
1029
- get: function() {
1030
- return isKeepAliveClass;
1031
- }
1032
- });
1033
- Object.defineProperty(exports, "resetBlacConfig", {
1034
- enumerable: true,
1035
- get: function() {
1036
- return resetBlacConfig;
1037
- }
1038
- });
1039
- Object.defineProperty(exports, "shallowEqualState", {
1040
- enumerable: true,
1041
- get: function() {
1042
- return shallowEqualState;
1043
- }
1044
- });
1045
-
1046
- //# sourceMappingURL=StateContainerRegistry-FWKzPfS-.cjs.map