@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
@@ -2,54 +2,68 @@
2
2
  // - Static + dynamic ([param], [...catchall]) Router
3
3
  // - Composable directory-scoped _middleware.ts chains + ctx.cookies + ctx.locals
4
4
  // - Unified Standard-Schema action() endpoint handling with CSRF verification
5
- // - <Head> collection + streaming <Suspense> (0-overhead fast path when unused)
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
8
  import type { BuildManifest, RouteManifestEntry } from '../build/index'
9
9
  import type { Html, HydrateStrategy } from '../jsx-runtime'
10
- import type { KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
- import type { ActionContext, ActionErrorFlash, ServerAction } from './action'
10
+ import type { DocumentHeadContext, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
+ import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
12
+ import type { DocumentOptions } from '../ssr/index'
13
+ import type { ActionErrorFlash, ActionResult, ServerAction } from './action'
12
14
  import type { CookieStore } from './cookies'
13
- import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
14
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
15
- import { extname, join, resolve } from 'node:path'
16
- import { loadConfig } from '../plugins/index'
17
- import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
15
+ import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext } from './http'
16
+ import type { TrustProxy } from './security'
17
+ import { existsSync, statSync } from 'node:fs'
18
+ import { extname, join } from 'node:path'
19
+ import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
20
+ import { createRenderContext, runWithRenderContext, streamChunkScript } from '../ssr/context'
18
21
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
19
- import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
22
+ import { ACTION_ERROR_COOKIE, executeAction, invokeActionCore, isServerAction } from './action'
20
23
  import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
21
- import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, extractRenderedIslands, finalizeResponse, makeRequestContext, MIME } from './http'
24
+ import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, etagMatches, extractRenderedIslands, finalizeResponse, isNotFound, makeRequestContext, MIME, wantsJson } from './http'
22
25
  import { Router } from './router'
23
26
  import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, resolveHstsValue, verifyOrigin, withCspHashes } from './security'
24
27
 
25
- export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
26
- export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
28
+ /**
29
+ * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
30
+ * Augment via `declare module '@kayjs/kay/server' { interface KayLocals { ... } }`.
31
+ */
32
+ export interface KayLocals {}
33
+
34
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
35
+ export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
27
36
  export { action, getActionError } from './action'
28
37
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
29
38
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
30
39
  export type { CompressionEncoding, PrecompressedEncoding } from './compress'
31
40
  export type { CookieOptions, Cookies } from './cookies'
32
- export { defineEnv } from './env'
33
- export { DEFAULT_MAX_REQUEST_BODY_SIZE } from './http'
34
- export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
35
- export { DEFAULT_CSP, DEFAULT_HSTS, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
36
- export type { SecurityHeadersOptions } from './security'
37
- export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
41
+ export { defineEnv, nodeEnv } from './env'
42
+ export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
43
+ export type { EmbeddedServerConfig, ExtractRouteParams, KayApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
44
+ export { createServer } from './loader'
45
+ export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
46
+ export type { SecurityHeadersOptions, TrustProxy } from './security'
47
+ export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
48
+ export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
38
49
 
39
50
  interface LoadedPageModule {
40
51
  default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
41
52
  load?: (ctx: RequestContext) => unknown | Promise<unknown>
53
+ clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
42
54
  csrf?: boolean | undefined
43
55
  GET?: (ctx: RequestContext) => Response | Promise<Response>
44
56
  POST?: (ctx: RequestContext) => Response | Promise<Response>
45
57
  PUT?: (ctx: RequestContext) => Response | Promise<Response>
46
58
  PATCH?: (ctx: RequestContext) => Response | Promise<Response>
47
59
  DELETE?: (ctx: RequestContext) => Response | Promise<Response>
60
+ HEAD?: (ctx: RequestContext) => Response | Promise<Response>
61
+ OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
48
62
  [key: string]: unknown
49
63
  }
50
64
 
51
65
  interface LoadedLayoutModule {
52
- default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: Record<string, unknown> }) => Html | string | Promise<Html | string>
66
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: KayLocals }) => Html | string | Promise<Html | string>
53
67
  }
54
68
 
