@clarity-js/ssr 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,156 @@
1
- # Temporary Holding Version
1
+ # @clarity-js/ssr
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A server for [Clarity.js](https://clarity-js.com) apps, on the core's `renderToString`. One handler in the Web
4
+ standard — `(Request) => Promise<Response>` — that:
5
+
6
+ - renders pages with everything they ask the server for: a route's `loader`, `useServerData()` fetches,
7
+ `useHead()` tags, the router's path, and the state the client hydrates from;
8
+ - answers API routes (`GET`, `POST`, … exported from a route module) and server actions;
9
+ - redirects, refuses or 404s when a loader says so (`throw redirect('/login')`);
10
+ - streams when you ask: the head's fixed part leaves at once, the page follows when its data is ready;
11
+ - runs as is on Bun, Deno, Cloudflare Workers, Vercel/Netlify edge and Hono, and on Node, Express and Fastify
12
+ through small adapters;
13
+ - prerenders pages to files with the same code, so a static page is exactly the page the server sends.
14
+
15
+ No dependencies.
16
+
17
+ ```sh
18
+ npm install @clarity-js/ssr
19
+ ```
20
+
21
+ ## Routes
22
+
23
+ A route module may export a page component (`default`), a `loader`, `head` tags, and HTTP handlers. A module
24
+ with handlers and no component is an API route.
25
+
26
+ ```js
27
+ // pages/blog/[slug].js
28
+ import { notFound, redirect } from '@clarity-js/ssr'
29
+ export { default } from './Post.clarity'
30
+
31
+ export async function loader(ctx) { // ctx: params, query, cookies, request, locals, setStatus, setHeader
32
+ if (ctx.params.slug === 'old') throw redirect('/blog/new', 301)
33
+ const post = await ctx.locals.db.posts.find(ctx.params.slug)
34
+ if (!post) throw notFound()
35
+ ctx.setHeader('cache-control', 'max-age=60')
36
+ return post // the page gets it as `data`
37
+ }
38
+ export const head = ({ data }) => ({ title: data.title, meta: [{ name: 'description', content: data.summary }] })
39
+
40
+ export async function POST(request, ctx) { // a form posted to the page
41
+ await ctx.locals.db.comments.add(ctx.params.slug, await request.formData())
42
+ throw redirect(ctx.url, 303)
43
+ }
44
+ ```
45
+
46
+ ```js
47
+ // pages/api/posts.js — JSON in, JSON out
48
+ export const GET = (request, ctx) => ctx.locals.db.posts.list({ page: Number(ctx.query.page ?? 1) })
49
+ ```
50
+
51
+ ## The handler
52
+
53
+ ```js
54
+ import { createHandler } from '@clarity-js/ssr'
55
+ import { routes } from 'virtual:clarity-pages' // the Vite plugin's route table, or scanRoutes(), or your own
56
+ import NotFound from './NotFound.clarity'
57
+ import ErrorPage from './Error.clarity'
58
+ import * as actions from './actions.js'
59
+
60
+ export const handler = createHandler({
61
+ routes,
62
+ notFound: NotFound, // ({ path })
63
+ error: ErrorPage, // ({ error }) — the error's text only outside production
64
+ actions, // defineServerAction() exports, at POST /_clarity/actions/:name
65
+ locals: async (request) => ({ db, user: await session(request) }),
66
+ stream: false,
67
+ document: {
68
+ title: 'Shop', titleTemplate: '%s · Shop', lang: 'en',
69
+ stylesheets: ['/assets/app.css'], clientScript: '/assets/app.js',
70
+ nonce: (request) => crypto.randomUUID(), // for a Content-Security-Policy
71
+ },
72
+ })
73
+ ```
74
+
75
+ An app that routes itself with `<Router>`/`<Route>` passes `app: App` instead of `routes`; the router sees the
76
+ request's path.
77
+
78
+ ## Where it runs
79
+
80
+ ```js
81
+ // Bun, Deno, Cloudflare Workers, Hono
82
+ export default { fetch: handler }
83
+ Deno.serve(handler)
84
+ app.all('*', (c) => handler(c.req.raw)) // Hono
85
+
86
+ // Node
87
+ import { serve, toNodeHandler } from '@clarity-js/ssr/node'
88
+ serve(handler, { port: 3000 })
89
+ http.createServer(toNodeHandler(handler))
90
+
91
+ // Express — paths the app does not know go on to the next middleware
92
+ import clarity from '@clarity-js/ssr/express'
93
+ app.use(express.static('dist/client'))
94
+ app.use(clarity({ routes, document: { clientScript: '/assets/app.js' } }))
95
+
96
+ // Fastify — a catch-all route next to yours
97
+ import clarity from '@clarity-js/ssr/fastify'
98
+ await app.register(clarity, { routes })
99
+ ```
100
+
101
+ ## Prerender
102
+
103
+ ```js
104
+ import { scanRoutes, prerender, staticPaths } from '@clarity-js/ssr/node'
105
+ const routes = await scanRoutes('dist/server/pages')
106
+ const handler = createHandler({ routes, document: { clientScript: '/assets/app.js' } })
107
+ const { written, failed } = await prerender({ handler, paths: [...staticPaths(routes), '/blog/hello'], outDir: 'dist/client' })
108
+ ```
109
+
110
+ `/` becomes `index.html`, `/about` becomes `about/index.html`, `/feed.xml` stays `feed.xml`.
111
+
112
+ ## Server components and islands
113
+
114
+ A page with `server component`s (Clarity 1.14) is rendered in passes until every loader is done; the islands
115
+ they use are listed in the page's data. `GET /_clarity/server?c=<id>&p=<props JSON>` gives the browser a server
116
+ component it needs again (shown later by a client component, or with other props): its HTML and its islands.
117
+ The props come from the browser — treat them as a query string.
118
+
119
+ ## Partial prerendering
120
+
121
+ `<defer>` marks what depends on the request. Prerender the pages as shells, then let the handler answer with
122
+ the shell at once and fill its holes in the same response:
123
+
124
+ ```js
125
+ import { prerender, pprShells } from '@clarity-js/ssr/node'
126
+ await prerender({ handler, paths: ['/', '/shop'], outDir: 'dist/client', ppr: true }) // shells → dist/client/_ppr
127
+ const server = createHandler({ routes, ppr: pprShells('dist/client/_ppr') })
128
+ ```
129
+
130
+ The fills arrive as `<template data-clarity-fill>` and the data they add as JSON; `/_clarity/fill.js` (which
131
+ the shell loads) and `hydrateRoot()` put them in place. No script runs inline, and each request gets its own
132
+ nonce in the shell.
133
+
134
+ ## Build for a platform
135
+
136
+ ```sh
137
+ npx clarity build --adapter node | static | vercel | netlify | cloudflare
138
+ ```
139
+
140
+ `src/server.js` (or `--server`) exports the handler, and may export `routes`, `prerender` (paths) and
141
+ `ppr = true`. The build uses the project's Vite and writes the browser's files, the prerendered pages and
142
+ shells, and the server for the platform (`@clarity-js/ssr/build` does the same from a script:
143
+ `build({ adapter, root })`). On Node, `withStatic(handler, 'dist/client')` serves the files first.
144
+
145
+ ## Lower level
146
+
147
+ `renderPage({ component, props, url, ctx, ...document })` gives `{ status, headers, html, state }`;
148
+ `streamPage(...)` gives `{ status, headers, body }` with a `ReadableStream`. Concurrent requests never see each
149
+ other's head tags or data: each render pass reads its head in the same synchronous step.
150
+
151
+ Streaming has one trade-off: once the start of the document has left, the status is sent. A redirect thrown
152
+ later becomes a meta refresh and `location.replace()`, and an error becomes an error body.
153
+
154
+ ## License
155
+
156
+ MIT
package/build.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** `clarity build --adapter <name>`: the app built for where it will run (1.14). */
2
+ export const ADAPTERS: ReadonlyArray<'node' | 'static' | 'vercel' | 'netlify' | 'cloudflare'>
3
+ export function build(options: {
4
+ adapter: 'node' | 'static' | 'vercel' | 'netlify' | 'cloudflare'
5
+ /** the project's root (default: the working directory) */
6
+ root?: string
7
+ /** the server entry, exporting the handler (default src/server.js) */
8
+ server?: string
9
+ /** where it goes (default dist) */
10
+ out?: string
11
+ mode?: string
12
+ log?: (line: string) => void
13
+ }): Promise<{ adapter: string; client: string; written: string[]; shells: string[]; output: string[]; next: string; assets: { scripts: string[]; stylesheets: string[] } }>
14
+ /** The source of the module an adapter runs. */
15
+ export function adapterEntry(adapter: string, options: { entry: string; shells?: Record<string, string> | null; clientDir?: string; assets?: { scripts: string[]; stylesheets: string[] } | null }): string
package/build.js ADDED
@@ -0,0 +1,193 @@
1
+ // `clarity build --adapter <name>`: an app built for where it will run, with the project's own Vite.
2
+ //
3
+ // node dist/client + dist/server/index.mjs → node dist/server/index.mjs
4
+ // static dist/client, every page prerendered → any static host
5
+ // vercel .vercel/output (Build Output API v3) → vercel deploy --prebuilt
6
+ // netlify dist/client + .netlify/v1/functions → netlify deploy (publish dist/client)
7
+ // cloudflare dist/client + dist/worker + dist/wrangler.json → wrangler deploy -c dist/wrangler.json
8
+ //
9
+ // The server entry (default src/server.js) exports the handler — `export default createHandler({ … })` —
10
+ // and may export `prerender` (paths, or a function that gives them), `routes` (their paths without
11
+ // parameters are prerendered too) and `ppr = true` (partial prerendering: pages with <defer> are prerendered
12
+ // as shells, put in the server's bundle, and filled per request).
13
+
14
+ import { createRequire } from 'node:module'
15
+ import { existsSync, realpathSync } from 'node:fs'
16
+ import { mkdir, writeFile, rm, cp, readFile } from 'node:fs/promises'
17
+ import { join, resolve, relative } from 'node:path'
18
+ import { pathToFileURL } from 'node:url'
19
+ import { prerender as prerenderPages, staticPaths } from './node.js'
20
+ import { setClientAssets } from './handler.js'
21
+
22
+ export const ADAPTERS = ['node', 'static', 'vercel', 'netlify', 'cloudflare']
23
+ const EDGE = new Set(['cloudflare'])
24
+ const BUNDLED = new Set(['vercel', 'netlify', 'cloudflare']) // the function folder has no node_modules
25
+
26
+ const posix = (p) => p.split('\\').join('/')
27
+
28
+ async function viteOf(root) {
29
+ let pkgFile
30
+ try { pkgFile = createRequire(join(root, 'package.json')).resolve('vite/package.json') } catch {
31
+ throw new Error('`clarity build --adapter` builds with the project\'s Vite: run `npm install -D vite` in ' + root)
32
+ }
33
+ // its ES module entry (the CommonJS one is deprecated)
34
+ const pkg = JSON.parse(await readFile(pkgFile, 'utf8'))
35
+ let e = pkg.exports?.['.'] ?? pkg.module ?? pkg.main
36
+ while (e && typeof e === 'object') e = e.import ?? e.default ?? e.node
37
+ const mod = await import(pathToFileURL(join(pkgFile, '..', e ?? 'index.js')).href)
38
+ return mod.build ? mod : mod.default
39
+ }
40
+
41
+ /** The source of the module each adapter runs: the server entry, the shells, and the platform's glue. */
42
+ export function adapterEntry(adapter, { entry, shells = null, clientDir = '../client', assets = null, named = false }) {
43
+ const lines = [named ? `import { handler } from ${JSON.stringify(entry)}` : `import handler from ${JSON.stringify(entry)}`]
44
+ const withAssets = assets && (assets.scripts.length || assets.stylesheets.length)
45
+ const withShells = shells && Object.keys(shells).length
46
+ if (withAssets || withShells) lines.push(`import { ${[withAssets && 'setClientAssets', withShells && 'setShells'].filter(Boolean).join(', ')} } from '@clarity-js/ssr'`)
47
+ if (withAssets) lines.push(`setClientAssets(${JSON.stringify(assets)})`)
48
+ if (withShells) lines.push(`setShells(${JSON.stringify(shells)})`)
49
+ if (adapter === 'node') {
50
+ lines.push(
51
+ `import { serve, withStatic } from '@clarity-js/ssr/node'`,
52
+ `import { fileURLToPath } from 'node:url'`,
53
+ `const client = fileURLToPath(new URL(${JSON.stringify(clientDir.endsWith('/') ? clientDir : clientDir + '/')}, import.meta.url))`,
54
+ `export const fetch = withStatic(handler, client)`,
55
+ `if (process.env.CLARITY_NO_LISTEN !== '1') serve(fetch, { port: Number(process.env.PORT) || 3000, hostname: process.env.HOST, trustProxy: process.env.TRUST_PROXY === '1' })`,
56
+ )
57
+ } else if (adapter === 'vercel') {
58
+ lines.push(`import { toNodeHandler } from '@clarity-js/ssr/node'`, `export default toNodeHandler(handler, { trustProxy: true })`)
59
+ } else if (adapter === 'netlify') {
60
+ lines.push(`export default (request, context) => handler(request, context)`, `export const config = { path: '/*', preferStatic: true }`)
61
+ } else if (adapter === 'cloudflare') {
62
+ lines.push(`export default { fetch: (request, env, ctx) => handler(request, { env, ctx }) }`)
63
+ } else throw new Error(`no adapter ${adapter}`)
64
+ return lines.join('\n') + '\n'
65
+ }
66
+
67
+ /**
68
+ * Build the app for a platform.
69
+ * @param {{ adapter: string, root?: string, server?: string, out?: string, log?: (line: string) => void, mode?: string }} options
70
+ * @returns {Promise<{ adapter: string, client: string, written: string[], shells: string[], output: string[], next: string }>}
71
+ */
72
+ export async function build({ adapter, root = process.cwd(), server = 'src/server.js', out = 'dist', log = () => {}, mode = 'production' } = {}) {
73
+ if (!ADAPTERS.includes(adapter)) throw new Error(`--adapter is one of ${ADAPTERS.join(', ')} (got ${adapter ?? 'nothing'})`)
74
+ // the real path: Vite resolves index.html through links (/tmp → /private/tmp on a Mac) and must find it under root
75
+ root = realpathSync(resolve(root))
76
+ const outDir = resolve(root, out)
77
+ const entry = resolve(root, server)
78
+ if (!existsSync(entry)) throw new Error(`no server entry at ${posix(relative(root, entry) || entry)}: write one that exports the handler (export default createHandler({ … })), or name it with --server`)
79
+ const vite = await viteOf(root)
80
+ const client = join(outDir, 'client')
81
+ const quiet = { logLevel: 'warn', mode }
82
+ // a component's module imports the runtime's usual names whether it uses them or not: not worth a warning
83
+ const onwarn = (w, warn) => { if (w.code !== 'UNUSED_EXTERNAL_IMPORT') warn(w) }
84
+
85
+ // 1. the browser's files
86
+ log('client → ' + posix(relative(root, client)))
87
+ await vite.build({ ...quiet, root, build: { outDir: client, emptyOutDir: true, manifest: true } })
88
+
89
+ // the browser's entry, from Vite's manifest: what every page loads (unless the document names its own)
90
+ let assets = { scripts: [], stylesheets: [] }
91
+ try {
92
+ const manifest = JSON.parse(await readFile(join(client, '.vite', 'manifest.json'), 'utf8'))
93
+ for (const chunk of Object.values(manifest)) {
94
+ if (!chunk.isEntry) continue
95
+ if (/\.m?js$/.test(chunk.file)) assets.scripts.push('/' + chunk.file)
96
+ for (const css of chunk.css ?? []) assets.stylesheets.push('/' + css)
97
+ }
98
+ } catch { /* no manifest */ }
99
+ await rm(join(client, '.vite'), { recursive: true, force: true }) // read; not for the public
100
+ // the HTML page Vite made is the browser's way in for a client-only app; here the server renders the pages
101
+ if (adapter !== 'static') await rm(join(client, 'index.html'), { force: true })
102
+ setClientAssets(assets)
103
+
104
+ // 2. the server entry, to prerender with
105
+ const pre = join(outDir, '.prerender')
106
+ log('server entry → prerender')
107
+ // (Clarity and its server stay outside the bundle, so the build and the entry share one runtime)
108
+ const shared = { external: ['@ozsarman/clarityjs', '@clarity-js/ssr'] }
109
+ await vite.build({ ...quiet, root, ssr: shared, build: { ssr: entry, outDir: pre, emptyOutDir: true, rollupOptions: { onwarn, output: { entryFileNames: 'entry.mjs' } } } })
110
+ const app = await import(pathToFileURL(join(pre, 'entry.mjs')).href + '?t=' + Date.now())
111
+ const handler = app.default ?? app.handler
112
+ if (typeof handler !== 'function') throw new Error('the server entry exports no handler: export default createHandler({ … })')
113
+ const listed = typeof app.prerender === 'function' ? await app.prerender() : app.prerender ?? []
114
+ const paths = [...new Set([...listed, ...(Array.isArray(app.routes) ? staticPaths(app.routes) : [])])]
115
+ const ppr = !!app.ppr && adapter !== 'static'
116
+ if (app.ppr && adapter === 'static') log('ppr: a static host cannot fill holes per request — its pages are prerendered whole')
117
+ if (adapter === 'static' && !paths.length) throw new Error('the static adapter writes the pages the entry names: export const prerender = [\'/\', \'/about\'] (or export routes)')
118
+
119
+ // 3. prerender (shells too, with ppr)
120
+ let written = [], shellFiles = [], shells = null
121
+ if (paths.length) {
122
+ const pprDir = join(outDir, '.ppr')
123
+ const res = await prerenderPages({ handler, paths, outDir: client, ppr, pprDir })
124
+ for (const f of res.failed) log(`prerender ${f.path}: ${f.status ?? f.error?.message ?? f.error}`)
125
+ written = res.written
126
+ shellFiles = res.shells
127
+ if (res.shells.length) {
128
+ const manifest = JSON.parse(await readFile(join(pprDir, 'manifest.json'), 'utf8'))
129
+ shells = {}
130
+ for (const [path, file] of Object.entries(manifest)) shells[path] = await readFile(join(pprDir, file), 'utf8')
131
+ }
132
+ await rm(pprDir, { recursive: true, force: true })
133
+ log(`prerendered ${written.length} page(s)${shellFiles.length ? `, ${shellFiles.length} shell(s)` : ''}`)
134
+ }
135
+ await rm(pre, { recursive: true, force: true })
136
+
137
+ // 4. what the platform runs
138
+ const output = []
139
+ let next = ''
140
+ if (adapter === 'static') {
141
+ next = `upload ${posix(relative(root, client))} to any static host`
142
+ } else {
143
+ const glue = join(outDir, '.adapter')
144
+ await mkdir(glue, { recursive: true })
145
+ const where = {
146
+ node: { dir: join(outDir, 'server'), file: 'index.mjs', clientDir: posix(relative(join(outDir, 'server'), client)) },
147
+ vercel: { dir: join(root, '.vercel/output/functions/index.func'), file: 'index.mjs' },
148
+ netlify: { dir: join(root, '.netlify/v1/functions'), file: 'clarity-ssr.mjs' },
149
+ cloudflare: { dir: join(outDir, 'worker'), file: 'index.js' },
150
+ }[adapter]
151
+ const src = join(glue, 'entry.mjs')
152
+ await writeFile(src, adapterEntry(adapter, { entry: posix(relative(glue, entry)).replace(/^(?!\.)/, './'), shells, clientDir: where.clientDir, assets, named: typeof app.default !== 'function' }))
153
+ if (adapter !== 'netlify') await rm(where.dir, { recursive: true, force: true })
154
+ await vite.build({
155
+ ...quiet, root,
156
+ build: { ssr: src, outDir: where.dir, emptyOutDir: adapter !== 'netlify', target: 'es2022', rollupOptions: { onwarn, output: { entryFileNames: where.file, inlineDynamicImports: BUNDLED.has(adapter) } } },
157
+ ssr: BUNDLED.has(adapter) ? { noExternal: true, target: EDGE.has(adapter) ? 'webworker' : 'node' } : shared,
158
+ resolve: EDGE.has(adapter) ? { conditions: ['worker', 'browser', 'import', 'module', 'default'] } : undefined,
159
+ })
160
+ await rm(glue, { recursive: true, force: true })
161
+ output.push(join(where.dir, where.file))
162
+
163
+ if (adapter === 'node') {
164
+ next = `node ${posix(relative(root, join(where.dir, where.file)))}`
165
+ } else if (adapter === 'vercel') {
166
+ const base = join(root, '.vercel/output')
167
+ await rm(join(base, 'static'), { recursive: true, force: true })
168
+ await cp(client, join(base, 'static'), { recursive: true })
169
+ await writeFile(join(where.dir, '.vc-config.json'), JSON.stringify({ runtime: 'nodejs22.x', handler: where.file, launcherType: 'Nodejs', supportsResponseStreaming: true }, null, 2) + '\n')
170
+ await writeFile(join(where.dir, 'package.json'), '{ "type": "module" }\n')
171
+ await writeFile(join(base, 'config.json'), JSON.stringify({ version: 3, routes: [{ src: '^/assets/(.*)$', headers: { 'cache-control': 'public, max-age=31536000, immutable' }, continue: true }, { handle: 'filesystem' }, { src: '/(.*)', dest: '/index' }] }, null, 2) + '\n')
172
+ output.push(join(base, 'config.json'), join(base, 'static'))
173
+ next = 'vercel deploy --prebuilt'
174
+ } else if (adapter === 'netlify') {
175
+ const cfg = join(root, '.netlify/v1/config.json')
176
+ await writeFile(cfg, JSON.stringify({ headers: [{ for: '/assets/*', values: { 'cache-control': 'public, max-age=31536000, immutable' } }] }, null, 2) + '\n')
177
+ output.push(cfg)
178
+ next = `netlify deploy --dir ${posix(relative(root, client))} (the publish directory is ${posix(relative(root, client))})`
179
+ } else if (adapter === 'cloudflare') {
180
+ let name = 'clarity-app'
181
+ try { name = (JSON.parse(await readFile(join(root, 'package.json'), 'utf8')).name || name).replace(/^@[^/]+\//, '').replace(/[^a-z0-9-]/gi, '-').toLowerCase() } catch { /* no name */ }
182
+ const today = new Date().toISOString().slice(0, 10)
183
+ const wrangler = { name, main: posix(relative(outDir, join(where.dir, where.file))), compatibility_date: today, assets: { directory: posix(relative(outDir, client)), binding: 'ASSETS', html_handling: 'drop-trailing-slash' } } // /about is about/index.html, with no redirect to /about/
184
+ await writeFile(join(outDir, 'wrangler.json'), JSON.stringify(wrangler, null, 2) + '\n')
185
+ await writeFile(join(client, '_headers'), '/assets/*\n Cache-Control: public, max-age=31536000, immutable\n')
186
+ output.push(join(outDir, 'wrangler.json'))
187
+ next = `wrangler deploy -c ${posix(relative(root, join(outDir, 'wrangler.json')))}`
188
+ }
189
+ }
190
+ setClientAssets(null)
191
+ return { adapter, client, written, shells: shells ? Object.keys(shells) : [], output, next, assets }
192
+ }
193
+
package/express.js ADDED
@@ -0,0 +1,10 @@
1
+ // Express (and Connect): app.use(clarity({ routes, document: { clientScript: '/assets/app.js' } }))
2
+ // Paths the app does not know go on to the next middleware; a parsed req.body is passed on to API routes.
3
+ import { createHandler } from './handler.js'
4
+ import { toNodeHandler } from './node.js'
5
+
6
+ export function createExpressMiddleware(options = {}) {
7
+ const { trustProxy = false, ...rest } = options
8
+ return toNodeHandler(createHandler({ passthrough: true, ...rest }), { trustProxy })
9
+ }
10
+ export default createExpressMiddleware
package/fastify.js ADDED
@@ -0,0 +1,24 @@
1
+ // Fastify: await app.register(clarity, { routes, document: { … } })
2
+ // Registers a catch-all route; anything Fastify already routes is not touched.
3
+ import { createHandler } from './handler.js'
4
+ import { toRequest, sendResponse } from './node.js'
5
+
6
+ export async function clarityFastify(fastify, options = {}) {
7
+ const { trustProxy = false, prefix: _prefix, ...rest } = options
8
+ const handler = createHandler(rest)
9
+ fastify.route({
10
+ method: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
11
+ url: '/*',
12
+ async handler(request, reply) {
13
+ const req = request.raw
14
+ if (request.body !== undefined) req.body = request.body
15
+ const response = await handler(toRequest(req, { trustProxy, res: reply.raw }), { request, reply })
16
+ reply.hijack()
17
+ await sendResponse(reply.raw, response)
18
+ },
19
+ })
20
+ }
21
+ // Fastify reads this to skip encapsulation, so the route is added to the app that registers the plugin
22
+ clarityFastify[Symbol.for('skip-override')] = true
23
+ export const createFastifyPlugin = (options) => async (fastify) => clarityFastify(fastify, options)
24
+ export default clarityFastify
package/handler.js ADDED
@@ -0,0 +1,230 @@
1
+ // One request handler for a whole Clarity app, in the Web standard: (Request) => Promise<Response>.
2
+ // Use it as is on Bun, Deno, Cloudflare Workers, Vercel/Netlify edge and Hono; on Node, wrap it with
3
+ // toNodeHandler() from '@clarity-js/ssr/node' (or the Express / Fastify adapters).
4
+
5
+ import { sortRoutes, selectRoute } from '@ozsarman/clarityjs/pages-router'
6
+ import { createActionRouter } from '@ozsarman/clarityjs/server-actions'
7
+ import { renderServer } from '@ozsarman/clarityjs/ssr'
8
+ import { serverComponentById } from '@ozsarman/clarityjs/server-components'
9
+ import { fillScript } from '@ozsarman/clarityjs/ppr'
10
+ import { renderPage, streamPage, streamPPR, createContext, ServerResponse, NONCE_PLACEHOLDER } from './render.js'
11
+
12
+ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
13
+ const ACTIONS = '/_clarity/actions/'
14
+ const SERVER = '/_clarity/server'
15
+ const FILL = '/_clarity/fill.js'
16
+ const SHELL_HEADER = 'x-clarity-prerender'
17
+
18
+ let _shells = null
19
+ let _assets = null
20
+ /**
21
+ * What every page loads when its document names no clientScript / stylesheets of its own: the browser
22
+ * entry Vite built (`clarity build --adapter` reads it from Vite's manifest).
23
+ * @param {{ scripts?: string[], stylesheets?: string[] } | null} assets
24
+ */
25
+ export function setClientAssets(assets) { _assets = assets ? { scripts: [...(assets.scripts ?? [])], stylesheets: [...(assets.stylesheets ?? [])] } : null }
26
+
27
+ /**
28
+ * The prerendered shells for every handler that was not given its own `ppr` (what `clarity build --adapter`
29
+ * puts in front of your server entry: the shells it prerendered, in the bundle).
30
+ * @param {{ get(path: string): string | null | Promise<string | null> } | Map<string, string> | Record<string, string> | null} source
31
+ */
32
+ export function setShells(source) {
33
+ if (!source) { _shells = null; return }
34
+ if (typeof source.get === 'function') { _shells = source; return }
35
+ const map = new Map(Object.entries(source))
36
+ _shells = { get: (path) => map.get(path) ?? null }
37
+ }
38
+
39
+ function pickComponent(mod) {
40
+ if (typeof mod?.default === 'function') return mod.default
41
+ for (const [name, v] of Object.entries(mod ?? {})) if (typeof v === 'function' && /^[A-Z]/.test(name) && !METHODS.includes(name)) return v
42
+ return null
43
+ }
44
+
45
+ /** What a handler returned → a Response: a Response as is, a string as HTML, anything else as JSON. */
46
+ export function toResponse(value, init = {}) {
47
+ if (value instanceof Response) return value
48
+ if (value == null) return new Response(null, { status: 204, ...init })
49
+ if (typeof value === 'string') return new Response(value, { ...init, headers: { 'content-type': 'text/html; charset=utf-8', ...init.headers } })
50
+ return Response.json(value, init)
51
+ }
52
+
53
+ function fromSignal(err) {
54
+ const headers = new Headers(err.headers)
55
+ if (err.location) { headers.set('location', err.location); return new Response(null, { status: err.status, headers }) }
56
+ return new Response(err.body ?? String(err.status), { status: err.status, headers })
57
+ }
58
+
59
+ /**
60
+ * @param {object} options
61
+ * @param {Array<{ pattern: string, load?: () => Promise<object>, module?: object, component?: Function }>} [options.routes]
62
+ * the route table — `routes` from 'virtual:clarity-pages', scanRoutes() from '@clarity-js/ssr/node', or your own.
63
+ * A route's module may export a page component (default), `loader(ctx)` (its result is the page's `data`
64
+ * prop), `head` ({ title, meta, … } for useHead), and GET/POST/PUT/PATCH/DELETE handlers
65
+ * `(request, ctx) => Response | object | string`. A module with handlers and no component is an API route.
66
+ * @param {Function} [options.app] or one root component that routes itself (Router/Route); rendered for every path
67
+ * @param {Function} [options.notFound] the 404 page component ({ path })
68
+ * @param {Function} [options.error] the 500 page component ({ error }) — the error itself is never shown in production
69
+ * @param {object|object[]} [options.actions] modules of defineServerAction() exports, served at POST /_clarity/actions/:name
70
+ * @param {(request, platform) => object | Promise<object>} [options.locals] per-request values for ctx.locals (the user, the db)
71
+ * @param {boolean} [options.stream] stream the pages (see streamPage)
72
+ * @param {string} [options.basePath] the app lives under this path ('/shop')
73
+ * @param {boolean} [options.passthrough] answer an unmatched path with a bare 404 marked for adapters to call next()
74
+ * @param {(error, request) => void} [options.onError]
75
+ * @param {object} [options.document] what every page shares: title, titleTemplate, lang, dir, styles, stylesheets,
76
+ * clientScript, scripts, head, nonce (string or (request) => string), appId, bodyAttrs, htmlAttrs, document()
77
+ * @param {{ get(path: string): string | null | Promise<string | null> } | Map<string, string>} [options.ppr]
78
+ * partial prerendering: the shells prerender({ ppr: true }) made (pprShells(dir) of '@clarity-js/ssr/node').
79
+ * A page that has one is answered with it at once, and the contents of its <defer> holes follow.
80
+ */
81
+ export function createHandler(options = {}) {
82
+ const { app = null, notFound: NotFound = null, error: ErrorPage = null, stream = false, basePath = '', passthrough = false, onError = (e) => console.error('[@clarity-js/ssr]', e) } = options
83
+ const routes = sortRoutes((options.routes ?? []).map((r) => ({ ...r, pattern: r.pattern ?? r.path })))
84
+ const modules = new Map()
85
+ const actions = options.actions ? createActionRouter(...[].concat(options.actions)).fetch() : null
86
+ const dev = typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production'
87
+
88
+ const load = async (route) => {
89
+ if (route.module) return route.module
90
+ if (route.component) return { default: route.component }
91
+ if (!modules.has(route.pattern)) modules.set(route.pattern, Promise.resolve(route.load()).catch((e) => { modules.delete(route.pattern); throw e }))
92
+ return modules.get(route.pattern)
93
+ }
94
+
95
+ const shellOf = async (path) => {
96
+ const p = options.ppr ?? _shells
97
+ if (!p) return null
98
+ const got = typeof p.get === 'function' ? await p.get(path) : null
99
+ return typeof got === 'string' ? got : null
100
+ }
101
+
102
+ async function page(component, request, ctx, extra = {}) {
103
+ const doc = { ...(options.document ?? {}) }
104
+ if (_assets && doc.clientScript == null && doc.scripts == null && _assets.scripts.length) doc.clientScript = _assets.scripts
105
+ if (_assets && doc.stylesheets == null && _assets.stylesheets.length) doc.stylesheets = _assets.stylesheets
106
+ const shellMode = request.headers.get(SHELL_HEADER) === 'shell'
107
+ const nonce = shellMode ? NONCE_PLACEHOLDER : typeof doc.nonce === 'function' ? doc.nonce(request) : doc.nonce
108
+ const o = { ...doc, ...extra, nonce, component, ctx, url: ctx.url, props: { params: ctx.params, path: ctx.path, query: ctx.query, ...extra.props } }
109
+ if (shellMode) {
110
+ // prerender({ ppr: true }) asks for the shell: holes show their fallbacks; the data is JSON (no nonce yet)
111
+ const r = await renderPage({ ...o, ppr: 'shell', dataScript: 'json', fillScript: (basePath || '') + FILL, throwSignals: true })
112
+ const headers = new Headers(r.headers)
113
+ headers.set('x-clarity-holes', String((r.html.match(/<!--ppr:/g) ?? []).length))
114
+ return new Response(request.method === 'HEAD' ? null : r.html, { status: r.status, headers })
115
+ }
116
+ if (request.method === 'GET' && (options.ppr ?? _shells)) {
117
+ const shell = await shellOf(ctx.path)
118
+ if (shell) {
119
+ const r = streamPPR({ ...o, shell, onError: (e) => onError(e, request) })
120
+ return new Response(r.body, { status: r.status, headers: r.headers })
121
+ }
122
+ }
123
+ if (stream && request.method !== 'HEAD') {
124
+ const r = streamPage({ ...o, onError: (e) => onError(e, request) })
125
+ return new Response(r.body, { status: r.status, headers: r.headers })
126
+ }
127
+ const r = await renderPage({ ...o, throwSignals: true })
128
+ return new Response(request.method === 'HEAD' ? null : r.html, { status: r.status, headers: r.headers })
129
+ }
130
+
131
+ async function errorPage(err, request, ctx) {
132
+ onError(err, request)
133
+ if (ErrorPage) {
134
+ try {
135
+ ctx.setStatus(500)
136
+ return await page(ErrorPage, request, ctx, { props: { error: dev ? err : { message: 'Something went wrong' } } })
137
+ } catch (again) { onError(again, request) }
138
+ }
139
+ return new Response(dev ? `<pre>${String(err?.stack ?? err).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c])}</pre>` : '<h1>500</h1>', { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } })
140
+ }
141
+
142
+ // GET /_clarity/server?c=<id>&p=<props as JSON>&ns=<island ids' start>: a server component the browser needs
143
+ // again (a client component shows it later, or its props changed) — its HTML and its islands, as JSON.
144
+ // The props come from the browser: a server component treats them as it would a query string.
145
+ let allLoaded = null
146
+ let fillText = null
147
+ async function serverComponent(request, url, platform, method) {
148
+ if (method !== 'GET' && method !== 'HEAD') return new Response('Method Not Allowed', { status: 405, headers: { allow: 'GET, HEAD' } })
149
+ const id = url.searchParams.get('c') ?? ''
150
+ let C = serverComponentById(id)
151
+ if (!C && routes.length) { // its page may not have been loaded on this server yet
152
+ allLoaded ??= Promise.allSettled(routes.filter((r) => r.load || r.module || r.component).map(load))
153
+ await allLoaded
154
+ C = serverComponentById(id)
155
+ }
156
+ if (!C) return Response.json({ error: `no server component ${id}` }, { status: 404 })
157
+ let props
158
+ try { props = JSON.parse(url.searchParams.get('p') || '{}') } catch { props = null }
159
+ if (props === null || typeof props !== 'object' || Array.isArray(props)) return Response.json({ error: 'p must be the props as a JSON object' }, { status: 400 })
160
+ const ns = /^[a-z0-9-]{1,16}$/i.test(url.searchParams.get('ns') ?? '') ? url.searchParams.get('ns') : 'f-'
161
+ let ctx
162
+ try {
163
+ const locals = (await options.locals?.(request, platform)) ?? {}
164
+ ctx = createContext({ request, url: url.pathname + url.search, locals, platform })
165
+ const out = await renderServer(C, props, { ctx, ns })
166
+ const headers = new Headers(ctx.response.headers)
167
+ if (!headers.has('cache-control')) headers.set('cache-control', 'private, no-store')
168
+ return Response.json({ html: out.html, islands: out.islands }, { status: ctx.response.status, headers })
169
+ } catch (err) {
170
+ if (err instanceof Response) return err
171
+ if (err instanceof ServerResponse) return fromSignal(err)
172
+ onError(err, request)
173
+ return Response.json({ error: dev ? String(err?.message ?? err) : 'Something went wrong' }, { status: 500 })
174
+ }
175
+ }
176
+
177
+ return async function handle(request, platform) {
178
+ const url = new URL(request.url)
179
+ let path = url.pathname
180
+ if (basePath) {
181
+ if (path !== basePath && !path.startsWith(basePath + '/')) return new Response('Not Found', { status: 404, headers: passthrough ? { 'x-clarity-passthrough': '1' } : {} })
182
+ path = path.slice(basePath.length) || '/'
183
+ }
184
+ if (actions && path.startsWith(ACTIONS)) {
185
+ const inner = new URL(url); inner.pathname = path
186
+ return actions(new Request(inner, request))
187
+ }
188
+ const method = request.method.toUpperCase()
189
+ if (path === SERVER) return serverComponent(request, url, platform, method)
190
+ if (path === FILL && (method === 'GET' || method === 'HEAD')) {
191
+ return new Response(method === 'HEAD' ? null : (fillText ??= fillScript()), { headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'public, max-age=3600' } })
192
+ }
193
+ let ctx
194
+ try {
195
+ const locals = (await options.locals?.(request, platform)) ?? {}
196
+ const match = selectRoute(routes, path)
197
+ ctx = createContext({ request, url: path + url.search, params: match?.params ?? {}, locals, platform })
198
+ if (match) {
199
+ const mod = await load(match.route)
200
+ const Page = pickComponent(mod)
201
+ const fn = mod[method] ?? (method === 'HEAD' ? mod.GET : null)
202
+ if (fn && (method !== 'GET' || !Page)) return toResponse(await fn(request, ctx), { status: ctx.response.status, headers: ctx.response.headers })
203
+ if (!Page) {
204
+ const allow = METHODS.filter((m) => typeof mod[m] === 'function')
205
+ return new Response('Method Not Allowed', { status: 405, headers: { allow: allow.join(', ') } })
206
+ }
207
+ if (method !== 'GET' && method !== 'HEAD') return new Response('Method Not Allowed', { status: 405, headers: { allow: ['GET', 'HEAD', ...METHODS.filter((m) => typeof mod[m] === 'function')].join(', ') } })
208
+ const data = typeof mod.loader === 'function' ? await mod.loader(ctx) : undefined
209
+ const head = typeof mod.head === 'function' ? mod.head({ data, params: ctx.params }) : mod.head ?? (mod.meta?.title ? { title: mod.meta.title } : null)
210
+ return await page(Page, request, ctx, { headTags: head, props: data === undefined ? {} : { data } })
211
+ }
212
+ if (app) return await page(app, request, ctx)
213
+ if (passthrough && !NotFound) return new Response('Not Found', { status: 404, headers: { 'x-clarity-passthrough': '1' } })
214
+ throw new ServerResponse(404)
215
+ } catch (err) {
216
+ if (err instanceof Response) return err
217
+ if (err instanceof ServerResponse) {
218
+ if (err.status === 404 && NotFound && !err.location && err.body == null) {
219
+ try {
220
+ ctx ??= createContext({ request, url: path + url.search, platform })
221
+ ctx.setStatus(404)
222
+ return await page(NotFound, request, ctx, { props: { path } })
223
+ } catch (again) { return errorPage(again, request, ctx) }
224
+ }
225
+ return fromSignal(err)
226
+ }
227
+ return errorPage(err, request, ctx ?? createContext({ request, url: path, platform }))
228
+ }
229
+ }
230
+ }