<!-- Generated by scripts/generate-docs.ts. Do not edit directly. -->

# effective-rsc documentation

Build Server Components and Server Functions with React, Schema, and Effect. These docs assume
familiarity with React and Effect; start with Getting started for a working application.

Define your application in `src/application.tsx`. Create its Pages, Layouts, Routes, and Server
Functions from one `Application.ersc()` instance, then export `ERSC.make(...)`.

Import authoring APIs from `effective-rsc` in server modules. Client Components use
`effective-rsc/client` for Server Function queries and streams. The package root cannot be imported
by Client Components.

## Getting started

Install Bun 1.4 or newer, then create an application with compatible dependencies and Tailwind:

```sh
bunx create-ersc-app my-application
cd my-application
bun run dev
```

Open `http://localhost:18193`. Omit the directory to use the interactive prompt; pass `--no-install`
to install dependencies yourself.

The application entry is `src/application.tsx`. It defines a root Layout containing the HTML
document, attaches Pages to Routes, and exports `ERSC.make(...)`. Other filenames are yours to choose.

### Styles and assets

Import CSS from the module that uses it. The starter's `src/styles.css` includes Tailwind; plain CSS
works too. Imported images, fonts, and media resolve to built asset URLs. Reference
`effective-rsc/types` in `src/environment.d.ts` so TypeScript recognizes these imports.
Files in `public/` are served from `/`.

### Production

```sh
bun run check
bun run build
bun run start
```

Both `ersc dev` and `ersc start` accept `--hostname` and `--port`. Flags override `HOST` and `PORT`;
defaults are `localhost` and `18193`.

### A minimal application

Define a root Layout and Page, then export the application with ERSC.make.

```tsx
import { Effect } from 'effect';
import { Application } from 'effective-rsc';

const ERSC = Application.ersc();

const RootLayout = ERSC.Layout.make({
  render: ({ children }) =>
    Effect.succeed(
      <html lang='en'>
        <body>{children}</body>
      </html>,
    ),
});

const HomePage = ERSC.Page.make({
  render: () => Effect.succeed(<h1>Hello from effective-rsc</h1>),
});

export default ERSC.make({
  routes: ERSC.Routes.make({ layout: RootLayout }).page('/', HomePage),
});
```

### More examples

- **[Importing styles](./docs/01-getting-started/20_styling.tsx)**: Import styles from the module that uses them.

## Manual installation

Create a Bun package and install the framework with its exact compatible peers:

```sh
mkdir my-effective-rsc-app
cd my-effective-rsc-app
bun init -y
bun add effective-rsc@0.1.4 \
  effect@4.0.0-rc.113 \
  @effect/platform-browser@4.0.0-rc.113 \
  @effect/platform-bun@4.0.0-rc.113 \
  react@19.3.0-canary-1d34f91d-20260909 \
  react-dom@19.3.0-canary-1d34f91d-20260909 \
  react-server-dom-rspack@0.1.0
bun add --dev \
  typescript@7.0.2 \
  @types/bun@^1.4.2 \
  @types/react@19.3.0 \
  @types/react-dom@19.3.0
```

Add the framework commands to `package.json`:

```json
{
  "type": "module",
  "scripts": {
    "dev": "ersc dev",
    "check": "tsc --noEmit",
    "build": "ersc build",
    "start": "ersc start"
  }
}
```

Create `tsconfig.json`:

```json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "jsx": "react-jsx",
    "noEmit": true,
    "strict": true,
    "erasableSyntaxOnly": true,
    "exactOptionalPropertyTypes": true,
    "noUncheckedIndexedAccess": true,
    "noUncheckedSideEffectImports": true,
    "types": ["bun", "react", "react-dom", "react/canary"],
    "lib": ["ESNext", "DOM", "DOM.Iterable"]
  },
  "include": ["src"]
}
```

Create `src/environment.d.ts` so TypeScript accepts stylesheet and asset imports:

```ts
/// <reference types="effective-rsc/types" />
```