55
69
  interface LoadedMiddlewareModule {
@@ -60,150 +74,442 @@ interface LoadedErrorModule {
60
74
  default: (props: { error: unknown }) => Html | string | Promise<Html | string>
61
75
  }
62
76
 
77
+ const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
78
+
63
79
  const textEncoder = new TextEncoder()
80
+ // Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
81
+ const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
82
+ // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
83
+ const DEFAULT_STREAM_TIMEOUT = 30_000
84
+
85
+ // A build file ready to serve: headers and compression key are fixed at startup, so a request only picks a variant.
86
+ interface ServedFile {
87
+ key: string
88
+ headers: Record<string, string>
89
+ /** Headers of the on-the-fly compressed variant; undefined when the file is never compressed here. */
90
+ compressedHeaders: Record<string, string> | undefined
91
+ body: BodyInit
92
+ read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
93
+ }
94
+
95
+ interface Sidecar {
96
+ body: BodyInit
97
+ headers: Record<string, string>
98
+ }
99
+
100
+ interface AssetEntry {
101
+ file: ServedFile
102
+ br: Sidecar | undefined
103
+ gz: Sidecar | undefined
104
+ }
105
+
106
+ interface PublicEntry {
107
+ file: ServedFile
108
+ etag: string
109
+ notModifiedHeaders: Record<string, string>
110
+ }
111
+
112
+ type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
113
+
114
+ interface CompiledRoute {
115
+ entry: RouteManifestEntry
116
+ mod: LoadedPageModule
117
+ layouts: LoadedLayoutModule[]
118
+ middlewares: Middleware[]
119
+ /** Dynamic segments (`:param` / `*rest`), so the path names no single URL. */
120
+ dynamic: boolean
121
+ /** Options every document of this route shares; a request adds its body, head and islands. */
122
+ doc: DocumentOptions
123
+ }
124
+
125
+ interface PluginRouteDef {
126
+ handler: (ctx: RequestContext) => Response | Promise<Response>
127
+ csrf: boolean
128
+ trustedOrigins: Set<string> | undefined
129
+ trustProxy: TrustProxy
130
+ }
131
+
132
+ interface ScopedMiddleware {
133
+ mw: Middleware
134
+ scope: 'all' | 'dynamic' | string
135
+ }
136
+
137
+ const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
138
+ const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
139
+ const hasActionErrorCookie = (request: Request): boolean => (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
140
+ // A read the pre-rendered and fast static paths may answer: nothing to flash back to the page.
141
+ const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request)
142
+
143
+ /** Runs `middlewares` in order around `last`; each calls `next` at most once. */
144
+ async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
145
+ if (middlewares.length === 0)
146
+ return last()
147
+ let index = -1
148
+ const dispatch = async (i: number): Promise<Response> => {
149
+ if (i <= index)
150
+ throw new Error('kay: middleware called next() multiple times')
151
+ index = i
152
+ return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
153
+ }
154
+ return dispatch(0)
155
+ }
156
+
157
+ async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
158
+ if (signal.aborted)
159
+ return undefined
160
+ const remaining = Math.max(0, deadlineMs - Date.now())
161
+ let timer: ReturnType<typeof setTimeout> | undefined
162
+ const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
163
+ const onAbort = () => resolve(undefined)
164
+ signal.addEventListener('abort', onAbort, { once: true })
165
+ timer = setTimeout(() => {
166
+ signal.removeEventListener('abort', onAbort)
167
+ const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${remaining} ms`)
168
+ resolve({ html: chunk.renderError(error), error })
169
+ }, remaining)
170
+ })
171
+ try {
172
+ return await Promise.race([chunk.settled, abortedOrTimedOut])
173
+ }
174
+ finally {
175
+ clearTimeout(timer)
176
+ }
177
+ }
64
178
 
65
- type PrerenderEntry = { kind: 'file', path: string, hasIslands: boolean } | { kind: 'html', html: string, hasIslands: boolean }
179
+ function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
180
+ return entry.headTags !== undefined && entry.headTags.length > 0
181
+ ? [...(manifest.headTags ?? []), ...entry.headTags]
182
+ : manifest.headTags
183
+ }
184
+
185
+ function allowedMethodsHeader(mod: LoadedPageModule): string {
186
+ const allowed = new Set<string>()
187
+ if (typeof mod.default === 'function') {
188
+ allowed.add('GET')
189
+ allowed.add('HEAD')
190
+ }
191
+ for (const m of HTTP_METHOD_EXPORTS) {
192
+ if (typeof mod[m] === 'function')
193
+ allowed.add(m)
194
+ }
195
+ if (allowed.has('GET'))
196
+ allowed.add('HEAD')
197
+ return [...allowed].join(', ')
198
+ }
199
+
200
+ function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
201
+ const allowed = new Set<string>()
202
+ for (const m of methods.keys()) {
203
+ if (m === 'ALL')
204
+ continue
205
+ allowed.add(m)
206
+ }
207
+ if (allowed.has('GET'))
208
+ allowed.add('HEAD')
209
+ return [...allowed].join(', ')
210
+ }
211
+
212
+ async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
213
+ try {
214
+ await body.cancel()
215
+ }
216
+ catch {}
217
+ }
218
+
219
+ function stripHeadBody(res: Response): Response {
220
+ if (res.body !== null)
221
+ void cancelBodyQuietly(res.body)
222
+ return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
223
+ }
224
+
225
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
226
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
227
+ }
228
+
229
+ function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
230
+ if (keys.length === 0)
231
+ return undefined
232
+ const picked: Record<string, unknown> = {}
233
+ let count = 0
234
+ for (const k of keys) {
235
+ if (Object.hasOwn(obj, k)) {
236
+ Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
237
+ count++
238
+ }
239
+ }
240
+ return count > 0 ? picked : undefined
241
+ }
242
+
243
+ function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
244
+ if (data === undefined)
245
+ return {}
246
+ if (typeof mod.clientData === 'function') {
247
+ const subset = mod.clientData(data)
248
+ return subset === undefined ? {} : { data: subset }
249
+ }
250
+ if (Array.isArray(mod.clientData)) {
251
+ if (!isPlainObject(data))
252
+ return {}
253
+ const subset = pickObjectKeys(data, mod.clientData)
254
+ return subset === undefined ? {} : { data: subset }
255
+ }
256
+ if (entry.islandDataKeys !== undefined) {
257
+ if (entry.islandDataKeys.length === 0)
258
+ return {}
259
+ if (isPlainObject(data)) {
260
+ const subset = pickObjectKeys(data, entry.islandDataKeys)
261
+ return subset === undefined ? {} : { data: subset }
262
+ }
263
+ }
264
+ return { data }
265
+ }
266
+
267
+ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
268
+ if (scope === 'all')
269
+ return true
270
+ if (scope === 'dynamic')
271
+ return !isStaticFast
272
+ return path === scope || path.startsWith(scope.endsWith('/') ? scope : `${scope}/`)
273
+ }
66
274
 
67
275
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
68
- const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
276
+ const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, lang = 'en', security } = config
277
+ const plugins = resolvePlugins(config.plugins)
69
278
  const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
70
- const trustedOrigins = config.trustedOrigins ? new Set(config.trustedOrigins) : undefined
71
- const trustProxy = config.trustProxy === true
279
+ const site = config.site?.replace(/\/$/, '') || undefined
280
+ const trustedOriginsList = config.trustedOrigins ?? []
281
+ const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
282
+ const trustProxy = config.trustProxy ?? false
72
283
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
284
+ const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
285
+ const isDev = config.dev ?? (process.env.KAY_DEV === '1')
286
+ const serverRoot = config.root ?? process.cwd()
287
+ const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
288
+ const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
289
+ const parentAppCtx = getAppContext()
290
+
73
291
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
292
+ const headHooks = plugins
293
+ .map(p => p.head)
294
+ .filter((fn): fn is NonNullable<KayPlugin['head']> => typeof fn === 'function')
74
295
  const htmlTransformers = plugins
75
296
  .map(p => p.transformHtml)
76
297
  .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
77
298
 
78
299
  const securityEntries = buildSecurityHeaderEntries(security)
79
- const securityRecord: Record<string, string> = {}
80
- for (let i = 0; i < securityEntries.length; i++) {
81
- const [k, v] = securityEntries[i]!
82
- securityRecord[k] = v
83
- }
84
- const nosniffEnabled = security !== false && (security?.contentTypeOptions ?? true)
300
+ const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
301
+ const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
85
302
  const hstsValue = resolveHstsValue(security)
86
- const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy)
303
+ const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
304
+ // The one way out of every response not built with the security headers already in place.
305
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore): Response => withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
306
+ const serverError = (): Response => new Response('Internal Server Error', {
307
+ status: 500,
308
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
309
+ })
87
310
 
88
- const htmlBaseHeaders: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
311
+ // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
89
312
  const baseCsp = resolveCspPolicy(security)
90
- const makeHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> => {
91
- const base = isDynamic
92
- ? { ...htmlBaseHeaders, 'cache-control': 'private' }
93
- : htmlBaseHeaders
94
- if (baseCsp === undefined || (!hasIslands && !hasSuspense))
95
- return base
96
- const styleHashes: string[] = []
97
- const scriptHashes: string[] = []
98
- if (hasIslands)
99
- styleHashes.push(KAY_ISLAND_STYLE_HASH)
100
- if (hasSuspense) {
101
- styleHashes.push(KAY_SUSPENSE_STYLE_HASH)
102
- scriptHashes.push(KAY_STREAM_SCRIPT_HASH)
313
+ const htmlHeaderSets: Record<string, string>[] = []
314
+ for (let i = 0; i < 8; i++) {
315
+ const isDynamic = (i & 4) !== 0
316
+ const hasIslands = (i & 2) !== 0
317
+ const hasSuspense = (i & 1) !== 0
318
+ const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
319
+ if (isDynamic)
320
+ headers['cache-control'] = 'private'
321
+ if (baseCsp !== undefined && (hasIslands || hasSuspense)) {
322
+ headers['content-security-policy'] = withCspHashes(baseCsp, {
323
+ styleHashes: [...(hasIslands ? [KAY_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [KAY_SUSPENSE_STYLE_HASH] : [])],
324
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
325
+ })
103
326
  }
104
- return { ...base, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
327
+ htmlHeaderSets.push(headers)
105
328
  }
106
- const htmlHeadersPlain = makeHtmlHeaders(false, false, false)
107
- const htmlHeadersIslands = makeHtmlHeaders(true, false, false)
108
- const htmlHeadersSuspense = makeHtmlHeaders(false, true, false)
109
- const htmlHeadersBoth = makeHtmlHeaders(true, true, false)
110
- const selectHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
111
- hasIslands
112
- ? (hasSuspense ? htmlHeadersBoth : htmlHeadersIslands)
113
- : (hasSuspense ? htmlHeadersSuspense : htmlHeadersPlain)
114
-
115
- const dynHeadersPlain = makeHtmlHeaders(false, false, true)
116
- const dynHeadersIslands = makeHtmlHeaders(true, false, true)
117
- const dynHeadersSuspense = makeHtmlHeaders(false, true, true)
118
- const dynHeadersBoth = makeHtmlHeaders(true, true, true)
119
- const selectDynamicHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
120
- hasIslands
121
- ? (hasSuspense ? dynHeadersBoth : dynHeadersIslands)
122
- : (hasSuspense ? dynHeadersSuspense : dynHeadersPlain)
123
-
124
- const compressEnabled = config.compress ?? (process.env.KAY_DEV !== '1')
329
+ const htmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> =>
330
+ htmlHeaderSets[(isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)]!
331
+
332
+ const compressEnabled = config.compress ?? !isDev
125
333
  const compressCache = compressEnabled ? new CompressionCache() : undefined
334
+ const varyEncoding: Record<string, string> = compressCache !== undefined ? { vary: 'Accept-Encoding' } : {}
126
335
 
127
- // Collect plugin server hooks (supports both sync and async plugin setup)
128
- interface PluginRouteDef {
129
- handler: (ctx: RequestContext) => Response | Promise<Response>
130
- csrf: boolean
336
+ const toBody = (body: EmbeddedBody): BodyInit => typeof body === 'string' ? Bun.file(body) : body
337
+ const readBody = async (body: EmbeddedBody): Promise<Uint8Array<ArrayBuffer>> => typeof body === 'string' ? new Uint8Array(await Bun.file(body).arrayBuffer()) : body
338
+ const builtFile = (key: string, source: EmbeddedBody, headers: Record<string, string>, compressedHeaders: Record<string, string> | undefined): ServedFile =>
339
+ ({ key, headers, compressedHeaders, body: toBody(source), read: () => readBody(source) })
340
+
341
+ const publicMap = new Map<string, PublicEntry>()
342
+ const publicCacheControl = isDev ? 'no-cache' : 'public, max-age=3600'
343
+
344
+ const registerPublicEntry = (rel: string, body: EmbeddedBody, explicitEtag?: string): void => {
345
+ const cleanRel = rel.replace(/^\/+/, '')
346
+ const etag = explicitEtag ?? `W/"${Bun.hash(typeof body === 'string' ? cleanRel : body).toString(36)}"`
347
+ const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
348
+ const hasVary = compressCache !== undefined && isCompressibleType(type)
349
+ const validators = { etag, 'cache-control': publicCacheControl, ...(hasVary ? { vary: 'Accept-Encoding' } : {}), ...nosniffHeader }
350
+ const headers = { 'content-type': type, ...validators }
351
+ publicMap.set(`/${cleanRel}`, {
352
+ etag,
353
+ notModifiedHeaders: validators,
354
+ file: builtFile(`p:/${cleanRel}:${etag}`, body, headers, hasVary ? { ...headers, etag: toWeakEtag(etag) } : undefined),
355
+ })
131
356
  }
132
- const globalMiddlewares: Middleware[] = []
357
+
358
+ for (const [rel, body] of Object.entries(publicAssets))
359
+ registerPublicEntry(rel, body, publicEtags[rel])
360
+
361
+ const serverAppCtx = createAppContext({
362
+ root: serverRoot,
363
+ outDir: serverOutDir,
364
+ publicDir: serverPublicDir,
365
+ assetPrefix,
366
+ site,
367
+ dev: isDev,
368
+ onRegisterPublicFile: (rel) => {
369
+ parentAppCtx?.registerPublicFile(rel)
370
+ const cleanRel = rel.replace(/^\/+/, '')
371
+ const abs = join(serverPublicDir, cleanRel)
372
+ if (existsSync(abs)) {
373
+ const st = statSync(abs)
374
+ registerPublicEntry(cleanRel, abs, `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`)
375
+ }
376
+ },
377
+ })
378
+
379
+ // Plugin server hooks (plugin setup may be sync or async)
380
+ const scopedMiddlewares: ScopedMiddleware[] = []
381
+ const shutdownHooks: (() => void | Promise<void>)[] = []
133
382
  const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
134
383
  const pluginRouter = new Router<Map<string, PluginRouteDef>>()
135
384
  const pluginRouteEntries = new Map<string, Map<string, PluginRouteDef>>()
136
385
 
137
- const pluginApi: ServerPluginAPI = {
138
- use(mw) {
139
- globalMiddlewares.push(mw)
140
- },
141
- route(method, path, handler, options?: PluginRouteOptions) {
142
- let byMethod = pluginRouteEntries.get(path)
143
- if (byMethod === undefined) {
144
- byMethod = new Map()
145
- pluginRouteEntries.set(path, byMethod)
146
- pluginRouter.add(path, byMethod)
147
- }
148
- byMethod.set(method.toUpperCase(), { handler, csrf: options?.csrf ?? true })
149
- },
150
- rewrite(fn) {
151
- pluginRewrites.push(fn)
152
- },
386
+ const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
387
+ const actionByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
388
+
389
+ const registerPluginRoute = (
390
+ method: string,
391
+ path: string,
392
+ handler: (ctx: RequestContext) => Response | Promise<Response>,
393
+ options?: PluginRouteOptions,
394
+ ): void => {
395
+ const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
396
+ let byMethod = pluginRouteEntries.get(normPath)
397
+ if (byMethod === undefined) {
398
+ byMethod = new Map()
399
+ pluginRouteEntries.set(normPath, byMethod)
400
+ pluginRouter.add(normPath, byMethod)
401
+ }
402
+ let routeTrustedOrigins = trustedOrigins
403
+ if (options?.trustedOrigins !== undefined && options.trustedOrigins.length > 0) {
404
+ routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...options.trustedOrigins])
405
+ }
406
+ byMethod.set(method.toUpperCase(), {
407
+ handler,
408
+ csrf: options?.csrf ?? true,
409
+ trustedOrigins: routeTrustedOrigins,
410
+ trustProxy: options?.trustProxy ?? trustProxy,
411
+ })
153
412
  }
154
413
 
155
- for (const plugin of plugins) {
156
- if (plugin.server !== undefined)
157
- await plugin.server(pluginApi)
414
+ async function invokeRegisteredAction<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
415
+ const dirMiddlewares = actionByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
416
+ if (dirMiddlewares.length === 0)
417
+ return invokeActionCore(act, input, ctx)
418
+
419
+ let actionResult: ActionResult<O> | undefined
420
+ const res = await runChain(ctx, dirMiddlewares, async () => {
421
+ actionResult = await invokeActionCore(act, input, ctx)
422
+ return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
423
+ })
424
+ if (actionResult !== undefined)
425
+ return actionResult
426
+ // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
427
+ const ct = res.headers.get('content-type') ?? ''
428
+ if (ct.includes('application/json')) {
429
+ try {
430
+ const body = await res.clone().json() as Record<string, unknown>
431
+ return {
432
+ ok: false,
433
+ status: res.status,
434
+ error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
435
+ }
436
+ }
437
+ catch {}
438
+ }
439
+ let text = ''
440
+ try {
441
+ text = await res.clone().text()
442
+ }
443
+ catch {}
444
+ return {
445
+ ok: false,
446
+ status: res.status,
447
+ error: text || res.statusText || 'Forbidden',
448
+ }
158
449
  }
159
450
 
160
- const hasGlobalMiddleware = globalMiddlewares.length > 0
161
- const hasPluginRewrites = pluginRewrites.length > 0
162
- const hasHtmlTransformers = htmlTransformers.length > 0
451
+ const {
452
+ manifest: _m,
453
+ modules: _mods,
454
+ assets: _a,
455
+ publicAssets: _pa,
456
+ publicEtags: _pe,
457
+ prerendered: _pr,
458
+ prerenderedFiles: _pf,
459
+ ...forwardedConfig
460
+ } = config as EmbeddedServerConfig & Record<string, unknown>
461
+ const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
163
462
 
164
- // Hashed build asset table (immutable cache + precompressed .br/.gz sidecars + optional lazy compression)
165
- interface AssetEntry {
166
- body: EmbeddedBody
167
- br?: EmbeddedBody | undefined
168
- gz?: EmbeddedBody | undefined
169
- type: string
170
- compressible: boolean
171
- headers: Record<string, string>
172
- varyHeaders: Record<string, string>
173
- }
174
- const assetMap = new Map<string, AssetEntry>()
175
- for (const [rel, body] of Object.entries(assets)) {
176
- const brSidecar = assets[`${rel}.br`] ?? (typeof body === 'string' && existsSync(`${body}.br`) ? `${body}.br` : undefined)
177
- const gzSidecar = assets[`${rel}.gz`] ?? (typeof body === 'string' && existsSync(`${body}.gz`) ? `${body}.gz` : undefined)
178
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
179
- const compressible = isCompressibleType(type)
180
- const headers: Record<string, string> = {
181
- 'content-type': type,
182
- 'cache-control': 'public, max-age=31536000, immutable',
183
- ...(nosniffEnabled ? { 'x-content-type-options': 'nosniff' } : {}),
463
+ for (const plugin of plugins) {
464
+ if (plugin.dispose !== undefined)
465
+ shutdownHooks.push(() => plugin.dispose!())
466
+ if (plugin.server !== undefined) {
467
+ const pluginApi: ServerPluginAPI = {
468
+ root: serverRoot,
469
+ outDir: serverOutDir,
470
+ assetPrefix,
471
+ site,
472
+ dev: isDev,
473
+ trustProxy,
474
+ trustedOrigins: trustedOriginsList,
475
+ config: readonlyRuntimeConfig,
476
+ use(mw: Middleware, options?: MiddlewareOptions) {
477
+ scopedMiddlewares.push({ mw, scope: options?.scope ?? 'all' })
478
+ },
479
+ route: registerPluginRoute,
480
+ rewrite(fn) {
481
+ pluginRewrites.push(fn)
482
+ },
483
+ provide: serverAppCtx.provide,
484
+ inject: serverAppCtx.inject,
485
+ getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
486
+ return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
487
+ },
488
+ onShutdown(fn) {
489
+ shutdownHooks.push(fn)
490
+ },
491
+ invokeAction: invokeRegisteredAction,
492
+ }
493
+ await runWithAppContext(serverAppCtx, () => plugin.server!(pluginApi))
184
494
  }
185
- const canVary = (compressible && compressCache !== undefined) || brSidecar !== undefined || gzSidecar !== undefined
186
- const varyHeaders: Record<string, string> = canVary
187
- ? { ...headers, vary: 'Accept-Encoding' }
188
- : headers
189
- assetMap.set(`${assetPrefix}/${rel}`, { body, br: brSidecar, gz: gzSidecar, type, compressible, headers, varyHeaders })
190
495
  }
191
496
 
192
- // Static public/ file table (ETag + 304 + zero-copy Bun.file + optional lazy compression)
193
- interface PublicEntry {
194
- body: EmbeddedBody
195
- type: string
196
- etag: string
197
- compressible: boolean
198
- }
199
- const publicMap = new Map<string, PublicEntry>()
200
- for (const [rel, body] of Object.entries(publicAssets)) {
201
- const etag = publicEtags[rel] ?? (typeof body === 'string' ? `W/"${Bun.hash(rel).toString(36)}"` : `W/"${Bun.hash(body).toString(36)}"`)
202
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
203
- publicMap.set(`/${rel}`, { body, type, etag, compressible: isCompressibleType(type) })
497
+ const allPluginMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
498
+ const staticFastPluginMiddlewares: readonly Middleware[] = scopedMiddlewares
499
+ .filter(m => m.scope === 'all')
500
+ .map(m => m.mw)
501
+ const hasPathScopedMiddlewares = scopedMiddlewares.some(m => m.scope !== 'all' && m.scope !== 'dynamic')
502
+ const middlewaresFor = (path: string, isStaticFast = false): readonly Middleware[] => {
503
+ if (scopedMiddlewares.length === 0)
504
+ return allPluginMiddlewares
505
+ if (!hasPathScopedMiddlewares)
506
+ return isStaticFast ? staticFastPluginMiddlewares : allPluginMiddlewares
507
+ return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, isStaticFast)).map(m => m.mw)
204
508
  }
509
+ const hasPluginRewrites = pluginRewrites.length > 0
510
+ const hasHeadHooks = headHooks.length > 0
511
+ const hasHtmlTransformers = htmlTransformers.length > 0
205
512
 
206
- const toResponseBody = (body: EmbeddedBody) => typeof body === 'string' ? Bun.file(body) : body
207
513
  const errorHooks: ((info: ServerErrorInfo) => void)[] = []
208
514
  if (config.onError !== undefined)
209
515
  errorHooks.push(config.onError)
@@ -212,302 +518,424 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
212
518
  errorHooks.push(p.onError)
213
519
  }
214
520
  const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
215
- for (let i = 0; i < errorHooks.length; i++) {
521
+ for (const hook of errorHooks) {
216
522
  try {
217
- errorHooks[i]!({ error, request, source })
523
+ hook({ error, request, source })
218
524
  }
219
525
  catch {}
220
526
  }
221
527
  }
222
528
 
223
- async function serveAsset(request: Request, pathname: string, asset: AssetEntry): Promise<Response> {
224
- if (request.method === 'HEAD')
225
- return withHsts(new Response(null, { status: 200, headers: asset.varyHeaders }), request)
226
-
227
- // Serve precompressed .br / .gz sidecars directly without on-the-fly recompression
228
- if (compressEnabled && (asset.br !== undefined || asset.gz !== undefined)) {
229
- const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), {
230
- br: asset.br !== undefined,
231
- gz: asset.gz !== undefined,
232
- })
233
- if (preEnc !== undefined) {
234
- const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
235
- const headers: Record<string, string> = { ...asset.headers, 'content-encoding': preEnc, 'vary': 'Accept-Encoding' }
236
- if (headers.etag !== undefined)
237
- headers.etag = toWeakEtag(headers.etag)
238
- return withHsts(new Response(toResponseBody(sidecar), { status: 200, headers }), request)
239
- }
529
+ // Hashed build assets: immutable cache, precompressed .br/.gz sidecars, optional lazy compression.
530
+ // Skip `.br`/`.gz` sidecars as standalone HTTP routes when their base asset exists.
531
+ const assetMap = new Map<string, AssetEntry>()
532
+ for (const [rel, body] of Object.entries(assets)) {
533
+ if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
534
+ continue
535
+ const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
536
+ const compressible = compressCache !== undefined && isCompressibleType(type)
537
+ const headers: Record<string, string> = {
538
+ 'content-type': type,
539
+ 'cache-control': 'public, max-age=31536000, immutable',
540
+ ...nosniffHeader,
240
541
  }
241
-
242
- if (compressCache !== undefined && asset.compressible) {
243
- const enc = pickEncoding(request.headers.get('accept-encoding'))
244
- if (enc !== undefined) {
245
- const key = `${enc}:a:${pathname}`
246
- let compressed = compressCache.get(key)
247
- if (compressed === undefined) {
248
- const rawBytes = typeof asset.body === 'string'
249
- ? new Uint8Array(await Bun.file(asset.body).arrayBuffer())
250
- : asset.body
251
- compressed = compressCache.compress(rawBytes, enc, `a:${pathname}`)
252
- if (compressed === undefined)
253
- return withHsts(new Response(rawBytes, { status: 200, headers: asset.varyHeaders }), request)
254
- }
255
- return withHsts(new Response(compressed, {
256
- status: 200,
257
- headers: { ...asset.headers, 'content-encoding': enc, vary: 'Accept-Encoding' },
258
- }), request)
259
- }
542
+ const sidecar = (ext: 'br' | 'gz', encoding: string): Sidecar | undefined => {
543
+ const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
544
+ return source === undefined ? undefined : { body: toBody(source), headers: { ...headers, 'content-encoding': encoding, 'vary': 'Accept-Encoding' } }
260
545
  }
261
-
262
- return withHsts(new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders }), request)
546
+ const br = sidecar('br', 'br')
547
+ const gz = sidecar('gz', 'gzip')
548
+ const varyHeaders = compressible || br !== undefined || gz !== undefined ? { ...headers, vary: 'Accept-Encoding' } : headers
549
+ assetMap.set(`${assetPrefix}/${rel}`, {
550
+ file: builtFile(`a:${assetPrefix}/${rel}`, body, varyHeaders, compressible ? varyHeaders : undefined),
551
+ br,
552
+ gz,
553
+ })
263
554
  }
264
555
 
265
- async function servePublic(request: Request, pathname: string, pub: PublicEntry): Promise<Response> {
266
- const cacheControl = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
267
- const hasVary = pub.compressible && compressCache !== undefined
268
- const nosniffHeader: Record<string, string> = nosniffEnabled ? { 'x-content-type-options': 'nosniff' } : {}
269
- if (request.headers.get('if-none-match') === pub.etag) {
270
- const h: Record<string, string> = hasVary
271
- ? { 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding', ...nosniffHeader }
272
- : { 'etag': pub.etag, 'cache-control': cacheControl, ...nosniffHeader }
273
- return withHsts(new Response(null, { status: 304, headers: h }), request)
274
- }
275
-
276
- const baseHeaders: Record<string, string> = hasVary
277
- ? { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding', ...nosniffHeader }
278
- : { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, ...nosniffHeader }
279
-
556
+ async function serveFile(request: Request, file: ServedFile): Promise<Response> {
280
557
  if (request.method === 'HEAD')
281
- return withHsts(new Response(null, { status: 200, headers: baseHeaders }), request)
282
-
283
- if (hasVary) {
558
+ return withHsts(new Response(null, { status: 200, headers: file.headers }), request)
559
+ if (file.compressedHeaders !== undefined && compressCache !== undefined) {
284
560
  const enc = pickEncoding(request.headers.get('accept-encoding'))
285
561
  if (enc !== undefined) {
286
- const staticKey = `p:${pathname}:${pub.etag}`
287
- let compressed = compressCache.get(`${enc}:${staticKey}`)
288
- if (compressed === undefined) {
289
- const rawBytes = typeof pub.body === 'string'
290
- ? new Uint8Array(await Bun.file(pub.body).arrayBuffer())
291
- : pub.body
292
- compressed = compressCache.compress(rawBytes, enc, staticKey)
293
- if (compressed === undefined)
294
- return withHsts(new Response(rawBytes, { status: 200, headers: baseHeaders }), request)
295
- }
296
- return withHsts(new Response(compressed, {
297
- status: 200,
298
- headers: { ...baseHeaders, 'etag': toWeakEtag(pub.etag), 'content-encoding': enc },
299
- }), request)
562
+ const compressed = await compressCache.file(file.key, enc, file.read)
563
+ if (compressed !== undefined)
564
+ return withHsts(new Response(compressed, { status: 200, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
300
565
  }
301
566
  }
302
-
303
- return withHsts(new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders }), request)
567
+ return withHsts(new Response(file.body, { status: 200, headers: file.headers }), request)
304
568
  }
305
569
 
306
- async function servePrerendered(request: Request, pathname: string, pre: PrerenderEntry): Promise<Response> {
307
- const base = selectHtmlHeaders(pre.hasIslands, false)
308
- const headers = compressCache !== undefined
309
- ? { ...base, vary: 'Accept-Encoding' }
310
- : base
311
-
312
- if (request.method === 'HEAD')
313
- return withHsts(new Response(null, { status: 200, headers }), request)
314
-
315
- if (compressCache !== undefined) {
316
- const enc = pickEncoding(request.headers.get('accept-encoding'))
317
- if (enc !== undefined) {
318
- const staticKey = `pre:${pathname}`
319
- let compressed = compressCache.get(`${enc}:${staticKey}`)
320
- if (compressed === undefined) {
321
- const rawBytes = pre.kind === 'file'
322
- ? new Uint8Array(await Bun.file(pre.path).arrayBuffer())
323
- : textEncoder.encode(pre.html)
324
- compressed = compressCache.compress(rawBytes, enc, staticKey)
325
- if (compressed === undefined)
326
- return withHsts(new Response(rawBytes, { status: 200, headers }), request)
327
- }
328
- return withHsts(new Response(compressed, {
329
- status: 200,
330
- headers: { ...headers, 'content-encoding': enc },
331
- }), request)
570
+ async function serveAsset(request: Request, asset: AssetEntry): Promise<Response> {
571
+ if (compressEnabled && request.method !== 'HEAD' && (asset.br !== undefined || asset.gz !== undefined)) {
572
+ const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), { br: asset.br !== undefined, gz: asset.gz !== undefined })
573
+ if (preEnc !== undefined) {
574
+ const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
575
+ return withHsts(new Response(sidecar.body, { status: 200, headers: sidecar.headers }), request)
332
576
  }
333
577
  }
578
+ return serveFile(request, asset.file)
579
+ }
334
580
 
335
- const body = pre.kind === 'file' ? Bun.file(pre.path) : pre.html
336
- return withHsts(new Response(body, { status: 200, headers }), request)
581
+ async function servePublic(request: Request, pub: PublicEntry): Promise<Response> {
582
+ if (etagMatches(request.headers.get('if-none-match'), pub.etag))
583
+ return withHsts(new Response(null, { status: 304, headers: pub.notModifiedHeaders }), request)
584
+ return serveFile(request, pub.file)
337
585
  }
338
586
 
339
- // Register server actions and assign their live URLs
340
- const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
587
+ // Server actions and their live URLs
341
588
  for (const entry of manifest.actions) {
342
589
  const mod = modules[entry.file] as Record<string, unknown> | undefined
343
590
  const act = mod?.[entry.exportName]
344
591
  if (isServerAction(act)) {
345
592
  ;(act as { url: string }).url = entry.url
346
- const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
347
- actionHandlers.set(entry.url, { act, middlewares: [...globalMiddlewares, ...middlewares] })
593
+ const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
594
+ actionByRef.set(act, dirMiddlewares)
595
+ actionHandlers.set(entry.url, { act, middlewares: [...middlewaresFor(entry.url), ...dirMiddlewares] })
348
596
  }
349
597
  }
350
598
 
351
599
  const errorMod = manifest.errorFile ? modules[manifest.errorFile] as LoadedErrorModule : undefined
352
600
  const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as LoadedPageModule : undefined
353
601
 
354
- // Static prerendered pages table (zero-copy file paths preferred; raw HTML strings supported)
355
- const prerenderedMap = new Map<string, PrerenderEntry>()
356
- const fastPrerenderedMap = new Map<string, PrerenderEntry>()
602
+ // Prerendered pages (zero-copy file paths preferred; raw HTML strings supported). `fastPrerenderedMap` holds those nothing may intercept.
603
+ const prerenderedMap = new Map<string, ServedFile>()
604
+ const fastPrerenderedMap = new Map<string, ServedFile>()
357
605
  for (const route of manifest.routes) {
358
- if (route.prerendered) {
359
- const routeHasIslands = route.islandChunks.length > 0
360
- for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
361
- const filePath = prerenderedFiles[relHtml]
362
- const html = prerendered[relHtml]
363
- const entry: PrerenderEntry | undefined = filePath !== undefined
364
- ? { kind: 'file', path: filePath, hasIslands: routeHasIslands }
365
- : html !== undefined
366
- ? { kind: 'html', html, hasIslands: routeHasIslands }
367
- : undefined
368
- if (entry !== undefined) {
369
- prerenderedMap.set(urlPath, entry)
370
- if (route.middlewares.length === 0 && !hasGlobalMiddleware && pluginRouter.match(urlPath) === undefined)
371
- fastPrerenderedMap.set(urlPath, entry)
606
+ if (route.prerendered === undefined)
607
+ continue
608
+ const headers: Record<string, string> = { ...htmlHeaders(route.islandChunks.length > 0, false, false), ...varyEncoding }
609
+ const compressedHeaders = compressCache !== undefined ? headers : undefined
610
+ for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
611
+ const filePath = prerenderedFiles[relHtml]
612
+ const html = prerendered[relHtml]
613
+ const key = `pre:${urlPath}`
614
+ const entry: ServedFile | undefined = filePath !== undefined
615
+ ? builtFile(key, filePath, headers, compressedHeaders)
616
+ : html !== undefined
617
+ ? { key, headers, compressedHeaders, body: html, read: () => textEncoder.encode(html) }
618
+ : undefined
619
+ if (entry === undefined)
620
+ continue
621
+ prerenderedMap.set(urlPath, entry)
622
+ if (route.middlewares.length === 0 && middlewaresFor(urlPath, true).length === 0 && !hasPluginRewrites && pluginRouter.match(urlPath) === undefined)
623
+ fastPrerenderedMap.set(urlPath, entry)
624
+ }
625
+ }
626
+
627
+ const router = new Router<CompiledRoute>()
628
+ const fastStaticPages = new Map<string, FastHandler>()
629
+
630
+ // Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
631
+ const rootLayoutFile = manifest.rootLayoutFile
632
+ const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
633
+ const fallbackDoc: DocumentOptions = {
634
+ body: '',
635
+ headTags: manifest.headTags,
636
+ styles: manifest.globalStyles ?? manifest.styles,
637
+ runtimeScript: manifest.runtimeScript,
638
+ alwaysLoadRuntime,
639
+ lang,
640
+ }
641
+
642
+ const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
643
+
644
+ async function resolveDocumentHead(
645
+ rctx: RenderContext,
646
+ baseHeadTags: readonly string[] | undefined,
647
+ url: URL,
648
+ req?: Request,
649
+ ctx?: RequestContext,
650
+ ): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string> }> {
651
+ const collectedParts = rctx.headParts.join('')
652
+ if (!hasHeadHooks) {
653
+ return {
654
+ head: (rctx.title ?? '') + collectedParts,
655
+ lang,
656
+ htmlAttrs: rctx.htmlAttrs,
657
+ }
658
+ }
659
+
660
+ const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
661
+ const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
662
+ const initialTitleTag = rctx.title
663
+ const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
664
+ let currentTitle = initialTitleInner
665
+ let titleDirty = false
666
+ let currentLang = htmlAttrs.lang ?? lang
667
+ let headBuf = (initialTitleTag ?? '') + collectedParts
668
+ if (baseHeadTags !== undefined) {
669
+ for (let i = 0; i < baseHeadTags.length; i++)
670
+ headBuf += baseHeadTags[i]
671
+ }
672
+ const added: string[] = []
673
+
674
+ const docHead: DocumentHeadContext = {
675
+ get lang() {
676
+ return currentLang
677
+ },
678
+ set lang(v: string) {
679
+ currentLang = v
680
+ htmlAttrs.lang = v
681
+ },
682
+ htmlAttrs,
683
+ get title() {
684
+ return currentTitle
685
+ },
686
+ set title(v: string | undefined) {
687
+ currentTitle = v
688
+ titleDirty = true
689
+ },
690
+ get headHtml() {
691
+ return headBuf
692
+ },
693
+ add(html: string) {
694
+ if (html !== '') {
695
+ added.push(html)
696
+ headBuf += html
372
697
  }
698
+ },
699
+ }
700
+
701
+ for (const hook of headHooks) {
702
+ try {
703
+ await hook(docHead, headCtx)
373
704
  }
705
+ catch (err) {
706
+ notifyError(err, req ?? headCtx.request, 'plugin')
707
+ }
708
+ }
709
+
710
+ const titleHtml = titleDirty
711
+ ? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
712
+ : (initialTitleTag ?? '')
713
+ return {
714
+ head: titleHtml + collectedParts + (added.length > 0 ? added.join('') : ''),
715
+ lang: currentLang,
716
+ htmlAttrs,
374
717
  }
375
718
  }
376
719
 
377
- interface CompiledRoute {
378
- entry: RouteManifestEntry
379
- mod: LoadedPageModule
380
- layouts: LoadedLayoutModule[]
381
- middlewares: Middleware[]
382
- fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
383
- docPrefix: string
384
- docSuffix: string
720
+ async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
721
+ if (!hasHtmlTransformers)
722
+ return html
723
+ const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
724
+ let out = html
725
+ for (const transform of htmlTransformers) {
726
+ try {
727
+ out = await transform(out, transformCtx)
728
+ }
729
+ catch (err) {
730
+ notifyError(err, req ?? transformCtx.request, 'plugin')
731
+ }
732
+ }
733
+ return out
385
734
  }
386
735
 
387
- const router = new Router<CompiledRoute>()
388
- const fastStaticPages = new Map<string, (req: Request, remoteIp?: string) => Response | Promise<Response>>()
736
+ function resolveRenderedIslands(rctx: ReturnType<typeof createRenderContext>, body: string): { hasIslands: boolean, eagerChunks: string[] } {
737
+ if (rctx.hasIslands) {
738
+ const eagerChunks: string[] = []
739
+ for (const [chunk, eager] of rctx.renderedIslands) {
740
+ if (eager)
741
+ eagerChunks.push(chunk)
742
+ }
743
+ return { hasIslands: true, eagerChunks }
744
+ }
745
+ // Fallback only if raw HTML injected a <kay-island> without going through ssrIsland/ssrIslandStatic.
746
+ if (body.includes('<kay-island'))
747
+ return extractRenderedIslands(body)
748
+ return { hasIslands: false, eagerChunks: [] }
749
+ }
750
+
751
+ async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
752
+ if (renderInner !== undefined) {
753
+ try {
754
+ const effUrl = url ?? new URL(`http://localhost/${status}`)
755
+ const rctx = createRenderContext()
756
+ const body = await runWithRenderContext(rctx, async () => {
757
+ let inner = ssrChild(await renderInner() as Html)
758
+ if (rootLayoutMod !== undefined)
759
+ inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
760
+ return inner
761
+ })
762
+ const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
763
+ const docHead = await resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
764
+ const docHtml = renderDocument({
765
+ ...fallbackDoc,
766
+ body,
767
+ head: docHead.head,
768
+ lang: docHead.lang,
769
+ htmlAttrs: docHead.htmlAttrs,
770
+ preloadChunks: eagerChunks,
771
+ hasIslands,
772
+ })
773
+ const html = await applyHtmlTransforms(docHtml, effUrl, req, ctx)
774
+ return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true) })
775
+ }
776
+ catch (err) {
777
+ if (req !== undefined)
778
+ notifyError(err, req, 'route')
779
+ }
780
+ }
781
+ return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
782
+ }
783
+
784
+ const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
785
+ renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), 'Internal Server Error', url, req, ctx)
786
+
787
+ const notFoundPage = notFoundMod?.default
788
+ const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
789
+ renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
790
+
791
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
792
+ if (wantsJson(request))
793
+ return finish(Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
794
+ return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
795
+ }
796
+
797
+ async function renderNotFound(cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext): Promise<Response> {
798
+ const res = await runChain(ctx, middlewaresFor(url.pathname), () => buildNotFoundResponse(url, request, ctx))
799
+ return finish(res, request, cookieStore)
800
+ }
801
+
802
+ function refuseCrossSite(request: Request, reason: string, cookieStore?: CookieStore): Response {
803
+ return finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore)
804
+ }
389
805
 
