prunelle 0.8.0 → 0.10.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.
Files changed (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -0,0 +1,54 @@
1
+ // An API route that exports a Standard Schema as `schema` has its input checked before the handler runs, with the same 400 envelope actions answer.
2
+
3
+ import type { RequestContext } from './http'
4
+ import type { StandardSchemaV1 } from './standard-schema'
5
+ import { validateSchema } from './standard-schema'
6
+
7
+ const QUERY_METHODS = new Set(['GET', 'HEAD'])
8
+
9
+ export function isStandardSchema(value: unknown): value is StandardSchemaV1 {
10
+ return typeof value === 'object' && value !== null && typeof (value as { '~standard'?: { validate?: unknown } })['~standard']?.validate === 'function'
11
+ }
12
+
13
+ // A key repeated in the query becomes an array, the way a form's repeated field does.
14
+ function queryObject(url: URL): Record<string, string | string[]> {
15
+ const out: Record<string, string | string[]> = {}
16
+ for (const key of new Set(url.searchParams.keys())) {
17
+ const values = url.searchParams.getAll(key)
18
+ Object.defineProperty(out, key, { value: values.length === 1 ? values[0]! : values, enumerable: true, writable: true, configurable: true })
19
+ }
20
+ return out
21
+ }
22
+
23
+ const invalid = (error: string): Response => Response.json({ ok: false, status: 400, error }, { status: 400 })
24
+
25
+ /** Checks `ctx` against the module's `schema` and sets `ctx.input` to the parsed value; answers the 400 when the input is invalid, and nothing when the module declares no schema. The handler's body stays readable: the check reads a clone. */
26
+ export async function validateRouteInput(schema: unknown, ctx: RequestContext): Promise<Response | undefined> {
27
+ if (!isStandardSchema(schema))
28
+ return undefined
29
+ const { request } = ctx
30
+ let raw: unknown
31
+ if (QUERY_METHODS.has(request.method.toUpperCase())) {
32
+ raw = queryObject(ctx.url)
33
+ }
34
+ else {
35
+ const text = await request.clone().text().catch(() => undefined)
36
+ if (text === undefined)
37
+ return invalid('Invalid request body')
38
+ if (text.trim() !== '') {
39
+ if (!(request.headers.get('content-type') ?? '').toLowerCase().includes('application/json'))
40
+ return invalid('Expected a JSON body')
41
+ try {
42
+ raw = JSON.parse(text)
43
+ }
44
+ catch {
45
+ return invalid('Invalid request body')
46
+ }
47
+ }
48
+ }
49
+ const checked = await validateSchema(schema, raw)
50
+ if (!checked.ok)
51
+ return Response.json({ ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues }, { status: 400 })
52
+ ctx.input = checked.value
53
+ return undefined
54
+ }
@@ -11,7 +11,7 @@ import type { NormalizedConsentConfig } from './consent'
11
11
  import type { CookieStore } from './cookies'
12
12
  import type { DocumentHooks, HtmlHeaders } from './document'
13
13
  import type { NotifyError } from './errors'
14
- import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { PhaseTiming, RequestIdResolver } from './health'
15
15
  import type { Middleware, RequestContext } from './http'
16
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
17
  import type { ParamMatcherMap } from './param-matchers'
@@ -23,15 +23,18 @@ import type { StreamTracker } from './stream'
23
23
  import { runWithAppContext } from '../plugins/index'
24
24
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
25
25
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
26
- import { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action'
26
+ import { ACTION_ERROR_COOKIE, getActionError, hydrateActionErrorFlash } from './action'
27
+ import { markFlashedFields } from './field-errors'
27
28
  import { compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, mergeVaryValue } from './compress'
29
+ import { cancelQuietly, markHandled } from './discard'
28
30
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
29
31
  import { endTimer, startTimer } from './health'
30
32
  import { isNotFound, makeRequestContext, runChain } from './http'
31
33
  import { allowedMethodsHeader, hasPublicFavicon, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
32
34
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
33
35
  import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
34
- import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, parseCacheDuration, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
36
+ import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, markUrlDerivedLocals, parseCacheDuration, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
37
+ import { validateRouteInput } from './route-input'
35
38
  import { Router } from './router'
36
39
  import { createFastStaticPageHandler, methodNotAllowed } from './routing'
37
40
  import { styleHashesOf } from './security'
@@ -55,6 +58,8 @@ export interface CompiledRoute {
55
58
  dirMiddlewares: Middleware[]
56
59
  /** Precomputed plugin + directory middlewares for non-rewritten static paths. */
57
60
  middlewares: Middleware[]
61
+ /** Under an app `_middleware.ts` or a path-scoped plugin middleware, which may let only some visitors in. */
62
+ gated: boolean
58
63
  /** Dynamic segments (`:param` / `*rest`), so the path names no single URL. */
59
64
  dynamic: boolean
60
65
  /** Options every document of this route shares; a request adds its body, head and islands. */
@@ -80,6 +85,7 @@ function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, mod:
80
85
  navigation,
81
86
  hasFavicon,
82
87
  regionScript: entry.usesRegion === true ? manifest.regionScript : undefined,
88
+ buildId: manifest.buildId,
83
89
  styles: entry.styles ?? manifest.styles,
84
90
  }
85
91
  }
@@ -95,13 +101,15 @@ export interface RouteTableOptions {
95
101
  navigation: DocumentOptions['navigation']
96
102
  hasFavicon?: boolean | undefined
97
103
  middlewaresFor: (path: string, kind?: RequestKind) => readonly Middleware[]
104
+ /** Whether a plugin middleware scoped to a path covers `path`, so it may let only some visitors in. */
105
+ isGatedByPlugin: (path: string) => boolean
98
106
  /** Whether a plugin rewrite, head hook, HTML transform or route may change what `path` answers. */
99
107
  pluginIntercepts: (path: string) => boolean
100
108
  fast: SharedFastOptions
101
109
  }
102
110
 
103
111
  export function compileRouteTable(options: RouteTableOptions): { router: Router<CompiledRoute>, fastStaticPages: Map<string, FastHandler> } {
104
- const { manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation, middlewaresFor, pluginIntercepts, fast } = options
112
+ const { manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation, middlewaresFor, isGatedByPlugin, pluginIntercepts, fast } = options
105
113
  const hasFavicon = options.hasFavicon ?? hasPublicFavicon(manifest)
106
114
  const router = new Router<CompiledRoute>(paramMatchers ?? BUILTIN_PARAM_MATCHERS)
107
115
  const fastStaticPages = new Map<string, FastHandler>()
@@ -122,8 +130,11 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
122
130
  if (canFastPath)
123
131
  fastStaticPages.set(entry.path, createFastStaticPageHandler({ ...fast, entry, mod, layouts, doc, reviveScript: manifest.reviveScript, hasIslands: entry.islandChunks.length > 0, hasLoad }))
124
132
 
125
- const routeEntry = entry.cache !== undefined && dirMiddlewares.length > 0 ? { ...entry, cache: { ...entry.cache, cacheControl: GATED_ROUTE_CACHE_CONTROL } } : entry
126
- router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags), idleTimeout })
133
+ // A gate may refuse a request, so a CDN must not hand a cached 200 to everyone: the route is cached by the server only.
134
+ const middlewares = [...middlewaresFor(entry.path), ...dirMiddlewares]
135
+ const gated = dirMiddlewares.length > 0 || isGatedByPlugin(entry.path)
136
+ const routeEntry = entry.cache !== undefined && gated ? { ...entry, cache: { ...entry.cache, cacheControl: GATED_ROUTE_CACHE_CONTROL } } : entry
137
+ router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares, gated, dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags), idleTimeout })
127
138
  }