Create `src/application.tsx` using the minimal application example, then run `bun run dev`.
To add Tailwind, install `tailwindcss@4.3.3` as a dev dependency and put
`@import 'tailwindcss';` in an imported stylesheet.

Keep the framework and its peers on a compatible release set when upgrading; the scaffold template
ships that set together.

## Guides

Familiarity with React Server Components and Effect is assumed.

## Server Functions

Export `ERSC.ServerFn.make({ input, handler })` from a module marked `'use server'`. `input` is a
Schema; `handler` returns an Effect and can use application services. Callers pass the Schema's
encoded type, and the handler receives its decoded type. Let the Schema infer handler parameters.

### Forms and mutations

Use `Schema.fromFormData(...)` for form input and return `void` to pass a function directly to
`<form action>`. For feedback with `useActionState`, declare
`input: [StateSchema, FormSchema]` and `handler: (previousState, form) => ...`.
Pass the native reference to `useActionState` to retain submission without JavaScript.

Direct browser calls and form actions refresh the current route after execution. The result can
arrive before suspended content in that refresh finishes.

### Queries and streams

Import `ServerFn` from `effective-rsc/client` to query a Server Function or consume its stream.
`ServerFn.query(reference)(...args)` retrieves the function's result as an Effect;
`ServerFn.queryAtom(reference)` exposes it as an atom for `@effect/atom-react`.
The atom helper cancels its previous request when called again.

Return an Effect `Stream` from the server handler to send chunks as they become available.
Read it with `ServerFn.stream(reference)` or display its latest chunk with
`ServerFn.streamAtom(reference)`. Both expose chunks as they arrive, so client code can process or
display an ongoing result.

### Outcomes and failures

Return expected outcomes, such as unavailable data or a declined operation, as a tagged success
value. The handler and any returned Stream must have a `never` error channel.
Framework failures reject direct-call Promises; the client helpers expose `ServerFnError` in their
Effect or Stream error channel. Use `Effect.catchTag` or inspect an atom's `AsyncResult` cause.

- **[Creating the Server Function authoring module](./docs/02-guides/01-server-functions/10_ersc.ts)**
- **[Defining a Server Function](./docs/02-guides/01-server-functions/20_follow-author.ts)**: ERSC decodes FormData before running the Effect handler.
- **[Rendering a direct form action](./docs/02-guides/01-server-functions/30_follow-author-button.tsx)**: A FormData Server Function can be passed directly to form action.
- **[Composing the Server Function application](./docs/02-guides/01-server-functions/40_application.tsx)**
- **[Defining a stateful form action](./docs/02-guides/01-server-functions/50_greet.ts)**: A schema list decodes React's previous state and submitted FormData separately.
- **[Rendering a stateful form](./docs/02-guides/01-server-functions/60_greeting-form.tsx)**: Pass the native reference to useActionState so React also owns progressive form submission.
- **[Modelling an expected outcome](./docs/02-guides/01-server-functions/70_lookup-author.ts)**: The handler's Effect error channel is `never`, so expected outcomes belong in its success value.
- **[Reading a Server Function from the browser](./docs/02-guides/01-server-functions/80_author-preview.tsx)**: `queryAtom` exposes the author lookup as atom state, with typed results and `ServerFnError` failures.

## Services

1. Declare application services with `Application.ersc<Catalog | Mailer>()`.
2. Use those services in Page, Layout, Component, and Server Function Effects.
3. Provide their Layer once with `ERSC.make({ routes, layer })`.

The Layer is built at startup and released at shutdown. Use middleware to provide request-local
services such as the current user.

- **[An application-owned service](./docs/02-guides/02-services/10_catalog.ts)**: ERSC consumes the service contract and Layer; their construction is ordinary Effect code.
- **[Providing application services](./docs/02-guides/02-services/20_application.tsx)**: Declare the service union on ERSC and provide its Layer once at ERSC.make.

## Routing, parameters, and loading

Attach a Page with `routes.page(path, page)`. Group routes under a Layout and optional Loading
fallback, then nest them with `routes.mount(prefix, childRoutes)`. Each operation returns new Routes;
mounting preserves the child's layouts, loading fallbacks, and middleware.