390
806
  for (const entry of manifest.routes) {
391
807
  const mod = modules[entry.file] as LoadedPageModule
392
808
  const layouts = entry.layouts.map(l => modules[l] as LoadedLayoutModule)
393
- const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
394
-
809
+ const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
810
+ const routePluginMiddlewares = middlewaresFor(entry.path)
811
+ const fastPluginMiddlewares = middlewaresFor(entry.path, true)
812
+ const dynamic = entry.path.includes(':') || entry.path.includes('*')
395
813
  const hasIslands = entry.islandChunks.length > 0
396
- const routeStyles = entry.styles ?? manifest.styles
397
- const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
398
- ? [...(manifest.headTags ?? []), ...entry.headTags]
399
- : manifest.headTags
400
- const shell = renderDocument({
401
- body: '\0',
402
- headTags: routeHeadTags,
814
+ const doc: DocumentOptions = {
815
+ body: '',
816
+ headTags: mergedHeadTags(manifest, entry),
403
817
  lang,
404
818
  runtimeScript: manifest.runtimeScript,
405
819
  alwaysLoadRuntime,
406
- preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks,
407
- styles: routeStyles,
408
- hasIslands,
409
- })
410
- const splitAt = shell.indexOf('\0')
411
- const docPrefix = shell.slice(0, splitAt)
412
- const docSuffix = shell.slice(splitAt + 1)
820
+ styles: entry.styles ?? manifest.styles,
821
+ }
413
822
 
414
- // Ultra-fast zero-overhead path when route is static, has no middleware, no <Head>/<Suspense>, and no intercepting plugin hooks
415
- const canFastPath = !hasGlobalMiddleware
823
+ // Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, and no intercepting plugin hook
824
+ const canFastPath = fastPluginMiddlewares.length === 0
416
825
  && !hasPluginRewrites
826
+ && !hasHeadHooks
417
827
  && !hasHtmlTransformers
418
828
  && pluginRouter.match(entry.path) === undefined
419
- && !entry.path.includes(':')
420
- && !entry.path.includes('*')
421
- && middlewares.length === 0
829
+ && !dynamic
830
+ && dirMiddlewares.length === 0
422
831
  && !entry.usesRenderContext
423
832
  && typeof mod.default === 'function'
424
833
  && mod.GET === undefined
425
834
 
426
- let fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
427
835
  if (canFastPath) {
836
+ const shell = renderDocument({ ...doc, body: '\0', preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks, hasIslands })
837
+ const splitAt = shell.indexOf('\0')
838
+ const docPrefix = shell.slice(0, splitAt)
839
+ const docSuffix = shell.slice(splitAt + 1)
428
840
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
429
- const fastHeaders = selectDynamicHtmlHeaders(hasIslands, false)
841
+ const fastHeaders = htmlHeaders(hasIslands, false, true)
430
842
 
431
- fastHandler = (request: Request, remoteIp?: string): Response | Promise<Response> => {
432
- const handleErr = (error: unknown): Promise<Response> => {
433
- notifyError(error, request, 'route')
434
- return renderError(error, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, new URL(request.url), request)
435
- }
843
+ const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
844
+ notifyError(error, request, 'route')
845
+ return renderError(error, cookieStore, url, request, ctx)
846
+ }
847
+ const respondHtml = (body: string, request: Request, cookieStore?: CookieStore): Response => {
848
+ const res = compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache, !entry.hasLoad)
849
+ return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
850
+ }
851
+ const layoutProps = (inner: string, url: URL, locals: KayLocals) => ({ children: raw(inner), url, params: {}, locals })
852
+
853
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
436
854
  try {
437
- const reqUrl = new URL(request.url)
438
- const respondHtml = (body: string): Response =>
439
- withHsts(compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache), request)
440
-
441
- const wrapLayouts = (inner: string): Response | Promise<Response> => {
442
- if (layouts.length === 0)
443
- return respondHtml(inner)
444
- if (singleLayout !== undefined) {
445
- const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
446
- if (w instanceof Promise)
447
- return w.then(x => respondHtml(ssrChild(x as Html)), handleErr)
448
- return respondHtml(ssrChild(w as Html))
449
- }
450
- return (async () => {
451
- let cur = inner
452
- for (let i = layouts.length - 1; i >= 0; i--)
453
- cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
454
- return respondHtml(cur)
455
- })().catch(handleErr)
456
- }
855
+ return respondHtml(ssrChild(await wrapped as Html), request, cookieStore)
856
+ }
857
+ catch (error) {
858
+ return fail(error, request, url, cookieStore, ctx)
859
+ }
860
+ }
457
861
 
