@isograph/puchi
Puchi wraps @isograph/pico with callable sources and derived values. A derived computation records the sources and derived values it reads. The caller never passes a node to a read.
Isograph publishes main builds under the main npm tag. A release tag publishes the stable version.
npm install @isograph/puchi@main
const price = source(10);
const quantity = source(2);
const total = derived(() => price() * quantity());
const totals: number[] = [];
const stop = subscribe(total, (value) => totals.push(value));
total(); // 20
batch(() => {
price.set(12);
quantity.set(3);
});
total(); // 36
totals; // [36]
stop();
The listener receives 36 when the batch commits both writes. Subscribing does not deliver the initial 20. Calling total() gives the current value at either point.
Sources, derived values and subscriptions
function source<T>(initial: T, equal?: Equal<T>): Source<T>;
function derived<T>(
compute: (previous: T | undefined) => T,
equal?: Equal<T>,
): Derived<T>;
function batch<T>(fn: () => T): T;
function subscribe<T>(
node: Source<T> | Derived<T>,
listener: (value: T) => unknown,
onError?: (error: unknown) => unknown,
): () => void;
Source<T>is callable. For a handle namedprice,price()returns its value, and its readonlysetproperty accepts(value: T) => void. The read records a dependency when a computation is running. Callsetoutside computations and subscribers.Derived<T>is a callable reader without a setter. Reading it inside another computation records a dependency. A top-level read gets the current value. Usesubscribeto retain the computation and react to changed results.batch(fn)accepts a synchronous function and returns its result. The body may write sources and stop subscriptions. Reading a signal, subscribing, or nesting a batch throws. Puchi commits writes before returning or rethrowing an exception from the body. If the body returns a promise, the batch closes immediately. Writes after anawaitoccur in a later update.subscribe(node, listener, onError?)accepts either kind of reader. Start the subscription outside computations, subscribers and batches. The returned stop function is idempotent and may run in a batch. Call it outside computations and subscribers. A subscriber may read final values. Defer writes until the subscriber has returned.
Equality
type Equal<T> = (previous: T, next: T) => boolean;
Sources and derived values compare successive values with === by default. A source can take an equality function as its second argument. Each set compares its argument with the last value the source accepted, including earlier writes in the same batch. When the comparison returns true, the source keeps that value and skips the write. A derived value can take an equality function in the same position. An equal result keeps its previous identity and skips notifications to dependents. These comparisons assume that previously stored objects stay immutable. A source invokes its comparator from set. If that comparator throws, the exception reaches the caller before the value changes. A derived value invokes its comparator inside the computation and handles a thrown exception according to the chosen constructor.
const point = source({ x: 1, y: 2 }, (a, b) => a.x === b.x && a.y === b.y);
const x = derived(
() => ({ value: point().x }),
(a, b) => a.value === b.value,
);
A computation can receive its previous successful result, as in derived<number>((previous) => Math.max(previous ?? 0, price())), while Pico still has that result cached. It receives undefined on its first run, after a failed run, and after Pico disposes its cached value. Computations and equality functions run synchronously. Reads before a throw remain dependencies, so changing one of those inputs can make a failed computation succeed on its next run.
Errors
function derivedResult<T>(
compute: (previous: T | undefined) => T,
equal?: Equal<T>,
): Derived<Result<T>>;
function derivedOrNull<T>(
compute: (previous: T | undefined) => T,
equal?: Equal<T>,
): Derived<T | null>;
function derivedOrError<T>(
compute: (previous: T | undefined) => T,
equal?: Equal<T>,
): Derived<T | Err>;
function derivedOrSymbol<T>(
compute: (previous: T | undefined) => T,
equal?: Equal<T>,
): Derived<T | typeof FAILED>;
Each constructor accepts the same computation and optional equality function as derived. The computation must be synchronous and pure. It may read other Puchi signals, and its dependencies must form an acyclic graph. Its return type determines how callers can distinguish failure from a successful value. Result<T> exposes a readonly ok discriminator and either a readonly value: T when true or a readonly error: unknown when false.
derived(fn) catches an exception inside Pico. Reading the derived value rethrows the original exception to the reader. If a second Puchi computation reads that value, the second computation can catch the exception itself or use one of these constructors.
derivedOrNull(fn)returnsT | nulland returnsnullwhenfnthrows.derivedOrError(fn)returnsT | Err. AnErrextendsError. Its public constructor isnew Err(cause: unknown), its message isPuchi computation failed, and its inheritedcauseproperty holds that original value.derivedResult(fn)returns{ ok: true, value: T }or{ ok: false, error: unknown }. The tag distinguishes a failure even when a successful computation can returnnull, an error or a symbol.derivedOrSymbol(fn)returnsT | typeof FAILED. The exported constantFAILEDhas typeunique symbol. Compare the returned value to it by identity.
const text = source('broken');
const count = derivedResult(() => {
const n = Number(text());
if (!Number.isFinite(n)) throw new RangeError('Expected a number');
return n;
});
const first = count();
if (!first.ok) console.error(first.error);
text.set('3');
const next = count();
if (next.ok) console.log(next.value); // 3
subscribe(node, listener, onError) calls onError in a microtask if the listener throws or returns a rejected promise. Subscribing to a throwing derived sends a new computation failure to the same handler. Other subscribers continue to run. The default handler logs the error with console.error. If a custom error handler throws or rejects, Puchi logs that error too.