prunelle 0.1.1 → 0.7.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -5,42 +5,48 @@
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'
16
+ export { rateLimitKey } from './rate-limit'
17
+ export { sanitizeMarkdownHtml } from './sanitize-html'
15
18
  import type { LoadedMiddlewareModule } from './page'
19
+ import type { ServerPluginHost } from './plugin-host'
16
20
  import type { RequestPath } from './request-path'
17
21
  import type { CompiledRoute } from './route-table'
18
22
  import type { FastHandler } from './routing'
19
- import type { TrustProxy } from './security'
23
+ import type { OriginRefusal, TrustProxy } from './security'
20
24
  import { join } from 'node:path'
21
25
  import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
22
- import { createRenderContext, runWithRenderContext } from '../ssr/context'
23
26
  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'
27
+ import { executeAction, finishActionRedirect, isServerAction } from './action'
26
28
  import { createActionRegistry } from './action-registry'
27
29
  import { createAssets } from './assets'
28
- import { CompressionCache, compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, maybeCompressResponse } from './compress'
30
+ import { CompressionCache, maybeCompressResponse } from './compress'
29
31
  import { normalizeConsentConfig } from './consent'
30
- import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeStyleHashes, resolveRenderedIslands, revivePreload, withPluginHtmlCsp } from './document'
32
+ import { devFromEnv, nodeEnv } from './env'
33
+ import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './document'
31
34
  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'
35
+ import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
36
+ import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
37
+ import { stripHeadBody } from './page'
38
+ import { resolveParamMatchers } from './param-matchers'
39
+ import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
35
40
 
36
- import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
41
+ import { withRegionVary } from './region'
37
42
  import { decodeRequestPath, literalPath } from './request-path'
38
43
  import { nativePrerenderedCheck } from './prerendered'
39
- import { compileRouteTable } from './route-table'
44
+ import { createRouteCache } from './route-cache'
45
+ import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
40
46
  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'
47
+ import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
48
+ import { buildSecurityHeaderEntries, isLoopbackHost, logOriginHint, resolveHstsValue, verifyOrigin } from './security'
49
+ import { createStreamTracker } from './stream'
44
50
 
45
51
  /**
46
52
  * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
@@ -48,19 +54,23 @@ import { createStreamTracker, STREAM_TAIL_MARK, streamDocument } from './stream'
48
54
  */
49
55
  export interface PrunelleLocals {}
50
56
 
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'
57
+ 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'
58
+ 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'
59
+ export { currentRequest } from './request-scope'
53
60
  export { action, getActionError } from './action'
54
61
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
55
62
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
56
63
  export type { CompressionEncoding, PrecompressedEncoding } from './compress'
57
64
  export type { RequestConsent } from './consent'
58
65
  export type { CookieOptions, Cookies } from './cookies'
59
- export { defineEnv, nodeEnv } from './env'
66
+ export { defineEnv, devFromEnv, nodeEnv } from './env'
67
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
60
68
  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'
69
+ export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
62
70
  export { createServer } from './loader'
63
- 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'
71
+ export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
72
+ export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
73
+ export { DEFAULT_COOP, DEFAULT_CORP, DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isLoopbackHost, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
64
74
  export type { SecurityHeadersOptions, TrustProxy } from './security'
65
75
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
66
76
  export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
@@ -70,55 +80,100 @@ const DEFAULT_STREAM_TIMEOUT = 30_000
70
80
 
71
81
 
72
82
  const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
83
+ const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
84
+
85
+ function maybeRenderDenied(
86
+ res: Response,
87
+ request: Request,
88
+ url: URL,
89
+ ctx: RequestContext,
90
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
91
+ routeFile?: string,
92
+ isApi = false,
93
+ ): Response | Promise<Response> {
94
+ if (isApi)
95
+ return res
96
+ const denied = getDeniedInfo(res)
97
+ if (denied === undefined || !acceptsHtml(request))
98
+ return res
99
+ return renderDenied(denied, url, request, ctx, routeFile)
100
+ }
101
+
73
102
  const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
74
103
  // A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
75
104
  const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
76
105
  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
106
 
78
- function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string | undefined): T | undefined {
107
+ function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
108
+ const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
109
+ return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
110
+ }
111
+
112
+ function matchStaticOrPublic(
113
+ request: Request,
114
+ requestPath: RequestPath,
115
+ assetMap: ReadonlyMap<string, ServedFile>,
116
+ publicMap: ReadonlyMap<string, ServedFile>,
117
+ pluginRouter: ServerPluginHost['router'],
118
+ ): ServedFile | undefined {
119
+ const { staticPath } = requestPath
79
120
  if (staticPath === undefined)
80
121
  return undefined
81
- const normPath = staticPath.length > 1 && staticPath.endsWith('/') ? staticPath.slice(0, -1) : staticPath
82
- return map.get(staticPath) ?? map.get(normPath)
122
+ const asset = assetMap.get(staticPath)
123
+ if (asset !== undefined)
124
+ return asset
125
+ const pub = publicMap.get(staticPath)
126
+ if (pub === undefined)
127
+ return undefined
128
+ const matchedPlugin = pluginRouter.match(requestPath)
129
+ const reqMethod = request.method.toUpperCase()
130
+ const shadowedByPlugin = matchedPlugin !== undefined
131
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
132
+ return shadowedByPlugin ? undefined : pub
83
133
  }