458
- const renderPage = (data: unknown): Response | Promise<Response> => {
459
- const pageProps: Record<string, unknown> = {
460
- params: {},
461
- locals: {},
462
- url: reqUrl,
463
- ...(data !== undefined ? { data } : {}),
464
- }
465
- if (entry.isIsland && entry.islandChunk !== undefined) {
466
- const inner = ssrIsland(
467
- entry.path,
468
- entry.islandChunk,
469
- () => ssrChild(mod.default!(pageProps) as Html),
470
- data !== undefined ? { data } : {},
471
- entry.islandHydrate as HydrateStrategy | undefined,
472
- )
473
- return wrapLayouts(inner)
474
- }
475
- const rendered = mod.default!(pageProps)
476
- if (rendered instanceof Promise)
477
- return rendered.then(r => wrapLayouts(ssrChild(r as Html)), handleErr)
478
- return wrapLayouts(ssrChild(rendered as Html))
862
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
863
+ if (layouts.length === 0)
864
+ return respondHtml(inner, request, cookieStore)
865
+ if (singleLayout !== undefined) {
866
+ const wrapped = singleLayout.default(layoutProps(inner, url, locals))
867
+ if (wrapped instanceof Promise)
868
+ return finishSingleLayout(wrapped, request, url, cookieStore, ctx)
869
+ return respondHtml(ssrChild(wrapped as Html), request, cookieStore)
870
+ }
871
+ return (async () => {
872
+ try {
873
+ let cur = inner
874
+ for (let i = layouts.length - 1; i >= 0; i--)
875
+ cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
876
+ return respondHtml(cur, request, cookieStore)
877
+ }
878
+ catch (error) {
879
+ return fail(error, request, url, cookieStore, ctx)
479
880
  }
881
+ })()
882
+ }
883
+
884
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
885
+ try {
886
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, cookieStore, ctx)
887
+ }
888
+ catch (error) {
889
+ return fail(error, request, url, cookieStore, ctx)
890
+ }
891
+ }
892
+
893
+ const renderPage = (data: unknown, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
894
+ const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
895
+ if (entry.isIsland && entry.islandChunk !== undefined) {
896
+ return wrapLayouts(ssrIsland(
897
+ entry.islandChunk,
898
+ () => ssrChild(mod.default!(pageProps) as Html),
899
+ pickPageIslandProps(data, entry, mod),
900
+ entry.islandHydrate as HydrateStrategy | undefined,
901
+ true,
902
+ ), request, url, locals, cookieStore, ctx)
903
+ }
904
+ const rendered = mod.default!(pageProps)
905
+ if (rendered instanceof Promise)
906
+ return finishAsyncPage(rendered, request, url, locals, cookieStore, ctx)
907
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, cookieStore, ctx)
908
+ }
480
909
 
