@blac/core 2.0.19 → 2.1.0

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 (129) hide show
  1. package/dist/StateContainerRegistry-8zNFMAf7.js +1067 -0
  2. package/dist/StateContainerRegistry-8zNFMAf7.js.map +1 -0
  3. package/dist/StateContainerRegistry-Bx2ly-ba.cjs +1162 -0
  4. package/dist/StateContainerRegistry-Bx2ly-ba.cjs.map +1 -0
  5. package/dist/StateContainerRegistry-C75QpeaO.cjs +1260 -0
  6. package/dist/StateContainerRegistry-C75QpeaO.cjs.map +1 -0
  7. package/dist/StateContainerRegistry-CS18y4au.cjs +1163 -0
  8. package/dist/StateContainerRegistry-CS18y4au.cjs.map +1 -0
  9. package/dist/StateContainerRegistry-D8nu7Z0T.js +1068 -0
  10. package/dist/StateContainerRegistry-D8nu7Z0T.js.map +1 -0
  11. package/dist/StateContainerRegistry-DL5Ai7wh.js +1153 -0
  12. package/dist/StateContainerRegistry-DL5Ai7wh.js.map +1 -0
  13. package/dist/StateContainerRegistry-DWOzx7Gd.js +1154 -0
  14. package/dist/StateContainerRegistry-DWOzx7Gd.js.map +1 -0
  15. package/dist/StateContainerRegistry-G81GcCRm.cjs +1261 -0
  16. package/dist/StateContainerRegistry-G81GcCRm.cjs.map +1 -0
  17. package/dist/acquire-B1LYXSGj.js +35 -0
  18. package/dist/acquire-B1LYXSGj.js.map +1 -0
  19. package/dist/acquire-BJ3xUEmh.cjs +46 -0
  20. package/dist/acquire-BJ3xUEmh.cjs.map +1 -0
  21. package/dist/acquire-B_p1fNEh.cjs +46 -0
  22. package/dist/acquire-B_p1fNEh.cjs.map +1 -0
  23. package/dist/acquire-BdsVZBSe.js +35 -0
  24. package/dist/acquire-BdsVZBSe.js.map +1 -0
  25. package/dist/acquire-CE0uq0Dx.cjs +46 -0
  26. package/dist/acquire-CE0uq0Dx.cjs.map +1 -0
  27. package/dist/acquire-CU0u8BMn.js +35 -0
  28. package/dist/acquire-CU0u8BMn.js.map +1 -0
  29. package/dist/acquire-CkgLJ8WL.cjs +46 -0
  30. package/dist/acquire-CkgLJ8WL.cjs.map +1 -0
  31. package/dist/acquire-DTvfYJ0y.js +35 -0
  32. package/dist/acquire-DTvfYJ0y.js.map +1 -0
  33. package/dist/config-C1T6Jw7n.cjs +32 -0
  34. package/dist/config-C1T6Jw7n.cjs.map +1 -0
  35. package/dist/config-D2A8ZYRM.js +16 -0
  36. package/dist/config-D2A8ZYRM.js.map +1 -0
  37. package/dist/config-D34BkraU.cjs +32 -0
  38. package/dist/config-D34BkraU.cjs.map +1 -0
  39. package/dist/config-DOO82lbZ.js +16 -0
  40. package/dist/config-DOO82lbZ.js.map +1 -0
  41. package/dist/config-DWUq7zEQ.cjs +32 -0
  42. package/dist/config-DWUq7zEQ.cjs.map +1 -0
  43. package/dist/config-DXI3kzmA.js +16 -0
  44. package/dist/config-DXI3kzmA.js.map +1 -0
  45. package/dist/config-ZVy_yFZ3.js +16 -0
  46. package/dist/config-ZVy_yFZ3.js.map +1 -0
  47. package/dist/config-cwaTn5oy.cjs +32 -0
  48. package/dist/config-cwaTn5oy.cjs.map +1 -0
  49. package/dist/config.d.cts +7 -3
  50. package/dist/config.d.ts +7 -3
  51. package/dist/constants.d.cts +2 -13
  52. package/dist/constants.d.ts +2 -13
  53. package/dist/core/StateContainer.d.ts +28 -1
  54. package/dist/core/StateContainerRegistry.d.ts +72 -2
  55. package/dist/core/symbols.d.ts +6 -0
  56. package/dist/debug.cjs +3 -3
  57. package/dist/debug.js +3 -3
  58. package/dist/decorators/blac.d.ts +2 -0
  59. package/dist/ensure-11-asM1e.js +677 -0
  60. package/dist/ensure-11-asM1e.js.map +1 -0
  61. package/dist/ensure-B2DYCbbI.cjs +578 -0
  62. package/dist/ensure-B2DYCbbI.cjs.map +1 -0
  63. package/dist/ensure-B59ri8oo.js +555 -0
  64. package/dist/ensure-B59ri8oo.js.map +1 -0
  65. package/dist/ensure-BEeY5Ab7.js +673 -0
  66. package/dist/ensure-BEeY5Ab7.js.map +1 -0
  67. package/dist/ensure-BKdq5xsY.cjs +578 -0
  68. package/dist/ensure-BKdq5xsY.cjs.map +1 -0
  69. package/dist/ensure-BSJHkUNX.js +555 -0
  70. package/dist/ensure-BSJHkUNX.js.map +1 -0
  71. package/dist/ensure-D3WWWwMo.cjs +714 -0
  72. package/dist/ensure-D3WWWwMo.cjs.map +1 -0
  73. package/dist/ensure-r1C_7K6_.cjs +718 -0
  74. package/dist/ensure-r1C_7K6_.cjs.map +1 -0
  75. package/dist/events.d.cts +42 -0
  76. package/dist/events.d.ts +42 -0
  77. package/dist/index.cjs +61 -6
  78. package/dist/index.cjs.map +1 -1
  79. package/dist/index.d.cts +7 -6
  80. package/dist/index.d.ts +7 -6
  81. package/dist/index.js +56 -8
  82. package/dist/index.js.map +1 -1
  83. package/dist/management-8x1OVMi6.js +38 -0
  84. package/dist/management-8x1OVMi6.js.map +1 -0
  85. package/dist/management-BZgsi29F.js +38 -0
  86. package/dist/management-BZgsi29F.js.map +1 -0
  87. package/dist/management-C-WGcwPD.js +38 -0
  88. package/dist/management-C-WGcwPD.js.map +1 -0
  89. package/dist/management-Dg2SxUb6.cjs +85 -0
  90. package/dist/management-Dg2SxUb6.cjs.map +1 -0
  91. package/dist/management-P_Vi_cvw.js +38 -0
  92. package/dist/management-P_Vi_cvw.js.map +1 -0
  93. package/dist/management-QWLpbXlW.cjs +85 -0
  94. package/dist/management-QWLpbXlW.cjs.map +1 -0
  95. package/dist/management-hkY13log.cjs +85 -0
  96. package/dist/management-hkY13log.cjs.map +1 -0
  97. package/dist/management-iE4x6IQY.cjs +85 -0
  98. package/dist/management-iE4x6IQY.cjs.map +1 -0
  99. package/dist/plugin/PluginManager.d.ts +11 -0
  100. package/dist/plugins.cjs +1 -1
  101. package/dist/plugins.js +1 -1
  102. package/dist/registry/index.d.ts +1 -1
  103. package/dist/registry/release.d.ts +17 -1
  104. package/dist/testing.cjs +4 -4
  105. package/dist/testing.js +4 -4
  106. package/dist/utils/idGenerator.d.ts +0 -36
  107. package/dist/utils/static-props.d.ts +5 -0
  108. package/dist/utils/structural-key.d.ts +11 -1
  109. package/dist/watch/index.d.ts +1 -0
  110. package/dist/watch/observe.d.ts +13 -0
  111. package/dist/watch-B0pUfh-v.cjs +119 -0
  112. package/dist/watch-B0pUfh-v.cjs.map +1 -0
  113. package/dist/watch-BDiwCPmb.js +108 -0
  114. package/dist/watch-BDiwCPmb.js.map +1 -0
  115. package/dist/watch-BW7gYiDf.js +108 -0
  116. package/dist/watch-BW7gYiDf.js.map +1 -0
  117. package/dist/watch-Bx0y-Kcc.js +108 -0
  118. package/dist/watch-Bx0y-Kcc.js.map +1 -0
  119. package/dist/watch-DttHqefn.js +108 -0
  120. package/dist/watch-DttHqefn.js.map +1 -0
  121. package/dist/watch-DxdIZjpt.cjs +119 -0
  122. package/dist/watch-DxdIZjpt.cjs.map +1 -0
  123. package/dist/watch-aoNLQAXp.cjs +119 -0
  124. package/dist/watch-aoNLQAXp.cjs.map +1 -0
  125. package/dist/watch-entry.cjs +1 -1
  126. package/dist/watch-entry.js +1 -1
  127. package/dist/watch-lEco5Tbl.cjs +119 -0
  128. package/dist/watch-lEco5Tbl.cjs.map +1 -0
  129. package/package.json +3 -3
