prunelle 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -10,52 +10,58 @@ 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 { DevTiming } from './health'
14
- import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
13
+ import type { PhaseTiming } from './health'
14
+
15
+ import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext, ServeOptions } from './http'
15
16
  import type { RateLimiter, RateLimitStore } from './rate-limit'
17
+ import { memoryLimiters } from './rate-limit'
16
18
  export { rateLimitKey } from './rate-limit'
17
19
  export { sanitizeMarkdownHtml } from './sanitize-html'
18
20
  import type { LoadedMiddlewareModule } from './page'
19
21
  import type { ServerPluginHost } from './plugin-host'
22
+ import type { RouteCache } from './route-cache'
20
23
  import type { RequestPath } from './request-path'
21
- import type { CompiledRoute } from './route-table'
22
24
  import type { FastHandler } from './routing'
23
25
  import type { OriginRefusal, TrustProxy } from './security'
26
+ import type { PerProcessInput } from './workers'
24
27
  import { join } from 'node:path'
25
- import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
28
+ import { getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
26
29
  import { createNavigation } from '../ssr/navigation'
27
30
  import { executeAction, finishActionRedirect, isServerAction } from './action'
28
31
  import { createActionRegistry } from './action-registry'
29
32
  import { createAssets } from './assets'
30
- import { CompressionCache, maybeCompressResponse } from './compress'
33
+ import { CompressionCache } from './compress'
31
34
  import { normalizeConsentConfig } from './consent'
35
+ import { createCors } from './cors'
36
+ import { createServerAppContext } from './cookie-inventory'
32
37
  import { devFromEnv, nodeEnv } from './env'
33
- import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './document'
34
- import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
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 { createDocumentHooks, createHtmlHeaders } from './document'
39
+ import { createErrorNotifier, createFallbackPages } from './errors'
40
+ import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain } from './health'
41
+ import { createRequestObserver } from './request-log'
42
+ import { createRequestGuards, createRequestHandler, maybeRenderDenied } from './request-handler'
43
+ import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, finalizeResponse, makeRequestContext, runChain } from './http'
44
+ import { hasPublicFavicon } from './page'
38
45
  import { resolveParamMatchers } from './param-matchers'
39
- import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
46
+ import { createServerPluginHost } from './plugin-host'
40
47
 
41
48
  import { withRegionVary } from './region'
42
- import { decodeRequestPath, literalPath } from './request-path'
49
+ import { literalPath } from './request-path'
43
50
  import { nativePrerenderedCheck } from './prerendered'
51
+ import { receiveCacheInvalidation, serveCacheInvalidation } from './cache-invalidation'
44
52
  import { createRouteCache } from './route-cache'
45
- import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
53
+ import { SHARED_STORE } from './shared-store'
54
+ import { perProcessState } from './workers'
55
+ import { compileRouteTable, createCompiledRouteRenderer } from './route-table'
46
56
  import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
47
- import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
48
- import { buildSecurityHeaderEntries, isLoopbackHost, logOriginHint, resolveHstsValue, resolveTrustProxy, verifyOrigin } from './security'
57
+ import { serveHandlers } from './serve-handlers'
58
+ import { buildSecurityHeaderEntries, isLoopbackHost, resolveHstsValue, resolveTrustProxy, verifyOrigin } from './security'
49
59
  import { createStreamTracker } from './stream'
50
60
 
51
- /**
52
- * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
53
- * Augment via `declare module 'prunelle/server' { interface PrunelleLocals { ... } }`.
54
- */
55
- export interface PrunelleLocals {}
61
+ export type { PrunelleLocals } from './public'
56
62
 
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'
63
+ export { CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, JOBS_SERVICE, loadConfig, registerUserDataService, USER_DATA_SERVICE, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
64
+ 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, LogConfig, RequestPhase, RequestRecord, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig, UserDataService } from '../plugins/index'
59
65
  export { currentRequest } from './request-scope'
60
66
  export { action, getActionError } from './action'
