|
| 1 | +import { renderToReadableStream } from '@vitejs/plugin-rsc/rsc' |
| 2 | +import { getServerMessage } from '../routes/page' |
| 3 | + |
| 4 | +export default async function handler(request: Request) { |
| 5 | + const url = new URL(request.url) |
| 6 | + |
| 7 | + // handle rsc fetch calls by browser clients |
| 8 | + if (url.pathname === '/__rsc-function') { |
| 9 | + const id = request.headers.get('x-rsc-function-id') |
| 10 | + if (!id) return new Response('Missing RSC function id', { status: 400 }) |
| 11 | + |
| 12 | + const args = (await request.json()) as unknown[] |
| 13 | + const stream = await executeRscFn(id, args) |
| 14 | + return new Response(stream, { |
| 15 | + headers: { 'content-type': 'text/x-component;charset=utf-8' }, |
| 16 | + }) |
| 17 | + } |
| 18 | + |
| 19 | + // fully delegate to SSR |
| 20 | + const ssrEntry = await import.meta.viteRsc.loadModule< |
| 21 | + typeof import('./entry.ssr') |
| 22 | + >('ssr', 'index') |
| 23 | + return new Response(await ssrEntry.renderHtml(), { |
| 24 | + headers: { 'content-type': 'text/html' }, |
| 25 | + }) |
| 26 | +} |
| 27 | + |
| 28 | +// hard-coded RSC function registry for demo simplicity |
| 29 | +// TODO: Replace this with a split-module resolver: encoded module IDs with lazy |
| 30 | +// loading in dev, and a generated manifest in build. |
| 31 | +const rscFunctions = { getServerMessage: getServerMessage.handler } |
| 32 | + |
| 33 | +// The browser reaches this executor over HTTP, while SSR invokes it directly |
| 34 | +// through Vite's RSC environment to avoid an internal HTTP round trip. |
| 35 | +export async function executeRscFn( |
| 36 | + id: string, |
| 37 | + args: unknown[], |
| 38 | +): Promise<ReadableStream<Uint8Array>> { |
| 39 | + const rscFn = rscFunctions[id as keyof typeof rscFunctions] as |
| 40 | + | ((...args: unknown[]) => unknown) |
| 41 | + | undefined |
| 42 | + if (!rscFn) { |
| 43 | + throw new Error(`Unknown RSC function: ${id}`) |
| 44 | + } |
| 45 | + |
| 46 | + const result = await rscFn(...args) |
| 47 | + return renderToReadableStream(result) |
| 48 | +} |
| 49 | + |
| 50 | +if (import.meta.hot) { |
| 51 | + import.meta.hot.accept() |
| 52 | +} |
0 commit comments