@@ -0,0 +1,673 @@
1
+ import { a as INIT_CONFIG, c as getClassEquality, f as BLAC_ERROR_PREFIX, g as getBlacConfig, i as APPLY_DEPS, o as ON_DISPOSE, s as REMOVE_DEPS_OWNER } from "./StateContainerRegistry-DL5Ai7wh.js";
2
+ import { t as getRegistry } from "./config-ZVy_yFZ3.js";
3
+ import { ALL_PATHS, StructuralContainer } from "@dirtytalk/structural";
4
+ //#region src/utils/idGenerator.ts
5
+ /**
6
+ * Centralized ID Generation
7
+ *
8
+ * Provides consistent, collision-resistant ID generation for all BlaC subsystems.
9
+ * Uses timestamp + counter + random suffix for uniqueness.
10
+ */
11
+ /**
12
+ * Generate simple ID with timestamp and random (no counter tracking)
13
+ *
14
+ * Format: `${prefix}:${timestamp}_${random}`
15
+ *
16
+ * @param prefix - Prefix for the ID
17
+ * @returns Branded ID string
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const id = generateSimpleId('CounterBloc');
22
+ * // Returns: "CounterBloc:1698765432100_a3k9d7f2q"
23
+ * ```
24
+ */
25
+ function generateSimpleId(prefix, affix) {
26
+ if (affix) return `${prefix}:${affix}`;
27
+ return `${prefix}:${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
28
+ }
29
+ //#endregion
30
+ //#region src/events.ts
31
+ /**
32
+ * Subscriber storage, keyed by REGISTRY INSTANCE rather than a field on
33
+ * `StateContainerRegistry`. This gives registry-swap isolation (a test's
34
+ * `withTestRegistry`/`blacTestSetup` scope gets an independent subscriber
35
+ * set) for free, through machinery that already exists, with zero new
36
+ * public surface on `StateContainerRegistry`.
37
+ */
38
+ const busByRegistry = /* @__PURE__ */ new WeakMap();
39
+ function defineEvent(name) {
40
+ return { name };
41
+ }
42
+ /**
43
+ * @internal Bus scoped to an explicit registry — used by `StateContainer#on`
44
+ * so a container always listens on the bus of the registry it belongs to,
45
+ * not the ambient one. Not part of the public API.
46
+ */
47
+ function onEventFor(registry, token, handler) {
48
+ let bus = busByRegistry.get(registry);
49
+ if (!bus) {
50
+ bus = /* @__PURE__ */ new Map();
51
+ busByRegistry.set(registry, bus);
52
+ }
53
+ let handlers = bus.get(token);
54
+ if (!handlers) {
55
+ handlers = /* @__PURE__ */ new Set();
56
+ bus.set(token, handlers);
57
+ }
58
+ handlers.add(handler);
59
+ const tokenMap = bus;
60
+ const handlerSet = handlers;
61
+ let removed = false;
62
+ return () => {
63
+ if (removed) return;
64
+ removed = true;
65
+ handlerSet.delete(handler);
66
+ if (handlerSet.size === 0) tokenMap.delete(token);
67
+ };
68
+ }
69
+ /** Subscribe on the ambient registry (`getRegistry()`). */
70
+ function onEvent(token, handler) {
71
+ return onEventFor(getRegistry(), token, handler);
72
+ }
73
+ /**
74
+ * Dispatch `token` to every current subscriber on the ambient registry, in
75
+ * registration order.
76
+ *
77
+ * Cost is O(subscribers for this token) — a token with no subscribers (or no
78
+ * bus yet on this registry) returns immediately, never touching live
79
+ * instances.
80
+ *
81
+ * Dispatch iterates a SNAPSHOT of the handler `Set`, so it is safe for a
82
+ * handler to synchronously call `emitEvent`/`onEvent` re-entrantly: a nested
83
+ * `emitEvent` for the same token completes against its own snapshot, and a
84
+ * handler registered via `onEvent` during dispatch is NOT invoked for the
85
+ * in-flight emit (it only sees emits that start after it subscribed).
86
+ *
87
+ * The variadic tuple (`void extends P ? [] : [P]`) means a `void`-payload
88
+ * token needs no second argument, and a typed-payload token requires one.
89
+ */
90
+ function emitEvent(token, ...payload) {
91
+ const handlers = busByRegistry.get(getRegistry())?.get(token);
92
+ if (!handlers) return;
93
+ const value = payload[0];
94
+ for (const handler of Array.from(handlers)) try {
95
+ handler(value);
96
+ } catch (error) {
97
+ console.error(`${BLAC_ERROR_PREFIX} event handler error for '${token.name}':`, error);
98
+ }
99
+ }
100
+ //#endregion
101
+ //#region src/core/meta.ts
102
+ /**
103
+ * Non-enumerable brand carried on every `$blac` object produced by
104
+ * {@link createMeta}. Used by the clobber guard in `StateContainer` to detect
105
+ * a subclass class-field shadowing the base's own `$blac` property, and by the
106
+ * meta tests. Intentionally NOT re-exported from the package barrel.
107
+ */
108
+ const META_BRAND = Symbol("blac.meta");
109
+ const EMPTY_DEPS = /* @__PURE__ */ new Map();
110
+ /**
111
+ * Build the frozen, branded `$blac` meta object for a container.
112
+ *
113
+ * Called from a `StateContainer` field initializer (`$blac = createMeta(this)`).
114
+ * Only the back-reference is captured at this point; every getter/method reads
115
+ * the container's `_`-private fields lazily on access, so field-initializer
116
+ * ordering relative to those private fields is irrelevant.
117
+ *
118
+ * The getters close over `container` (the real instance), never over a
119
+ * `this`-receiver — this is what keeps `$blac` reads safe through
120
+ * `buildTrackedProxy`.
121
+ */
122
+ function createMeta(container) {
123
+ const c = container;
124
+ const meta = {
125
+ get name() {
126
+ return c._name;
127
+ },
128
+ get id() {
129
+ return c._instanceId;
130
+ },
131
+ get debug() {
132
+ return c._debug;
133
+ },
134
+ get createdAt() {
135
+ return c._createdAt;
136
+ },
137
+ get disposed() {
138
+ return c._disposed;
139
+ },
140
+ get dependencies() {
141
+ return c._dependencies ?? EMPTY_DEPS;
142
+ },
143
+ hydration: Object.freeze({
144
+ get status() {
145
+ return c._hydrationStatus;
146
+ },
147
+ get error() {
148
+ return c._hydrationError;
149
+ },
150
+ get isHydrated() {
151
+ return c._hydrationStatus === "hydrated";
152
+ },
153
+ get changedWhileHydrating() {
154
+ return c._changedWhileHydrating;
155
+ },
156
+ begin() {
157
+ c._beginHydration();
158
+ },
159
+ apply(next) {
160
+ return c._applyHydratedState(next);
161
+ },
162
+ finish() {
163
+ c._finishHydration();
164
+ },
165
+ fail(error) {
166
+ c._failHydration(error);
167
+ },
168
+ wait() {
169
+ return c._waitForHydration();
170
+ }
171
+ })
172
+ };
173
+ Object.defineProperty(meta, META_BRAND, {
174
+ value: true,
175
+ enumerable: false,
176
+ writable: false,
177
+ configurable: false
178
+ });
179
+ return Object.freeze(meta);
180
+ }
181
+ //#endregion
182
+ //#region src/core/StateContainer.ts
183
+ /**
184
+ * Brand symbol carried (non-enumerable) on every handle returned by
185
+ * `depend()`. Framework adapters (`@blac/react`) use this to detect handles
186
+ * inside a tracked-proxy and swap in a session-bound wrapper.
187
+ *
188
+ * @internal — exported for `@blac/react`; not part of the public API.
189
+ */
190
+ const DEP_BRAND = Symbol("blac.depHandle");
191
+ /**
192
+ * Shallow per-key `Object.is` comparison of two plain records. Keys are
193
+ * considered: a key present in one but not the other (regardless of value)
194
+ * makes the records unequal. Used to detect real deps changes.
195
+ */
196
+ function shallowEqualRecord(a, b) {
197
+ if (a === b) return true;
198
+ const aKeys = Object.keys(a);
199
+ if (aKeys.length !== Object.keys(b).length) return false;
200
+ for (const key of aKeys) {
201
+ if (!(key in b)) return false;
202
+ if (!Object.is(a[key], b[key])) return false;
203
+ }
204
+ return true;
205
+ }
206
+ /**
207
+ * BlaC's lifecycle/identity/dependency layer on top of `StructuralContainer`.
208
+ *
209
+ * StructuralContainer provides:
210
+ * - `state` getter
211
+ * - `emit` / `patch` / `update` (path-tracked, microtask-flushed)
212
+ * - `channel` (the underlying `DirtyChannel`)
213
+ * - `registerConsumerPaths` / `unregisterConsumer` (for fine-grained consumers)
214
+ * - per-class `PathInterner`
215
+ *
216
+ * StateContainer layers on:
217
+ * - identity / lifecycle / hydration (exposed via `$blac: BlacMeta`)
218
+ * - cross-bloc deps (`depend()`, `$blac.dependencies`)
219
+ * - per-consumer deps slices (`APPLY_DEPS` / `REMOVE_DEPS_OWNER` / `onDepsChanged`)
220
+ * - registry integration (config-driven equality, emit-rate circuit breaker)
221
+ *
222
+ * Subscribers can attach via:
223
+ * - `onSystemEvent('stateChanged' | 'dispose' | 'hydrationChanged', cb)` —
224
+ * coarse lifecycle events.
225
+ * - `this.channel.subscribe(interest, cb)` — path-scoped.
226
+ */
227
+ var StateContainer = class extends StructuralContainer {
228
+ static {
229
+ this.__excludeFromDevTools = false;
230
+ }
231
+ get deps() {
232
+ return this._deps;
233
+ }
234
+ /**
235
+ * @internal Apply one owner's (consumer's) deps slice. Shallow-merges the
236
+ * slice, reconciles keys the owner dropped since its last apply (other
237
+ * owners' keys untouched), dev-warns on cross-owner key collisions, then
238
+ * recomputes the merged view and fires onDepsChanged if it changed.
239
+ *
240
+ * Idempotent: re-applying an identical slice for the same owner is a no-op.
241
+ */
242
+ [APPLY_DEPS](ownerId, slice) {
243
+ if (this._disposed) return;
244
+ const owners = this._depsByOwner ??= /* @__PURE__ */ new Map();
245
+ const prevSlice = owners.get(ownerId);
246
+ if (prevSlice && shallowEqualRecord(prevSlice, slice)) return;
247
+ if (process.env.NODE_ENV !== "production") for (const key of Object.keys(slice)) for (const [otherOwner, otherSlice] of owners) {
248
+ if (otherOwner === ownerId) continue;
249
+ if (key in otherSlice && otherSlice[key] !== slice[key]) console.warn(`[${this._name}] multiple owners writing dep \`${String(key)}\`; last write wins`);
250
+ }
251
+ owners.set(ownerId, { ...slice });
252
+ this.reconcileDeps();
253
+ }
254
+ /**
255
+ * @internal Withdraw an owner's entire deps slice (consumer unmounted).
256
+ */
257
+ [REMOVE_DEPS_OWNER](ownerId) {
258
+ if (this._disposed) return;
259
+ if (!this._depsByOwner?.delete(ownerId)) return;
260
+ this.reconcileDeps();
261
+ }
262
+ /**
263
+ * @internal Subscribe to this instance's own disposal. Delegates to the
264
+ * per-instance `'dispose'` system event — used by `watch()` in place of
265
+ * filtering the global registry `'disposed'` event.
266
+ */
267
+ [ON_DISPOSE](handler) {
268
+ return this.onSystemEvent("dispose", handler);
269
+ }
270
+ reconcileDeps() {
271
+ const prev = this._deps;
272
+ const next = {};
273
+ if (this._depsByOwner) for (const slice of this._depsByOwner.values()) Object.assign(next, slice);
274
+ for (const key of Object.keys(prev)) if (!(key in next)) next[key] = void 0;
275
+ if (shallowEqualRecord(prev, next)) return;
276
+ this._deps = next;
277
+ this.onDepsChanged(next, prev);
278
+ this._registry.emit("depsChanged", this, prev, next);
279
+ }
280
+ onDepsChanged(_next, _prev) {}
281
+ get args() {
282
+ return this._config.args;
283
+ }
284
+ /**
285
+ * Declare a cross-bloc dependency. Returns a branded handle with two
286
+ * accessors — the dep instance is resolved against the registry on each call,
287
+ * which keeps the surface immune to dep-instance churn:
288
+ *
289
+ * - `handle.track(options?)` — reactive read. Returns `[state, instance]`.
290
+ * Inside a getter reached through the React proxy this subscribes the
291
+ * reading component to the dep's changes (base impl: live, no subscription).
292
+ * - `handle.untracked(options?)` — returns the live instance with no tracking,
293
+ * for imperative method calls and one-off reads.
294
+ *
295
+ * `defaultArgs` resolves the dep instance when an accessor is called without
296
+ * its own `args`; per-call `options.args` overrides it and can derive from
297
+ * current state. This does NOT auto-resubscribe outside the React proxy;
298
+ * non-React consumers needing updates should subscribe explicitly.
299
+ */
300
+ depend(Type, defaultArgs) {
301
+ if (!this._dependencies) this._dependencies = /* @__PURE__ */ new Map();
302
+ this._dependencies.set(Type, this._registry.resolveKey(Type, void 0, defaultArgs));
303
+ const resolve = (args) => {
304
+ const effectiveArgs = args ?? defaultArgs;
305
+ const key = this._registry.resolveKey(Type, void 0, effectiveArgs);
306
+ const edges = this._depEdges ??= /* @__PURE__ */ new Map();
307
+ let resolvedKeys = edges.get(Type);
308
+ if (resolvedKeys === void 0) {
309
+ resolvedKeys = /* @__PURE__ */ new Set();
310
+ edges.set(Type, resolvedKeys);
311
+ }
312
+ resolvedKeys.add(key);
313
+ return this._registry.acquire(Type, key, {
314
+ canCreate: true,
315
+ countRef: false,
316
+ args: effectiveArgs,
317
+ dependent: this
318
+ });
319
+ };
320
+ const handle = {
321
+ track: (options) => {
322
+ const instance = resolve(options?.args);
323
+ return [instance.state, instance];
324
+ },
325
+ untracked: (options) => resolve(options?.args)
326
+ };
327
+ Object.defineProperty(handle, DEP_BRAND, {
328
+ value: {
329
+ Type,
330
+ defaultArgs
331
+ },
332
+ enumerable: false,
333
+ writable: false,
334
+ configurable: false
335
+ });
336
+ return handle;
337
+ }
338
+ constructor(initialState, options) {
339
+ super(initialState, options);
340
+ this._depsByOwner = null;
341
+ this._deps = {};
342
+ this._disposed = false;
343
+ this._hydrationStatus = "idle";
344
+ this._changedWhileHydrating = false;
345
+ this._hydrationPromise = null;
346
+ this._hydrationPromiseSettled = false;
347
+ this._config = {};
348
+ this._initCalled = false;
349
+ this._emitWindowStart = 0;
350
+ this._emitCount = 0;
351
+ this._emitRateWarned = false;
352
+ this._systemEventHandlers = /* @__PURE__ */ new Map();
353
+ this._dependencies = null;
354
+ this._depEdges = null;
355
+ this._pendingChange = null;
356
+ this._bridgeUnsub = null;
357
+ this._registry = getRegistry();
358
+ this._equalityFn = getBlacConfig().equality;
359
+ this._name = this.constructor.name;
360
+ this._debug = false;
361
+ this._instanceId = generateSimpleId(this.constructor.name, "main");
362
+ this._createdAt = Date.now();
363
+ this.$blac = createMeta(this);
364
+ this.onSystemEvent = (event, handler) => {
365
+ let handlers = this._systemEventHandlers.get(event);
366
+ if (!handlers) {
367
+ handlers = /* @__PURE__ */ new Set();
368
+ this._systemEventHandlers.set(event, handlers);
369
+ }
370
+ const wasFirst = event === "stateChanged" && handlers.size === 0;
371
+ handlers.add(handler);
372
+ if (wasFirst) this._subscribeBridge();
373
+ let removed = false;
374
+ return () => {
375
+ if (removed) return;
376
+ removed = true;
377
+ handlers?.delete(handler);
378
+ if (event === "stateChanged" && (!handlers || handlers.size === 0)) {
379
+ this._bridgeUnsub?.();
380
+ this._bridgeUnsub = null;
381
+ this._pendingChange = null;
382
+ }
383
+ };
384
+ };
385
+ this.on = (token, handler) => {
386
+ if (this._disposed) return () => {};
387
+ const unsub = onEventFor(this._registry, token, handler);
388
+ this.onSystemEvent("dispose", unsub);
389
+ return unsub;
390
+ };
391
+ }
392
+ /**
393
+ * @internal Subscribe the channel bridge that turns flushes into
394
+ * 'stateChanged' system events. Interest is ALL_PATHS so we wake on every
395
+ * flush. Coalesced via `_pendingChange`: if no emit happened (e.g. a no-op
396
+ * patch), the bridge sees null and skips. Lazy: only subscribed while at
397
+ * least one 'stateChanged' handler exists.
398
+ */
399
+ _subscribeBridge() {
400
+ if (this._bridgeUnsub) return;
401
+ this._bridgeUnsub = this.channel.subscribe(() => ALL_PATHS, () => this._drainPending());
402
+ }
403
+ _hasStateChangedHandlers() {
404
+ const handlers = this._systemEventHandlers.get("stateChanged");
405
+ return !!handlers && handlers.size > 0;
406
+ }
407
+ /**
408
+ * Called once after construction with the args passed at acquire time, before the first
409
+ * state snapshot is read by any consumer. Override to seed args-derived state (via
410
+ * this.emit(...)) or kick off loads.
411
+ */
412
+ init(_args) {}
413
+ /**
414
+ * @internal Framework-only configuration entry point (registry + testing
415
+ * helpers). Writes the `_`-private identity fields directly, resolves
416
+ * per-class equality, emits the registry `created` event, and runs `init()`
417
+ * once. See {@link INIT_CONFIG}.
418
+ */
419
+ [INIT_CONFIG](config) {
420
+ this._config = { ...config };
421
+ this._name = this._config.name || this.constructor.name;
422
+ this._debug = this._config.debug ?? false;
423
+ this._instanceId = generateSimpleId(this.constructor.name, this._config.instanceId);
424
+ const perClass = getClassEquality(this.constructor);
425
+ this._equalityFn = perClass ?? getBlacConfig().equality;
426
+ this._registry.emit("created", this);
427
+ if (!this._initCalled) {
428
+ this._initCalled = true;
429
+ this.init(this._config.args);
430
+ }
431
+ if (process.env.NODE_ENV !== "production") {
432
+ if (!this.$blac?.[META_BRAND]) console.warn(`[blac] ${this.constructor.name} appears to declare its own \`$blac\` member, which shadows the reserved meta namespace. \`$blac\` is reserved by StateContainer — remove the subclass field.`);
433
+ }
434
+ }
435
+ dispose() {
436
+ if (this._disposed) return;
437
+ if (this._debug) console.log(`[${this._name}] Disposing...`);
438
+ if (this._depsByOwner) {
439
+ this._depsByOwner.clear();
440
+ this.reconcileDeps();
441
+ }
442
+ this._disposed = true;
443
+ if (this._hydrationStatus === "hydrating") this._failHydration(/* @__PURE__ */ new Error(`Hydration cancelled because ${this._name} was disposed`));
444
+ this.emitSystemEvent("dispose", void 0);
445
+ this._bridgeUnsub?.();
446
+ this._bridgeUnsub = null;
447
+ this._systemEventHandlers.clear();
448
+ this._pendingChange = null;
449
+ this._registry.emit("disposed", this);
450
+ if (this._debug) console.log(`[${this._name}] Disposed successfully`);
451
+ super.dispose();
452
+ }
453
+ emit(next) {
454
+ this.applyState(next, "default");
455
+ }
456
+ /**
457
+ * Override of `StructuralContainer.patch` that routes through the
458
+ * StateContainer concerns: disposed guard, dev-only emit-rate check,
459
+ * `_changedWhileHydrating` flag, pending-change capture (so `stateChanged`
460
+ * system events see the merged prev/next), and the registry-level
461
+ * `stateChanged` notification. We still call
462
+ * `super.patch` so path-marking semantics (the whole point of patch) are
463
+ * preserved.
464
+ */
465
+ patch(partial) {
466
+ if (this._disposed) throw new Error(`Cannot emit state from disposed container ${this._name}`);
467
+ const prev = this.state;
468
+ let hasKeys = false;
469
+ let allEqual = true;
470
+ for (const key in partial) {
471
+ hasKeys = true;
472
+ if (!Object.is(prev[key], partial[key])) {
473
+ allEqual = false;
474
+ break;
475
+ }
476
+ }
477
+ if (!hasKeys) return;
478
+ if (allEqual) return;
479
+ if (process.env.NODE_ENV !== "production") this._checkEmitRate();
480
+ super.patch(partial);
481
+ const next = this.state;
482
+ if (Object.is(prev, next)) return;
483
+ if (this._hydrationStatus === "hydrating") this._changedWhileHydrating = true;
484
+ if (this._hasStateChangedHandlers()) if (this._pendingChange) this._pendingChange.next = next;
485
+ else this._pendingChange = {
486
+ prev,
487
+ next
488
+ };
489
+ if (this._registry.hasStateChangedListeners) this._registry.notifyStateChanged(this, prev, next);
490
+ }
491
+ applyState(next, source) {
492
+ if (this._disposed) throw new Error(`Cannot emit state from disposed container ${this._name}`);
493
+ const prev = this.state;
494
+ if (prev === next) return;
495
+ if (this._equalityFn(prev, next)) return;
496
+ if (process.env.NODE_ENV !== "production") this._checkEmitRate();
497
+ if (this._hydrationStatus === "hydrating" && source !== "hydration") this._changedWhileHydrating = true;
498
+ if (this._hasStateChangedHandlers()) if (this._pendingChange) this._pendingChange.next = next;
499
+ else this._pendingChange = {
500
+ prev,
501
+ next
502
+ };
503
+ super.emit(next);
504
+ if (this._registry.hasStateChangedListeners) this._registry.notifyStateChanged(this, prev, next);
505
+ }
506
+ /**
507
+ * Called by the channel-bridge subscriber on each flush. Drains the
508
+ * pending change (if any) into the 'stateChanged' system event.
509
+ * No pending change == flush from a no-op patch == skip.
510
+ */
511
+ _drainPending() {
512
+ const pending = this._pendingChange;
513
+ if (!pending) return;
514
+ this._pendingChange = null;
515
+ const handlers = this._systemEventHandlers.get("stateChanged");
516
+ if (handlers && handlers.size > 0) {
517
+ const payload = {
518
+ state: pending.next,
519
+ previousState: pending.prev
520
+ };
521
+ let count = 0;
522
+ const size = handlers.size;
523
+ for (const handler of handlers) {
524
+ if (++count > size) break;
525
+ try {
526
+ handler(payload);
527
+ } catch (error) {
528
+ console.error(`[${this._name}] Error in system event handler:`, error);
529
+ }
530
+ }
531
+ }
532
+ }
533
+ _beginHydration() {
534
+ if (this._disposed) throw new Error(`Cannot begin hydration for disposed container ${this._name}`);
535
+ this._changedWhileHydrating = false;
536
+ this._hydrationError = void 0;
537
+ this._hydrationPromise = null;
538
+ this._resolveHydrationPromise = void 0;
539
+ this._rejectHydrationPromise = void 0;
540
+ this._hydrationPromiseSettled = false;
541
+ this.ensureHydrationPromise();
542
+ this.setHydrationStatus("hydrating");
543
+ }
544
+ _applyHydratedState(next) {
545
+ if (this._disposed) return false;
546
+ if (this._hydrationStatus !== "hydrating" || this._changedWhileHydrating) return false;
547
+ this.applyState(next, "hydration");
548
+ return true;
549
+ }
550
+ _finishHydration() {
551
+ if (this._hydrationStatus !== "hydrating") {
552
+ if (this._hydrationStatus === "hydrated") return;
553
+ if (this._hydrationStatus === "error") this.ensureHydrationPromise();
554
+ }
555
+ this.setHydrationStatus("hydrated");
556
+ this.resolveHydration();
557
+ }
558
+ _failHydration(error) {
559
+ const err = error instanceof Error ? error : /* @__PURE__ */ new Error(`Hydration failed: ${String(error)}`);
560
+ this._hydrationError = err;
561
+ this.setHydrationStatus("error", err);
562
+ this.rejectHydration(err);
563
+ }
564
+ _waitForHydration() {
565
+ if (this._hydrationStatus === "idle" || this._hydrationStatus === "hydrated") return Promise.resolve();
566
+ if (this._hydrationStatus === "error") return Promise.reject(this._hydrationError ?? /* @__PURE__ */ new Error(`Hydration failed for container ${this._name}`));
567
+ return this.ensureHydrationPromise();
568
+ }
569
+ setHydrationStatus(status, error) {
570
+ const previousStatus = this._hydrationStatus;
571
+ this._hydrationStatus = status;
572
+ this._hydrationError = error;
573
+ this.emitSystemEvent("hydrationChanged", {
574
+ status,
575
+ previousStatus,
576
+ error,
577
+ changedWhileHydrating: this._changedWhileHydrating
578
+ });
579
+ this._registry.emit("hydrationChanged", this, status, previousStatus);
580
+ }
581
+ ensureHydrationPromise() {
582
+ if (!this._hydrationPromise || this._hydrationPromiseSettled) {
583
+ this._hydrationPromiseSettled = false;
584
+ this._hydrationPromise = new Promise((resolve, reject) => {
585
+ this._resolveHydrationPromise = () => {
586
+ if (this._hydrationPromiseSettled) return;
587
+ this._hydrationPromiseSettled = true;
588
+ resolve();
589
+ };
590
+ this._rejectHydrationPromise = (error) => {
591
+ if (this._hydrationPromiseSettled) return;
592
+ this._hydrationPromiseSettled = true;
593
+ reject(error);
594
+ };
595
+ });
596
+ this._hydrationPromise.catch(() => {});
597
+ }
598
+ return this._hydrationPromise;
599
+ }
600
+ resolveHydration() {
601
+ this._resolveHydrationPromise?.();
602
+ }
603
+ rejectHydration(error) {
604
+ this.ensureHydrationPromise();
605
+ this._rejectHydrationPromise?.(error);
606
+ }
607
+ emitSystemEvent(event, payload) {
608
+ const handlers = this._systemEventHandlers.get(event);
609
+ if (!handlers) return;
610
+ const size = handlers.size;
611
+ let count = 0;
612
+ for (const handler of handlers) {
613
+ if (++count > size) break;
614
+ try {
615
+ handler(payload);
616
+ } catch (error) {
617
+ console.error(`[${this._name}] Error in system event handler:`, error);
618
+ }
619
+ }
620
+ }
621
+ /**
622
+ * Dev-only soft circuit breaker. Counts real state changes in a rolling 1s
623
+ * window and warns once if the rate exceeds `maxEmitsPerSecond` — the
624
+ * signature of a runaway loop (RAF/animation or emit-on-every-commit) pushing
625
+ * high-frequency data through state, which freezes subscribers/plugins.
626
+ */
627
+ _checkEmitRate() {
628
+ const limit = getBlacConfig().maxEmitsPerSecond;
629
+ if (!(limit > 0) || !Number.isFinite(limit) || this._emitRateWarned) return;
630
+ const now = Date.now();
631
+ if (now - this._emitWindowStart >= 1e3) {
632
+ this._emitWindowStart = now;
633
+ this._emitCount = 1;
634
+ return;
635
+ }
636
+ this._emitCount++;
637
+ if (this._emitCount > limit) {
638
+ this._emitRateWarned = true;
639
+ console.warn(`[${this._name}] emitted more than ${limit} state changes in under a second. This is usually a runaway loop pushing high-frequency data through state (e.g. \`emit\`/\`patch\` inside a requestAnimationFrame loop, or an effect that emits on every render). It can freeze the app by saturating subscribers and plugins (logging/devtools). Keep high-frequency work imperative and emit only coarse/throttled state, or raise \`configureBlac({ maxEmitsPerSecond })\`. (This warning fires once.)`);
640
+ }
641
+ }
642
+ };
643
+ //#endregion
644
+ //#region src/core/Cubit.ts
645
+ /**
646
+ * `Cubit<S>` is a `StateContainer<S>` with `emit` / `patch` exposed as
647
+ * public mutation surface. Today it adds nothing structurally beyond
648
+ * `StateContainer` — both are inherited from the underlying
649
+ * `StructuralContainer<S>`. Kept as a real class (not a type alias) because
650
+ * downstream code does `instance instanceof Cubit` checks.
651
+ *
652
+ * The class body is intentionally empty: a no-op `emit` override would
653
+ * still go through `applyState`, and `patch` is inherited from
654
+ * `StructuralContainer` (path-diffed, microtask-flushed). A caller that
655
+ * wants "skip if no real change" patch semantics can wrap `patch`
656
+ * themselves or call `emit` after a manual equality check.
657
+ */
658
+ var Cubit = class extends StateContainer {};
659
+ //#endregion
660
+ //#region src/registry/ensure.ts
661
+ /**
662
+ * Ensure an instance exists without taking ownership (no ref added). Instance
663
+ * identity is derived purely from `args`, matching `acquire`.
664
+ */
665
+ function ensure(BlocClass, opts) {
666
+ const registry = getRegistry();
667
+ const key = registry.resolveKey(BlocClass, void 0, opts?.args);
668
+ return registry.ensure(BlocClass, key, opts?.args);
669
+ }
670
+ //#endregion
671
+ export { defineEvent as a, StateContainer as i, Cubit as n, emitEvent as o, DEP_BRAND as r, onEvent as s, ensure as t };
672
+
673
+ //# sourceMappingURL=ensure-BEeY5Ab7.js.map