blac

    Going deeper

    How BlaC Works Internally

    Rebuild BlaC's reactivity engine from the ground up in four stages — the dirty channel, the path interner, the recording proxy, the observed skeleton, and cross-bloc dependencies.

    This chapter rebuilds BlaC’s reactivity engine from the ground up, one stage at a time. By the end you will be able to point at every moving part — the dirty channel, the path interner, the recording proxy, the observed skeleton, and the cross-bloc dependency layer — and say exactly what it does and why it has to.

    If you only want the rules for writing components, read Tracking and Dependency Tracking. This page is for when you want the machine. It is grounded directly in the source: the engine lives in @dirtytalk/engine, the path machinery in @dirtytalk/structural, and BlaC’s lifecycle layer in @blac/core’s StateContainer. The companion design narrative is the Mental Model; the distilled standalone version is DirtyTalk.

    We build in four stages, each strictly on top of the last:

    Stage 1 state + listeners "something changed — wake everyone"
    │ (DirtyChannel, coalesced flush)
    ▼
    Stage 2 paths "what changed — as interned integers"
    │ (PathInterner, PathSet, intersection)
    ▼
    Stage 3 the skeleton "who reads what — diff once, fan out cheap"
    │ (trackRender proxy + observed skeleton)
    ▼
    Stage 4 cross-bloc deps "one bloc leans on another"
    (StateContainer.depend / registry)

    Stage 1 — State and listeners

    Start with the smallest honest model: a value, a set of listeners, and a way to say “I changed.” Every reactive store has this core. The naive version notifies every listener synchronously on every change.

    BlaC’s real notification core is DirtyChannel<Region> from @dirtytalk/engine, but we approach it from the outside in. From the outside, that contract is what Cubit exposes: a value behind state, mutated by emit / update, with watch (or the lower-level subscribe) firing on every coalesced flush. This block type-checks against the real @blac/core surface:

    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    ,
    const watch: WatchFn
    watch
    ,
    function ensure<T extends StateContainerConstructor>(BlocClass: T, opts?: {
    args?: ExtractArgs<T>;
    }): InstanceType<T>

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    } from '@blac/core';
    class
    class CounterCubit
    CounterCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    count: number
    count
    : number }> {
    constructor() {
    super({
    count: number
    count
    : 0 });
    }
    CounterCubit.increment(): void
    increment
    () {
    // Immutable replacement. Several synchronous emits coalesce into ONE flush.
    this.
    Cubit<{ count: number; }, void, Record<string, never>>.emit(next: {
    count: number;
    }): void
    emit
    ({
    count: number
    count
    : this.
    StateContainer<{ count: number; }, void, Record<string, never>>.state: {
    count: number;
    }
    state
    .
    count: number
    count
    + 1 });
    }
    }
    // watch wakes on every flush and hands you the instance with the latest state.
    const
    const stop: () => void
    stop
    =
    watch<typeof CounterCubit>(bloc: typeof CounterCubit | BlocRef<typeof CounterCubit>, callback: (bloc: CounterCubit) => void | unique symbol, options?: WatchOptions): () => void (+1 overload)
    watch
    (
    class CounterCubit
    CounterCubit
    , (
    counter: CounterCubit
    counter
    ) =>
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    ('woke at',
    counter: CounterCubit
    counter
    .
    StateContainer<{ count: number; }, void, Record<string, never>>.state: {
    count: number;
    }
    state
    .
    count: number
    count
    ),
    );
    const
    const c: CounterCubit
    c
    =
    ensure<typeof CounterCubit>(BlocClass: typeof CounterCubit, opts?: {
    args?: void | undefined;
    } | undefined): CounterCubit

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    (
    class CounterCubit
    CounterCubit
    );
    const c: CounterCubit
    c
    .
    CounterCubit.increment(): void
    increment
    ();
    const c: CounterCubit
    c
    .
    CounterCubit.increment(): void
    increment
    (); // two emits, same tick → callback fires once with count: 2
    const stop: () => void
    stop
    ();

    Underneath, watch is a thin bridge over the real notification core: DirtyChannel<Region> from @dirtytalk/engine. It is generic over a Region — an opaque “what changed” value governed by a Space<Region> algebra (empty, isEmpty, union, intersects). Two properties make it more than a plain EventEmitter. Modeled with a trivial boolean Region where “dirty” is just true (illustrative — @dirtytalk/engine is the engine package, not a docs dependency, so this block is shown rather than type-checked):

    import { DirtyChannel, SyncScheduler, type Space } from '@dirtytalk/engine';
    // The simplest possible Region: a boolean. `true` = "something changed".
    const BoolSpace: Space<boolean> = {
    empty: () => false,
    isEmpty: (r) => r === false,
    union: (a, b) => a || b,
    // Any non-empty dirty wakes any interested subscriber.
    intersects: (interest, dirty) => interest && dirty,
    };
    class Counter {
    private _state = 0;
    // SyncScheduler flushes inline (production uses MicrotaskScheduler).
    private channel = new DirtyChannel<boolean>(BoolSpace, new SyncScheduler());
    get state() {
    return this._state;
    }
    listen(cb: () => void) {
    return this.channel.subscribe(
    () => true, // interest: "I care about everything"
    () => cb(),
    );
    }
    increment() {
    this._state += 1;
    this.channel.mark(true); // "something changed"
    }
    }

    The two load-bearing properties of DirtyChannel:

    1. Marks accumulate, flushes coalesce. mark(region) unions the region into an accumulator and asks the scheduler to flush once. Several synchronous marks collapse into a single flush — so three emits in one tick wake each listener at most once.
    2. Interests are thunks evaluated at flush time. A subscriber registers subscribe(() => interest, cb). On flush the channel evaluates the interest thunk, tests space.intersects(interest, dirty), and calls cb only on a hit. (This is the seam Stage 2 and 3 exploit; here the region is just “everything.”)
    Stage 1: mark → flush → wake everyone
    increment() increment() (same tick)
    │ │
    ▼ ▼
    mark(true) mark(true) union → still `true`
    └─────┬──────┘
    ▼
    scheduler.request(flush) coalesced: scheduled once
    │
    ▼
    flush: dirty = true ───────────► every subscriber whose
    interest intersects → cb()

    This is everything a Cubit does at the listener level. The watch(BlocClass, cb) helper is exactly this: it bridges every flush to a callback that wakes on any change, regardless of what changed, applied from outside React. The flush is microtask-coalesced, which is why several synchronous emits produce a single notification.

    What’s missing: “wake everyone” is wasteful. A container with twenty fields wakes a listener that reads one of them on all twenty kinds of change. Stage 2 makes “what changed” precise.


    Stage 2 — Paths

    Replace the boolean region with a set of changed paths. A path is a dotted route to a leaf in the state tree: user.name, items, user.address.city. A mutation marks the paths it touched; a listener declares the paths it reads; the channel wakes a listener only when those two sets intersect.

    Comparing and unioning dotted strings on every mutation would be wasteful, so every path is interned into a small integer PathId once. PathInterner (in @dirtytalk/structural, used internally by every BlaC container) is a bidirectional string ↔ PathId table: intern(path) returns a stable id (the next sequential integer, starting at 0), idempotently; lookup(id) reverses it.

    import { PathInterner } from '@dirtytalk/structural';
    const interner = new PathInterner();
    interner.intern('user.name'); // 0
    interner.intern('user.email'); // 1
    interner.intern('user.name'); // 0 again — idempotent
    interner.lookup(0); // 'user.name'
    interner.size; // 2

    Ids are only comparable inside one interner’s namespace, so BlaC keeps one interner per container subclass, keyed by constructor in a WeakMap (StructuralContainer.getInternerFor). Every instance of one Cubit subclass shares an interner, so their ids line up and can be unioned/intersected freely; distinct subclasses get distinct interners even if their state shapes match. The WeakMap lets the interner be collected once the class is gone.

    A PathSet is the unit of both “interest” and “dirtiness.” It is either a concrete Set<PathId> or the ALL_PATHS sentinel ("every possible path"). The set algebra is a Space<PathSet> — PathSetSpace — the same Space contract from Stage 1, now over path sets instead of booleans:

    import {
    PathInterner,
    PathSetSpace,
    ALL_PATHS,
    type PathSet,
    } from '@dirtytalk/structural';
    const interner = new PathInterner();
    const name = interner.intern('user.name'); // 0
    const email = interner.intern('user.email'); // 1
    // A listener that reads user.name; a mutation that changed user.email.
    const interest: PathSet = new Set([name]);
    const dirty: PathSet = new Set([email]);
    PathSetSpace.intersects(interest, dirty); // false → stays asleep
    PathSetSpace.intersects(new Set([name]), new Set([name])); // true → wakes
    // ALL_PATHS intersects any non-empty set (used for "wake everyone" signalling).
    PathSetSpace.intersects(ALL_PATHS, dirty); // true
    PathSetSpace.intersects(interest, ALL_PATHS); // true
    // ...but an empty interest never wakes — "I care about nothing".
    PathSetSpace.intersects(PathSetSpace.empty(), ALL_PATHS); // false

    ALL_PATHS and the PathSet type are the only path primitives BlaC re-exports from @blac/core (for plugins composing subscribe and consume calls); this type-checked block uses them directly:

    import {
    const ALL_PATHS: typeof ALL_PATHS
    ALL_PATHS
    , type
    type PathSet = typeof ALL_PATHS | Set<number>
    PathSet
    } from '@blac/core';
    // A plugin or devtools panel can declare blanket interest in every change.
    const
    const blanketInterest: PathSet
    blanketInterest
    :
    type PathSet = typeof ALL_PATHS | Set<number>
    PathSet
    =
    const ALL_PATHS: typeof ALL_PATHS
    ALL_PATHS
    ;
    void
    const blanketInterest: typeof ALL_PATHS
    blanketInterest
    ;

    The channel is identical to Stage 1; only the Region changed from boolean to PathSet. intersects does the discrimination: iterate the smaller set, look up in the larger, return on the first hit. That is the entire per-listener cost of a change — no tree walk.

    Where do the changed paths come from? The mutators compute them:

    • emit(next) installs a new immutable state, then diffs to find which observed paths changed value (Stage 3 covers the skeleton bound on that diff).
    • patch(partial) is exactly emit(deepMerge(state, partial)): it goes through the same diff as emit, which is value-filtered and prunes unchanged references. So an over-spread patch that re-sets a whole parent when one field changed does not over-wake the siblings, and a patch that replaces an array with equal contents wakes readers of the whole array but not of its unchanged children.
    • update(fn) is sugar for emit(fn(state)).

    From the public surface, the three mutators look like this — and all type-check:

    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    } from '@blac/core';
    interface
    interface UserState
    UserState
    {
    UserState.user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : string;
    email: string
    email
    : string };
    UserState.items: string[]
    items
    : string[];
    }
    class
    class UserCubit
    UserCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <
    interface UserState
    UserState
    > {
    constructor() {
    super({
    UserState.user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : 'Ada',
    email: string
    email
    : 'ada@x.io' },
    UserState.items: string[]
    items
    : [] });
    }
    // patch: deep-merges; marks only paths whose value actually changed.
    // Here only `user.email` moves → `user.name` consumers stay asleep.
    UserCubit.setEmail(email: string): void
    setEmail
    (
    email: string
    email
    : string) {
    this.
    Cubit<UserState, void, Record<string, never>>.patch(partial: {
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined;
    items?: readonly string[] | undefined;
    }): void

    Merge partial into the state. Plain-object branches merge recursively; arrays, class instances, Map, Set, Date and primitives replace the slot. A key cannot be removed this way (undefined is stored as a value); use emit or update for that.

    @see ― emit for the StateContainer concerns layered onto super.patch.

    patch
    ({
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined
    user
    : {
    email?: string | undefined
    email
    } });
    }
    // update: sugar for emit(fn(state)); replace immutably.
    UserCubit.addItem(item: string): void
    addItem
    (
    item: string
    item
    : string) {
    this.
    Cubit<UserState, void, Record<string, never>>.update(fn: (state: UserState) => UserState): void
    update
    ((
    s: UserState
    s
    ) => ({ ...
    s: UserState
    s
    ,
    UserState.items: string[]
    items
    : [...
    s: UserState
    s
    .
    UserState.items: string[]
    items
    ,
    item: string
    item
    ] }));
    }
    // emit: replace the whole state.
    UserCubit.reset(): void
    reset
    () {
    this.
    Cubit<UserState, void, Record<string, never>>.emit(next: UserState): void
    emit
    ({
    UserState.user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : '',
    email: string
    email
    : '' },
    UserState.items: string[]
    items
    : [] });
    }
    }
    void
    class UserCubit
    UserCubit
    ;
    Stage 2: paths as interned ids
    state = { user: { name, email }, items }
    intern: user.name → 0 user.email → 1 items → 2
    emit changes user.email ──► dirty = { 1 }
    │
    ┌────────────────┼────────────────┐
    ▼ ▼ ▼
    interest {0} interest {1} interest {2}
    (reads name) (reads email) (reads items)
    ∩ {1} = ∅ ∩ {1} = {1} ∩ {1} = ∅
    asleep WAKE asleep

    What’s still missing: a listener must somehow declare its path set. Writing it by hand is a selector — the exact thing BlaC avoids. Stage 3 makes the read itself the declaration.


    Stage 3 — The recording proxy and the observed skeleton

    A consumer declares which paths it reads by reading them. trackRender(state, interner) wraps state in a recording Proxy and returns { value, paths }: value is the proxy you read during render, paths is a live Set<PathId> that grows as you touch properties off value. trackRender is internal (@dirtytalk/structural); the React adapter calls it for you on every render, so you never import it directly. Shown here to make the mechanism concrete:

    import { PathInterner, trackRender, type PathId } from '@dirtytalk/structural';
    interface State {
    user: { name: string; email: string };
    items: number[];
    }
    const state: State = {
    user: { name: 'Ada', email: 'ada@x.io' },
    items: [1, 2, 3],
    };
    const interner = new PathInterner();
    const { value, paths } = trackRender(state, interner);
    // Simulate what a component's render does: read the fields it displays.
    void value.user.name; // records `user.name`
    void value.items; // records `items`
    // `paths` now holds exactly the interned ids of what was read.
    const read: PathId[] = [...(paths as Set<PathId>)].sort();
    read.map((id) => interner.lookup(id)); // ['items', 'user.name']

    The recording rules are deliberate, and each one earns its keep:

    • Leaf-only (maximal) recording. Reading user.name records user.name and drops the intermediate user from the set. So when an immutable update replaces the whole user object because a sibling (user.email) changed, a consumer that only read user.name does not wake — its recorded leaf still resolves to the same value. Read the whole user object (no deeper key) and user stays your leaf, so any change inside it wakes you.
    • Own, non-symbol reads only. Symbol keys (Symbol.iterator) and inherited prototype props never record. Re-reads are idempotent (it’s a Set).
    • Nested plain objects/arrays return child proxies recording into the same set, cached per target so value.user === value.user within one render.
    • Iteration is per item. .map / .find / for..of run against the proxy, so they record items.length and each field the callback reads (items.0.title, …). includes / indexOf / lastIndexOf run on the raw array and record items.
    • Leaf collection types are not recursed. Map, Set, Date, and class instances are returned raw (wrapping them would rebind receiver-checked built-ins like Map.prototype.get). A reference change to the whole value still wakes you, but an in-place .set() does not.

    Now the payoff. With N consumers sharing a container, the naive way to find who to wake is per-consumer diffing: N tree walks. BlaC does one walk plus one lookup per changed path instead.

    The trick is the observed skeleton: the union of every consumer’s watched paths. On a mutation, emit diffs prev vs next only along the skeleton — it reads each skeleton path in both states and includes it iff the value moved (Object.is by default). The container keeps the skeleton as a path trie, so the walk stops at every unchanged reference: replacing one item of a 1,000-item list compares 1,000 item references and descends into one. That one walk produces the dirty set; then each changed path is looked up in an index of the consumers watching it (Stage 2). You feed the skeleton through the public consume / setPaths API:

    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    ,
    function ensure<T extends StateContainerConstructor>(BlocClass: T, opts?: {
    args?: ExtractArgs<T>;
    }): InstanceType<T>

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    } from '@blac/core';
    class
    class UserCubit
    UserCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : string;
    email: string
    email
    : string } }> {
    constructor() {
    super({
    user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : 'Ada',
    email: string
    email
    : 'ada@x.io' } });
    }
    UserCubit.setEmail(email: string): void
    setEmail
    (
    email: string
    email
    : string) {
    this.
    Cubit<{ user: { name: string; email: string; }; }, void, Record<string, never>>.patch(partial: {
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined;
    }): void

    Merge partial into the state. Plain-object branches merge recursively; arrays, class instances, Map, Set, Date and primitives replace the slot. A key cannot be removed this way (undefined is stored as a value); use emit or update for that.

    @see ― emit for the StateContainer concerns layered onto super.patch.

    patch
    ({
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined
    user
    : {
    email?: string | undefined
    email
    } });
    }
    }
    const
    const bloc: UserCubit
    bloc
    =
    ensure<typeof UserCubit>(BlocClass: typeof UserCubit, opts?: {
    args?: void | undefined;
    } | undefined): UserCubit

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    (
    class UserCubit
    UserCubit
    );
    const {
    const interner: PathInterner
    interner
    } =
    const bloc: UserCubit
    bloc
    ;
    // Two consumers: one reads user.name, the other reads user.email.
    const
    const a: Consumer
    a
    =
    const bloc: UserCubit
    bloc
    .
    StructuralContainer<{ user: { name: string; email: string; }; }>.consume(cb: (dirty: PathSet) => void): Consumer

    Register a reader. It watches nothing until setPaths is called; after that cb runs, once per flush, when a watched path changed value. cb receives the changed path ids among those any consumer watches.

    consume
    (() =>
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    ('A woke'));
    const a: Consumer
    a
    .
    Consumer.setPaths(paths: PathSet): void

    Replace the watched paths. The set is indexed as passed and must not be mutated afterwards; passing the current set again is a no-op. ALL_PATHS wakes on every change.

    setPaths
    (new
    var Set: SetConstructor
    new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
    Set
    ([
    const interner: PathInterner
    interner
    .
    PathInterner.intern(path: string): PathId
    intern
    ('user.name')]));
    const
    const b: Consumer
    b
    =
    const bloc: UserCubit
    bloc
    .
    StructuralContainer<{ user: { name: string; email: string; }; }>.consume(cb: (dirty: PathSet) => void): Consumer

    Register a reader. It watches nothing until setPaths is called; after that cb runs, once per flush, when a watched path changed value. cb receives the changed path ids among those any consumer watches.

    consume
    ((
    dirty: PathSet
    dirty
    ) =>
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    ('B woke', [...(
    dirty: PathSet
    dirty
    as
    interface Set<T>
    Set
    <number>)].
    Array<number>.map<string>(callbackfn: (value: number, index: number, array: number[]) => string, thisArg?: any): string[]

    Calls a defined callback function on each element of an array, and returns an array that contains the results.

    @param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

    @param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

    map
    ((
    id: number
    id
    ) =>
    const interner: PathInterner
    interner
    .
    PathInterner.lookup(id: PathId): string
    lookup
    (
    id: number
    id
    ))),
    );
    const b: Consumer
    b
    .
    Consumer.setPaths(paths: PathSet): void

    Replace the watched paths. The set is indexed as passed and must not be mutated afterwards; passing the current set again is a no-op. ALL_PATHS wakes on every change.

    setPaths
    (new
    var Set: SetConstructor
    new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
    Set
    ([
    const interner: PathInterner
    interner
    .
    PathInterner.intern(path: string): PathId
    intern
    ('user.email')]));
    // The skeleton is {user.name, user.email}. ONE diff walk, bounded to it,
    // finds that only user.email moved: B wakes, A stays asleep.
    const bloc: UserCubit
    bloc
    .
    UserCubit.setEmail(email: string): void
    setEmail
    ('ada@new.io');

    consume(cb) registers a consumer and setPaths(paths) replaces what it watches; the container recomputes the skeleton as the union of all consumers’ paths, and dispose() drops one.

    Stage 3: one walk, then N cheap intersections
    consumerA reads {user.name} consumerB reads {user.email}
    \ /
    \ /
    ▼ union ▼
    skeleton = {user.name, user.email}
    │
    emit(next) ─► diff(prev, next) along skeleton ◄── the ONE walk
    │
    ▼
    dirty = {user.email}
    ┌────────────┴────────────┐
    ▼ ▼
    A ∩ dirty = ∅ B ∩ dirty = {user.email}
    asleep WAKE

    How React ties in

    useBloc needs no selector because the JSX is the interest declaration. Per render it renders against the recording proxy, then at commit calls consumer.setPaths(paths) on its container.consume(...) consumer — after render, since during render the set is still empty and would freeze an empty skeleton, silently dropping wakeups. On unmount it calls consumer.dispose(). The consumer re-renders only when a watched path changed.

    Conditional reads therefore reshape the skeleton automatically, render to render. To opt out and gate re-renders by a derived value array instead, pass select to useBloc.


    Stage 4 — Cross-bloc dependencies

    The final layer: one bloc leaning on another. This lives in @blac/core’s StateContainer (the class Cubit extends), not in the structural engine — deps are about identity and lifecycle, not path diffing.

    this.depend(OtherBloc) declares a dependency and returns a DepHandle. Calling .untracked() or .track() on the handle resolves the dependency against the registry, so the declaring bloc never holds a stale instance reference across dep churn:

    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    } from '@blac/core';
    class
    class AuthCubit
    AuthCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    userId: string | null
    userId
    : string | null }> {
    constructor() {
    super({
    userId: string | null
    userId
    : null });
    }
    AuthCubit.login(userId: string): void
    login
    (
    userId: string
    userId
    : string) {
    this.
    Cubit<{ userId: string | null; }, void, Record<string, never>>.emit(next: {
    userId: string | null;
    }): void
    emit
    ({
    userId: string | null
    userId
    });
    }
    }
    class
    class DashboardCubit
    DashboardCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    ready: boolean
    ready
    : boolean }> {
    // `depend` returns a handle resolved against the registry per call.
    private
    DashboardCubit.auth: DepHandle<typeof AuthCubit>
    auth
    = this.
    StateContainer<{ ready: boolean; }, void, Record<string, never>>.depend<typeof AuthCubit>(Type: typeof AuthCubit, defaultArgs?: void | undefined): DepHandle<typeof AuthCubit>

    Declare a cross-bloc dependency. Returns a branded handle with two accessors — the dep instance is resolved against the registry on each call, which keeps the surface immune to dep-instance churn:

    • handle.track(options?) — reactive read. Returns [state, instance]. Inside a getter reached through the React proxy this subscribes the reading component to the dep's changes (base impl: live, no subscription).
    • handle.untracked(options?) — returns the live instance with no tracking, for imperative method calls and one-off reads.

    defaultArgs resolves the dep instance when an accessor is called without its own args; per-call options.args overrides it and can derive from current state. This does NOT auto-resubscribe outside the React proxy; non-React consumers needing updates should subscribe explicitly.

    depend
    (
    class AuthCubit
    AuthCubit
    );
    constructor() {
    super({
    ready: boolean
    ready
    : false });
    }
    get
    DashboardCubit.currentUser: string | null
    currentUser
    (): string | null {
    const [
    const authState: {
    readonly userId: string | null;
    }
    authState
    ] = this.
    DashboardCubit.auth: DepHandle<typeof AuthCubit>
    auth
    .
    DepHandle<typeof AuthCubit>.track(options?: DepAccessOptions<typeof AuthCubit> | undefined): [{
    readonly userId: string | null;
    }, AuthCubit]
    track
    (); // resolve + track in render
    return
    const authState: {
    readonly userId: string | null;
    }
    authState
    .
    userId: string | null
    userId
    ;
    }
    }

    Two design points fall out of the source:

    • depend separates .track() from .untracked(). this.depend(AuthCubit) records the dependency (visible via the dependencies getter) and returns a DepHandle. Inside a method or background action, call this.auth.untracked() to resolve the live AuthCubit via ensure() without registering a render subscription. Inside a getter read during a React render, call this.auth.track() — the active DepSession opened by useBloc’s getter wrapper wraps the dependency in its own tracking proxy and subscribes the consuming component to the exact leaf paths read on AuthCubit (without creating a bloc-to-bloc channel cycle).
    • Per-consumer deps are a separate, owner-keyed mechanism. The APPLY_DEPS / REMOVE_DEPS_OWNER symbols (from @blac/core/internal, used by the React adapter) let each consumer inject a slice of deps keyed by an owner id; StateContainer shallow-merges all live owners’ slices, dev-warns on cross-owner key collisions (last write wins), and fires onDepsChanged only when the merged view actually changes. This is distinct from depend’s bloc-to-bloc resolution.
    Stage 4: deps resolve through the registry
    DashboardCubit registry
    │ │
    │ this.depend(AuthCubit) │
    │ ── records dep, returns handle ──► │
    │ │
    │ auth.track() / auth.untracked() ────►│ ── ensure(AuthCubit) returns
    │ │ the live AuthCubit instance
    │ ◄──────────── instance ──────────── │
    ▼
    reads dep.state (.track() records leaf paths into the active
    useBloc DepSession; .untracked() reads raw state)

    StateContainer adds the rest of the lifecycle around these four stages: identity ($blac.name, $blac.id), disposal, hydration, an onSystemEvent('stateChanged' | 'dispose' | 'hydrationChanged', cb) surface, and a dev-only emit-rate circuit breaker that warns once when a runaway loop pushes too many changes through state in a second. But the reactivity itself is the four stages above: a coalescing channel, interned paths, a recording proxy feeding an observed skeleton, and a registry resolving cross-bloc deps.


    Putting it together: one update, end to end

    A single emit flows through all four stages:

    1. A method calls emit / update / patch. StateContainer runs its guards (disposed, equality short-circuit, emit-rate check), captures the prev/next change, and delegates change-detection to StructuralContainer. (Stage 1 + 4 wrapper.)
    2. The container installs the new immutable state and computes the dirty PathSet by diffing against the observed skeleton (patch is emit of the merged state, so both take this path), then marks it on its channel. (Stage 2 + 3.)
    3. The DirtyChannel coalesces marks and schedules one flush per tick. (Stage 1.)
    4. On flush, consumers are found by looking up each dirty path in the container’s path index; ALL_PATHS consumers (subscribe, watch, plugins) are woken by every flush. Only consumers whose watched paths changed have their callback fired (React re-render, watch callback, plugin sink). (Stage 1 + 2.)
    5. On the next render, the proxy re-records each consumer’s interest from scratch, so conditional reads reshape the skeleton automatically. (Stage 3.)

    The practical takeaway is the same sentence the whole machine exists to make true, cheaply: read exactly the state you render, keep state immutable, and BlaC re-renders the minimum.

    See also