prunelle 0.1.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) 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 +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  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 +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -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 +636 -0
  36. package/src/cli/check-imports.ts +31 -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 +101 -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 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. 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 { hasPublicFavicon, 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,77 +54,126 @@ 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
- export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
76
+ export type { InferInput, InferOutput, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
67
77
 
68
78
  // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
69
79
  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,74 @@ 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(
295
+ security: EmbeddedServerConfig['security'],
296
+ trustProxy: TrustProxy,
297
+ isDev: boolean,
298
+ site: string | undefined,
299
+ explicitNodeEnv: string | undefined,
300
+ ) {
301
+ const resolvedNodeEnv = explicitNodeEnv ?? nodeEnv()
302
+ // An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
303
+ const httpsSite = !isDev && resolvedNodeEnv !== 'development' && resolvedNodeEnv !== 'test' && site?.startsWith('https://') === true
304
+ const securityEntries = buildSecurityHeaderEntries(security)
305
+ const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
306
+ const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
307
+ const hstsValue = resolveHstsValue(security)
308
+ // Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
309
+ let proxyChecked = trustProxy !== false || isDev || resolvedNodeEnv !== 'production'
310
+ const withHsts = (res: Response, request: Request): Response => {
311
+ if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
312
+ proxyChecked = true
313
+ 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.')
314
+ }
315
+ return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
316
+ }
317
+ // The one way out of every response not built with the security headers already in place.
318
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
319
+ withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
320
+ return { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError: makeServerError(securityRecord), fileGone: makeFileGone(securityRecord) }
321
+ }
322
+
198
323
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
199
324
  const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
200
325
  const plugins = resolvePlugins(config.plugins)
@@ -206,7 +331,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
206
331
  const consent = normalizeConsentConfig(config.consent)
207
332
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
208
333
  const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
209
- const isDev = config.dev ?? (process.env.PRUNELLE_DEV === '1')
334
+ const isDev = config.dev ?? devFromEnv()
210
335
  const serverRoot = config.root ?? process.cwd()
211
336
  const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
212
337
  const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
@@ -217,21 +342,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
217
342
  const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
218
343
  const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
219
344
 
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)
345
+ const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site, config.nodeEnv ?? parentAppCtx?.nodeEnv)
346
+ const resolveRequestId = createRequestIdResolver(trustProxy)
229
347
  const navigation = createNavigation(config.navigation)
230
348
  const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
231
349
  const streams = createStreamTracker()
232
350
 
233
351
  const compressEnabled = config.compress ?? !isDev
234
352
  const compressCache = compressEnabled ? new CompressionCache() : undefined
353
+ const routeCache = createRouteCache(config.routeCache, isDev || config.prerender === true)
235
354
 
236
355
  const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, securityRecord, withHsts })
237
356
  const { assetMap, publicMap, serveFile } = files
@@ -261,226 +380,105 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
261
380
  assetPrefix,
262
381
  site,
263
382
  dev: isDev,
383
+ devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost),
264
384
  trustProxy,
265
385
  trustedOriginsList,
266
386
  trustedOrigins,
267
387
  })
268
388
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
389
+ const healthPath = `${assetPrefix}/health`
269
390
  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
391
  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)
