prunelle 0.1.1 → 0.5.2

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 (105) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -10,28 +10,38 @@ 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 { Middleware, RequestContext } from './http'
13
+ import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { DeniedInfo, Middleware, RequestContext } from './http'
14
15
  import type { PrunelleLocals } from './index'
15
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
+ import type { ParamMatcherMap } from './param-matchers'
16
18
  import type { RequestPath } from './request-path'
19
+ import type { RouteCache, RouteCacheSpec } from './route-cache'
17
20
  import type { TrustProxy } from './security'
18
21
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
19
22
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
20
23
  import { keepScrollTag } from '../ssr/navigation'
21
24
  import { compressedHtmlResponse, maybeCompressResponse } from './compress'
22
25
  import { headTagStyleHashes, mergeStyleHashes } from './document'
23
- import { isNotFound, makeRequestContext } from './http'
26
+ import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
27
+ import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
24
28
  import { pickPageIslandProps } from './page'
29
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
25
30
  import { withRegionVary } from './region'
26
- import { pathPrefix } from './request-path'
31
+ import { decodeRequestPath, pathPrefix } from './request-path'
32
+ import { isCacheableRequest, serveCachedHit, withCacheControl } from './route-cache'
27
33
  import { Router } from './router'
28
34
  import { styleHashesOf } from './security'
29
35
 
30
36
  const MIDDLEWARE_BASENAME_RE = /(?:^|\/)_middleware\.js$/
37
+ const ROUTE_GROUP_RE = /^\([^/()]+\)$/
38
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
39
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
40
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
31
41
  const CATCH_ALL_BRACKET_RE = /\[\.\.\.([^\]]+)\]/g
32
42
  const PARAM_BRACKET_RE = /\[([^\]]+)\]/g
33
43
 
34
- export type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
44
+ export type FastHandler = (req: Request, remoteIp?: string, url?: URL, requestId?: string) => Response | Promise<Response>
35
45
 
36
46
 