Define path parameters in a Page's `params` Schema. Its encoded keys must match the route's
`:parameters` and accept strings; `render` receives decoded values. Mount prefixes cannot contain
parameters. Unmatched routes and rejected path parameters return `404`.

The root Routes needs a Layout containing the HTML document and at least one Page. A Loading
fallback is synchronous and renders below its Layout while descendants suspend.

- **[Creating one routing authoring module](./docs/02-guides/03-routing/10_ersc.ts)**
- **[Layouts and loading fallbacks](./docs/02-guides/03-routing/10_layouts.tsx)**: Layout is Effectful; Loading is synchronous and service-free.
- **[Static and parameterized Pages](./docs/02-guides/03-routing/20_pages.tsx)**: A Page Schema decodes captured path strings for render.
- **[Composing and mounting Routes](./docs/02-guides/03-routing/30_routes.tsx)**: Mounting retains the child graph's Layout and Loading ancestry.
- **[Closing the route graph](./docs/02-guides/03-routing/40_application.ts)**

## Middleware

Create middleware with `ERSC.Middleware.make(handler)`, then derive an authoring view with
`ERSC.withMiddleware(middleware)`. Routes and Server Functions created from that view run through
the middleware.

Declare request services with `ERSC.Middleware.make<{ provides: CurrentUser }>(handler)` and provide
them to the downstream Effect. Pages, Layouts, and Components created from the derived view can
require those services when rendered under its Routes or Server Functions. A derived view belongs
to the same application.

Chain `withMiddleware` in request order; responses unwind in reverse. For server-wide policy,
including assets and unmatched requests, register native global Effect HTTP middleware through the
application Layer.

- **[Defining an authenticated view](./docs/02-guides/04-middleware/10_auth.ts)**: Middleware can short-circuit a request and provide typed services downstream.
- **[Consuming middleware data in a Page](./docs/02-guides/04-middleware/20_account-page.tsx)**
- **[Consuming middleware data in a Server Function](./docs/02-guides/04-middleware/30_update-profile.ts)**
- **[Activating middleware with Routes](./docs/02-guides/04-middleware/40_application.tsx)**

## Userland HTTP

Register native Effect `HttpRouter`, `HttpApi`, or RPC layers in the Layer passed to
`ERSC.make({ layer })`. They share the framework's HTTP server, application services, and shutdown
scope.

Register routes that require application services with `HttpRouter.use`, then retain those services
with `Layer.provideMerge`.

Native global middleware belongs in the same application Layer. It observes Page requests, Server
Function requests, userland HTTP, assets, and unmatched requests. ERSC-scoped middleware has narrower
reach.

- **[Composing ERSC and userland HTTP](./docs/02-guides/05-http/10_application-layer.tsx)**: ERSC concerns and native HTTP routes share one application Layer.

## Deploying to Vercel

Deploy to Vercel with Bun 1.4+. The `@ersc/vercel` version must match the installed `effective-rsc` version.

```sh
bun add --dev @ersc/vercel
```

Set the build script in `package.json`:

```json
{
  "scripts": {
    "build": "ersc build --adapter @ersc/vercel"
  }
}
```

Commit `bun.lock`, connect your GitHub repository in Vercel, and set:

| Setting          | Value                           |
| ---------------- | ------------------------------- |
| Framework Preset | Other                           |
| Root Directory   | Application directory           |
| Install Command  | `bun install --frozen-lockfile` |
| Build Command    | `bun run --bun build`           |
| Output Directory | Leave the override disabled     |

Add your environment variables and deploy. The adapter generates `.vercel/output/`; no custom
server entry or `vercel.json` is needed.