392
+ effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
393
+
394
+ let healthHandler: ReturnType<typeof createHealthHandler>
395
+ let renderError: ReturnType<typeof createFallbackPages>['renderError']
396
+ let renderDenied: ReturnType<typeof createFallbackPages>['renderDenied']
397
+ let renderNotFound: ReturnType<typeof createNotFoundRenderer>
398
+ let refuseCrossSite: ReturnType<typeof createRequestGuards>['refuseCrossSite']
399
+ let checkBodyLimit: ReturnType<typeof createRequestGuards>['checkBodyLimit']
400
+ let router: ReturnType<typeof compileRouteTable>['router']
401
+ let fastStaticPages: ReturnType<typeof compileRouteTable>['fastStaticPages']
402
+ let fastPrerenderedMap: ReadonlyMap<string, ServedFile>
403
+ let renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
404
+ let dispatchAction: ReturnType<typeof createActionDispatcher>
405
+ try {
406
+ healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId, exposeErrors: isDev })
407
+ const routesPrefix = inferRoutesServerPrefix(manifest)
408
+ const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
409
+ const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
410
+ const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
411
+ registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
412
+ const hasFavicon = hasPublicFavicon(manifest, publicMap, serverPublicDir)
413
+ const fallbacks = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, dev: isDev, document, htmlHeaders, notifyError, finish })
414
+ ;({ renderError, renderDenied } = fallbacks)
415
+ renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
416
+ ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
417
+ ;({ router, fastStaticPages } = compileRouteTable({
418
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor,
419
+ pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
420
+ fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
421
+ }))
422
+ const collected = files.collectPrerendered(manifest.routes, {
423
+ prerendered, prerenderedFiles, prerenderedEtags,
424
+ // The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
425
+ // no-cache, not public: an app middleware may gate the page, and its ETag still spares a revisit the download.
426
+ htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
427
+ isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
428
+ })
429
+ fastPrerenderedMap = collected.fast
430
+ renderCompiledRoute = createCompiledRouteRenderer({
431
+ 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,
432
+ })
433
+ dispatchAction = createActionDispatcher({
434
+ actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
435
+ })
319
436
  }
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)
437
+ catch (error) {
438
+ await pluginHost.dispose()
439
+ throw error
433
440
  }
434
441
 
435
- const dispatchAction = createActionDispatcher({
436
- actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
437
- })
438
-
439
442
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
440
443
  async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
444
+ const requestId = resolveRequestId(request)
441
445
  try {
442
446
  const url = new URL(request.url)
443
447
  const rawPathname = url.pathname
444
448
  const requestPath = decodeRequestPath(rawPathname)
445
449
  if (requestPath === undefined)
446
- return finish(badRequest(), request)
450
+ return finish(badRequest(), request, undefined, requestId)
447
451
  const { staticPath, scopedPath } = requestPath
452
+ if (staticPath === healthPath)
453
+ return healthHandler(request, requestId)
448
454
  const read = isRead(request)
449
455
 
450
456
  // 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
- }
457
+ if (read) {
458
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
459
+ if (staticFile !== undefined)
460
+ return withRequestId(await serveFile(request, staticFile), requestId)
464
461
  }
465
462
 
466
463
  // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
467
464
  const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
468
465
  if (registeredAction !== undefined)
469
- return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited)
466
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
470
467
 
471
468
  // 3. Prerendered static HTML, then 4. the zero-overhead static route path
472
469
  const plainRead = isPlainRead(request)
473
470
  if (plainRead && staticPath !== undefined) {
474
471
  const pre = fastPrerenderedMap.get(staticPath)
475
472
  if (pre !== undefined)
476
- return serveFile(request, pre)
473
+ return withRequestId(await serveFile(request, pre), requestId)
477
474
  const fast = fastStaticPages.get(staticPath)
478
475
  if (fast !== undefined)
479
- return fast(request, remoteIp, url)
476
+ return fast(request, remoteIp, url, requestId)
480
477
  }
481
478
 
482
479
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
483
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
480
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
481
+ const timing = createTiming(isDev)
484
482
 
485
483
  // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
486
484
  let effectivePath = rawPathname
@@ -493,17 +491,17 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
493
491
  if (effectivePath !== rawPathname) {
494
492
  const rewritten = decodeRequestPath(effectivePath)
495
493
  if (rewritten === undefined)
496
- return finish(badRequest(), request, cookieStore)
494
+ return finish(badRequest(), request, cookieStore, requestId)
497
495
  effective = rewritten
498
496
  const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
499
497
  if (rewrittenAction !== undefined)
500
- return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, { ctx, cookieStore })
498
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
501
499
  }
502
500
  const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
503
501
 
504
502
  // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
505
503
  const method = request.method.toUpperCase()
506
- const pluginMatch = pluginRouter.match(effective)
504
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
507
505
  const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
