@blac/core 2.0.21 → 2.0.22

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 (37) hide show
  1. package/dist/StateContainerRegistry-141uHhtF.cjs.map +1 -1
  2. package/dist/StateContainerRegistry-BH7aOMWV.js +892 -0
  3. package/dist/StateContainerRegistry-BH7aOMWV.js.map +1 -0
  4. package/dist/StateContainerRegistry-BsH_s0pJ.js +895 -0
  5. package/dist/StateContainerRegistry-BsH_s0pJ.js.map +1 -0
  6. package/dist/StateContainerRegistry-CBLeHObO.cjs +1002 -0
  7. package/dist/StateContainerRegistry-CBLeHObO.cjs.map +1 -0
  8. package/dist/StateContainerRegistry-MkT0W4C2.cjs +999 -0
  9. package/dist/StateContainerRegistry-MkT0W4C2.cjs.map +1 -0
  10. package/dist/StateContainerRegistry-vWgsD-RP.js.map +1 -1
  11. package/dist/constants.d.cts +0 -7
  12. package/dist/constants.d.ts +0 -7
  13. package/dist/core/StateContainer.d.ts +16 -7
  14. package/dist/core/StateContainerRegistry.d.ts +9 -4
  15. package/dist/core/meta.d.ts +34 -41
  16. package/dist/ensure-BjhbDW8Z.cjs +761 -0
  17. package/dist/ensure-BjhbDW8Z.cjs.map +1 -0
  18. package/dist/ensure-BnVyd6s4.js +730 -0
  19. package/dist/ensure-BnVyd6s4.js.map +1 -0
  20. package/dist/ensure-CneMkpbI.js +731 -0
  21. package/dist/ensure-CneMkpbI.js.map +1 -0
  22. package/dist/ensure-D15vGnk5.cjs +783 -0
  23. package/dist/ensure-D15vGnk5.cjs.map +1 -0
  24. package/dist/ensure-D3w6YGp9.cjs +784 -0
  25. package/dist/ensure-D3w6YGp9.cjs.map +1 -0
  26. package/dist/ensure-dsqWhIuO.js +708 -0
  27. package/dist/ensure-dsqWhIuO.js.map +1 -0
  28. package/dist/index.cjs +2 -2
  29. package/dist/index.js +2 -2
  30. package/dist/plugin/PluginManager.d.ts +9 -4
  31. package/dist/plugins.cjs +7 -4
  32. package/dist/plugins.cjs.map +1 -1
  33. package/dist/plugins.js +7 -4
  34. package/dist/plugins.js.map +1 -1
  35. package/dist/testing.cjs +2 -2
  36. package/dist/testing.js +2 -2
  37. package/package.json +2 -3
