@rsc-kit/core 0.20.3 → 0.20.5

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.
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,+EAA+E;AAC/E,2DAA2D;AAC3D,EAAE;AACF,4CAA4C;AAC5C,oFAAoF;AACpF,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,4EAA4E;AAC5E,yEAAyE;AAEzE,OAAO,EACL,YAAY,EACZ,UAAU,EACV,SAAS,EACT,WAAW,EACX,YAAY,EACZ,MAAM,EACN,QAAQ,EACR,aAAa,EACb,gBAAgB,GACjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,GAAG,EAAE,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/E,OAAO,EACL,UAAU,EACV,YAAY,EACZ,SAAS,EACT,QAAQ,EACR,MAAM,GACP,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E;YACxE,2DAA2D;YAC3D,EAAE;YACF,wEAAwE;YACxE,mCAAmC;YACnC,YAAY,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,YAAY;YACzC,GAAG,mBAAmB,EAAE;SACzB,CAAC;QACF,mBAAmB,EAAE;QACrB,aAAa,EAAE;QACf,mBAAmB,EAAE;QACrB,oBAAoB,EAAE;QACtB,aAAa,EAAE;QACf,0BAA0B,EAAE;QAC5B,eAAe,EAAE;QACjB,kBAAkB,EAAE;QACpB,YAAY;KACb,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAS,mBAAmB;IAC1B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,yBAAyB;QAAE,OAAO,EAAE,CAAC;IAEtD,4EAA4E;IAC5E,yEAAyE;IACzE,yEAAyE;IACzE,WAAW;IACX,OAAO,EAAE,mBAAmB,EAAE,uCAAuC,EAAE,CAAC;AAC1E,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAO,GAA8B,EAAE;IAEvC,IAAI,CAAC;QACH,qEAAqE;QACrE,mCAAmC;QACnC,MAAM,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;QACjE,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC;QACpD,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAEnD,CAAC;QAEF,OAAO,CAAC,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAAC,MAAM,CAAC;QACP,yEAAyE;QACzE,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// File-based routing for React Server Components, as a Vite plugin.\n//\n// Host-agnostic by design: it discovers an app/ route tree, generates the three\n// entries, and exposes a render contract over a global the host installs. What\n// that global is called, and how a route declares dynamic props, are options —\n// nothing here knows or cares which backend is driving it.\n//\n// import { rscKit } from '<package>/vite'\n// export default defineConfig({ plugins: [rscKit(), react({ compiler: true })] })\n//\n// The plugin discovers the app/ route tree, generates the three entries that\n// carry the route composition and the worker's render contract, and supplies\n// the structural config (entries, output dirs, base). @vitejs/plugin-rsc is\n// included here so it always runs before any react() layer the app adds.\n\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n createReadStream,\n} from \"node:fs\";\nimport { gzipSync } from \"node:zlib\";\nimport { createHash } from \"node:crypto\";\nimport { createRequire } from \"node:module\";\nimport { spawnSync } from \"node:child_process\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport rsc, { getPluginApi } from \"@vitejs/plugin-rsc\";\nimport { loadEnv } from \"vite\";\nimport type { PrerenderResult } from \"./prerender.js\";\nimport { REPORT_FILE, buildReport } from \"./buildReport.js\";\nimport { MANIFEST_PATH, manifestWarning, webManifest } from \"./webManifest.js\";\nimport {\n ASSET_BASE,\n allAppAssets,\n appAssets,\n headTags,\n typeOf,\n} from \"./appAssets.js\";\nimport { reactCacheImports } from \"./reactCache.js\";\nimport {\n clientEntries,\n clientScanPlugin,\n engineClientEntries,\n} from \"./clientEntries.js\";\nimport { serverImportsOfClientPackages } from \"./clientImports.js\";\nimport {\n automaticSitemap,\n METADATA_ROUTES,\n ROOT_FILES,\n rootFileType,\n} from \"./metadataRoutes.js\";\nimport { ownHosts } from \"./hostRouting.js\";\nimport { unrollBarrelImports } from \"./barrelImports.js\";\nimport type { MetadataRouteKind } from \"./metadataRoutes.js\";\nimport { serverRendererMessage, SERVER_RENDERER, ssrProxyModule, UseSsrError, withoutSsrDirective } from \"./useSsr.js\";\nimport type { ClientLibraryImport } from \"./clientImports.js\";\nimport type { AppAssets } from \"./appAssets.js\";\nimport type { WebManifestOptions } from \"./webManifest.js\";\nimport type { Plugin, PluginOption, ResolvedConfig } from \"vite\";\nimport { httpHostCalls } from \"./hostCalls.js\";\nimport { bytecodeNote } from \"./bytecodeCheck.js\";\nimport { clientPackages, importsServerRenderer, packageDir as installedPackageDir, packageEntryInGraph, polyfillsToTrace, traceableByName } from \"./clientPackages.js\";\nimport type {\n ManifestIntercept,\n ManifestRoute,\n RouteManifest,\n RouteSegment,\n} from \"./manifest.js\";\n\nexport interface RscKitOptions {\n /** Project root. Defaults to RSC_PROJECT_ROOT, then cwd. */\n projectRoot?: string;\n /** Directory holding the app/ route tree. Defaults to `src`. */\n sourceDir?: string;\n /**\n * Say what built the site: `<meta name=\"generator\" content=\"rsc-kit\">` in\n * every document and `X-Powered-By: rsc-kit` on every response. The name\n * only, never the version - a version in every response is what a\n * vulnerability scanner filters on. On by default; `false` for a team\n * whose policy strips every framework identifier.\n *\n * `X-RSC-Kit: stored | rendered | shell` - how a response was answered, the\n * header a developer reads in the Network tab - is not this and is always\n * sent: it names no product, and a CDN rule or a check can key on it.\n */\n identify?: boolean;\n /**\n * An OpenAPI document from the route tree, at `/openapi.json`.\n *\n * One path per route.ts, one operation per method export, parameters and\n * request bodies from the route's `params`, `searchParams` and `body`\n * schemas - a Standard Schema that describes itself as JSON Schema (Zod 4,\n * ArkType). A route under a middleware.ts gets a security requirement. A\n * route says the rest about itself with `export const openapi = { summary,\n * tags, responses }`; the document says its own with `info`, `servers`,\n * `security`. An api route the build stores, without middleware.\n *\n * The page that reads it is Scalar's: `export const GET = ApiReference({\n * url: '/openapi.json' })` from @scalar/nextjs-api-reference in a route.ts.\n */\n openapi?:\n | boolean\n | {\n path?: string;\n info?: { title?: string; version?: string; description?: string };\n servers?: { url: string; description?: string }[];\n security?: Record<string, string[]>[];\n components?: Record<string, unknown>;\n tags?: { name: string; description?: string }[];\n };\n /**\n * Unroll named imports from a barrel package on the server, in development.\n *\n * `import { ArrowRight } from 'lucide-react'` reaches a file that re-exports\n * fifteen hundred icons, one module each; the browser gets the package\n * pre-bundled, the server environments do not, so Vite loaded every icon\n * module on the first request. The import is rewritten to the module that\n * owns the name, read from the barrel itself. On by default; `false` to\n * leave imports as written.\n */\n barrelImports?: boolean;\n /**\n * The site's own hosts, beyond the one in the root layout's metadataBase.\n *\n * A request from any other host is routed with the host in front of the\n * path: `admin.example.com/users` reaches `app/admin/users/page.tsx`, the\n * file `example.com/admin/users` reaches by path; `acme.example.com/`\n * reaches `app/[domain]/page.tsx` with `domain: \"acme\"`, and a custom\n * domain `acme.com/` the same file with `domain: \"acme.com\"`. The site's\n * own hosts keep path routing, so an app adds tenants without moving a\n * file. `www.` of each is its own too. With no metadataBase and nothing\n * here, every host is the site's own and nothing is prepended.\n */\n hosts?: string[];\n /**\n * Serve the app from a service worker, so it survives a reload with no\n * network at all.\n *\n * Everything else this engine keeps — held pages, the prefetch cache — lives\n * in one page's memory. Reload with no network and the browser shows its own\n * error page: no script runs, so nothing cached in JavaScript is reachable.\n * A worker is the only thing on the other side of that line.\n *\n * Off by default. It changes what a visitor sees when your deploy is broken,\n * which is not a decision to make for someone.\n */\n offline?: boolean;\n /**\n * Whether a page stored without the runtime gets its stylesheet inlined\n * into the document, so the first paint waits on no request but the\n * document itself.\n *\n * 'auto' inline when the sheet is at most 10 kB gzipped (the default)\n * false never - keep the link, and let the browser cache one file\n * across every page; the choice for a site of many small pages\n * true always, whatever the size\n * number your own cap, in gzipped bytes\n *\n * Only for a page with no runtime. One with React on it keeps its link\n * regardless, because React expects to find it in the DOM to hydrate.\n */\n inlineStylesheets?: \"auto\" | boolean | number;\n /**\n * Run the project's own typecheck as part of `vite build`, and fail the\n * build on an error. On by default when the project has a `tsconfig.json`\n * and `typescript` installed; `false` turns it off.\n *\n * A build that bundles a `<Link href=\"/nowhere\">` and stores every page\n * has produced a broken site that looks finished. The route types exist so\n * that link is an error - but Vite never typechecks, so the error only\n * showed for whoever ran `tsc` separately. `next build` typechecks for the\n * same reason.\n */\n typecheck?: boolean;\n /**\n * The most a server action body may be, in bytes. 8 MB unless set.\n *\n * Arguments and uploaded files arrive in one body, read whole before the\n * action runs; over this the answer is 413 before a byte is kept. Raise it\n * for an app that uploads larger files through actions.\n */\n maxActionBody?: number;\n /** Where the server bundles and generated entries go. Defaults to `.rsc`. */\n outDir?: string;\n /**\n * A file the dev server writes its own url into, and removes on shutdown.\n *\n * Laravel's convention, and the reason it is worth adopting: a dev server\n * picks its port at runtime — 5173 is the most contended port on a developer's\n * machine, and Vite silently moves to the next free one — so anything holding\n * a fixed url is wrong the moment a second project is running. A backend that\n * reads this file follows the server instead of guessing at it.\n */\n hotFile?: string;\n /**\n * Packages the server bundles import at runtime rather than inline.\n *\n * For a dependency with a native binary, one that spawns a process, or one\n * that reads files beside itself - anything a bundle breaks. A default list\n * covers the usual ones (sharp, bcrypt, better-sqlite3, prisma, puppeteer,\n * ...); this adds to it. Nitro traces an external package into\n * .output/server/node_modules with its binaries, so the deployment is still\n * one directory.\n */\n serverExternalPackages?: string[];\n /**\n * Where `rpc()` goes while `vite dev` is serving.\n *\n * A built deployment installs this itself — the server that runs\n * createRscHandler passes `hostCalls`. The dev server has no such server in\n * front of it, so without this every rpc() during development is refused and\n * any page whose data comes from the backend renders blank.\n *\n * Both halves default to the app's own .env, which for a Laravel app already\n * has them: APP_URL for the backend and RSC_HOST_CALL_SECRET for the secret.\n * That is the difference between \"configure the dev server\" and \"it works\".\n */\n hostCall?: { endpoint?: string; secret?: string; path?: string };\n\n /**\n * Where the dev server hands a url it does not own.\n *\n * The route tree is only part of an application: /login, a Blade page, a\n * webhook and an uploaded file under /storage all belong to the backend. So\n * in development this origin is the whole app rather than the RSC half of\n * it, and a browser can sit on it instead of on a proxy in front of it.\n *\n * Defaults to the same place host calls go — RSC_BACKEND, then APP_URL —\n * because a second setting that could disagree with the first is a bug\n * waiting to be filed. `false` restores the plain 404.\n *\n * The built server forwards too — the entry that carries this is the one\n * Nitro bundles — with the origin read at build time from the project's\n * .env, while host calls read it from the process at runtime. A build on a\n * machine whose .env names a different backend than production's sets\n * RSC_BACKEND for the build. The name predates that: it was the dev server's\n * alone before Nitro built the server from the same entry.\n */\n devFallback?: string | false;\n\n /**\n * This package's directory, holding the client runtime the browser entry\n * imports. Vite stages configs through node_modules/.vite-temp, so\n * import.meta.dir is not this file's real location by the time the plugin\n * runs — a host invoking the build out of process passes the real path\n * through RSC_PACKAGE_DIR.\n */\n packageDir?: string;\n /**\n * Name of the global the host installs for calling its own functions from a\n * server component — `await rpc('getUser', id)`. The mechanism is\n * host-agnostic; only the name is a convention, so a host that prefers\n * something else can say so.\n */\n hostGlobal?: string;\n /**\n * JSON file of `{urlPattern, slot}` entries naming the routes the client\n * router should intercept rather than navigate to. Written by the host,\n * which owns route discovery.\n */\n interceptManifestFile?: string;\n /**\n * Bare-specifier prefix for importing the client runtime, as in\n * `import Link from '<prefix>/Link'`, aliased to this package's js/\n * directory.\n *\n * Only needed when this package is not resolvable from the project's\n * node_modules — a host that vendors it through its own package manager,\n * say. Installed from npm, the package name resolves on its own and no\n * alias is required.\n */\n packageAlias?: string;\n /**\n * Origin the Vite dev server is reachable at, e.g. `http://localhost:5173`.\n *\n * Set only when running under the dev server. @vitejs/plugin-rsc emits its\n * bootstrap and CSS links root-relative in dev and no Vite setting moves\n * them, so with the host serving the page the browser would ask the host for\n * modules only Vite can answer. Given this, the SSR entry rewrites them onto\n * the dev origin — see devUrls.ts. Empty in a build, where the URLs are real\n * built assets.\n */\n devOrigin?: string;\n /**\n * What the build produces.\n *\n * 'server' the default: pages are served by a host, and a payload is\n * asked for with a header on the page's own url.\n * 'export' files any static host can serve. Payloads get addresses of\n * their own, because a host serving files cannot act on a\n * header, and the client is built to ask for those instead.\n */\n output?: \"server\" | \"export\";\n /** Where an exported site is written, relative to the project root. */\n exportPath?: string;\n /**\n * Filename payloads are served under on a static host, e.g. `index.rsc`.\n *\n * Only for an exported build. Normally the payload shares the page's url and\n * is asked for with a header; a host that serves files cannot answer that,\n * so the payload needs an address of its own.\n */\n staticPayloads?: string;\n /**\n * How to tell that a route's props are resolved dynamically by the host, so\n * the page cannot be prerendered whole.\n *\n * Entirely host-defined: a host that writes a config file beside the page\n * names that file and the pattern that marks it dynamic. Omitted, no page is\n * classified dynamic on this basis.\n */\n routeConfig?: { file: string; dynamicPattern: RegExp };\n /**\n * Functions the host exposes to the app, as `{ exportedName: target }`.\n *\n * The build writes a \"use server\" module of stubs for these, each one\n * calling the host global with its target — so app code imports an ordinary\n * async function and never names the transport. Discovery belongs to the\n * host, whose functions these are; only the rendering is here, because the\n * module has to land beside the app's source and that path is the build's.\n *\n * A host whose functions are already JavaScript passes nothing.\n */\n hostActions?: Record<string, string>;\n}\n\n// Resolved once per rscKit() call. One build runs in one process, so these are\n// module state rather than threaded through every helper.\nlet projectRoot: string;\nlet sourceDir: string;\nlet inlineStylesheets: \"auto\" | boolean | number = \"auto\";\nlet resolvedConfig: ResolvedConfig | null = null;\n\n/** Server files importing a client library, read off the rsc graph when it is built. */\nlet clientLibraryImports: ClientLibraryImport[] = [];\n\n/** Modules a runtime provides and no bundle should try to carry. */\nconst RUNTIME_BUILTINS = [\"bun\", /^bun:/];\n\n/**\n * Packages the server bundles import rather than inline, by default.\n *\n * Each of these ships a native binary, spawns one, or reads files relative to\n * its own location - none of which survives being rolled into a bundle. Left\n * external, Nitro traces them into .output/server/node_modules with their\n * binaries, and the built server imports them the way the package expects.\n * Next keeps the same list under serverExternalPackages, for the same reason.\n * `rscKit({ serverExternalPackages })` adds to it.\n */\n/**\n * Side-effect polyfills a dependency checks for at module evaluation, which\n * the generated entry imports before anything else when the project has\n * them. Bundler chunking does not keep an external import's place.\n */\nconst FIRST_POLYFILLS = [\"reflect-metadata\"];\n\nconst DEFAULT_SERVER_EXTERNALS = [\n \"sharp\",\n \"canvas\",\n \"bcrypt\",\n \"argon2\",\n \"@node-rs/argon2\",\n \"@node-rs/bcrypt\",\n \"better-sqlite3\",\n \"sqlite3\",\n \"libsql\",\n \"@libsql/client\",\n \"@prisma/client\",\n \"prisma\",\n \"puppeteer\",\n \"puppeteer-core\",\n \"playwright\",\n \"playwright-core\",\n \"jsdom\",\n \"node-pty\",\n \"onnxruntime-node\",\n \"@sentry/profiling-node\",\n \"pdfkit\",\n \"mongodb\",\n \"oslo\",\n \"@resvg/resvg-js\",\n \"@napi-rs/canvas\",\n // Not native: a polyfill that must run before anything reads Reflect.getMetadata.\n // tsyringe, typeorm and inversify check for it at module evaluation, and a\n // bundler that splits them into their own chunk hoists that chunk's evaluation\n // above the polyfill's - so the check fails in a bundle that has the polyfill\n // in it. External, the import statement stays where the source put it, and\n // Node runs it first.\n \"reflect-metadata\",\n];\n\n/** A package name as a rollup external: the package and every subpath of it. */\nfunction externalPackage(name: string): RegExp {\n return new RegExp(\"^\" + name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") + \"(?:/|$)\");\n}\n\nfunction arrayOf<T>(value: T | T[] | null | undefined): T[] {\n return value == null ? [] : Array.isArray(value) ? value : [value];\n}\n\n/**\n * What a client chunk is called on disk.\n *\n * A \"use server\" module reaches the browser as a proxy - one stub per export\n * that calls the action by id - and the proxy keeps the file's identity, so\n * the bundler can name a chunk after it. When shared client code is merged\n * into that chunk the output has a file called `auth-actions-…js` in\n * public/assets: fifty kilobytes of UI components with the name of the\n * server file, which reads as a leak to anyone who looks. Nothing leaked -\n * the proxy holds ids, never bodies - but a name that says otherwise is a\n * bug. Such a chunk is called what it is.\n */\nfunction clientChunkFileName(chunk: {\n name: string;\n facadeModuleId: string | null;\n moduleIds: string[];\n}): string {\n const table = resolvedConfig\n ? getPluginApi(resolvedConfig)?.manager?.serverReferences?.metaMap\n : undefined;\n\n if (table && table.size > 0) {\n const bare = (id: string) => {\n const file = id.split(\"?\")[0]!.split(\"/\").pop() ?? \"\";\n\n return file.replace(/\\.[^.]+$/, \"\");\n };\n const serverModules = new Set([...table.keys()].map(bare));\n const namedAfterServerModule =\n (chunk.facadeModuleId !== null &&\n serverModules.has(bare(chunk.facadeModuleId))) ||\n (serverModules.has(chunk.name) &&\n chunk.moduleIds.some((id) => bare(id) === chunk.name));\n\n if (namedAfterServerModule) return \"assets/client-[hash].js\";\n }\n\n return \"assets/[name]-[hash].js\";\n}\nlet maxActionBody: number | undefined;\nlet outDir: string;\nlet appDir: string;\nlet genDir: string;\nlet publicAssetsDir: string;\n/** Where generated ambient declarations go — `.rsc-kit` at the project root. */\nlet typesDir: string;\nlet hotFile: string;\nlet hostCallOptions: RscKitOptions[\"hostCall\"];\nlet packageDir: string;\nlet hostGlobal: string;\nlet interceptManifestFile: string;\nlet packageAlias: string | null;\n/** Dev-server origin; empty in a build. See devUrls.ts. */\nlet devOrigin: string;\n/** 'server' or 'export' — see RscKitOptions.output. */\nlet output: string;\n/** Where an exported site is written. */\nlet exportPath: string;\n/**\n * Filename payloads are exported under, empty unless building for a static\n * host. Set, the client asks `<page>/<name>` for a payload instead of asking\n * for the page's own url with a header a static host cannot act on.\n */\nlet staticPayloads: string;\nlet routeConfig: { file: string; dynamicPattern: RegExp } | null;\n/** Whether `vite build` freezes pages when it finishes — see RscKitOptions. */\nlet prerenderAfterBuild: boolean;\n/** True during `vite build --watch`, where re-rendering every route is noise. */\nlet isWatch = false;\n/** Whether a service worker is generated and registered — see options. */\nlet offline = false;\nlet typecheck = true;\nlet webManifestOptions: WebManifestOptions | null = null;\n/** The site's own hosts, from the root layout's metadataBase and rscKit({ hosts }). */\nlet siteHosts: string[] = [];\nlet hostsOption: string[] = [];\nlet barrelImports = true;\nlet identify = true;\n/** Resolved from RscKitOptions.openapi; null when off. */\nlet openapi: { path: string; document: Record<string, unknown> } | null = null;\nlet foundAssets: AppAssets = {\n favicon: null,\n icons: [],\n appleIcon: null,\n openGraph: null,\n twitter: null,\n};\n/** Host functions to generate stubs for — see RscKitOptions.hostActions. */\nlet hostActions: Record<string, string>;\n\n/**\n * This file's directory.\n *\n * Not `import.meta.dir`, which is Bun-only: Vite bundles the config and runs it\n * under Node, where that is undefined and the path resolution below throws\n * before the build starts. Reached whenever RSC_PACKAGE_DIR is unset — which is\n * the ordinary case for an app that installs the engine from npm and runs\n * `vite build` itself.\n */\n/** This package's name, for excluding it from dep optimization. */\nconst PACKAGE_NAME: string = (() => {\n try {\n const manifest = JSON.parse(\n readFileSync(\n join(dirname(fileURLToPath(import.meta.url)), \"..\", \"package.json\"),\n \"utf-8\",\n ),\n ) as { name?: string };\n\n return manifest.name ?? \"@rsc-kit/core\";\n } catch {\n return \"@rsc-kit/core\";\n }\n})();\n\nfunction thisDir(): string {\n return dirname(fileURLToPath(import.meta.url));\n}\n\n/** routeConfig supplied through the environment, for out-of-process hosts. */\nfunction envRouteConfig(): { file: string; dynamicPattern: RegExp } | null {\n const file = process.env.RSC_ROUTE_CONFIG_FILE;\n const pattern = process.env.RSC_ROUTE_CONFIG_PATTERN;\n\n if (!file || !pattern) return null;\n\n return { file, dynamicPattern: new RegExp(pattern) };\n}\n\n/** The file a backend writes its action names into. */\nconst HOST_ACTIONS_FILE = \"rsc-host-actions.json\";\n\n/**\n * Host actions, read from a file the backend wrote.\n *\n * A file rather than an environment variable, because the backend no longer\n * drives the build — `vite build` does. Discovery has to stay where the classes\n * are (reflection through Composer's autoloader finds what a class inherits;\n * a regex would silently miss every inherited action), but the handoff is just\n * a map of names, and a JSON file is something any language can write:\n *\n * php artisan rsc:action-manifest > rsc-host-actions.json\n * go run ./cmd/rsc-actions > rsc-host-actions.json\n *\n * Absent is not an error. An app with no host actions has no file, and one\n * that has them regenerates it as part of its build.\n */\nfunction fileHostActions(root: string): Record<string, string> {\n const path = join(root, HOST_ACTIONS_FILE);\n\n if (!existsSync(path)) return {};\n\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n\n // An empty list is an empty map. PHP's json_encode writes an empty\n // array as [] whatever it was declared as, so a backend with no\n // actions yet wrote exactly that - and the first `dev` of a fresh\n // install refused to start over a file that said, correctly, \"none\".\n if (Array.isArray(parsed) && parsed.length === 0) return {};\n\n if (\n parsed === null ||\n typeof parsed !== \"object\" ||\n Array.isArray(parsed)\n ) {\n throw new Error('expected an object of { jsName: \"Class.method\" }');\n }\n\n return parsed as Record<string, string>;\n } catch (error) {\n // Loud, because the alternative is generating no stubs: every import of a\n // server action then fails at build time, naming the import rather than\n // this file.\n throw new Error(\n `Could not read ${HOST_ACTIONS_FILE}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/**\n * The alias that lets a vendored copy of this package be imported by name.\n *\n * Only when the package is not installed, because an alias is a path rewrite\n * and rewrites nothing through the package's own exports. With both in play\n * the specifier meant two different things: `<pkg>/Form` resolved to whatever\n * file happened to sit at js/Form, rather than to what ./Form is declared to\n * mean. Installed from npm, ordinary resolution reads the exports map and the\n * two cannot drift.\n */\nfunction aliasEntries(): Array<{ find: RegExp; replacement: string }> {\n const entries: Array<{ find: RegExp; replacement: string }> = [\n // A library written for Next reads the request through next/headers -\n // Vercel's flags SDK does, through `flags/next` - and headers() and\n // cookies() here have the same names and shapes, with one object per\n // request, which is what its per-request dedupe keys on. Answered by\n // this package, so such a library runs unchanged and without Next.\n { find: /^next\\/headers$/, replacement: join(packageDir, \"request\") },\n ];\n\n if (!packageAlias) return entries;\n\n if (existsSync(join(projectRoot, \"node_modules\", packageAlias))) return entries;\n\n entries.push({\n find: new RegExp(\n \"^\" + packageAlias.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") + \"/(.*)$\",\n ),\n replacement: join(packageDir, \"js\") + \"/$1\",\n });\n\n return entries;\n}\n\nfunction resolvePaths(options: RscKitOptions): void {\n projectRoot = resolve(\n options.projectRoot || process.env.RSC_PROJECT_ROOT || process.cwd(),\n );\n sourceDir = resolve(\n options.sourceDir || process.env.RSC_SOURCE_DIR || join(projectRoot, \"src\"),\n );\n outDir = resolve(\n options.outDir || process.env.RSC_OUT_DIR || join(projectRoot, \".rsc\"),\n );\n appDir = join(sourceDir, \"app\");\n\n // Generated entries live under the (in-project) out dir so module resolution\n // can walk up to the project's node_modules (@vitejs/plugin-rsc, react, ...).\n genDir = join(outDir, \".gen\");\n\n // Not a migration guard — those are not worth carrying in a pre-release.\n // This is the silent-failure guard the rest of this file is written to be.\n //\n // Nitro publishes the assets and serves them from its own root. A prefix set\n // here would be emitted into the markup and answered by nobody: every asset\n // 404s while every page still renders, so the app arrives unstyled, never\n // hydrates, and logs nothing anywhere. Vite does not typecheck a config, so\n // removing the option from the type is not enough to stop it.\n //\n // There is deliberately no check for `nitro`. It is gone from the type, and\n // a config still passing `nitro: true` is asking for exactly what it gets.\n const removed = [\"assetsDir\", \"assetsUrl\"].filter(\n (key) => (options as Record<string, unknown>)[key] !== undefined,\n );\n\n if (removed.length > 0) {\n throw new Error(\n `[rsc-kit] ${removed.join(\" and \")} ${removed.length === 1 ? \"is\" : \"are\"} no longer an option.\\n\\n` +\n \"Nitro publishes the browser assets to .output/public and serves them from its own\\n\" +\n \"root, so there is no prefix to set. That directory is the deployment — point nginx\\n\" +\n \"or a CDN at it if something other than the app should serve them.\",\n );\n }\n\n // Vite's own default. Nitro overrides it with .output/public, which is why\n // there is nothing here to configure.\n publicAssetsDir = resolve(join(projectRoot, \"dist/client\"));\n typesDir = join(projectRoot, \".rsc-kit\");\n hotFile = options.hotFile || process.env.RSC_HOT_FILE || \"\";\n hostCallOptions = options.hostCall;\n packageDir = resolve(\n options.packageDir || process.env.RSC_PACKAGE_DIR || thisDir(),\n );\n hostGlobal = options.hostGlobal || process.env.RSC_HOST_GLOBAL || \"rpc\";\n interceptManifestFile = resolve(\n options.interceptManifestFile ||\n process.env.RSC_INTERCEPT_MANIFEST ||\n join(outDir, \"intercept-manifest.json\"),\n );\n packageAlias = options.packageAlias || process.env.RSC_PACKAGE_ALIAS || null;\n devOrigin = options.devOrigin || process.env.RSC_DEV_ORIGIN || \"\";\n output = options.output || process.env.RSC_OUTPUT || \"server\";\n exportPath = options.exportPath || process.env.RSC_EXPORT_PATH || \"dist\";\n // An export decides this for itself: the client has to ask for payloads by\n // url because there is no server to read a header, and the name it asks for\n // is the one the export writes.\n staticPayloads =\n options.staticPayloads ||\n process.env.RSC_STATIC_PAYLOADS ||\n (output === \"export\" ? \"index.rsc\" : \"\");\n\n // No default: which file marks a route dynamic is the host's convention, and\n // guessing one here would bake a particular backend into a generic plugin.\n // The env pair exists so a host driving the build out of process can pass it\n // without writing a config file.\n routeConfig = options.routeConfig ?? envRouteConfig();\n // A host driving the build out of process cannot pass an option, and may\n // prerender itself afterwards with paths only it knows.\n // No public switch. A page that must not be frozen says so with\n // `await connection()`, and the build names every page that could not be\n // rendered - the same model Next has with cache components, where the\n // only opt-out is per page. RSC_PRERENDER=0 remains, internal: watch mode\n // sets it, and so does a host that drives the build out of process and\n // prerenders itself afterwards with paths only it knows.\n prerenderAfterBuild = process.env.RSC_PRERENDER !== \"0\";\n offline = options.offline === true;\n typecheck = options.typecheck !== false;\n hostsOption = options.hosts ?? [];\n barrelImports = options.barrelImports !== false;\n identify = options.identify !== false;\n openapi = options.openapi\n ? (() => {\n const { path, ...document } = typeof options.openapi === \"object\" ? options.openapi : {};\n\n return { path: path || \"/openapi.json\", document };\n })()\n : null;\n inlineStylesheets = options.inlineStylesheets ?? \"auto\";\n maxActionBody = options.maxActionBody;\n // One place, and it is the file. A plugin option as well would be the same\n // thing sayable in two places, which is the problem the file was moved to\n // solve rather than a convenience to keep beside it.\n webManifestOptions = declaredManifest(join(sourceDir, \"app\"));\n foundAssets = appAssets(join(sourceDir, \"app\"));\n\n // An app that put icons where they could be found has already listed them.\n // Writing them again in the manifest is the same set in two places, and the\n // one that goes stale is the one nobody looks at.\n if (\n webManifestOptions &&\n !webManifestOptions.icons?.length &&\n foundAssets.icons.length\n ) {\n webManifestOptions = {\n ...webManifestOptions,\n icons: foundAssets.icons.map((icon) => icon.href),\n };\n }\n hostActions = options.hostActions ?? fileHostActions(projectRoot);\n}\n\ninterface Component {\n name: string; // route-relative key, e.g. \"app/page\", \"app/layout\"\n absPath: string;\n alias: string; // safe JS identifier for the generated import\n}\n\nfunction log(...args: unknown[]): void {\n console.error(\"[rsc-kit]\", ...args);\n}\n\n// ── The route manifest ───────────────────────────────────────────────────────\n\n/**\n * What the plugin knows about the route tree, written out for a host to read.\n *\n * The plugin already walks app/ to generate the entries, and every host has to\n * know the same things — which url a component answers, what layouts wrap it,\n * which slots and sections belong to it. Laravel scans the tree a second time\n * to work that out; a JS host would have to write a third. This is the one\n * answer, emitted where both can read it.\n *\n * Urls are expressed as segments rather than as a pattern string, because the\n * pattern is the host's dialect: Laravel writes {slug}, Hono writes :slug, and\n * neither is the plugin's business.\n */\n\n/** `[...path]` → catchAll, `[id]` → param, `(group)` → nothing at all. */\nfunction urlSegments(componentName: string): RouteSegment[] {\n const parts = componentName.split(\"/\").slice(1, -1);\n const segments: RouteSegment[] = [];\n\n for (const part of parts) {\n // A route group organises files without appearing in the url.\n if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n // A slot directory is not part of its page's url either.\n if (part.startsWith(\"@\")) continue;\n\n if (part.startsWith(\"[...\") && part.endsWith(\"]\")) {\n segments.push({ type: \"catchAll\", value: part.slice(4, -1) });\n continue;\n }\n\n if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n // At the top of app/ - the first segment the url has - a parameter is\n // the host's: bound from acme.example.com, never from example.com/acme.\n segments.push({\n type: segments.length === 0 ? \"host\" : \"param\",\n value: part.slice(1, -1),\n });\n continue;\n }\n\n // An interception marker says which url this replaces, not what it is\n // called: (.)photo intercepts the sibling /photo. Left in place the\n // manifest would claim a route at /(.)photo, which nothing can navigate to.\n segments.push({ type: \"static\", value: part.replace(/^\\(\\.{1,3}\\)/, \"\") });\n }\n\n return segments;\n}\n\n/** Whether a component sits under an interception marker: (.) (..) (...) */\nfunction isIntercept(componentName: string): boolean {\n return componentName.split(\"/\").some((part) => /^\\(\\.{1,3}\\)/.test(part));\n}\n\n/** The slot directory a component lives under, if any. */\nfunction slotOf(componentName: string): string | null {\n const part = componentName.split(\"/\").find((p) => p.startsWith(\"@\"));\n\n return part ? part.slice(1) : null;\n}\n\n/**\n * Everything the plugin discovered, as a host needs it.\n *\n * Ancestry is by path prefix: a layout at app/docs applies to everything under\n * app/docs, which is the same rule the composition uses.\n */\nfunction routeManifest(): RouteManifest {\n const names = [...components.keys()];\n const dirOf = (name: string) => name.split(\"/\").slice(0, -1).join(\"/\");\n\n // By path, not by string: 'app/slow3' begins with 'app/slow' as text and is\n // not inside it, which would hand /slow3 the loading state of /slow.\n const isUnder = (dir: string, ancestor: string) =>\n dir === ancestor || dir.startsWith(ancestor + \"/\");\n\n const ancestors = (name: string, base: string) =>\n names\n .filter(\n (n) =>\n n.endsWith(\"/\" + base) &&\n !isIntercept(n) &&\n isUnder(dirOf(name), dirOf(n)),\n )\n .sort((a, b) => a.length - b.length);\n\n /** Project-root-relative, posix — the same string on every machine. */\n const fromRoot = (abs: string) =>\n relative(projectRoot, abs).replace(/\\\\/g, \"/\");\n\n /** The host's config file in a directory, if the host named one and it exists. */\n const configIn = (absDir: string): string | null => {\n if (!routeConfig) return null;\n\n const path = join(absDir, routeConfig.file);\n\n return existsSync(path) ? fromRoot(path) : null;\n };\n\n /** Ancestor configs, outermost first, excluding the page's own directory. */\n const ancestorConfigs = (dir: string): string[] => {\n const found: string[] = [];\n const parts = dir.split(\"/\").slice(0, -1);\n\n while (parts.length > 0) {\n const path = configIn(join(sourceDir, parts.join(\"/\")));\n\n if (path) found.unshift(path);\n\n parts.pop();\n }\n\n return found;\n };\n\n /**\n * Host middleware named by a route.ts beside or above a page.\n *\n * // app/admin/route.ts\n * export const middleware = ['auth', 'can:update,post']\n *\n * Read statically rather than imported, for the same reason\n * generateStaticParams is detected by reading the source: this runs while the\n * manifest is being built, before there is a bundle to execute.\n *\n * The names mean nothing here. They are the host's vocabulary — Laravel\n * middleware aliases, a Go router's names — and the engine only carries them\n * to whoever knows what they mean.\n */\n const middlewareIn = (absDir: string): string[] => {\n // middleware.ts first: it is the file named for what this is. A guard\n // the engine runs is its default export; the names a host runs are its\n // `middleware` export, and a file may carry either or both. route.ts is\n // read too, for the apps written before middleware.ts could.\n for (const file of [\"middleware.ts\", \"middleware.tsx\", \"route.ts\", \"route.tsx\"]) {\n const path = join(absDir, file);\n\n if (!existsSync(path)) continue;\n\n const match = readFileSync(path, \"utf-8\").match(\n /export\\s+const\\s+middleware\\s*(?::[^=]+)?=\\s*\\[([^\\]]*)\\]/,\n );\n\n if (!match) continue;\n\n // Each quoted literal, rather than splitting the list on commas: a\n // middleware name carries its arguments after a colon and those are\n // comma-separated too, so splitting turns 'throttle:60,1' into a\n // throttle of 60 and a middleware called 1.\n return [...match[1].matchAll(/['\"`]([^'\"`]*)['\"`]/g)]\n .map((quoted) => quoted[1].trim())\n .filter(Boolean);\n }\n\n return [];\n };\n\n /**\n * Every host middleware above and on a page, outermost first.\n *\n * Order is the whole of it: an outer guard has to run before an inner one, or\n * a check deciding whether the inner check is even reachable runs second.\n * Duplicates are dropped, so a name repeated down the tree runs once, at the\n * outermost point it was asked for.\n */\n const hostMiddleware = (dir: string): string[] => {\n const parts = dir.split(\"/\").filter(Boolean);\n const found: string[] = [];\n\n for (let depth = 0; depth <= parts.length; depth++) {\n for (const name of middlewareIn(\n join(sourceDir, ...parts.slice(0, depth)),\n )) {\n if (!found.includes(name)) found.push(name);\n }\n }\n\n return found;\n };\n\n const routes: ManifestRoute[] = [];\n const intercepts: ManifestIntercept[] = [];\n\n for (const name of names) {\n if (name.endsWith(\"/page\") && isIntercept(name)) {\n const slot = slotOf(name);\n\n if (slot) {\n const marker =\n name\n .split(\"/\")\n .find((p) => /^\\(\\.{1,3}\\)/.test(p))\n ?.match(/^\\(\\.{1,3}\\)/)?.[0] ?? \"(.)\";\n\n intercepts.push({\n component: name,\n slot,\n segments: urlSegments(name),\n marker,\n });\n }\n\n continue;\n }\n\n if (!name.endsWith(\"/page\") || slotOf(name)) continue;\n\n const slots: Record<string, string> = {};\n\n for (const candidate of names) {\n const slot = slotOf(candidate);\n // A slot belongs to the layout in the directory that declares it, so it\n // applies to a page only if that directory is on the page's path.\n if (!slot || isIntercept(candidate) || !candidate.endsWith(\"/default\"))\n continue;\n if (isUnder(dirOf(name), candidate.split(\"/@\")[0]))\n slots[slot] = candidate;\n }\n\n routes.push({\n component: name,\n segments: urlSegments(name),\n layouts: ancestors(name, \"layout\").map((n) => n),\n loadings: ancestors(name, \"loading\").map((n) => n),\n errors: ancestors(name, \"error\"),\n middleware: ancestors(name, \"middleware\").map((n) => n),\n slots,\n sections: names.filter(\n (n) => SECTION_FILE.test(n + \".tsx\") && dirOf(n) === dirOf(name),\n ),\n config: configIn(join(sourceDir, dirOf(name))),\n hostMiddleware: hostMiddleware(dirOf(name)),\n ancestorConfigs: ancestorConfigs(dirOf(name)),\n staticParams: hasStaticParams(components.get(name)!.absPath),\n });\n }\n\n // What the build decided, for a host that has to act on it afterwards —\n // writing the site out, and knowing which filename the client will ask for.\n return {\n version: 1,\n build: {\n output,\n exportPath,\n payloadName: staticPayloads,\n hosts: siteHosts,\n identify,\n },\n routes,\n intercepts,\n apis: [...apiRoutes.values()].map(({ name, methods, generated, absPath }) => ({\n name,\n segments: urlSegments(name),\n methods,\n // The OpenAPI document is synthesised from nothing on disk.\n source: generated\n ? generated.file\n ? relative(sourceDir, generated.file).replace(/\\\\/g, \"/\")\n : undefined\n : relative(sourceDir, absPath).replace(/\\\\/g, \"/\"),\n // A synthesised robots.txt or sitemap.xml runs no guard: it exists to be\n // read by anyone, and a guard on the root would 401 the crawler.\n middleware: generated ? [] : ancestors(name, \"middleware\"),\n })),\n };\n}\n\n/**\n * Say so when the typechecker cannot see the declarations just written.\n *\n * Moving them out of the source directory buys a tidy `src/` and costs this:\n * `include` used to cover them by accident, and now it has to name `.rsc-kit`.\n * A project that does not is not broken in any way it can notice — every file\n * is written, every build passes, and `Link` quietly takes `string` again\n * instead of the route union, so a link to a page that does not exist compiles\n * and 404s in the browser.\n *\n * A guess, deliberately, and only ever a warning: `include` is one of several\n * ways a tsconfig can reach a file, `extends` can supply it, and a project\n * with no tsconfig at all is not doing this checking anyway. Wrong here costs\n * a line of output; silent costs the types.\n */\nfunction warnIfTypesUnreachable(): void {\n const config = join(projectRoot, \"tsconfig.json\");\n\n if (!existsSync(config)) return;\n\n try {\n // Comments are legal in a tsconfig and JSON.parse does not take them.\n const text = readFileSync(config, \"utf-8\").replace(\n /\\/\\*[\\s\\S]*?\\*\\/|(^|\\s)\\/\\/.*$/gm,\n \"$1\",\n );\n const include = (JSON.parse(text) as { include?: unknown }).include;\n\n if (!Array.isArray(include)) return;\n\n const covers = (what: string) =>\n include.some(\n (entry) => typeof entry === \"string\" && entry.includes(what),\n );\n\n if (!covers(\".rsc-kit\")) {\n log(\n `tsconfig.json does not include .rsc-kit, where the generated types are written.\\n` +\n ` Add \".rsc-kit/**/*\" to \"include\", or typed routes and rpc() fall back to string.`,\n );\n }\n } catch {\n // An unparseable tsconfig is the project's own problem, not this one's.\n }\n}\n\n// ── What the app imports ─────────────────────────────────────────────────────\n\n/**\n * Write the modules the app's source imports but nobody writes by hand.\n *\n * Two destinations, and the difference is whether anything imports the file.\n *\n * The stubs are imported by relative path, so they have to sit in the source\n * directory — that path is the app's, and only the build knows it.\n *\n * The declarations are not imported by anything. They are ambient, which needs\n * them inside the project and nothing more, so they go in `.rsc-kit/` at the\n * root: four generated files in `src/` sat among the app's own and had to be\n * gitignored one by one, and every one of them was noise beside the pages.\n *\n * Ambient still means the typechecker has to be told the directory exists —\n * see the warning below, because a tsconfig that does not include it turns\n * every one of these into a file nobody reads.\n *\n * Rewritten on every run. The failure they prevent is invisible at build\n * time — a stale stub calls a global that has since been renamed, and only\n * the browser ever finds out.\n */\nfunction writeHostBindings(manifest: RouteManifest): void {\n mkdirSync(sourceDir, { recursive: true });\n mkdirSync(typesDir, { recursive: true });\n\n // The global is installed at runtime, so nothing in app source declares it\n // and a typecheck cannot see it. Written whether or not there are actions:\n // server components call it directly too.\n writeFileSync(join(typesDir, \"rsc-env.d.ts\"), renderHostGlobalTypes());\n\n // The urls this build found, so a link to a page that does not exist fails\n // the typecheck instead of the browser.\n writeFileSync(join(typesDir, \"rsc-routes.d.ts\"), renderRouteTypes(manifest));\n\n // The bundle the host imports is generated, so nothing declares it. Written\n // here rather than left to the app: every app needs the identical file, and\n // an app-authored one goes stale — the first version named only RscEngine,\n // which typechecks a server and fails a prerender script.\n writeFileSync(join(typesDir, \"rsc-engine.d.ts\"), ENGINE_TYPES);\n\n warnIfTypesUnreachable();\n\n const target = join(sourceDir, \"server-actions.generated.ts\");\n\n // A host with no functions of its own leaves no file behind: kept, its\n // stubs would go on naming targets the host has stopped answering for.\n if (Object.keys(hostActions).length === 0) {\n if (existsSync(target)) rmSync(target);\n\n return;\n }\n\n writeFileSync(target, renderHostActions());\n}\n\n/**\n * The generated engine bundle, as the type its callers expect.\n *\n * Both contracts: createRscHandler serves requests, prerender() renders at\n * build time and needs three methods the first does not have. manifest() is\n * optional on both because a host may be handed an engine without one — this\n * is the generated bundle, which always exports it, and saying so is what lets\n * exportSite() be called without a guard that could never fire.\n */\nconst ENGINE_TYPES = `// @generated — do not edit. Written by the RSC build.\ndeclare module '*/dist/rsc/index.js' {\n import type { RscEngine } from '@rsc-kit/core/host'\n import type { PrerenderEngine } from '@rsc-kit/core/prerender'\n\n const engine: RscEngine & PrerenderEngine & Required<Pick<PrerenderEngine, 'manifest'>>\n\n export = engine\n}\n`;\n\n/**\n * Render every route once and write what can be stored.\n *\n * Imported at call time, not at the top of this file: `prerender` pulls in the\n * render pipeline, and a dev server that never prerenders should not pay for\n * loading it.\n */\n/**\n * What the build classified when it classified nothing.\n *\n * With prerendering off there is no probe and no answer to report, so every\n * route is dynamic by construction rather than by measurement — printed the\n * same way so the output means the same thing either way.\n */\nfunction reportAllDynamic(): void {\n const routes = routeManifest().routes;\n\n for (const route of routes) {\n // The pattern rather than a url: nothing was rendered, so there are no\n // params and inventing one would name a page that may not exist.\n const path = route.segments\n .map((segment) =>\n segment.type === \"static\" ? segment.value : `[${segment.value}]`,\n )\n .join(\"/\");\n\n console.log(` \\u0192 /${path}`);\n }\n\n console.log(`\n \\u0192 (Dynamic) server-rendered on demand\n\n ${routes.length} dynamic — prerendering is off`);\n}\n\n/**\n * The service worker, written into the client output at build time.\n *\n * Scoped to the site root because it is served from there, so it sees every\n * navigation. Three kinds of request, three answers:\n *\n * Hashed assets are immutable by construction — the name changes when the\n * bytes do — so they are answered from the cache and only fetched once ever.\n *\n * Documents and payloads go to the network first and fall back to the cache,\n * because a page whose data moved on should say so while there is a network to\n * ask. Only the fallback is what makes a reload work with none.\n *\n * A document and its payload share a url and differ by header. They do not\n * collide, because the server sends `Vary: X-RSC, ...` and the Cache API\n * honours it when a Response is stored whole and matched with its Request.\n *\n * Nothing else is touched. An action is a POST and must never be answered from\n * a cache; anything cross-origin is somebody else's to cache.\n */\nexport const SERVICE_WORKER = (\n version: string,\n precache: string[],\n frozen: string[] = [],\n offlineUrl: string | null = null,\n swExtra: string | null = null,\n): string => `// GENERATED by rscKit() — do not edit.\nconst VERSION = ${JSON.stringify(version)}\nconst CACHE = 'rsc-kit-' + VERSION\nconst PRECACHE = ${JSON.stringify(precache, null, 2)}\n\n// The urls the build stored whole. Their answer cannot change until the next\n// deploy, and a deploy changes VERSION and sweeps this cache — so for these,\n// and only these, the cache is the better source and the network is the\n// fallback rather than the other way round.\n//\n// Everything else stays network-first. A page that reads the request has a\n// right answer that depends on the request, and serving yesterday's from a\n// cache would be wrong in a way the visitor cannot see.\nconst FROZEN = new Set(${JSON.stringify(frozen)})\n\n// The page to show when a navigation cannot be answered at all.\n//\n// An ordinary route at /offline, stored at build time like any other — nothing\n// special about the file, only about when it is served. Null when the app has\n// none, and then a navigation with nothing cached fails as it always did.\n//\n// Deliberately NOT the cached root. That was tried: the document IS the page\n// here, so the visitor got the home page's markup under the address they asked\n// for and it did not hydrate — a wrong page pretending to be the right one.\n// This one is about being offline whatever url it appears under, so it is the\n// only page that can honestly stand in for another.\nconst OFFLINE_URL = ${JSON.stringify(offlineUrl)}\n${\n swExtra\n ? `\n// The app's own worker code — push, notification clicks, background sync.\n//\n// importScripts rather than a bundled import, because this file is evaluated\n// in a worker scope by the browser rather than built: whatever the app wrote is\n// run as it was written, in the same global, so its listeners sit beside the\n// ones below.\n//\n// First, so an app handler for an event this file does not handle is registered\n// before anything here can call respondWith on it.\nself.importScripts(${JSON.stringify(swExtra)})\n`\n : \"\"\n}\n\nself.addEventListener('install', (event) => {\n // The new worker takes over rather than waiting for every tab to close.\n // Safe here because assets are content-hashed: a page already open keeps\n // asking for the names it was built with, and those are still cached under\n // their own version until this activates and sweeps.\n event.waitUntil(\n caches\n .open(CACHE)\n // The offline page is fetched rather than copied from the build output:\n // it is served by the host out of the prerendered directory, which this\n // worker cannot see. Added here so it is in the cache before it is\n // needed, which is the only moment it cannot be fetched.\n .then((cache) => cache.addAll(OFFLINE_URL ? [...PRECACHE, OFFLINE_URL] : PRECACHE).then(() => cache))\n // And the payload each precached page boots from. A document alone is\n // markup that never hydrates: the client fetches its payload on boot,\n // and a precached / rendered offline and stayed inert because that\n // request had nothing cached to answer it.\n .then((cache) =>\n Promise.all(\n PRECACHE.filter((url) => !/\\\\.[a-z0-9]+$/i.test(url))\n .concat(OFFLINE_URL ? [OFFLINE_URL] : [])\n .map((url) => {\n const warm = new Request(url, { headers: { 'X-RSC': '1' } })\n\n return fetch(warm)\n .then((payload) => {\n if (mayStore(payload)) return cache.put(keyFor(warm), payload)\n\n // Said, not swallowed: a page whose payload cannot be kept\n // is one that will render offline and never hydrate, and\n // the reason - a no-store from a guard above it, usually -\n // is only visible here.\n console.warn('[rsc-kit] offline: the payload for ' + url + ' was not stored (' + (payload.headers.get('Cache-Control') || payload.status) + '), so it will not hydrate offline')\n })\n .catch(() => {})\n }),\n ),\n )\n .then(() => self.skipWaiting()),\n )\n})\n\nself.addEventListener('activate', (event) => {\n event.waitUntil(\n caches\n .keys()\n .then((keys) => {\n const older = keys.filter((k) => k.startsWith('rsc-kit-') && k !== CACHE)\n\n return Promise.all(older.map((k) => caches.delete(k))).then(() => older.length > 0)\n })\n .then((swept) => self.clients.claim().then(() => swept))\n // Only when something older was swept. The first worker a visitor ever\n // gets activates too, and told them \"a new version is ready\" on their\n // second page - there was no previous version to be new against.\n .then((swept) => (swept ? tellTheOpenPages() : undefined)),\n )\n})\n\n// A page open right now is running the previous build's javascript, and the\n// chunks it has not loaded yet were just swept. It cannot fix that by itself —\n// only a reload gets the new ones — so it is told, and the app decides what to\n// say about it.\n//\n// After the sweep rather than before, so a page acting on this immediately\n// reloads into the new version rather than racing the deletion.\nasync function tellTheOpenPages() {\n const open = await self.clients.matchAll({ type: 'window' })\n\n for (const page of open) page.postMessage({ type: 'rsc-kit:updated', version: VERSION })\n}\n\nconst immutable = (url) => url.pathname.startsWith('/assets/') || /-[A-Za-z0-9_-]{8,}\\\\.[a-z]+$/.test(url.pathname)\n\n// Whether a response may be kept at all.\n//\n// \\`no-store\\` is not advice here, it is the answer. A query defaults to\n// \\`private, no-store\\` precisely because it may read the session, and a worker\n// that files it by url alone would serve one visitor's answer to whoever signs\n// in next — the Cache API has no notion of who asked. A live response is worse\n// again: the clone goes on streaming long after the page that opened it is\n// gone.\n//\n// Checked before every put, rather than only for the paths that happen to reach\n// a query today. A new cacheable route added later must not have to remember\n// this.\nconst mayStore = (response) =>\n response.ok && !(response.headers.get('Cache-Control') || '').includes('no-store')\n\n// What a response is filed under. A payload request carries headers the url\n// does not, so the url is where they have to go.\nconst keyFor = (request) => {\n if (!request.headers.get('X-RSC')) return request\n\n const url = new URL(request.url)\n url.searchParams.set('__rsc', request.headers.get('X-RSC-Segments') || '')\n\n return new Request(url, { headers: request.headers })\n}\n\n// Nothing cached for a request and no network: the offline page for a\n// navigation, and for the boot of a page the offline page stood in for -\n// the runtime asks for the payload of the url in the address bar, which is\n// the one thing nothing has - the offline page's own payload, which is what\n// the document on screen is. A boot only, no segments header: a navigation\n// while offline still fails as itself, and the page already open keeps its\n// banner. Null when there is no offline page, or nothing of it cached.\nconst standIn = async (request) => {\n if (!OFFLINE_URL) return null\n\n if (request.mode === 'navigate') return (await caches.match(OFFLINE_URL)) ?? null\n\n if (request.headers.get('X-RSC') && !request.headers.get('X-RSC-Segments')) {\n return (\n (await caches.match(\n keyFor(new Request(new URL(OFFLINE_URL, self.location.origin), { headers: { 'X-RSC': '1' } })),\n MATCH,\n )) ?? null\n )\n }\n\n return null\n}\n\n// The Cache API honours Vary, and a stored payload varies on X-RSC - so a\n// payload warmed with one spelling of that header was a miss for a boot\n// that sent another, and a precached page rendered offline with its payload\n// sitting in the cache, unmatched. What Vary is for is already in the key:\n// the ?__rsc=<segments> above is the one header the answer differs on.\nconst MATCH = { ignoreVary: true }\n\nself.addEventListener('fetch', (event) => {\n const request = event.request\n const url = new URL(request.url)\n\n if (request.method !== 'GET' || url.origin !== self.location.origin) return\n\n if (immutable(url)) {\n event.respondWith(\n caches.match(request).then(\n (hit) =>\n hit ??\n fetch(request).then((response) => {\n if (mayStore(response)) {\n const copy = response.clone()\n caches.open(CACHE).then((cache) => cache.put(request, copy))\n }\n\n return response\n }),\n ),\n )\n\n return\n }\n\n // A stored page, asked for without a query string. Cache first, and refresh\n // in the background so the next visit has the new one even if this worker\n // never updates.\n //\n // The query matters for the same reason it matters to a stored api route:\n // the build answered the bare url, and a page reading ?q= answers\n // differently for every value of it.\n if (FROZEN.has(url.pathname.replace(/\\\\/+$/, '') || '/') && !url.search) {\n event.respondWith(\n caches.match(keyFor(request), MATCH).then((hit) => {\n const fresh = fetch(request)\n .then((response) => {\n if (mayStore(response)) {\n const copy = response.clone()\n caches.open(CACHE).then((cache) => cache.put(keyFor(request), copy))\n }\n\n return response\n })\n .catch(async (error) => {\n if (hit) return hit\n\n // Stored by the build but never visited from this browser, so\n // nothing is cached for it, and no network: the offline page is\n // the honest answer, the same as for any other navigation - and\n // its payload for the boot that follows, so the page it stood\n // in for hydrates. Without this a frozen page failed with\n // ERR_FAILED where an unstored one showed /offline, and then\n // stood inert where an unstored one hydrated.\n return (await standIn(request)) ?? Promise.reject(error)\n })\n\n // Not awaited when there is a hit: the point is that the visitor does\n // not wait for the network for a page that cannot have changed.\n return hit ?? fresh\n }),\n )\n\n return\n }\n\n event.respondWith(\n fetch(request)\n .then((response) => {\n if (mayStore(response)) {\n const copy = response.clone()\n caches.open(CACHE).then((cache) => cache.put(keyFor(request), copy))\n\n // A document is not enough to boot from. The client hydrates from a\n // payload it fetches for itself, and on a first visit that request\n // happens before this worker controls the page — so it is never\n // cached, and a reload with no network has the markup and nothing to\n // hydrate it with.\n //\n // \\`X-RSC: 1\\` and no segments header is exactly what a fresh boot\n // sends, which is what makes this entry the one it finds: the server\n // varies on those, and the Cache API matches on the same.\n if (request.mode === 'navigate') {\n const warm = new Request(request.url, { headers: { 'X-RSC': '1' } })\n\n fetch(warm)\n .then((payload) => {\n if (mayStore(payload)) {\n caches.open(CACHE).then((cache) => cache.put(keyFor(warm), payload))\n }\n })\n .catch(() => {})\n }\n\n // And the other way round. Moving between pages fetches payloads and\n // never documents, so a page reached only by a link had nothing to\n // serve when someone reloaded its url — it navigated fine and then\n // died on refresh, which is the half of offline nobody would trust.\n //\n // Once per url: the document is fetched only when the cache has none,\n // so this costs one extra request the first time a page is visited\n // rather than one on every navigation to it.\n if (request.headers.get('X-RSC')) {\n const document = new Request(request.url)\n\n caches.open(CACHE).then(async (cache) => {\n if (await cache.match(document)) return\n\n const fresh = await fetch(document).catch(() => null)\n\n if (fresh && mayStore(fresh)) await cache.put(document, fresh)\n })\n }\n }\n\n return response\n })\n .catch(async () => {\n const hit = await caches.match(keyFor(request), MATCH)\n\n if (hit) return hit\n\n // Nothing cached for this url and no network to ask.\n //\n // Falling back to the cached ROOT was worse than failing: the document\n // IS the page here, so the visitor got the home page's markup under the\n // address they asked for, and it did not hydrate — a wrong page\n // pretending to be the right one.\n //\n // An offline page is different, and is the one page that can honestly\n // stand in for another: it is about being offline, not about the url it\n // appears under. Navigations only — a payload request answered with a\n // document would be decoded as one and throw.\n const stood = await standIn(request)\n\n if (stood) return stood\n\n // Letting it fail says what is true, and a page already open is\n // unaffected.\n return Response.error()\n }),\n )\n})\n`;\n\n/**\n * Write the worker beside the assets it caches.\n *\n * The version is a hash of what is being precached rather than a build id from\n * the environment. The names are content-hashed already, so a build that\n * changed nothing produces the same list and leaves the visitor's cache alone,\n * and a build that changed anything produces a different one — which is the\n * whole of cache invalidation, without asking anyone to set a variable.\n */\n/**\n * Write the web app manifest into the client output, beside the assets.\n *\n * Into the same directory the browser is served from, because that is where a\n * relative icon path resolves — a manifest served from somewhere else resolves\n * its icons somewhere else too, and the failure is a browser that quietly does\n * not offer to install.\n */\n/**\n * The manifest an app declared beside its routes.\n *\n * `src/app/manifest.ts`, default-exporting the object — the same shape every\n * other thing about a route tree takes here, and the reason this is a file\n * rather than a `vite.config.ts` key. A manifest is not build configuration\n * any more than a page is; it is one more thing the app declares about itself,\n * and it belongs where the app is.\n *\n * Evaluated with the TypeScript stripped rather than imported: this runs while\n * the plugin is being constructed, long before there is a module graph to pull\n * it through, and importing an app module here would drag its imports in with\n * it. The file is a literal object by contract, which is all that has to parse.\n */\nexport function declaredManifest(appDir: string): WebManifestOptions | null {\n for (const extension of [\"ts\", \"tsx\", \"js\", \"mjs\"]) {\n const file = join(appDir, `manifest.${extension}`);\n\n if (!existsSync(file)) continue;\n\n const source = readFileSync(file, \"utf-8\");\n // The object literal after `export default`, with a `satisfies` or `as`\n // annotation tolerated after it — which is how anyone who wants the type\n // checked will actually write the file, and getting that wrong would refuse\n // the recommended spelling.\n //\n // A manifest that is not a literal — computed, imported from elsewhere — is\n // refused loudly rather than silently ignored, because the failure would\n // otherwise be an app that is simply not installable with nothing said.\n const match =\n /export\\s+default\\s+(\\{[\\s\\S]*\\})(?:\\s+(?:satisfies|as)\\s+[\\w.<>\\[\\]| ]+)?\\s*;?\\s*$/.exec(\n source.trim(),\n );\n\n if (!match) {\n throw new Error(\n `[rsc-kit] app/manifest.${extension} must default-export an object literal.\\n` +\n \"It is read at build time, before there is a module graph to evaluate it in, so it \" +\n \"cannot be computed or imported from elsewhere.\",\n );\n }\n\n try {\n // Function rather than JSON.parse: the file is TypeScript source with\n // unquoted keys, trailing commas and comments in it, none of which JSON\n // accepts and all of which are ordinary in a file a person edits.\n return new Function(`return (${match[1]})`)() as WebManifestOptions;\n } catch (error) {\n throw new Error(\n `[rsc-kit] Could not read app/manifest.${extension}: ${(error as Error).message}`,\n );\n }\n }\n\n return null;\n}\n\n/**\n * Copy the icons and share images into the client output.\n *\n * They live in `app/` so the build can read them - an icon's filename decides\n * what goes in the manifest - but a browser has to be able to fetch them, and\n * nothing serves `app/`. Copied rather than symlinked: the output is what gets\n * deployed, and a link into a source tree that is not deployed points nowhere.\n */\nfunction copyAppAssets(clientDir: string): void {\n if (!existsSync(clientDir)) return;\n\n for (const file of rootFiles) {\n copyFileSync(join(sourceDir, \"app\", file), join(clientDir, file));\n }\n\n const all = allAppAssets(foundAssets);\n\n if (all.length === 0) return;\n\n for (const asset of all) {\n const to = join(clientDir, asset.href.slice(1));\n\n mkdirSync(dirname(to), { recursive: true });\n copyFileSync(join(sourceDir, \"app\", asset.file), to);\n }\n\n log(`icons: ${all.length} copied from app/`);\n}\n\nfunction writeWebManifest(\n clientDir: string,\n options: WebManifestOptions,\n): void {\n if (!existsSync(clientDir)) return;\n\n writeFileSync(join(clientDir, MANIFEST_PATH.slice(1)), webManifest(options));\n\n const warning = manifestWarning(options);\n\n if (warning) log(warning);\n else log(`manifest: ${options.name} is installable`);\n}\n\n/**\n * The url a navigation falls back to when nothing else can answer it.\n *\n * An ordinary route at /offline, and it has to be one the build STORED — a\n * page that renders per request cannot be served when there is no request to\n * be made. So a dynamic /offline is refused as a fallback rather than\n * precached and found wanting at the one moment it matters, and the build says\n * which read did it.\n */\nexport function offlineFallback(\n frozen: string[],\n results: PrerenderResult[],\n): string | null {\n const found = results.find((r) => r.url === \"/offline\");\n\n if (!found) return null;\n\n if (!frozen.includes(\"/offline\")) {\n // The reason already reads \"dynamic — called cookies()\", and this sentence\n // has said \"not stored\" by the time it gets there, so the prefix would say\n // it twice with a dash in the middle of both. A shell's reason is a\n // sentence of its own - \"connection() awaited by AuthLinks streams per\n // request; the rest is stored\" - and takes no \"it\" in front, and the\n // part about the rest being stored is not the point here.\n const why =\n found.type === \"shell\"\n ? (found.reason?.replace(/; the rest is stored$/, \"\") ?? null)\n : found.reason\n ? \"it \" + found.reason.replace(/^dynamic — /, \"\")\n : null;\n\n log(\n \"offline: /offline cannot be the fallback\" +\n (why ? `, because ${why}` : \"\") +\n \". A fallback has to be servable with no network at all.\",\n );\n\n return null;\n }\n\n return \"/offline\";\n}\n\n/**\n * The app's own service worker code, if it wrote any.\n *\n * `src/app/sw.js`, copied next to the generated worker and imported by it. Plain\n * javascript rather than TypeScript, and that is not an oversight: it is\n * evaluated by the browser in a worker scope with no build step in front of it,\n * so what is written is what runs. Calling it .js says so.\n *\n * This is the only way to add an event this package does not handle — push,\n * notificationclick, sync — without giving up everything the generated worker\n * does. There is no option for it because there is nothing to configure: the\n * file is there or it is not.\n */\nfunction copyServiceWorkerExtra(clientDir: string): string | null {\n const source = join(sourceDir, \"app\", \"sw.js\");\n\n if (!existsSync(source)) return null;\n\n copyFileSync(source, join(clientDir, \"sw-app.js\"));\n\n return \"/sw-app.js\";\n}\n\n/**\n * Whether a public file is worth fetching before it is asked for.\n *\n * The precache is what lets the app boot with no network: the scripts, the\n * stylesheets, the fonts, the manifest and its icons. Everything else in\n * public/ - an image, a wasm module, the share card - is cached the first\n * time it is used, which is what the fetch handler does for any hashed\n * asset. Precaching all of it made an install cost a megabyte before the\n * visitor had seen a page: 765 kB of it a webp encoder, the rest a png no\n * browser ever renders.\n */\nexport function bootsTheApp(file: string): boolean {\n if (/\\.(?:m?js|css|woff2?|webmanifest|json)$/i.test(file)) return !/\\.wasm\\.js$/i.test(file);\n if (/(?:^|\\/)(?:icon|apple-icon|favicon)[^/]*\\.(?:png|ico|svg)$/i.test(file)) return true;\n\n return false;\n}\n\nfunction writeServiceWorker(\n clientDir: string,\n frozen: string[] = [],\n offlineUrl: string | null = null,\n): void {\n if (!existsSync(clientDir)) return;\n\n // Before the walk, so it lands in the precache with everything else. The\n // worker importScripts it while evaluating, which is the one moment it cannot\n // go to the network for it — a worker whose import fails does not start, and\n // then nothing is cached at all.\n const extra = copyServiceWorkerExtra(clientDir);\n\n const files: string[] = [];\n\n const walk = (dir: string, prefix: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n // Not itself, and not a map: a debugger asks for those, a visitor does\n // not, and precaching them doubles what an install costs.\n if (entry.name === \"sw.js\" || entry.name.endsWith(\".map\")) continue;\n\n const path = join(dir, entry.name);\n\n if (entry.isDirectory()) walk(path, `${prefix}${entry.name}/`);\n else if (bootsTheApp(`${prefix}${entry.name}`)) files.push(`${prefix}${entry.name}`);\n }\n };\n\n walk(clientDir, \"\");\n\n const precache = [\"/\", ...files.map((file) => `/${file}`)].sort();\n const version = createHash(\"sha256\")\n .update(precache.join(\"\\n\"))\n .digest(\"hex\")\n .slice(0, 12);\n\n writeFileSync(\n join(clientDir, \"sw.js\"),\n SERVICE_WORKER(version, precache, frozen, offlineUrl, extra),\n );\n\n log(\n `offline: ${precache.length} files precached as rsc-kit-${version}` +\n (offlineUrl ? `, falling back to ${offlineUrl}` : \"\") +\n (extra ? \", with app/sw.js\" : \"\"),\n );\n}\n\n/**\n * The rsc bundle the build just wrote, whatever it decided to call it.\n *\n * Two things were assumed here and both were wrong for somebody. The directory\n * was assumed to be <outDir>/dist/rsc, which Nitro does not use — it builds the\n * environment under node_modules/.nitro. And the file was assumed to be\n * index.js, which Vite only emits for a package that declares `type: module`;\n * everyone else got index.mjs. Either miss returned quietly, and a build that\n * prerendered nothing printed exactly what a build with no pages to freeze\n * prints.\n */\nfunction resolveRscBundle(dir: string): string | null {\n for (const name of [\"index.js\", \"index.mjs\"]) {\n const candidate = join(dir, name);\n\n if (existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Every server action the bundle registered, from the plugin's own table.\n *\n * Only the app's: the engine registers a few of its own and they are not the\n * project's to be warned about.\n */\nfunction knownActionsOf(\n config: { plugins: readonly unknown[] },\n root: string,\n): KnownAction[] {\n const api = getPluginApi(config as never);\n const metaMap = api?.manager?.serverReferences?.metaMap;\n\n if (!metaMap) return [];\n\n const out: KnownAction[] = [];\n\n for (const meta of metaMap.values()) {\n if (meta.importId.includes(\"/node_modules/\")) continue;\n\n const file = relative(root, meta.importId.split(\"?\")[0] ?? meta.importId);\n\n for (const name of meta.exportNames) {\n out.push({ id: `${meta.referenceKey}#${name}`, name, file });\n }\n }\n\n return out;\n}\n\nasync function auditActions(\n engine: unknown,\n known: KnownAction[],\n): Promise<\n { id: string; name: string; file: string; client: boolean; query: boolean }[]\n> {\n const audit = (\n engine as {\n auditActions?: (\n ids: string[],\n ) => Promise<{ id: string; client: boolean; query: boolean }[]>;\n }\n ).auditActions;\n\n if (!audit || known.length === 0) return [];\n\n const byId = new Map(known.map((k) => [k.id, k]));\n\n return (await audit(known.map((k) => k.id))).map((a) => ({\n ...byId.get(a.id)!,\n client: a.client,\n query: a.query,\n }));\n}\n\n/**\n * Inlined into a page with no runtime when it is at most this big on the\n * wire. The point is the round trip, not the bytes: a stylesheet that\n * compresses to a few KB costs a whole trip before anything paints, while a\n * large one is better fetched once and cached across pages. Measured\n * gzipped, because that is what travels - a sheet of @font-face\n * declarations is long and compresses to almost nothing.\n */\nconst INLINE_STYLESHEET_LIMIT = 10 * 1024;\n\nexport function smallStylesheetReader(\n assetsDir: string,\n setting: \"auto\" | true | number,\n): (href: string) => string | null {\n const limit =\n setting === true\n ? Infinity\n : setting === \"auto\"\n ? INLINE_STYLESHEET_LIMIT\n : setting;\n\n return (href) => {\n if (!href.startsWith(\"/\") || href.includes(\"..\")) return null;\n\n try {\n const css = readFileSync(join(assetsDir, href), \"utf-8\");\n\n return gzipSync(css).length > limit ? null : css;\n } catch {\n return null;\n }\n };\n}\n\n/** A server action the bundle registered: where it is and what it is called. */\nexport interface KnownAction {\n id: string;\n name: string;\n file: string;\n}\n\nasync function prerenderAfterBundles(\n bundle: string | null,\n staticDir: string,\n assetsDir: string,\n knownActions: KnownAction[] = [],\n): Promise<{ frozen: string[]; results: PrerenderResult[] }> {\n // A missing bundle used to be a silent `return`, and under Nitro it was the\n // normal case: the path was assumed to be <outDir>/dist/rsc/index.js, Nitro\n // builds the rsc environment somewhere else entirely, and so every Nitro app\n // — every scaffolded app, and Laravel — prerendered nothing at all. No\n // classification printed, no route frozen, and every page renders per\n // visitor. The caller resolves the path from the environment now, so this is\n // back to being the impossible case it reads as.\n if (!bundle) {\n throw new Error(\n \"[rsc-kit] The build produced no rsc bundle to prerender from.\\n\" +\n \"Prerendering renders the app, so it needs the bundle the build just wrote.\",\n );\n }\n\n const [\n {\n prerender,\n NotPrerenderable,\n summary,\n legend,\n notes,\n clientJsSize,\n pathKey: pathKeyOf,\n },\n { writeTo },\n { prerenderApiRoutes },\n ] = await Promise.all([\n import(\"./prerender.js\"),\n import(\"./files.js\"),\n import(\"./apiPrerender.js\"),\n ]);\n\n // Cleared first: a route that changes classification between builds\n // otherwise leaves its old shell on disk and the host goes on serving it.\n // Nothing warns — the page loads, with content from the previous build.\n rmSync(staticDir, { recursive: true, force: true });\n\n const engine = (await import(pathToFileURL(bundle).href)) as never;\n const mark: Record<string, string> = {\n frozen: \"○\",\n shell: \"◐\",\n blocked: \"✗\",\n error: \"✗\",\n };\n let failed = 0;\n\n // Weighed from the page the prerenderer just wrote, so the column is what\n // that page actually loads rather than a total every route is charged for.\n const weigh = weighClientJs(assetsDir);\n const sized = new Map<string, number>();\n const pending: { line: string; bytes: number | null; extra: string[] }[] = [];\n\n // Every result as it lands, so a refusal still has the whole table.\n //\n // prerender() throws NotPrerenderable when a page blocked above every\n // boundary, and it used to throw past everything below: no table printed,\n // no report written. The terminal got the advice; the report on disk was\n // the previous build's, and an agent reading it through the MCP server was\n // told the routes were fine, as of some minutes ago. A build that refuses\n // is the build an agent most needs written down.\n const collected: PrerenderResult[] = [];\n let refusal: InstanceType<typeof NotPrerenderable> | null = null;\n let results: PrerenderResult[];\n\n try {\n results = await prerender({\n engine,\n write: writeTo(staticDir),\n serviceWorker: offline,\n stylesheet:\n inlineStylesheets === false\n ? undefined\n : smallStylesheetReader(assetsDir, inlineStylesheets),\n onResult: (r) => {\n collected.push(r);\n\n if (r.type === \"error\" || r.type === \"blocked\") failed++;\n\n const key = pathKeyOf(r.url);\n const file = [`${key}.html`, `${key}.ppr.html`]\n .map((name) => join(staticDir, name))\n .find((path) => existsSync(path));\n\n const bytes = file ? weigh(readFileSync(file, \"utf-8\")) : null;\n\n if (bytes !== null) sized.set(r.url, bytes);\n\n pending.push({\n line: ` ${mark[r.type] ?? \" \"} ${r.url}`,\n bytes,\n extra: [\n ...(r.reason ? [` ${r.reason}`] : []),\n ...(r.note ? [` ${r.note}`] : []),\n ...(r.warning ? [` ⚠ ${r.warning}`] : []),\n ],\n });\n },\n });\n } catch (error) {\n if (!(error instanceof NotPrerenderable)) throw error;\n\n refusal = error;\n results = collected;\n }\n\n // After the pages, sharing their output. An api route is a url the build\n // either answered or could not, which is the same question the table above\n // is already answering — a second list under its own heading would be two\n // places to look for one fact.\n const manifest = (\n engine as { manifest(): import(\"./manifest.js\").RouteManifest }\n ).manifest();\n const apis = await prerenderApiRoutes(engine, manifest, writeTo(staticDir));\n\n // A sitemap the build writes itself, when the app wrote none: every url\n // it stored or was told about, minus the guarded ones. It needs the site's\n // host, which the root layout's metadataBase is for; without one there is\n // nothing to write and the report says so once.\n const writesSitemap = manifest.apis?.some(\n (api) => api.name === \"app/sitemap.xml/route\",\n );\n const hasSitemapFile = rootFiles.includes(\"sitemap.xml\");\n\n if (!writesSitemap && !hasSitemapFile) {\n const base = rootMetadataBase(join(sourceDir, \"app\"));\n\n if (base) {\n const xml = automaticSitemap(results, manifest.routes, base);\n const stored = JSON.stringify({\n status: 200,\n headers: [[\"content-type\", \"application/xml; charset=utf-8\"]],\n body: xml,\n varies: false,\n });\n\n await writeTo(staticDir)(\"sitemap.xml.api.json\", stored);\n pending.push({\n line: \" ○ /sitemap.xml\",\n bytes: null,\n extra: [\n ` written by the build: ${xml.split(\"<url>\").length - 1} urls; a sitemap.ts beside the root layout replaces it`,\n ],\n });\n } else {\n pending.push({\n line: \" - /sitemap.xml\",\n bytes: null,\n extra: [\n \" not written: the root layout has no metadataBase to make the urls absolute\",\n ],\n });\n }\n }\n\n for (const api of apis) {\n pending.push({\n line: ` ${api.type === \"frozen\" ? \"○\" : \"ƒ\"} ${api.url}`,\n bytes: null,\n extra: [\n ...(api.reason ? [` ${api.reason}`] : []),\n ...(api.warning ? [` ⚠ ${api.warning}`] : []),\n ],\n });\n }\n\n // Printed together rather than as each route lands, because a column has to\n // line up and the widest url is not known until the last one is in.\n const column = Math.max(...pending.map((p) => p.line.length)) + 2;\n\n for (const row of pending) {\n const size = row.bytes === null ? \"\" : clientJsSize(row.bytes);\n\n console.log(size ? row.line.padEnd(column) + size : row.line);\n\n for (const line of row.extra) console.log(line);\n }\n\n const count = (type: string) => results.filter((r) => r.type === type).length;\n\n // The actions, after the routes. Which ones a client built is a mark on the\n // loaded function, so the bundle is asked; the answer is the one fact about\n // an action nothing else in the app states — whether anything checks who\n // calls it.\n const audited = await auditActions(engine, knownActions);\n const bare = audited.filter((a) => !a.client);\n\n if (bare.length > 0) {\n const byFile = new Map<string, string[]>();\n\n for (const a of bare)\n byFile.set(a.file, [...(byFile.get(a.file) ?? []), a.name]);\n\n console.log(\n `\\n \\u26a0 ${bare.length} ${bare.length === 1 ? \"action runs\" : \"actions run\"} no middleware: ` +\n [...byFile]\n .map(([file, names]) => `${names.join(\", \")} (${file})`)\n .join(\"; \"),\n );\n console.log(\n \" Nothing checks who calls them. Fine for a public one; otherwise build it\\n\" +\n \" from an action client, so the check cannot be forgotten.\",\n );\n }\n\n // Server files importing cache from React. Its cache() memoises on the\n // dispatcher a render installs, so in a guard, an action, an api route or\n // the SSR pass it calls straight through - no dedupe, no error, the helper\n // runs twice. The difference is silent, which is why this line exists.\n const reactCache = reactCacheImports(sourceDir);\n\n if (reactCache.length > 0) {\n console.log(\n `\\n \\u26a0 ${reactCache.length} server ${reactCache.length === 1 ? \"file imports\" : \"files import\"} cache from 'react': ` +\n reactCache.join(\", \"),\n );\n console.log(\n \" React's cache() dedupes only inside a component render; in a guard, an action or\\n\" +\n \" an api route it calls straight through. Import it from @rsc-kit/core/cache instead.\",\n );\n }\n\n // Server files importing a client library. Legal - a server component may\n // render a client component from a package - but the shape that costs an\n // afternoon is a file with no \"use client\" that only wraps them, so the\n // library's internals run on the server. Said, with the packages and the\n // importer, so the person reading can tell which it is.\n if (clientLibraryImports.length > 0) {\n console.log(\n `\\n \\u2139 ${clientLibraryImports.length} server ${clientLibraryImports.length === 1 ? \"file imports\" : \"files import\"} a client library: ` +\n clientLibraryImports\n .map(\n (c) =>\n `${c.file} (${c.packages.join(\", \")}${c.from ? `; imported by ${c.from}` : \"\"})`,\n )\n .join(\"; \"),\n );\n console.log(\n ' Legal for a server component. A file that only wraps client components wants \"use client\" -\\n' +\n \" as shadcn ships it - so the server stops at the boundary.\",\n );\n }\n\n // Written from the rows that were just printed rather than recomputed: the\n // report and the terminal must not be able to disagree about what happened.\n writeFileSync(\n join(outDir, REPORT_FILE),\n buildReport(\n results.map((r) => ({\n url: r.url,\n component: r.component,\n type: r.type,\n reason: r.reason,\n warning: r.warning ?? null,\n note: r.note ?? null,\n clientJs: sized.get(r.url) ?? null,\n })),\n apis.map((a) => ({\n url: a.url,\n name: a.name,\n type: a.type,\n reason: a.reason,\n warning: a.warning ?? null,\n })),\n audited,\n reactCache,\n clientLibraryImports,\n ),\n );\n\n const note = notes(results);\n const counted = [...results, ...apis];\n\n console.log(`\n${legend(counted)}\n\n ${summary(counted)}${note ? `\\n\\n${note}` : \"\"}`);\n\n // The table and the report are on disk. Now the refusal, in its own words.\n if (refusal) throw new Error(refusal.message);\n\n if (failed > 0) {\n throw new Error(\n `[rsc-kit] ${failed} route${failed === 1 ? \"\" : \"s\"} failed to render.\\n` +\n \"Prerendering runs your app: whatever those pages need at render time has to be\\n\" +\n \"reachable from the build. Give it that, or mark the read with `await connection()`\\n\" +\n \"so the page renders per request and the rest of it is still stored.\",\n );\n }\n\n if (output === \"export\")\n await exportAfterPrerender(results, staticDir, assetsDir);\n\n // The urls whose answer cannot change until the next build. The service\n // worker serves these from its cache first rather than asking the network\n // and falling back — see writeServiceWorker.\n //\n // Two narrowings beyond \"frozen\", and neither is redundant even though the\n // worker would survive without them. A guarded route IS frozen — the guard\n // is a serving decision, not a build one — but its response is per visitor\n // and must never be read from a cache that has no notion of who asked. A\n // redirect is stored as a destination rather than a page, so there is no\n // document to serve from a cache at all.\n //\n // Both are already refused downstream: a guarded response carries no-store\n // and a 3xx is not `ok`. Saying it here as well means the list means what it\n // says, rather than being a wider list that happens to be filtered later.\n const guarded = new Set(\n manifest.routes.filter((r) => r.middleware?.length).map((r) => r.component),\n );\n\n return {\n frozen: results\n .filter((r) => r.type === \"frozen\" && !guarded.has(r.component))\n .filter((r) => existsSync(join(staticDir, pathKeyOf(r.url) + \".html\")))\n .map((r) => r.url),\n results,\n };\n}\n\n/**\n * Weighs the javascript one stored page makes the browser download.\n *\n * Read back out of the html rather than worked out from the module graph,\n * because the html is the answer: React writes a modulepreload for every chunk\n * the page needs, so whatever is in there is what the browser fetches. Nothing\n * here has to agree with the bundler about anything.\n *\n * Gzipped, and each chunk weighed once however many pages name it — the same\n * three files appear on every route and compressing them per page is the whole\n * cost of this function.\n *\n * Returns null when there is no page to weigh, which is a route rendered on\n * demand. A build must not fail over a column it prints for information.\n */\nfunction weighClientJs(assetsDir: string): (html: string) => number | null {\n const weighed = new Map<string, number>();\n\n const bytesOf = (asset: string): number => {\n const cached = weighed.get(asset);\n\n if (cached !== undefined) return cached;\n\n const file = join(assetsDir, asset);\n const bytes = existsSync(file)\n ? gzipSync(readFileSync(file)).byteLength\n : 0;\n\n weighed.set(asset, bytes);\n\n return bytes;\n };\n\n return (html: string) => {\n if (!html) return null;\n\n const named = new Set<string>();\n\n // Split rather than matched: /assets/name.js is the only shape written, and\n // a regex over a whole document is the slower half of this function.\n for (const piece of html.split(\"/assets/\").slice(1)) {\n const name = piece.split(/[\"'\\s)]/)[0];\n\n if (name.endsWith(\".js\")) named.add(\"assets/\" + name);\n }\n\n let total = 0;\n\n for (const asset of named) total += bytesOf(asset);\n\n return total;\n };\n}\n\n/**\n * Turn the frozen output into a directory a static host can serve.\n *\n * Part of the build rather than a script the app writes, for the same reason\n * prerendering is: it needs the results the build already has, and the engine\n * bundle they came from is somewhere only the build knows. That path used to be\n * stable enough to hard-code in an example — `build/dist/rsc/index.js` — and it\n * is not any more, because Nitro builds the rsc environment under\n * node_modules. A script asking for it would be a script that breaks.\n *\n * RSC_EXPORT_FORCE writes the site anyway and reports what it left out, which\n * is how an app is moved towards being exportable. Without it a route that\n * could not be frozen fails the build, because a shell on a static host is a\n * page that loads and then stays empty forever.\n */\nasync function exportAfterPrerender(\n results: PrerenderResult[],\n staticDir: string,\n assetsDir: string,\n): Promise<void> {\n const [\n { exportSite, NotExportable },\n { writeTo, prerenderedFrom, copyAssets },\n ] = await Promise.all([import(\"./export.js\"), import(\"./files.js\")]);\n\n try {\n const { pages, refused } = await exportSite({\n results,\n read: prerenderedFrom(staticDir),\n write: writeTo(exportPath),\n manifest: routeManifest() as never,\n assets: copyAssets(join(assetsDir, \"assets\"), exportPath, \"/assets/\"),\n force: process.env.RSC_EXPORT_FORCE === \"1\",\n });\n\n console.log(\n `\\n Exported ${pages} page${pages === 1 ? \"\" : \"s\"} to ${relative(projectRoot, exportPath)}`,\n );\n\n if (refused.length > 0) {\n console.log(\n ` Left out ${refused.length}: ${refused.map((r) => r.url).join(\", \")}`,\n );\n }\n } catch (error) {\n if (!(error instanceof NotExportable)) throw error;\n\n throw new Error(`[rsc-kit] ${error.message}`);\n }\n}\n\n/** `/posts/[slug]` — the pattern, in the shape the app writes its links in. */\nfunction patternOf(segments: RouteSegment[]): string {\n if (segments.length === 0) return \"/\";\n\n return (\n \"/\" +\n segments\n .map((segment) =>\n segment.type === \"static\"\n ? segment.value\n : segment.type === \"catchAll\"\n ? `[...${segment.value}]`\n : `[${segment.value}]`,\n )\n .join(\"/\")\n );\n}\n\n/**\n * The app's routes as a union, for `@rsc-kit/core/routes` to derive from.\n *\n * Rewritten every build like the other generated files: a route deleted from\n * the tree has to stop being a valid href, and the only thing that knows is\n * the walk that just happened.\n *\n * Interception patterns are deliberately absent. An interceptor answers a url\n * that some real route already owns — listing it would put the same href in\n * the union twice and imply you could link to a modal.\n */\nfunction renderRouteTypes(manifest: RouteManifest): string {\n const patterns = [\n ...new Set(manifest.routes.map((route) => patternOf(route.segments))),\n ].sort();\n const apis = [\n ...new Set((manifest.apis ?? []).map((route) => patternOf(route.segments))),\n ].sort();\n\n // Each pattern to the page module that answers it, as a type-only import\n // from the generated file's own directory. SearchExportOf reads the page's\n // `searchParams` export, or undefined when there is none, so nothing here\n // has to look inside the file - the typechecker already has every page\n // open. One line per route, and a page without a schema costs nothing.\n const search = new Map<string, string>();\n\n for (const route of manifest.routes) {\n const pattern = patternOf(route.segments);\n\n if (search.has(pattern)) continue;\n\n const target = relative(typesDir, join(sourceDir, route.component)).replace(\n /\\\\/g,\n \"/\",\n );\n\n search.set(pattern, target.startsWith(\".\") ? target : \"./\" + target);\n }\n\n // Section names are read from the source - section('orders', …) - the way\n // generateStaticParams is detected, because this runs before any bundle\n // exists. A name computed at runtime is not seen and revalidate() falls\n // back to refusing it at the renderer, as before.\n const regions = [\n ...new Set([\n ...[...components.values()]\n .filter((c) => SECTION_FILE.test(c.absPath))\n .flatMap((c) =>\n [\n ...readFileSync(c.absPath, \"utf-8\").matchAll(\n /\\bsection\\(\\s*['\"`]([^'\"`]+)['\"`]/g,\n ),\n ].map((m) => m[1]),\n ),\n ...[...components.keys()].flatMap((name) => {\n const slot = name.split(\"/\").find((part) => part.startsWith(\"@\"));\n\n return slot ? [slot.slice(1)] : [];\n }),\n ]),\n ].sort();\n\n return [\n \"// @generated — do not edit. Written by the RSC build from the route tree.\",\n \"//\",\n \"// Turns Link, navigate() and route() into typed apis: an href that no route\",\n \"// answers stops compiling. Delete this file and they fall back to `string`,\",\n \"// which is what a project that has not built yet gets.\",\n \"\",\n \"// `export {}` is load-bearing: in a file with no import or export,\",\n \"// `declare module` *replaces* the real module rather than augmenting it,\",\n \"// and Route and route() vanish from it with no error to explain why.\",\n \"export {}\",\n \"\",\n \"declare module '@rsc-kit/core/routes' {\",\n \" interface Register {\",\n patterns.length > 0\n ? \" routes:\\n\" +\n patterns.map((p) => \" | \" + JSON.stringify(p)).join(\"\\n\")\n : \" // No routes found under the source directory.\\n routes: never\",\n // The searchParams schema each page exports, read off the module's type.\n // This is what types Link's `search` prop and href() per route.\n \" search: {\",\n ...[...search]\n .sort()\n .map(\n ([pattern, target]) =>\n \" \" +\n JSON.stringify(pattern) +\n \": SearchExportOf<typeof import(\" +\n JSON.stringify(target) +\n \")>\",\n ),\n \" }\",\n \" }\",\n // Api routes are a separate union, so Link refuses an api url and apiUrl()\n // refuses a page. Linking to an api route navigates the browser away to a\n // json document, which is the mistake worth catching.\n // Regions: every section('name', …) the build read, and every @slot\n // directory. This is what types revalidate().\n \" interface RegisterRegions {\",\n regions.length > 0\n ? \" regions:\\n\" +\n regions.map((r) => \" | \" + JSON.stringify(r)).join(\"\\n\")\n : \" // No sections or slots found under the source directory.\\n regions: never\",\n \" }\",\n \" interface RegisterApi {\",\n apis.length > 0\n ? \" apis:\\n\" +\n apis.map((p) => \" | \" + JSON.stringify(p)).join(\"\\n\")\n : \" // No route.ts files found under the source directory.\\n apis: never\",\n \" }\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** The \"use server\" module exposing each host function as a plain async call. */\nfunction renderHostActions(): string {\n const lines = [\n '\"use server\";',\n \"// @generated — do not edit. Written by the RSC build from the host action map.\",\n \"\",\n ];\n\n for (const [name, target] of Object.entries(hostActions)) {\n lines.push(\"export async function \" + name + \"(...args: unknown[]) {\");\n lines.push(\n \" return await (globalThis as any).\" +\n hostGlobal +\n \"(\" +\n JSON.stringify(target) +\n \", ...args);\",\n );\n lines.push(\"}\");\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n/** Ambient declaration for the host global, written beside the app's source. */\nfunction renderHostGlobalTypes(): string {\n return [\n \"// @generated — do not edit.\",\n \"//\",\n \"// \" +\n hostGlobal +\n \"() is installed on globalThis by the RSC worker, so it has no\",\n \"// import to resolve. This declares it for the typechecker; run\",\n \"// `tsc --noEmit` to catch calls to a host global that no longer exists.\",\n \"//\",\n \"// Deliberately not a module — no import/export — so the declaration is\",\n \"// global to the project without every file having to reference it.\",\n \"\",\n \"declare function \" +\n hostGlobal +\n \"<T = unknown>(name: string, ...args: unknown[]): Promise<T>;\",\n \"\",\n ].join(\"\\n\");\n}\n\n// ── Discovery ────────────────────────────────────────────────────────────────\n\nconst ROUTE_FILES = [\n \"page\",\n \"layout\",\n \"loading\",\n \"error\",\n \"not-found\",\n \"default\",\n \"middleware\",\n];\n/** The methods a route.ts may export. HEAD and OPTIONS are answered for you. */\nconst API_METHODS = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"HEAD\",\n \"OPTIONS\",\n];\n/** `orders.section.tsx` — a region of a page that can be refreshed by name. */\nconst SECTION_FILE = /\\.section\\.(tsx|jsx|ts|js)$/;\nconst EXTS = [\"tsx\", \"jsx\", \"ts\", \"js\"];\n\nfunction findRouteFile(dir: string, base: string): string | null {\n for (const ext of EXTS) {\n const p = join(dir, `${base}.${ext}`);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction componentName(absPath: string): string {\n const rel = relative(sourceDir, absPath).replace(/\\\\/g, \"/\");\n return rel.replace(/\\.(tsx|jsx|ts|js)$/, \"\");\n}\n\n/**\n * The identifier a route file is imported as in the generated entries.\n *\n * One-to-one with the path, which the obvious \"replace everything odd with an\n * underscore\" is not: app/agent-account/page and app/agent/account/page\n * both came out as _c_app_agent_account_page, and the entry declared the\n * same import twice. A slash is an underscore, because that is what every\n * alias reads like; anything else that is not a letter or digit - a hyphen,\n * a dot, the brackets of a param, the parens of a group, an underscore of\n * its own - is its character code, so no two paths share an alias.\n */\nexport function toAlias(name: string): string {\n return (\n \"_c_\" +\n name.replace(/[^a-zA-Z0-9]/g, (char) => (char === \"/\" ? \"_\" : \"$\" + char.charCodeAt(0).toString(16)))\n );\n}\n\nconst components = new Map<string, Component>();\n\n/**\n * `route.ts` files, by the name a url is matched against.\n *\n * Kept apart from `components` on purpose: these are not React and never enter\n * the render. They are imported by the generated entry and called with a\n * Request, which is why they can export whatever methods they like rather than\n * a default component.\n */\nconst apiRoutes = new Map<\n string,\n {\n name: string;\n absPath: string;\n methods: string[];\n /** Synthesised from a convention file beside the root layout - see metadataRoutes. */\n generated?: { kind: MetadataRouteKind | \"openapi\"; file: string };\n }\n>();\n\nconst OPENAPI_ROUTE_ID = \"virtual:rsc-kit/openapi\";\n\n/**\n * /openapi.json, when asked for, registered as an api route at the path the\n * option names. Synthesised like a sitemap: stored by the build, without\n * middleware - a document exists to be read.\n */\nfunction registerOpenApiRoutes(): void {\n if (!openapi) return;\n\n const name = `app${openapi.path.replace(/\\/$/, \"\")}/route`;\n\n if (apiRoutes.has(name)) {\n throw new Error(\n `[rsc-kit] ${openapi.path} is answered by ${apiRoutes.get(name)!.absPath} and by rscKit({ openapi }). Move one.`,\n );\n }\n\n apiRoutes.set(name, { name, absPath: OPENAPI_ROUTE_ID, methods: [\"GET\"], generated: { kind: \"openapi\", file: \"\" } });\n}\n\n/** The module behind the synthesised /openapi.json route. */\nfunction openApiPlugin(): Plugin {\n return {\n name: \"rsc-kit:openapi\",\n resolveId(id) {\n if (id === OPENAPI_ROUTE_ID) return \"\\0\" + id;\n },\n load(id) {\n if (id !== \"\\0\" + OPENAPI_ROUTE_ID || !openapi) return;\n\n // Every route.ts the app wrote, imported so its schemas can describe\n // themselves at request time; the synthesised ones are not an API.\n const routes = [...apiRoutes.values()].filter((r) => !r.generated);\n const guarded = new Set(\n (routeManifest().apis ?? []).filter((api) => api.middleware.length > 0).map((api) => api.name),\n );\n const imports = routes.map((r, i) => `import * as __r${i} from ${JSON.stringify(r.absPath)}`);\n const entries = routes.map(\n (r, i) =>\n ` { pattern: ${JSON.stringify(patternOf(urlSegments(r.name)))}, methods: ${JSON.stringify(r.methods)}, guarded: ${guarded.has(r.name)}, module: __r${i} }`,\n );\n\n return [\n ...imports,\n `import { openApiResponse } from ${JSON.stringify(join(packageDir, \"openapi\"))}`,\n `const routes = [\\n${entries.join(\",\\n\")}\\n]`,\n `export const GET = () => openApiResponse(routes, ${JSON.stringify(openapi.document)})`,\n \"\",\n ].join(\"\\n\");\n },\n };\n}\n\n\n/** Files beside the root layout served at the root as they are: robots.txt, a hand-written sitemap.xml, humans.txt. */\nlet rootFiles: string[] = [];\n\nconst METADATA_ROUTE_ID = \"virtual:rsc-kit/metadata-route/\";\n\n/**\n * robots.ts, sitemap.ts, llms.ts beside the root layout, each registered as\n * an api route at the file it stands for. The module the entry imports is\n * synthesised (metadataRoutesPlugin): the app's default export, formatted by\n * the engine, with the root layout's metadataBase for relative urls.\n *\n * Api routes, so nothing else is new: the build stores the ones that read\n * nothing per request and names the ones that do. Without middleware, on\n * purpose - these exist to be read by anyone, and a guard on the root would\n * otherwise 401 the crawler asking for robots.txt.\n */\nfunction registerMetadataRoutes(appDir: string): void {\n rootFiles = existsSync(appDir)\n ? readdirSync(appDir)\n .filter((name) => ROOT_FILES.test(name))\n .sort()\n : [];\n\n for (const kind of Object.keys(METADATA_ROUTES) as MetadataRouteKind[]) {\n const source = [\"ts\", \"tsx\", \"js\", \"mjs\"]\n .map((ext) => join(appDir, `${kind}.${ext}`))\n .find((file) => existsSync(file));\n\n if (!source) continue;\n\n const { file } = METADATA_ROUTES[kind];\n\n if (rootFiles.includes(file)) {\n throw new Error(\n `[rsc-kit] app/${basename(source)} and app/${file} both answer /${file}. Keep one: the function, or the file as written.`,\n );\n }\n\n const name = `app/${file}/route`;\n\n if (apiRoutes.has(name)) {\n throw new Error(\n `[rsc-kit] app/${basename(source)} and app/${file}/route.ts both answer /${file}. Keep one.`,\n );\n }\n\n apiRoutes.set(name, {\n name,\n absPath: METADATA_ROUTE_ID + kind,\n methods: [\"GET\"],\n generated: { kind, file: source },\n });\n }\n}\n\n/** The module behind a synthesised metadata route. */\nfunction metadataRoutesPlugin(): Plugin {\n return {\n name: \"rsc-kit:metadata-routes\",\n resolveId(id) {\n if (id.startsWith(METADATA_ROUTE_ID)) return \"\\0\" + id;\n },\n load(id) {\n if (!id.startsWith(\"\\0\" + METADATA_ROUTE_ID)) return;\n\n const kind = id.slice(\n (\"\\0\" + METADATA_ROUTE_ID).length,\n ) as MetadataRouteKind;\n const route = [...apiRoutes.values()].find(\n (r) => r.generated?.kind === kind,\n );\n\n if (!route?.generated) return;\n\n const rootLayout = components.get(\"app/layout\")?.absPath ?? null;\n\n return [\n `import produce from ${JSON.stringify(route.generated.file)}`,\n rootLayout\n ? `import * as __root from ${JSON.stringify(rootLayout)}`\n : \"const __root = {}\",\n `import { metadataResponse } from ${JSON.stringify(join(packageDir, \"metadataRoutes\"))}`,\n `export const GET = () => metadataResponse(${JSON.stringify(kind)}, produce, __root.metadata?.metadataBase ?? null)`,\n \"\",\n ].join(\"\\n\");\n },\n };\n}\n\nfunction register(absPath: string): Component {\n const name = componentName(absPath);\n const existing = components.get(name);\n if (existing) return existing;\n const c: Component = { name, absPath, alias: toAlias(name) };\n components.set(name, c);\n return c;\n}\n\n/** Walk app/ collecting page/layout/loading/default/middleware components. */\n/**\n * Record a route.ts and the methods it exports.\n *\n * Syntactic, deliberately. A handler assembled at runtime is not found, which\n * errs toward refusing a file whose shape we would be guessing at rather than\n * registering a url that answers 405 to everything.\n */\nfunction registerApiRoute(absPath: string): void {\n const name = componentName(absPath);\n const source = readFileSync(absPath, \"utf-8\");\n const methods = API_METHODS.filter((method) =>\n new RegExp(\n `^\\\\s*export\\\\s+(?:async\\\\s+function|function|const|let|var)\\\\s+${method}\\\\b`,\n \"m\",\n ).test(source),\n );\n\n if (methods.length === 0) {\n // `route.ts` is also where a host declares the guards for everything below\n // it — the file predates api routes and is still read that way. One that\n // exports middleware is that file, not an endpoint, and saying so would be\n // telling someone their working config is broken.\n if (/^\\s*export\\s+(?:const|let|var|function)\\s+middleware\\b/m.test(source))\n return;\n\n throw new Error(\n `[rsc-kit] ${relative(projectRoot, absPath)} exports no request methods.\\n` +\n ` Export one named for the method it answers — export function GET(request: Request) — ` +\n `or delete the file. One of: ${API_METHODS.join(\", \")}.`,\n );\n }\n\n apiRoutes.set(name, { name, absPath, methods });\n}\n\n/**\n * Whether a middleware.ts is a guard the engine runs, or only names guards\n * the host runs. The engine imports a guard's default export; a file with\n * none - `export const middleware = ['auth']` and nothing else - has nothing\n * to import, and registering it would make the build fail on an export that\n * was never meant to exist.\n */\nfunction isEngineGuard(absPath: string): boolean {\n return /export\\s+default\\b/.test(readFileSync(absPath, \"utf-8\"));\n}\n\nfunction discover(dir: string): void {\n for (const base of ROUTE_FILES) {\n const p = findRouteFile(dir, base);\n if (p && (base !== \"middleware\" || isEngineGuard(p))) register(p);\n }\n\n // route.ts — an api endpoint, colocated with the pages it sits among. Read\n // for its method exports here rather than at request time, so a route that\n // exports nothing callable is a build error instead of a 404 nobody explains.\n const api = findRouteFile(dir, \"route\");\n\n if (api) registerApiRoute(api);\n\n // Named regions. Registered like any other component so the generated entry\n // imports them — which is what runs section() and puts the name in the\n // registry the server looks up to re-render one on its own.\n for (const entry of readdirSync(dir)) {\n if (SECTION_FILE.test(entry)) register(join(dir, entry));\n }\n\n for (const entry of readdirSync(dir)) {\n const abs = join(dir, entry);\n if (statSync(abs).isDirectory()) discover(abs);\n }\n}\n\n/**\n * Which of the two metadata exports a module actually has.\n *\n * Both are read separately because the generated entry names each one it\n * mentions, and naming an export that is not there is a bundler warning on\n * every build — `Import 'generateMetadata' will always be undefined`. Most\n * pages export only the static object, so referencing both meant that warning\n * for almost every route in an app.\n */\n/**\n * The root layout's metadataBase, read from the source. Wanted while the\n * manifest is built, before there is a bundle to execute - the same reason\n * generateStaticParams is detected by reading. A `new URL('…')` or a string\n * literal; anything computed is not seen, and rscKit({ hosts }) says it.\n */\nfunction rootMetadataBase(appDir: string): string | null {\n const layout = [\"layout.tsx\", \"layout.jsx\", \"layout.ts\", \"layout.js\"]\n .map((name) => join(appDir, name))\n .find((file) => existsSync(file));\n\n if (!layout) return null;\n\n const match =\n /metadataBase\\s*:\\s*(?:new\\s+URL\\(\\s*)?[\"'`](https?:\\/\\/[^\"'`]+)[\"'`]/.exec(\n readFileSync(layout, \"utf-8\"),\n );\n\n return match ? match[1] : null;\n}\n\nfunction metadataExports(absPath: string): {\n static: boolean;\n generate: boolean;\n viewport: boolean;\n /** Whether the file renders these itself, so the engine's defaults stand down. */\n writes: { charset: boolean; viewport: boolean };\n} {\n const src = readFileSync(absPath, \"utf-8\");\n\n return {\n static: /export\\s+const\\s+metadata\\b/.test(src),\n generate: /export\\s+(async\\s+)?function\\s+generateMetadata\\b/.test(src),\n viewport: /export\\s+const\\s+viewport\\b/.test(src),\n writes: {\n charset: /\\bcharSet\\s*=/.test(src),\n viewport: /name\\s*=\\s*[\"']viewport[\"']/.test(src),\n },\n };\n}\n\n/**\n * Which urls exist for a parameterised route.\n *\n * The one thing about a route the build cannot work out for itself: only the\n * app knows its slugs. Everything else about whether a page can be frozen is\n * observed by rendering it — a page that suspends past the shell budget, or\n * reaches for the host, says so by doing it. This is asked rather than\n * inferred because there is nothing to infer it from.\n */\nfunction hasStaticParams(absPath: string): boolean {\n const src = readFileSync(absPath, \"utf-8\");\n\n return /export\\s+((async\\s+)?function\\s+generateStaticParams|const\\s+generateStaticParams)/.test(\n src,\n );\n}\n\n/**\n * Which url schemas a page exports.\n *\n * Read from the source rather than by importing the module, the same way\n * metadata and generateStaticParams are: this runs while the graph is being\n * generated, and importing a page here would pull the app's whole server tree\n * into the plugin.\n *\n * `const` only. A schema is a value — `export function params` would be a\n * function, which no Standard Schema is, so matching it would generate an\n * import for something that can never validate.\n */\nfunction urlSchemaExports(absPath: string): {\n params: boolean;\n searchParams: boolean;\n} {\n const src = readFileSync(absPath, \"utf-8\");\n\n return {\n params: /export\\s+const\\s+params\\s*[=:]/.test(src),\n searchParams: /export\\s+const\\s+searchParams\\s*[=:]/.test(src),\n };\n}\n\n// ── Codegen ──────────────────────────────────────────────────────────────────\n\n/**\n * The dev fall-through, emitted only when there is a backend to hand a url to.\n *\n * A JavaScript host has no backend — it IS the backend — so its entry should\n * not carry this code, its constants, or the branch that tests them. Nothing\n * generated is cheaper than something generated that returns early, and it\n * keeps every backend-shaped idea out of a runtime that has no backend.\n */\nconst FALLBACK_CONSTS = `const FALLBACK_ORIGIN = __ORIGIN__\nconst FALLBACK_MARKER = 'x-rsc-renderer-fallback'\nconst PROXIED_MARKER = 'x-rsc-proxied-by-backend'\n`;\n\nconst FALLBACK_BODY = ` const answer = await devHandler(request)\n\n if (answer) return answer\n\n // Nothing here owns this url. In development the backend usually does — a\n // Blade page, /login, a webhook, an uploaded file under /storage — so the\n // request is handed on rather than refused, and this origin is the whole\n // application instead of the RSC half of it.\n //\n // FALLBACK_MARKER is what stops this looping. The backend's own fallback\n // forwards what it cannot route BACK to this server, so without a marker a\n // url neither side owns would bounce between them until something gave out.\n // Seeing it, the backend answers 404 itself.\n // Came from the backend's own proxy, so it has already been through that\n // route table and the answer there was no. Sending it back asks the same\n // question a second time.\n if (!FALLBACK_ORIGIN || request.headers.has(PROXIED_MARKER)) {\n return new Response('Not found', { status: 404 })\n }\n\n // Built from the origin rather than by assigning onto a copy of this url.\n // The URL host setter keeps whatever port is already there when the value it\n // is given has none, so a portless backend — every Herd or Valet site —\n // would inherit the dev server's own port and this server would call itself.\n const here = new URL(request.url)\n const target = new URL(here.pathname + here.search, FALLBACK_ORIGIN)\n\n const headers = new Headers(request.headers)\n\n // Never forwarded: a vhost server routes on it, so telling Herd the host is\n // localhost:5173 means it has no such site and answers 404. fetch sets it\n // from the target instead.\n headers.delete('host')\n headers.set(FALLBACK_MARKER, '1')\n\n // What the browser actually asked for. Without these the backend generates\n // absolute urls — url(), route(), redirects, form actions — against its own\n // origin rather than this one, and a redirect walks the browser off this\n // server onto the backend.\n //\n // They only take effect if the backend trusts this proxy: Laravel needs the\n // renderer's address in trustProxies. Sent regardless, because a header an\n // untrusting backend ignores costs nothing, and the alternative is that\n // there is no way to get it right at all.\n headers.set('x-forwarded-host', here.host)\n headers.set('x-forwarded-proto', here.protocol.replace(':', ''))\n\n const hasBody = request.method !== 'GET' && request.method !== 'HEAD'\n\n try {\n return await fetch(target, {\n method: request.method,\n headers,\n body: hasBody ? request.body : undefined,\n // A redirect is the backend's answer and belongs to the browser.\n // Following it here would return the destination's body under this url.\n redirect: 'manual',\n ...(hasBody ? { duplex: 'half' } : {}),\n } as RequestInit)\n } catch (error) {\n return new Response(\n // The cause, not just the wrapper: fetch reports every network failure\n // as the same 'TypeError: fetch failed', and the refused address\n // underneath it is the whole of the diagnosis.\n 'The backend at ' + FALLBACK_ORIGIN + ' is not answering: ' +\n String((error as { cause?: unknown }).cause ?? error),\n { status: 502 },\n )\n }\n`;\n\n/**\n * Wire host calls when Nitro is the server.\n *\n * Every other arrangement installs this from outside: the dev server does it in\n * configureServer, and a generated server.ts passes hostCalls to\n * createRscHandler. Under Nitro there is no such file — this module IS the\n * server — so an rpc() page renders its loading fallback forever and the\n * backend never hears from it. Silent, which is the worst kind.\n *\n * Read at request time rather than at build time: the endpoint belongs to the\n * deployment, and baking it in would mean rebuilding to change where the\n * backend is.\n */\n/**\n * What a generated server.ts passes, for the arrangement that has no server.ts.\n *\n * props: a page reading `params` gets its url params from the engine, and the\n * query string is merged in here — `params.q` should mean the same thing\n * whether it arrived in the path or after the ?. Only the Laravel template\n * passed this before, so the other hosts quietly did not have it.\n *\n * version: the client compares it on every navigation and falls back to a full\n * load when it changes. Without one, a browser keeps talking to a deployment\n * that is gone — worst behind a CDN, where the shell it holds may already be\n * older than the payloads it asks for.\n */\n/**\n * Where frozen pages live inside `.output/server`, written by the build and\n * found by the generated entry. One constant because the two halves are in\n * different processes — a name written down twice is a name that drifts, and\n * the failure is silent: the server finds no directory, decides nothing was\n * frozen, and renders every page live exactly as it did before.\n */\nconst NITRO_STATIC_DIR = \"rsc-static\";\n\n/**\n * Serve what the build froze.\n *\n * `import.meta.env.PROD` rather than an unconditional reader: in development\n * there is no build output to serve, and a stale one would be worse than none.\n * Vite replaces it with a literal, so the dev bundle keeps no reference to it.\n */\nconst NITRO_PRERENDERED = ` prerendered: import.meta.env.PROD\n ? prerenderedBeside(import.meta.url, ${JSON.stringify(NITRO_STATIC_DIR)})\n : undefined,\n`;\n\nconst NITRO_HANDLER_OPTIONS = ` props: (match, request) => ({\n ...match.params,\n ...Object.fromEntries(new URL(request.url).searchParams),\n }),\n // A built server gzips what it answers, where the runtime can; the dev\n // server answers raw, which is what a person reading a response wants.\n compress: import.meta.env.PROD,\n`;\n\nconst NITRO_HOST_CALLS = `\nlet hostInstalled = false\n\nfunction installHostCallsOnce(): void {\n if (hostInstalled) return\n hostInstalled = true\n\n const origin = process.env.RSC_BACKEND ?? process.env.APP_URL\n const secret = process.env.RSC_HOST_CALL_SECRET\n\n // Both, or neither: a secret without a backend has nowhere to go, and a\n // backend without one is refused at the door. See the dev server, which\n // gates on exactly the same pair.\n if (!origin || !secret) return\n\n const path = process.env.RSC_HOST_CALL_PATH ?? '/__rsc/host-call'\n\n installHostFn(httpHostCalls({ endpoint: origin.replace(/\\\\/$/, '') + path, secret }))\n}\n\n`;\n/**\n * The app's process bootstrap, if it has one: `instrumentation.ts` beside\n * `app/`, the name Next uses so a reader arriving from there knows what it\n * is.\n *\n * Two things make it a framework concern rather than an import the app\n * adds. Module evaluation order: a page that configures a shared package at\n * import time runs before any module the app could put first, and only the\n * generated entry can import something before the pages. And \"before the\n * first request\": an async `register()` — connecting, validating env — has\n * to be awaited by every entry point a host or a prerender can call, which\n * is a list the app cannot see.\n */\nfunction instrumentationFile(): { file: string; hasRegister: boolean } | null {\n for (const ext of [\"ts\", \"tsx\", \"mts\", \"js\", \"mjs\"]) {\n const file = join(sourceDir, `instrumentation.${ext}`);\n\n if (!existsSync(file)) continue;\n\n // Both halves are optional: a file of imports is a bootstrap, a file\n // with register() is a hook. The entry must only name `register` when it\n // exists - a namespace import's missing member is a bundler warning on\n // every build (IMPORT_IS_UNDEFINED), which is the app being told off for\n // a file written exactly as documented.\n const hasRegister = /export\\s+(?:async\\s+)?(?:function\\s+register\\b|const\\s+register\\b|let\\s+register\\b|\\{[^}]*\\bregister\\b[^}]*\\})/.test(\n readFileSync(file, \"utf-8\"),\n );\n\n return { file, hasRegister };\n }\n\n return null;\n}\n\nfunction generateEntryRsc(fallbackOrigin = \"\"): string {\n const instrumentation = instrumentationFile();\n // The 404 page, if the app has one, and the layouts it renders inside.\n // Computed here rather than looked up at runtime: not-found is not a route,\n // so the manifest has no entry to read its chain from.\n const notFoundComponent = [...components.keys()].find((name) =>\n name.endsWith(\"/not-found\"),\n );\n const notFoundLayouts = notFoundComponent\n ? [...components.keys()]\n .filter(\n (name) =>\n name.endsWith(\"/layout\") &&\n notFoundComponent.startsWith(name.slice(0, -\"layout\".length)),\n )\n .sort((a, b) => a.length - b.length)\n : [];\n\n const imports: string[] = [];\n const mapEntries: string[] = [];\n const metaEntries: string[] = [];\n const paramEntries: string[] = [];\n const schemaEntries: string[] = [];\n const apiEntries: string[] = [];\n\n // Namespace imports: a route.ts exports one function per method, and which\n // ones it exports is the thing the dispatcher needs.\n for (const [index, route] of [...apiRoutes.values()].entries()) {\n imports.push(\n `import * as __api${index} from ${JSON.stringify(route.absPath)}`,\n );\n apiEntries.push(` ${JSON.stringify(route.name)}: __api${index},`);\n }\n\n for (const c of components.values()) {\n imports.push(`import ${c.alias} from ${JSON.stringify(c.absPath)}`);\n mapEntries.push(` ${JSON.stringify(c.name)}: ${c.alias},`);\n\n const meta = metadataExports(c.absPath);\n\n if (meta.static || meta.generate || meta.viewport || meta.writes.charset || meta.writes.viewport) {\n if (meta.static || meta.generate || meta.viewport) {\n imports.push(\n `import * as ${c.alias}_meta from ${JSON.stringify(c.absPath)}`,\n );\n }\n\n const fields = [\n meta.static ? `static: ${c.alias}_meta.metadata` : null,\n meta.generate ? `generate: ${c.alias}_meta.generateMetadata` : null,\n meta.viewport ? `viewport: ${c.alias}_meta.viewport` : null,\n meta.writes.charset || meta.writes.viewport ? `writes: ${JSON.stringify(meta.writes)}` : null,\n ].filter(Boolean);\n\n metaEntries.push(\n ` ${JSON.stringify(c.name)}: { ${fields.join(\", \")} },`,\n );\n }\n\n if (hasStaticParams(c.absPath)) {\n // The namespace import may already be in place for metadata; a second\n // one of the same module is the same binding, so this is safe to repeat.\n imports.push(\n `import * as ${c.alias}_params from ${JSON.stringify(c.absPath)}`,\n );\n paramEntries.push(\n ` ${JSON.stringify(c.name)}: ${c.alias}_params.generateStaticParams,`,\n );\n }\n\n const urlSchemas = urlSchemaExports(c.absPath);\n\n if (urlSchemas.params || urlSchemas.searchParams) {\n imports.push(\n `import * as ${c.alias}_schema from ${JSON.stringify(c.absPath)}`,\n );\n\n const fields = [\n urlSchemas.params ? `params: ${c.alias}_schema.params` : null,\n urlSchemas.searchParams\n ? `searchParams: ${c.alias}_schema.searchParams`\n : null,\n ].filter(Boolean);\n\n schemaEntries.push(\n ` ${JSON.stringify(c.name)}: { ${fields.join(\", \")} },`,\n );\n }\n }\n\n // The engine's own modules are named without an extension: this plugin runs\n // from src/ in its own repo and from dist/ once published, and Vite resolves\n // either. Naming .tsx here builds fine from source and fails after publish.\n return `// GENERATED by rscKit() — do not edit.\n${\n // First, before any page: an import's side effects run in import order,\n // and a package configured here has to be configured before a page module\n // that reads it at evaluation time.\n instrumentation?.hasRegister\n ? `import * as __instrumentation from ${JSON.stringify(instrumentation.file)}`\n : instrumentation\n ? `import ${JSON.stringify(instrumentation.file)}\\nconst __instrumentation: { register?: () => unknown } = {}`\n : \"const __instrumentation: { register?: () => unknown } = {}\"\n}\nimport { SegmentBoundary } from ${JSON.stringify(join(packageDir, \"js/SegmentBoundary\"))}\nimport { LoadingBoundary } from ${JSON.stringify(join(packageDir, \"js/LoadingBoundary\"))}\nimport { DocumentTitle } from ${JSON.stringify(join(packageDir, \"js/DocumentTitle\"))}\nimport { SlotBoundary } from ${JSON.stringify(join(packageDir, \"js/SlotBoundary\"))}\nimport { RouteErrorBoundary } from ${JSON.stringify(join(packageDir, \"js/RouteErrorBoundary\"))}\nimport { sectionComponent } from ${JSON.stringify(join(packageDir, \"js/section\"))}\nimport { PathnameProvider } from ${JSON.stringify(join(packageDir, \"js/PathnameProvider\"))}\nimport { DefaultRouteError } from ${JSON.stringify(join(packageDir, \"js/DefaultRouteError\"))}\nimport { searchParams as requestSearchParams } from ${JSON.stringify(join(packageDir, \"request\"))}\nimport { parseParams, parseSearchParams, parseBody, isSearchParamsError, isBodyError } from ${JSON.stringify(join(packageDir, \"routeSchema\"))}\nimport { notFoundDigest, isNotFoundSignal } from ${JSON.stringify(join(packageDir, \"notFound\"))}\nimport { noteRequestRead, urlOf } from ${JSON.stringify(join(packageDir, \"request\"))}\nimport { redirectDigest } from ${JSON.stringify(join(packageDir, \"redirectDigest\"))}\nimport { createRscHandler } from ${JSON.stringify(join(packageDir, \"host\"))}\nimport { httpHostCalls } from ${JSON.stringify(join(packageDir, \"hostCalls\"))}\nimport { prerenderedBeside } from ${JSON.stringify(join(packageDir, \"files\"))}\nimport { renderToReadableStream, decodeReply, decodeAction, decodeFormState, loadServerAction } from '@vitejs/plugin-rsc/rsc'\nimport { isQuery, queryCacheControl, isQueryValidationError } from ${JSON.stringify(join(packageDir, \"query\"))}\nimport { isActionValidationError, isClientBuilt } from ${JSON.stringify(join(packageDir, \"action\"))}\nimport { noteFallback as noteCaughtRead } from ${JSON.stringify(join(packageDir, \"request\"))}\nimport { isOutdatedOptimizedDep, outdatedDepResponse } from ${JSON.stringify(join(packageDir, \"devReload\"))}\nimport { sharedDepth } from ${JSON.stringify(join(packageDir, \"routing\"))}\nimport { Suspense, createElement, Fragment } from 'react'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n${imports.join(\"\\n\")}\n\ntype HostFn = (name: string, ...args: unknown[]) => Promise<unknown>\ntype LayoutEntry = { component: string; props?: Record<string, unknown> }\ntype SlotOverride = { component: string; props?: Record<string, unknown> }\n\nconst components: Record<string, any> = {\n${mapEntries.join(\"\\n\")}\n}\n\n/**\n * The url schemas a page exported, by component name.\n *\n * Empty for a page that exported none, which is the common case — the lookup\n * below then hands the url through untouched and costs a property read.\n */\n/**\n * The manifest to link from every page, or null when the app declared none.\n *\n * A literal rather than a define: defines are configured per environment and\n * this is read while rendering, in the rsc one. Generated in, so an app with\n * no manifest carries the word null and no branch worth taking.\n */\n/** Head tags for the icons and share images found in app/. */\nconst APP_HEAD: { tag: any; props: Record<string, string> }[] = ${JSON.stringify(\n headTags(foundAssets),\n )}\n\nconst WEB_MANIFEST: { href: string; themeColor?: string } | null = ${JSON.stringify(\n webManifestOptions\n ? {\n href: MANIFEST_PATH,\n ...(webManifestOptions.themeColor\n ? { themeColor: webManifestOptions.themeColor }\n : {}),\n }\n : null,\n )}\n\nconst urlSchemas: Record<string, { params?: any; searchParams?: any }> = {\n${schemaEntries.join(\"\\n\")}\n}\n\n/** route.ts modules, by the name the manifest matched. */\nconst apiRoutes: Record<string, any> = {\n${apiEntries.join(\"\\n\")}\n}\n\n/**\n * Answer an api route.\n *\n * The handler is handed an ordinary Request and the route params, and whatever\n * Response it returns is the answer. Nothing renders; there is no payload and\n * no client involved.\n *\n * HEAD falls back to GET, which is what the spec says it is — the same response\n * without a body. Answering 405 instead breaks link checkers and anything that\n * probes before it fetches.\n */\n/**\n * A promise that does not start until something awaits it.\n *\n * A thenable rather than a promise for the reason pageSearchParams is one:\n * every handler is handed all three of these whether it reads them or not, and\n * a real promise would run the work - and record the read - for every route on\n * every request.\n */\nfunction lazily<T>(start: () => Promise<T>): Promise<T> {\n let pending: Promise<T> | null = null\n\n const begin = (): Promise<T> => {\n if (!pending) {\n pending = start()\n pending.catch(() => {})\n }\n\n return pending\n }\n\n return {\n then: (ok, fail) => begin().then(ok, fail),\n catch: (fail) => begin().catch(fail),\n finally: (done) => begin().finally(done),\n } as Promise<T>\n}\n\n/** Whether a method may carry a body worth reading. */\nfunction hasBody(method: string): boolean {\n return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE'\n}\n\n/**\n * What an api route answers when its own schema refused the request.\n *\n * Three statuses, because the three failures are three different things and\n * collapsing them would leave a client unable to tell a url that names nothing\n * from one it addressed wrongly:\n *\n * 404 the params do not describe a resource - the url names nothing\n * 400 the query string is wrong - the resource exists, the request did not\n * 422 the body is wrong - the same status an action returns for the same\n * failure, so a client has one shape to handle\n */\nfunction refusedInput(error: unknown): Response {\n const json = (status: number, payload: unknown) =>\n new Response(JSON.stringify(payload), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n\n if (isNotFoundSignal(error)) return json(404, { message: 'Not found' })\n\n if (isSearchParamsError(error)) {\n return json(400, { message: error.message, errors: error.errors })\n }\n\n if (isBodyError(error)) return json(422, { message: error.message, errors: error.errors })\n\n throw error\n}\n\nexport async function handleApiRoute(\n name: string,\n request: Request,\n params: Record<string, string>,\n allow: string,\n): Promise<Response> {\n await instrumented()\n applyHost()\n\n const mod = apiRoutes[name]\n const method = request.method\n const handler = mod?.[method] ?? (method === 'HEAD' ? mod?.GET : undefined)\n\n if (!handler) {\n // Allow is not optional on a 405: without it a client cannot tell which\n // methods would have worked, and neither can a person reading the logs.\n return new Response('Method not allowed', { status: 405, headers: { Allow: allow } })\n }\n\n // Awaited by the handler, not before it - the same shape a page's props have,\n // and for more than symmetry. A route that never awaits its query string\n // provably does not vary by it, so the build can store one answer and the\n // host can serve it for any query at all. Resolved eagerly here, that fact\n // is unknowable and every ?utm_source= misses the stored answer.\n //\n // Schemas stay optional per route and per kind. A route that exported none\n // gets the raw params, the URLSearchParams, and a body nobody has read.\n const input = {\n params: lazily(() => parseParams(mod.params, params)),\n searchParams: lazily(() => {\n // Declaring a schema is itself a statement that the query matters, so a\n // route with one is treated as varying by it whether or not the handler\n // reaches for the value.\n noteRequestRead('searchParams')\n\n // Through urlOf, so the build's probe books this read to searchParams\n // rather than to the url - a route reads request.url itself when it\n // wants the query the Next way, and that read is the one that matters.\n return parseSearchParams(mod.searchParams, new URL(urlOf(request)).searchParams)\n }),\n body: hasBody(method) ? lazily(() => parseBody(mod.body, request)) : undefined,\n }\n\n if (mod.searchParams) noteRequestRead('searchParams')\n\n let answer\n try {\n answer = await handler(request, input)\n } catch (error) {\n // A refusal raised by one of the thenables above surfaces here, because the\n // handler awaited it and did not catch it. Anything else is the route's own\n // failure and is left to the caller.\n return refusedInput(error)\n }\n\n // A HEAD answered by GET must not carry a body.\n if (method === 'HEAD' && answer instanceof Response) {\n return new Response(null, { status: answer.status, headers: answer.headers })\n }\n\n return answer\n}\n\nconst metadataMap: Record<string, { static?: any; generate?: (p: any) => any; viewport?: any; writes?: { charset: boolean; viewport: boolean } }> = {\n${metaEntries.join(\"\\n\")}\n}\n\n/**\n * The viewport, in Next's shape: export const viewport on a layout or page,\n * layouts outer to inner then the page, merged per key. What is not set is\n * Next's default - width=device-width, initial-scale=1 - because a layout\n * ported from Next never wrote the tag: Next put it there, and a page with\n * no viewport meta is the desktop layout on a phone, which is how a port\n * found out.\n */\nfunction resolveViewport(component: string, layouts: LayoutEntry[]): Record<string, unknown> {\n const merged: Record<string, unknown> = { width: 'device-width', initialScale: 1 }\n\n for (const l of layouts) Object.assign(merged, metadataMap[l.component]?.viewport ?? {})\n Object.assign(merged, metadataMap[component]?.viewport ?? {})\n\n return merged\n}\n\n/** The content attribute for a viewport object, spelled the way browsers read it. */\nfunction viewportContent(viewport: Record<string, unknown>): string {\n const names: Record<string, string> = {\n width: 'width',\n height: 'height',\n initialScale: 'initial-scale',\n minimumScale: 'minimum-scale',\n maximumScale: 'maximum-scale',\n userScalable: 'user-scalable',\n viewportFit: 'viewport-fit',\n interactiveWidget: 'interactive-widget',\n }\n const parts: string[] = []\n\n for (const [key, name] of Object.entries(names)) {\n const value = viewport[key]\n\n if (value === undefined || value === null) continue\n\n parts.push(name + '=' + (typeof value === 'boolean' ? (value ? 'yes' : 'no') : String(value)))\n }\n\n return parts.join(', ')\n}\n\n/** Whether any file on the route renders the tag itself. */\nfunction routeWrites(component: string, layouts: LayoutEntry[], tag: 'charset' | 'viewport'): boolean {\n return [...layouts.map((l) => l.component), component].some((name) => metadataMap[name]?.writes?.[tag] === true)\n}\n\nconst staticParamsMap: Record<string, () => any> = {\n${paramEntries.join(\"\\n\")}\n}\n\n/**\n * The route table this bundle was built from.\n *\n * Embedded rather than read back from routes.json, so a host cannot pair a\n * fresh bundle with a stale manifest — the two came out of the same build and\n * now cannot be separated. The file is still written, because a host that\n * cannot import a JavaScript module has no other way to read it.\n */\nexport function manifest(): any {\n return ${JSON.stringify(routeManifest())}\n}\n\nlet cachedBuildId: string | null = null\n\n/**\n * What this build's client is, as a short id.\n *\n * Derived from the bootstrap script the document ships - the hashed name of\n * the browser entry, which changes with the client references and chunks\n * it maps - so two builds whose browsers would disagree never share one.\n * The host puts it on every answer and compares it against what a client\n * says it is running; a mismatch on a payload request is a 409, and the\n * client loads the document instead. Read once, on demand, because the\n * bootstrap content is a build product this bundle only reaches at runtime.\n */\nexport async function buildId(): Promise<string> {\n if (cachedBuildId !== null) return cachedBuildId\n\n const content: string = await (import.meta as any).viteRsc.loadBootstrapScriptContent('index')\n let hash = 2166136261\n\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i)\n hash = Math.imul(hash, 16777619) >>> 0\n }\n\n cachedBuildId = hash.toString(16).padStart(8, '0')\n\n return cachedBuildId\n}\n\n/**\n * For each server action id, whether a client built it. The build asks after\n * the bundle exists, because the answer is a mark on the loaded function and\n * nothing static could tell a wrapped export from a bare one.\n */\nexport async function auditActions(ids: string[]): Promise<{ id: string; client: boolean; query: boolean }[]> {\n const out: { id: string; client: boolean; query: boolean }[] = []\n\n for (const id of ids) {\n let fn: unknown = null\n\n try {\n fn = await loadServerAction(id)\n } catch {\n continue\n }\n\n if (typeof fn !== 'function') continue\n\n out.push({ id, client: isClientBuilt(fn), query: isQuery(fn) })\n }\n\n return out\n}\n\n/**\n * The param sets a route declares, or null when it declares none.\n *\n * Null and [] are different answers: no generateStaticParams means the route\n * is rendered on demand, an empty array means the app looked and there is\n * nothing to build. Collapsing them silently prerenders nothing for a route\n * that asked for everything, or the reverse.\n */\nexport async function getStaticParams(component: string): Promise<Record<string, string>[] | null> {\n await instrumented()\n\n const generate = staticParamsMap[component]\n\n if (!generate) return null\n\n return (await generate()) as Record<string, string>[]\n}\n\n// The host installs its callable via installHostFn. The global must be set\n// synchronously INSIDE each render fn (applyHost) right before\n// renderToReadableStream — setting it once ahead of a separate render call does\n// not reach the Flight render.\nconst HOST_GLOBAL = ${JSON.stringify(hostGlobal)}\n\n/**\n * The reserved name a host answers route middleware on.\n *\n * Prefixed so it cannot collide with a function an application registered.\n * A host that has never heard of it answers \"no such function\", which\n * throws — the correct answer for a guarded route on a host that cannot\n * check the guard.\n */\nconst HOST_MIDDLEWARE_FN = '__rsc.middleware'\n\n/**\n * instrumentation.ts's register(), once.\n *\n * On a long-lived server it runs at startup: the entry is evaluated when the\n * process starts, and this begins then, so env that fails validation fails\n * the boot rather than the first visitor, and the first request does not\n * pay for it. On a Worker there is no startup — an isolate is created for a\n * request, and a binding is only readable once one has arrived — so it runs\n * at the first request of each isolate instead. Every entry point awaits it\n * either way, which is what makes \"before the first render\" hold whether the\n * caller is the built server, the dev server or the prerender.\n *\n * A rejection is not memoised. Env that fails validation fails the same way\n * on every request, which is right; a database that was not up yet gets\n * asked again rather than leaving the process permanently refusing. In\n * production a startup failure is reported and the process exits, because a\n * server that could not bootstrap has nothing correct to serve; the dev\n * server stays up and reports it on the page instead.\n */\nlet __instrumented: Promise<void> | null = null\n\nfunction instrumented(): Promise<void> {\n if (!__instrumented) {\n __instrumented = Promise.resolve()\n .then(() => __instrumentation.register?.())\n .then(\n () => undefined,\n (error) => {\n __instrumented = null\n throw error\n },\n )\n }\n\n return __instrumented\n}\n\n// Workers name themselves; nothing else does. Where there is a process to\n// start, start now.\nconst isolateRuntime = typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers'\n\nif (__instrumentation.register && !isolateRuntime) {\n instrumented().catch((error) => {\n console.error('[rsc-kit] instrumentation.ts register() failed:', error)\n\n if (!import.meta.env.DEV && typeof process !== 'undefined' && typeof process.exit === 'function') {\n process.exit(1)\n }\n })\n}\n\nlet currentHost: HostFn | null = null\n\nexport function installHostFn(fn: HostFn) {\n currentHost = fn\n return () => {\n if (currentHost === fn) currentHost = null\n }\n}\n\n/**\n * The probe's stand-in host, for whichever render is asking.\n *\n * Held in async context rather than on the global, because two prerenders\n * running at once each need their own. The previous shape saved the real host,\n * overwrote the global and restored it afterwards — correct for one render at\n * a time and silently wrong for two: the second overwrites the first's saved\n * value, and both pages then call whichever closure assigned last, so\n * usedDynamicApis is recorded against the wrong page and routes are\n * misclassified. Benign for a host that installs none; wrong for any host\n * that does.\n */\nconst probeHost = new AsyncLocalStorage<(...args: unknown[]) => Promise<unknown>>()\n\nfunction applyHost() {\n // A dispatcher, installed once. App code calls a global; which implementation\n // that reaches is a question about the render it is inside.\n //\n ;(globalThis as Record<string, unknown>)[HOST_GLOBAL] = (...args: unknown[]) => {\n const fn = probeHost.getStore() ?? currentHost\n\n // An optional call was here, and it answered every rpc() with undefined\n // when no host was installed. undefined is a value: the component renders\n // with it, the render succeeds, and a prerender freezes the result. The\n // page then hydrates against an undefined prop, the client component reads\n // a property of it, React unmounts the document, and the browser shows a\n // blank page with nothing in the console.\n //\n // No backticks in this region — everything from the generated entry\n // onward is a template literal, and one ends it here.\n // Rejected rather than thrown: rpc() is documented to return a promise, so\n // a caller that stores it before awaiting must get a rejection, not an\n // exception from the call itself.\n if (!fn) {\n return Promise.reject(\n new Error(\n 'No host callable is installed, so ' + String(args[0]) + ' cannot be answered. ' +\n 'A render that needs the host must either run with one installed or be probed.',\n ),\n )\n }\n\n return fn(...args)\n }\n}\n\n/**\n * Which layout renders a given slot.\n *\n * The slot component's own path names the directory that declares it:\n * app/docs/@modal/default is declared in app/docs, and the layout there is the\n * one whose props it belongs in. Falls back to the innermost layout when\n * nothing matches, which is the shape a single-layout app has anyway.\n */\nfunction ownerLayoutIndex(slotComponent: string, layouts: LayoutEntry[]): number {\n const at = slotComponent.indexOf('/@')\n if (at === -1) return layouts.length - 1\n\n const ownerDir = slotComponent.slice(0, at)\n const suffix = '/layout'\n const found = layouts.findIndex(\n (l) => (l.component.endsWith(suffix) ? l.component.slice(0, -suffix.length) : l.component) === ownerDir,\n )\n\n return found === -1 ? layouts.length - 1 : found\n}\n\n/**\n * The query string, prepared for a page that may never ask for it.\n *\n * Created for every render but awaited by almost none, so its rejection has to\n * be claimed here: an unhandled one fails the render of a page that did\n * nothing wrong. Awaiting it still surfaces the real error.\n */\nfunction pageSearchParams(): Promise<URLSearchParams> {\n // Lazy. Every page is handed this whether it reads it or not, and reading the\n // request is what marks a page as needing one — so starting it eagerly told\n // the build that every page was dynamic, and put url() beside every route in\n // the output as though someone had written it.\n //\n // A thenable rather than a promise, so nothing happens until a page awaits.\n let pending: Promise<URLSearchParams> | null = null\n\n const start = (): Promise<URLSearchParams> => {\n if (!pending) {\n pending = requestSearchParams()\n\n // Attached here for the same reason it always was: during a prerender\n // this never settles, and an unobserved rejection ends the process.\n pending.catch(() => {})\n }\n\n return pending\n }\n\n return {\n then: (ok, fail) => start().then(ok, fail),\n catch: (fail) => start().catch(fail),\n finally: (done) => start().finally(done),\n } as Promise<URLSearchParams>\n}\n\n/**\n * A page's params, through its own schema if it exported one.\n *\n * Laziness is preserved on purpose. The params promise may be one that never\n * settles - that is how the prerender probe says \"not for any particular url\"\n * - so this must not await eagerly. Chaining keeps a never-settling promise\n * never-settling, and the schema runs only if the page reads it.\n */\nfunction checkedParams(\n schemas: { params?: any } | undefined,\n params: Promise<Record<string, unknown>>,\n): Promise<unknown> {\n if (!schemas || !schemas.params) return params\n\n return params.then((value) => parseParams(schemas.params, value))\n}\n\n/**\n * A page's query string, through its own schema if it exported one.\n *\n * Wrapped as a thenable rather than chained, so a page that never reads the\n * query still never starts the read - the whole thing pageSearchParams exists\n * to guarantee. Calling .then on it here would start it for every page, and\n * every page would be reported as reading the request.\n */\nfunction checkedSearchParams(\n schemas: { searchParams?: any } | undefined,\n search: Promise<URLSearchParams>,\n): Promise<unknown> {\n if (!schemas || !schemas.searchParams) return search\n\n let pending: Promise<unknown> | null = null\n\n const start = (): Promise<unknown> => {\n if (!pending) {\n pending = search.then((value) => parseSearchParams(schemas.searchParams, value))\n pending.catch(() => {})\n }\n\n return pending\n }\n\n return {\n then: (ok, fail) => start().then(ok, fail),\n catch: (fail) => start().catch(fail),\n finally: (done) => start().finally(done),\n } as Promise<unknown>\n}\n\nlet errorChains: Record<string, string[]> | null = null\n\n/** The error.tsx files above a component, outermost first. */\nfunction errorChain(component: string): string[] {\n if (!errorChains) {\n errorChains = {}\n\n for (const route of manifest().routes as { component: string; errors?: string[] }[]) {\n if (route.errors?.length) errorChains[route.component] = route.errors\n }\n }\n\n return errorChains[component] ?? []\n}\n\n// Composition: layout(outer..inner) > Suspense(loading, innermost-first) > page.\nfunction buildElement(\n component: string,\n props: Record<string, unknown>,\n layouts: LayoutEntry[],\n loadings: string[],\n parallelSlots: Record<string, string>,\n slotOverrides: Record<string, SlotOverride>,\n head: unknown[] = [],\n from = 0,\n pageKey = '',\n bootstrap = true,\n // What await params gives the page. A never-settling one is how the\n // prerender probe says \"not for any particular url\": the page suspends where\n // it reads, everything above it still paints, and that is a shell one file\n // can serve for every url the route matches.\n params: Promise<Record<string, unknown>> = Promise.resolve(props),\n) {\n const Component = components[component]\n if (!Component) throw new Error('Unknown RSC component: ' + component)\n\n // Awaitable rather than spread. Spread, a page reads its slug synchronously\n // and renders to completion during the probe — producing a page about an\n // invented value, right for nothing — which is why such a route could only\n // ever be rendered per request.\n const schemas = urlSchemas[component]\n\n let element = createElement(Component, {\n params: checkedParams(schemas, params),\n searchParams: checkedSearchParams(schemas, pageSearchParams()),\n })\n\n // Through LoadingBoundary when the runtime is shipped, so a server render\n // can tell the engine's boundary from one the developer wrote by name -\n // see that file. A page shipping no runtime gets a plain Suspense: a\n // client component would drag React in for a wrapper nothing can use.\n for (let i = loadings.length - 1; i >= 0; i--) {\n const Loading = components[loadings[i]]\n const fallback = Loading ? createElement(Loading) : null\n\n element = bootstrap\n ? createElement(LoadingBoundary, { fallback }, element)\n : createElement(Suspense, { fallback }, element)\n }\n\n // Outside the Suspense boundary, innermost first — the nearest error.tsx to\n // the failure answers, the same rule loading.tsx follows. Outside, so a\n // component that throws while its fallback is showing is still caught.\n //\n // Read from the route table rather than passed in, for the same reason the\n // middleware chain is: every render path is covered by construction, and no\n // caller has to remember to forward them.\n const errors = errorChain(component)\n\n for (let i = errors.length - 1; i >= 0; i--) {\n const Fallback = components[errors[i]]\n\n if (!Fallback) continue\n\n element = createElement(\n RouteErrorBoundary,\n { fallback: Fallback as never, resetKey: pageKey || component },\n element,\n )\n }\n\n // Outermost, for a throw no error.tsx covers - including one in a layout,\n // which the boundary inside that layout cannot see. Without it React\n // unmounted the document on hydration: a black page with the cause nowhere\n // near it. Only with the runtime: it is a client component, and a route\n // shipping none has nothing to catch with.\n if (bootstrap) {\n element = createElement(\n RouteErrorBoundary,\n { fallback: DefaultRouteError as never, resetKey: pageKey || component },\n element,\n )\n }\n\n // <title>/<meta> go OUTSIDE the Suspense boundaries so they reach the shell\n // immediately — inside, they would be withheld until the page's data\n // resolves, delaying the whole document on a slow page.\n if (head.length) element = createElement(Fragment, null, ...head, element)\n\n // A slot belongs to the layout in the directory that declares it, which is\n // not necessarily the innermost one: slots are collected by walking up from\n // the page to the app root. Handing every slot to the innermost layout drops\n // any the innermost does not declare, silently — the page renders, the modal\n // just never appears.\n const slotsByLayout = new Map<number, Record<string, unknown>>()\n\n for (const [slot, value] of Object.entries(parallelSlots)) {\n const override = slotOverrides[slot]\n let rendered: unknown = null\n\n // Slot components are pages too — an interceptor is a page in a slot — so\n // they get the same awaitables the page does rather than spread values.\n if (override) {\n const OverrideComp = components[override.component]\n rendered = OverrideComp\n ? createElement(OverrideComp, {\n params: Promise.resolve(override.props ?? {}),\n searchParams: pageSearchParams(),\n })\n : null\n } else {\n const SlotComp = components[value]\n rendered = SlotComp\n ? createElement(SlotComp, { params, searchParams: pageSearchParams() })\n : null\n }\n\n const owner = ownerLayoutIndex(value, layouts)\n if (owner < from) continue\n\n const bucket = slotsByLayout.get(owner) ?? {}\n // Wrapped so an action can put a re-rendered slot here without the page\n // around it being asked for again. With nothing stored the boundary\n // renders exactly what is passed, so this changes nothing on its own.\n bucket[slot] = bootstrap ? createElement(SlotBoundary, { name: slot }, rendered) : rendered\n slotsByLayout.set(owner, bucket)\n }\n\n // Indices stay absolute: from skips the layouts the client already has\n // mounted, so slot ownership and boundary depth mean the same thing whether\n // this is a whole document or one segment of it.\n for (let i = layouts.length - 1; i >= from; i--) {\n const Layout = components[layouts[i].component]\n if (!Layout) continue\n\n // The seam a navigation can replace on its own. Depth counts from the\n // outermost layout, so depth 1 is everything below the root layout and the\n // deepest boundary wraps the page alone. With nothing in the client store\n // these render their children unchanged.\n //\n // It is a client component, so a route shipping no runtime must not get\n // one — otherwise every page would drag React in for a seam nothing can\n // use, and no page could ever be JS-free.\n if (bootstrap) {\n element = createElement(SegmentBoundary, { depth: i + 1, pageKey }, element)\n }\n\n element = createElement(Layout, {\n ...(layouts[i].props ?? {}),\n ...(slotsByLayout.get(i) ?? {}),\n children: element,\n })\n }\n\n // The url the client hooks answer with during a server render. Outside the\n // boundaries, so a page keeps it across a partial navigation; omitted with\n // the runtime, since a route shipping none has nothing to read it.\n if (bootstrap && pageKey) {\n element = createElement(PathnameProvider, { value: pageKey }, element)\n }\n\n return element\n}\n\n// Resolve route metadata into React elements. React 19 hoists <title>/<meta>\n// rendered anywhere in the tree into <head> — so the \"vite way\" for metadata is\n// to render it as elements, rather than a backend injecting a <head> string.\nasync function renderTree(\n component: string,\n props: Record<string, unknown>,\n layouts: LayoutEntry[],\n loadings: string[],\n parallelSlots: Record<string, string>,\n slotOverrides: Record<string, SlotOverride>,\n from = 0,\n pageKey = '',\n bootstrap = true,\n params?: Promise<Record<string, unknown>>,\n) {\n // The FULL chain, always: a title template lives on an outer layout, and a\n // partial render still has to produce the same <title> the whole document\n // would have.\n const md = await resolveMetadata(component, props, layouts)\n const head: unknown[] = []\n\n // Rendered into the tree rather than written into the app's layout: React\n // hoists a link and a meta into <head> from anywhere, so this works for an\n // app that already has a layout and never asks anyone to edit one. The\n // engine knows the manifest exists; the app should not have to.\n // Icons and share images the build found in app/. Rendered here so React\n // hoists them into <head>, the same way the manifest link is — an app never\n // edits its layout to get a favicon.\n // Where the site lives, for making a relative image or url absolute. Read\n // here, above the found images, because those are the ones most likely to\n // be relative: an opengraph-image.png in app/ is emitted as /_app/..., and a\n // share-card scraper needs the origin in front of it.\n const base = md?.metadataBase ? String(md.metadataBase) : null\n const absolute = (value: unknown): string => {\n const text = String(value instanceof URL ? value.href : value)\n\n if (!base || /^[a-z][a-z0-9+.-]*:/i.test(text)) return text\n\n return new URL(text, base).href\n }\n\n // What Next wrote into every document without being asked, and a layout\n // copied from a Next app therefore never writes: the charset, and the\n // viewport - without which a phone lays the page out at desktop width.\n // Rendered unless a file on the route renders the tag itself.\n if (!routeWrites(component, layouts, 'charset')) head.push(createElement('meta', { key: '__cs', charSet: 'utf-8' }))\n\n const viewport = resolveViewport(component, layouts)\n\n if (!routeWrites(component, layouts, 'viewport')) {\n head.push(createElement('meta', { key: '__vp', name: 'viewport', content: viewportContent(viewport) }))\n }\n\n // themeColor and colorScheme live on the viewport export in Next, and one\n // set there wins over the web manifest's colour below.\n const themeColors = viewport.themeColor as string | { media?: string; color: string }[] | undefined\n\n if (typeof themeColors === 'string') {\n head.push(createElement('meta', { key: '__vtc', name: 'theme-color', content: themeColors }))\n } else if (Array.isArray(themeColors)) {\n for (const [i, entry] of themeColors.entries()) {\n head.push(createElement('meta', { key: '__vtc' + i, name: 'theme-color', content: entry.color, ...(entry.media ? { media: entry.media } : {}) }))\n }\n }\n if (typeof viewport.colorScheme === 'string') {\n head.push(createElement('meta', { key: '__vcs', name: 'color-scheme', content: viewport.colorScheme }))\n }\n\n for (const [i, found] of APP_HEAD.entries()) {\n const props = { ...found.props }\n\n if (props.content && /^(og:image|twitter:image)$/.test(props.property ?? props.name ?? '')) {\n props.content = absolute(props.content)\n }\n\n head.push(createElement(found.tag, { key: '__a' + i, ...props }))\n }\n\n if (WEB_MANIFEST) {\n head.push(createElement('link', { key: '__mf', rel: 'manifest', href: WEB_MANIFEST.href }))\n\n if (WEB_MANIFEST.themeColor && themeColors === undefined) {\n head.push(\n createElement('meta', { key: '__tc', name: 'theme-color', content: WEB_MANIFEST.themeColor }),\n )\n }\n }\n\n if (md) {\n if (md.title != null) {\n // The element is what a server render puts in <head>, and what a route\n // with no runtime relies on entirely.\n head.push(createElement('title', { key: '__t' }, String(md.title)))\n\n // And the effect is what keeps it right once pages are retained — see\n // DocumentTitle. Only where there is a runtime to run it: a client\n // component on a route that ships none is refused by the build.\n if (bootstrap) head.push(createElement(DocumentTitle, { key: '__ts', title: String(md.title) }))\n }\n if (md.description != null) head.push(createElement('meta', { key: '__d', name: 'description', content: String(md.description) }))\n // The name only, never the version - see the identify option.\n if (manifest().build?.identify) head.push(createElement('meta', { key: '__g', name: 'generator', content: 'rsc-kit' }))\n }\n\n // Which build this document is, for the client to say on every navigation\n // - read from the document rather than learned from the first answer,\n // because a document a service worker served from its cache is the last\n // build's while the answers are this one's. An id, not a version number.\n if (bootstrap) head.push(createElement('meta', { key: '__v', name: 'rsc-kit:build', content: await buildId() }))\n\n if (md) {\n\n // robots is a string, or the object Next takes: index and follow as\n // their no- forms, the flags by name, the limits as name:value. googleBot\n // is the same shape for the googlebot tag. The object used to fall\n // through to the catch-all below as \"[object Object]\" - which no crawler\n // reads, on the one page that asked not to be indexed.\n const robotsContent = (value: unknown): string => {\n if (typeof value !== 'object' || value === null) return String(value)\n\n const r = value as Record<string, unknown>\n const parts: string[] = []\n\n if (r.index != null) parts.push(r.index ? 'index' : 'noindex')\n if (r.follow != null) parts.push(r.follow ? 'follow' : 'nofollow')\n for (const flag of ['noarchive', 'nosnippet', 'noimageindex', 'nocache', 'notranslate', 'indexifembedded', 'nositelinkssearchbox']) {\n if (r[flag]) parts.push(flag)\n }\n if (r.unavailable_after != null) parts.push('unavailable_after: ' + String(r.unavailable_after))\n for (const limit of ['max-video-preview', 'max-image-preview', 'max-snippet']) {\n if (r[limit] != null) parts.push(limit + ':' + String(r[limit]))\n }\n\n return parts.join(', ')\n }\n\n if (md.robots != null) {\n head.push(createElement('meta', { key: '__r', name: 'robots', content: robotsContent(md.robots) }))\n\n const bot = typeof md.robots === 'object' ? (md.robots as { googleBot?: unknown }).googleBot : null\n\n if (bot != null) head.push(createElement('meta', { key: '__rg', name: 'googlebot', content: robotsContent(bot) }))\n }\n\n // og: and its relatives are PROPERTY, not name. Facebook's scraper - and\n // Slack's, and LinkedIn's - reads only property=, so every og tag this\n // used to emit with name= was invisible to the thing it existed for.\n // Twitter reads name=, which is why the two are not one rule.\n const isProperty = (k: string) => /^(og|article|profile|book|music|video|fb):/.test(k)\n // The keys whose CONTENT is a url. Exact, plus the :url and :secure_url\n // spellings - not og:image:width, which a looser match turned into\n // https://site/1200 and no scraper would ever read.\n const isUrlKey = (k: string) => /^(og:image|og:url|twitter:image)(:(secure_)?url)?$/.test(k)\n const tag = (k: string, v: unknown) =>\n createElement('meta', {\n key: '__m_' + k + '_' + String(v).slice(0, 40),\n [isProperty(k) ? 'property' : 'name']: k,\n content: isUrlKey(k) ? absolute(v) : String(v),\n })\n\n // One image, or several. Each becomes its own og:image plus the size and\n // alt tags beside it, which is how a scraper is told which is which.\n const images = (prefix: string, value: unknown): void => {\n const list = Array.isArray(value) ? value : [value]\n\n for (const item of list) {\n if (item == null) continue\n\n if (typeof item === 'object' && !(item instanceof URL)) {\n const image = item as { url: unknown; width?: number; height?: number; alt?: string; type?: string }\n\n head.push(tag(prefix, image.url))\n if (image.width) head.push(tag(prefix + ':width', image.width))\n if (image.height) head.push(tag(prefix + ':height', image.height))\n if (image.alt) head.push(tag(prefix + ':alt', image.alt))\n if (image.type) head.push(tag(prefix + ':type', image.type))\n } else {\n head.push(tag(prefix, item))\n }\n }\n }\n\n if (md.openGraph) {\n const og = md.openGraph as Record<string, unknown>\n\n if (og.title != null) head.push(tag('og:title', og.title))\n if (og.description != null) head.push(tag('og:description', og.description))\n if (og.url != null) head.push(tag('og:url', og.url))\n if (og.siteName != null) head.push(tag('og:site_name', og.siteName))\n if (og.type != null) head.push(tag('og:type', og.type))\n if (og.locale != null) head.push(tag('og:locale', og.locale))\n if (og.images != null) images('og:image', og.images)\n }\n\n if (md.twitter) {\n const tw = md.twitter as Record<string, unknown>\n\n if (tw.card != null) head.push(tag('twitter:card', tw.card))\n if (tw.title != null) head.push(tag('twitter:title', tw.title))\n if (tw.description != null) head.push(tag('twitter:description', tw.description))\n if (tw.site != null) head.push(tag('twitter:site', tw.site))\n if (tw.creator != null) head.push(tag('twitter:creator', tw.creator))\n if (tw.images != null) images('twitter:image', tw.images)\n }\n\n // icons is links, not meta. A string is one icon; an object names which\n // rel each is for. The ones found in app/ are already in APP_HEAD above,\n // so this is for an app that wants to say it explicitly.\n const links = (rel: string, value: unknown): void => {\n const list = Array.isArray(value) ? value : [value]\n\n for (const item of list) {\n if (item == null) continue\n\n const icon = typeof item === 'object' && !(item instanceof URL)\n ? (item as Record<string, unknown>)\n : { url: item }\n\n head.push(\n createElement('link', {\n key: '__i_' + rel + '_' + String(icon.url).slice(0, 40),\n rel: (icon.rel as string) ?? rel,\n href: absolute(icon.url),\n ...(icon.type ? { type: icon.type } : {}),\n ...(icon.sizes ? { sizes: icon.sizes } : {}),\n ...(icon.media ? { media: icon.media } : {}),\n }),\n )\n }\n }\n\n if (md.icons != null) {\n const icons = md.icons as Record<string, unknown> | string | unknown[]\n\n if (typeof icons === 'string' || Array.isArray(icons) || icons instanceof URL) {\n links('icon', icons)\n } else {\n if (icons.icon != null) links('icon', icons.icon)\n if (icons.apple != null) links('apple-touch-icon', icons.apple)\n if (icons.shortcut != null) links('shortcut icon', icons.shortcut)\n if (icons.other != null) links('icon', icons.other)\n }\n }\n\n // other is flattened in beside the named keys, because it is a place to put\n // meta tags rather than a meta tag by that name. A key at the top level\n // still renders - the type no longer invites one, but an app written\n // against the old shape must not silently lose its tags.\n const structured = new Set(['title', 'description', 'robots', 'metadataBase', 'openGraph', 'twitter', 'icons', 'other'])\n const named = Object.entries(md).filter(([k]) => !structured.has(k))\n const extra = Object.entries((md.other ?? {}) as Record<string, unknown>)\n\n for (const [k, v] of [...named, ...extra]) {\n if (v == null) continue\n\n if (Array.isArray(v)) {\n for (const item of v) head.push(tag(k, item))\n } else {\n head.push(tag(k, v))\n }\n }\n }\n\n // Metadata elements are rendered INSIDE the document tree so React 19 hoists\n // <title>/<meta> into <head> (hoisting only works from within the tree).\n return buildElement(component, props, layouts, loadings, parallelSlots, slotOverrides, head, from, pageKey, bootstrap, params)\n}\n\n/**\n * The shallowest layout this render must actually produce.\n *\n * An interceptor replaces a slot on the layout that declares it. If that layout\n * is one the client already has, a partial render would never reach it and the\n * modal would silently not appear — so the render is widened to include it.\n */\nfunction segmentStart(\n from: number,\n layouts: LayoutEntry[],\n parallelSlots: Record<string, string>,\n slotOverrides: Record<string, SlotOverride>,\n): number {\n let start = from\n\n for (const slot of Object.keys(slotOverrides)) {\n const declared = parallelSlots[slot]\n if (!declared) continue\n\n const owner = ownerLayoutIndex(declared, layouts)\n if (owner < start) start = owner\n }\n\n return start\n}\n\n/**\n * Run a route's middleware before anything at or below them is rendered.\n *\n * A guard is middleware.ts in a directory: a function that returns nothing and\n * refuses by redirecting or throwing. It exists because a check is not UI, and\n * making it one was the problem — a layout that checks who you are is also a\n * layout that fetches a nav bar, and the two have opposite needs.\n *\n * Layouts are skipped on a partial navigation, which is the whole point of\n * partial navigation, and the client decides how many to skip by naming what\n * it claims to hold. Nothing verifies that claim; nothing can. So a check that\n * lives in a layout is a check the caller can decline. Forcing the layout to\n * run instead makes every navigation pay for its data fetching to re-run a\n * check that costs one query.\n *\n * Guards are not part of that arithmetic. Every render path runs the whole\n * chain, in order, outermost first — a full load, a partial navigation, a\n * revalidation, an interception. There is no marker to forget: the file is the\n * declaration.\n */\nlet middlewareChains: Record<string, string[]> | null = null\n\nlet hostChains: Record<string, string[]> | null = null\n\n/**\n * Guards the host runs, named by a route.ts and meaningless here.\n *\n * Asked before the engine's own middleware.ts guards, because a host's are the\n * coarser check — a session, a rate limit — and running application code to\n * decide whether application code may run is the wrong way round.\n *\n * It fails CLOSED, and that is the whole of its design. This call reaches\n * another process over a network, so it can time out, be refused, or answer\n * something unparseable — and every one of those is a guarded page rendered to\n * whoever asked, if the absence of a refusal is read as permission. Only a\n * literal true allows.\n */\nasync function runHostMiddleware(component) {\n if (!hostChains) {\n hostChains = {}\n\n for (const route of manifest().routes) {\n if (route.hostMiddleware?.length) hostChains[route.component] = route.hostMiddleware\n }\n }\n\n const names = hostChains[component] ?? []\n\n if (names.length === 0) return\n\n if (!currentHost) {\n throw new Error(\n 'Route ' + component + ' declares host middleware (' + names.join(', ') +\n ') but no host callable is installed, so it cannot be checked.',\n )\n }\n\n const answer = await currentHost(HOST_MIDDLEWARE_FN, names)\n\n // Anything other than a literal true. A host answering null, undefined, a\n // string, or an object it happened to build on the way to an error is not\n // saying yes.\n if (answer !== true) {\n throw new Error('Host middleware refused ' + component + ' (' + names.join(', ') + ').')\n }\n}\n\n\nasync function runMiddleware(component: string, props: Record<string, unknown> = {}): Promise<void> {\n await runHostMiddleware(component)\n\n // Read from the route table rather than passed in, so every render path is\n // covered by construction and no host has to remember to forward them.\n if (!middlewareChains) {\n middlewareChains = {}\n\n for (const route of manifest().routes as { component: string; middleware?: string[] }[]) {\n if (route.middleware?.length) middlewareChains[route.component] = route.middleware\n }\n\n // Api routes too. They are keyed by the module name rather than a\n // component, but the chain above them is the same one the pages beside\n // them run.\n for (const api of (manifest().apis ?? []) as { name: string; middleware?: string[] }[]) {\n if (api.middleware?.length) middlewareChains[api.name] = api.middleware\n }\n }\n\n for (const name of middlewareChains[component] ?? []) {\n const guard = components[name]\n\n // A declared guard that is not in the bundle is not \"no guard\" — it is a\n // check that silently does not happen, which is the same reasoning the\n // host applies when the engine cannot run middleware at all. Currently\n // unreachable, because the chain and the component map come from one\n // discovery pass; it is one refactor away from being reachable, and this\n // is the place that has to fail closed.\n if (!guard) {\n throw new Error(\n 'Route middleware ' + name + ' is declared for ' + component + ' but is not in the bundle.',\n )\n }\n\n // Sequential and awaited, outermost first: an outer guard refusing means\n // the inner one should never have been asked. A directory may declare\n // several as a list - reused checks imported from one place - and they\n // run in the order written, stopping at the first refusal.\n for (const check of Array.isArray(guard) ? guard : [guard]) {\n if (typeof check !== 'function') {\n throw new Error(\n 'Route middleware ' + name + ' exports something that is not a function or a list of them.',\n )\n }\n\n await check(props)\n }\n }\n}\n\n// SPA-navigation Flight stream (worker: rsc-stream).\n/**\n * Run a route's middleware without rendering anything.\n *\n * For a host serving a page it did not render: a frozen page is read from disk\n * and never touches the engine, so the check has to be asked for. Refusing\n * throws, exactly as it does mid-render.\n */\nexport async function runRouteMiddleware(component: string, props: Record<string, unknown> = {}): Promise<void> {\n await instrumented()\n applyHost()\n\n return runMiddleware(component, props)\n}\n\nexport async function handleRscStream(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n from = 0,\n pageKey = '',\n): Promise<{ stream: ReadableStream; clientChunks: unknown; segmentDepth: number }> {\n await instrumented()\n applyHost()\n\n // The host proposes how much the client already has; the engine decides what\n // is actually safe to skip and reports back what it rendered.\n const start = segmentStart(from, layouts, parallelSlots, slotOverrides)\n\n // Before anything below them is rendered, never after.\n await runMiddleware(component, props)\n\n return {\n stream: renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, start, pageKey),\n { onError: flightOnError },\n ),\n clientChunks: {},\n segmentDepth: start,\n }\n}\n\n/**\n * The digest React sends to the client in place of a server error's message.\n *\n * A redirect thrown after the shell has flushed has no header left to travel\n * in — the status line is already sent. React transmits a digest for every\n * server error, in production as well as development, so the destination\n * rides there and the client's boundary performs it.\n *\n * redirectDigest is imported by the generated entry, at the top of this\n * template. An import added to this file instead compiles and bundles without\n * complaint, and then throws at render time against a name that is not there.\n *\n * Returning undefined leaves React's own behaviour alone for everything else.\n */\nfunction flightOnError(error: unknown): string | undefined {\n const digest = redirectDigest(error) ?? notFoundDigest(error)\n\n if (digest) return digest\n\n console.error('[rsc-kit]', error)\n\n return undefined\n}\n\n// Initial-load HTML stream + hydration payload (worker: rsc-html-stream).\nexport async function handleRscHtmlStream(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n nonce?: string,\n pageKey = '',\n bootstrap = true,\n): Promise<{ htmlStream: ReadableStream; rscPayloadPromise: Promise<string>; clientChunks: unknown }> {\n await instrumented()\n applyHost()\n await runMiddleware(component, props)\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, 0, pageKey, bootstrap),\n { onError: flightOnError },\n )\n const [forHtml, forPayload] = flight.tee()\n const rscPayloadPromise = new Response(forPayload).text()\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsr(forHtml, nonce, undefined, bootstrap)\n return { htmlStream, rscPayloadPromise, clientChunks: {} }\n}\n\n/**\n * A form posted to the page before the page had a runtime.\n *\n * React writes the action's id into the form it emits for a server action,\n * so a browser with no javascript yet - or none at all - posts the fields\n * to the page's own url. The action runs from those fields, exactly as it\n * would have been called, and the page renders afterwards with what it\n * returned as React's form state: a useActionState form shows its result,\n * a redirect() thrown by the action leaves through the scope the way a\n * page's would, and a cookie it set is on the answer.\n */\nexport async function handleRscFormPost(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n nonce?: string,\n pageKey = '',\n bootstrap = true,\n formData: FormData = new FormData(),\n): Promise<{ htmlStream: ReadableStream }> {\n await instrumented()\n applyHost()\n await runMiddleware(component, props)\n\n // The function the form named, bound to what it posted. Nothing named -\n // a plain form posted here by mistake - and the page simply renders.\n const action = await decodeAction(formData)\n let formState: unknown\n\n if (action) {\n const result = await action()\n\n formState = await decodeFormState(result, formData)\n }\n\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, 0, pageKey, bootstrap),\n { onError: flightOnError },\n )\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsr(flight, nonce, undefined, bootstrap, formState)\n\n return { htmlStream }\n}\n\n/**\n * Finish a shell that was frozen at build time.\n *\n * The render is an ordinary one — real host, real data, middleware included —\n * and the postponed state decides what of it actually reaches the wire. React\n * skips everything the shell already emitted and writes only the boundaries it\n * could not finish then.\n *\n * bootstrap is deliberately false. The shell shipped the bootstrap script; a\n * second one would boot the client runtime twice.\n */\nexport async function handleRscResume(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n postponed: unknown = null,\n nonce?: string,\n pageKey = '',\n): Promise<{ htmlStream: ReadableStream }> {\n await instrumented()\n applyHost()\n await runMiddleware(component, props)\n\n // The tree must be shaped exactly as it was when the shell was frozen, or\n // React cannot line the resumed segments up with the slots left for them:\n //\n // Couldn't find all resumable slots by key/index during replaying.\n // The tree doesn't match so React will fallback to client rendering.\n //\n // Hence \\`true\\` here rather than false. It reads like it would emit a second\n // bootstrap script, and it does not — resume() takes no bootstrap content at\n // all, so the shell's remains the only one. What this flag actually decides\n // is whether the tree carries its SegmentBoundary, and the shell's did.\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, 0, pageKey, true),\n { onError: flightOnError },\n )\n\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsrResume(flight, postponed, nonce)\n\n return { htmlStream }\n}\n\n// Server action (worker: rsc-action).\n/** The page an action was invoked from, so what it invalidated can be rendered. */\ninterface PageContext {\n component: string\n props: Record<string, unknown>\n layouts: LayoutEntry[]\n loadings: string[]\n parallelSlots: Record<string, string>\n /**\n * The sections this route declares, which is what bounds a revalidate.\n *\n * Optional only because a host built against an older manifest may not send\n * it; absent, no named section can be revalidated at all. Refusing is the\n * safe reading — the alternative is the registry, which holds every section\n * in the app.\n */\n sections?: string[]\n}\n\n/**\n * Render one thing an action said it invalidated.\n *\n * 'all' the whole document, layouts included\n * 'page' everything below the layouts, which stay as they are\n * <slot> a single parallel slot, by the name its directory gave it\n *\n * A slot is the only unit smaller than a page the server can name, which is\n * why two tables have to be slots to be refreshed apart from each other.\n */\nasync function renderRevalidated(target: string, page: PageContext): Promise<unknown> {\n // Every target below 'all' renders without the layout chain above it, which\n // is the same skip a navigation performs and needs the same guard run.\n await runMiddleware(page.component, page.props)\n\n if (target === 'all' || target === 'page') {\n return renderTree(\n page.component,\n page.props,\n page.layouts,\n page.loadings,\n page.parallelSlots,\n {},\n target === 'all' ? 0 : page.layouts.length,\n '',\n )\n }\n\n // A named region first: it is the lighter of the two, and the one a page\n // reaches for when it only wants part of itself refreshed.\n //\n // Scoped to the sections this route declares. The registry is a module-level\n // map keyed by name, and the generated entry imports every component in the\n // app eagerly, so a name-keyed registry holds every section in the app by the\n // time a request arrives — and two pages may legitimately both call theirs\n // 'stats', where the last one loaded wins.\n //\n // So the target is resolved through the module this route declares, not\n // through a shared map: the manifest says which section files belong to this\n // page, the components map turns one into its module, and section() left the\n // unwrapped component on the export. Identity, rather than string matching.\n //\n // Read from the manifest rather than from the message. The host is not the\n // adversary here, but the route table is build-time truth and already in this\n // bundle, so there is no reason to depend on a field a host has to remember\n // to send — one that forgot would be silently unprotected.\n const owner = manifest().routes.find((route: any) => route.component === page.component)\n const declared: string[] = owner?.sections ?? page.sections ?? []\n\n // A target of orders names the file app/ledger/orders.section. Matched on\n // that stem, so a target cannot reach a sibling by suffix.\n const path = declared.find((name: string) => name.split('/').pop() === target + '.section')\n const Section = path ? sectionComponent(components[path]) : undefined\n\n // No throw here: the target may be a slot, which the branch below resolves.\n // A name that is a section of some *other* page simply does not match, falls\n // through, and is refused there — where the error can name both kinds.\n\n if (Section) {\n // The component, not the wrapper section() returned. The client replaces\n // what is inside the boundary, so sending the wrapper would nest a new\n // boundary inside the old one on every refresh.\n return createElement(Section, page.props)\n }\n\n // hasOwn, so a target of __proto__ or constructor names nothing.\n const slotComponent = Object.hasOwn(page.parallelSlots, target)\n ? page.parallelSlots[target]\n : undefined\n\n if (!slotComponent) {\n throw new Error(\n 'Cannot revalidate ' + target + ': no section or slot of this page by that name. ' +\n 'Sections: ' +\n (declared.map((n: string) => n.split('/').pop()!.replace('.section', '')).join(', ') ||\n 'none') +\n '. Slots: ' +\n (Object.keys(page.parallelSlots).join(', ') || 'none'),\n )\n }\n\n const SlotComp = components[slotComponent]\n\n if (!SlotComp) throw new Error('Unknown RSC component: ' + slotComponent)\n\n return createElement(SlotComp, {\n params: Promise.resolve(page.props),\n searchParams: pageSearchParams(),\n })\n}\n\n/**\n * Answer one read.\n *\n * Only functions declared with query() are reachable. The id comes off the url,\n * and every registered server action has one — without the mark, this address\n * would invoke mutations over GET, for anyone who can fetch it.\n */\nexport async function handleQuery(\n id: string,\n args: string,\n report?: (error: unknown) => string,\n): Promise<\n | { stream: ReadableStream; cacheControl: string }\n | { status: number; message: string; errors?: Record<string, string[]> }\n | null\n> {\n await instrumented()\n applyHost()\n\n let fn: unknown\n\n try {\n fn = await loadServerAction(id)\n } catch {\n return null\n }\n\n // Null for both, deliberately. Saying \"that exists but is not a query\" tells\n // whoever is probing this endpoint which ids are real actions, and the ids\n // are stable across a build.\n if (!isQuery(fn)) return null\n\n const decoded = (await decodeReply(args)) as unknown[]\n\n // Awaited here rather than handed to the renderer as a promise, so a refusal\n // is still a status line rather than an error row inside a 200. React strips\n // a thrown message in production, so a query that rejected mid-stream would\n // reach the browser as \"an error occurred\" with the fields gone.\n let result: unknown\n\n try {\n result = await (fn as (...a: unknown[]) => unknown)(...decoded)\n } catch (error) {\n if (isQueryValidationError(error)) {\n return { status: 422, errors: error.errors, message: error.message }\n }\n\n return { status: 500, message: report ? report(error) : 'Query failed.' }\n }\n\n return {\n stream: renderToReadableStream(result, {\n onError: (error: unknown) => (report ? report(error) : 'Query failed.'),\n }),\n cacheControl: queryCacheControl(fn),\n }\n}\n\nexport async function handleAction(\n actionId: string,\n body: string | FormData | Uint8Array,\n contentType = 'text/plain',\n page?: PageContext,\n takeRevalidated?: () => string[],\n): Promise<{ stream: ReadableStream }> {\n await instrumented()\n applyHost()\n\n // Every body arrives as bytes on its own socket frame — an upload because it\n // has to, the rest because the transport does not special-case them. What\n // differs is what they decode to: multipart is FormData, everything else is\n // the text encodeReply produced.\n //\n // Treating only multipart as bytes and leaving the rest empty is a silent\n // failure: the action runs with no arguments at all.\n let decodable: string | FormData\n\n if (typeof body === 'string') {\n decodable = body\n } else if (contentType.includes('multipart/form-data')) {\n decodable = await new Response(body, { headers: { 'Content-Type': contentType } }).formData()\n } else {\n decodable = new TextDecoder().decode(body)\n }\n\n // Checked before decoding, because React's decoder does not fail cleanly on\n // a malformed payload: the parse error is raised inside a chunk nobody\n // awaits, so the promise decodeReply returned never settles. The caller\n // cannot catch that — no try/catch anywhere sees it — and the request hangs\n // while the rejection escapes. On Node, whose default is to exit on an\n // unhandled rejection, that is the whole process, reachable by anyone who\n // can post to the action endpoint.\n //\n // A reply that is not multipart is the JSON model encodeReply produced, so\n // parsing it is both the check and the whole of it.\n if (typeof decodable === 'string') {\n try {\n JSON.parse(decodable)\n } catch {\n throw new Error('Malformed server action body: expected the payload encodeReply produces.')\n }\n }\n\n const args = (await decodeReply(decodable)) as unknown[]\n const action = await loadServerAction(actionId)\n\n // A query reached the ACTION endpoint, which means it was called directly\n // rather than through fetchQuery — so it went out as a POST and none of the\n // reasons it was marked a read apply to it. It still works, which is the\n // problem: nothing else would ever mention it. Only in development, and only\n // a warning, because the call is not wrong, just not what was asked for.\n if (isQuery(action) && import.meta.env?.DEV) {\n console.warn(\n '[rsc-kit] ' + actionId + ' is a query but was called directly, so it was sent as a POST. ' +\n 'Call it through fetchQuery() to send a GET.',\n )\n }\n\n // A plain \"use server\" function that threw fieldErrors() gets the same\n // treatment createActionClient gives its handlers: the throw becomes the\n // returned { validationErrors } that <Form> reads. Left thrown, React\n // serialises the rejection opaquely — production strips the message — and the\n // fields it named never reach the browser.\n let result: unknown\n\n try {\n result = await (action as (...a: unknown[]) => unknown)(...args)\n } catch (error) {\n if (!isActionValidationError(error)) throw error\n\n result = { validationErrors: error.errors }\n }\n\n // Read after the action has run: what it invalidated is only known once its\n // host calls have been made. Rendering here rather than telling the browser\n // to ask is the whole point — the answer carries what went stale with it.\n const targets = takeRevalidated?.() ?? []\n\n if (targets.length === 0 || !page) {\n return { stream: renderToReadableStream(result) }\n }\n\n const revalidated: Record<string, unknown> = {}\n\n for (const target of targets) {\n revalidated[target] = await renderRevalidated(target, page)\n }\n\n // Marked, so an action whose own result happens to be an object with a\n // 'result' key is not mistaken for this envelope.\n return { stream: renderToReadableStream({ __rscRevalidated: revalidated, result }) }\n}\n\nexport async function resolveMetadata(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n): Promise<Record<string, unknown> | null> {\n await instrumented()\n\n const pageEntry = metadataMap[component]\n const page: Record<string, unknown> = pageEntry\n ? (pageEntry.generate\n // The same awaitables the page receives. Resolved rather than\n // suspending, even during the probe: a title has to be produced for\n // the shell, and there is no fallback for a <title>.\n ? ((await pageEntry.generate({\n params: Promise.resolve(props),\n searchParams: pageSearchParams(),\n })) ?? {})\n : { ...(pageEntry.static ?? {}) })\n : {}\n\n // Non-title metadata: layout defaults (outer→inner), page overrides.\n //\n // other merges per key rather than being replaced, so a page adding one\n // custom tag keeps the ones its layout set. Assigning it like any other key\n // would mean a root layout's theme-color disappearing from every page that\n // happened to declare one of its own.\n const merged: Record<string, unknown> = {}\n const other: Record<string, unknown> = {}\n\n const take = (from: Record<string, unknown>) => {\n for (const [k, v] of Object.entries(from)) {\n if (k === 'title') continue\n if (k === 'other') Object.assign(other, v as Record<string, unknown>)\n else merged[k] = v\n }\n }\n\n for (const l of layouts) {\n const s = metadataMap[l.component]?.static\n\n if (s) take(s as Record<string, unknown>)\n }\n\n take(page)\n\n if (Object.keys(other).length > 0) merged.other = other\n\n // Title: the page title with the NEAREST layout title.template applied; if the\n // page has no title, the nearest layout default/string title.\n let title: string | undefined = typeof page.title === 'string' ? page.title : undefined\n for (let i = layouts.length - 1; i >= 0; i--) {\n const lt = metadataMap[layouts[i].component]?.static?.title as\n | string | { template?: string; default?: string } | undefined\n if (lt && typeof lt === 'object') {\n if (title != null && lt.template) { title = lt.template.replace('%s', title); break }\n if (title == null && lt.default) { title = lt.default; break }\n } else if (title == null && typeof lt === 'string') { title = lt; break }\n }\n if (title != null) merged.title = title\n\n return Object.keys(merged).length ? merged : null\n}\n\n// Buffered render (worker: rsc / rscWithoutCallbacks — used at prerender time).\nexport async function handleRsc(\n component: string,\n props: Record<string, unknown> = {},\n _callbackSocket: string | null = null,\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n from = 0,\n pageKey = '',\n bootstrap = true,\n canReachHost = true,\n): Promise<{ body: string; rscPayload: string; clientChunks: unknown; usedDynamicApis: boolean; dynamicBecause: string[]; clientComponents: string[]; serverReferences: boolean }> {\n await instrumented()\n applyHost()\n\n // A build renders this with no host installed, so every rpc() has to suspend\n // rather than answer — which is what marks the page as needing a request.\n // Without the probe those calls found no host at all, and the page was\n // frozen holding whatever undefined rendered to.\n //\n // Defaults to true because the other caller is an interception, which runs\n // at request time with a real host and must not be probed.\n let usedDynamicApis = false\n const hostCalls: string[] = []\n\n const probe = (...args: unknown[]) => {\n usedDynamicApis = true\n\n // The name it was called with, so the build can say rpc(\"getUser\") rather\n // than \"this page reached for the host\" and leave you to find which call.\n const name = typeof args[0] === 'string' ? args[0] : null\n const said = name ? 'rpc(' + JSON.stringify(name) + ')' : 'rpc()'\n\n if (!hostCalls.includes(said)) hostCalls.push(said)\n\n return new Promise<never>(() => {})\n }\n\n // Not a generic arrow function: this file is generated as .tsx, where <T>\n // parses as JSX and the build fails on a tag it cannot close.\n const runWith = canReachHost\n ? (fn: () => Promise<unknown>) => fn()\n : (fn: () => Promise<unknown>) => probeHost.run(probe, fn)\n\n // renderTree (not bare buildElement) so the prerendered Flight payload carries\n // the same <title>/<meta> elements the live SPA payload does.\n const tree = await runWith(() =>\n renderTree(component, props, layouts, loadings, parallelSlots, {}, from, pageKey, bootstrap),\n )\n\n const flight = renderToReadableStream(tree, { onError: flightOnError })\n const [forHtml, forPayload] = flight.tee()\n const rscPayload = await new Response(forPayload).text()\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsr(forHtml, undefined, undefined, bootstrap)\n const body = await new Response(htmlStream).text()\n\n return {\n body,\n rscPayload,\n clientChunks: {},\n usedDynamicApis,\n // Client reference rows name the components the browser has to run. Shipping\n // no runtime would leave them as inert markup, so the host refuses — and\n // says which components forced the decision, since they are usually in a\n // shared layout rather than the page itself.\n clientComponents: clientReferenceNames(rscPayload),\n serverReferences: hasServerReference(rscPayload),\n }\n}\n\n/**\n * Names of the client components a payload references.\n *\n * A row reads 1:I[\"<module>\",[],\"Name\",1]; the fourth quoted field is the\n * export. Parsed by splitting rather than matching, because this function is\n * emitted into a template literal where a regex would need double escaping.\n */\nfunction clientReferenceNames(payload: string): string[] {\n const names = new Set<string>()\n\n // A string React has already sent is referenced by row - \"$1\" for the\n // string in row 1 - rather than repeated. The export name of a client\n // reference is exactly the kind of string that repeats, so it arrives that\n // way and has to be looked up, or the refusal names a component \"$1\".\n const strings = new Map<string, string>()\n\n for (const line of payload.split('\\\\n')) {\n const match = /^(\\\\d+):\"(.*)\"$/.exec(line)\n if (match) strings.set('$' + match[1], match[2]!)\n }\n\n for (const row of payload.split(':I[').slice(1)) {\n const name = row.split('\"')[3]\n if (name) names.add(strings.get(name) ?? name)\n }\n\n return [...names]\n}\n\n/**\n * Whether the payload carries a server reference - an action handed to a\n * form or a client component. A row of {\"id\":\"...\",\"bound\":...} is one,\n * however it is pointed at ($F for a function prop, $h for a form action).\n * A page with one needs the runtime to submit it.\n */\nexport function hasServerReference(payload: string): boolean {\n return /^\\\\d+:\\\\{\"id\":\"[^\"]+\",\"bound\":/m.test(payload)\n}\n\n// Flight payload only (worker: rsc-payload — build-time).\n//\n// The segment variant of a prerendered route needs the payload and nothing\n// else. handleRsc also renders the HTML, which for that variant is built and\n// thrown away — a whole SSR pass per route for output nobody reads.\n/**\n * Render one thing on its own, for a client asking to refresh it.\n *\n * The same targets an action can mark. This is the path for a refresh nobody\n * mutated anything to earn — a button, a poll, a websocket saying the orders\n * table moved.\n */\nexport async function handleRscRevalidate(\n target: string,\n page: PageContext,\n): Promise<{ rscPayload: string }> {\n await instrumented()\n applyHost()\n\n const flight = renderToReadableStream(await renderRevalidated(target, page))\n\n return { rscPayload: await new Response(flight).text() }\n}\n\nexport async function handleRscPayload(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n from = 0,\n pageKey = '',\n): Promise<{ rscPayload: string }> {\n await instrumented()\n applyHost()\n\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, {}, from, pageKey),\n { onError: flightOnError },\n )\n\n return { rscPayload: await new Response(flight).text() }\n}\n\n// PPR shell + classification (worker: rsc-ppr-shell — build-time).\n//\n// rpc() is replaced by a probe that records the call and never resolves, so\n// every subtree depending on per-request data stays suspended while everything\n// static renders normally. Whatever React has flushed when the deadline passes\n// IS the shell: layouts, static markup, and Suspense fallbacks.\n//\n// The two flags this returns are what the prerender pipeline classifies on:\n// usedDynamicApis — the page touched rpc(), so it cannot be frozen whole\n// timedOut — the render never finished, i.e. it is still waiting on\n// data, so only the shell is safe to cache\n// A page that sets neither is genuinely static and can be prerendered fully.\nconst PPR_SHELL_TIMEOUT_MS = Number(process.env.RSC_PPR_TIMEOUT_MS || 2000)\n\nexport async function handleRscPprShell(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n // The url this shell will be served for, when it is served for exactly one.\n // Empty for a parameterised route, whose shell is shared across every url it\n // matches and therefore cannot carry one.\n pageKey = '',\n // How long to let the render run before taking whatever has flushed.\n //\n // A parameter because not every caller is asking the same question. Deciding\n // what a page's shell IS needs the full budget — the point is to wait out\n // everything that can resolve. Asking whether anything paints at all without\n // a root fallback is a boolean about the first flush, and a page that paints,\n // paints immediately: giving that the same budget spends two seconds per\n // route to learn nothing the first millisecond did not say.\n budgetMs = PPR_SHELL_TIMEOUT_MS,\n // Whether this build can answer host calls.\n //\n // False is the old and still the usual answer: the stub suspends, and a page\n // reaching for its host becomes a shell rather than freezing data fetched\n // once at build time.\n //\n // A host that opened a callback socket for the build says true, and then the\n // call is made and its answer stored. That is the only way a page whose data\n // lives in the host can be static at all, since a host call is its only route\n // to that data — and\n // connection() is how such a page opts back out.\n //\n // Asked of the caller rather than read from whatever host happens to be\n // installed, because those are different statements: a test that installed\n // one is not a build that can reach the host.\n canReachHost = false,\n): Promise<{ shellHtml: string; clientChunks: unknown; timedOut: boolean; usedDynamicApis: boolean; error?: string }> {\n // Deliberately no middleware here. The probe is asking whether the content is\n // the same for everyone, which is a question about the page. Whether a\n // particular caller may see it is a question about the request, and there is\n // no request at build time — running a guard here would refuse every time\n // and make every guarded route dynamic for the wrong reason.\n let usedDynamicApis = false\n\n await instrumented()\n applyHost()\n\n const probe = (..._args: unknown[]) => {\n usedDynamicApis = true\n\n // Never resolves: the awaiting component suspends and React renders its\n // Suspense fallback into the shell instead of the real content.\n return new Promise<unknown>(() => {})\n }\n\n let shellHtml = ''\n let completed = false\n let error: string | undefined\n let postponed: unknown = null\n\n // The budget, declared before the error handler that consults it.\n const controller = new AbortController()\n const budget = setTimeout(() => controller.abort(), budgetMs)\n\n // Anything that failed while producing this shell.\n //\n // A rejection inside a Suspense boundary does NOT reach the caller: React\n // catches it, keeps the fallback, and the render goes on to finish. So the\n // probe looked like a page that had nothing left to do — no postponed state,\n // no thrown error — and the fallback was frozen as a finished static page.\n // A database the build machine cannot reach produced a permanently loading\n // page, stored, with the build reporting success.\n let renderFailure: string | undefined\n\n const noteFailure = (e: unknown, info?: { componentStack?: string }): string | undefined => {\n const digest = redirectDigest(e)\n\n // A redirect is a classification here, not a failure.\n if (digest) return digest\n\n // A read the server could not answer, caught at a boundary: the fallback\n // there is what gets stored. Noted with its component so the build can\n // say so on the route's line; the digest goes into the document for the\n // browser to recognise.\n if ((e as { digest?: string } | null)?.digest === 'rsc-kit:search-params-fallback') {\n const where = /at ([A-Z_$][\\\\w$]*)/.exec(info?.componentStack ?? '')?.[1]\n noteCaughtRead('useSearchParams()' + (where ? ' in ' + where : ''))\n return 'rsc-kit:search-params-fallback'\n }\n\n // Every probe ends by aborting, so React reports that abort. Asked of the\n // signal rather than matched against the message: a string test would be a\n // guess about wording, and would quietly stop working when React changed it.\n if (controller.signal.aborted) return undefined\n\n renderFailure ??= e instanceof Error ? e.message : String(e)\n console.error('[rsc-kit]', e)\n\n return undefined\n }\n\n // The budget is an abort signal rather than a race. \\`prerender\\` resolves when\n // it is aborted, handing back both what flushed and where it stopped, so there\n // is nothing left to cancel by hand and no window in which the render is still\n // going after the caller has moved on.\n\n // Everything the render does happens inside the scope, so the stand-in host\n // travels with it rather than with the process.\n const runWith = canReachHost\n ? (fn: () => Promise<void>) => fn()\n : (fn: () => Promise<void>) => probeHost.run(probe, fn)\n\n const produce = runWith(async () => {\n try {\n // Params settle only when this probe is for one concrete url. A route\n // that listed its urls is being rendered for one of them, so the page\n // can be frozen whole; a route that listed none is being rendered for\n // the pattern, where any value would be an invention.\n const tree = await renderTree(\n component,\n props,\n layouts,\n loadings,\n parallelSlots,\n {},\n 0,\n pageKey,\n true,\n pageKey ? Promise.resolve(props) : new Promise(() => {}),\n )\n // Quiet about a redirect: during the probe it is a classification, not\n // a failure, and React would otherwise print a stack for every one.\n const flight = renderToReadableStream(tree, { onError: noteFailure })\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n // The flight stream stays open across this. A Flight stream that has\n // closed tells the decoder the connection ended, so the boundary waiting\n // on it errors rather than staying pending — and an errored boundary is\n // finished, not postponed: it comes back null and there is nothing left\n // to resume from.\n const prerendered = await ssr.handleSsrPrerender(flight, {\n signal: controller.signal,\n onError: noteFailure,\n })\n\n postponed = prerendered.postponed\n\n const reader = prerendered.prelude.getReader()\n const decoder = new TextDecoder()\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n shellHtml += decoder.decode(value, { stream: true })\n }\n\n completed = true\n } catch (e: any) {\n error = e?.message ?? String(e)\n }\n })\n\n await produce\n clearTimeout(budget)\n\n // timedOut used to mean the stopwatch ran out. It now means React has\n // boundaries it could not finish — the thing the caller was always asking\n // about, and exact rather than inferred: a page that finishes inside the\n // budget says so by postponing nothing.\n return {\n shellHtml,\n clientChunks: {},\n timedOut: postponed !== null,\n usedDynamicApis,\n error,\n postponed,\n renderFailure,\n }\n}\n\n/**\n * What \\`vite dev\\` serves.\n *\n * @vitejs/plugin-rsc's dev server calls this module's default export for every\n * request, so implementing it is the whole of dev mode: the same handler the\n * production server builds, over the same route table, against modules Vite\n * re-evaluates on edit. Nothing is prebuilt, so there is no build to keep in\n * step and no NODE_ENV to match — this is React's development build because\n * Vite is running in development.\n *\n * Assets are deliberately absent: Vite serves its own.\n *\n * Frozen pages are absent *in development* — a frozen page is a build\n * artifact, and serving one here would hand back the last build's HTML for a\n * file just edited. Under Nitro this same file is also the production entry,\n * and reading that reason as applying to both is what left every built Nitro\n * server rendering live pages it had already frozen. The gate is the mode, not\n * the file.\n */\n${fallbackOrigin ? FALLBACK_CONSTS.replace(\"__ORIGIN__\", JSON.stringify(fallbackOrigin)) : \"\"}${NITRO_HOST_CALLS}\nlet devHandler: ((request: Request) => Promise<Response | null>) | null = null\n\nexport default async function handler(request: Request): Promise<Response> {\n try {\n return await serve(request)\n } catch (error) {\n // Vite re-optimised a server pre-bundle under this render. The condition\n // is over already; the page is asked to load again.\n if (import.meta.env.DEV && isOutdatedOptimizedDep(error)) return outdatedDepResponse(request)\n\n throw error\n }\n}\n\nasync function serve(request: Request): Promise<Response> {\n // The startup plugin's probe. Nitro loads this module at the first request\n // rather than when the server starts, so a plugin that runs at startup\n // sends one request to load it; the module's evaluation began register(),\n // and this waits for it so a failure is reported as the startup failure it\n // is. No page is rendered and nothing is disclosed.\n if (request.headers.get('x-rsc-kit-startup') !== null) {\n await instrumented()\n\n return new Response(null, { status: 204 })\n }\n\n installHostCallsOnce()\n\n devHandler ??= createRscHandler({\n engine: {\n manifest,\n getStaticParams,\n installHostFn,\n handleRsc,\n handleRscStream,\n handleRscHtmlStream,\n handleRscFormPost,\n handleRscRevalidate,\n handleRscPayload,\n handleRscPprShell,\n handleRscResume,\n handleAction,\n handleQuery,\n handleApiRoute,\n resolveMetadata,\n runRouteMiddleware,\n buildId,\n } as never,\n${NITRO_HANDLER_OPTIONS}${NITRO_PRERENDERED} maxActionBody: ${maxActionBody === undefined ? \"undefined\" : String(maxActionBody)},\n })\n\n${fallbackOrigin ? FALLBACK_BODY : \" return (await devHandler(request)) ?? (await notFound(request))\\n\"}}\n\n/**\n * The page for a url nothing answers.\n *\n * Rendered through its layout chain like any other page, so the 404 a visitor\n * sees is the app rather than a bare string — and returned with a 404, because\n * a page that says \"not found\" under a 200 is a page search engines index.\n *\n * Without a not-found.tsx this is the string it always was.\n */\nasync function notFound(request: Request): Promise<Response> {\n ${\n notFoundComponent\n ? `\n // A navigation, not a document: answer with the not-found tree as a\n // payload, at the depth the client already holds, so the router renders\n // it in place - the layout stays, the url changes, nothing reloads. The\n // status is still 404; a payload is a payload whatever it says.\n if (request.headers.get('X-RSC')) {\n try {\n const chain = ${JSON.stringify(notFoundLayouts)}\n const from = sharedDepth(request.headers.get('X-RSC-Segments'), chain)\n const { rscPayload } = await handleRscPayload(\n ${JSON.stringify(notFoundComponent)},\n {},\n ${JSON.stringify(notFoundLayouts.map((component) => ({ component, props: {} })))},\n [],\n {},\n from,\n '/404',\n )\n\n return new Response(rscPayload, {\n status: 404,\n headers: {\n 'Content-Type': 'text/x-component; charset=utf-8',\n 'X-RSC-Segment-Depth': String(from),\n 'X-RSC-Layouts': chain.join(','),\n 'Cache-Control': 'no-store',\n Vary: 'X-RSC',\n },\n })\n } catch {\n // Fall through to the document answer below.\n }\n }\n\n try {\n const { htmlStream } = await handleRscHtmlStream(\n ${JSON.stringify(notFoundComponent)},\n {},\n ${JSON.stringify(notFoundLayouts.map((component) => ({ component, props: {} })))},\n [],\n {},\n {},\n undefined,\n '/404',\n )\n\n return new Response(htmlStream, {\n status: 404,\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n })\n } catch {\n // A 404 page that throws is still a 404. Falling back rather than\n // answering 500 keeps the status honest about what happened.\n }\n `\n : \"\"\n }\n return new Response('Not found', { status: 404 })\n}\n`;\n}\n\nfunction generateEntrySsr(): string {\n const devUrls = join(packageDir, \"devUrls\");\n const request = join(packageDir, \"request\");\n const fallbackReport = join(packageDir, \"js/fallbackReport\");\n const redirectDigestModule = join(packageDir, \"redirectDigest\");\n const notFoundModule = join(packageDir, \"notFound\");\n\n return `// GENERATED by rscKit() — do not edit.\nimport { createFromReadableStream } from '@vitejs/plugin-rsc/ssr'\nimport { renderToReadableStream, resume } from 'react-dom/server.edge'\nimport { prerender } from 'react-dom/static.edge'\nimport { rewriteViteDevUrlStream } from ${JSON.stringify(devUrls)}\nimport { noteFallback } from ${JSON.stringify(request)}\nimport { cancelledByConsumer, caughtByLoading } from ${JSON.stringify(fallbackReport)}\nimport { parseRedirectDigest } from ${JSON.stringify(redirectDigestModule)}\nimport { isNotFoundDigest } from ${JSON.stringify(notFoundModule)}\n\n// Set only by the dev server. @vitejs/plugin-rsc emits its bootstrap and CSS\n// links root-relative in dev, which would send the browser to the host for\n// modules only Vite can answer — see devUrls.ts.\nconst DEV_ORIGIN = ${JSON.stringify(devOrigin)}\n\nexport async function handleSsr(\n rscStream: ReadableStream,\n nonce?: string,\n onError?: (error: unknown) => void,\n bootstrap = true,\n formState?: unknown,\n): Promise<ReadableStream> {\n const root = await createFromReadableStream(rscStream)\n\n // Without the bootstrap the page ships no client runtime at all: no React,\n // no Flight client, no router. HTML only. A page with nothing interactive on\n // it has no use for 70kB of hydration.\n const bootstrapScriptContent = bootstrap\n ? await (import.meta as any).viteRsc.loadBootstrapScriptContent('index')\n : undefined\n\n // Without an onError handler React rejects each abortable task on its own,\n // and those rejections surface as unhandled — noisy for the PPR shell render,\n // which aborts on purpose once it has the shell.\n const html = await renderToReadableStream(root as any, {\n bootstrapScriptContent,\n nonce,\n onError: onError ?? reportRenderError('ssr'),\n // What a posted form's action returned, for the useActionState that\n // asked: React seats it in the form it belongs to.\n ...(formState !== undefined ? { formState: formState as any } : {}),\n })\n\n return DEV_ORIGIN ? rewriteViteDevUrlStream(html, DEV_ORIGIN) : html\n}\n\n/**\n * The same render, stopped at the first thing it cannot finish.\n *\n * \\`renderToReadableStream\\` and then cancelling gives you the bytes that\n * flushed and nothing else — the render is *aborted*, so React has no record of\n * where it got to. \\`prerender\\` aborts the same way but hands back\n * \\`postponed\\`: enough state to pick the render back up later, against data\n * that did not exist at build time.\n *\n * The rscStream must still be OPEN when this returns. A Flight stream that has\n * closed tells the decoder the connection ended, so the boundary waiting on it\n * *errors* rather than staying pending — and an errored boundary is not\n * postponed, it is finished. \\`postponed\\` comes back null and there is nothing\n * to resume.\n */\nexport async function handleSsrPrerender(\n rscStream: ReadableStream,\n options: { nonce?: string; bootstrap?: boolean; signal?: AbortSignal } = {},\n): Promise<{ prelude: ReadableStream; postponed: unknown }> {\n const root = await createFromReadableStream(rscStream)\n\n const bootstrapScriptContent =\n options.bootstrap === false\n ? undefined\n : await (import.meta as any).viteRsc.loadBootstrapScriptContent('index')\n\n const { prelude, postponed } = await prerender(root as any, {\n bootstrapScriptContent,\n nonce: options.nonce,\n signal: options.signal,\n // Aborting is how this ends, so React's report of it is not news. A read\n // caught at a boundary is: the build attaches it to the route.\n onError: (error: unknown, info?: { componentStack?: string }) => {\n if ((error as { digest?: string } | null)?.digest !== 'rsc-kit:search-params-fallback') return\n const where = /at ([A-Z_$][\\\\w$]*)/.exec(info?.componentStack ?? '')?.[1]\n noteFallback('useSearchParams()' + (where ? ' in ' + where : ''))\n return 'rsc-kit:search-params-fallback'\n },\n })\n\n return {\n prelude: DEV_ORIGIN ? rewriteViteDevUrlStream(prelude, DEV_ORIGIN) : prelude,\n postponed: postponed ?? null,\n }\n}\n\n/**\n * What a server render says about an error, first render and resume alike.\n *\n * The query-string fallback is the designed path for a stored page, and its\n * digest is what lets the client tell it from a fault on hydration; returned\n * so React writes it into the document. Under a boundary the developer wrote\n * there is nothing to say; with nothing closer than a loading.tsx, one line.\n */\nfunction reportRenderError(phase: 'ssr' | 'resume') {\n return (error: unknown, info?: { componentStack?: string }) => {\n // The consumer cancelled - a browser that left mid-stream, a prefetch\n // abandoned. React reports it as an error; the page had none.\n if (cancelledByConsumer(error)) return\n\n const digest = (error as { digest?: string } | null)?.digest\n\n // A redirect or a notFound() the render asked for arrives here as the\n // Flight row's error, once per boundary it was thrown in. The rsc side\n // already turned it into a digest on purpose; it is the page's answer,\n // and the host reads it off the digest. Not an error to print, four\n // times or once.\n if (parseRedirectDigest(digest) || isNotFoundDigest(digest)) return digest\n\n if (digest === 'rsc-kit:search-params-fallback') {\n // The component is the first frame of React's stack. Noted on the\n // request so the build attaches it to the route; printed as one line,\n // not a stack, so the server says which boundary it wants.\n const where = /at ([A-Z_$][\\\\w$]*)/.exec(info?.componentStack ?? '')?.[1]\n\n noteFallback('useSearchParams()' + (where ? ' in ' + where : ''))\n\n if (caughtByLoading(info?.componentStack)) {\n console.error(\n '[rsc-kit] ' + (where ? where + ': ' : '') +\n 'useSearchParams() was read on the server with nothing closer than a loading.tsx, so the whole ' +\n 'segment shows that fallback until the query arrives. A <Suspense> around the component that reads ' +\n 'keeps the rest of the page painted.',\n )\n }\n\n return digest\n }\n\n console.error('[rsc-kit:' + phase + ']', error)\n }\n}\n\n/**\n * Pick a build-time render back up, against data that exists now.\n *\n * Emits ONLY what the shell left unfinished — the hidden segments plus React's\n * own script to move them into place. It is meant to be concatenated after the\n * shell, and it carries no bootstrap of its own: the shell already shipped one.\n *\n * The swap is done by that inline script, not by hydration, so the holes land\n * even on a page whose JavaScript never loads.\n */\nexport async function handleSsrResume(\n rscStream: ReadableStream,\n postponed: unknown,\n nonce?: string,\n): Promise<ReadableStream> {\n const root = await createFromReadableStream(rscStream)\n\n const html = await resume(root as any, postponed as any, {\n nonce,\n // The same reading of an error the first render has. This used to log\n // every error raw, so a query read the developer's own boundary caught -\n // the designed path, on every resume of a shell whose hole holds one -\n // printed as \"[rsc-kit:resume] Error: useSearchParams() was read...\" on\n // every request, with advice the app had already followed.\n onError: reportRenderError('resume'),\n })\n\n return DEV_ORIGIN ? rewriteViteDevUrlStream(html, DEV_ORIGIN) : html\n}\n${SSR_SERVICE}`;\n}\n\n/**\n * What Nitro calls this environment through.\n *\n * Nitro addresses each Vite environment as a service and calls fetch on it —\n * `mod = _mod.default || _mod; mod.fetch(req)` — so an entry that exports only\n * named functions is a 500 on every request. The named ones stay: the rsc\n * entry still reaches them through loadModule. This only adds the door Nitro\n * knocks on, and the request goes straight back to the rsc entry, which is the\n * one that owns rendering.\n */\nconst SSR_SERVICE = `\nexport default {\n fetch: async (request: Request): Promise<Response> => {\n const rsc = await import.meta.viteRsc.loadModule<{\n default: (request: Request) => Promise<Response>\n }>('rsc', 'index')\n\n return rsc.default(request)\n },\n}\n`;\n\nfunction generateEntryBrowser(): string {\n const clientBootstrap = join(packageDir, \"js/createViteRscApp\");\n\n // Only for an exported build, and only what the client needs to work out how\n // much of a page to ask for: a file server sends no headers, so without this\n // every navigation takes the whole document and replaces the root. Inlined\n // rather than fetched, so it costs no request. Omitted entirely otherwise —\n // a server answers this, and shipping a route table to every browser for\n // nothing is a page-weight cost with no benefit.\n const routesForClient = staticPayloads\n ? routeManifest().routes.map((route) => ({\n segments: route.segments,\n layouts: route.layouts,\n }))\n : null;\n\n const refreshModule = join(packageDir, \"js/navigate\");\n\n return `// GENERATED by rscKit() — do not edit.\nimport { createViteRscApp } from ${JSON.stringify(clientBootstrap)}\nimport { refresh } from ${JSON.stringify(refreshModule)}\n\ncreateViteRscApp(document, ${JSON.stringify(interceptManifest())}, ${JSON.stringify(\n {\n staticPayloads: staticPayloads || null,\n routes: routesForClient,\n // Every route.ts, as a url pattern, so a link to one is treated as an\n // anchor rather than prefetched and fetched as a page.\n apiRoutes: (routeManifest().apis ?? []).map((api) => patternOf(api.segments)),\n },\n )})\n\n// A server component is not a module the browser has, so Vite cannot replace\n// it the way it replaces a client one. @vitejs/plugin-rsc says so instead:\n// when a module in the rsc graph changes it sends this, and re-fetching the\n// payload is the update. Without a listener an edit to a page reaches the\n// server and stops there, and the browser goes on showing the old render\n// until someone reloads by hand.\n//\n// 'all', not 'page': a layout is a server component too, and refreshing only\n// below it would leave an edited layout on screen unchanged. It costs nothing\n// extra — a client component below is remounted either way, because the new\n// payload carries a fresh reference to its module. Editing that component\n// directly is the case where state survives, and that is Fast Refresh doing\n// it rather than this.\nif (import.meta.hot) {\n import.meta.hot.on('rsc:update', () => {\n void refresh('all')\n })\n}\n${\n offline\n ? `\n// Registered after load rather than during it, so fetching and installing the\n// worker competes with nothing the first visit actually needs. The second\n// visit is the one it is for.\n//\n// Not in development: the dev server is the thing you are editing, and a\n// worker answering from a cache in front of it turns every edit into a\n// question about which copy you are looking at.\nif ('serviceWorker' in navigator && import.meta.env.PROD) {\n const register = () => {\n void navigator.serviceWorker.register('/sw.js').catch(() => {\n // A worker that will not register is not a reason for the page to fail.\n // The app works; it just will not survive being reloaded offline.\n })\n }\n\n // This runs after the boot payload has been fetched and decoded, and on a\n // fast load the page has finished loading by then - a listener added now\n // waits for an event that has already fired, and nothing registered until\n // the next navigation.\n if (document.readyState === 'complete') register()\n else window.addEventListener('load', register)\n}\n`\n : \"\"\n}`;\n}\n\n/**\n * Intercepted URL patterns, published by the host before the build.\n *\n * The client has to recognise an intercepted link before it asks the server,\n * so the patterns are baked into the browser entry. The host owns the file\n * because it owns route discovery; an absent or unreadable one just means no\n * interception, never a failed build.\n */\n/**\n * The intercepted urls the client router has to recognise, in its dialect.\n *\n * Generated here rather than read from a file the host wrote. The host used to\n * discover these because it owned the walk of app/; now the plugin does, and a\n * host writing them meant producing this file before the build that needed it —\n * an ordering that only worked because the two steps happened to be in the\n * right sequence.\n */\nfunction interceptManifest(): Array<{ urlPattern: string; slot: string }> {\n return routeManifest().intercepts.map((entry) => ({\n // The client writes [id] where a Laravel route writes {id}.\n urlPattern:\n \"/\" +\n entry.segments\n .map((seg) =>\n seg.type === \"static\" ? seg.value : \"[\" + seg.value + \"]\",\n )\n .join(\"/\"),\n slot: entry.slot,\n }));\n}\n\n// ── Validation ───────────────────────────────────────────────────────────────\n\n/**\n * Extract the body of a file's default-exported function.\n *\n * Only the page component's OWN body matters for the loading.tsx rule — sibling\n * components declared in the same file render behind their own boundaries, so\n * their host calls do not block the route's shell.\n */\nfunction defaultExportBody(source: string): string | null {\n const match = source.match(\n /export\\s+default\\s+(?:async\\s+)?function[^(]*\\([^)]*\\)\\s*{/,\n );\n if (!match) return null;\n\n // Walk from the opening brace to its match, ignoring braces in strings.\n let depth = 0;\n const start = match.index! + match[0].length - 1;\n\n for (let i = start; i < source.length; i++) {\n const ch = source[i];\n if (ch === \"{\") depth++;\n else if (ch === \"}\" && --depth === 0) return source.slice(start, i + 1);\n }\n\n return null;\n}\n\n/**\n * Does the page component's own render block on the host callable?\n *\n * Only an awaited call blocks. Starting a call and handing the promise to a\n * child — for a client component to unwrap with use() inside its own Suspense\n * boundary — lets the page paint immediately and needs no loading.tsx.\n *\n * The check is deliberately syntactic: a call awaited indirectly, through a\n * variable, is not caught. That errs toward letting a build through rather than\n * rejecting a page that is actually fine.\n */\nfunction pageBlocksOnHostCall(source: string): boolean {\n const isAsyncDefault = /export\\s+default\\s+async\\s+function/.test(source);\n if (!isAsyncDefault) return false;\n\n const body = defaultExportBody(source);\n\n // Matches `await rpc(`, and the explicitly-qualified forms a typed codebase\n // may use: `await globalThis.rpc(` / `await (globalThis as any).rpc(`.\n const qualifier =\n \"(?:\\\\(\\\\s*globalThis[^)]*\\\\)\\\\s*\\\\.\\\\s*|globalThis\\\\s*\\\\.\\\\s*)?\";\n const awaited = new RegExp(`\\\\bawait\\\\s+${qualifier}${hostGlobal}\\\\s*[<(]`);\n\n return body !== null && awaited.test(body);\n}\n\n/** Walk up from the page directory to app/ looking for a loading file. */\nfunction hasLoadingInChain(pageDir: string): boolean {\n let dir = pageDir;\n\n while (dir.startsWith(appDir)) {\n if (findRouteFile(dir, \"loading\")) return true;\n if (dir === appDir) break;\n dir = dirname(dir);\n }\n\n return false;\n}\n\n/**\n * A route needs loading.tsx only when the PAGE ITSELF blocks — an async default\n * export awaiting the host callable, or the host resolving props dynamically. Both\n * suspend before anything can paint, so without a boundary the user sees a\n * blank screen. A page whose slow work lives in children behind their own\n * <Suspense> already paints a shell and needs nothing.\n */\n/**\n * An `error.tsx` has to be a client component.\n *\n * It is rendered inside a React error boundary, which is a class component in\n * the browser, and it is handed a `reset` callback to call. A server component\n * can be neither. Caught here rather than at runtime, where the symptom is a\n * boundary that renders nothing while the error it was written for goes to the\n * console.\n */\nfunction validateErrorBoundaries(): string[] {\n const wrong: string[] = [];\n\n for (const c of components.values()) {\n if (!c.name.endsWith(\"/error\")) continue;\n\n const source = readFileSync(c.absPath, \"utf-8\");\n\n if (!/^\\s*['\"]use client['\"]/m.test(source)) {\n wrong.push(` ${relative(projectRoot, c.absPath)}`);\n }\n }\n\n return wrong;\n}\n\nfunction validateLoadingBoundaries(): string[] {\n const errors: string[] = [];\n\n for (const c of components.values()) {\n if (!c.name.endsWith(\"/page\") && c.name !== \"app/page\") continue;\n\n const pageDir = dirname(c.absPath);\n const source = readFileSync(c.absPath, \"utf-8\");\n\n let reason: string | null = null;\n\n if (pageBlocksOnHostCall(source)) {\n reason = `its default export awaits ${hostGlobal}()`;\n } else {\n const configPath = routeConfig ? join(pageDir, routeConfig.file) : null;\n\n if (\n routeConfig &&\n configPath &&\n existsSync(configPath) &&\n routeConfig.dynamicPattern.test(readFileSync(configPath, \"utf-8\"))\n ) {\n reason = `${routeConfig.file} resolves props dynamically`;\n }\n }\n\n if (reason && !hasLoadingInChain(pageDir)) {\n errors.push(\n ` ${c.name} — ${reason}, but has no loading.tsx in its directory chain`,\n );\n }\n }\n\n return errors;\n}\n\n// ── Plugin ───────────────────────────────────────────────────────────────────\n\n/** Names of plugins that transform JSX and must run after rsc() has split it. */\nconst JSX_PLUGIN_PATTERN = /react|babel|oxc/i;\n\n/**\n * The server-side stand-in for a client export, made extendable.\n *\n * In the rsc environment plugin-rsc replaces every export of a \"use client\"\n * module with a stub that throws when called. It emits the stub as an arrow\n * function, and an arrow function has no prototype, so a server module that\n * does `class NullStore extends ReactStore` - base-ui does, with only the\n * base class marked \"use client\" - dies at the class declaration with\n * \"The superclass is not a constructor\", on a line nobody wrote, whenever a\n * server component imports the library directly. Next.js allows that import;\n * React's own client references are proxies over a real function.\n *\n * A `function` stub has a prototype, so the declaration succeeds, and the\n * stub still throws - now from `super()`, with its own message - if the\n * class is ever constructed on the server.\n */\nconst CLIENT_STUB =\n /registerClientReference\\(\\s*\\(\\) => \\{ throw new Error\\(\"Unexpectedly client reference export '\"/g;\n\nfunction extendableClientReferences(): Plugin {\n return {\n name: \"rsc-kit:extendable-client-references\",\n enforce: \"post\",\n applyToEnvironment: (environment) => environment.name === \"rsc\",\n transform(code) {\n if (!code.includes(\"Unexpectedly client reference export\")) return;\n\n return {\n code: code.replace(\n CLIENT_STUB,\n 'registerClientReference(function () { throw new Error(\"Unexpectedly client reference export \\'\"',\n ),\n map: null,\n };\n },\n };\n}\n\n/**\n * The worker the dev server serves at /sw.js: it removes the one a production\n * run left on this origin, and the caches with it, then reloads each page it\n * was controlling so they load uncontrolled. Nothing else runs in development.\n */\nexport const DEV_WORKER = `self.addEventListener('install', () => self.skipWaiting())\nself.addEventListener('activate', (event) => {\n event.waitUntil((async () => {\n const keys = await caches.keys()\n await Promise.all(keys.filter((k) => k.startsWith('rsc-kit-')).map((k) => caches.delete(k)))\n await self.clients.claim()\n const pages = await self.clients.matchAll({ type: 'window' })\n await self.registration.unregister()\n for (const page of pages) page.navigate(page.url).catch(() => {})\n })())\n})\n`;\n\n/**\n * Named imports from a barrel package, unrolled on the server environments.\n *\n * The browser gets lucide pre-bundled; the server environments do not, so\n * `import { ArrowRight } from 'lucide-react'` loaded and transformed every\n * icon module - 3,700 transforms, twenty-five seconds before the first\n * document, for thirteen icons. See barrelImports. Development only: a\n * build tree-shakes the barrel itself.\n */\nfunction barrelImportsPlugin(): Plugin {\n const entries = new Map<string, string | null>();\n\n return {\n name: \"rsc-kit:barrel-imports\",\n apply: () => barrelImports && process.env.NODE_ENV !== \"production\",\n enforce: \"pre\",\n applyToEnvironment: (environment) =>\n environment.name === \"rsc\" || environment.name === \"ssr\",\n async transform(code, id) {\n if (\n id.includes(\"/node_modules/\") ||\n !/\\.[cm]?[jt]sx?$/.test(id.split(\"?\")[0])\n )\n return;\n if (!code.includes(\"from\")) return;\n\n const pending: Promise<void>[] = [];\n const wanted = new Set<string>();\n\n for (const m of code.matchAll(\n /import\\s*(?:type\\s+)?\\{[^}]*\\}\\s*from\\s*['\"]([^'\"./][^'\"]*)['\"]/g,\n )) {\n wanted.add(m[1]);\n }\n\n for (const specifier of wanted) {\n if (entries.has(specifier)) continue;\n\n pending.push(\n this.resolve(specifier, id).then((resolved) => {\n entries.set(\n specifier,\n resolved && !resolved.external ? resolved.id.split(\"?\")[0] : null,\n );\n }),\n );\n }\n\n await Promise.all(pending);\n\n const out = unrollBarrelImports(\n code,\n (specifier) => entries.get(specifier) ?? null,\n );\n\n return out === null ? undefined : { code: out, map: null };\n },\n };\n}\n\n/**\n * \"use ssr\" modules, rewritten for the server-components environment into\n * proxies that call the real module in the ssr environment. See useSsr.ts.\n *\n * Before every other transform, so the cross-environment import this emits\n * is still ahead of plugin-rsc's handling of it - and so the module's own\n * imports, react-dom/server among them, are never resolved here at all.\n */\nfunction useSsrModules(): Plugin {\n return {\n name: \"rsc-kit:use-ssr\",\n enforce: \"pre\",\n applyToEnvironment: (environment) => environment.name === \"rsc\" || environment.name === \"ssr\",\n transform(code, id) {\n if (!code.includes(\"use ssr\")) return;\n\n // In the environment the module runs in, the directive has done its\n // work and is a string the bundler warns about. Out it goes.\n if (this.environment.name === \"ssr\") {\n const stripped = withoutSsrDirective(code);\n\n return stripped === null ? undefined : { code: stripped, map: null };\n }\n\n try {\n const proxy = ssrProxyModule(code, id);\n\n return proxy === null ? undefined : { code: proxy, map: null };\n } catch (error) {\n if (error instanceof UseSsrError) this.error(error.message);\n\n throw error;\n }\n },\n };\n}\n\n/**\n * react-dom/server, imported where server components render, becomes a\n * module that throws the fix instead of React's refusal - naming the app\n * file that imported it (through @react-email/render, say) and the\n * directive that moves it. The build says the same once, as a warning.\n */\nconst RENDERER_STUB = \"\\0rsc-kit:react-dom-server?from=\";\n\n/** What react-dom/server exports, across its node, edge and browser entries. */\nconst SERVER_RENDERER_EXPORTS = [\n \"renderToString\",\n \"renderToStaticMarkup\",\n \"renderToReadableStream\",\n \"renderToPipeableStream\",\n \"renderToStaticNodeStream\",\n \"resume\",\n \"resumeToPipeableStream\",\n \"resumeAndPrerender\",\n \"resumeAndPrerenderToNodeStream\",\n \"prerender\",\n \"prerenderToNodeStream\",\n];\n\nexport function serverRendererInRsc(): Plugin {\n const warned = new Set<string>();\n\n const appImporter = (\n ctx: {\n environment: { mode: string; moduleGraph?: unknown };\n getModuleInfo(id: string): { importers: readonly string[] } | null;\n },\n importer: string | null,\n ): string | null => {\n let current = importer;\n\n for (let hop = 0; current && hop < 12; hop++) {\n if (!current.includes(\"/node_modules/\"))\n return relative(process.cwd(), current.split(\"?\")[0]);\n\n const next: string | undefined =\n ctx.environment.mode === \"build\"\n ? ctx.getModuleInfo(current)?.importers[0]\n : ((\n ctx.environment.moduleGraph as\n | {\n getModuleById(\n id: string,\n ): { importers: Set<{ id: string | null }> } | undefined;\n }\n | undefined\n )\n ?.getModuleById(current)\n ?.importers.values()\n .next().value?.id ?? undefined);\n\n if (!next) break;\n\n current = next;\n }\n\n return importer ? relative(process.cwd(), importer.split(\"?\")[0]) : null;\n };\n\n // Per package, so a dependency imported from twenty files is read once.\n const externalRenderers = new Map<string, boolean>();\n // Packages already named by the warning above, so the stub's own warning\n // - \"imported by node_modules/<package>/dist/index.mjs\" - stays quiet for\n // them: one problem, one line.\n const warnedPackages = new Set<string>();\n\n return {\n name: \"rsc-kit:server-renderer\",\n // Before Vite's own resolver, which otherwise answers react-dom/server\n // with React's react-server entry - a real module missing the export,\n // and a build that fails on MISSING_EXPORT with no mention of the fix.\n enforce: \"pre\",\n applyToEnvironment: (environment) => environment.name === \"rsc\",\n async resolveId(source, importer) {\n // Only an import from a module: a resolve with no importer is Vite\n // asking whether the specifier exists - deciding what to externalise -\n // and answering that with the stub would answer the wrong question.\n if (SERVER_RENDERER.test(source)) {\n return importer ? RENDERER_STUB + encodeURIComponent(importer) : undefined;\n }\n\n // A bare import from app code of a package the build leaves external:\n // its own import of react-dom/server is never resolved here, so the\n // stub above never sees it. @react-email/render, imported by an\n // action, built clean and threw React's refusal at the first visitor.\n // The package is read once for the import, and the build warns the\n // same way it does for a direct one - naming the app file and the\n // package - without stubbing a module that may also be used well.\n if (!importer || importer.includes(\"/node_modules/\") || importer.startsWith(\"\\0\")) return;\n if (!/^(?:@[\\w.-]+\\/)?[\\w.-]+/.test(source) || source.startsWith(\".\")) return;\n // The generated entries import plugin-rsc, whose ssr half imports the\n // renderer for its own reasons; that is the build's, not the app's.\n if (outDir && importer.startsWith(outDir)) return;\n\n const name = source.startsWith(\"@\") ? source.split(\"/\").slice(0, 2).join(\"/\") : source.split(\"/\")[0];\n\n if (name === \"react-dom\" || name === \"react\" || name.startsWith(\"@rsc-kit/\") || name.startsWith(\"@vitejs/\")) return;\n\n let imports = externalRenderers.get(name);\n\n if (imports === undefined) {\n // Vite answers a dependency either as external, by its bare name,\n // or by the file it resolved to under node_modules - which of the\n // two depends on how the environment was set up, and both are a\n // dependency whose imports the build will not look inside.\n const resolved = await this.resolve(source, importer, { skipSelf: true });\n const id = resolved?.id ?? \"\";\n const marker = `/node_modules/${name}/`;\n const at = id.lastIndexOf(marker);\n const dir = resolved?.external\n ? installedPackageDir(name, dirname(importer.split(\"?\")[0]))\n : at !== -1\n ? id.slice(0, at + marker.length - 1)\n : null;\n\n imports = dir !== null && importsServerRenderer(dir);\n externalRenderers.set(name, imports);\n }\n\n if (!imports) return;\n\n const message =\n `${relative(process.cwd(), importer.split(\"?\")[0])} imports ${name}, which imports react-dom/server, and ` +\n serverRendererMessage(null).replace(/^react-dom\\/server cannot run/, \"that cannot run\");\n\n if (!warned.has(message)) {\n warned.add(message);\n warnedPackages.add(name);\n this.warn(message);\n }\n },\n load(id) {\n if (!id.startsWith(RENDERER_STUB)) return;\n\n const importer =\n decodeURIComponent(id.slice(RENDERER_STUB.length)) || null;\n const message = serverRendererMessage(\n appImporter(this as never, importer),\n );\n\n // The last node_modules segment: Bun's store nests the real package\n // under node_modules/.bun/<pkg>@<v>/node_modules/<pkg>.\n const viaPackage = [...(importer ?? \"\").matchAll(/\\/node_modules\\/((?:@[^/]+\\/)?[^/]+)\\//g)].at(-1)?.[1];\n\n if (\n this.environment.mode === \"build\" &&\n !warned.has(message) &&\n !(viaPackage && warnedPackages.has(viaPackage))\n ) {\n warned.add(message);\n this.warn(message);\n }\n\n // Every name the renderer exports, each throwing the fix when called.\n // A module that threw when loaded took the whole server down at boot\n // for one action nobody had called yet, and a stub with no exports\n // failed the build on MISSING_EXPORT with the message scrolled past.\n const refuse = `() => { throw new Error(${JSON.stringify(message)}) }`;\n\n return (\n SERVER_RENDERER_EXPORTS.map((name) => `export const ${name} = ${refuse};`).join(\"\\n\") +\n `\\nexport const version = \"0.0.0\";\\nexport default { ${SERVER_RENDERER_EXPORTS.join(\", \")}, version };\\n`\n );\n },\n };\n}\n\n/**\n * The project's typecheck, as part of the build.\n *\n * Runs once, in the first environment to start, after the route types have\n * been written by the config hook - so a link to a route that does not exist\n * is an error here and not a 404 found after deploying. Skipped where the\n * project is not doing this checking at all: no tsconfig.json, or no\n * typescript to run. Its own output is the message, because that is what\n * the developer would have read from `tsc`.\n */\nexport type TypecheckOutcome =\n | { ran: false; because: \"no tsconfig\" | \"no typescript\" }\n | { ran: true; ok: true; seconds: number }\n | { ran: true; ok: false; output: string };\n\n/**\n * `tsc --noEmit` on the project's own tsconfig, the way `check` runs it.\n *\n * Through package.json rather than a subpath: TypeScript's exports map does\n * not expose bin/tsc, and the bin field is where the name lives. Its output\n * is the message, because that is what the developer would have read.\n */\nexport function typecheckProject(root: string): TypecheckOutcome {\n const tsconfig = join(root, \"tsconfig.json\");\n\n if (!existsSync(tsconfig)) return { ran: false, because: \"no tsconfig\" };\n\n let tsc: string;\n\n try {\n const fromApp = createRequire(join(root, \"package.json\"));\n const manifest = fromApp.resolve(\"typescript/package.json\");\n const bin = (fromApp(manifest) as { bin?: string | Record<string, string> })\n .bin;\n const relative = typeof bin === \"string\" ? bin : bin?.tsc;\n\n if (!relative) return { ran: false, because: \"no typescript\" };\n\n tsc = join(dirname(manifest), relative);\n } catch {\n return { ran: false, because: \"no typescript\" };\n }\n\n const started = Date.now();\n const script = /\\.[cm]?js$/.test(tsc) || !/\\.\\w+$/.test(tsc);\n const result = spawnSync(\n script ? process.execPath : tsc,\n // Plain lines, not coloured ones: they go into a build error, and the\n // test that reads them is a reader too.\n [...(script ? [tsc] : []), \"--noEmit\", \"--pretty\", \"false\", \"-p\", tsconfig],\n { cwd: root, encoding: \"utf-8\", maxBuffer: 64 * 1024 * 1024 },\n );\n\n if (result.status === 0)\n return { ran: true, ok: true, seconds: (Date.now() - started) / 1000 };\n\n return {\n ran: true,\n ok: false,\n output: `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim(),\n };\n}\n\n/**\n * The project's typecheck, as part of the build.\n *\n * Runs once, in the first environment to start, after the route types have\n * been written by the config hook - so a link to a route that does not exist\n * is an error here and not a 404 found after deploying. Skipped where the\n * project is not doing this checking at all: no tsconfig.json, or no\n * typescript to run.\n */\nfunction typecheckPlugin(): Plugin {\n let ran = false;\n\n return {\n name: \"rsc-kit:typecheck\",\n apply: \"build\",\n buildStart() {\n if (ran || !typecheck || isWatch) return;\n\n ran = true;\n\n const outcome = typecheckProject(projectRoot);\n\n if (!outcome.ran) return;\n\n if (outcome.ok) {\n log(`typecheck: ok (${outcome.seconds.toFixed(1)}s)`);\n\n return;\n }\n\n throw new Error(\n \"[rsc-kit] The typecheck failed, so the build stops here.\\n\\n\" +\n outcome.output +\n \"\\n\\nrscKit({ typecheck: false }) builds without it.\",\n );\n },\n };\n}\n\n/**\n * Which server files import a client library, read off the rsc environment's\n * module graph once it is built. plugin-rsc classifies the client packages\n * (every package with react among its peers) and excludes them from the\n * server optimizers; that list is the one used here, minus this package -\n * a server component importing Link is the norm - and plugin-rsc's own.\n */\nfunction clientImportsAudit(): Plugin {\n return {\n name: \"rsc-kit:client-imports\",\n apply: \"build\",\n applyToEnvironment: (environment) => environment.name === \"rsc\",\n buildEnd() {\n const excluded =\n (resolvedConfig?.environments?.rsc?.optimizeDeps?.exclude as\n string[] | undefined) ?? [];\n const clientPackages = excluded.filter(\n (name) => !name.startsWith(\"@vitejs/plugin-rsc\"),\n );\n\n if (clientPackages.length === 0) return;\n\n clientLibraryImports = serverImportsOfClientPackages(\n {\n moduleIds: () => this.getModuleIds(),\n importedIds: (id) => this.getModuleInfo(id)?.importedIds ?? [],\n importers: (id) => this.getModuleInfo(id)?.importers ?? [],\n },\n {\n sourceDir,\n clientPackages,\n ignore: [PACKAGE_NAME, \"server-only\", \"client-only\"],\n },\n );\n },\n };\n}\n\n/**\n * A Nitro runtime plugin, so instrumentation.ts runs when the server starts.\n *\n * Nitro loads the rsc service at the first request, not at startup - so\n * without this, register() would run when the first visitor arrived, and a\n * bad environment would take down a server that had already reported itself\n * up. The plugin runs at app init and sends the service one request, which\n * loads the module; loading it begins register(), and the request waits for\n * it. Not on a Worker: there is no startup, and the first request is the\n * first chance to read a binding.\n */\nconst STARTUP_PLUGIN = `import { viteServices } from \"#nitro/virtual/vite-services\"\n\nexport default function rscKitStartup() {\n if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') return\n\n // The ssr service is the one Nitro's renderer asks; its fetch imports the\n // rsc entry and hands the request on. The rsc service's own export is the\n // handler function, not a { fetch }, so it cannot be probed directly.\n const ssr = viteServices.ssr\n if (!ssr) return\n\n // Two ways to fail, one outcome. register() rejecting is reported by the\n // module itself. instrumentation.ts throwing at import - an env schema\n // refusing - means the module never evaluated, so nothing in it can\n // report; the load rejects here instead. Either way a server that could\n // not bootstrap has nothing correct to serve, and says so and stops\n // rather than reporting itself up.\n ssr\n .fetch(new Request('http://rsc-kit.internal/_rsc/startup', { headers: { 'x-rsc-kit-startup': '1' } }))\n .then((response) => {\n if (!response.ok) throw new Error('the startup probe answered ' + response.status)\n })\n .catch((error) => {\n console.error('[rsc-kit] instrumentation.ts failed at startup:', error)\n\n if (typeof process !== 'undefined' && typeof process.exit === 'function') process.exit(1)\n })\n}\n`;\n\ninterface NitroModuleHost {\n options: {\n dev?: boolean;\n plugins?: string[];\n virtual?: Record<string, string | (() => string)>;\n /** Packages Nitro traces into .output/server/node_modules rather than bundling. */\n traceDeps?: (string | RegExp)[];\n /** Precompressed .gz/.br beside every public asset, served by Nitro with the encoding. */\n compressPublicAssets?: boolean | Record<string, unknown>;\n preset?: string;\n output: { serverDir: string };\n rollupConfig?: Record<string, unknown>;\n };\n hooks: { hook(name: \"compiled\", fn: () => void): void };\n}\n\n/**\n * Where NODE_ENV=development came from, and what to do about it.\n *\n * Vite reads NODE_ENV from its env files in this order, later winning, and\n * only when the process did not already set it - so the last file that\n * names it is the one that decided. No file naming it means the shell or\n * `--mode` did.\n */\nfunction nodeEnvSetIn(mode: string, envDir?: string | false): string | null {\n const files = [\".env\", \".env.local\", `.env.${mode}`, `.env.${mode}.local`];\n let culprit: string | null = null;\n\n // The project's root, not Vite's: this plugin points Vite's root at the\n // build directory, and the app's .env is read from the project root - by\n // Nitro's dotenv loading into process.env, and by Vite where envDir says\n // so. Both places are looked at; the project's is where the file is.\n const dirs = [...new Set([projectRoot, envDir || projectRoot])];\n\n for (const dir of dirs) for (const name of files) {\n const path = join(dir, name);\n\n if (!existsSync(path)) continue;\n\n const lines = readFileSync(path, \"utf-8\").split(\"\\n\");\n const at = lines.findIndex((line) => /^\\s*(?:export\\s+)?NODE_ENV\\s*=/.test(line));\n\n if (at !== -1) culprit = `${path}:${at + 1}`;\n }\n\n return culprit;\n}\n\nfunction refuseDevelopmentBuild(config: ResolvedConfig): string {\n const culprit = nodeEnvSetIn(config.mode, config.envDir);\n\n return (\n \"[rsc-kit] vite build is running as a development build, and the output cannot work: \" +\n \"the pages are compiled against React's development JSX runtime (jsxDEV), the server \" +\n \"bundles carry React's production build, and every route fails to render.\\n\\n\" +\n (culprit\n ? `NODE_ENV=development is set in ${culprit}. Remove that line - Vite sets NODE_ENV ` +\n \"itself: development under `vite`, production under `vite build`.\"\n : `NODE_ENV is \"${process.env.NODE_ENV ?? \"\"}\" from the environment or --mode ` +\n \"(mode: \" + JSON.stringify(config.mode) + \"). Build with NODE_ENV=production, or unset it.\")\n );\n}\n\nexport function rscKit(options: RscKitOptions = {}): PluginOption[] {\n resolvePaths(options);\n\n const serverExternals: (string | RegExp)[] = [\n ...RUNTIME_BUILTINS,\n ...[...DEFAULT_SERVER_EXTERNALS, ...(options.serverExternalPackages ?? [])].map(externalPackage),\n ];\n\n // Dependencies with a \"use client\" file that plugin-rsc would leave\n // external, because they never declared react as a peer. Bundled into the\n // server graphs so the directive is read, the same as a package that did.\n const bundledClientPackages = clientPackages(projectRoot);\n\n for (const name of bundledClientPackages) {\n console.warn(\n `[rsc-kit] bundling ${name}: it has \"use client\" files but does not declare react ` +\n \"as a peer dependency, so its components would otherwise run on the server.\",\n );\n }\n\n const routesPlugin: Plugin & { nitro?: unknown } = {\n name: \"rsc-kit\",\n\n // A Nitro module, which Nitro's Vite plugin collects from any plugin\n // that carries one. Only for a built server: the dev server evaluates\n // the entry through Vite's runner when it is first asked for, and there\n // is no earlier moment to offer.\n nitro: {\n name: \"rsc-kit\",\n setup(nitro: NitroModuleHost) {\n if (nitro.options.dev) return;\n\n // Said at the end of a bun build, only when true: which module keeps\n // `bun build --compile --bytecode` from applying, and where. Bun\n // itself names no file and exits 0. See bytecodeCheck.ts.\n if (nitro.options.preset === \"bun\") {\n nitro.hooks.hook(\"compiled\", () => {\n const note = bytecodeNote(nitro.options.output.serverDir);\n\n if (note) log(note);\n });\n }\n\n // External at Nitro's layer too. The Vite build leaves these as\n // imports, and Nitro would then bundle them into its own chunks -\n // which for a native package fails at load, and for a polyfill like\n // reflect-metadata runs it after the chunk that checks for it.\n // Traced, each is copied into .output/server/node_modules and\n // imported by the built server the way its author expected.\n // Only the ones the tracer can find by name. It says so, once per\n // name, for every entry it cannot - a list of every native package\n // anyone might install is mostly ones this app does not have, and\n // one the app has only through a dependency, under an isolated\n // store, is reached through that dependency and not by name.\n // And the polyfills, by pattern: bundled, one merged into the chunk\n // of the dependency that checks for it, after that chunk's imports -\n // and the server did not boot. External, the entry's import of it\n // comes first. See polyfillsToTrace.\n nitro.options.traceDeps = [\n ...(nitro.options.traceDeps ?? []),\n ...traceableByName([...DEFAULT_SERVER_EXTERNALS, ...(options.serverExternalPackages ?? [])], projectRoot),\n ...polyfillsToTrace(FIRST_POLYFILLS, projectRoot),\n ];\n\n // The assets, precompressed at build and served with their encoding\n // by Nitro's own static handler; the host gzips the rest as it\n // answers. Between them a bun or node server answering the internet\n // by itself sends nothing raw. A config that set this keeps it.\n // Nitro's default is a literal false, so ?? would not do; an object\n // is a configuration and is kept.\n if (typeof nitro.options.compressPublicAssets !== \"object\") nitro.options.compressPublicAssets = true;\n\n nitro.options.virtual ??= {};\n\n // The names of functions survive Nitro's bundle. The pages were\n // prerendered against Vite's own server bundles, where a dependency\n // is loaded from node_modules under the names it was written with;\n // Nitro then bundles that dependency into the server, and renames a\n // function whose name collides with another's - J becomes J2 - and\n // `name` follows the identifier. React's resume of a stored shell\n // compares the component names it recorded with the ones it meets,\n // and a renamed one is \"Expected the resume to render <J> in this\n // slot but instead it rendered <J2>\", on every request, with the\n // hole rendered in the browser instead. keepNames pins `name` to\n // what the source said, whatever the identifier became.\n nitro.options.rollupConfig = {\n ...(nitro.options.rollupConfig ?? {}),\n output: { keepNames: true, ...((nitro.options.rollupConfig as { output?: object } | undefined)?.output ?? {}) },\n } as never;\n\n // A polyfill a dependency checks for at module evaluation, loaded\n // before any service. The bundler places an external import after\n // the chunk imports of the module that had it, whatever the source\n // said, so reflect-metadata came up after tsyringe (under\n // @peculiar/x509, under @simplewebauthn/server) - by luck survivable\n // run as a directory, fatal compiled into a binary. A Nitro plugin\n // is evaluated by the entry itself, and the services that carry the\n // app are loaded lazily after it; imported by file, the polyfill is\n // inlined there and runs first wherever the server runs. Only for a\n // project whose graph has it.\n const polyfills = FIRST_POLYFILLS.map((name) => packageEntryInGraph(projectRoot, name)).filter(\n (entry): entry is string => entry !== null,\n );\n\n if (polyfills.length) {\n nitro.options.virtual[\"#rsc-kit/polyfills\"] =\n polyfills.map((entry) => `import ${JSON.stringify(entry)};`).join(\"\\n\") +\n \"\\nexport default () => {};\\n\";\n nitro.options.plugins = [\"#rsc-kit/polyfills\", ...(nitro.options.plugins ?? [])];\n }\n\n if (!instrumentationFile()) return;\n\n nitro.options.virtual[\"#rsc-kit/startup\"] = STARTUP_PLUGIN;\n nitro.options.plugins = [...(nitro.options.plugins ?? []), \"#rsc-kit/startup\"];\n },\n },\n\n config(_config, env) {\n if (!existsSync(appDir)) {\n throw new Error(\n `[rsc-kit] No app directory at ${appDir} — nothing to build.`,\n );\n }\n\n // Both maps, not one: the config hook runs again when the config\n // changes under a dev server, and a route.ts or a synthesised\n // robots.txt left over from the previous run read as a duplicate.\n components.clear();\n apiRoutes.clear();\n discover(appDir);\n registerMetadataRoutes(appDir);\n registerOpenApiRoutes();\n siteHosts = ownHosts(rootMetadataBase(appDir), hostsOption);\n\n // Silent when it worked. The names were printed on every dev start and\n // every build — thirty of them for a middling app, above the output that\n // actually says something, and the build's classification table lists\n // every route anyway.\n //\n // Nothing found is the case worth a word, because the app still builds:\n // a server with no routes answers 404 to everything, which reads as a\n // routing bug rather than as an empty directory. Fatal for a build,\n // said out loud for a dev server — where deleting the last page while\n // editing is a state to pass through, not to be thrown out of.\n if (components.size === 0) {\n const message =\n `No routes under ${appDir}. A directory with a page.tsx in it is a route; ` +\n \"without one there is nothing to serve.\";\n\n if (env.command === \"build\") throw new Error(`[rsc-kit] ${message}`);\n\n log(message);\n }\n\n const notClient = validateErrorBoundaries();\n\n if (notClient.length) {\n throw new Error(\n \"[rsc-kit] An error.tsx must be a client component.\\n\\n\" +\n notClient.join(\"\\n\") +\n \"\\n\\nAdd 'use client' at the top. It is rendered inside an error boundary and is\\n\" +\n \"handed a reset() callback to call, neither of which a server component can do.\",\n );\n }\n\n const loadingErrors = validateLoadingBoundaries();\n\n if (loadingErrors.length) {\n throw new Error(\n \"[rsc-kit] A page that blocks before it can paint needs a loading.tsx boundary.\\n\\n\" +\n loadingErrors.join(\"\\n\") +\n \"\\n\\nAdd loading.tsx in the page directory (or a parent), or move the slow work\\n\" +\n \"into a child component wrapped in its own <Suspense> so the page can paint.\",\n );\n }\n\n // Before the entries, because the app's own source imports these and the\n // module graph is walked as soon as this hook returns.\n const manifest = routeManifest();\n\n writeHostBindings(manifest);\n\n if (existsSync(genDir)) rmSync(genDir, { recursive: true, force: true });\n mkdirSync(genDir, { recursive: true });\n\n // Where a url this server does not own is handed on. Resolved exactly as\n // host calls resolve their endpoint, from the app's own .env, so the two\n // cannot end up pointing at different backends. Development only: a\n // build's server.ts decides this for itself.\n const backendEnv = loadEnv(env.mode, projectRoot, \"\");\n\n // Only a backend this server could actually call. The shared secret is\n // what makes one a backend rather than a url that happens to be in the\n // environment — APP_URL is not a Laravel-only name, and a JavaScript\n // host that sets it for its own reasons must not find its 404s being\n // posted to it. Host calls gate on exactly the same pair, so the two\n // cannot end up disagreeing about whether a backend is there.\n //\n // Naming devFallback explicitly opts in regardless: someone who wrote\n // the address down means it.\n const backendSecret =\n hostCallOptions?.secret ?? backendEnv.RSC_HOST_CALL_SECRET;\n const detected = backendSecret\n ? (hostCallOptions?.endpoint ??\n backendEnv.RSC_BACKEND ??\n backendEnv.APP_URL ??\n \"\")\n : \"\";\n\n const fallbackOrigin =\n options.devFallback === false ? \"\" : (options.devFallback ?? detected);\n\n writeFileSync(\n join(genDir, \"entry.rsc.tsx\"),\n generateEntryRsc(fallbackOrigin),\n );\n writeFileSync(join(genDir, \"entry.ssr.tsx\"), generateEntrySsr());\n writeFileSync(join(genDir, \"entry.browser.tsx\"), generateEntryBrowser());\n\n // Written beside the entries, for a host to read instead of walking the\n // route tree itself. Laravel scans it a second time today; a JS host\n // would otherwise have to write a third walk of the same directories.\n writeFileSync(\n join(outDir, \"routes.json\"),\n JSON.stringify(manifest, null, 2),\n );\n\n return {\n // Off, not merely unused: Vite warns when publicDir sits inside outDir,\n // and assetsDir is normally a directory under the build output. An app\n // that wants static files can set its own publicDir outside it.\n publicDir: false,\n /**\n * The mode this was built in, baked into the server bundles.\n *\n * Vite substitutes `process.env.NODE_ENV` for a client build and\n * leaves it alone for the server ones, because server code runs where\n * `process.env` is real. Reasonable in general, and wrong here: React\n * picks its build from that expression when its module is first\n * evaluated, so leaving it to the runtime makes every server carry a\n * NODE_ENV it must not get wrong — and a production bundle started\n * without one renders every page perfectly and hydrates none of them.\n *\n * The build already knows which mode it is. Saying so here means the\n * answer travels with the bundle instead of with whoever starts it.\n */\n define: {\n \"process.env.NODE_ENV\": JSON.stringify(\n env.mode === \"development\" ? \"development\" : \"production\",\n ),\n __RSC_OFFLINE__: JSON.stringify(offline),\n },\n /*\n * This package's client modules are served as source, never\n * pre-bundled.\n *\n * Vite treats an installed package as a dependency and optimizes it,\n * which binds its JSX imports to one particular optimized\n * react/jsx-runtime chunk. The moment Vite discovers another dependency\n * and re-optimizes, that chunk's hash changes and the binding breaks:\n *\n * SyntaxError: The requested module '.../react_jsx-runtime.js?v=...'\n * does not provide an export named 't'\n *\n * Which reads as a React or a bundler bug. What it does is take down\n * every page importing Link or Form — the shell renders, hydration\n * throws, React unmounts the document, and the page goes blank with\n * that message the only clue.\n *\n * Excluded rather than pinned, because the package already ships ESM\n * that needs no conversion. The app's own excludes are kept.\n */\n optimizeDeps: {\n exclude: [PACKAGE_NAME, ...(_config.optimizeDeps?.exclude ?? [])],\n // Every \"use client\" file, so the browser's dependencies are all\n // found at startup. The client entry reaches only the engine and\n // React; the app's client components arrive through payloads, page\n // by page, and a dependency first seen on the third page visited\n // re-optimised every pre-bundle under a running page - two Reacts,\n // a blank document, then Vite's own reload. See clientEntries.\n // Naming entries replaces the input, so the browser entry is named\n // too, or the engine and React would be the ones left out.\n entries: [\n ...(Array.isArray(_config.optimizeDeps?.entries)\n ? _config.optimizeDeps.entries\n : _config.optimizeDeps?.entries\n ? [_config.optimizeDeps.entries]\n : []),\n // Entries are globs: a route group's parentheses, or a bracket\n // in a dynamic segment, would otherwise read as pattern syntax\n // and match nothing - and the scanner would crawl nothing, quietly.\n ...[\n join(genDir, \"entry.browser.tsx\"),\n ...engineClientEntries(),\n ...clientEntries(sourceDir),\n ].map((file) => file.replace(/[()[\\]{}*?!+@]/g, \"\\\\$&\")),\n ],\n rolldownOptions: {\n ...(_config.optimizeDeps?.rolldownOptions ?? {}),\n plugins: [\n clientScanPlugin(),\n ...arrayOf(_config.optimizeDeps?.rolldownOptions?.plugins),\n ],\n },\n },\n // Public URL for browser-facing client assets, and a BUILD concern\n // only: it says where the built files will be served from.\n //\n // Applying it in dev makes it Vite's public base, and then the dev\n // server answers pages only under that prefix — every route 404s with\n // \"The server is configured with a public base URL\", which reads as a\n // routing bug rather than as this line. In dev the pages are the root;\n // the assets come from the same origin either way.\n base: \"/\",\n // Where the generated entries live, so Vite resolves them as its own\n // source. A build concern only.\n //\n // Not during preview. `vite preview` serves what was built, and Nitro's\n // preview reads its build info from `<vite root>/node_modules/.nitro` —\n // so pointing the root at this directory sent it looking somewhere no\n // build ever writes, and every preview failed with \"Cannot load nitro\n // build info. Make sure to build first.\" after a build that had just\n // succeeded.\n ...(env.isPreview ? {} : { root: outDir }),\n // Force single instances of React/RSC runtime — critical when the\n // package is symlinked (local dev / monorepo), else \"use client\"\n // components SSR against a second React copy and hooks throw.\n //\n // react-server-dom-webpack is deliberately absent: @vitejs/plugin-rsc\n // vendors its own copy, nothing here imports the specifier, and the\n // built bundles reference it zero times — deduping it was a no-op left\n // over from the hand-rolled engine.\n resolve: {\n dedupe: [\"react\", \"react-dom\", \"@vitejs/plugin-rsc\"],\n // `import Link from '<packageAlias>/Link'` resolves to the client\n // runtime shipped here, for hosts that vendor this package outside\n // node_modules. Installed from npm the name resolves on its own.\n alias: aliasEntries(),\n },\n build: {\n emptyOutDir: true,\n // Rolldown reports, after every build, which plugin hooks took\n // the time. Here the answer is always the same: the typecheck hook\n // - tsc, run before the bundle on purpose, as `next build` does -\n // and the two resolvers that look at every import. A paragraph\n // saying so at the end of each docker build is not a finding.\n rollupOptions: { checks: { pluginTimings: false } },\n },\n // What reaches the browser. Vite's own VITE_ prefix, and PUBLIC_ - the\n // scaffold's spelling, and Next's minus its brand - so a variable\n // named for a port reads through import.meta.env without a config\n // line. A config that set its own prefixes keeps them; Vite merges.\n envPrefix: [\"VITE_\", \"PUBLIC_\"],\n environments: {\n // Server bundles — stay under the (non-public) out dir. `bun` and\n // `bun:*` are the runtime's own modules, like `node:*`: nothing to\n // bundle, and a build under Node has nothing to resolve them to.\n // Left as imports for the runtime that has them.\n rsc: {\n build: {\n rollupOptions: {\n input: { index: join(genDir, \"entry.rsc.tsx\") },\n external: serverExternals,\n },\n },\n resolve: { noExternal: bundledClientPackages },\n optimizeDeps: { exclude: bundledClientPackages },\n },\n ssr: {\n build: {\n rollupOptions: {\n input: { index: join(genDir, \"entry.ssr.tsx\") },\n external: serverExternals,\n },\n },\n resolve: { noExternal: bundledClientPackages },\n optimizeDeps: { exclude: bundledClientPackages },\n },\n // Client bundle — emitted into public/ for the web server to serve.\n client: {\n build: {\n outDir: publicAssetsDir,\n emptyOutDir: true,\n rollupOptions: {\n input: { index: join(genDir, \"entry.browser.tsx\") },\n output: { chunkFileNames: clientChunkFileName },\n },\n },\n },\n },\n };\n },\n\n /**\n * Restart when the route tree changes shape.\n *\n * The entries and the route table are generated in `config()`, which runs\n * once. An edit to a page is picked up because Vite re-evaluates the\n * module, but a page that did not exist when the server started is not in\n * the table — the request 404s, and the file is right there on disk, which\n * is a confusing thing to be told.\n *\n * Only add and unlink: a change to an existing file needs no new table,\n * and restarting on every keystroke would throw away the module graph for\n * nothing.\n */\n configureServer(server) {\n // The icons and share images live in app/, which nothing serves; the\n // build copies them beside the client output. There is no output while\n // developing, so the same hrefs the head tags carry are answered from\n // app/ here - and the web manifest with them - or the tab has no icon\n // and the console a 404 for a file that is right there.\n server.middlewares.use((req, res, next) => {\n const url = (req.url ?? \"\").split(\"?\")[0];\n\n // A worker registered by a production run on this origin - `bun run\n // start` on the port the dev server uses next - outlives that run and\n // answers the dev server's documents from its cache: a stored page is\n // cache-first, so a refresh brings back yesterday's document with\n // yesterday's module hashes, and a 504 for each. The browser fetches\n // /sw.js again on every navigation to look for an update; in\n // development that fetch gets a worker whose only job is to remove\n // itself, its caches, and reload the pages it controlled.\n // robots.txt, a hand-written sitemap.xml, humans.txt: beside the root\n // layout, served at the root. The build copies them beside the client\n // output; here they are read from app/.\n if (url.startsWith(\"/\") && rootFiles.includes(url.slice(1))) {\n res.setHeader(\"Content-Type\", rootFileType(url.slice(1)));\n res.end(readFileSync(join(sourceDir, \"app\", url.slice(1))));\n\n return;\n }\n\n if (url === \"/sw.js\") {\n res.setHeader(\"Content-Type\", \"text/javascript\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(DEV_WORKER);\n\n return;\n }\n\n if (webManifestOptions && url === MANIFEST_PATH) {\n res.setHeader(\"Content-Type\", \"application/manifest+json\");\n res.end(webManifest(webManifestOptions));\n\n return;\n }\n\n const asset = allAppAssets(foundAssets).find((a) => a.href === url);\n const file = asset ? join(sourceDir, \"app\", asset.file) : null;\n\n if (!asset || !file || !existsSync(file)) return next();\n\n res.setHeader(\"Content-Type\", typeOf(asset.file));\n createReadStream(file).pipe(res);\n });\n\n // rpc() has to reach the backend while the dev server is serving.\n //\n // A built deployment installs this itself: the server running\n // createRscHandler passes `hostCalls`. Nothing does that here, and with\n // no host installed every rpc() is refused — so a page whose data comes\n // from the backend renders its shell and then blanks, which reads as a\n // hydration bug rather than a missing wire.\n server.httpServer?.once(\"listening\", async () => {\n const env = server.environments?.rsc as\n | {\n runner?: { import(id: string): Promise<Record<string, unknown>> };\n }\n | undefined;\n\n if (!env?.runner) return;\n\n // The app's own .env, unprefixed. A Laravel app already has both of\n // these, which is what makes this need no configuring: APP_URL is the\n // backend and RSC_HOST_CALL_SECRET is the secret it checks.\n const fromEnv = loadEnv(server.config.mode, projectRoot, \"\");\n const secret = hostCallOptions?.secret ?? fromEnv.RSC_HOST_CALL_SECRET;\n const origin =\n hostCallOptions?.endpoint ?? fromEnv.RSC_BACKEND ?? fromEnv.APP_URL;\n\n if (!secret || !origin) return;\n\n const path =\n hostCallOptions?.path ??\n fromEnv.RSC_HOST_CALL_PATH ??\n \"/__rsc/host-call\";\n const endpoint = origin.replace(/\\/$/, \"\") + path;\n\n try {\n const entry = await env.runner.import(join(genDir, \"entry.rsc.tsx\"));\n const install = entry.installHostFn as\n ((fn: unknown) => void) | undefined;\n\n install?.(httpHostCalls({ endpoint, secret }));\n } catch (error) {\n // Reported rather than thrown: the dev server is still useful for\n // every page that needs no data, and a failure here would otherwise\n // look like the server refusing to start.\n server.config.logger.warn(\n `[rsc-kit] could not wire host calls to ${endpoint}: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n });\n\n // Written once the server is listening, because only then is the port\n // known. Removed on shutdown so a backend can tell a dev server that is\n // gone from one that is merely slow to answer.\n if (hotFile) {\n const remove = () => {\n try {\n if (existsSync(hotFile)) rmSync(hotFile);\n } catch {}\n };\n\n server.httpServer?.once(\"listening\", () => {\n // The url Vite resolved, not one built from the port. A dev server\n // whose port is already taken on IPv4 binds IPv6 only and keeps the\n // number — so http://127.0.0.1:<port> is a reachable-looking address\n // that nothing answers, and the backend reports the renderer as down\n // while it is plainly running.\n const resolved = server.resolvedUrls?.local?.[0];\n const address = server.httpServer?.address();\n\n const url =\n resolved ??\n (typeof address === \"object\" && address\n ? `http://${address.family === \"IPv6\" ? `[${address.address}]` : address.address}:${address.port}`\n : null);\n\n if (!url) return;\n\n mkdirSync(dirname(hotFile), { recursive: true });\n writeFileSync(hotFile, url.replace(/\\/$/, \"\"));\n });\n\n for (const signal of [\"SIGINT\", \"SIGTERM\", \"exit\"] as const) {\n process.once(signal, remove);\n }\n\n server.httpServer?.once(\"close\", remove);\n }\n\n const shapes = new Set(ROUTE_FILES.map((name) => name));\n\n const affectsRouting = (file: string): boolean => {\n if (!file.startsWith(sourceDir)) return false;\n\n const base = file.split(\"/\").pop() ?? \"\";\n const stem = base.replace(/\\.(tsx|jsx|ts|js)$/, \"\");\n\n // The host's route-config file, whatever it named it. Hardcoding one\n // here would put a backend's convention back into a plugin that is\n // published without any — generic-host.test.ts fails if it reappears.\n return (\n (base !== stem && shapes.has(stem)) ||\n SECTION_FILE.test(base) ||\n (routeConfig !== null && base === routeConfig.file)\n );\n };\n\n const restart = (file: string) => {\n if (!affectsRouting(file)) return;\n\n server.config.logger.info(\n `[rsc-kit] route tree changed (${file.slice(sourceDir.length + 1)}) — restarting`,\n );\n void server.restart();\n };\n\n // Watched explicitly: the Vite root is the *out* directory, so the app's\n // source tree is outside it and nothing would report a file appearing.\n server.watcher.add(sourceDir);\n\n server.watcher.on(\"add\", restart);\n server.watcher.on(\"unlink\", restart);\n\n // The host actions are read once, in config(), from the file the\n // backend writes; the \"use server\" stubs are generated from it. A\n // backend that writes a new action - `make:rsc-action` under a running\n // dev server - rewrites the file, and until the server started again\n // the stub was not there to import. Any event: the file appears on a\n // first action, changes on the next, and goes when the last is removed.\n const hostActionsPath = join(projectRoot, HOST_ACTIONS_FILE);\n const hostActionsChanged = (file: string) => {\n if (file !== hostActionsPath) return;\n\n server.config.logger.info(\n `[rsc-kit] ${HOST_ACTIONS_FILE} changed — restarting`,\n );\n void server.restart();\n };\n\n server.watcher.add(hostActionsPath);\n server.watcher.on(\"add\", hostActionsChanged);\n server.watcher.on(\"change\", hostActionsChanged);\n server.watcher.on(\"unlink\", hostActionsChanged);\n },\n\n /**\n * Freeze what can be frozen, once every bundle exists.\n *\n * `buildApp` runs after all three environments are built, which is the\n * first moment the rsc bundle can be imported — prerendering is the app\n * rendering itself, so it needs the thing the build just produced. This\n * plugin is ordered after @vitejs/plugin-rsc's, so its own buildApp has\n * already run and the bundles are on disk.\n *\n * Automatic because the alternative is a second command to remember, and\n * forgetting it costs the whole difference silently: every page still\n * works, each one just renders again for every visitor.\n *\n * Skipped in watch mode. A rebuild on every keystroke that also re-renders\n * every route is not a feedback loop anyone wants.\n */\n async buildApp(builder) {\n if (isWatch) return;\n\n // Say what the build did, even when it stored nothing.\n //\n // Turning prerendering off used to print no classification at all — no\n // marks, no legend, no counts — so a build that stored nothing looked\n // exactly like a build that had not got to that step. Every route renders\n // per visitor now, which is a thing worth being told rather than left to\n // infer from an absence.\n if (!prerenderAfterBuild) {\n reportAllDynamic();\n\n return;\n }\n\n // Asked of the build rather than assumed from `outDir`. The two layouts\n // differ — <outDir>/dist/rsc on its own, node_modules/.nitro/… under\n // Nitro — and hard-coding the first is what silently skipped the second.\n // Both environments emit `index.js`, so this is one path, not a branch.\n const rscOut =\n builder?.environments?.rsc?.config?.build?.outDir ??\n join(outDir, \"dist/rsc\");\n const bundle = resolveRscBundle(rscOut);\n\n // Where the frozen pages go, which is not the same question.\n //\n // On its own the plugin owns the output and server.ts reads <outDir>/static\n // from the repository. Under Nitro the deployment is `.output/` and\n // nothing outside it is copied to the server — so pages written anywhere\n // else exist on the build machine and nowhere after that. They go beside\n // the server bundle instead, and buildApp runs before Nitro assembles, so\n // they are in place by the time it does.\n const clientOut = builder?.environments?.client?.config?.build?.outDir;\n const staticDir = clientOut\n ? join(dirname(clientOut), \"server\", NITRO_STATIC_DIR)\n : join(outDir, NITRO_STATIC_DIR);\n\n const { frozen, results } = await prerenderAfterBundles(\n bundle,\n staticDir,\n clientOut ?? publicAssetsDir,\n builder ? knownActionsOf(builder.config, projectRoot) : [],\n );\n\n // The same pages once more, as a module. A Worker has no filesystem, and\n // until this existed every Cloudflare deploy rendered its \"static\" pages\n // live, silently - the reader found no directory and fell through. The\n // module is uploaded as a sibling of the bundle and imported at runtime\n // when the directory is not there. Only under Nitro, whose presets are\n // the ones without a disk; on its own the plugin serves from outDir.\n if (clientOut && existsSync(staticDir)) {\n const { inlineModuleName, inlineModuleSource, compileEntrySource } =\n await import(\"./files.js\");\n\n writeFileSync(\n join(dirname(staticDir), inlineModuleName(NITRO_STATIC_DIR)),\n await inlineModuleSource(staticDir),\n );\n\n // And the entry a binary is compiled from, so the pages above end up\n // inside it rather than rendered live: bun build --compile\n // .output/server/compile.mjs. The scaffold's script names it.\n writeFileSync(\n join(dirname(staticDir), \"compile.mjs\"),\n compileEntrySource(NITRO_STATIC_DIR),\n );\n }\n\n // Manifest first. The service worker precaches whatever it finds in this\n // directory, so writing it afterwards leaves it out of the list — and an\n // installed app whose manifest is the one file that needs the network is\n // the wrong way round.\n copyAppAssets(clientOut ?? publicAssetsDir);\n if (webManifestOptions)\n writeWebManifest(clientOut ?? publicAssetsDir, webManifestOptions);\n if (offline) {\n writeServiceWorker(\n clientOut ?? publicAssetsDir,\n frozen,\n offlineFallback(frozen, results),\n );\n }\n },\n\n configResolved(config: ResolvedConfig) {\n // A build that is not a production build cannot work here, and the\n // way it fails is opaque: plugin-react emits the development JSX\n // runtime (jsxDEV), the server bundles resolve React's production\n // build, and every route fails to render with React's \"message\n // omitted in production builds\". The usual cause is NODE_ENV=development\n // in a .env file, which Vite honours - a line the scaffold itself once\n // wrote. Named, with the file and line, before any of that happens.\n //\n // Refused rather than overridden, because a plugin cannot override it:\n // Vite notes whether NODE_ENV was set before it loads the config file\n // and applies the .env value after the config hooks have run, so an\n // assignment here is overwritten - and patching the resolved config\n // afterwards leaves the client bundle's process.env.NODE_ENV and\n // import.meta.env.DEV already decided, which is a production server\n // serving a development client.\n if (config.command === \"build\" && !config.isProduction) {\n throw new Error(refuseDevelopmentBuild(config));\n }\n\n isWatch = config.build?.watch != null;\n resolvedConfig = config;\n\n // Keep Nitro's hot-update handler out of the rsc environment.\n //\n // For every environment that is not the browser's, Nitro treats a\n // changed module the browser does not also have as \"the server changed,\n // reload the page\": it sends full-reload and returns an EMPTY module list.\n // A returned list replaces the modules every later hook sees — so\n // plugin-rsc's handler, which is the one that knows a server component\n // can be refetched in place, gets zero modules, returns early, and never\n // sends rsc:update.\n //\n // That was a crude reload on a plain app and no reload at all on one\n // with Tailwind, whose own hook runs earlier still and rewrites the\n // change as a CSS update — so Nitro saw nothing server-only either, and\n // an edit to a page did nothing in the browser.\n //\n // The rsc environment's reload story is plugin-rsc's, not Nitro's.\n // Nitro's hook is left alone for every other environment.\n type HotHook = (\n this: { environment?: { name?: string } },\n ctx: unknown,\n ) => unknown;\n const nitroMain = config.plugins.find((p) => p.name === \"nitro:main\") as\n { hotUpdate?: HotHook } | undefined;\n\n if (nitroMain?.hotUpdate) {\n const original = nitroMain.hotUpdate;\n\n nitroMain.hotUpdate = function (this, ctx) {\n if (this.environment?.name === \"rsc\") return;\n\n return original.call(this, ctx);\n } as HotHook;\n }\n // rsc() splits the module graph into client and server; a JSX transform\n // placed ahead of it sees the wrong graph and fails in ways that are hard\n // to trace back here. Cheaper to refuse than to let it through.\n const names = config.plugins.map((p) => p.name);\n const rscAt = names.findIndex((n) => n === \"rsc\" || n.startsWith(\"rsc:\"));\n const jsxAt = names.findIndex((n) => JSX_PLUGIN_PATTERN.test(n));\n\n if (rscAt !== -1 && jsxAt !== -1 && jsxAt < rscAt) {\n throw new Error(\n `[rsc-kit] Plugin \"${names[jsxAt]}\" is resolved ahead of rsc(), so it would ` +\n \"transform JSX before the client/server split.\\n\" +\n \"Put rscKit() first in your plugins array. If it already is, that plugin \" +\n \"sets enforce: 'pre' and needs to be moved after rsc() explicitly.\",\n );\n }\n },\n };\n\n // rsc() ships as several plugins, and it has to lead. A promise is a legal\n // member of a Vite plugins array and is flattened in place, so this keeps\n // rscKit() one entry in the app's config while still resolving the\n // plugin at call time — see appPluginRsc for why that matters.\n // With Nitro, the server handler is Nitro's — it takes the rsc entry's\n // default export and builds the server around it. Leaving plugin-rsc's own\n // handler in place means two things claiming the same role.\n return [\n appPluginRsc({\n serverHandler: false,\n // One chunk per client component, rather than one for the whole app.\n //\n // plugin-rsc already loads a client reference with `await import()`, so\n // the browser only fetches what a page actually renders — but its default\n // groups every reference by the SERVER chunk that proxies it, and this\n // package builds the server as a single chunk. So every client component\n // in an app landed in one group, and a page with a button pulled in the\n // editor, the chart and the map that live on other routes.\n //\n // Grouping by the component's own module restores the split the dynamic\n // import was there to make use of.\n clientChunks: (meta) => meta.normalizedId,\n ...actionEncryptionKey(),\n }),\n barrelImportsPlugin(),\n useSsrModules(),\n serverRendererInRsc(),\n metadataRoutesPlugin(),\n openApiPlugin(),\n extendableClientReferences(),\n typecheckPlugin(),\n clientImportsAudit(),\n routesPlugin,\n ];\n}\n\n/**\n * @vitejs/plugin-rsc, resolved from the app rather than from here.\n *\n * `isRunnableDevEnvironment` is an instanceof check that plugin-rsc runs\n * against its own copy of Vite. Two copies — this package's and the app's —\n * make a perfectly runnable environment report false, and the message names\n * the environment rather than the duplication.\n *\n * That is not a hypothetical layout. It is what installing this package from a\n * directory produces, because the checkout carries its own devDependencies:\n * the app runs its Vite, this file imports that Vite's plugin, and the two\n * never recognise each other. A build never reaches the check, so everything\n * works right up until dev mode.\n *\n * Resolving from the project root gets the app's copy, whose own `vite` import\n * then resolves to the app's Vite as well — one pair, and the check passes.\n */\n/**\n * Where the key that encrypts bound action arguments comes from.\n *\n * A server action can close over server-side values, and React sends those to\n * the browser encrypted so the page cannot read them. The process that decrypts\n * them on the way back has to hold the same key.\n *\n * By default plugin-rsc generates one per build and bakes it in. Every instance\n * of one build therefore agrees, and the only exposure is a deploy: a browser\n * holding a page from the old build calls an action on the new one, and the\n * key has changed underneath it. The call fails with nothing useful in it.\n *\n * Setting RSC_ACTION_ENCRYPTION_KEY makes the key outlive the build and closes\n * that window. It is read at RUNTIME, not baked in, so the same artifact can be\n * deployed anywhere — but it must then be set everywhere the app runs, and set\n * to the same value. Half-configured is worse than unconfigured: instances\n * would disagree, and the failure looks like an intermittently broken action.\n *\n * Unset, the build-time key is used and nothing changes. That is the default\n * because it is the one that cannot be got half right.\n */\nfunction actionEncryptionKey(): { defineEncryptionKey?: string } {\n if (!process.env.RSC_ACTION_ENCRYPTION_KEY) return {};\n\n // An expression, not a value: plugin-rsc substitutes this source text where\n // the key is read, so what ships is the lookup rather than the secret. A\n // literal here would put the key in the bundle, which is the thing being\n // avoided.\n return { defineEncryptionKey: \"process.env.RSC_ACTION_ENCRYPTION_KEY\" };\n}\n\nasync function appPluginRsc(\n options: Parameters<typeof rsc>[0] = {},\n): Promise<PluginOption[]> {\n try {\n // Resolved against a file *in* the root, since a directory specifier\n // resolves relative to its parent.\n const fromApp = createRequire(join(projectRoot, \"package.json\"));\n const entry = fromApp.resolve(\"@vitejs/plugin-rsc\");\n const mod = (await import(pathToFileURL(entry).href)) as {\n default: typeof rsc;\n };\n\n return (mod.default ?? rsc)(options);\n } catch {\n // The app does not have its own; one copy, and the bundled import is it.\n return rsc(options);\n }\n}\n"]}
1
+ {"version":3,"file":"vite.js","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,+EAA+E;AAC/E,2DAA2D;AAC3D,EAAE;AACF,4CAA4C;AAC5C,oFAAoF;AACpF,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,4EAA4E;AAC5E,yEAAyE;AAEzE,OAAO,EACL,YAAY,EACZ,UAAU,EACV,SAAS,EACT,WAAW,EACX,YAAY,EACZ,MAAM,EACN,QAAQ,EACR,aAAa,EACb,gBAAgB,GACjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,aAAa,EAA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,EAAE;QACrB,aAAa,EAAE;QACf,mBAAmB,EAAE;QACrB,oBAAoB,EAAE;QACtB,aAAa,EAAE;QACf,0BAA0B,EAAE;QAC5B,eAAe,EAAE;QACjB,kBAAkB,EAAE;QACpB,YAAY;KACb,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAS,mBAAmB;IAC1B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,yBAAyB;QAAE,OAAO,EAAE,CAAC;IAEtD,4EAA4E;IAC5E,yEAAyE;IACzE,yEAAyE;IACzE,WAAW;IACX,OAAO,EAAE,mBAAmB,EAAE,uCAAuC,EAAE,CAAC;AAC1E,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAO,GAA8B,EAAE;IAEvC,IAAI,CAAC;QACH,qEAAqE;QACrE,mCAAmC;QACnC,MAAM,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;QACjE,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC;QACpD,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAEnD,CAAC;QAEF,OAAO,CAAC,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAAC,MAAM,CAAC;QACP,yEAAyE;QACzE,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// File-based routing for React Server Components, as a Vite plugin.\n//\n// Host-agnostic by design: it discovers an app/ route tree, generates the three\n// entries, and exposes a render contract over a global the host installs. What\n// that global is called, and how a route declares dynamic props, are options —\n// nothing here knows or cares which backend is driving it.\n//\n// import { rscKit } from '<package>/vite'\n// export default defineConfig({ plugins: [rscKit(), react({ compiler: true })] })\n//\n// The plugin discovers the app/ route tree, generates the three entries that\n// carry the route composition and the worker's render contract, and supplies\n// the structural config (entries, output dirs, base). @vitejs/plugin-rsc is\n// included here so it always runs before any react() layer the app adds.\n\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n createReadStream,\n} from \"node:fs\";\nimport { gzipSync } from \"node:zlib\";\nimport { createHash } from \"node:crypto\";\nimport { createRequire } from \"node:module\";\nimport { spawnSync } from \"node:child_process\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport rsc, { getPluginApi } from \"@vitejs/plugin-rsc\";\nimport { loadEnv } from \"vite\";\nimport type { PrerenderResult } from \"./prerender.js\";\nimport { REPORT_FILE, buildReport } from \"./buildReport.js\";\nimport { MANIFEST_PATH, manifestWarning, webManifest } from \"./webManifest.js\";\nimport {\n ASSET_BASE,\n allAppAssets,\n appAssets,\n headTags,\n typeOf,\n} from \"./appAssets.js\";\nimport { reactCacheImports } from \"./reactCache.js\";\nimport {\n clientEntries,\n clientScanPlugin,\n engineClientEntries,\n} from \"./clientEntries.js\";\nimport { serverImportsOfClientPackages } from \"./clientImports.js\";\nimport {\n automaticSitemap,\n METADATA_ROUTES,\n ROOT_FILES,\n rootFileType,\n} from \"./metadataRoutes.js\";\nimport { ownHosts } from \"./hostRouting.js\";\nimport { unrollBarrelImports } from \"./barrelImports.js\";\nimport type { MetadataRouteKind } from \"./metadataRoutes.js\";\nimport { serverRendererMessage, SERVER_RENDERER, ssrProxyModule, UseSsrError, withoutSsrDirective } from \"./useSsr.js\";\nimport type { ClientLibraryImport } from \"./clientImports.js\";\nimport type { AppAssets } from \"./appAssets.js\";\nimport type { WebManifestOptions } from \"./webManifest.js\";\nimport type { Plugin, PluginOption, ResolvedConfig } from \"vite\";\nimport { httpHostCalls } from \"./hostCalls.js\";\nimport { bytecodeNote } from \"./bytecodeCheck.js\";\nimport { clientPackages, importsServerRenderer, packageDir as installedPackageDir, packageEntryInGraph, polyfillsToTrace, traceableByName } from \"./clientPackages.js\";\nimport type {\n ManifestIntercept,\n ManifestRoute,\n RouteManifest,\n RouteSegment,\n} from \"./manifest.js\";\n\nexport interface RscKitOptions {\n /** Project root. Defaults to RSC_PROJECT_ROOT, then cwd. */\n projectRoot?: string;\n /** Directory holding the app/ route tree. Defaults to `src`. */\n sourceDir?: string;\n /**\n * Say what built the site: `<meta name=\"generator\" content=\"rsc-kit\">` in\n * every document and `X-Powered-By: rsc-kit` on every response. The name\n * only, never the version - a version in every response is what a\n * vulnerability scanner filters on. On by default; `false` for a team\n * whose policy strips every framework identifier.\n *\n * `X-RSC-Kit: stored | rendered | shell` - how a response was answered, the\n * header a developer reads in the Network tab - is not this and is always\n * sent: it names no product, and a CDN rule or a check can key on it.\n */\n identify?: boolean;\n /**\n * An OpenAPI document from the route tree, at `/openapi.json`.\n *\n * One path per route.ts, one operation per method export, parameters and\n * request bodies from the route's `params`, `searchParams` and `body`\n * schemas - a Standard Schema that describes itself as JSON Schema (Zod 4,\n * ArkType). A route under a middleware.ts gets a security requirement. A\n * route says the rest about itself with `export const openapi = { summary,\n * tags, responses }`; the document says its own with `info`, `servers`,\n * `security`. An api route the build stores, without middleware.\n *\n * The page that reads it is Scalar's: `export const GET = ApiReference({\n * url: '/openapi.json' })` from @scalar/nextjs-api-reference in a route.ts.\n */\n openapi?:\n | boolean\n | {\n path?: string;\n info?: { title?: string; version?: string; description?: string };\n servers?: { url: string; description?: string }[];\n security?: Record<string, string[]>[];\n components?: Record<string, unknown>;\n tags?: { name: string; description?: string }[];\n };\n /**\n * Unroll named imports from a barrel package on the server, in development.\n *\n * `import { ArrowRight } from 'lucide-react'` reaches a file that re-exports\n * fifteen hundred icons, one module each; the browser gets the package\n * pre-bundled, the server environments do not, so Vite loaded every icon\n * module on the first request. The import is rewritten to the module that\n * owns the name, read from the barrel itself. On by default; `false` to\n * leave imports as written.\n */\n barrelImports?: boolean;\n /**\n * The site's own hosts, beyond the one in the root layout's metadataBase.\n *\n * A request from any other host is routed with the host in front of the\n * path: `admin.example.com/users` reaches `app/admin/users/page.tsx`, the\n * file `example.com/admin/users` reaches by path; `acme.example.com/`\n * reaches `app/[domain]/page.tsx` with `domain: \"acme\"`, and a custom\n * domain `acme.com/` the same file with `domain: \"acme.com\"`. The site's\n * own hosts keep path routing, so an app adds tenants without moving a\n * file. `www.` of each is its own too. With no metadataBase and nothing\n * here, every host is the site's own and nothing is prepended.\n */\n hosts?: string[];\n /**\n * Serve the app from a service worker, so it survives a reload with no\n * network at all.\n *\n * Everything else this engine keeps — held pages, the prefetch cache — lives\n * in one page's memory. Reload with no network and the browser shows its own\n * error page: no script runs, so nothing cached in JavaScript is reachable.\n * A worker is the only thing on the other side of that line.\n *\n * Off by default. It changes what a visitor sees when your deploy is broken,\n * which is not a decision to make for someone.\n */\n offline?: boolean;\n /**\n * Whether a page stored without the runtime gets its stylesheet inlined\n * into the document, so the first paint waits on no request but the\n * document itself.\n *\n * 'auto' inline when the sheet is at most 10 kB gzipped (the default)\n * false never - keep the link, and let the browser cache one file\n * across every page; the choice for a site of many small pages\n * true always, whatever the size\n * number your own cap, in gzipped bytes\n *\n * Only for a page with no runtime. One with React on it keeps its link\n * regardless, because React expects to find it in the DOM to hydrate.\n */\n inlineStylesheets?: \"auto\" | boolean | number;\n /**\n * Run the project's own typecheck as part of `vite build`, and fail the\n * build on an error. On by default when the project has a `tsconfig.json`\n * and `typescript` installed; `false` turns it off.\n *\n * A build that bundles a `<Link href=\"/nowhere\">` and stores every page\n * has produced a broken site that looks finished. The route types exist so\n * that link is an error - but Vite never typechecks, so the error only\n * showed for whoever ran `tsc` separately. `next build` typechecks for the\n * same reason.\n */\n typecheck?: boolean;\n /**\n * The most a server action body may be, in bytes. 8 MB unless set.\n *\n * Arguments and uploaded files arrive in one body, read whole before the\n * action runs; over this the answer is 413 before a byte is kept. Raise it\n * for an app that uploads larger files through actions.\n */\n maxActionBody?: number;\n /** Where the server bundles and generated entries go. Defaults to `.rsc`. */\n outDir?: string;\n /**\n * A file the dev server writes its own url into, and removes on shutdown.\n *\n * Laravel's convention, and the reason it is worth adopting: a dev server\n * picks its port at runtime — 5173 is the most contended port on a developer's\n * machine, and Vite silently moves to the next free one — so anything holding\n * a fixed url is wrong the moment a second project is running. A backend that\n * reads this file follows the server instead of guessing at it.\n */\n hotFile?: string;\n /**\n * Packages the server bundles import at runtime rather than inline.\n *\n * For a dependency with a native binary, one that spawns a process, or one\n * that reads files beside itself - anything a bundle breaks. A default list\n * covers the usual ones (sharp, bcrypt, better-sqlite3, prisma, puppeteer,\n * ...); this adds to it. Nitro traces an external package into\n * .output/server/node_modules with its binaries, so the deployment is still\n * one directory.\n */\n serverExternalPackages?: string[];\n /**\n * Where `rpc()` goes while `vite dev` is serving.\n *\n * A built deployment installs this itself — the server that runs\n * createRscHandler passes `hostCalls`. The dev server has no such server in\n * front of it, so without this every rpc() during development is refused and\n * any page whose data comes from the backend renders blank.\n *\n * Both halves default to the app's own .env, which for a Laravel app already\n * has them: APP_URL for the backend and RSC_HOST_CALL_SECRET for the secret.\n * That is the difference between \"configure the dev server\" and \"it works\".\n */\n hostCall?: { endpoint?: string; secret?: string; path?: string };\n\n /**\n * Where the dev server hands a url it does not own.\n *\n * The route tree is only part of an application: /login, a Blade page, a\n * webhook and an uploaded file under /storage all belong to the backend. So\n * in development this origin is the whole app rather than the RSC half of\n * it, and a browser can sit on it instead of on a proxy in front of it.\n *\n * Defaults to the same place host calls go — RSC_BACKEND, then APP_URL —\n * because a second setting that could disagree with the first is a bug\n * waiting to be filed. `false` restores the plain 404.\n *\n * The built server forwards too — the entry that carries this is the one\n * Nitro bundles — with the origin read at build time from the project's\n * .env, while host calls read it from the process at runtime. A build on a\n * machine whose .env names a different backend than production's sets\n * RSC_BACKEND for the build. The name predates that: it was the dev server's\n * alone before Nitro built the server from the same entry.\n */\n devFallback?: string | false;\n\n /**\n * This package's directory, holding the client runtime the browser entry\n * imports. Vite stages configs through node_modules/.vite-temp, so\n * import.meta.dir is not this file's real location by the time the plugin\n * runs — a host invoking the build out of process passes the real path\n * through RSC_PACKAGE_DIR.\n */\n packageDir?: string;\n /**\n * Name of the global the host installs for calling its own functions from a\n * server component — `await rpc('getUser', id)`. The mechanism is\n * host-agnostic; only the name is a convention, so a host that prefers\n * something else can say so.\n */\n hostGlobal?: string;\n /**\n * JSON file of `{urlPattern, slot}` entries naming the routes the client\n * router should intercept rather than navigate to. Written by the host,\n * which owns route discovery.\n */\n interceptManifestFile?: string;\n /**\n * Bare-specifier prefix for importing the client runtime, as in\n * `import Link from '<prefix>/Link'`, aliased to this package's js/\n * directory.\n *\n * Only needed when this package is not resolvable from the project's\n * node_modules — a host that vendors it through its own package manager,\n * say. Installed from npm, the package name resolves on its own and no\n * alias is required.\n */\n packageAlias?: string;\n /**\n * Origin the Vite dev server is reachable at, e.g. `http://localhost:5173`.\n *\n * Set only when running under the dev server. @vitejs/plugin-rsc emits its\n * bootstrap and CSS links root-relative in dev and no Vite setting moves\n * them, so with the host serving the page the browser would ask the host for\n * modules only Vite can answer. Given this, the SSR entry rewrites them onto\n * the dev origin — see devUrls.ts. Empty in a build, where the URLs are real\n * built assets.\n */\n devOrigin?: string;\n /**\n * What the build produces.\n *\n * 'server' the default: pages are served by a host, and a payload is\n * asked for with a header on the page's own url.\n * 'export' files any static host can serve. Payloads get addresses of\n * their own, because a host serving files cannot act on a\n * header, and the client is built to ask for those instead.\n */\n output?: \"server\" | \"export\";\n /** Where an exported site is written, relative to the project root. */\n exportPath?: string;\n /**\n * Filename payloads are served under on a static host, e.g. `index.rsc`.\n *\n * Only for an exported build. Normally the payload shares the page's url and\n * is asked for with a header; a host that serves files cannot answer that,\n * so the payload needs an address of its own.\n */\n staticPayloads?: string;\n /**\n * How to tell that a route's props are resolved dynamically by the host, so\n * the page cannot be prerendered whole.\n *\n * Entirely host-defined: a host that writes a config file beside the page\n * names that file and the pattern that marks it dynamic. Omitted, no page is\n * classified dynamic on this basis.\n */\n routeConfig?: { file: string; dynamicPattern: RegExp };\n /**\n * Functions the host exposes to the app, as `{ exportedName: target }`.\n *\n * The build writes a \"use server\" module of stubs for these, each one\n * calling the host global with its target — so app code imports an ordinary\n * async function and never names the transport. Discovery belongs to the\n * host, whose functions these are; only the rendering is here, because the\n * module has to land beside the app's source and that path is the build's.\n *\n * A host whose functions are already JavaScript passes nothing.\n */\n hostActions?: Record<string, string>;\n}\n\n// Resolved once per rscKit() call. One build runs in one process, so these are\n// module state rather than threaded through every helper.\nlet projectRoot: string;\nlet sourceDir: string;\nlet inlineStylesheets: \"auto\" | boolean | number = \"auto\";\nlet resolvedConfig: ResolvedConfig | null = null;\n\n/** Server files importing a client library, read off the rsc graph when it is built. */\nlet clientLibraryImports: ClientLibraryImport[] = [];\n\n/** Modules a runtime provides and no bundle should try to carry. */\nconst RUNTIME_BUILTINS = [\"bun\", /^bun:/];\n\n/**\n * Packages the server bundles import rather than inline, by default.\n *\n * Each of these ships a native binary, spawns one, or reads files relative to\n * its own location - none of which survives being rolled into a bundle. Left\n * external, Nitro traces them into .output/server/node_modules with their\n * binaries, and the built server imports them the way the package expects.\n * Next keeps the same list under serverExternalPackages, for the same reason.\n * `rscKit({ serverExternalPackages })` adds to it.\n */\n/**\n * Side-effect polyfills a dependency checks for at module evaluation, which\n * the generated entry imports before anything else when the project has\n * them. Bundler chunking does not keep an external import's place.\n */\nconst FIRST_POLYFILLS = [\"reflect-metadata\"];\n\nconst DEFAULT_SERVER_EXTERNALS = [\n \"sharp\",\n \"canvas\",\n \"bcrypt\",\n \"argon2\",\n \"@node-rs/argon2\",\n \"@node-rs/bcrypt\",\n \"better-sqlite3\",\n \"sqlite3\",\n \"libsql\",\n \"@libsql/client\",\n \"@prisma/client\",\n \"prisma\",\n \"puppeteer\",\n \"puppeteer-core\",\n \"playwright\",\n \"playwright-core\",\n \"jsdom\",\n \"node-pty\",\n \"onnxruntime-node\",\n \"@sentry/profiling-node\",\n \"pdfkit\",\n \"mongodb\",\n \"oslo\",\n \"@resvg/resvg-js\",\n \"@napi-rs/canvas\",\n // Not native: a polyfill that must run before anything reads Reflect.getMetadata.\n // tsyringe, typeorm and inversify check for it at module evaluation, and a\n // bundler that splits them into their own chunk hoists that chunk's evaluation\n // above the polyfill's - so the check fails in a bundle that has the polyfill\n // in it. External, the import statement stays where the source put it, and\n // Node runs it first.\n \"reflect-metadata\",\n];\n\n/** A package name as a rollup external: the package and every subpath of it. */\nfunction externalPackage(name: string): RegExp {\n return new RegExp(\"^\" + name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") + \"(?:/|$)\");\n}\n\nfunction arrayOf<T>(value: T | T[] | null | undefined): T[] {\n return value == null ? [] : Array.isArray(value) ? value : [value];\n}\n\n/**\n * What a client chunk is called on disk.\n *\n * A \"use server\" module reaches the browser as a proxy - one stub per export\n * that calls the action by id - and the proxy keeps the file's identity, so\n * the bundler can name a chunk after it. When shared client code is merged\n * into that chunk the output has a file called `auth-actions-…js` in\n * public/assets: fifty kilobytes of UI components with the name of the\n * server file, which reads as a leak to anyone who looks. Nothing leaked -\n * the proxy holds ids, never bodies - but a name that says otherwise is a\n * bug. Such a chunk is called what it is.\n */\nfunction clientChunkFileName(chunk: {\n name: string;\n facadeModuleId: string | null;\n moduleIds: string[];\n}): string {\n const table = resolvedConfig\n ? getPluginApi(resolvedConfig)?.manager?.serverReferences?.metaMap\n : undefined;\n\n if (table && table.size > 0) {\n const bare = (id: string) => {\n const file = id.split(\"?\")[0]!.split(\"/\").pop() ?? \"\";\n\n return file.replace(/\\.[^.]+$/, \"\");\n };\n const serverModules = new Set([...table.keys()].map(bare));\n const namedAfterServerModule =\n (chunk.facadeModuleId !== null &&\n serverModules.has(bare(chunk.facadeModuleId))) ||\n (serverModules.has(chunk.name) &&\n chunk.moduleIds.some((id) => bare(id) === chunk.name));\n\n if (namedAfterServerModule) return \"assets/client-[hash].js\";\n }\n\n return \"assets/[name]-[hash].js\";\n}\nlet maxActionBody: number | undefined;\nlet outDir: string;\nlet appDir: string;\nlet genDir: string;\nlet publicAssetsDir: string;\n/** Where generated ambient declarations go — `.rsc-kit` at the project root. */\nlet typesDir: string;\nlet hotFile: string;\nlet hostCallOptions: RscKitOptions[\"hostCall\"];\nlet packageDir: string;\nlet hostGlobal: string;\nlet interceptManifestFile: string;\nlet packageAlias: string | null;\n/** Dev-server origin; empty in a build. See devUrls.ts. */\nlet devOrigin: string;\n/** 'server' or 'export' — see RscKitOptions.output. */\nlet output: string;\n/** Where an exported site is written. */\nlet exportPath: string;\n/**\n * Filename payloads are exported under, empty unless building for a static\n * host. Set, the client asks `<page>/<name>` for a payload instead of asking\n * for the page's own url with a header a static host cannot act on.\n */\nlet staticPayloads: string;\nlet routeConfig: { file: string; dynamicPattern: RegExp } | null;\n/** Whether `vite build` freezes pages when it finishes — see RscKitOptions. */\nlet prerenderAfterBuild: boolean;\n/** True during `vite build --watch`, where re-rendering every route is noise. */\nlet isWatch = false;\n/** Whether a service worker is generated and registered — see options. */\nlet offline = false;\nlet typecheck = true;\nlet webManifestOptions: WebManifestOptions | null = null;\n/** The site's own hosts, from the root layout's metadataBase and rscKit({ hosts }). */\nlet siteHosts: string[] = [];\nlet hostsOption: string[] = [];\nlet barrelImports = true;\nlet identify = true;\n/** Resolved from RscKitOptions.openapi; null when off. */\nlet openapi: { path: string; document: Record<string, unknown> } | null = null;\nlet foundAssets: AppAssets = {\n favicon: null,\n icons: [],\n appleIcon: null,\n openGraph: null,\n twitter: null,\n};\n/** Host functions to generate stubs for — see RscKitOptions.hostActions. */\nlet hostActions: Record<string, string>;\n\n/**\n * This file's directory.\n *\n * Not `import.meta.dir`, which is Bun-only: Vite bundles the config and runs it\n * under Node, where that is undefined and the path resolution below throws\n * before the build starts. Reached whenever RSC_PACKAGE_DIR is unset — which is\n * the ordinary case for an app that installs the engine from npm and runs\n * `vite build` itself.\n */\n/** This package's name, for excluding it from dep optimization. */\nconst PACKAGE_NAME: string = (() => {\n try {\n const manifest = JSON.parse(\n readFileSync(\n join(dirname(fileURLToPath(import.meta.url)), \"..\", \"package.json\"),\n \"utf-8\",\n ),\n ) as { name?: string };\n\n return manifest.name ?? \"@rsc-kit/core\";\n } catch {\n return \"@rsc-kit/core\";\n }\n})();\n\nfunction thisDir(): string {\n return dirname(fileURLToPath(import.meta.url));\n}\n\n/** routeConfig supplied through the environment, for out-of-process hosts. */\nfunction envRouteConfig(): { file: string; dynamicPattern: RegExp } | null {\n const file = process.env.RSC_ROUTE_CONFIG_FILE;\n const pattern = process.env.RSC_ROUTE_CONFIG_PATTERN;\n\n if (!file || !pattern) return null;\n\n return { file, dynamicPattern: new RegExp(pattern) };\n}\n\n/** The file a backend writes its action names into. */\nconst HOST_ACTIONS_FILE = \"rsc-host-actions.json\";\n\n/**\n * Host actions, read from a file the backend wrote.\n *\n * A file rather than an environment variable, because the backend no longer\n * drives the build — `vite build` does. Discovery has to stay where the classes\n * are (reflection through Composer's autoloader finds what a class inherits;\n * a regex would silently miss every inherited action), but the handoff is just\n * a map of names, and a JSON file is something any language can write:\n *\n * php artisan rsc:action-manifest > rsc-host-actions.json\n * go run ./cmd/rsc-actions > rsc-host-actions.json\n *\n * Absent is not an error. An app with no host actions has no file, and one\n * that has them regenerates it as part of its build.\n */\nfunction fileHostActions(root: string): Record<string, string> {\n const path = join(root, HOST_ACTIONS_FILE);\n\n if (!existsSync(path)) return {};\n\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n\n // An empty list is an empty map. PHP's json_encode writes an empty\n // array as [] whatever it was declared as, so a backend with no\n // actions yet wrote exactly that - and the first `dev` of a fresh\n // install refused to start over a file that said, correctly, \"none\".\n if (Array.isArray(parsed) && parsed.length === 0) return {};\n\n if (\n parsed === null ||\n typeof parsed !== \"object\" ||\n Array.isArray(parsed)\n ) {\n throw new Error('expected an object of { jsName: \"Class.method\" }');\n }\n\n return parsed as Record<string, string>;\n } catch (error) {\n // Loud, because the alternative is generating no stubs: every import of a\n // server action then fails at build time, naming the import rather than\n // this file.\n throw new Error(\n `Could not read ${HOST_ACTIONS_FILE}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/**\n * The alias that lets a vendored copy of this package be imported by name.\n *\n * Only when the package is not installed, because an alias is a path rewrite\n * and rewrites nothing through the package's own exports. With both in play\n * the specifier meant two different things: `<pkg>/Form` resolved to whatever\n * file happened to sit at js/Form, rather than to what ./Form is declared to\n * mean. Installed from npm, ordinary resolution reads the exports map and the\n * two cannot drift.\n */\nfunction aliasEntries(): Array<{ find: RegExp; replacement: string }> {\n const entries: Array<{ find: RegExp; replacement: string }> = [\n // A library written for Next reads the request through next/headers -\n // Vercel's flags SDK does, through `flags/next` - and headers() and\n // cookies() here have the same names and shapes, with one object per\n // request, which is what its per-request dedupe keys on. Answered by\n // this package, so such a library runs unchanged and without Next.\n { find: /^next\\/headers$/, replacement: join(packageDir, \"request\") },\n ];\n\n if (!packageAlias) return entries;\n\n if (existsSync(join(projectRoot, \"node_modules\", packageAlias))) return entries;\n\n entries.push({\n find: new RegExp(\n \"^\" + packageAlias.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") + \"/(.*)$\",\n ),\n replacement: join(packageDir, \"js\") + \"/$1\",\n });\n\n return entries;\n}\n\nfunction resolvePaths(options: RscKitOptions): void {\n projectRoot = resolve(\n options.projectRoot || process.env.RSC_PROJECT_ROOT || process.cwd(),\n );\n sourceDir = resolve(\n options.sourceDir || process.env.RSC_SOURCE_DIR || join(projectRoot, \"src\"),\n );\n outDir = resolve(\n options.outDir || process.env.RSC_OUT_DIR || join(projectRoot, \".rsc\"),\n );\n appDir = join(sourceDir, \"app\");\n\n // Generated entries live under the (in-project) out dir so module resolution\n // can walk up to the project's node_modules (@vitejs/plugin-rsc, react, ...).\n genDir = join(outDir, \".gen\");\n\n // Not a migration guard — those are not worth carrying in a pre-release.\n // This is the silent-failure guard the rest of this file is written to be.\n //\n // Nitro publishes the assets and serves them from its own root. A prefix set\n // here would be emitted into the markup and answered by nobody: every asset\n // 404s while every page still renders, so the app arrives unstyled, never\n // hydrates, and logs nothing anywhere. Vite does not typecheck a config, so\n // removing the option from the type is not enough to stop it.\n //\n // There is deliberately no check for `nitro`. It is gone from the type, and\n // a config still passing `nitro: true` is asking for exactly what it gets.\n const removed = [\"assetsDir\", \"assetsUrl\"].filter(\n (key) => (options as Record<string, unknown>)[key] !== undefined,\n );\n\n if (removed.length > 0) {\n throw new Error(\n `[rsc-kit] ${removed.join(\" and \")} ${removed.length === 1 ? \"is\" : \"are\"} no longer an option.\\n\\n` +\n \"Nitro publishes the browser assets to .output/public and serves them from its own\\n\" +\n \"root, so there is no prefix to set. That directory is the deployment — point nginx\\n\" +\n \"or a CDN at it if something other than the app should serve them.\",\n );\n }\n\n // Vite's own default. Nitro overrides it with .output/public, which is why\n // there is nothing here to configure.\n publicAssetsDir = resolve(join(projectRoot, \"dist/client\"));\n typesDir = join(projectRoot, \".rsc-kit\");\n hotFile = options.hotFile || process.env.RSC_HOT_FILE || \"\";\n hostCallOptions = options.hostCall;\n packageDir = resolve(\n options.packageDir || process.env.RSC_PACKAGE_DIR || thisDir(),\n );\n hostGlobal = options.hostGlobal || process.env.RSC_HOST_GLOBAL || \"rpc\";\n interceptManifestFile = resolve(\n options.interceptManifestFile ||\n process.env.RSC_INTERCEPT_MANIFEST ||\n join(outDir, \"intercept-manifest.json\"),\n );\n packageAlias = options.packageAlias || process.env.RSC_PACKAGE_ALIAS || null;\n devOrigin = options.devOrigin || process.env.RSC_DEV_ORIGIN || \"\";\n output = options.output || process.env.RSC_OUTPUT || \"server\";\n exportPath = options.exportPath || process.env.RSC_EXPORT_PATH || \"dist\";\n // An export decides this for itself: the client has to ask for payloads by\n // url because there is no server to read a header, and the name it asks for\n // is the one the export writes.\n staticPayloads =\n options.staticPayloads ||\n process.env.RSC_STATIC_PAYLOADS ||\n (output === \"export\" ? \"index.rsc\" : \"\");\n\n // No default: which file marks a route dynamic is the host's convention, and\n // guessing one here would bake a particular backend into a generic plugin.\n // The env pair exists so a host driving the build out of process can pass it\n // without writing a config file.\n routeConfig = options.routeConfig ?? envRouteConfig();\n // A host driving the build out of process cannot pass an option, and may\n // prerender itself afterwards with paths only it knows.\n // No public switch. A page that must not be frozen says so with\n // `await connection()`, and the build names every page that could not be\n // rendered - the same model Next has with cache components, where the\n // only opt-out is per page. RSC_PRERENDER=0 remains, internal: watch mode\n // sets it, and so does a host that drives the build out of process and\n // prerenders itself afterwards with paths only it knows.\n prerenderAfterBuild = process.env.RSC_PRERENDER !== \"0\";\n offline = options.offline === true;\n typecheck = options.typecheck !== false;\n hostsOption = options.hosts ?? [];\n barrelImports = options.barrelImports !== false;\n identify = options.identify !== false;\n openapi = options.openapi\n ? (() => {\n const { path, ...document } = typeof options.openapi === \"object\" ? options.openapi : {};\n\n return { path: path || \"/openapi.json\", document };\n })()\n : null;\n inlineStylesheets = options.inlineStylesheets ?? \"auto\";\n maxActionBody = options.maxActionBody;\n // One place, and it is the file. A plugin option as well would be the same\n // thing sayable in two places, which is the problem the file was moved to\n // solve rather than a convenience to keep beside it.\n webManifestOptions = declaredManifest(join(sourceDir, \"app\"));\n foundAssets = appAssets(join(sourceDir, \"app\"));\n\n // An app that put icons where they could be found has already listed them.\n // Writing them again in the manifest is the same set in two places, and the\n // one that goes stale is the one nobody looks at.\n if (\n webManifestOptions &&\n !webManifestOptions.icons?.length &&\n foundAssets.icons.length\n ) {\n webManifestOptions = {\n ...webManifestOptions,\n icons: foundAssets.icons.map((icon) => icon.href),\n };\n }\n hostActions = options.hostActions ?? fileHostActions(projectRoot);\n}\n\ninterface Component {\n name: string; // route-relative key, e.g. \"app/page\", \"app/layout\"\n absPath: string;\n alias: string; // safe JS identifier for the generated import\n}\n\nfunction log(...args: unknown[]): void {\n console.error(\"[rsc-kit]\", ...args);\n}\n\n// ── The route manifest ───────────────────────────────────────────────────────\n\n/**\n * What the plugin knows about the route tree, written out for a host to read.\n *\n * The plugin already walks app/ to generate the entries, and every host has to\n * know the same things — which url a component answers, what layouts wrap it,\n * which slots and sections belong to it. Laravel scans the tree a second time\n * to work that out; a JS host would have to write a third. This is the one\n * answer, emitted where both can read it.\n *\n * Urls are expressed as segments rather than as a pattern string, because the\n * pattern is the host's dialect: Laravel writes {slug}, Hono writes :slug, and\n * neither is the plugin's business.\n */\n\n/** `[...path]` → catchAll, `[id]` → param, `(group)` → nothing at all. */\nfunction urlSegments(componentName: string): RouteSegment[] {\n const parts = componentName.split(\"/\").slice(1, -1);\n const segments: RouteSegment[] = [];\n\n for (const part of parts) {\n // A route group organises files without appearing in the url.\n if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n // A slot directory is not part of its page's url either.\n if (part.startsWith(\"@\")) continue;\n\n if (part.startsWith(\"[...\") && part.endsWith(\"]\")) {\n segments.push({ type: \"catchAll\", value: part.slice(4, -1) });\n continue;\n }\n\n if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n // At the top of app/ - the first segment the url has - a parameter is\n // the host's: bound from acme.example.com, never from example.com/acme.\n segments.push({\n type: segments.length === 0 ? \"host\" : \"param\",\n value: part.slice(1, -1),\n });\n continue;\n }\n\n // An interception marker says which url this replaces, not what it is\n // called: (.)photo intercepts the sibling /photo. Left in place the\n // manifest would claim a route at /(.)photo, which nothing can navigate to.\n segments.push({ type: \"static\", value: part.replace(/^\\(\\.{1,3}\\)/, \"\") });\n }\n\n return segments;\n}\n\n/** Whether a component sits under an interception marker: (.) (..) (...) */\nfunction isIntercept(componentName: string): boolean {\n return componentName.split(\"/\").some((part) => /^\\(\\.{1,3}\\)/.test(part));\n}\n\n/** The slot directory a component lives under, if any. */\nfunction slotOf(componentName: string): string | null {\n const part = componentName.split(\"/\").find((p) => p.startsWith(\"@\"));\n\n return part ? part.slice(1) : null;\n}\n\n/**\n * Everything the plugin discovered, as a host needs it.\n *\n * Ancestry is by path prefix: a layout at app/docs applies to everything under\n * app/docs, which is the same rule the composition uses.\n */\nfunction routeManifest(): RouteManifest {\n const names = [...components.keys()];\n const dirOf = (name: string) => name.split(\"/\").slice(0, -1).join(\"/\");\n\n // By path, not by string: 'app/slow3' begins with 'app/slow' as text and is\n // not inside it, which would hand /slow3 the loading state of /slow.\n const isUnder = (dir: string, ancestor: string) =>\n dir === ancestor || dir.startsWith(ancestor + \"/\");\n\n const ancestors = (name: string, base: string) =>\n names\n .filter(\n (n) =>\n n.endsWith(\"/\" + base) &&\n !isIntercept(n) &&\n isUnder(dirOf(name), dirOf(n)),\n )\n .sort((a, b) => a.length - b.length);\n\n /** Project-root-relative, posix — the same string on every machine. */\n const fromRoot = (abs: string) =>\n relative(projectRoot, abs).replace(/\\\\/g, \"/\");\n\n /** The host's config file in a directory, if the host named one and it exists. */\n const configIn = (absDir: string): string | null => {\n if (!routeConfig) return null;\n\n const path = join(absDir, routeConfig.file);\n\n return existsSync(path) ? fromRoot(path) : null;\n };\n\n /** Ancestor configs, outermost first, excluding the page's own directory. */\n const ancestorConfigs = (dir: string): string[] => {\n const found: string[] = [];\n const parts = dir.split(\"/\").slice(0, -1);\n\n while (parts.length > 0) {\n const path = configIn(join(sourceDir, parts.join(\"/\")));\n\n if (path) found.unshift(path);\n\n parts.pop();\n }\n\n return found;\n };\n\n /**\n * Host middleware named by a route.ts beside or above a page.\n *\n * // app/admin/route.ts\n * export const middleware = ['auth', 'can:update,post']\n *\n * Read statically rather than imported, for the same reason\n * generateStaticParams is detected by reading the source: this runs while the\n * manifest is being built, before there is a bundle to execute.\n *\n * The names mean nothing here. They are the host's vocabulary — Laravel\n * middleware aliases, a Go router's names — and the engine only carries them\n * to whoever knows what they mean.\n */\n const middlewareIn = (absDir: string): string[] => {\n // middleware.ts first: it is the file named for what this is. A guard\n // the engine runs is its default export; the names a host runs are its\n // `middleware` export, and a file may carry either or both. route.ts is\n // read too, for the apps written before middleware.ts could.\n for (const file of [\"middleware.ts\", \"middleware.tsx\", \"route.ts\", \"route.tsx\"]) {\n const path = join(absDir, file);\n\n if (!existsSync(path)) continue;\n\n const match = readFileSync(path, \"utf-8\").match(\n /export\\s+const\\s+middleware\\s*(?::[^=]+)?=\\s*\\[([^\\]]*)\\]/,\n );\n\n if (!match) continue;\n\n // Each quoted literal, rather than splitting the list on commas: a\n // middleware name carries its arguments after a colon and those are\n // comma-separated too, so splitting turns 'throttle:60,1' into a\n // throttle of 60 and a middleware called 1.\n return [...match[1].matchAll(/['\"`]([^'\"`]*)['\"`]/g)]\n .map((quoted) => quoted[1].trim())\n .filter(Boolean);\n }\n\n return [];\n };\n\n /**\n * Every host middleware above and on a page, outermost first.\n *\n * Order is the whole of it: an outer guard has to run before an inner one, or\n * a check deciding whether the inner check is even reachable runs second.\n * Duplicates are dropped, so a name repeated down the tree runs once, at the\n * outermost point it was asked for.\n */\n const hostMiddleware = (dir: string): string[] => {\n const parts = dir.split(\"/\").filter(Boolean);\n const found: string[] = [];\n\n for (let depth = 0; depth <= parts.length; depth++) {\n for (const name of middlewareIn(\n join(sourceDir, ...parts.slice(0, depth)),\n )) {\n if (!found.includes(name)) found.push(name);\n }\n }\n\n return found;\n };\n\n const routes: ManifestRoute[] = [];\n const intercepts: ManifestIntercept[] = [];\n\n for (const name of names) {\n if (name.endsWith(\"/page\") && isIntercept(name)) {\n const slot = slotOf(name);\n\n if (slot) {\n const marker =\n name\n .split(\"/\")\n .find((p) => /^\\(\\.{1,3}\\)/.test(p))\n ?.match(/^\\(\\.{1,3}\\)/)?.[0] ?? \"(.)\";\n\n intercepts.push({\n component: name,\n slot,\n segments: urlSegments(name),\n marker,\n });\n }\n\n continue;\n }\n\n if (!name.endsWith(\"/page\") || slotOf(name)) continue;\n\n const slots: Record<string, string> = {};\n\n for (const candidate of names) {\n const slot = slotOf(candidate);\n // A slot belongs to the layout in the directory that declares it, so it\n // applies to a page only if that directory is on the page's path.\n if (!slot || isIntercept(candidate) || !candidate.endsWith(\"/default\"))\n continue;\n if (isUnder(dirOf(name), candidate.split(\"/@\")[0]))\n slots[slot] = candidate;\n }\n\n routes.push({\n component: name,\n segments: urlSegments(name),\n layouts: ancestors(name, \"layout\").map((n) => n),\n loadings: ancestors(name, \"loading\").map((n) => n),\n errors: ancestors(name, \"error\"),\n middleware: ancestors(name, \"middleware\").map((n) => n),\n slots,\n sections: names.filter(\n (n) => SECTION_FILE.test(n + \".tsx\") && dirOf(n) === dirOf(name),\n ),\n config: configIn(join(sourceDir, dirOf(name))),\n hostMiddleware: hostMiddleware(dirOf(name)),\n ancestorConfigs: ancestorConfigs(dirOf(name)),\n staticParams: hasStaticParams(components.get(name)!.absPath),\n });\n }\n\n // What the build decided, for a host that has to act on it afterwards —\n // writing the site out, and knowing which filename the client will ask for.\n return {\n version: 1,\n build: {\n output,\n exportPath,\n payloadName: staticPayloads,\n hosts: siteHosts,\n identify,\n },\n routes,\n intercepts,\n apis: [...apiRoutes.values()].map(({ name, methods, generated, absPath }) => ({\n name,\n segments: urlSegments(name),\n methods,\n // The OpenAPI document is synthesised from nothing on disk.\n source: generated\n ? generated.file\n ? relative(sourceDir, generated.file).replace(/\\\\/g, \"/\")\n : undefined\n : relative(sourceDir, absPath).replace(/\\\\/g, \"/\"),\n // A synthesised robots.txt or sitemap.xml runs no guard: it exists to be\n // read by anyone, and a guard on the root would 401 the crawler.\n middleware: generated ? [] : ancestors(name, \"middleware\"),\n })),\n };\n}\n\n/**\n * Say so when the typechecker cannot see the declarations just written.\n *\n * Moving them out of the source directory buys a tidy `src/` and costs this:\n * `include` used to cover them by accident, and now it has to name `.rsc-kit`.\n * A project that does not is not broken in any way it can notice — every file\n * is written, every build passes, and `Link` quietly takes `string` again\n * instead of the route union, so a link to a page that does not exist compiles\n * and 404s in the browser.\n *\n * A guess, deliberately, and only ever a warning: `include` is one of several\n * ways a tsconfig can reach a file, `extends` can supply it, and a project\n * with no tsconfig at all is not doing this checking anyway. Wrong here costs\n * a line of output; silent costs the types.\n */\nfunction warnIfTypesUnreachable(): void {\n const config = join(projectRoot, \"tsconfig.json\");\n\n if (!existsSync(config)) return;\n\n try {\n // Comments are legal in a tsconfig and JSON.parse does not take them.\n const text = readFileSync(config, \"utf-8\").replace(\n /\\/\\*[\\s\\S]*?\\*\\/|(^|\\s)\\/\\/.*$/gm,\n \"$1\",\n );\n const include = (JSON.parse(text) as { include?: unknown }).include;\n\n if (!Array.isArray(include)) return;\n\n const covers = (what: string) =>\n include.some(\n (entry) => typeof entry === \"string\" && entry.includes(what),\n );\n\n if (!covers(\".rsc-kit\")) {\n log(\n `tsconfig.json does not include .rsc-kit, where the generated types are written.\\n` +\n ` Add \".rsc-kit/**/*\" to \"include\", or typed routes and rpc() fall back to string.`,\n );\n }\n } catch {\n // An unparseable tsconfig is the project's own problem, not this one's.\n }\n}\n\n// ── What the app imports ─────────────────────────────────────────────────────\n\n/**\n * Write the modules the app's source imports but nobody writes by hand.\n *\n * Two destinations, and the difference is whether anything imports the file.\n *\n * The stubs are imported by relative path, so they have to sit in the source\n * directory — that path is the app's, and only the build knows it.\n *\n * The declarations are not imported by anything. They are ambient, which needs\n * them inside the project and nothing more, so they go in `.rsc-kit/` at the\n * root: four generated files in `src/` sat among the app's own and had to be\n * gitignored one by one, and every one of them was noise beside the pages.\n *\n * Ambient still means the typechecker has to be told the directory exists —\n * see the warning below, because a tsconfig that does not include it turns\n * every one of these into a file nobody reads.\n *\n * Rewritten on every run. The failure they prevent is invisible at build\n * time — a stale stub calls a global that has since been renamed, and only\n * the browser ever finds out.\n */\nfunction writeHostBindings(manifest: RouteManifest): void {\n mkdirSync(sourceDir, { recursive: true });\n mkdirSync(typesDir, { recursive: true });\n\n // The global is installed at runtime, so nothing in app source declares it\n // and a typecheck cannot see it. Written whether or not there are actions:\n // server components call it directly too.\n writeFileSync(join(typesDir, \"rsc-env.d.ts\"), renderHostGlobalTypes());\n\n // The urls this build found, so a link to a page that does not exist fails\n // the typecheck instead of the browser.\n writeFileSync(join(typesDir, \"rsc-routes.d.ts\"), renderRouteTypes(manifest));\n\n // The bundle the host imports is generated, so nothing declares it. Written\n // here rather than left to the app: every app needs the identical file, and\n // an app-authored one goes stale — the first version named only RscEngine,\n // which typechecks a server and fails a prerender script.\n writeFileSync(join(typesDir, \"rsc-engine.d.ts\"), ENGINE_TYPES);\n\n warnIfTypesUnreachable();\n\n const target = join(sourceDir, \"server-actions.generated.ts\");\n\n // A host with no functions of its own leaves no file behind: kept, its\n // stubs would go on naming targets the host has stopped answering for.\n if (Object.keys(hostActions).length === 0) {\n if (existsSync(target)) rmSync(target);\n\n return;\n }\n\n writeFileSync(target, renderHostActions());\n}\n\n/**\n * The generated engine bundle, as the type its callers expect.\n *\n * Both contracts: createRscHandler serves requests, prerender() renders at\n * build time and needs three methods the first does not have. manifest() is\n * optional on both because a host may be handed an engine without one — this\n * is the generated bundle, which always exports it, and saying so is what lets\n * exportSite() be called without a guard that could never fire.\n */\nconst ENGINE_TYPES = `// @generated — do not edit. Written by the RSC build.\ndeclare module '*/dist/rsc/index.js' {\n import type { RscEngine } from '@rsc-kit/core/host'\n import type { PrerenderEngine } from '@rsc-kit/core/prerender'\n\n const engine: RscEngine & PrerenderEngine & Required<Pick<PrerenderEngine, 'manifest'>>\n\n export = engine\n}\n`;\n\n/**\n * Render every route once and write what can be stored.\n *\n * Imported at call time, not at the top of this file: `prerender` pulls in the\n * render pipeline, and a dev server that never prerenders should not pay for\n * loading it.\n */\n/**\n * What the build classified when it classified nothing.\n *\n * With prerendering off there is no probe and no answer to report, so every\n * route is dynamic by construction rather than by measurement — printed the\n * same way so the output means the same thing either way.\n */\nfunction reportAllDynamic(): void {\n const routes = routeManifest().routes;\n\n for (const route of routes) {\n // The pattern rather than a url: nothing was rendered, so there are no\n // params and inventing one would name a page that may not exist.\n const path = route.segments\n .map((segment) =>\n segment.type === \"static\" ? segment.value : `[${segment.value}]`,\n )\n .join(\"/\");\n\n console.log(` \\u0192 /${path}`);\n }\n\n console.log(`\n \\u0192 (Dynamic) server-rendered on demand\n\n ${routes.length} dynamic — prerendering is off`);\n}\n\n/**\n * The service worker, written into the client output at build time.\n *\n * Scoped to the site root because it is served from there, so it sees every\n * navigation. Three kinds of request, three answers:\n *\n * Hashed assets are immutable by construction — the name changes when the\n * bytes do — so they are answered from the cache and only fetched once ever.\n *\n * Documents and payloads go to the network first and fall back to the cache,\n * because a page whose data moved on should say so while there is a network to\n * ask. Only the fallback is what makes a reload work with none.\n *\n * A document and its payload share a url and differ by header. They do not\n * collide, because the server sends `Vary: X-RSC, ...` and the Cache API\n * honours it when a Response is stored whole and matched with its Request.\n *\n * Nothing else is touched. An action is a POST and must never be answered from\n * a cache; anything cross-origin is somebody else's to cache.\n */\nexport const SERVICE_WORKER = (\n version: string,\n precache: string[],\n frozen: string[] = [],\n offlineUrl: string | null = null,\n swExtra: string | null = null,\n): string => `// GENERATED by rscKit() — do not edit.\nconst VERSION = ${JSON.stringify(version)}\nconst CACHE = 'rsc-kit-' + VERSION\n\n// This worker's own cache, and only that. \\`caches.match()\\` searches every\n// cache on the origin - the previous worker's included, until this one's\n// activation sweeps it - and answered a payload request for the page with\n// the previous build's payload: client references this build does not\n// have, and the page reloaded to recover. A document, a payload, a page\n// this worker did not cache is not served from a cache it did not fill.\nconst own = (key, options) => caches.open(CACHE).then((cache) => cache.match(key, options))\nconst PRECACHE = ${JSON.stringify(precache, null, 2)}\n\n// The urls the build stored whole. Their answer cannot change until the next\n// deploy, and a deploy changes VERSION and sweeps this cache — so for these,\n// and only these, the cache is the better source and the network is the\n// fallback rather than the other way round.\n//\n// Everything else stays network-first. A page that reads the request has a\n// right answer that depends on the request, and serving yesterday's from a\n// cache would be wrong in a way the visitor cannot see.\nconst FROZEN = new Set(${JSON.stringify(frozen)})\n\n// The page to show when a navigation cannot be answered at all.\n//\n// An ordinary route at /offline, stored at build time like any other — nothing\n// special about the file, only about when it is served. Null when the app has\n// none, and then a navigation with nothing cached fails as it always did.\n//\n// Deliberately NOT the cached root. That was tried: the document IS the page\n// here, so the visitor got the home page's markup under the address they asked\n// for and it did not hydrate — a wrong page pretending to be the right one.\n// This one is about being offline whatever url it appears under, so it is the\n// only page that can honestly stand in for another.\nconst OFFLINE_URL = ${JSON.stringify(offlineUrl)}\n${\n swExtra\n ? `\n// The app's own worker code — push, notification clicks, background sync.\n//\n// importScripts rather than a bundled import, because this file is evaluated\n// in a worker scope by the browser rather than built: whatever the app wrote is\n// run as it was written, in the same global, so its listeners sit beside the\n// ones below.\n//\n// First, so an app handler for an event this file does not handle is registered\n// before anything here can call respondWith on it.\nself.importScripts(${JSON.stringify(swExtra)})\n`\n : \"\"\n}\n\nself.addEventListener('install', (event) => {\n // The new worker takes over rather than waiting for every tab to close.\n // Safe here because assets are content-hashed: a page already open keeps\n // asking for the names it was built with, and those are still cached under\n // their own version until this activates and sweeps.\n event.waitUntil(\n caches\n .open(CACHE)\n // The offline page is fetched rather than copied from the build output:\n // it is served by the host out of the prerendered directory, which this\n // worker cannot see. Added here so it is in the cache before it is\n // needed, which is the only moment it cannot be fetched.\n .then((cache) => cache.addAll(OFFLINE_URL ? [...PRECACHE, OFFLINE_URL] : PRECACHE).then(() => cache))\n // And the payload each precached page boots from. A document alone is\n // markup that never hydrates: the client fetches its payload on boot,\n // and a precached / rendered offline and stayed inert because that\n // request had nothing cached to answer it.\n .then((cache) =>\n Promise.all(\n PRECACHE.filter((url) => !/\\\\.[a-z0-9]+$/i.test(url))\n .concat(OFFLINE_URL ? [OFFLINE_URL] : [])\n .map((url) => {\n const warm = new Request(url, { headers: { 'X-RSC': '1' } })\n\n return fetch(warm)\n .then((payload) => {\n if (mayStore(payload)) return cache.put(keyFor(warm), payload)\n\n // Said, not swallowed: a page whose payload cannot be kept\n // is one that will render offline and never hydrate, and\n // the reason - a no-store from a guard above it, usually -\n // is only visible here.\n console.warn('[rsc-kit] offline: the payload for ' + url + ' was not stored (' + (payload.headers.get('Cache-Control') || payload.status) + '), so it will not hydrate offline')\n })\n .catch(() => {})\n }),\n ),\n )\n .then(() => self.skipWaiting()),\n )\n})\n\nself.addEventListener('activate', (event) => {\n event.waitUntil(\n caches\n .keys()\n .then((keys) => {\n const older = keys.filter((k) => k.startsWith('rsc-kit-') && k !== CACHE)\n\n return Promise.all(older.map((k) => caches.delete(k))).then(() => older.length > 0)\n })\n .then((swept) => self.clients.claim().then(() => swept))\n // Only when something older was swept. The first worker a visitor ever\n // gets activates too, and told them \"a new version is ready\" on their\n // second page - there was no previous version to be new against.\n .then((swept) => (swept ? tellTheOpenPages() : undefined)),\n )\n})\n\n// A page open right now is running the previous build's javascript, and the\n// chunks it has not loaded yet were just swept. It cannot fix that by itself —\n// only a reload gets the new ones — so it is told, and the app decides what to\n// say about it.\n//\n// After the sweep rather than before, so a page acting on this immediately\n// reloads into the new version rather than racing the deletion.\nasync function tellTheOpenPages() {\n const open = await self.clients.matchAll({ type: 'window' })\n\n for (const page of open) page.postMessage({ type: 'rsc-kit:updated', version: VERSION })\n}\n\nconst immutable = (url) => url.pathname.startsWith('/assets/') || /-[A-Za-z0-9_-]{8,}\\\\.[a-z]+$/.test(url.pathname)\n\n// The build the server is on, as a page reported it: a page told 409 - its\n// build is not the server's - says so here before it loads the document,\n// and answers with the same to say it has been heard. Until this worker is\n// replaced, a stored document from any other build is served from the\n// network rather than the cache. Without this a phone lived in a loop for\n// as long as the new worker took to install: the old worker served the old\n// document from cache, the old client was told 409 on its first tap, loaded\n// the document - the old one again - and so on, once per url, a document\n// load per tap, for the tens of seconds a phone spends precaching.\nlet serverBuild = null\n\nself.addEventListener('message', (event) => {\n const data = event.data\n\n if (data && data.type === 'rsc-kit:server-build' && typeof data.version === 'string') {\n serverBuild = data.version\n\n if (event.ports && event.ports[0]) event.ports[0].postMessage({ type: 'rsc-kit:server-build', version: serverBuild })\n }\n})\n\n// Whether a cached document may be the previous build's: the server has\n// been reported on another build than the copy carries, or a newer worker\n// is installing or waiting behind this one.\nconst maybeStale = (hit) => {\n if (!hit) return false\n if (self.registration && (self.registration.installing || self.registration.waiting)) return true\n\n const built = hit.headers.get('X-RSC-Version')\n\n return serverBuild !== null && built !== null && built !== serverBuild\n}\n\n// Whether a response may be kept at all.\n//\n// \\`no-store\\` is not advice here, it is the answer. A query defaults to\n// \\`private, no-store\\` precisely because it may read the session, and a worker\n// that files it by url alone would serve one visitor's answer to whoever signs\n// in next — the Cache API has no notion of who asked. A live response is worse\n// again: the clone goes on streaming long after the page that opened it is\n// gone.\n//\n// Checked before every put, rather than only for the paths that happen to reach\n// a query today. A new cacheable route added later must not have to remember\n// this.\nconst mayStore = (response) =>\n response.ok && !(response.headers.get('Cache-Control') || '').includes('no-store')\n\n// What a response is filed under. A payload request carries headers the url\n// does not, so the url is where they have to go.\nconst keyFor = (request) => {\n if (!request.headers.get('X-RSC')) return request\n\n const url = new URL(request.url)\n url.searchParams.set('__rsc', request.headers.get('X-RSC-Segments') || '')\n\n return new Request(url, { headers: request.headers })\n}\n\n// Nothing cached for a request and no network: the offline page for a\n// navigation, and for the boot of a page the offline page stood in for -\n// the runtime asks for the payload of the url in the address bar, which is\n// the one thing nothing has - the offline page's own payload, which is what\n// the document on screen is. A boot only, no segments header: a navigation\n// while offline still fails as itself, and the page already open keeps its\n// banner. Null when there is no offline page, or nothing of it cached.\nconst standIn = async (request) => {\n if (!OFFLINE_URL) return null\n\n if (request.mode === 'navigate') return (await own(OFFLINE_URL)) ?? null\n\n if (request.headers.get('X-RSC') && !request.headers.get('X-RSC-Segments')) {\n return (\n (await own(\n keyFor(new Request(new URL(OFFLINE_URL, self.location.origin), { headers: { 'X-RSC': '1' } })),\n MATCH,\n )) ?? null\n )\n }\n\n return null\n}\n\n// The Cache API honours Vary, and a stored payload varies on X-RSC - so a\n// payload warmed with one spelling of that header was a miss for a boot\n// that sent another, and a precached page rendered offline with its payload\n// sitting in the cache, unmatched. What Vary is for is already in the key:\n// the ?__rsc=<segments> above is the one header the answer differs on.\nconst MATCH = { ignoreVary: true }\n\nself.addEventListener('fetch', (event) => {\n const request = event.request\n const url = new URL(request.url)\n\n if (request.method !== 'GET' || url.origin !== self.location.origin) return\n\n if (immutable(url)) {\n event.respondWith(\n caches.match(request).then(\n (hit) =>\n hit ??\n fetch(request).then((response) => {\n if (mayStore(response)) {\n const copy = response.clone()\n caches.open(CACHE).then((cache) => cache.put(request, copy))\n }\n\n return response\n }),\n ),\n )\n\n return\n }\n\n // A stored page, asked for without a query string. Cache first, and refresh\n // in the background so the next visit has the new one even if this worker\n // never updates.\n //\n // The query matters for the same reason it matters to a stored api route:\n // the build answered the bare url, and a page reading ?q= answers\n // differently for every value of it.\n if (FROZEN.has(url.pathname.replace(/\\\\/+$/, '') || '/') && !url.search) {\n event.respondWith(\n own(keyFor(request), MATCH).then((hit) => {\n const fresh = fetch(request)\n .then((response) => {\n if (mayStore(response)) {\n const copy = response.clone()\n caches.open(CACHE).then((cache) => cache.put(keyFor(request), copy))\n }\n\n return response\n })\n .catch(async (error) => {\n if (hit) return hit\n\n // Stored by the build but never visited from this browser, so\n // nothing is cached for it, and no network: the offline page is\n // the honest answer, the same as for any other navigation - and\n // its payload for the boot that follows, so the page it stood\n // in for hydrates. Without this a frozen page failed with\n // ERR_FAILED where an unstored one showed /offline, and then\n // stood inert where an unstored one hydrated.\n return (await standIn(request)) ?? Promise.reject(error)\n })\n\n // Not awaited when there is a hit: the point is that the visitor does\n // not wait for the network for a page that cannot have changed - and\n // a deploy is how it changes, so a copy that may be the previous\n // build's waits for the network, with the copy as the fallback.\n if (maybeStale(hit)) return fresh.catch(() => hit)\n\n return hit ?? fresh\n }),\n )\n\n return\n }\n\n event.respondWith(\n fetch(request)\n .then((response) => {\n if (mayStore(response)) {\n const copy = response.clone()\n caches.open(CACHE).then((cache) => cache.put(keyFor(request), copy))\n\n // A document is not enough to boot from. The client hydrates from a\n // payload it fetches for itself, and on a first visit that request\n // happens before this worker controls the page — so it is never\n // cached, and a reload with no network has the markup and nothing to\n // hydrate it with.\n //\n // \\`X-RSC: 1\\` and no segments header is exactly what a fresh boot\n // sends, which is what makes this entry the one it finds: the server\n // varies on those, and the Cache API matches on the same.\n if (request.mode === 'navigate') {\n const warm = new Request(request.url, { headers: { 'X-RSC': '1' } })\n\n fetch(warm)\n .then((payload) => {\n if (mayStore(payload)) {\n caches.open(CACHE).then((cache) => cache.put(keyFor(warm), payload))\n }\n })\n .catch(() => {})\n }\n\n // And the other way round. Moving between pages fetches payloads and\n // never documents, so a page reached only by a link had nothing to\n // serve when someone reloaded its url — it navigated fine and then\n // died on refresh, which is the half of offline nobody would trust.\n //\n // Once per url: the document is fetched only when the cache has none,\n // so this costs one extra request the first time a page is visited\n // rather than one on every navigation to it.\n if (request.headers.get('X-RSC')) {\n const document = new Request(request.url)\n\n caches.open(CACHE).then(async (cache) => {\n if (await cache.match(document)) return\n\n const fresh = await fetch(document).catch(() => null)\n\n if (fresh && mayStore(fresh)) await cache.put(document, fresh)\n })\n }\n }\n\n return response\n })\n .catch(async () => {\n const hit = await own(keyFor(request), MATCH)\n\n if (hit) return hit\n\n // Nothing cached for this url and no network to ask.\n //\n // Falling back to the cached ROOT was worse than failing: the document\n // IS the page here, so the visitor got the home page's markup under the\n // address they asked for, and it did not hydrate — a wrong page\n // pretending to be the right one.\n //\n // An offline page is different, and is the one page that can honestly\n // stand in for another: it is about being offline, not about the url it\n // appears under. Navigations only — a payload request answered with a\n // document would be decoded as one and throw.\n const stood = await standIn(request)\n\n if (stood) return stood\n\n // Letting it fail says what is true, and a page already open is\n // unaffected.\n return Response.error()\n }),\n )\n})\n`;\n\n/**\n * Write the worker beside the assets it caches.\n *\n * The version is a hash of what is being precached rather than a build id from\n * the environment. The names are content-hashed already, so a build that\n * changed nothing produces the same list and leaves the visitor's cache alone,\n * and a build that changed anything produces a different one — which is the\n * whole of cache invalidation, without asking anyone to set a variable.\n */\n/**\n * Write the web app manifest into the client output, beside the assets.\n *\n * Into the same directory the browser is served from, because that is where a\n * relative icon path resolves — a manifest served from somewhere else resolves\n * its icons somewhere else too, and the failure is a browser that quietly does\n * not offer to install.\n */\n/**\n * The manifest an app declared beside its routes.\n *\n * `src/app/manifest.ts`, default-exporting the object — the same shape every\n * other thing about a route tree takes here, and the reason this is a file\n * rather than a `vite.config.ts` key. A manifest is not build configuration\n * any more than a page is; it is one more thing the app declares about itself,\n * and it belongs where the app is.\n *\n * Evaluated with the TypeScript stripped rather than imported: this runs while\n * the plugin is being constructed, long before there is a module graph to pull\n * it through, and importing an app module here would drag its imports in with\n * it. The file is a literal object by contract, which is all that has to parse.\n */\nexport function declaredManifest(appDir: string): WebManifestOptions | null {\n for (const extension of [\"ts\", \"tsx\", \"js\", \"mjs\"]) {\n const file = join(appDir, `manifest.${extension}`);\n\n if (!existsSync(file)) continue;\n\n const source = readFileSync(file, \"utf-8\");\n // The object literal after `export default`, with a `satisfies` or `as`\n // annotation tolerated after it — which is how anyone who wants the type\n // checked will actually write the file, and getting that wrong would refuse\n // the recommended spelling.\n //\n // A manifest that is not a literal — computed, imported from elsewhere — is\n // refused loudly rather than silently ignored, because the failure would\n // otherwise be an app that is simply not installable with nothing said.\n const match =\n /export\\s+default\\s+(\\{[\\s\\S]*\\})(?:\\s+(?:satisfies|as)\\s+[\\w.<>\\[\\]| ]+)?\\s*;?\\s*$/.exec(\n source.trim(),\n );\n\n if (!match) {\n throw new Error(\n `[rsc-kit] app/manifest.${extension} must default-export an object literal.\\n` +\n \"It is read at build time, before there is a module graph to evaluate it in, so it \" +\n \"cannot be computed or imported from elsewhere.\",\n );\n }\n\n try {\n // Function rather than JSON.parse: the file is TypeScript source with\n // unquoted keys, trailing commas and comments in it, none of which JSON\n // accepts and all of which are ordinary in a file a person edits.\n return new Function(`return (${match[1]})`)() as WebManifestOptions;\n } catch (error) {\n throw new Error(\n `[rsc-kit] Could not read app/manifest.${extension}: ${(error as Error).message}`,\n );\n }\n }\n\n return null;\n}\n\n/**\n * Copy the icons and share images into the client output.\n *\n * They live in `app/` so the build can read them - an icon's filename decides\n * what goes in the manifest - but a browser has to be able to fetch them, and\n * nothing serves `app/`. Copied rather than symlinked: the output is what gets\n * deployed, and a link into a source tree that is not deployed points nowhere.\n */\nfunction copyAppAssets(clientDir: string): void {\n if (!existsSync(clientDir)) return;\n\n for (const file of rootFiles) {\n copyFileSync(join(sourceDir, \"app\", file), join(clientDir, file));\n }\n\n const all = allAppAssets(foundAssets);\n\n if (all.length === 0) return;\n\n for (const asset of all) {\n const to = join(clientDir, asset.href.slice(1));\n\n mkdirSync(dirname(to), { recursive: true });\n copyFileSync(join(sourceDir, \"app\", asset.file), to);\n }\n\n log(`icons: ${all.length} copied from app/`);\n}\n\nfunction writeWebManifest(\n clientDir: string,\n options: WebManifestOptions,\n): void {\n if (!existsSync(clientDir)) return;\n\n writeFileSync(join(clientDir, MANIFEST_PATH.slice(1)), webManifest(options));\n\n const warning = manifestWarning(options);\n\n if (warning) log(warning);\n else log(`manifest: ${options.name} is installable`);\n}\n\n/**\n * The url a navigation falls back to when nothing else can answer it.\n *\n * An ordinary route at /offline, and it has to be one the build STORED — a\n * page that renders per request cannot be served when there is no request to\n * be made. So a dynamic /offline is refused as a fallback rather than\n * precached and found wanting at the one moment it matters, and the build says\n * which read did it.\n */\nexport function offlineFallback(\n frozen: string[],\n results: PrerenderResult[],\n): string | null {\n const found = results.find((r) => r.url === \"/offline\");\n\n if (!found) return null;\n\n if (!frozen.includes(\"/offline\")) {\n // The reason already reads \"dynamic — called cookies()\", and this sentence\n // has said \"not stored\" by the time it gets there, so the prefix would say\n // it twice with a dash in the middle of both. A shell's reason is a\n // sentence of its own - \"connection() awaited by AuthLinks streams per\n // request; the rest is stored\" - and takes no \"it\" in front, and the\n // part about the rest being stored is not the point here.\n const why =\n found.type === \"shell\"\n ? (found.reason?.replace(/; the rest is stored$/, \"\") ?? null)\n : found.reason\n ? \"it \" + found.reason.replace(/^dynamic — /, \"\")\n : null;\n\n log(\n \"offline: /offline cannot be the fallback\" +\n (why ? `, because ${why}` : \"\") +\n \". A fallback has to be servable with no network at all.\",\n );\n\n return null;\n }\n\n return \"/offline\";\n}\n\n/**\n * The app's own service worker code, if it wrote any.\n *\n * `src/app/sw.js`, copied next to the generated worker and imported by it. Plain\n * javascript rather than TypeScript, and that is not an oversight: it is\n * evaluated by the browser in a worker scope with no build step in front of it,\n * so what is written is what runs. Calling it .js says so.\n *\n * This is the only way to add an event this package does not handle — push,\n * notificationclick, sync — without giving up everything the generated worker\n * does. There is no option for it because there is nothing to configure: the\n * file is there or it is not.\n */\nfunction copyServiceWorkerExtra(clientDir: string): string | null {\n const source = join(sourceDir, \"app\", \"sw.js\");\n\n if (!existsSync(source)) return null;\n\n copyFileSync(source, join(clientDir, \"sw-app.js\"));\n\n return \"/sw-app.js\";\n}\n\n/**\n * Whether a public file is worth fetching before it is asked for.\n *\n * The precache is what lets the app boot with no network: the scripts, the\n * stylesheets, the fonts, the manifest and its icons. Everything else in\n * public/ - an image, a wasm module, the share card - is cached the first\n * time it is used, which is what the fetch handler does for any hashed\n * asset. Precaching all of it made an install cost a megabyte before the\n * visitor had seen a page: 765 kB of it a webp encoder, the rest a png no\n * browser ever renders.\n */\nexport function bootsTheApp(file: string): boolean {\n if (/\\.(?:m?js|css|woff2?|webmanifest|json)$/i.test(file)) return !/\\.wasm\\.js$/i.test(file);\n if (/(?:^|\\/)(?:icon|apple-icon|favicon)[^/]*\\.(?:png|ico|svg)$/i.test(file)) return true;\n\n return false;\n}\n\nfunction writeServiceWorker(\n clientDir: string,\n frozen: string[] = [],\n offlineUrl: string | null = null,\n): void {\n if (!existsSync(clientDir)) return;\n\n // Before the walk, so it lands in the precache with everything else. The\n // worker importScripts it while evaluating, which is the one moment it cannot\n // go to the network for it — a worker whose import fails does not start, and\n // then nothing is cached at all.\n const extra = copyServiceWorkerExtra(clientDir);\n\n const files: string[] = [];\n\n const walk = (dir: string, prefix: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n // Not itself, and not a map: a debugger asks for those, a visitor does\n // not, and precaching them doubles what an install costs.\n if (entry.name === \"sw.js\" || entry.name.endsWith(\".map\")) continue;\n\n const path = join(dir, entry.name);\n\n if (entry.isDirectory()) walk(path, `${prefix}${entry.name}/`);\n else if (bootsTheApp(`${prefix}${entry.name}`)) files.push(`${prefix}${entry.name}`);\n }\n };\n\n walk(clientDir, \"\");\n\n const precache = [\"/\", ...files.map((file) => `/${file}`)].sort();\n const version = createHash(\"sha256\")\n .update(precache.join(\"\\n\"))\n .digest(\"hex\")\n .slice(0, 12);\n\n writeFileSync(\n join(clientDir, \"sw.js\"),\n SERVICE_WORKER(version, precache, frozen, offlineUrl, extra),\n );\n\n log(\n `offline: ${precache.length} files precached as rsc-kit-${version}` +\n (offlineUrl ? `, falling back to ${offlineUrl}` : \"\") +\n (extra ? \", with app/sw.js\" : \"\"),\n );\n}\n\n/**\n * The rsc bundle the build just wrote, whatever it decided to call it.\n *\n * Two things were assumed here and both were wrong for somebody. The directory\n * was assumed to be <outDir>/dist/rsc, which Nitro does not use — it builds the\n * environment under node_modules/.nitro. And the file was assumed to be\n * index.js, which Vite only emits for a package that declares `type: module`;\n * everyone else got index.mjs. Either miss returned quietly, and a build that\n * prerendered nothing printed exactly what a build with no pages to freeze\n * prints.\n */\nfunction resolveRscBundle(dir: string): string | null {\n for (const name of [\"index.js\", \"index.mjs\"]) {\n const candidate = join(dir, name);\n\n if (existsSync(candidate)) return candidate;\n }\n\n return null;\n}\n\n/**\n * Every server action the bundle registered, from the plugin's own table.\n *\n * Only the app's: the engine registers a few of its own and they are not the\n * project's to be warned about.\n */\nfunction knownActionsOf(\n config: { plugins: readonly unknown[] },\n root: string,\n): KnownAction[] {\n const api = getPluginApi(config as never);\n const metaMap = api?.manager?.serverReferences?.metaMap;\n\n if (!metaMap) return [];\n\n const out: KnownAction[] = [];\n\n for (const meta of metaMap.values()) {\n if (meta.importId.includes(\"/node_modules/\")) continue;\n\n const file = relative(root, meta.importId.split(\"?\")[0] ?? meta.importId);\n\n for (const name of meta.exportNames) {\n out.push({ id: `${meta.referenceKey}#${name}`, name, file });\n }\n }\n\n return out;\n}\n\nasync function auditActions(\n engine: unknown,\n known: KnownAction[],\n): Promise<\n { id: string; name: string; file: string; client: boolean; query: boolean }[]\n> {\n const audit = (\n engine as {\n auditActions?: (\n ids: string[],\n ) => Promise<{ id: string; client: boolean; query: boolean }[]>;\n }\n ).auditActions;\n\n if (!audit || known.length === 0) return [];\n\n const byId = new Map(known.map((k) => [k.id, k]));\n\n return (await audit(known.map((k) => k.id))).map((a) => ({\n ...byId.get(a.id)!,\n client: a.client,\n query: a.query,\n }));\n}\n\n/**\n * Inlined into a page with no runtime when it is at most this big on the\n * wire. The point is the round trip, not the bytes: a stylesheet that\n * compresses to a few KB costs a whole trip before anything paints, while a\n * large one is better fetched once and cached across pages. Measured\n * gzipped, because that is what travels - a sheet of @font-face\n * declarations is long and compresses to almost nothing.\n */\nconst INLINE_STYLESHEET_LIMIT = 10 * 1024;\n\nexport function smallStylesheetReader(\n assetsDir: string,\n setting: \"auto\" | true | number,\n): (href: string) => string | null {\n const limit =\n setting === true\n ? Infinity\n : setting === \"auto\"\n ? INLINE_STYLESHEET_LIMIT\n : setting;\n\n return (href) => {\n if (!href.startsWith(\"/\") || href.includes(\"..\")) return null;\n\n try {\n const css = readFileSync(join(assetsDir, href), \"utf-8\");\n\n return gzipSync(css).length > limit ? null : css;\n } catch {\n return null;\n }\n };\n}\n\n/** A server action the bundle registered: where it is and what it is called. */\nexport interface KnownAction {\n id: string;\n name: string;\n file: string;\n}\n\nasync function prerenderAfterBundles(\n bundle: string | null,\n staticDir: string,\n assetsDir: string,\n knownActions: KnownAction[] = [],\n): Promise<{ frozen: string[]; results: PrerenderResult[] }> {\n // A missing bundle used to be a silent `return`, and under Nitro it was the\n // normal case: the path was assumed to be <outDir>/dist/rsc/index.js, Nitro\n // builds the rsc environment somewhere else entirely, and so every Nitro app\n // — every scaffolded app, and Laravel — prerendered nothing at all. No\n // classification printed, no route frozen, and every page renders per\n // visitor. The caller resolves the path from the environment now, so this is\n // back to being the impossible case it reads as.\n if (!bundle) {\n throw new Error(\n \"[rsc-kit] The build produced no rsc bundle to prerender from.\\n\" +\n \"Prerendering renders the app, so it needs the bundle the build just wrote.\",\n );\n }\n\n const [\n {\n prerender,\n NotPrerenderable,\n summary,\n legend,\n notes,\n clientJsSize,\n pathKey: pathKeyOf,\n },\n { writeTo },\n { prerenderApiRoutes },\n ] = await Promise.all([\n import(\"./prerender.js\"),\n import(\"./files.js\"),\n import(\"./apiPrerender.js\"),\n ]);\n\n // Cleared first: a route that changes classification between builds\n // otherwise leaves its old shell on disk and the host goes on serving it.\n // Nothing warns — the page loads, with content from the previous build.\n rmSync(staticDir, { recursive: true, force: true });\n\n const engine = (await import(pathToFileURL(bundle).href)) as never;\n const mark: Record<string, string> = {\n frozen: \"○\",\n shell: \"◐\",\n blocked: \"✗\",\n error: \"✗\",\n };\n let failed = 0;\n\n // Weighed from the page the prerenderer just wrote, so the column is what\n // that page actually loads rather than a total every route is charged for.\n const weigh = weighClientJs(assetsDir);\n const sized = new Map<string, number>();\n const pending: { line: string; bytes: number | null; extra: string[] }[] = [];\n\n // Every result as it lands, so a refusal still has the whole table.\n //\n // prerender() throws NotPrerenderable when a page blocked above every\n // boundary, and it used to throw past everything below: no table printed,\n // no report written. The terminal got the advice; the report on disk was\n // the previous build's, and an agent reading it through the MCP server was\n // told the routes were fine, as of some minutes ago. A build that refuses\n // is the build an agent most needs written down.\n const collected: PrerenderResult[] = [];\n let refusal: InstanceType<typeof NotPrerenderable> | null = null;\n let results: PrerenderResult[];\n\n try {\n results = await prerender({\n engine,\n write: writeTo(staticDir),\n serviceWorker: offline,\n stylesheet:\n inlineStylesheets === false\n ? undefined\n : smallStylesheetReader(assetsDir, inlineStylesheets),\n onResult: (r) => {\n collected.push(r);\n\n if (r.type === \"error\" || r.type === \"blocked\") failed++;\n\n const key = pathKeyOf(r.url);\n const file = [`${key}.html`, `${key}.ppr.html`]\n .map((name) => join(staticDir, name))\n .find((path) => existsSync(path));\n\n const bytes = file ? weigh(readFileSync(file, \"utf-8\")) : null;\n\n if (bytes !== null) sized.set(r.url, bytes);\n\n pending.push({\n line: ` ${mark[r.type] ?? \" \"} ${r.url}`,\n bytes,\n extra: [\n ...(r.reason ? [` ${r.reason}`] : []),\n ...(r.note ? [` ${r.note}`] : []),\n ...(r.warning ? [` ⚠ ${r.warning}`] : []),\n ],\n });\n },\n });\n } catch (error) {\n if (!(error instanceof NotPrerenderable)) throw error;\n\n refusal = error;\n results = collected;\n }\n\n // After the pages, sharing their output. An api route is a url the build\n // either answered or could not, which is the same question the table above\n // is already answering — a second list under its own heading would be two\n // places to look for one fact.\n const manifest = (\n engine as { manifest(): import(\"./manifest.js\").RouteManifest }\n ).manifest();\n const apis = await prerenderApiRoutes(engine, manifest, writeTo(staticDir));\n\n // A sitemap the build writes itself, when the app wrote none: every url\n // it stored or was told about, minus the guarded ones. It needs the site's\n // host, which the root layout's metadataBase is for; without one there is\n // nothing to write and the report says so once.\n const writesSitemap = manifest.apis?.some(\n (api) => api.name === \"app/sitemap.xml/route\",\n );\n const hasSitemapFile = rootFiles.includes(\"sitemap.xml\");\n\n if (!writesSitemap && !hasSitemapFile) {\n const base = rootMetadataBase(join(sourceDir, \"app\"));\n\n if (base) {\n const xml = automaticSitemap(results, manifest.routes, base);\n const stored = JSON.stringify({\n status: 200,\n headers: [[\"content-type\", \"application/xml; charset=utf-8\"]],\n body: xml,\n varies: false,\n });\n\n await writeTo(staticDir)(\"sitemap.xml.api.json\", stored);\n pending.push({\n line: \" ○ /sitemap.xml\",\n bytes: null,\n extra: [\n ` written by the build: ${xml.split(\"<url>\").length - 1} urls; a sitemap.ts beside the root layout replaces it`,\n ],\n });\n } else {\n pending.push({\n line: \" - /sitemap.xml\",\n bytes: null,\n extra: [\n \" not written: the root layout has no metadataBase to make the urls absolute\",\n ],\n });\n }\n }\n\n for (const api of apis) {\n pending.push({\n line: ` ${api.type === \"frozen\" ? \"○\" : \"ƒ\"} ${api.url}`,\n bytes: null,\n extra: [\n ...(api.reason ? [` ${api.reason}`] : []),\n ...(api.warning ? [` ⚠ ${api.warning}`] : []),\n ],\n });\n }\n\n // Printed together rather than as each route lands, because a column has to\n // line up and the widest url is not known until the last one is in.\n const column = Math.max(...pending.map((p) => p.line.length)) + 2;\n\n for (const row of pending) {\n const size = row.bytes === null ? \"\" : clientJsSize(row.bytes);\n\n console.log(size ? row.line.padEnd(column) + size : row.line);\n\n for (const line of row.extra) console.log(line);\n }\n\n const count = (type: string) => results.filter((r) => r.type === type).length;\n\n // The actions, after the routes. Which ones a client built is a mark on the\n // loaded function, so the bundle is asked; the answer is the one fact about\n // an action nothing else in the app states — whether anything checks who\n // calls it.\n const audited = await auditActions(engine, knownActions);\n const bare = audited.filter((a) => !a.client);\n\n if (bare.length > 0) {\n const byFile = new Map<string, string[]>();\n\n for (const a of bare)\n byFile.set(a.file, [...(byFile.get(a.file) ?? []), a.name]);\n\n console.log(\n `\\n \\u26a0 ${bare.length} ${bare.length === 1 ? \"action runs\" : \"actions run\"} no middleware: ` +\n [...byFile]\n .map(([file, names]) => `${names.join(\", \")} (${file})`)\n .join(\"; \"),\n );\n console.log(\n \" Nothing checks who calls them. Fine for a public one; otherwise build it\\n\" +\n \" from an action client, so the check cannot be forgotten.\",\n );\n }\n\n // Server files importing cache from React. Its cache() memoises on the\n // dispatcher a render installs, so in a guard, an action, an api route or\n // the SSR pass it calls straight through - no dedupe, no error, the helper\n // runs twice. The difference is silent, which is why this line exists.\n const reactCache = reactCacheImports(sourceDir);\n\n if (reactCache.length > 0) {\n console.log(\n `\\n \\u26a0 ${reactCache.length} server ${reactCache.length === 1 ? \"file imports\" : \"files import\"} cache from 'react': ` +\n reactCache.join(\", \"),\n );\n console.log(\n \" React's cache() dedupes only inside a component render; in a guard, an action or\\n\" +\n \" an api route it calls straight through. Import it from @rsc-kit/core/cache instead.\",\n );\n }\n\n // Server files importing a client library. Legal - a server component may\n // render a client component from a package - but the shape that costs an\n // afternoon is a file with no \"use client\" that only wraps them, so the\n // library's internals run on the server. Said, with the packages and the\n // importer, so the person reading can tell which it is.\n if (clientLibraryImports.length > 0) {\n console.log(\n `\\n \\u2139 ${clientLibraryImports.length} server ${clientLibraryImports.length === 1 ? \"file imports\" : \"files import\"} a client library: ` +\n clientLibraryImports\n .map(\n (c) =>\n `${c.file} (${c.packages.join(\", \")}${c.from ? `; imported by ${c.from}` : \"\"})`,\n )\n .join(\"; \"),\n );\n console.log(\n ' Legal for a server component. A file that only wraps client components wants \"use client\" -\\n' +\n \" as shadcn ships it - so the server stops at the boundary.\",\n );\n }\n\n // Written from the rows that were just printed rather than recomputed: the\n // report and the terminal must not be able to disagree about what happened.\n writeFileSync(\n join(outDir, REPORT_FILE),\n buildReport(\n results.map((r) => ({\n url: r.url,\n component: r.component,\n type: r.type,\n reason: r.reason,\n warning: r.warning ?? null,\n note: r.note ?? null,\n clientJs: sized.get(r.url) ?? null,\n })),\n apis.map((a) => ({\n url: a.url,\n name: a.name,\n type: a.type,\n reason: a.reason,\n warning: a.warning ?? null,\n })),\n audited,\n reactCache,\n clientLibraryImports,\n ),\n );\n\n const note = notes(results);\n const counted = [...results, ...apis];\n\n console.log(`\n${legend(counted)}\n\n ${summary(counted)}${note ? `\\n\\n${note}` : \"\"}`);\n\n // The table and the report are on disk. Now the refusal, in its own words.\n if (refusal) throw new Error(refusal.message);\n\n if (failed > 0) {\n throw new Error(\n `[rsc-kit] ${failed} route${failed === 1 ? \"\" : \"s\"} failed to render.\\n` +\n \"Prerendering runs your app: whatever those pages need at render time has to be\\n\" +\n \"reachable from the build. Give it that, or mark the read with `await connection()`\\n\" +\n \"so the page renders per request and the rest of it is still stored.\",\n );\n }\n\n if (output === \"export\")\n await exportAfterPrerender(results, staticDir, assetsDir);\n\n // The urls whose answer cannot change until the next build. The service\n // worker serves these from its cache first rather than asking the network\n // and falling back — see writeServiceWorker.\n //\n // Two narrowings beyond \"frozen\", and neither is redundant even though the\n // worker would survive without them. A guarded route IS frozen — the guard\n // is a serving decision, not a build one — but its response is per visitor\n // and must never be read from a cache that has no notion of who asked. A\n // redirect is stored as a destination rather than a page, so there is no\n // document to serve from a cache at all.\n //\n // Both are already refused downstream: a guarded response carries no-store\n // and a 3xx is not `ok`. Saying it here as well means the list means what it\n // says, rather than being a wider list that happens to be filtered later.\n const guarded = new Set(\n manifest.routes.filter((r) => r.middleware?.length).map((r) => r.component),\n );\n\n return {\n frozen: results\n .filter((r) => r.type === \"frozen\" && !guarded.has(r.component))\n .filter((r) => existsSync(join(staticDir, pathKeyOf(r.url) + \".html\")))\n .map((r) => r.url),\n results,\n };\n}\n\n/**\n * Weighs the javascript one stored page makes the browser download.\n *\n * Read back out of the html rather than worked out from the module graph,\n * because the html is the answer: React writes a modulepreload for every chunk\n * the page needs, so whatever is in there is what the browser fetches. Nothing\n * here has to agree with the bundler about anything.\n *\n * Gzipped, and each chunk weighed once however many pages name it — the same\n * three files appear on every route and compressing them per page is the whole\n * cost of this function.\n *\n * Returns null when there is no page to weigh, which is a route rendered on\n * demand. A build must not fail over a column it prints for information.\n */\nfunction weighClientJs(assetsDir: string): (html: string) => number | null {\n const weighed = new Map<string, number>();\n\n const bytesOf = (asset: string): number => {\n const cached = weighed.get(asset);\n\n if (cached !== undefined) return cached;\n\n const file = join(assetsDir, asset);\n const bytes = existsSync(file)\n ? gzipSync(readFileSync(file)).byteLength\n : 0;\n\n weighed.set(asset, bytes);\n\n return bytes;\n };\n\n return (html: string) => {\n if (!html) return null;\n\n const named = new Set<string>();\n\n // Split rather than matched: /assets/name.js is the only shape written, and\n // a regex over a whole document is the slower half of this function.\n for (const piece of html.split(\"/assets/\").slice(1)) {\n const name = piece.split(/[\"'\\s)]/)[0];\n\n if (name.endsWith(\".js\")) named.add(\"assets/\" + name);\n }\n\n let total = 0;\n\n for (const asset of named) total += bytesOf(asset);\n\n return total;\n };\n}\n\n/**\n * Turn the frozen output into a directory a static host can serve.\n *\n * Part of the build rather than a script the app writes, for the same reason\n * prerendering is: it needs the results the build already has, and the engine\n * bundle they came from is somewhere only the build knows. That path used to be\n * stable enough to hard-code in an example — `build/dist/rsc/index.js` — and it\n * is not any more, because Nitro builds the rsc environment under\n * node_modules. A script asking for it would be a script that breaks.\n *\n * RSC_EXPORT_FORCE writes the site anyway and reports what it left out, which\n * is how an app is moved towards being exportable. Without it a route that\n * could not be frozen fails the build, because a shell on a static host is a\n * page that loads and then stays empty forever.\n */\nasync function exportAfterPrerender(\n results: PrerenderResult[],\n staticDir: string,\n assetsDir: string,\n): Promise<void> {\n const [\n { exportSite, NotExportable },\n { writeTo, prerenderedFrom, copyAssets },\n ] = await Promise.all([import(\"./export.js\"), import(\"./files.js\")]);\n\n try {\n const { pages, refused } = await exportSite({\n results,\n read: prerenderedFrom(staticDir),\n write: writeTo(exportPath),\n manifest: routeManifest() as never,\n assets: copyAssets(join(assetsDir, \"assets\"), exportPath, \"/assets/\"),\n force: process.env.RSC_EXPORT_FORCE === \"1\",\n });\n\n console.log(\n `\\n Exported ${pages} page${pages === 1 ? \"\" : \"s\"} to ${relative(projectRoot, exportPath)}`,\n );\n\n if (refused.length > 0) {\n console.log(\n ` Left out ${refused.length}: ${refused.map((r) => r.url).join(\", \")}`,\n );\n }\n } catch (error) {\n if (!(error instanceof NotExportable)) throw error;\n\n throw new Error(`[rsc-kit] ${error.message}`);\n }\n}\n\n/** `/posts/[slug]` — the pattern, in the shape the app writes its links in. */\nfunction patternOf(segments: RouteSegment[]): string {\n if (segments.length === 0) return \"/\";\n\n return (\n \"/\" +\n segments\n .map((segment) =>\n segment.type === \"static\"\n ? segment.value\n : segment.type === \"catchAll\"\n ? `[...${segment.value}]`\n : `[${segment.value}]`,\n )\n .join(\"/\")\n );\n}\n\n/**\n * The app's routes as a union, for `@rsc-kit/core/routes` to derive from.\n *\n * Rewritten every build like the other generated files: a route deleted from\n * the tree has to stop being a valid href, and the only thing that knows is\n * the walk that just happened.\n *\n * Interception patterns are deliberately absent. An interceptor answers a url\n * that some real route already owns — listing it would put the same href in\n * the union twice and imply you could link to a modal.\n */\nfunction renderRouteTypes(manifest: RouteManifest): string {\n const patterns = [\n ...new Set(manifest.routes.map((route) => patternOf(route.segments))),\n ].sort();\n const apis = [\n ...new Set((manifest.apis ?? []).map((route) => patternOf(route.segments))),\n ].sort();\n\n // Each pattern to the page module that answers it, as a type-only import\n // from the generated file's own directory. SearchExportOf reads the page's\n // `searchParams` export, or undefined when there is none, so nothing here\n // has to look inside the file - the typechecker already has every page\n // open. One line per route, and a page without a schema costs nothing.\n const search = new Map<string, string>();\n\n for (const route of manifest.routes) {\n const pattern = patternOf(route.segments);\n\n if (search.has(pattern)) continue;\n\n const target = relative(typesDir, join(sourceDir, route.component)).replace(\n /\\\\/g,\n \"/\",\n );\n\n search.set(pattern, target.startsWith(\".\") ? target : \"./\" + target);\n }\n\n // Section names are read from the source - section('orders', …) - the way\n // generateStaticParams is detected, because this runs before any bundle\n // exists. A name computed at runtime is not seen and revalidate() falls\n // back to refusing it at the renderer, as before.\n const regions = [\n ...new Set([\n ...[...components.values()]\n .filter((c) => SECTION_FILE.test(c.absPath))\n .flatMap((c) =>\n [\n ...readFileSync(c.absPath, \"utf-8\").matchAll(\n /\\bsection\\(\\s*['\"`]([^'\"`]+)['\"`]/g,\n ),\n ].map((m) => m[1]),\n ),\n ...[...components.keys()].flatMap((name) => {\n const slot = name.split(\"/\").find((part) => part.startsWith(\"@\"));\n\n return slot ? [slot.slice(1)] : [];\n }),\n ]),\n ].sort();\n\n return [\n \"// @generated — do not edit. Written by the RSC build from the route tree.\",\n \"//\",\n \"// Turns Link, navigate() and route() into typed apis: an href that no route\",\n \"// answers stops compiling. Delete this file and they fall back to `string`,\",\n \"// which is what a project that has not built yet gets.\",\n \"\",\n \"// `export {}` is load-bearing: in a file with no import or export,\",\n \"// `declare module` *replaces* the real module rather than augmenting it,\",\n \"// and Route and route() vanish from it with no error to explain why.\",\n \"export {}\",\n \"\",\n \"declare module '@rsc-kit/core/routes' {\",\n \" interface Register {\",\n patterns.length > 0\n ? \" routes:\\n\" +\n patterns.map((p) => \" | \" + JSON.stringify(p)).join(\"\\n\")\n : \" // No routes found under the source directory.\\n routes: never\",\n // The searchParams schema each page exports, read off the module's type.\n // This is what types Link's `search` prop and href() per route.\n \" search: {\",\n ...[...search]\n .sort()\n .map(\n ([pattern, target]) =>\n \" \" +\n JSON.stringify(pattern) +\n \": SearchExportOf<typeof import(\" +\n JSON.stringify(target) +\n \")>\",\n ),\n \" }\",\n \" }\",\n // Api routes are a separate union, so Link refuses an api url and apiUrl()\n // refuses a page. Linking to an api route navigates the browser away to a\n // json document, which is the mistake worth catching.\n // Regions: every section('name', …) the build read, and every @slot\n // directory. This is what types revalidate().\n \" interface RegisterRegions {\",\n regions.length > 0\n ? \" regions:\\n\" +\n regions.map((r) => \" | \" + JSON.stringify(r)).join(\"\\n\")\n : \" // No sections or slots found under the source directory.\\n regions: never\",\n \" }\",\n \" interface RegisterApi {\",\n apis.length > 0\n ? \" apis:\\n\" +\n apis.map((p) => \" | \" + JSON.stringify(p)).join(\"\\n\")\n : \" // No route.ts files found under the source directory.\\n apis: never\",\n \" }\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** The \"use server\" module exposing each host function as a plain async call. */\nfunction renderHostActions(): string {\n const lines = [\n '\"use server\";',\n \"// @generated — do not edit. Written by the RSC build from the host action map.\",\n \"\",\n ];\n\n for (const [name, target] of Object.entries(hostActions)) {\n lines.push(\"export async function \" + name + \"(...args: unknown[]) {\");\n lines.push(\n \" return await (globalThis as any).\" +\n hostGlobal +\n \"(\" +\n JSON.stringify(target) +\n \", ...args);\",\n );\n lines.push(\"}\");\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n/** Ambient declaration for the host global, written beside the app's source. */\nfunction renderHostGlobalTypes(): string {\n return [\n \"// @generated — do not edit.\",\n \"//\",\n \"// \" +\n hostGlobal +\n \"() is installed on globalThis by the RSC worker, so it has no\",\n \"// import to resolve. This declares it for the typechecker; run\",\n \"// `tsc --noEmit` to catch calls to a host global that no longer exists.\",\n \"//\",\n \"// Deliberately not a module — no import/export — so the declaration is\",\n \"// global to the project without every file having to reference it.\",\n \"\",\n \"declare function \" +\n hostGlobal +\n \"<T = unknown>(name: string, ...args: unknown[]): Promise<T>;\",\n \"\",\n ].join(\"\\n\");\n}\n\n// ── Discovery ────────────────────────────────────────────────────────────────\n\nconst ROUTE_FILES = [\n \"page\",\n \"layout\",\n \"loading\",\n \"error\",\n \"not-found\",\n \"default\",\n \"middleware\",\n];\n/** The methods a route.ts may export. HEAD and OPTIONS are answered for you. */\nconst API_METHODS = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"HEAD\",\n \"OPTIONS\",\n];\n/** `orders.section.tsx` — a region of a page that can be refreshed by name. */\nconst SECTION_FILE = /\\.section\\.(tsx|jsx|ts|js)$/;\nconst EXTS = [\"tsx\", \"jsx\", \"ts\", \"js\"];\n\nfunction findRouteFile(dir: string, base: string): string | null {\n for (const ext of EXTS) {\n const p = join(dir, `${base}.${ext}`);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction componentName(absPath: string): string {\n const rel = relative(sourceDir, absPath).replace(/\\\\/g, \"/\");\n return rel.replace(/\\.(tsx|jsx|ts|js)$/, \"\");\n}\n\n/**\n * The identifier a route file is imported as in the generated entries.\n *\n * One-to-one with the path, which the obvious \"replace everything odd with an\n * underscore\" is not: app/agent-account/page and app/agent/account/page\n * both came out as _c_app_agent_account_page, and the entry declared the\n * same import twice. A slash is an underscore, because that is what every\n * alias reads like; anything else that is not a letter or digit - a hyphen,\n * a dot, the brackets of a param, the parens of a group, an underscore of\n * its own - is its character code, so no two paths share an alias.\n */\nexport function toAlias(name: string): string {\n return (\n \"_c_\" +\n name.replace(/[^a-zA-Z0-9]/g, (char) => (char === \"/\" ? \"_\" : \"$\" + char.charCodeAt(0).toString(16)))\n );\n}\n\nconst components = new Map<string, Component>();\n\n/**\n * `route.ts` files, by the name a url is matched against.\n *\n * Kept apart from `components` on purpose: these are not React and never enter\n * the render. They are imported by the generated entry and called with a\n * Request, which is why they can export whatever methods they like rather than\n * a default component.\n */\nconst apiRoutes = new Map<\n string,\n {\n name: string;\n absPath: string;\n methods: string[];\n /** Synthesised from a convention file beside the root layout - see metadataRoutes. */\n generated?: { kind: MetadataRouteKind | \"openapi\"; file: string };\n }\n>();\n\nconst OPENAPI_ROUTE_ID = \"virtual:rsc-kit/openapi\";\n\n/**\n * /openapi.json, when asked for, registered as an api route at the path the\n * option names. Synthesised like a sitemap: stored by the build, without\n * middleware - a document exists to be read.\n */\nfunction registerOpenApiRoutes(): void {\n if (!openapi) return;\n\n const name = `app${openapi.path.replace(/\\/$/, \"\")}/route`;\n\n if (apiRoutes.has(name)) {\n throw new Error(\n `[rsc-kit] ${openapi.path} is answered by ${apiRoutes.get(name)!.absPath} and by rscKit({ openapi }). Move one.`,\n );\n }\n\n apiRoutes.set(name, { name, absPath: OPENAPI_ROUTE_ID, methods: [\"GET\"], generated: { kind: \"openapi\", file: \"\" } });\n}\n\n/** The module behind the synthesised /openapi.json route. */\nfunction openApiPlugin(): Plugin {\n return {\n name: \"rsc-kit:openapi\",\n resolveId(id) {\n if (id === OPENAPI_ROUTE_ID) return \"\\0\" + id;\n },\n load(id) {\n if (id !== \"\\0\" + OPENAPI_ROUTE_ID || !openapi) return;\n\n // Every route.ts the app wrote, imported so its schemas can describe\n // themselves at request time; the synthesised ones are not an API.\n const routes = [...apiRoutes.values()].filter((r) => !r.generated);\n const guarded = new Set(\n (routeManifest().apis ?? []).filter((api) => api.middleware.length > 0).map((api) => api.name),\n );\n const imports = routes.map((r, i) => `import * as __r${i} from ${JSON.stringify(r.absPath)}`);\n const entries = routes.map(\n (r, i) =>\n ` { pattern: ${JSON.stringify(patternOf(urlSegments(r.name)))}, methods: ${JSON.stringify(r.methods)}, guarded: ${guarded.has(r.name)}, module: __r${i} }`,\n );\n\n return [\n ...imports,\n `import { openApiResponse } from ${JSON.stringify(join(packageDir, \"openapi\"))}`,\n `const routes = [\\n${entries.join(\",\\n\")}\\n]`,\n `export const GET = () => openApiResponse(routes, ${JSON.stringify(openapi.document)})`,\n \"\",\n ].join(\"\\n\");\n },\n };\n}\n\n\n/** Files beside the root layout served at the root as they are: robots.txt, a hand-written sitemap.xml, humans.txt. */\nlet rootFiles: string[] = [];\n\nconst METADATA_ROUTE_ID = \"virtual:rsc-kit/metadata-route/\";\n\n/**\n * robots.ts, sitemap.ts, llms.ts beside the root layout, each registered as\n * an api route at the file it stands for. The module the entry imports is\n * synthesised (metadataRoutesPlugin): the app's default export, formatted by\n * the engine, with the root layout's metadataBase for relative urls.\n *\n * Api routes, so nothing else is new: the build stores the ones that read\n * nothing per request and names the ones that do. Without middleware, on\n * purpose - these exist to be read by anyone, and a guard on the root would\n * otherwise 401 the crawler asking for robots.txt.\n */\nfunction registerMetadataRoutes(appDir: string): void {\n rootFiles = existsSync(appDir)\n ? readdirSync(appDir)\n .filter((name) => ROOT_FILES.test(name))\n .sort()\n : [];\n\n for (const kind of Object.keys(METADATA_ROUTES) as MetadataRouteKind[]) {\n const source = [\"ts\", \"tsx\", \"js\", \"mjs\"]\n .map((ext) => join(appDir, `${kind}.${ext}`))\n .find((file) => existsSync(file));\n\n if (!source) continue;\n\n const { file } = METADATA_ROUTES[kind];\n\n if (rootFiles.includes(file)) {\n throw new Error(\n `[rsc-kit] app/${basename(source)} and app/${file} both answer /${file}. Keep one: the function, or the file as written.`,\n );\n }\n\n const name = `app/${file}/route`;\n\n if (apiRoutes.has(name)) {\n throw new Error(\n `[rsc-kit] app/${basename(source)} and app/${file}/route.ts both answer /${file}. Keep one.`,\n );\n }\n\n apiRoutes.set(name, {\n name,\n absPath: METADATA_ROUTE_ID + kind,\n methods: [\"GET\"],\n generated: { kind, file: source },\n });\n }\n}\n\n/** The module behind a synthesised metadata route. */\nfunction metadataRoutesPlugin(): Plugin {\n return {\n name: \"rsc-kit:metadata-routes\",\n resolveId(id) {\n if (id.startsWith(METADATA_ROUTE_ID)) return \"\\0\" + id;\n },\n load(id) {\n if (!id.startsWith(\"\\0\" + METADATA_ROUTE_ID)) return;\n\n const kind = id.slice(\n (\"\\0\" + METADATA_ROUTE_ID).length,\n ) as MetadataRouteKind;\n const route = [...apiRoutes.values()].find(\n (r) => r.generated?.kind === kind,\n );\n\n if (!route?.generated) return;\n\n const rootLayout = components.get(\"app/layout\")?.absPath ?? null;\n\n return [\n `import produce from ${JSON.stringify(route.generated.file)}`,\n rootLayout\n ? `import * as __root from ${JSON.stringify(rootLayout)}`\n : \"const __root = {}\",\n `import { metadataResponse } from ${JSON.stringify(join(packageDir, \"metadataRoutes\"))}`,\n `export const GET = () => metadataResponse(${JSON.stringify(kind)}, produce, __root.metadata?.metadataBase ?? null)`,\n \"\",\n ].join(\"\\n\");\n },\n };\n}\n\nfunction register(absPath: string): Component {\n const name = componentName(absPath);\n const existing = components.get(name);\n if (existing) return existing;\n const c: Component = { name, absPath, alias: toAlias(name) };\n components.set(name, c);\n return c;\n}\n\n/** Walk app/ collecting page/layout/loading/default/middleware components. */\n/**\n * Record a route.ts and the methods it exports.\n *\n * Syntactic, deliberately. A handler assembled at runtime is not found, which\n * errs toward refusing a file whose shape we would be guessing at rather than\n * registering a url that answers 405 to everything.\n */\nfunction registerApiRoute(absPath: string): void {\n const name = componentName(absPath);\n const source = readFileSync(absPath, \"utf-8\");\n const methods = API_METHODS.filter((method) =>\n new RegExp(\n `^\\\\s*export\\\\s+(?:async\\\\s+function|function|const|let|var)\\\\s+${method}\\\\b`,\n \"m\",\n ).test(source),\n );\n\n if (methods.length === 0) {\n // `route.ts` is also where a host declares the guards for everything below\n // it — the file predates api routes and is still read that way. One that\n // exports middleware is that file, not an endpoint, and saying so would be\n // telling someone their working config is broken.\n if (/^\\s*export\\s+(?:const|let|var|function)\\s+middleware\\b/m.test(source))\n return;\n\n throw new Error(\n `[rsc-kit] ${relative(projectRoot, absPath)} exports no request methods.\\n` +\n ` Export one named for the method it answers — export function GET(request: Request) — ` +\n `or delete the file. One of: ${API_METHODS.join(\", \")}.`,\n );\n }\n\n apiRoutes.set(name, { name, absPath, methods });\n}\n\n/**\n * Whether a middleware.ts is a guard the engine runs, or only names guards\n * the host runs. The engine imports a guard's default export; a file with\n * none - `export const middleware = ['auth']` and nothing else - has nothing\n * to import, and registering it would make the build fail on an export that\n * was never meant to exist.\n */\nfunction isEngineGuard(absPath: string): boolean {\n return /export\\s+default\\b/.test(readFileSync(absPath, \"utf-8\"));\n}\n\nfunction discover(dir: string): void {\n for (const base of ROUTE_FILES) {\n const p = findRouteFile(dir, base);\n if (p && (base !== \"middleware\" || isEngineGuard(p))) register(p);\n }\n\n // route.ts — an api endpoint, colocated with the pages it sits among. Read\n // for its method exports here rather than at request time, so a route that\n // exports nothing callable is a build error instead of a 404 nobody explains.\n const api = findRouteFile(dir, \"route\");\n\n if (api) registerApiRoute(api);\n\n // Named regions. Registered like any other component so the generated entry\n // imports them — which is what runs section() and puts the name in the\n // registry the server looks up to re-render one on its own.\n for (const entry of readdirSync(dir)) {\n if (SECTION_FILE.test(entry)) register(join(dir, entry));\n }\n\n for (const entry of readdirSync(dir)) {\n const abs = join(dir, entry);\n if (statSync(abs).isDirectory()) discover(abs);\n }\n}\n\n/**\n * Which of the two metadata exports a module actually has.\n *\n * Both are read separately because the generated entry names each one it\n * mentions, and naming an export that is not there is a bundler warning on\n * every build — `Import 'generateMetadata' will always be undefined`. Most\n * pages export only the static object, so referencing both meant that warning\n * for almost every route in an app.\n */\n/**\n * The root layout's metadataBase, read from the source. Wanted while the\n * manifest is built, before there is a bundle to execute - the same reason\n * generateStaticParams is detected by reading. A `new URL('…')` or a string\n * literal; anything computed is not seen, and rscKit({ hosts }) says it.\n */\nfunction rootMetadataBase(appDir: string): string | null {\n const layout = [\"layout.tsx\", \"layout.jsx\", \"layout.ts\", \"layout.js\"]\n .map((name) => join(appDir, name))\n .find((file) => existsSync(file));\n\n if (!layout) return null;\n\n const match =\n /metadataBase\\s*:\\s*(?:new\\s+URL\\(\\s*)?[\"'`](https?:\\/\\/[^\"'`]+)[\"'`]/.exec(\n readFileSync(layout, \"utf-8\"),\n );\n\n return match ? match[1] : null;\n}\n\nfunction metadataExports(absPath: string): {\n static: boolean;\n generate: boolean;\n viewport: boolean;\n /** Whether the file renders these itself, so the engine's defaults stand down. */\n writes: { charset: boolean; viewport: boolean };\n} {\n const src = readFileSync(absPath, \"utf-8\");\n\n return {\n static: /export\\s+const\\s+metadata\\b/.test(src),\n generate: /export\\s+(async\\s+)?function\\s+generateMetadata\\b/.test(src),\n viewport: /export\\s+const\\s+viewport\\b/.test(src),\n writes: {\n charset: /\\bcharSet\\s*=/.test(src),\n viewport: /name\\s*=\\s*[\"']viewport[\"']/.test(src),\n },\n };\n}\n\n/**\n * Which urls exist for a parameterised route.\n *\n * The one thing about a route the build cannot work out for itself: only the\n * app knows its slugs. Everything else about whether a page can be frozen is\n * observed by rendering it — a page that suspends past the shell budget, or\n * reaches for the host, says so by doing it. This is asked rather than\n * inferred because there is nothing to infer it from.\n */\nfunction hasStaticParams(absPath: string): boolean {\n const src = readFileSync(absPath, \"utf-8\");\n\n return /export\\s+((async\\s+)?function\\s+generateStaticParams|const\\s+generateStaticParams)/.test(\n src,\n );\n}\n\n/**\n * Which url schemas a page exports.\n *\n * Read from the source rather than by importing the module, the same way\n * metadata and generateStaticParams are: this runs while the graph is being\n * generated, and importing a page here would pull the app's whole server tree\n * into the plugin.\n *\n * `const` only. A schema is a value — `export function params` would be a\n * function, which no Standard Schema is, so matching it would generate an\n * import for something that can never validate.\n */\nfunction urlSchemaExports(absPath: string): {\n params: boolean;\n searchParams: boolean;\n} {\n const src = readFileSync(absPath, \"utf-8\");\n\n return {\n params: /export\\s+const\\s+params\\s*[=:]/.test(src),\n searchParams: /export\\s+const\\s+searchParams\\s*[=:]/.test(src),\n };\n}\n\n// ── Codegen ──────────────────────────────────────────────────────────────────\n\n/**\n * The dev fall-through, emitted only when there is a backend to hand a url to.\n *\n * A JavaScript host has no backend — it IS the backend — so its entry should\n * not carry this code, its constants, or the branch that tests them. Nothing\n * generated is cheaper than something generated that returns early, and it\n * keeps every backend-shaped idea out of a runtime that has no backend.\n */\nconst FALLBACK_CONSTS = `const FALLBACK_ORIGIN = __ORIGIN__\nconst FALLBACK_MARKER = 'x-rsc-renderer-fallback'\nconst PROXIED_MARKER = 'x-rsc-proxied-by-backend'\n`;\n\nconst FALLBACK_BODY = ` const answer = await devHandler(request)\n\n if (answer) return answer\n\n // Nothing here owns this url. In development the backend usually does — a\n // Blade page, /login, a webhook, an uploaded file under /storage — so the\n // request is handed on rather than refused, and this origin is the whole\n // application instead of the RSC half of it.\n //\n // FALLBACK_MARKER is what stops this looping. The backend's own fallback\n // forwards what it cannot route BACK to this server, so without a marker a\n // url neither side owns would bounce between them until something gave out.\n // Seeing it, the backend answers 404 itself.\n // Came from the backend's own proxy, so it has already been through that\n // route table and the answer there was no. Sending it back asks the same\n // question a second time.\n if (!FALLBACK_ORIGIN || request.headers.has(PROXIED_MARKER)) {\n return new Response('Not found', { status: 404 })\n }\n\n // Built from the origin rather than by assigning onto a copy of this url.\n // The URL host setter keeps whatever port is already there when the value it\n // is given has none, so a portless backend — every Herd or Valet site —\n // would inherit the dev server's own port and this server would call itself.\n const here = new URL(request.url)\n const target = new URL(here.pathname + here.search, FALLBACK_ORIGIN)\n\n const headers = new Headers(request.headers)\n\n // Never forwarded: a vhost server routes on it, so telling Herd the host is\n // localhost:5173 means it has no such site and answers 404. fetch sets it\n // from the target instead.\n headers.delete('host')\n headers.set(FALLBACK_MARKER, '1')\n\n // What the browser actually asked for. Without these the backend generates\n // absolute urls — url(), route(), redirects, form actions — against its own\n // origin rather than this one, and a redirect walks the browser off this\n // server onto the backend.\n //\n // They only take effect if the backend trusts this proxy: Laravel needs the\n // renderer's address in trustProxies. Sent regardless, because a header an\n // untrusting backend ignores costs nothing, and the alternative is that\n // there is no way to get it right at all.\n headers.set('x-forwarded-host', here.host)\n headers.set('x-forwarded-proto', here.protocol.replace(':', ''))\n\n const hasBody = request.method !== 'GET' && request.method !== 'HEAD'\n\n try {\n return await fetch(target, {\n method: request.method,\n headers,\n body: hasBody ? request.body : undefined,\n // A redirect is the backend's answer and belongs to the browser.\n // Following it here would return the destination's body under this url.\n redirect: 'manual',\n ...(hasBody ? { duplex: 'half' } : {}),\n } as RequestInit)\n } catch (error) {\n return new Response(\n // The cause, not just the wrapper: fetch reports every network failure\n // as the same 'TypeError: fetch failed', and the refused address\n // underneath it is the whole of the diagnosis.\n 'The backend at ' + FALLBACK_ORIGIN + ' is not answering: ' +\n String((error as { cause?: unknown }).cause ?? error),\n { status: 502 },\n )\n }\n`;\n\n/**\n * Wire host calls when Nitro is the server.\n *\n * Every other arrangement installs this from outside: the dev server does it in\n * configureServer, and a generated server.ts passes hostCalls to\n * createRscHandler. Under Nitro there is no such file — this module IS the\n * server — so an rpc() page renders its loading fallback forever and the\n * backend never hears from it. Silent, which is the worst kind.\n *\n * Read at request time rather than at build time: the endpoint belongs to the\n * deployment, and baking it in would mean rebuilding to change where the\n * backend is.\n */\n/**\n * What a generated server.ts passes, for the arrangement that has no server.ts.\n *\n * props: a page reading `params` gets its url params from the engine, and the\n * query string is merged in here — `params.q` should mean the same thing\n * whether it arrived in the path or after the ?. Only the Laravel template\n * passed this before, so the other hosts quietly did not have it.\n *\n * version: the client compares it on every navigation and falls back to a full\n * load when it changes. Without one, a browser keeps talking to a deployment\n * that is gone — worst behind a CDN, where the shell it holds may already be\n * older than the payloads it asks for.\n */\n/**\n * Where frozen pages live inside `.output/server`, written by the build and\n * found by the generated entry. One constant because the two halves are in\n * different processes — a name written down twice is a name that drifts, and\n * the failure is silent: the server finds no directory, decides nothing was\n * frozen, and renders every page live exactly as it did before.\n */\nconst NITRO_STATIC_DIR = \"rsc-static\";\n\n/**\n * Serve what the build froze.\n *\n * `import.meta.env.PROD` rather than an unconditional reader: in development\n * there is no build output to serve, and a stale one would be worse than none.\n * Vite replaces it with a literal, so the dev bundle keeps no reference to it.\n */\nconst NITRO_PRERENDERED = ` prerendered: import.meta.env.PROD\n ? prerenderedBeside(import.meta.url, ${JSON.stringify(NITRO_STATIC_DIR)})\n : undefined,\n`;\n\nconst NITRO_HANDLER_OPTIONS = ` props: (match, request) => ({\n ...match.params,\n ...Object.fromEntries(new URL(request.url).searchParams),\n }),\n // A built server gzips what it answers, where the runtime can; the dev\n // server answers raw, which is what a person reading a response wants.\n compress: import.meta.env.PROD,\n`;\n\nconst NITRO_HOST_CALLS = `\nlet hostInstalled = false\n\nfunction installHostCallsOnce(): void {\n if (hostInstalled) return\n hostInstalled = true\n\n const origin = process.env.RSC_BACKEND ?? process.env.APP_URL\n const secret = process.env.RSC_HOST_CALL_SECRET\n\n // Both, or neither: a secret without a backend has nowhere to go, and a\n // backend without one is refused at the door. See the dev server, which\n // gates on exactly the same pair.\n if (!origin || !secret) return\n\n const path = process.env.RSC_HOST_CALL_PATH ?? '/__rsc/host-call'\n\n installHostFn(httpHostCalls({ endpoint: origin.replace(/\\\\/$/, '') + path, secret }))\n}\n\n`;\n/**\n * The app's process bootstrap, if it has one: `instrumentation.ts` beside\n * `app/`, the name Next uses so a reader arriving from there knows what it\n * is.\n *\n * Two things make it a framework concern rather than an import the app\n * adds. Module evaluation order: a page that configures a shared package at\n * import time runs before any module the app could put first, and only the\n * generated entry can import something before the pages. And \"before the\n * first request\": an async `register()` — connecting, validating env — has\n * to be awaited by every entry point a host or a prerender can call, which\n * is a list the app cannot see.\n */\nfunction instrumentationFile(): { file: string; hasRegister: boolean } | null {\n for (const ext of [\"ts\", \"tsx\", \"mts\", \"js\", \"mjs\"]) {\n const file = join(sourceDir, `instrumentation.${ext}`);\n\n if (!existsSync(file)) continue;\n\n // Both halves are optional: a file of imports is a bootstrap, a file\n // with register() is a hook. The entry must only name `register` when it\n // exists - a namespace import's missing member is a bundler warning on\n // every build (IMPORT_IS_UNDEFINED), which is the app being told off for\n // a file written exactly as documented.\n const hasRegister = /export\\s+(?:async\\s+)?(?:function\\s+register\\b|const\\s+register\\b|let\\s+register\\b|\\{[^}]*\\bregister\\b[^}]*\\})/.test(\n readFileSync(file, \"utf-8\"),\n );\n\n return { file, hasRegister };\n }\n\n return null;\n}\n\nfunction generateEntryRsc(fallbackOrigin = \"\"): string {\n const instrumentation = instrumentationFile();\n // The 404 page, if the app has one, and the layouts it renders inside.\n // Computed here rather than looked up at runtime: not-found is not a route,\n // so the manifest has no entry to read its chain from.\n const notFoundComponent = [...components.keys()].find((name) =>\n name.endsWith(\"/not-found\"),\n );\n const notFoundLayouts = notFoundComponent\n ? [...components.keys()]\n .filter(\n (name) =>\n name.endsWith(\"/layout\") &&\n notFoundComponent.startsWith(name.slice(0, -\"layout\".length)),\n )\n .sort((a, b) => a.length - b.length)\n : [];\n\n const imports: string[] = [];\n const mapEntries: string[] = [];\n const metaEntries: string[] = [];\n const paramEntries: string[] = [];\n const schemaEntries: string[] = [];\n const apiEntries: string[] = [];\n\n // Namespace imports: a route.ts exports one function per method, and which\n // ones it exports is the thing the dispatcher needs.\n for (const [index, route] of [...apiRoutes.values()].entries()) {\n imports.push(\n `import * as __api${index} from ${JSON.stringify(route.absPath)}`,\n );\n apiEntries.push(` ${JSON.stringify(route.name)}: __api${index},`);\n }\n\n for (const c of components.values()) {\n imports.push(`import ${c.alias} from ${JSON.stringify(c.absPath)}`);\n mapEntries.push(` ${JSON.stringify(c.name)}: ${c.alias},`);\n\n const meta = metadataExports(c.absPath);\n\n if (meta.static || meta.generate || meta.viewport || meta.writes.charset || meta.writes.viewport) {\n if (meta.static || meta.generate || meta.viewport) {\n imports.push(\n `import * as ${c.alias}_meta from ${JSON.stringify(c.absPath)}`,\n );\n }\n\n const fields = [\n meta.static ? `static: ${c.alias}_meta.metadata` : null,\n meta.generate ? `generate: ${c.alias}_meta.generateMetadata` : null,\n meta.viewport ? `viewport: ${c.alias}_meta.viewport` : null,\n meta.writes.charset || meta.writes.viewport ? `writes: ${JSON.stringify(meta.writes)}` : null,\n ].filter(Boolean);\n\n metaEntries.push(\n ` ${JSON.stringify(c.name)}: { ${fields.join(\", \")} },`,\n );\n }\n\n if (hasStaticParams(c.absPath)) {\n // The namespace import may already be in place for metadata; a second\n // one of the same module is the same binding, so this is safe to repeat.\n imports.push(\n `import * as ${c.alias}_params from ${JSON.stringify(c.absPath)}`,\n );\n paramEntries.push(\n ` ${JSON.stringify(c.name)}: ${c.alias}_params.generateStaticParams,`,\n );\n }\n\n const urlSchemas = urlSchemaExports(c.absPath);\n\n if (urlSchemas.params || urlSchemas.searchParams) {\n imports.push(\n `import * as ${c.alias}_schema from ${JSON.stringify(c.absPath)}`,\n );\n\n const fields = [\n urlSchemas.params ? `params: ${c.alias}_schema.params` : null,\n urlSchemas.searchParams\n ? `searchParams: ${c.alias}_schema.searchParams`\n : null,\n ].filter(Boolean);\n\n schemaEntries.push(\n ` ${JSON.stringify(c.name)}: { ${fields.join(\", \")} },`,\n );\n }\n }\n\n // The engine's own modules are named without an extension: this plugin runs\n // from src/ in its own repo and from dist/ once published, and Vite resolves\n // either. Naming .tsx here builds fine from source and fails after publish.\n return `// GENERATED by rscKit() — do not edit.\n${\n // First, before any page: an import's side effects run in import order,\n // and a package configured here has to be configured before a page module\n // that reads it at evaluation time.\n instrumentation?.hasRegister\n ? `import * as __instrumentation from ${JSON.stringify(instrumentation.file)}`\n : instrumentation\n ? `import ${JSON.stringify(instrumentation.file)}\\nconst __instrumentation: { register?: () => unknown } = {}`\n : \"const __instrumentation: { register?: () => unknown } = {}\"\n}\nimport { SegmentBoundary } from ${JSON.stringify(join(packageDir, \"js/SegmentBoundary\"))}\nimport { LoadingBoundary } from ${JSON.stringify(join(packageDir, \"js/LoadingBoundary\"))}\nimport { DocumentTitle } from ${JSON.stringify(join(packageDir, \"js/DocumentTitle\"))}\nimport { SlotBoundary } from ${JSON.stringify(join(packageDir, \"js/SlotBoundary\"))}\nimport { RouteErrorBoundary } from ${JSON.stringify(join(packageDir, \"js/RouteErrorBoundary\"))}\nimport __rsc_assets from 'virtual:vite-rsc/assets-manifest'\nimport { sectionComponent } from ${JSON.stringify(join(packageDir, \"js/section\"))}\nimport { PathnameProvider } from ${JSON.stringify(join(packageDir, \"js/PathnameProvider\"))}\nimport { DefaultRouteError } from ${JSON.stringify(join(packageDir, \"js/DefaultRouteError\"))}\nimport { searchParams as requestSearchParams } from ${JSON.stringify(join(packageDir, \"request\"))}\nimport { parseParams, parseSearchParams, parseBody, isSearchParamsError, isBodyError } from ${JSON.stringify(join(packageDir, \"routeSchema\"))}\nimport { notFoundDigest, isNotFoundSignal } from ${JSON.stringify(join(packageDir, \"notFound\"))}\nimport { noteRequestRead, urlOf } from ${JSON.stringify(join(packageDir, \"request\"))}\nimport { redirectDigest } from ${JSON.stringify(join(packageDir, \"redirectDigest\"))}\nimport { createRscHandler } from ${JSON.stringify(join(packageDir, \"host\"))}\nimport { httpHostCalls } from ${JSON.stringify(join(packageDir, \"hostCalls\"))}\nimport { prerenderedBeside } from ${JSON.stringify(join(packageDir, \"files\"))}\nimport { renderToReadableStream, decodeReply, decodeAction, decodeFormState, loadServerAction } from '@vitejs/plugin-rsc/rsc'\nimport { isQuery, queryCacheControl, isQueryValidationError } from ${JSON.stringify(join(packageDir, \"query\"))}\nimport { isActionValidationError, isClientBuilt } from ${JSON.stringify(join(packageDir, \"action\"))}\nimport { noteFallback as noteCaughtRead } from ${JSON.stringify(join(packageDir, \"request\"))}\nimport { isOutdatedOptimizedDep, outdatedDepResponse } from ${JSON.stringify(join(packageDir, \"devReload\"))}\nimport { sharedDepth } from ${JSON.stringify(join(packageDir, \"routing\"))}\nimport { Suspense, createElement, Fragment } from 'react'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n${imports.join(\"\\n\")}\n\ntype HostFn = (name: string, ...args: unknown[]) => Promise<unknown>\ntype LayoutEntry = { component: string; props?: Record<string, unknown> }\ntype SlotOverride = { component: string; props?: Record<string, unknown> }\n\nconst components: Record<string, any> = {\n${mapEntries.join(\"\\n\")}\n}\n\n/**\n * The url schemas a page exported, by component name.\n *\n * Empty for a page that exported none, which is the common case — the lookup\n * below then hands the url through untouched and costs a property read.\n */\n/**\n * The manifest to link from every page, or null when the app declared none.\n *\n * A literal rather than a define: defines are configured per environment and\n * this is read while rendering, in the rsc one. Generated in, so an app with\n * no manifest carries the word null and no branch worth taking.\n */\n/** Head tags for the icons and share images found in app/. */\nconst APP_HEAD: { tag: any; props: Record<string, string> }[] = ${JSON.stringify(\n headTags(foundAssets),\n )}\n\nconst WEB_MANIFEST: { href: string; themeColor?: string } | null = ${JSON.stringify(\n webManifestOptions\n ? {\n href: MANIFEST_PATH,\n ...(webManifestOptions.themeColor\n ? { themeColor: webManifestOptions.themeColor }\n : {}),\n }\n : null,\n )}\n\nconst urlSchemas: Record<string, { params?: any; searchParams?: any }> = {\n${schemaEntries.join(\"\\n\")}\n}\n\n/** route.ts modules, by the name the manifest matched. */\nconst apiRoutes: Record<string, any> = {\n${apiEntries.join(\"\\n\")}\n}\n\n/**\n * Answer an api route.\n *\n * The handler is handed an ordinary Request and the route params, and whatever\n * Response it returns is the answer. Nothing renders; there is no payload and\n * no client involved.\n *\n * HEAD falls back to GET, which is what the spec says it is — the same response\n * without a body. Answering 405 instead breaks link checkers and anything that\n * probes before it fetches.\n */\n/**\n * A promise that does not start until something awaits it.\n *\n * A thenable rather than a promise for the reason pageSearchParams is one:\n * every handler is handed all three of these whether it reads them or not, and\n * a real promise would run the work - and record the read - for every route on\n * every request.\n */\nfunction lazily<T>(start: () => Promise<T>): Promise<T> {\n let pending: Promise<T> | null = null\n\n const begin = (): Promise<T> => {\n if (!pending) {\n pending = start()\n pending.catch(() => {})\n }\n\n return pending\n }\n\n return {\n then: (ok, fail) => begin().then(ok, fail),\n catch: (fail) => begin().catch(fail),\n finally: (done) => begin().finally(done),\n } as Promise<T>\n}\n\n/** Whether a method may carry a body worth reading. */\nfunction hasBody(method: string): boolean {\n return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE'\n}\n\n/**\n * What an api route answers when its own schema refused the request.\n *\n * Three statuses, because the three failures are three different things and\n * collapsing them would leave a client unable to tell a url that names nothing\n * from one it addressed wrongly:\n *\n * 404 the params do not describe a resource - the url names nothing\n * 400 the query string is wrong - the resource exists, the request did not\n * 422 the body is wrong - the same status an action returns for the same\n * failure, so a client has one shape to handle\n */\nfunction refusedInput(error: unknown): Response {\n const json = (status: number, payload: unknown) =>\n new Response(JSON.stringify(payload), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n\n if (isNotFoundSignal(error)) return json(404, { message: 'Not found' })\n\n if (isSearchParamsError(error)) {\n return json(400, { message: error.message, errors: error.errors })\n }\n\n if (isBodyError(error)) return json(422, { message: error.message, errors: error.errors })\n\n throw error\n}\n\nexport async function handleApiRoute(\n name: string,\n request: Request,\n params: Record<string, string>,\n allow: string,\n): Promise<Response> {\n await instrumented()\n applyHost()\n\n const mod = apiRoutes[name]\n const method = request.method\n const handler = mod?.[method] ?? (method === 'HEAD' ? mod?.GET : undefined)\n\n if (!handler) {\n // Allow is not optional on a 405: without it a client cannot tell which\n // methods would have worked, and neither can a person reading the logs.\n return new Response('Method not allowed', { status: 405, headers: { Allow: allow } })\n }\n\n // Awaited by the handler, not before it - the same shape a page's props have,\n // and for more than symmetry. A route that never awaits its query string\n // provably does not vary by it, so the build can store one answer and the\n // host can serve it for any query at all. Resolved eagerly here, that fact\n // is unknowable and every ?utm_source= misses the stored answer.\n //\n // Schemas stay optional per route and per kind. A route that exported none\n // gets the raw params, the URLSearchParams, and a body nobody has read.\n const input = {\n params: lazily(() => parseParams(mod.params, params)),\n searchParams: lazily(() => {\n // Declaring a schema is itself a statement that the query matters, so a\n // route with one is treated as varying by it whether or not the handler\n // reaches for the value.\n noteRequestRead('searchParams')\n\n // Through urlOf, so the build's probe books this read to searchParams\n // rather than to the url - a route reads request.url itself when it\n // wants the query the Next way, and that read is the one that matters.\n return parseSearchParams(mod.searchParams, new URL(urlOf(request)).searchParams)\n }),\n body: hasBody(method) ? lazily(() => parseBody(mod.body, request)) : undefined,\n }\n\n if (mod.searchParams) noteRequestRead('searchParams')\n\n let answer\n try {\n answer = await handler(request, input)\n } catch (error) {\n // A refusal raised by one of the thenables above surfaces here, because the\n // handler awaited it and did not catch it. Anything else is the route's own\n // failure and is left to the caller.\n return refusedInput(error)\n }\n\n // A HEAD answered by GET must not carry a body.\n if (method === 'HEAD' && answer instanceof Response) {\n return new Response(null, { status: answer.status, headers: answer.headers })\n }\n\n return answer\n}\n\nconst metadataMap: Record<string, { static?: any; generate?: (p: any) => any; viewport?: any; writes?: { charset: boolean; viewport: boolean } }> = {\n${metaEntries.join(\"\\n\")}\n}\n\n/**\n * The viewport, in Next's shape: export const viewport on a layout or page,\n * layouts outer to inner then the page, merged per key. What is not set is\n * Next's default - width=device-width, initial-scale=1 - because a layout\n * ported from Next never wrote the tag: Next put it there, and a page with\n * no viewport meta is the desktop layout on a phone, which is how a port\n * found out.\n */\nfunction resolveViewport(component: string, layouts: LayoutEntry[]): Record<string, unknown> {\n const merged: Record<string, unknown> = { width: 'device-width', initialScale: 1 }\n\n for (const l of layouts) Object.assign(merged, metadataMap[l.component]?.viewport ?? {})\n Object.assign(merged, metadataMap[component]?.viewport ?? {})\n\n return merged\n}\n\n/** The content attribute for a viewport object, spelled the way browsers read it. */\nfunction viewportContent(viewport: Record<string, unknown>): string {\n const names: Record<string, string> = {\n width: 'width',\n height: 'height',\n initialScale: 'initial-scale',\n minimumScale: 'minimum-scale',\n maximumScale: 'maximum-scale',\n userScalable: 'user-scalable',\n viewportFit: 'viewport-fit',\n interactiveWidget: 'interactive-widget',\n }\n const parts: string[] = []\n\n for (const [key, name] of Object.entries(names)) {\n const value = viewport[key]\n\n if (value === undefined || value === null) continue\n\n parts.push(name + '=' + (typeof value === 'boolean' ? (value ? 'yes' : 'no') : String(value)))\n }\n\n return parts.join(', ')\n}\n\n/** Whether any file on the route renders the tag itself. */\nfunction routeWrites(component: string, layouts: LayoutEntry[], tag: 'charset' | 'viewport'): boolean {\n return [...layouts.map((l) => l.component), component].some((name) => metadataMap[name]?.writes?.[tag] === true)\n}\n\nconst staticParamsMap: Record<string, () => any> = {\n${paramEntries.join(\"\\n\")}\n}\n\n/**\n * The route table this bundle was built from.\n *\n * Embedded rather than read back from routes.json, so a host cannot pair a\n * fresh bundle with a stale manifest — the two came out of the same build and\n * now cannot be separated. The file is still written, because a host that\n * cannot import a JavaScript module has no other way to read it.\n */\nexport function manifest(): any {\n return ${JSON.stringify(routeManifest())}\n}\n\n/**\n * The stylesheet and the client entry every document of this build links,\n * from the build's own manifest, for the host's Link header - a CDN sends\n * it ahead as 103 Early Hints. The root layout's stylesheet is the one the\n * document carries; the entry's own is usually empty, and either way both\n * are named. See earlyHints.ts.\n */\nexport function criticalAssets(): { styles: string[]; modules: string[]; fonts: string[] } {\n // Nothing to send ahead in development: the entry is Vite's own url, and\n // there is no CDN in front to hint.\n if (import.meta.env.DEV) return { styles: [], modules: [], fonts: [] }\n\n const manifest = __rsc_assets as {\n clientEntryUrl?: string\n clientEntryDeps?: { css?: string[] }\n serverResources?: Record<string, { css?: string[] }>\n }\n const styles = new Set<string>(manifest.clientEntryDeps?.css ?? [])\n\n const rootLayouts = ['app/layout.tsx', 'app/layout.jsx', 'app/layout.ts', 'app/layout.js']\n\n for (const [file, resources] of Object.entries(manifest.serverResources ?? {})) {\n if (rootLayouts.some((name) => file === name || file.endsWith('/' + name))) {\n for (const href of resources.css ?? []) styles.add(href)\n }\n }\n\n return {\n styles: [...styles],\n modules: manifest.clientEntryUrl ? [manifest.clientEntryUrl] : [],\n fonts: [],\n }\n}\n\nlet cachedBuildId: string | null = null\n\n/**\n * What this build's client is, as a short id.\n *\n * Derived from the bootstrap script the document ships and the assets\n * manifest behind it - the entry, every client reference and the chunks\n * each loads - so two builds whose browsers would disagree never share one.\n * The host puts it on every answer and compares it against what a client\n * says it is running; a mismatch on a payload request is a 409, and the\n * client loads the document instead. Read once, on demand, because the\n * bootstrap content is a build product this bundle only reaches at runtime.\n */\nexport async function buildId(): Promise<string> {\n if (cachedBuildId !== null) return cachedBuildId\n\n // The bootstrap script names the entry; the assets manifest names every\n // client reference and the chunks each loads. A client component added\n // to a layout changes the manifest and not always the entry - the\n // reference map is its own chunk - and that is exactly the change an old\n // client cannot survive, so the id covers both.\n const content: string =\n (await (import.meta as any).viteRsc.loadBootstrapScriptContent('index')) + JSON.stringify(__rsc_assets)\n let hash = 2166136261\n\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i)\n hash = Math.imul(hash, 16777619) >>> 0\n }\n\n cachedBuildId = hash.toString(16).padStart(8, '0')\n\n return cachedBuildId\n}\n\n/**\n * For each server action id, whether a client built it. The build asks after\n * the bundle exists, because the answer is a mark on the loaded function and\n * nothing static could tell a wrapped export from a bare one.\n */\nexport async function auditActions(ids: string[]): Promise<{ id: string; client: boolean; query: boolean }[]> {\n const out: { id: string; client: boolean; query: boolean }[] = []\n\n for (const id of ids) {\n let fn: unknown = null\n\n try {\n fn = await loadServerAction(id)\n } catch {\n continue\n }\n\n if (typeof fn !== 'function') continue\n\n out.push({ id, client: isClientBuilt(fn), query: isQuery(fn) })\n }\n\n return out\n}\n\n/**\n * The param sets a route declares, or null when it declares none.\n *\n * Null and [] are different answers: no generateStaticParams means the route\n * is rendered on demand, an empty array means the app looked and there is\n * nothing to build. Collapsing them silently prerenders nothing for a route\n * that asked for everything, or the reverse.\n */\nexport async function getStaticParams(component: string): Promise<Record<string, string>[] | null> {\n await instrumented()\n\n const generate = staticParamsMap[component]\n\n if (!generate) return null\n\n return (await generate()) as Record<string, string>[]\n}\n\n// The host installs its callable via installHostFn. The global must be set\n// synchronously INSIDE each render fn (applyHost) right before\n// renderToReadableStream — setting it once ahead of a separate render call does\n// not reach the Flight render.\nconst HOST_GLOBAL = ${JSON.stringify(hostGlobal)}\n\n/**\n * The reserved name a host answers route middleware on.\n *\n * Prefixed so it cannot collide with a function an application registered.\n * A host that has never heard of it answers \"no such function\", which\n * throws — the correct answer for a guarded route on a host that cannot\n * check the guard.\n */\nconst HOST_MIDDLEWARE_FN = '__rsc.middleware'\n\n/**\n * instrumentation.ts's register(), once.\n *\n * On a long-lived server it runs at startup: the entry is evaluated when the\n * process starts, and this begins then, so env that fails validation fails\n * the boot rather than the first visitor, and the first request does not\n * pay for it. On a Worker there is no startup — an isolate is created for a\n * request, and a binding is only readable once one has arrived — so it runs\n * at the first request of each isolate instead. Every entry point awaits it\n * either way, which is what makes \"before the first render\" hold whether the\n * caller is the built server, the dev server or the prerender.\n *\n * A rejection is not memoised. Env that fails validation fails the same way\n * on every request, which is right; a database that was not up yet gets\n * asked again rather than leaving the process permanently refusing. In\n * production a startup failure is reported and the process exits, because a\n * server that could not bootstrap has nothing correct to serve; the dev\n * server stays up and reports it on the page instead.\n */\nlet __instrumented: Promise<void> | null = null\n\nfunction instrumented(): Promise<void> {\n if (!__instrumented) {\n __instrumented = Promise.resolve()\n .then(() => __instrumentation.register?.())\n .then(\n () => undefined,\n (error) => {\n __instrumented = null\n throw error\n },\n )\n }\n\n return __instrumented\n}\n\n// Workers name themselves; nothing else does. Where there is a process to\n// start, start now.\nconst isolateRuntime = typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers'\n\nif (__instrumentation.register && !isolateRuntime) {\n instrumented().catch((error) => {\n console.error('[rsc-kit] instrumentation.ts register() failed:', error)\n\n if (!import.meta.env.DEV && typeof process !== 'undefined' && typeof process.exit === 'function') {\n process.exit(1)\n }\n })\n}\n\nlet currentHost: HostFn | null = null\n\nexport function installHostFn(fn: HostFn) {\n currentHost = fn\n return () => {\n if (currentHost === fn) currentHost = null\n }\n}\n\n/**\n * The probe's stand-in host, for whichever render is asking.\n *\n * Held in async context rather than on the global, because two prerenders\n * running at once each need their own. The previous shape saved the real host,\n * overwrote the global and restored it afterwards — correct for one render at\n * a time and silently wrong for two: the second overwrites the first's saved\n * value, and both pages then call whichever closure assigned last, so\n * usedDynamicApis is recorded against the wrong page and routes are\n * misclassified. Benign for a host that installs none; wrong for any host\n * that does.\n */\nconst probeHost = new AsyncLocalStorage<(...args: unknown[]) => Promise<unknown>>()\n\nfunction applyHost() {\n // A dispatcher, installed once. App code calls a global; which implementation\n // that reaches is a question about the render it is inside.\n //\n ;(globalThis as Record<string, unknown>)[HOST_GLOBAL] = (...args: unknown[]) => {\n const fn = probeHost.getStore() ?? currentHost\n\n // An optional call was here, and it answered every rpc() with undefined\n // when no host was installed. undefined is a value: the component renders\n // with it, the render succeeds, and a prerender freezes the result. The\n // page then hydrates against an undefined prop, the client component reads\n // a property of it, React unmounts the document, and the browser shows a\n // blank page with nothing in the console.\n //\n // No backticks in this region — everything from the generated entry\n // onward is a template literal, and one ends it here.\n // Rejected rather than thrown: rpc() is documented to return a promise, so\n // a caller that stores it before awaiting must get a rejection, not an\n // exception from the call itself.\n if (!fn) {\n return Promise.reject(\n new Error(\n 'No host callable is installed, so ' + String(args[0]) + ' cannot be answered. ' +\n 'A render that needs the host must either run with one installed or be probed.',\n ),\n )\n }\n\n return fn(...args)\n }\n}\n\n/**\n * Which layout renders a given slot.\n *\n * The slot component's own path names the directory that declares it:\n * app/docs/@modal/default is declared in app/docs, and the layout there is the\n * one whose props it belongs in. Falls back to the innermost layout when\n * nothing matches, which is the shape a single-layout app has anyway.\n */\nfunction ownerLayoutIndex(slotComponent: string, layouts: LayoutEntry[]): number {\n const at = slotComponent.indexOf('/@')\n if (at === -1) return layouts.length - 1\n\n const ownerDir = slotComponent.slice(0, at)\n const suffix = '/layout'\n const found = layouts.findIndex(\n (l) => (l.component.endsWith(suffix) ? l.component.slice(0, -suffix.length) : l.component) === ownerDir,\n )\n\n return found === -1 ? layouts.length - 1 : found\n}\n\n/**\n * The query string, prepared for a page that may never ask for it.\n *\n * Created for every render but awaited by almost none, so its rejection has to\n * be claimed here: an unhandled one fails the render of a page that did\n * nothing wrong. Awaiting it still surfaces the real error.\n */\nfunction pageSearchParams(): Promise<URLSearchParams> {\n // Lazy. Every page is handed this whether it reads it or not, and reading the\n // request is what marks a page as needing one — so starting it eagerly told\n // the build that every page was dynamic, and put url() beside every route in\n // the output as though someone had written it.\n //\n // A thenable rather than a promise, so nothing happens until a page awaits.\n let pending: Promise<URLSearchParams> | null = null\n\n const start = (): Promise<URLSearchParams> => {\n if (!pending) {\n pending = requestSearchParams()\n\n // Attached here for the same reason it always was: during a prerender\n // this never settles, and an unobserved rejection ends the process.\n pending.catch(() => {})\n }\n\n return pending\n }\n\n return {\n then: (ok, fail) => start().then(ok, fail),\n catch: (fail) => start().catch(fail),\n finally: (done) => start().finally(done),\n } as Promise<URLSearchParams>\n}\n\n/**\n * A page's params, through its own schema if it exported one.\n *\n * Laziness is preserved on purpose. The params promise may be one that never\n * settles - that is how the prerender probe says \"not for any particular url\"\n * - so this must not await eagerly. Chaining keeps a never-settling promise\n * never-settling, and the schema runs only if the page reads it.\n */\nfunction checkedParams(\n schemas: { params?: any } | undefined,\n params: Promise<Record<string, unknown>>,\n): Promise<unknown> {\n if (!schemas || !schemas.params) return params\n\n return params.then((value) => parseParams(schemas.params, value))\n}\n\n/**\n * A page's query string, through its own schema if it exported one.\n *\n * Wrapped as a thenable rather than chained, so a page that never reads the\n * query still never starts the read - the whole thing pageSearchParams exists\n * to guarantee. Calling .then on it here would start it for every page, and\n * every page would be reported as reading the request.\n */\nfunction checkedSearchParams(\n schemas: { searchParams?: any } | undefined,\n search: Promise<URLSearchParams>,\n): Promise<unknown> {\n if (!schemas || !schemas.searchParams) return search\n\n let pending: Promise<unknown> | null = null\n\n const start = (): Promise<unknown> => {\n if (!pending) {\n pending = search.then((value) => parseSearchParams(schemas.searchParams, value))\n pending.catch(() => {})\n }\n\n return pending\n }\n\n return {\n then: (ok, fail) => start().then(ok, fail),\n catch: (fail) => start().catch(fail),\n finally: (done) => start().finally(done),\n } as Promise<unknown>\n}\n\nlet errorChains: Record<string, string[]> | null = null\n\n/** The error.tsx files above a component, outermost first. */\nfunction errorChain(component: string): string[] {\n if (!errorChains) {\n errorChains = {}\n\n for (const route of manifest().routes as { component: string; errors?: string[] }[]) {\n if (route.errors?.length) errorChains[route.component] = route.errors\n }\n }\n\n return errorChains[component] ?? []\n}\n\n// Composition: layout(outer..inner) > Suspense(loading, innermost-first) > page.\nfunction buildElement(\n component: string,\n props: Record<string, unknown>,\n layouts: LayoutEntry[],\n loadings: string[],\n parallelSlots: Record<string, string>,\n slotOverrides: Record<string, SlotOverride>,\n head: unknown[] = [],\n from = 0,\n pageKey = '',\n bootstrap = true,\n // What await params gives the page. A never-settling one is how the\n // prerender probe says \"not for any particular url\": the page suspends where\n // it reads, everything above it still paints, and that is a shell one file\n // can serve for every url the route matches.\n params: Promise<Record<string, unknown>> = Promise.resolve(props),\n) {\n const Component = components[component]\n if (!Component) throw new Error('Unknown RSC component: ' + component)\n\n // Awaitable rather than spread. Spread, a page reads its slug synchronously\n // and renders to completion during the probe — producing a page about an\n // invented value, right for nothing — which is why such a route could only\n // ever be rendered per request.\n const schemas = urlSchemas[component]\n\n let element = createElement(Component, {\n params: checkedParams(schemas, params),\n searchParams: checkedSearchParams(schemas, pageSearchParams()),\n })\n\n // Through LoadingBoundary when the runtime is shipped, so a server render\n // can tell the engine's boundary from one the developer wrote by name -\n // see that file. A page shipping no runtime gets a plain Suspense: a\n // client component would drag React in for a wrapper nothing can use.\n for (let i = loadings.length - 1; i >= 0; i--) {\n const Loading = components[loadings[i]]\n const fallback = Loading ? createElement(Loading) : null\n\n element = bootstrap\n ? createElement(LoadingBoundary, { fallback }, element)\n : createElement(Suspense, { fallback }, element)\n }\n\n // Outside the Suspense boundary, innermost first — the nearest error.tsx to\n // the failure answers, the same rule loading.tsx follows. Outside, so a\n // component that throws while its fallback is showing is still caught.\n //\n // Read from the route table rather than passed in, for the same reason the\n // middleware chain is: every render path is covered by construction, and no\n // caller has to remember to forward them.\n const errors = errorChain(component)\n\n for (let i = errors.length - 1; i >= 0; i--) {\n const Fallback = components[errors[i]]\n\n if (!Fallback) continue\n\n element = createElement(\n RouteErrorBoundary,\n { fallback: Fallback as never, resetKey: pageKey || component },\n element,\n )\n }\n\n // Outermost, for a throw no error.tsx covers - including one in a layout,\n // which the boundary inside that layout cannot see. Without it React\n // unmounted the document on hydration: a black page with the cause nowhere\n // near it. Only with the runtime: it is a client component, and a route\n // shipping none has nothing to catch with.\n if (bootstrap) {\n element = createElement(\n RouteErrorBoundary,\n { fallback: DefaultRouteError as never, resetKey: pageKey || component },\n element,\n )\n }\n\n // <title>/<meta> go OUTSIDE the Suspense boundaries so they reach the shell\n // immediately — inside, they would be withheld until the page's data\n // resolves, delaying the whole document on a slow page.\n if (head.length) element = createElement(Fragment, null, ...head, element)\n\n // A slot belongs to the layout in the directory that declares it, which is\n // not necessarily the innermost one: slots are collected by walking up from\n // the page to the app root. Handing every slot to the innermost layout drops\n // any the innermost does not declare, silently — the page renders, the modal\n // just never appears.\n const slotsByLayout = new Map<number, Record<string, unknown>>()\n\n for (const [slot, value] of Object.entries(parallelSlots)) {\n const override = slotOverrides[slot]\n let rendered: unknown = null\n\n // Slot components are pages too — an interceptor is a page in a slot — so\n // they get the same awaitables the page does rather than spread values.\n if (override) {\n const OverrideComp = components[override.component]\n rendered = OverrideComp\n ? createElement(OverrideComp, {\n params: Promise.resolve(override.props ?? {}),\n searchParams: pageSearchParams(),\n })\n : null\n } else {\n const SlotComp = components[value]\n rendered = SlotComp\n ? createElement(SlotComp, { params, searchParams: pageSearchParams() })\n : null\n }\n\n const owner = ownerLayoutIndex(value, layouts)\n if (owner < from) continue\n\n const bucket = slotsByLayout.get(owner) ?? {}\n // Wrapped so an action can put a re-rendered slot here without the page\n // around it being asked for again. With nothing stored the boundary\n // renders exactly what is passed, so this changes nothing on its own.\n bucket[slot] = bootstrap ? createElement(SlotBoundary, { name: slot }, rendered) : rendered\n slotsByLayout.set(owner, bucket)\n }\n\n // Indices stay absolute: from skips the layouts the client already has\n // mounted, so slot ownership and boundary depth mean the same thing whether\n // this is a whole document or one segment of it.\n for (let i = layouts.length - 1; i >= from; i--) {\n const Layout = components[layouts[i].component]\n if (!Layout) continue\n\n // The seam a navigation can replace on its own. Depth counts from the\n // outermost layout, so depth 1 is everything below the root layout and the\n // deepest boundary wraps the page alone. With nothing in the client store\n // these render their children unchanged.\n //\n // It is a client component, so a route shipping no runtime must not get\n // one — otherwise every page would drag React in for a seam nothing can\n // use, and no page could ever be JS-free.\n if (bootstrap) {\n element = createElement(SegmentBoundary, { depth: i + 1, pageKey }, element)\n }\n\n element = createElement(Layout, {\n ...(layouts[i].props ?? {}),\n ...(slotsByLayout.get(i) ?? {}),\n children: element,\n })\n }\n\n // The url the client hooks answer with during a server render. Outside the\n // boundaries, so a page keeps it across a partial navigation; omitted with\n // the runtime, since a route shipping none has nothing to read it.\n if (bootstrap && pageKey) {\n element = createElement(PathnameProvider, { value: pageKey }, element)\n }\n\n return element\n}\n\n// Resolve route metadata into React elements. React 19 hoists <title>/<meta>\n// rendered anywhere in the tree into <head> — so the \"vite way\" for metadata is\n// to render it as elements, rather than a backend injecting a <head> string.\nasync function renderTree(\n component: string,\n props: Record<string, unknown>,\n layouts: LayoutEntry[],\n loadings: string[],\n parallelSlots: Record<string, string>,\n slotOverrides: Record<string, SlotOverride>,\n from = 0,\n pageKey = '',\n bootstrap = true,\n params?: Promise<Record<string, unknown>>,\n) {\n // The FULL chain, always: a title template lives on an outer layout, and a\n // partial render still has to produce the same <title> the whole document\n // would have.\n const md = await resolveMetadata(component, props, layouts)\n const head: unknown[] = []\n\n // Rendered into the tree rather than written into the app's layout: React\n // hoists a link and a meta into <head> from anywhere, so this works for an\n // app that already has a layout and never asks anyone to edit one. The\n // engine knows the manifest exists; the app should not have to.\n // Icons and share images the build found in app/. Rendered here so React\n // hoists them into <head>, the same way the manifest link is — an app never\n // edits its layout to get a favicon.\n // Where the site lives, for making a relative image or url absolute. Read\n // here, above the found images, because those are the ones most likely to\n // be relative: an opengraph-image.png in app/ is emitted as /_app/..., and a\n // share-card scraper needs the origin in front of it.\n const base = md?.metadataBase ? String(md.metadataBase) : null\n const absolute = (value: unknown): string => {\n const text = String(value instanceof URL ? value.href : value)\n\n if (!base || /^[a-z][a-z0-9+.-]*:/i.test(text)) return text\n\n return new URL(text, base).href\n }\n\n // What Next wrote into every document without being asked, and a layout\n // copied from a Next app therefore never writes: the charset, and the\n // viewport - without which a phone lays the page out at desktop width.\n // Rendered unless a file on the route renders the tag itself.\n if (!routeWrites(component, layouts, 'charset')) head.push(createElement('meta', { key: '__cs', charSet: 'utf-8' }))\n\n const viewport = resolveViewport(component, layouts)\n\n if (!routeWrites(component, layouts, 'viewport')) {\n head.push(createElement('meta', { key: '__vp', name: 'viewport', content: viewportContent(viewport) }))\n }\n\n // themeColor and colorScheme live on the viewport export in Next, and one\n // set there wins over the web manifest's colour below.\n const themeColors = viewport.themeColor as string | { media?: string; color: string }[] | undefined\n\n if (typeof themeColors === 'string') {\n head.push(createElement('meta', { key: '__vtc', name: 'theme-color', content: themeColors }))\n } else if (Array.isArray(themeColors)) {\n for (const [i, entry] of themeColors.entries()) {\n head.push(createElement('meta', { key: '__vtc' + i, name: 'theme-color', content: entry.color, ...(entry.media ? { media: entry.media } : {}) }))\n }\n }\n if (typeof viewport.colorScheme === 'string') {\n head.push(createElement('meta', { key: '__vcs', name: 'color-scheme', content: viewport.colorScheme }))\n }\n\n for (const [i, found] of APP_HEAD.entries()) {\n const props = { ...found.props }\n\n if (props.content && /^(og:image|twitter:image)$/.test(props.property ?? props.name ?? '')) {\n props.content = absolute(props.content)\n }\n\n head.push(createElement(found.tag, { key: '__a' + i, ...props }))\n }\n\n if (WEB_MANIFEST) {\n head.push(createElement('link', { key: '__mf', rel: 'manifest', href: WEB_MANIFEST.href }))\n\n if (WEB_MANIFEST.themeColor && themeColors === undefined) {\n head.push(\n createElement('meta', { key: '__tc', name: 'theme-color', content: WEB_MANIFEST.themeColor }),\n )\n }\n }\n\n if (md) {\n if (md.title != null) {\n // The element is what a server render puts in <head>, and what a route\n // with no runtime relies on entirely.\n head.push(createElement('title', { key: '__t' }, String(md.title)))\n\n // And the effect is what keeps it right once pages are retained — see\n // DocumentTitle. Only where there is a runtime to run it: a client\n // component on a route that ships none is refused by the build.\n if (bootstrap) head.push(createElement(DocumentTitle, { key: '__ts', title: String(md.title) }))\n }\n if (md.description != null) head.push(createElement('meta', { key: '__d', name: 'description', content: String(md.description) }))\n // The name only, never the version - see the identify option.\n if (manifest().build?.identify) head.push(createElement('meta', { key: '__g', name: 'generator', content: 'rsc-kit' }))\n }\n\n // Which build this document is, for the client to say on every navigation\n // - read from the document rather than learned from the first answer,\n // because a document a service worker served from its cache is the last\n // build's while the answers are this one's. An id, not a version number.\n if (bootstrap) head.push(createElement('meta', { key: '__v', name: 'rsc-kit:build', content: await buildId() }))\n\n if (md) {\n\n // robots is a string, or the object Next takes: index and follow as\n // their no- forms, the flags by name, the limits as name:value. googleBot\n // is the same shape for the googlebot tag. The object used to fall\n // through to the catch-all below as \"[object Object]\" - which no crawler\n // reads, on the one page that asked not to be indexed.\n const robotsContent = (value: unknown): string => {\n if (typeof value !== 'object' || value === null) return String(value)\n\n const r = value as Record<string, unknown>\n const parts: string[] = []\n\n if (r.index != null) parts.push(r.index ? 'index' : 'noindex')\n if (r.follow != null) parts.push(r.follow ? 'follow' : 'nofollow')\n for (const flag of ['noarchive', 'nosnippet', 'noimageindex', 'nocache', 'notranslate', 'indexifembedded', 'nositelinkssearchbox']) {\n if (r[flag]) parts.push(flag)\n }\n if (r.unavailable_after != null) parts.push('unavailable_after: ' + String(r.unavailable_after))\n for (const limit of ['max-video-preview', 'max-image-preview', 'max-snippet']) {\n if (r[limit] != null) parts.push(limit + ':' + String(r[limit]))\n }\n\n return parts.join(', ')\n }\n\n if (md.robots != null) {\n head.push(createElement('meta', { key: '__r', name: 'robots', content: robotsContent(md.robots) }))\n\n const bot = typeof md.robots === 'object' ? (md.robots as { googleBot?: unknown }).googleBot : null\n\n if (bot != null) head.push(createElement('meta', { key: '__rg', name: 'googlebot', content: robotsContent(bot) }))\n }\n\n // og: and its relatives are PROPERTY, not name. Facebook's scraper - and\n // Slack's, and LinkedIn's - reads only property=, so every og tag this\n // used to emit with name= was invisible to the thing it existed for.\n // Twitter reads name=, which is why the two are not one rule.\n const isProperty = (k: string) => /^(og|article|profile|book|music|video|fb):/.test(k)\n // The keys whose CONTENT is a url. Exact, plus the :url and :secure_url\n // spellings - not og:image:width, which a looser match turned into\n // https://site/1200 and no scraper would ever read.\n const isUrlKey = (k: string) => /^(og:image|og:url|twitter:image)(:(secure_)?url)?$/.test(k)\n const tag = (k: string, v: unknown) =>\n createElement('meta', {\n key: '__m_' + k + '_' + String(v).slice(0, 40),\n [isProperty(k) ? 'property' : 'name']: k,\n content: isUrlKey(k) ? absolute(v) : String(v),\n })\n\n // One image, or several. Each becomes its own og:image plus the size and\n // alt tags beside it, which is how a scraper is told which is which.\n const images = (prefix: string, value: unknown): void => {\n const list = Array.isArray(value) ? value : [value]\n\n for (const item of list) {\n if (item == null) continue\n\n if (typeof item === 'object' && !(item instanceof URL)) {\n const image = item as { url: unknown; width?: number; height?: number; alt?: string; type?: string }\n\n head.push(tag(prefix, image.url))\n if (image.width) head.push(tag(prefix + ':width', image.width))\n if (image.height) head.push(tag(prefix + ':height', image.height))\n if (image.alt) head.push(tag(prefix + ':alt', image.alt))\n if (image.type) head.push(tag(prefix + ':type', image.type))\n } else {\n head.push(tag(prefix, item))\n }\n }\n }\n\n if (md.openGraph) {\n const og = md.openGraph as Record<string, unknown>\n\n if (og.title != null) head.push(tag('og:title', og.title))\n if (og.description != null) head.push(tag('og:description', og.description))\n if (og.url != null) head.push(tag('og:url', og.url))\n if (og.siteName != null) head.push(tag('og:site_name', og.siteName))\n if (og.type != null) head.push(tag('og:type', og.type))\n if (og.locale != null) head.push(tag('og:locale', og.locale))\n if (og.images != null) images('og:image', og.images)\n }\n\n if (md.twitter) {\n const tw = md.twitter as Record<string, unknown>\n\n if (tw.card != null) head.push(tag('twitter:card', tw.card))\n if (tw.title != null) head.push(tag('twitter:title', tw.title))\n if (tw.description != null) head.push(tag('twitter:description', tw.description))\n if (tw.site != null) head.push(tag('twitter:site', tw.site))\n if (tw.creator != null) head.push(tag('twitter:creator', tw.creator))\n if (tw.images != null) images('twitter:image', tw.images)\n }\n\n // icons is links, not meta. A string is one icon; an object names which\n // rel each is for. The ones found in app/ are already in APP_HEAD above,\n // so this is for an app that wants to say it explicitly.\n const links = (rel: string, value: unknown): void => {\n const list = Array.isArray(value) ? value : [value]\n\n for (const item of list) {\n if (item == null) continue\n\n const icon = typeof item === 'object' && !(item instanceof URL)\n ? (item as Record<string, unknown>)\n : { url: item }\n\n head.push(\n createElement('link', {\n key: '__i_' + rel + '_' + String(icon.url).slice(0, 40),\n rel: (icon.rel as string) ?? rel,\n href: absolute(icon.url),\n ...(icon.type ? { type: icon.type } : {}),\n ...(icon.sizes ? { sizes: icon.sizes } : {}),\n ...(icon.media ? { media: icon.media } : {}),\n }),\n )\n }\n }\n\n if (md.icons != null) {\n const icons = md.icons as Record<string, unknown> | string | unknown[]\n\n if (typeof icons === 'string' || Array.isArray(icons) || icons instanceof URL) {\n links('icon', icons)\n } else {\n if (icons.icon != null) links('icon', icons.icon)\n if (icons.apple != null) links('apple-touch-icon', icons.apple)\n if (icons.shortcut != null) links('shortcut icon', icons.shortcut)\n if (icons.other != null) links('icon', icons.other)\n }\n }\n\n // other is flattened in beside the named keys, because it is a place to put\n // meta tags rather than a meta tag by that name. A key at the top level\n // still renders - the type no longer invites one, but an app written\n // against the old shape must not silently lose its tags.\n const structured = new Set(['title', 'description', 'robots', 'metadataBase', 'openGraph', 'twitter', 'icons', 'other'])\n const named = Object.entries(md).filter(([k]) => !structured.has(k))\n const extra = Object.entries((md.other ?? {}) as Record<string, unknown>)\n\n for (const [k, v] of [...named, ...extra]) {\n if (v == null) continue\n\n if (Array.isArray(v)) {\n for (const item of v) head.push(tag(k, item))\n } else {\n head.push(tag(k, v))\n }\n }\n }\n\n // Metadata elements are rendered INSIDE the document tree so React 19 hoists\n // <title>/<meta> into <head> (hoisting only works from within the tree).\n return buildElement(component, props, layouts, loadings, parallelSlots, slotOverrides, head, from, pageKey, bootstrap, params)\n}\n\n/**\n * The shallowest layout this render must actually produce.\n *\n * An interceptor replaces a slot on the layout that declares it. If that layout\n * is one the client already has, a partial render would never reach it and the\n * modal would silently not appear — so the render is widened to include it.\n */\nfunction segmentStart(\n from: number,\n layouts: LayoutEntry[],\n parallelSlots: Record<string, string>,\n slotOverrides: Record<string, SlotOverride>,\n): number {\n let start = from\n\n for (const slot of Object.keys(slotOverrides)) {\n const declared = parallelSlots[slot]\n if (!declared) continue\n\n const owner = ownerLayoutIndex(declared, layouts)\n if (owner < start) start = owner\n }\n\n return start\n}\n\n/**\n * Run a route's middleware before anything at or below them is rendered.\n *\n * A guard is middleware.ts in a directory: a function that returns nothing and\n * refuses by redirecting or throwing. It exists because a check is not UI, and\n * making it one was the problem — a layout that checks who you are is also a\n * layout that fetches a nav bar, and the two have opposite needs.\n *\n * Layouts are skipped on a partial navigation, which is the whole point of\n * partial navigation, and the client decides how many to skip by naming what\n * it claims to hold. Nothing verifies that claim; nothing can. So a check that\n * lives in a layout is a check the caller can decline. Forcing the layout to\n * run instead makes every navigation pay for its data fetching to re-run a\n * check that costs one query.\n *\n * Guards are not part of that arithmetic. Every render path runs the whole\n * chain, in order, outermost first — a full load, a partial navigation, a\n * revalidation, an interception. There is no marker to forget: the file is the\n * declaration.\n */\nlet middlewareChains: Record<string, string[]> | null = null\n\nlet hostChains: Record<string, string[]> | null = null\n\n/**\n * Guards the host runs, named by a route.ts and meaningless here.\n *\n * Asked before the engine's own middleware.ts guards, because a host's are the\n * coarser check — a session, a rate limit — and running application code to\n * decide whether application code may run is the wrong way round.\n *\n * It fails CLOSED, and that is the whole of its design. This call reaches\n * another process over a network, so it can time out, be refused, or answer\n * something unparseable — and every one of those is a guarded page rendered to\n * whoever asked, if the absence of a refusal is read as permission. Only a\n * literal true allows.\n */\nasync function runHostMiddleware(component) {\n if (!hostChains) {\n hostChains = {}\n\n for (const route of manifest().routes) {\n if (route.hostMiddleware?.length) hostChains[route.component] = route.hostMiddleware\n }\n }\n\n const names = hostChains[component] ?? []\n\n if (names.length === 0) return\n\n if (!currentHost) {\n throw new Error(\n 'Route ' + component + ' declares host middleware (' + names.join(', ') +\n ') but no host callable is installed, so it cannot be checked.',\n )\n }\n\n const answer = await currentHost(HOST_MIDDLEWARE_FN, names)\n\n // Anything other than a literal true. A host answering null, undefined, a\n // string, or an object it happened to build on the way to an error is not\n // saying yes.\n if (answer !== true) {\n throw new Error('Host middleware refused ' + component + ' (' + names.join(', ') + ').')\n }\n}\n\n\nasync function runMiddleware(component: string, props: Record<string, unknown> = {}): Promise<void> {\n await runHostMiddleware(component)\n\n // Read from the route table rather than passed in, so every render path is\n // covered by construction and no host has to remember to forward them.\n if (!middlewareChains) {\n middlewareChains = {}\n\n for (const route of manifest().routes as { component: string; middleware?: string[] }[]) {\n if (route.middleware?.length) middlewareChains[route.component] = route.middleware\n }\n\n // Api routes too. They are keyed by the module name rather than a\n // component, but the chain above them is the same one the pages beside\n // them run.\n for (const api of (manifest().apis ?? []) as { name: string; middleware?: string[] }[]) {\n if (api.middleware?.length) middlewareChains[api.name] = api.middleware\n }\n }\n\n for (const name of middlewareChains[component] ?? []) {\n const guard = components[name]\n\n // A declared guard that is not in the bundle is not \"no guard\" — it is a\n // check that silently does not happen, which is the same reasoning the\n // host applies when the engine cannot run middleware at all. Currently\n // unreachable, because the chain and the component map come from one\n // discovery pass; it is one refactor away from being reachable, and this\n // is the place that has to fail closed.\n if (!guard) {\n throw new Error(\n 'Route middleware ' + name + ' is declared for ' + component + ' but is not in the bundle.',\n )\n }\n\n // Sequential and awaited, outermost first: an outer guard refusing means\n // the inner one should never have been asked. A directory may declare\n // several as a list - reused checks imported from one place - and they\n // run in the order written, stopping at the first refusal.\n for (const check of Array.isArray(guard) ? guard : [guard]) {\n if (typeof check !== 'function') {\n throw new Error(\n 'Route middleware ' + name + ' exports something that is not a function or a list of them.',\n )\n }\n\n await check(props)\n }\n }\n}\n\n// SPA-navigation Flight stream (worker: rsc-stream).\n/**\n * Run a route's middleware without rendering anything.\n *\n * For a host serving a page it did not render: a frozen page is read from disk\n * and never touches the engine, so the check has to be asked for. Refusing\n * throws, exactly as it does mid-render.\n */\nexport async function runRouteMiddleware(component: string, props: Record<string, unknown> = {}): Promise<void> {\n await instrumented()\n applyHost()\n\n return runMiddleware(component, props)\n}\n\nexport async function handleRscStream(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n from = 0,\n pageKey = '',\n): Promise<{ stream: ReadableStream; clientChunks: unknown; segmentDepth: number }> {\n await instrumented()\n applyHost()\n\n // The host proposes how much the client already has; the engine decides what\n // is actually safe to skip and reports back what it rendered.\n const start = segmentStart(from, layouts, parallelSlots, slotOverrides)\n\n // Before anything below them is rendered, never after.\n await runMiddleware(component, props)\n\n return {\n stream: renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, start, pageKey),\n { onError: flightOnError },\n ),\n clientChunks: {},\n segmentDepth: start,\n }\n}\n\n/**\n * The digest React sends to the client in place of a server error's message.\n *\n * A redirect thrown after the shell has flushed has no header left to travel\n * in — the status line is already sent. React transmits a digest for every\n * server error, in production as well as development, so the destination\n * rides there and the client's boundary performs it.\n *\n * redirectDigest is imported by the generated entry, at the top of this\n * template. An import added to this file instead compiles and bundles without\n * complaint, and then throws at render time against a name that is not there.\n *\n * Returning undefined leaves React's own behaviour alone for everything else.\n */\nfunction flightOnError(error: unknown): string | undefined {\n const digest = redirectDigest(error) ?? notFoundDigest(error)\n\n if (digest) return digest\n\n console.error('[rsc-kit]', error)\n\n return undefined\n}\n\n// Initial-load HTML stream + hydration payload (worker: rsc-html-stream).\nexport async function handleRscHtmlStream(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n nonce?: string,\n pageKey = '',\n bootstrap = true,\n): Promise<{ htmlStream: ReadableStream; rscPayloadPromise: Promise<string>; clientChunks: unknown }> {\n await instrumented()\n applyHost()\n await runMiddleware(component, props)\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, 0, pageKey, bootstrap),\n { onError: flightOnError },\n )\n const [forHtml, forPayload] = flight.tee()\n const rscPayloadPromise = new Response(forPayload).text()\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsr(forHtml, nonce, undefined, bootstrap)\n return { htmlStream, rscPayloadPromise, clientChunks: {} }\n}\n\n/**\n * A form posted to the page before the page had a runtime.\n *\n * React writes the action's id into the form it emits for a server action,\n * so a browser with no javascript yet - or none at all - posts the fields\n * to the page's own url. The action runs from those fields, exactly as it\n * would have been called, and the page renders afterwards with what it\n * returned as React's form state: a useActionState form shows its result,\n * a redirect() thrown by the action leaves through the scope the way a\n * page's would, and a cookie it set is on the answer.\n */\nexport async function handleRscFormPost(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n nonce?: string,\n pageKey = '',\n bootstrap = true,\n formData: FormData = new FormData(),\n): Promise<{ htmlStream: ReadableStream }> {\n await instrumented()\n applyHost()\n await runMiddleware(component, props)\n\n // The function the form named, bound to what it posted. Nothing named -\n // a plain form posted here by mistake - and the page simply renders.\n const action = await decodeAction(formData)\n let formState: unknown\n\n if (action) {\n const result = await action()\n\n formState = await decodeFormState(result, formData)\n }\n\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, 0, pageKey, bootstrap),\n { onError: flightOnError },\n )\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsr(flight, nonce, undefined, bootstrap, formState)\n\n return { htmlStream }\n}\n\n/**\n * Finish a shell that was frozen at build time.\n *\n * The render is an ordinary one — real host, real data, middleware included —\n * and the postponed state decides what of it actually reaches the wire. React\n * skips everything the shell already emitted and writes only the boundaries it\n * could not finish then.\n *\n * bootstrap is deliberately false. The shell shipped the bootstrap script; a\n * second one would boot the client runtime twice.\n */\nexport async function handleRscResume(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n slotOverrides: Record<string, SlotOverride> = {},\n postponed: unknown = null,\n nonce?: string,\n pageKey = '',\n): Promise<{ htmlStream: ReadableStream }> {\n await instrumented()\n applyHost()\n await runMiddleware(component, props)\n\n // The tree must be shaped exactly as it was when the shell was frozen, or\n // React cannot line the resumed segments up with the slots left for them:\n //\n // Couldn't find all resumable slots by key/index during replaying.\n // The tree doesn't match so React will fallback to client rendering.\n //\n // Hence \\`true\\` here rather than false. It reads like it would emit a second\n // bootstrap script, and it does not — resume() takes no bootstrap content at\n // all, so the shell's remains the only one. What this flag actually decides\n // is whether the tree carries its SegmentBoundary, and the shell's did.\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, slotOverrides, 0, pageKey, true),\n { onError: flightOnError },\n )\n\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsrResume(flight, postponed, nonce)\n\n return { htmlStream }\n}\n\n// Server action (worker: rsc-action).\n/** The page an action was invoked from, so what it invalidated can be rendered. */\ninterface PageContext {\n component: string\n props: Record<string, unknown>\n layouts: LayoutEntry[]\n loadings: string[]\n parallelSlots: Record<string, string>\n /**\n * The sections this route declares, which is what bounds a revalidate.\n *\n * Optional only because a host built against an older manifest may not send\n * it; absent, no named section can be revalidated at all. Refusing is the\n * safe reading — the alternative is the registry, which holds every section\n * in the app.\n */\n sections?: string[]\n}\n\n/**\n * Render one thing an action said it invalidated.\n *\n * 'all' the whole document, layouts included\n * 'page' everything below the layouts, which stay as they are\n * <slot> a single parallel slot, by the name its directory gave it\n *\n * A slot is the only unit smaller than a page the server can name, which is\n * why two tables have to be slots to be refreshed apart from each other.\n */\nasync function renderRevalidated(target: string, page: PageContext): Promise<unknown> {\n // Every target below 'all' renders without the layout chain above it, which\n // is the same skip a navigation performs and needs the same guard run.\n await runMiddleware(page.component, page.props)\n\n if (target === 'all' || target === 'page') {\n return renderTree(\n page.component,\n page.props,\n page.layouts,\n page.loadings,\n page.parallelSlots,\n {},\n target === 'all' ? 0 : page.layouts.length,\n '',\n )\n }\n\n // A named region first: it is the lighter of the two, and the one a page\n // reaches for when it only wants part of itself refreshed.\n //\n // Scoped to the sections this route declares. The registry is a module-level\n // map keyed by name, and the generated entry imports every component in the\n // app eagerly, so a name-keyed registry holds every section in the app by the\n // time a request arrives — and two pages may legitimately both call theirs\n // 'stats', where the last one loaded wins.\n //\n // So the target is resolved through the module this route declares, not\n // through a shared map: the manifest says which section files belong to this\n // page, the components map turns one into its module, and section() left the\n // unwrapped component on the export. Identity, rather than string matching.\n //\n // Read from the manifest rather than from the message. The host is not the\n // adversary here, but the route table is build-time truth and already in this\n // bundle, so there is no reason to depend on a field a host has to remember\n // to send — one that forgot would be silently unprotected.\n const owner = manifest().routes.find((route: any) => route.component === page.component)\n const declared: string[] = owner?.sections ?? page.sections ?? []\n\n // A target of orders names the file app/ledger/orders.section. Matched on\n // that stem, so a target cannot reach a sibling by suffix.\n const path = declared.find((name: string) => name.split('/').pop() === target + '.section')\n const Section = path ? sectionComponent(components[path]) : undefined\n\n // No throw here: the target may be a slot, which the branch below resolves.\n // A name that is a section of some *other* page simply does not match, falls\n // through, and is refused there — where the error can name both kinds.\n\n if (Section) {\n // The component, not the wrapper section() returned. The client replaces\n // what is inside the boundary, so sending the wrapper would nest a new\n // boundary inside the old one on every refresh.\n return createElement(Section, page.props)\n }\n\n // hasOwn, so a target of __proto__ or constructor names nothing.\n const slotComponent = Object.hasOwn(page.parallelSlots, target)\n ? page.parallelSlots[target]\n : undefined\n\n if (!slotComponent) {\n throw new Error(\n 'Cannot revalidate ' + target + ': no section or slot of this page by that name. ' +\n 'Sections: ' +\n (declared.map((n: string) => n.split('/').pop()!.replace('.section', '')).join(', ') ||\n 'none') +\n '. Slots: ' +\n (Object.keys(page.parallelSlots).join(', ') || 'none'),\n )\n }\n\n const SlotComp = components[slotComponent]\n\n if (!SlotComp) throw new Error('Unknown RSC component: ' + slotComponent)\n\n return createElement(SlotComp, {\n params: Promise.resolve(page.props),\n searchParams: pageSearchParams(),\n })\n}\n\n/**\n * Answer one read.\n *\n * Only functions declared with query() are reachable. The id comes off the url,\n * and every registered server action has one — without the mark, this address\n * would invoke mutations over GET, for anyone who can fetch it.\n */\nexport async function handleQuery(\n id: string,\n args: string,\n report?: (error: unknown) => string,\n): Promise<\n | { stream: ReadableStream; cacheControl: string }\n | { status: number; message: string; errors?: Record<string, string[]> }\n | null\n> {\n await instrumented()\n applyHost()\n\n let fn: unknown\n\n try {\n fn = await loadServerAction(id)\n } catch {\n return null\n }\n\n // Null for both, deliberately. Saying \"that exists but is not a query\" tells\n // whoever is probing this endpoint which ids are real actions, and the ids\n // are stable across a build.\n if (!isQuery(fn)) return null\n\n const decoded = (await decodeReply(args)) as unknown[]\n\n // Awaited here rather than handed to the renderer as a promise, so a refusal\n // is still a status line rather than an error row inside a 200. React strips\n // a thrown message in production, so a query that rejected mid-stream would\n // reach the browser as \"an error occurred\" with the fields gone.\n let result: unknown\n\n try {\n result = await (fn as (...a: unknown[]) => unknown)(...decoded)\n } catch (error) {\n if (isQueryValidationError(error)) {\n return { status: 422, errors: error.errors, message: error.message }\n }\n\n return { status: 500, message: report ? report(error) : 'Query failed.' }\n }\n\n return {\n stream: renderToReadableStream(result, {\n onError: (error: unknown) => (report ? report(error) : 'Query failed.'),\n }),\n cacheControl: queryCacheControl(fn),\n }\n}\n\nexport async function handleAction(\n actionId: string,\n body: string | FormData | Uint8Array,\n contentType = 'text/plain',\n page?: PageContext,\n takeRevalidated?: () => string[],\n): Promise<{ stream: ReadableStream }> {\n await instrumented()\n applyHost()\n\n // Every body arrives as bytes on its own socket frame — an upload because it\n // has to, the rest because the transport does not special-case them. What\n // differs is what they decode to: multipart is FormData, everything else is\n // the text encodeReply produced.\n //\n // Treating only multipart as bytes and leaving the rest empty is a silent\n // failure: the action runs with no arguments at all.\n let decodable: string | FormData\n\n if (typeof body === 'string') {\n decodable = body\n } else if (contentType.includes('multipart/form-data')) {\n decodable = await new Response(body, { headers: { 'Content-Type': contentType } }).formData()\n } else {\n decodable = new TextDecoder().decode(body)\n }\n\n // Checked before decoding, because React's decoder does not fail cleanly on\n // a malformed payload: the parse error is raised inside a chunk nobody\n // awaits, so the promise decodeReply returned never settles. The caller\n // cannot catch that — no try/catch anywhere sees it — and the request hangs\n // while the rejection escapes. On Node, whose default is to exit on an\n // unhandled rejection, that is the whole process, reachable by anyone who\n // can post to the action endpoint.\n //\n // A reply that is not multipart is the JSON model encodeReply produced, so\n // parsing it is both the check and the whole of it.\n if (typeof decodable === 'string') {\n try {\n JSON.parse(decodable)\n } catch {\n throw new Error('Malformed server action body: expected the payload encodeReply produces.')\n }\n }\n\n const args = (await decodeReply(decodable)) as unknown[]\n const action = await loadServerAction(actionId)\n\n // A query reached the ACTION endpoint, which means it was called directly\n // rather than through fetchQuery — so it went out as a POST and none of the\n // reasons it was marked a read apply to it. It still works, which is the\n // problem: nothing else would ever mention it. Only in development, and only\n // a warning, because the call is not wrong, just not what was asked for.\n if (isQuery(action) && import.meta.env?.DEV) {\n console.warn(\n '[rsc-kit] ' + actionId + ' is a query but was called directly, so it was sent as a POST. ' +\n 'Call it through fetchQuery() to send a GET.',\n )\n }\n\n // A plain \"use server\" function that threw fieldErrors() gets the same\n // treatment createActionClient gives its handlers: the throw becomes the\n // returned { validationErrors } that <Form> reads. Left thrown, React\n // serialises the rejection opaquely — production strips the message — and the\n // fields it named never reach the browser.\n let result: unknown\n\n try {\n result = await (action as (...a: unknown[]) => unknown)(...args)\n } catch (error) {\n if (!isActionValidationError(error)) throw error\n\n result = { validationErrors: error.errors }\n }\n\n // Read after the action has run: what it invalidated is only known once its\n // host calls have been made. Rendering here rather than telling the browser\n // to ask is the whole point — the answer carries what went stale with it.\n const targets = takeRevalidated?.() ?? []\n\n if (targets.length === 0 || !page) {\n return { stream: renderToReadableStream(result) }\n }\n\n const revalidated: Record<string, unknown> = {}\n\n for (const target of targets) {\n revalidated[target] = await renderRevalidated(target, page)\n }\n\n // Marked, so an action whose own result happens to be an object with a\n // 'result' key is not mistaken for this envelope.\n return { stream: renderToReadableStream({ __rscRevalidated: revalidated, result }) }\n}\n\nexport async function resolveMetadata(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n): Promise<Record<string, unknown> | null> {\n await instrumented()\n\n const pageEntry = metadataMap[component]\n const page: Record<string, unknown> = pageEntry\n ? (pageEntry.generate\n // The same awaitables the page receives. Resolved rather than\n // suspending, even during the probe: a title has to be produced for\n // the shell, and there is no fallback for a <title>.\n ? ((await pageEntry.generate({\n params: Promise.resolve(props),\n searchParams: pageSearchParams(),\n })) ?? {})\n : { ...(pageEntry.static ?? {}) })\n : {}\n\n // Non-title metadata: layout defaults (outer→inner), page overrides.\n //\n // other merges per key rather than being replaced, so a page adding one\n // custom tag keeps the ones its layout set. Assigning it like any other key\n // would mean a root layout's theme-color disappearing from every page that\n // happened to declare one of its own.\n const merged: Record<string, unknown> = {}\n const other: Record<string, unknown> = {}\n\n const take = (from: Record<string, unknown>) => {\n for (const [k, v] of Object.entries(from)) {\n if (k === 'title') continue\n if (k === 'other') Object.assign(other, v as Record<string, unknown>)\n else merged[k] = v\n }\n }\n\n for (const l of layouts) {\n const s = metadataMap[l.component]?.static\n\n if (s) take(s as Record<string, unknown>)\n }\n\n take(page)\n\n if (Object.keys(other).length > 0) merged.other = other\n\n // Title: the page title with the NEAREST layout title.template applied; if the\n // page has no title, the nearest layout default/string title.\n let title: string | undefined = typeof page.title === 'string' ? page.title : undefined\n for (let i = layouts.length - 1; i >= 0; i--) {\n const lt = metadataMap[layouts[i].component]?.static?.title as\n | string | { template?: string; default?: string } | undefined\n if (lt && typeof lt === 'object') {\n if (title != null && lt.template) { title = lt.template.replace('%s', title); break }\n if (title == null && lt.default) { title = lt.default; break }\n } else if (title == null && typeof lt === 'string') { title = lt; break }\n }\n if (title != null) merged.title = title\n\n return Object.keys(merged).length ? merged : null\n}\n\n// Buffered render (worker: rsc / rscWithoutCallbacks — used at prerender time).\nexport async function handleRsc(\n component: string,\n props: Record<string, unknown> = {},\n _callbackSocket: string | null = null,\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n from = 0,\n pageKey = '',\n bootstrap = true,\n canReachHost = true,\n): Promise<{ body: string; rscPayload: string; clientChunks: unknown; usedDynamicApis: boolean; dynamicBecause: string[]; clientComponents: string[]; serverReferences: boolean }> {\n await instrumented()\n applyHost()\n\n // A build renders this with no host installed, so every rpc() has to suspend\n // rather than answer — which is what marks the page as needing a request.\n // Without the probe those calls found no host at all, and the page was\n // frozen holding whatever undefined rendered to.\n //\n // Defaults to true because the other caller is an interception, which runs\n // at request time with a real host and must not be probed.\n let usedDynamicApis = false\n const hostCalls: string[] = []\n\n const probe = (...args: unknown[]) => {\n usedDynamicApis = true\n\n // The name it was called with, so the build can say rpc(\"getUser\") rather\n // than \"this page reached for the host\" and leave you to find which call.\n const name = typeof args[0] === 'string' ? args[0] : null\n const said = name ? 'rpc(' + JSON.stringify(name) + ')' : 'rpc()'\n\n if (!hostCalls.includes(said)) hostCalls.push(said)\n\n return new Promise<never>(() => {})\n }\n\n // Not a generic arrow function: this file is generated as .tsx, where <T>\n // parses as JSX and the build fails on a tag it cannot close.\n const runWith = canReachHost\n ? (fn: () => Promise<unknown>) => fn()\n : (fn: () => Promise<unknown>) => probeHost.run(probe, fn)\n\n // renderTree (not bare buildElement) so the prerendered Flight payload carries\n // the same <title>/<meta> elements the live SPA payload does.\n const tree = await runWith(() =>\n renderTree(component, props, layouts, loadings, parallelSlots, {}, from, pageKey, bootstrap),\n )\n\n const flight = renderToReadableStream(tree, { onError: flightOnError })\n const [forHtml, forPayload] = flight.tee()\n const rscPayload = await new Response(forPayload).text()\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n const htmlStream = await ssr.handleSsr(forHtml, undefined, undefined, bootstrap)\n const body = await new Response(htmlStream).text()\n\n return {\n body,\n rscPayload,\n clientChunks: {},\n usedDynamicApis,\n // Client reference rows name the components the browser has to run. Shipping\n // no runtime would leave them as inert markup, so the host refuses — and\n // says which components forced the decision, since they are usually in a\n // shared layout rather than the page itself.\n clientComponents: clientReferenceNames(rscPayload),\n serverReferences: hasServerReference(rscPayload),\n }\n}\n\n/**\n * Names of the client components a payload references.\n *\n * A row reads 1:I[\"<module>\",[],\"Name\",1]; the fourth quoted field is the\n * export. Parsed by splitting rather than matching, because this function is\n * emitted into a template literal where a regex would need double escaping.\n */\nfunction clientReferenceNames(payload: string): string[] {\n const names = new Set<string>()\n\n // A string React has already sent is referenced by row - \"$1\" for the\n // string in row 1 - rather than repeated. The export name of a client\n // reference is exactly the kind of string that repeats, so it arrives that\n // way and has to be looked up, or the refusal names a component \"$1\".\n const strings = new Map<string, string>()\n\n for (const line of payload.split('\\\\n')) {\n const match = /^(\\\\d+):\"(.*)\"$/.exec(line)\n if (match) strings.set('$' + match[1], match[2]!)\n }\n\n for (const row of payload.split(':I[').slice(1)) {\n const name = row.split('\"')[3]\n if (name) names.add(strings.get(name) ?? name)\n }\n\n return [...names]\n}\n\n/**\n * Whether the payload carries a server reference - an action handed to a\n * form or a client component. A row of {\"id\":\"...\",\"bound\":...} is one,\n * however it is pointed at ($F for a function prop, $h for a form action).\n * A page with one needs the runtime to submit it.\n */\nexport function hasServerReference(payload: string): boolean {\n return /^\\\\d+:\\\\{\"id\":\"[^\"]+\",\"bound\":/m.test(payload)\n}\n\n// Flight payload only (worker: rsc-payload — build-time).\n//\n// The segment variant of a prerendered route needs the payload and nothing\n// else. handleRsc also renders the HTML, which for that variant is built and\n// thrown away — a whole SSR pass per route for output nobody reads.\n/**\n * Render one thing on its own, for a client asking to refresh it.\n *\n * The same targets an action can mark. This is the path for a refresh nobody\n * mutated anything to earn — a button, a poll, a websocket saying the orders\n * table moved.\n */\nexport async function handleRscRevalidate(\n target: string,\n page: PageContext,\n): Promise<{ rscPayload: string }> {\n await instrumented()\n applyHost()\n\n const flight = renderToReadableStream(await renderRevalidated(target, page))\n\n return { rscPayload: await new Response(flight).text() }\n}\n\nexport async function handleRscPayload(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n from = 0,\n pageKey = '',\n): Promise<{ rscPayload: string }> {\n await instrumented()\n applyHost()\n\n const flight = renderToReadableStream(\n await renderTree(component, props, layouts, loadings, parallelSlots, {}, from, pageKey),\n { onError: flightOnError },\n )\n\n return { rscPayload: await new Response(flight).text() }\n}\n\n// PPR shell + classification (worker: rsc-ppr-shell — build-time).\n//\n// rpc() is replaced by a probe that records the call and never resolves, so\n// every subtree depending on per-request data stays suspended while everything\n// static renders normally. Whatever React has flushed when the deadline passes\n// IS the shell: layouts, static markup, and Suspense fallbacks.\n//\n// The two flags this returns are what the prerender pipeline classifies on:\n// usedDynamicApis — the page touched rpc(), so it cannot be frozen whole\n// timedOut — the render never finished, i.e. it is still waiting on\n// data, so only the shell is safe to cache\n// A page that sets neither is genuinely static and can be prerendered fully.\nconst PPR_SHELL_TIMEOUT_MS = Number(process.env.RSC_PPR_TIMEOUT_MS || 2000)\n\nexport async function handleRscPprShell(\n component: string,\n props: Record<string, unknown> = {},\n layouts: LayoutEntry[] = [],\n loadings: string[] = [],\n parallelSlots: Record<string, string> = {},\n // The url this shell will be served for, when it is served for exactly one.\n // Empty for a parameterised route, whose shell is shared across every url it\n // matches and therefore cannot carry one.\n pageKey = '',\n // How long to let the render run before taking whatever has flushed.\n //\n // A parameter because not every caller is asking the same question. Deciding\n // what a page's shell IS needs the full budget — the point is to wait out\n // everything that can resolve. Asking whether anything paints at all without\n // a root fallback is a boolean about the first flush, and a page that paints,\n // paints immediately: giving that the same budget spends two seconds per\n // route to learn nothing the first millisecond did not say.\n budgetMs = PPR_SHELL_TIMEOUT_MS,\n // Whether this build can answer host calls.\n //\n // False is the old and still the usual answer: the stub suspends, and a page\n // reaching for its host becomes a shell rather than freezing data fetched\n // once at build time.\n //\n // A host that opened a callback socket for the build says true, and then the\n // call is made and its answer stored. That is the only way a page whose data\n // lives in the host can be static at all, since a host call is its only route\n // to that data — and\n // connection() is how such a page opts back out.\n //\n // Asked of the caller rather than read from whatever host happens to be\n // installed, because those are different statements: a test that installed\n // one is not a build that can reach the host.\n canReachHost = false,\n): Promise<{ shellHtml: string; clientChunks: unknown; timedOut: boolean; usedDynamicApis: boolean; error?: string }> {\n // Deliberately no middleware here. The probe is asking whether the content is\n // the same for everyone, which is a question about the page. Whether a\n // particular caller may see it is a question about the request, and there is\n // no request at build time — running a guard here would refuse every time\n // and make every guarded route dynamic for the wrong reason.\n let usedDynamicApis = false\n\n await instrumented()\n applyHost()\n\n const probe = (..._args: unknown[]) => {\n usedDynamicApis = true\n\n // Never resolves: the awaiting component suspends and React renders its\n // Suspense fallback into the shell instead of the real content.\n return new Promise<unknown>(() => {})\n }\n\n let shellHtml = ''\n let completed = false\n let error: string | undefined\n let postponed: unknown = null\n\n // The budget, declared before the error handler that consults it.\n const controller = new AbortController()\n const budget = setTimeout(() => controller.abort(), budgetMs)\n\n // Anything that failed while producing this shell.\n //\n // A rejection inside a Suspense boundary does NOT reach the caller: React\n // catches it, keeps the fallback, and the render goes on to finish. So the\n // probe looked like a page that had nothing left to do — no postponed state,\n // no thrown error — and the fallback was frozen as a finished static page.\n // A database the build machine cannot reach produced a permanently loading\n // page, stored, with the build reporting success.\n let renderFailure: string | undefined\n\n const noteFailure = (e: unknown, info?: { componentStack?: string }): string | undefined => {\n const digest = redirectDigest(e)\n\n // A redirect is a classification here, not a failure.\n if (digest) return digest\n\n // A read the server could not answer, caught at a boundary: the fallback\n // there is what gets stored. Noted with its component so the build can\n // say so on the route's line; the digest goes into the document for the\n // browser to recognise.\n if ((e as { digest?: string } | null)?.digest === 'rsc-kit:search-params-fallback') {\n const where = /at ([A-Z_$][\\\\w$]*)/.exec(info?.componentStack ?? '')?.[1]\n noteCaughtRead('useSearchParams()' + (where ? ' in ' + where : ''))\n return 'rsc-kit:search-params-fallback'\n }\n\n // Every probe ends by aborting, so React reports that abort. Asked of the\n // signal rather than matched against the message: a string test would be a\n // guess about wording, and would quietly stop working when React changed it.\n if (controller.signal.aborted) return undefined\n\n renderFailure ??= e instanceof Error ? e.message : String(e)\n console.error('[rsc-kit]', e)\n\n return undefined\n }\n\n // The budget is an abort signal rather than a race. \\`prerender\\` resolves when\n // it is aborted, handing back both what flushed and where it stopped, so there\n // is nothing left to cancel by hand and no window in which the render is still\n // going after the caller has moved on.\n\n // Everything the render does happens inside the scope, so the stand-in host\n // travels with it rather than with the process.\n const runWith = canReachHost\n ? (fn: () => Promise<void>) => fn()\n : (fn: () => Promise<void>) => probeHost.run(probe, fn)\n\n const produce = runWith(async () => {\n try {\n // Params settle only when this probe is for one concrete url. A route\n // that listed its urls is being rendered for one of them, so the page\n // can be frozen whole; a route that listed none is being rendered for\n // the pattern, where any value would be an invention.\n const tree = await renderTree(\n component,\n props,\n layouts,\n loadings,\n parallelSlots,\n {},\n 0,\n pageKey,\n true,\n pageKey ? Promise.resolve(props) : new Promise(() => {}),\n )\n // Quiet about a redirect: during the probe it is a classification, not\n // a failure, and React would otherwise print a stack for every one.\n const flight = renderToReadableStream(tree, { onError: noteFailure })\n const ssr = await (import.meta as any).viteRsc.loadModule('ssr', 'index')\n // The flight stream stays open across this. A Flight stream that has\n // closed tells the decoder the connection ended, so the boundary waiting\n // on it errors rather than staying pending — and an errored boundary is\n // finished, not postponed: it comes back null and there is nothing left\n // to resume from.\n const prerendered = await ssr.handleSsrPrerender(flight, {\n signal: controller.signal,\n onError: noteFailure,\n })\n\n postponed = prerendered.postponed\n\n const reader = prerendered.prelude.getReader()\n const decoder = new TextDecoder()\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n shellHtml += decoder.decode(value, { stream: true })\n }\n\n completed = true\n } catch (e: any) {\n error = e?.message ?? String(e)\n }\n })\n\n await produce\n clearTimeout(budget)\n\n // timedOut used to mean the stopwatch ran out. It now means React has\n // boundaries it could not finish — the thing the caller was always asking\n // about, and exact rather than inferred: a page that finishes inside the\n // budget says so by postponing nothing.\n return {\n shellHtml,\n clientChunks: {},\n timedOut: postponed !== null,\n usedDynamicApis,\n error,\n postponed,\n renderFailure,\n }\n}\n\n/**\n * What \\`vite dev\\` serves.\n *\n * @vitejs/plugin-rsc's dev server calls this module's default export for every\n * request, so implementing it is the whole of dev mode: the same handler the\n * production server builds, over the same route table, against modules Vite\n * re-evaluates on edit. Nothing is prebuilt, so there is no build to keep in\n * step and no NODE_ENV to match — this is React's development build because\n * Vite is running in development.\n *\n * Assets are deliberately absent: Vite serves its own.\n *\n * Frozen pages are absent *in development* — a frozen page is a build\n * artifact, and serving one here would hand back the last build's HTML for a\n * file just edited. Under Nitro this same file is also the production entry,\n * and reading that reason as applying to both is what left every built Nitro\n * server rendering live pages it had already frozen. The gate is the mode, not\n * the file.\n */\n${fallbackOrigin ? FALLBACK_CONSTS.replace(\"__ORIGIN__\", JSON.stringify(fallbackOrigin)) : \"\"}${NITRO_HOST_CALLS}\nlet devHandler: ((request: Request) => Promise<Response | null>) | null = null\n\nexport default async function handler(request: Request): Promise<Response> {\n try {\n return await serve(request)\n } catch (error) {\n // Vite re-optimised a server pre-bundle under this render. The condition\n // is over already; the page is asked to load again.\n if (import.meta.env.DEV && isOutdatedOptimizedDep(error)) return outdatedDepResponse(request)\n\n throw error\n }\n}\n\nasync function serve(request: Request): Promise<Response> {\n // The startup plugin's probe. Nitro loads this module at the first request\n // rather than when the server starts, so a plugin that runs at startup\n // sends one request to load it; the module's evaluation began register(),\n // and this waits for it so a failure is reported as the startup failure it\n // is. No page is rendered and nothing is disclosed.\n if (request.headers.get('x-rsc-kit-startup') !== null) {\n await instrumented()\n\n return new Response(null, { status: 204 })\n }\n\n installHostCallsOnce()\n\n devHandler ??= createRscHandler({\n engine: {\n manifest,\n getStaticParams,\n installHostFn,\n handleRsc,\n handleRscStream,\n handleRscHtmlStream,\n handleRscFormPost,\n handleRscRevalidate,\n handleRscPayload,\n handleRscPprShell,\n handleRscResume,\n handleAction,\n handleQuery,\n handleApiRoute,\n resolveMetadata,\n runRouteMiddleware,\n buildId,\n criticalAssets,\n } as never,\n${NITRO_HANDLER_OPTIONS}${NITRO_PRERENDERED} maxActionBody: ${maxActionBody === undefined ? \"undefined\" : String(maxActionBody)},\n })\n\n${fallbackOrigin ? FALLBACK_BODY : \" return (await devHandler(request)) ?? (await notFound(request))\\n\"}}\n\n/**\n * The page for a url nothing answers.\n *\n * Rendered through its layout chain like any other page, so the 404 a visitor\n * sees is the app rather than a bare string — and returned with a 404, because\n * a page that says \"not found\" under a 200 is a page search engines index.\n *\n * Without a not-found.tsx this is the string it always was.\n */\nasync function notFound(request: Request): Promise<Response> {\n ${\n notFoundComponent\n ? `\n // A navigation, not a document: answer with the not-found tree as a\n // payload, at the depth the client already holds, so the router renders\n // it in place - the layout stays, the url changes, nothing reloads. The\n // status is still 404; a payload is a payload whatever it says.\n if (request.headers.get('X-RSC')) {\n try {\n const chain = ${JSON.stringify(notFoundLayouts)}\n const from = sharedDepth(request.headers.get('X-RSC-Segments'), chain)\n const { rscPayload } = await handleRscPayload(\n ${JSON.stringify(notFoundComponent)},\n {},\n ${JSON.stringify(notFoundLayouts.map((component) => ({ component, props: {} })))},\n [],\n {},\n from,\n '/404',\n )\n\n return new Response(rscPayload, {\n status: 404,\n headers: {\n 'Content-Type': 'text/x-component; charset=utf-8',\n 'X-RSC-Segment-Depth': String(from),\n 'X-RSC-Layouts': chain.join(','),\n 'Cache-Control': 'no-store',\n Vary: 'X-RSC',\n },\n })\n } catch {\n // Fall through to the document answer below.\n }\n }\n\n try {\n const { htmlStream } = await handleRscHtmlStream(\n ${JSON.stringify(notFoundComponent)},\n {},\n ${JSON.stringify(notFoundLayouts.map((component) => ({ component, props: {} })))},\n [],\n {},\n {},\n undefined,\n '/404',\n )\n\n return new Response(htmlStream, {\n status: 404,\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n })\n } catch {\n // A 404 page that throws is still a 404. Falling back rather than\n // answering 500 keeps the status honest about what happened.\n }\n `\n : \"\"\n }\n return new Response('Not found', { status: 404 })\n}\n`;\n}\n\nfunction generateEntrySsr(): string {\n const devUrls = join(packageDir, \"devUrls\");\n const request = join(packageDir, \"request\");\n const fallbackReport = join(packageDir, \"js/fallbackReport\");\n const redirectDigestModule = join(packageDir, \"redirectDigest\");\n const notFoundModule = join(packageDir, \"notFound\");\n const earlyClicks = join(packageDir, \"js/earlyClicks\");\n\n return `// GENERATED by rscKit() — do not edit.\nimport { createFromReadableStream } from '@vitejs/plugin-rsc/ssr'\nimport { renderToReadableStream, resume } from 'react-dom/server.edge'\nimport { prerender } from 'react-dom/static.edge'\nimport { rewriteViteDevUrlStream } from ${JSON.stringify(devUrls)}\nimport { noteFallback } from ${JSON.stringify(request)}\nimport { cancelledByConsumer, caughtByLoading } from ${JSON.stringify(fallbackReport)}\nimport { parseRedirectDigest } from ${JSON.stringify(redirectDigestModule)}\nimport { isNotFoundDigest } from ${JSON.stringify(notFoundModule)}\nimport { EARLY_CLICKS } from ${JSON.stringify(earlyClicks)}\n\n// Set only by the dev server. @vitejs/plugin-rsc emits its bootstrap and CSS\n// links root-relative in dev, which would send the browser to the host for\n// modules only Vite can answer — see devUrls.ts.\nconst DEV_ORIGIN = ${JSON.stringify(devOrigin)}\n\nexport async function handleSsr(\n rscStream: ReadableStream,\n nonce?: string,\n onError?: (error: unknown) => void,\n bootstrap = true,\n formState?: unknown,\n): Promise<ReadableStream> {\n const root = await createFromReadableStream(rscStream)\n\n // Without the bootstrap the page ships no client runtime at all: no React,\n // no Flight client, no router. HTML only. A page with nothing interactive on\n // it has no use for 70kB of hydration.\n // The click listener first, then the runtime's import: a tap in the\n // seconds before the runtime hydrates is held for it rather than given\n // to the browser as a document load. See earlyClicks.ts.\n const bootstrapScriptContent = bootstrap\n ? EARLY_CLICKS + (await (import.meta as any).viteRsc.loadBootstrapScriptContent('index'))\n : undefined\n\n // Without an onError handler React rejects each abortable task on its own,\n // and those rejections surface as unhandled — noisy for the PPR shell render,\n // which aborts on purpose once it has the shell.\n const html = await renderToReadableStream(root as any, {\n bootstrapScriptContent,\n nonce,\n onError: onError ?? reportRenderError('ssr'),\n // What a posted form's action returned, for the useActionState that\n // asked: React seats it in the form it belongs to.\n ...(formState !== undefined ? { formState: formState as any } : {}),\n })\n\n return DEV_ORIGIN ? rewriteViteDevUrlStream(html, DEV_ORIGIN) : html\n}\n\n/**\n * The same render, stopped at the first thing it cannot finish.\n *\n * \\`renderToReadableStream\\` and then cancelling gives you the bytes that\n * flushed and nothing else — the render is *aborted*, so React has no record of\n * where it got to. \\`prerender\\` aborts the same way but hands back\n * \\`postponed\\`: enough state to pick the render back up later, against data\n * that did not exist at build time.\n *\n * The rscStream must still be OPEN when this returns. A Flight stream that has\n * closed tells the decoder the connection ended, so the boundary waiting on it\n * *errors* rather than staying pending — and an errored boundary is not\n * postponed, it is finished. \\`postponed\\` comes back null and there is nothing\n * to resume.\n */\nexport async function handleSsrPrerender(\n rscStream: ReadableStream,\n options: { nonce?: string; bootstrap?: boolean; signal?: AbortSignal } = {},\n): Promise<{ prelude: ReadableStream; postponed: unknown }> {\n const root = await createFromReadableStream(rscStream)\n\n const bootstrapScriptContent =\n options.bootstrap === false\n ? undefined\n : EARLY_CLICKS + (await (import.meta as any).viteRsc.loadBootstrapScriptContent('index'))\n\n const { prelude, postponed } = await prerender(root as any, {\n bootstrapScriptContent,\n nonce: options.nonce,\n signal: options.signal,\n // Aborting is how this ends, so React's report of it is not news. A read\n // caught at a boundary is: the build attaches it to the route.\n onError: (error: unknown, info?: { componentStack?: string }) => {\n if ((error as { digest?: string } | null)?.digest !== 'rsc-kit:search-params-fallback') return\n const where = /at ([A-Z_$][\\\\w$]*)/.exec(info?.componentStack ?? '')?.[1]\n noteFallback('useSearchParams()' + (where ? ' in ' + where : ''))\n return 'rsc-kit:search-params-fallback'\n },\n })\n\n return {\n prelude: DEV_ORIGIN ? rewriteViteDevUrlStream(prelude, DEV_ORIGIN) : prelude,\n postponed: postponed ?? null,\n }\n}\n\n/**\n * What a server render says about an error, first render and resume alike.\n *\n * The query-string fallback is the designed path for a stored page, and its\n * digest is what lets the client tell it from a fault on hydration; returned\n * so React writes it into the document. Under a boundary the developer wrote\n * there is nothing to say; with nothing closer than a loading.tsx, one line.\n */\nfunction reportRenderError(phase: 'ssr' | 'resume') {\n return (error: unknown, info?: { componentStack?: string }) => {\n // The consumer cancelled - a browser that left mid-stream, a prefetch\n // abandoned. React reports it as an error; the page had none.\n if (cancelledByConsumer(error)) return\n\n const digest = (error as { digest?: string } | null)?.digest\n\n // A redirect or a notFound() the render asked for arrives here as the\n // Flight row's error, once per boundary it was thrown in. The rsc side\n // already turned it into a digest on purpose; it is the page's answer,\n // and the host reads it off the digest. Not an error to print, four\n // times or once.\n if (parseRedirectDigest(digest) || isNotFoundDigest(digest)) return digest\n\n if (digest === 'rsc-kit:search-params-fallback') {\n // The component is the first frame of React's stack. Noted on the\n // request so the build attaches it to the route; printed as one line,\n // not a stack, so the server says which boundary it wants.\n const where = /at ([A-Z_$][\\\\w$]*)/.exec(info?.componentStack ?? '')?.[1]\n\n noteFallback('useSearchParams()' + (where ? ' in ' + where : ''))\n\n if (caughtByLoading(info?.componentStack)) {\n console.error(\n '[rsc-kit] ' + (where ? where + ': ' : '') +\n 'useSearchParams() was read on the server with nothing closer than a loading.tsx, so the whole ' +\n 'segment shows that fallback until the query arrives. A <Suspense> around the component that reads ' +\n 'keeps the rest of the page painted.',\n )\n }\n\n return digest\n }\n\n console.error('[rsc-kit:' + phase + ']', error)\n }\n}\n\n/**\n * Pick a build-time render back up, against data that exists now.\n *\n * Emits ONLY what the shell left unfinished — the hidden segments plus React's\n * own script to move them into place. It is meant to be concatenated after the\n * shell, and it carries no bootstrap of its own: the shell already shipped one.\n *\n * The swap is done by that inline script, not by hydration, so the holes land\n * even on a page whose JavaScript never loads.\n */\nexport async function handleSsrResume(\n rscStream: ReadableStream,\n postponed: unknown,\n nonce?: string,\n): Promise<ReadableStream> {\n const root = await createFromReadableStream(rscStream)\n\n const html = await resume(root as any, postponed as any, {\n nonce,\n // The same reading of an error the first render has. This used to log\n // every error raw, so a query read the developer's own boundary caught -\n // the designed path, on every resume of a shell whose hole holds one -\n // printed as \"[rsc-kit:resume] Error: useSearchParams() was read...\" on\n // every request, with advice the app had already followed.\n onError: reportRenderError('resume'),\n })\n\n return DEV_ORIGIN ? rewriteViteDevUrlStream(html, DEV_ORIGIN) : html\n}\n${SSR_SERVICE}`;\n}\n\n/**\n * What Nitro calls this environment through.\n *\n * Nitro addresses each Vite environment as a service and calls fetch on it —\n * `mod = _mod.default || _mod; mod.fetch(req)` — so an entry that exports only\n * named functions is a 500 on every request. The named ones stay: the rsc\n * entry still reaches them through loadModule. This only adds the door Nitro\n * knocks on, and the request goes straight back to the rsc entry, which is the\n * one that owns rendering.\n */\nconst SSR_SERVICE = `\nexport default {\n fetch: async (request: Request): Promise<Response> => {\n const rsc = await import.meta.viteRsc.loadModule<{\n default: (request: Request) => Promise<Response>\n }>('rsc', 'index')\n\n return rsc.default(request)\n },\n}\n`;\n\nfunction generateEntryBrowser(): string {\n const clientBootstrap = join(packageDir, \"js/createViteRscApp\");\n\n // Only for an exported build, and only what the client needs to work out how\n // much of a page to ask for: a file server sends no headers, so without this\n // every navigation takes the whole document and replaces the root. Inlined\n // rather than fetched, so it costs no request. Omitted entirely otherwise —\n // a server answers this, and shipping a route table to every browser for\n // nothing is a page-weight cost with no benefit.\n const routesForClient = staticPayloads\n ? routeManifest().routes.map((route) => ({\n segments: route.segments,\n layouts: route.layouts,\n }))\n : null;\n\n const refreshModule = join(packageDir, \"js/navigate\");\n\n return `// GENERATED by rscKit() — do not edit.\nimport { createViteRscApp } from ${JSON.stringify(clientBootstrap)}\nimport { refresh } from ${JSON.stringify(refreshModule)}\n\ncreateViteRscApp(document, ${JSON.stringify(interceptManifest())}, ${JSON.stringify(\n {\n staticPayloads: staticPayloads || null,\n routes: routesForClient,\n // Every route.ts, as a url pattern, so a link to one is treated as an\n // anchor rather than prefetched and fetched as a page.\n apiRoutes: (routeManifest().apis ?? []).map((api) => patternOf(api.segments)),\n },\n )})\n\n// A server component is not a module the browser has, so Vite cannot replace\n// it the way it replaces a client one. @vitejs/plugin-rsc says so instead:\n// when a module in the rsc graph changes it sends this, and re-fetching the\n// payload is the update. Without a listener an edit to a page reaches the\n// server and stops there, and the browser goes on showing the old render\n// until someone reloads by hand.\n//\n// 'all', not 'page': a layout is a server component too, and refreshing only\n// below it would leave an edited layout on screen unchanged. It costs nothing\n// extra — a client component below is remounted either way, because the new\n// payload carries a fresh reference to its module. Editing that component\n// directly is the case where state survives, and that is Fast Refresh doing\n// it rather than this.\nif (import.meta.hot) {\n import.meta.hot.on('rsc:update', () => {\n void refresh('all')\n })\n}\n${\n offline\n ? `\n// Registered after load rather than during it, so fetching and installing the\n// worker competes with nothing the first visit actually needs. The second\n// visit is the one it is for.\n//\n// Not in development: the dev server is the thing you are editing, and a\n// worker answering from a cache in front of it turns every edit into a\n// question about which copy you are looking at.\nif ('serviceWorker' in navigator && import.meta.env.PROD) {\n const register = () => {\n void navigator.serviceWorker.register('/sw.js').catch(() => {\n // A worker that will not register is not a reason for the page to fail.\n // The app works; it just will not survive being reloaded offline.\n })\n }\n\n // This runs after the boot payload has been fetched and decoded, and on a\n // fast load the page has finished loading by then - a listener added now\n // waits for an event that has already fired, and nothing registered until\n // the next navigation.\n if (document.readyState === 'complete') register()\n else window.addEventListener('load', register)\n}\n`\n : \"\"\n}`;\n}\n\n/**\n * Intercepted URL patterns, published by the host before the build.\n *\n * The client has to recognise an intercepted link before it asks the server,\n * so the patterns are baked into the browser entry. The host owns the file\n * because it owns route discovery; an absent or unreadable one just means no\n * interception, never a failed build.\n */\n/**\n * The intercepted urls the client router has to recognise, in its dialect.\n *\n * Generated here rather than read from a file the host wrote. The host used to\n * discover these because it owned the walk of app/; now the plugin does, and a\n * host writing them meant producing this file before the build that needed it —\n * an ordering that only worked because the two steps happened to be in the\n * right sequence.\n */\nfunction interceptManifest(): Array<{ urlPattern: string; slot: string }> {\n return routeManifest().intercepts.map((entry) => ({\n // The client writes [id] where a Laravel route writes {id}.\n urlPattern:\n \"/\" +\n entry.segments\n .map((seg) =>\n seg.type === \"static\" ? seg.value : \"[\" + seg.value + \"]\",\n )\n .join(\"/\"),\n slot: entry.slot,\n }));\n}\n\n// ── Validation ───────────────────────────────────────────────────────────────\n\n/**\n * Extract the body of a file's default-exported function.\n *\n * Only the page component's OWN body matters for the loading.tsx rule — sibling\n * components declared in the same file render behind their own boundaries, so\n * their host calls do not block the route's shell.\n */\nfunction defaultExportBody(source: string): string | null {\n const match = source.match(\n /export\\s+default\\s+(?:async\\s+)?function[^(]*\\([^)]*\\)\\s*{/,\n );\n if (!match) return null;\n\n // Walk from the opening brace to its match, ignoring braces in strings.\n let depth = 0;\n const start = match.index! + match[0].length - 1;\n\n for (let i = start; i < source.length; i++) {\n const ch = source[i];\n if (ch === \"{\") depth++;\n else if (ch === \"}\" && --depth === 0) return source.slice(start, i + 1);\n }\n\n return null;\n}\n\n/**\n * Does the page component's own render block on the host callable?\n *\n * Only an awaited call blocks. Starting a call and handing the promise to a\n * child — for a client component to unwrap with use() inside its own Suspense\n * boundary — lets the page paint immediately and needs no loading.tsx.\n *\n * The check is deliberately syntactic: a call awaited indirectly, through a\n * variable, is not caught. That errs toward letting a build through rather than\n * rejecting a page that is actually fine.\n */\nfunction pageBlocksOnHostCall(source: string): boolean {\n const isAsyncDefault = /export\\s+default\\s+async\\s+function/.test(source);\n if (!isAsyncDefault) return false;\n\n const body = defaultExportBody(source);\n\n // Matches `await rpc(`, and the explicitly-qualified forms a typed codebase\n // may use: `await globalThis.rpc(` / `await (globalThis as any).rpc(`.\n const qualifier =\n \"(?:\\\\(\\\\s*globalThis[^)]*\\\\)\\\\s*\\\\.\\\\s*|globalThis\\\\s*\\\\.\\\\s*)?\";\n const awaited = new RegExp(`\\\\bawait\\\\s+${qualifier}${hostGlobal}\\\\s*[<(]`);\n\n return body !== null && awaited.test(body);\n}\n\n/** Walk up from the page directory to app/ looking for a loading file. */\nfunction hasLoadingInChain(pageDir: string): boolean {\n let dir = pageDir;\n\n while (dir.startsWith(appDir)) {\n if (findRouteFile(dir, \"loading\")) return true;\n if (dir === appDir) break;\n dir = dirname(dir);\n }\n\n return false;\n}\n\n/**\n * A route needs loading.tsx only when the PAGE ITSELF blocks — an async default\n * export awaiting the host callable, or the host resolving props dynamically. Both\n * suspend before anything can paint, so without a boundary the user sees a\n * blank screen. A page whose slow work lives in children behind their own\n * <Suspense> already paints a shell and needs nothing.\n */\n/**\n * An `error.tsx` has to be a client component.\n *\n * It is rendered inside a React error boundary, which is a class component in\n * the browser, and it is handed a `reset` callback to call. A server component\n * can be neither. Caught here rather than at runtime, where the symptom is a\n * boundary that renders nothing while the error it was written for goes to the\n * console.\n */\nfunction validateErrorBoundaries(): string[] {\n const wrong: string[] = [];\n\n for (const c of components.values()) {\n if (!c.name.endsWith(\"/error\")) continue;\n\n const source = readFileSync(c.absPath, \"utf-8\");\n\n if (!/^\\s*['\"]use client['\"]/m.test(source)) {\n wrong.push(` ${relative(projectRoot, c.absPath)}`);\n }\n }\n\n return wrong;\n}\n\nfunction validateLoadingBoundaries(): string[] {\n const errors: string[] = [];\n\n for (const c of components.values()) {\n if (!c.name.endsWith(\"/page\") && c.name !== \"app/page\") continue;\n\n const pageDir = dirname(c.absPath);\n const source = readFileSync(c.absPath, \"utf-8\");\n\n let reason: string | null = null;\n\n if (pageBlocksOnHostCall(source)) {\n reason = `its default export awaits ${hostGlobal}()`;\n } else {\n const configPath = routeConfig ? join(pageDir, routeConfig.file) : null;\n\n if (\n routeConfig &&\n configPath &&\n existsSync(configPath) &&\n routeConfig.dynamicPattern.test(readFileSync(configPath, \"utf-8\"))\n ) {\n reason = `${routeConfig.file} resolves props dynamically`;\n }\n }\n\n if (reason && !hasLoadingInChain(pageDir)) {\n errors.push(\n ` ${c.name} — ${reason}, but has no loading.tsx in its directory chain`,\n );\n }\n }\n\n return errors;\n}\n\n// ── Plugin ───────────────────────────────────────────────────────────────────\n\n/** Names of plugins that transform JSX and must run after rsc() has split it. */\nconst JSX_PLUGIN_PATTERN = /react|babel|oxc/i;\n\n/**\n * The server-side stand-in for a client export, made extendable.\n *\n * In the rsc environment plugin-rsc replaces every export of a \"use client\"\n * module with a stub that throws when called. It emits the stub as an arrow\n * function, and an arrow function has no prototype, so a server module that\n * does `class NullStore extends ReactStore` - base-ui does, with only the\n * base class marked \"use client\" - dies at the class declaration with\n * \"The superclass is not a constructor\", on a line nobody wrote, whenever a\n * server component imports the library directly. Next.js allows that import;\n * React's own client references are proxies over a real function.\n *\n * A `function` stub has a prototype, so the declaration succeeds, and the\n * stub still throws - now from `super()`, with its own message - if the\n * class is ever constructed on the server.\n */\nconst CLIENT_STUB =\n /registerClientReference\\(\\s*\\(\\) => \\{ throw new Error\\(\"Unexpectedly client reference export '\"/g;\n\nfunction extendableClientReferences(): Plugin {\n return {\n name: \"rsc-kit:extendable-client-references\",\n enforce: \"post\",\n applyToEnvironment: (environment) => environment.name === \"rsc\",\n transform(code) {\n if (!code.includes(\"Unexpectedly client reference export\")) return;\n\n return {\n code: code.replace(\n CLIENT_STUB,\n 'registerClientReference(function () { throw new Error(\"Unexpectedly client reference export \\'\"',\n ),\n map: null,\n };\n },\n };\n}\n\n/**\n * The worker the dev server serves at /sw.js: it removes the one a production\n * run left on this origin, and the caches with it, then reloads each page it\n * was controlling so they load uncontrolled. Nothing else runs in development.\n */\nexport const DEV_WORKER = `self.addEventListener('install', () => self.skipWaiting())\nself.addEventListener('activate', (event) => {\n event.waitUntil((async () => {\n const keys = await caches.keys()\n await Promise.all(keys.filter((k) => k.startsWith('rsc-kit-')).map((k) => caches.delete(k)))\n await self.clients.claim()\n const pages = await self.clients.matchAll({ type: 'window' })\n await self.registration.unregister()\n for (const page of pages) page.navigate(page.url).catch(() => {})\n })())\n})\n`;\n\n/**\n * Named imports from a barrel package, unrolled on the server environments.\n *\n * The browser gets lucide pre-bundled; the server environments do not, so\n * `import { ArrowRight } from 'lucide-react'` loaded and transformed every\n * icon module - 3,700 transforms, twenty-five seconds before the first\n * document, for thirteen icons. See barrelImports. Development only: a\n * build tree-shakes the barrel itself.\n */\nfunction barrelImportsPlugin(): Plugin {\n const entries = new Map<string, string | null>();\n\n return {\n name: \"rsc-kit:barrel-imports\",\n apply: () => barrelImports && process.env.NODE_ENV !== \"production\",\n enforce: \"pre\",\n applyToEnvironment: (environment) =>\n environment.name === \"rsc\" || environment.name === \"ssr\",\n async transform(code, id) {\n if (\n id.includes(\"/node_modules/\") ||\n !/\\.[cm]?[jt]sx?$/.test(id.split(\"?\")[0])\n )\n return;\n if (!code.includes(\"from\")) return;\n\n const pending: Promise<void>[] = [];\n const wanted = new Set<string>();\n\n for (const m of code.matchAll(\n /import\\s*(?:type\\s+)?\\{[^}]*\\}\\s*from\\s*['\"]([^'\"./][^'\"]*)['\"]/g,\n )) {\n wanted.add(m[1]);\n }\n\n for (const specifier of wanted) {\n if (entries.has(specifier)) continue;\n\n pending.push(\n this.resolve(specifier, id).then((resolved) => {\n entries.set(\n specifier,\n resolved && !resolved.external ? resolved.id.split(\"?\")[0] : null,\n );\n }),\n );\n }\n\n await Promise.all(pending);\n\n const out = unrollBarrelImports(\n code,\n (specifier) => entries.get(specifier) ?? null,\n );\n\n return out === null ? undefined : { code: out, map: null };\n },\n };\n}\n\n/**\n * \"use ssr\" modules, rewritten for the server-components environment into\n * proxies that call the real module in the ssr environment. See useSsr.ts.\n *\n * Before every other transform, so the cross-environment import this emits\n * is still ahead of plugin-rsc's handling of it - and so the module's own\n * imports, react-dom/server among them, are never resolved here at all.\n */\nfunction useSsrModules(): Plugin {\n return {\n name: \"rsc-kit:use-ssr\",\n enforce: \"pre\",\n applyToEnvironment: (environment) => environment.name === \"rsc\" || environment.name === \"ssr\",\n transform(code, id) {\n if (!code.includes(\"use ssr\")) return;\n\n // In the environment the module runs in, the directive has done its\n // work and is a string the bundler warns about. Out it goes.\n if (this.environment.name === \"ssr\") {\n const stripped = withoutSsrDirective(code);\n\n return stripped === null ? undefined : { code: stripped, map: null };\n }\n\n try {\n const proxy = ssrProxyModule(code, id);\n\n return proxy === null ? undefined : { code: proxy, map: null };\n } catch (error) {\n if (error instanceof UseSsrError) this.error(error.message);\n\n throw error;\n }\n },\n };\n}\n\n/**\n * react-dom/server, imported where server components render, becomes a\n * module that throws the fix instead of React's refusal - naming the app\n * file that imported it (through @react-email/render, say) and the\n * directive that moves it. The build says the same once, as a warning.\n */\nconst RENDERER_STUB = \"\\0rsc-kit:react-dom-server?from=\";\n\n/** What react-dom/server exports, across its node, edge and browser entries. */\nconst SERVER_RENDERER_EXPORTS = [\n \"renderToString\",\n \"renderToStaticMarkup\",\n \"renderToReadableStream\",\n \"renderToPipeableStream\",\n \"renderToStaticNodeStream\",\n \"resume\",\n \"resumeToPipeableStream\",\n \"resumeAndPrerender\",\n \"resumeAndPrerenderToNodeStream\",\n \"prerender\",\n \"prerenderToNodeStream\",\n];\n\nexport function serverRendererInRsc(): Plugin {\n const warned = new Set<string>();\n\n const appImporter = (\n ctx: {\n environment: { mode: string; moduleGraph?: unknown };\n getModuleInfo(id: string): { importers: readonly string[] } | null;\n },\n importer: string | null,\n ): string | null => {\n let current = importer;\n\n for (let hop = 0; current && hop < 12; hop++) {\n if (!current.includes(\"/node_modules/\"))\n return relative(process.cwd(), current.split(\"?\")[0]);\n\n const next: string | undefined =\n ctx.environment.mode === \"build\"\n ? ctx.getModuleInfo(current)?.importers[0]\n : ((\n ctx.environment.moduleGraph as\n | {\n getModuleById(\n id: string,\n ): { importers: Set<{ id: string | null }> } | undefined;\n }\n | undefined\n )\n ?.getModuleById(current)\n ?.importers.values()\n .next().value?.id ?? undefined);\n\n if (!next) break;\n\n current = next;\n }\n\n return importer ? relative(process.cwd(), importer.split(\"?\")[0]) : null;\n };\n\n // Per package, so a dependency imported from twenty files is read once.\n const externalRenderers = new Map<string, boolean>();\n // Packages already named by the warning above, so the stub's own warning\n // - \"imported by node_modules/<package>/dist/index.mjs\" - stays quiet for\n // them: one problem, one line.\n const warnedPackages = new Set<string>();\n\n return {\n name: \"rsc-kit:server-renderer\",\n // Before Vite's own resolver, which otherwise answers react-dom/server\n // with React's react-server entry - a real module missing the export,\n // and a build that fails on MISSING_EXPORT with no mention of the fix.\n enforce: \"pre\",\n applyToEnvironment: (environment) => environment.name === \"rsc\",\n async resolveId(source, importer) {\n // Only an import from a module: a resolve with no importer is Vite\n // asking whether the specifier exists - deciding what to externalise -\n // and answering that with the stub would answer the wrong question.\n if (SERVER_RENDERER.test(source)) {\n return importer ? RENDERER_STUB + encodeURIComponent(importer) : undefined;\n }\n\n // A bare import from app code of a package the build leaves external:\n // its own import of react-dom/server is never resolved here, so the\n // stub above never sees it. @react-email/render, imported by an\n // action, built clean and threw React's refusal at the first visitor.\n // The package is read once for the import, and the build warns the\n // same way it does for a direct one - naming the app file and the\n // package - without stubbing a module that may also be used well.\n if (!importer || importer.includes(\"/node_modules/\") || importer.startsWith(\"\\0\")) return;\n if (!/^(?:@[\\w.-]+\\/)?[\\w.-]+/.test(source) || source.startsWith(\".\")) return;\n // The generated entries import plugin-rsc, whose ssr half imports the\n // renderer for its own reasons; that is the build's, not the app's.\n if (outDir && importer.startsWith(outDir)) return;\n\n const name = source.startsWith(\"@\") ? source.split(\"/\").slice(0, 2).join(\"/\") : source.split(\"/\")[0];\n\n if (name === \"react-dom\" || name === \"react\" || name.startsWith(\"@rsc-kit/\") || name.startsWith(\"@vitejs/\")) return;\n\n let imports = externalRenderers.get(name);\n\n if (imports === undefined) {\n // Vite answers a dependency either as external, by its bare name,\n // or by the file it resolved to under node_modules - which of the\n // two depends on how the environment was set up, and both are a\n // dependency whose imports the build will not look inside.\n const resolved = await this.resolve(source, importer, { skipSelf: true });\n const id = resolved?.id ?? \"\";\n const marker = `/node_modules/${name}/`;\n const at = id.lastIndexOf(marker);\n const dir = resolved?.external\n ? installedPackageDir(name, dirname(importer.split(\"?\")[0]))\n : at !== -1\n ? id.slice(0, at + marker.length - 1)\n : null;\n\n imports = dir !== null && importsServerRenderer(dir);\n externalRenderers.set(name, imports);\n }\n\n if (!imports) return;\n\n const message =\n `${relative(process.cwd(), importer.split(\"?\")[0])} imports ${name}, which imports react-dom/server, and ` +\n serverRendererMessage(null).replace(/^react-dom\\/server cannot run/, \"that cannot run\");\n\n if (!warned.has(message)) {\n warned.add(message);\n warnedPackages.add(name);\n this.warn(message);\n }\n },\n load(id) {\n if (!id.startsWith(RENDERER_STUB)) return;\n\n const importer =\n decodeURIComponent(id.slice(RENDERER_STUB.length)) || null;\n const message = serverRendererMessage(\n appImporter(this as never, importer),\n );\n\n // The last node_modules segment: Bun's store nests the real package\n // under node_modules/.bun/<pkg>@<v>/node_modules/<pkg>.\n const viaPackage = [...(importer ?? \"\").matchAll(/\\/node_modules\\/((?:@[^/]+\\/)?[^/]+)\\//g)].at(-1)?.[1];\n\n if (\n this.environment.mode === \"build\" &&\n !warned.has(message) &&\n !(viaPackage && warnedPackages.has(viaPackage))\n ) {\n warned.add(message);\n this.warn(message);\n }\n\n // Every name the renderer exports, each throwing the fix when called.\n // A module that threw when loaded took the whole server down at boot\n // for one action nobody had called yet, and a stub with no exports\n // failed the build on MISSING_EXPORT with the message scrolled past.\n const refuse = `() => { throw new Error(${JSON.stringify(message)}) }`;\n\n return (\n SERVER_RENDERER_EXPORTS.map((name) => `export const ${name} = ${refuse};`).join(\"\\n\") +\n `\\nexport const version = \"0.0.0\";\\nexport default { ${SERVER_RENDERER_EXPORTS.join(\", \")}, version };\\n`\n );\n },\n };\n}\n\n/**\n * The project's typecheck, as part of the build.\n *\n * Runs once, in the first environment to start, after the route types have\n * been written by the config hook - so a link to a route that does not exist\n * is an error here and not a 404 found after deploying. Skipped where the\n * project is not doing this checking at all: no tsconfig.json, or no\n * typescript to run. Its own output is the message, because that is what\n * the developer would have read from `tsc`.\n */\nexport type TypecheckOutcome =\n | { ran: false; because: \"no tsconfig\" | \"no typescript\" }\n | { ran: true; ok: true; seconds: number }\n | { ran: true; ok: false; output: string };\n\n/**\n * `tsc --noEmit` on the project's own tsconfig, the way `check` runs it.\n *\n * Through package.json rather than a subpath: TypeScript's exports map does\n * not expose bin/tsc, and the bin field is where the name lives. Its output\n * is the message, because that is what the developer would have read.\n */\nexport function typecheckProject(root: string): TypecheckOutcome {\n const tsconfig = join(root, \"tsconfig.json\");\n\n if (!existsSync(tsconfig)) return { ran: false, because: \"no tsconfig\" };\n\n let tsc: string;\n\n try {\n const fromApp = createRequire(join(root, \"package.json\"));\n const manifest = fromApp.resolve(\"typescript/package.json\");\n const bin = (fromApp(manifest) as { bin?: string | Record<string, string> })\n .bin;\n const relative = typeof bin === \"string\" ? bin : bin?.tsc;\n\n if (!relative) return { ran: false, because: \"no typescript\" };\n\n tsc = join(dirname(manifest), relative);\n } catch {\n return { ran: false, because: \"no typescript\" };\n }\n\n const started = Date.now();\n const script = /\\.[cm]?js$/.test(tsc) || !/\\.\\w+$/.test(tsc);\n const result = spawnSync(\n script ? process.execPath : tsc,\n // Plain lines, not coloured ones: they go into a build error, and the\n // test that reads them is a reader too.\n [...(script ? [tsc] : []), \"--noEmit\", \"--pretty\", \"false\", \"-p\", tsconfig],\n { cwd: root, encoding: \"utf-8\", maxBuffer: 64 * 1024 * 1024 },\n );\n\n if (result.status === 0)\n return { ran: true, ok: true, seconds: (Date.now() - started) / 1000 };\n\n return {\n ran: true,\n ok: false,\n output: `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim(),\n };\n}\n\n/**\n * The project's typecheck, as part of the build.\n *\n * Runs once, in the first environment to start, after the route types have\n * been written by the config hook - so a link to a route that does not exist\n * is an error here and not a 404 found after deploying. Skipped where the\n * project is not doing this checking at all: no tsconfig.json, or no\n * typescript to run.\n */\nfunction typecheckPlugin(): Plugin {\n let ran = false;\n\n return {\n name: \"rsc-kit:typecheck\",\n apply: \"build\",\n buildStart() {\n if (ran || !typecheck || isWatch) return;\n\n ran = true;\n\n const outcome = typecheckProject(projectRoot);\n\n if (!outcome.ran) return;\n\n if (outcome.ok) {\n log(`typecheck: ok (${outcome.seconds.toFixed(1)}s)`);\n\n return;\n }\n\n throw new Error(\n \"[rsc-kit] The typecheck failed, so the build stops here.\\n\\n\" +\n outcome.output +\n \"\\n\\nrscKit({ typecheck: false }) builds without it.\",\n );\n },\n };\n}\n\n/**\n * Which server files import a client library, read off the rsc environment's\n * module graph once it is built. plugin-rsc classifies the client packages\n * (every package with react among its peers) and excludes them from the\n * server optimizers; that list is the one used here, minus this package -\n * a server component importing Link is the norm - and plugin-rsc's own.\n */\nfunction clientImportsAudit(): Plugin {\n return {\n name: \"rsc-kit:client-imports\",\n apply: \"build\",\n applyToEnvironment: (environment) => environment.name === \"rsc\",\n buildEnd() {\n const excluded =\n (resolvedConfig?.environments?.rsc?.optimizeDeps?.exclude as\n string[] | undefined) ?? [];\n const clientPackages = excluded.filter(\n (name) => !name.startsWith(\"@vitejs/plugin-rsc\"),\n );\n\n if (clientPackages.length === 0) return;\n\n clientLibraryImports = serverImportsOfClientPackages(\n {\n moduleIds: () => this.getModuleIds(),\n importedIds: (id) => this.getModuleInfo(id)?.importedIds ?? [],\n importers: (id) => this.getModuleInfo(id)?.importers ?? [],\n },\n {\n sourceDir,\n clientPackages,\n ignore: [PACKAGE_NAME, \"server-only\", \"client-only\"],\n },\n );\n },\n };\n}\n\n/**\n * A Nitro runtime plugin, so instrumentation.ts runs when the server starts.\n *\n * Nitro loads the rsc service at the first request, not at startup - so\n * without this, register() would run when the first visitor arrived, and a\n * bad environment would take down a server that had already reported itself\n * up. The plugin runs at app init and sends the service one request, which\n * loads the module; loading it begins register(), and the request waits for\n * it. Not on a Worker: there is no startup, and the first request is the\n * first chance to read a binding.\n */\nconst STARTUP_PLUGIN = `import { viteServices } from \"#nitro/virtual/vite-services\"\n\nexport default function rscKitStartup() {\n if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') return\n\n // The ssr service is the one Nitro's renderer asks; its fetch imports the\n // rsc entry and hands the request on. The rsc service's own export is the\n // handler function, not a { fetch }, so it cannot be probed directly.\n const ssr = viteServices.ssr\n if (!ssr) return\n\n // Two ways to fail, one outcome. register() rejecting is reported by the\n // module itself. instrumentation.ts throwing at import - an env schema\n // refusing - means the module never evaluated, so nothing in it can\n // report; the load rejects here instead. Either way a server that could\n // not bootstrap has nothing correct to serve, and says so and stops\n // rather than reporting itself up.\n ssr\n .fetch(new Request('http://rsc-kit.internal/_rsc/startup', { headers: { 'x-rsc-kit-startup': '1' } }))\n .then((response) => {\n if (!response.ok) throw new Error('the startup probe answered ' + response.status)\n })\n .catch((error) => {\n console.error('[rsc-kit] instrumentation.ts failed at startup:', error)\n\n if (typeof process !== 'undefined' && typeof process.exit === 'function') process.exit(1)\n })\n}\n`;\n\ninterface NitroModuleHost {\n options: {\n dev?: boolean;\n plugins?: string[];\n virtual?: Record<string, string | (() => string)>;\n /** Packages Nitro traces into .output/server/node_modules rather than bundling. */\n traceDeps?: (string | RegExp)[];\n /** Precompressed .gz/.br beside every public asset, served by Nitro with the encoding. */\n compressPublicAssets?: boolean | Record<string, unknown>;\n preset?: string;\n output: { serverDir: string };\n rollupConfig?: Record<string, unknown>;\n routeRules?: Record<string, unknown>;\n };\n hooks: { hook(name: \"compiled\", fn: () => void): void };\n}\n\n/**\n * Where NODE_ENV=development came from, and what to do about it.\n *\n * Vite reads NODE_ENV from its env files in this order, later winning, and\n * only when the process did not already set it - so the last file that\n * names it is the one that decided. No file naming it means the shell or\n * `--mode` did.\n */\nfunction nodeEnvSetIn(mode: string, envDir?: string | false): string | null {\n const files = [\".env\", \".env.local\", `.env.${mode}`, `.env.${mode}.local`];\n let culprit: string | null = null;\n\n // The project's root, not Vite's: this plugin points Vite's root at the\n // build directory, and the app's .env is read from the project root - by\n // Nitro's dotenv loading into process.env, and by Vite where envDir says\n // so. Both places are looked at; the project's is where the file is.\n const dirs = [...new Set([projectRoot, envDir || projectRoot])];\n\n for (const dir of dirs) for (const name of files) {\n const path = join(dir, name);\n\n if (!existsSync(path)) continue;\n\n const lines = readFileSync(path, \"utf-8\").split(\"\\n\");\n const at = lines.findIndex((line) => /^\\s*(?:export\\s+)?NODE_ENV\\s*=/.test(line));\n\n if (at !== -1) culprit = `${path}:${at + 1}`;\n }\n\n return culprit;\n}\n\nfunction refuseDevelopmentBuild(config: ResolvedConfig): string {\n const culprit = nodeEnvSetIn(config.mode, config.envDir);\n\n return (\n \"[rsc-kit] vite build is running as a development build, and the output cannot work: \" +\n \"the pages are compiled against React's development JSX runtime (jsxDEV), the server \" +\n \"bundles carry React's production build, and every route fails to render.\\n\\n\" +\n (culprit\n ? `NODE_ENV=development is set in ${culprit}. Remove that line - Vite sets NODE_ENV ` +\n \"itself: development under `vite`, production under `vite build`.\"\n : `NODE_ENV is \"${process.env.NODE_ENV ?? \"\"}\" from the environment or --mode ` +\n \"(mode: \" + JSON.stringify(config.mode) + \"). Build with NODE_ENV=production, or unset it.\")\n );\n}\n\nexport function rscKit(options: RscKitOptions = {}): PluginOption[] {\n resolvePaths(options);\n\n const serverExternals: (string | RegExp)[] = [\n ...RUNTIME_BUILTINS,\n ...[...DEFAULT_SERVER_EXTERNALS, ...(options.serverExternalPackages ?? [])].map(externalPackage),\n ];\n\n // Dependencies with a \"use client\" file that plugin-rsc would leave\n // external, because they never declared react as a peer. Bundled into the\n // server graphs so the directive is read, the same as a package that did.\n const bundledClientPackages = clientPackages(projectRoot);\n\n for (const name of bundledClientPackages) {\n console.warn(\n `[rsc-kit] bundling ${name}: it has \"use client\" files but does not declare react ` +\n \"as a peer dependency, so its components would otherwise run on the server.\",\n );\n }\n\n const routesPlugin: Plugin & { nitro?: unknown } = {\n name: \"rsc-kit\",\n\n // A Nitro module, which Nitro's Vite plugin collects from any plugin\n // that carries one. Only for a built server: the dev server evaluates\n // the entry through Vite's runner when it is first asked for, and there\n // is no earlier moment to offer.\n nitro: {\n name: \"rsc-kit\",\n setup(nitro: NitroModuleHost) {\n if (nitro.options.dev) return;\n\n // Said at the end of a bun build, only when true: which module keeps\n // `bun build --compile --bytecode` from applying, and where. Bun\n // itself names no file and exits 0. See bytecodeCheck.ts.\n if (nitro.options.preset === \"bun\") {\n nitro.hooks.hook(\"compiled\", () => {\n const note = bytecodeNote(nitro.options.output.serverDir);\n\n if (note) log(note);\n });\n }\n\n // External at Nitro's layer too. The Vite build leaves these as\n // imports, and Nitro would then bundle them into its own chunks -\n // which for a native package fails at load, and for a polyfill like\n // reflect-metadata runs it after the chunk that checks for it.\n // Traced, each is copied into .output/server/node_modules and\n // imported by the built server the way its author expected.\n // Only the ones the tracer can find by name. It says so, once per\n // name, for every entry it cannot - a list of every native package\n // anyone might install is mostly ones this app does not have, and\n // one the app has only through a dependency, under an isolated\n // store, is reached through that dependency and not by name.\n // And the polyfills, by pattern: bundled, one merged into the chunk\n // of the dependency that checks for it, after that chunk's imports -\n // and the server did not boot. External, the entry's import of it\n // comes first. See polyfillsToTrace.\n nitro.options.traceDeps = [\n ...(nitro.options.traceDeps ?? []),\n ...traceableByName([...DEFAULT_SERVER_EXTERNALS, ...(options.serverExternalPackages ?? [])], projectRoot),\n ...polyfillsToTrace(FIRST_POLYFILLS, projectRoot),\n ];\n\n // The assets, precompressed at build and served with their encoding\n // by Nitro's own static handler; the host gzips the rest as it\n // answers. Between them a bun or node server answering the internet\n // by itself sends nothing raw. A config that set this keeps it.\n // Nitro's default is a literal false, so ?? would not do; an object\n // is a configuration and is kept.\n if (typeof nitro.options.compressPublicAssets !== \"object\") nitro.options.compressPublicAssets = true;\n\n nitro.options.virtual ??= {};\n\n // The worker script is never cached by heuristics. It was served\n // with no Cache-Control at all, and a browser keeps such a file for a\n // tenth of its age: a deploy's new worker then installs the previous\n // deploy's list against the new server, every file 404s, and the\n // install fails - leaving the old worker in charge, serving the old\n // documents, for as long as the browser holds the script.\n nitro.options.routeRules = {\n ...(nitro.options.routeRules ?? {}),\n \"/sw.js\": { ...((nitro.options.routeRules as Record<string, { headers?: Record<string, string> }> | undefined)?.[\"/sw.js\"] ?? {}), headers: { \"cache-control\": \"no-cache\", ...((nitro.options.routeRules as Record<string, { headers?: Record<string, string> }> | undefined)?.[\"/sw.js\"]?.headers ?? {}) } },\n };\n\n // The names of functions survive Nitro's bundle. The pages were\n // prerendered against Vite's own server bundles, where a dependency\n // is loaded from node_modules under the names it was written with;\n // Nitro then bundles that dependency into the server, and renames a\n // function whose name collides with another's - J becomes J2 - and\n // `name` follows the identifier. React's resume of a stored shell\n // compares the component names it recorded with the ones it meets,\n // and a renamed one is \"Expected the resume to render <J> in this\n // slot but instead it rendered <J2>\", on every request, with the\n // hole rendered in the browser instead. keepNames pins `name` to\n // what the source said, whatever the identifier became.\n nitro.options.rollupConfig = {\n ...(nitro.options.rollupConfig ?? {}),\n output: { keepNames: true, ...((nitro.options.rollupConfig as { output?: object } | undefined)?.output ?? {}) },\n } as never;\n\n // A polyfill a dependency checks for at module evaluation, loaded\n // before any service. The bundler places an external import after\n // the chunk imports of the module that had it, whatever the source\n // said, so reflect-metadata came up after tsyringe (under\n // @peculiar/x509, under @simplewebauthn/server) - by luck survivable\n // run as a directory, fatal compiled into a binary. A Nitro plugin\n // is evaluated by the entry itself, and the services that carry the\n // app are loaded lazily after it; imported by file, the polyfill is\n // inlined there and runs first wherever the server runs. Only for a\n // project whose graph has it.\n const polyfills = FIRST_POLYFILLS.map((name) => packageEntryInGraph(projectRoot, name)).filter(\n (entry): entry is string => entry !== null,\n );\n\n if (polyfills.length) {\n nitro.options.virtual[\"#rsc-kit/polyfills\"] =\n polyfills.map((entry) => `import ${JSON.stringify(entry)};`).join(\"\\n\") +\n \"\\nexport default () => {};\\n\";\n nitro.options.plugins = [\"#rsc-kit/polyfills\", ...(nitro.options.plugins ?? [])];\n }\n\n if (!instrumentationFile()) return;\n\n nitro.options.virtual[\"#rsc-kit/startup\"] = STARTUP_PLUGIN;\n nitro.options.plugins = [...(nitro.options.plugins ?? []), \"#rsc-kit/startup\"];\n },\n },\n\n config(_config, env) {\n if (!existsSync(appDir)) {\n throw new Error(\n `[rsc-kit] No app directory at ${appDir} — nothing to build.`,\n );\n }\n\n // Both maps, not one: the config hook runs again when the config\n // changes under a dev server, and a route.ts or a synthesised\n // robots.txt left over from the previous run read as a duplicate.\n components.clear();\n apiRoutes.clear();\n discover(appDir);\n registerMetadataRoutes(appDir);\n registerOpenApiRoutes();\n siteHosts = ownHosts(rootMetadataBase(appDir), hostsOption);\n\n // Silent when it worked. The names were printed on every dev start and\n // every build — thirty of them for a middling app, above the output that\n // actually says something, and the build's classification table lists\n // every route anyway.\n //\n // Nothing found is the case worth a word, because the app still builds:\n // a server with no routes answers 404 to everything, which reads as a\n // routing bug rather than as an empty directory. Fatal for a build,\n // said out loud for a dev server — where deleting the last page while\n // editing is a state to pass through, not to be thrown out of.\n if (components.size === 0) {\n const message =\n `No routes under ${appDir}. A directory with a page.tsx in it is a route; ` +\n \"without one there is nothing to serve.\";\n\n if (env.command === \"build\") throw new Error(`[rsc-kit] ${message}`);\n\n log(message);\n }\n\n const notClient = validateErrorBoundaries();\n\n if (notClient.length) {\n throw new Error(\n \"[rsc-kit] An error.tsx must be a client component.\\n\\n\" +\n notClient.join(\"\\n\") +\n \"\\n\\nAdd 'use client' at the top. It is rendered inside an error boundary and is\\n\" +\n \"handed a reset() callback to call, neither of which a server component can do.\",\n );\n }\n\n const loadingErrors = validateLoadingBoundaries();\n\n if (loadingErrors.length) {\n throw new Error(\n \"[rsc-kit] A page that blocks before it can paint needs a loading.tsx boundary.\\n\\n\" +\n loadingErrors.join(\"\\n\") +\n \"\\n\\nAdd loading.tsx in the page directory (or a parent), or move the slow work\\n\" +\n \"into a child component wrapped in its own <Suspense> so the page can paint.\",\n );\n }\n\n // Before the entries, because the app's own source imports these and the\n // module graph is walked as soon as this hook returns.\n const manifest = routeManifest();\n\n writeHostBindings(manifest);\n\n if (existsSync(genDir)) rmSync(genDir, { recursive: true, force: true });\n mkdirSync(genDir, { recursive: true });\n\n // Where a url this server does not own is handed on. Resolved exactly as\n // host calls resolve their endpoint, from the app's own .env, so the two\n // cannot end up pointing at different backends. Development only: a\n // build's server.ts decides this for itself.\n const backendEnv = loadEnv(env.mode, projectRoot, \"\");\n\n // Only a backend this server could actually call. The shared secret is\n // what makes one a backend rather than a url that happens to be in the\n // environment — APP_URL is not a Laravel-only name, and a JavaScript\n // host that sets it for its own reasons must not find its 404s being\n // posted to it. Host calls gate on exactly the same pair, so the two\n // cannot end up disagreeing about whether a backend is there.\n //\n // Naming devFallback explicitly opts in regardless: someone who wrote\n // the address down means it.\n const backendSecret =\n hostCallOptions?.secret ?? backendEnv.RSC_HOST_CALL_SECRET;\n const detected = backendSecret\n ? (hostCallOptions?.endpoint ??\n backendEnv.RSC_BACKEND ??\n backendEnv.APP_URL ??\n \"\")\n : \"\";\n\n const fallbackOrigin =\n options.devFallback === false ? \"\" : (options.devFallback ?? detected);\n\n writeFileSync(\n join(genDir, \"entry.rsc.tsx\"),\n generateEntryRsc(fallbackOrigin),\n );\n writeFileSync(join(genDir, \"entry.ssr.tsx\"), generateEntrySsr());\n writeFileSync(join(genDir, \"entry.browser.tsx\"), generateEntryBrowser());\n\n // Written beside the entries, for a host to read instead of walking the\n // route tree itself. Laravel scans it a second time today; a JS host\n // would otherwise have to write a third walk of the same directories.\n writeFileSync(\n join(outDir, \"routes.json\"),\n JSON.stringify(manifest, null, 2),\n );\n\n return {\n // Off, not merely unused: Vite warns when publicDir sits inside outDir,\n // and assetsDir is normally a directory under the build output. An app\n // that wants static files can set its own publicDir outside it.\n publicDir: false,\n /**\n * The mode this was built in, baked into the server bundles.\n *\n * Vite substitutes `process.env.NODE_ENV` for a client build and\n * leaves it alone for the server ones, because server code runs where\n * `process.env` is real. Reasonable in general, and wrong here: React\n * picks its build from that expression when its module is first\n * evaluated, so leaving it to the runtime makes every server carry a\n * NODE_ENV it must not get wrong — and a production bundle started\n * without one renders every page perfectly and hydrates none of them.\n *\n * The build already knows which mode it is. Saying so here means the\n * answer travels with the bundle instead of with whoever starts it.\n */\n define: {\n \"process.env.NODE_ENV\": JSON.stringify(\n env.mode === \"development\" ? \"development\" : \"production\",\n ),\n __RSC_OFFLINE__: JSON.stringify(offline),\n },\n /*\n * This package's client modules are served as source, never\n * pre-bundled.\n *\n * Vite treats an installed package as a dependency and optimizes it,\n * which binds its JSX imports to one particular optimized\n * react/jsx-runtime chunk. The moment Vite discovers another dependency\n * and re-optimizes, that chunk's hash changes and the binding breaks:\n *\n * SyntaxError: The requested module '.../react_jsx-runtime.js?v=...'\n * does not provide an export named 't'\n *\n * Which reads as a React or a bundler bug. What it does is take down\n * every page importing Link or Form — the shell renders, hydration\n * throws, React unmounts the document, and the page goes blank with\n * that message the only clue.\n *\n * Excluded rather than pinned, because the package already ships ESM\n * that needs no conversion. The app's own excludes are kept.\n */\n optimizeDeps: {\n exclude: [PACKAGE_NAME, ...(_config.optimizeDeps?.exclude ?? [])],\n // Every \"use client\" file, so the browser's dependencies are all\n // found at startup. The client entry reaches only the engine and\n // React; the app's client components arrive through payloads, page\n // by page, and a dependency first seen on the third page visited\n // re-optimised every pre-bundle under a running page - two Reacts,\n // a blank document, then Vite's own reload. See clientEntries.\n // Naming entries replaces the input, so the browser entry is named\n // too, or the engine and React would be the ones left out.\n entries: [\n ...(Array.isArray(_config.optimizeDeps?.entries)\n ? _config.optimizeDeps.entries\n : _config.optimizeDeps?.entries\n ? [_config.optimizeDeps.entries]\n : []),\n // Entries are globs: a route group's parentheses, or a bracket\n // in a dynamic segment, would otherwise read as pattern syntax\n // and match nothing - and the scanner would crawl nothing, quietly.\n ...[\n join(genDir, \"entry.browser.tsx\"),\n ...engineClientEntries(),\n ...clientEntries(sourceDir),\n ].map((file) => file.replace(/[()[\\]{}*?!+@]/g, \"\\\\$&\")),\n ],\n rolldownOptions: {\n ...(_config.optimizeDeps?.rolldownOptions ?? {}),\n plugins: [\n clientScanPlugin(),\n ...arrayOf(_config.optimizeDeps?.rolldownOptions?.plugins),\n ],\n },\n },\n // Public URL for browser-facing client assets, and a BUILD concern\n // only: it says where the built files will be served from.\n //\n // Applying it in dev makes it Vite's public base, and then the dev\n // server answers pages only under that prefix — every route 404s with\n // \"The server is configured with a public base URL\", which reads as a\n // routing bug rather than as this line. In dev the pages are the root;\n // the assets come from the same origin either way.\n base: \"/\",\n // Where the generated entries live, so Vite resolves them as its own\n // source. A build concern only.\n //\n // Not during preview. `vite preview` serves what was built, and Nitro's\n // preview reads its build info from `<vite root>/node_modules/.nitro` —\n // so pointing the root at this directory sent it looking somewhere no\n // build ever writes, and every preview failed with \"Cannot load nitro\n // build info. Make sure to build first.\" after a build that had just\n // succeeded.\n ...(env.isPreview ? {} : { root: outDir }),\n // Force single instances of React/RSC runtime — critical when the\n // package is symlinked (local dev / monorepo), else \"use client\"\n // components SSR against a second React copy and hooks throw.\n //\n // react-server-dom-webpack is deliberately absent: @vitejs/plugin-rsc\n // vendors its own copy, nothing here imports the specifier, and the\n // built bundles reference it zero times — deduping it was a no-op left\n // over from the hand-rolled engine.\n resolve: {\n dedupe: [\"react\", \"react-dom\", \"@vitejs/plugin-rsc\"],\n // `import Link from '<packageAlias>/Link'` resolves to the client\n // runtime shipped here, for hosts that vendor this package outside\n // node_modules. Installed from npm the name resolves on its own.\n alias: aliasEntries(),\n },\n build: {\n emptyOutDir: true,\n // Rolldown reports, after every build, which plugin hooks took\n // the time. Here the answer is always the same: the typecheck hook\n // - tsc, run before the bundle on purpose, as `next build` does -\n // and the two resolvers that look at every import. A paragraph\n // saying so at the end of each docker build is not a finding.\n rollupOptions: { checks: { pluginTimings: false } },\n },\n // What reaches the browser. Vite's own VITE_ prefix, and PUBLIC_ - the\n // scaffold's spelling, and Next's minus its brand - so a variable\n // named for a port reads through import.meta.env without a config\n // line. A config that set its own prefixes keeps them; Vite merges.\n envPrefix: [\"VITE_\", \"PUBLIC_\"],\n environments: {\n // Server bundles — stay under the (non-public) out dir. `bun` and\n // `bun:*` are the runtime's own modules, like `node:*`: nothing to\n // bundle, and a build under Node has nothing to resolve them to.\n // Left as imports for the runtime that has them.\n rsc: {\n build: {\n rollupOptions: {\n input: { index: join(genDir, \"entry.rsc.tsx\") },\n external: serverExternals,\n },\n },\n resolve: { noExternal: bundledClientPackages },\n optimizeDeps: { exclude: bundledClientPackages },\n },\n ssr: {\n build: {\n rollupOptions: {\n input: { index: join(genDir, \"entry.ssr.tsx\") },\n external: serverExternals,\n },\n },\n resolve: { noExternal: bundledClientPackages },\n optimizeDeps: { exclude: bundledClientPackages },\n },\n // Client bundle — emitted into public/ for the web server to serve.\n client: {\n build: {\n outDir: publicAssetsDir,\n emptyOutDir: true,\n rollupOptions: {\n input: { index: join(genDir, \"entry.browser.tsx\") },\n output: { chunkFileNames: clientChunkFileName },\n },\n },\n },\n },\n };\n },\n\n /**\n * Restart when the route tree changes shape.\n *\n * The entries and the route table are generated in `config()`, which runs\n * once. An edit to a page is picked up because Vite re-evaluates the\n * module, but a page that did not exist when the server started is not in\n * the table — the request 404s, and the file is right there on disk, which\n * is a confusing thing to be told.\n *\n * Only add and unlink: a change to an existing file needs no new table,\n * and restarting on every keystroke would throw away the module graph for\n * nothing.\n */\n configureServer(server) {\n // The icons and share images live in app/, which nothing serves; the\n // build copies them beside the client output. There is no output while\n // developing, so the same hrefs the head tags carry are answered from\n // app/ here - and the web manifest with them - or the tab has no icon\n // and the console a 404 for a file that is right there.\n server.middlewares.use((req, res, next) => {\n const url = (req.url ?? \"\").split(\"?\")[0];\n\n // A worker registered by a production run on this origin - `bun run\n // start` on the port the dev server uses next - outlives that run and\n // answers the dev server's documents from its cache: a stored page is\n // cache-first, so a refresh brings back yesterday's document with\n // yesterday's module hashes, and a 504 for each. The browser fetches\n // /sw.js again on every navigation to look for an update; in\n // development that fetch gets a worker whose only job is to remove\n // itself, its caches, and reload the pages it controlled.\n // robots.txt, a hand-written sitemap.xml, humans.txt: beside the root\n // layout, served at the root. The build copies them beside the client\n // output; here they are read from app/.\n if (url.startsWith(\"/\") && rootFiles.includes(url.slice(1))) {\n res.setHeader(\"Content-Type\", rootFileType(url.slice(1)));\n res.end(readFileSync(join(sourceDir, \"app\", url.slice(1))));\n\n return;\n }\n\n if (url === \"/sw.js\") {\n res.setHeader(\"Content-Type\", \"text/javascript\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(DEV_WORKER);\n\n return;\n }\n\n if (webManifestOptions && url === MANIFEST_PATH) {\n res.setHeader(\"Content-Type\", \"application/manifest+json\");\n res.end(webManifest(webManifestOptions));\n\n return;\n }\n\n const asset = allAppAssets(foundAssets).find((a) => a.href === url);\n const file = asset ? join(sourceDir, \"app\", asset.file) : null;\n\n if (!asset || !file || !existsSync(file)) return next();\n\n res.setHeader(\"Content-Type\", typeOf(asset.file));\n createReadStream(file).pipe(res);\n });\n\n // rpc() has to reach the backend while the dev server is serving.\n //\n // A built deployment installs this itself: the server running\n // createRscHandler passes `hostCalls`. Nothing does that here, and with\n // no host installed every rpc() is refused — so a page whose data comes\n // from the backend renders its shell and then blanks, which reads as a\n // hydration bug rather than a missing wire.\n server.httpServer?.once(\"listening\", async () => {\n const env = server.environments?.rsc as\n | {\n runner?: { import(id: string): Promise<Record<string, unknown>> };\n }\n | undefined;\n\n if (!env?.runner) return;\n\n // The app's own .env, unprefixed. A Laravel app already has both of\n // these, which is what makes this need no configuring: APP_URL is the\n // backend and RSC_HOST_CALL_SECRET is the secret it checks.\n const fromEnv = loadEnv(server.config.mode, projectRoot, \"\");\n const secret = hostCallOptions?.secret ?? fromEnv.RSC_HOST_CALL_SECRET;\n const origin =\n hostCallOptions?.endpoint ?? fromEnv.RSC_BACKEND ?? fromEnv.APP_URL;\n\n if (!secret || !origin) return;\n\n const path =\n hostCallOptions?.path ??\n fromEnv.RSC_HOST_CALL_PATH ??\n \"/__rsc/host-call\";\n const endpoint = origin.replace(/\\/$/, \"\") + path;\n\n try {\n const entry = await env.runner.import(join(genDir, \"entry.rsc.tsx\"));\n const install = entry.installHostFn as\n ((fn: unknown) => void) | undefined;\n\n install?.(httpHostCalls({ endpoint, secret }));\n } catch (error) {\n // Reported rather than thrown: the dev server is still useful for\n // every page that needs no data, and a failure here would otherwise\n // look like the server refusing to start.\n server.config.logger.warn(\n `[rsc-kit] could not wire host calls to ${endpoint}: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n });\n\n // Written once the server is listening, because only then is the port\n // known. Removed on shutdown so a backend can tell a dev server that is\n // gone from one that is merely slow to answer.\n if (hotFile) {\n const remove = () => {\n try {\n if (existsSync(hotFile)) rmSync(hotFile);\n } catch {}\n };\n\n server.httpServer?.once(\"listening\", () => {\n // The url Vite resolved, not one built from the port. A dev server\n // whose port is already taken on IPv4 binds IPv6 only and keeps the\n // number — so http://127.0.0.1:<port> is a reachable-looking address\n // that nothing answers, and the backend reports the renderer as down\n // while it is plainly running.\n const resolved = server.resolvedUrls?.local?.[0];\n const address = server.httpServer?.address();\n\n const url =\n resolved ??\n (typeof address === \"object\" && address\n ? `http://${address.family === \"IPv6\" ? `[${address.address}]` : address.address}:${address.port}`\n : null);\n\n if (!url) return;\n\n mkdirSync(dirname(hotFile), { recursive: true });\n writeFileSync(hotFile, url.replace(/\\/$/, \"\"));\n });\n\n for (const signal of [\"SIGINT\", \"SIGTERM\", \"exit\"] as const) {\n process.once(signal, remove);\n }\n\n server.httpServer?.once(\"close\", remove);\n }\n\n const shapes = new Set(ROUTE_FILES.map((name) => name));\n\n const affectsRouting = (file: string): boolean => {\n if (!file.startsWith(sourceDir)) return false;\n\n const base = file.split(\"/\").pop() ?? \"\";\n const stem = base.replace(/\\.(tsx|jsx|ts|js)$/, \"\");\n\n // The host's route-config file, whatever it named it. Hardcoding one\n // here would put a backend's convention back into a plugin that is\n // published without any — generic-host.test.ts fails if it reappears.\n return (\n (base !== stem && shapes.has(stem)) ||\n SECTION_FILE.test(base) ||\n (routeConfig !== null && base === routeConfig.file)\n );\n };\n\n const restart = (file: string) => {\n if (!affectsRouting(file)) return;\n\n server.config.logger.info(\n `[rsc-kit] route tree changed (${file.slice(sourceDir.length + 1)}) — restarting`,\n );\n void server.restart();\n };\n\n // Watched explicitly: the Vite root is the *out* directory, so the app's\n // source tree is outside it and nothing would report a file appearing.\n server.watcher.add(sourceDir);\n\n server.watcher.on(\"add\", restart);\n server.watcher.on(\"unlink\", restart);\n\n // The host actions are read once, in config(), from the file the\n // backend writes; the \"use server\" stubs are generated from it. A\n // backend that writes a new action - `make:rsc-action` under a running\n // dev server - rewrites the file, and until the server started again\n // the stub was not there to import. Any event: the file appears on a\n // first action, changes on the next, and goes when the last is removed.\n const hostActionsPath = join(projectRoot, HOST_ACTIONS_FILE);\n const hostActionsChanged = (file: string) => {\n if (file !== hostActionsPath) return;\n\n server.config.logger.info(\n `[rsc-kit] ${HOST_ACTIONS_FILE} changed — restarting`,\n );\n void server.restart();\n };\n\n server.watcher.add(hostActionsPath);\n server.watcher.on(\"add\", hostActionsChanged);\n server.watcher.on(\"change\", hostActionsChanged);\n server.watcher.on(\"unlink\", hostActionsChanged);\n },\n\n /**\n * Freeze what can be frozen, once every bundle exists.\n *\n * `buildApp` runs after all three environments are built, which is the\n * first moment the rsc bundle can be imported — prerendering is the app\n * rendering itself, so it needs the thing the build just produced. This\n * plugin is ordered after @vitejs/plugin-rsc's, so its own buildApp has\n * already run and the bundles are on disk.\n *\n * Automatic because the alternative is a second command to remember, and\n * forgetting it costs the whole difference silently: every page still\n * works, each one just renders again for every visitor.\n *\n * Skipped in watch mode. A rebuild on every keystroke that also re-renders\n * every route is not a feedback loop anyone wants.\n */\n async buildApp(builder) {\n if (isWatch) return;\n\n // Say what the build did, even when it stored nothing.\n //\n // Turning prerendering off used to print no classification at all — no\n // marks, no legend, no counts — so a build that stored nothing looked\n // exactly like a build that had not got to that step. Every route renders\n // per visitor now, which is a thing worth being told rather than left to\n // infer from an absence.\n if (!prerenderAfterBuild) {\n reportAllDynamic();\n\n return;\n }\n\n // Asked of the build rather than assumed from `outDir`. The two layouts\n // differ — <outDir>/dist/rsc on its own, node_modules/.nitro/… under\n // Nitro — and hard-coding the first is what silently skipped the second.\n // Both environments emit `index.js`, so this is one path, not a branch.\n const rscOut =\n builder?.environments?.rsc?.config?.build?.outDir ??\n join(outDir, \"dist/rsc\");\n const bundle = resolveRscBundle(rscOut);\n\n // Where the frozen pages go, which is not the same question.\n //\n // On its own the plugin owns the output and server.ts reads <outDir>/static\n // from the repository. Under Nitro the deployment is `.output/` and\n // nothing outside it is copied to the server — so pages written anywhere\n // else exist on the build machine and nowhere after that. They go beside\n // the server bundle instead, and buildApp runs before Nitro assembles, so\n // they are in place by the time it does.\n const clientOut = builder?.environments?.client?.config?.build?.outDir;\n const staticDir = clientOut\n ? join(dirname(clientOut), \"server\", NITRO_STATIC_DIR)\n : join(outDir, NITRO_STATIC_DIR);\n\n const { frozen, results } = await prerenderAfterBundles(\n bundle,\n staticDir,\n clientOut ?? publicAssetsDir,\n builder ? knownActionsOf(builder.config, projectRoot) : [],\n );\n\n // The same pages once more, as a module. A Worker has no filesystem, and\n // until this existed every Cloudflare deploy rendered its \"static\" pages\n // live, silently - the reader found no directory and fell through. The\n // module is uploaded as a sibling of the bundle and imported at runtime\n // when the directory is not there. Only under Nitro, whose presets are\n // the ones without a disk; on its own the plugin serves from outDir.\n if (clientOut && existsSync(staticDir)) {\n const { inlineModuleName, inlineModuleSource, compileEntrySource } =\n await import(\"./files.js\");\n\n writeFileSync(\n join(dirname(staticDir), inlineModuleName(NITRO_STATIC_DIR)),\n await inlineModuleSource(staticDir),\n );\n\n // And the entry a binary is compiled from, so the pages above end up\n // inside it rather than rendered live: bun build --compile\n // .output/server/compile.mjs. The scaffold's script names it.\n writeFileSync(\n join(dirname(staticDir), \"compile.mjs\"),\n compileEntrySource(NITRO_STATIC_DIR),\n );\n }\n\n // Manifest first. The service worker precaches whatever it finds in this\n // directory, so writing it afterwards leaves it out of the list — and an\n // installed app whose manifest is the one file that needs the network is\n // the wrong way round.\n copyAppAssets(clientOut ?? publicAssetsDir);\n if (webManifestOptions)\n writeWebManifest(clientOut ?? publicAssetsDir, webManifestOptions);\n if (offline) {\n writeServiceWorker(\n clientOut ?? publicAssetsDir,\n frozen,\n offlineFallback(frozen, results),\n );\n }\n },\n\n configResolved(config: ResolvedConfig) {\n // A build that is not a production build cannot work here, and the\n // way it fails is opaque: plugin-react emits the development JSX\n // runtime (jsxDEV), the server bundles resolve React's production\n // build, and every route fails to render with React's \"message\n // omitted in production builds\". The usual cause is NODE_ENV=development\n // in a .env file, which Vite honours - a line the scaffold itself once\n // wrote. Named, with the file and line, before any of that happens.\n //\n // Refused rather than overridden, because a plugin cannot override it:\n // Vite notes whether NODE_ENV was set before it loads the config file\n // and applies the .env value after the config hooks have run, so an\n // assignment here is overwritten - and patching the resolved config\n // afterwards leaves the client bundle's process.env.NODE_ENV and\n // import.meta.env.DEV already decided, which is a production server\n // serving a development client.\n if (config.command === \"build\" && !config.isProduction) {\n throw new Error(refuseDevelopmentBuild(config));\n }\n\n isWatch = config.build?.watch != null;\n resolvedConfig = config;\n\n // Keep Nitro's hot-update handler out of the rsc environment.\n //\n // For every environment that is not the browser's, Nitro treats a\n // changed module the browser does not also have as \"the server changed,\n // reload the page\": it sends full-reload and returns an EMPTY module list.\n // A returned list replaces the modules every later hook sees — so\n // plugin-rsc's handler, which is the one that knows a server component\n // can be refetched in place, gets zero modules, returns early, and never\n // sends rsc:update.\n //\n // That was a crude reload on a plain app and no reload at all on one\n // with Tailwind, whose own hook runs earlier still and rewrites the\n // change as a CSS update — so Nitro saw nothing server-only either, and\n // an edit to a page did nothing in the browser.\n //\n // The rsc environment's reload story is plugin-rsc's, not Nitro's.\n // Nitro's hook is left alone for every other environment.\n type HotHook = (\n this: { environment?: { name?: string } },\n ctx: unknown,\n ) => unknown;\n const nitroMain = config.plugins.find((p) => p.name === \"nitro:main\") as\n { hotUpdate?: HotHook } | undefined;\n\n if (nitroMain?.hotUpdate) {\n const original = nitroMain.hotUpdate;\n\n nitroMain.hotUpdate = function (this, ctx) {\n if (this.environment?.name === \"rsc\") return;\n\n return original.call(this, ctx);\n } as HotHook;\n }\n // rsc() splits the module graph into client and server; a JSX transform\n // placed ahead of it sees the wrong graph and fails in ways that are hard\n // to trace back here. Cheaper to refuse than to let it through.\n const names = config.plugins.map((p) => p.name);\n const rscAt = names.findIndex((n) => n === \"rsc\" || n.startsWith(\"rsc:\"));\n const jsxAt = names.findIndex((n) => JSX_PLUGIN_PATTERN.test(n));\n\n if (rscAt !== -1 && jsxAt !== -1 && jsxAt < rscAt) {\n throw new Error(\n `[rsc-kit] Plugin \"${names[jsxAt]}\" is resolved ahead of rsc(), so it would ` +\n \"transform JSX before the client/server split.\\n\" +\n \"Put rscKit() first in your plugins array. If it already is, that plugin \" +\n \"sets enforce: 'pre' and needs to be moved after rsc() explicitly.\",\n );\n }\n },\n };\n\n // rsc() ships as several plugins, and it has to lead. A promise is a legal\n // member of a Vite plugins array and is flattened in place, so this keeps\n // rscKit() one entry in the app's config while still resolving the\n // plugin at call time — see appPluginRsc for why that matters.\n // With Nitro, the server handler is Nitro's — it takes the rsc entry's\n // default export and builds the server around it. Leaving plugin-rsc's own\n // handler in place means two things claiming the same role.\n return [\n appPluginRsc({\n serverHandler: false,\n // One chunk per client component, rather than one for the whole app.\n //\n // plugin-rsc already loads a client reference with `await import()`, so\n // the browser only fetches what a page actually renders — but its default\n // groups every reference by the SERVER chunk that proxies it, and this\n // package builds the server as a single chunk. So every client component\n // in an app landed in one group, and a page with a button pulled in the\n // editor, the chart and the map that live on other routes.\n //\n // Grouping by the component's own module restores the split the dynamic\n // import was there to make use of.\n clientChunks: (meta) => meta.normalizedId,\n ...actionEncryptionKey(),\n }),\n barrelImportsPlugin(),\n useSsrModules(),\n serverRendererInRsc(),\n metadataRoutesPlugin(),\n openApiPlugin(),\n extendableClientReferences(),\n typecheckPlugin(),\n clientImportsAudit(),\n routesPlugin,\n ];\n}\n\n/**\n * @vitejs/plugin-rsc, resolved from the app rather than from here.\n *\n * `isRunnableDevEnvironment` is an instanceof check that plugin-rsc runs\n * against its own copy of Vite. Two copies — this package's and the app's —\n * make a perfectly runnable environment report false, and the message names\n * the environment rather than the duplication.\n *\n * That is not a hypothetical layout. It is what installing this package from a\n * directory produces, because the checkout carries its own devDependencies:\n * the app runs its Vite, this file imports that Vite's plugin, and the two\n * never recognise each other. A build never reaches the check, so everything\n * works right up until dev mode.\n *\n * Resolving from the project root gets the app's copy, whose own `vite` import\n * then resolves to the app's Vite as well — one pair, and the check passes.\n */\n/**\n * Where the key that encrypts bound action arguments comes from.\n *\n * A server action can close over server-side values, and React sends those to\n * the browser encrypted so the page cannot read them. The process that decrypts\n * them on the way back has to hold the same key.\n *\n * By default plugin-rsc generates one per build and bakes it in. Every instance\n * of one build therefore agrees, and the only exposure is a deploy: a browser\n * holding a page from the old build calls an action on the new one, and the\n * key has changed underneath it. The call fails with nothing useful in it.\n *\n * Setting RSC_ACTION_ENCRYPTION_KEY makes the key outlive the build and closes\n * that window. It is read at RUNTIME, not baked in, so the same artifact can be\n * deployed anywhere — but it must then be set everywhere the app runs, and set\n * to the same value. Half-configured is worse than unconfigured: instances\n * would disagree, and the failure looks like an intermittently broken action.\n *\n * Unset, the build-time key is used and nothing changes. That is the default\n * because it is the one that cannot be got half right.\n */\nfunction actionEncryptionKey(): { defineEncryptionKey?: string } {\n if (!process.env.RSC_ACTION_ENCRYPTION_KEY) return {};\n\n // An expression, not a value: plugin-rsc substitutes this source text where\n // the key is read, so what ships is the lookup rather than the secret. A\n // literal here would put the key in the bundle, which is the thing being\n // avoided.\n return { defineEncryptionKey: \"process.env.RSC_ACTION_ENCRYPTION_KEY\" };\n}\n\nasync function appPluginRsc(\n options: Parameters<typeof rsc>[0] = {},\n): Promise<PluginOption[]> {\n try {\n // Resolved against a file *in* the root, since a directory specifier\n // resolves relative to its parent.\n const fromApp = createRequire(join(projectRoot, \"package.json\"));\n const entry = fromApp.resolve(\"@vitejs/plugin-rsc\");\n const mod = (await import(pathToFileURL(entry).href)) as {\n default: typeof rsc;\n };\n\n return (mod.default ?? rsc)(options);\n } catch {\n // The app does not have its own; one copy, and the bundled import is it.\n return rsc(options);\n }\n}\n"]}