UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

3,786 lines • 216 kB
// How to build the things this framework has, in the shape that works.
//
// The other half of this server, and the more useful one. Introspection answers
// "what did my build do"; this answers "how do I do X here", which is the
// question an agent actually has — and the one it otherwise answers from Next
// and React habits that produce code which looks right and is not.
//
// Long-form on purpose. AGENTS.md has to be short enough to sit in context for
// every turn, so it can only say the rule. These are fetched when the topic
// comes up, so they can afford the working example and the caveat under it.
//
// Every snippet here is the recommended spelling from the guides, not a
// paraphrase. When a guide changes, this changes with it — a recipe that has
// drifted is worse than no recipe, because it is followed with confidence.
const RECIPES = [
    {
        topic: 'forms',
        summary: 'Submitting to a server action, with pending state and field errors. Uncontrolled by default; read with error() and field()',
        body: `THE RULE: forms are UNCONTROLLED. Inputs keep their value in the DOM,
an initial value is defaultValue, the action reads FormData. Do NOT write
useState + value/onChange per input, and do NOT reach for TanStack Form.

ONE WAY TO READ A FORM - two words, the same everywhere:
  error('title')  the field's error, or undefined. !!error('title') is invalid.
                  Nested fields are paths: error('address.city'), error('items[0].name').
                  The names are TYPED from the action's input (a stub's typed
                  parameter, or createActionClient().input(schema)), so
                  error('titel') fails tsc: Field names. Open when the action
                  says nothing (a FormData function, a url, a cast). A component
                  below the form types its prop with FieldNamesOf<typeof action>
                  from '@rsc-kit/core/form'. A WRAPPER you write around a stub
                  (a function of a FormData) declares its fields on its
                  parameter: (form: FormFields<'id' | 'name'>) - then error()
                  is closed to them. A TEAM-SCOPED stub func(ctx, team, in) is a
                  form's action as stub.bind(null, team): the form fills the
                  struct after the bound args, and the names stay - but bind
                  into a const first, inline bind() loses them. A stub whose
                  parameters are plain strings has no struct for a form to fill:
                  wrap it. A form that posts NOTHING (values in React state)
                  names its fields on the form: <Form fields={['size']}>.
  formError       the refusal NOT about a field (serverError - a 402/409 - or a
                  form-level validation message), or undefined. Render it as
                  {formError && <p role="alert">{formError}</p>}; do not keep it
                  from onError in your own state.
  field('title')  a binding to spread - ONLY for a field whose value the UI must
                  hold (a character count, a live preview, a control with no
                  native element). Everything else stays uncontrolled.
Beside them: pending, dirty, succeeded, recentlySucceeded, reset(), clearErrors(),
and data (what is being submitted).

There is nothing else. No errors map, no fieldState, no useFormValues, no
useFormStatus - those were removed; if you see them in old code, convert them.

Use <Form>. It takes the server action itself, not a url.

\`\`\`tsx
'use client'
import Form from '@rsc-kit/core/form'
import { createPost } from '../actions'

export function NewPost() {
  return (
    <Form action={createPost} schema={schema}>
      {({ pending, error }) => (
        <>
          <input name="title" />
          {error('title') && <p>{error('title')}</p>}
          <button disabled={pending}>Save</button>
        </>
      )}
    </Form>
  )
}
\`\`\`

In a child component, useForm() returns EXACTLY what the render prop gets, so
the code is the same:

\`\`\`tsx
import { useForm } from '@rsc-kit/core/form'

function SubmitButton() {
  const { pending } = useForm()
  return <button disabled={pending}>Save</button>
}
\`\`\`

(Not React's useFormStatus - a different hook with a different answer.)

Passing \`schema\` validates in the browser BEFORE the action is called, so a
mistake costs no round trip. It is a courtesy, never a control: the action is a
public endpoint reachable without your form, so the server must check too.

A BACKEND ACTION WITH A SCHEMA needs no \`schema\` prop: when rsc-host.json has
"schemas": { "Signup.store": { schema, messages } }, <Form action={store}> checks
it in the browser with the backend's own messages, on blur and submit (Laravel:
a FormRequest's schema(); Go: reg.CheckInBrowser(name), from the struct's
validate tags). Loaded lazily by the action's id - nothing in the
page, works for a client-imported or a server-passed action - and a blank
optional field is not posted, since the backend's rules read "" as a value.

A schema on the server (\`client.input(schema)\`) does NOT give you client-side
validation. Pass it to the form as well — the same schema is fine.

A field is checked when it is LEFT, not as it is typed (the form listens for
focusout, so uncontrolled fields are covered), and on submit. So error() has
nothing for a field nobody reached - there is no "touched" to check first.

CHECKED BY THE SERVER BEFORE SUBMIT: on <Form action={a} precognitive>, when a
field is left having CHANGED, the form also asks the action - marked as a check,
so its guards and validation run and its body does NOT. OFF without the prop:
the server then hears only the submit and validate() (a schema still checks on
blur - it is the browser's). A check passes the guards, so a throttle counts it;
let checks through in the limiter (Laravel: $request->isPrecognitive() ?
Limit::none() : Limit::perMinute(5)->by($request->ip())). It asks only an action that can stop before its body: createActionClient() with
.input(schema), or a backend function listed in rsc-host.json "validates"
(Laravel: one whose first parameter is a FormRequest - Precognition's rules,
filtered to the field). A plain "use server" function is never called to check.
For a wizard step or any other moment, the render prop / useForm() has:
  validate('email', 'name')  ask now about these (none = every field); resolves
                             true when they pass. '*' is one segment: 'items.*.sku'.
  validating                 true while a check is out
  valid('email')             a check passed and the field is unchanged since
A wizard keeps every step's fields in the form (hidden, not unmounted) and does
\`onClick={async () => (await validate('email')) && setStep(2)}\`. Checking as
it is typed is validate() in onChange - debounce it yourself.

STOPPING BOTS: put <Honeypot /> (import { Honeypot } from '@rsc-kit/core/honeypot')
inside any form that posts to a server action - <Form>, a plain <form action>,
with or without JS, a "use server" function or a Laravel/Go action. A post with
its hidden field filled is answered as a success and dropped BEFORE the action
runs; the trap is stripped otherwise, so the action never sees it. The field is
'homepage'; <Honeypot name="website" /> renames it. Forms without it are not
checked. Crude spam only - add a rate limit (Laravel: throttle middleware on
the action class) for a form worth attacking. Do NOT hand-roll a hidden input
and check it in the action.

Values are uncontrolled, so an initial one is React's own \`defaultValue\`. A
refused submit keeps what was typed, because the DOM kept it.

A repeated name is an array. With one selected it is a string, which no
z.array() accepts - so for anything that is a list by nature end the name in
\`[]\` and it is always an array, brackets dropped from the key:

\`\`\`tsx
<input type="checkbox" name="tags[]" value="react" />   // -> { tags: ['react'] }
\`\`\`

Names that describe a shape build it: \`address.city\` nests, and
\`items[0].name\` (or \`items[0][name]\`) makes an array of objects. That is
the shape the schema was written against, and error() takes the same path.

Binding a field - a rich editor, a select, a value read as it is typed:

\`\`\`tsx
<Form action={save} defaultValues={{ body: '' }}>
  {({ field, error }) => (
    <>
      <Editor {...field('body')} />
      <span>{field('body').value.length}/100</span>
      {error('body') && <p>{error('body')}</p>}
    </>
  )}
</Form>
\`\`\`

field() gives { name, value, onChange, onBlur } - react-hook-form Controller's
four. onChange takes a DOM event OR a bare value. A bound field is still an
ordinary named input, so it arrives in FormData with the rest.

shadcn Field components, with the two words:

\`\`\`tsx
<Field data-invalid={!!error('title')}>
  <FieldLabel htmlFor="title">Title</FieldLabel>
  <Input id="title" name="title" aria-invalid={!!error('title')} />
  <FieldError>{error('title')}</FieldError>
</Field>
\`\`\`

FieldError renders its children and renders nothing when there are none.

A bound field re-renders the form. For a LARGE controlled form, put the field in
its own component and use useField - the same two words for one name, and it
re-renders that component and nothing else:

\`\`\`tsx
function Title() {
  const { field, error } = useField('title')
  return <Input {...field} aria-invalid={!!error} />
}
\`\`\`

A preview or summary reads a bound value the same way:
\`const { field } = useField('title'); field.value\`. Only BOUND values can be
read - an uncontrolled input's value is the DOM's.

For something that is NOT a descendant - a top bar - create the store above both
and hand it in; useField(name, store) reads it:

\`\`\`tsx
const store = useFormStore({ title: '' })

<TopBar store={store} />                      // outside the form: useField('title', store)
<Form action={save} store={store}>…</Form>
\`\`\`

Creating the store does not subscribe to it, so the holder does not re-render
per keystroke.

A submit from outside the form is html, not a second api:

\`\`\`tsx
<Form id="bug-report" action={reportBug}>…</Form>
<Button type="submit" form="bug-report">Submit</Button>
\`\`\`

It works before hydration. The action is on the form element as well as in the
submit handler, so the markup is submittable on its own; a refusal shows on its
fields through error() even with no javascript.

**components.json needs "rsc": true.** shadcn's init sees a plain Vite
project and writes false, and then a dialog or dropdown it adds has no
"use client". create-rsc-kit --shadcn and rsc-kit init --shadcn set it; after
a bare \`shadcn init\`, set it by hand. \`import { cn } from "cn"\` in its
components is correct: cn is shadcn's own package (lib/utils re-exports it).

**components.json's tailwind.css must be a stylesheet the app loads**: the root
layout's styles.css or a file it @imports. shadcn writes the theme (colours,
.dark, @custom-variant dark) there. In a Laravel app resources/css/app.css is
loaded only by Blade's @vite, so a theme there is a theme nothing loads - no
colours, no dark mode: @import '../../css/app.css' from
resources/js/app/styles.css (rsc-kit init does), or move it into styles.css
and point components.json at it.

**shadcn/ui works as-is.** Input, Textarea, Button and Label are styled native
elements, so \`name\` does what it always does. Select, Checkbox, Switch and
RadioGroup render a hidden native control whenever given a \`name\`, on Base
UI and on Radix alike - omit it and they are invisible to the form. A Base UI
Select changes that control without an event; <Form> watches its controls, so
dirty and valid() still see the pick.

Do NOT use shadcn's own Form/FormField/FormControl with this. Those wrap
react-hook-form, a different system for the same job. One or the other.

A SEARCH ON THE PAGE IT IS ON: a GET form (action is a url string) whose action
is the page the visitor is already on keeps that page on screen while the query
runs - no shell is shown first, the old results stay, an input keeps what was
typed, and Back returns to the query it left. pending is true until the new
results are on screen:

\`\`\`tsx
<Form action="/lookup" method="get">
  {({ pending }) => <><input name="q" /><button>{pending ? 'Searching…' : 'Search'}</button></>}
</Form>
\`\`\`

To show a skeleton where the results are instead of the old results, style them
from the form's own data-pending attribute (the results stay OUTSIDE the form, no
client wrapper): section:has(form[data-pending]) #results { display: none }, and
the same selector showing a #results-skeleton.

Do NOT patch around a skeleton on an in-page search with your own useState,
router.replace or a Suspense key: the form already does this. It is the form
only - a <Link> or visit() to the same path with another query is a page of its
own. A search to ANOTHER page still shows that page's shell first.

A REDIRECT FROM AN ACTION keeps the layouts as they were, like a link: right
for save-then-list. If the action changed what a LAYOUT reads (team switch,
sign-in, a count in the sidebar), call revalidate('all') BEFORE redirect() -
the destination then comes back whole, layouts included. A named section counts
too. Backend: Rsc::revalidate('all') before the redirect. Without it the page is
new and the sidebar is stale until a reload.

SAYING IT WORKED ("Password updated." after a save that stays on the page):
the action RETURNS the message and the form shows it - <Form action={x}
onSuccess={(message) => toast.success(message)}>, or useAction's onSuccess.
onSuccess is typed from the method (core 0.45.4), so a Laravel method declared
": string" hands a string. NOT a flash and back(): nothing needs to render for
it, and a kept page never toasts twice. Rsc::revalidate() first when the save
changed what the page shows.

A MESSAGE FOR THE NEXT PAGE ("Saved." after a save that redirects): the return
value goes to the form, which the redirect replaced. Call
await flash('Product saved.') from @rsc-kit/core/flash in the action before
redirect(), and render ONE client component in the root layout:
useFlash(({ message, kind }) => toast(message)) from @rsc-kit/core/useFlash.
kind: 'success' (default) | 'error' | 'info' | 'warning'. flash() sets a cookie:
an action, middleware or route.ts, NEVER a page. The browser takes it after the
navigation (or when the cookie changes) and clears it, so a stored page stays
cacheable. Do NOT read it in a server component, and render it as text.
From Laravel, flash as on any route: return back()->with('status', 'Invoice
sent.') (laravel 0.31). The flash lasts the whole render the redirect leads to,
and the page reads session('status') with an rpc() in its own Suspense slot -
NOT useFlash(), which reads a cookie Laravel never sets. A toast fired from an
effect fires again when the router shows a kept page: remember what it showed.
From Go, the same message as a JS action: rsckit.Flash(ctx,
rsckit.FlashSuccess, "Invoice sent."). In an action called by rpc() it rides
the host call onto the page, as a login cookie does; NOT from a batched read.
The same useFlash() shows it. Nothing secret: the browser reads it,
unencrypted.`,
    },
    {
        topic: 'draft-mode',
        summary: 'Letting an editor preview unpublished content on a stored, kept or CDN-cached page',
        body: `Draft mode is ONE VISITOR'S switch: while it is on, their requests skip the
stored (prerendered) page, the kept page (export const revalidate), the PPR
shell and cache() across requests, render the page NOW with their session,
and go out private, no-store. Everyone else is served exactly as before. Do
NOT add connection(), a query param or a second route for previews.

\`\`\`ts
'use server'
import { draftMode } from '@rsc-kit/core/draft'
import { redirect } from '@rsc-kit/core/redirect'

export async function preview(slug: string) {
  // authorize FIRST: draft mode is a switch, not a guard
  await (await draftMode()).enable()          // enable({ maxAge: 600 }); an hour by default
  redirect(\`/posts/\${slug}\`)
}
export async function stopPreviewing() { await (await draftMode()).disable() }
\`\`\`

In the page: \`const { isEnabled } = await draftMode()\` and read the draft
when it is true. Asking does NOT make the page dynamic: it is still
prerendered (isEnabled is false at build) and kept for everyone else.

enable()/disable() SET A COOKIE: call them from a server action, a route.ts
(a CMS's preview link: check a token, enable, Response.redirect) or a
middleware - never from a page. From an action, the page re-renders in the new
mode in the same answer and the tab's prefetched and held pages are dropped,
so no published copy shows after enable and no draft after disable.

The cookie (rsc-draft, HttpOnly, Lax) is signed with a key derived from
RSC_SIGNING_SECRET - required in production, or draft mode stays off. A
forged or expired one is ignored. A BACKEND is told on every host call:
X-RSC-Draft: 1, read as $request->draft() on Laravel and rsckit.Drafting(ctx)
on Go - never request()->header(), which a visitor could send to an app route;
the renderer never forwards the browser's. A CDN other than Homeport's edge / the edge
worker (which read edge.json bypass.cookies) must bypass its cache on the
rsc-draft cookie for pages that export revalidate.`,
    },
    {
        topic: 'prefetch',
        summary: 'Making a navigation feel instant',
        body: `\`<Link>\` fetches its payload as it comes into view, on EVERY device
(desktop too), when the browser is idle, as Next does - and again when the
link comes back into view or the tab is visible again, a request only once
the held payload has expired (no timer: an idle page fetches nothing) - the
first 12 links in view per page (a payload is the whole page, 30 KB for a
product with its related products; the rest wait for a touch or a settled
hover) - the bytes only, held 30 s (per-visitor page) or 5 min (a page the build made,
marked public), and the eager <img>s the payload names are preloaded at low
priority as it lands (the first 6 a page; not loading="lazy"; nothing under
Save-Data), so a product picture is decoded before the tap. Do NOT write an
image-prefetch route or an effect per card in the app. It is decoded - which
loads the page's client chunks - on intent: a pointer settled 100 ms on the link, a mousedown, a touchstart,
each 60-300 ms before the click. A click then finds a decoded tree and
nothing on the network is between the click and the page: the SPA feel,
on a slow network too. A link to a guarded page (Sign in -> /agent ->
/login) prefetches the redirect's destination too, so the tap asks only
the guard, which answers before rendering (0.49.1). Save-Data turns the viewport prefetch off. To MEASURE a navigation
(the number "slow on my phone" needs): every navigation leaves User Timing
marks rsc-kit:navigate:start / :decoded / :applied and a measure
rsc-kit:navigate (click to the commit) - in the Performance panel, or
performance.getEntriesByName('rsc-kit:navigate') in a console; a gap
before :decoded is network or chunks (the link was not on screen, or
prefetch={false}), after :applied is the render. A tap BEFORE the runtime has
hydrated is held by the bootstrap script and navigated to once the router
is wired (a document load after 4 s if the runtime never comes) - so a slow
phone's first tap is not a full reload. A form posting a server action
submitted in that window is held and submitted again after hydration, so
"Add to cart" tapped early is an action, not a full-page POST. Usually there is nothing to do; do
NOT add a viewport observer, touch handler or pre-hydration click shim in
the app. A tag manager on the main thread (Facebook Pixel, Clarity) is the
usual reason hydration is late: load those after the page is interactive.
A <ViewTransition> around the page is the usual reason a navigation is
slow on an iPhone (every iOS browser is WebKit): WebKit snapshots the
outgoing page at its FULL height, a 12,000 px landing page is 44 megapixels
at 3x, ~600-900 ms frozen per navigation and enough memory for iOS to
discard the tab (which returns as a reload). A navigation here is an
instant swap, like Next - do NOT add a page fade in a port; a port that
has one should remove it. The transition worth having is a shared element
(<ViewTransition name=...> on one image). If a page fade is wanted anyway,
<PageTransition className=...> from @rsc-kit/core/PageTransition is the
one that skips WebKit (and reduced motion), and ships its own CSS - a
120 ms cross-fade with pointer-events off on the overlay; nothing to add to
the stylesheet. Props: duration (ms, 0 = instant swap), webkit="run" for a
one-screen page that measured fine. See read_guide view-transitions.

\`\`\`tsx
import Link from '@rsc-kit/core/Link'

<Link href="/orders">Orders</Link>
<Link href="/orders" prefetch={false}>Orders</Link>   // opt out
<Link href="/orders" cacheFor={30_000}>Orders</Link>  // hold the payload longer
\`\`\`

\`href\` is typed to the routes the build found, so a link to a page that no
longer exists stops compiling - and a url the backend owns is one once it is
named in backendPaths. Cast with \`as Route\` only when the destination is
genuinely computed.

To prefetch from code — a row about to be clicked, a wizard's next step:

\`\`\`ts
import { prefetch } from '@rsc-kit/core/router'

prefetch('/orders/42')
prefetch('/orders/42', undefined, { intent: true })  // and decode it now: the chunks too
\`\`\`

What is prefetched is the RSC payload, not the html, so it is small and it warms
the same cache the navigation will read. Never the page on screen, and never a
page still held behind it (the page just left): a navigation to that reveals
it. After an action that revalidated, and after refresh(), every prefetched
payload and every held page is dropped - they are from before the write - so
visit() to a list after creating a row fetches the list with the row in it.
What an action re-rendered goes under the page it was invoked on: a tap that
left the page while the action was in flight is answered by fetching the page
now showing again, whole, never by putting the old page under the new url.

The client components a prefetched page renders are loaded (code only) as its
payload lands - the first eight per page, bounded per document - so the first
visit to a page does not wait on a chunk after the page arrived. Nothing to
configure. Serve over HTTP/2 (Cloudflare does by default): every client
component is its own small chunk.`,
    },
    {
        topic: 'validation',
        summary: 'Checking input — forms, actions, urls and request bodies',
        body: `One contract everywhere: any Standard Schema (Zod, Valibot, ArkType).

**Actions** validate on arrival and RETURN their failures, because React strips
a thrown message in production:

\`\`\`ts
export const createPost = client.input(schema).handler(async ({ input, ctx }) => …)
\`\`\`

**Urls** validate by exporting a schema beside the page or route:

\`\`\`ts
export const params = z.object({ slug: z.string().min(1) })
export const searchParams = z.object({ page: z.coerce.number().int().min(1).default(1) })
\`\`\`

Values arrive parsed and typed — \`?page=3\` is the number 3, a missing one is
the default. Never hand-parse \`Number(searchParams.get('page'))\`.

The same schema types every LINK to that page. Write search params as an
object, never as a string:

\`\`\`tsx
<Link href="/search" search={{ q: 'shoes', page: 2 }}>…</Link>   // typed by the page's schema
visit(href('/search', { q: 'shoes' }))                              // same check, as a string
\`\`\`

A key the page never reads, or a number written as text, does not compile;
a key the page requires is required on the link. A page with no schema takes
any scalars. Do NOT build \`?q=\${q}\` by hand when the page has a schema.

**Api route bodies** the same way:

\`\`\`ts
export const body = z.object({ title: z.string().min(1) })

export async function POST(request: Request, { body }) {
  const { title } = await body
}
\`\`\`

The failures answer differently on purpose:

  bad params        404 — the url does not describe a page
  bad searchParams  the error boundary (400 for an api route)
  bad body          422, the status an action already uses

A bad query is deliberately NOT a 404, or one bad link makes a real page look
deleted.`,
    },
    {
        topic: 'action-client',
        summary: 'Middleware for server actions, so a check cannot be forgotten',
        body: `\`\`\`ts title="src/server/client.ts"
'use server'
import { createActionClient } from '@rsc-kit/core/action'

export const client = createActionClient({ onError: report })
  .use(async ({ next }) => {
    const user = await currentUser()

    if (!user) throw new ServerAuthenticationError()

    return next({ ctx: { user } })
  })
\`\`\`

\`\`\`ts title="src/server/posts.ts"
'use server'
import { client } from './client'

export const createPost = client.input(schema).handler(async ({ input, ctx }) => …)
export const getPosts   = client.query(async ({ ctx }) => …)
\`\`\`

\`.handler()\` is a mutation (POST). \`.query()\` is a read (GET). Both run the
chain, so \`ctx.user\` is typed and non-null inside them.

For a failure the schema cannot know - an account not found, a slug taken -
the handler is given \`fieldErrors\`, typed to its own input so a field the
schema does not have is a compile error:

\`\`\`ts
.handler(async ({ input, fieldErrors }) => {
  if (!account) return fieldErrors({ email: 'Account not found' })
})
\`\`\`

WRITE return fieldErrors(...). It throws either way, but TypeScript cannot see
a never-return through a destructured argument, so without the return the
value you checked stays possibly-undefined on the next line. It lands in
validationErrors on that field, the same place a schema refusal does. This is
next-safe-action's returnValidationErrors with no schema argument and no
_errors nesting.

A plain "use server" function with no action client imports the same thing,
untyped, from '@rsc-kit/core/action'. Same rule: return fieldErrors(...). <Form>
shows the fields as error('name') and the "" key as formError, and useAction
returns them as validationErrors; AWAITED DIRECTLY it rejects with
ServerValidationError (@rsc-kit/core/errors: .errors, .fieldErrors, .formErrors)
- as does a backend stub whose input was refused - so code after the await does
not take a refused input for its result. One rule for a stub: anything that did
not happen REJECTS (ActionRefusedError, ServerValidationError); only a redirect
resolves ({ redirected }), and isRedirected is the one check on a resolved value.

When the INPUT is fine and the answer is still no - a project with orders
attached, a plan without the feature - that is a refusal, not a field error.
Use refuse(message, data), and declare the data's shape with .refusal(schema):

\`\`\`ts
.refusal(z.object({ blockers: z.array(z.object({ id: z.number(), href: z.string() })) }))
.handler(async ({ input, refuse }) => {
  if (attached.length) return refuse('Still in use', { blockers: attached.map(toLink) })
})
\`\`\`

The message is result.serverError (a form's formError) and is never replaced
by onError's generic message. The data is result.refusal, typed from the
schema and checked against it (a form's formRefusal, typed from the form's
action - no cast; a component below the form uses useForm<Values, Refusal>(). Do NOT encode blockers into the message or into
fieldErrors({ '': ... }) - the links are lost. Do NOT re-derive them from the
page's own list - a refusal decided at the moment of the write knows what is
blocking it now. A backend refuses the same way (Laravel Rsc::refuse(), Go
RefuseWith) and arrives as the same result.refusal. Data from an action with
no .refusal(schema) is not sent. Through a generated stub (<Form
action={ordersDelete}>) only the MESSAGE arrives, as formError: a plain
function has no .refusal(schema), so the data is left out and the log says so -
to act on it, call rpc() from a createActionClient action with .refusal(schema).
Awaited DIRECTLY, a stub REJECTS with ActionRefusedError (@rsc-kit/core/errors:
.message, .status), so code after the await does not run for a refused write -
only a redirect resolves. <Form> shows it as formError, useAction as serverError.
A query built with .input(schema) takes that schema's input (a wrong key fails
tsc); a query cannot redirect - throw ServerAuthenticationError (401) instead. Any backend refusal with a status, data or
not (Go Refuse(503, "busy"), Laravel abort(429)), and a backend's 401, 403 or
404, arrive as result.serverError with the backend's message - never onError's.
Through a generated stub they are formError, and awaited directly an
ActionRefusedError with .status 401, 403 or 404 - a backend 404 in an action
is its message, never a 500 (an action has no not-found page).
Do NOT write an onError that unwraps those; only a real failure reaches it. A
.query() read rejects with the same message, and fetchQuery's error carries
.status and .refusal.

The point is not convenience. An action cannot be added without the check,
because there is no other constructor to reach for.

Stack clients for a narrower rule:

\`\`\`ts
export const admin = client.use(async ({ ctx, next }) => {
  if (!ctx.user.isAdmin) throw new ServerAuthorizationError()
  return next({ ctx })
})
\`\`\`

Route \`middleware.ts\` does NOT run for actions — an action renders no route.
That is why the check goes here.

The built action is typed by its schema: createPost({ title: 1 }) fails the
typecheck; FormData is accepted beside it (how <Form> calls it). It always
resolves to an object - data | validationErrors | serverError | redirected.

From a button, not a form - useAction (next-safe-action's useAction, and its
useOptimisticAction through React's useOptimistic):

  'use client'
  import { useAction } from '@rsc-kit/core/useAction'
  const [shown, hide] = useOptimistic(posts, (list, id: number) => list.filter((p) => p.id !== id))
  const { execute, executeAsync, isPending, status, result, reset } = useAction(archivePost, {
    optimistic: ({ id }) => hide(id),     // inside the transition; React reverts it on failure
    onSuccess: (data) => …,               // typed from the handler
    onError: (message, result) => toast.error(message), // serverError, or the first validation message
    onSettled: (result) => …,
  })
  <button disabled={isPending} onClick={() => execute({ id })}>

execute never throws (a thrown failure becomes serverError); a redirect runs no
callback and sets no state; execute keeps one identity and reads the newest
callbacks. A backend's generated stub takes useAction too -
useAction(verification.send) - and onSuccess gets what the backend returned.

An action body - arguments and any uploaded files, read whole - is capped at
8 MB; over it the answer is 413 before a byte is kept. rscKit({ maxActionBody })
raises it. For large files, mint a pre-signed url and upload straight to storage.`,
    },
    {
        topic: 'data',
        summary: 'Loading data, streaming it, and when the browser needs to refetch',
        body: `**In a server component, just await it.** No loader, no getServerSideProps.

\`\`\`tsx
export default async function Page() {
  const posts = await db.posts.all()
}
\`\`\`

**Better: do not await.** Pass the promise down and let a client component
resolve it — the shell paints at once and the rows stream into the same
response, with no request from the browser:

\`\`\`tsx
export default function Page() {
  const posts = getPosts()            // not awaited

  return (
    <Suspense fallback={<Skeleton />}>
      <List posts={posts} />          {/* 'use client': use(posts) */}
    </Suspense>
  )
}
\`\`\`

Reach for this first. It is the thing RSC is for.

**When the BROWSER decides to refetch** — a filter, another page, a refresh —
call fetchQuery. It is a plain async function that returns the typed answer;
NO library is needed:

\`\`\`tsx
const [listings, setListings] = useState(initial)      // the server-rendered value
const [pending, start] = useTransition()
const show = (kind) => start(async () => setListings(await fetchQuery(getListings, [kind])))
\`\`\`
Works in an onClick, onSubmit, useEffect - anywhere in the browser.

**When you want CACHING** (stale-while-revalidate, dedupe, offline), hand the
same call to the library that holds the answer; this package ships none:
\`\`\`tsx
useQuery({ queryKey: ['posts', kind], queryFn: () => fetchQuery(getPosts, [kind]) })
useSWR(['posts', kind], () => fetchQuery(getPosts, [kind]))
\`\`\`
fetchQuery sends the read as a GET and goes to the server every time, which
is what a fetcher needs. It will never cache, dedupe or batch: a client
cache is the library's job, and a batch would lose the per-read cache key a
GET has. The ladder, most reads stopping on the first rung:
  1. the value now: fetchQuery + setState
  2. survive a reload / let a CDN serve it: query(fn, { cache: 'public', maxAge })
     - HTTP caching, no code in the page
  3. staleness, background refresh, optimistic updates, shared across
     components: TanStack or SWR with fetchQuery as the fetcher
Do not add a cache on top of it, and do not install TanStack for a single
button that reads once.

Keep the arrow: TanStack calls a bare \`queryFn\` with its own context, and a
server function serialises whatever it is handed.

A value that keeps CHANGING while someone watches - polling, SSE, realtime -
is how_to live-data, not this.`,
    },
    {
        topic: 'suspense',
        summary: 'Where boundaries go, and why the build cares',
        body: `A boundary is what lets a page be stored with a hole in it rather than not
stored at all.

\`\`\`tsx
<Suspense fallback={<Skeleton />}>
  <Slow />
</Suspense>
\`\`\`

THE DEFAULT PATTERN - write pages this way: the page is a SYNCHRONOUS
component; fixed copy, titles and frames go straight in it (they are the
stored shell); each read is its own async "slot" component under its own
<Suspense>, with a skeleton the shape of what it replaces:

\`\`\`tsx
export default function ShopifyPage() {            // not async
  return (
    <Card>
      <CardTitle>Shopify</CardTitle>                {/* in the shell */}
      <Suspense><ConnectButtonSlot /></Suspense>    {/* nothing until known */}
      <Suspense fallback={<ConnectionsSkeleton rows={1} />}>
        <ConnectionSlot />                          {/* async: its own read + check */}
      </Suspense>
    </Card>
  )
}
\`\`\`

Each slot does its own read and its own permission check, so a fast part is
not held back by a slow one, and a slot can move or be revalidated as a
section on its own.

loading.tsx wraps the WHOLE page in one boundary. Use it only for a page that
is one read and nothing else (a detail page whose skeleton is the page). Do
NOT reach for it by default:
- the heading/copy/frames the page already knows wait with the data;
- the slowest read holds back every other part;
- notFound()/redirect() or a backend 404 decided under it may already have a
  200 on the wire for a person (the page then ends with a noindex tag; a
  crawler is answered with the finished page and gets the real 404) - a
  check that must be a 404 for everyone goes in middleware.ts, which runs
  before anything is sent;
- it sits BELOW its layout: a layout that awaits (params, session) needs its
  own <Suspense> inside the layout;
- a ROOT loading.tsx hides pages waiting in the wrong place (the build only
  warns "nothing painted without the root loading.tsx").

The build renders every page. Whatever has not resolved when the budget expires
becomes the hole; everything above it is stored and served instantly. So a page
with no boundary above its slow part cannot be stored at all — the build says
so:

    ƒ  /orders
       blocks before anything can paint. Add a loading.tsx beside it, or put a
       <Suspense> above the waiting, and it has a skeleton to store.

Fix that by moving the read into a slot under <Suspense>, not by adding a
loading.tsx.

A painted fallback stays up at least 300 ms - React's rule: content that
arrives within 300 ms of the fallback painting waits until then. A stored
shell's holes arrive a moment after the shell, so fast data shows its
skeleton for the full 300 ms (a flash on every app launch). So: no boundary
around data that is always fast; fallbacks shaped like the content (same
card, same size, numbers blank); no animate-pulse on short-lived fallbacks.

A boundary does NOT fix a frozen \`Date.now()\`. Prerendering renders straight
through a component that never awaits, so the value is captured exactly as
before. A boundary becomes a hole only when something inside it waits.

redirect() and notFound() inside a boundary still work: the shell has gone
out, so the status stays 200 for a person - a late notFound() ends the page
with <meta name="robots" content="noindex"> - while a search engine or
link-preview crawler (matched by user agent) is answered once the whole page
has rendered and gets the real 404 or redirect. For a person the redirect
travels in the row's error digest and the browser
performs it as a navigation, layouts kept. A destination that is not this app's
is a DOCUMENT LOAD, wherever the redirect is called: redirect('https://other.site/..')
type-checks as written, and so does a url the backend owns once it is named in
backendPaths (see the backend recipe) - no \`as Route\`. The url that redirected
is replaced in history either way, so Back does not return to a page that sends
you out again. A late notFound() is the same: the browser asks for not-found.tsx and shows it where the page was, url unchanged.
A not-found.tsx beside a layout answers notFound() from every page under it,
inside that layout - the nearest one above the page wins, like error.tsx, so a
section keeps its header on a 404 (app/(shop)/not-found.tsx under
app/(shop)/layout.tsx). A url no route owns is answered by the ROOT one only.
error.tsx's reset() ASKS THE SERVER AGAIN for the page (layouts kept) and shows
what it answers, so a "Try again" button recovers from a failure that has
passed; it is the whole retry - no refresh() beside it, no location.reload().
An error.tsx on the route never sees either - a redirect or a missing page is
the page's answer, not a failure, and nothing should check isNotFoundDigest -
and the same holds
for a component under its own <Suspense> and for a parallel route slot. Only
an authorization check should NOT be there: the layouts above already
rendered. See the redirects guide.

TO LET A CDN KEEP A PAGE RENDERED PER REQUEST: export const revalidate = 60
(seconds, a number literal; a layout may export it too and the smallest wins,
0 anywhere turns it off). The page is rendered whole, then sent Cache-Control:
public, max-age=0, s-maxage=60, stale-while-revalidate=86400,
stale-if-error=86400 and CDN-Cache-Control: max-age=60,
stale-while-revalidate=86400, stale-if-error=86400 with an ETag only if the
render read nothing of the visitor; a 404 is kept a minute at most. A CDN that
reads CDN-Cache-Control caches on it (Homeport's edge reads nothing else, and
strips it, so it is not visible in a browser there). CDN-Cache-Control is sent
ONLY when a purge can reach the CDN (CDN_PURGE_URL set, or installPurge()), so
an edge never keeps a page changed() cannot take back; s-maxage still says the
lifetime. purge({ paths }) also sends a subdomain folder's path as visitors use
it: /merchant/orders purges /orders too. stale-if-error lets the CDN serve the
kept copy while the origin is down or deploying. The tags of every
cache(fn, { tags }) answer it used go out as Cache-Tag: posts,post:1, for a
CDN that purges by tag. changed(tag) calls the purge installed with
installPurge(async ({ tags }) => ...) from @rsc-kit/core/purge, after the
answer has gone - one hook, any CDN's API; a failure is logged, never fails
the change. With CDN_PURGE_URL set it is cdnPurge() with nothing to install;
CDN_PURGE_URL is the ONLY name read (RSC_PURGE_URL and HOMEPORT_PURGE_URL no longer are; homeportPurge() is now cdnPurge(), no alias). Rsc::changed() and reg.Changed() post their own purge
there, since a backend's change never passes through the engine. The host also keeps the page itself - ISR on every host: a
repeat request is answered from the kept copy (X-RSC-Kit: cached, Age); past
revalidate the stale copy goes out at once while one render replaces it;
changed(tag) makes the next request for a page that read that tag render, on
every instance, never stale. Kept in installCacheStore's store or 64 MB /
10,000 pages of memory, under the url with its query sorted and campaign tags
(utm_*, gclid, fbclid...) dropped: a url with them is answered from the copy
kept without them, and what it renders itself is never kept - read utm_source
in the browser, not in a revalidate page. Off in dev, on Homeport, and with pageCache: false. Whether a CDN answered is its own
entry in Cache-Status (hit), never X-RSC-Kit, which is stored with the copy. Homeport's entry, named
homeport and last, comes with its next engine release: look for hit in that entry, not anywhere in
the header; stored is no proof, the next request's hit is. A static page, shell or asset hit has no
entry and says X-Homeport-Edge: page, shell or asset. A revalidate page calls its backend as nobody: no cookie, no
Authorization, and a cookie the backend sets is dropped - do NOT export it on
a page that shows who is signed in. Otherwise the page is sent private,
no-store with Cache-Status: rsc-kit; fwd=bypass; detail=<reason> (cookies,
headers, request, connection, host-middleware, set-cookie, nonce, status,
failed-render, payload-url, payload-shape: a payload whose X-RSC headers are
not the router's for the page, an intercepted one included) and a log line naming what read the visitor. It is
not prerendered.

FOR A SERVER IN FRONT THAT SERVES THE FILES (nginx, a CDN, a PHP front
controller): every server build writes .output/files.json - { v: 1, root:
"public", files: ["/assets/…", "/sw.js", …], precompressed: ["br", "gzip",
"zstd"], headers: [{ match: "/assets/**", headers: { "cache-control":
"public, max-age=31536000, immutable" } }, { match: "/sw.js", … max-age=0,
must-revalidate }, the same for /sw-app.js, /manifest.webmanifest and
/_app/**], middleware: false }. Serve exactly the listed files from
root, a .br/.gz/.zst sibling with Content-Encoding when accepted, with the
headers whose match is the path or a /** prefix of it, every match in order
(a later one wins a header name). Paths are raw, not percent-encoded: decode
the request path first. It fails closed: a file under a route rule it cannot
state (a /:name.js pattern, redirect, cors, proxy) is left out, and its
request goes to the app. On Vercel it is .vercel/output/files.json - Nitro's
output dir. No middleware.ts, route.ts or rscKit({ headers }) applies to a
file. Do NOT derive the list from the directory or hard-code /assets/
immutable and forget /sw.js. A file no entry matches (the app's own
public/ files) gets no Cache-Control: do not add one.

FOR AN EDGE THAT CACHES PAGES: rsc-kit implements the edge contract (v2,
docs: reference/edge-contract). Every server build writes .output/edge.json -
{ v: 2, build, shells, static, bypass } (+ nonceShells under a
contentSecurityPolicy) - whose shells are url patterns ("/",
"/[team]/[app]", "/docs/[...slug]"), the ◐ pages, and whose static are
concrete paths, the ○ pages at the path each was rendered at: both less every
page with middleware (middleware.ts or the host's export const middleware) or
bound to the host, at most 200 each, [] when there are none. A root
middleware.ts - where security headers usually go - is above every page and
empties both lists; the build names the middleware that kept pages out.
Headers fixed for every page go in rscKit({ headers: { 'X-Frame-Options':
'DENY' } }) instead: set on every response, sent to the edge as the page's
headers, and the page stays listed. Only the contract's allow list is
accepted (no Cache-Control or Link); anything else is a build error. GET
/_edge/page?path= answers a shell, or a static page whole with complete: true
and, in its headers, the Cache-Control its document goes out with (public,
max-age=0, must-revalidate) - a shell names none, its document is per request;
POST /_edge/resume?url= answers a shell's holes. Both answer only a request
whose Edge-Token header holds the EDGE_TOKEN env var; unset, both are a 404. A
static page's payload is copied to /assets/_rsc/<hash>.rsc (immutable) and
named in its document, so it boots with no request to the origin. build covers
the client bundle and every stored page's bytes, so a server-only change is a
new build and an edge drops what it cached; it is not X-RSC-Version, and open
tabs do not reload for it. There is no v1 (ppr.json, /_ppr/*, PPR_TOKEN) any
more. Do NOT derive the lists from .output/server/rsc-static/: a guarded page
has a file there too, and _team_ cannot say whether it was a parameter.`,
    },
    {
        topic: 'offline',
        summary: 'Service worker, and what it does and does not cache',
        body: `\`\`\`ts title="vite.config.ts"
rscKit({ offline: true })
\`\`\`

The build writes a service worker that precaches the client bundle and caches
pages at runtime — a document fetch warms its payload, a payload fetch warms its
document, so a page reached by a link still works when reloaded offline.

Pages the build stored whole are served from the cache FIRST, because they
cannot change until a deploy and a deploy sweeps the cache. Everything else is
network-first with the cache as fallback.

Nothing marked \`no-store\` is ever kept — which is how a guarded page and a
session-reading query stay out of a cache that has no notion of who asked.

In a component:

\`\`\`tsx
import { useOnline } from '@rsc-kit/core/useOnline'

const online = useOnline()
\`\`\`

A navigation nothing answers: offline (navigator.onLine false) the page stays,
useOnline() is false and window gets an rsc-navigate-error event; online it is
the server that is down, and the url is loaded as a document so the browser
shows its error. Do NOT add a fetch wrapper or a "server unreachable" reload
in the app for it.

There is no push and no background sync. Push needs a subscription endpoint and
a sender; background sync needs idempotent replay. Both are the app's decisions.

Every document carries a Link header naming its stylesheet, client entry
and preloaded fonts (stored documents included); Cloudflare sends it as 103
Early Hints. Nothing to configure; do NOT add rel=preload headers or a
_headers file for these in the app.

Across a deploy: the worker serves the previous build's document first, so a
returning visitor's first navigation reaches the new server from the old
client. Handled: every document carries its build (<meta name="rsc-kit:build">),
the client sends it as X-RSC-Version, the server answers 409 to another
build and the client loads the document; once the worker has announced a
new build (useAppUpdate), the next navigation is a document load; a payload
naming a client reference the page lacks reloads like a missing chunk. Do
NOT add prefetch={false} or reload logic in the app for "client reference
not found" - it is the package's, and fixed.

TURNING IT OFF: remove offline and deploy. A build without offline writes a
/sw.js that deletes the caches, unregisters and reloads the pages the old
worker held, so browsers that visited are cleaned up. Do NOT write an
unregister script in the app. An app's own public/sw.js is left as it is.`,
    },
    {
        topic: 'pwa',
        summary: 'Making the app installable',
        body: `A NEW app: bun create rsc-kit@latest my-app --pwa. It turns on offline and
writes src/app/manifest.ts, a static src/app/offline/page.tsx and starter icons
(icon-192.png, icon-512.png, icon-maskable-512.png, apple-icon.png) - Chrome
reports it installable with nothing missing. Replace the icons, keep the names.
Nothing in rsc-kit processes images.

An EXISTING app - a manifest file beside the routes:

\`\`\`ts title="src/app/manifest.ts"
import type { WebManifest } from '@rsc-kit/core/manifest-file'

export default {
  name: 'Orders',
  shortName: 'Orders',
  themeColor: '#0b0b0c',
  backgroundColor: '#ffffff',
} satisfies WebManifest
\`\`\`

Read at build time, so it must be an object literal — not computed, not
imported from elsewhere.

**Icons need no listing.** Put them in \`src/app/\` and the build finds them:

    favicon.ico          served at /favicon.ico
    icon-192.png         <link rel="icon">, and the manifest's icons
    icon-512.png
    icon-maskable-512.png  manifest only, purpose "maskable" (safe-zone padded)
    apple-icon.png       <link rel="apple-touch-icon">
    apple-splash-1179x2556.png  iOS launch screen for that device, portrait
    opengraph-image.png  <meta property="og:image">
    twitter-image.png    <meta name="twitter:image">

    screenshot-wide-1280x720.png  manifest screenshots, form_factor wide (desktop)
    screenshot-narrow-750x1334.png  form_factor narrow (phone) - Chrome's richer install sheet

Sizes are read from the filename; no image is ever opened or resized.

Set id: '/' in the manifest and never change it - without it the app's identity
is its startUrl, and changing that orphans every install (the build warns).
scope, orientation, categories and shortcuts are typed too.

An install button: useInstall() from '@rsc-kit/core/install' ->
{ canInstall, install, installed, ios }. The offer (beforeinstallprompt) is
caught by the page's inline bootstrap, so a button that mounts late still gets
it - do NOT add your own beforeinstallprompt listener in an effect, it can miss
the event. install() resolves 'accepted' | 'dismissed' | 'unavailable'. On iOS
there is no offer; when ios is true, tell the visitor Share -> Add to Home Screen.

**Splash screens.** Android draws its own from the manifest: name, the 512px
icon and backgroundColor - set all three. iOS needs one image per device and
orientation: name each apple-splash-WIDTHxHEIGHT.png at the device's pixel
size (landscape swaps them) and the build writes the media query from a device
table; a size no device has is named at build and linked nowhere. A Next port
can keep metadata.appleWebApp ({ capable, title, statusBarStyle, startupImage })
unchanged. read_guide({ slug: 'pwa' }) has the size table.

**One grey frame on a dark launch (iOS).** In dark mode an installed app can
show one frame of grey (~#2C2C2E) between the splash and the page: iOS starts
dismissing the splash a frame before the page paints, and the empty web view
shows through. Nothing in the page reaches it - not color-scheme, an html
background, cards or placeholders. It is 1/60 s; do not chase it.

The build says whether it worked:

    [rsc-kit] manifest: Orders is installable
    [rsc-kit] manifest: no icons, so no browser will offer to install this.

There is no layout to edit — React hoists the tags into <head>.

Pair it with \`offline: true\`. They are separate options because they are
separate decisions.

**Push and background sync** need listeners the generated worker does not have,
so it imports yours from \`src/app/sw.js\` — plain javascript, evaluated by the
browser with no build step in front of it:

\`\`\`js
self.addEventListener('push', (event) => {
  const payload = event.data ? event.data.json() : {}

  event.waitUntil(self.registration.showNotification(payload.title, { body: payload.body }))
})
\`\`\`

The rest is the web api and \`web-push\`, not this package: VAPID keys, a
subscribe call behind a button, the subscription stored by a server action
against a USER rather than a session, and a sender that deletes an endpoint on
404 or 410 rather than retrying a dead one forever.

For background sync, make the endpoint idempotent. The browser decides when a
sync runs and may run it more than once — a request that reached the server
whose response did not arrive is retried, and if that posts a message twice the
person sent it twice.`,
    },
    {
        topic: 'starter-kits',
        summary: 'A finished app with auth: the JS, Go and Laravel starter kits',
        body: `A NEW app with registration, login, email verification, password reset,
two-factor, passkeys and settings already built is a starter kit, not a scaffold:

    bun create rsc-kit@latest my-app --kit js    # JavaScript alone, Bun or Node, SQLite
    bun create rsc-kit@latest my-app --kit go    # a Go server behind the renderer
    laravel new my-app --using=rsc-kit/laravel-starter-kit

--kit downloads the kit's latest RELEASE (not main; the kit commits its
lockfile, so the dependencies are the release's) into an EMPTY directory, names
package.json after it, and runs the kit's own install and setup (a .env with
fresh secrets, then a build). --no-install stops after the download; then run
install and setup yourself, the same two commands a clone needs. --kit js set
up from npm (npm create rsc-kit my-app -- --kit js) runs on Node. --kit
laravel is refused with the laravel new command, since Composer installs it.

The three kits share one UI, file for file; what differs is what answers the
pages. In the JS kit a page calls an async function (currentUser() in
src/lib/auth.ts) and a middleware.ts calls a guard (await requireUser()). In
the Go and Laravel kits a page calls rpc('Shared.user') and middleware.ts names
guards: export const middleware = ['auth'].

Guides: /hosts/js/starter-kit, /hosts/go/starter-kit, /hosts/laravel/starter-kit.`,
    },
    {
        topic: 'no-javascript',
        summary: 'The default is none; "use client" is how a page asks for it',
        body: `There is NO JavaScript on a stored page until something on it needs some.
A route that freezes whole, renders none of the app's client components, and
has no server action in its tree ships nothing - no React, no router. The
build says so:

  ○  /about    no js
     no client components, so ships no javascript; stylesheet inlined

"use client" IS the opt-in. Put a client component on the page - a counter, a
<Link>, an update prompt - and it has the runtime, because there is now
something for the runtime to do. There is NO switch in either direction:
nothing can need the runtime without a client component or an action in the
tree, and a page that must stay this way is an assertion on build-report.json
(its clientJs is null), not a setting.

The check reads the rendered tree, so a <Link> in a shared layout counts -
pages under a layout with a nav keep the runtime; a route group with its own
plain layout drops it. Navigation into such a page from a Link elsewhere
still works: its flight payload is written with the wrappers.

A page without the runtime also gets its stylesheet inlined when small
(rscKit({ inlineStylesheets }) to change), and still registers the service
worker with one inlined line. So does every other stored page, shells
included; one that hydrates keeps its link as media="print" so React finds
it rather than fetching it again. Do not "fix" that link - it is not render
blocking, and removing it makes React download the sheet after hydration.

Do NOT restructure an app to chase this, and do NOT look for export const
clientJs - it does not exist. The size column says what each route costs; a
page that is 82 kB because of one <Link> is fine.

A VISITOR WITH JAVASCRIPT TURNED OFF still gets what is inside a <Suspense>
(loading.tsx included). A streamed document that left a boundary pending
carries <noscript><meta http-equiv="refresh" content="0;url='/page?_nojs=1'">,
and the marked url is answered whole, like a crawler's request. The engine
strips _nojs before the page sees the url. Cost: that visitor loads the page
twice. Do NOT add your own noscript redirect, and do NOT read _nojs in a page.
A form posted without JavaScript is answered whole already. A PPR SHELL carries
the tag too, per url even when stored once for a pattern like /docs/[slug],
and so does one an edge serves from its cache (the edge contract's shell names
the path it was asked for). Not covered: a browser that blocks meta refresh.`,
    },
    {
        topic: 'api-routes',
        summary: 'HTTP endpoints beside the pages',
        body: `\`src/app/**/route.ts\`, one export per method:

\`\`\`ts title="src/app/api/posts/[id]/route.ts"
import type { RouteContext } from '@rsc-kit/core/route-schema'

export const params = z.object({ id: z.coerce.number().int() })
export const body = z.object({ title: z.string().min(1) })

export async function GET(request: Request, { params }: RouteContext<typeof params>) {
  const { id } = await params

  return Response.json(await findPost(id))
}

export async function POST(request: Request, { params, body }: RouteContext<typeof params, never, typeof body>) {
  const { title } = await body

  return Response.json(await createPost(title), { status: 201 })
}
\`\`\`

TYPE THE CONTEXT: RouteContext<'/api/items/[id]'> types params from the
route's segments (the pattern is checked against the routes the build found);
RouteContext<typeof params> from a schema. Every field is a PROMISE - a sync
params.id is a compile error, never a route that 404s. Do NOT hand-write
{ params: { id: string } }.

A real \`Request\` in, a real \`Response\` out. \`params\`, \`searchParams\` and
\`body\` are awaited, the same way a page's props are.

Fetch one through \`apiUrl\` and the path is checked against the routes the
build found:

    import { apiUrl } from '@rsc-kit/core/routes'
    await fetch(apiUrl('/api/posts/' + id))

A route.ts is a Route too (type Route from '@rsc-kit/core/routes' covers pages
AND route.ts files, as Next's does): Link, visit and redirect accept it. The
client treats a link to a route as an anchor - never prefetched, a full
navigation, not a payload fetch. ApiRoute is the narrower union for apiUrl:
apiUrl refuses a page, because fetching one gets html. It checks the PATH, not
the response type - for types across the boundary use a server action or a
query, where the return type is the function's because it is the same function.

A POST, PUT, PATCH or DELETE a browser sends from another site is answered 403
before the handler runs (Sec-Fetch-Site, else Origin against the host - Go's
http.CrossOriginProtection rule; actions and forms too). No CSRF token: do NOT
add one. A webhook or server sends neither header and is never refused. Another
origin that should post: rscKit({ trustedOrigins: ['https://admin.example.com'] }).
An api ANY site posts to from the browser (an embedded widget, its origins in a
database): export const crossOrigin = true in that route.ts (a literal). Another
site's request then reaches the handler WITHOUT the visitor's cookies (cookies(),
headers(), request and backend calls see none) - authenticate with a key the
caller sends, check Origin yourself, and export OPTIONS for the CORS preflight.

They run their directory's \`middleware.ts\`, so an endpoint under a guarded
path is guarded.

A \`GET\` that reads nothing from the request is answered from disk. Awaiting
\`searchParams\` says the answer depends on the query; never touching it means
the stored answer is served for any query at all. NEVER read the query with
new URL(request.url).searchParams (the Next way): the build cannot see that
read, and reading request.url at all makes the route dynamic (the table says
"reads the request - url"). A webhook verification handshake (hub.mode,
hub.challenge) reads the awaited searchParams. A GET that answers 4xx/5xx to
the build is never stored either (the table says "answered 403 to the build").

redirect() thrown from a handler is the route's answer: a real 3xx Location
for whoever asked (a signed-url export, a moved endpoint); notFound() is its
404. A guard's redirect above a route.ts is a refusal: a browser that
navigated there gets the Location, code that fetched it gets 401 +
X-RSC-Redirect (fetch would follow a Location and hand back the login page).

Exporting a \`body\` schema consumes the stream, so \`request.json()\` inside the
handler will find it already read. Use the parsed value.

A GET that reads nothing is stored - and two more things keep one per request:
a Set-Cookie on its Response (an answer for one visitor; classified dynamic,
whatever it read), and a body it froze from Date.now() or Math.random() is
stored WITH a warning on the route's line. Read the request (await
connection()) to run it on demand.`,
    },
    {
        topic: 'authorization',
        summary: 'Guarding pages, actions, api routes and queries',
        body: `Each entry point defends itself. There is no single place that covers all of
them, and believing otherwise is how a hole is left.

**A page or an api route**: \`middleware.ts\` in its directory guards everything
at or below it.

\`\`\`ts title="src/app/admin/middleware.ts"
import { redirect } from '@rsc-kit/core/redirect'

export default async function guard() {
  if (!(await currentUser())) redirect('/login')
}
\`\`\`

A prefetched link runs its guard ahead of the click. A guard that REMEMBERS
something - the url to return to after sign-in - asks prefetching() (from
@rsc-kit/core/request) first, or a link prefetched after logout becomes where
the next sign-in lands. A backend's guards are told by x-rsc-prefetch on each
host call; Laravel answers \$request->prefetch() with true and leaves the
session as it was, Go has rsckit.Prefetching(ctx), and a cookie set during a
prefetch never reaches the browser. The click asks the guard again, for real.

Several checks in one directory: export default [signedIn, verified, admin] -
run in order, stopping at the first refusal; reuse a check by importing it
from one place. Directories still compose outermost first.

The engine's server-only entries (request, redirect, revalidate, cache,
section, host, ...) are REFUSED in the browser bundle: a build or a dev load
fails with "'@rsc-kit/core/redirect' is for the server, and ended up in the
browser bundle" and the import chain. The cause is a helper file both a page
and a client component import - split it. Mark your own server-only files with
import 'server-only' (the build honours it).

A page never answers a request the browser marks as an image, script,
stylesheet or font (Sec-Fetch-Dest): it gets a plain 404 before any middleware,
layout or backend call runs, so a dynamic /[team] route does not run its guard
for /favicon.ico. A route.ts still answers such a request - an image endpoint
is a route, not a page - and a navigation or fetch() gets the page as always.

**An action or a query**: middleware does NOT run — they render no route. Build
them from an action client so the check cannot be forgotten. See the
\`action-client\` topic.

**Authorise on identity, not arguments.** \`deletePost(id)\` that trusts the id
is the whole of an IDOR: the caller chooses the id, so check the row belongs to
\`ctx.user\`.

A guarded page can still be frozen at build time — the guard is a serving
decision, not a build one. Its response is marked private so no cache keeps it.`,
    },
    {
        topic: 'dynamic',
        summary: 'Why a page is not static, and how to choose',
        body: `A page is stored at build time unless it reads the request. Reading it is what
opts out, and the accessors are async. usePathname() in a client component on
a route that lists no urls ([id] with no generateStaticParams) answers "" in
that route's shell - one shell serves every url, so no link is active and a
breadcrumb is empty until hydration, when the hook moves to the browser's url
by itself; the boot payload agrees with the shell, so nothing mismatches.
Nothing to wrap, nothing to do.

\`\`\`ts
import { cookies, headers, searchParams, connection } from '@rsc-kit/core/request'

const theme = (await cookies()).get('theme')?.value   // { name, value } | undefined, as in Next
await connection()   // "render this per visitor", said deliberately
\`\`\`

A page's \`params\` and \`searchParams\` props are promises for the same reason.

The build says which call did it, per route:

    ◐  /locale     85 kB
       cookies(), headers() stream per request; the rest is stored

That is usually correct — a page whose content depends on who is asking cannot
be one stored file. Change it only when the read was accidental.

READ THE BADGE (or X-RSC-Kit) BEFORE CHANGING CACHING CODE. Under vite dev every
page has a badge in its bottom-right corner - "○ Stored whole", "◐ Not stored
whole", "◐ Asks the backend", "○ Kept 60 s", "ƒ Private" - and clicking it lists
what this render read, with the component: "reads cookies() in Header",
"calls rpc("Shared.user")". Read it before adding connection(), moving a read
under <Suspense> or exporting revalidate; on a built server X-RSC-Kit says
stored | shell | rendered | cached. Outside a revalidate page it reports this
dev render's reads, not the build's verdict (vite build prints that). Never in
a build; rscKit({ devOverlay: false }) turns it off.

For a parameterised route, \`generateStaticParams\` turns one shell into a page
per url:

\`\`\`ts
export async function generateStaticParams() {
  return (await db.posts.all()).map((p) => ({ slug: p.slug }))
}
\`\`\`

A value that must differ per visitor but needs no server — a clock,
localStorage, a map — belongs in the browser only:

\`\`\`tsx
'use client'
import { browser } from 'react-dom'

function Clock() {
  use(browser('the time is the visitor\\'s, not the build machine\\'s'))
}
\`\`\`

It needs a Suspense boundary, and the page stays frozen.

There is NO app-wide switch to turn prerendering off (no rscKit({ prerender })
and no export const dynamic). A page that must render per request says
await connection() in the page; the build names any page it could not render
at build time, and that is the page to mark. "All of it per request" is
await connection() in the root layout with a root loading.tsx - every page a
stored fallback with the rest streamed, five times slower on a page that could
have been stored (bench/ in the repo). Do not reach for it.`,
    },
    {
        topic: 'metadata',
        summary: 'Titles, share cards, and the one setting production needs',
        body: `\`\`\`tsx
export const metadata: Metadata = {
  title: 'Orders',
  openGraph: { title: 'Orders', description: '…', images: '/cover.png' },
}
\`\`\`

A layout takes a title TEMPLATE - { template: '%s · Site', default: 'Site' } -
and layouts merge outward-in, so site-wide values go on the root layout once.

**Set metadataBase on the root layout. It is not optional in production.**

\`\`\`tsx
metadataBase: new URL('https://example.com')
\`\`\`

A share-card scraper needs an ABSOLUTE image url and Facebook, Slack and
LinkedIn refuse a relative one silently - the link unfurls with no image and
nothing says why. metadataBase makes every relative url, image and icon
absolute. Same name as Next, so a port carries it across.

Use the structured objects: openGraph and twitter are typed, an image can be
{ url, width, height, alt }, and it is the shape a Next app already has. A flat
'og:title' or 'twitter:card' key at the top level was removed and throws an
error naming the key; a tag with no field of its own goes under other. og: renders as property=, twitter: as name= -
what each scraper reads.

alternates: { canonical, languages: { en, fr, 'x-default' } } renders
<link rel="canonical"> and <link rel="alternate" hreflang> per language, made
absolute with metadataBase - Next's shape. For a site in several languages see
how_to('i18n').

An opengraph-image.png in app/ is found by name and needs no listing; it still
needs metadataBase to go out absolute.

A page's OWN share image is a file beside it: src/app/pricing/opengraph-image.png
(and twitter-image.png) is the card for /pricing and the pages beneath it, the
NEAREST folder winning - a route group like (marketing) counts as a folder, and
[slug] covers every page it answers. Do not add a per-page tag to get this. A page
that exports openGraph.images replaces the site's image rather than adding a
second og:image behind it; the nearer of the file and the export wins, and in the
same folder the file does. An openGraph with no images leaves the card to the file.
_private, @slot and (.)intercepted folders are not searched.

Charset and viewport: every document gets <meta charSet="utf-8"> and
<meta name="viewport" content="width=device-width, initial-scale=1"> as Next
wrote them - do NOT add them to a ported layout to fix a desktop layout on a
phone; a layout that renders either itself is left alone. To change it:
export const viewport: Viewport (from @rsc-kit/core/metadata) on a layout or
page, Next's shape - width, initialScale, maximumScale, userScalable,
viewportFit, themeColor (string or [{ media, color }]), colorScheme - merged
outer to inner then the page.

generateMetadata never holds up a page: it streams under a boundary of its
own, so the shell goes out at once and the <title>/<meta> arrive when the
lookup finishes. A stored pattern shell has a hole where they go and the
request fills it with the real values. A crawler is answered with the
finished page, metadata in <head>. Static \`metadata\` alone is in the first
bytes. Nothing to do in the app - do not move a lookup out of
generateMetadata to "speed it up".`,
    },
    {
        topic: 'i18n',
        summary: 'A site in several languages: /en and /fr stored per locale, <html lang>, hreflang, / by Accept-Language, translations, backend data',
        body: `The locale is the FIRST url segment. Every page lives under app/[locale]/,
and that layout is the one that writes <html lang={locale}>:

\`\`\`tsx
// src/app/[locale]/layout.tsx
import { notFound } from '@rsc-kit/core/not-found'
import { isLocale, locales } from '../../i18n'

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }))   // listed ONCE, here
}

export default async function LocaleLayout({ children, params }) {
  const { locale } = await params
  if (!isLocale(locale)) notFound()              // /de/about is a 404
  return <html lang={locale}><body>{children}</body></html>
}
\`\`\`

- A layout's generateStaticParams lists its own folder's params for EVERY page
  beneath it: [locale]/about/page.tsx lists nothing and is stored as /en/about
  and /fr/about. A page with a param of its own lists only that one and
  receives the layout's: generateStaticParams({ params: { locale } }).
- app/layout.tsx stays, WITHOUT <html>: it returns children and holds
  metadataBase (the sitemap and hreflang links read it). app/not-found.tsx
  renders inside it only, so it writes its own <html>.
- / is app/route.ts, NOT a page: GET reads the locale cookie, else matches
  Accept-Language against the list (the guide's negotiate(): q-values, then
  the base tag, then the default), and answers 307 to /{locale} with
  Vary: Accept-Language, Cookie. Do NOT read headers()/cookies() in a
  [locale] layout or middleware to pick the language: every page would render
  per visitor instead of being stored.
- Translations: src/messages/{locale}.json, loaded in a SERVER component
  through a map of imports - { en: () => import('./messages/en.json'), ... }.
  Zero client bytes. A client component gets the strings it shows as props;
  never import a catalogue into a 'use client' file. Dates and numbers:
  new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeZone: 'UTC' }) and
  Intl.NumberFormat - a stored page is formatted at build, so name the zone.
- Links keep the prefix: localized(locale, '/about') returning
  \`/\${Locale}\${P}\` keeps typed routes checking the href.
- A switcher: a client form (usePathname for the current path) posting to a
  server action that sets cookies().set('locale', ...) and redirects to the
  same path in the chosen locale. / then remembers it.
- hreflang: generateMetadata returns alternates: { canonical: '/fr/about',
  languages: { en: '/en/about', fr: '/fr/about', 'x-default': '/en/about' } }.
  sitemap.ts entries take alternates: { languages } the same way.

BACKEND DATA (Laravel, Go): pass the locale as an ARGUMENT -
rpc('Posts.show', locale, slug). A host call forwards Cookie and Authorization,
not Accept-Language, and a stored page's calls are made at build as nobody, so
the argument is the only thing that is there - and it keys what is stored.
Laravel: public function show(string $locale, string $slug), check it against
the supported list (abort_unless(..., 404)), App::setLocale($locale) in EVERY
function that translates (a render's calls reach Laravel as one batch, so one
that does not set it gets the previous call's), then __(), trans_choice() and
Carbon ->translatedFormat(). The locale cookie is written by the renderer in
plain text: $middleware->encryptCookies(except: ['locale']) if Laravel reads it.
Go: func(ctx, locale, slug string), refuse an unknown one with
rsckit.Refuse(404, ...), pick the catalogue - golang.org/x/text/message
NewPrinter(tag).Sprintf, or a map.

Guide: read_guide('guides/internationalisation').`,
    },
    {
        topic: 'vite-config',
        summary: 'The vite.config.ts an app needs - nitro() builds the server and a build without it is refused; Tailwind needs an @source covering the app tree',
        body: `\`\`\`ts
import { defineConfig } from 'vite'
import { nitro } from 'nitro/vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { rscKit } from '@rsc-kit/core/vite'

export default defineConfig({
  plugins: [nitro({ preset: 'node', serveStatic: 'inline' }), rscKit(), react(), tailwindcss()],
})
\`\`\`

nitro() is not optional: it builds the server around the route tree. A vite
build without it is REFUSED ("vite build has no nitro() plugin") - add the
plugin and install nitro at the pinned version (how_to bun). The preset is
where it runs: node, bun, cloudflare_module, vercel.

TAILWIND NEEDS @source over the app tree, in the stylesheet:

\`\`\`css
@import 'tailwindcss';
@source '../';
\`\`\`

A server component never enters the browser bundle, so without it every class
a server component uses is missing from the CSS, the build succeeds, and the
page arrives unstyled. The build WARNS "imports Tailwind with no @source
covering src/app" and names the line to add. In a Laravel app the styles.css
init wrote imports resources/css/app.css and carries the @source itself.

Full guide: read_guide({ slug: 'installation' }).`,
    },
    {
        topic: 'fonts',
        summary: 'Self-hosted fonts from npm, and porting next/font',
        body: `There is no font loader. Install the font from Fontsource, import its
css, name it in a variable:

\`\`\`css
@import '@fontsource-variable/fraunces/full.css';
@import '@fontsource-variable/geist';

:root {
  --font-display: 'Fraunces Variable', ui-serif, Georgia, serif;
  --font-sans: 'Geist Variable', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    'Helvetica Neue', Arial, sans-serif,
    'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}
\`\`\`

Put the font in FRONT of a full stack, not in place of one. A bare
'Geist Variable', sans-serif drops the emoji fonts - Geist has no emoji glyphs,
and with nothing named after it some systems draw a box - and drops the
metrics-matched fallback that makes the swap moment smaller. Those are
Tailwind's own defaults; shadcn's generated line loses both.

Vite hashes the woff2 files and serves them with the other assets. Nothing is
fetched from Google at runtime and nothing is downloaded at build - the files
are in node_modules.

Porting next/font: every option was something Fontsource already did.
subsets -> every subset ships behind a unicode-range and the browser fetches
only what the page uses. style: ['italic'] -> full-italic.css. axes -> full.css
has every axis; standard.css is weight only. display: 'swap' -> already in
every rule. className={font.variable} -> nothing, the variable is on :root.

The one line next/font added that you add yourself is the preload:

\`\`\`tsx
import fraunces from '@fontsource-variable/fraunces/files/fraunces-latin-full-normal.woff2?url'
<link rel="preload" href={fraunces} as="font" type="font/woff2" crossOrigin="anonymous" />
\`\`\`

?url is Vite's and gives the hashed path. Preload the one file the first paint
needs; preloading all of them defeats the subsetting.

Do NOT reach for next/font, @next/font or a Google Fonts link tag.

GETTING TO 100 ON A PHONE (do it last, once the design is settled). Fontsource's
stylesheet declares every subset of every weight with font-display: swap; a
throttled phone audit sees the largest text repaint when the font lands, and
scores 99. Three moves:
1. Own the @font-face rules, latin only: import the files with ?url, declare
   them yourself with the latin unicode-range.
2. font-display: optional for the body faces - the text paints once, in the
   fallback on a cold slow load, in the web font when cached. Keep swap for the
   headline face, which is preloaded and arrives with the document.
3. One weight per family; variable only where the axes are used. Declare the
   range you ask for (font-weight: 400 500) so nothing requests a missing file.
Put the preloads before the <style> with the faces. Measured on rsc-kit.dev:
Speed Index 1.7s to 0.9s, 99 to a steady 100, fonts 114 kB to 74 kB.
THE RULE: a font never blocks the page - text paints in the fallback before
the web font arrives. Three ways to break it, all avoided: a fonts.googleapis
<link> (render-blocking CSS from a cold origin - self-host via Fontsource
instead), font-display: block or unset (invisible text for up to 3s - every
rule says swap or optional), preloading every file (preload only what the
first paint needs).

AFTER THE ANSWER: after(() => sendEmail(user)) from @rsc-kit/core/request
queues work to run once the response is on its way - from an action, a
component, middleware or an api route. Do NOT use a detached promise: on a
Worker the isolate dies with the response unless work is handed to
waitUntil, which after() does; on a process it runs detached. Rejections
are logged, never surfaced.

WRITE THE SCHEMA FOR THE SHAPE IT WANTS. The form is read the way the schema
means it, on both sides (Zod 4 / ArkType describe themselves as JSON Schema;
Valibot not yet - its values arrive as strings):
  notify: z.boolean()             // unchecked posts nothing -> false; "on" -> true
  limit:  z.number().int()        // "5" -> 5. NOT z.coerce.number()
  tags:   z.array(z.string())     // one -> ['a'], none ticked -> []
  policy: z.string().optional()   // hidden behind a switch -> absent when off
  + .refine((s) => !s.notify || s.policy) for "required when the switch is on"
Nested names nest: fields[0][name] / fields[0].name -> { fields: [{ name }] };
auth[kind] picks a discriminated union's branch. No per-checkbox transform,
no checkbox() helper. The action decodes the same object the form validated.
Offline (rscKit({ offline: true })): the precache is what boots the app - js,
css, fonts, manifest, icons, / and /offline with their boot payloads; images,
wasm and the share card are cached on first use. A frozen page never visited
falls back to /offline like any other navigation. Do not add a second service
worker or a precache list; app/sw.js is importScripts'd into this one.
MOVING DOMAIN (www -> bare, old -> new): redirect everything on the old
origin EXCEPT /sw.js, which the app keeps serving there for a few weeks. A
browser never updates a worker whose script redirects, so without the
exception a returning visitor's worker serves the old origin's stored pages
and the offline page instead of the redirect. From 0.42.1 the worker also
leaves on its own when a request fails because its url now redirects.

An action that redirect()s RESOLVES with { redirected: '/where' } on the
client once the navigation starts - it does not throw, so a plain
startTransition(async () => await logOut()) needs no catch (a rejection
there unmounts the root). The result is always an object (exactly one of
data / validationErrors / serverError / redirected is set), so reading any
field of it is safe. Do NOT wrap actions in a hook to catch
ServerRedirectError; nothing throws.

A generated backend stub (Go/Laravel actions in src/server-actions/<class>.ts) is
typed Promise<T | Redirected>, not an ActionResult: the redirect answer is
{ redirected } in place of T. Narrow with isRedirected from
'@rsc-kit/core/errors' before reading it, and also before any "success" that
follows an await of a void stub:
  const secret = await databases.reveal(id)
  if (isRedirected(secret)) return
Reading secret.Password first is a type error on purpose. A <Form> or
useAction already skips onSuccess on a redirect - except one back to the page
it was called from (Laravel's back(), Fortify's 2FA enable), which is the
save succeeding: onSuccess runs and resetOnSuccess resets.

tsc does NOT see a redirect read as text: a template literal around a
string | Redirected compiles and goes to /t/[object Object]. The type-aware oxlint rules
typescript/restrict-template-expressions, no-base-to-string and
restrict-plus-operands do (a create-rsc-kit --lint project has them; run
oxlint src --type-aware, with oxlint-tsgolint installed). Nothing flags
"await stub(); toast.success()" - check isRedirected there, and test a click:
mount the component with happy-dom + react-dom/client + act, replace the stubs
module (mock.module / vi.mock), and assert the redirected case shows no
success. Register happy-dom IN THAT TEST FILE and GlobalRegistrator.unregister()
after it, from a module the file imports FIRST (import './dom'), not a beforeAll:
a library checks for a DOM when it is imported (Base UI picks its layout effect
from typeof document once), so a component imported earlier never opens its
dialogs. Never in a global preload: it replaces Request/Headers/fetch, drops
the Cookie header, and createTestApp then refuses to run. Run bun test
--isolate. See the testing guide, "Components".

Before hydration a submit is a native POST to the page's url (React's hidden
$ACTION_ fields); the host runs the action and re-renders the page with the
result seated in the <Form> that posted - a refusal shows on its fields
without javascript; a redirect() is followed, a cookie lands. Nothing to
configure; <Form> uses useActionState under a wrapper so the action keeps
its (formData) signature.
A blank control is absent for any optional field (z.email().optional()
accepts it; an optional union is not read as its first branch) and "" for a
required one (z.string().min(1) refuses it). A leaf
with no JSON Schema (z.date()) arrives as posted; its siblings still coerce.
<Form ref={...}> is fine: the caller's ref is filled beside the form's own.
Render props also carry dirty (anything differs from mount, uncontrolled
fields included; baseline moves on a successful submit; reset() clears it):
{({ dirty, reset }) => <Button disabled={!dirty}>Save</Button>} - the RHF
isDirty gate for Save/Discard.

Full guide: read_guide({ slug: 'fonts' }).`,
    },
    {
        topic: 'from-next',
        summary: 'Porting a Next.js app - what carries over, what to rename, what is different on purpose',
        body: `The app/ conventions are the same: layout, page, loading, error, not-found,
route.ts, [slug], [...path], (group), @slot, (.)intercept. "use client" and
"use server" are React's. Copy src/app first, fix imports second.
A (group) adds nothing to the url, so two groups can hold the same page:
(home)/page.tsx and (preview)/(home)/page.tsx are both / and stop the build
with an error naming both. Give one a real directory: (preview)/home/page.tsx.
Each [param] in a url needs its own name - app/p/[id]/[id] stops the build, as
do [__proto__], [constructor] and [prototype]. A [...path] catch-all also
answers the url with nothing after it, path then "".

IMPORTS
  next/link                    -> @rsc-kit/core/Link (href typed; search typed by the page's schema)
  useRouter().push / .replace  -> visit(url) / visit(url, { replace: true }) from @rsc-kit/core/router
  useRouter().refresh()        -> refresh() from @rsc-kit/core/router, or revalidate() in the action
  usePathname / useSearchParams-> @rsc-kit/core/usePathname, @rsc-kit/core/useSearchParams (nuqs: @rsc-kit/core/nuqs)
  useParams()                  -> the page's params prop, passed down
  cookies(), headers()         -> same names, from @rsc-kit/core/request. A cookie set in an action is what
                                  get()/has()/getAll() answer for the rest of that request, the sections it
                                  revalidates included - set('agent', id) then revalidate('all') is a whole switcher
  redirect() / notFound()      -> @rsc-kit/core/redirect / @rsc-kit/core/not-found
  revalidatePath/Tag           -> revalidate('name') on a section() - targeted, rides back with the action; the
                                  name is typed to the sections and slots the build found
  Metadata, Viewport           -> @rsc-kit/core/metadata (metadataBase, openGraph, twitter, icons as-is;
                                  export const viewport as-is; charset + viewport tags are written for you)
  app/robots.ts, app/sitemap.ts -> the same files and shapes; app/llms.ts beside them (how_to seo-files)
  middleware.ts subdomain rewrite -> nothing: a host is a route segment (how_to domains)
  flags/next (Vercel Flags SDK) -> OpenFeature (how_to feature-flags): @openfeature/server-sdk, context
                                  from cookies(); Pennant on Laravel. Nothing aliases next/headers any more
  next/font                    -> Fontsource (how_to fonts)
  next/image                   -> unpic or vite-imagetools (how_to images)
  next/script                  -> a <script> tag (how_to scripts)
  NEXT_PUBLIC_*                -> VITE_* in src/env.ts (how_to env); server vars typed there too
  import 'server-only'         -> keep it (the build honours it). Under bun test the real package throws on
                                  import, so the scaffold's tests/preload.ts stubs it: bunfig.toml
                                  [test] preload = ["./tests/preload.ts"], mock.module('server-only', () => ({})).
                                  A project without those two files adds them before unit-testing an action.
  next-safe-action             -> createActionClient() (how_to action-client); returnValidationErrors -> return fieldErrors({...})
                                  useAction / useOptimisticAction -> useAction from @rsc-kit/core/useAction
                                  (optimistic: option + React's useOptimistic)
  cache from 'react'           -> cache from @rsc-kit/core/cache: React's dedupes only inside a render; this one
                                  spans the request (guards, actions, api routes). The build names files still on React's
  unstable_cache, revalidateTag -> cache(fn, { key, revalidate, tags }) from @rsc-kit/core/cache keeps answers ACROSS
                                  requests (memory, or installCacheStore({ get, set }) for Redis/KV); changed(tag)
                                  from @rsc-kit/core/changed makes the next ask miss - no purge. Runs as nobody:
                                  cookies()/headers() throw inside it; arguments and answers are JSON
  @react-email/render, renderToString in an action -> the same call, in a module that starts with "use ssr"
                                  (the build warns naming the app file and the package; the stub throws when called)
                                  (how_to emails). Next gets away with it only for externalised packages; here it is explicit
  import type { Route } from 'next' -> import type { Route } from '@rsc-kit/core/routes' (pages AND route.ts; a link to a route.ts is an anchor, never prefetched)

DIFFERENT ON PURPOSE
- No export const dynamic. A page is frozen unless it READS the request; await
  connection() is the explicit mark. export const revalidate = 60 keeps a page
  that reads nothing of the visitor - ISR, in the engine and at a CDN.
- middleware.ts is per directory, on the server, full API; not one edge file.
  It does not run for actions - the check goes in the action.
- Actions return failures ({ validationErrors }, { serverError }), not throw.
- No image optimizer, no opengraph-image.tsx - put opengraph-image.png in src/app.
- Tests need no browser: createTestApp() is the deployed handler. It builds
  with the project's own build script on the runtime the tests run under, and
  answers files the build wrote to .output/public (assets, sw.js, the
  manifest, icons) as production does - app.fetch('/sw.js') is a real test.
- A component library (base-ui, Radix) imports as it did, from server
  components too. A shadcn-style components/ui/ folder keeps "use client" at
  the top of each file, as shipped; without it the server evaluates the
  library's internals for nothing. The build names the case that BREAKS: "N
  server files reach client-only React: <file> (<package>: useState)" - a
  server file whose code, or a library's under it, reaches a hook the server
  lacks; a render calling it fails "(0, ...useState) is not a function". Add
  "use client" to that file. Icons and packages that ship their own
  directive are not named.

SCAFFOLD FLAGS: --host=bun|node|worker --validation=zod|valibot|arktype|none
--env/--no-env (typed env vars via @t3-oss/env-core in src/env.ts, in the
chosen library; server vars never reach the browser, VITE_ prefix for ones
that may). Pick the library the Next app already uses.

ORDER: scaffold -> copy src/app -> fix imports -> build (it typechecks first,
so a Link to a route that does not exist fails here) and READ the output: a
route that is not ○ names what streams and from which component (a cookies()
in a layout reaches every page; the build says so) -> decide each action the
build lists as running no middleware -> check.

CONVERT THE FORMS AND ACTIONS - do not carry them. useActionState +
useFormStatus, react-hook-form, TanStack Form and useState-per-input all
still COMPILE here, which is why a port leaves them. Each becomes
<Form action={…} schema={…}> (how_to forms) and a createActionClient()
handler (how_to action-client). Remove the form library when the last form
is converted. A port that keeps two form systems has ported nothing.

Full guide: read_guide({ slug: 'coming-from-next' }).`,
    },
    {
        topic: 'from-inertia',
        summary: 'Porting a Laravel + Inertia React app - what stays in Laravel, what the pages become, what goes',
        body: `Laravel stays, all of it: models, policies, form requests, middleware, jobs,
the session. What changes is who renders the page: Inertia rendered it in
the browser from props a controller assembled; here the page is a server
component rendered in front of Laravel that reads by name with rpc().
Install: composer require rsc-kit/laravel && php artisan rsc:install
(runs rsc-kit init; one vite.config.ts, laravel-vite-plugin moved aside;
route tree is resources/js/app). In a terminal it asks: React Compiler,
Tailwind, shadcn/ui, oxlint - never a validation library or typed env (Laravel
has FormRequests and .env). composer require itself cannot ask: Composer runs
no dependency's scripts. Unattended: --compiler=oxc --tailwind --shadcn --lint.
See how_to backend for rpc(), attributes,
make:rsc-action and the manifest.

WHAT EACH PIECE BECOMES
  resources/js/Pages/Orders/Index.jsx     -> resources/js/app/orders/page.tsx (the file is the route)
  Route::get + Inertia::render(...props)  -> nothing: the controller body moves to app/Rsc/Orders.php::recent(),
                                             the page does await rpc<Order[]>('Orders.recent', 20). Delete the route.
  usePage().props.auth.user, share()      -> a read in the layout that shows it: rpc('Shared.auth'), passed as props.
                                             No global props bag. Deepest layout that needs it - a read in the root
                                             layout makes every page render per request (the build says so).
  usePage().props.flash                   -> the action's return value, back on the form that submitted
  <Link href={route('x', id)}> (Ziggy)    -> <Link href="/orders/1"> from @rsc-kit/core/Link, typed to the tree. Drop Ziggy.
  router.visit / router.get               -> visit(url) from @rsc-kit/core/router
  router.reload({ only })                 -> Rsc::revalidate('orders') in the action re-renders that section with the answer
  router.post, useForm().post('/orders')  -> a server action: php artisan make:rsc-action Orders --method=create --auth
                                             --revalidate=orders, then <Form action={orders.create}> from @rsc-kit/core/form
                                             (import * as orders from './server-actions/orders', the module the build writes)
  useForm errors/processing               -> <Form>'s errors (a FormRequest's ValidationException lands on the fields)
                                             and pending
  ->middleware(['auth','verified'])       -> export const middleware = ['auth', 'verified'] in middleware.ts beside the page
  Inertia::defer, <WhenVisible>, lazy()   -> <Suspense> around the component that awaits; the shell streams first
  <Head title>                            -> export const metadata = { title }
  Page.layout = ... (persistent layouts)  -> layout.tsx in the directory
  app.blade.php @inertia @vite            -> resources/js/app/layout.tsx with <html><body>; no Blade root view
  createInertiaApp(), ssr.jsx, start-ssr  -> nothing; init writes the entry; every page renders on the server
  usePoll                                 -> usePolling (how_to live-data)
  <Link prefetch>                         -> the default (hover)
  Inertia::render('Error')                -> error.tsx, not-found.tsx
  RedirectResponse from a controller      -> the same redirect()/to_route()/back(), returned from the action;
                                             redirect() from @rsc-kit/core/redirect in a page or guard
  NProgress                               -> <PageTransition> from @rsc-kit/core/PageTransition, or nothing

Auth pages: Auth.login with a LoginRequest calling Auth::attempt() - a cookie
queued during the call lands on the response; redirect('/dashboard') in the
guard sends a signed-in visitor on. /login can also stay Laravel's (Fortify):
any url the tree does not have is forwarded.

DIFFERENT ON PURPOSE: no controller per page (a page reads three things,
calls three methods); no props bag and no partial reloads (sections
revalidate); / is the React tree's, welcome route or not; two processes
(php artisan serve needs PHP_CLI_SERVER_WORKERS=4 and --no-reload); the
build says what each page costs - most pages that read nothing per visitor
freeze, which Inertia never could.

ORDER: install -> move Pages/ into app/ one directory per url, layouts to
layout.tsx -> per page, controller body into app/Rsc, rpc() it, delete the
route -> npm run build and READ the output (a read in the root layout
reaches every page; move it down) -> CONVERT THE FORMS (each useForm is a
make:rsc-action + <Form>; useForm still compiles here, which is why a port
leaves it) -> replace route() with typed hrefs; tsc finds the rest -> build
again -> browser. Drop @inertiajs/react, laravel-vite-plugin and ziggy from
package.json when the last import is gone.

Full guide: read_guide({ slug: 'coming-from-inertia' }).`,
    },
    {
        topic: 'emails',
        summary: 'Render React to HTML on the server - an email, a PDF, a feed - from an action or a route, with "use ssr"',
        body: `@react-email/render, renderToString, anything on react-dom/server, called from
a server action or a route, fails: "react-dom/server is not supported in React
Server Components". React means it: where server components render, react is
the server-only build - the renderer needs the client build's internals, and
the components it would render import that same react (no useState, no
useContext). No alias fixes it. The rendering has to run in the ssr
environment, the one that turns pages into HTML for the browser.

Put the rendering - the template AND the call that renders it - in a module
that starts with "use ssr". Everything else imports it normally:

\`\`\`tsx
// src/lib/email/render.tsx
"use ssr";
import { render } from '@react-email/render'
import { OtpEmail } from './otp-email'

export async function renderOtpEmail(code: string) {
  const email = <OtpEmail code={code} />
  const [html, text] = await Promise.all([render(email), render(email, { plainText: true })])
  return { html, text }
}
\`\`\`

\`\`\`ts
// src/lib/email/send-otp.ts - a plain server module, called from the action
import { renderOtpEmail } from './render'
export async function sendOtpEmail(to: string, code: string) {
  const { html, text } = await renderOtpEmail(code)
  await transporter.sendMail({ to, subject: 'Your code', html, text })
}
\`\`\`

Where server components render, the build replaces the module with async
proxies of its exports that call across - what "use client" does for a
component, in the other direction. Same process; dev and build; nothing to
configure.

RULES
- Exports are async functions. The call crosses environments, so the answer is
  a promise. A sync function, a value, a class, export { } or export * is
  refused at build with its name. Types are fine.
- Pass DATA across, not elements: renderOtpEmail(code), never
  render(<OtpEmail/>) from the caller. An element built on the calling side
  carries components from that side's react, and they render with no hooks.
- The module's imports are the ssr side's: @react-email/components,
  react-dom/server, a PDF or Markdown renderer. Keep the module to rendering;
  the database call belongs on the calling side.

Imported react-dom/server directly (through a library, usually)? It now throws
the fix in its message, naming the app file that pulled it in, and the build
warns once with the same. Do NOT alias react-dom/server, externalise react, or
move the action out of the app - the directive is the whole fix.

Full guide: read_guide({ slug: 'emails' }).`,
    },
    {
        topic: 'seo-files',
        summary: 'robots.txt, sitemap.xml and llms.txt from a file beside the root layout - the shapes Next uses, stored at build when they can be',
        body: `Files beside the root layout, named for what they answer:
  src/app/robots.ts    -> /robots.txt    default export returns MetadataRoute.Robots
  src/app/sitemap.ts   -> /sitemap.xml   default export returns MetadataRoute.Sitemap (an array)
  src/app/llms.ts      -> /llms.txt      default export returns MetadataRoute.Llms
  src/app/llms-full.ts -> /llms-full.txt default export returns a string
The types: import type { MetadataRoute } from '@rsc-kit/core/metadata'. The
same names and shapes as Next's app/robots.ts and app/sitemap.ts; copy them.

\`\`\`ts
// src/app/robots.ts
export default function robots(): MetadataRoute.Robots {
  return { rules: [{ userAgent: '*', allow: '/', disallow: ['/api/'] }], sitemap: '/sitemap.xml' }
}
// src/app/sitemap.ts
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await db.post.findMany()
  return [{ url: '/', priority: 1 }, ...posts.map((p) => ({ url: \`/blog/\${p.slug}\`, lastModified: p.updatedAt }))]
}
// src/app/llms.ts
export default function llms(): MetadataRoute.Llms {
  return { title: 'Acme', summary: 'What it is.', sections: [{ title: 'Pages', links: [{ title: 'Pricing', url: '/pricing' }] }] }
}
\`\`\`

A relative url is made absolute with the root layout's metadataBase; without
one it is a build error. Any of them may return a string, served as written.

NO sitemap.ts? The build writes /sitemap.xml itself: every stored page and
every generateStaticParams url, lastModified = the build, minus guarded
routes (middleware.ts above them), failed pages and not-found. Needs the root
layout's metadataBase. Write sitemap.ts only when you need urls the build
cannot see or per-url changeFrequency/priority.

HOW FRESH - the function decides, the same rule every route follows:
  write nothing                        -> the build's own sitemap, stored; fresh every deploy
  sitemap.ts that reads the database   -> stored at build (○); fresh every deploy
  sitemap.ts that awaits connection()  -> rendered per request (ƒ); fresh every crawl
\`\`\`ts
export default async function sitemap() {
  await connection()   // from '@rsc-kit/core/request' - per request, like a page
  return (await db.post.findMany()).map((p) => ({ url: \`/blog/\${p.slug}\`, lastModified: p.updatedAt }))
}
\`\`\`
Reading the database at build is fine; the REQUEST makes it dynamic, not the
data. Same for robots.ts and llms.ts. No middleware runs for
them - a root guard must not 401 the crawler. The url is typed
(route('/sitemap.xml')).

A file as written beside the root layout is served at the root as it is:
robots.txt, sitemap.xml, sitemap-*.xml, llms.txt, llms-full.txt, humans.txt,
security.txt, ads.txt. A file and a function for the same url is a build
error. Do NOT put these in public/ and do NOT write a middleware.ts for them.
A file of the same name already in public/ (Laravel ships public/robots.txt
and an empty public/favicon.ico) is answered instead of the app's - dev start
and the build warn "is answered at /robots.txt" - delete the public/ one.

Full guide: read_guide({ slug: 'seo-files' }).`,
    },
    {
        topic: 'domains',
        summary: 'Subdomains and custom domains as route segments - admin.example.com reaches app/admin, a tenant host binds [domain], no rewrite',
        body: `A request from a host that is not the site's own is matched with the host
in FRONT of the path. The site's own hosts: the root layout's metadataBase
(a literal - a computed one is not read for routing), www. of it, and
rscKit({ hosts: [...] }). ONE of the two must name the site, or a subdomain
is a foreign host whose segment is the whole name and is served by path,
silently. With the address in the environment (Laravel's APP_URL), use
hosts: loadEnv in vite.config.ts and hosts: [new URL(env.APP_URL).host] -
that also names the local example.test under Herd, which a production
metadataBase does not. hosts also takes a staging/internal name or a second
brand domain. localhost and ips are always own.

  example.com/admin           -> /admin              app/admin/page.tsx
  admin.example.com/          -> /admin              the same file (subdomain of an own host = its label)
  acme.example.com/settings   -> /acme/settings      app/[domain]/settings/page.tsx, domain "acme"
  acme.com/settings           -> /acme.com/settings  the same file, domain "acme.com" (other host = whole host)

The visitor's url is untouched; only the match changes. Only a top-level
[domain] or [host] directory binds the host; app/[slug] or app/[collection] at
the top is a path parameter, as in Next. A top-level [domain]
binds ONLY from a host, never from a path: example.com/nope is a 404, not a
tenant called "nope". A layout gets params too (its own segments' and those above, as a promise),
and is rendered again when its own value changes. A route listing no urls
stores one shell for all values, so a layout awaiting params above every
boundary fails the build: read them under <Suspense> in the layout, or list
the urls with generateStaticParams. A tenant check that should 404 goes in
[domain]/middleware.ts - its argument is the params, and notFound() there is
a real 404. Otherwise [domain] is an ordinary dynamic segment: params.domain in every page/layout under it, loading/error files
as usual. A
directory named for a host (app/admin/) wins over [domain]. A subdomain with no
directory of its name (no app/merchant/) is served by path - the home page on
merchant.example.com/ - and the dev server says "has no app/merchant/ - served
by path" once per host. Add the directory; no config.

Links to another host: a typed href is the FOLDER path (/merchant/orders =
example.com/merchant/orders - both addresses work, nothing redirects). To link
to the subdomain or a tenant use hostUrl from '@rsc-kit/core/routes':
hostUrl('merchant', '/orders') -> //merchant.example.com/orders (path typed
as the pages under app/merchant, folder taken off); hostUrl(tenant.slug,
'/settings') -> //testbrand.example.com/settings (host autocompletes to the
top-level folders but takes any string; path typed by the tenant tree);
hostUrl('acme.com', '/settings') -> //acme.com/settings (a dot = whole
domain); hostUrl('/pricing') -> //example.com/pricing (back to the site from
a subdomain). The site's host is the first rscKit({ hosts }) entry, port
kept; with none named a folder's url is its path. Same string on server and
browser; works in <Link>, visit() and redirect(). Do NOT build
\`//\${slug}.\${host}\` by hand or read the request host for links.

A folder only ever seen on its subdomain: rscKit({ hosts: [...], subdomains:
['merchant'] }). Then example.com/merchant/orders is a 301 to
merchant.example.com/orders (only on the site's own host - not localhost, a
preview or <app>.homeport.run, where the path form renders and links keep it;
edge.json leaves the folder out; a backendPaths entry under it stops the
build); <Link href="/merchant/orders">,
visit() and redirect() go to the subdomain with no hostUrl; on the subdomain
href="/pricing" goes to the site; Laravel's route('merchant.orders') is the
subdomain url. example.com/merchant is then the subdomain's home - a landing
page goes in its own folder (app/sell/). Needs hosts and app/merchant/, or dev
and the build stop.

\`\`\`tsx
// src/app/[domain]/layout.tsx
export default async function TenantLayout({ params, children }) {
  const { domain } = await params
  const tenant = await tenantByDomain(domain)   // "acme" or "acme.com", as stored
  if (!tenant) notFound()
  return <TenantProvider tenant={tenant}>{children}</TenantProvider>
}
// src/app/[domain]/page.tsx - domains in a database: list them, they are stored at build
export async function generateStaticParams() {
  return (await db.tenant.findMany()).map((t) => ({ domain: t.domain }))
}
\`\`\`

Only when a route could answer it (a top-level [domain] directory, or one
named for the host); otherwise the host is the site's own. Keep metadataBase as
the production host: localhost and ips are always own, so dev routes by path.
To try a tenant locally: curl -H 'X-Forwarded-Host: acme.example.com'
http://localhost:3000/ (or /etc/hosts). Behind a proxy the
host is X-Forwarded-Host, then Host. Not for a static export (a file server
sees no host). Do NOT write a middleware rewrite, do NOT
read the host in every page - the segment already is the host. The root layout
needs metadataBase (or rscKit({ hosts })) or every host is the site's own.

Full guide: read_guide({ slug: 'domains' }).`,
    },
    {
        topic: 'identify',
        summary: 'What a response says about itself - X-RSC-Kit (how it was served, always) and X-Powered-By + a generator tag (what built it, off with identify: false)',
        body: `Every response carries X-RSC-Kit: stored | rendered | shell - a page from a
file the build wrote, rendered for this visitor, or a stored shell with its
holes rendered now. A stored answer also carries an ETag of its bytes, and
If-None-Match with it is a 304 with no body. X-RSC-Kit is the header to read
when a page is slower than expected (like X-Nextjs-Cache); a CDN rule or
health check can key on it. Names no product; always sent.

By default a response also says what built it: X-Powered-By: rsc-kit and
<meta name="generator" content="rsc-kit"> in every document (BuiltWith,
Wappalyzer). The NAME only, never the version - a version in every response
is what a vulnerability scanner filters on.

rscKit({ identify: false }) turns off the name (header and tag) for a policy
that strips framework identifiers; X-RSC-Kit stays. Do not strip X-RSC-Kit
at the proxy - it is what tells you whether a stored page was served.

Full guide: read_guide({ slug: 'response-headers' }).`,
    },
    {
        topic: 'content-security-policy',
        summary: 'A strict Content-Security-Policy on every page - rscKit({ contentSecurityPolicy }) adds each page\'s hashes, and a nonce where it streams',
        body: `\`\`\`ts title="vite.config.ts"
rscKit({ contentSecurityPolicy: {} })   // strict default
rscKit({
  contentSecurityPolicy: {                // the default, plus Turnstile
    extend: { 'script-src': 'https://challenges.cloudflare.com', 'frame-src': 'https://challenges.cloudflare.com' },
  },
})
rscKit({
  contentSecurityPolicy: {                // the whole policy, replacing the default
    directives: { 'default-src': ["'self'"], 'img-src': ["'self'", 'data:'], 'frame-ancestors': ["'none'"] },
    reportOnly: false,   // true: Content-Security-Policy-Report-Only
  },
})
\`\`\`

{} is: default-src 'self'; base-uri 'self'; object-src 'none'; style-src-attr
'unsafe-inline'. To allow one more origin use \`extend\`, never a retyped
default: it ADDS to the default, and a directive the default does not name
starts from its fallback (script-src, frame-src from default-src 'self'), so
'self' is kept - do not write it. frame-ancestors and form-action fall back to
nothing and are only what you write. A source added to a 'none' directive
replaces the 'none'; extend cannot close one ('frame-src': "'none'" fails the
build). extend and directives together fail the build. The engine adds a
script-src and style-src naming the page's OWN inline code - the boot script,
React's streaming scripts - so the policy needs no 'unsafe-inline'. How, by
page:

- stored at build, or kept by revalidate: the hash of each inline script and
  style; no nonce, so caches still share it
- a PPR shell: the shell's hashes plus a nonce for the holes resumed into it
- rendered per request: a nonce, new per response, which React puts on every
  script it writes

The payload a page hydrates from is <script type="application/json"> data
blocks: never run, never judged by the policy. A directive you wrote with
'unsafe-inline' is left alone (a hash beside it would switch it off).

YOUR OWN inline code: a <script> or <style> in a stored page or shell is hashed
and runs. One inside a <Suspense> hole, on a per-request page, or brought by a
navigation is REFUSED - put CSS in a stylesheet and code in a module, or add
'unsafe-inline' to style-src. Keep style-src-attr 'unsafe-inline': React's
style={{...}} is an attribute, which no hash or nonce can allow.
A stored or kept page is hashed AS WRITTEN: a <script> inside untrusted HTML
printed with dangerouslySetInnerHTML is hashed and runs too. SANITIZE such
HTML; the policy does not cover it there.

A LIBRARY THAT TAKES A NONCE (next-themes, an analytics snippet): pass it
useNonce() from '@rsc-kit/core/useNonce', a client hook - wrap the provider in
a 'use client' component and render that from the root layout:
  const nonce = useNonce(); <ThemeProvider nonce={nonce} ...>
Never read a nonce on the server and pass it down as a prop: a navigation's
payload has a different nonce from the document's. useNonce() is undefined on
a page allowed by hash (stored, a shell's own HTML) - the library's inline
script is hashed there and runs; a <style> it inserts after hydration runs only
where the page has a nonce (next-themes' disableTransitionOnChange: drop it, or
'unsafe-inline' in style-src, on a stored page with no holes).

Everywhere: Node, Bun, Docker, Workers, functions. A static export carries a
<meta http-equiv="Content-Security-Policy"> per page (no frame-ancestors,
report-uri, report-to, sandbox or report-only in a meta). An edge gets each
static page's policy with its hashes. Under a policy edge.json moves the shells
to nonceShells: an edge serves them only if it mints a nonce per response
(Edge-Accept: nonce, the {edge-nonce} placeholder in the page's policy,
Edge-Nonce on the resume); any other edge leaves them to the origin.

In vite dev the same policy is sent, plus 'unsafe-eval' (React's development
build), the local dev server in connect-src (ws://localhost:*, 127.0.0.1 - the
HMR socket of a page served from my-app.test) and the dev server's origin when
the page comes from another one. Every
dev page renders per request, so it runs by nonce - Vite's CSS updates and
error overlay included - and your own inline <script>/<style> is refused there
even on a page the build stores. A refusal shows in dev first, never only in
production. Never 'unsafe-eval' in a build.

Do NOT also put a Content-Security-Policy in rscKit({ headers }) - the build
refuses both. Do NOT set a nonce policy in a middleware or in the backend in
front (a Laravel CSP package): React never sees that nonce, so every streamed
page is refused, and two policies are both enforced. A middleware that does set
one keeps it, and the engine adds nothing.

Full guide: read_guide({ slug: 'content-security-policy' }).`,
    },
    {
        topic: 'backend',
        summary: 'BAP (Backend-Answered Pages): a Laravel, Go or other backend behind the renderer - rpc() reaches it, middleware.ts names its middleware, app/Rsc/Actions are its server actions',
        body: `The model is a BAP - Backend-Answered Pages: a page rendered in front of
the backend rather than by it (MPA: backend renders; SPA: browser renders and
calls an API; BAP: a renderer on the server renders and calls the backend
over loopback). The backend is the part that is not a page - models, session,
auth, policies, jobs - answering one private endpoint, and it keeps every
route of its own. The whole model, and how to build for it:
read_guide({ slug: 'backend-answered-pages' }).

Go: in a Go module, rsc-kit init sees go.mod, writes the JS half - the
project's first package.json if it has none - and .env (RSC_BACKEND + a
generated secret) and prints the Go wiring; go get github.com/rsc-kit/go.
A new app: bun create rsc-kit --backend=<url>, or rsc-kit init in an empty
directory, which starts one there.
Laravel Go: laravelgo.Mount(route, func(ctx) http.Handler { return services.From(ctx).RSC })
from github.com/rsc-kit/go/laravelgo, NOT route.Handle - a standard handler runs
after Laravel Go saved the session, so a login is lost while answering 200.
Build the endpoint in services with env.String("RSC_HOST_CALL_SECRET", "")
(Laravel Go's .env is not in os.Getenv); auth.Attempt/auth.Logout/Session() take
laravelgo.Request(ctx). Guide: /hosts/go/laravel-go.

The backend writes rsc-host.json at the project root (beside vite.config.ts):
{ "actions": { module: { export: "Function.name" } }, "functions": ["Function.name", ...] }.
actions become "use server" modules, one per class: { "orders": { "create":
"Orders.create" } } is src/server-actions/orders.ts exporting create, and an
__invoke (or a Go function with no method) is the module's default export;
functions type rpc()'s first argument, so a misspelt name fails tsc. rpc is a
GLOBAL the build declares in .rsc-kit/rsc-env.d.ts - never import it. Have
Vite write the manifest so it cannot go stale:
rscKit({ hostManifest: { command: ['go', 'run', '.', '-manifest', '../rsc-host.json'], cwd: 'backend', watch: ['backend'] } })
(watch: rerun when the backend's source changes under dev, so new functions are typed
without a restart). rsc-host.json is rewritten every dev start and build, so it
is gitignored (init and create-rsc-kit add it); a CI typecheck before the build writes it first
(php artisan rsc:host-manifest). Committed rsc-host.json/types anyway? CI:
rsc-kit-typegen --check fails when they are stale.
An optional "sources" ({ "Orders.recent": { file, line, name } }, file relative to
the manifest) makes go-to-definition on the word rpc open the backend's function;
the string is not a link. Needs the function in "types". It restarts nothing and is
never stale, so do not strip it.
(Go: reg.WriteManifest(path); Laravel: php artisan rsc:host-manifest).

rpc() at build: with hostManifest, the build ASKS THE BACKEND and stores what is
the same for everyone; there is no attribute to add. A function that reads the
visitor (session, cookie, header, auth, address) or answers 401/403 is noticed
and streams per request, so it needs a <Suspense> above it as before. A stored
answer lasts until the next build - no tag, Rsc::changed or cache() refreshes it:
await connection() before the call asks per request, export const revalidate = 60
keeps it for a time. The build then needs the backend's database; a function that
throws fails the build; a function that writes, called from a render, writes at
build. Not noticed: raw $_COOKIE, state kept outside the framework (Go: outside
ctx) - await connection() there. No database in CI: hostManifest: { calls: false }.
Laravel answers by itself. Go: reg.BuildCalls("-calls") and, when that flag is
given, reg.ServeCalls(os.Stdin, os.Stdout) before the -manifest branch; a context
key that is not the visitor's: rsckit.NotTheVisitor("main.requestIDKey").
Go TYPED functions - prefer these: reg.Handle("Orders.recent", func(ctx context.Context, limit int) ([]Order, error) {...})
and reg.HandleAction(jsName, name, fn). Any positional params (structs, slices,
maps...), a trailing pointer is optional, variadic takes the rest. Their types
go into rsc-host.json, so rpc('Orders.recent', 5) is Order[] with no <T>, and
the action stub is typed and also accepts a FormData (fields -> the struct param:
the first, or the one after args bound with stub.bind(null, team)).
A typed Go function's nil slice/map is sent as []/{} (only a nil pointer is null).
A Go type with its own MarshalJSON is unknown in TypeScript - do NOT write a
narrowing helper in the page; give the type a JSONSchema method (rsc-kit/go v0.11.0+):
func (Money) JSONSchema() rsckit.Schema { return rsckit.Schema{"type": "string"} }
(keywords the build reads: type, items, properties/required, additionalProperties, enum, anyOf).
A backend FAILURE in development carries its trace: the thrown error's cause is
"Backend <Type>" with the PHP/Go frames, and the stack says "Caused in the backend
by ..." - read that before guessing (Laravel: app.debug; Go: CallbackHandler.Debug
or RSC_DEBUG=1). Never in production.
A server ACTION that fails in development opens Vite's error overlay on the
page: the backend's exception as the heading, the app's own file:line (e.g.
app/Rsc/Actions/Notification.php:20) as its file, dependency frames counted.
Production answers a bare 500. Fix the line it names; the overlay is not a bug.
An action answered by something other than the renderer (a 502 because the
renderer is not running, a proxy's error) opens the overlay with the status and
the answer's text. A page that throws opens it too, even reached by a link.
A failed rpc() in a server component: catch and check
error instanceof ServerAuthenticationError (401) / ServerAuthorizationError (403)
from '@rsc-kit/core/errors'; rethrow anything else.
reg.Register(name, func(ctx, args rsckit.Args) (any, error)) stays untyped.
Laravel: rsc:host-manifest types each app/Rsc method from its PHP signature -
int/float/string/bool params (nullable, defaults optional, variadic), a
FormRequest first param from its rules(), and a result that is a scalar, a
backed enum, or a plain class with public typed properties (a data object ->
an interface). array/Model/Collection/JsonSerializable stay unknown: give
those rpc<T>(). Return a data object, not an array, to get a typed result. Tests
answer the backend with createTestApp({ host }) - how_to testing.

Writing or changing an ADAPTER: it must pass the conformance suite before it
ships - register the Conformance.* functions (read_guide your-own-backend,
"Before you ship"), serve them, and run
npx -y -p @rsc-kit/core rsc-kit-conformance --endpoint <url>/__rsc/host-call --secret <s> --manifest rsc-host.json
(Go: cmd/conformance; Laravel: tests/Conformance are fixtures to copy).
BAP vs Inertia for a Laravel team: read_guide bap-vs-inertia.

A backend in another language answers that ONE endpoint, POST /__rsc/host-call,
and the renderer wires itself from two variables in .env: RSC_BACKEND (a
Laravel app's APP_URL counts) and RSC_HOST_CALL_SECRET. Both or neither.
A refused connection is tried again for up to 2s (nothing was sent, so nothing
runs twice): a backend started beside the renderer may come up second. Nothing
else is retried.
RSC_BACKEND_HEADERS={"X-Preview-Token":"..."} (JSON object) puts fixed headers
on every request to RSC_BACKEND, host calls and forwarded urls alike, never to
another origin; read once at startup; malformed stops the server, naming the
variable but not the value. For a platform that admits the renderer by a
header (a private preview).

A url the route tree does not own goes to the backend (/login, a webhook, an
OAuth callback). One that it DOES match does not: a dynamic root route such as
[team]/[app] matches every two-segment url, renders, says notFound() - and a page
that said that is never forwarded, so the backend's /gitlab/connect was the
app's 404 (and sign-in looped) - Laravel's /login and /auth/* as much as Go's
when the renderer is in front. Name the backend's prefixes, and they are
forwarded BEFORE any page is asked: rscKit({ backendPaths: ['/auth', '/github',
'/gitlab'] }). A prefix at a segment boundary (/auth, not /authors), every
method; '/', /_rsc and the host-call endpoint (/__rsc/host-call) are refused; a
team called auth is then unreachable. A whole segment in brackets is any one
segment: backendPaths: ['/login/[provider]'] is /login/google and what is under
it, NOT /login, which stays the page - for a backend route with a parameter
under a url that is a page. A page it would cover (login/forgot/page.tsx) stops
dev and the build, since it would never render; a dynamic FIRST segment and a
catch-all are refused; nothing is checked per request. Prefer a prefix of the
backend's own ('/auth') when the urls can move. The build lists the plain
prefixes as backendPaths in
.output/rsc-kit.json ([] when none; a dynamic one is left out and goes through
the renderer), so a proxy in front sends them straight to
the backend instead of through the renderer. The renderer never forwards a
browser's request for the host-call endpoint, however it is spelled
(/index.php/__rsc/host-call, //__rsc/host-call, an encoded slash): it answers
with its not-found page. A forwarded url carries no x-rsc- header the visitor
sent; only the renderer's own (x-rsc-renderer-fallback). Do NOT
write catch-all route.ts files that forward by hand: that copies the forwarding.
A named prefix is also a DOCUMENT LOAD in the browser, never a page: a Link,
visit() or redirect('/gitlab/connect') to it loads the document and is
never prefetched, so the backend route may bounce on to another site (an OAuth
start). NOT named, the router fetches it as a payload, the bounce to another
origin is a hop a fetch cannot make, and the tap does nothing. Do NOT work around
it with a client component that sets window.location.

Laravel: composer require rsc-kit/laravel, then php artisan rsc:install. It
runs rsc-kit init, which writes ONE vite.config.ts (laravel-vite-plugin is
moved aside - the renderer owns the frontend). Source is resources/js (the route tree is resources/js/app).

rpc() is a global the renderer installs in its own process (never imported,
never in the browser bundle): one POST to the backend's host-call endpoint
with { function, args }, the secret and the visitor's cookie; the answer is
the return value as JSON, typed by rpc<T>(). Refusals arrive as their kind
(422/401/403/redirect, or the status the backend gave: abort(429, 'Slow down')
keeps its 429 and its message), never a 500; sibling calls in one tick are batched
and each resolves the moment the backend answers it.
A BAP server bundle carries no database driver, ORM or auth library - the
backend owns those.

Reach PHP from a server component - rpc() is a global, typed in
.rsc-kit/rsc-env.d.ts, server render only:

  // app/Rsc/Orders.php: public function recent(int $limit): array
  const orders = await rpc<Order[]>('Orders.recent', 5)

The call runs AS THE VISITOR (their cookie is forwarded; auth()->user() is
them). Refuse with Laravel's own attributes, as on a controller
(Illuminate\\Routing\\Attributes\\Controllers): #[Middleware('auth')],
#[Authorize('update', Order::class)], #[Middleware('throttle:60,1')]. Before
rsc-kit/laravel 0.28 #[Authorize] guarded nothing; there, use
#[Middleware('can:update,App\\Models\\Order')]. A method takes services and
#[CurrentUser] beside its arguments (0.28), and a call never sends
them. logout(Request $request) works as in a controller (0.29): the form is its
input, the visitor's session and user are on it; request() is the host call's.
An action's guards run against the page its form was posted from (core 0.44,
laravel 0.30): #[Middleware('signed')] on verify(EmailVerificationRequest
$request) checks the link the visitor followed, and $request->route('id') is
the page's {id}. A model param is bound from the page: publish(Post $post) with
#[Middleware('auth')] #[Middleware('can:update,post')] is the page's {post},
the one the policy saw (404 from no page). One guard per attribute: Laravel's
takes a string, and an array is a TypeError. An action is a POST endpoint: the page's guards
never run for it, and the caller picks the page, so every action carries its
own auth and authorizes the record it changes. When the method takes a
Request, its guards' request carries the form's fields too (laravel 0.31.1), so
Fortify's throttle:login, keyed on the email, counts per email.
A method answers as a controller does (laravel 0.31): return redirect(),
to_route() or back() - back() is the page the form was posted from, a
success for <Form> - or a Responsable (Fortify's LoginResponse); a JsonResponse
is its data. From deeper in, throw Laravel's HttpResponseException.
back()->withErrors() is a 422 under the fields. There is no RscRedirectException
and no Rsc::flash: Laravel's own redirect and flash do it.
A stub is a plain form's action too (core 0.45.3): <form
action={session.destroy}><button>Sign out</button></form> typechecks, and a
redirect it returns is followed. Use <Form> when the form shows errors.
A ValidationException lands on the form as validationErrors; Authentication/Authorization exceptions answer 401/403. An
action shows an abort()'s message to the visitor as written, so give it one -
abort(429, 'Slow down'); without one the form says "Refused.". Only a failure
is replaced by onError's generic message.

Guard a route in Laravel's vocabulary, no route declared in PHP:

  // resources/js/app/admin/middleware.ts
  export const middleware = ['auth', 'verified', 'can:update,post']

They run against the page's request, not the host call's: signed checks the
link the visitor followed, throttle counts per visitor and once per page load,
and can:update,post gets the {post} the route bound - bind it with
Route::bind or Route::model, since a page has no controller signature for
implicit binding. auth sends a guest to route('login'); an app with no route
of that name fails with "Route [login] not defined" - set
$middleware->redirectGuestsTo('/login') in bootstrap/app.php (a full url when
login is on another host). A page is named by its path (app/orders/[id] is
orders.id, the root is home); one Laravel's code asks for by name declares it
in the page: export const name = 'verification.verify' (or 'login',
'password.reset', 'verification.notice') - the notification's link is then the
page, no routes/web.php route, no createUrlUsing. A route.ts may declare one
too; a name routes/web.php also gives a route elsewhere fails at boot. In Go, a guard reads rsckit.PageFrom(ctx) (URL, and Params:
only the route's own, never the query) and rsckit.ClientIP(ctx).

Make one: php artisan make:rsc-action Orders --method=cancel --auth
--can=update,Order --middleware=throttle:60,1 --revalidate=orders (--rpc for
an rpc() class under app/Rsc; no --method = invokable; a slash nests,
Billing/Invoices). Do NOT hand-write the attributes from memory; the command
writes the ones the registry reads, and it writes the manifest
(rsc-host.json) too - a running dev server restarts on its own when it
changes, so the export is importable when the command returns.
One dev server per app: a second vite names the one already running (composer
dev, Herd's artisan dev or an editor may have started it) - use that one. In a
terminal the second exits, naming the pid to stop; under a runner it waits and
starts when the first stops. A vite that sits waiting is not hung.
Server actions are classes in app/Rsc/Actions, found by reflection in PHP;
\`php artisan rsc:host-manifest\` writes rsc-host.json - { actions,
functions } - and vite.config.ts runs it as dev and every build start:
rscKit({ hostManifest: { command: ['php', 'artisan', 'rsc:host-manifest'] } }).
functions types rpc()'s first argument, so a misspelt name fails tsc. The
build writes a "use server" module per class from actions - import * as
orders from './server-actions/orders' in a client component, then
orders.cancel(id); a nested class, Billing/Invoices, is server-actions/billing/invoices.
An invokable class is the module's default: import sendInvite from
'./server-actions/send-invite'. server-actions/ is the build's: never edit it. Rsc::revalidate('orders')
in the action returns the re-rendered region with the answer.

Per url: if the React tree has it, React renders it, otherwise Laravel does
- including / : the welcome route in routes/web.php answers nothing while
resources/js/app/page.tsx exists (the package registers the tree's urls from
bootstrap/rsc/vite/routes.json after routes/web.php). Do NOT tell the user
to delete the welcome route to make the page show; do not add Laravel routes
for React pages.

php artisan serve is one worker, which deadlocks the proxy - unless
PHP_CLI_SERVER_WORKERS=4 in .env AND serve --no-reload (Laravel ignores
the variable otherwise). Herd, Valet, FPM, Octane are fine as they are. Production: put the renderer in front (bun
.output/server/index.mjs with the app's .env), restrict /__rsc/host-call at
the web server.

Any other language implements the same endpoint - request { function, args },
reply { result | validationErrors | unauthenticated | unauthorized | redirect
| error, revalidate }, answers '__rsc.middleware' with true or a refusal, and
a batch { calls: [...] } as application/x-ndjson - one line per call AS IT
FINISHES, { index, status, ...reply }, in any order, flushed each time
(X-Accel-Buffering: no) - or, less good, one JSON { replies: [...] } in
order (every call then waits for the slowest). Calls issued in the same
render tick travel as one batch, so parallel reads are one backend request
and a fast read still resolves while a slow sibling runs. Batches are
required: any other answer fails every call in it (at most 50 per batch;
413 for more is fine).

Full guides: read_guide({ slug: 'backend-answered-pages' }), read_guide({ slug: 'laravel' }), read_guide({ slug: 'go' }), read_guide({ slug: 'your-own-backend' }).`,
    },
    {
        topic: 'startup',
        summary: 'Once-per-process setup and teardown, and request logging - src/instrumentation.ts is imported before any page, its register() awaited before the first request, its shutdown() called when the server stops, its onRequest() once each response is over',
        body: `Setup that belongs to the process - validating env, configuring a shared
package, warming a connection - goes in src/instrumentation.ts. Do NOT import
a bootstrap module from pages to get the same effect; it depends on nobody
forgetting, and the failure is a page throwing "not configured" for whoever
reaches it first.

  // src/instrumentation.ts
  import './env'                       // refuses at import -> server fails at startup
  export async function register() {   // optional; the first render waits for it
    await db.connect()
  }
  export async function shutdown() {   // optional; called when the server stops
    await db.end()
  }

The generated entry imports this file FIRST, so a package configured here is
configured before any page module evaluates. register() is awaited by every
entry point (server, dev, prerender, middleware, actions, api routes), once
per process. On a server it runs at startup and a failure exits the process;
on a Worker it runs at the isolate's first request.

Stopping is automatic: on SIGTERM/SIGINT a built server drains in-flight
requests (SERVER_SHUTDOWN_TIMEOUT, 5s), calls shutdown() (RSC_SHUTDOWN_TIMEOUT,
10s; a hang or throw does not hold it) and exits 0. Do NOT add a SIGTERM
handler that calls process.exit() - it runs before the drain and drops
in-flight requests. A logger flushes on 'exit', never on a signal.

Request logging: export onRequest() from the same file, and the engine calls it
once per request it answers (page, payload, action, route.ts) when the response
is OVER - the last byte sent, or the visitor gone mid-stream:

  export const onRequestHeaders = ['cf-ray']   // the only headers it is given
  export function onRequest({ method, pathname, status, durationMs, aborted, error, headers }: ServedRequest) {}
  // ServedRequest from '@rsc-kit/core/request'

durationMs runs to the last byte; aborted is true when the visitor left
mid-stream; error is set when the render failed. pathname has NO query string.
Do NOT log from middleware.ts for this (it runs before the render, so it never
sees the end), and do NOT wrap the server entry - it is generated. onRequest()
is not awaited, and a throw from it never fails the page.

A file in src/commands (how_to commands) does NOT import this one unless it
exports \`register = true\` (the literal): without it the command runs from a
bundle that leaves instrumentation.ts out, so none of its top level - env
validation included - runs for it. With it, the file is imported and
register() runs first.

Worker rule: read bindings INSIDE register(), not at the top of the module -
process.env is empty until the first request arrives.

A scaffolded app with env validation already has this file importing ./env.
Build machines without production variables: SKIP_ENV_VALIDATION=1.

Never NODE_ENV in a .env: Vite sets it (development under vite, production
under vite build) and a .env line overrides it for the build, which then
compiles pages against React's dev JSX runtime (jsxDEV) and every route
fails with React's opaque "message omitted in production builds". The build
refuses this and names the file:line. A plugin cannot override it (Vite
applies the .env value after plugins run), so remove the line - other tools
that want it keep it in their own .env.

Full guide: read_guide({ slug: 'instrumentation' }).`,
    },
    {
        topic: 'commands',
        summary: 'A release step or a worker is the same app started differently - src/commands/<name>.ts run as ./app migrate, or node .output/server/commands.mjs migrate',
        body: `Migrations before a deploy, a queue worker, a one-off script: a file in
src/commands, with a default export. It shares the pages' bundle and
dependencies (the database package, the logger), so there is no second build and
no second binary.

  // src/commands/migrate.ts
  import { db } from '@repo/database'
  export const description = 'Apply the database migrations'   // plain string; \`--help\` lists it
  export const register = true                                  // opt in to instrumentation.ts and its register()
  export default async function (args: string[]) {
    await db.migrate({ dryRun: args.includes('--dry-run') })
  }

  ./app migrate --dry-run                                  # the compiled binary
  node .output/server/commands.mjs migrate --dry-run       # a plain build (bun works too)
  ./app --help                                             # lists them
  ./app                                                    # no arguments: the server, as ever

The return value is the exit code: nothing is 0, a number 0-255 is itself, a
throw is 1 with the error and each cause on a [cause]: line (Drizzle's failed
query keeps the database's reason there - do NOT catch to re-log it), any other
return (a string, 256) is 1 and says so.
An unknown name exits 2. Return the code - do NOT process.exit() inside a
command, it skips shutdown(). args is everything after the name, untouched:
./app migrate --help gives migrate the --help.

A command is a file DIRECTLY in src/commands; the name is the file's name. \`*.d.ts\`,
\`*.test.ts\`, \`*.spec.ts\` and names starting with _ or . are not commands (_shared.ts
is how two share a helper). A folder is not one: db/seed.ts is not db:seed, and
the build says so.

./app --help and an unknown name are answered before the app loads (from a list in
the entry), so they need no valid environment. A real command loads the app's
code, but NOT instrumentation.ts unless it exports \`register = true\` (the
literal; the build reads it to pick the bundle): a queue drain should not fail
on the web's Stripe key. It validates what it imports - \`import '@repo/env/worker'\`
in the command. With register = true, instrumentation.ts is imported (its env
validated), register() runs first, and shutdown() after it returns, also after
it throws.

A worker is a command that waits. Its second argument is the context,
{ signal, deadline } (the type is CommandContext, from '@rsc-kit/core/commands',
which also has defineCommand to type a command without annotating it). signal
is aborted by SIGTERM/SIGINT. Return when it aborts and the process runs
shutdown() and exits 0; RSC_SHUTDOWN_TIMEOUT (10s) bounds it, a second signal
does not wait. deadline is when the runner stops waiting (a Date.now() time),
undefined until told to stop - budget the current job against
context.deadline - Date.now(), do not re-read RSC_SHUTDOWN_TIMEOUT. deadline
is a GETTER: do NOT destructure it ((args, { signal, deadline }) reads it once,
at the start, when it is always undefined, and keeps that); read context.deadline
when you need it. signal is a plain property and can be destructured.

A stop reaches a command one of two ways, so a command that waits needs BOTH
the check and the listener. BEFORE it starts (while the app loads, tens of ms, or
during register()) the signal is ALREADY aborted and its 'abort' event has fired -
the runner gives the event loop one turn before calling the command, so a waiting
stop is delivered first (the same on Node, Bun and a binary). AFTER it starts
(the usual case) signal.aborted turns true and 'abort' fires while it runs. So:
check signal.aborted as the command starts, and listen for 'abort' - or pass
signal to something that does ({ signal } to a queue, sleep(ms, undefined,
{ signal })). Checking alone misses a stop during a long await; listening alone
waits for ever on a stop that came first. The loop below does both.

  import { defineCommand } from '@rsc-kit/core/commands'

  export default defineCommand(async (_args, { signal }) => {
    while (!signal.aborted) await queue.processNext({ signal })
  })

The entry holds SIGTERM/SIGINT from its first line, however long the app takes
to load. In a compiled binary Bun first parses every module in the file (about
170 ms for 580 modules and 119 MB), and a stop in that time is the default
action: exit 143. --splitting makes the entry its own chunk, and the scaffold's
compile script has it: bun build --compile --splitting
.output/server/compile.mjs --outfile dist/app. An app made before it keeps its
old script until the flag is added; Bun 1.2 refuses it ("cannot use --compile
with --splitting"). The same stop 250 ms into an 80 MB
binary exits 143 without it and 0 with it. A plain build has no such window.
--sourcemap with --compile embeds the map and ALSO writes .map files beside the
binary (one per chunk with --splitting: hundreds for a large app, dist/ in the
hundreds of MB). The binary does not read them - a stack trace is the same with
them deleted - so ship the binary alone and rm -f dist/*.map, or leave
--sourcemap off (the scaffold does).

Do NOT run \`node .output/server/index.mjs migrate\`: index.mjs is the server and
ignores its arguments, so that starts the server. Commands are for the bun and
node presets only. On a Worker the build leaves src/commands out and says so
(run the file in CI, or wrangler for D1); in \`vite dev\` run the file itself
(\`bun src/commands/migrate.ts\`). The build lists them in .output/rsc-kit.json
as \`commands\`.

A scheduler is a command that keeps running (like Laravel's schedule:work): a
\`while (!signal.aborted)\` loop that runs what is due and then
\`await sleep(60_000, undefined, { signal }).catch(() => {})\` (sleep is
setTimeout from node:timers/promises), started as \`./app schedule\`. Run ONE
instance - two run every job twice, which is why a schedule does not belong in
the web server, which runs as many copies as it is scaled to. A job that runs
once a day is an ordinary command started by the platform's cron.

Full guide: read_guide({ slug: 'commands' }).`,
    },
    {
        topic: 'workers',
        summary: 'Cloudflare Workers: bindings (D1, R2, KV) from cloudflare:workers',
        body: `On Cloudflare the preset is cloudflare_module (Workers), never
cloudflare_pages: a Pages build answers every page with a bare 500, and
Cloudflare is moving Pages projects to Workers.

A D1 database, an R2 bucket or a KV namespace named in wrangler.jsonc is
read from \`cloudflare:workers\`, the runtime's own module: the bundle leaves
it external, like bun:sqlite. \`vite dev\` under Bun or Node has no such module,
so import it lazily, behind a runtime check - never at the top of a module a
page imports, or dev and the build fail to resolve it.

\`\`\`ts
const onWorkers = typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers'

export async function db() {
  if (onWorkers) {
    const { env } = await import('cloudflare:workers')
    return env.DB
  }
  const { Database } = await import('bun:sqlite')
  return new Database('data/local.sqlite')
}
\`\`\`

The build renders through the same module: a page that reads a table and
nothing from the request is frozen from the local database at build time,
and only pages that read the url or the request reach D1 per request. Do NOT
put env.DB on a global or read it at import time. wrangler.jsonc: the
d1_databases / r2_buckets entries wrangler printed at create time.`,
    },
    {
        topic: 'bun',
        summary: 'Running on Bun - Vite on Bun\'s runtime (bun --bun vite), native deps external (serverExternalPackages), and the gotchas that are Bun\'s not ours',
        body: `The vite bin has a node shebang: \`bun run dev\` alone starts Vite - dev
server, build, prerender - under NODE, and an app importing 'bun' or
'bun:sqlite' fails at first render with "Cannot find package 'bun'". Scripts
on a Bun app: dev "bun --bun vite", build "bun --bun vite build". createTestApp
runs the project's build script on the runtime the tests use.

Nitro is pinned EXACTLY in package.json: "nitro": "3.0.261103-rc" - never ^3.0.0,
which npm resolves to an older plain 3.0.0 that 404s every route. That version is
also the OLDEST rsc-kit runs on: an older one (3.0.0 included) stops the build
with "nitro X is older than 3.0.261103-rc"; fix the pin and install again.

Native dependencies (sharp, bcrypt, better-sqlite3, @prisma/client, puppeteer,
...) are external to the server bundles by default; Nitro traces them into
.output/server/node_modules with their binaries. Add one:
rscKit({ serverExternalPackages: ['@acme/native'] }). Same as Next's option.
A compiled binary (bun run compile) carries those packages and writes them to
disk on its first start, to $RSC_KIT_RUNTIME_DIR/<hash>/ (default: beside the
binary), and loads them from there - so the binary needs a WRITABLE directory:
on a read-only filesystem set RSC_KIT_RUNTIME_DIR (e.g. /tmp/app). One
directory is safe to share: a later start writes nothing, two at once do not
clash, and each version has its own hash folder (one untouched for a day is
removed). What goes to disk: packages with a .node/.wasm (or os/cpu), packages
depending on them, their dependencies, and anything in serverExternalPackages
(name a pure-JS package there when it reads files beside its own code); pure JS
stays bundled. Compiling for another platform (--target=bun-linux-x64 on a Mac)
needs that platform's packages installed beside the build machine's:
bun install --os=darwin --os=linux --cpu=arm64 --cpu=x64. Without them
\`bun run compile\` (and compile:binary after that build) fails and names them;
do NOT work around it by dropping --target or copying node_modules next to the binary.
The compile step is two scripts: compile is "vite build && bun run compile:binary",
compile:binary is the bun build --compile alone, and .output/rsc-kit.json names
compile:binary so a deploy that has just built does not build again. Keep both;
do NOT put vite build back inside compile:binary.

The other direction: a dependency with "use client" files that does NOT
declare react as a peerDependency (generated wrappers, workspace packages
with react under dependencies) would be left external by plugin-rsc and its
directive never read - hooks then run on the server. The build detects direct
dependencies in that state and bundles them, printing
"[rsc-kit] bundling <pkg>: it has "use client" files but does not declare
react as a peer dependency". Nothing to configure; fix the package's
peerDependencies when it is yours.

Bun's, not the framework's: bun test loads the package .env (use
--env-file=/dev/null to isolate); Stripe's constructEvent throws on Bun
(no sync WebCrypto) - use constructEventAsync; Bun's pg puts SQLSTATE in
errno where Node's pg uses code.

Never NODE_ENV in a .env (the build refuses it, naming the line). Build
machines without secrets: SKIP_ENV_VALIDATION=1. A built server started
with no NODE_ENV sets the one it was built with in its own process before
the app loads, so process.env.NODE_ENV and env.NODE_ENV are 'production' at
run time - do NOT add NODE_ENV=production to a start command or a Dockerfile.
That makes rsc-kit's production checks run: an app using refreshOn sets
RSC_SIGNING_SECRET or its live pages answer 500.

reflect-metadata (tsyringe, typeorm, inversify - often under
@simplewebauthn/server): nothing to import; when the graph has it the build
loads it in a Nitro plugin ahead of the app, so the "tsyringe requires a
reflect polyfill" boot error does not happen in a directory or a binary.

Build, then start - NEVER run vite build while bun/node .output/server/index.mjs
is serving from that .output: services load lazily and a failed import of a
half-written chunk is cached by the runtime (ENOENT 500s until restart).

Single binary (Bun): bun build --compile .output/server/compile.mjs
--outfile dist/app (the scaffold's "compile" script). With src/commands the same
binary is also ./app migrate (how_to commands). compile.mjs is written
by the build and embeds the frozen pages; with serveStatic: 'inline' in the
Nitro plugin the assets (and their .br/.gz) are inside too. Ship dist/app
alone - a Dockerfile copies nothing else, not .output/public. --bytecode
compiles the JS ahead of time (cold boot 275 ms -> 72 ms measured, for an
image 81 MB -> 117 MB - on a pod the pull costs more than the boot saves).
Bytecode is CommonJS: a module using import.meta.env / .filename / .resolve
/ bare import.meta (a dependency, usually) fails it, and Bun names no file
and EXITS 0 - the binary dies at boot with "import.meta is only valid
inside modules". Use --bytecode --format=esm, which applies regardless. A production
app ported from Next measured the binary image at 50.12 MiB against the
Next image's 104.56 MiB, the docker build at 2m45s against 5m13s, and
Lighthouse at 99 mobile / 100 desktop - nothing tuned for the numbers.

Nothing is sent raw: a built bun/node server gzips what it answers
(documents, streams flushed per chunk, payloads, stored pages, api routes)
for a request that accepts it, and the build writes .br/.gz beside every
public asset, served by Nitro. Nothing to configure; a Worker leaves it to
the platform. Off: compress: false on the handler / compressPublicAssets:
false in Nitro config; Cache-Control: no-transform exempts one answer. Do
NOT add a compression middleware or precompress assets yourself.

Full guide: read_guide({ slug: 'bun' }).`,
    },
    {
        topic: 'openapi',
        summary: 'An OpenAPI document derived from route.ts files - rscKit({ openapi }) - and Scalar\'s page over it, mounted as a route',
        body: `Do NOT hand-write an OpenAPI spec. rscKit({ openapi: true }) in
vite.config.ts answers /openapi.json, derived from every route.ts: the
directory is the path ([id] -> {id}), each method export an operation,
params/searchParams/body schemas the parameters and request body (Zod 4 and
ArkType describe themselves as JSON Schema; Valibot not yet), a middleware.ts
above a route a security requirement + 401/403. Stored at build, no middleware.

Document-level parts go on the option:
  rscKit({ openapi: { info, servers, security, components: { securitySchemes } } })
What a route says about itself, beside its handler:
  export const openapi = { summary, tags, responses: { 200: {...} }, POST: { summary } }
  export const openapi = false   // leave this route out (the reference page, a webhook)
  export const openapi = { DELETE: false }  // one method out; HEAD/OPTIONS never documented
Webhook-heavy app: rscKit({ openapi: { include: 'declared' } }) documents only
routes that export openapi, so callbacks need no opt-out line.
Response bodies are declared in openapi.responses until a typed helper exists.

The page: Scalar's renderer, one route, nothing shipped by the engine:
  // src/app/reference/route.ts    (bun add @scalar/client-side-rendering)
  import { renderApiReference } from '@scalar/client-side-rendering'
  export const GET = () => new Response(renderApiReference({ config: { url: '/openapi.json' } }),
    { headers: { 'Content-Type': 'text/html; charset=utf-8' } })
  export const openapi = false
NOT @scalar/nextjs-api-reference: same call plus a theme, but its peer
dependency on next makes npm/pnpm/bun install all of Next.js into the app.

Porting a spec file: delete its paths (they are the routes now, and body
validates at runtime), move info/servers/security to the option, move a
route's summary/tags/responses to its openapi export.

Full guide: read_guide({ slug: 'openapi' }).`,
    },
    {
        topic: 'secrets',
        summary: 'The secrets rsc-kit reads - RSC_HOST_CALL_SECRET, RSC_SIGNING_SECRET, RSC_ACTION_ENCRYPTION_KEY - what each protects, how to generate them, where they go in production, and what rotating one does',
        body: `Three, each its own key for its own job. Never reuse one as another.

  RSC_HOST_CALL_SECRET       renderer <-> Go/Laravel backend calls. Required with a
                             backend; read by the renderer AND the backend.
  RSC_SIGNING_SECRET         signs refreshOn names a page hands the tab. Required in
                             production when any page/section uses refreshOn (the
                             server refuses to serve without it). Renderer only.
                             Never falls back to the host-call secret.
  RSC_ACTION_ENCRYPTION_KEY  optional: pins the key server actions encrypt with, so
                             actions survive a deploy. Set at BUILD time too.

GENERATE - once each, a different value each:
  openssl rand -base64 32
  node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
  php -r "echo base64_encode(random_bytes(32)), PHP_EOL;"
Development: create-rsc-kit / rsc-kit init (with a backend) and
php artisan rsc:install write the first two into .env already.

PRODUCTION - in the platform's environment settings, never in git:
- the SAME value on every instance (a tab served by one renderer is checked by
  another; a call may land on any backend replica);
- read at runtime, so one build deploys anywhere (except the action key).

ROTATING is a deploy:
- host-call: the backend first. Give it the new value and the old one as
  RSC_HOST_CALL_SECRET_PREVIOUS (it answers either), then the renderer the new
  value, then remove RSC_HOST_CALL_SECRET_PREVIOUS. No call is refused. Before
  core 0.30.54 / go v0.17.0 / laravel 0.21, change both together.
- signing: open pages stop refreshing until reloaded; nothing else breaks.
- action key: actions from pages loaded before the change fail.

Docs: /hosts/deployment/secrets/.`,
    },
    {
        topic: 'env',
        summary: 'Typed environment variables - src/env.ts with @t3-oss/env-core in the app\'s validation library; refused at startup by name. Never NODE_ENV in .env',
        body: `A scaffolded app has src/env.ts when it said yes to typed environment
variables (create-rsc-kit --env, with --validation=zod|valibot|arktype). To
add it to an app without one: install @t3-oss/env-core and write the same file.

\`\`\`ts
// src/env.ts
import * as z from 'zod'   // or valibot / arktype - any Standard Schema library
import { createEnv } from '@t3-oss/env-core'

export const env = createEnv({
  server: {
    NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
    DATABASE_URL: z.url(),
    SESSION_SECRET: z.string().min(1),
  },
  clientPrefix: 'VITE_',
  client: { VITE_SITE_URL: z.url() },
  // No bare process.env: import.meta.env carries the VITE_ values, and the
  // file does not throw in the browser if a client component imports it.
  runtimeEnv: { ...(typeof process === 'undefined' ? {} : process.env), ...import.meta.env },
  emptyStringAsUndefined: true,
  skipValidation: typeof process !== 'undefined' && !!process.env.SKIP_ENV_VALIDATION,
})
\`\`\`

Read env.DATABASE_URL, never process.env.DATABASE_URL: the first is typed and
was checked at startup (a missing or malformed one fails then, with its name),
the second is string | undefined. env.NODE_ENV is 'production' on a built
server with nothing set (the server sets it from the build's mode before the
app loads), so its .default('development') is only a dev server's or a
script's. A server variable never reaches the browser;
a browser-readable one MUST start with VITE_ and is read from import.meta.env
(Vite's own prefix and the only one - a PUBLIC_* variable, once accepted
beside it, fails the build by name), which is why runtimeEnv merges both. Commit .env.example, not .env.

CLIENT COMPONENTS DO NOT IMPORT src/env.ts. A "use client" file (or a lib file
one imports) reads import.meta.env.VITE_X directly, declared in
ImportMetaEnv. Importing env there ships the validation library to the
browser - measured: 20 kB gzipped of Zod + env-core in a chunk that needed one
url. The value is still validated: the server imports env at startup.

Next: NEXT_PUBLIC_* becomes VITE_*; @t3-oss/env-nextjs becomes
@t3-oss/env-core with runtimeEnv as above (env-nextjs's experimental__runtimeEnv
is not needed).`,
    },
    {
        topic: 'refresh-on',
        summary: 'Refresh a page or section when the backend says its data changed - a webhook, a job, another user - with nothing polling: refreshOn on a section + Changed / Rsc::changed / changed(); server-initiated revalidation; where revalidateTag was',
        body: `A section names the data it shows; whatever changes it says so, from
anywhere; every open tab showing it refreshes. No polling, no stream to
write, no library.
\`\`\`tsx
// src/app/t/[team]/repos.section.tsx
import { section } from '@rsc-kit/core/section'
const ReposSection = section('repos', Repos, { refreshOn: ({ params }) => [\`team:\${params.team}:repos\`] })
export default ReposSection   // named, so the editor offers it as an import: a bare export default section(...) is offered as reposSection
// the name is the file's: repos.section.tsx is section('repos'); a different name fails the build
// a page: export const refreshOn = ({ params }) => [...]  -> a change refreshes the page
// typed from its schemas: export const refreshOn: PageRefreshOn<typeof params> = ({ params }) => [...]
//   (import type { PageRefreshOn } from '@rsc-kit/core/section'; params arrive awaited + parsed)
// no schema: PageRefreshOn<'/[team]/[app]/[env]'> types params from the route's pattern;
//   a misspelt param or a pattern that is not a route fails the typecheck
// export const / function / { refreshOn } / { refreshOn } from './x' all count; export * from does not
\`\`\`
A LAYOUT'S REGION - what is the same on every tab (a title, a status, the tab bar)
belongs in the layout, which stays mounted while the pages under it change, and
when it shows data that changes it is a section there. A page refreshes the
sections beside it and then those beside its layouts, nearest first, so
revalidate('header') from an action on any tab, or a refreshOn change, renders
just that. Put it in its own <Suspense> in the layout (it reads params, and a
layout that awaits them above every boundary fails the build). Pass
params={params} through; a refresh renders the section with the page's props, which hold every segment the layout's do. A name
is unique along the chain (the nearer one wins). A refresh is swapped in as a
transition: the section keeps what it showed until the new content is ready,
never its skeleton, so do NOT add a cache or a held copy to avoid the blink.
What a refresh rendered lasts
as long as the layout: a visit to another page under it keeps it, so a rename's
new name stays in the frame after the form navigates. refresh('<section>') keeps the
pages held for Back and what was prefetched; refresh() and refresh('all') drop them,
so poll a section by name, not the page, where Back should stay instant. The active tab is usePathname()
in a client component, not a refresh. Do NOT draw the header in each tab's page
inside its Suspense: a tab switch mounts a new page, and its fallback replaces
the header until the data arrives.
PARENT AND CHILD - a change to a child changes its parent's list: say both
where the write is - changed(\`app:\${id}\`, \`team:\${teamId}:apps\`) - and let each
region name only what it shows. Never make a list watch every child's name.
NOTHING ANNOUNCES IT (a host's logs, a third-party status) - usePolling, not refreshOn.
WHO MAY WATCH - a name is signed for a day, so a tab can watch only what its page
was rendered with; past that the tab renders its regions again as its visitor and
gets fresh names, and someone who lost access (removed from the team) is refused
that render and stops hearing. A page or section that ends in notFound() hands out
no names, so build:\${params.build} from the url is not signed for a build that is
not there - but only notFound() from the page's or section's own function: a
record looked up in a child component is past that, so look it up in refreshOn
or the page itself. Never put a secret in a name; ids only.
TEST IT - (await createTestApp()).watched('/teams/acme') -> { page: [...], apps: [...] },
the names each region is handed; [] means refreshOn gave none (also warned in dev).
SAY IT CHANGED - wherever the change happens, not only in an action:
  Go:      reg.Changed(ctx, "team:"+teamID+":repos")         // the webhook handler, a job
  Laravel: Rsc::changed("team:$teamId:repos");               // a controller, a job, a listener
  JS only: import { changed } from '@rsc-kit/core/changed'; await changed(\`team:\${team}:repos\`)
ANY DATABASE - rsc-kit ships no driver; hand it yours. Postgres:
postgresVersions(sql) (postgres.js/Bun.sql, or Drizzle's db.$client) - one
statement per change, instant via LISTEN. MySQL/MariaDB: sqlVersions({
dialect: 'mysql', query: async (t, p) => (await pool.query(t, p))[0] })
(mysql2). SQLite: sqlVersions({ dialect: 'sqlite', query: async (t, p) =>
db.query(t).all(...p) }). libSQL/Turso: sqlVersions({ dialect: 'sqlite',
query: async (sql, args) => (await client.execute({ sql, args })).rows }).
Always pass dialect: without it a change is a read + write per name.
Redis/ORM query builders: createVersions({ read, bump, listen?, notify? }).
Instant across instances: postgres.js LISTEN, Redis pub/sub; others within ~1s.
NO BACKEND (JS only) - changed() works as-is on one server. With more than
one instance, or a worker process that finishes jobs, keep versions in a
table they all share: installVersionSource(postgresVersions(sql)) in
instrumentation.ts register() AND in the worker (postgres.js LISTENs, so
cross-instance changes are instant; so does Bun.sql (Bun 1.4+); any SQL
driver/ORM: sqlVersions({ query }) - Prisma: query: (t, p) =>
prisma.$queryRawUnsafe(t, ...p); anything else (Drizzle query builder, Redis,
KV): createVersions({ read(names), bump(names), listen?, notify? }) and
rsc-kit does the waiting/waking). An app-installed store always wins over a
backend's. In-memory versions fail with 2+ instances; in production rsc-kit logs a
warning once when it falls back to them - installVersionSource(memoryVersions())
says "one instance on purpose" and silences it.
A DIRECT DATABASE EDIT (psql, a migration, an admin tool, another app) says
NOTHING: nothing watches tables, so open tabs stay stale until refreshed (a reload
reads fresh - the data is not wrong). Make the WRITER call changed() after the
commit; or put a TRIGGER on the data table that upserts the rsc_versions row in
the same transaction (moves with the commit, a rollback moves nothing) and, on
Postgres, pg_notify('rsc_versions', '') so tabs hear at once - without it up to
30s with a listening store, 1s without; the name must be spelt as refreshOn
spells it. usePolling only where nothing can say it.
Table: rsc_versions(name TEXT PRIMARY KEY, version BIGINT NOT NULL) - same as
Go's SQLVersions. ANY process can bump without rsc-kit, with one upsert that
moves version to GREATEST(version + 1, now in ms) - Postgres:
INSERT ... VALUES (name, (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
ON CONFLICT (name) DO UPDATE SET version = GREATEST(rsc_versions.version + 1,
EXCLUDED.version); then NOTIFY rsc_versions. MySQL: GREATEST(version + 1,
VALUES(version)) with FLOOR(UNIX_TIMESTAMP(NOW(3)) * 1000); SQLite: MAX(...)
with CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER).
CLEANUP - a version is the time a name last changed, so deleting old rows is
always safe (a tab holding one refreshes once; it never comes back at a value
a tab holds): versions.prune() on sqlVersions/postgresVersions (30 days), or
DELETE FROM rsc_versions WHERE version < <ms 30 days ago> from a cron.
memoryVersions forgets after 30 days; the server forgets names no tab
watches. Go: store.Prune(ctx, 0) on SQLVersions/MemoryVersions. Laravel:
cache keys expire after RSC_VERSIONS_KEEP_DAYS (30); with
RSC_VERSIONS=database schedule php artisan rsc:prune-versions daily. A custom store's bump MUST use nextVersion(current) - never + 1, which repeats once a row is pruned.
GO, SEVERAL INSTANCES - SQLVersions is noticed within ChangedPoll (1s). For
at once: SQLVersions{..., Notify: "rsc_versions"} plus reg.WakeOn(ctx,
listener) where the listener (pgx: LISTEN rsc_versions, WaitForNotification)
calls connected() then wake() per notification. One instance needs neither.
WORKERS, ONE HUB - by default each isolate watches its own tabs: one ask per
tab every 2s. nitro({ preset: 'cloudflare_durable' }) plus wrangler.jsonc
durable_objects binding "$DurableObject" (class "$DurableObject", migration
new_sqlite_classes) and vars RSC_CHANGES_HUB: "$DurableObject" sends every
tab's stream to one Durable Object: one ask for all tabs, changed() in any
isolate wakes it at once (instant even on D1), one wakeOn/broadcast
connection. Versions still live in the shared store (D1, backend). Costs
Durable Object active time while tabs watch; opt-in, never detected.
TABLE - the app owns rsc_versions (rsc-kit never creates/alters it at
runtime): name TEXT PRIMARY KEY (MySQL: VARCHAR(255)), version BIGINT NOT
NULL. Extra columns fine if they have defaults. Drizzle: a pgTable in your
schema + createVersions with the query builder (not raw SQL).
POOLERS - a pooler in TRANSACTION mode (PgBouncer; DigitalOcean/Supabase/Neon
pooled URLs) silently drops LISTEN. postgresVersions probes once as it starts
listening; if deaf it logs why and reads every second. Fix:
postgresVersions(pool, { listenWith: directOrSessionModeClient }) - one extra
connection per process; reads/writes stay on the pool. (await connection() is
unrelated: it is about rendering per request.)
POLL ON PURPOSE - postgresVersions(pool, { listen: false }) when direct
connections are scarce: no listener, no probe, no warning; one indexed read per
second per process for all its tabs; other instances' changes within ~1s.
WORKERS / SERVERLESS - the stream is stateless (signed names) so it runs where
responses stream, but: each isolate/instance watches for its own tabs, so
in-memory versions are useless - use a shared store. Platform request limits
cut streams (they reconnect and catch up); billed-per-second functions pay for
every watching tab; Hyperdrive/serverless drivers can't LISTEN (probe falls back
to 1s, or listen: false). No streaming at all: usePolling.
CLOUDFLARE WORKERS + D1 (verified on wrangler dev; examples/cloudflare /live):
  // src/versions.ts - import the binding INSIDE the query: the build prerenders
  // in Node, runs register(), and cannot load 'cloudflare:workers' (a top-level
  // import breaks the build).
  const db = async () => (await import('cloudflare:workers')).env.DB
  export const versions = () => sqlVersions({ dialect: 'sqlite',
    query: async (t, p) => (await (await db()).prepare(t).bind(...p).all()).results })
  // src/instrumentation.ts: installVersionSource(versions)
  // wrangler.jsonc (Nitro merges it): "d1_databases": [{ "binding": "DB",
  //   "database_name": "my-app", "database_id": "<id>", "migrations_dir": "migrations" }]
  // migrations/0001_rsc_versions.sql:
  //   CREATE TABLE IF NOT EXISTS rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
  // npx wrangler d1 migrations apply DB --remote (--local for wrangler dev)
  // npx wrangler secret put RSC_SIGNING_SECRET (.dev.vars for wrangler dev)
  // A section reading D1 itself: await connection() first - D1 is per request.
INSTALL LAZILY - installVersionSource(() => postgresVersions(client)): a
factory, made on first use. register() also runs in the build, often without
DB settings; a store made there makes its client there.
LISTEN THROUGH AN ORM - pass the driver's listen/notify to createVersions:
Drizzle on Bun.sql: listen: wake => client.listen('rsc_versions', wake),
notify: () => client.notify('rsc_versions', '') with the SQL client you gave
drizzle(). node-postgres: a dedicated pg.Client, LISTEN rsc_versions, and
on('notification', wake). A listening store reads the table only as a safety
net (~every 5s per server), not every second. NOTIFY inside a transaction is
delivered on commit, so it keeps the after-commit rule for you.
AFTER COMMIT - call changed() AFTER the transaction resolves, never inside
it: a tab refreshes at once and would read the old data, then sit at the new
version. Laravel: DB::afterCommit(fn () => Rsc::changed(...)).
SAME NAME - many sections/pages may refresh on one name; one changed() moves
it once and every tab refreshes what it shows. Section names are per page.
STARTUP - declare RSC_SIGNING_SECRET in src/env.ts like every other variable,
required in production (z.string().min(32) when NODE_ENV is production): the
deploy then fails before taking traffic. No env.ts: assertSigningSecret() from
@rsc-kit/core/changed in register() does the same. Otherwise rsc-kit refuses
on the first request.
SECRET - set RSC_SIGNING_SECRET, the same on every instance, with or without
a backend (NOT the host-call secret). In production an app using refreshOn
refuses to serve without it. Names are signed per request, never at build.
REQUEST - a refreshOn function gets params and searchParams ALREADY AWAITED
(({ params }) => [\`team:\${params.team}\`] is right), and runs per request:
cookies()/headers() work, e.g. a name for the signed-in user.
ISOLATION - a name is a signal, not data or a permission: a refresh renders
for that tab's visitor through their own session and guards, so nobody sees
another's data through a name. A tab can only listen for names its page was
rendered with (signed). Name the data narrowly with ids: conversation:{id},
inbox:{userId}. No emails/secrets in names. Never shared: true on per-visitor
sections.
SHARED - section(name, C, { refreshOn, shared: true }) for a section that
renders the same for everyone allowed to see the page: tabs refreshing
because of the same change share ONE render (guards still run per tab).
The shared render runs as nobody (rpc() sends no cookie, auth()->user() is
null); one that reads cookies()/headers() is not shared, each tab renders its
own. Never on per-visitor content.
LARAVEL - keep the default (versions in the cache; the renderer asks Laravel
~every 2s, ONE request per renderer process for all its tabs - negligible).
Laravel stays the only thing talking to its database. RSC_VERSIONS=database
(publish rsc-migrations) is for pruning or for writers outside Laravel; Laravel
still answers. INSTANT: Laravel broadcasting (any Pusher-protocol server:
Reverb, Pusher, Soketi) - RSC_BROADCAST=true in Laravel, RSC_BROADCAST_URL +
RSC_BROADCAST_KEY for the renderer. Rsc::changed() announces a change (no
names - public channel), the renderer asks Laravel at once, else every 30s.
Never have the renderer read Laravel's database.
WAKE ANYTHING - wakeOn(listen) from @rsc-kit/core/changed: listenToBroadcast({
url, key }), or (wake) => subscriber.subscribe('rsc:changed', wake) for Redis.
A wake carries nothing; the renderer then asks where versions live. Versions
are still needed: they say WHICH names moved, per visitor, and let a
reconnecting tab catch up.
DEBUG - dev console lists what each region watches; a region missing there
rendered no names (server log says why). Hidden tabs stop watching and catch
up when shown.
COST - per visible tab one SSE connection (keepalive every 8s - set
RSC_STREAM_KEEPALIVE_MS lower if a server/proxy drops idle connections sooner;
~40 bytes
per change); per change one refresh of just the sections showing the name;
per server one versions read covering all its tabs.
HOW - a name has a version, a number that moves when it is said to have
changed; nothing else travels. The page learns versions at render, one SSE
stream per tab (only on a page with names) watches them, and a moved version
calls refresh(section) for exactly the regions holding the name. Versions
live where the backend keeps shared state (Laravel's cache, a table in Go
via reg.Versions(&rsckit.SQLVersions{...}), this process without a backend). Go
holds the ask and answers the moment a name moves; Laravel (PHP-FPM) answers
at once and the renderer asks again ~2s later. Runs on Workers/Vercel: the
stream is stateless, names are signed by the renderer (a tab may only watch
names its page was rendered with).
FROM NEXT - this replaces revalidateTag, and is not the same thing: Next's
tags label Data Cache entries and revalidateTag() purges them (the NEXT
request refetches; open tabs learn nothing). rsc-kit has no data cache -
every render is fresh - so refreshOn names what is on screen and changed()
refreshes every open tab now. Port: tags: ['posts'] on the fetch ->
refreshOn: ['posts'] on the section; revalidateTag('posts') -> changed('posts').
WHEN - use names when the change comes from OUTSIDE the tab: webhooks, jobs,
teammates. Use revalidate('orders') inside the action that made the change.
Use usePolling for a value with no backend signal; useEvents for a stream of
values (live-data).
TEST - testChanges() from @rsc-kit/core/testing: host: { ...names.host };
names.changed('team:1:repos').
A name's name is not secret, but what its version reveals is only "something
named this changed"; do not put secrets in name names.`,
    },
    {
        topic: 'live-data',
        summary: 'A value that keeps changing - realtime, live updates: usePolling over a query, or server-sent events (SSE, streaming from a middleware.ts generator) with useEvents - both feed TanStack, SWR or setState. For a backend-side change (webhook, job) see refresh-on',
        body: `Neither is part of query() - a query answers once and is cacheable.

POLLING - start here when you have no change feed yet. Reuses the query,
goes through its Cache-Control (a CDN collapses many tabs into one origin
read per interval), pauses when the tab is hidden, never overlaps two reads.
\`\`\`tsx
import { usePolling } from '@rsc-kit/core/usePolling'
const { data, status, refresh } = usePolling(() => fetchQuery(getSeats), { every: 2_000 })
\`\`\`
UNTIL IT SETTLES - a job that ends. until(data) says the last read; onSettled
fires once on it. The result is the DATA; what to
do on settling is the page's choice:
  // a server-rendered list, some jobs still running: re-render through the server
  usePolling(() => fetchQuery(jobStatus, [id]), { every: 2_000, enabled: !isTerminal(job), until: isTerminal, onSettled: () => refresh('page') })
  // the page that owns the job's state machine: the value in hand
  const { data, status } = usePolling(read, { every: 1_500, until: isTerminal, onSettled: (f) => dispatch(f.status) })
Settled = stopped until refresh() or the inputs change. status: 'reading' |
'paused' | 'settled' | 'idle'.

SERVER-SENT EVENTS - when something can push. Better per update (bytes only
on change, instant), but holds a connection per open tab (fine on Bun/Node,
a limit on Workers or a small container), is uncacheable, and needs a source
of change to yield from - a generator that polls the DB itself just moved the
polling. An ordinary route.ts: beside its pages, runs middleware.ts above it.
\`\`\`ts
// src/app/api/orders/[id]/events/route.ts
import { events, named } from '@rsc-kit/core/events'
export const GET = events(async function* ({ params, signal }) {
  const { id } = await params
  for await (const status of orderStatus(id, { signal })) yield { status }
  // yield named('paid', order, { id: order.id }) names a message / gives an id
})
\`\`\`
\`\`\`tsx
import { useEvents } from '@rsc-kit/core/useEvents'
const { latest, all, status, close } = useEvents(\`/api/orders/\${id}/events\`)
// latest is typed from the route: what its generator yields. { event: 'paid' }
// types the named messages. A url no route answers fails the typecheck; another
// site's stream is unknown until named: useEvents<Message>(url).
\`\`\`
events() frames JSON, sends a keepalive, sets text/event-stream + no-store,
ends the generator on disconnect (signal). EventSource reconnects a dropped
connection and resumes with Last-Event-ID when you yielded ids; after an error
answer (a 502 mid-deploy) the hook opens a new one, backing off 1s to 30s, and
at once when the browser is back online. close() stops it.

NO LIBRARY NEEDED. Both hooks ARE state: read data (polling) or latest
(events) and render it. Neither needs TanStack or SWR.
  const { latest } = useEvents(url); const current = latest ?? initial   // the server value until the first message
WITH A STORE - when the value already lives somewhere, hand every value on so
that stays the truth: a useState, a reducer, or a cache library:
  useEvents(url, { onMessage: setOrder })                                            // useState
  useEvents(url, { onMessage: (m) => dispatch({ type: 'update', m }) })              // reducer
  useEvents(url, { onMessage: (m) => queryClient.setQueryData(['order', id], m) })  // TanStack
  useEvents(url, { onMessage: (m) => mutate(['order', id], m, false) })             // SWR
  usePolling(read, { every, onData: setSeats })
STABLE CALLBACKS: a callback a timer/subscription/listener calls that must see
the latest props is useEffectEvent from React (19.2+), never a ref assigned
each render, and never in a dependency array. Both hooks are built on it.

ERRORS: both hooks expose error as state AND fire onError - a failed poll read
(the next interval still reads) or a dropped stream (EventSource reconnects
itself). Use onError for a toast/log; do NOT watch error in a useEffect.
usePolling's onError gets (error, { failures }) - failed reads in a row, reset
by a success - so toast on the third, not the first.
fetchQuery(query, args) types args from the query: fetchQuery(getSeats) for a
query that takes nothing, fetchQuery(status, [{ id }]) refused if the query's
input has no id.
Do NOT put a stream on query() or on a server action, and do NOT poll from
inside an events() generator.

Full guides: read_guide({ slug: 'queries' }) for polling, read_guide({ slug:
'api-routes' }) for the streaming route.`,
    },
    {
        topic: 'images',
        summary: 'Responsive images with no optimizer - unpic for a CDN, imagetools for files in the repo',
        body: `There is NO image component and NO image server. Do not add next/image or
write an optimizer route. next/image is a srcset-writing component plus a
resize-on-request process; the first is a library, the second belongs to the
CDN.

An image on a CDN (Cloudinary, imgix, Cloudflare Images, Bunny, Vercel,
Netlify, ...): @unpic/react. Plain component, works in a server component,
ships no javascript, detects the CDN from the url:

\`\`\`tsx
import { Image } from '@unpic/react'

<Image src="https://res.cloudinary.com/demo/image/upload/sample.jpg" layout="constrained" width={800} height={600} alt="..." />
\`\`\`

A file in the repo, a handful of them: vite-imagetools, resized ONCE at build
time. Add imagetools() to the vite plugins, then:

\`\`\`tsx
import hero from '../hero.png?w=400;800;1200&format=webp&as=srcset'
import heroSrc from '../hero.png?w=800&format=webp'

<img srcSet={hero} src={heroSrc} sizes="(min-width: 800px) 800px, 100vw" width={800} height={600} alt="..." />
\`\`\`

Declare the query tails in src/images.d.ts, or the build's typecheck stops on
the imports (a pattern may hold ONE *, so '*?*' matches nothing):

  declare module '*&as=srcset' { const srcset: string; export default srcset }
  declare module '*&format=webp' { const url: string; export default url }

Hundreds of files in the repo: that is a CDN's job; move them and use unpic.
An icon or a logo: a plain <img>, or inline the svg.

Full guide: read_guide({ slug: 'images' }).`,
    },
    {
        topic: 'scripts',
        summary: 'Third-party scripts - analytics, tag managers - without a Script component',
        body: `Write the script tag. React 19 does what Next's Script component existed for.

An external script with async, rendered from a server component, is HOISTED
into head and DEDUPLICATED by React - the same src in three components is one
tag. That is afterInteractive:

\`\`\`tsx
<script async src="https://www.clarity.ms/tag/abc123" />
\`\`\`

An inline snippet renders where it is written and runs during parse, before
hydration - the earlier moment, which is what an analytics snippet wants:

\`\`\`tsx
<script id="ms-clarity" dangerouslySetInnerHTML={{ __html: '...' }} />
\`\`\`

Put site-wide scripts in the ROOT LAYOUT, which renders once and is kept
across navigations.

There is no Script component to import. The only case needing one - a script
that touches DOM React rendered, or an onLoad callback - is a client component
with useEffect that creates the tag. Ten lines of the user's own.`,
    },
    {
        topic: 'web-vitals',
        summary: 'LCP, INP and CLS from real visitors: <WebVitals endpoint> in the root layout posts them when the tab is hidden; useWebVitals for an analytics tool',
        body: `Field data (real visitors), not a lab score. Install the peer and put the
component in the ROOT LAYOUT (it renders nothing):

  bun add web-vitals

  // src/app/layout.tsx
  import { WebVitals } from '@rsc-kit/core/web-vitals'
  <body><WebVitals endpoint="/api/vitals" />{children}</body>

  // src/app/api/vitals/route.ts
  import type { VitalsBatch } from '@rsc-kit/core/web-vitals'
  export async function POST(request: Request) {
    const { path, navigations, metrics } = (await request.json()) as VitalsBatch
    // metrics: [{ name, value, rating, delta, id, navigationType }]
    return new Response(null, { status: 204 })
  }

One POST (sendBeacon, else fetch keepalive, with cookies) each time the tab
is HIDDEN, carrying every metric since the last. STORE BY id AND KEEP THE LAST
VALUE: CLS and INP can be sent again for the same id. Values are ms, CLS has
no unit. Judge each metric at the 75th PERCENTILE per path (good: LCP 2.5s,
INP 200ms, CLS 0.1, FCP 1.8s, TTFB 0.8s), never an average.

CLIENT NAVIGATIONS are not page loads: path is the page the document LOADED
(as in Chrome's field data); LCP/FCP/TTFB describe that load; CLS and INP keep
counting across client navigations, and navigations counts them - filter
navigations = 0 for one page's own CLS/INP. Reports carry the path, not the
route pattern (the browser router has no route table): group dynamic routes in
the endpoint. Soft-navigation LCP is experimental and not used.

An analytics tool instead: a client component of your own with
  useWebVitals((metric, { path, navigations }) => gtag('event', metric.name, { value: metric.value, metric_id: metric.id, page_path: path }))
Do NOT pass a function prop to <WebVitals> from a server layout; there is none.

SAME ORIGIN only: a route.ts POST a browser sends cross-site is answered 403
(Sec-Fetch-Site); a beacon to your own endpoint is same-origin and passes.
The endpoint must not demand a CSRF token (a beacon cannot send one): on
Laravel a route in routes/api.php (routes/web.php answers 419); on Go an
ordinary POST handler decoding JSON.

Costs nothing unless imported. Imported: ~1 KB with the layout, and
web-vitals (~3.3 KB) as its own file requested after load + idle - never in
hydration's way. A visit that leaves before load reports nothing. Do NOT
write your own PerformanceObservers for this.

Full guide: read_guide({ slug: 'web-vitals' }).`,
    },
    {
        topic: 'feature-flags',
        summary: 'OpenFeature in a server component; Pennant on Laravel and the OpenFeature Go SDK on Go, read with rpc()',
        body: `JS app: bun add @openfeature/server-sdk @openfeature/core. One module, src/server/flags.ts:

  import { cache } from 'react'
  import { OpenFeature, InMemoryProvider } from '@openfeature/server-sdk'
  import { cookies } from '@rsc-kit/core/request'

  await OpenFeature.setProviderAndWait(new InMemoryProvider({
    'new-banner': { variants: { on: true, off: false }, defaultVariant: 'off', disabled: false,
      contextEvaluator: (c) => (c.targetingKey === 'ada' ? 'on' : 'off') },
  }))
  const client = OpenFeature.getClient()
  const visitor = cache(async () => ({ targetingKey: (await cookies()).get('user')?.value ?? 'anonymous' }))
  export const newBanner = cache(async () => client.getBooleanValue('new-banner', false, await visitor()))

React cache() evaluates once per render. The evaluation context is passed with
every call - not set globally, not a transaction context. Swap InMemoryProvider
for the flag service's provider (openfeature.dev/ecosystem); the calls stay.
An evaluation never throws: a failure answers the default. setProviderAndWait
rejects if the provider cannot start; setProvider does not wait.

A flag read from cookies() is per visitor: render it in its own async component
under <Suspense> so the rest of the page is still stored. A flag with no
context reads nothing and the page is stored whole.

Laravel: Pennant, as its docs show. Feature::define('new-banner', fn (User $user) => ...)
in a provider, and a class under app/Rsc returns Feature::active('new-banner');
the page reads rpc('Flags.newBanner'). Pennant's default scope is the signed-in
user, so the build leaves the call to the request (Suspense as above);
Feature::for(null) is answered at build and stored.

Go: github.com/open-feature/go-sdk in a handler -
client.BooleanValue(ctx, "new-banner", false, openfeature.NewEvaluationContext(id, nil)).
The SDK reads its own context value, which the build counts as a visitor read,
so nothing is stored. An app that never sets OpenFeature's transaction context:
reg.ServeCalls(os.Stdin, os.Stdout, rsckit.NotTheVisitor("github.com/open-feature/go-sdk/openfeature")).

Test: await withRequest(new Request(url, { headers: { Cookie: 'user=ada' } }), newBanner).

Not flags/next: it reads the request through Next, and 4.5.2 added a
next/navigation import that broke every page reading a flag.

Full guide: read_guide({ slug: 'feature-flags' }).`,
    },
    {
        topic: 'testing',
        summary: 'Unit-testing actions, queries and routes; the whole app without a port',
        body: `Almost everything is a function. Any test runner works.

**Actions, queries, api routes: import and call.** "use server" is a string in
a test file, so the function is importable. An action built on the action
client runs its whole middleware chain when called and RETURNS its failures:

\`\`\`ts
const result = await createPost({ title: '' })
expect(result.validationErrors).toEqual({ title: ['too short'] })
\`\`\`

An api route takes a Request and the context the engine gives it - params is a
PROMISE:

\`\`\`ts
const res = await GET(new Request('https://app.test/api/x'), { params: Promise.resolve({ id: '1' }) })
\`\`\`

**Anything reading cookies() or headers():** open the request scope yourself.

\`\`\`ts
import { withRequest } from '@rsc-kit/core/request'
await withRequest(new Request('https://app.test/', { headers: { Cookie: 'session=abc' } }), currentUser)
\`\`\`

**The whole app as Request -> Response, no port:**

\`\`\`ts
import { createTestApp } from '@rsc-kit/core/testing'
const app = await createTestApp()
const res = await app.fetch('/admin', { redirect: 'manual' })   // real router, real middleware
\`\`\`

It builds when anything the build is made from is newer than the last build -
source, vite.config, package.json, the lockfile, the installed @rsc-kit/core -
so an upgrade is picked up. This is where a guard that never ran or a 404 that
came back 200 shows up.

To assert something is NOT on a page, use app.markup(path), not fetch(): the
document streams the page's payload in <script>s, which holds every prop a
client component was given, shown or not. markup() is the document with every
<script> removed. Do NOT strip scripts by hand.

**A Go or Laravel backend, answered in the test (nothing running):**

\`\`\`ts
import { createTestApp, hostReply, HOST_MIDDLEWARE } from '@rsc-kit/core/testing'
const app = await createTestApp({
  host: {
    'Apps.list': ({ args, headers }) => [{ id: 1 }],          // rpc('Apps.list', ...)
    'Apps.create': () => hostReply.invalid({ name: ['Taken.'] }),
    [HOST_MIDDLEWARE]: ({ args, headers }) =>                  // middleware.ts guards; args[0] = names
      headers.get('cookie')?.includes('session=') ? true : hostReply.unauthenticated(),
  },
})
\`\`\`

The host handlers are TYPED from rsc-host.json (interface RscHostFunctions in
.rsc-kit/rsc-env.d.ts): only functions the backend has, typed args, and the
function's result type or a hostReply answer - never a raw { status: 401 } or a
made-up shape. Refusals ALWAYS through hostReply, which passes the same
conformance suite the real adapters do. hostReply.fail(message) = an unexpected
error. Answers go through the real host-call client, so they behave as the backend's
would: hostReply.unauthenticated() -> 401, unauthorized() -> 403,
redirect(to), refuse(status, message), invalid(errors) -> validationErrors,
revalidating(result, ...regions). A name with no handler fails the call,
naming it. RSC_BACKEND in .env is not called.

A url the app forwards to the backend (a Go route, /login) is a 502 in a test
unless createTestApp({ backend: (request) => new Response(...) }) answers it;
it gets the request as the backend would.

**What still needs a browser:** a server action called OVER THE WIRE (the id is
React's and private), hydration, navigation. Playwright against vite preview.
That limit is narrower than Next's: the action's logic is a unit test here.

**What to write when you add something.** Before running check, not after:

- A guarded route (middleware.ts, or a page reading the session): a stranger
  is turned away, and someone signed in gets 200.
  \`\`\`ts
  expect((await app.fetch('/admin', { redirect: 'manual' })).status).toBe(302)
  expect((await app.fetch('/admin', { headers: { Cookie: 'session=ada' } })).status).toBe(200)
  \`\`\`
- An action: its refusal, by calling it. Bad input answers validationErrors;
  a stranger answers serverError (or throws ServerAuthenticationError if you
  built it without the client).
  \`\`\`ts
  expect((await createPost({ title: '' })).validationErrors).toBeDefined()
  \`\`\`
- An action that takes an id: someone else's id is refused. This is the IDOR
  test and the one most often missing.
- A query: the shape of its answer, and what a filter changes.
- An api route: status, content-type, and the 4xx it answers to a bad body.
- A page that should stay static: assert on the build report - no test, a CI
  check that build-report.json still says frozen for it.

Do NOT start a dev server, spawn a process or pick a port in a test. Do NOT
add a second runner. The one in tests/ goes through the real build already.`,
    },
    {
        topic: 'admin',
        summary: 'An admin panel with @rsc-kit/press: resources over any data source, server or client tables, Standard Schema forms, auth, tenants, plugins, themes',
        body: `@rsc-kit/press builds an admin panel from resources; a theme draws it
(@rsc-kit/press/shadcn: sidebar, data table, dialogs). The app keeps what is
its own: where the data lives, who may see it, whose it is. Full guides:
admin, admin-plugins. There is no @rsc-kit/admin any more - do not import it.
  @rsc-kit/press          defineResource, memorySource, perTenant, definePlugin, types
  @rsc-kit/press/admin    definePanel, resourceParams, recordParams, listSearch, pluginsSearch, AdminTheme
  @rsc-kit/press/forms    defineBlueprint - a form defined once, drawn in pages and panels (how_to blueprints)
  @rsc-kit/press/pages    definePages - pages an editor builds from blocks (how_to pages)
  @rsc-kit/press/shadcn   shadcn (the theme; it draws panels and public forms)

SETUP: the app needs Tailwind v4 + shadcn (create-rsc-kit --tailwind --shadcn).
In the app's stylesheet, after tailwind and shadcn:
  @import "@rsc-kit/press/shadcn.css";
Without it the panel renders unstyled - the line is Tailwind's @source for the
theme's components.

A RESOURCE:
\`\`\`ts
import * as z from 'zod'
import { defineResource } from '@rsc-kit/press'

export const products = defineResource<Product>()({
  name: 'products', key: 'id', title: 'name',
  icon: Package,                       // lucide-react, optional
  source: productsSource,              // a DataSource, below
  mode: 'server',                      // or 'client'; server is the default
  table: (col) => [
    col.text('name').searchable().sortable(),
    col.money('price').sortable(),
    col.badge('status'),
    col.boolean('featured').hidden(),  // off in the Columns menu at first
    col.date('createdAt'),
    // col.text('image').cell((value, row) => <Avatar .../>) - a server component
  ],
  // locale: 'de-DE',                  // money/date columns and the dashboard count; 'en' unless said
  // col.money('price').currency('EUR') - 'USD' unless said; col.x(...).locale('en-GB') overrides
  filters: ['status'],
  form: z.object({ name: z.string().min(2), price: z.number().positive(), status: z.enum(['draft', 'active']), featured: z.boolean() }),
  fields: { description: { type: 'textarea', description: 'Help text' } },
  perPage: 10,
})
\`\`\`

THE FORM IS ANY STANDARD SCHEMA - zod, valibot, arktype, Effect Schema. Use
the one the app already has; do NOT add zod for the panel. The schema checks
every save on the server, errors under each field. Fields come from the
schema's Standard JSON Schema (zod 4.2+ has it). A schema without it MUST list
every field in fields: { title: { type: 'text' } } - the panel throws saying
so. A number field arrives as a number: write z.number(), NOT z.coerce.number().
A switch that is off is false; an empty optional field is absent.
BROWSER CHECK: the same schema's constraints become attributes (required,
min/max, minlength/maxlength, an anchored pattern, type=email, step=1 for an
integer); a wrong field is caught before submit and the browser's message
shows in the field's FieldError. The schema never ships to the browser, so it
works the same when the rules live in Laravel/Go. A courtesy only: custom
messages and uniqueness come from the server. Do NOT add a client-side
schema run.
THEME: the header menu is Light/Dark/System (System default, follows the OS);
it sets class="dark" on <html> before paint, so the root layout's <html> gets
suppressHydrationWarning. modeToggle: false hides it.

A DATA SOURCE is five functions, and the panel calls nothing else - a
database, ORM, REST API or rpc() into Laravel/Go alike:
\`\`\`ts
import type { DataSource } from '@rsc-kit/press'

const source: DataSource<Customer, Values> = {
  async list({ q, sort, dir, page, perPage, filters, searchable }, { tenant }) { return { rows, total } },
  find: (id, { tenant }) => ...,       // null -> 404, for the page AND a save/delete of that id
  create: (values, { tenant }) => ...,
  update: (id, values, { tenant }) => ...,
  delete: (id, { tenant }) => ...,
}
\`\`\`
TWO OPTIONAL FUNCTIONS, for a big table - a source without one is asked list
as before, so add them only where list is too much:
  findMany: (ids, { tenant }) => ...   // rows with these keys (strings), any order
  count: ({ tenant }) => ...           // a number, or null for a dash
findMany serves a table's col.relation(): one call per related resource per
page, with only the keys that page's rows hold, instead of list() with
perPage: null. It MUST scope as list does - only rows this visitor, in this
tenant, could have listed; a key that is not theirs is left out, not an
error. A form's relation select still calls list() for every row. count
serves the dashboard's card instead of list() with perPage: 1. memorySource
has both; perTenant passes them to the tenant's source.
PAGES BY COUNT OR BY CURSOR - list answers either, per resource:
  { rows, total }               counted: numbered pages, "12 orders"
  { rows, next, prev }          by cursor: Previous/Next links carrying ?cursor=,
                                no count; null is no page that way
The source is told the cursor it handed out as query.cursor (absent on the
first page) and reads it instead of page. Laravel's cursorPaginate maps as
{ rows: p.data as Order[], next: p.next_cursor, prev: p.prev_cursor }, and
paginate as { rows: p.data as Order[], total: p.total } - a paginator result is
typed as it encodes, its rows unknown. cursorPaginate is called with
cursorPaginate($query['perPage'], cursor: $query['cursor'] ?? null). Do NOT
count a table just to page it.
The last argument of every call is the context { tenant } (null without
tenancy). On a Laravel/Go backend the functions call rpc() and the backend
validates again - the panel's check is the renderer's, the backend's counts.
A WRITE THAT HAPPENED, THEN FAILED (committed, then reading the row back
threw): throw new WrittenError(message) from create/update (import from
'@rsc-kit/press'). The files the form uploaded stay (any other throw takes them
back), the editor sees the error, and an edit is still told to plugins. An
installed plugin answering 2xx to create/update without { row } is the same.
A BACKEND 422 (unique:products,sku, a stock check) shows under the same fields
as the schema's, values kept: do NOT catch it in create/update - let the rpc()
call throw, and the panel's save answers it as field errors.
THE BACKEND'S ACTIONS AS THE FORM: when a FormRequest or a Go struct already
says what a record takes, write NO schema. Give the generated actions instead
of form, and the source only list/find/delete:
  source: { list, find, delete },
  actions: { create: products.store, update: products.update },   // import * as products from '../server-actions/products'
  fields: { category_id: { relation: 'categories' } },   // the backend's names, typechecked
form and actions are one or the other, never both. The create form is drawn
from create's input, the edit form from update's. create(values); update(values,
key) - the KEY COMES SECOND:
  Laravel: update(UpdateProductRequest $request, string $product) - the key is
    the FormRequest's route parameter by that name, so
    Rule::unique('products')->ignore($this->route('product')) works, and
    Route::model() binds it.
  Go: func(ctx context.Context, in ProductInput, id string)
An update taking only the values, or a create taking a key, throws at startup.
memorySource(rows, key, make) is for tests and demos; perTenant((tenantId) =>
source) keeps one source per tenant.

OPTIONS: an enum's values are shown humanized ('in_stock' reads "In stock")
and saved as they are; fields: { status: { options: ['draft', { value:
'active', label: 'Live' }] } } labels them yourself. An optional select starts
on "None", which saves nothing.

RELATIONS (belongsTo): fields: { categoryId: { relation: 'categories' } } is a
select of the categories resource's rows - its key saved, its title shown -
and col.relation('categoryId', 'categories') shows the title, not the id.
The choices are that resource's list() with perPage: null AS THE VISITOR
(tenant-scoped), so relate to a resource with a select's worth of rows. The
save checks the posted id with the related source's find() as the visitor: an
id from another tenant is refused under the field ("Choose one of the listed
categories."). A z.number() relation arrives as a number. A relation to a
resource the panel does not have throws when the panel is defined.

WRITE-ONLY FIELDS: fields: { password: { writeOnly: true } }, or
.meta({ writeOnly: true }) in the schema. Never told to a plugin and never sent
to the edit form: an edit shows it empty, leaving it empty keeps what is stored
(update is NOT given the field - write update to change only what it is given),
and a typed value replaces it. Do NOT prefill it, and do NOT hash an absent
value. A blueprint on a page of your own needs an edit schema where it is
optional. INSIDE A BLOCK, in the panel, it is not sent either: each block comes
with from (where it stood in the record), posted back as name.i.from, and a
block saved with it empty keeps what that block had, moved or not - written
back with the block, since a block list is saved whole. A theme of your own
MUST post name.i.from for a block the record had. A blueprint on a page of
your own still sends a block's write-only value (it has no record to restore
it from).

BULK ACTIONS: a resource that is not readOnly ticks rows and offers the
panel's own Delete below the table. bulkActions: [{ name: 'publish', label:
'Publish', destructive?: true, run: (rows, context) => ... }] adds more. run
gets ROWS, each found with the source's find() as the visitor - an id that is
not theirs never reaches it - after authorize. destructive asks first. The
toast says "3 products published." with done: 'published' (else "Publish: 3
products."), or run's own string. 'delete' is
reserved, and a readOnly resource with bulkActions throws.

TABLE MODE: 'server' - each search/filter/sort/page is a request, list() gets
one page (perPage a number), state is in the url (links, back button, works
without JS); for data that grows. 'client' - list() is called once with
perPage: null and returns EVERY row; search, filters, sort and paging run in
the browser; for small data (hundreds of rows). A source must handle
perPage: null if any resource using it is client mode.

THE PANEL:
\`\`\`ts
import { definePanel } from '@rsc-kit/press/admin'
import { shadcn } from '@rsc-kit/press/shadcn'

export const panel = definePanel({
  path: '/admin',
  theme: shadcn,                       // required; { ...shadcn, Dashboard: Mine } replaces one page
  resources: [products, customers],
  authorize: async () => (await currentUser())?.isAdmin === true,
  user: currentUser,                   // { name, email?, avatar? } for the sidebar footer
  signOut: () => endSession(),         // runs in a server action, lands on /
  tenancy: { label: 'Teams', tenants: () => teamsOfUser(), current: () => teamFromCookie(), switch: (id) => setTeamCookie(id) },
  plugins: [auditLog()],
})
\`\`\`
AUTH: the panel has no login of its own; authorize asks the app's. It runs on
every page AND every save, delete and tenant switch (actions are public
endpoints). A refusal is a 404. Do NOT guard only the pages.
THEME: an AdminTheme is an object of components - Shell, Brand,
TenantSwitcher, Nav, Breadcrumbs, UserMenu, Dashboard, Index, Table, Form,
Plugins, Cell, Loading. Each gets data, bound server actions and drawn
elements as props, never a component, so any may be a client component. The
panel owns the guard, the data and the Suspense boundaries; a theme only draws.
TENANTS: current() is read from the session; the panel refuses a current
tenant that is not in tenants() (a forged cookie). switch() runs in a server
action, so cookies().set works there.

MOUNTING - seven route files, because the engine finds routes, url schemas and
sections by their files. Each re-exports from the panel:
  src/app/admin/middleware.ts                       export default panel.middleware
  src/app/admin/layout.tsx                          export default panel.Layout
  src/app/admin/page.tsx                            export default panel.Dashboard
  src/app/admin/[resource]/page.tsx                 export const params = resourceParams
                                                    export const searchParams = listSearch
                                                    export default panel.Index
  src/app/admin/[resource]/admin-table.section.tsx  export default panel.Table
  src/app/admin/[resource]/new/page.tsx             export const params = resourceParams
                                                    export default panel.Create
  src/app/admin/[resource]/[id]/page.tsx            export const params = recordParams
                                                    export default panel.Edit
resourceParams, recordParams and listSearch come from '@rsc-kit/press/admin'. The
section MUST be named admin-table.section.tsx: a delete refreshes it by name.

PLUGINS: definePlugin({ name, resources?, widgets?, onChange? }). A widget is
{ title, description?, component } - a server component given { tenant }.
onChange(change) runs after a save/delete is written, with { panel, resource,
id, change, values?, tenant }; a plugin that throws is logged and never fails
the save. Export a function of options returning the plugin. Publish with
@rsc-kit/press and react as PEER dependencies and the npm keyword
rsc-kit-admin-plugin.`,
    },
    {
        topic: 'blueprints',
        summary: 'A form defined once with defineBlueprint from @rsc-kit/press/forms - a contact form, a sign-up, an edit page, an admin resource\'s form - from a Standard Schema or the backend\'s actions: browser and server checks, a bot trap',
        body: `defineBlueprint turns a Standard Schema, or the backend's actions, into a
form defined once - fields, checks, saves - drawn in any page with
<contact.Form />, as an edit page with <profile.Form id={...} values={...} />,
and as an admin resource's create and edit pages with
defineResource({ form: profile }). Full guide: blueprints.

\`\`\`ts title="src/forms/contact.ts"
import * as z from 'zod'
import { defineBlueprint } from '@rsc-kit/press/forms'
import { shadcn } from '@rsc-kit/press/shadcn'

export const contact = defineBlueprint({
  name: 'contact',                     // unique; lowercase letters, digits, dashes
  form: z.object({ name: z.string().min(2), email: z.email(), message: z.string().min(10) }),
  fields: { message: { type: 'textarea' } },   // what the schema cannot say
  theme: shadcn,
  submit: 'Send message',
  done: 'Thanks - we will be in touch.',       // shown in place of the form
  // redirect: '/thanks',                      // OR this; never both
  handle: async (values) => { await db.insert(messages).values(values) },   // creates
  // update: async (values, key) => { ... },   // edits, when drawn with an id
})
\`\`\`

\`\`\`tsx title="src/app/contact/page.tsx"
import { contact } from '@/forms/contact'
export default function ContactPage() {
  return <main><h1>Contact us</h1><contact.Form /></main>
}
\`\`\`

The form reads nothing from the request: the page stays static and is stored
by the build. Do NOT add connection() or a Suspense boundary for it.

CHECKS: the schema's constraints become the browser's (required, minlength,
type="email", pattern), with the message under the field. The schema checks
every submission on the server again, and handle() only gets values that
passed. A refusal handle() decides goes under its field:
  import { fieldErrors } from '@rsc-kit/core/action'
  if (await subscribed(email)) fieldErrors({ email: 'Already on the list.' })

EDITING A RECORD: give it update(values, key), and draw
<profile.Form id={user.id} values={user} />. Only the blueprint's own fields
of values reach the browser. THE KEY COMES BACK FROM THE BROWSER and anyone
can post another: update must check the visitor may change that record (a
FormRequest's authorize(), a comparison with the session's user). Drawn with
an id and no update, or without one and no handle/create, it throws.
honeypot: false drops the bot trap for a form only signed-in people reach.

IN A PANEL: defineResource<Row>()({ ..., form: blueprint }) - the panel's
create and edit pages are the blueprint's form. A blueprint that saves (both
create and update) saves the panel's records too, so source is only
{ list, find, delete }; one that does not needs a whole source. Say fields and
actions on the blueprint, never again on the resource (that throws).

A BACKEND, WITH NO SCHEMA: defineBlueprint({ name, actions: { create: send }, theme }),
with import { send } from '../server-actions/contact' - the
action itself, never its name as a string (a string throws). No form, no
handle, no zod. actions is { create, update }, either or both: create's input
draws the create form, update's the edit form, and update is called
(values, key) - update(UpdateProfile $request, string $user) in Laravel,
reading the key with $this->route('user'); func(ctx, in ProfileInput,
id string) in Go. bunx rsc-kit make:form Contact.send writes forms/contact.ts.
The action is a Laravel class in app/Rsc/Actions (Contact::send is
send in server-actions/contact; a class in app/Rsc is rpc only and has no action) or Go's
reg.HandleAction("Contact.send", fn). Fields and browser checks
come from what it takes (rsc-host.json): a Laravel FormRequest's rules(), or a
Go struct, whose validate tags are read as hints and never run, so the Go
function must still check. It takes one object; a file needs form and handle.
A 422 from Laravel (a FormRequest type-hinted on the method, whose authorize()
returns true) or Go (rsckit.InvalidField) lands under the same fields,
uncaught. To check in TypeScript first, keep a schema and
handle: (values) => send(values).

THE BOT TRAP: every form carries a hidden field named homepage. Filled in, the
submission is answered as a success and dropped - handle() never runs. So a
form cannot have a field named homepage. It is not a CAPTCHA; rate-limit a form
worth attacking. Every host call carries the visitor's address
(X-Rsc-Client-Ip), so Laravel's throttle:5,1 on the action counts each
visitor ($request->ip()), as Go's rsckit.ClientIP(ctx) does. Behind a load
balancer or Cloudflare set RSC_TRUST_FORWARDED=1 on the renderer, or every
visitor arrives as the balancer; behind two in a row (Cloudflare in front of a
balancer) set it to 2. The address is the X-Forwarded-For hop those proxies
appended, counted from the right - never the leftmost, which the visitor wrote. The same flag has the renderer believe
X-Forwarded-Host and X-Forwarded-Proto from a proxy on another machine; from
its own machine it believes them without it, and from anywhere else not at all;
like the address they are counted from the right, so a visitor's value ahead
of an appending proxy's is never read.
The visitor's User-Agent rides along too (X-Rsc-Client-User-Agent):
Laravel's $request->userAgent() and Go's rsckit.ClientUserAgent(ctx) are the
visitor's browser, for a log or an audit entry - never r.UserAgent() in Go,
which is the renderer's runtime.

A THEME draws it with one component, BlueprintForm (type FormsTheme from
@rsc-kit/press/forms), given action, fields, values, submit, done and
honeypot (render <Honeypot name={honeypot} /> from @rsc-kit/core/honeypot); replace it with theme: { ...shadcn, BlueprintForm: Mine }.
VISIBLE: fields: { company: { visible: { when: 'topic', is: 'sales' } } }
shows a field only while another has one of the values in is (one or a
list); not turns it round; neither means once the other is filled in or
switched on. A hidden field is not sent or browser-checked, and the server
drops one sent anyway, so the schema makes it optional. Laravel's
required_if:topic,sales and Go's validate:"required_if=Topic sales" are read
as visible, required when shown.
FROM: fields: { slug: { from: { field: 'title' } } } fills the slug as the
title is typed, until it is edited by hand; left empty, the server fills it.
when and field name another field of the form, or startup fails.
SETUP is the panel's: bun add @rsc-kit/press, and
@import "@rsc-kit/press/shadcn.css" in the stylesheet.`,
    },
    {
        topic: 'pages',
        summary: 'Landing pages built in the admin panel from the app\'s blocks with @rsc-kit/press/pages: defineBlock, definePages, one catch-all route, real 404s',
        body: `An editor builds pages in the admin panel from blocks the app defines; one
catch-all route serves them, read from the source on every request - a save is
live on the next visit, nothing is rebuilt. Full guide: pages.

A BLOCK is a schema for what the editor fills in, and a server component:
\`\`\`tsx title="src/site/blocks.tsx"
import * as z from 'zod'
import { defineBlock } from '@rsc-kit/press'

export const hero = defineBlock({
  name: 'hero',                                   // lowercase, digits, dashes
  form: z.object({ heading: z.string().min(3), lead: z.string().optional() }),
  fields: { lead: { type: 'textarea' } },
  render: ({ data }) => <section><h1>{data.heading}</h1>{data.lead && <p>{data.lead}</p>}</section>,
})
// A block may place a public form: render: () => <contact.Form />
\`\`\`

THE PAGES and the three files that serve them:
\`\`\`ts title="src/site/pages.ts"
import { definePages } from '@rsc-kit/press/pages'
export const site = definePages({ blocks: [hero, features, text], source: pagesSource })
\`\`\`
\`\`\`tsx title="src/app/[...path]/page.tsx"
import { site } from '@/site/pages'
export const generateMetadata = site.generateMetadata
export default function SitePage({ params }: { params: Promise<{ path: string }> }) {
  return <main><site.Page params={params} /></main>
}
\`\`\`
\`\`\`ts title="src/app/[...path]/middleware.ts"
import { site } from '@/site/pages'
export default site.middleware      // REQUIRED for real 404s
\`\`\`
And resources: [site.resource, ...] in definePanel.

Without the middleware, a draft or a typo answers 200: the route's shell has
gone out before the page finds nothing. site.middleware does the lookup before
anything is sent.

A catch-all is the weakest route: every other page wins over it. Its param may
have any name, with others before it (app/[locale]/[...path]): the last one,
the catch-all, is read. The slug is
the address (about, pricing/teams); the page with slug home is served at / when
there is no app/page.tsx (definePages({ home }) renames it; /home itself 404s).

THE SOURCE: rows { id, title, slug, description?, published, blocks }, blocks a
list of { type, data } (a JSON column). list() is asked for filters: { slug } to
find a page and MUST honour it. memorySource does; a Laravel/Go backend filters
the column. memorySource is demo-only: edits are lost on restart and not
shared between replicas - real pages go in the app's database (a pages table,
JSON blocks column, behind rpc()). Each block's data is checked by its own schema on save, errors under
blocks.<index>.<field>; a second page at a taken slug is refused under slug.

A looked-up page is kept between requests with cache() (memory unless the app
calls installCacheStore) for definePages({ revalidate }) seconds, 60 by default,
false to ask every request. A save in the panel calls changed('press:pages'), so
it is live on the next visit; a write straight to the database shows on expiry,
or at once after the app calls changed('press:pages') itself.

BLOCKS IN ANY RESOURCE: fields: { body: { blocks: [text, quote] } } on a
z.array(z.any()) property gives it the block editor; draw it with
<Blocks blocks={[text, quote]} value={post.body} /> from @rsc-kit/press.
A block kind the code no longer defines is left out of the page, not an error.

UPLOADS: fields: { photo: { type: 'image', storage, maxSize } } on a z.url()
(or z.string()) property; type: 'file' with accept: '.pdf' for documents.
Works in a resource, a block and a public form. storage is
{ put(file, { field, tenant }) => Promise<string> } - press ships none; the
string is what the record saves (a url). Write to S3/R2/disk from put; a
Laravel/Go backend gets the url, not the file (rpc() carries JSON), so use the
bucket its disk reads. Uploads are stored only after the rest of the form
passes. Image fields refuse SVG unless accept NAMES it ('image/svg+xml' or
'.svg'): a wildcard like 'image/*' takes only what the bytes prove (PNG, JPEG,
GIF, WebP, AVIF, PDF), and one with nothing provable under it ('text/*',
'video/*') throws when the field is defined - name the types ('text/csv,.csv'). Make the property
.nullable() for a Remove button that saves null. Old files are not deleted.`,
    },
];
/** Every topic, with one line each — what a caller reads before choosing. */
export function listTopics() {
    return [
        'Topics. Ask for one with how_to({ topic }).',
        '',
        ...RECIPES.map((r) => `${r.topic.padEnd(16)} ${r.summary}`),
    ].join('\n');
}
/** One recipe, or the list plus a nudge when the topic is not one. */
export function howTo(topic) {
    const wanted = topic.trim().toLowerCase().replace(/[\s_]+/g, '-');
    const found = RECIPES.find((r) => r.topic === wanted) ??
        // A near miss is common and worth answering rather than refusing: someone
        // asks for "form" or "queries" and means the obvious thing.
        RECIPES.find((r) => r.topic.startsWith(wanted) || wanted.startsWith(r.topic)) ??
        // The summary is prose, so a multi-word ask is matched with its spaces back.
        RECIPES.find((r) => r.summary.toLowerCase().replace(/[-\s]+/g, ' ').includes(wanted.replace(/-/g, ' ')));
    if (!found)
        return `No topic "${topic}".\n\n${listTopics()}`;
    return `# ${found.topic} — ${found.summary}\n\n${found.body}`;
}
/** For tests, so a recipe cannot be added without being reachable. */
export const TOPICS = RECIPES.map((r) => r.topic);
//# sourceMappingURL=recipes.js.map