84
134
 
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
- )
135
+ function createRequestGuards(
136
+ maxRequestBodySize: number,
137
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
138
+ ) {
139
+ const refuseCrossSite = (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string): Response => {
140
+ logOriginHint(check.hint)
141
+ return finish(Response.json({ ok: false, status: 403, error: check.reason }, { status: 403 }), request, cookieStore, requestId)
96
142
  }
97
- else {
98
- inner = ssrChild(await mod.default!(pageProps) as Html)
143
+
144
+ const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
145
+ if (bodyLimited)
146
+ return request
147
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
148
+ if (bounded.ok)
149
+ return bounded.request
150
+ const status = bounded.aborted ? 400 : 413
151
+ const message = bounded.aborted ? 'Bad Request' : 'Payload Too Large'
152
+ return finish(wantsJson(request)
153
+ ? Response.json({ ok: false, status, error: message }, { status })
154
+ : new Response(message, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
99
155
  }
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
156
+ return { refuseCrossSite, checkBodyLimit }
103
157
  }
104
158
 
105
-
106
159
  interface ActionDispatcherDeps {
107
160
  actions: ActionRegistry
108
161
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
109
162
  trustedOrigins: Set<string> | undefined
110
163
  trustProxy: TrustProxy
164
+ httpsSite: boolean
111
165
  consent: NormalizedConsentConfig | undefined
112
166
  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
167
+ isDev: boolean
168
+ refuseCrossSite: (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string) => Response
169
+ checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
170
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
116
171
  notifyError: NotifyError
117
172
  renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
118
173
  }
119
174
 
120
175
  function createActionDispatcher(deps: ActionDispatcherDeps) {
121
- const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
176
+ const { actions, rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
122
177
  const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
123
178
  const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
124
179
  if (act.rateLimit === undefined)
@@ -137,6 +192,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
137
192
  rawPathname: string,
138
193
  remoteIp: string | undefined,
139
194
  bodyLimited: boolean,
195
+ requestId: string,
140
196
  existing?: { ctx: RequestContext, cookieStore: CookieStore },
141
197
  ): Promise<Response> => {
142
198
  const actionHandler = request.method === 'POST' ? registeredAction : undefined
@@ -144,29 +200,30 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
144
200
  if (actionHandler !== undefined) {
145
201
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
146
202
  if (!originCheck.ok)
147
- return refuseCrossSite(request, originCheck.reason, existing?.cookieStore)
148
- const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore)
203
+ return refuseCrossSite(request, originCheck, existing?.cookieStore, requestId)
204
+ const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
149
205
  if (checked instanceof Response)
150
206
  return checked
151
207
  req = checked
152
208
  }
153
209
  const { act, middlewares } = registeredAction
154
- const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent })
210
+ const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
155
211
  ctx.request = req
156
212
  if (existing === undefined && rewrites.length > 0) {
157
213
  for (const rewrite of rewrites)
158
214
  rewrite(rawPathname, ctx)
159
215
  }
216
+ const timing = createTiming(isDev)
160
217
  try {
161
- const res = await actions.run(ctx, () => runChain(ctx, middlewares, () =>
218
+ const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
162
219
  actionHandler !== undefined
163
220
  ? executeAction(act, req, ctx, trustedOrigins, trustProxy, limiterFor(act))
164
221
  : methodNotAllowed('POST'),
165
- ))
166
- return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore)
222
+ timing, runChain))
223
+ return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore, ctx.requestId, formatServerTiming(timing))
167
224
  }
168
225
  catch (error) {
169
- notifyError(error, req, 'action')
226
+ notifyError(error, req, 'action', ctx.requestId)
170
227
  return renderError(error, cookieStore, ctx.url, req, ctx)
171
228
  }
