# TypeScript: @zwire/core

> Complete API reference for @zwire/core Layer 0 scopes, signals, effects, batching, ownership, resource, and devtools.

## Scopes

| Export | Signature | Description |
| :--- | :--- | :--- |
| `createScope` | `createScope(options?: ScopeOptions): ReactiveScope` | Creates an isolated reactive graph (`mode: 'client' \| 'ssr'`). In `'ssr'` mode, subscriptions and effects are silent no-ops and never retain listeners. |
| `createChildScope` | `createChildScope(parent, options?): ReactiveScope` | Creates an isolated graph that inherits the parent mode by default. Disposing the parent disposes all descendants. Disposing a child early detaches it from its parent. |
| `defaultScope` | `const defaultScope: ReactiveScope` | Ambient client-mode scope used by top-level helpers when no `scope` option is provided. |

```ts
interface ScopeOptions {
  mode?: 'client' | 'ssr';
}

interface ReactiveScope {
  readonly mode: ScopeMode;
  readonly disposed: boolean;
  atom<T>(initial: T, options?: AtomOptions<T>): Atom<T>;
  computed<T>(fn: (prev?: T) => T, options?: ComputedOptions<T>): Computed<T>;
  effect(fn: EffectFn, options?: EffectOptions): Unsubscribe;
  subscribe<T>(signal: ReadableSignal<T>, listener: Subscriber<T>): Unsubscribe;
  batch<R>(fn: () => R): R;
  untracked<R>(fn: () => R): R;
  dispose(): void;
}
```

## Signals, Effects, Batching & Lifecycle Hooks

Library signals implement `peek(): T`. It reads the current value, including any draft overlay, without making the caller depend on that signal. External get-only objects still satisfy `ReadableSignal<T>`.

| Export | Signature | Description |
| :--- | :--- | :--- |
| `atom` | `atom<T>(initial: T, options?: AtomOptions<T> & { scope?: ReactiveScope }): Atom<T>` | Creates a writable signal. `set(next)` treats functions as updaters `(prev) => next`; use `setValue(val)` to store function values literally. Safe with `undefined`, `NaN`, and `-0`/`+0` (`Object.is` default equality). |
| `computed` | `computed<T>(fn: (prev?: T) => T, options?: ComputedOptions<T> & { scope?: ReactiveScope }): Computed<T>` | Lazy derived signal with diamond glitch-freedom, early cutoff, cycle detection (`Error('Cycle')`), and GC-safe forward-only unwatched links. |
| `effect` | `effect(fn: EffectFn, options?: EffectOptions & { scope?: ReactiveScope }): Unsubscribe` | Auto-tracking side effect with `onCleanup(cb)` registration; automatically re-tracks dynamic dependencies and cleans up on re-run, manual unsubscribe, or `scope.dispose()`. |
| `subscribe` | `subscribe<T>(signal: ReadableSignal<T>, listener: Subscriber<T>, scope?: ReactiveScope): Unsubscribe` | Subscribes to changes on any `ReadableSignal<T>`. An explicit `scope.subscribe` subscription is released when either its owner or its source scope is disposed. |
| `batch` | `batch<R>(fn: () => R, scope?: ReactiveScope): R` | Coalesces writes into a single glitch-free flush upon outermost batch exit. Exception-safe: throwing subscribers never poison the queue or skip siblings. |
| `untracked` | `untracked<R>(fn: () => R, scope?: ReactiveScope): R` | Evaluates `fn` without recording dependencies in any enclosing `computed()` or `effect()`. |
| `shallowEqual` | `shallowEqual(a: unknown, b: unknown): boolean` | Zero-allocation shallow equality helper for primitives (`Object.is`), `Date`, `RegExp`, `Map`, `Set`, `.equals()` protocol, and plain objects (prototype + own string/symbol keys). |
| `watch` | `watch<T>(source: ReadableSignal<T>, cb: WatchCallback<T>, options?: WatchOptions<T>, scope?): Unsubscribe` | Observes `source` with `(next, prev, onCleanup)` and optional `{ immediate, equals }` cutoff; also available as `scope.watch(...)`. |
| `scoped` | `scoped<T>(factory: (scope: ReactiveScope) => T): Scoped<T>` | Defines state once at module level and instantiates it lazily per scope: `definition(scope?)` runs the factory on first use for that scope (untracked, detached from the calling owner) and returns the same instance afterwards. Omitting `scope` resolves `defaultScope`; a disposed scope throws. A child scope gets its own instance. |
| `createRoot` / `onCleanup` / `getOwner` / `runWithOwner` / `catchError` | Scoped lexical ownership tree primitives | Per-scope intrusive `Owner` tree (`scope._owner`) for automatic bottom-up LIFO cascade disposal of nested effects/subscriptions and scoped error boundaries without sacrificing `F_UNWATCHED` GC safety. |
| `NotReady` / `isNotReady` | `class NotReady extends Error` / `isNotReady(err): err is NotReady` | Suspense / async not-ready sentinel handled inside `computed` without firing `onError` (zero overhead on synchronous paths). |

