Spektrum API Reference - v1.2.0
    Preparing search index...

    Interface Spektrum

    interface Spektrum {
        appState: State;
        appStateDelta: State;
        checkpoints: CheckpointView[];
        cursor: number;
        forks: ForkRecord[];
        history: HistoryEntry[];
        intents: Record<string, Element[]>;
        refs: Record<string, Element>;
        replaying: boolean;
        snapshots: Snapshot[];
        addAsync<T = any>(path: string, fn: () => Promise<T>): () => Promise<void>;
        addSystem(paths: string[], fn: SystemFn): () => void;
        addValue(path: string, value: number, id?: string): void;
        attempt<T = any>(
            name: string,
            fn: (signal: AbortSignal) => T,
        ): AttemptHandle<T>;
        bindDOM(root?: Element | Document): () => void;
        checkpoint(name: string, metadata?: any): void;
        computed(
            path: string,
            deps: string[],
            fn: (state: State) => any,
        ): () => void;
        defineFn(name: string, fn: BoundFn, meta?: FnMeta): void;
        describe(): SpektrumManifest;
        explain(opts?: { from?: number; to?: number }): ExplainedEntry[];
        findByIntent(name: string): Element[];
        onError(fn: ErrorHandler): () => void;
        onError(fn: null): void;
        onFork(fn: ForkHandler): () => void;
        onFork(fn: null): void;
        onRecord(fn: RecordHandler): () => void;
        onRecord(fn: null): void;
        refresh(path: string): Promise<void> | undefined;
        removeSystem(fn: SystemFn): boolean;
        replay(n: number): void;
        reset(): void;
        resetState(): void;
        run(): void;
        serialize(
            opts?: { includeForks?: boolean; includeHistory?: boolean },
        ): string;
        setValue(path: string, value: any, id?: string): void;
        tick(): void;
        trigger(id: string, path: string, value: number): void;
        watch(deps: string[], fn: SystemFn): () => void;
    }
    Index

    Properties

    appState: State

    Committed state. Direct mutation persists; setValue/trigger go through the delta.

    appStateDelta: State

    Pending writes for the next tick. Cleared at the start of each pass.

    checkpoints: CheckpointView[]

    Filtered view of history: every checkpoint entry with its history index appended. Allocates on read; for hot paths walk history directly and filter inline.

    cursor: number

    Index of the next history slot. Equals history.length unless scrubbed back via replay.

    forks: ForkRecord[]

    Tails of history dropped by mutate-while-scrubbed-back, oldest first. Each entry is a plain HistoryEntry[] plus the cursor it forked from and a timestamp; restore by re-applying via setValue / trigger. Capped by forkLimit.

    history: HistoryEntry[]

    Append-only log of recorded mutations.

    intents: Record<string, Element[]>

    Semantic element registry populated from data-intent="verb.noun". Each intent maps to the array of elements currently carrying it. Used by findByIntent() and surfaced in describe(). Lets agents locate UI by purpose ("checkout.submit") instead of by selector.

    refs: Record<string, Element>

    DOM handles registered via data-ref="name". Keyed by the ref name.

    replaying: boolean

    True while replay() is in flight.

    snapshots: Snapshot[]

    Replay-acceleration snapshots. Populated only when snapshotEvery is set.

    Methods

    • Async resource. Sets ${path}.loading / ${path}.error / ${path}.data as the promise progresses. Each phase records through setValue (so the round-trip lands in history; replay re-applies the values without re-issuing the fetch). Returns the run function for refetching; also indexed by path so refresh(path) works without retaining the handle.

      Type Parameters

      • T = any

      Parameters

      • path: string
      • fn: () => Promise<T>

      Returns () => Promise<void>

    • Subscribe a system to one or more paths. Returns an unsubscribe function.

      Parameters

      Returns () => void

    • Record an additive numeric change. Multiple addValues on the same path within one tick accumulate against the prior value. id defaults to add:${path}.

      Parameters

      • path: string
      • value: number
      • Optionalid: string

      Returns void

    • Speculative execution. Drops a checkpoint, runs fn, returns a handle the caller uses to commit (mark in history) or discard (rewind cursor). fn may return a value or a Promise — the caller awaits and decides.

      Type Parameters

      • T = any

      Parameters

      • name: string
      • fn: (signal: AbortSignal) => T

      Returns AttemptHandle<T>

    • Scan a DOM subtree for declarative bindings: {{expr}}, :attr="expr", data-if, data-each, data-key, data-model, data-ref, and data-action. Returns a destroy function that undoes every binding it set up.

      Parameters

      • Optionalroot: Element | Document

      Returns () => void

    • Record a tagged checkpoint into history. Pure marker — replay walks past it without state effect. Use to mark logically atomic boundaries (search complete, form submitted, wizard step done). Fires onRecord. Replay-to-checkpoint: spektrum.replay(spektrum.checkpoints.find(c => c.id === name).index + 1)

      Parameters

      • name: string
      • Optionalmetadata: any

      Returns void

    • First-class derived value. Primes synchronously from current state on registration (so registering after deps are populated still lands the initial value), then re-computes when any deps path changes. Writes to both state and delta so mid-tick reads see fresh values.

      Parameters

      • path: string
      • deps: string[]
      • fn: (state: State) => any

      Returns () => void

    • Register a named handler callable from data-fn attributes. Optional meta declares the handler's purpose, input, and output shape — surfaced via describe() so agents know what each verb does without reading the source.

      Parameters

      Returns void

    • Operational manifest of the running instance. One JSON object containing state, registered systems, fns and their schemas, named refs, registered intents, checkpoints, and history shape. Cheap. The single best first call for an agent orienting itself.

      Returns SpektrumManifest

    • Causal trace over a slice of history. Each entry is annotated with the systems whose subscriptions intersect its path. Useful for agents reconstructing why state moved. Note: subscriber set is the CURRENT registry, not a historical record of who actually fired.

      Parameters

      • Optionalopts: { from?: number; to?: number }

      Returns ExplainedEntry[]

    • Locate elements by their declared data-intent. Returns a copy so the caller can iterate without racing the registry.

      Parameters

      • name: string

      Returns Element[]

    • Subscribe an error handler. Called as (err, systemFn) whenever a subscribed system throws inside tick(). Multiple handlers may be registered; each call appends a subscriber and returns an unsubscribe handle. Without any handler, errors fall through to console.error. Pass null to clear every subscriber on this hook.

      Parameters

      Returns () => void

    • Parameters

      • fn: null

      Returns void

    • Subscribe a fork hook. Fires when a record() truncates history (mutate-while-scrubbed-back), receiving the captured ForkRecord. Descriptive: the truncate has already happened by the time the hook runs; the dropped entries are accessible on forks and via the hook argument. Multiple handlers may be registered; returns an unsubscribe handle. Pass null to clear all subscribers.

      Parameters

      Returns () => void

    • Parameters

      • fn: null

      Returns void

    • Subscribe a post-record hook. Called synchronously with every recorded HistoryEntry after it's been applied, snapshotted, and trimmed. Does not fire during replay() (replay re-applies without re-recording). Multiple handlers may be registered; returns an unsubscribe handle. Pass null to clear all subscribers.

      Parameters

      Returns () => void

    • Parameters

      • fn: null

      Returns void

    • Re-run the loader previously registered via addAsync(path, …). Returns the run Promise, or undefined when path was never registered. Lets callers refetch without retaining the handle.

      Parameters

      • path: string

      Returns Promise<void> | undefined

    • Detach the first system registered with fn. Returns true if removed.

      Parameters

      Returns boolean

    • Reset state and re-apply the first n recorded entries. O(K) when snapshotEvery is set.

      Parameters

      • n: number

      Returns void

    • Same as resetState(), but also clears systems registered via addSystem. Built-in fns and hook registrations survive. Warns when active systems are present at call time — silent detachment has bitten users; call resetState() instead when you only want to wipe state.

      Returns void

    • Wipe runtime state, refs, history, snapshots, forks. Preserves registered systems, defineFn entries, and hooks (onError, onRecord, onFork). Use this from library code that wants to clear state without nuking the host app's subscriptions.

      Returns void

    • rAF-driven tick pump. Reschedules itself every animation frame.

      Returns void

    • Serialize a portable snapshot of the instance. By default includes state, history, and cursor so a fresh instance can loadHistory it back to the same point. Pass { includeHistory: false } for a state-only snapshot; { includeForks: true } to also include preserved fork tails (debug-only; forks aren't replay-restored by loadHistory).

      Parameters

      • Optionalopts: { includeForks?: boolean; includeHistory?: boolean }

      Returns string

    • Record an absolute set. id defaults to set:${path} so the entry stays locatable in history and explain(). Pairs with addValue (same argument order) so authors can swap one for the other without re-ordering.

      Parameters

      • path: string
      • value: any
      • Optionalid: string

      Returns void

    • Run one simulation step, draining the delta to quiescence.

      Returns void

    • Parameters

      • id: string
      • path: string
      • value: number

      Returns void

      Use Spektrum.addValue — same semantics with a (path, value, id?) argument order that matches setValue. trigger (id-first) is the pre-1.0 spelling, kept as a thin alias for back-compat.

    • Conventional alias for addSystem. Same signature.

      Parameters

      Returns () => void