prunelle 0.1.1 → 0.5.3

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 (120) 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 +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +62 -0
  75. package/src/plugins/types.ts +32 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +128 -31
  90. package/src/server/index.ts +230 -260
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. package/ts-plugin.cjs +4277 -0
@@ -5,42 +5,45 @@
5
5
  // - <Head> collection + cancel-safe streaming <Suspense> (0-overhead fast path when unused)
6
6
  // - Hybrid prerendered HTML serving + embedded single-executable mode
7
7
 
8
- import type { Html, HydrateStrategy } from '../jsx-runtime'
9
8
  import type { ActionRegistry, RegisteredAction } from './action-registry'
9
+ import type { ServedFile } from './assets'
10
10
  import type { NormalizedConsentConfig } from './consent'
11
11
  import type { CookieStore } from './cookies'
12
12
  import type { NotifyError } from './errors'
13
- import type { EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
13
+ import type { DevTiming } from './health'
14
+ import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
14
15
  import type { RateLimiter, RateLimitStore } from './rate-limit'
15
16
  import type { LoadedMiddlewareModule } from './page'
17
+ import type { ServerPluginHost } from './plugin-host'
16
18
  import type { RequestPath } from './request-path'
17
19
  import type { CompiledRoute } from './route-table'
18
20
  import type { FastHandler } from './routing'
19
21
  import type { TrustProxy } from './security'
20
22
  import { join } from 'node:path'
21
23
  import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
22
- import { createRenderContext, runWithRenderContext } from '../ssr/context'
23
24
  import { createNavigation } from '../ssr/navigation'
24
- import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
25
- import { ACTION_ERROR_COOKIE, executeAction, finishActionRedirect, hydrateActionErrorFlash, isServerAction } from './action'
25
+ import { executeAction, finishActionRedirect, isServerAction } from './action'
26
26
  import { createActionRegistry } from './action-registry'
27
27
  import { createAssets } from './assets'
28
- import { CompressionCache, compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, maybeCompressResponse } from './compress'
28
+ import { CompressionCache, maybeCompressResponse } from './compress'
29
29
  import { normalizeConsentConfig } from './consent'
30
- import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeStyleHashes, resolveRenderedIslands, revivePreload, withPluginHtmlCsp } from './document'
30
+ import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './document'
31
31
  import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
32
- import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
33
- import { allowedMethodsHeader, pickPageIslandProps, stripHeadBody } from './page'
34
- import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
32
+ import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
33
+ import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
34
+ import { stripHeadBody } from './page'
35
+ import { resolveParamMatchers } from './param-matchers'
36
+ import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
35
37
 
36
- import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
38
+ import { withRegionVary } from './region'
37
39
  import { decodeRequestPath, literalPath } from './request-path'
38
40
  import { nativePrerenderedCheck } from './prerendered'
39
- import { compileRouteTable } from './route-table'
41
+ import { createRouteCache } from './route-cache'
42
+ import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
40
43
  import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
41
- import { hasActionErrorCookie, isPlainRead, isRead, serveHandlers } from './serve-handlers'
42
- import { buildSecurityHeaderEntries, resolveHstsValue, styleHashesOf, verifyOrigin } from './security'
43
- import { createStreamTracker, STREAM_TAIL_MARK, streamDocument } from './stream'
44
+ import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
45
+ import { buildSecurityHeaderEntries, resolveHstsValue, verifyOrigin } from './security'
46
+ import { createStreamTracker } from './stream'
44
47
 
45
48
  /**
46
49
  * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
@@ -48,8 +51,9 @@ import { createStreamTracker, STREAM_TAIL_MARK, streamDocument } from './stream'
48
51
  */
49
52
  export interface PrunelleLocals {}
50
53
 