61
67
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
@@ -66,7 +72,7 @@ export type { CookieOptions, Cookies } from './cookies'
66
72
  export { defineEnv, devFromEnv, nodeEnv } from './env'
67
73
  export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
68
74
  export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
69
- export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
75
+ export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, RoutePattern, ServerOptions, StatusPageProps } from './http'
70
76
  export { createServer } from './loader'
71
77
  export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
72
78
  export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
@@ -79,83 +85,10 @@ export type { InferInput, InferOutput, StandardJSONSchemaConverter, StandardJSON
79
85
  const DEFAULT_STREAM_TIMEOUT = 30_000
80
86
 
81
87
 
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
-
102
88
  const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
103
89
  // A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
104
- const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
105
90
  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 } })
106
91
 
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
120
- if (staticPath === undefined)
121
- return undefined
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
133
- }
134
-
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)
142
- }
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)
155
- }
156
- return { refuseCrossSite, checkBodyLimit }
157
- }
158
-
159
92
  interface ActionDispatcherDeps {
160
93
  actions: ActionRegistry
161
94
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
@@ -180,7 +113,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
180
113
  return undefined
181
114
  let limiter = limiters.get(act)
182
115
  if (limiter === undefined) {
183
- limiter = rateLimits.limiter(act.rateLimit)
116
+ limiter = rateLimits.limiter(act.rateLimit, `action:${act.url}`)
184
117
  limiters.set(act, limiter)
185
118
  }
186
119
  return limiter
@@ -214,7 +147,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
214
147
  for (const rewrite of rewrites)
215
148
  rewrite(rawPathname, ctx)
216
149
  }
217
- const timing = createTiming(isDev)
150
+ const timing = createTiming(isDev, request)
218
151
  try {
219
152
  const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
220
153
  actionHandler !== undefined
@@ -273,7 +206,7 @@ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
273
206
  ctx: RequestContext,
274
207
  effective: RequestPath,
275
208
  rawScopedPath: string,
276
- timing?: DevTiming,
209
+ timing?: PhaseTiming,
277
210
  ): Promise<Response> => {
278
211
  const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
279
212
  const ancestor = ancestorMiddlewaresFor(effective)
@@ -302,34 +235,50 @@ function createSecurityResponders(
302
235
  const resolvedNodeEnv = explicitNodeEnv ?? nodeEnv()
303
236
  // An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
304
237
  const httpsSite = !isDev && resolvedNodeEnv !== 'development' && resolvedNodeEnv !== 'test' && site?.startsWith('https://') === true
305
- const securityEntries = buildSecurityHeaderEntries(security)
238
+ const securityEntries = buildSecurityHeaderEntries(security, httpsSite)
306
239
  const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
307
240
  const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
308
241
  const hstsValue = resolveHstsValue(security)
309
242
  // Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
310
243
  let proxyChecked = trustProxy !== false || isDev || resolvedNodeEnv !== 'production'
311
- const withHsts = (res: Response, request: Request): Response => {
312
- if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
313
- proxyChecked = true
314
- 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.')
315
- }
316
- return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
317
- }
244
+ const hstsAlwaysOff = hstsValue === undefined || isDev
245
+ const noProxyHsts = !httpsSite && trustProxy === false
246
+ const withHsts = proxyChecked && hstsAlwaysOff
247
+ ? (res: Response): Response => res
248
+ : (res: Response, request: Request): Response => {
249
+ if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
250
+ proxyChecked = true
251
+ 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.')
252
+ }
253
+ if (hstsAlwaysOff || (noProxyHsts && !request.url.startsWith('https:')))
254
+ return res
255
+ return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
256
+ }
318
257
  // The one way out of every response not built with the security headers already in place.
319
258
  const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
320
259
  withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
321
260
  return { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError: makeServerError(securityRecord), fileGone: makeFileGone(securityRecord) }
322
261
  }
323
262
 
