Skip to main content

@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 named price, price() returns its value, and its readonly set property accepts (value: T) => void. The read records a dependency when a computation is running. Call set outside 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. Use subscribe to 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 an await occur 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) returns T | null and returns null when fn throws.
  • derivedOrError(fn) returns T | Err. An Err extends Error. Its public constructor is new Err(cause: unknown), its message is Puchi computation failed, and its inherited cause property 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 return null, an error or a symbol.
  • derivedOrSymbol(fn) returns T | typeof FAILED. The exported constant FAILED has type unique 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.