51
- export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
52
- export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ComplianceConfig, ComplianceRule, ConsentConfig, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
54
+ export { CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, JOBS_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
55
+ export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ComplianceConfig, ComplianceRule, ConsentConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, JobsEnqueueOptions, JobsQueueOptions, JobsService, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
56
+ export { currentRequest } from './request-scope'
53
57
  export { action, getActionError } from './action'
54
58
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
55
59
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
@@ -57,9 +61,12 @@ export type { CompressionEncoding, PrecompressedEncoding } from './compress'
57
61
  export type { RequestConsent } from './consent'
58
62
  export type { CookieOptions, Cookies } from './cookies'
59
63
  export { defineEnv, nodeEnv } from './env'
64
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
60
65
  export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
61
- export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
66
+ export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
62
67
  export { createServer } from './loader'
68
+ export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
69
+ export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
63
70
  export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
64
71
  export type { SecurityHeadersOptions, TrustProxy } from './security'
65
72
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
@@ -70,39 +77,80 @@ const DEFAULT_STREAM_TIMEOUT = 30_000
70
77
 
71
78
 
72
79
  const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
80
+ const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
81
+
82
+ function maybeRenderDenied(
83
+ res: Response,
84
+ request: Request,
85
+ url: URL,
86
+ ctx: RequestContext,
87
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
88
+ routeFile?: string,
89
+ isApi = false,
90
+ ): Response | Promise<Response> {
91
+ if (isApi)
92
+ return res
93
+ const denied = getDeniedInfo(res)
94
+ if (denied === undefined || !acceptsHtml(request))
95
+ return res
96
+ return renderDenied(denied, url, request, ctx, routeFile)
97
+ }
98
+
73
99
  const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
74
100
  // A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
75
101
  const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
76
102
  const makeFileGone = (securityRecord: Record<string, string>) => (): Response => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...securityRecord } })
77
103
 
78
- function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string | undefined): T | undefined {
104
+ function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
105
+ const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
106
+ return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
107
+ }
108
+
109
+ function matchStaticOrPublic(
110
+ request: Request,
111
+ requestPath: RequestPath,
112
+ assetMap: ReadonlyMap<string, ServedFile>,
113
+ publicMap: ReadonlyMap<string, ServedFile>,
114
+ pluginRouter: ServerPluginHost['router'],
115
+ ): ServedFile | undefined {
116
+ const { staticPath } = requestPath
79
117
  if (staticPath === undefined)
80
118
  return undefined
81
- const normPath = staticPath.length > 1 && staticPath.endsWith('/') ? staticPath.slice(0, -1) : staticPath
82
- return map.get(staticPath) ?? map.get(normPath)
119
+ const asset = assetMap.get(staticPath)
120
+ if (asset !== undefined)
121
+ return asset
122
+ const pub = publicMap.get(staticPath)
123
+ if (pub === undefined)
124
+ return undefined
125
+ const matchedPlugin = pluginRouter.match(requestPath)
126
+ const reqMethod = request.method.toUpperCase()
127
+ const shadowedByPlugin = matchedPlugin !== undefined
128
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
129
+ return shadowedByPlugin ? undefined : pub
83
130
  }
84
131
 
