@blac/core
v2.0.22
Published
Type-safe, class-based state management with proxy tracking and plugin system
Maintainers
Readme
@blac/core
Core state management primitives for BlaC — state containers, registry, plugins, and tracking utilities.
[!WARNING] BlaC v2 is in pre-release (beta). While in beta, breaking API changes may ship in patch releases without a major version bump. Pin an exact version and check the changelog before upgrading. Strict semver resumes once v2 is officially out of beta.
Installation
pnpm add @blac/coreState Containers
Cubit
The primary building block. Extends StateContainer with public emit, update, and patch methods. Supports typed Args for construction data and Deps for non-serializable handles.
import { Cubit } from '@blac/core';
class CounterCubit extends Cubit<{ count: number }> {
constructor() {
super({ count: 0 });
}
increment = () => this.emit({ count: this.state.count + 1 });
decrement = () => this.update((s) => ({ count: s.count - 1 }));
reset = () => this.patch({ count: 0 });
}emit(newState)— replace the entire stateupdate(fn)— derive new state from currentpatch(partial)— shallow merge (object state only)
Args and Identity Keying
Blocs can declare an Args type to receive typed construction data, which derives instance identity by default:
import { Cubit } from '@blac/core';
class UserCardCubit extends Cubit<UserCardState, { userId: string }> {
// Constructor is always zero-arg
init(args: { userId: string }) {
// Called by framework once, synchronously at creation, before first snapshot
this.userId = args.userId;
}
// Optional: control how args map to identity (default = structural hash)
static key = (args) => args.userId;
}init is for synchronous state seeding, not side effects. Kick off a fetch, subscription, or timer from onActivate(signal) instead — it only fires once something actually owns the instance and hands you an AbortSignal for cleanup. See the @blac/react README for the full lifecycle.
Key mechanics:
- Different args ⇒ different instance (structural hash by default, or
static keyif declared). init(args)called once per instance, right afternew Type(), before the first state snapshot — no flash, correct initial state.- Serializable only — refs, callbacks, DOM elements belong in the
depslane (below).
Deps: Non-Serializable Handles
Non-serializable values (refs, callbacks, class instances) use the Deps generic type and are read via this.deps.x:
import { Cubit } from '@blac/core';
class FileUploadCubit extends Cubit<
UploadState,
{ endpoint: string }, // Args
{ inputRef?: RefObject<HTMLInputElement> } // Deps
> {
init(args: { endpoint: string }) {
this.endpoint = args.endpoint;
}
openPicker() {
// Read deps lazily; may be undefined
this.deps.inputRef?.current?.click?.();
}
}Properties of deps:
- Per-consumer merged — each
useBloccall contributes its own slice; the bloc sees the union. - Never keying — different refs/callbacks don't fork the instance.
- Live — can change over time; merged on every commit.
- Optional
onDepsChangedhook — fires after each merge (see below).
onDepsChanged Lifecycle Hook
For handles that require initialization (canvas setup, RTE editor binding), use onDepsChanged to react when a dep arrives or changes:
class CanvasRendererCubit extends Cubit<
RenderState,
{ sceneId: string },
{ canvas?: HTMLCanvasElement; controller?: RteController }
> {
onDepsChanged(next: this['deps'], prev: this['deps']) {
if (next.canvas && next.canvas !== prev.canvas) {
// Wait for canvas, then init GPU/render loop
this.initRenderer(next.canvas);
}
if (!next.canvas && prev.canvas) {
// Canvas unmounted → tear down
this.disposeRenderer();
}
if (next.controller !== prev.controller) {
this.bindController(next.controller);
}
}
}StateContainer
Abstract base class for managing state outside the bloc/cubit pattern. Mutation is protected: the class owns its transitions and callers go through the methods it exposes.
import { StateContainer } from '@blac/core';
class AuthContainer extends StateContainer<{ token: string | null }> {
constructor() {
super({ token: null });
}
login(token: string) {
this.emit({ token });
}
logout() {
this.emit({ token: null });
}
}Public API: state, subscribe(interest, cb), dispose(), $blac ($blac.name, $blac.id, $blac.debug, $blac.createdAt, $blac.disposed, $blac.dependencies, $blac.hydration)
Protected: emit(state), patch(partial), update(fn) — state mutation is restricted to the class itself, as in the example above. Use Cubit when a caller needs to drive state from outside.
Protected API: init(args) (optional), onDepsChanged(next, prev) (optional), onSystemEvent(event, handler), depend(Type, defaultArgs?) (returns a DepHandle, not an instance)
Registry
Manages instance lifecycles and ref counting.
import {
acquire,
ensure,
borrow,
borrowSafe,
release,
hasInstance,
getRefCount,
} from '@blac/core';
const counter = acquire(CounterCubit); // create or reuse, increment ref count
const shared = ensure(CounterCubit); // create or reuse, no ref count change
const existing = borrow(CounterCubit); // get existing, throws if missing
const maybe = borrowSafe(CounterCubit); // get existing, returns { error, instance }
release(CounterCubit); // decrement ref count, auto-dispose at 0 (unless keepAlive)Configuration
import { Cubit, blac } from '@blac/core';
@blac({ keepAlive: true })
class AuthCubit extends Cubit<AuthState> {}
@blac({ excludeFromDevTools: true })
class InternalCubit extends Cubit<State> {}Watch
Observe state changes outside of a UI framework.
import { watch, instance } from '@blac/core';
const stop = watch(CounterCubit, (counter) => {
console.log(counter.state.count);
if (counter.state.count >= 10) return watch.STOP;
});
// Watch a specific named instance
const stop2 = watch(instance(CounterCubit, { id: 'counter-1' }), (c) => {
console.log(c.state.count);
});State tracking (which blocs/state a function accesses) is automatic — see Tracked for details.
Plugins
import { getPluginManager } from '@blac/core/plugins';
import { type BlacPlugin } from '@blac/core';
const myPlugin: BlacPlugin = {
name: 'my-plugin',
version: '1.0.0',
onStateChange(ctx, prev, next, paths) {
console.log(ctx.container?.$blac.name, prev, '→', next);
},
};
getPluginManager().install(myPlugin, { environment: 'development' });Subpath Exports
| Export | Contents |
| -------------------- | --------------------------------------------- |
| @blac/core | All core classes, registry, decorators, watch |
| @blac/core/plugins | Plugin system types and utilities |
| @blac/core/testing | Test utilities |
License
MIT