> **Split Effects & Optional Scheduler:** `scope.effect(compute, apply, options?)` (and standalone `effect(...)`) supports 2-phase Solid 2.0 split effects (pure tracked `compute` with equality cutoff → untracked `apply` side effect). `createScope({ scheduler: 'sync' | 'microtask' | ((flush) => void) })` enables opt-in microtask auto-batching paired with `scope.flush()`.
> **Duck-typed `FieldSubscribable<T>` protocol:** `@zwire/core` exports `type FieldSubscribable<T>` (`subscribeField(selector, listener, options?)`), implemented by `ObjectStore` and `DeepStore` so all UI adapters route `useSelector` through `O(1)` fine-grained field subscriptions.
| `onWatched` | `onWatched(sig: ReadableSignal<any>, listener: WatchedHook): Unsubscribe` | Fires when `sig` transitions from 0 → ≥1 subscribers. May return a `CleanupFn` invoked on unwatch. |
| `onUnwatched` | `onUnwatched(sig: ReadableSignal<any>, listener: UnwatchedHook): Unsubscribe` | Fires when `sig` transitions from ≥1 → 0 subscribers. |

---

## Async reads with `@zwire/core/resource`

`resource(load, options?)` (`ResourceOptions<T>`: `{ scope?, initialValue?, lazy? }`) starts a request immediately (or defers the first load until first `.get()`, `.read()`, `.subscribe()`, or `.refetch()` when `lazy: true`). Signals read synchronously by `load(signal)` select its dependencies. A dependency change aborts the previous request and starts a new load. When `initialValue` is supplied, the resource starts in `refreshing` without throwing a Suspense promise; otherwise the first pending `read()` throws a promise for Suspense. Subsequent refreshes return the last successful value, and a failed request makes `read()` throw its error. Call `refetch()` to abort any in-flight request and re-run `load` while preserving reactive dependencies, or `mutate(next)` to locally update the resolved value immediately (aborting in-flight work). Subscribe to `state` to observe `pending`, `ready`, `refreshing`, `error`, and `disposed`. Use `isPending(target)` to check pending/refreshing status reactively and `resolve(fn, scope?)` to await `NotReady`-throwing reactive reads as a native `Promise<T>`. Calling `dispose()` or disposing the owning scope aborts active work. SSR scopes load once (unless `refetch()` is called explicitly).

```ts
import { createScope } from '@zwire/core';
import { resource } from '@zwire/core/resource';

const scope = createScope();
const page = scope.atom(1);
const content = resource(async (signal) => {
  const response = await fetch('/pages/' + page.get(), { signal });
  if (!response.ok) throw new Error(String(response.status));
  return response.text();
}, { scope });
```

## Graph snapshots with `@zwire/core/devtools`

Use `createInspectableScope(options?)` when you need graph snapshots. Pass `{ label }` when creating an atom or computed to name it. `scope.inspectGraph()` returns nodes with scope-local IDs, kinds, dependency and active subscriber IDs, and the ordered optimistic layer ID for each intent on an atom. An unwatched computed keeps its forward dependencies. Snapshots inspect links without evaluating user code. The recorder holds weak references so abandoned nodes can be collected.