85
- async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: Record<string, unknown>, ctx: RequestContext): Promise<string> {
86
- const { entry, mod, layouts } = route
87
- let inner: string
88
- if (entry.isIsland && entry.islandChunk !== undefined) {
89
- inner = ssrIsland(
90
- entry.islandChunk,
91
- () => ssrChild(mod.default!(pageProps) as Html),
92
- pickPageIslandProps(data, entry, mod),
93
- entry.islandHydrate as HydrateStrategy | undefined,
94
- true, mod.default!.name,
95
- )
96
- }
97
- else {
98
- inner = ssrChild(await mod.default!(pageProps) as Html)
132
+ function createRequestGuards(
133
+ maxRequestBodySize: number,
134
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
135
+ ) {
136
+ const refuseCrossSite = (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string): Response =>
137
+ finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore, requestId)
138
+
139
+ const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
140
+ if (bodyLimited)
141
+ return request
142
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
143
+ if (bounded.ok)
144
+ return bounded.request
145
+ const status = bounded.aborted ? 400 : 413
146
+ const message = bounded.aborted ? 'Bad Request' : 'Payload Too Large'
147
+ return finish(wantsJson(request)
148
+ ? Response.json({ ok: false, status, error: message }, { status })
149
+ : new Response(message, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
99
150
  }
100
- for (let i = layouts.length - 1; i >= 0; i--)
101
- inner = ssrChild(await layouts[i]!.default({ children: raw(inner), url: ctx.url, params: ctx.params, locals: ctx.locals }) as Html)
102
- return inner
151
+ return { refuseCrossSite, checkBodyLimit }
103
152
  }
104
153
 
105
-
106
154
  interface ActionDispatcherDeps {
107
155
  actions: ActionRegistry
108
156
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
@@ -110,15 +158,16 @@ interface ActionDispatcherDeps {
110
158
  trustProxy: TrustProxy
111
159
  consent: NormalizedConsentConfig | undefined
112
160
  rateLimits: RateLimitStore
113
- refuseCrossSite: (request: Request, reason: string, cookieStore?: CookieStore) => Response
114
- checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore) => Promise<Request | Response>
115
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
161
+ isDev: boolean
162
+ refuseCrossSite: (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string) => Response
163
+ checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
164
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
116
165
  notifyError: NotifyError
117
166
  renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
118
167
  }
119
168
 
120
169
  function createActionDispatcher(deps: ActionDispatcherDeps) {
121
- const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
170
+ const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
122
171
  const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
123
172
  const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
124
173
  if (act.rateLimit === undefined)
@@ -137,6 +186,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
137
186
  rawPathname: string,
138
187
  remoteIp: string | undefined,
139
188
  bodyLimited: boolean,
189
+ requestId: string,
140
190
  existing?: { ctx: RequestContext, cookieStore: CookieStore },
141
191
  ): Promise<Response> => {
142
192
  const actionHandler = request.method === 'POST' ? registeredAction : undefined
@@ -144,29 +194,30 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
144
194
  if (actionHandler !== undefined) {
145
195
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
146
196
  if (!originCheck.ok)
147
- return refuseCrossSite(request, originCheck.reason, existing?.cookieStore)
148
- const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore)
197
+ return refuseCrossSite(request, originCheck.reason, existing?.cookieStore, requestId)
198
+ const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
149
199
  if (checked instanceof Response)
150
200
  return checked
151
201
  req = checked
152
202
  }
153
203
  const { act, middlewares } = registeredAction
154
- const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent })
204
+ const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent, requestId })
155
205
  ctx.request = req
156
206
  if (existing === undefined && rewrites.length > 0) {
157
207
  for (const rewrite of rewrites)
158
208
  rewrite(rawPathname, ctx)
159
209
  }
210
+ const timing = createTiming(isDev)
160
211
  try {
161
- const res = await actions.run(ctx, () => runChain(ctx, middlewares, () =>
212
+ const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
162
213
  actionHandler !== undefined
163
214
  ? executeAction(act, req, ctx, trustedOrigins, trustProxy, limiterFor(act))
164
215
  : methodNotAllowed('POST'),
165
- ))
166
- return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore)
216
+ timing, runChain))
217
+ return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore, ctx.requestId, formatServerTiming(timing))
167
218
  }
168
219
  catch (error) {
169
- notifyError(error, req, 'action')
220
+ notifyError(error, req, 'action', ctx.requestId)
170
221
  return renderError(error, cookieStore, ctx.url, req, ctx)
171
222
  }
172
223
  }
@@ -195,6 +246,44 @@ function registerManifestActions({ manifest, modules, actions, routesPrefix, rou
195
246
  }
196
247
  }
197
248
 
249
+ interface NotFoundRendererDeps {
250
+ actions: ActionRegistry
251
+ pluginMiddlewaresFor: (effectiveScopedPath: string, rawScopedPath: string) => readonly Middleware[]
252
+ ancestorMiddlewaresFor: ReturnType<typeof createAncestorMiddlewareLookup>
253
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
254
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
255
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
256
+ notifyError: NotifyError
257
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
258
+ }
259
+
260
+ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
261
+ const { actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse, renderDenied, renderError, notifyError, finish } = deps
262
+ return async (
263
+ cookieStore: CookieStore,
264
+ url: URL,
265
+ request: Request,
266
+ ctx: RequestContext,
267
+ effective: RequestPath,
268
+ rawScopedPath: string,
269
+ timing?: DevTiming,
270
+ ): Promise<Response> => {
271
+ const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
272
+ const ancestor = ancestorMiddlewaresFor(effective)
273
+ if (ancestor !== undefined)
274
+ ctx.params = ancestor.params
275
+ const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
276
+ try {
277
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx), timing, runChain))
278
+ return finish(await maybeRenderDenied(rawRes, request, url, ctx, renderDenied), request, cookieStore, ctx.requestId, formatServerTiming(timing))
279
+ }
280
+ catch (error) {
281
+ notifyError(error, request, 'route', ctx.requestId)
282
+ return renderError(error, cookieStore, url, request, ctx)
283
+ }
284
+ }
285
+ }
286
+
198
287
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
199
288
  const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
