@rsc-kit/core 0.22.8 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,7 +20,7 @@ import { ServerRedirectError, noteRedirected, throwForFailedAction } from "./err
20
20
  import { fetchPagePayload } from "./pagePayload";
21
21
  import { claimRead, setQueryCodec } from "./queryClient";
22
22
  import { clearSegments, dropHidden, isHeld, prerenderSegment, restoreSegments, setSegment } from "./segmentStore";
23
- import { cancelPrefetch, isPrefetched, navigate, setApiRoutes, refresh, applyRevalidations, prefetch, retentionKey, setCallServer, setHeldLayouts, setStaticPayloads, setStaticRoutes, seedStaticChain, payloadUrl, setDeserializer, setInterceptManifest, getHeldLayouts, setNavigateHandler, setHeldHandlers, setPrerenderHandler, setReplaceRootHandler, setRestoreHandler, setVersion, } from "./navigate";
23
+ import { cancelPrefetch, forgetOtherPages, isPrefetched, navigate, setApiRoutes, refresh, applyRevalidations, prefetch, retentionKey, setCallServer, setHeldLayouts, setStaticPayloads, setStaticRoutes, seedStaticChain, payloadUrl, setDeserializer, setInterceptManifest, getHeldLayouts, setNavigateHandler, setHeldHandlers, setPrerenderHandler, setReplaceRootHandler, setRestoreHandler, setVersion, } from "./navigate";
24
24
  /**
25
25
  * A redirect that travelled as an error: the digest of the error itself, or
26
26
  * of the cause React wraps it in when it reports client-rendering a boundary
@@ -114,7 +114,15 @@ export async function createViteRscApp(container = document, interceptEntries =
114
114
  // state dropped, pending went false - and the page it redirected to
115
115
  // arrived a frame later. A new chat's first message vanished from
116
116
  // the thread and came back with its reply.
117
+ //
118
+ // Asked of the server, never revealed from what the router holds. The
119
+ // action may have changed anything the destination reads - a cookie,
120
+ // a membership, a row - and a page kept from before it, or prefetched
121
+ // before it, shows the world as it was: a sign-in that redirected
122
+ // back showed the page signed out until a reload. What a revalidating
123
+ // action already drops, a redirecting one drops too.
117
124
  if (isSafeRedirect(err.location)) {
125
+ forgetOtherPages();
118
126
  try {
119
127
  await navigate(err.location, { replace: true });
120
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"createViteRscApp.js","sourceRoot":"","sources":["../../src/js/createViteRscApp.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,qFAAqF;AACrF,8EAA8E;AAC9E,4EAA4E;AAC5E,qCAAqC;AACrC,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EACL,wBAAwB,EACxB,WAAW,EACX,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AACrF,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,gBAAgB,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAElH,OAAO,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GAAG,EAAE,MAAM,CAAC,CAC7B,CAAC;IACF,eAAe,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAEpC,uEAAuE;IACvE,oEAAoE;IACpE,mBAAmB,CAAC,CAAC,IAAa,EAAE,GAAW,EAAE,YAAoB,EAAE,EAAE;QACvE,gBAAgB,CAAC,YAAY,EAAE,GAAG,EAAE,IAAiB,CAAC,CAAC;IACzD,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,GAAG,EAAE;QACvC,yEAAyE;QACzE,gEAAgE;QAChE,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,YAAY,CAClB,EAAE,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,EAChC,EAAE,EACF,MAAM,CAAC,QAAQ,CAAC,IAAI,CACrB,CAAC;IAEF,sEAAsE;IACtE,sEAAsE;IACtE,sEAAsE;IACtE,mEAAmE;IACnE,cAAc,CAAC,GAAG,EAAE,CAAC,iBAAiB,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAY,CAAC,CAAC,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["// Vite-engine client bootstrap. Uses @vitejs/plugin-rsc's browser runtime as\n// the Flight deserializer + action encoder, and drives the package's engine-agnostic\n// navigate.ts SPA engine (Link, prefetch, popstate) through it. This replaces\n// the bun engine's createRscApp + the hand-rolled webpack shim — the plugin\n// resolves client references itself.\nimport { SEARCH_PARAMS_FALLBACK } from \"./useSearchParams\";\nimport { recoverFromStaleAssets } from \"./staleAssets\";\nimport { afterHydration, replayEarlyClicks } from \"./earlyClicks\";\nimport { parseRedirectDigest } from \"../redirectDigest.js\";\nimport { showDevNotice } from \"./devNotice\";\nimport { caughtByLoading } from \"./fallbackReport\";\nimport { noteNavigation } from \"./segmentStore\";\nimport type { Route } from \"../routes.js\";\nimport { isSafeRedirect } from \"../safeUrl.js\";\nimport {\n createFromReadableStream,\n encodeReply,\n setServerCallback,\n} from \"@vitejs/plugin-rsc/browser\";\nimport { createElement, startTransition } from \"react\";\nimport { createRoot, hydrateRoot } from \"react-dom/client\";\nimport { activityMarkersIn } from \"./activityMarkers\";\nimport { ActivityRoot } from \"./ActivityRouter\";\nimport { ServerRedirectError, noteRedirected, throwForFailedAction } from \"./errors\";\nimport { fetchPagePayload } from \"./pagePayload\";\nimport { claimRead, setQueryCodec } from \"./queryClient\";\nimport { clearSegments, dropHidden, isHeld, prerenderSegment, restoreSegments, setSegment } from \"./segmentStore\";\nimport type { ReactNode } from \"react\";\nimport {\n cancelPrefetch,\n isPrefetched,\n navigate,\n setApiRoutes,\n refresh,\n applyRevalidations,\n prefetch,\n retentionKey,\n setCallServer,\n setHeldLayouts,\n setStaticPayloads,\n setStaticRoutes,\n seedStaticChain,\n payloadUrl,\n setDeserializer,\n setInterceptManifest,\n getHeldLayouts,\n setNavigateHandler,\n setHeldHandlers,\n setPrerenderHandler,\n setReplaceRootHandler,\n setRestoreHandler,\n setVersion,\n} from \"./navigate\";\n\n\n/**\n * A redirect that travelled as an error: the digest of the error itself, or\n * of the cause React wraps it in when it reports client-rendering a boundary\n * the server had already failed.\n */\nfunction isRedirect(error: unknown): boolean {\n const digest = (error as { digest?: unknown } | null)?.digest;\n const cause = (error as { cause?: { digest?: unknown } } | null)?.cause;\n\n return parseRedirectDigest(digest) !== null || parseRedirectDigest(cause?.digest) !== null;\n}\n\nexport async function createViteRscApp(\n container: Document | Element = document,\n interceptEntries: { urlPattern: string; slot: string }[] = [],\n options: { staticPayloads?: string | null; routes?: unknown[] | null; apiRoutes?: string[] } = {},\n): Promise<void> {\n // The urls a route.ts answers: a link to one is an anchor, never a\n // prefetch, never a payload fetch.\n if (options.apiRoutes) setApiRoutes(options.apiRoutes);\n // An exported build has no server to negotiate with, so payloads live at\n // their own urls rather than behind a header on the page's url.\n setStaticPayloads(options.staticPayloads ?? null);\n // Only an exported build ships this: with no server to negotiate with, the\n // client works out for itself how much of a page it still holds.\n if (options.routes) setStaticRoutes(options.routes as never);\n // The router has to recognise an intercepted link before it asks the server,\n // so the patterns are baked into the generated browser entry. Without them\n // every intercepted route falls through to a full-page navigation.\n setInterceptManifest(interceptEntries);\n\n async function callServer(id: string, args: unknown[]): Promise<unknown> {\n // A read opened a slot before calling the reference, and this is the first\n // point at which the id exists on the client — React keeps it private and\n // hands it over only here. Claiming the slot enqueues the read for the\n // batched GET instead of posting it.\n const read = claimRead(id, args);\n\n if (read) return await read;\n\n const encoded = await encodeReply(args);\n\n // encodeReply returns FormData as soon as an argument contains a File.\n // Sending that as multipart would make PHP consume php://input while\n // parsing it, leaving the action with an empty body — so serialize it to\n // raw bytes under an opaque content-type and send the real one in\n // X-RSC-Content-Type for the worker to rebuild FormData from.\n let body: BodyInit;\n let realContentType: string;\n\n if (encoded instanceof FormData) {\n const serialized = new Response(encoded);\n body = await serialized.arrayBuffer();\n realContentType =\n serialized.headers.get(\"content-type\") ?? \"multipart/form-data\";\n } else {\n body = encoded as BodyInit;\n realContentType = \"text/plain;charset=UTF-8\";\n }\n\n // Where the action was invoked from. The host resolves it to the\n // components that render the page, so anything the action says it\n // invalidated can come back with the answer instead of being fetched\n // afterwards - and what comes back is for this page, not whichever is\n // showing when it lands.\n const from = window.location.pathname + window.location.search;\n\n const res = await fetch(\"/_rsc/action\", {\n method: \"POST\",\n headers: {\n \"X-RSC-Action\": id,\n \"X-RSC-Referer\": from,\n \"X-RSC-Content-Type\": realContentType,\n \"Content-Type\": \"application/octet-stream\",\n \"X-XSRF-TOKEN\": decodeURIComponent(\n document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1] ?? \"\",\n ),\n },\n body,\n });\n\n // A failed action does not answer with a Flight stream, and the decoder\n // cannot tell — it reports its own parse failure instead of what the\n // server said.\n try {\n await throwForFailedAction(res);\n } catch (err) {\n // A redirect is an instruction, not something for a form to display:\n // an expired session answers this way, and the destination is the login\n // page rather than a message about one.\n if (err instanceof ServerRedirectError) {\n // The destination came off a response header, so it is checked here\n // too — the engine refuses these at the source, but a proxy or a host\n // in front of it can write whatever it likes. A navigation, not a\n // document load: the layouts stay mounted and the history entry the\n // form was on is replaced, the way a redirect after a POST should\n // be - Back does not return to the submitted form.\n //\n // Awaited, so the action is still pending when the destination's\n // tree is handed to React: the two are one transition, committed\n // together. Not awaited, the action ended first - its optimistic\n // state dropped, pending went false - and the page it redirected to\n // arrived a frame later. A new chat's first message vanished from\n // the thread and came back with its reply.\n if (isSafeRedirect(err.location)) {\n try {\n await navigate(err.location as Route, { replace: true });\n } catch {\n // Announced by the navigation itself, as rsc-navigate-error. The\n // action did redirect; that is still its answer.\n }\n }\n\n // Performed, so resolved - not thrown. The call's answer is \"you are\n // being taken somewhere\": an object saying so, the shape an action's\n // result already has, so a caller reading result.validationErrors\n // reads undefined rather than throwing. A caller that awaited the\n // action in a plain startTransition had no catch for a throw, the\n // rejection reached React, and the root unmounted to a white page\n // on every logout.\n noteRedirected(err.location);\n\n return { redirected: err.location };\n }\n\n throw err;\n }\n\n const answer = await createFromReadableStream(res.body!, { callServer });\n\n return unwrapRevalidated(answer, from);\n }\n\n /**\n * Put anything the action re-rendered on screen, and hand back its result.\n *\n * The trees travel with the answer rather than being fetched afterwards, so\n * the caller sees only what its action returned and never knows the page\n * was updated around it.\n */\n function unwrapRevalidated(answer: unknown, from: string): unknown {\n if (\n answer === null ||\n typeof answer !== \"object\" ||\n !(\"__rscRevalidated\" in answer)\n ) {\n return answer;\n }\n\n const envelope = answer as {\n __rscRevalidated: Record<string, unknown>;\n result: unknown;\n };\n\n applyRevalidations(from, envelope.__rscRevalidated as Record<string, ReactNode>);\n\n return envelope.result;\n }\n\n setDeserializer(createFromReadableStream as never);\n // The query transport speaks Flight too, and reaches the runtime through here\n // rather than importing it: a second import of the browser runtime from the\n // client-component graph is a second client-reference registry, and the\n // symptom is components that render as undefined with nothing logged.\n setQueryCodec({\n deserialize: (stream) =>\n createFromReadableStream(stream, { callServer }) as Promise<unknown>,\n encode: (args) => encodeReply(args) as Promise<string | FormData>,\n // The way back when a read cannot ride in a url. Re-entering callServer is\n // safe: the slot was cleared the moment the reference returned, so this\n // takes the ordinary POST path rather than claiming a read again.\n asAction: (id, args) => callServer(id, args),\n });\n setCallServer(callServer);\n // The plugin's own \"use server\" client stubs route through its registered\n // server callback — register the same transport there too.\n setServerCallback(callServer as never);\n\n // Link / Form / router live in a separate build graph and reach the SPA\n // engine through these globals.\n (window as unknown as { __rsc_navigate: typeof navigate }).__rsc_navigate =\n navigate;\n (window as unknown as { __rsc_prefetch: typeof prefetch }).__rsc_prefetch =\n prefetch;\n (\n window as unknown as { __rsc_cancel_prefetch: typeof cancelPrefetch }\n ).__rsc_cancel_prefetch = cancelPrefetch;\n (\n window as unknown as { __rsc_is_prefetched: typeof isPrefetched }\n ).__rsc_is_prefetched = isPrefetched;\n (window as unknown as { __rsc_refresh: typeof refresh }).__rsc_refresh =\n refresh;\n\n // Hydrate from the RSC endpoint (same url + X-RSC, no version header).\n //\n // Everything from here to the decode is failure handling, because this is\n // the one request with nothing watching it. A page whose shell is already\n // rendered looks fine while this fails, and its fallbacks stay on screen\n // indefinitely with nothing reported anywhere.\n const res = await fetchPagePayload(payloadUrl(window.location.href));\n\n // Seed the router with the build this DOCUMENT is, so a redeploy is caught\n // on the next navigation: the host answers 409 to a client of another\n // build, and the document is loaded again. From the document's own meta\n // first - a document a service worker served from its cache is the last\n // build's, while the payload just fetched is this one's, and seeding from\n // the payload would have the old client claim to be new. The header is\n // the fallback for a document with no meta.\n const documentBuild = document.querySelector('meta[name=\"rsc-kit:build\"]')?.getAttribute(\"content\");\n const servedVersion = documentBuild || res.headers.get(\"X-RSC-Version\");\n\n if (servedVersion) {\n setVersion(servedVersion);\n }\n\n // The chain this page is built from, so the next navigation can say what is\n // already mounted and be sent only what changed.\n // A server says what this page is built from; a file server says nothing,\n // so an exported build works it out from the table it was given.\n const servedLayouts = res.headers.get(\"X-RSC-Layouts\");\n\n if (servedLayouts !== null) {\n setHeldLayouts(servedLayouts.split(\",\"));\n } else if (!seedStaticChain(window.location.href)) {\n setHeldLayouts([]);\n }\n const tree = await createFromReadableStream(res.body!, { callServer });\n\n // Retaining the previous page behind <Activity> needs a wrapper above the\n // page, and React will not hydrate a *document* container through one: the\n // root child of a document has to be <html>, and wrapping it hangs the\n // renderer outright (React 19.2.7). An app whose root layout owns <html>\n // therefore hydrates the tree directly and navigations replace it, as before.\n //\n // Apps that hydrate into an element get retention. Giving it to document-\n // rooted apps means SPA navigation returning only the changed segment rather\n // than a whole document, which is an engine change, not a client one.\n const retains = container !== document;\n\n const shell = retains\n ? createElement(ActivityRoot, {\n initialKey: retentionKey(window.location.href, null),\n initialTree: tree as ReactNode,\n })\n : (tree as ReactNode);\n\n // A document that cannot be hydrated by this tree is client-rendered\n // instead - a repaint, not a freeze. React 19.2 does not recover from a\n // hydration mismatch at an <Activity>: it retries hydrating the boundary,\n // mismatches again, and never returns to the main thread. Every segment\n // boundary is an Activity, one per layout, so a document with none where\n // the page has layouts is that mismatch, guaranteed, before React starts.\n // What produced one: a parameterised route's PPR shell, rendered without\n // a page key and, by a build before this one, without the Activities too.\n // None rather than fewer: a boundary inside a Suspense hole the shell left\n // unfinished has no marker and is client-rendered by React on its own,\n // which is not a mismatch. The stale-asset reload does not apply - the\n // document would come back the same.\n const missing = retains && getHeldLayouts().length > 0 && activityMarkersIn(container) === 0;\n\n if (missing) {\n console.warn(\n \"[rsc-kit] The document has no <Activity> boundaries where the page has layouts, so it cannot be hydrated; rendering the page instead. A PPR shell built by an earlier release lacks them - rebuild.\",\n );\n }\n\n // The payload answered with an error status - the not-found page for a\n // url the shell was served for anyway. It is not the document on screen,\n // so it is rendered, not hydrated: a mismatch at an Activity is the loop\n // above, and this one is certain.\n const disagrees = !res.ok;\n\n const onRecoverableError = (error: unknown, errorInfo: unknown) => {\n // A client component whose chunk the server no longer has fails while\n // hydrating, and React reports that as recoverable: the page is loaded\n // again, with the current names.\n if (recoverFromStaleAssets(error)) return;\n\n // A redirect decided inside a boundary: the server's row carried it as\n // the digest, React client-renders the boundary and reports that it\n // did, and the RedirectBoundary is already performing it. Nothing to\n // read in the console about a page doing what it was told.\n if (isRedirect(error)) return;\n\n // A PPR shell is served with its Suspense boundaries deliberately\n // unfinished — the build aborts the render once the static part is out.\n // React reports that as #419 and client-renders the boundary from the\n // Flight payload, which is the intended path, not a fault to report.\n const message = String((error as { message?: string })?.message ?? error);\n\n if (\n message.includes(\"419\") ||\n message.includes(\"did not finish this Suspense boundary\")\n ) {\n return;\n }\n\n // A view transition the browser cancelled because the tab was not\n // visible. React reports it here; the update still landed, and a tab\n // in the background is not a fault in the page.\n if (message.includes(\"Transition was aborted\")) return;\n\n // A navigation another one overtook: its request was aborted, and a\n // row of its payload that a component was still reading rejects with\n // the abort. React recovers by rendering the root again synchronously\n // and reports the recovery here as #520, with the abort as the cause.\n // The page it recovered to is the one the second navigation asked for;\n // the abort was the design, not a fault.\n const cause = (error as { cause?: { name?: string; message?: string } } | null)?.cause;\n\n if (\n cause?.name === \"AbortError\" ||\n /\\baborted\\b/i.test(cause?.message ?? \"\") ||\n /\\baborted\\b/i.test(message)\n ) {\n return;\n }\n // A page whose query string was read under a boundary carries the\n // fallback there; React reports the recovery on hydration. Under a\n // boundary the developer wrote, that is the designed path and nothing\n // is said. With nothing closer than a loading.tsx, the whole segment\n // showed the fallback until the query arrived - said here, in the\n // page and the console, for whoever is looking at either. Production\n // has no stack to tell the two apart; the build's note on the route is\n // the record there.\n if (\n (error as { digest?: string })?.digest === SEARCH_PARAMS_FALLBACK ||\n message.includes(\"useSearchParams()\")\n ) {\n const stack = (errorInfo as { componentStack?: string } | null)\n ?.componentStack;\n\n if (!caughtByLoading(stack)) return;\n\n const hint =\n \"useSearchParams() was read on the server with nothing closer than a loading.tsx, so the \" +\n \"whole segment showed that fallback until the query arrived. A <Suspense> around the \" +\n \"component that reads keeps the rest of the page painted.\";\n\n showDevNotice(hint, stack);\n console.error(new Error(hint), errorInfo);\n\n return;\n }\n\n console.error(error, errorInfo);\n };\n\n const rootOptions = {\n onRecoverableError,\n // A chunk the deploy no longer serves is not a fault in the page; the\n // document is loaded again, and the new names come with it. Anything\n // else is reported the way React would have.\n onUncaughtError(error: unknown, errorInfo: unknown) {\n if (recoverFromStaleAssets(error)) return;\n\n console.error(error, errorInfo);\n },\n onCaughtError(error: unknown, errorInfo: unknown) {\n if (recoverFromStaleAssets(error)) return;\n // Caught by the RedirectBoundary, which is performing it.\n if (isRedirect(error)) return;\n\n console.error(error, errorInfo);\n },\n };\n\n const root = missing || disagrees\n ? (() => {\n const created = createRoot(container as Element, rootOptions);\n\n created.render(shell);\n\n return created;\n })()\n : hydrateRoot(container, shell, rootOptions);\n\n // Depth 0 is a whole document and replaces the root. Anything deeper is one\n // segment: handing it to the boundary at that depth leaves the layouts above\n // it mounted, which is the point of asking for a partial render at all.\n setNavigateHandler((tree: unknown, key: string, segmentDepth: number, inPlaceOf?: string | null) => {\n const newTree = tree as ReactNode;\n\n // From here on the boundary animates; the seed commit before this did not.\n noteNavigation();\n\n if (segmentDepth > 0) {\n setSegment(segmentDepth, key, newTree, inPlaceOf);\n\n return;\n }\n\n clearSegments();\n root.render(newTree);\n });\n\n // The whole document again, in place - revalidate(\"all\"). Not through the\n // handler above: that clears the boundaries and renders the tree as a new\n // page, and a boundary emptied re-keys its Activity to the current url and\n // remounts everything under it. A port's \"added to cart\" went with the\n // form's state that way, on every product reached by a link. Here the root\n // takes the tree in a transition and each boundary hands its page the new\n // children under the key it has - see replaceActive.\n setReplaceRootHandler((tree: unknown) => {\n startTransition(() => root.render(tree as ReactNode));\n });\n\n // Back and forward reveal a page the boundaries are still holding, with the\n // form you were filling in still filled in, and without asking the server.\n setRestoreHandler((key: string, maxAge?: number) =>\n restoreSegments(key, maxAge),\n );\n setHeldHandlers(isHeld, dropHidden);\n\n // A touch or a settled hover: the page is rendered hidden now, and the\n // click reveals it. See warm() in navigate.ts and prerenderSegment.\n setPrerenderHandler((tree: unknown, key: string, segmentDepth: number) => {\n prerenderSegment(segmentDepth, key, tree as ReactNode);\n });\n\n window.addEventListener(\"popstate\", () => {\n // restore: back and forward reveal the page you were on, with its state.\n // Wherever the browser just went; not a literal this app wrote.\n navigate(window.location.href as Route, { replace: true, restore: true });\n });\n\n history.replaceState(\n { rscUrl: window.location.href },\n \"\",\n window.location.href,\n );\n\n // A tap held by the bootstrap script, navigated to once hydration has\n // committed - not now: the runtime's script running is seconds before\n // React can dispatch a click on a phone still downloading chunks, and\n // a tap in that window would be the browser's. See earlyClicks.ts.\n afterHydration(() => replayEarlyClicks((url) => navigate(url as Route)));\n}\n\n"]}
1
+ {"version":3,"file":"createViteRscApp.js","sourceRoot":"","sources":["../../src/js/createViteRscApp.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,qFAAqF;AACrF,8EAA8E;AAC9E,4EAA4E;AAC5E,qCAAqC;AACrC,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EACL,wBAAwB,EACxB,WAAW,EACX,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AACvD,OAAO,E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AC,QAAQ,CAAC,IAAI,CACrB,CAAC;IAEF,sEAAsE;IACtE,sEAAsE;IACtE,sEAAsE;IACtE,mEAAmE;IACnE,cAAc,CAAC,GAAG,EAAE,CAAC,iBAAiB,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAY,CAAC,CAAC,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["// Vite-engine client bootstrap. Uses @vitejs/plugin-rsc's browser runtime as\n// the Flight deserializer + action encoder, and drives the package's engine-agnostic\n// navigate.ts SPA engine (Link, prefetch, popstate) through it. This replaces\n// the bun engine's createRscApp + the hand-rolled webpack shim — the plugin\n// resolves client references itself.\nimport { SEARCH_PARAMS_FALLBACK } from \"./useSearchParams\";\nimport { recoverFromStaleAssets } from \"./staleAssets\";\nimport { afterHydration, replayEarlyClicks } from \"./earlyClicks\";\nimport { parseRedirectDigest } from \"../redirectDigest.js\";\nimport { showDevNotice } from \"./devNotice\";\nimport { caughtByLoading } from \"./fallbackReport\";\nimport { noteNavigation } from \"./segmentStore\";\nimport type { Route } from \"../routes.js\";\nimport { isSafeRedirect } from \"../safeUrl.js\";\nimport {\n createFromReadableStream,\n encodeReply,\n setServerCallback,\n} from \"@vitejs/plugin-rsc/browser\";\nimport { createElement, startTransition } from \"react\";\nimport { createRoot, hydrateRoot } from \"react-dom/client\";\nimport { activityMarkersIn } from \"./activityMarkers\";\nimport { ActivityRoot } from \"./ActivityRouter\";\nimport { ServerRedirectError, noteRedirected, throwForFailedAction } from \"./errors\";\nimport { fetchPagePayload } from \"./pagePayload\";\nimport { claimRead, setQueryCodec } from \"./queryClient\";\nimport { clearSegments, dropHidden, isHeld, prerenderSegment, restoreSegments, setSegment } from \"./segmentStore\";\nimport type { ReactNode } from \"react\";\nimport {\n cancelPrefetch,\n forgetOtherPages,\n isPrefetched,\n navigate,\n setApiRoutes,\n refresh,\n applyRevalidations,\n prefetch,\n retentionKey,\n setCallServer,\n setHeldLayouts,\n setStaticPayloads,\n setStaticRoutes,\n seedStaticChain,\n payloadUrl,\n setDeserializer,\n setInterceptManifest,\n getHeldLayouts,\n setNavigateHandler,\n setHeldHandlers,\n setPrerenderHandler,\n setReplaceRootHandler,\n setRestoreHandler,\n setVersion,\n} from \"./navigate\";\n\n\n/**\n * A redirect that travelled as an error: the digest of the error itself, or\n * of the cause React wraps it in when it reports client-rendering a boundary\n * the server had already failed.\n */\nfunction isRedirect(error: unknown): boolean {\n const digest = (error as { digest?: unknown } | null)?.digest;\n const cause = (error as { cause?: { digest?: unknown } } | null)?.cause;\n\n return parseRedirectDigest(digest) !== null || parseRedirectDigest(cause?.digest) !== null;\n}\n\nexport async function createViteRscApp(\n container: Document | Element = document,\n interceptEntries: { urlPattern: string; slot: string }[] = [],\n options: { staticPayloads?: string | null; routes?: unknown[] | null; apiRoutes?: string[] } = {},\n): Promise<void> {\n // The urls a route.ts answers: a link to one is an anchor, never a\n // prefetch, never a payload fetch.\n if (options.apiRoutes) setApiRoutes(options.apiRoutes);\n // An exported build has no server to negotiate with, so payloads live at\n // their own urls rather than behind a header on the page's url.\n setStaticPayloads(options.staticPayloads ?? null);\n // Only an exported build ships this: with no server to negotiate with, the\n // client works out for itself how much of a page it still holds.\n if (options.routes) setStaticRoutes(options.routes as never);\n // The router has to recognise an intercepted link before it asks the server,\n // so the patterns are baked into the generated browser entry. Without them\n // every intercepted route falls through to a full-page navigation.\n setInterceptManifest(interceptEntries);\n\n async function callServer(id: string, args: unknown[]): Promise<unknown> {\n // A read opened a slot before calling the reference, and this is the first\n // point at which the id exists on the client — React keeps it private and\n // hands it over only here. Claiming the slot enqueues the read for the\n // batched GET instead of posting it.\n const read = claimRead(id, args);\n\n if (read) return await read;\n\n const encoded = await encodeReply(args);\n\n // encodeReply returns FormData as soon as an argument contains a File.\n // Sending that as multipart would make PHP consume php://input while\n // parsing it, leaving the action with an empty body — so serialize it to\n // raw bytes under an opaque content-type and send the real one in\n // X-RSC-Content-Type for the worker to rebuild FormData from.\n let body: BodyInit;\n let realContentType: string;\n\n if (encoded instanceof FormData) {\n const serialized = new Response(encoded);\n body = await serialized.arrayBuffer();\n realContentType =\n serialized.headers.get(\"content-type\") ?? \"multipart/form-data\";\n } else {\n body = encoded as BodyInit;\n realContentType = \"text/plain;charset=UTF-8\";\n }\n\n // Where the action was invoked from. The host resolves it to the\n // components that render the page, so anything the action says it\n // invalidated can come back with the answer instead of being fetched\n // afterwards - and what comes back is for this page, not whichever is\n // showing when it lands.\n const from = window.location.pathname + window.location.search;\n\n const res = await fetch(\"/_rsc/action\", {\n method: \"POST\",\n headers: {\n \"X-RSC-Action\": id,\n \"X-RSC-Referer\": from,\n \"X-RSC-Content-Type\": realContentType,\n \"Content-Type\": \"application/octet-stream\",\n \"X-XSRF-TOKEN\": decodeURIComponent(\n document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1] ?? \"\",\n ),\n },\n body,\n });\n\n // A failed action does not answer with a Flight stream, and the decoder\n // cannot tell — it reports its own parse failure instead of what the\n // server said.\n try {\n await throwForFailedAction(res);\n } catch (err) {\n // A redirect is an instruction, not something for a form to display:\n // an expired session answers this way, and the destination is the login\n // page rather than a message about one.\n if (err instanceof ServerRedirectError) {\n // The destination came off a response header, so it is checked here\n // too — the engine refuses these at the source, but a proxy or a host\n // in front of it can write whatever it likes. A navigation, not a\n // document load: the layouts stay mounted and the history entry the\n // form was on is replaced, the way a redirect after a POST should\n // be - Back does not return to the submitted form.\n //\n // Awaited, so the action is still pending when the destination's\n // tree is handed to React: the two are one transition, committed\n // together. Not awaited, the action ended first - its optimistic\n // state dropped, pending went false - and the page it redirected to\n // arrived a frame later. A new chat's first message vanished from\n // the thread and came back with its reply.\n //\n // Asked of the server, never revealed from what the router holds. The\n // action may have changed anything the destination reads - a cookie,\n // a membership, a row - and a page kept from before it, or prefetched\n // before it, shows the world as it was: a sign-in that redirected\n // back showed the page signed out until a reload. What a revalidating\n // action already drops, a redirecting one drops too.\n if (isSafeRedirect(err.location)) {\n forgetOtherPages();\n\n try {\n await navigate(err.location as Route, { replace: true });\n } catch {\n // Announced by the navigation itself, as rsc-navigate-error. The\n // action did redirect; that is still its answer.\n }\n }\n\n // Performed, so resolved - not thrown. The call's answer is \"you are\n // being taken somewhere\": an object saying so, the shape an action's\n // result already has, so a caller reading result.validationErrors\n // reads undefined rather than throwing. A caller that awaited the\n // action in a plain startTransition had no catch for a throw, the\n // rejection reached React, and the root unmounted to a white page\n // on every logout.\n noteRedirected(err.location);\n\n return { redirected: err.location };\n }\n\n throw err;\n }\n\n const answer = await createFromReadableStream(res.body!, { callServer });\n\n return unwrapRevalidated(answer, from);\n }\n\n /**\n * Put anything the action re-rendered on screen, and hand back its result.\n *\n * The trees travel with the answer rather than being fetched afterwards, so\n * the caller sees only what its action returned and never knows the page\n * was updated around it.\n */\n function unwrapRevalidated(answer: unknown, from: string): unknown {\n if (\n answer === null ||\n typeof answer !== \"object\" ||\n !(\"__rscRevalidated\" in answer)\n ) {\n return answer;\n }\n\n const envelope = answer as {\n __rscRevalidated: Record<string, unknown>;\n result: unknown;\n };\n\n applyRevalidations(from, envelope.__rscRevalidated as Record<string, ReactNode>);\n\n return envelope.result;\n }\n\n setDeserializer(createFromReadableStream as never);\n // The query transport speaks Flight too, and reaches the runtime through here\n // rather than importing it: a second import of the browser runtime from the\n // client-component graph is a second client-reference registry, and the\n // symptom is components that render as undefined with nothing logged.\n setQueryCodec({\n deserialize: (stream) =>\n createFromReadableStream(stream, { callServer }) as Promise<unknown>,\n encode: (args) => encodeReply(args) as Promise<string | FormData>,\n // The way back when a read cannot ride in a url. Re-entering callServer is\n // safe: the slot was cleared the moment the reference returned, so this\n // takes the ordinary POST path rather than claiming a read again.\n asAction: (id, args) => callServer(id, args),\n });\n setCallServer(callServer);\n // The plugin's own \"use server\" client stubs route through its registered\n // server callback — register the same transport there too.\n setServerCallback(callServer as never);\n\n // Link / Form / router live in a separate build graph and reach the SPA\n // engine through these globals.\n (window as unknown as { __rsc_navigate: typeof navigate }).__rsc_navigate =\n navigate;\n (window as unknown as { __rsc_prefetch: typeof prefetch }).__rsc_prefetch =\n prefetch;\n (\n window as unknown as { __rsc_cancel_prefetch: typeof cancelPrefetch }\n ).__rsc_cancel_prefetch = cancelPrefetch;\n (\n window as unknown as { __rsc_is_prefetched: typeof isPrefetched }\n ).__rsc_is_prefetched = isPrefetched;\n (window as unknown as { __rsc_refresh: typeof refresh }).__rsc_refresh =\n refresh;\n\n // Hydrate from the RSC endpoint (same url + X-RSC, no version header).\n //\n // Everything from here to the decode is failure handling, because this is\n // the one request with nothing watching it. A page whose shell is already\n // rendered looks fine while this fails, and its fallbacks stay on screen\n // indefinitely with nothing reported anywhere.\n const res = await fetchPagePayload(payloadUrl(window.location.href));\n\n // Seed the router with the build this DOCUMENT is, so a redeploy is caught\n // on the next navigation: the host answers 409 to a client of another\n // build, and the document is loaded again. From the document's own meta\n // first - a document a service worker served from its cache is the last\n // build's, while the payload just fetched is this one's, and seeding from\n // the payload would have the old client claim to be new. The header is\n // the fallback for a document with no meta.\n const documentBuild = document.querySelector('meta[name=\"rsc-kit:build\"]')?.getAttribute(\"content\");\n const servedVersion = documentBuild || res.headers.get(\"X-RSC-Version\");\n\n if (servedVersion) {\n setVersion(servedVersion);\n }\n\n // The chain this page is built from, so the next navigation can say what is\n // already mounted and be sent only what changed.\n // A server says what this page is built from; a file server says nothing,\n // so an exported build works it out from the table it was given.\n const servedLayouts = res.headers.get(\"X-RSC-Layouts\");\n\n if (servedLayouts !== null) {\n setHeldLayouts(servedLayouts.split(\",\"));\n } else if (!seedStaticChain(window.location.href)) {\n setHeldLayouts([]);\n }\n const tree = await createFromReadableStream(res.body!, { callServer });\n\n // Retaining the previous page behind <Activity> needs a wrapper above the\n // page, and React will not hydrate a *document* container through one: the\n // root child of a document has to be <html>, and wrapping it hangs the\n // renderer outright (React 19.2.7). An app whose root layout owns <html>\n // therefore hydrates the tree directly and navigations replace it, as before.\n //\n // Apps that hydrate into an element get retention. Giving it to document-\n // rooted apps means SPA navigation returning only the changed segment rather\n // than a whole document, which is an engine change, not a client one.\n const retains = container !== document;\n\n const shell = retains\n ? createElement(ActivityRoot, {\n initialKey: retentionKey(window.location.href, null),\n initialTree: tree as ReactNode,\n })\n : (tree as ReactNode);\n\n // A document that cannot be hydrated by this tree is client-rendered\n // instead - a repaint, not a freeze. React 19.2 does not recover from a\n // hydration mismatch at an <Activity>: it retries hydrating the boundary,\n // mismatches again, and never returns to the main thread. Every segment\n // boundary is an Activity, one per layout, so a document with none where\n // the page has layouts is that mismatch, guaranteed, before React starts.\n // What produced one: a parameterised route's PPR shell, rendered without\n // a page key and, by a build before this one, without the Activities too.\n // None rather than fewer: a boundary inside a Suspense hole the shell left\n // unfinished has no marker and is client-rendered by React on its own,\n // which is not a mismatch. The stale-asset reload does not apply - the\n // document would come back the same.\n const missing = retains && getHeldLayouts().length > 0 && activityMarkersIn(container) === 0;\n\n if (missing) {\n console.warn(\n \"[rsc-kit] The document has no <Activity> boundaries where the page has layouts, so it cannot be hydrated; rendering the page instead. A PPR shell built by an earlier release lacks them - rebuild.\",\n );\n }\n\n // The payload answered with an error status - the not-found page for a\n // url the shell was served for anyway. It is not the document on screen,\n // so it is rendered, not hydrated: a mismatch at an Activity is the loop\n // above, and this one is certain.\n const disagrees = !res.ok;\n\n const onRecoverableError = (error: unknown, errorInfo: unknown) => {\n // A client component whose chunk the server no longer has fails while\n // hydrating, and React reports that as recoverable: the page is loaded\n // again, with the current names.\n if (recoverFromStaleAssets(error)) return;\n\n // A redirect decided inside a boundary: the server's row carried it as\n // the digest, React client-renders the boundary and reports that it\n // did, and the RedirectBoundary is already performing it. Nothing to\n // read in the console about a page doing what it was told.\n if (isRedirect(error)) return;\n\n // A PPR shell is served with its Suspense boundaries deliberately\n // unfinished — the build aborts the render once the static part is out.\n // React reports that as #419 and client-renders the boundary from the\n // Flight payload, which is the intended path, not a fault to report.\n const message = String((error as { message?: string })?.message ?? error);\n\n if (\n message.includes(\"419\") ||\n message.includes(\"did not finish this Suspense boundary\")\n ) {\n return;\n }\n\n // A view transition the browser cancelled because the tab was not\n // visible. React reports it here; the update still landed, and a tab\n // in the background is not a fault in the page.\n if (message.includes(\"Transition was aborted\")) return;\n\n // A navigation another one overtook: its request was aborted, and a\n // row of its payload that a component was still reading rejects with\n // the abort. React recovers by rendering the root again synchronously\n // and reports the recovery here as #520, with the abort as the cause.\n // The page it recovered to is the one the second navigation asked for;\n // the abort was the design, not a fault.\n const cause = (error as { cause?: { name?: string; message?: string } } | null)?.cause;\n\n if (\n cause?.name === \"AbortError\" ||\n /\\baborted\\b/i.test(cause?.message ?? \"\") ||\n /\\baborted\\b/i.test(message)\n ) {\n return;\n }\n // A page whose query string was read under a boundary carries the\n // fallback there; React reports the recovery on hydration. Under a\n // boundary the developer wrote, that is the designed path and nothing\n // is said. With nothing closer than a loading.tsx, the whole segment\n // showed the fallback until the query arrived - said here, in the\n // page and the console, for whoever is looking at either. Production\n // has no stack to tell the two apart; the build's note on the route is\n // the record there.\n if (\n (error as { digest?: string })?.digest === SEARCH_PARAMS_FALLBACK ||\n message.includes(\"useSearchParams()\")\n ) {\n const stack = (errorInfo as { componentStack?: string } | null)\n ?.componentStack;\n\n if (!caughtByLoading(stack)) return;\n\n const hint =\n \"useSearchParams() was read on the server with nothing closer than a loading.tsx, so the \" +\n \"whole segment showed that fallback until the query arrived. A <Suspense> around the \" +\n \"component that reads keeps the rest of the page painted.\";\n\n showDevNotice(hint, stack);\n console.error(new Error(hint), errorInfo);\n\n return;\n }\n\n console.error(error, errorInfo);\n };\n\n const rootOptions = {\n onRecoverableError,\n // A chunk the deploy no longer serves is not a fault in the page; the\n // document is loaded again, and the new names come with it. Anything\n // else is reported the way React would have.\n onUncaughtError(error: unknown, errorInfo: unknown) {\n if (recoverFromStaleAssets(error)) return;\n\n console.error(error, errorInfo);\n },\n onCaughtError(error: unknown, errorInfo: unknown) {\n if (recoverFromStaleAssets(error)) return;\n // Caught by the RedirectBoundary, which is performing it.\n if (isRedirect(error)) return;\n\n console.error(error, errorInfo);\n },\n };\n\n const root = missing || disagrees\n ? (() => {\n const created = createRoot(container as Element, rootOptions);\n\n created.render(shell);\n\n return created;\n })()\n : hydrateRoot(container, shell, rootOptions);\n\n // Depth 0 is a whole document and replaces the root. Anything deeper is one\n // segment: handing it to the boundary at that depth leaves the layouts above\n // it mounted, which is the point of asking for a partial render at all.\n setNavigateHandler((tree: unknown, key: string, segmentDepth: number, inPlaceOf?: string | null) => {\n const newTree = tree as ReactNode;\n\n // From here on the boundary animates; the seed commit before this did not.\n noteNavigation();\n\n if (segmentDepth > 0) {\n setSegment(segmentDepth, key, newTree, inPlaceOf);\n\n return;\n }\n\n clearSegments();\n root.render(newTree);\n });\n\n // The whole document again, in place - revalidate(\"all\"). Not through the\n // handler above: that clears the boundaries and renders the tree as a new\n // page, and a boundary emptied re-keys its Activity to the current url and\n // remounts everything under it. A port's \"added to cart\" went with the\n // form's state that way, on every product reached by a link. Here the root\n // takes the tree in a transition and each boundary hands its page the new\n // children under the key it has - see replaceActive.\n setReplaceRootHandler((tree: unknown) => {\n startTransition(() => root.render(tree as ReactNode));\n });\n\n // Back and forward reveal a page the boundaries are still holding, with the\n // form you were filling in still filled in, and without asking the server.\n setRestoreHandler((key: string, maxAge?: number) =>\n restoreSegments(key, maxAge),\n );\n setHeldHandlers(isHeld, dropHidden);\n\n // A touch or a settled hover: the page is rendered hidden now, and the\n // click reveals it. See warm() in navigate.ts and prerenderSegment.\n setPrerenderHandler((tree: unknown, key: string, segmentDepth: number) => {\n prerenderSegment(segmentDepth, key, tree as ReactNode);\n });\n\n window.addEventListener(\"popstate\", () => {\n // restore: back and forward reveal the page you were on, with its state.\n // Wherever the browser just went; not a literal this app wrote.\n navigate(window.location.href as Route, { replace: true, restore: true });\n });\n\n history.replaceState(\n { rscUrl: window.location.href },\n \"\",\n window.location.href,\n );\n\n // A tap held by the bootstrap script, navigated to once hydration has\n // committed - not now: the runtime's script running is seconds before\n // React can dispatch a click on a phone still downloading chunks, and\n // a tap in that window would be the browser's. See earlyClicks.ts.\n afterHydration(() => replayEarlyClicks((url) => navigate(url as Route)));\n}\n\n"]}
@@ -0,0 +1,55 @@
1
+ import type { ActionResult } from "../action.js";
2
+ type AnyAction = (...args: any[]) => Promise<ActionResult<any>>;
3
+ type DataOf<A extends AnyAction> = Awaited<ReturnType<A>> extends ActionResult<infer D> ? D : never;
4
+ export type UseActionStatus = "idle" | "executing" | "hasSucceeded" | "hasErrored";
5
+ export interface UseActionOptions<A extends AnyAction> {
6
+ /**
7
+ * Called inside the action's transition, before the action runs, with what
8
+ * it was called with - where React's `useOptimistic` setter goes. React
9
+ * puts the optimistic state back when the transition ends, so a failed
10
+ * action takes its change back on its own.
11
+ */
12
+ optimistic?: (...args: Parameters<A>) => void;
13
+ /** The action answered with data: no serverError, no validationErrors. */
14
+ onSuccess?: (data: DataOf<A>) => void;
15
+ /**
16
+ * The action refused or failed. With a serverError, that message; with
17
+ * validationErrors, the first one - so a button with no field beside it
18
+ * still has something to show.
19
+ */
20
+ onError?: (message: string, result: ActionResult<DataOf<A>>) => void;
21
+ /** After either, for state that tracks the call rather than its outcome. */
22
+ onSettled?: (result: ActionResult<DataOf<A>>) => void;
23
+ }
24
+ /**
25
+ * Call an action from a button rather than a form.
26
+ *
27
+ * const { execute, isPending } = useAction(archivePost, {
28
+ * optimistic: (input) => hide(input.id),
29
+ * onError: (message) => toast.error(message),
30
+ * })
31
+ *
32
+ * <button disabled={isPending} onClick={() => execute({ id })}>Archive</button>
33
+ *
34
+ * The action's own types carry through: `execute` takes what the action's
35
+ * schema takes, and `onSuccess` is handed what its handler returns. A form does
36
+ * not need this - <Form> reads the same result on its own.
37
+ *
38
+ * Neither `execute` nor `executeAsync` throws. An action built on the action
39
+ * client returns its failures, and anything thrown on the way - the network,
40
+ * a server that answered with a page - becomes a serverError: left thrown,
41
+ * the transition never settled and an optimistic change stayed on screen as
42
+ * though the write had worked.
43
+ *
44
+ * An action that redirected settles nothing: no callback runs and no state is
45
+ * set, because the page is on its way somewhere else.
46
+ */
47
+ export declare function useAction<A extends AnyAction>(action: A, options?: UseActionOptions<A>): {
48
+ execute: (...args: Parameters<A>) => void;
49
+ executeAsync: (...args: Parameters<A>) => Promise<ActionResult<DataOf<A>>>;
50
+ isPending: boolean;
51
+ status: UseActionStatus;
52
+ result: ActionResult<DataOf<A>>;
53
+ reset: () => void;
54
+ };
55
+ export default useAction;
@@ -0,0 +1,79 @@
1
+ "use client";
2
+ import { useCallback, useLayoutEffect, useRef, useState, useTransition } from "react";
3
+ /**
4
+ * Call an action from a button rather than a form.
5
+ *
6
+ * const { execute, isPending } = useAction(archivePost, {
7
+ * optimistic: (input) => hide(input.id),
8
+ * onError: (message) => toast.error(message),
9
+ * })
10
+ *
11
+ * <button disabled={isPending} onClick={() => execute({ id })}>Archive</button>
12
+ *
13
+ * The action's own types carry through: `execute` takes what the action's
14
+ * schema takes, and `onSuccess` is handed what its handler returns. A form does
15
+ * not need this - <Form> reads the same result on its own.
16
+ *
17
+ * Neither `execute` nor `executeAsync` throws. An action built on the action
18
+ * client returns its failures, and anything thrown on the way - the network,
19
+ * a server that answered with a page - becomes a serverError: left thrown,
20
+ * the transition never settled and an optimistic change stayed on screen as
21
+ * though the write had worked.
22
+ *
23
+ * An action that redirected settles nothing: no callback runs and no state is
24
+ * set, because the page is on its way somewhere else.
25
+ */
26
+ export function useAction(action, options = {}) {
27
+ const [isPending, startTransition] = useTransition();
28
+ const [result, setResult] = useState({});
29
+ const [settled, setSettled] = useState(null);
30
+ // Read when the action runs, not when execute was made: execute keeps one
31
+ // identity across renders, so an onClick built on it is not rebuilt, and a
32
+ // callback closing over newer state is still the one called.
33
+ const latest = useRef({ action, options });
34
+ useLayoutEffect(() => {
35
+ latest.current = { action, options };
36
+ });
37
+ const run = useCallback(async (args) => {
38
+ const { action, options } = latest.current;
39
+ options.optimistic?.(...args);
40
+ let next;
41
+ try {
42
+ next = (await action(...args));
43
+ }
44
+ catch (error) {
45
+ next = { serverError: error instanceof Error ? error.message : String(error) };
46
+ }
47
+ if (next.redirected !== undefined)
48
+ return next;
49
+ setResult(next);
50
+ setSettled(next.serverError !== undefined || next.validationErrors ? "hasErrored" : "hasSucceeded");
51
+ if (next.serverError !== undefined) {
52
+ options.onError?.(next.serverError, next);
53
+ }
54
+ else if (next.validationErrors) {
55
+ options.onError?.(Object.values(next.validationErrors).flat()[0] ?? "Invalid input.", next);
56
+ }
57
+ else {
58
+ options.onSuccess?.(next.data);
59
+ }
60
+ options.onSettled?.(next);
61
+ return next;
62
+ }, []);
63
+ const executeAsync = useCallback((...args) => new Promise((resolve) => {
64
+ startTransition(async () => {
65
+ resolve(await run(args));
66
+ });
67
+ }), [run]);
68
+ const execute = useCallback((...args) => {
69
+ void executeAsync(...args);
70
+ }, [executeAsync]);
71
+ const reset = useCallback(() => {
72
+ setResult({});
73
+ setSettled(null);
74
+ }, []);
75
+ const status = isPending ? "executing" : (settled ?? "idle");
76
+ return { execute, executeAsync, isPending, status, result, reset };
77
+ }
78
+ export default useAction;
79
+ //# sourceMappingURL=useAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAction.js","sourceRoot":"","sources":["../../src/js/useAction.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AA+BtF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,SAAS,CAAsB,MAAS,EAAE,OAAO,GAAwB,EAAE;IAGzF,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,GAAG,aAAa,EAAE,CAAC;IACrD,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAS,EAAE,CAAC,CAAC;IACjD,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAuC,IAAI,CAAC,CAAC;IAEnF,0EAA0E;IAC1E,2EAA2E;IAC3E,6DAA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AC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,gBAAgB,EAAE,IAAI,CAAC,CAAC;QAC9F,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,IAAiB,CAAC,CAAC;QAC9C,CAAC;QAED,OAAO,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,CAAC;QAE1B,OAAO,IAAI,CAAC;IACd,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,YAAY,GAAG,WAAW,CAC9B,CAAC,GAAG,IAAmB,EAAmB,EAAE,CAC1C,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QACtB,eAAe,CAAC,KAAK,IAAI,EAAE;YACzB,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,EACJ,CAAC,GAAG,CAAC,CACN,CAAC;IAEF,MAAM,OAAO,GAAG,WAAW,CACzB,CAAC,GAAG,IAAmB,EAAQ,EAAE;QAC/B,KAAK,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7B,CAAC,EACD,CAAC,YAAY,CAAC,CACf,CAAC;IAEF,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,SAAS,CAAC,EAAE,CAAC,CAAC;QACd,UAAU,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,MAAM,GAAoB,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC;IAE9E,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AACrE,CAAC;AAED,eAAe,SAAS,CAAC","sourcesContent":["\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState, useTransition } from \"react\";\nimport type { ActionResult } from \"../action.js\";\n\n// Any built action: createActionClient's handler(), with or without a schema.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyAction = (...args: any[]) => Promise<ActionResult<any>>;\n\ntype DataOf<A extends AnyAction> = Awaited<ReturnType<A>> extends ActionResult<infer D> ? D : never;\n\nexport type UseActionStatus = \"idle\" | \"executing\" | \"hasSucceeded\" | \"hasErrored\";\n\nexport interface UseActionOptions<A extends AnyAction> {\n /**\n * Called inside the action's transition, before the action runs, with what\n * it was called with - where React's `useOptimistic` setter goes. React\n * puts the optimistic state back when the transition ends, so a failed\n * action takes its change back on its own.\n */\n optimistic?: (...args: Parameters<A>) => void;\n /** The action answered with data: no serverError, no validationErrors. */\n onSuccess?: (data: DataOf<A>) => void;\n /**\n * The action refused or failed. With a serverError, that message; with\n * validationErrors, the first one - so a button with no field beside it\n * still has something to show.\n */\n onError?: (message: string, result: ActionResult<DataOf<A>>) => void;\n /** After either, for state that tracks the call rather than its outcome. */\n onSettled?: (result: ActionResult<DataOf<A>>) => void;\n}\n\n/**\n * Call an action from a button rather than a form.\n *\n * const { execute, isPending } = useAction(archivePost, {\n * optimistic: (input) => hide(input.id),\n * onError: (message) => toast.error(message),\n * })\n *\n * <button disabled={isPending} onClick={() => execute({ id })}>Archive</button>\n *\n * The action's own types carry through: `execute` takes what the action's\n * schema takes, and `onSuccess` is handed what its handler returns. A form does\n * not need this - <Form> reads the same result on its own.\n *\n * Neither `execute` nor `executeAsync` throws. An action built on the action\n * client returns its failures, and anything thrown on the way - the network,\n * a server that answered with a page - becomes a serverError: left thrown,\n * the transition never settled and an optimistic change stayed on screen as\n * though the write had worked.\n *\n * An action that redirected settles nothing: no callback runs and no state is\n * set, because the page is on its way somewhere else.\n */\nexport function useAction<A extends AnyAction>(action: A, options: UseActionOptions<A> = {}) {\n type Result = ActionResult<DataOf<A>>;\n\n const [isPending, startTransition] = useTransition();\n const [result, setResult] = useState<Result>({});\n const [settled, setSettled] = useState<\"hasSucceeded\" | \"hasErrored\" | null>(null);\n\n // Read when the action runs, not when execute was made: execute keeps one\n // identity across renders, so an onClick built on it is not rebuilt, and a\n // callback closing over newer state is still the one called.\n const latest = useRef({ action, options });\n\n useLayoutEffect(() => {\n latest.current = { action, options };\n });\n\n const run = useCallback(async (args: Parameters<A>): Promise<Result> => {\n const { action, options } = latest.current;\n\n options.optimistic?.(...args);\n\n let next: Result;\n\n try {\n next = (await action(...args)) as Result;\n } catch (error) {\n next = { serverError: error instanceof Error ? error.message : String(error) };\n }\n\n if (next.redirected !== undefined) return next;\n\n setResult(next);\n setSettled(next.serverError !== undefined || next.validationErrors ? \"hasErrored\" : \"hasSucceeded\");\n\n if (next.serverError !== undefined) {\n options.onError?.(next.serverError, next);\n } else if (next.validationErrors) {\n options.onError?.(Object.values(next.validationErrors).flat()[0] ?? \"Invalid input.\", next);\n } else {\n options.onSuccess?.(next.data as DataOf<A>);\n }\n\n options.onSettled?.(next);\n\n return next;\n }, []);\n\n const executeAsync = useCallback(\n (...args: Parameters<A>): Promise<Result> =>\n new Promise((resolve) => {\n startTransition(async () => {\n resolve(await run(args));\n });\n }),\n [run],\n );\n\n const execute = useCallback(\n (...args: Parameters<A>): void => {\n void executeAsync(...args);\n },\n [executeAsync],\n );\n\n const reset = useCallback(() => {\n setResult({});\n setSettled(null);\n }, []);\n\n const status: UseActionStatus = isPending ? \"executing\" : (settled ?? \"idle\");\n\n return { execute, executeAsync, isPending, status, result, reset };\n}\n\nexport default useAction;\n"]}
@@ -0,0 +1,53 @@
1
+ import type { HostCallReply } from './hostCalls.js';
2
+ declare const REPLY: unique symbol;
3
+ /** The name the engine asks a host's route guards under. */
4
+ export declare const HOST_MIDDLEWARE = "__rsc.middleware";
5
+ /** What a test handler is given: the call's arguments, and the headers the renderer forwarded. */
6
+ export interface HostCallInput {
7
+ args: unknown[];
8
+ /** The visitor's request headers the renderer passed on - the cookie, the Accept-Language. */
9
+ headers: Headers;
10
+ }
11
+ /** Answers one function. Return a value for its result, or one of `hostReply`'s answers. */
12
+ export type HostHandler = (call: HostCallInput) => unknown;
13
+ /**
14
+ * The backend's functions, by the name rpc() calls them with.
15
+ *
16
+ * Route guards declared for the host are asked as `__rsc.middleware`
17
+ * (`HOST_MIDDLEWARE`), with the guard names as the first argument; answer
18
+ * `true` to let the page render. Anything else refuses, as a real host's
19
+ * answer would.
20
+ */
21
+ export type TestHost = Record<string, HostHandler>;
22
+ type Reply = Omit<HostCallReply, 'result'> & {
23
+ [REPLY]: true;
24
+ };
25
+ /**
26
+ * The protocol's own answers, for a handler to return.
27
+ *
28
+ * host: {
29
+ * 'Apps.list': ({ headers }) =>
30
+ * headers.get('cookie')?.includes('session=') ? [{ id: 1 }] : hostReply.unauthenticated(),
31
+ * 'Apps.create': ({ args }) => hostReply.invalid({ name: ['Taken.'] }),
32
+ * }
33
+ */
34
+ export declare const hostReply: {
35
+ /** No session: the page answers 401, an action its auth error. */
36
+ readonly unauthenticated: (message?: string) => Reply;
37
+ /** A session that still may not: 403. */
38
+ readonly unauthorized: (message?: string) => Reply;
39
+ /** Send the visitor somewhere else, as the host's redirect does. */
40
+ readonly redirect: (to: string, status?: number) => Reply;
41
+ /** Refuse with a status - a 404 for a record this caller cannot see, a 429. */
42
+ readonly refuse: (status: number, message?: string) => Reply;
43
+ /** The input was refused, by field: an action returns these as validationErrors. */
44
+ readonly invalid: (errors: Record<string, string[]>) => Reply;
45
+ /** A result, and the regions of the page the call says it changed. */
46
+ readonly revalidating: (result: unknown, ...targets: string[]) => Reply;
47
+ };
48
+ /**
49
+ * A fetch that answers the host-call endpoint from `host`: one call as
50
+ * itself, a batch as `{ replies }`, in order.
51
+ */
52
+ export declare function testHostFetch(host: TestHost): typeof fetch;
53
+ export {};
@@ -0,0 +1,76 @@
1
+ // A backend for tests: answers rpc() calls and host middleware the way a Go
2
+ // or Laravel host answers them over HTTP, without one running.
3
+ //
4
+ // The app under test talks to it through the real client, httpHostCalls,
5
+ // handed a fetch that answers in-process. So a test exercises what ships -
6
+ // batching, a redirect raised as the engine's own, an unauthenticated reply
7
+ // becoming a 401 - and only the backend is stood in for.
8
+ const REPLY = Symbol.for('rsc-kit.test-host-reply');
9
+ /** The name the engine asks a host's route guards under. */
10
+ export const HOST_MIDDLEWARE = '__rsc.middleware';
11
+ const reply = (fields) => ({ ...fields, [REPLY]: true });
12
+ /**
13
+ * The protocol's own answers, for a handler to return.
14
+ *
15
+ * host: {
16
+ * 'Apps.list': ({ headers }) =>
17
+ * headers.get('cookie')?.includes('session=') ? [{ id: 1 }] : hostReply.unauthenticated(),
18
+ * 'Apps.create': ({ args }) => hostReply.invalid({ name: ['Taken.'] }),
19
+ * }
20
+ */
21
+ export const hostReply = {
22
+ /** No session: the page answers 401, an action its auth error. */
23
+ unauthenticated: (message) => reply({ unauthenticated: true, error: message }),
24
+ /** A session that still may not: 403. */
25
+ unauthorized: (message) => reply({ unauthorized: true, error: message }),
26
+ /** Send the visitor somewhere else, as the host's redirect does. */
27
+ redirect: (to, status = 307) => reply({ redirect: to, redirectStatus: status }),
28
+ /** Refuse with a status - a 404 for a record this caller cannot see, a 429. */
29
+ refuse: (status, message = 'Refused.') => reply({ error: message, refusalStatus: status }),
30
+ /** The input was refused, by field: an action returns these as validationErrors. */
31
+ invalid: (errors) => reply({ validationErrors: errors }),
32
+ /** A result, and the regions of the page the call says it changed. */
33
+ revalidating: (result, ...targets) => reply({ result, revalidate: targets }),
34
+ };
35
+ function isReply(value) {
36
+ return typeof value === 'object' && value !== null && value[REPLY] === true;
37
+ }
38
+ async function answer(host, name, args, headers) {
39
+ const handler = host[name];
40
+ // Fails the call rather than answering null: a function the test forgot
41
+ // is a test that would otherwise pass against nothing.
42
+ if (!handler) {
43
+ return {
44
+ error: name === HOST_MIDDLEWARE
45
+ ? `the page asked its host guards (${JSON.stringify(args[0])}) and the test host has no "${HOST_MIDDLEWARE}" handler`
46
+ : `the test host has no handler for ${JSON.stringify(name)}`,
47
+ };
48
+ }
49
+ const value = await handler({ args, headers });
50
+ if (isReply(value)) {
51
+ const { [REPLY]: _, ...fields } = value;
52
+ return fields;
53
+ }
54
+ return { result: value === undefined ? null : value };
55
+ }
56
+ /**
57
+ * A fetch that answers the host-call endpoint from `host`: one call as
58
+ * itself, a batch as `{ replies }`, in order.
59
+ */
60
+ export function testHostFetch(host) {
61
+ return (async (_input, init) => {
62
+ const headers = new Headers(init?.headers);
63
+ const body = JSON.parse(String(init?.body ?? '{}'));
64
+ // The renderer's own headers are not the visitor's.
65
+ headers.delete('x-rsc-host-secret');
66
+ headers.delete('content-type');
67
+ const json = (value) => new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } });
68
+ if ('calls' in body) {
69
+ return json({
70
+ replies: await Promise.all(body.calls.map((c) => answer(host, c.function, c.args ?? [], headers))),
71
+ });
72
+ }
73
+ return json(await answer(host, body.function, body.args ?? [], headers));
74
+ });
75
+ }
76
+ //# sourceMappingURL=testHost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testHost.js","sourceRoot":"","sources":["../src/testHost.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+DAA+D;AAC/D,EAAE;AACF,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,yDAAyD;AAIzD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAA;AAEnD,4DAA4D;AAC5D,MAAM,CAAC,MAAM,eAAe,GAAG,kBAAkB,CAAA;AAwBjD,MAAM,KAAK,GAAG,CAAC,MAAiC,EAAS,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAA;AAE1F;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,kEAAkE;IAClE,eAAe,EAAE,CAAC,OAAgB,EAAS,EAAE,CAAC,KAAK,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC9F,yCAAyC;IACzC,YAA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I,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;aACnG,CAAC,CAAA;QACJ,CAAC;QAED,OAAO,IAAI,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAA;IAC1E,CAAC,CAAiB,CAAA;AACpB,CAAC","sourcesContent":["// A backend for tests: answers rpc() calls and host middleware the way a Go\n// or Laravel host answers them over HTTP, without one running.\n//\n// The app under test talks to it through the real client, httpHostCalls,\n// handed a fetch that answers in-process. So a test exercises what ships -\n// batching, a redirect raised as the engine's own, an unauthenticated reply\n// becoming a 401 - and only the backend is stood in for.\n\nimport type { HostCallReply } from './hostCalls.js'\n\nconst REPLY = Symbol.for('rsc-kit.test-host-reply')\n\n/** The name the engine asks a host's route guards under. */\nexport const HOST_MIDDLEWARE = '__rsc.middleware'\n\n/** What a test handler is given: the call's arguments, and the headers the renderer forwarded. */\nexport interface HostCallInput {\n args: unknown[]\n /** The visitor's request headers the renderer passed on - the cookie, the Accept-Language. */\n headers: Headers\n}\n\n/** Answers one function. Return a value for its result, or one of `hostReply`'s answers. */\nexport type HostHandler = (call: HostCallInput) => unknown\n\n/**\n * The backend's functions, by the name rpc() calls them with.\n *\n * Route guards declared for the host are asked as `__rsc.middleware`\n * (`HOST_MIDDLEWARE`), with the guard names as the first argument; answer\n * `true` to let the page render. Anything else refuses, as a real host's\n * answer would.\n */\nexport type TestHost = Record<string, HostHandler>\n\ntype Reply = Omit<HostCallReply, 'result'> & { [REPLY]: true }\n\nconst reply = (fields: Omit<Reply, typeof REPLY>): Reply => ({ ...fields, [REPLY]: true })\n\n/**\n * The protocol's own answers, for a handler to return.\n *\n * host: {\n * 'Apps.list': ({ headers }) =>\n * headers.get('cookie')?.includes('session=') ? [{ id: 1 }] : hostReply.unauthenticated(),\n * 'Apps.create': ({ args }) => hostReply.invalid({ name: ['Taken.'] }),\n * }\n */\nexport const hostReply = {\n /** No session: the page answers 401, an action its auth error. */\n unauthenticated: (message?: string): Reply => reply({ unauthenticated: true, error: message }),\n /** A session that still may not: 403. */\n unauthorized: (message?: string): Reply => reply({ unauthorized: true, error: message }),\n /** Send the visitor somewhere else, as the host's redirect does. */\n redirect: (to: string, status = 307): Reply => reply({ redirect: to, redirectStatus: status }),\n /** Refuse with a status - a 404 for a record this caller cannot see, a 429. */\n refuse: (status: number, message = 'Refused.'): Reply => reply({ error: message, refusalStatus: status }),\n /** The input was refused, by field: an action returns these as validationErrors. */\n invalid: (errors: Record<string, string[]>): Reply => reply({ validationErrors: errors }),\n /** A result, and the regions of the page the call says it changed. */\n revalidating: (result: unknown, ...targets: string[]): Reply =>\n reply({ result, revalidate: targets } as Omit<Reply, typeof REPLY>),\n} as const\n\nfunction isReply(value: unknown): value is Reply {\n return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[REPLY] === true\n}\n\nasync function answer(host: TestHost, name: string, args: unknown[], headers: Headers): Promise<HostCallReply> {\n const handler = host[name]\n\n // Fails the call rather than answering null: a function the test forgot\n // is a test that would otherwise pass against nothing.\n if (!handler) {\n return {\n error:\n name === HOST_MIDDLEWARE\n ? `the page asked its host guards (${JSON.stringify(args[0])}) and the test host has no \"${HOST_MIDDLEWARE}\" handler`\n : `the test host has no handler for ${JSON.stringify(name)}`,\n }\n }\n\n const value = await handler({ args, headers })\n\n if (isReply(value)) {\n const { [REPLY]: _, ...fields } = value\n\n return fields\n }\n\n return { result: value === undefined ? null : value }\n}\n\n/**\n * A fetch that answers the host-call endpoint from `host`: one call as\n * itself, a batch as `{ replies }`, in order.\n */\nexport function testHostFetch(host: TestHost): typeof fetch {\n return (async (_input: RequestInfo | URL, init?: RequestInit) => {\n const headers = new Headers(init?.headers)\n const body = JSON.parse(String(init?.body ?? '{}')) as\n | { function: string; args?: unknown[] }\n | { calls: { function: string; args?: unknown[] }[] }\n\n // The renderer's own headers are not the visitor's.\n headers.delete('x-rsc-host-secret')\n headers.delete('content-type')\n\n const json = (value: unknown) =>\n new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } })\n\n if ('calls' in body) {\n return json({\n replies: await Promise.all(body.calls.map((c) => answer(host, c.function, c.args ?? [], headers))),\n })\n }\n\n return json(await answer(host, body.function, body.args ?? [], headers))\n }) as typeof fetch\n}\n"]}
package/dist/testing.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type TestHost } from './testHost.js';
2
+ export { hostReply, HOST_MIDDLEWARE, type HostCallInput, type HostHandler, type TestHost } from './testHost.js';
1
3
  export interface TestApp {
2
4
  /** A path, not a url. The origin is whatever the app was told it is. */
3
5
  fetch(path: string, init?: RequestInit): Promise<Response>;
@@ -18,6 +20,12 @@ export interface TestAppOptions {
18
20
  build?: boolean;
19
21
  /** The origin requests are made against. Nothing reads it; it is a url. */
20
22
  origin?: string;
23
+ /**
24
+ * The backend, answered in the test: rpc() calls and host guards by name.
25
+ * The app reaches it through the same client it uses against a real one,
26
+ * so nothing listens and RSC_BACKEND is not called. See `hostReply`.
27
+ */
28
+ host?: TestHost;
21
29
  }
22
30
  /**
23
31
  * A file the build put in .output/public, answered the way Nitro's static
package/dist/testing.js CHANGED
@@ -19,6 +19,9 @@ import { spawnSync } from 'node:child_process';
19
19
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
20
20
  import { extname, join, resolve, sep } from 'node:path';
21
21
  import { pathToFileURL } from 'node:url';
22
+ import { httpHostCalls } from './hostCalls.js';
23
+ import { testHostFetch } from './testHost.js';
24
+ export { hostReply, HOST_MIDDLEWARE } from './testHost.js';
22
25
  /**
23
26
  * Where the build put the server bundle.
24
27
  *
@@ -169,10 +172,20 @@ export async function createTestApp(options = {}) {
169
172
  if (typeof entry.default !== 'function') {
170
173
  throw new Error(`[rsc-kit] ${bundle} does not export a request handler.`);
171
174
  }
175
+ const host = options.host
176
+ ? httpHostCalls({ endpoint: 'http://test-host/__rsc/host-call', secret: 'test', fetch: testHostFetch(options.host) })
177
+ : null;
178
+ if (host && !entry.installHostFn) {
179
+ throw new Error(`[rsc-kit] ${bundle} cannot take a host. Rebuild against the current @rsc-kit/core.`);
180
+ }
172
181
  return {
173
182
  bundle,
174
183
  fetch: async (path, init) => {
175
184
  const request = new Request(new URL(path, origin), init);
185
+ // Per request, not once: the loaded bundle is shared by every app a
186
+ // run creates, and the host is this app's.
187
+ if (host)
188
+ entry.installHostFn(host);
176
189
  return staticFile(root, request) ?? entry.default(request);
177
190
  },
178
191
  };