481
- if (entry.hasLoad && typeof mod.load === 'function') {
482
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp })
483
- const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
484
- if (!cookieStore.hasChanges)
485
- return res instanceof Promise ? res.then(r => withHsts(r, request), handleErr) : withHsts(res, request)
486
- if (res instanceof Promise)
487
- return res.then(r => withHsts(finalizeResponse(r, cookieStore, securityEntries), request), handleErr)
488
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
910
+ fastStaticPages.set(entry.path, (request, remoteIp, url = new URL(request.url)) => {
911
+ try {
912
+ if (!entry.hasLoad || typeof mod.load !== 'function')
913
+ return renderPage(undefined, request, url, {})
914
+
915
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
916
+ return (async () => {
917
+ try {
918
+ const loaded = await mod.load!(ctx)
919
+ if (isNotFound(loaded))
920
+ return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
921
+ if (loaded instanceof Response)
922
+ return finish(loaded, request, cookieStore)
923
+ return await renderPage(loaded, request, url, ctx.locals, cookieStore, ctx)
489
924
  }
490
- const loaded = mod.load(ctx)
491
- if (loaded instanceof Promise) {
492
- return loaded.then(
493
- data => finish(data instanceof Response ? data : renderPage(data)),
494
- handleErr,
495
- )
925
+ catch (error) {
926
+ if (isNotFound(error))
927
+ return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
928
+ return fail(error, request, url, cookieStore, ctx)
496
929
  }
497
- if (loaded instanceof Response)
498
- return finish(loaded)
499
- return finish(renderPage(loaded))
500
- }
501
- return renderPage(undefined)
930
+ })()
502
931
  }
503
932
  catch (error) {
504
- return handleErr(error)
933
+ return fail(error, request, url)
505
934
  }
506
- }
507
- fastStaticPages.set(entry.path, fastHandler)
935
+ })
508
936
  }
509
937
 
510
- router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
938
+ router.add(entry.path, { entry, mod, layouts, middlewares: [...routePluginMiddlewares, ...dirMiddlewares], dynamic, doc })
511
939
  }
512
940
 
