# Scopes, SSR & Ownership

> Per-request ReactiveScope and Rust Scope/SyncScope isolation, SSR mode, scoped() module definitions, Owner trees, and unwatched computed GC safety.

Every reactive primitive in `zwire` belongs to a **scope** (`ReactiveScope` in TypeScript; `Scope` or thread-safe `SyncScope` in Rust). There is no hidden module-level reactive graph.

## Per-request isolation & SSR mode

In browser single-page apps, top-level helpers (`atom`, `computed`, `effect`, `batch`) default to `defaultScope` for zero ceremony. On the server—or in tests and multi-tenant workers—create an isolated scope per request:

```ts
import { atom, computed, createScope } from '@zwire/core';

export function renderRequest(initialCount: number) {
  const scope = createScope({ mode: 'ssr' });
  try {
    const count = atom(initialCount, { scope });
    const doubled = computed(() => count.get() * 2, { scope });
    return `Count: ${doubled.get()}`;
  } finally {
    scope.dispose();
  }
}
```

In `'ssr'` mode, `effect()` and `subscribe()` become silent no-ops and never retain listener references, eliminating listener leaks on request-scoped graphs.

In Rust, every graph is explicitly scoped from the start:

```rust
use zwire::prelude::*;

let scope = Scope::ssr();
let count = scope.atom(21_i64);
let doubled = scope.computed(move |cx| cx.get(count) * 2);
assert_eq!(scope.get(doubled), 42);
```

## Module-level definitions with `scoped()`

Defining state at module scope without leaking it across requests is handled by `scoped(factory)`. The factory runs lazily on first access for a given scope—untracked and detached from the caller's owner—and returns the same instance on subsequent calls for that scope:

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

export const counterModel = scoped((scope) => {
  const count = scope.atom(0);
  const doubled = scope.computed(() => count.get() * 2);
  return { count, doubled };
});

const reqA = createScope({ mode: 'ssr' });
const reqB = createScope({ mode: 'ssr' });
counterModel(reqA).count.set(10);
// reqB is completely isolated: counterModel(reqB).count.get() === 0
```

All four UI framework adapters (`@zwire/react`, `@zwire/vue`, `@zwire/solid`, `@zwire/svelte`) provide `ScopeProvider` and `useScoped(counterModel)` so components bind to the nearest provider's scope automatically.

## Child scopes & lexical `Owner` trees

- **`createChildScope(parent)`**: Inherits `parent.mode` by default. Disposing the parent cascades disposal to all children; disposing a child early detaches it from its parent.
- **`createRoot` / `onCleanup` / `catchError`**: An intrusive per-scope `Owner` tree tracks nested effects and subscriptions and tears them down bottom-up in LIFO order when the root disposes.
- **Rust `Owner` / `SyncOwner`**: Mirrors the same lexical ownership model with RAII drop semantics and `WeakScope` / `WeakSyncScope` references inside scope-owned closures to prevent reference cycles.

## Unwatched `computed` GC safety

Unwatched `computed` nodes record dependencies using **forward-only links** (`comp._deps -> dep`), never inserting themselves into `dep._subs`. As soon as user code drops a reference to an unwatched `computed`, V8 and JavaScriptCore can reclaim it immediately without `dispose()` calls. Subscribing promotes links to bidirectional `dep._subs`; unsubscribing cascades `unlinkSub` back upstream.