172
229
  }
@@ -195,6 +252,67 @@ function registerManifestActions({ manifest, modules, actions, routesPrefix, rou
195
252
  }
196
253
  }
197
254
 
255
+ interface NotFoundRendererDeps {
256
+ actions: ActionRegistry
257
+ pluginMiddlewaresFor: (effectiveScopedPath: string, rawScopedPath: string) => readonly Middleware[]
258
+ ancestorMiddlewaresFor: ReturnType<typeof createAncestorMiddlewareLookup>
259
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
260
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
261
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
262
+ notifyError: NotifyError
263
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
264
+ }
265
+
266
+ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
267
+ const { actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse, renderDenied, renderError, notifyError, finish } = deps
268
+ return async (
269
+ cookieStore: CookieStore,
270
+ url: URL,
271
+ request: Request,
272
+ ctx: RequestContext,
273
+ effective: RequestPath,
274
+ rawScopedPath: string,
275
+ timing?: DevTiming,
276
+ ): Promise<Response> => {
277
+ const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
278
+ const ancestor = ancestorMiddlewaresFor(effective)
279
+ if (ancestor !== undefined)
280
+ ctx.params = ancestor.params
281
+ const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
282
+ try {
283
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx), timing, runChain))
284
+ return finish(await maybeRenderDenied(rawRes, request, url, ctx, renderDenied), request, cookieStore, ctx.requestId, formatServerTiming(timing))
285
+ }
286
+ catch (error) {
287
+ notifyError(error, request, 'route', ctx.requestId)
288
+ return renderError(error, cookieStore, url, request, ctx)
289
+ }
290
+ }
291
+ }
292
+
293
+ /** The security headers every response carries, and the helpers that put them on a response built without them. */
294
+ function createSecurityResponders(security: EmbeddedServerConfig['security'], trustProxy: TrustProxy, isDev: boolean, site: string | undefined) {
295
+ // An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
296
+ const httpsSite = site?.startsWith('https://') === true
297
+ const securityEntries = buildSecurityHeaderEntries(security)
298
+ const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
299
+ const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
300
+ const hstsValue = resolveHstsValue(security)
301
+ // Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
302
+ let proxyChecked = trustProxy !== false || isDev || nodeEnv() !== 'production'
303
+ const withHsts = (res: Response, request: Request): Response => {
304
+ if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
305
+ proxyChecked = true
306
+ console.warn('prunelle: a request came through a proxy (it carries x-forwarded-proto) but trustProxy is off, so ctx.ip and rate limits see the proxy\'s address and https is known from site alone: set trustProxy in prunelle.config.ts to the proxy the server runs behind.')
307
+ }
308
+ return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, undefined, httpsSite)
309
+ }
310
+ // The one way out of every response not built with the security headers already in place.
311
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
312
+ withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
313
+ return { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError: makeServerError(securityRecord), fileGone: makeFileGone(securityRecord) }
314
+ }
315
+
198
316
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
199
317
  const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
200
318
  const plugins = resolvePlugins(config.plugins)
@@ -206,7 +324,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
206
324
  const consent = normalizeConsentConfig(config.consent)
207
325
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
208
326
  const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
209
- const isDev = config.dev ?? (process.env.PRUNELLE_DEV === '1')
327
+ const isDev = config.dev ?? devFromEnv()
210
328
  const serverRoot = config.root ?? process.cwd()
211
329
  const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
212
330
  const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
@@ -217,21 +335,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
217
335
  const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
218
336
  const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
219
337
 
220
- const securityEntries = buildSecurityHeaderEntries(security)
221
- const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
222
- const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
223
- const hstsValue = resolveHstsValue(security)
224
- const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
225
- // 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)
227
- const serverError = makeServerError(securityRecord)
228
- const fileGone = makeFileGone(securityRecord)
338
+ const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site)
339
+ const resolveRequestId = createRequestIdResolver(trustProxy)
229
340
  const navigation = createNavigation(config.navigation)
230
341
  const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
231
342
  const streams = createStreamTracker()
232
343
 
233
344
  const compressEnabled = config.compress ?? !isDev
234
345
  const compressCache = compressEnabled ? new CompressionCache() : undefined
346
+ const routeCache = createRouteCache(config.routeCache, isDev || config.prerender === true)
235
347
 
236
348
  const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, securityRecord, withHsts })
237
349
  const { assetMap, publicMap, serveFile } = files
@@ -261,226 +373,105 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
261
373
  assetPrefix,
262
374
  site,