200
289
  const plugins = resolvePlugins(config.plugins)
@@ -223,7 +312,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
223
312
  const hstsValue = resolveHstsValue(security)
224
313
  const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
225
314
  // The one way out of every response not built with the security headers already in place.
226
- const finish = (res: Response, request: Request, cookieStore?: CookieStore): Response => withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
315
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
316
+ withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
317
+ const resolveRequestId = createRequestIdResolver(trustProxy)
227
318
  const serverError = makeServerError(securityRecord)
228
319
  const fileGone = makeFileGone(securityRecord)
229
320
  const navigation = createNavigation(config.navigation)
@@ -232,6 +323,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
232
323
 
233
324
  const compressEnabled = config.compress ?? !isDev
234
325
  const compressCache = compressEnabled ? new CompressionCache() : undefined
326
+ const routeCache = createRouteCache(config.routeCache, isDev || config.prerender === true)
235
327
 
236
328
  const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, securityRecord, withHsts })
237
329
  const { assetMap, publicMap, serveFile } = files
@@ -266,221 +358,98 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
266
358
  trustedOrigins,
267
359
  })
268
360
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
361
+ const healthPath = `${assetPrefix}/health`
269
362
  const hasPluginRewrites = pluginHost.rewrites.length > 0
270
- const routesPrefix = inferRoutesServerPrefix(manifest)
271
- const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
272
- const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix)
273
363
  const pluginMiddlewaresFor = (effectiveScopedPath: string, rawScopedPath: string): readonly Middleware[] =>
274
- effectiveScopedPath === rawScopedPath
275
- ? middlewaresFor(effectiveScopedPath)
276
- : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
277
-
278
- registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
279
-
280
-
281
- const { buildNotFoundResponse, renderError } = createFallbackPages({ manifest, modules, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
282
-
283
- async function renderNotFound(
284
- cookieStore: CookieStore,
285
- url: URL,
286
- request: Request,
287
- ctx: RequestContext,
288
- effective: RequestPath,
289
- rawScopedPath: string,
290
- ): Promise<Response> {
291
- const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
292
- const ancestor = ancestorMiddlewaresFor(effective)
293
- if (ancestor !== undefined)
294
- ctx.params = ancestor.params
295
- const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
296
- try {
297
- const res = await actions.run(ctx, () => runChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx)))
298
- return finish(res, request, cookieStore)
299
- }
300
- catch (error) {
301
- notifyError(error, request, 'route')
302
- return renderError(error, cookieStore, url, request, ctx)
303
- }
364
+ effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
365
+
366
+ let healthHandler: ReturnType<typeof createHealthHandler>
367
+ let renderError: ReturnType<typeof createFallbackPages>['renderError']
368
+ let renderDenied: ReturnType<typeof createFallbackPages>['renderDenied']
369
+ let renderNotFound: ReturnType<typeof createNotFoundRenderer>
370
+ let refuseCrossSite: ReturnType<typeof createRequestGuards>['refuseCrossSite']
371
+ let checkBodyLimit: ReturnType<typeof createRequestGuards>['checkBodyLimit']
372
+ let router: ReturnType<typeof compileRouteTable>['router']
373
+ let fastStaticPages: ReturnType<typeof compileRouteTable>['fastStaticPages']
374
+ let fastPrerenderedMap: ReadonlyMap<string, ServedFile>
375
+ let renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
376
+ let dispatchAction: ReturnType<typeof createActionDispatcher>
377
+ try {
378
+ healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId })
379
+ const routesPrefix = inferRoutesServerPrefix(manifest)
380
+ const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
381
+ const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
382
+ const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
383
+ registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
384
+ const fallbacks = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
385
+ renderError = fallbacks.renderError
386
+ renderDenied = fallbacks.renderDenied
387
+ renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
388
+ ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
389
+ ;({ router, fastStaticPages } = compileRouteTable({
390
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
391
+ pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
392
+ fast: { trustProxy, consent, htmlHeaders, compressCache, routeCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
393
+ }))
394
+ const collected = files.collectPrerendered(manifest.routes, {
395
+ prerendered, prerenderedFiles, prerenderedEtags,
396
+ // The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
397
+ htmlHeaders: (route, urlPath) => withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true),
398
+ isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
399
+ })
400
+ fastPrerenderedMap = collected.fast
401
+ renderCompiledRoute = createCompiledRouteRenderer({
402
+ manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
403
+ })
404
+ dispatchAction = createActionDispatcher({
405
+ actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
406
+ })
304
407
  }