For [monorepos](https://vercel.com/docs/monorepos/monorepo-faq), enable **Include source files outside
of the Root Directory in the Build Step**. With Turborepo, use
`bun run --bun turbo run build --filter=your-app` to build the app and its workspace dependencies.

## Advanced

Application behavior to account for when managing resources, navigation, mutations, and deployment.
ERSC is experimental; each guide calls out relevant limitations.

## Resources and cancellation

The Layer passed to `ERSC.make` is built once at startup and released at shutdown. Use it for
application services; use middleware and scoped Effects for request-local resources.

Page, Layout, Component, and Server Function Effects run with their request. Response completion,
disconnection, or interruption closes the request and finalizes its resources. Give background work
that must outlive the response an explicit application owner.

Interrupting a `ServerFn.query` Effect cancels its pending invocation. A `ServerFn.stream` consumer
owns the browser request until it completes or is interrupted. Atom helpers cancel an earlier run
when invoked again.

Returned Effect Streams also belong to the request. Cancellation waits for their asynchronous
finalizers before releasing request resources, including when the client stops consuming a stream.

In development, a successful rebuild interrupts the old application's requests before replacing its
services. An interrupted Server Function is not automatically retried.

## Client navigation

Use ordinary `<a href>` links. ERSC uses the Navigation API and `NavigationPrecommitController`
when available. Other browsers use full-page navigation while Client Components, Server Functions,
and HMR still work. Without JavaScript, links and native forms remain usable.

The shared Layout stays mounted across client navigation. URL, history, focus, and default scroll
advance when the destination first appears; suspended content can continue streaming afterward.
The current page stays visible while its replacement loads. Later render failures go to React Error
Boundaries.

Back/Forward can reuse completed route trees. New navigations fetch fresh content, and mutations
invalidate that history cache. Redirects follow their destination; responses that cannot be rendered
as a route fall back to full-document navigation.

**Scroll limitation:** history restoration may clamp a saved position against a Loading fallback
and keep that position after content arrives. Stream-aware restoration is not implemented.

### React View Transitions

Add React `<ViewTransition>` boundaries and CSS in your application. ERSC supplies these additive
types when it first publishes a navigation or refresh:

| Event                              | Types                                                                                |
| ---------------------------------- | ------------------------------------------------------------------------------------ |
| Routed navigation                  | `navigation`, plus `navigation-push`, `navigation-replace`, or `navigation-traverse` |
| Push or forward history traversal  | `navigation-forward`                                                                 |
| Backward history traversal         | `navigation-backward`                                                                |
| Browser-provided visual transition | `navigation-ua-visual-transition`                                                    |
| Mutation refresh                   | `server-function`                                                                    |
| HMR refresh                        | `hmr-refresh`                                                                        |

Replace has no direction type. Traversal adds one only when history indices establish a direction.
Choose whether to animate HMR or browser-provided transitions. Suspense reveals that arrive later
need their own boundaries and styling; they do not inherit these types.

Add application types to a link:

```tsx
<a href='/photos/2' data-ersc-transition-types='photo-next'>
  Next photo
</a>
```

Separate multiple types with spaces. They supplement built-in types for that push or replace and
are not replayed on Back/Forward. `navigation`, `navigation-*`, `server-function`, and `hmr-refresh`
are reserved and ignored in the attribute.

## Results and route refresh

| Invocation                                  | Result                             | Route behavior              |
| ------------------------------------------- | ---------------------------------- | --------------------------- |
| Direct browser call or hydrated form action | Promise or React action state      | Refreshes the current route |
| Form submission without JavaScript          | New document with React form state | Renders the submitted route |
| `ServerFn.query` / `queryAtom`              | Effect or atom result              | No refresh                  |
| `ServerFn.stream` / `streamAtom`            | Stream or latest chunk             | No refresh                  |

For hydrated mutations, the result settles independently of suspended refresh content. Calls may
execute concurrently. ERSC applies a response tree only while it still belongs to the current page;
otherwise it fetches a fresh current-page tree. A completed mutation response invalidates cached
Back/Forward trees, including when its result describes an expected application failure.

Handle expected outcomes in the returned value. Input-validation and server-defect failures reject
the hydrated invocation, but its response can still refresh the route. A route-render failure uses
React's Error Boundaries and does not replace an already completed function result.

Without JavaScript, native forms receive a complete document with updated form state. Invalid input
returns `400`; an unhandled server failure follows the server error response path. Passing the native
reference to `useActionState` preserves this form behavior. Extra arguments bound inside a Client
Component currently do not work without JavaScript; bind them on the server when progressive
submission is required.

## Production startup

Run `ersc build`, then `ersc start`. Deploy `.ersc/`, `public/`, and runtime dependencies with
Bun 1.4 or newer. Flags `--hostname` and `--port` override `HOST` and `PORT`; defaults are
`localhost` and `18193`.

For a custom Bun entry, await `start({ root, hostname, port })` from `effective-rsc/server`.
All options are required; `root` is the application directory. The Promise resolves when ready.
Startup failures reject and exit. ERSC handles signals and cleanup; do not wrap it in
`BunRuntime.runMain`.

### Deployment adapters

`ersc build --adapter <package>` packages the build using an installed adapter. It does not upload;
follow the deployment provider's setup. Omitting `--adapter` skips packaging and leaves any previous
adapter output in place.

Adapter authors can use the [framework build contract](https://github.com/nikhilsnayak/effective-rsc/blob/main/docs/architecture/build.md#deployment-adapters).

### Server entry

Save this as `server.ts` in the application root and run it with `bun server.ts` after building.

```ts
import { start } from 'effective-rsc/server';

await start({
  hostname: 'localhost',
  port: 18193,
  root: import.meta.dir,
});
```

## API reference

| Import                 | Use                                                      |
| ---------------------- | -------------------------------------------------------- |
| `effective-rsc`        | `Application` and server authoring factories             |
| `effective-rsc/client` | `ServerFn` query/stream helpers and error types          |
| `effective-rsc/server` | Custom Bun startup with `start`                          |
| `effective-rsc/build`  | Deployment adapter types                                 |
| `effective-rsc/types`  | TypeScript declarations for stylesheet and asset imports |

`Application.ersc<Services>()` returns `Page`, `Layout`, `Loading`, `Component`, `Middleware`,
`Routes`, `ServerFn`, `withMiddleware`, and `make`. Create values from one instance and its derived
views. The package root is server-only; importing it from a Client Component throws.

## Application

`Application.ersc<Services>()` creates the application's authoring API. Declare the application
service union in `Services`, or omit it when no services are needed. Create all application values
from this instance or its `withMiddleware` views.

`ERSC.make({ routes, layer })` returns the application definition to export from
`src/application.tsx`. `layer` must provide the declared services and may register native Effect
HTTP routes. It is optional when `Services` is `never` and is built once at startup.

## Page

`ERSC.Page.make({ render })` defines a static Page. Add `params` to decode path parameters:
`ERSC.Page.make({ params, render })`. Attach it with `routes.page(path, page)`.

`render` returns an Effect producing React output. Its service requirements must be available from
the application or the Page's middleware view. Parameter Schemas must encode exactly the path's
parameter names as strings; `render({ params })` receives their decoded values.

Rejected parameters return `404` on page loads and navigation. During a mutation refresh, rejection
is a React render error and preserves the completed Server Function result.

## Layout

`ERSC.Layout.make({ render })` creates a wrapper whose `render({ children })` returns an Effect
producing React output. It can use application and middleware services. The root Layout must include
`<html>` and `<body>`; nested Layouts wrap their child routes.

## Loading

`ERSC.Loading.make({ render })` creates a Suspense fallback for a Routes scope. `render` returns
React output synchronously and cannot require services. Each scope accepts at most one Loading value,
rendered below its Layout.

## Component

`ERSC.Component.make({ render })` creates an Effectful Server Component. Props are inferred from
`render`; required services must be available from the application or middleware. Use the component
within your application's server-rendered tree.

- **[An Effectful Server Component](./docs/04-api-reference/05-component/10_component.tsx)**: Use Effect to render a Server Component with typed props.

## Middleware

`ERSC.Middleware.make(handler)` accepts an Effect HTTP middleware.
`ERSC.withMiddleware(middleware)` returns a view of the same application with that middleware attached.

Use `ERSC.Middleware.make<{ provides: CurrentUser }>(handler)` to declare a service provided to the
downstream Effect; use a union for multiple services. All factories on the derived view can use those
services. Routes and ServerFn activate middleware; Page, Layout, and Component consume it while
rendered in that scope. Rendering outside a required scope throws `TypeError`.

Chain middleware in request order. Ancestors run first; response transformations unwind in reverse.
Repeating a middleware in one resolved route chain is rejected. Shared middleware across mounted
scopes runs once.

### Reach

| Request                             | Route middleware               | Server Function middleware | Global middleware |
| ----------------------------------- | ------------------------------ | -------------------------- | ----------------- |
| Page load or navigation             | Matched route chain            | No                         | Yes               |
| Hydrated or progressive mutation    | Remaining chain around refresh | Function chain             | Yes               |
| Query or stream helper              | No                             | Function chain             | Yes               |
| User HTTP, assets, unmatched routes | No                             | No                         | Yes               |

A mutation refresh skips middleware already active for its Server Function. Register native global
Effect HTTP middleware through the application Layer for server-wide policy.

## Routes

`ERSC.Routes.make({ layout?, loading? })` creates a route scope. Its methods return new Routes:

- `page(path, page)` adds a Page at an absolute Effect HTTP pattern. Parameter Schema keys must
  exactly match path parameters.
- `mount(prefix, childRoutes)` mounts non-empty Routes from the same application below an absolute,
  parameter-free prefix, retaining Layout, Loading, and middleware ancestry.

Conflicting matcher shapes and the `/_ersc` namespace are rejected. The root Routes must have a
Layout and at least one Page. Routes created from a `withMiddleware` view activate that middleware.

## ServerFn

Export `ERSC.ServerFn.make({ input, handler })` from a `'use server'` module. It creates a native
React Server Function: callers pass encoded Schema values; the Effect handler receives decoded
values and may require application or middleware services. `input` is optional; omit it for a
Server Function that takes no arguments. Direct server invocation throws.

### Arguments

| `input`              | Caller and handler arguments      |
| -------------------- | --------------------------------- |
| One Schema           | One argument                      |
| Readonly schema list | One argument per Schema, in order |
| Omitted or `[]`      | No arguments                      |

An Array or Tuple Schema describes one argument. Inline schema lists infer tuples without
`as const`; let the Schema infer handler parameters.

Omitted `input` and `[]` both reject extra arguments, including FormData supplied by a form.

```ts
const followAuthor = ERSC.ServerFn.make({
  input: Schema.Struct({ authorId: Schema.NonEmptyString }),
  handler: ({ authorId }) => Effect.succeed({ authorId, following: true }),
});
```

### Forms

To use `<form action>`, decode FormData and return `void`:

```tsx
const followAuthorForm = ERSC.ServerFn.make({
  input: Schema.fromFormData(Schema.Struct({ authorId: Schema.NonEmptyString })),
  handler: ({ authorId }) => Effect.logInfo('Followed author', { authorId }),
});

<form action={followAuthorForm}>
  <input name='authorId' />
  <button type='submit'>Follow</button>
</form>;
```

For `useActionState`, declare previous state and FormData as positional arguments:

```ts
const greet = ERSC.ServerFn.make({
  input: [
    Schema.Struct({ message: Schema.String }),
    Schema.fromFormData(Schema.Struct({ name: Schema.NonEmptyString })),
  ],
  handler: (_previousState, { name }) => Effect.succeed({ message: `Hello, ${name}` }),
});
```

Pass `greet` to `useActionState(greet, { message: '' })`, and its returned action to the form.
Previous state is client input; never use it as authority for authorization or stored application
state. Native `.bind` can prefill leading arguments. Bind on the server when the form must work
without JavaScript; client-created bindings currently do not progressively enhance.

### Outcomes and errors

The handler's Effect error channel must be `never`. Return expected application outcomes in the
success value, for example a tagged union. Client references resolve `Promise<Output>` or reject
with a `ServerFnError`, exported from `effective-rsc/client`:

| Error                    | Meaning                                        | Data                                                        |
| ------------------------ | ---------------------------------------------- | ----------------------------------------------------------- |
| `ServerFnInputError`     | Arguments failed Schema validation             | `detail.message`                                            |
| `ServerFnDefect`         | Unhandled server failure                       | `digest` matching the server log; development error details |
| `ServerFnTransportError` | Encoding, request, or response decoding failed | `detail`, when available                                    |

Production redacts server failure details. Query and stream helpers expose these errors in their
Effect or Stream error channel; atom helpers expose them through `AsyncResult`.

### Streaming output

When the handler returns an Effect `Stream`, the client Promise resolves a `ReadableStream` of its
chunks. Consume it with `ServerFn.stream` or `streamAtom`. A failure during streaming reaches those
helpers as a `ServerFnDefect` when React supplies a server digest; transport failures remain
`ServerFnTransportError`.

```ts
const readTicks = ERSC.ServerFn.make({
  input: Schema.Struct({ count: Schema.Finite }),
  handler: ({ count }) => Effect.succeed(Stream.range(1, count)),
});
```

Every returned Stream must have a `never` error channel and require only available services.
All return alternatives must be Streams or all must be non-stream values. Unions of valid Streams
combine their chunk types; `Stream<A> | null` is rejected. Return `Stream.empty` for no chunks.
A streaming function cannot be a direct form action, which requires `Promise<void>`.

Rate-limit producers: Flight does not apply consumer backpressure, so faster producers can buffer
on the server and client. Cancellation awaits the returned Stream's finalizers before releasing
request resources; see Resources and cancellation.

Functions created from a middleware view activate that middleware for mutations and queries.
Browser requests require an Origin matching the application host and are limited to 10 MiB.

## Client queries and streams

Import `ServerFn` from `effective-rsc/client` to query a Server Function for a value or consume its
stream. The helpers expose results as Effects, Streams, or atoms, with typed failures and cancellation.

| Helper                    | Server return type | Client result                                                                               |
| ------------------------- | ------------------ | ------------------------------------------------------------------------------------------- |
| `ServerFn.query(fn)`      | Non-stream value   | Function returning `Effect<Output, ServerFnError>`                                          |
| `ServerFn.queryAtom(fn)`  | Non-stream value   | `Atom.AtomResultFn<Args, Output, ServerFnError>`                                            |
| `ServerFn.stream(fn)`     | Effect `Stream<A>` | Function returning `Stream<A, ServerFnError>`                                               |
| `ServerFn.streamAtom(fn)` | Effect `Stream<A>` | Atom of the latest chunk; may also fail with `Cause.NoSuchElementError` for an empty stream |

Function helpers take the original encoded arguments: `ServerFn.query(lookupAuthor)({ authorId })`.
Atom setters take an argument tuple: `lookup([{ authorId }])`.

Value helpers reject any return union containing a `ReadableStream`. Stream helpers require every
return alternative to be a `ReadableStream`, as exposed by a streaming Server Function reference.

Queries and streams do not trigger a route refresh. For React forms and `useActionState`, pass the
native Server Function reference directly.

### Cancellation and atoms

Interrupting a query Effect cancels its pending invocation. Streams emit values immediately and
complete only after both the returned stream and its server response finish. Until then, interruption
or early termination cancels unfinished work, including pending Server Components in received values.
A late transport failure fails the stream; nested React render errors remain local to their content.
Completion means delivery finished, not that the UI rendered successfully.

Each atom helper supersedes its own in-flight run when called again; `Atom.Interrupt` cancels it
explicitly. `streamAtom` publishes values as they arrive and stays `waiting` until the full response
finishes. Plain query calls run independently.

With `@effect/atom-react`, provide a `RegistryProvider` above consumers; a Client Component wrapper
can be rendered by the root Layout. A nested provider gives its subtree a separate registry.
`useAtomInitialValues` can seed values. Shared atom instances share state within that registry; create
separate instances when reads should be independent.

Read successes and failure causes from `AsyncResult`. `streamAtom` keeps the latest chunk;
`Atom.pull` can accumulate chunks from an Effect Stream. Pulling does not add network backpressure.