263
+ // `invalidateCache()` works from the plugins' own server hooks on, and hears the other processes once a plugin host opened the shared store.
264
+ async function startPlugins(options: Parameters<typeof createServerPluginHost>[0], routeCache: RouteCache | undefined): Promise<ServerPluginHost> {
265
+ serveCacheInvalidation(options.appCtx, routeCache)
266
+ const host = await createServerPluginHost(options)
267
+ receiveCacheInvalidation(options.appCtx.inject(SHARED_STORE), routeCache)
268
+ return host
269
+ }
270
+
324
271
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
325
272
  const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
326
273
  const plugins = resolvePlugins(config.plugins)
327
274
  const assetPrefix = (config.assetPrefix ?? '/_pru').replace(/\/$/, '')
328
275
  const site = config.site?.replace(/\/$/, '') || undefined
329
276
  const trustedOriginsList = config.trustedOrigins ?? []
330
- const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
277
+ const cors = createCors(config.cors)
278
+ const csrfOrigins = [...trustedOriginsList, ...cors?.trusted ?? []]
279
+ const trustedOrigins = csrfOrigins.length > 0 ? new Set(csrfOrigins) : undefined
331
280
  const trustProxy = resolveTrustProxy(config.trustProxy ?? false, site, trustedOriginsList)
332
- const consent = normalizeConsentConfig(config.consent)
281
+ const consent = normalizeConsentConfig(config.consent, lang)
333
282
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
334
283
  const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
335
284
  const isDev = config.dev ?? devFromEnv()
@@ -339,14 +288,14 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
339
288
  const parentAppCtx = getAppContext()
340
289
 
341
290
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
342
- const notifyError = createErrorNotifier(config.onError, plugins, { dev: isDev, sink: config.errorSink })
291
+ const notifyError = createErrorNotifier(config.onError, plugins, { dev: isDev, sink: config.errorSink, format: config.log?.format })
343
292
  const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
344
293
  const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
345
294
 
346
295
  const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site, config.nodeEnv ?? parentAppCtx?.nodeEnv)
347
296
  const resolveRequestId = createRequestIdResolver(trustProxy)
348
- const navigation = createNavigation(config.navigation)
349
- const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
297
+ const navigation = createNavigation(config.navigation, assetPrefix)
298
+ const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins, httpsSite)
350
299
  const streams = createStreamTracker()
351
300
 
352
301
  const compressEnabled = config.compress ?? !isDev
@@ -357,35 +306,16 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
357
306
  const { assetMap, publicMap, serveFile } = files
358
307
  files.registerPublicFiles(publicAssets, publicEtags)
359
308
 
360
- const serverAppCtx = createAppContext({
361
- root: serverRoot,
362
- outDir: serverOutDir,
363
- publicDir: serverPublicDir,
364
- assetPrefix,
365
- site,
366
- dev: isDev, nodeEnv: config.nodeEnv ?? parentAppCtx?.nodeEnv,
367
- onRegisterPublicFile: (rel) => {
368
- parentAppCtx?.registerPublicFile(rel)
369
- files.registerPublicFromDisk(serverPublicDir, rel)
370
- },
309
+ const serverAppCtx = createServerAppContext({
310
+ root: serverRoot, outDir: serverOutDir, publicDir: serverPublicDir, assetPrefix, site, dev: isDev, nodeEnv: config.nodeEnv ?? parentAppCtx?.nodeEnv,
311
+ parent: parentAppCtx, registerPublicFromDisk: files.registerPublicFromDisk, consent, manifest, plugins, lang,
371
312
  })
372
313
 
373
314
  const actions = createActionRegistry()
374
- const pluginHost = await createServerPluginHost({
375
- plugins,
376
- config,
377
- manifest,
378
- appCtx: serverAppCtx,
379
- root: serverRoot,
380
- outDir: serverOutDir,
381
- assetPrefix,
382
- site,
383
- dev: isDev,
384
- devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost),
385
- trustProxy,
386
- trustedOriginsList,
387
- trustedOrigins,
388
- })
315
+ const pluginHost = await startPlugins({
316
+ plugins, config, manifest, appCtx: serverAppCtx, root: serverRoot, outDir: serverOutDir, assetPrefix, site, dev: isDev,
317
+ devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost), trustProxy, trustedOriginsList: csrfOrigins, trustedOrigins, notifyError,
318
+ }, routeCache)
389
319
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
390
320
  const healthPath = `${assetPrefix}/health`
