@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/index.d.ts ADDED
@@ -0,0 +1,114 @@
1
+ export interface ServerContext {
2
+ request: Request | null
3
+ url: string
4
+ path: string
5
+ params: Record<string, string>
6
+ query: Record<string, string>
7
+ cookies: Record<string, string>
8
+ locals: Record<string, any>
9
+ platform: unknown
10
+ response: { status: number; headers: Headers }
11
+ setStatus(code: number): void
12
+ setHeader(name: string, value: string): void
13
+ appendHeader(name: string, value: string): void
14
+ }
15
+
16
+ export class ServerResponse extends Error {
17
+ status: number
18
+ location: string | null
19
+ headers: Record<string, string>
20
+ body: string | null
21
+ }
22
+ /** throw redirect('/login') */
23
+ export function redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ServerResponse
24
+ /** throw notFound() */
25
+ export function notFound(body?: string | null): ServerResponse
26
+ /** throw httpError(403, 'No entry') */
27
+ export function httpError(status: number, body?: string | null): ServerResponse
28
+
29
+ export interface DocumentOptions {
30
+ title?: string
31
+ titleTemplate?: string
32
+ lang?: string
33
+ dir?: 'ltr' | 'rtl'
34
+ styles?: string
35
+ stylesheets?: string | string[]
36
+ clientScript?: string | string[]
37
+ scripts?: string[]
38
+ head?: string
39
+ nonce?: string
40
+ appId?: string
41
+ bodyAttrs?: Record<string, string | boolean>
42
+ htmlAttrs?: Record<string, string | boolean>
43
+ /** 'json': the page's data as <script type="application/json" id="__CLARITY_DATA__"> — no inline script to run (1.14) */
44
+ dataScript?: 'script' | 'json'
45
+ /** a script the head loads with async (a prerendered shell loads /_clarity/fill.js) */
46
+ fillScript?: string
47
+ /** Your own document: gets the rendered parts (start = up to the static head, end = the rest). */
48
+ document?: (parts: { html: string; state: object; head: { title: string; metas: string; links: string; scripts: string }; start: string; end: string; escapeHTML(s: string): string }) => string
49
+ }
50
+
51
+ export interface RenderOptions extends DocumentOptions {
52
+ component: Function
53
+ props?: Record<string, any>
54
+ url?: string
55
+ ctx?: Partial<ServerContext>
56
+ /** Tags as useHead() takes them ({ title, meta, link }), set before the component's own. */
57
+ headTags?: object
58
+ idPrefix?: string
59
+ /** partial prerendering: 'shell' draws each <defer> as its fallback, 'fill' draws its content (1.14) */
60
+ ppr?: 'shell' | 'fill' | null
61
+ }
62
+
63
+ export function createContext(init?: { request?: Request; url?: string; params?: Record<string, string>; locals?: Record<string, any>; platform?: unknown }): ServerContext
64
+ export function renderPage(options: RenderOptions & { throwSignals?: boolean }): Promise<{ status: number; headers: Headers; html: string; state: object; serverData: object }>
65
+ /** A prerendered shell at once, then the contents of its <defer> holes for this request, in one response (1.14). */
66
+ export function streamPPR(options: RenderOptions & { shell: string; onError?: (error: unknown) => void }): { status: number; headers: Headers; body: ReadableStream<Uint8Array> }
67
+ /** The ids of the holes in a prerendered shell. */
68
+ export function shellHoles(shell: string): string[]
69
+ /** What a shell's nonce is until a request gives it its own. */
70
+ export const NONCE_PLACEHOLDER: string
71
+ export function streamPage(options: RenderOptions & { onError?: (error: unknown) => void }): { status: number; headers: Headers; body: ReadableStream<Uint8Array> }
72
+
73
+ export interface RouteModule {
74
+ default?: Function
75
+ loader?: (ctx: ServerContext) => any
76
+ head?: object | ((info: { data: any; params: Record<string, string> }) => object)
77
+ GET?: (request: Request, ctx: ServerContext) => any
78
+ POST?: (request: Request, ctx: ServerContext) => any
79
+ PUT?: (request: Request, ctx: ServerContext) => any
80
+ PATCH?: (request: Request, ctx: ServerContext) => any
81
+ DELETE?: (request: Request, ctx: ServerContext) => any
82
+ [k: string]: any
83
+ }
84
+ export interface Route {
85
+ pattern?: string
86
+ path?: string
87
+ file?: string
88
+ load?: () => Promise<RouteModule>
89
+ module?: RouteModule
90
+ component?: Function
91
+ }
92
+
93
+ export interface HandlerOptions {
94
+ routes?: Route[]
95
+ app?: Function
96
+ notFound?: Function
97
+ error?: Function
98
+ actions?: object | object[]
99
+ locals?: (request: Request, platform: unknown) => object | Promise<object>
100
+ stream?: boolean
101
+ basePath?: string
102
+ passthrough?: boolean
103
+ onError?: (error: unknown, request: Request) => void
104
+ document?: Omit<DocumentOptions, 'nonce'> & { nonce?: string | ((request: Request) => string) }
105
+ /** partial prerendering: the shells prerender({ ppr: true }) made — pprShells(dir) of '@clarity-js/ssr/node' (1.14) */
106
+ ppr?: { get(path: string): string | null | Promise<string | null> }
107
+ }
108
+ export type Handler = (request: Request, platform?: unknown) => Promise<Response>
109
+ export function createHandler(options?: HandlerOptions): Handler
110
+ /** The prerendered shells for every handler that was not given its own `ppr` (1.14). */
111
+ /** What every page loads when its document names none: the browser entry Vite built (1.14). */
112
+ export function setClientAssets(assets: { scripts?: string[]; stylesheets?: string[] } | null): void
113
+ export function setShells(source: { get(path: string): string | null | Promise<string | null> } | Map<string, string> | Record<string, string> | null): void
114
+ export function toResponse(value: unknown, init?: ResponseInit): Response
package/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @clarity-js/ssr — a server for a Clarity app, on the core's renderToString.
3
+ *
4
+ * One handler in the Web standard, (Request) => Promise<Response>, that renders pages (loaders,
5
+ * useServerData(), useHead(), the router's path, the state for hydration), answers API routes and server
6
+ * actions, streams when you ask, and redirects or 404s when a loader says so. It runs as is on Bun, Deno,
7
+ * Cloudflare Workers and Hono; '@clarity-js/ssr/node' puts it on node:http, Express and Fastify, and prerenders
8
+ * pages to files with the same code.
9
+ *
10
+ * import { createHandler } from '@clarity-js/ssr'
11
+ * import { routes } from 'virtual:clarity-pages'
12
+ * export default { fetch: createHandler({ routes, document: { title: 'Shop', clientScript: '/assets/app.js' } }) }
13
+ */
14
+ export { createHandler, toResponse, setShells, setClientAssets } from './handler.js'
15
+ export { renderPage, streamPage, streamPPR, shellHoles, NONCE_PLACEHOLDER, createContext, redirect, notFound, httpError, ServerResponse } from './render.js'
package/node.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { IncomingMessage, ServerResponse as NodeResponse, Server } from 'node:http'
2
+ import type { Handler, HandlerOptions, Route } from './index.js'
3
+
4
+ export function toRequest(req: IncomingMessage & { body?: unknown; originalUrl?: string }, options?: { trustProxy?: boolean; res?: NodeResponse }): Request
5
+ export function sendResponse(res: NodeResponse, response: Response): Promise<void>
6
+ export function toNodeHandler(handler: Handler, options?: { trustProxy?: boolean }): (req: IncomingMessage, res: NodeResponse, next?: (err?: unknown) => void) => Promise<void>
7
+ export function serve(handler: Handler, options?: { port?: number; hostname?: string; trustProxy?: boolean; onListen?: (info: { port: number }) => void }): Server
8
+ export function scanRoutes(dir: string, options?: { extensions?: RegExp; ignore?: RegExp }): Promise<Route[]>
9
+ export function staticPaths(routes: Route[]): string[]
10
+ export function prerender(options: { handler: Handler; paths: string[] | (() => string[] | Promise<string[]>); outDir?: string; origin?: string; concurrency?: number; onPage?: (info: { path: string; file: string; shell: boolean; done: number; total: number }) => void; ppr?: boolean; pprDir?: string }): Promise<{ written: string[]; shells: string[]; failed: { path: string; status?: number; error?: unknown }[] }>
11
+ /** The files of a folder first (dist/client), then the handler. */
12
+ export function withStatic(handler: Handler, dir: string, options?: { immutable?: string }): Handler
13
+ /** The shells prerender({ ppr: true }) wrote, for createHandler({ ppr }). */
14
+ export function pprShells(dir: string): { get(path: string): Promise<string | null>; paths(): Promise<string[]> }
15
+
16
+ export function createExpressMiddleware(options?: HandlerOptions & { trustProxy?: boolean }): (req: IncomingMessage, res: NodeResponse, next: (err?: unknown) => void) => Promise<void>
17
+ export function clarityFastify(fastify: any, options?: HandlerOptions & { trustProxy?: boolean }): Promise<void>
18
+ export function createFastifyPlugin(options?: HandlerOptions & { trustProxy?: boolean }): (fastify: any) => Promise<void>
19
+ export default createExpressMiddleware
package/node.js ADDED
@@ -0,0 +1,218 @@
1
+ // Node pieces: the Web handler on node:http (and so on Express, Fastify, Koa, Connect), a small server, the
2
+ // route table from a pages folder, and prerendering pages to files with the same handler.
3
+
4
+ import http from 'node:http'
5
+ import { Readable } from 'node:stream'
6
+ import { readdir, mkdir, writeFile, readFile, stat } from 'node:fs/promises'
7
+ import { createReadStream } from 'node:fs'
8
+ import { join, relative, dirname, resolve, sep } from 'node:path'
9
+ import { pathToFileURL } from 'node:url'
10
+ import { filePathToRoutePattern, sortRoutes } from '@ozsarman/clarityjs/pages-router'
11
+
12
+ /** An IncomingMessage as a Web Request. A body a framework has already parsed (req.body) is sent on. */
13
+ export function toRequest(req, { trustProxy = false, res = null } = {}) {
14
+ const proto = (trustProxy && String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim()) || (req.socket?.encrypted ? 'https' : 'http')
15
+ const host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host || 'localhost'
16
+ const url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`)
17
+ const headers = new Headers()
18
+ for (const [k, v] of Object.entries(req.headers)) {
19
+ if (v == null || k.startsWith(':')) continue
20
+ if (Array.isArray(v)) for (const one of v) headers.append(k, one)
21
+ else headers.set(k, String(v))
22
+ }
23
+ const init = { method: req.method, headers }
24
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
25
+ if (req.body !== undefined) {
26
+ const b = req.body
27
+ const raw = typeof b === 'string' || b instanceof Uint8Array
28
+ init.body = raw ? b : b instanceof URLSearchParams ? b.toString() : JSON.stringify(b)
29
+ if (!raw && !(b instanceof URLSearchParams)) headers.set('content-type', 'application/json')
30
+ headers.delete('content-length')
31
+ } else {
32
+ init.body = Readable.toWeb(req)
33
+ init.duplex = 'half'
34
+ }
35
+ }
36
+ if (res) {
37
+ // the client went away before the answer was sent: request.signal lets loaders stop their work
38
+ const controller = new AbortController()
39
+ res.once('close', () => { if (!res.writableFinished) controller.abort() })
40
+ init.signal = controller.signal
41
+ }
42
+ return new Request(url, init)
43
+ }
44
+
45
+ /** Write a Web Response to a ServerResponse, streaming its body. */
46
+ export async function sendResponse(res, response) {
47
+ res.statusCode = response.status
48
+ const cookies = response.headers.getSetCookie?.() ?? []
49
+ for (const [k, v] of response.headers) if (k !== 'set-cookie') res.setHeader(k, v)
50
+ if (cookies.length) res.setHeader('set-cookie', cookies)
51
+ if (!response.body) { res.end(); return }
52
+ res.flushHeaders?.()
53
+ const reader = response.body.getReader()
54
+ try {
55
+ for (;;) {
56
+ const { done, value } = await reader.read()
57
+ if (done) break
58
+ if (!res.write(value)) await new Promise((r) => res.once('drain', r))
59
+ }
60
+ } finally { res.end() }
61
+ }
62
+
63
+ /**
64
+ * The Web handler as a Node (req, res, next?) handler. With `next` (Express, Connect), a 404 the handler marks
65
+ * as passthrough goes on to the next middleware.
66
+ */
67
+ export function toNodeHandler(handler, { trustProxy = false } = {}) {
68
+ return async function clarity(req, res, next) {
69
+ try {
70
+ const response = await handler(toRequest(req, { trustProxy, res }), { req, res })
71
+ if (typeof next === 'function' && response.headers.get('x-clarity-passthrough')) return next()
72
+ await sendResponse(res, response)
73
+ } catch (err) {
74
+ if (typeof next === 'function') return next(err)
75
+ console.error('[@clarity-js/ssr]', err)
76
+ if (!res.headersSent) { res.statusCode = 500; res.end('Internal Server Error') } else res.end()
77
+ }
78
+ }
79
+ }
80
+
81
+ const TYPES = {
82
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
83
+ '.json': 'application/json', '.map': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
84
+ '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
85
+ '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf', '.wasm': 'application/wasm', '.glb': 'model/gltf-binary',
86
+ '.gltf': 'model/gltf+json', '.ktx2': 'image/ktx2', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav', '.mp4': 'video/mp4', '.webm': 'video/webm',
87
+ '.pdf': 'application/pdf', '.webmanifest': 'application/manifest+json',
88
+ }
89
+
90
+ /**
91
+ * The files of a folder first, then the handler: what a built app's server needs (`dist/client` and the
92
+ * pages prerendered into it). Files under `immutable` (default `/assets/`, where Vite puts hashed files)
93
+ * are cached for a year; the rest are checked each time. `/about` finds `about/index.html`. Nothing
94
+ * outside the folder is reachable, and dotfiles are not served.
95
+ * @param {(request: Request, platform?: unknown) => Promise<Response>} handler
96
+ * @param {string} dir
97
+ * @param {{ immutable?: string }} [options]
98
+ */
99
+ export function withStatic(handler, dir, { immutable = '/assets/' } = {}) {
100
+ const root = resolve(dir)
101
+ const find = async (pathname) => {
102
+ let p
103
+ try { p = decodeURIComponent(pathname) } catch { return null }
104
+ if (p.includes('\0') || /(^|\/)\.[^/]/.test(p)) return null
105
+ for (const cand of p.endsWith('/') ? [p + 'index.html'] : [p, p + '/index.html']) {
106
+ const file = resolve(root, '.' + cand)
107
+ if (file !== root && !file.startsWith(root + sep)) return null
108
+ try { const st = await stat(file); if (st.isFile()) return { file, st } } catch { /* not there */ }
109
+ }
110
+ return null
111
+ }
112
+ return async function staticFirst(request, platform) {
113
+ if (request.method === 'GET' || request.method === 'HEAD') {
114
+ const url = new URL(request.url)
115
+ const got = await find(url.pathname)
116
+ if (got) {
117
+ const ext = got.file.slice(got.file.lastIndexOf('.')).toLowerCase()
118
+ const headers = new Headers({ 'content-type': TYPES[ext] ?? 'application/octet-stream', 'content-length': String(got.st.size), 'last-modified': got.st.mtime.toUTCString() })
119
+ headers.set('cache-control', url.pathname.startsWith(immutable) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
120
+ if (request.method === 'HEAD') return new Response(null, { headers })
121
+ return new Response(Readable.toWeb(createReadStream(got.file)), { headers })
122
+ }
123
+ }
124
+ return handler(request, platform)
125
+ }
126
+ }
127
+
128
+ /** A node:http server for the handler. `serve(handler, { port: 3000 })` */
129
+ export function serve(handler, { port = Number(process.env.PORT) || 3000, hostname, trustProxy = false, onListen } = {}) {
130
+ const server = http.createServer(toNodeHandler(handler, { trustProxy }))
131
+ server.listen(port, hostname, () => (onListen ?? (({ port: p }) => console.log(`Clarity app on http://${hostname ?? 'localhost'}:${p}`)))({ port: server.address().port }))
132
+ return server
133
+ }
134
+
135
+ const PAGE = /\.(m?js|clarity)$/
136
+ /**
137
+ * The route table of a pages folder, for createHandler(): pages/blog/[slug].js → /blog/:slug, pages/api/users.js
138
+ * → /api/users. Modules load on first request. `.clarity` pages need a loader that compiles them — run Node with
139
+ * `--import @clarity-js/testing/register`, or build the server with Vite.
140
+ */
141
+ export async function scanRoutes(dir, { extensions = PAGE, ignore = /(^|\/)(_|\.)/ } = {}) {
142
+ const root = resolve(dir)
143
+ const files = []
144
+ const walk = async (d) => {
145
+ for (const e of await readdir(d, { withFileTypes: true })) {
146
+ const full = join(d, e.name)
147
+ const rel = relative(root, full).split(sep).join('/')
148
+ if (ignore.test(rel)) continue
149
+ if (e.isDirectory()) await walk(full)
150
+ else if (extensions.test(e.name)) files.push(rel)
151
+ }
152
+ }
153
+ await walk(root)
154
+ return sortRoutes(files.map((file) => ({ pattern: filePathToRoutePattern(file), file, load: () => import(pathToFileURL(join(root, file)).href) })))
155
+ }
156
+
157
+ /** The patterns of a route table that have no parameters: what prerender() can do without being told. */
158
+ export const staticPaths = (routes) => routes.map((r) => r.pattern ?? r.path).filter((p) => p && !/[:*]/.test(p))
159
+
160
+ /**
161
+ * Render paths with the handler and write them as files: '/' → index.html, '/about' → about/index.html,
162
+ * '/feed.xml' → feed.xml. The same handler as the server, so a static page is the page the server sends.
163
+ *
164
+ * With `ppr: true` (partial prerendering) each page is rendered as a shell: a page with `<defer>` holes is
165
+ * not a finished page, so it goes to `<pprDir>` (default `<outDir>/_ppr`) with a manifest.json, for the
166
+ * server (createHandler({ ppr: pprShells(dir) })) to answer with at once and fill per request. A page with
167
+ * no hole is written as usual.
168
+ * @returns {Promise<{ written: string[], shells: string[], failed: { path, status?, error? }[] }>}
169
+ */
170
+ export async function prerender({ handler, paths, outDir = 'dist', origin = 'http://localhost', concurrency = 4, onPage, ppr = false, pprDir = join(outDir, '_ppr') } = {}) {
171
+ const list = typeof paths === 'function' ? await paths() : paths
172
+ const written = [], failed = [], shells = []
173
+ const manifest = {}
174
+ const queue = [...new Set(list)]
175
+ const worker = async () => {
176
+ for (let p; (p = queue.shift()) !== undefined;) {
177
+ try {
178
+ const headers = ppr ? { 'x-clarity-prerender': 'shell' } : {}
179
+ const response = await handler(new Request(new URL(p, origin), { headers }), { prerender: true })
180
+ if (!response.ok) { failed.push({ path: p, status: response.status }); continue }
181
+ const clean = p.split(/[?#]/)[0]
182
+ const file = /\.[a-z0-9]+$/i.test(clean) ? clean : join(clean, 'index.html')
183
+ const holes = ppr ? Number(response.headers.get('x-clarity-holes') || 0) : 0
184
+ const out = join(holes ? pprDir : outDir, file)
185
+ await mkdir(dirname(out), { recursive: true })
186
+ await writeFile(out, Buffer.from(await response.arrayBuffer()))
187
+ if (holes) { shells.push(out); manifest[clean] = file.split(sep).join('/').replace(/^\/+/, '') } else written.push(out)
188
+ onPage?.({ path: p, file: out, shell: !!holes, done: written.length + shells.length + failed.length, total: list.length })
189
+ } catch (error) { failed.push({ path: p, error }) }
190
+ }
191
+ }
192
+ await Promise.all(Array.from({ length: Math.max(1, concurrency) }, worker))
193
+ if (shells.length) {
194
+ await mkdir(pprDir, { recursive: true })
195
+ await writeFile(join(pprDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n')
196
+ }
197
+ return { written: written.sort(), shells: shells.sort(), failed }
198
+ }
199
+
200
+ /**
201
+ * The shells prerender({ ppr: true }) wrote, for createHandler({ ppr }). Read once, kept in memory.
202
+ * @param {string} dir the folder with manifest.json (prerender's `pprDir`)
203
+ * @returns {{ get(path: string): Promise<string | null>, paths(): Promise<string[]> }}
204
+ */
205
+ export function pprShells(dir) {
206
+ let loaded = null
207
+ const load = () => (loaded ??= (async () => {
208
+ let manifest = {}
209
+ try { manifest = JSON.parse(await readFile(join(dir, 'manifest.json'), 'utf8')) } catch { return new Map() }
210
+ const map = new Map()
211
+ for (const [path, file] of Object.entries(manifest)) map.set(path, await readFile(join(dir, file), 'utf8'))
212
+ return map
213
+ })())
214
+ return {
215
+ async get(path) { return (await load()).get(path) ?? null },
216
+ async paths() { return [...(await load()).keys()] },
217
+ }
218
+ }
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@clarity-js/ssr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "A server for Clarity.js apps: one Web-standard handler that renders pages (loaders, server data, head, hydration state), answers API routes and server actions, streams, redirects and 404s — on Bun, Deno, Workers and Hono as is, and on Node, Express and Fastify through adapters; prerenders pages to files with the same code. No dependencies.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "module": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": { "types": "./index.d.ts", "import": "./index.js", "default": "./index.js" },
11
+ "./node": { "types": "./node.d.ts", "import": "./node.js", "default": "./node.js" },
12
+ "./express": { "types": "./node.d.ts", "import": "./express.js", "default": "./express.js" },
13
+ "./fastify": { "types": "./node.d.ts", "import": "./fastify.js", "default": "./fastify.js" },
14
+ "./build": { "types": "./build.d.ts", "import": "./build.js", "default": "./build.js" },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": ["index.js", "handler.js", "render.js", "node.js", "express.js", "fastify.js", "build.js", "index.d.ts", "node.d.ts", "build.d.ts", "README.md"],
18
+ "sideEffects": false,
19
+ "keywords": ["clarity", "@ozsarman/clarityjs", "ssr", "server-side-rendering", "streaming", "ssg", "prerender", "express", "fastify", "hono", "bun", "deno", "cloudflare-workers"],
20
+ "author": "Özdemir Şarman",
21
+ "license": "MIT",
22
+ "peerDependencies": { "@ozsarman/clarityjs": ">=1.14.0" },
23
+ "homepage": "https://clarity-js.com/docs/packages#ssr",
24
+ "repository": { "type": "git", "url": "git+https://github.com/ozdemirsarman/clarity.js.git", "directory": "packages/clarity-ssr" },
25
+ "engines": { "node": ">=18.0.0" }
26
+ }
package/render.js ADDED
@@ -0,0 +1,258 @@
1
+ // Rendering a page on the server: the component's loader, useServerData() fetches, useHead() tags, the router's
2
+ // path, the serialized state, and the response's status and headers — as one document or as a stream.
3
+ // Platform-neutral: no Node APIs, so the same code runs on Node, Bun, Deno and edge workers.
4
+
5
+ import { renderToString, escapeHTML, escapeAttr, safeJSONForScript } from '@ozsarman/clarityjs/ssr'
6
+ import { _beginServerData, _endServerData } from '@ozsarman/clarityjs/server-data'
7
+ import { createHead, renderHead } from '@ozsarman/clarityjs/head'
8
+ import { setServerPath } from '@ozsarman/clarityjs/router'
9
+ import { resolveServerComponents } from '@ozsarman/clarityjs/server-components'
10
+ import { _setPPR } from '@ozsarman/clarityjs/runtime'
11
+
12
+ const SERVER_DATA_KEY = '__serverData'
13
+
14
+ /** Thrown from a loader, a page or a fetcher to answer with something else than the page. */
15
+ export class ServerResponse extends Error {
16
+ constructor(status, { location = null, headers = {}, body = null } = {}) {
17
+ super(location ? `redirect ${status} → ${location}` : `HTTP ${status}`)
18
+ this.name = 'ServerResponse'
19
+ this.status = status
20
+ this.location = location
21
+ this.headers = headers
22
+ this.body = body
23
+ }
24
+ }
25
+ /** `throw redirect('/login')` — 302 unless you say otherwise (301, 303, 307, 308). */
26
+ export const redirect = (location, status = 302) => new ServerResponse(status, { location })
27
+ /** `throw notFound()` — the 404 page (or the text) instead of this one. */
28
+ export const notFound = (body = null) => new ServerResponse(404, { body })
29
+ /** `throw httpError(403, 'No entry')` */
30
+ export const httpError = (status, body = null) => new ServerResponse(status, { body })
31
+
32
+ /**
33
+ * The context a loader, a page's server block and useServerData() fetchers receive.
34
+ * setStatus / setHeader change the response; locals carries what your middleware put there.
35
+ */
36
+ export function createContext({ request = null, url = '/', params = {}, locals = {}, platform = null } = {}) {
37
+ const u = new URL(url, 'http://localhost')
38
+ const response = { status: 200, headers: new Headers() }
39
+ return {
40
+ request, params, locals, platform,
41
+ url: u.pathname + u.search, path: u.pathname,
42
+ query: Object.fromEntries(u.searchParams),
43
+ cookies: parseCookies(request?.headers?.get?.('cookie') ?? ''),
44
+ response,
45
+ setStatus(code) { response.status = code },
46
+ setHeader(name, value) { response.headers.set(name, value) },
47
+ appendHeader(name, value) { response.headers.append(name, value) },
48
+ }
49
+ }
50
+
51
+ function parseCookies(header) {
52
+ const out = {}
53
+ for (const part of header.split(';')) {
54
+ const i = part.indexOf('=')
55
+ if (i < 0) continue
56
+ const k = part.slice(0, i).trim()
57
+ if (!k || k in out) continue
58
+ try { out[k] = decodeURIComponent(part.slice(i + 1).trim()) } catch { out[k] = part.slice(i + 1).trim() }
59
+ }
60
+ return out
61
+ }
62
+
63
+ /**
64
+ * Render the component with everything it asks the server for. Two synchronous passes when it uses
65
+ * useServerData() (collect, fetch, render again); the head is read inside the same synchronous pass, so
66
+ * concurrent requests never see each other's tags.
67
+ */
68
+ async function renderApp({ component, props = {}, ctx, url, title = '', titleTemplate = null, headTags = null, idPrefix, ppr = null, ns = '' }) {
69
+ if (typeof component !== 'function') throw new TypeError('[@clarity-js/ssr] component must be a Clarity component (a function)')
70
+ let p = props
71
+ if (typeof component.__clarity_server__ === 'function') p = { ...props, __ssr: await component.__clarity_server__(props, ctx) }
72
+ const pass = (data) => {
73
+ _beginServerData(data)
74
+ let result, collected, headHtml
75
+ if (ppr) _setPPR(ppr)
76
+ try {
77
+ if (url) setServerPath(url)
78
+ const head = createHead({ defaultTitle: title, titleTemplate })
79
+ if (headTags) head._register(headTags)
80
+ result = renderToString(component, p, idPrefix ? { idPrefix } : {})
81
+ headHtml = renderHead(head)
82
+ } finally { collected = _endServerData(); if (ppr) _setPPR(null) }
83
+ return { result, collected, headHtml }
84
+ }
85
+ // server components (1.14): each pass starts the loaders it meets; the next draws what they brought
86
+ const loaded = new Map()
87
+ const run = (data) => resolveServerComponents(() => pass(data), { ctx, cache: loaded, ns })
88
+ let { result: first, islands } = await run({})
89
+ let { result, collected, headHtml } = first
90
+ let serverData = {}
91
+ if (collected?.pending.length) {
92
+ serverData = {}
93
+ await Promise.all(collected.pending.map(async ({ key, fetcher }) => { serverData[key] = typeof fetcher === 'function' ? await fetcher(ctx) : undefined }))
94
+ const again = await run(serverData)
95
+ ;({ result, headHtml } = again.result)
96
+ islands = again.islands
97
+ }
98
+ let state = Object.keys(serverData).length ? { ...result.state, [SERVER_DATA_KEY]: serverData } : result.state
99
+ if (Object.keys(islands).length) state = { ...state, __islands: islands }
100
+ return { html: result.html, state, serverData, islands, head: headHtml, aiContracts: result.aiContracts }
101
+ }
102
+
103
+ const attrs = (o = {}) => Object.entries(o).filter(([, v]) => v != null && v !== false).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escapeAttr(v)}"`)).join('')
104
+
105
+ function documentParts(o, rendered) {
106
+ const nonce = o.nonce ? ` nonce="${escapeAttr(o.nonce)}"` : ''
107
+ const scripts = [].concat(o.clientScript ?? [], o.scripts ?? [])
108
+ const start = [
109
+ '<!DOCTYPE html>',
110
+ `<html${attrs({ lang: o.lang ?? 'en', dir: o.dir, ...o.htmlAttrs })}>`,
111
+ '<head>',
112
+ '<meta charset="utf-8">',
113
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
114
+ o.nonce ? `<meta property="csp-nonce"${nonce}>` : '', // what the runtime gives a <style> it must make (1.15)
115
+ ...[].concat(o.stylesheets ?? []).map((href) => `<link rel="stylesheet" href="${escapeAttr(href)}">`),
116
+ o.styles ? `<style${nonce}>${o.styles}</style>` : '',
117
+ ...scripts.map((src) => `<link rel="modulepreload" href="${escapeAttr(src)}">`),
118
+ o.fillScript ? `<script src="${escapeAttr(o.fillScript)}" async${nonce}></script>` : '',
119
+ o.head ?? '',
120
+ ].filter(Boolean).join('\n')
121
+ if (!rendered) return { start }
122
+ const h = rendered.head ?? {}
123
+ const hasState = rendered.state && Object.keys(rendered.state).length
124
+ // as JSON (`dataScript: 'json'`, and always in a prerendered shell): no script that runs inline, so no nonce
125
+ const stateScript = !hasState ? '' : o.dataScript === 'json'
126
+ ? `<script type="application/json" id="__CLARITY_DATA__">${safeJSONForScript(rendered.state)}</script>`
127
+ : `<script${nonce}>window.__CLARITY_DATA__=${safeJSONForScript(rendered.state)};</script>`
128
+ const end = [
129
+ h.title, h.metas, h.links, h.scripts,
130
+ '</head>',
131
+ `<body${attrs(o.bodyAttrs)}>`,
132
+ `<div id="${escapeAttr(o.appId ?? 'app')}">${rendered.html}</div>`,
133
+ stateScript,
134
+ ...scripts.map((src) => `<script type="module" src="${escapeAttr(src)}"${nonce}></script>`),
135
+ '</body>',
136
+ '</html>',
137
+ ].filter(Boolean).join('\n')
138
+ return { start, end }
139
+ }
140
+
141
+ function signalResponse(err, o) {
142
+ const headers = new Headers({ 'content-type': 'text/html; charset=utf-8', ...err.headers })
143
+ if (err.location) { headers.set('location', err.location); return { status: err.status, headers, html: '' } }
144
+ return { status: err.status, headers, html: err.body == null ? `<!DOCTYPE html><title>${err.status}</title><h1>${err.status}</h1>` : String(err.body) }
145
+ }
146
+
147
+ /**
148
+ * Render a whole HTML document.
149
+ * @returns {Promise<{ status, headers: Headers, html, state, serverData }>}
150
+ */
151
+ export async function renderPage(options = {}) {
152
+ const ctx = options.ctx?.response ? options.ctx : createContext({ url: options.url ?? '/', ...options.ctx })
153
+ try {
154
+ const rendered = await renderApp({ ...options, ctx, url: options.url ?? ctx.url })
155
+ const { start, end } = documentParts(options, rendered)
156
+ const html = typeof options.document === 'function' ? options.document({ ...rendered, start, end, escapeHTML }) : `${start}\n${end}`
157
+ const headers = new Headers(ctx.response.headers)
158
+ if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
159
+ return { status: ctx.response.status, headers, html, state: rendered.state, serverData: rendered.serverData }
160
+ } catch (err) {
161
+ if (err instanceof ServerResponse && !options.throwSignals) return signalResponse(err, options)
162
+ throw err
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Stream the document: the head's fixed part (charset, styles, preloads of the client script) leaves at once,
168
+ * so the browser starts on the assets while loaders and fetches run; the rest follows when the page is ready.
169
+ * A redirect thrown after the start has left becomes a meta refresh plus location.replace().
170
+ * @returns {{ status, headers: Headers, body: ReadableStream<Uint8Array> }}
171
+ */
172
+ export function streamPage(options = {}) {
173
+ const ctx = options.ctx?.response ? options.ctx : createContext({ url: options.url ?? '/', ...options.ctx })
174
+ const enc = new TextEncoder()
175
+ const { start } = documentParts(options)
176
+ const body = new ReadableStream({
177
+ async start(controller) {
178
+ controller.enqueue(enc.encode(start + '\n'))
179
+ try {
180
+ const rendered = await renderApp({ ...options, ctx, url: options.url ?? ctx.url })
181
+ controller.enqueue(enc.encode(documentParts(options, rendered).end))
182
+ } catch (err) {
183
+ let tail
184
+ if (err instanceof ServerResponse && err.location) {
185
+ const to = escapeAttr(err.location)
186
+ tail = `<meta http-equiv="refresh" content="0;url=${to}">\n<script${options.nonce ? ` nonce="${escapeAttr(options.nonce)}"` : ''}>location.replace(${safeJSONForScript(err.location)})</script>\n</head><body></body></html>`
187
+ } else {
188
+ if (!(err instanceof ServerResponse)) options.onError?.(err)
189
+ const status = err instanceof ServerResponse ? err.status : 500
190
+ tail = `<title>${status}</title>\n</head><body>${err instanceof ServerResponse && err.body != null ? String(err.body) : `<h1>${status}</h1>`}</body></html>`
191
+ }
192
+ controller.enqueue(enc.encode(tail))
193
+ }
194
+ controller.close()
195
+ },
196
+ })
197
+ const headers = new Headers(ctx.response.headers)
198
+ if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
199
+ return { status: ctx.response.status, headers, body }
200
+ }
201
+
202
+ // ─── Partial prerendering (1.14) ─────────────────────────────────────────────
203
+
204
+ /** What a shell's nonce is until a request gives it its own. */
205
+ export const NONCE_PLACEHOLDER = '__CLARITY_NONCE__'
206
+
207
+ /** The ids of the holes (`<defer>`) in a prerendered shell, in the order they stand. */
208
+ export function shellHoles(shell) {
209
+ return [...String(shell).matchAll(/<!--ppr:([^>]*?)-->/g)].map((m) => m[1])
210
+ }
211
+
212
+ /**
213
+ * Answer with a prerendered shell at once, then with the contents of its holes as the page renders them
214
+ * for this request — one response. The contents arrive as `<template data-clarity-fill>`, the data they
215
+ * add as `<script type="application/json" data-clarity-fill-data>`; /_clarity/fill.js (loaded by the
216
+ * shell) and hydrateRoot() put them in place. If the render fails the holes keep their fallbacks.
217
+ * @param {object} options what renderPage() takes, and `shell`: the HTML prerender() made for this path
218
+ * @returns {{ status, headers: Headers, body: ReadableStream<Uint8Array> }}
219
+ */
220
+ export function streamPPR(options = {}) {
221
+ const ctx = options.ctx?.response ? options.ctx : createContext({ url: options.url ?? '/', ...options.ctx })
222
+ const enc = new TextEncoder()
223
+ const nonce = options.nonce ? escapeAttr(options.nonce) : null
224
+ let shell = String(options.shell ?? '')
225
+ shell = nonce ? shell.split(`nonce="${NONCE_PLACEHOLDER}"`).join(`nonce="${nonce}"`) : shell.split(` nonce="${NONCE_PLACEHOLDER}"`).join('')
226
+ const cut = shell.lastIndexOf('</body>')
227
+ const first = cut >= 0 ? shell.slice(0, cut) : shell
228
+ const last = cut >= 0 ? shell.slice(cut) : ''
229
+ const holes = shellHoles(shell)
230
+ const body = new ReadableStream({
231
+ async start(controller) {
232
+ controller.enqueue(enc.encode(first))
233
+ try {
234
+ const rendered = await renderApp({ ...options, ctx, url: options.url ?? ctx.url, ppr: 'fill', ns: 'p-' })
235
+ const html = rendered.html
236
+ let out = ''
237
+ for (const id of holes) {
238
+ const open = `<!--ppr:${id}-->`, close = `<!--/ppr:${id}-->`
239
+ const a = html.indexOf(open), b = a < 0 ? -1 : html.indexOf(close, a + open.length)
240
+ if (a < 0 || b < 0) continue
241
+ out += `<template data-clarity-fill="${escapeAttr(id)}">${html.slice(a + open.length, b)}</template>\n`
242
+ }
243
+ const data = {}
244
+ if (rendered.islands && Object.keys(rendered.islands).length) data.__islands = rendered.islands
245
+ if (rendered.serverData && Object.keys(rendered.serverData).length) data[SERVER_DATA_KEY] = rendered.serverData
246
+ out += `<script type="application/json" data-clarity-fill-data>${safeJSONForScript(data)}</script>\n`
247
+ controller.enqueue(enc.encode(out))
248
+ } catch (err) {
249
+ if (!(err instanceof ServerResponse)) options.onError?.(err)
250
+ }
251
+ controller.enqueue(enc.encode(last))
252
+ controller.close()
253
+ },
254
+ })
255
+ const headers = new Headers(ctx.response.headers)
256
+ if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
257
+ return { status: ctx.response.status, headers, body }
258
+ }