128
139
  return { router, fastStaticPages }
129
140
  }
@@ -174,6 +185,7 @@ export interface CompiledRouteRendererDeps {
174
185
  actions: ActionRegistry
175
186
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
176
187
  trustProxy: TrustProxy
188
+ httpsSite?: boolean | undefined
177
189
  consent: NormalizedConsentConfig | undefined
178
190
  resolveRequestId: RequestIdResolver
179
191
  serverAppCtx: AppRuntimeContext
@@ -191,18 +203,22 @@ async function renderPageDocument(
191
203
  ctx: RequestContext,
192
204
  hasFlash: boolean,
193
205
  setIdleTimeout?: (seconds: number) => void,
194
- timing?: DevTiming,
206
+ timing?: PhaseTiming,
195
207
  privateTracker?: PrivateReadTracker,
196
208
  ): Promise<RenderedPageOutput> {
197
209
  const { entry, doc } = route
198
210
  const renderStart = startTimer(timing)
199
211
  const rctx = createRenderContext(undefined, undefined, privateTracker !== undefined ? privateTracker.consent : ctx.consent, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId))
200
- const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
201
- if (hasFlash)
212
+ let body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
213
+ if (hasFlash) {
202
214
  ctx.cookies.delete(ACTION_ERROR_COOKIE)
215
+ body = await markFlashedFields(body, getActionError(ctx.locals))
216
+ }
203
217
  // A route's `export const lang` names the language it is written in, so a plugin head hook such as i18n's cannot replace it.
204
218
  const pageLang = typeof route.mod.lang === 'string' ? route.mod.lang : undefined
205
- const resolvedHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
219
+ // Plugin hooks get the tracked context too, so a head or transformHtml read of private request data keeps the page out of the cache.
220
+ const hookCtx = privateTracker?.ctx ?? ctx
221
+ const resolvedHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, hookCtx)
206
222
  const docHead = pageLang === undefined ? resolvedHead : { ...resolvedHead, lang: pageLang, htmlAttrs: { ...resolvedHead.htmlAttrs, lang: pageLang } }