37
47
  export function methodNotAllowed(allow: string): Response {
@@ -42,7 +52,14 @@ export function methodNotAllowed(allow: string): Response {
42
52
  export function toBunRouteKey(path: string): string | undefined {
43
53
  if (path.includes('*'))
44
54
  return undefined
45
- return path.split('/').map(encodeURIComponent).join('/')
55
+ return path.split('/').map((seg) => {
56
+ if (seg.includes('%')) {
57
+ const decoded = decodeRequestPath(`/${seg}`)
58
+ if (decoded?.staticPath !== undefined)
59
+ return encodeURIComponent(decoded.staticPath.slice(1))
60
+ }
61
+ return encodeURIComponent(seg)
62
+ }).join('/')
46
63
  }
47
64
 
48
65
  function dirnamePrefix(file: string): string {
@@ -50,10 +67,26 @@ function dirnamePrefix(file: string): string {
50
67
  return slash === -1 ? '' : file.slice(0, slash + 1)
51
68
  }
52
69
 
70
+ function convertDirSegment(seg: string): string {
71
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(seg)
72
+ if (opt !== null)
73
+ return `:${opt[1]}?`
74
+ const catchAll = CATCH_ALL_SEG_RE.exec(seg)
75
+ if (catchAll !== null)
76
+ return `*${catchAll[1]}`
77
+ const param = PARAM_SEG_RE.exec(seg)
78
+ if (param !== null)
79
+ return `:${param[1]}`
80
+ return seg.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')
81
+ }
82
+
53
83
  function dirToRoutePattern(relDir: string): string {
54
84
  if (relDir === '')
55
85
  return '/'
56
- return `/${relDir.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')}`
86
+ const parts = relDir.split('/').filter(p => p !== '' && !ROUTE_GROUP_RE.test(p))
87
+ if (parts.length === 0)
88
+ return '/'
89
+ return `/${parts.map(convertDirSegment).join('/')}`
57
90
  }
58
91
 
59
92
  /** Infers the compiled module prefix for files under `routesDir` (e.g. `'server/'` or `'server/src/routes/'`). */
@@ -66,9 +99,17 @@ export function inferRoutesServerPrefix(manifest: BuildManifest): string {
66
99
  const fileParts = route.file.split('/')
67
100
  const pathSegs = route.path === '/' ? [] : route.path.replace(/^\/|\/$/g, '').split('/')
68
101
  const isIndex = fileParts[fileParts.length - 1] === 'index.js'
69
- const routePartCount = pathSegs.length + (isIndex ? 1 : 0)
70
- if (routePartCount <= fileParts.length) {
71
- const prefixParts = fileParts.slice(0, fileParts.length - routePartCount)
102
+ let remaining = pathSegs.length + (isIndex ? 1 : 0)
103
+ let idx = fileParts.length
104
+ while (idx > 0 && remaining > 0) {
105
+ idx--
106
+ if (!ROUTE_GROUP_RE.test(fileParts[idx]!))
107
+ remaining--
108
+ }
109
+ while (idx > 0 && ROUTE_GROUP_RE.test(fileParts[idx - 1]!))
110
+ idx--
111
+ if (remaining === 0) {
112
+ const prefixParts = fileParts.slice(0, idx)
72
113
  return prefixParts.length === 0 ? '' : `${prefixParts.join('/')}/`
73
114
  }
74
115
  }
@@ -107,6 +148,7 @@ export function createAncestorMiddlewareLookup(
107
148
  manifest: BuildManifest,
108
149
  modules: Record<string, unknown>,
109
150
  routesPrefix: string,
151
+ paramMatchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS,
110
152
  ): (path: RequestPath) => AncestorMiddlewareMatch | undefined {
111
153
  const byPattern = new Map<string, Middleware[]>()
112
154
  const seenModules = new Set<string>()
@@ -122,6 +164,9 @@ export function createAncestorMiddlewareLookup(
122
164
  return
123
165
  const rel = modKey.slice(routesPrefix.length)
124
166
  const relDir = rel.replace(MIDDLEWARE_BASENAME_RE, '')
167
+ // A `(group)` middleware only applies to routes/actions inside that group, never to unrelated unmatched URLs.
168
+ if (relDir !== '' && relDir.split('/').some(p => ROUTE_GROUP_RE.test(p)))
169
+ return
125
170
  const pattern = dirToRoutePattern(relDir)
126
171
  let list = byPattern.get(pattern)
127
172
  if (list === undefined) {
@@ -147,7 +192,7 @@ export function createAncestorMiddlewareLookup(
147
192
  if (byPattern.size === 0)
148
193
  return () => undefined
149
194
 
150
- const dirRouter = new Router<Middleware[]>()
195
+ const dirRouter = new Router<Middleware[]>(paramMatchers)
151
196
  for (const [pattern, list] of byPattern)
152
197
  dirRouter.add(pattern, list)
153
198
 
@@ -181,37 +226,86 @@ export interface FastStaticPageOptions {
181
226
  consent?: NormalizedConsentConfig | undefined
182
227
  htmlHeaders: HtmlHeaders
183
228
  compressCache: CompressionCache | undefined
229
+ routeCache?: RouteCache | undefined
184
230
  actions: ActionRegistry
185
- buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext) => Promise<Response>
186
- renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
231
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
232
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
233
+ renderDenied?: ((denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>) | undefined
187
234
  notifyError: NotifyError
188
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
235
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
189
236
  withHsts: (res: Response, request: Request) => Response
237
+ dev?: boolean | undefined
238
+ resolveRequestId?: RequestIdResolver | undefined
190
239
  }
191
240
 
192
- /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
193
- export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
194
- const {
195
- entry,
196
- mod,
197
- layouts,
198
- doc,
199
- reviveScript,
200
- hasIslands,
201
- hasLoad,
202
- trustProxy,
203
- consent,
204
- htmlHeaders,
205
- compressCache,
206
- actions,
207
- buildNotFoundResponse,
208
- renderError,
209
- notifyError,
210
- finish,
211
- withHsts,
212
- } = options
213
-
214
- const eagerChunks = entry.eagerIslandChunks ?? entry.islandChunks
241
+ interface FastRevalidateContext {
242
+ entry: RouteManifestEntry
243
+ mod: LoadedPageModule
244
+ layouts: LoadedLayoutModule[]
245
+ hasLoad: boolean
246
+ hasIslands: boolean
247
+ trustProxy: TrustProxy
248
+ consent: NormalizedConsentConfig | undefined
249
+ htmlHeaders: HtmlHeaders
250
+ routeCache: RouteCache
251
+ actions: ActionRegistry
252
+ notifyError: NotifyError
253
+ getRequestId: RequestIdResolver
254
+ docPrefix: string
255
+ revivingPrefix: string
256
+ docSuffix: string
257
+ headStyleHashes: string[]
258
+ }
259
+
260
+ async function revalidateFastStaticRoute(
261
+ rc: FastRevalidateContext,
262
+ url: URL,
263
+ cacheKey: string,
264
+ cacheSpec: RouteCacheSpec,
265
+ ): Promise<void> {
266
+ const bgReq = new Request(url.href, { method: 'GET' })
267
+ const bgReqId = rc.getRequestId(bgReq)
268
+ const { ctx, cookieStore } = makeRequestContext(bgReq, {}, { trustProxy: rc.trustProxy, url, consent: rc.consent, requestId: bgReqId })
269
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => rc.notifyError(error, bgReq, 'route', bgReqId))
270
+ await rc.actions.run(ctx, async () => {
271
+ let data: unknown
272
+ if (rc.hasLoad) {
273
+ try {
274
+ data = await rc.mod.load!(ctx)
275
+ }
276
+ catch (error) {
277
+ if (isNotFound(error)) {
278
+ rc.routeCache.delete(cacheKey)
279
+ return
280
+ }
281
+ throw error
282
+ }
283
+ if (isNotFound(data) || data instanceof Response) {
284
+ rc.routeCache.delete(cacheKey)
285
+ return
286
+ }
287
+ }
288
+ const body = await runWithRenderContext(rctx, async () => {
289
+ const pageProps: Record<string, unknown> = { params: {}, locals: ctx.locals, url, ...(data !== undefined ? { data } : {}) }
290
+ let cur = rc.entry.isIsland && rc.entry.islandChunk !== undefined
291
+ ? ssrIsland(rc.entry.islandChunk, () => ssrChild(rc.mod.default!(pageProps) as Html), pickPageIslandProps(data, rc.entry, rc.mod), rc.entry.islandHydrate as HydrateStrategy | undefined, true, rc.mod.default!.name)
292
+ : ssrChild(await rc.mod.default!(pageProps) as Html)
293
+ for (let i = rc.layouts.length - 1; i >= 0; i--)
294
+ cur = ssrChild(await rc.layouts[i]!.default({ children: raw(cur), url, params: {}, locals: ctx.locals }) as Html)
295
+ return cur
296
+ })
297
+ if (cookieStore.hasChanges) {
298
+ rc.routeCache.delete(cacheKey)
299
+ return
300
+ }
301
+ const html = (rctx.revives ? rc.revivingPrefix : rc.docPrefix) + body + keepScrollTag(body) + rc.docSuffix
302
+ const styleHashes = mergeStyleHashes(rc.headStyleHashes, styleHashesOf(rctx.inlineStyles))
303
+ const headers = withCacheControl(withRegionVary(rc.htmlHeaders(rc.hasIslands, false, true, styleHashes), rctx.regionNames.size > 0), cacheSpec.cacheControl)
304
+ rc.routeCache.set(cacheKey, html, headers, cacheSpec)
305
+ })
306
+ }
307
+
308
+ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveScript: string | undefined, hasIslands: boolean): { docPrefix: string, revivingPrefix: string, docSuffix: string } {
215
309
  const shellAround = (preloadChunks: string[]): [string, string] => {
216
310
  const shell = renderDocument({ ...doc, body: '\0', preloadChunks, hasIslands })
217
311
  const splitAt = shell.indexOf('\0')
@@ -219,46 +313,68 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
219
313
  }
220
314
  const [docPrefix, docSuffix] = shellAround(eagerChunks)
221
315
  const revivingPrefix = reviveScript === undefined ? docPrefix : shellAround([...eagerChunks, reviveScript])[0]
316
+ return { docPrefix, revivingPrefix, docSuffix }
317
+ }
318
+
319
+ /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
320
+ export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
321
+ const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, routeCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
322
+ const isDev = options.dev === true
323
+ const getRequestId: RequestIdResolver = options.resolveRequestId ?? (req => resolveFallbackRequestId(req, trustProxy))
324
+ const cacheSpec = routeCache !== undefined ? entry.cache : undefined
325
+ const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
222
326
  const headStyleHashes = headTagStyleHashes(doc.headTags)
223
327
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
328
+ const revalidateCtx: FastRevalidateContext | undefined = cacheSpec !== undefined && routeCache !== undefined
329
+ ? { entry, mod, layouts, hasLoad, hasIslands, trustProxy, consent, htmlHeaders, routeCache, actions, notifyError, getRequestId, docPrefix, revivingPrefix, docSuffix, headStyleHashes }
330
+ : undefined
224
331
 
225
332
  const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
226
- notifyError(error, request, 'route')
227
- return renderError(error, cookieStore, url, request, ctx)
333
+ notifyError(error, request, 'route', ctx?.requestId)
334
+ return renderError(error, cookieStore, url, request, ctx, entry.file)
228
335
  }
229
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore?: CookieStore): Response => {
336
+ const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
230
337
  const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
231
338
  const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
232
339
  const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
340
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
341
+ if (cacheSpec !== undefined && routeCache !== undefined && !cookieStore.hasChanges && isCacheableRequest(request)) {
342
+ const cachedHeaders = withCacheControl(headers, cacheSpec.cacheControl)
343
+ const stored = routeCache.set(ctx.url.pathname + ctx.url.search, html, cachedHeaders, cacheSpec)
344
+ return withHsts(routeCache.respondMiss(stored, html, cachedHeaders, request, ctx.requestId, compressCache, st), request)
345
+ }
233
346
  const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
234
- return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
347
+ res.headers.set('x-request-id', ctx.requestId)
348
+ if (st !== undefined)
349
+ res.headers.set('server-timing', st)
350
+ return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
235
351
  }
236
352
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
237
353
 
238
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
354
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
239
355
  try {
240
- return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore)
356
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
241
357
  }
242
358
  catch (error) {
243
359
  return fail(error, request, url, cookieStore, ctx)
244
360
  }
245
361
  }
246
362
 
247
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
363
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
248
364
  if (layouts.length === 0)
249
- return respondHtml(inner, request, rctx, cookieStore)
365
+ return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
250
366
  if (singleLayout !== undefined) {
251
367
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
252
368
  if (wrapped instanceof Promise)
253
- return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx)
254
- return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore)
369
+ return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
370
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
255
371
  }