@@ -0,0 +1,761 @@
1
+ const require_StateContainerRegistry = require("./StateContainerRegistry-141uHhtF.cjs");
2
+ let _dirtytalk_structural = require("@dirtytalk/structural");
3
+ //#region src/utils/idGenerator.ts
4
+ /**
5
+ * Centralized ID Generation
6
+ *
7
+ * Provides consistent, collision-resistant ID generation for all BlaC subsystems.
8
+ * Uses timestamp + counter + random suffix for uniqueness.
9
+ */
10
+ /**
11
+ * Generate simple ID with timestamp and random (no counter tracking)
12
+ *
13
+ * Format: `${prefix}:${timestamp}_${random}`
14
+ *
15
+ * @param prefix - Prefix for the ID
16
+ * @returns Branded ID string
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const id = generateSimpleId('CounterBloc');
21
+ * // Returns: "CounterBloc:1698765432100_a3k9d7f2q"
22
+ * ```
23
+ */
24
+ function generateSimpleId(prefix, affix) {
25
+ if (affix) return `${prefix}:${affix}`;
26
+ return `${prefix}:${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
27
+ }
28
+ //#endregion
29
+ //#region src/registry/config.ts
30
+ let _registry = require_StateContainerRegistry.globalRegistry;
31
+ /**
32
+ * @public
33
+ */
34
+ function getRegistry() {
35
+ return _registry;
36
+ }
37
+ /**
38
+ * @public
39
+ */
40
+ function setRegistry(registry) {
41
+ _registry = registry;
42
+ }
43
+ /**
44
+ * @public
45
+ */
46
+ function getStats() {
47
+ return _registry.getStats();
48
+ }
49
+ //#endregion
50
+ //#region src/core/meta.ts
51
+ /**
52
+ * `$blac` meta namespace for `StateContainer`.
53
+ *
54
+ * Getters/methods here close over the *real* container instance captured at
55
+ * `createMeta` time rather than reading a `this`-receiver. `buildTrackedProxy`
56
+ * no longer uses a `this`-Proxy (getters run with `this` = the real instance),
57
+ * so ES `#private` is safe here now; the closure style is kept because it also
58
+ * keeps this own, frozen property independent of the proxy entirely.
59
+ */
60
+ /**
61
+ * Non-enumerable brand carried on every `$blac` object produced by
62
+ * {@link createMeta}. Used by the clobber guard in `StateContainer` to detect
63
+ * a subclass class-field shadowing the base's own `$blac` property, and by the
64
+ * meta tests. Intentionally NOT re-exported from the package barrel.
65
+ */
66
+ const META_BRAND = Symbol("blac.meta");
67
+ const EMPTY_DEPS = /* @__PURE__ */ new Map();
68
+ /**
69
+ * Build the frozen, branded `$blac` meta object for a container.
70
+ *
71
+ * Called from a `StateContainer` field initializer (`$blac = createMeta(this)`).
72
+ * Only the back-reference is captured at this point; every getter/method reads
73
+ * the container's `_`-private fields lazily on access, so field-initializer
74
+ * ordering relative to those private fields is irrelevant.
75
+ *
76
+ * The getters close over `container` (the real instance), never over a
77
+ * `this`-receiver — this is what keeps `$blac` reads safe through
78
+ * `buildTrackedProxy`.
79
+ */
80
+ function createMeta(container) {
81
+ const c = container;
82
+ const meta = {
83
+ get name() {
84
+ return c._name;
85
+ },
86
+ get id() {
87
+ return c._instanceId ??= generateSimpleId(require_StateContainerRegistry.getBlacName(c.constructor), "main");
88
+ },
89
+ get debug() {
90
+ return c._debug;
91
+ },
92
+ get createdAt() {
93
+ return c._createdAt;
94
+ },
95
+ get disposed() {
96
+ return c._disposed;
97
+ },
98
+ get dependencies() {
99
+ return c._dependencies ?? EMPTY_DEPS;
100
+ },
101
+ hydration: Object.freeze({
102
+ get status() {
103
+ return c._hydrationStatus;
104
+ },
105
+ get error() {
106
+ return c._hydrationError;
107
+ },
108
+ get isHydrated() {
109
+ return c._hydrationStatus === "hydrated";
110
+ },
111
+ get changedWhileHydrating() {
112
+ return c._changedWhileHydrating;
113
+ },
114
+ begin() {
115
+ c._beginHydration();
116
+ },
117
+ apply(next) {
118
+ return c._applyHydratedState(next);
119
+ },
120
+ finish() {
121
+ c._finishHydration();
122
+ },
123
+ fail(error) {
124
+ c._failHydration(error);
125
+ },
126
+ wait() {
127
+ return c._waitForHydration();
128
+ }
129
+ })
130
+ };
131
+ Object.defineProperty(meta, META_BRAND, {
132
+ value: true,
133
+ enumerable: false,
134
+ writable: false,
135
+ configurable: false
136
+ });
137
+ return Object.freeze(meta);
138
+ }
139
+ //#endregion
140
+ //#region src/core/StateContainer.ts
141
+ /**
142
+ * Brand symbol carried (non-enumerable) on every handle returned by
143
+ * `depend()`. Framework adapters (`@blac/react`) use this to detect handles
144
+ * inside a tracked-proxy and swap in a session-bound wrapper.
145
+ *
146
+ * @internal — exported for `@blac/react`; not part of the public API.
147
+ */
148
+ const DEP_BRAND = Symbol("blac.depHandle");
149
+ /**
150
+ * Shallow per-key `Object.is` comparison of two plain records. Keys are
151
+ * considered: a key present in one but not the other (regardless of value)
152
+ * makes the records unequal. Used to detect real deps changes.
153
+ */
154
+ function shallowEqualRecord(a, b) {
155
+ if (a === b) return true;
156
+ const aKeys = Object.keys(a);
157
+ if (aKeys.length !== Object.keys(b).length) return false;
158
+ for (const key of aKeys) {
159
+ if (!(key in b)) return false;
160
+ if (!Object.is(a[key], b[key])) return false;
161
+ }
162
+ return true;
163
+ }
164
+ /**
165
+ * BlaC's lifecycle/identity/dependency layer on top of `StructuralContainer`.
166
+ *
167
+ * StructuralContainer provides:
168
+ * - `state` getter
169
+ * - `emit` / `patch` / `update` (path-tracked, microtask-flushed)
170
+ * - `channel` (the underlying `DirtyChannel`)
171
+ * - `registerConsumerPaths` / `unregisterConsumer` (for fine-grained consumers)
172
+ * - per-class `PathInterner`
173
+ *
174
+ * StateContainer layers on:
175
+ * - identity / lifecycle / hydration (exposed via `$blac: BlacMeta`)
176
+ * - cross-bloc deps (`depend()`, `$blac.dependencies`)
177
+ * - per-consumer deps slices (`APPLY_DEPS` / `REMOVE_DEPS_OWNER` / `onDepsChanged`)
178
+ * - registry integration (config-driven equality, emit-rate circuit breaker)
179
+ *
180
+ * Subscribers can attach via:
181
+ * - `onSystemEvent('stateChanged' | 'dispose' | 'hydrationChanged', cb)` —
182
+ * coarse lifecycle events.
183
+ * - `this.channel.subscribe(interest, cb)` — path-scoped.
184
+ */
185
+ var StateContainer = class extends _dirtytalk_structural.StructuralContainer {
186
+ static {
187
+ this.__excludeFromDevTools = false;
188
+ }
189
+ get deps() {
190
+ return this._deps;
191
+ }
192
+ /**
193
+ * @internal Apply one owner's (consumer's) deps slice. Shallow-merges the
194
+ * slice, reconciles keys the owner dropped since its last apply (other
195
+ * owners' keys untouched), dev-warns on cross-owner key collisions, then
196
+ * recomputes the merged view and fires onDepsChanged if it changed.
197
+ *
198
+ * Idempotent: re-applying an identical slice for the same owner is a no-op.
199
+ */
200
+ [require_StateContainerRegistry.APPLY_DEPS](ownerId, slice) {
201
+ if (this._disposed) return;
202
+ const owners = this._depsByOwner ??= /* @__PURE__ */ new Map();
203
+ const prevSlice = owners.get(ownerId);
204
+ if (prevSlice && shallowEqualRecord(prevSlice, slice)) return;
205
+ if (require_StateContainerRegistry.IS_DEV) for (const key of Object.keys(slice)) for (const [otherOwner, otherSlice] of owners) {
206
+ if (otherOwner === ownerId) continue;
207
+ if (key in otherSlice && otherSlice[key] !== slice[key]) console.warn(`[${this._name}] multiple owners writing dep \`${String(key)}\`; last write wins`);
208
+ }
209
+ owners.set(ownerId, { ...slice });
210
+ this.reconcileDeps();
211
+ }
212
+ /**
213
+ * @internal Withdraw an owner's entire deps slice (consumer unmounted).
214
+ */
215
+ [require_StateContainerRegistry.REMOVE_DEPS_OWNER](ownerId) {
216
+ if (this._disposed) return;
217
+ if (!this._depsByOwner?.delete(ownerId)) return;
218
+ this.reconcileDeps();
219
+ }
220
+ /**
221
+ * @internal Subscribe to this instance's own disposal. Delegates to the
222
+ * per-instance `'dispose'` system event — used by `watch()` in place of
223
+ * filtering the global registry `'disposed'` event.
224
+ */
225
+ [require_StateContainerRegistry.ON_DISPOSE](handler) {
226
+ return this.onSystemEvent("dispose", handler);
227
+ }
228
+ /**
229
+ * @internal Drive the 0↔1 ownership transition. Idempotent: repeated calls
230
+ * with the same value are no-ops, so the registry can call it from every
231
+ * acquire/release without tracking edges itself.
232
+ *
233
+ * Returns which real transition (if any) just happened, so the registry can
234
+ * emit the matching `activated`/`deactivated` plugin event without exposing
235
+ * `_activation` itself — `'none'` for an idempotent no-op call.
236
+ */
237
+ [require_StateContainerRegistry.SET_ACTIVE](active) {
238
+ if (this._disposed) return "none";
239
+ if (active === (this._activation !== null)) return "none";
240
+ if (active) {
241
+ this._activation = new AbortController();
242
+ this.onActivate(this._activation.signal);
243
+ return {
244
+ kind: "activated",
245
+ signal: this._activation.signal
246
+ };
247
+ }
248
+ this._abortActivation();
249
+ this.onDeactivate();
250
+ return "deactivated";
251
+ }
252
+ _abortActivation() {
253
+ this._activation?.abort();
254
+ this._activation = null;
255
+ }
256
+ reconcileDeps() {
257
+ const prev = this._deps;
258
+ const next = {};
259
+ if (this._depsByOwner) for (const slice of this._depsByOwner.values()) Object.assign(next, slice);
260
+ for (const key of Object.keys(prev)) if (!(key in next)) next[key] = void 0;
261
+ if (shallowEqualRecord(prev, next)) return;
262
+ this._deps = next;
263
+ this.onDepsChanged(next, prev);
264
+ this._registry.emit("depsChanged", this, prev, next);
265
+ }
266
+ onDepsChanged(_next, _prev) {}
267
+ get state() {
268
+ return this._stateOverride ?? super.state;
269
+ }
270
+ /**
271
+ * @internal Run `fn` with `state` reporting `tracked`, and with dep handles
272
+ * read off `this` routed through `onDepHandle`. Restored in `finally`, and
273
+ * nestable — getters reading other getters stay in tracked context.
274
+ *
275
+ * The dep hook lives here rather than in the adapter's proxy because getters
276
+ * now run with `this` = the real instance (so ES `#private` works), which
277
+ * means a `this.someDep` read never passes through the proxy's trap.
278
+ */
279
+ [require_StateContainerRegistry.WITH_TRACKED_STATE](tracked, fn, onDepHandle) {
280
+ const prevState = this._stateOverride;
281
+ const prevHook = this._depHandleHook;
282
+ this._stateOverride = tracked;
283
+ this._depHandleHook = onDepHandle;
284
+ try {
285
+ return fn();
286
+ } finally {
287
+ this._stateOverride = prevState;
288
+ this._depHandleHook = prevHook;
289
+ }
290
+ }
291
+ get args() {
292
+ return this._config.args;
293
+ }
294
+ /**
295
+ * Declare a cross-bloc dependency. Returns a branded handle with two
296
+ * accessors — the dep instance is resolved against the registry on each call,
297
+ * which keeps the surface immune to dep-instance churn:
298
+ *
299
+ * - `handle.track(options?)` — reactive read. Returns `[state, instance]`.
300
+ * Inside a getter reached through the React proxy this subscribes the
301
+ * reading component to the dep's changes (base impl: live, no subscription).
302
+ * - `handle.untracked(options?)` — returns the live instance with no tracking,
303
+ * for imperative method calls and one-off reads.
304
+ *
305
+ * `defaultArgs` resolves the dep instance when an accessor is called without
306
+ * its own `args`; per-call `options.args` overrides it and can derive from
307
+ * current state. This does NOT auto-resubscribe outside the React proxy;
308
+ * non-React consumers needing updates should subscribe explicitly.
309
+ */
310
+ depend(Type, defaultArgs) {
311
+ if (!this._dependencies) this._dependencies = /* @__PURE__ */ new Map();
312
+ this._dependencies.set(Type, this._registry.resolveKey(Type, void 0, defaultArgs));
313
+ const resolve = (args) => {
314
+ const effectiveArgs = args ?? defaultArgs;
315
+ const key = this._registry.resolveKey(Type, void 0, effectiveArgs);
316
+ return this._registry.acquire(Type, key, {
317
+ canCreate: true,
318
+ countRef: false,
319
+ args: effectiveArgs,
320
+ dependent: this
321
+ });
322
+ };
323
+ const handle = {
324
+ track: (options) => {
325
+ const wrapped = this._depHandleHook?.(handle);
326
+ if (wrapped !== void 0 && wrapped !== handle) return wrapped.track(options);
327
+ const instance = resolve(options?.args);
328
+ return [instance.state, instance];
329
+ },
330
+ untracked: (options) => resolve(options?.args)
331
+ };
332
+ Object.defineProperty(handle, DEP_BRAND, {
333
+ value: {
334
+ Type,
335
+ defaultArgs
336
+ },
337
+ enumerable: false,
338
+ writable: false,
339
+ configurable: false
340
+ });
341
+ return handle;
342
+ }
343
+ constructor(initialState, options) {
344
+ super(initialState, options);
345
+ this._depsByOwner = null;
346
+ this._deps = {};
347
+ this._disposed = false;
348
+ this._hydrationStatus = "idle";
349
+ this._changedWhileHydrating = false;
350
+ this._hydrationPromise = null;
351
+ this._hydrationPromiseSettled = false;
352
+ this._config = {};
353
+ this._initCalled = false;
354
+ this._activation = null;
355
+ this._emitWindowStart = 0;
356
+ this._emitCount = 0;
357
+ this._emitRateWarned = false;
358
+ this._systemEventHandlers = /* @__PURE__ */ new Map();
359
+ this._dependencies = null;
360
+ this._pendingChange = null;
361
+ this._bridgeUnsub = null;
362
+ this._registry = getRegistry();
363
+ this._equalityFn = require_StateContainerRegistry.getBlacConfig().equality;
364
+ this._name = require_StateContainerRegistry.getBlacName(this.constructor);
365
+ this._debug = false;
366
+ this._createdAt = Date.now();
367
+ this.$blac = createMeta(this);
368
+ this.onSystemEvent = (event, handler) => {
369
+ let handlers = this._systemEventHandlers.get(event);
370
+ if (!handlers) {
371
+ handlers = /* @__PURE__ */ new Set();
372
+ this._systemEventHandlers.set(event, handlers);
373
+ }
374
+ handlers.add(handler);
375
+ if (event === "stateChanged" && this._bridgeUnsub === null) this._bridgeUnsub = this.channel.subscribe(() => _dirtytalk_structural.ALL_PATHS, () => this._drainPending());
376
+ return () => {
377
+ handlers?.delete(handler);
378
+ if (event === "stateChanged" && handlers?.size === 0) {
379
+ this._bridgeUnsub?.();
380
+ this._bridgeUnsub = null;
381
+ this._pendingChange = null;
382
+ }
383
+ };
384
+ };
385
+ }
386
+ /**
387
+ * Called once after construction with the args passed at acquire time, before the first
388
+ * state snapshot is read by any consumer. Override to seed args-derived state (via
389
+ * this.emit(...)) or kick off loads.
390
+ */
391
+ init(_args) {}
392
+ /**
393
+ * Called when this instance goes from unowned to owned (first ref or first
394
+ * `depend()` dependent). Override to start work that should only run while
395
+ * something is actually using the instance — fetches, timers, listeners.
396
+ *
397
+ * `signal` aborts on the matching {@link onDeactivate} and on dispose, so
398
+ * async work started here can be cancelled without extra bookkeeping.
399
+ *
400
+ * Runs before the first `useBlocDeps` slice is applied, so `this.deps` is
401
+ * empty on first activation — use `onDepsChanged` for deps-driven work.
402
+ */
403
+ onActivate(_signal) {}
404
+ /**
405
+ * Called when this instance goes from owned back to unowned while surviving
406
+ * in the registry (i.e. `keepAlive`). A disposed instance does NOT get this
407
+ * callback — `dispose()` is the teardown path for that case.
408
+ */
409
+ onDeactivate() {}
410
+ /**
411
+ * @internal Framework-only configuration entry point (registry + testing
412
+ * helpers). Writes the `_`-private identity fields directly, resolves
413
+ * per-class equality, emits the registry `created` event, and runs `init()`
414
+ * once. See {@link INIT_CONFIG}.
415
+ */
416
+ [require_StateContainerRegistry.INIT_CONFIG](config) {
417
+ this._config = { ...config };
418
+ this._name = this._config.name || require_StateContainerRegistry.getBlacName(this.constructor);
419
+ this._debug = this._config.debug ?? false;
420
+ this._instanceId = generateSimpleId(require_StateContainerRegistry.getBlacName(this.constructor), this._config.instanceId);
421
+ const perClass = require_StateContainerRegistry.getClassEquality(this.constructor);
422
+ this._equalityFn = perClass ?? require_StateContainerRegistry.getBlacConfig().equality;
423
+ if (!this._initCalled) {
424
+ this._initCalled = true;
425
+ this.init(this._config.args);
426
+ }
427
+ this._registry.emit("created", this);
428
+ if (require_StateContainerRegistry.IS_DEV) {
429
+ 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.`);
430
+ }
431
+ }
432
+ dispose() {
433
+ if (this._disposed) return;
434
+ if (this._debug) console.log(`[${this._name}] Disposing...`);
435
+ if (this._depsByOwner) {
436
+ this._depsByOwner.clear();
437
+ this.reconcileDeps();
438
+ }
439
+ this._disposed = true;
440
+ if (this._hydrationStatus === "hydrating") this._failHydration(/* @__PURE__ */ new Error(`Hydration cancelled because ${this._name} was disposed`));
441
+ this.emitSystemEvent("dispose", void 0);
442
+ this._bridgeUnsub?.();
443
+ this._bridgeUnsub = null;
444
+ this._abortActivation();
445
+ this._systemEventHandlers.clear();
446
+ this._pendingChange = null;
447
+ this._registry.emit("disposed", this);
448
+ super.dispose();
449
+ if (this._debug) console.log(`[${this._name}] Disposed successfully`);
450
+ }
451
+ emit(next) {
452
+ this.applyState(next, "default");
453
+ }
454
+ /**
455
+ * Override of `StructuralContainer.patch` that routes through the
456
+ * StateContainer concerns: disposed guard, dev-only emit-rate check,
457
+ * `_changedWhileHydrating` flag, pending-change capture (so `stateChanged`
458
+ * system events see the merged prev/next), and the registry-level
459
+ * `stateChanged` notification. We still call
460
+ * `super.patch` so path-marking semantics (the whole point of patch) are
461
+ * preserved.
462
+ */
463
+ patch(partial) {
464
+ if (this._disposed) {
465
+ this._warnDisposedMutation("patch");
466
+ return;
467
+ }
468
+ const prev = this.state;
469
+ super.patch(partial);
470
+ const next = this.state;
471
+ if (Object.is(prev, next)) return;
472
+ if (require_StateContainerRegistry.IS_DEV) this._checkEmitRate();
473
+ if (this._hydrationStatus === "hydrating") this._changedWhileHydrating = true;
474
+ if (this._bridgeUnsub !== null) if (this._pendingChange) this._pendingChange.next = next;
475
+ else this._pendingChange = {
476
+ prev,
477
+ next
478
+ };
479
+ if (this._registry.hasStateChangedListeners) this._registry.notifyStateChanged(this, prev, next);
480
+ }
481
+ applyState(next, source) {
482
+ if (this._disposed) {
483
+ this._warnDisposedMutation("emit");
484
+ return;
485
+ }
486
+ const prev = this.state;
487
+ if (prev === next) return;
488
+ if (this._equalityFn(prev, next)) return;
489
+ if (require_StateContainerRegistry.IS_DEV) this._checkEmitRate();
490
+ if (this._hydrationStatus === "hydrating" && source !== "hydration") this._changedWhileHydrating = true;
491
+ if (this._bridgeUnsub !== null) if (this._pendingChange) this._pendingChange.next = next;
492
+ else this._pendingChange = {
493
+ prev,
494
+ next
495
+ };
496
+ super.emit(next);
497
+ if (this._registry.hasStateChangedListeners) this._registry.notifyStateChanged(this, prev, next);
498
+ }
499
+ /**
500
+ * Called by the channel-bridge subscriber on each flush. Drains the
501
+ * pending change (if any) into the 'stateChanged' system event.
502
+ * No pending change == flush from a no-op patch == skip.
503
+ */
504
+ _drainPending() {
505
+ const pending = this._pendingChange;
506
+ if (!pending) return;
507
+ this._pendingChange = null;
508
+ const handlers = this._systemEventHandlers.get("stateChanged");
509
+ if (handlers && handlers.size > 0) {
510
+ const payload = {
511
+ state: pending.next,
512
+ previousState: pending.prev
513
+ };
514
+ let count = 0;
515
+ const size = handlers.size;
516
+ for (const handler of handlers) {
517
+ if (++count > size) break;
518
+ try {
519
+ handler(payload);
520
+ } catch (error) {
521
+ console.error(`[${this._name}] Error in system event handler:`, error);
522
+ }
523
+ }
524
+ }
525
+ }
526
+ _beginHydration() {
527
+ if (this._disposed) throw new Error(`Cannot begin hydration for disposed container ${this._name}`);
528
+ this._changedWhileHydrating = false;
529
+ this._hydrationError = void 0;
530
+ this._hydrationPromise = null;
531
+ this._resolveHydrationPromise = void 0;
532
+ this._rejectHydrationPromise = void 0;
533
+ this._hydrationPromiseSettled = false;
534
+ this.ensureHydrationPromise();
535
+ this.setHydrationStatus("hydrating");
536
+ }
537
+ _warnDisposedMutation(op) {
538
+ if (require_StateContainerRegistry.IS_DEV) console.warn(`[blac] ${this._name}: ${op}() after dispose ignored. This usually means an async method resolved after the last consumer unmounted. Guard with \`if (this.$blac.disposed) return\` after each \`await\`, or abort the work from \`onSystemEvent('dispose', ...)\`.`);
539
+ }
540
+ _applyHydratedState(next) {
541
+ if (this._disposed) return false;
542
+ if (this._hydrationStatus !== "hydrating" || this._changedWhileHydrating) {
543
+ if (require_StateContainerRegistry.IS_DEV && this._changedWhileHydrating) console.warn(`[blac] ${this._name}: persisted state discarded because the container emitted while hydrating.`);
544
+ return false;
545
+ }
546
+ this.applyState(next, "hydration");
547
+ return true;
548
+ }
549
+ _finishHydration() {
550
+ if (this._hydrationStatus !== "hydrating") {
551
+ if (this._hydrationStatus === "hydrated") return;
552
+ if (this._hydrationStatus === "error") this.ensureHydrationPromise();
553
+ }
554
+ this.setHydrationStatus("hydrated");
555
+ this.resolveHydration();
556
+ }
557
+ _failHydration(error) {
558
+ const err = error instanceof Error ? error : /* @__PURE__ */ new Error(`Hydration failed: ${String(error)}`);
559
+ this._hydrationError = err;
560
+ this.setHydrationStatus("error", err);
561
+ this.rejectHydration(err);
562
+ }
563
+ _waitForHydration() {
564
+ if (this._hydrationStatus === "idle" || this._hydrationStatus === "hydrated") return Promise.resolve();
565
+ if (this._hydrationStatus === "error") return Promise.reject(this._hydrationError ?? /* @__PURE__ */ new Error(`Hydration failed for container ${this._name}`));
566
+ return this.ensureHydrationPromise();
567
+ }
568
+ setHydrationStatus(status, error) {
569
+ const previousStatus = this._hydrationStatus;
570
+ this._hydrationStatus = status;
571
+ this._hydrationError = error;
572
+ this.emitSystemEvent("hydrationChanged", {
573
+ status,
574
+ previousStatus,
575
+ error,
576
+ changedWhileHydrating: this._changedWhileHydrating
577
+ });
578
+ this._registry.emit("hydrationChanged", this, status, previousStatus);
579
+ }
580
+ ensureHydrationPromise() {
581
+ if (!this._hydrationPromise || this._hydrationPromiseSettled) {
582
+ this._hydrationPromiseSettled = false;
583
+ this._hydrationPromise = new Promise((resolve, reject) => {
584
+ this._resolveHydrationPromise = () => {
585
+ if (this._hydrationPromiseSettled) return;
586
+ this._hydrationPromiseSettled = true;
587
+ resolve();
588
+ };
589
+ this._rejectHydrationPromise = (error) => {
590
+ if (this._hydrationPromiseSettled) return;
591
+ this._hydrationPromiseSettled = true;
592
+ reject(error);
593
+ };
594
+ });
595
+ this._hydrationPromise.catch(() => {});
596
+ }
597
+ return this._hydrationPromise;
598
+ }
599
+ resolveHydration() {
600
+ this._resolveHydrationPromise?.();
601
+ }
602
+ rejectHydration(error) {
603
+ this.ensureHydrationPromise();
604
+ this._rejectHydrationPromise?.(error);
605
+ }
606
+ emitSystemEvent(event, payload) {
607
+ const handlers = this._systemEventHandlers.get(event);
608
+ if (!handlers) return;
609
+ for (const handler of handlers) try {
610
+ handler(payload);
611
+ } catch (error) {
612
+ console.error(`[${this._name}] Error in system event handler:`, error);
613
+ }
614
+ }
615
+ /**
616
+ * Dev-only soft circuit breaker. Counts real state changes in a rolling 1s
617
+ * window and warns once if the rate exceeds `maxEmitsPerSecond` — the
618
+ * signature of a runaway loop (RAF/animation or emit-on-every-commit) pushing
619
+ * high-frequency data through state, which freezes subscribers/plugins.
620
+ */
621
+ _checkEmitRate() {
622
+ const limit = require_StateContainerRegistry.getBlacConfig().maxEmitsPerSecond;
623
+ if (!(limit > 0) || !Number.isFinite(limit) || this._emitRateWarned) return;
624
+ const now = Date.now();
625
+ if (now - this._emitWindowStart >= 1e3) {
626
+ this._emitWindowStart = now;
627
+ this._emitCount = 1;
628
+ return;
629
+ }
630
+ this._emitCount++;
631
+ if (this._emitCount > limit) {
632
+ this._emitRateWarned = true;
633
+ 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.)`);
634
+ }
635
+ }
636
+ };
637
+ //#endregion
638
+ //#region src/core/Cubit.ts
639
+ /**
640
+ * `Cubit<S>` is a `StateContainer<S>` that exposes mutation publicly.
641
+ *
642
+ * That is the whole difference, and it is a real one: on `StateContainer`
643
+ * `emit` / `patch` / `update` are `protected`, so a container mutates itself
644
+ * from its own methods and callers go through the API it chooses to publish.
645
+ * `Cubit` re-declares the three as `public` for the cases where a caller
646
+ * legitimately drives state from outside — test helpers, devtools
647
+ * time-travel, benchmarks.
648
+ *
649
+ * Reach for `StateContainer` when business logic should live in the class,
650
+ * and `Cubit` when the caller owns the transitions.
651
+ */
652
+ var Cubit = class extends StateContainer {
653
+ emit(next) {
654
+ super.emit(next);
655
+ }
656
+ patch(partial) {
657
+ super.patch(partial);
658
+ }
659
+ update(fn) {
660
+ super.update(fn);
661
+ }
662
+ };
663
+ //#endregion
664
+ //#region src/registry/acquire.ts
665
+ /**
666
+ * Acquire an instance with ref tracking (ownership semantics). Instance
667
+ * identity is derived purely from `args` (via the class's `static key(args)`,
668
+ * a structural hash of `args`, or the default sentinel when there are none).
669
+ *
670
+ * @param BlocClass - The StateContainer class constructor
671
+ * @param opts - `args` derives the instance key; `refId` names the reference
672
+ * for debugging and is auto-generated when omitted.
673
+ */
674
+ function acquire(BlocClass, opts) {
675
+ const registry = getRegistry();
676
+ const key = registry.resolveKey(BlocClass, void 0, opts?.args);
677
+ return registry.acquire(BlocClass, key, {
678
+ canCreate: true,
679
+ countRef: true,
680
+ refId: opts?.refId,
681
+ args: opts?.args
682
+ });
683
+ }
684
+ /**
685
+ * Resolve the storage key an instance would be acquired under, given its
686
+ * construction `args`. This is the canonical key-computation path. Callers that
687
+ * both acquire and release against the `@internal` registry tier (e.g.
688
+ * `@blac/react` `useBloc`) must use this once and pass the same resolved key to
689
+ * both, so the ref is dropped under the key it was taken.
690
+ */
691
+ function resolveInstanceKey(BlocClass, args) {
692
+ return getRegistry().resolveKey(BlocClass, void 0, args);
693
+ }
694
+ //#endregion
695
+ //#region src/registry/ensure.ts
696
+ /**
697
+ * Ensure an instance exists without taking ownership (no ref added). Instance
698
+ * identity is derived purely from `args`, matching `acquire`.
699
+ */
700
+ function ensure(BlocClass, opts) {
701
+ const registry = getRegistry();
702
+ const key = registry.resolveKey(BlocClass, void 0, opts?.args);
703
+ return registry.ensure(BlocClass, key, opts?.args);
704
+ }
705
+ //#endregion
706
+ Object.defineProperty(exports, "Cubit", {
707
+ enumerable: true,
708
+ get: function() {
709
+ return Cubit;
710
+ }
711
+ });
712
+ Object.defineProperty(exports, "DEP_BRAND", {
713
+ enumerable: true,
714
+ get: function() {
715
+ return DEP_BRAND;
716
+ }
717
+ });
718
+ Object.defineProperty(exports, "StateContainer", {
719
+ enumerable: true,
720
+ get: function() {
721
+ return StateContainer;
722
+ }
723
+ });
724
+ Object.defineProperty(exports, "acquire", {
725
+ enumerable: true,
726
+ get: function() {
727
+ return acquire;
728
+ }
729
+ });
730
+ Object.defineProperty(exports, "ensure", {
731
+ enumerable: true,
732
+ get: function() {
733
+ return ensure;
734
+ }
735
+ });
736
+ Object.defineProperty(exports, "getRegistry", {
737
+ enumerable: true,
738
+ get: function() {
739
+ return getRegistry;
740
+ }
741
+ });
742
+ Object.defineProperty(exports, "getStats", {
743
+ enumerable: true,
744
+ get: function() {
745
+ return getStats;
746
+ }
747
+ });
748
+ Object.defineProperty(exports, "resolveInstanceKey", {
749
+ enumerable: true,
750
+ get: function() {
751
+ return resolveInstanceKey;
752
+ }
753
+ });
754
+ Object.defineProperty(exports, "setRegistry", {
755
+ enumerable: true,
756
+ get: function() {
757
+ return setRegistry;
758
+ }
759
+ });
760
+
761
+ //# sourceMappingURL=ensure-BjhbDW8Z.cjs.map