305
-
306
- function refuseCrossSite(request: Request, reason: string, cookieStore?: CookieStore): Response {
307
- return finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore)
408
+ catch (error) {
409
+ await pluginHost.dispose()
410
+ throw error
308
411
  }
309
412
 
310
- async function checkBodyLimit(request: Request, bodyLimited: boolean, cookieStore?: CookieStore): Promise<Request | Response> {
311
- if (bodyLimited)
312
- return request
313
- const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
314
- if (bounded.ok)
315
- return bounded.request
316
- return finish(wantsJson(request)
317
- ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
318
- : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore)
319
- }
320
-
321
- const { router, fastStaticPages } = compileRouteTable({
322
- manifest, modules, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
323
- pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
324
- fast: { trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, notifyError, finish, withHsts },
325
- })
326
- const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
327
- prerendered,
328
- prerenderedFiles,
329
- prerenderedEtags,
330
- // The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
331
- htmlHeaders: (route, urlPath) => withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true),
332
- isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
333
- })
334
-
335
- async function renderCompiledRoute(
336
- route: CompiledRoute,
337
- ctx: RequestContext,
338
- disableTimeout?: () => void,
339
- staticPath?: string,
340
- ): Promise<Response> {
341
- const { entry, mod, doc } = route
342
-
343
- const isRegion = hasRegionHeader(ctx.request)
344
- // Serve prerendered HTML after middlewares have passed (skip on full-page GETs with a flash cookie so it hydrates & clears, and on region requests)
345
- if (isRead(ctx.request)) {
346
- const pre = lookupPrerendered(prerenderedMap, staticPath)
347
- if (pre !== undefined && !isRegion && (ctx.request.method === 'HEAD' || !hasActionErrorCookie(ctx.request)))
348
- return serveFile(ctx.request, pre)
349
- // Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
350
- if (pre === undefined && entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
351
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
352
- }
353
-
354
- // API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
355
- const method = ctx.request.method.toUpperCase()
356
- const methodHandler = mod[method]
357
- if (typeof methodHandler === 'function')
358
- return await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
359
- if (method === 'HEAD' && typeof mod.GET === 'function')
360
- return stripHeadBody(await mod.GET(ctx))
361
-
362
- // Page routes only handle GET/HEAD; unsafe methods (POST/PUT/PATCH/DELETE) without a method export get 405.
363
- if (typeof mod.default !== 'function' || !isRead(ctx.request))
364
- return methodNotAllowed(allowedMethodsHeader(mod))
365
- if (isRegion && requestedRegion(ctx.request) === undefined)
366
- return invalidRegionResponse(ctx.request)
367
-
368
- // Hydrate one-shot flash cookie on full page GETs only; defer deletion until a full page renders (not load() redirects or <Region> requests)
369
- const hasFlash = ctx.request.method === 'GET' && !isRegion && hasActionErrorCookie(ctx.request) && hydrateActionErrorFlash(ctx)
370
-
371
- let data: unknown
372
- if (entry.hasLoad && typeof mod.load === 'function') {
373
- try {
374
- data = await mod.load(ctx)
375
- }
376
- catch (error) {
377
- if (isNotFound(error))
378
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
379
- throw error
380
- }
381
- }
382
- if (isNotFound(data))
383
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
384
- if (data instanceof Response)
385
- return data
386
- const pageProps: Record<string, unknown> = {
387
- params: ctx.params,
388
- locals: ctx.locals,
389
- url: ctx.url,
390
- ...(data !== undefined ? { data } : {}),
391
- }
392
-
393
- if (isRegion) {
394
- return respondRegion(
395
- ctx.request, mod, pageProps, entry.path, htmlHeaders,
396
- rctx => resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
397
- streamTimeout, error => notifyError(error, ctx.request, 'route'),
398
- hasHtmlTransformers ? html => applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
399
- )
400
- }
401
-
402
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, ctx.request, 'route'))
403
- const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, ctx))
404
- if (hasFlash)
405
- ctx.cookies.delete(ACTION_ERROR_COOKIE)
406
- const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
407
- const renderedIslands = resolveRenderedIslands(rctx, body)
408
- const isStreamed = rctx.pending.length > 0
409
- const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
410
- // A streamed page preloads before its boundaries render, so it takes the route's eager islands: a lazy one loads when its strategy fires.
411
- const preloadChunks = [...isStreamed ? entry.eagerIslandChunks ?? entry.islandChunks : renderedIslands.eagerChunks, ...revivePreload(rctx, manifest.reviveScript)]
412
- const hasRegions = rctx.regionNames.size > 0
413
-
414
- const trustedStyleHashes = mergeStyleHashes(route.headStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles))
415
-
416
- // Streaming SSR when <Suspense> boundaries are pending, compressed per flush, never buffered
417
- if (isStreamed) {
418
- if (ctx.request.method === 'HEAD')
419
- return markCompressionHandled(new Response(null, { status: 200, headers: withRegionVary(htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions) }))
420
- disableTimeout?.()
421
- const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
422
- // Transforms see the document with its initial body; boundaries resolved later stream as they render.
423
- const shell = hasHtmlTransformers ? await applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
424
- const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
425
- return compressedHtmlStream(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route')), 200, withRegionVary(htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, compressCache)
426
- }
427
-
428
- const docHtml = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
429
- const html = hasHtmlTransformers ? await applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
430
- const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
431
-
432
- return compressedHtmlResponse(html, 200, withRegionVary(htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions), ctx.request, compressCache)
433
- }
434
-
435
- const dispatchAction = createActionDispatcher({
436
- actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
437
- })
438
-
439
413
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
440
414
  async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