513
941
  async function renderCompiledRoute(
@@ -515,33 +943,61 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
515
943
  ctx: RequestContext,
516
944
  disableTimeout?: () => void,
517
945
  ): Promise<Response> {
518
- const { entry, mod, layouts } = route
946
+ const { entry, mod, layouts, doc } = route
519
947
 
520
948
  // Serve prerendered HTML after middlewares have passed (when route had middlewares)
521
- if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
949
+ if (isRead(ctx.request)) {
522
950
  const rawPath = ctx.url.pathname
523
951
  const normPath = rawPath.length > 1 && rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath
524
952
  const pre = prerenderedMap.get(rawPath) ?? prerenderedMap.get(normPath)
525
953
  if (pre !== undefined)
526
- return servePrerendered(ctx.request, rawPath, pre)
954
+ return serveFile(ctx.request, pre)
527
955
  // Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
528
- if (entry.prerender === true && entry.prerendered !== undefined && (entry.path.includes(':') || entry.path.includes('*')))
529
- return buildNotFoundResponse(ctx.url)
956
+ if (entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
957
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
530
958
  }
531
959
 
532
- // API route (.ts exporting GET/POST/etc.)
533
- const methodHandler = mod[ctx.request.method]
534
- if (typeof methodHandler === 'function') {
535
- const res = await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
536
- if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
537
- disableTimeout?.()
538
- return maybeCompressResponse(res, ctx.request, compressCache)
960
+ // API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
961
+ const method = ctx.request.method.toUpperCase()
962
+ const methodHandler = mod[method]
963
+ if (typeof methodHandler === 'function')
964
+ return await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
965
+ if (method === 'HEAD' && typeof mod.GET === 'function')
966
+ return stripHeadBody(await mod.GET(ctx))
967
+
968
+ // Page routes only handle GET/HEAD; unsafe methods (POST/PUT/PATCH/DELETE) without a method export get 405.
969
+ if (typeof mod.default !== 'function' || !isRead(ctx.request)) {
970
+ const allow = allowedMethodsHeader(mod)
971
+ return new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 })
539
972
  }
540
973
 
541
- if (typeof mod.default !== 'function')
542
- return new Response('Method Not Allowed', { status: 405 })
974
+ // Hydrate & clear one-shot progressive form validation flash cookie only on page GETs (never API/plugin GETs)
975
+ if (ctx.request.method === 'GET' && hasActionErrorCookie(ctx.request)) {
976
+ const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
977
+ if (rawFlash !== undefined) {
978
+ try {
979
+ const parsed: unknown = JSON.parse(rawFlash)
980
+ if (isPlainObject(parsed))
981
+ ctx.locals.actionError = parsed as unknown as ActionErrorFlash
982
+ }
983
+ catch {}
984
+ ctx.cookies.delete(ACTION_ERROR_COOKIE)
985
+ }
986
+ }
543
987
 
544
- const data = entry.hasLoad && typeof mod.load === 'function' ? await mod.load(ctx) : undefined
988
+ let data: unknown
989
+ if (entry.hasLoad && typeof mod.load === 'function') {
990
+ try {
991
+ data = await mod.load(ctx)
992
+ }
993
+ catch (error) {
994
+ if (isNotFound(error))
995
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
996
+ throw error
997
+ }
998
+ }
999
+ if (isNotFound(data))
1000
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
545
1001
  if (data instanceof Response)
546
1002
  return data
547
1003
  const pageProps: Record<string, unknown> = {
@@ -556,11 +1012,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
556
1012
  let inner: string
557
1013
  if (entry.isIsland && entry.islandChunk !== undefined) {
558
1014
  inner = ssrIsland(
559
- entry.path,
560
1015
  entry.islandChunk,
561
1016
  () => ssrChild(mod.default!(pageProps) as Html),
562
- data !== undefined ? { data } : {},
1017
+ pickPageIslandProps(data, entry, mod),
563
1018
  entry.islandHydrate as HydrateStrategy | undefined,
1019
+ true,
564
1020
  )
565
1021
  }
566
1022
  else {
@@ -572,384 +1028,279 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
572
1028
  }
573
1029
 
574
1030
  const body = await runWithRenderContext(rctx, renderBody)
575
- const collectedHead = renderCollectedHead(rctx)
576
- const renderedIslands = extractRenderedIslands(body)
577
- const hasIslands = renderedIslands.hasIslands || rctx.pending.length > 0 && entry.islandChunks.length > 0
578
- const preloadChunks = rctx.pending.length > 0 ? entry.islandChunks : renderedIslands.eagerChunks
579
-
580
- const routeStyles = entry.styles ?? manifest.styles
581
- const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
582
- ? [...(manifest.headTags ?? []), ...entry.headTags]
583
- : manifest.headTags
584
-
585
- // Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
586
- if (rctx.pending.length > 0) {
1031
+ const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
1032
+ const renderedIslands = resolveRenderedIslands(rctx, body)
1033
+ const isStreamed = rctx.pending.length > 0
1034
+ const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
1035
+ const preloadChunks = isStreamed ? entry.islandChunks : renderedIslands.eagerChunks
1036
+
1037
+ // Streaming SSR when <Suspense> boundaries are pending (never buffered for compression)
1038
+ if (isStreamed) {
1039
+ if (ctx.request.method === 'HEAD')
1040
+ return new Response(null, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
587
1041
  disableTimeout?.()
588
- const shell = renderDocument({
589
- body: '\0',
590
- head: collectedHead,
591
- headTags: routeHeadTags,
592
- lang,
593
- runtimeScript: manifest.runtimeScript,
594
- alwaysLoadRuntime,
595
- preloadChunks,
596
- styles: routeStyles,
597
- hasIslands,
598
- hasSuspense: true,
599
- })
600
- const splitAt = shell.indexOf('\0')
601
- const headHtml = shell.slice(0, splitAt)
602
- const tailHtml = shell.slice(splitAt + 1)
1042
+ let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
1043
+ // Transforms see the document with its initial body; boundaries resolved later stream as they render.
1044
+ for (const transform of htmlTransformers)
1045
+ shell = await transform(shell, ctx)
1046
+ let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
1047
+ let tailOffset = STREAM_TAIL_MARK.length
1048
+ if (splitAt === -1) {
1049
+ splitAt = shell.lastIndexOf('</body>')
1050
+ tailOffset = 0
1051
+ }
1052
+ const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
1053
+ const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
1054
+
1055
+ const abortCtrl = new AbortController()
1056
+ let closed = false
1057
+ const deadline = Date.now() + streamTimeout
1058
+
1059
+ const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
1060
+ if (closed || abortCtrl.signal.aborted)
1061
+ return
1062
+ try {
1063
+ controller.enqueue(data)
1064
+ }
1065
+ catch {
1066
+ closed = true
1067
+ abortCtrl.abort()
1068
+ }
1069
+ }
603
1070
 
604
1071
  const stream = new ReadableStream<Uint8Array>({
605
1072
  async start(controller) {
606
- controller.enqueue(textEncoder.encode(headHtml + body))
607
- await Promise.all(
608
- rctx.pending.map(async (chunk) => {
609
- const resolved = await chunk.promise
610
- controller.enqueue(textEncoder.encode(streamChunkScript(chunk.id, resolved)))
611
- }),
612
- )
613
- controller.enqueue(textEncoder.encode(tailHtml))
614
- controller.close()
1073
+ safeEnqueue(controller, textEncoder.encode(openingHtml))
1074
+ // A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
1075
+ let flushed = 0
1076
+ const flushPending = async (): Promise<void> => {
1077
+ if (closed || abortCtrl.signal.aborted)
1078
+ return
1079
+ const chunks = rctx.pending.slice(flushed)
1080
+ flushed = rctx.pending.length
1081
+ await Promise.all(chunks.map(async (chunk) => {
1082
+ const settled = await settleWithin(chunk, deadline, abortCtrl.signal)
1083
+ if (settled === undefined || closed || abortCtrl.signal.aborted)
1084
+ return
1085
+ if ('error' in settled)
1086
+ notifyError(settled.error, ctx.request, 'route')
1087
+ safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
1088
+ await flushPending()
1089
+ }))
1090
+ }
1091
+ await flushPending()
1092
+ if (!closed && !abortCtrl.signal.aborted) {
1093
+ safeEnqueue(controller, textEncoder.encode(tailHtml))
1094
+ closed = true
1095
+ try {
1096
+ controller.close()
1097
+ }
1098
+ catch {}
1099
+ }
1100
+ },
1101
+ cancel() {
1102
+ closed = true
1103
+ abortCtrl.abort()
615
1104
  },
616
1105
  })
617
1106
 
618
- return new Response(stream, { status: 200, headers: { ...selectDynamicHtmlHeaders(hasIslands, true) } })
1107
+ return new Response(stream, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
619
1108
  }
620
1109
 
621
- let html = renderDocument({
622
- body,
623
- head: collectedHead,
624
- headTags: routeHeadTags,
625
- lang,
626
- runtimeScript: manifest.runtimeScript,
627
- alwaysLoadRuntime,
628
- preloadChunks,
629
- styles: routeStyles,
630
- hasIslands,
631
- })
632
-
633
- for (let i = 0; i < htmlTransformers.length; i++)
634
- html = await htmlTransformers[i]!(html, ctx)
635
-
636
- return compressedHtmlResponse(html, 200, selectDynamicHtmlHeaders(hasIslands, false), ctx.request, compressCache)
637
- }
638
-
639
- const rootLayoutFile = manifest.routes.find(r => r.layouts.length > 0)?.layouts[0]
640
- const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
641
- const fallbackStyles = manifest.globalStyles ?? manifest.styles
642
-
643
- async function buildErrorResponse(error: unknown, url?: URL): Promise<Response> {
644
- if (errorMod !== undefined) {
645
- try {
646
- const rctx = createRenderContext()
647
- const body = await runWithRenderContext(rctx, async () => {
648
- let inner = ssrChild(await errorMod.default({ error }) as Html)
649
- if (rootLayoutMod !== undefined)
650
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/500'), params: {}, locals: {} }) as Html)
651
- return inner
652
- })
653
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
654
- return new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private' } })
655
- }
656
- catch {}
657
- }
658
- return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
659
- }
660
-
661
- async function renderError(error: unknown, cookieStore: CookieStore, url?: URL, request?: Request): Promise<Response> {
662
- const base = finalizeResponse(await buildErrorResponse(error, url), cookieStore, securityEntries)
663
- return request !== undefined ? withHsts(base, request) : base
664
- }
665
-
666
- async function buildNotFoundResponse(url?: URL): Promise<Response> {
667
- const notFoundFn = notFoundMod?.default
668
- if (notFoundFn !== undefined) {
669
- try {
670
- const rctx = createRenderContext()
671
- const body = await runWithRenderContext(rctx, async () => {
672
- let inner = ssrChild(await notFoundFn({}) as Html)
673
- if (rootLayoutMod !== undefined)
674
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/404'), params: {}, locals: {} }) as Html)
675
- return inner
676
- })
677
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
678
- return new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private' } })
679
- }
680
- catch {}
681
- }
682
- return new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })
683
- }
1110
+ let html = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
1111
+ for (const transform of htmlTransformers)
1112
+ html = await transform(html, ctx)
684
1113
 
685
- async function renderNotFound(cookieStore: CookieStore, url?: URL, request?: Request): Promise<Response> {
686
- const base = finalizeResponse(await buildNotFoundResponse(url), cookieStore, securityEntries)
687
- return request !== undefined ? withHsts(base, request) : base
1114
+ return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true), ctx.request, compressCache)
688
1115
  }
689
1116
 
690
- function requestWantsJson(request: Request): boolean {
691
- return (request.headers.get('accept') ?? '').includes('application/json')
692
- || (request.headers.get('content-type') ?? '').includes('application/json')
693
- }
694
-
695
- async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
1117
+ // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
1118
+ async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
696
1119
  try {
697
- const pathname = new URL(request.url).pathname
1120
+ const url = new URL(request.url)
1121
+ const pathname = url.pathname
1122
+ const read = isRead(request)
698
1123
 
699
- // 1. Static client assets
700
- if (request.method === 'GET' || request.method === 'HEAD') {
1124
+ // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
1125
+ if (read) {
701
1126
  const asset = assetMap.get(pathname)
702
1127
  if (asset !== undefined)
703
- return serveAsset(request, pathname, asset)
1128
+ return serveAsset(request, asset)
1129
+ const pub = publicMap.get(pathname)
1130
+ if (pub !== undefined) {
1131
+ const matchedPlugin = pluginRouter.match(pathname)
1132
+ const reqMethod = request.method.toUpperCase()
1133
+ const shadowedByPlugin = matchedPlugin !== undefined
1134
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
1135
+ if (!shadowedByPlugin)
1136
+ return servePublic(request, pub)
1137
+ }
704
1138
  }
705
1139
 
706
- // 1b. Static public/ files (no-cache in dev so edits/plugins never get stuck in browser cache)
707
- if (request.method === 'GET' || request.method === 'HEAD') {
708
- const pub = publicMap.get(pathname)
709
- if (pub !== undefined)
710
- return servePublic(request, pathname, pub)
1140
+ // Actions only accept POST; other methods get 405 before any middleware runs.
1141
+ const registeredAction = actionHandlers.get(pathname)
1142
+ if (registeredAction !== undefined && request.method !== 'POST')
1143
+ return finish(new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } }), request)
1144
+
1145
+ // Actions are origin-checked before their body is read and before any middleware runs.
1146
+ const actionHandler = request.method === 'POST' ? registeredAction : undefined
1147
+ if (actionHandler !== undefined) {
1148
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
1149
+ if (!originCheck.ok)
1150
+ return refuseCrossSite(request, originCheck.reason)
711
1151
  }