207
223
  rctx.headFlushed = true
208
224
  const renderedIslands = resolveRenderedIslands(rctx, body)
@@ -210,6 +226,7 @@ async function renderPageDocument(
210
226
  const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
211
227
  const preloadChunks = [...isStreamed ? entry.eagerIslandChunks ?? entry.islandChunks : renderedIslands.eagerChunks, ...revivePreload(rctx, deps.manifest.reviveScript)]
212
228
  const hasRegions = rctx.regionNames.size > 0
229
+ const needsIslandStyle = hasIslands || (doc.regionScript !== undefined && doc.runtimeScript !== undefined)
213
230
  const trustedStyleHashes = mergeStyleHashes(route.headStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles))
214
231
 
215
232
  if (isStreamed) {
@@ -218,27 +235,27 @@ async function renderPageDocument(
218
235
  if (ctx.request.method === 'HEAD') {
219
236
  rctx.aborted = true
220
237
  endTimer(timing, 'stream', streamStart)
221
- const headers = withRegionVary(deps.htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions)
238
+ const headers = withRegionVary(deps.htmlHeaders(needsIslandStyle, true, true, trustedStyleHashes), hasRegions)
222
239
  if (deps.compressCache !== undefined)
223
240
  headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
224
241
  return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers })) }
225
242
  }
226
243
  setIdleTimeout?.(0)
227
244
  const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
228
- const shell = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
245
+ const shell = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docShell, ctx.url, ctx.request, hookCtx) : docShell
229
246
  const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
230
247
  rctx.headersFlushed = true
231
248
  endTimer(timing, 'stream', streamStart)
232
- const transformChunk = deps.hasHtmlTransformers ? (html: string) => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined
233
- const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk, deps.streams), 200, withRegionVary(deps.htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
249
+ const transformChunk = deps.hasHtmlTransformers ? (html: string) => deps.applyHtmlTransforms(html, ctx.url, ctx.request, hookCtx) : undefined
250
+ const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk, deps.streams), 200, withRegionVary(deps.htmlHeaders(needsIslandStyle, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
234
251
  return { kind: 'stream', response }
235
252
  }
236
253
 
237
254
  const docHtml = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
238
- const html = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
255
+ const html = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docHtml, ctx.url, ctx.request, hookCtx) : docHtml
239
256
  const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
240
257
  endTimer(timing, 'render', renderStart)
241
- return { kind: 'html', html, headers: withRegionVary(deps.htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions) }
258
+ return { kind: 'html', html, headers: withRegionVary(deps.htmlHeaders(needsIslandStyle, false, true, finalStyleHashes), hasRegions) }
242
259
  }
