prunelle 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,472 @@
1
+ // Request pathname decoding, manifest prefix/ancestor middleware lookup, 405 helper, and fast static page handler.
2
+
3
+ import type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from '../build/index'
4
+ import type { Html, HydrateStrategy } from '../jsx-runtime'
5
+ import type { DocumentOptions } from '../ssr/index'
6
+ import type { RenderContext } from '../ssr/context'
7
+ import type { ActionRegistry } from './action-registry'
8
+ import type { CompressionCache } from './compress'
9
+ import type { NormalizedConsentConfig } from './consent'
10
+ import type { CookieStore } from './cookies'
11
+ import type { HtmlHeaders } from './document'
12
+ import type { NotifyError } from './errors'
13
+ import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { DeniedInfo, Middleware, RequestContext } from './http'
15
+ import type { PrunelleLocals } from './index'
16
+ import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
+ import type { ParamMatcherMap } from './param-matchers'
18
+ import type { RequestPath } from './request-path'
19
+ import type { RouteCache, RouteCacheSpec } from './route-cache'
20
+ import type { TrustProxy } from './security'
21
+ import { createRenderContext, runWithRenderContext } from '../ssr/context'
22
+ import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
23
+ import { keepScrollTag } from '../ssr/navigation'
24
+ import { compressedHtmlResponse, maybeCompressResponse } from './compress'
25
+ import { headTagStyleHashes, mergeStyleHashes } from './document'
26
+ import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
27
+ import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
28
+ import { pickPageIslandProps } from './page'
29
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
30
+ import { withRegionVary } from './region'
31
+ import { decodeRequestPath, pathPrefix } from './request-path'
32
+ import { isCacheableRequest, serveCachedHit, withCacheControl } from './route-cache'
33
+ import { Router } from './router'
34
+ import { styleHashesOf } from './security'
35
+
36
+ const MIDDLEWARE_BASENAME_RE = /(?:^|\/)_middleware\.js$/
37
+ const ROUTE_GROUP_RE = /^\([^/()]+\)$/
38
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
39
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
40
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
41
+ const CATCH_ALL_BRACKET_RE = /\[\.\.\.([^\]]+)\]/g
42
+ const PARAM_BRACKET_RE = /\[([^\]]+)\]/g
43
+
44
+ export type FastHandler = (req: Request, remoteIp?: string, url?: URL, requestId?: string) => Response | Promise<Response>
45
+
46
+
47
+ export function methodNotAllowed(allow: string): Response {
48
+ return new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 })
49
+ }
50
+
51
+ /** Encodes a static route/asset path for Bun.serve's `routes` table (which requires ASCII keys and treats `*` as a wildcard). */
52
+ export function toBunRouteKey(path: string): string | undefined {
53
+ if (path.includes('*'))
54
+ return undefined
55
+ return path.split('/').map((seg) => {
56
+ if (seg.includes('%')) {
57
+ const decoded = decodeRequestPath(`/${seg}`)
58
+ if (decoded?.staticPath !== undefined)
59
+ return encodeURIComponent(decoded.staticPath.slice(1))
60
+ }
61
+ return encodeURIComponent(seg)
62
+ }).join('/')
63
+ }
64
+
65
+ function dirnamePrefix(file: string): string {
66
+ const slash = file.lastIndexOf('/')
67
+ return slash === -1 ? '' : file.slice(0, slash + 1)
68
+ }
69
+
70
+ function convertDirSegment(seg: string): string {
71
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(seg)
72
+ if (opt !== null)
73
+ return `:${opt[1]}?`
74
+ const catchAll = CATCH_ALL_SEG_RE.exec(seg)
75
+ if (catchAll !== null)
76
+ return `*${catchAll[1]}`
77
+ const param = PARAM_SEG_RE.exec(seg)
78
+ if (param !== null)
79
+ return `:${param[1]}`
80
+ return seg.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')
81
+ }
82
+
83
+ function dirToRoutePattern(relDir: string): string {
84
+ if (relDir === '')
85
+ return '/'
86
+ const parts = relDir.split('/').filter(p => p !== '' && !ROUTE_GROUP_RE.test(p))
87
+ if (parts.length === 0)
88
+ return '/'
89
+ return `/${parts.map(convertDirSegment).join('/')}`
90
+ }
91
+
92
+ /** Infers the compiled module prefix for files under `routesDir` (e.g. `'server/'` or `'server/src/routes/'`). */
93
+ export function inferRoutesServerPrefix(manifest: BuildManifest): string {
94
+ const rootSpecial = manifest.rootLayoutFile ?? manifest.errorFile ?? manifest.notFoundFile
95
+ if (rootSpecial !== undefined)
96
+ return dirnamePrefix(rootSpecial)
97
+
98
+ for (const route of manifest.routes) {
99
+ const fileParts = route.file.split('/')
100
+ const pathSegs = route.path === '/' ? [] : route.path.replace(/^\/|\/$/g, '').split('/')
101
+ const isIndex = fileParts[fileParts.length - 1] === 'index.js'
102
+ let remaining = pathSegs.length + (isIndex ? 1 : 0)
103
+ let idx = fileParts.length
104
+ while (idx > 0 && remaining > 0) {
105
+ idx--
106
+ if (!ROUTE_GROUP_RE.test(fileParts[idx]!))
107
+ remaining--
108
+ }
109
+ while (idx > 0 && ROUTE_GROUP_RE.test(fileParts[idx - 1]!))
110
+ idx--
111
+ if (remaining === 0) {
112
+ const prefixParts = fileParts.slice(0, idx)
113
+ return prefixParts.length === 0 ? '' : `${prefixParts.join('/')}/`
114
+ }
115
+ }
116
+
117
+ for (const entry of manifest.actions) {
118
+ if (entry.file.startsWith('server/src/routes/'))
119
+ return 'server/src/routes/'
120
+ }
121
+ return 'server/'
122
+ }
123
+
124
+ /** Derives an action's route directory prefix (e.g. `'/admin'`) when declared under `routesDir`. */
125
+ export function actionRoutePrefix(
126
+ entry: ActionManifestEntry,
127
+ routesPrefix: string,
128
+ routePathByFile: ReadonlyMap<string, string>,
129
+ ): string | undefined {
130
+ const exactRoutePath = routePathByFile.get(entry.file)
131
+ if (exactRoutePath !== undefined)
132
+ return exactRoutePath
133
+ if (!entry.file.startsWith(routesPrefix))
134
+ return undefined
135
+ const rel = entry.file.slice(routesPrefix.length)
136
+ const slash = rel.lastIndexOf('/')
137
+ const relDir = slash === -1 ? '' : rel.slice(0, slash)
138
+ return dirToRoutePattern(relDir)
139
+ }
140
+
141
+ export interface AncestorMiddlewareMatch {
142
+ middlewares: Middleware[]
143
+ params: Record<string, string>
144
+ }
145
+
146
+ /** Builds a lookup returning the outermost-to-innermost `_middleware.ts` chain for any unmatched pathname. */
147
+ export function createAncestorMiddlewareLookup(
148
+ manifest: BuildManifest,
149
+ modules: Record<string, unknown>,
150
+ routesPrefix: string,
151
+ paramMatchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS,
152
+ ): (path: RequestPath) => AncestorMiddlewareMatch | undefined {
153
+ const byPattern = new Map<string, Middleware[]>()
154
+ const seenModules = new Set<string>()
155
+
156
+ const addMiddlewareModule = (modKey: string): void => {
157
+ if (seenModules.has(modKey))
158
+ return
159
+ seenModules.add(modKey)
160
+ if (!modKey.startsWith(routesPrefix) || !MIDDLEWARE_BASENAME_RE.test(modKey))
161
+ return
162
+ const mod = modules[modKey] as LoadedMiddlewareModule | undefined
163
+ if (typeof mod?.default !== 'function')
164
+ return
165
+ const rel = modKey.slice(routesPrefix.length)
166
+ const relDir = rel.replace(MIDDLEWARE_BASENAME_RE, '')
167
+ // A `(group)` middleware only applies to routes/actions inside that group, never to unrelated unmatched URLs.
168
+ if (relDir !== '' && relDir.split('/').some(p => ROUTE_GROUP_RE.test(p)))
169
+ return
170
+ const pattern = dirToRoutePattern(relDir)
171
+ let list = byPattern.get(pattern)
172
+ if (list === undefined) {
173
+ list = []
174
+ byPattern.set(pattern, list)
175
+ }
176
+ list.push(mod.default)
177
+ }
178
+
179
+ for (const route of manifest.routes) {
180
+ for (const mwKey of route.middlewares)
181
+ addMiddlewareModule(mwKey)
182
+ }
183
+ for (const act of manifest.actions) {
184
+ for (const mwKey of act.middlewares)
185
+ addMiddlewareModule(mwKey)
186
+ }
187
+ for (const modKey of Object.keys(modules)) {
188
+ if (modKey.startsWith(routesPrefix) && MIDDLEWARE_BASENAME_RE.test(modKey))
189
+ addMiddlewareModule(modKey)
190
+ }
191
+
192
+ if (byPattern.size === 0)
193
+ return () => undefined
194
+
195
+ const dirRouter = new Router<Middleware[]>(paramMatchers)
196
+ for (const [pattern, list] of byPattern)
197
+ dirRouter.add(pattern, list)
198
+
199
+ return (path: RequestPath): AncestorMiddlewareMatch | undefined => {
200
+ const middlewares: Middleware[] = []
201
+ const params: Record<string, string> = {}
202
+
203
+ for (let i = 0; i <= path.segments.length; i++) {
204
+ const matched = dirRouter.match(pathPrefix(path, i))
205
+ if (matched !== undefined) {
206
+ for (const mw of matched.data)
207
+ middlewares.push(mw)
208
+ Object.assign(params, matched.params)
209
+ }
210
+ }
211
+
212
+ return middlewares.length > 0 ? { middlewares, params } : undefined
213
+ }
214
+ }
215
+
216
+ export interface FastStaticPageOptions {
217
+ entry: RouteManifestEntry
218
+ mod: LoadedPageModule
219
+ layouts: LoadedLayoutModule[]
220
+ doc: DocumentOptions
221
+ /** The prop revivers, preloaded by the responses whose island props need them. */
222
+ reviveScript: string | undefined
223
+ hasIslands: boolean
224
+ hasLoad: boolean
225
+ trustProxy: TrustProxy
226
+ consent?: NormalizedConsentConfig | undefined
227
+ htmlHeaders: HtmlHeaders
228
+ compressCache: CompressionCache | undefined
229
+ routeCache?: RouteCache | undefined
230
+ actions: ActionRegistry
231
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
232
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
233
+ renderDenied?: ((denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>) | undefined
234
+ notifyError: NotifyError
235
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
236
+ withHsts: (res: Response, request: Request) => Response
237
+ dev?: boolean | undefined
238
+ resolveRequestId?: RequestIdResolver | undefined
239
+ }
240
+
241
+ interface FastRevalidateContext {
242
+ entry: RouteManifestEntry
243
+ mod: LoadedPageModule
244
+ layouts: LoadedLayoutModule[]
245
+ hasLoad: boolean
246
+ hasIslands: boolean
247
+ trustProxy: TrustProxy
248
+ consent: NormalizedConsentConfig | undefined
249
+ htmlHeaders: HtmlHeaders
250
+ routeCache: RouteCache
251
+ actions: ActionRegistry
252
+ notifyError: NotifyError
253
+ getRequestId: RequestIdResolver
254
+ docPrefix: string
255
+ revivingPrefix: string
256
+ docSuffix: string
257
+ headStyleHashes: string[]
258
+ }
259
+
260
+ async function revalidateFastStaticRoute(
261
+ rc: FastRevalidateContext,
262
+ url: URL,
263
+ cacheKey: string,
264
+ cacheSpec: RouteCacheSpec,
265
+ ): Promise<void> {
266
+ const bgReq = new Request(url.href, { method: 'GET' })
267
+ const bgReqId = rc.getRequestId(bgReq)
268
+ const { ctx, cookieStore } = makeRequestContext(bgReq, {}, { trustProxy: rc.trustProxy, url, consent: rc.consent, requestId: bgReqId })
269
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => rc.notifyError(error, bgReq, 'route', bgReqId))
270
+ await rc.actions.run(ctx, async () => {
271
+ let data: unknown
272
+ if (rc.hasLoad) {
273
+ try {
274
+ data = await rc.mod.load!(ctx)
275
+ }
276
+ catch (error) {
277
+ if (isNotFound(error)) {
278
+ rc.routeCache.delete(cacheKey)
279
+ return
280
+ }
281
+ throw error
282
+ }
283
+ if (isNotFound(data) || data instanceof Response) {
284
+ rc.routeCache.delete(cacheKey)
285
+ return
286
+ }
287
+ }
288
+ const body = await runWithRenderContext(rctx, async () => {
289
+ const pageProps: Record<string, unknown> = { params: {}, locals: ctx.locals, url, ...(data !== undefined ? { data } : {}) }
290
+ let cur = rc.entry.isIsland && rc.entry.islandChunk !== undefined
291
+ ? ssrIsland(rc.entry.islandChunk, () => ssrChild(rc.mod.default!(pageProps) as Html), pickPageIslandProps(data, rc.entry, rc.mod), rc.entry.islandHydrate as HydrateStrategy | undefined, true, rc.mod.default!.name)
292
+ : ssrChild(await rc.mod.default!(pageProps) as Html)
293
+ for (let i = rc.layouts.length - 1; i >= 0; i--)
294
+ cur = ssrChild(await rc.layouts[i]!.default({ children: raw(cur), url, params: {}, locals: ctx.locals }) as Html)
295
+ return cur
296
+ })
297
+ if (cookieStore.hasChanges) {
298
+ rc.routeCache.delete(cacheKey)
299
+ return
300
+ }
301
+ const html = (rctx.revives ? rc.revivingPrefix : rc.docPrefix) + body + keepScrollTag(body) + rc.docSuffix
302
+ const styleHashes = mergeStyleHashes(rc.headStyleHashes, styleHashesOf(rctx.inlineStyles))
303
+ const headers = withCacheControl(withRegionVary(rc.htmlHeaders(rc.hasIslands, false, true, styleHashes), rctx.regionNames.size > 0), cacheSpec.cacheControl)
304
+ rc.routeCache.set(cacheKey, html, headers, cacheSpec)
305
+ })
306
+ }
307
+
308
+ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveScript: string | undefined, hasIslands: boolean): { docPrefix: string, revivingPrefix: string, docSuffix: string } {
309
+ const shellAround = (preloadChunks: string[]): [string, string] => {
310
+ const shell = renderDocument({ ...doc, body: '\0', preloadChunks, hasIslands })
311
+ const splitAt = shell.indexOf('\0')
312
+ return [shell.slice(0, splitAt), shell.slice(splitAt + 1)]
313
+ }
314
+ const [docPrefix, docSuffix] = shellAround(eagerChunks)
315
+ const revivingPrefix = reviveScript === undefined ? docPrefix : shellAround([...eagerChunks, reviveScript])[0]
316
+ return { docPrefix, revivingPrefix, docSuffix }
317
+ }
318
+
319
+ /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
320
+ export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
321
+ const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, routeCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
322
+ const isDev = options.dev === true
323
+ const getRequestId: RequestIdResolver = options.resolveRequestId ?? (req => resolveFallbackRequestId(req, trustProxy))
324
+ const cacheSpec = routeCache !== undefined ? entry.cache : undefined
325
+ const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
326
+ const headStyleHashes = headTagStyleHashes(doc.headTags)
327
+ const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
328
+ const revalidateCtx: FastRevalidateContext | undefined = cacheSpec !== undefined && routeCache !== undefined
329
+ ? { entry, mod, layouts, hasLoad, hasIslands, trustProxy, consent, htmlHeaders, routeCache, actions, notifyError, getRequestId, docPrefix, revivingPrefix, docSuffix, headStyleHashes }
330
+ : undefined
331
+
332
+ const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
333
+ notifyError(error, request, 'route', ctx?.requestId)
334
+ return renderError(error, cookieStore, url, request, ctx, entry.file)
335
+ }
336
+ const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
337
+ const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
338
+ const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
339
+ const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
340
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
341
+ if (cacheSpec !== undefined && routeCache !== undefined && !cookieStore.hasChanges && isCacheableRequest(request)) {
342
+ const cachedHeaders = withCacheControl(headers, cacheSpec.cacheControl)
343
+ const stored = routeCache.set(ctx.url.pathname + ctx.url.search, html, cachedHeaders, cacheSpec)
344
+ return withHsts(routeCache.respondMiss(stored, html, cachedHeaders, request, ctx.requestId, compressCache, st), request)
345
+ }
346
+ const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
347
+ res.headers.set('x-request-id', ctx.requestId)
348
+ if (st !== undefined)
349
+ res.headers.set('server-timing', st)
350
+ return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
351
+ }
352
+ const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
353
+
354
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
355
+ try {
356
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
357
+ }
358
+ catch (error) {
359
+ return fail(error, request, url, cookieStore, ctx)
360
+ }
361
+ }
362
+
363
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
364
+ if (layouts.length === 0)
365
+ return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
366
+ if (singleLayout !== undefined) {
367
+ const wrapped = singleLayout.default(layoutProps(inner, url, locals))
368
+ if (wrapped instanceof Promise)
369
+ return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
370
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
371
+ }
372
+ return (async () => {
373
+ try {
374
+ let cur = inner
375
+ for (let i = layouts.length - 1; i >= 0; i--)
376
+ cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
377
+ return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
378
+ }
379
+ catch (error) {
380
+ return fail(error, request, url, cookieStore, ctx)
381
+ }
382
+ })()
383
+ }
384
+
385
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
386
+ try {
387
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
388
+ }
389
+ catch (error) {
390
+ return fail(error, request, url, cookieStore, ctx)
391
+ }
392
+ }
393
+
394
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
395
+ if (timing !== undefined)
396
+ timing.render = performance.now()
397
+ const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
398
+ if (entry.isIsland && entry.islandChunk !== undefined) {
399
+ return wrapLayouts(ssrIsland(
400
+ entry.islandChunk,
401
+ () => ssrChild(mod.default!(pageProps) as Html),
402
+ pickPageIslandProps(data, entry, mod),
403
+ entry.islandHydrate as HydrateStrategy | undefined,
404
+ true,
405
+ mod.default!.name,
406
+ ), request, url, locals, rctx, cookieStore, ctx, timing)
407
+ }
408
+ const rendered = mod.default!(pageProps)
409
+ if (rendered instanceof Promise)
410
+ return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
411
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
412
+ }
413
+
414
+ return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
415
+ const reqId = requestId ?? getRequestId(request)
416
+ if (revalidateCtx !== undefined && cacheSpec !== undefined && routeCache !== undefined && !(request.method === 'HEAD' && typeof mod.HEAD === 'function') && isCacheableRequest(request)) {
417
+ const cacheKey = url.pathname + url.search
418
+ const cached = serveCachedHit(routeCache, cacheKey, request, reqId, compressCache, () => revalidateFastStaticRoute(revalidateCtx, url, cacheKey, cacheSpec), error => notifyError(error, request, 'route', reqId))
419
+ if (cached !== undefined)
420
+ return withHsts(cached, request)
421
+ }
422
+ const timing = createTiming(isDev)
423
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId: reqId })
424
+ if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
425
+ return actions.run(ctx, async () => {
426
+ try {
427
+ return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
428
+ }
429
+ catch (error) {
430
+ return fail(error, request, url, cookieStore, ctx)
431
+ }
432
+ })
433
+ }
434
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
435
+ try {
436
+ if (!hasLoad)
437
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
438
+
439
+ return actions.run(ctx, async () => {
440
+ let loaded: unknown
441
+ const loadStart = startTimer(timing)
442
+ try {
443
+ loaded = await mod.load!(ctx)
444
+ }
445
+ catch (error) {
446
+ if (isNotFound(error))
447
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
448
+ return fail(error, request, url, cookieStore, ctx)
449
+ }
450
+ endTimer(timing, 'load', loadStart)
451
+ if (isNotFound(loaded))
452
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
453
+ if (loaded instanceof Response) {
454
+ const denied = getDeniedInfo(loaded)
455
+ const out = denied !== undefined && renderDenied !== undefined && acceptsHtml(request)
456
+ ? await renderDenied(denied, url, request, ctx, entry.file)
457
+ : loaded
458
+ return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
459
+ }
460
+ try {
461
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
462
+ }
463
+ catch (error) {
464
+ return fail(error, request, url, cookieStore, ctx)
465
+ }
466
+ })
467
+ }
468
+ catch (error) {
469
+ return fail(error, request, url, cookieStore, ctx)
470
+ }
471
+ }
472
+ }