712
1152
 
713
1153
  // Enforce request body size cap before actions, plugin routes, and API routes
714
- const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
1154
+ const bounded = bodyLimited ? { ok: true as const, request } : await enforceRequestBodyLimit(request, maxRequestBodySize)
715
1155
  if (!bounded.ok) {
716
- const res413 = requestWantsJson(request)
1156
+ const res413 = wantsJson(request)
717
1157
  ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
718
1158
  : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } })
719
- return withHsts(finalizeResponse(res413, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, securityEntries), request)
1159
+ return finish(res413, request)
720
1160
  }
721
1161
  const req = bounded.request
722
1162
 
723
- // 2. Server actions (POST /_kay/action/<id>): global plugin middlewares, then the _middleware.ts chain of the action's folder
724
- if (req.method === 'POST') {
725
- const handler = actionHandlers.get(pathname)
726
- if (handler !== undefined) {
727
- const { act, middlewares } = handler
728
- const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
729
- const runAction = async (): Promise<Response> => {
730
- const actionCtx: ActionContext = {
731
- request: ctx.request,
732
- url: ctx.url,
733
- params: ctx.params,
734
- cookies: ctx.cookies,
735
- locals: ctx.locals,
736
- ip: ctx.ip,
737
- redirect: ctx.redirect,
738
- deny: ctx.deny,
739
- }
740
- return executeAction(act, req, actionCtx, trustedOrigins, trustProxy, maxRequestBodySize)
741
- }
742
- let index = -1
743
- const dispatch = async (i: number): Promise<Response> => {
744
- if (i <= index)
745
- throw new Error('kay: middleware called next() multiple times')
746
- index = i
747
- if (i < middlewares.length)
748
- return middlewares[i]!(ctx, () => dispatch(i + 1))
749
- return runAction()
750
- }
751
- try {
752
- const res = await dispatch(0)
753
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
754
- }
755
- catch (error) {
756
- notifyError(error, req, 'action')
757
- if (requestWantsJson(req)) {
758
- return withHsts(
759
- finalizeResponse(
760
- Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }),
761
- cookieStore,
762
- securityEntries,
763
- ),
764
- req,
765
- )
766
- }
767
- return renderError(error, cookieStore, ctx.url, req)
768
- }
1163
+ // 2. Server actions (POST /_kay/action/<id>): plugin middlewares, then the _middleware.ts chain of the action's folder
1164
+ if (actionHandler !== undefined) {
1165
+ const { act, middlewares } = actionHandler
1166
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
1167
+ try {
1168
+ return finish(await runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy)), req, cookieStore)
1169
+ }
1170
+ catch (error) {
1171
+ notifyError(error, req, 'action')
1172
+ return renderError(error, cookieStore, ctx.url, req, ctx)
769
1173
  }
770
1174
  }
771
1175
 
772
- const hasActionErrorFlash = (req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
773
-
774
- // 3. Prerendered static HTML (safe even when plugins add routes or build-time transformHtml!)
775
- if (!hasActionErrorFlash && (req.method === 'GET' || req.method === 'HEAD')) {
1176
+ // 3. Prerendered static HTML, then 4. the zero-overhead static route path
1177
+ const plainRead = isPlainRead(req)
1178
+ if (plainRead) {
776
1179
  const pre = fastPrerenderedMap.get(pathname)
777
1180
  if (pre !== undefined)
778
- return servePrerendered(req, pathname, pre)
779
- }
780
-
781
- // 4. Ultra-fast static route path
782
- if (!hasActionErrorFlash && (req.method === 'GET' || req.method === 'HEAD')) {
1181
+ return serveFile(req, pre)
783
1182
  const fast = fastStaticPages.get(pathname)
784
1183
  if (fast !== undefined)
785
- return fast(req, remoteIp)
1184
+ return fast(req, remoteIp, url)
786
1185
  }
787
1186
 
788
1187
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
789
- const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
790
-
791
- // Hydrate & clear one-shot progressive form validation flash cookie
792
- if (hasActionErrorFlash && req.method === 'GET') {
793
- const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
794
- if (rawFlash !== undefined) {
795
- try {
796
- ctx.locals.actionError = JSON.parse(rawFlash) as ActionErrorFlash
797
- }
798
- catch {}
799
- ctx.cookies.delete(ACTION_ERROR_COOKIE)
800
- }
801
- }
1188
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
802
1189
 
803
1190
  // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
804
1191
  let effectivePath = pathname
805
- for (let i = 0; i < pluginRewrites.length; i++) {
806
- const nextPath = pluginRewrites[i]!(effectivePath, ctx)
1192
+ for (const rewrite of pluginRewrites) {
1193
+ const nextPath = rewrite(effectivePath, ctx)
807
1194
  if (nextPath !== undefined)
808
1195
  effectivePath = nextPath
809
1196
  }
810
1197
 
811
- // Check custom plugin routes first (e.g. GET /sitemap.xml, POST /auth/callback, GET /api/board)
812
- // Run global plugin middlewares so ctx.locals (e.g. auth user/session) is available in plugin routes too.
1198
+ // Custom plugin routes run behind plugin middlewares so ctx.locals (e.g. auth user/session) is available.
1199
+ const method = req.method.toUpperCase()
813
1200
  const pluginMatch = pluginRouter.match(effectivePath)
814
- if (pluginMatch !== undefined) {
815
- const routeDef = pluginMatch.data.get(req.method.toUpperCase()) ?? pluginMatch.data.get('ALL')
816
- if (routeDef !== undefined) {
817
- if (routeDef.csrf) {
818
- const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
819
- if (!originCheck.ok) {
820
- return withHsts(
821
- finalizeResponse(
822
- Response.json({ ok: false, status: 403, error: originCheck.reason }, { status: 403 }),
823
- cookieStore,
824
- securityEntries,
825
- ),
826
- req,
827
- )
828
- }
829
- }
830
- ctx.params = pluginMatch.params
831
- let res: Response
832
- try {
833
- if (globalMiddlewares.length === 0) {
834
- res = await routeDef.handler(ctx)
835
- }
836
- else {
837
- let index = -1
838
- const dispatch = async (i: number): Promise<Response> => {
839
- if (i <= index)
840
- throw new Error('kay: middleware called next() multiple times')
841
- index = i
842
- if (i < globalMiddlewares.length)
843
- return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
844
- return routeDef.handler(ctx)
845
- }
846
- res = await dispatch(0)
847
- }
848
- if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
849
- disableTimeout?.()
850
- return withHsts(finalizeResponse(await maybeCompressResponse(res, req, compressCache), cookieStore, securityEntries), req)
851
- }
852
- catch (error) {
853
- notifyError(error, req, 'plugin')
854
- return renderError(error, cookieStore, ctx.url, req)
855
- }
1201
+ const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
1202
+ const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
1203
+ const routeDef = directPluginDef ?? headFallbackPluginDef
1204
+ if (pluginMatch !== undefined && routeDef !== undefined) {
1205
+ if (routeDef.csrf) {
1206
+ const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy, url)
1207
+ if (!originCheck.ok)
1208
+ return refuseCrossSite(req, originCheck.reason, cookieStore)
1209
+ }
1210
+ ctx.params = pluginMatch.params
1211
+ try {
1212
+ let res = await runChain(ctx, allPluginMiddlewares, () => routeDef.handler(ctx))
1213
+ if (headFallbackPluginDef !== undefined)
1214
+ res = stripHeadBody(res)
1215
+ else if (isEventStream(res))
1216
+ disableTimeout?.()
1217
+ return finish(await maybeCompressResponse(res, req, compressCache), req, cookieStore)
1218
+ }
1219
+ catch (error) {
1220
+ notifyError(error, req, 'plugin')
1221
+ return renderError(error, cookieStore, ctx.url, req, ctx)
856
1222
  }
857
1223
  }
858
1224
 
859
1225
  const matched = router.match(effectivePath)
860
- if (matched === undefined)
861
- return renderNotFound(cookieStore, ctx.url, req)
1226
+ if (matched === undefined) {
1227
+ if (pluginMatch !== undefined) {
1228
+ const allow = allowedPluginMethodsHeader(pluginMatch.data)
1229
+ return finish(new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 }), req)
1230
+ }
1231
+ return renderNotFound(cookieStore, ctx.url, req, ctx)
1232
+ }
862
1233
 
863
1234
  ctx.params = matched.params
864
1235
  const route = matched.data
865
1236
 
866
- // CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
867
- if (typeof route.mod[req.method] === 'function' && route.mod.csrf !== false) {
868
- const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
869
- if (!originCheck.ok) {
870
- return withHsts(
871
- finalizeResponse(
872
- Response.json({ ok: false, status: 403, error: originCheck.reason }, { status: 403 }),
873
- cookieStore,
874
- securityEntries,
875
- ),
876
- req,
877
- )
878
- }
1237
+ // Reject unsupported HTTP methods with 405 + Allow BEFORE any middleware or CSRF check runs.
1238
+ const supportsMethod = typeof route.mod[method] === 'function'
1239
+ || (method === 'HEAD' && typeof route.mod.GET === 'function')
1240
+ || (typeof route.mod.default === 'function' && (method === 'GET' || method === 'HEAD'))
1241
+ if (!supportsMethod) {
1242
+ const allow = allowedMethodsHeader(route.mod)
1243
+ return finish(new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 }), req)
879
1244
  }
880
1245
 
881
- const allMiddlewares = globalMiddlewares.length > 0
882
- ? [...globalMiddlewares, ...route.middlewares]
883
- : route.middlewares
1246
+ // CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
1247
+ if (typeof route.mod[method] === 'function' && route.mod.csrf !== false) {
1248
+ const originCheck = verifyOrigin(req, trustedOrigins, trustProxy, url)
1249
+ if (!originCheck.ok)
1250
+ return refuseCrossSite(req, originCheck.reason, cookieStore)
1251
+ }
884
1252
 
885
1253
  try {
886
- let index = -1
887
- const dispatch = async (i: number): Promise<Response> => {
888
- if (i <= index)
889
- throw new Error('kay: middleware called next() multiple times')
890
- index = i
891
- if (i < allMiddlewares.length)
892
- return allMiddlewares[i]!(ctx, () => dispatch(i + 1))
893
- return renderCompiledRoute(route, ctx, disableTimeout)
894
- }
895
- const res = await dispatch(0)
896
- if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
1254
+ const res = await runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout))
1255
+ if (isEventStream(res))
897
1256
  disableTimeout?.()
898
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
1257
+ // Compress uncompressed API/middleware responses after the middleware chain unwinds.
1258
+ const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, req, compressCache)
1259
+ return finish(finalRes, req, cookieStore)
899
1260
  }
900
1261
  catch (error) {
901
1262
  notifyError(error, req, 'route')
902
- return renderError(error, cookieStore, ctx.url, req)
1263
+ return renderError(error, cookieStore, ctx.url, req, ctx)
903
1264
  }
904
1265
  }
905
1266
  catch (error) {
906
1267
  notifyError(error, request, 'route')
907
- return withHsts(
908
- new Response('Internal Server Error', {
909
- status: 500,
910
- headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
911
- }),
912
- request,
913
- )
1268
+ return withHsts(serverError(), request)
914
1269
  }
915
1270
  }
916
1271
 