243
260
 
244
261
  async function revalidateCompiledRoute(
@@ -253,12 +270,15 @@ async function revalidateCompiledRoute(
253
270
  const routeCache = deps.routeCache
254
271
  if (routeCache === undefined)
255
272
  return
273
+ const generation = routeCache.generation
256
274
  await runWithAppContext(deps.serverAppCtx, async () => {
257
275
  const bgReq = new Request(url.href, { method: 'GET' })
258
276
  const bgReqId = deps.resolveRequestId(bgReq)
259
- const { ctx, cookieStore } = makeRequestContext(bgReq, { ...params }, { trustProxy: deps.trustProxy, url, consent: deps.consent, requestId: bgReqId })
277
+ const { ctx, cookieStore } = makeRequestContext(bgReq, { ...params }, { trustProxy: deps.trustProxy, httpsSite: deps.httpsSite, url, consent: deps.consent, requestId: bgReqId })
260
278
  for (const rewrite of deps.rewrites)
261
279
  rewrite(url.pathname, ctx)
280
+ if (deps.rewrites.length > 0)
281
+ markUrlDerivedLocals(ctx.locals)
262
282
  await deps.actions.run(ctx, async () => {
263
283
  let rendered: RenderedPageOutput | undefined
264
284
  let nonCacheable = false
@@ -275,7 +295,7 @@ async function revalidateCompiledRoute(
275
295
  return new Response(null, { status: 404 })
276
296
  }
277
297
  if (error instanceof Response) {
278
- void error.body?.cancel().catch(() => undefined)
298
+ void cancelQuietly(error.body)
279
299
  throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
280
300
  }
281
301
  throw error
@@ -293,9 +313,11 @@ async function revalidateCompiledRoute(
293
313
  ? new Response(null, { status: 200, headers: rendered.headers })
294
314
  : rendered.response
295
315
  })
316
+ if (routeCache.generation !== generation)
317
+ return
296
318
  if (!nonCacheable && rendered?.kind === 'html' && res.status === 200 && !cookieStore.hasChanges)
297
319
  routeCache.set(cacheKey, rendered.html, withCacheControl(rendered.headers, cacheSpec.cacheControl), cacheSpec)
298
- else
320
+ else if (rendered !== undefined || (res.status !== 401 && res.status !== 403 && (res.status < 300 || res.status >= 400)))
299
321
  routeCache.delete(cacheKey)
300
322
  })
301
323
  })
@@ -305,7 +327,7 @@ async function runCompiledRouteLoad(
305
327
  deps: CompiledRouteRendererDeps,
306
328
  route: CompiledRoute,
307
329
  ctx: RequestContext,
308
- timing?: DevTiming,
330
+ timing?: PhaseTiming,
309
331
  ): Promise<{ kind: 'response', response: Response } | { kind: 'data', data: unknown }> {
310
332
  const { entry, mod } = route
311
333
  let data: unknown
@@ -318,7 +340,7 @@ async function runCompiledRouteLoad(
318
340
  if (isNotFound(error))
319
341
  return { kind: 'response', response: await deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file) }
320
342
  if (error instanceof Response) {
321
- void error.body?.cancel().catch(() => undefined)
343
+ void cancelQuietly(error.body)
322
344
  throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
323
345
  }
324
346
  throw error
@@ -350,9 +372,9 @@ async function resolvePrerenderedOrApi(
350
372
  const method = ctx.request.method.toUpperCase()
351
373
  const methodHandler = routeMethodHandler(mod, method)
352
374
  if (methodHandler !== undefined)
353
- return await methodHandler(ctx)
375
+ return await validateRouteInput(mod.schema, ctx) ?? await methodHandler(ctx)
354
376
  if (method === 'HEAD' && typeof mod.GET === 'function')
355
- return stripHeadBody(await mod.GET(ctx))
377
+ return await validateRouteInput(mod.schema, ctx) ?? stripHeadBody(await mod.GET(ctx))
356
378
  return undefined
357
379
  }
358
380
 
@@ -363,7 +385,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
363
385
  cookieStore: CookieStore,
364
386
  setIdleTimeout?: (seconds: number) => void,
365
387
  staticPath?: string,
366
- timing?: DevTiming,
388
+ timing?: PhaseTiming,
367
389
  middlewares: readonly Middleware[] = route.middlewares,
368
390
  ): Promise<Response> {
369
391
  const { entry, mod, doc } = route
@@ -384,14 +406,16 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
384
406
  const cacheSpec = deps.routeCache !== undefined && !isRegion && !hasFlash && isCacheableRequest(ctx.request) ? entry.cache : undefined
385
407
  const cacheKey = cacheSpec !== undefined ? routeCacheKey(ctx.url) : undefined
386
408
  let inflight: PromiseWithResolvers<RouteCacheSingleflightResult | undefined> | undefined
409
+ const generation = deps.routeCache?.generation
387
410
  if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined) {
411
+ // A gate may read a cookie, a header or the client address, none of which an anonymous background render carries: a gated route revalidates synchronously on the request that passed it.
388
412
  const cached = serveCachedHit(
389
413
  deps.routeCache,
390
414
  cacheKey,
391
415
  ctx.request,
392
416
  ctx.requestId,
393
417
  deps.compressCache,
394
- () => revalidateCompiledRoute(deps, route, ctx.url, ctx.params, cacheKey, cacheSpec, middlewares),
418
+ route.gated ? undefined : () => revalidateCompiledRoute(deps, route, ctx.url, ctx.params, cacheKey, cacheSpec, middlewares),
395
419
  error => deps.notifyError(error, ctx.request, 'route', ctx.requestId),
396
420
  )
397
421
  if (cached !== undefined)
@@ -404,7 +428,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
404
428
  }
405
429
  else {
406
430
  inflight = Promise.withResolvers<RouteCacheSingleflightResult | undefined>()
407
- void inflight.promise.catch(() => undefined)
431
+ markHandled(inflight.promise)
408
432
  deps.routeCache.trackInflight(cacheKey, inflight.promise)
409
433
  }
410
434
  }