263
375
  dev: isDev,
376
+ devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost),
264
377
  trustProxy,
265
378
  trustedOriginsList,
266
379
  trustedOrigins,
267
380
  })
268
381
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
382
+ const healthPath = `${assetPrefix}/health`
269
383
  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
384
  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
- }
304
- }
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)
308
- }
309
-
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)
385
+ effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
386
+
387
+ let healthHandler: ReturnType<typeof createHealthHandler>
388
+ let renderError: ReturnType<typeof createFallbackPages>['renderError']
389
+ let renderDenied: ReturnType<typeof createFallbackPages>['renderDenied']
390
+ let renderNotFound: ReturnType<typeof createNotFoundRenderer>
391
+ let refuseCrossSite: ReturnType<typeof createRequestGuards>['refuseCrossSite']
392
+ let checkBodyLimit: ReturnType<typeof createRequestGuards>['checkBodyLimit']
393
+ let router: ReturnType<typeof compileRouteTable>['router']
394
+ let fastStaticPages: ReturnType<typeof compileRouteTable>['fastStaticPages']
395
+ let fastPrerenderedMap: ReadonlyMap<string, ServedFile>
396
+ let renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
397
+ let dispatchAction: ReturnType<typeof createActionDispatcher>
398
+ try {
399
+ healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId, exposeErrors: isDev })
400
+ const routesPrefix = inferRoutesServerPrefix(manifest)
401
+ const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
402
+ const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
403
+ const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
404
+ registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
405
+ const fallbacks = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
406
+ renderError = fallbacks.renderError
407
+ renderDenied = fallbacks.renderDenied
408
+ renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
409
+ ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
410
+ ;({ router, fastStaticPages } = compileRouteTable({
411
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
412
+ pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
413
+ fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
414
+ }))
415
+ const collected = files.collectPrerendered(manifest.routes, {
416
+ prerendered, prerenderedFiles, prerenderedEtags,
417
+ // The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
418
+ // no-cache, not public: an app middleware may gate the page, and its ETag still spares a revisit the download.
419
+ htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
420
+ isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
421
+ })
422
+ fastPrerenderedMap = collected.fast
423
+ renderCompiledRoute = createCompiledRouteRenderer({
424
+ manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, streams, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
425
+ })
426
+ dispatchAction = createActionDispatcher({
427
+ actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
428
+ })
319
429
  }
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)
430
+ catch (error) {
431
+ await pluginHost.dispose()
432
+ throw error
433
433
  }
434
434
 
435
- const dispatchAction = createActionDispatcher({
436
- actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
437
- })
438
-
439
435
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
440
436
  async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
437
+ const requestId = resolveRequestId(request)
441
438
  try {
442
439
  const url = new URL(request.url)
443
440
  const rawPathname = url.pathname
444
441
  const requestPath = decodeRequestPath(rawPathname)
445
442
  if (requestPath === undefined)
446
- return finish(badRequest(), request)
443
+ return finish(badRequest(), request, undefined, requestId)
447
444
  const { staticPath, scopedPath } = requestPath
445
+ if (staticPath === healthPath)
446
+ return healthHandler(request, requestId)
448
447
  const read = isRead(request)
449
448
 
450
449
  // 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
- }
450
+ if (read) {
451
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
452
+ if (staticFile !== undefined)
453
+ return withRequestId(await serveFile(request, staticFile), requestId)
464
454
  }
465
455
 
466
456
  // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
467
457
  const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
468
458
  if (registeredAction !== undefined)
469
- return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited)
459
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
470
460
 
471
461
  // 3. Prerendered static HTML, then 4. the zero-overhead static route path
472
462
  const plainRead = isPlainRead(request)
473
463
  if (plainRead && staticPath !== undefined) {
474
464
  const pre = fastPrerenderedMap.get(staticPath)
475
465
  if (pre !== undefined)
476
- return serveFile(request, pre)
466
+ return withRequestId(await serveFile(request, pre), requestId)
477
467
  const fast = fastStaticPages.get(staticPath)
478
468
  if (fast !== undefined)
479
- return fast(request, remoteIp, url)
469
+ return fast(request, remoteIp, url, requestId)
480
470
  }
481
471
 
482
472
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
483
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
473
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
474
+ const timing = createTiming(isDev)
484
475
 
485
476
  // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
486
477
  let effectivePath = rawPathname