415
+ const requestId = resolveRequestId(request)
441
416
  try {
442
417
  const url = new URL(request.url)
443
418
  const rawPathname = url.pathname
444
419
  const requestPath = decodeRequestPath(rawPathname)
445
420
  if (requestPath === undefined)
446
- return finish(badRequest(), request)
421
+ return finish(badRequest(), request, undefined, requestId)
447
422
  const { staticPath, scopedPath } = requestPath
423
+ if (staticPath === healthPath)
424
+ return healthHandler(request, requestId)
448
425
  const read = isRead(request)
449
426
 
450
427
  // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
451
- if (read && staticPath !== undefined) {
452
- const asset = assetMap.get(staticPath)
453
- if (asset !== undefined)
454
- return serveFile(request, asset)
455
- const pub = publicMap.get(staticPath)
456
- if (pub !== undefined) {
457
- const matchedPlugin = pluginRouter.match(requestPath)
458
- const reqMethod = request.method.toUpperCase()
459
- const shadowedByPlugin = matchedPlugin !== undefined
460
- && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
461
- if (!shadowedByPlugin)
462
- return serveFile(request, pub)
463
- }
428
+ if (read) {
429
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
430
+ if (staticFile !== undefined)
431
+ return withRequestId(await serveFile(request, staticFile), requestId)
464
432
  }
465
433
 
466
434
  // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
467
435
  const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
468
436
  if (registeredAction !== undefined)
469
- return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited)
437
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
470
438
 
471
439
  // 3. Prerendered static HTML, then 4. the zero-overhead static route path
472
440
  const plainRead = isPlainRead(request)
473
441
  if (plainRead && staticPath !== undefined) {
474
442
  const pre = fastPrerenderedMap.get(staticPath)
475
443
  if (pre !== undefined)
476
- return serveFile(request, pre)
444
+ return withRequestId(await serveFile(request, pre), requestId)
477
445
  const fast = fastStaticPages.get(staticPath)
478
446
  if (fast !== undefined)
479
- return fast(request, remoteIp, url)
447
+ return fast(request, remoteIp, url, requestId)
480
448
  }
481
449
 
482
450
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
483
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
451
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId })
452
+ const timing = createTiming(isDev)
484
453
 
485
454
  // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
486
455
  let effectivePath = rawPathname
@@ -493,17 +462,17 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
493
462
  if (effectivePath !== rawPathname) {
494
463
  const rewritten = decodeRequestPath(effectivePath)
495
464
  if (rewritten === undefined)
496
- return finish(badRequest(), request, cookieStore)
465
+ return finish(badRequest(), request, cookieStore, requestId)
497
466
  effective = rewritten
498
467
  const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
499
468
  if (rewrittenAction !== undefined)
500
- return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, { ctx, cookieStore })
469
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
501
470
  }
