@clarity-js/ssr 1.0.0 → 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
@@ -109,6 +109,39 @@ const { written, failed } = await prerender({ handler, paths: [...staticPaths(ro
109
109
 
110
110
  `/` becomes `index.html`, `/about` becomes `about/index.html`, `/feed.xml` stays `feed.xml`.
111
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
+
112
145
  ## Lower level
113
146
 
114
147
  `renderPage({ component, props, url, ctx, ...document })` gives `{ status, headers, html, state }`;
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/handler.js CHANGED
@@ -4,10 +4,37 @@
4
4
 
5
5
  import { sortRoutes, selectRoute } from '@ozsarman/clarityjs/pages-router'
6
6
  import { createActionRouter } from '@ozsarman/clarityjs/server-actions'
7
- import { renderPage, streamPage, createContext, ServerResponse } from './render.js'
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'
8
11
 
9
12
  const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
10
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
+ }
11
38
 
12
39
  function pickComponent(mod) {
13
40
  if (typeof mod?.default === 'function') return mod.default
@@ -47,6 +74,9 @@ function fromSignal(err) {
47
74
  * @param {(error, request) => void} [options.onError]
48
75
  * @param {object} [options.document] what every page shares: title, titleTemplate, lang, dir, styles, stylesheets,
49
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.
50
80
  */
51
81
  export function createHandler(options = {}) {
52
82
  const { app = null, notFound: NotFound = null, error: ErrorPage = null, stream = false, basePath = '', passthrough = false, onError = (e) => console.error('[@clarity-js/ssr]', e) } = options
@@ -62,10 +92,34 @@ export function createHandler(options = {}) {
62
92
  return modules.get(route.pattern)
63
93
  }
64
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
+
65
102
  async function page(component, request, ctx, extra = {}) {
66
- const doc = options.document ?? {}
67
- const nonce = typeof doc.nonce === 'function' ? doc.nonce(request) : doc.nonce
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
68
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
+ }
69
123
  if (stream && request.method !== 'HEAD') {
70
124
  const r = streamPage({ ...o, onError: (e) => onError(e, request) })
71
125
  return new Response(r.body, { status: r.status, headers: r.headers })
@@ -85,6 +139,41 @@ export function createHandler(options = {}) {
85
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' } })
86
140
  }
87
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
+
88
177
  return async function handle(request, platform) {
89
178
  const url = new URL(request.url)
90
179
  let path = url.pathname
@@ -97,6 +186,10 @@ export function createHandler(options = {}) {
97
186
  return actions(new Request(inner, request))
98
187
  }
99
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
+ }
100
193
  let ctx
101
194
  try {
102
195
  const locals = (await options.locals?.(request, platform)) ?? {}
package/index.d.ts CHANGED
@@ -40,6 +40,10 @@ export interface DocumentOptions {
40
40
  appId?: string
41
41
  bodyAttrs?: Record<string, string | boolean>
42
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
43
47
  /** Your own document: gets the rendered parts (start = up to the static head, end = the rest). */
44
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
45
49
  }
@@ -52,10 +56,18 @@ export interface RenderOptions extends DocumentOptions {
52
56
  /** Tags as useHead() takes them ({ title, meta, link }), set before the component's own. */
53
57
  headTags?: object
54
58
  idPrefix?: string
59
+ /** partial prerendering: 'shell' draws each <defer> as its fallback, 'fill' draws its content (1.14) */
60
+ ppr?: 'shell' | 'fill' | null
55
61
  }
56
62
 
57
63
  export function createContext(init?: { request?: Request; url?: string; params?: Record<string, string>; locals?: Record<string, any>; platform?: unknown }): ServerContext
58
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
59
71
  export function streamPage(options: RenderOptions & { onError?: (error: unknown) => void }): { status: number; headers: Headers; body: ReadableStream<Uint8Array> }
60
72
 
61
73
  export interface RouteModule {
@@ -90,7 +102,13 @@ export interface HandlerOptions {
90
102
  passthrough?: boolean
91
103
  onError?: (error: unknown, request: Request) => void
92
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> }
93
107
  }
94
108
  export type Handler = (request: Request, platform?: unknown) => Promise<Response>
95
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
96
114
  export function toResponse(value: unknown, init?: ResponseInit): Response
package/index.js CHANGED
@@ -11,5 +11,5 @@
11
11
  * import { routes } from 'virtual:clarity-pages'
12
12
  * export default { fetch: createHandler({ routes, document: { title: 'Shop', clientScript: '/assets/app.js' } }) }
13
13
  */
14
- export { createHandler, toResponse } from './handler.js'
15
- export { renderPage, streamPage, createContext, redirect, notFound, httpError, ServerResponse } from './render.js'
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 CHANGED
@@ -7,7 +7,11 @@ export function toNodeHandler(handler: Handler, options?: { trustProxy?: boolean
7
7
  export function serve(handler: Handler, options?: { port?: number; hostname?: string; trustProxy?: boolean; onListen?: (info: { port: number }) => void }): Server
8
8
  export function scanRoutes(dir: string, options?: { extensions?: RegExp; ignore?: RegExp }): Promise<Route[]>
9
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; done: number; total: number }) => void }): Promise<{ written: string[]; failed: { path: string; status?: number; error?: unknown }[] }>
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[]> }
11
15
 
12
16
  export function createExpressMiddleware(options?: HandlerOptions & { trustProxy?: boolean }): (req: IncomingMessage, res: NodeResponse, next: (err?: unknown) => void) => Promise<void>
13
17
  export function clarityFastify(fastify: any, options?: HandlerOptions & { trustProxy?: boolean }): Promise<void>
package/node.js CHANGED
@@ -3,7 +3,8 @@
3
3
 
4
4
  import http from 'node:http'
5
5
  import { Readable } from 'node:stream'
6
- import { readdir, mkdir, writeFile } from 'node:fs/promises'
6
+ import { readdir, mkdir, writeFile, readFile, stat } from 'node:fs/promises'
7
+ import { createReadStream } from 'node:fs'
7
8
  import { join, relative, dirname, resolve, sep } from 'node:path'
8
9
  import { pathToFileURL } from 'node:url'
9
10
  import { filePathToRoutePattern, sortRoutes } from '@ozsarman/clarityjs/pages-router'
@@ -77,6 +78,53 @@ export function toNodeHandler(handler, { trustProxy = false } = {}) {
77
78
  }
78
79
  }
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
+
80
128
  /** A node:http server for the handler. `serve(handler, { port: 3000 })` */
81
129
  export function serve(handler, { port = Number(process.env.PORT) || 3000, hostname, trustProxy = false, onListen } = {}) {
82
130
  const server = http.createServer(toNodeHandler(handler, { trustProxy }))
@@ -112,27 +160,59 @@ export const staticPaths = (routes) => routes.map((r) => r.pattern ?? r.path).fi
112
160
  /**
113
161
  * Render paths with the handler and write them as files: '/' → index.html, '/about' → about/index.html,
114
162
  * '/feed.xml' → feed.xml. The same handler as the server, so a static page is the page the server sends.
115
- * @returns {Promise<{ written: string[], failed: { path, status?, error? }[] }>}
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? }[] }>}
116
169
  */
117
- export async function prerender({ handler, paths, outDir = 'dist', origin = 'http://localhost', concurrency = 4, onPage } = {}) {
170
+ export async function prerender({ handler, paths, outDir = 'dist', origin = 'http://localhost', concurrency = 4, onPage, ppr = false, pprDir = join(outDir, '_ppr') } = {}) {
118
171
  const list = typeof paths === 'function' ? await paths() : paths
119
- const written = [], failed = []
172
+ const written = [], failed = [], shells = []
173
+ const manifest = {}
120
174
  const queue = [...new Set(list)]
121
175
  const worker = async () => {
122
176
  for (let p; (p = queue.shift()) !== undefined;) {
123
177
  try {
124
- const response = await handler(new Request(new URL(p, origin)), { prerender: true })
178
+ const headers = ppr ? { 'x-clarity-prerender': 'shell' } : {}
179
+ const response = await handler(new Request(new URL(p, origin), { headers }), { prerender: true })
125
180
  if (!response.ok) { failed.push({ path: p, status: response.status }); continue }
126
181
  const clean = p.split(/[?#]/)[0]
127
182
  const file = /\.[a-z0-9]+$/i.test(clean) ? clean : join(clean, 'index.html')
128
- const out = join(outDir, file)
183
+ const holes = ppr ? Number(response.headers.get('x-clarity-holes') || 0) : 0
184
+ const out = join(holes ? pprDir : outDir, file)
129
185
  await mkdir(dirname(out), { recursive: true })
130
186
  await writeFile(out, Buffer.from(await response.arrayBuffer()))
131
- written.push(out)
132
- onPage?.({ path: p, file: out, done: written.length + failed.length, total: list.length })
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 })
133
189
  } catch (error) { failed.push({ path: p, error }) }
134
190
  }
135
191
  }
136
192
  await Promise.all(Array.from({ length: Math.max(1, concurrency) }, worker))
137
- return { written: written.sort(), failed }
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
+ }
138
218
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clarity-js/ssr",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
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
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -11,15 +11,16 @@
11
11
  "./node": { "types": "./node.d.ts", "import": "./node.js", "default": "./node.js" },
12
12
  "./express": { "types": "./node.d.ts", "import": "./express.js", "default": "./express.js" },
13
13
  "./fastify": { "types": "./node.d.ts", "import": "./fastify.js", "default": "./fastify.js" },
14
+ "./build": { "types": "./build.d.ts", "import": "./build.js", "default": "./build.js" },
14
15
  "./package.json": "./package.json"
15
16
  },
16
- "files": ["index.js", "handler.js", "render.js", "node.js", "express.js", "fastify.js", "index.d.ts", "node.d.ts", "README.md"],
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"],
17
18
  "sideEffects": false,
18
19
  "keywords": ["clarity", "@ozsarman/clarityjs", "ssr", "server-side-rendering", "streaming", "ssg", "prerender", "express", "fastify", "hono", "bun", "deno", "cloudflare-workers"],
19
20
  "author": "Özdemir Şarman",
20
21
  "license": "MIT",
21
- "peerDependencies": { "@ozsarman/clarityjs": ">=1.10.0" },
22
+ "peerDependencies": { "@ozsarman/clarityjs": ">=1.14.0" },
22
23
  "homepage": "https://clarity-js.com/docs/packages#ssr",
23
- "repository": { "type": "git", "url": "git+https://gitlab.com/ozsarman/clarity.js.git", "directory": "packages/clarity-ssr" },
24
+ "repository": { "type": "git", "url": "git+https://github.com/ozdemirsarman/clarity.js.git", "directory": "packages/clarity-ssr" },
24
25
  "engines": { "node": ">=18.0.0" }
25
26
  }
package/render.js CHANGED
@@ -6,6 +6,8 @@ import { renderToString, escapeHTML, escapeAttr, safeJSONForScript } from '@ozsa
6
6
  import { _beginServerData, _endServerData } from '@ozsarman/clarityjs/server-data'
7
7
  import { createHead, renderHead } from '@ozsarman/clarityjs/head'
8
8
  import { setServerPath } from '@ozsarman/clarityjs/router'
9
+ import { resolveServerComponents } from '@ozsarman/clarityjs/server-components'
10
+ import { _setPPR } from '@ozsarman/clarityjs/runtime'
9
11
 
10
12
  const SERVER_DATA_KEY = '__serverData'
11
13
 
@@ -63,31 +65,39 @@ function parseCookies(header) {
63
65
  * useServerData() (collect, fetch, render again); the head is read inside the same synchronous pass, so
64
66
  * concurrent requests never see each other's tags.
65
67
  */
66
- async function renderApp({ component, props = {}, ctx, url, title = '', titleTemplate = null, headTags = null, idPrefix }) {
68
+ async function renderApp({ component, props = {}, ctx, url, title = '', titleTemplate = null, headTags = null, idPrefix, ppr = null, ns = '' }) {
67
69
  if (typeof component !== 'function') throw new TypeError('[@clarity-js/ssr] component must be a Clarity component (a function)')
68
70
  let p = props
69
71
  if (typeof component.__clarity_server__ === 'function') p = { ...props, __ssr: await component.__clarity_server__(props, ctx) }
70
72
  const pass = (data) => {
71
73
  _beginServerData(data)
72
74
  let result, collected, headHtml
75
+ if (ppr) _setPPR(ppr)
73
76
  try {
74
77
  if (url) setServerPath(url)
75
78
  const head = createHead({ defaultTitle: title, titleTemplate })
76
79
  if (headTags) head._register(headTags)
77
80
  result = renderToString(component, p, idPrefix ? { idPrefix } : {})
78
81
  headHtml = renderHead(head)
79
- } finally { collected = _endServerData() }
82
+ } finally { collected = _endServerData(); if (ppr) _setPPR(null) }
80
83
  return { result, collected, headHtml }
81
84
  }
82
- let { result, collected, headHtml } = pass({})
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
83
90
  let serverData = {}
84
91
  if (collected?.pending.length) {
85
92
  serverData = {}
86
93
  await Promise.all(collected.pending.map(async ({ key, fetcher }) => { serverData[key] = typeof fetcher === 'function' ? await fetcher(ctx) : undefined }))
87
- ;({ result, headHtml } = pass(serverData))
94
+ const again = await run(serverData)
95
+ ;({ result, headHtml } = again.result)
96
+ islands = again.islands
88
97
  }
89
- const state = Object.keys(serverData).length ? { ...result.state, [SERVER_DATA_KEY]: serverData } : result.state
90
- return { html: result.html, state, serverData, head: headHtml, aiContracts: result.aiContracts }
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 }
91
101
  }
92
102
 
93
103
  const attrs = (o = {}) => Object.entries(o).filter(([, v]) => v != null && v !== false).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escapeAttr(v)}"`)).join('')
@@ -101,14 +111,20 @@ function documentParts(o, rendered) {
101
111
  '<head>',
102
112
  '<meta charset="utf-8">',
103
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)
104
115
  ...[].concat(o.stylesheets ?? []).map((href) => `<link rel="stylesheet" href="${escapeAttr(href)}">`),
105
116
  o.styles ? `<style${nonce}>${o.styles}</style>` : '',
106
117
  ...scripts.map((src) => `<link rel="modulepreload" href="${escapeAttr(src)}">`),
118
+ o.fillScript ? `<script src="${escapeAttr(o.fillScript)}" async${nonce}></script>` : '',
107
119
  o.head ?? '',
108
120
  ].filter(Boolean).join('\n')
109
121
  if (!rendered) return { start }
110
122
  const h = rendered.head ?? {}
111
- const stateScript = rendered.state && Object.keys(rendered.state).length ? `<script${nonce}>window.__CLARITY_DATA__=${safeJSONForScript(rendered.state)};</script>` : ''
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>`
112
128
  const end = [
113
129
  h.title, h.metas, h.links, h.scripts,
114
130
  '</head>',
@@ -182,3 +198,61 @@ export function streamPage(options = {}) {
182
198
  if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
183
199
  return { status: ctx.response.status, headers, body }
184
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
+ }