@@ -493,17 +484,17 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
493
484
  if (effectivePath !== rawPathname) {
494
485
  const rewritten = decodeRequestPath(effectivePath)
495
486
  if (rewritten === undefined)
496
- return finish(badRequest(), request, cookieStore)
487
+ return finish(badRequest(), request, cookieStore, requestId)
497
488
  effective = rewritten
498
489
  const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
499
490
  if (rewrittenAction !== undefined)
500
- return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, { ctx, cookieStore })
491
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
501
492
  }
502
493
  const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
503
494
 
504
495
  // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
505
496
  const method = request.method.toUpperCase()
506
- const pluginMatch = pluginRouter.match(effective)
497
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
507
498
  const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
508
499
  const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
509
500
  const routeDef = directPluginDef ?? headFallbackPluginDef
@@ -511,24 +502,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
511
502
  if (routeDef.csrf) {
512
503
  const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
513
504
  if (!originCheck.ok)
514
- return refuseCrossSite(request, originCheck.reason, cookieStore)
505
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
515
506
  }
516
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
507
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
517
508
  if (checked instanceof Response)
518
509
  return checked
519
510
  ctx.request = checked
520
511
  ctx.params = pluginMatch.params
521
512
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
522
513
  try {
523
- let res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => routeDef.handler(ctx)))
514
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
524
515
  if (headFallbackPluginDef !== undefined)
525
516
  res = stripHeadBody(res)
526
517
  else if (isEventStream(res))
527
518
  res = streams.track(res, disableTimeout)
528
- return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore)
519
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
529
520
  }
530
521
  catch (error) {
531
- notifyError(error, ctx.request, 'plugin')
522
+ notifyError(error, ctx.request, 'plugin', requestId)
532
523
  return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
533
524
  }
534
525
  }
@@ -537,7 +528,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
537
528
  if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
538
529
  const pub = publicMap.get(effectiveStaticPath)
539
530
  if (pub !== undefined)
540
- return serveFile(request, pub)
531
+ return withRequestId(await serveFile(request, pub), requestId)
541
532
  }
542
533
 
543
534
  const matched = router.match(effective)
@@ -547,28 +538,28 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
547
538
  const allow = allowedPluginMethodsHeader(pluginMatch.data)
548
539
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
549
540
  try {
550
- const res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => methodNotAllowed(allow)))
551
- return finish(res, request, cookieStore)
541
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
542
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
552
543
  }
553
544
  catch (error) {
554
- notifyError(error, request, 'plugin')
545
+ notifyError(error, request, 'plugin', requestId)
555
546
  return renderError(error, cookieStore, ctx.url, request, ctx)
556
547
  }
557
548
  }
558
- return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath)
549
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
559
550
  }
560
551
 
561
552
  ctx.params = matched.params
562
553
  const route = matched.data
563
554
 
564
555
  // 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') {
556
+ if (routeMethodHandler(route.mod, method) !== undefined) {
566
557
  if (route.mod.csrf !== false) {
567
558
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
568
559
  if (!originCheck.ok)
569
- return refuseCrossSite(request, originCheck.reason, cookieStore)
560
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
570
561
  }
571
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
562
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
572
563
  if (checked instanceof Response)
573
564
  return checked
574
565
  ctx.request = checked
@@ -579,30 +570,31 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
579
570
  : route.middlewares
580
571
 
581
572
  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
573
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, disableTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
574
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
575
+ const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
584
576
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
585
577
  const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
586
- return finish(finalRes, ctx.request, cookieStore)
578
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
587
579
  }
588
580
  catch (error) {
589
- notifyError(error, ctx.request, 'route')
590
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
581
+ notifyError(error, ctx.request, 'route', requestId)
582
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
591
583
  }
592
584
  }
593
585
  catch (error) {
594
- notifyError(error, request, 'route')
595
- return withHsts(isDev ? devErrorResponse(error, request) : serverError(), request)
586
+ notifyError(error, request, 'route', requestId)
587
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
596
588
  }
597
589
  }
598
590
 
599
- function handle(request: Request, remoteIp?: string): Promise<Response> {
600
- return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
591
+ function handle(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
592
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, disableTimeout))
601
593
  }
602
594
 
603
595
  const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
604
596
  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 })
597
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
606
598
 
607
599
  function serve(port = 3000, hostname = '127.0.0.1') {
608
600
  const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })
@@ -612,5 +604,5 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
612
604
  const reloadInto = (server: PrunelleServer): void => {
613
605
  server.reload(handlers(() => server))
614
606
  }
615
- return { handle, serve, reloadInto, closeStreams: streams.closeAll, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
607
+ return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, securityHeaders: securityRecord, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
616
608
  }