502
471
  const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
503
472
 
504
473
  // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
505
474
  const method = request.method.toUpperCase()
506
- const pluginMatch = pluginRouter.match(effective)
475
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
507
476
  const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
508
477
  const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
509
478
  const routeDef = directPluginDef ?? headFallbackPluginDef
@@ -511,24 +480,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
511
480
  if (routeDef.csrf) {
512
481
  const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
513
482
  if (!originCheck.ok)
514
- return refuseCrossSite(request, originCheck.reason, cookieStore)
483
+ return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
515
484
  }
516
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
485
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
517
486
  if (checked instanceof Response)
518
487
  return checked
519
488
  ctx.request = checked
520
489
  ctx.params = pluginMatch.params
521
490
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
522
491
  try {
523
- let res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => routeDef.handler(ctx)))
492
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
524
493
  if (headFallbackPluginDef !== undefined)
525
494
  res = stripHeadBody(res)
526
495
  else if (isEventStream(res))
527
496
  res = streams.track(res, disableTimeout)
528
- return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore)
497
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
529
498
  }
530
499
  catch (error) {
531
- notifyError(error, ctx.request, 'plugin')
500
+ notifyError(error, ctx.request, 'plugin', requestId)
532
501
  return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
533
502
  }
534
503
  }
@@ -537,7 +506,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
537
506
  if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
538
507
  const pub = publicMap.get(effectiveStaticPath)
539
508
  if (pub !== undefined)
540
- return serveFile(request, pub)
509
+ return withRequestId(await serveFile(request, pub), requestId)
541
510
  }
542
511
 
543
512
  const matched = router.match(effective)
@@ -547,28 +516,28 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
547
516
  const allow = allowedPluginMethodsHeader(pluginMatch.data)
548
517
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
549
518
  try {
550
- const res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => methodNotAllowed(allow)))
551
- return finish(res, request, cookieStore)
519
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
520
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
552
521
  }
553
522
  catch (error) {
554
- notifyError(error, request, 'plugin')
523
+ notifyError(error, request, 'plugin', requestId)
555
524
  return renderError(error, cookieStore, ctx.url, request, ctx)
556
525
  }
557
526
  }
558
- return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath)
527
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
559
528
  }
560
529
 
561
530
  ctx.params = matched.params
562
531
  const route = matched.data
563
532
 
564
533
  // CSRF verification & body limit for file-based API routes (opt out of CSRF via `export const csrf = false`)
565
- if (typeof route.mod[method] === 'function') {
534
+ if (routeMethodHandler(route.mod, method) !== undefined) {
566
535
  if (route.mod.csrf !== false) {
567
536
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
568
537
  if (!originCheck.ok)
569
- return refuseCrossSite(request, originCheck.reason, cookieStore)
538
+ return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
570
539
  }
571
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
540
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
572
541
  if (checked instanceof Response)
573
542
  return checked
574
543
  ctx.request = checked
@@ -579,30 +548,31 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
579
548
  : route.middlewares
580
549
 
581
550
  try {
582
- const rawRes = await actions.run(ctx, () => runChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, disableTimeout, staticPath)))
583
- const res = isEventStream(rawRes) ? streams.track(rawRes, disableTimeout) : rawRes
551
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, disableTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
552
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
553
+ const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
584
554
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
585
555
  const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
586
- return finish(finalRes, ctx.request, cookieStore)
556
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
587
557
  }
588
558
  catch (error) {
589
- notifyError(error, ctx.request, 'route')
590
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
559
+ notifyError(error, ctx.request, 'route', requestId)
560
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
591
561
  }
592
562
  }
593
563
  catch (error) {
594
- notifyError(error, request, 'route')
595
- return withHsts(isDev ? devErrorResponse(error, request) : serverError(), request)
564
+ notifyError(error, request, 'route', requestId)
565
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
596
566
  }
597
567
  }
598
568
 
599
- function handle(request: Request, remoteIp?: string): Promise<Response> {
600
- return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
569
+ function handle(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
570
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, disableTimeout))
601
571
  }
602
572
 
603
573
  const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
604
574
  const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
605
- const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, runRequest, runFast, notifyError, serverError, fileGone })
575
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
606
576
 
607
577
  function serve(port = 3000, hostname = '127.0.0.1') {
608
578
  const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })