import { createMemoryHistory, RouterProvider } from '@tanstack/react-router' import { QueryClient, dehydrate } from '@tanstack/react-query' import { renderToReadableStream } from 'react-dom/server.edge' import { packageContext } from 'kody:runtime' import { readVisitor, type Visitor } from './auth.ts' import { addItem, deleteItem, listItems } from './data/items.ts' import { createAppRouter } from './router.tsx' import type { AppApi, RouterContext } from './router-context.ts' const appBasePath = () => String(packageContext?.appBasePath ?? '').replace(/\/+$/, '') function serverApi(visitor: Visitor | null): AppApi { const userId = () => { if (!visitor) throw new Error('Sign in to use your list.') return visitor.userId } return { listItems: () => listItems(userId()), addItem: (text) => addItem(userId(), text), deleteItem: (id) => deleteItem(userId(), id), } } async function handleApi(request: Request, path: string, visitor: Visitor | null) { if (!visitor) { return Response.json({ error: 'Sign in to use your list.' }, { status: 401 }) } if (path === '/api/items' && request.method === 'GET') { return Response.json({ items: await listItems(visitor.userId) }) } if (path === '/api/items' && request.method === 'POST') { const body = (await request.json().catch(() => null)) as { text?: unknown } | null const text = typeof body?.text === 'string' ? body.text.trim() : '' if (!text || text.length > 200) { return Response.json({ error: 'Enter 1 to 200 characters.' }, { status: 400 }) } return Response.json({ item: await addItem(visitor.userId, text) }) } const match = /^\/api\/items\/([^/]+)$/.exec(path) if (match && request.method === 'DELETE') { await deleteItem(visitor.userId, decodeURIComponent(match[1]!)) return new Response(null, { status: 204 }) } return Response.json({ error: 'Not found' }, { status: 404 }) } async function renderPage(request: Request, visitor: Visitor | null) { const url = new URL(request.url) const context: RouterContext = { queryClient: new QueryClient(), api: serverApi(visitor), visitor, appBasePath: appBasePath(), assetBasePath: packageContext?.assetBasePath ?? '', clientModuleUrl: packageContext?.clientModuleUrl ?? null, hostedUrl: packageContext?.hostedUrl ?? null, } const router = createAppRouter({ history: createMemoryHistory({ initialEntries: [`${context.appBasePath}${url.pathname}${url.search}`], }), context, origin: url.origin, }) await router.load() context.dehydratedState = dehydrate(context.queryClient) const matches = router.state.matches const status = matches.some((match) => match.status === 'notFound') ? 404 : matches.some((match) => match.status === 'error') ? 500 : 200 const stream = await renderToReadableStream(, { onError(error) { console.error('render failed', error) }, }) return new Response(stream, { status, headers: { 'content-type': 'text/html; charset=utf-8' }, }) } export default { async fetch(request: Request) { const path = new URL(request.url).pathname const visitor = readVisitor(request) if (path === '/health') return Response.json({ ok: true }) if (path.startsWith('/api/')) return handleApi(request, path, visitor) if (request.method !== 'GET' && request.method !== 'HEAD') { return new Response('Method Not Allowed', { status: 405 }) } return renderPage(request, visitor) }, }