256
372
  return (async () => {
257
373
  try {
258
374
  let cur = inner
259
375
  for (let i = layouts.length - 1; i >= 0; i--)
260
376
  cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
261
- return respondHtml(cur, request, rctx, cookieStore)
377
+ return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
262
378
  }
263
379
  catch (error) {
264
380
  return fail(error, request, url, cookieStore, ctx)
@@ -266,16 +382,18 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
266
382
  })()
267
383
  }
268
384
 
269
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
385
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
270
386
  try {
271
- return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx)
387
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
272
388
  }
273
389
  catch (error) {
274
390
  return fail(error, request, url, cookieStore, ctx)
275
391
  }
276
392
  }
277
393
 
278
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
394
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
395
+ if (timing !== undefined)
396
+ timing.render = performance.now()
279
397
  const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
280
398
  if (entry.isIsland && entry.islandChunk !== undefined) {
281
399
  return wrapLayouts(ssrIsland(
@@ -285,47 +403,62 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
285
403
  entry.islandHydrate as HydrateStrategy | undefined,
286
404
  true,
287
405
  mod.default!.name,
288
- ), request, url, locals, rctx, cookieStore, ctx)
406
+ ), request, url, locals, rctx, cookieStore, ctx, timing)
289
407
  }
290
408
  const rendered = mod.default!(pageProps)
291
409
  if (rendered instanceof Promise)
292
- return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx)
293
- return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx)
410
+ return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
411
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
294
412
  }
295
413
 
296
- return (request, remoteIp, url = new URL(request.url)) => {
297
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
414
+ return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
415
+ const reqId = requestId ?? getRequestId(request)
416
+ if (revalidateCtx !== undefined && cacheSpec !== undefined && routeCache !== undefined && !(request.method === 'HEAD' && typeof mod.HEAD === 'function') && isCacheableRequest(request)) {
417
+ const cacheKey = url.pathname + url.search
418
+ const cached = serveCachedHit(routeCache, cacheKey, request, reqId, compressCache, () => revalidateFastStaticRoute(revalidateCtx, url, cacheKey, cacheSpec), error => notifyError(error, request, 'route', reqId))
419
+ if (cached !== undefined)
420
+ return withHsts(cached, request)
421
+ }
422
+ const timing = createTiming(isDev)
423
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId: reqId })
298
424
  if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
299
425
  return actions.run(ctx, async () => {
300
426
  try {
301
- return finish(await mod.HEAD!(ctx), request, cookieStore)
427
+ return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
302
428
  }
303
429
  catch (error) {
304
430
  return fail(error, request, url, cookieStore, ctx)
305
431
  }
306
432
  })
307
433
  }
308
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route'))
434
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
309
435
  try {
310
436
  if (!hasLoad)
311
- return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx)))
437
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
312
438
 
313
439
  return actions.run(ctx, async () => {
314
440
  let loaded: unknown
441
+ const loadStart = startTimer(timing)
315
442
  try {
316
443
  loaded = await mod.load!(ctx)
317
444
  }
318
445
  catch (error) {
319
446
  if (isNotFound(error))
320
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
447
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
321
448
  return fail(error, request, url, cookieStore, ctx)
322
449
  }
450
+ endTimer(timing, 'load', loadStart)
323
451
  if (isNotFound(loaded))
324
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
325
- if (loaded instanceof Response)
326
- return finish(await maybeCompressResponse(loaded, request, compressCache), request, cookieStore)
452
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
453
+ if (loaded instanceof Response) {
454
+ const denied = getDeniedInfo(loaded)
455
+ const out = denied !== undefined && renderDenied !== undefined && acceptsHtml(request)
456
+ ? await renderDenied(denied, url, request, ctx, entry.file)
457
+ : loaded
458
+ return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
459
+ }
327
460
  try {
328
- return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx))
461
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
329
462
  }
330
463
  catch (error) {
331
464
  return fail(error, request, url, cookieStore, ctx)