917
1272
  function handle(request: Request, remoteIp?: string): Promise<Response> {
918
- return handleInternal(request, remoteIp)
1273
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
919
1274
  }
920
1275
 
921
1276
  function serve(port = 3000, hostname = '127.0.0.1') {
922
1277
  let srvRef: ReturnType<typeof Bun.serve> | undefined
923
- const fetchReq = (req: Request) => handleInternal(
1278
+ const ipOf = (req: Request) => srvRef?.requestIP(req)?.address
1279
+ const fetchReq = (req: Request) => runWithAppContext(serverAppCtx, () => handleInternal(
924
1280
  req,
925
- srvRef?.requestIP(req)?.address,
1281
+ ipOf(req),
926
1282
  srvRef ? () => srvRef!.timeout(req, 0) : undefined,
927
- )
1283
+ true,
1284
+ ))
928
1285
 
929
1286
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
930
1287
 
931
1288
  for (const [path, asset] of assetMap)
932
- routes[path] = req => serveAsset(req, path, asset)
1289
+ routes[path] = req => isRead(req) ? serveAsset(req, asset) : fetchReq(req)
933
1290
 
934
1291
  for (const [path, pub] of publicMap) {
935
- if (!(path in routes))
936
- routes[path] = req => servePublic(req, path, pub)
1292
+ if (!(path in routes) && pluginRouter.match(path) === undefined)
1293
+ routes[path] = req => isRead(req) ? servePublic(req, pub) : fetchReq(req)
937
1294
  }
938
1295
 
939
1296
  for (const [path, pre] of fastPrerenderedMap) {
940
- if (!(path in routes)) {
941
- routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
942
- ? servePrerendered(req, path, pre)
943
- : fetchReq(req)
944
- }
1297
+ if (!(path in routes))
1298
+ routes[path] = req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req)
945
1299
  }
946
1300
 
947
1301
  for (const [path, handler] of fastStaticPages) {
948
- if (!(path in routes)) {
949
- routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
950
- ? handler(req, srvRef?.requestIP(req)?.address)
951
- : fetchReq(req)
952
- }
1302
+ if (!(path in routes))
1303
+ routes[path] = req => isPlainRead(req) ? runWithAppContext(serverAppCtx, () => handler(req, ipOf(req))) : fetchReq(req)
953
1304
  }
954
1305
 
955
1306
  srvRef = Bun.serve({
@@ -962,229 +1313,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
962
1313
  fetch: fetchReq,
963
1314
  error(err) {
964
1315
  notifyError(err, new Request('http://localhost/'), 'route')
965
- return new Response('Internal Server Error', {
966
- status: 500,
967
- headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
968
- })
1316
+ return serverError()
969
1317
  },
970
1318
  })
971
1319
  return srvRef
972
1320
  }
973
1321
 
974
- return { handle, serve }
975
- }
976
-
977
- function createStaticDirServer(
978
- outDir: string,
979
- assetPrefix: string,
980
- securityEntries: readonly [string, string][],
981
- compressEnabled: boolean,
982
- hstsValue: string | undefined,
983
- trustProxy: boolean,
984
- ): KayApp {
985
- const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
986
- const absRoot = resolve(outDir)
987
- const compressCache = compressEnabled ? new CompressionCache() : undefined
988
- const securityRecord: Record<string, string> = {}
989
- for (let i = 0; i < securityEntries.length; i++)
990
- securityRecord[securityEntries[i]![0]] = securityEntries[i]![1]
991
- const withHsts = (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy)
992
-
993
- function resolveStaticFile(pathname: string): string | undefined {
994
- let decoded: string
995
- try {
996
- decoded = decodeURIComponent(pathname)
997
- }
998
- catch {
999
- return undefined
1000
- }
1001
- const rel = decoded.replace(/^\/+/, '').replace(/\/+$/, '')
1002
- const candidates = rel === ''
1003
- ? ['index.html']
1004
- : [rel, `${rel}.html`, `${rel}/index.html`]
1005
- for (const c of candidates) {
1006
- const abs = resolve(absRoot, c)
1007
- if (abs !== absRoot && !abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
1008
- continue
1009
- if (existsSync(abs) && statSync(abs).isFile())
1010
- return abs
1011
- }
1012
- return undefined
1013
- }
1014
-
1015
- const initHeaders = (): Headers => {
1016
- const headers = new Headers()
1017
- for (let i = 0; i < securityEntries.length; i++)
1018
- headers.set(securityEntries[i]![0], securityEntries[i]![1])
1019
- return headers
1020
- }
1021
-
1022
- const handle = async (req: Request): Promise<Response> => {
1023
- if (req.method !== 'GET' && req.method !== 'HEAD')
1024
- return withHsts(new Response('Method Not Allowed', { status: 405, headers: initHeaders() }), req)
1025
-
1026
- const url = new URL(req.url)
1027
- const filePath = resolveStaticFile(url.pathname)
1028
- if (filePath === undefined) {
1029
- const notFoundPath = join(absRoot, '404.html')
1030
- if (existsSync(notFoundPath) && statSync(notFoundPath).isFile()) {
1031
- const headers = initHeaders()
1032
- headers.set('content-type', 'text/html; charset=utf-8')
1033
- return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
1034
- }
1035
- return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
1036
- }
1037
-
1038
- const st = statSync(filePath)
1039
- const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
1040
- const isImmutable = url.pathname.startsWith(cleanPrefix)
1041
- const cacheControl = isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate'
1042
- const headers = initHeaders()
1043
- headers.set('content-type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream')
1044
- headers.set('cache-control', cacheControl)
1045
- headers.set('etag', etag)
1046
-
1047
- if (req.headers.get('if-none-match') === etag)
1048
- return withHsts(new Response(null, { status: 304, headers }), req)
1049
-
1050
- if (compressEnabled && req.method !== 'HEAD') {
1051
- const hasBr = existsSync(`${filePath}.br`)
1052
- const hasGz = existsSync(`${filePath}.gz`)
1053
- if (hasBr || hasGz) {
1054
- const preEnc = pickPrecompressedEncoding(req.headers.get('accept-encoding'), { br: hasBr, gz: hasGz })
1055
- if (preEnc !== undefined) {
1056
- headers.set('content-encoding', preEnc)
1057
- headers.set('vary', 'Accept-Encoding')
1058
- headers.set('etag', toWeakEtag(etag))
1059
- return withHsts(new Response(Bun.file(`${filePath}.${preEnc === 'br' ? 'br' : 'gz'}`), { status: 200, headers }), req)
1060
- }
1061
- }
1062
- }
1063
-
1064
- headers.set('content-length', String(st.size))
1065
- const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
1066
- if (!compressEnabled || req.method === 'HEAD')
1067
- return withHsts(res, req)
1068
- return withHsts(await maybeCompressResponse(res, req, compressCache), req)
1069
- }
1070
-
1071
- return {
1072
- handle,
1073
- serve(port = 3000, hostname = '127.0.0.1') {
1074
- return Bun.serve({
1075
- port,
1076
- hostname,
1077
- idleTimeout: 30,
1078
- development: false,
1079
- fetch: handle,
1080
- error() {
1081
- return new Response('Internal Server Error', {
1082
- status: 500,
1083
- headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
1084
- })
1085
- },
1086
- })
1087
- },
1088
- }
1089
- }
1090
-
1091
- export async function createServer(options: ServerOptions): Promise<KayApp> {
1092
- const root = resolve(options.root)
1093
- const fileConfig = await loadConfig(root)
1094
- const plugins = options.plugins ?? fileConfig.plugins ?? []
1095
- const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
1096
- const clientDir = join(outDir, 'client')
1097
- const manifestPath = join(outDir, 'manifest.json')
1098
- const securityOpt = options.security ?? fileConfig.security
1099
- const trustProxy = (options.trustProxy ?? fileConfig.trustProxy) === true
1100
- const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
1101
-
1102
- if (!existsSync(manifestPath)) {
1103
- if (existsSync(outDir) && readdirSync(outDir).length > 0) {
1104
- const securityEntries = securityOpt === false ? [] : buildSecurityHeaderEntries(securityOpt ?? {})
1105
- return createStaticDirServer(
1106
- outDir,
1107
- options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
1108
- securityEntries,
1109
- (options.compress ?? fileConfig.compress) !== false,
1110
- resolveHstsValue(securityOpt),
1111
- trustProxy,
1112
- )
1113
- }
1114
- throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
1115
- }
1116
-
1117
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
1118
- const modules: Record<string, unknown> = {}
1119
- const assets: Record<string, EmbeddedBody> = {}
1120
- const publicAssets: Record<string, EmbeddedBody> = {}
1121
- const publicEtags: Record<string, string> = {}
1122
- const prerenderedFiles: Record<string, string> = {}
1123
- const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
1124
-
1125
- // Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
1126
- for (const rel of manifest.assets) {
1127
- const abs = join(clientDir, rel)
1128
- if (existsSync(abs)) {
1129
- assets[rel] = abs
1130
- if (existsSync(`${abs}.br`))
1131
- assets[`${rel}.br`] = `${abs}.br`
1132
- if (existsSync(`${abs}.gz`))
1133
- assets[`${rel}.gz`] = `${abs}.gz`
1134
- }
1135
- }
1136
-
1137
- for (const rel of manifest.publicFiles ?? []) {
1138
- const outAbs = join(outDir, 'public', rel)
1139
- const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
1140
- if (existsSync(abs)) {
1141
- publicAssets[rel] = abs
1142
- const st = statSync(abs)
1143
- publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
1144
- }
1145
- }
1146
-
1147
- const loadStamp = Date.now()
1148
- const loadMod = async (rel: string) => {
1149
- if (!(rel in modules))
1150
- modules[rel] = await import(`${join(outDir, rel)}?v=${loadStamp}`)
1151
- }
1152
-
1153
- for (const r of manifest.routes) {
1154
- await loadMod(r.file)
1155
- for (const l of r.layouts) await loadMod(l)
1156
- for (const m of r.middlewares) await loadMod(m)
1157
- if (r.prerendered) {
1158
- for (const [, relHtml] of Object.entries(r.prerendered)) {
1159
- const abs = join(outDir, relHtml)
1160
- if (existsSync(abs))
1161
- prerenderedFiles[relHtml] = abs
1322
+ let disposed = false
1323
+ async function dispose(): Promise<void> {
1324
+ if (disposed)
1325
+ return
1326
+ disposed = true
1327
+ for (const hook of shutdownHooks) {
1328
+ try {
1329
+ await hook()
1162
1330
  }
1331
+ catch {}
1163
1332
  }
1164
1333
  }
1165
- if (manifest.errorFile) await loadMod(manifest.errorFile)
1166
- if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
1167
- for (const a of manifest.actions) {
1168
- await loadMod(a.file)
1169
- for (const m of a.middlewares) await loadMod(m)
1170
- }
1171
1334
 
1172
- return createServerFromEmbedded({
1173
- manifest,
1174
- modules,
1175
- assets,
1176
- publicAssets,
1177
- publicEtags,
1178
- prerendered: {},
1179
- prerenderedFiles,
1180
- assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
1181
- lang: options.lang ?? fileConfig.lang,
1182
- security: securityOpt,
1183
- trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
1184
- trustProxy,
1185
- maxRequestBodySize,
1186
- compress: options.compress ?? fileConfig.compress,
1187
- onError: options.onError ?? fileConfig.onError,
1188
- plugins,
1189
- })
1335
+ return { handle, serve, dispose }
1190
1336
  }