@@ -422,6 +446,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
422
446
  rctx => deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
423
447
  deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId),
424
448
  deps.hasHtmlTransformers ? html => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
449
+ doc.buildId,
425
450
  )
426
451
  }
427
452
 
@@ -432,7 +457,8 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
432
457
  return compressedHtmlResponse(rendered.html, 200, withCacheControl(rendered.headers, 'private, no-store'), ctx.request, deps.compressCache)
433
458
  if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined && !cookieStore.hasChanges) {
434
459
  const cachedHeaders = withCacheControl(rendered.headers, cacheSpec.cacheControl)
435
- const stored = deps.routeCache.set(cacheKey, rendered.html, cachedHeaders, cacheSpec)
460
+ // A drop while this rendered may have changed what it read: answer with it, but keep it out of the cache.
461
+ const stored = deps.routeCache.generation === generation ? deps.routeCache.set(cacheKey, rendered.html, cachedHeaders, cacheSpec) : undefined
436
462
  inflight?.resolve({ entry: stored, html: rendered.html, headers: cachedHeaders })
437
463
  return deps.routeCache.respondMiss(stored, rendered.html, cachedHeaders, ctx.request, ctx.requestId, deps.compressCache)
438
464
  }
@@ -43,8 +43,9 @@ export interface RouteMatch<T> {
43
43
 
44
44
  const MAX_OPTIONAL_SEGMENTS = 6
45
45
 
46
+ // One trailing slash is dropped; a repeated one is left, so `//` and `/about//` both stay unmatched instead of `//` serving the home page.
46
47
  function normalizePath(path: string): string {
47
- return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
48
+ return path.length > 1 && path.endsWith('/') && !path.endsWith('//') ? path.slice(0, -1) : path
48
49
  }
49
50
 
50
51
  /**
@@ -10,17 +10,17 @@ import type { NormalizedConsentConfig } from './consent'
10
10
  import type { CookieStore } from './cookies'
11
11
  import type { HtmlHeaders } from './document'
12
12
  import type { NotifyError } from './errors'
13
- import type { DevTiming, RequestIdResolver } from './health'
13
+ import type { PhaseTiming, RequestIdResolver } from './health'
14
14
  import type { DeniedInfo, Middleware, RequestContext } from './http'
15
- import type { PrunelleLocals } from './index'
15
+ import type { PrunelleLocals } from './public'
16
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
17
  import type { ParamMatcherMap } from './param-matchers'
18
18
  import type { RequestPath } from './request-path'
19
19
  import type { TrustProxy } from './security'
20
- import { createRenderContext, runWithRenderContext } from '../ssr/context'
20
+ import { createRenderContext, hasRenderedRegions, runWithRenderContext } from '../ssr/context'
21
21
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
22
- import { keepScrollTag } from '../ssr/navigation'
23
- import { compressedHtmlResponse, maybeCompressResponse } from './compress'
22
+ import { withKeepScroll } from '../ssr/navigation'
23
+ import { compressedHtmlResponse, maybeCompressResponse, withVaryAcceptEncoding } from './compress'
24
24
  import { headTagStyleHashes, mergeStyleHashes } from './document'
25
25
  import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
26
26
  import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
@@ -247,6 +247,52 @@ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveSc
247
247
  return { docPrefix, revivingPrefix, docSuffix }
248
248
  }
249
249
 
250
+ interface FastHtmlResponderConfig {
251
+ docPrefix: string
252
+ revivingPrefix: string
253
+ docSuffix: string
254
+ headStyleHashes: readonly string[]
255
+ needsIslandStyle: boolean
256
+ baseVaryHeaders: Record<string, string>
257
+ varyPremerged: boolean
258
+ skipKeepScroll: boolean
259
+ hasLoad: boolean
260
+ htmlHeaders: HtmlHeaders
261
+ compressCache: CompressionCache | undefined
262
+ finish: FastStaticPageOptions['finish']
263
+ withHsts: FastStaticPageOptions['withHsts']
264
+ }
265
+
266
+ function createFastHtmlResponder(cfg: FastHtmlResponderConfig) {
267
+ const { docPrefix, revivingPrefix, docSuffix, headStyleHashes, needsIslandStyle, baseVaryHeaders, varyPremerged, skipKeepScroll, hasLoad, htmlHeaders, compressCache, finish, withHsts } = cfg
268
+ return (body: string, request: Request, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, timing?: PhaseTiming): Response => {
269
+ const prefix = rctx.revives ? revivingPrefix : docPrefix
270
+ const html = skipKeepScroll ? prefix + body + docSuffix : withKeepScroll(prefix, body, docSuffix)
271
+ const hasInlineStyles = rctx.inlineStyles !== undefined
272
+ const hasRegions = hasRenderedRegions(rctx)
273
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
274
+ let res: Response
275
+ if (!hasInlineStyles && !hasRegions) {
276
+ res = compressedHtmlResponse(html, 200, baseVaryHeaders, request, compressCache, !hasLoad, {
277
+ varyPremerged,
278
+ skipMarkHandled: true,
279
+ requestId: reqId,
280
+ serverTiming: st,
281
+ })
282
+ }
283
+ else {
284
+ const styleHashes = hasInlineStyles ? mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles)) : headStyleHashes
285
+ const headers = hasRegions ? withRegionVary(htmlHeaders(needsIslandStyle, false, true, styleHashes), true) : htmlHeaders(needsIslandStyle, false, true, styleHashes)
286
+ res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad, {
287
+ skipMarkHandled: true,
288
+ requestId: reqId,
289
+ serverTiming: st,
290
+ })
291
+ }
292
+ return cookieStore?.hasChanges ? finish(res, request, cookieStore, reqId, st) : withHsts(res, request)
293
+ }
294
+ }
295
+
250
296
  /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
251
297
  export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
252
298
  const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
@@ -255,68 +301,71 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
255
301
  const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
256
302
  const headStyleHashes = headTagStyleHashes(doc.headTags)
257
303
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
258
-
259
- const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
260
- notifyError(error, request, 'route', ctx?.requestId)
304
+ const needsIslandStyle = hasIslands || (doc.regionScript !== undefined && doc.runtimeScript !== undefined)
305
+ const baseHeaders = htmlHeaders(needsIslandStyle, false, true, headStyleHashes)
306
+ const baseVaryHeaders = compressCache !== undefined ? withVaryAcceptEncoding(baseHeaders) : baseHeaders
307
+ const skipRequestScope = !hasLoad && consent === undefined && entry.usesRequestScope === false
308
+ const hasHeadHandler = typeof mod.HEAD === 'function'
309
+
310
+ const fail = (error: unknown, request: Request, url: URL, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, remoteIp?: string): Promise<Response> => {
311
+ notifyError(error, request, 'route', reqId)
312
+ if (ctx === undefined) {
313
+ const built = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
314
+ return renderError(error, built.cookieStore, url, request, built.ctx, entry.file)
315
+ }
261
316
  return renderError(error, cookieStore, url, request, ctx, entry.file)
262
317
  }
263
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
264
- const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
265
- const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
266
- const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
267
- const st = timing !== undefined ? finishRenderTiming(timing) : undefined
268
- const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
269
- res.headers.set('x-request-id', ctx.requestId)
270
- if (st !== undefined)
271
- res.headers.set('server-timing', st)
272
- return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
273
- }
318
+ const respondHtml = createFastHtmlResponder({
319
+ docPrefix, revivingPrefix, docSuffix, headStyleHashes, needsIslandStyle, baseVaryHeaders,
320
+ varyPremerged: compressCache !== undefined, skipKeepScroll: entry.usesKeepScroll === false,
321
+ hasLoad, htmlHeaders, compressCache, finish, withHsts,
322
+ })
274
323
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
275
324
 
276
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
325
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Promise<Response> => {
277
326
  try {
278
- return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
327
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, reqId, cookieStore, timing)
279
328
  }
280
329
  catch (error) {
281
- return fail(error, request, url, cookieStore, ctx)
330
+ return fail(error, request, url, reqId, cookieStore, ctx)
282
331
  }
283
332
  }
284
333
 
285
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
334
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
286
335
  if (layouts.length === 0)
287
- return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
336
+ return respondHtml(inner, request, rctx, reqId, cookieStore, timing)
288
337
  if (singleLayout !== undefined) {
289
338
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
290
339
  if (wrapped instanceof Promise)
291
- return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
292
- return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
340
+ return finishSingleLayout(wrapped, request, url, rctx, reqId, cookieStore, ctx, timing)
341
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, reqId, cookieStore, timing)
293
342
  }
294
343
  return (async () => {
295
344
  try {
296
345
  let cur = inner
297
346
  for (let i = layouts.length - 1; i >= 0; i--)
298
347
  cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
299
- return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
348
+ return respondHtml(cur, request, rctx, reqId, cookieStore, timing)
300
349
  }
301
350
  catch (error) {
302
- return fail(error, request, url, cookieStore, ctx)
351
+ return fail(error, request, url, reqId, cookieStore, ctx)
303
352
  }
304
353
  })()
305
354
  }
306
355
 
307
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
356
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Promise<Response> => {
308
357
  try {
309
- return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
358
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, reqId, cookieStore, ctx, timing)
310
359
  }
311
360
  catch (error) {
312
- return fail(error, request, url, cookieStore, ctx)
361
+ return fail(error, request, url, reqId, cookieStore, ctx)
313
362
  }
314
363
  }
315
364
 
316
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
365
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
317
366
  if (timing !== undefined)
318
367
  timing.render = performance.now()
319
- const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
368
+ const pageProps: Record<string, unknown> = data !== undefined ? { params: {}, locals, url, data } : { params: {}, locals, url }
320
369
  if (entry.isIsland && entry.islandChunk !== undefined) {
321
370
  return wrapLayouts(ssrIsland(
322
371
  entry.islandChunk,
@@ -325,32 +374,42 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
325
374
  entry.islandHydrate as HydrateStrategy | undefined,
326
375
  true,
327
376
  mod.default!.name,
328
- ), request, url, locals, rctx, cookieStore, ctx, timing)
377
+ ), request, url, locals, rctx, reqId, cookieStore, ctx, timing)
329
378
  }
330
379
  const rendered = mod.default!(pageProps)
331
380
  if (rendered instanceof Promise)
332
- return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
333
- return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
381
+ return finishAsyncPage(rendered, request, url, locals, rctx, reqId, cookieStore, ctx, timing)
382
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, reqId, cookieStore, ctx, timing)
334
383
  }
335
384
 
336
385
  return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
337
386
  const reqId = requestId ?? getRequestId(request)
338
- const timing = createTiming(isDev)
387
+ const timing = createTiming(isDev, request)
388
+ if (skipRequestScope && !(hasHeadHandler && request.method === 'HEAD')) {
389
+ const locals: PrunelleLocals = {}
390
+ const rctx = createRenderContext(undefined, undefined, undefined, error => notifyError(error, request, 'route', reqId), true)
391
+ try {
392
+ return runWithRenderContext(rctx, () => renderPage(undefined, request, url, locals, rctx, reqId, undefined, undefined, timing))
393
+ }
394
+ catch (error) {
395
+ return fail(error, request, url, reqId, undefined, undefined, remoteIp)
396
+ }
397
+ }
339
398
  const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
340
- if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
399
+ if (hasHeadHandler && request.method === 'HEAD') {
341
400
  return actions.run(ctx, async () => {
342
401
  try {
343
402
  return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
344
403
  }
345
404
  catch (error) {
346
- return fail(error, request, url, cookieStore, ctx)
405
+ return fail(error, request, url, reqId, cookieStore, ctx)
347
406
  }
348
407
  })
349
408
  }
350
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
409
+ const rctx = createRenderContext(undefined, undefined, consent !== undefined ? ctx.consent : undefined, error => notifyError(error, request, 'route', reqId), true)
351
410
  try {
352
411
  if (!hasLoad)
353
- return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
412
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, reqId, cookieStore, ctx, timing)))
354
413
 
355
414
  return actions.run(ctx, async () => {
356
415
  let loaded: unknown
@@ -361,7 +420,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
361
420
  catch (error) {
362
421
  if (isNotFound(error))
363
422
  return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
364
- return fail(error, request, url, cookieStore, ctx)
423
+ return fail(error, request, url, reqId, cookieStore, ctx)
365
424
  }
366
425
  endTimer(timing, 'load', loadStart)
367
426
  if (isNotFound(loaded))
@@ -374,15 +433,15 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
374
433
  return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
375
434
  }
376
435
  try {
377
- return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
436
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, reqId, cookieStore, ctx, timing))
378
437
  }
379
438
  catch (error) {
380
- return fail(error, request, url, cookieStore, ctx)
439
+ return fail(error, request, url, reqId, cookieStore, ctx)
381
440
  }
382
441
  })
383
442
  }
384
443
  catch (error) {
385
- return fail(error, request, url, cookieStore, ctx)
444
+ return fail(error, request, url, reqId, cookieStore, ctx)
386
445
  }
387
446
  }
388
447
  }
@@ -1,4 +1,4 @@
1
- // HTML allow-list sanitizer for rendered Markdown, shared by @prunellejs/content and the @prunellejs/cms preview: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
1
+ // HTML allow-list sanitizer for rendered Markdown, used by @prunellejs/content: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
2
2
 
3
3
  const DROP_CONTENT_TAGS = new Set([
4
4
  'script',
@@ -290,8 +290,8 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
290
290
  const openIdx = openStack.lastIndexOf(tagName)
291
291
  if (openIdx === -1)
292
292
  continue
293
+ for (let k = openStack.length - 1; k >= openIdx; k--) out += `</${openStack[k]}>`
293
294
  openStack.length = openIdx
294
- out += `</${tagName}>`
295
295
  continue
296
296
  }
297
297
 
@@ -308,6 +308,8 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
308
308
  out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
309
309
  }
310
310
 
311
+ // Close what the input left open, or an untrusted `<div class="hidden">` swallows the page around it.
312
+ for (let k = openStack.length - 1; k >= 0; k--) out += `</${openStack[k]}>`
311
313
  return out
312
314
  }
313
315