508
506
  const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
509
507
  const routeDef = directPluginDef ?? headFallbackPluginDef
@@ -511,24 +509,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
511
509
  if (routeDef.csrf) {
512
510
  const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
513
511
  if (!originCheck.ok)
514
- return refuseCrossSite(request, originCheck.reason, cookieStore)
512
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
515
513
  }
516
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
514
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
517
515
  if (checked instanceof Response)
518
516
  return checked
519
517
  ctx.request = checked
520
518
  ctx.params = pluginMatch.params
521
519
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
522
520
  try {
523
- let res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => routeDef.handler(ctx)))
521
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
524
522
  if (headFallbackPluginDef !== undefined)
525
523
  res = stripHeadBody(res)
526
524
  else if (isEventStream(res))
527
525
  res = streams.track(res, disableTimeout)
528
- return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore)
526
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
529
527
  }
530
528
  catch (error) {
531
- notifyError(error, ctx.request, 'plugin')
529
+ notifyError(error, ctx.request, 'plugin', requestId)
532
530
  return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
533
531
  }
534
532
  }
@@ -537,7 +535,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
537
535
  if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
538
536
  const pub = publicMap.get(effectiveStaticPath)
539
537
  if (pub !== undefined)
540
- return serveFile(request, pub)
538
+ return withRequestId(await serveFile(request, pub), requestId)
541
539
  }
542
540
 
543
541
  const matched = router.match(effective)
@@ -547,28 +545,28 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
547
545
  const allow = allowedPluginMethodsHeader(pluginMatch.data)
548
546
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
549
547
  try {
550
- const res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => methodNotAllowed(allow)))
551
- return finish(res, request, cookieStore)
548
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
549
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
552
550
  }
553
551
  catch (error) {
554
- notifyError(error, request, 'plugin')
552
+ notifyError(error, request, 'plugin', requestId)
555
553
  return renderError(error, cookieStore, ctx.url, request, ctx)
556
554
  }
557
555
  }
558
- return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath)
556
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
559
557
  }
560
558
 
561
559
  ctx.params = matched.params
562
560
  const route = matched.data
563
561
 
564
562
  // 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') {
563
+ if (routeMethodHandler(route.mod, method) !== undefined) {
566
564
  if (route.mod.csrf !== false) {
567
565
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
568
566
  if (!originCheck.ok)
569
- return refuseCrossSite(request, originCheck.reason, cookieStore)
567
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
570
568
  }
571
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
569
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
572
570
  if (checked instanceof Response)
573
571
  return checked
574
572
  ctx.request = checked
@@ -579,30 +577,31 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
579
577
  : route.middlewares
580
578
 
581
579
  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
580
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, disableTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
581
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
582
+ const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
584
583
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
585
584
  const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
586
- return finish(finalRes, ctx.request, cookieStore)
585
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
587
586
  }
588
587
  catch (error) {
589
- notifyError(error, ctx.request, 'route')
590
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
588
+ notifyError(error, ctx.request, 'route', requestId)
589
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
591
590
  }
592
591
  }
593
592
  catch (error) {
594
- notifyError(error, request, 'route')
595
- return withHsts(isDev ? devErrorResponse(error, request) : serverError(), request)
593
+ notifyError(error, request, 'route', requestId)
594
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
596
595
  }
597
596
  }
598
597
 
599
- function handle(request: Request, remoteIp?: string): Promise<Response> {
600
- return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
598
+ function handle(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
599
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, disableTimeout))
601
600
  }
602
601
 
603
602
  const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
604
603
  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 })
604
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
606
605
 
607
606
  function serve(port = 3000, hostname = '127.0.0.1') {
608
607
  const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })
@@ -612,5 +611,5 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
612
611
  const reloadInto = (server: PrunelleServer): void => {
613
612
  server.reload(handlers(() => server))
614
613
  }
615
- return { handle, serve, reloadInto, closeStreams: streams.closeAll, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
614
+ return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, securityHeaders: securityRecord, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
616
615
  }