391
321
  const hasPluginRewrites = pluginHost.rewrites.length > 0
@@ -416,7 +346,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
416
346
  renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
417
347
  ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
418
348
  ;({ router, fastStaticPages } = compileRouteTable({
419
- manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor,
349
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor, isGatedByPlugin: pluginHost.isGatedByPlugin,
420
350
  pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
421
351
  fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
422
352
  }))
@@ -424,12 +354,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
424
354
  prerendered, prerenderedFiles, prerenderedEtags,
425
355
  // The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
426
356
  // no-cache, not public: an app middleware may gate the page, and its ETag still spares a revisit the download.
427
- htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
357
+ htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0 || (route.usesRegion === true && manifest.runtimeScript !== undefined), false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
428
358
  isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
429
359
  })
430
360
  fastPrerenderedMap = collected.fast
431
361
  renderCompiledRoute = createCompiledRouteRenderer({
432
- 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,
362
+ manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, streams, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, httpsSite, consent, resolveRequestId, serverAppCtx,
433
363
  })
434
364
  dispatchAction = createActionDispatcher({
435
365
  actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
@@ -440,178 +370,63 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
440
370
  throw error
441
371
  }
442
372
 
443
- // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
444
- async function handleInternal(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void, bodyLimited = false): Promise<Response> {
445
- const requestId = resolveRequestId(request)
446
- try {
447
- const url = new URL(request.url)
448
- const rawPathname = url.pathname
449
- const requestPath = decodeRequestPath(rawPathname)
450
- if (requestPath === undefined)
451
- return finish(badRequest(), request, undefined, requestId)
452
- const { staticPath, scopedPath } = requestPath
453
- if (staticPath === healthPath)
454
- return healthHandler(request, requestId)
455
- const read = isRead(request)
456
-
457
- // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
458
- if (read) {
459
- const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
460
- if (staticFile !== undefined)
461
- return withRequestId(await serveFile(request, staticFile), requestId)
462
- }
463
-
464
- // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
465
- const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
466
- if (registeredAction !== undefined)
467
- return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
468
-
469
- // 3. Prerendered static HTML, then 4. the zero-overhead static route path
470
- const plainRead = isPlainRead(request)
471
- if (plainRead && staticPath !== undefined) {
472
- const pre = fastPrerenderedMap.get(staticPath)
473
- if (pre !== undefined)
474
- return withRequestId(await serveFile(request, pre), requestId)
475
- const fast = fastStaticPages.get(staticPath)
476
- if (fast !== undefined)
477
- return fast(request, remoteIp, url, requestId)
478
- }
479
-
480
- // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
481
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
482
- const timing = createTiming(isDev)
483
-
484
- // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
485
- let effectivePath = rawPathname
486
- for (const rewrite of pluginHost.rewrites) {
487
- const nextPath = rewrite(effectivePath, ctx)
488
- if (nextPath !== undefined)
489
- effectivePath = nextPath
490
- }
491
- let effective = requestPath
492
- if (effectivePath !== rawPathname) {
493
- const rewritten = decodeRequestPath(effectivePath)
494
- if (rewritten === undefined)
495
- return finish(badRequest(), request, cookieStore, requestId)
496
- effective = rewritten
497
- const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
498
- if (rewrittenAction !== undefined)
499
- return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
500
- }
501
- const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
502
-
503
- // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
504
- const method = request.method.toUpperCase()
505
- const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
506
- const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
507
- const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
508
- const routeDef = directPluginDef ?? headFallbackPluginDef
509
- if (pluginMatch !== undefined && routeDef !== undefined) {
510
- if (routeDef.csrf) {
511
- const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
512
- if (!originCheck.ok)
513
- return refuseCrossSite(request, originCheck, cookieStore, requestId)
514
- }
515
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
516
- if (checked instanceof Response)
517
- return checked
518
- ctx.request = checked
519
- ctx.params = pluginMatch.params
520
- const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
521
- try {
522
- let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
523
- if (headFallbackPluginDef !== undefined)
524
- res = stripHeadBody(res)
525
- else if (isEventStream(res))
526
- res = streams.track(res, setIdleTimeout)
527
- return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
528
- }
529
- catch (error) {
530
- notifyError(error, ctx.request, 'plugin', requestId)
531
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
532
- }
533
- }
534
-
535
- // Localized/rewritten public/ links (e.g. /fr/logo.png -> /logo.png)
536
- if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
537
- const pub = publicMap.get(effectiveStaticPath)
538
- if (pub !== undefined)
539
- return withRequestId(await serveFile(request, pub), requestId)
540
- }
541
-
542
- const matched = router.match(effective)
543
- // Before any middleware: an unmatched path, a 405 and a route without a handler for the method are checked too, unless the route opts out.
544
- if (matched?.data.mod.csrf !== false) {
545
- const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
546
- if (!originCheck.ok)
547
- return refuseCrossSite(request, originCheck, cookieStore, requestId)
548
- }
549
- if (matched === undefined) {
550
- if (pluginMatch !== undefined) {
551
- ctx.params = pluginMatch.params
552
- const allow = allowedPluginMethodsHeader(pluginMatch.data)
553
- const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
554
- try {
555
- const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
556
- return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
557
- }
558
- catch (error) {
559
- notifyError(error, request, 'plugin', requestId)
560
- return renderError(error, cookieStore, ctx.url, request, ctx)
561
- }
562
- }
563
- return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
564
- }
565
-
566
- ctx.params = matched.params
567
- const route = matched.data
568
-
569
- // Body limit for file-based API routes; the origin was checked above.
570
- if (routeMethodHandler(route.mod, method) !== undefined) {
571
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
572
- if (checked instanceof Response)
573
- return checked
574
- ctx.request = checked
575
- }
576
-
577
- const routeMiddlewares = pluginHost.hasPathScopedMiddlewares && (route.dynamic || effectiveScopedPath !== scopedPath)
578
- ? [...pluginMiddlewaresFor(effectiveScopedPath, scopedPath), ...route.dirMiddlewares]
579
- : route.middlewares
580
-
581
- try {
582
- const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
583
- const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
584
- const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
585
- // Compress uncompressed API/middleware responses after the middleware chain unwinds.
586
- const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
587
- return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
588
- }
589
- catch (error) {
590
- notifyError(error, ctx.request, 'route', requestId)
591
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
592
- }
593
- }
594
- catch (error) {
595
- notifyError(error, request, 'route', requestId)
596
- return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
597
- }
598
- }
373
+ const handleInternal = createRequestHandler({
374
+ isDev, healthPath, healthHandler, resolveRequestId, finish, withHsts, serverError, assetMap, publicMap, serveFile, pluginHost, pluginMiddlewaresFor,
375
+ actions, dispatchAction, fastPrerenderedMap, fastStaticPages, router, trustProxy, httpsSite, consent, trustedOrigins, refuseCrossSite, checkBodyLimit,
376
+ streams, htmlHeaders, compressCache, notifyError, renderError, renderDenied, renderNotFound, renderCompiledRoute,
377
+ })
599
378
 
600
- function handle(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> {
601
- return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
602
- }
379
+ const observe = createRequestObserver(config.log, pluginHost.requestHooks, isDev)
380
+ const handleInternalRequest = (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
381
+ const corsWrap = cors?.wrapWith(finish)
382
+ const withCors = corsWrap?.(handleInternalRequest)
383
+ const handleRequest = withCors === undefined ? handleInternalRequest : async (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> => withCors(request, remoteIp, setIdleTimeout)
384
+ const handle = observe?.(handleRequest) ?? handleRequest
603
385
 
604
386
  const runRequest = (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, setIdleTimeout, true))
605
387
  const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
606
- const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
388
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe, cors: corsWrap })
607
389
 
608
- function serve(port = 3000, hostname = '127.0.0.1') {
609
- const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })
390
+ return appFacade({ config, plugins, handle, handlers, maxRequestBodySize, pluginHost, actions, inject: serverAppCtx.inject, streams, securityRecord })
391
+ }
392
+
393
+ interface AppFacadeDeps {
394
+ config: EmbeddedServerConfig
395
+ plugins: PerProcessInput['plugins']
396
+ handle: PrunelleApp['handle']
397
+ inject: NonNullable<PrunelleApp['inject']>
398
+ handlers: (server: () => PrunelleServer | undefined) => ReturnType<typeof serveHandlers>
399
+ maxRequestBodySize: number
400
+ pluginHost: ServerPluginHost
401
+ actions: ActionRegistry
402
+ streams: ReturnType<typeof createStreamTracker>
403
+ securityRecord: Readonly<Record<string, string>>
404
+ }
405
+
406
+ // What `createServerFromEmbedded` hands its caller: the request handler, and the ways to listen, reload, shut down and report.
407
+ function appFacade(deps: AppFacadeDeps): PrunelleApp {
408
+ const { config, plugins, handlers, pluginHost, streams } = deps
409
+ function serve(port = 3000, hostname = '127.0.0.1', serveOptions: ServeOptions = {}): PrunelleServer {
410
+ const server: PrunelleServer = Bun.serve({ port, hostname, reusePort: serveOptions.reusePort === true, idleTimeout: 30, maxRequestBodySize: deps.maxRequestBodySize, development: false, ...handlers(() => server) })
610
411
  return server
611
412
  }
612
-
613
- const reloadInto = (server: PrunelleServer): void => {
614
- server.reload(handlers(() => server))
413
+ return {
414
+ handle: deps.handle,
415
+ serve,
416
+ reloadInto: server => server.reload(handlers(() => server)),
417
+ perProcessState: () => perProcessState({
418
+ store: config.store,
419
+ limiters: memoryLimiters() + pluginHost.rateLimits.limiters,
420
+ actionsRateLimited: deps.actions.rateLimited(),
421
+ cachedRoutes: config.manifest.routes.some(route => route.cache !== undefined),
422
+ plugins,
423
+ }),
424
+ inject: deps.inject,
425
+ closeStreams: streams.closeAll,
426
+ securityHeaders: deps.securityRecord,
427
+ dispose: async () => {
428
+ await streams.closeAll()
429
+ await pluginHost.dispose()
430
+ },
615
431
  }
616
- return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, securityHeaders: securityRecord, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
617
432
  }
@@ -126,6 +126,8 @@ async function serveStaticDir(options: ServerOptions, root: string, outDir: stri
126
126
  errorSink: options.errorSink,
127
127
  httpsSite: !isDev && site?.startsWith('https://') === true,
128
128
  nodeEnv: options.nodeEnv,
129
+ log: options.log ?? config.log,
130
+ cors: options.cors ?? config.cors,
129
131
  },
130
132
  )
131
133
  }
@@ -3,9 +3,10 @@
3
3
  import type { BuildManifest, RouteManifestEntry } from '../build/index'
4
4
  import type { Html } from '../jsx-runtime'
5
5
  import type { Middleware, RequestContext } from './http'
6
- import type { PrunelleLocals } from './index'
6
+ import type { PrunelleLocals } from './public'
7
7
  import { existsSync } from 'node:fs'
8
8
  import { join } from 'node:path'
9
+ import { cancelQuietly } from './discard'
9
10
 
10
11
  export interface LoadedPageModule {
11
12
  default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
@@ -70,16 +71,9 @@ export function allowedMethodsHeader(mod: LoadedPageModule): string {
70
71
  return [...allowed].join(', ')
71
72
  }
72
73
 
73
- async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
74
- try {
75
- await body.cancel()
76
- }
77
- catch {}
78
- }
79
-
80
74
  export function stripHeadBody(res: Response): Response {
81
75
  if (res.body !== null)
82
- void cancelBodyQuietly(res.body)
76
+ void cancelQuietly(res.body)
83
77
  return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
84
78
  }
85
79