@kayjs/kay 2.0.0-alpha.5 → 2.0.0-alpha.7

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.
@@ -7,28 +7,32 @@
7
7
 
8
8
  import type { BuildManifest, RouteManifestEntry } from '../build/index'
9
9
  import type { Html, HydrateStrategy } from '../jsx-runtime'
10
- import type { KayPlugin, ServerPluginAPI } from '../plugins/index'
10
+ import type { KayPlugin, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
11
  import type { ActionContext, ServerAction } from './action'
12
12
  import type { CookieStore } from './cookies'
13
13
  import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
14
- import { existsSync, readFileSync } from 'node:fs'
14
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
15
15
  import { extname, join, resolve } from 'node:path'
16
16
  import { loadConfig } from '../plugins/index'
17
17
  import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
18
18
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
19
- import { executeAction, isServerAction } from './action'
19
+ import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
20
+ import type { ActionErrorFlash } from './action'
21
+ import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding } from './compress'
20
22
  import { extractRenderedIslands, finalizeResponse, makeRequestContext, MIME } from './http'
21
23
  import { Router } from './router'
22
- import { applySecurityHeaders } from './security'
24
+ import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, withCspHashes } from './security'
23
25
 
24
26
  export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
25
- export type { BuildPluginContext, KayConfig, KayPlugin, ServerPluginAPI } from '../plugins/index'
26
- export { action } from './action'
27
- export type { ActionContext, ActionResult, ServerAction } from './action'
27
+ export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
28
+ export { action, getActionError } from './action'
29
+ export type { ActionContext, ActionErrorFlash, ActionResult, ServerAction } from './action'
30
+ export { CompressionCache, isCompressibleType, pickEncoding } from './compress'
31
+ export type { CompressionEncoding } from './compress'
28
32
  export type { CookieOptions, Cookies } from './cookies'
29
33
  export { defineEnv } from './env'
30
34
  export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
31
- export { verifyOrigin } from './security'
35
+ export { KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
32
36
  export type { SecurityHeadersOptions } from './security'
33
37
  export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
34
38
 
@@ -55,8 +59,12 @@ interface LoadedErrorModule {
55
59
  default: (props: { error: unknown }) => Html | string | Promise<Html | string>
56
60
  }
57
61
 
62
+ const textEncoder = new TextEncoder()
63
+
64
+ type PrerenderEntry = { kind: 'file', path: string, hasIslands: boolean } | { kind: 'html', html: string, hasIslands: boolean }
65
+
58
66
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
59
- const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, lang = 'en', security, plugins = [] } = config
67
+ const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
60
68
  const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
61
69
  const trustedOrigins = config.trustedOrigins ? new Set(config.trustedOrigins) : undefined
62
70
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
@@ -64,6 +72,38 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
64
72
  .map(p => p.transformHtml)
65
73
  .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
66
74
 
75
+ const securityEntries = buildSecurityHeaderEntries(security)
76
+ const securityRecord: Record<string, string> = {}
77
+ for (let i = 0; i < securityEntries.length; i++) {
78
+ const [k, v] = securityEntries[i]!
79
+ securityRecord[k] = v
80
+ }
81
+ const htmlBaseHeaders: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
82
+ const baseCsp = security !== false ? security?.csp : undefined
83
+ const makeHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> => {
84
+ if (baseCsp === undefined || (!hasIslands && !hasSuspense))
85
+ return htmlBaseHeaders
86
+ const styleHashes: string[] = []
87
+ const scriptHashes: string[] = []
88
+ if (hasIslands)
89
+ styleHashes.push(KAY_ISLAND_STYLE_HASH)
90
+ if (hasSuspense) {
91
+ styleHashes.push(KAY_SUSPENSE_STYLE_HASH)
92
+ scriptHashes.push(KAY_STREAM_SCRIPT_HASH)
93
+ }
94
+ return { ...htmlBaseHeaders, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
95
+ }
96
+ const htmlHeadersPlain = makeHtmlHeaders(false, false)
97
+ const htmlHeadersIslands = makeHtmlHeaders(true, false)
98
+ const htmlHeadersSuspense = makeHtmlHeaders(false, true)
99
+ const htmlHeadersBoth = makeHtmlHeaders(true, true)
100
+ const selectHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
101
+ hasIslands
102
+ ? (hasSuspense ? htmlHeadersBoth : htmlHeadersIslands)
103
+ : (hasSuspense ? htmlHeadersSuspense : htmlHeadersPlain)
104
+ const compressEnabled = config.compress ?? (process.env.KAY_DEV !== '1')
105
+ const compressCache = compressEnabled ? new CompressionCache() : undefined
106
+
67
107
  // Collect plugin server hooks (supports both sync and async plugin setup)
68
108
  const globalMiddlewares: Middleware[] = []
69
109
  const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
@@ -93,22 +133,162 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
93
133
  await plugin.server(pluginApi)
94
134
  }
95
135
 
96
- const hasPluginRequestHooks = globalMiddlewares.length > 0 || pluginRewrites.length > 0 || htmlTransformers.length > 0 || pluginRouteEntries.size > 0
97
-
98
- // Hashed build asset table (immutable cache)
99
- const assetMap = new Map<string, { body: EmbeddedBody, type: string }>()
136
+ const hasGlobalMiddleware = globalMiddlewares.length > 0
137
+ const hasPluginRewrites = pluginRewrites.length > 0
138
+ const hasHtmlTransformers = htmlTransformers.length > 0
139
+
140
+ // Hashed build asset table (immutable cache + optional lazy compression)
141
+ interface AssetEntry {
142
+ body: EmbeddedBody
143
+ type: string
144
+ compressible: boolean
145
+ headers: Record<string, string>
146
+ varyHeaders: Record<string, string>
147
+ }
148
+ const assetMap = new Map<string, AssetEntry>()
100
149
  for (const [rel, body] of Object.entries(assets)) {
101
- assetMap.set(`${assetPrefix}/${rel}`, { body, type: MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream' })
150
+ const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
151
+ const compressible = isCompressibleType(type)
152
+ const headers: Record<string, string> = {
153
+ 'content-type': type,
154
+ 'cache-control': 'public, max-age=31536000, immutable',
155
+ }
156
+ const varyHeaders: Record<string, string> = compressible && compressCache !== undefined
157
+ ? { ...headers, vary: 'Accept-Encoding' }
158
+ : headers
159
+ assetMap.set(`${assetPrefix}/${rel}`, { body, type, compressible, headers, varyHeaders })
102
160
  }
103
161
 
104
- // Static public/ file table (ETag + 304 support)
105
- const publicMap = new Map<string, { body: EmbeddedBody, type: string, etag: string }>()
162
+ // Static public/ file table (ETag + 304 + zero-copy Bun.file + optional lazy compression)
163
+ interface PublicEntry {
164
+ body: EmbeddedBody
165
+ type: string
166
+ etag: string
167
+ compressible: boolean
168
+ }
169
+ const publicMap = new Map<string, PublicEntry>()
106
170
  for (const [rel, body] of Object.entries(publicAssets)) {
107
171
  const etag = publicEtags[rel] ?? (typeof body === 'string' ? `W/"${Bun.hash(rel).toString(36)}"` : `W/"${Bun.hash(body).toString(36)}"`)
108
- publicMap.set(`/${rel}`, { body, type: MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream', etag })
172
+ const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
173
+ publicMap.set(`/${rel}`, { body, type, etag, compressible: isCompressibleType(type) })
109
174
  }
110
175
 
111
176
  const toResponseBody = (body: EmbeddedBody) => typeof body === 'string' ? Bun.file(body) : body
177
+ const errorHooks: ((info: ServerErrorInfo) => void)[] = []
178
+ if (config.onError !== undefined)
179
+ errorHooks.push(config.onError)
180
+ for (const p of plugins) {
181
+ if (p.onError !== undefined)
182
+ errorHooks.push(p.onError)
183
+ }
184
+ const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
185
+ for (let i = 0; i < errorHooks.length; i++) {
186
+ try {
187
+ errorHooks[i]!({ error, request, source })
188
+ }
189
+ catch {}
190
+ }
191
+ }
192
+
193
+ async function serveAsset(request: Request, pathname: string, asset: AssetEntry): Promise<Response> {
194
+ if (request.method === 'HEAD')
195
+ return new Response(null, { status: 200, headers: asset.varyHeaders })
196
+
197
+ if (compressCache !== undefined && asset.compressible) {
198
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
199
+ if (enc !== undefined) {
200
+ const key = `${enc}:a:${pathname}`
201
+ let compressed = compressCache.get(key)
202
+ if (compressed === undefined) {
203
+ const rawBytes = typeof asset.body === 'string'
204
+ ? new Uint8Array(await Bun.file(asset.body).arrayBuffer())
205
+ : asset.body
206
+ compressed = compressCache.compress(rawBytes, enc, `a:${pathname}`)
207
+ if (compressed === undefined)
208
+ return new Response(rawBytes, { status: 200, headers: asset.varyHeaders })
209
+ }
210
+ return new Response(compressed, {
211
+ status: 200,
212
+ headers: { ...asset.headers, 'content-encoding': enc, vary: 'Accept-Encoding' },
213
+ })
214
+ }
215
+ }
216
+
217
+ return new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders })
218
+ }
219
+
220
+ async function servePublic(request: Request, pathname: string, pub: PublicEntry): Promise<Response> {
221
+ const cacheControl = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
222
+ const hasVary = pub.compressible && compressCache !== undefined
223
+ if (request.headers.get('if-none-match') === pub.etag) {
224
+ const h: Record<string, string> = hasVary
225
+ ? { 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding' }
226
+ : { 'etag': pub.etag, 'cache-control': cacheControl }
227
+ return new Response(null, { status: 304, headers: h })
228
+ }
229
+
230
+ const baseHeaders: Record<string, string> = hasVary
231
+ ? { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding' }
232
+ : { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl }
233
+
234
+ if (request.method === 'HEAD')
235
+ return new Response(null, { status: 200, headers: baseHeaders })
236
+
237
+ if (hasVary) {
238
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
239
+ if (enc !== undefined) {
240
+ const staticKey = `p:${pathname}:${pub.etag}`
241
+ let compressed = compressCache.get(`${enc}:${staticKey}`)
242
+ if (compressed === undefined) {
243
+ const rawBytes = typeof pub.body === 'string'
244
+ ? new Uint8Array(await Bun.file(pub.body).arrayBuffer())
245
+ : pub.body
246
+ compressed = compressCache.compress(rawBytes, enc, staticKey)
247
+ if (compressed === undefined)
248
+ return new Response(rawBytes, { status: 200, headers: baseHeaders })
249
+ }
250
+ return new Response(compressed, {
251
+ status: 200,
252
+ headers: { ...baseHeaders, 'content-encoding': enc },
253
+ })
254
+ }
255
+ }
256
+
257
+ return new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders })
258
+ }
259
+
260
+ async function servePrerendered(request: Request, pathname: string, pre: PrerenderEntry): Promise<Response> {
261
+ const base = selectHtmlHeaders(pre.hasIslands, false)
262
+ const headers = compressCache !== undefined
263
+ ? { ...base, vary: 'Accept-Encoding' }
264
+ : base
265
+
266
+ if (request.method === 'HEAD')
267
+ return new Response(null, { status: 200, headers })
268
+
269
+ if (compressCache !== undefined) {
270
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
271
+ if (enc !== undefined) {
272
+ const staticKey = `pre:${pathname}`
273
+ let compressed = compressCache.get(`${enc}:${staticKey}`)
274
+ if (compressed === undefined) {
275
+ const rawBytes = pre.kind === 'file'
276
+ ? new Uint8Array(await Bun.file(pre.path).arrayBuffer())
277
+ : textEncoder.encode(pre.html)
278
+ compressed = compressCache.compress(rawBytes, enc, staticKey)
279
+ if (compressed === undefined)
280
+ return new Response(rawBytes, { status: 200, headers })
281
+ }
282
+ return new Response(compressed, {
283
+ status: 200,
284
+ headers: { ...headers, 'content-encoding': enc },
285
+ })
286
+ }
287
+ }
288
+
289
+ const body = pre.kind === 'file' ? Bun.file(pre.path) : pre.html
290
+ return new Response(body, { status: 200, headers })
291
+ }
112
292
 
113
293
  // Register server actions and assign their live URLs
114
294
  const actionHandlers = new Map<string, ServerAction<unknown, unknown>>()
@@ -124,14 +304,25 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
124
304
  const errorMod = manifest.errorFile ? modules[manifest.errorFile] as LoadedErrorModule : undefined
125
305
  const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as LoadedPageModule : undefined
126
306
 
127
- // Static prerendered pages table
128
- const prerenderedMap = new Map<string, string>()
307
+ // Static prerendered pages table (zero-copy file paths preferred; raw HTML strings supported)
308
+ const prerenderedMap = new Map<string, PrerenderEntry>()
309
+ const fastPrerenderedMap = new Map<string, PrerenderEntry>()
129
310
  for (const route of manifest.routes) {
130
311
  if (route.prerendered) {
312
+ const routeHasIslands = route.islandChunks.length > 0
131
313
  for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
314
+ const filePath = prerenderedFiles[relHtml]
132
315
  const html = prerendered[relHtml]
133
- if (html !== undefined)
134
- prerenderedMap.set(urlPath, html)
316
+ const entry: PrerenderEntry | undefined = filePath !== undefined
317
+ ? { kind: 'file', path: filePath, hasIslands: routeHasIslands }
318
+ : html !== undefined
319
+ ? { kind: 'html', html, hasIslands: routeHasIslands }
320
+ : undefined
321
+ if (entry !== undefined) {
322
+ prerenderedMap.set(urlPath, entry)
323
+ if (route.middlewares.length === 0 && !hasGlobalMiddleware && pluginRouter.match(urlPath) === undefined)
324
+ fastPrerenderedMap.set(urlPath, entry)
325
+ }
135
326
  }
136
327
  }
137
328
  }
@@ -155,22 +346,29 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
155
346
  const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
156
347
 
157
348
  const hasIslands = entry.islandChunks.length > 0
349
+ const routeStyles = entry.styles ?? manifest.styles
350
+ const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
351
+ ? [...(manifest.headTags ?? []), ...entry.headTags]
352
+ : manifest.headTags
158
353
  const shell = renderDocument({
159
354
  body: '\0',
160
- headTags: manifest.headTags,
355
+ headTags: routeHeadTags,
161
356
  lang,
162
357
  runtimeScript: manifest.runtimeScript,
163
358
  alwaysLoadRuntime,
164
359
  preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks,
165
- styles: manifest.styles,
360
+ styles: routeStyles,
166
361
  hasIslands,
167
362
  })
168
363
  const splitAt = shell.indexOf('\0')
169
364
  const docPrefix = shell.slice(0, splitAt)
170
365
  const docSuffix = shell.slice(splitAt + 1)
171
366
 
172
- // Ultra-fast zero-overhead path when route is static, has no middleware, no <Head>/<Suspense>, no plugins
173
- const canFastPath = !hasPluginRequestHooks
367
+ // Ultra-fast zero-overhead path when route is static, has no middleware, no <Head>/<Suspense>, and no intercepting plugin hooks
368
+ const canFastPath = !hasGlobalMiddleware
369
+ && !hasPluginRewrites
370
+ && !hasHtmlTransformers
371
+ && pluginRouter.match(entry.path) === undefined
174
372
  && !entry.path.includes(':')
175
373
  && !entry.path.includes('*')
176
374
  && middlewares.length === 0
@@ -180,63 +378,84 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
180
378
 
181
379
  let fastHandler: ((req: Request) => Response | Promise<Response>) | undefined
182
380
  if (canFastPath) {
183
- const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8' }
184
- if (security !== false) {
185
- const h = new Headers(headers)
186
- applySecurityHeaders(h, security)
187
- h.forEach((v, k) => { headers[k] = v })
188
- }
189
381
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
382
+ const fastHeaders = selectHtmlHeaders(hasIslands, false)
190
383
 
191
384
  fastHandler = (request: Request): Response | Promise<Response> => {
192
- const reqUrl = new URL(request.url)
193
- const wrapLayouts = (inner: string): Response | Promise<Response> => {
194
- if (layouts.length === 0)
195
- return new Response(docPrefix + inner + docSuffix, { status: 200, headers })
196
- if (singleLayout !== undefined) {
197
- const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
198
- if (w instanceof Promise)
199
- return w.then(x => new Response(docPrefix + ssrChild(x as Html) + docSuffix, { status: 200, headers }))
200
- return new Response(docPrefix + ssrChild(w as Html) + docSuffix, { status: 200, headers })
201
- }
202
- return (async () => {
203
- let cur = inner
204
- for (let i = layouts.length - 1; i >= 0; i--)
205
- cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
206
- return new Response(docPrefix + cur + docSuffix, { status: 200, headers })
207
- })()
385
+ const handleErr = (error: unknown): Promise<Response> => {
386
+ notifyError(error, request, 'route')
387
+ return renderError(error, makeRequestContext(request, {}).cookieStore, new URL(request.url))
208
388
  }
389
+ try {
390
+ const reqUrl = new URL(request.url)
391
+ const respondHtml = (body: string): Response =>
392
+ compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache)
393
+
394
+ const wrapLayouts = (inner: string): Response | Promise<Response> => {
395
+ if (layouts.length === 0)
396
+ return respondHtml(inner)
397
+ if (singleLayout !== undefined) {
398
+ const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
399
+ if (w instanceof Promise)
400
+ return w.then(x => respondHtml(ssrChild(x as Html)), handleErr)
401
+ return respondHtml(ssrChild(w as Html))
402
+ }
403
+ return (async () => {
404
+ let cur = inner
405
+ for (let i = layouts.length - 1; i >= 0; i--)
406
+ cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
407
+ return respondHtml(cur)
408
+ })().catch(handleErr)
409
+ }
209
410
 
210
- const renderPage = (pageProps: Record<string, unknown>): Response | Promise<Response> => {
211
- if (entry.isIsland && entry.islandChunk !== undefined) {
212
- const inner = ssrIsland(
213
- entry.path,
214
- entry.islandChunk,
215
- () => ssrChild(mod.default!(pageProps) as Html),
216
- pageProps,
217
- entry.islandHydrate as HydrateStrategy | undefined,
218
- )
219
- return wrapLayouts(inner)
411
+ const renderPage = (data: unknown): Response | Promise<Response> => {
412
+ const pageProps: Record<string, unknown> = {
413
+ params: {},
414
+ locals: {},
415
+ url: reqUrl,
416
+ ...(data !== undefined ? { data } : {}),
417
+ }
418
+ if (entry.isIsland && entry.islandChunk !== undefined) {
419
+ const inner = ssrIsland(
420
+ entry.path,
421
+ entry.islandChunk,
422
+ () => ssrChild(mod.default!(pageProps) as Html),
423
+ data !== undefined ? { data } : {},
424
+ entry.islandHydrate as HydrateStrategy | undefined,
425
+ )
426
+ return wrapLayouts(inner)
427
+ }
428
+ const rendered = mod.default!(pageProps)
429
+ if (rendered instanceof Promise)
430
+ return rendered.then(r => wrapLayouts(ssrChild(r as Html)), handleErr)
431
+ return wrapLayouts(ssrChild(rendered as Html))
220
432
  }
221
- const rendered = mod.default!(pageProps)
222
- if (rendered instanceof Promise)
223
- return rendered.then(r => wrapLayouts(ssrChild(r as Html)))
224
- return wrapLayouts(ssrChild(rendered as Html))
225
- }
226
433
 
227
- if (entry.hasLoad && typeof mod.load === 'function') {
228
- const { ctx } = makeRequestContext(request, {})
229
- const loaded = mod.load(ctx)
230
- if (loaded instanceof Promise) {
231
- return loaded.then(data =>
232
- data instanceof Response ? data : renderPage(data !== undefined ? { data } : {}),
233
- )
434
+ if (entry.hasLoad && typeof mod.load === 'function') {
435
+ const { ctx, cookieStore } = makeRequestContext(request, {})
436
+ const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
437
+ if (!cookieStore.hasChanges)
438
+ return res
439
+ if (res instanceof Promise)
440
+ return res.then(r => finalizeResponse(r, cookieStore, securityEntries), handleErr)
441
+ return finalizeResponse(res, cookieStore, securityEntries)
442
+ }
443
+ const loaded = mod.load(ctx)
444
+ if (loaded instanceof Promise) {
445
+ return loaded.then(
446
+ data => finish(data instanceof Response ? data : renderPage(data)),
447
+ handleErr,
448
+ )
449
+ }
450
+ if (loaded instanceof Response)
451
+ return finish(loaded)
452
+ return finish(renderPage(loaded))
234
453
  }
235
- if (loaded instanceof Response)
236
- return loaded
237
- return renderPage(loaded !== undefined ? { data: loaded } : {})
454
+ return renderPage(undefined)
455
+ }
456
+ catch (error) {
457
+ return handleErr(error)
238
458
  }
239
- return renderPage({})
240
459
  }
241
460
  fastStaticPages.set(entry.path, fastHandler)
242
461
  }
@@ -244,22 +463,29 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
244
463
  router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
245
464
  }
246
465
 
247
- async function renderCompiledRoute(route: CompiledRoute, ctx: RequestContext, cookieStore: CookieStore): Promise<Response> {
466
+ async function renderCompiledRoute(route: CompiledRoute, ctx: RequestContext): Promise<Response> {
248
467
  const { entry, mod, layouts } = route
249
468
 
469
+ // Serve prerendered HTML after middlewares have passed (when route had middlewares)
470
+ if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
471
+ const pre = prerenderedMap.get(ctx.url.pathname)
472
+ if (pre !== undefined)
473
+ return servePrerendered(ctx.request, ctx.url.pathname, pre)
474
+ }
475
+
250
476
  // API route (.ts exporting GET/POST/etc.)
251
477
  const methodHandler = mod[ctx.request.method]
252
478
  if (typeof methodHandler === 'function') {
253
479
  const res = await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
254
- return finalizeResponse(res, cookieStore, security)
480
+ return maybeCompressResponse(res, ctx.request, compressCache)
255
481
  }
256
482
 
257
483
  if (typeof mod.default !== 'function')
258
- return finalizeResponse(new Response('Method Not Allowed', { status: 405 }), cookieStore, security)
484
+ return new Response('Method Not Allowed', { status: 405 })
259
485
 
260
486
  const data = entry.hasLoad && typeof mod.load === 'function' ? await mod.load(ctx) : undefined
261
487
  if (data instanceof Response)
262
- return finalizeResponse(data, cookieStore, security)
488
+ return data
263
489
  const pageProps: Record<string, unknown> = {
264
490
  params: ctx.params,
265
491
  locals: ctx.locals,
@@ -293,69 +519,67 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
293
519
  const hasIslands = renderedIslands.hasIslands || rctx.pending.length > 0 && entry.islandChunks.length > 0
294
520
  const preloadChunks = rctx.pending.length > 0 ? entry.islandChunks : renderedIslands.eagerChunks
295
521
 
296
- // Streaming SSR path when <Suspense> boundaries are pending!
522
+ const routeStyles = entry.styles ?? manifest.styles
523
+ const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
524
+ ? [...(manifest.headTags ?? []), ...entry.headTags]
525
+ : manifest.headTags
526
+
527
+ // Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
297
528
  if (rctx.pending.length > 0) {
298
529
  const shell = renderDocument({
299
530
  body: '\0',
300
531
  head: collectedHead,
301
- headTags: manifest.headTags,
532
+ headTags: routeHeadTags,
302
533
  lang,
303
534
  runtimeScript: manifest.runtimeScript,
304
535
  alwaysLoadRuntime,
305
536
  preloadChunks,
306
- styles: manifest.styles,
537
+ styles: routeStyles,
307
538
  hasIslands,
539
+ hasSuspense: true,
308
540
  })
309
541
  const splitAt = shell.indexOf('\0')
310
542
  const headHtml = shell.slice(0, splitAt)
311
543
  const tailHtml = shell.slice(splitAt + 1)
312
- const encoder = new TextEncoder()
313
544
 
314
545
  const stream = new ReadableStream<Uint8Array>({
315
546
  async start(controller) {
316
- controller.enqueue(encoder.encode(headHtml + body))
547
+ controller.enqueue(textEncoder.encode(headHtml + body))
317
548
  await Promise.all(
318
549
  rctx.pending.map(async (chunk) => {
319
550
  const resolved = await chunk.promise
320
- controller.enqueue(encoder.encode(streamChunkScript(chunk.id, resolved)))
551
+ controller.enqueue(textEncoder.encode(streamChunkScript(chunk.id, resolved)))
321
552
  }),
322
553
  )
323
- controller.enqueue(encoder.encode(tailHtml))
554
+ controller.enqueue(textEncoder.encode(tailHtml))
324
555
  controller.close()
325
556
  },
326
557
  })
327
558
 
328
- const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' })
329
- cookieStore.applyTo(headers)
330
- if (security !== false)
331
- applySecurityHeaders(headers, security)
332
- return new Response(stream, { status: 200, headers })
559
+ return new Response(stream, { status: 200, headers: { ...selectHtmlHeaders(hasIslands, true) } })
333
560
  }
334
561
 
335
562
  let html = renderDocument({
336
563
  body,
337
564
  head: collectedHead,
338
- headTags: manifest.headTags,
565
+ headTags: routeHeadTags,
339
566
  lang,
340
567
  runtimeScript: manifest.runtimeScript,
341
568
  alwaysLoadRuntime,
342
569
  preloadChunks,
343
- styles: manifest.styles,
570
+ styles: routeStyles,
344
571
  hasIslands,
345
572
  })
346
573
 
347
574
  for (let i = 0; i < htmlTransformers.length; i++)
348
575
  html = await htmlTransformers[i]!(html, ctx)
349
576
 
350
- const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' })
351
- cookieStore.applyTo(headers)
352
- if (security !== false)
353
- applySecurityHeaders(headers, security)
354
- return new Response(html, { status: 200, headers })
577
+ return compressedHtmlResponse(html, 200, selectHtmlHeaders(hasIslands, false), ctx.request, compressCache)
355
578
  }
356
579
 
357
580
  const rootLayoutFile = manifest.routes.find(r => r.layouts.length > 0)?.layouts[0]
358
581
  const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
582
+ const fallbackStyles = manifest.globalStyles ?? manifest.styles
359
583
 
360
584
  async function renderError(error: unknown, cookieStore: CookieStore, url?: URL): Promise<Response> {
361
585
  if (errorMod !== undefined) {
@@ -366,10 +590,10 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
366
590
  inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/500'), params: {}, locals: {} }) as Html)
367
591
  return inner
368
592
  })
369
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: manifest.styles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
370
- return finalizeResponse(new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, security)
593
+ const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
594
+ return finalizeResponse(new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, securityEntries)
371
595
  }
372
- return finalizeResponse(new Response('Internal Server Error', { status: 500 }), cookieStore, security)
596
+ return finalizeResponse(new Response('Internal Server Error', { status: 500 }), cookieStore, securityEntries)
373
597
  }
374
598
 
375
599
  async function renderNotFound(cookieStore: CookieStore, url?: URL): Promise<Response> {
@@ -382,43 +606,27 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
382
606
  inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/404'), params: {}, locals: {} }) as Html)
383
607
  return inner
384
608
  })
385
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: manifest.styles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
386
- return finalizeResponse(new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, security)
609
+ const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
610
+ return finalizeResponse(new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, securityEntries)
387
611
  }
388
- return finalizeResponse(new Response('Not Found', { status: 404 }), cookieStore, security)
612
+ return finalizeResponse(new Response('Not Found', { status: 404 }), cookieStore, securityEntries)
389
613
  }
390
614
 
391
615
  async function handle(request: Request): Promise<Response> {
392
616
  const pathname = new URL(request.url).pathname
393
617
 
394
618
  // 1. Static client assets
395
- const asset = assetMap.get(pathname)
396
- if (asset !== undefined) {
397
- return new Response(toResponseBody(asset.body), {
398
- status: 200,
399
- headers: {
400
- 'content-type': asset.type,
401
- 'cache-control': 'public, max-age=31536000, immutable',
402
- },
403
- })
619
+ if (request.method === 'GET' || request.method === 'HEAD') {
620
+ const asset = assetMap.get(pathname)
621
+ if (asset !== undefined)
622
+ return serveAsset(request, pathname, asset)
404
623
  }
405
624
 
406
625
  // 1b. Static public/ files (no-cache in dev so edits/plugins never get stuck in browser cache)
407
626
  if (request.method === 'GET' || request.method === 'HEAD') {
408
627
  const pub = publicMap.get(pathname)
409
- if (pub !== undefined) {
410
- const cacheControl = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
411
- if (request.headers.get('if-none-match') === pub.etag)
412
- return new Response(null, { status: 304, headers: { 'etag': pub.etag, 'cache-control': cacheControl } })
413
- return new Response(request.method === 'HEAD' ? null : toResponseBody(pub.body), {
414
- status: 200,
415
- headers: {
416
- 'content-type': pub.type,
417
- 'etag': pub.etag,
418
- 'cache-control': cacheControl,
419
- },
420
- })
421
- }
628
+ if (pub !== undefined)
629
+ return servePublic(request, pathname, pub)
422
630
  }
423
631
 
424
632
  // 2. Server actions (POST /_kay/action/<id>) — run global plugin middlewares first so ctx.locals (e.g. auth user) is populated
@@ -440,7 +648,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
440
648
  }
441
649
  if (globalMiddlewares.length === 0) {
442
650
  const res = await runAction()
443
- return finalizeResponse(res, cookieStore, security)
651
+ return finalizeResponse(res, cookieStore, securityEntries)
444
652
  }
445
653
  let index = -1
446
654
  const dispatch = async (i: number): Promise<Response> => {
@@ -451,24 +659,28 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
451
659
  return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
452
660
  return runAction()
453
661
  }
454
- const res = await dispatch(0)
455
- return finalizeResponse(res, cookieStore, security)
662
+ try {
663
+ const res = await dispatch(0)
664
+ return finalizeResponse(res, cookieStore, securityEntries)
665
+ }
666
+ catch (error) {
667
+ notifyError(error, request, 'action')
668
+ return renderError(error, cookieStore, ctx.url)
669
+ }
456
670
  }
457
671
  }
458
672
 
459
- // 3. Prerendered static HTML (when no plugin request hooks intercept)
460
- if (!hasPluginRequestHooks && (request.method === 'GET' || request.method === 'HEAD')) {
461
- const pre = prerenderedMap.get(pathname)
462
- if (pre !== undefined) {
463
- const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' })
464
- if (security !== false)
465
- applySecurityHeaders(headers, security)
466
- return new Response(pre, { status: 200, headers })
467
- }
673
+ const hasActionErrorFlash = (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
674
+
675
+ // 3. Prerendered static HTML (safe even when plugins add routes or build-time transformHtml!)
676
+ if (!hasActionErrorFlash && (request.method === 'GET' || request.method === 'HEAD')) {
677
+ const pre = fastPrerenderedMap.get(pathname)
678
+ if (pre !== undefined)
679
+ return servePrerendered(request, pathname, pre)
468
680
  }
469
681
 
470
682
  // 4. Ultra-fast static route path
471
- if (request.method === 'GET') {
683
+ if (!hasActionErrorFlash && (request.method === 'GET' || request.method === 'HEAD')) {
472
684
  const fast = fastStaticPages.get(pathname)
473
685
  if (fast !== undefined)
474
686
  return fast(request)
@@ -477,6 +689,18 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
477
689
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
478
690
  const { ctx, cookieStore } = makeRequestContext(request, {})
479
691
 
692
+ // Hydrate & clear one-shot progressive form validation flash cookie
693
+ if (hasActionErrorFlash && request.method === 'GET') {
694
+ const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
695
+ if (rawFlash !== undefined) {
696
+ try {
697
+ ctx.locals.actionError = JSON.parse(rawFlash) as ActionErrorFlash
698
+ }
699
+ catch {}
700
+ ctx.cookies.delete(ACTION_ERROR_COOKIE)
701
+ }
702
+ }
703
+
480
704
  // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
481
705
  let effectivePath = pathname
482
706
  for (let i = 0; i < pluginRewrites.length; i++) {
@@ -492,21 +716,29 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
492
716
  const methodHandler = pluginMatch.data.get(request.method.toUpperCase()) ?? pluginMatch.data.get('ALL')
493
717
  if (methodHandler !== undefined) {
494
718
  ctx.params = pluginMatch.params
495
- if (globalMiddlewares.length === 0) {
496
- const res = await methodHandler(ctx)
497
- return finalizeResponse(res, cookieStore, security)
719
+ let res: Response
720
+ try {
721
+ if (globalMiddlewares.length === 0) {
722
+ res = await methodHandler(ctx)
723
+ }
724
+ else {
725
+ let index = -1
726
+ const dispatch = async (i: number): Promise<Response> => {
727
+ if (i <= index)
728
+ throw new Error('kay: middleware called next() multiple times')
729
+ index = i
730
+ if (i < globalMiddlewares.length)
731
+ return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
732
+ return methodHandler(ctx)
733
+ }
734
+ res = await dispatch(0)
735
+ }
736
+ return finalizeResponse(await maybeCompressResponse(res, request, compressCache), cookieStore, securityEntries)
498
737
  }
499
- let index = -1
500
- const dispatch = async (i: number): Promise<Response> => {
501
- if (i <= index)
502
- throw new Error('kay: middleware called next() multiple times')
503
- index = i
504
- if (i < globalMiddlewares.length)
505
- return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
506
- return methodHandler(ctx)
738
+ catch (error) {
739
+ notifyError(error, request, 'plugin')
740
+ return renderError(error, cookieStore, ctx.url)
507
741
  }
508
- const res = await dispatch(0)
509
- return finalizeResponse(res, cookieStore, security)
510
742
  }
511
743
  }
512
744
 
@@ -528,62 +760,47 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
528
760
  index = i
529
761
  if (i < allMiddlewares.length)
530
762
  return allMiddlewares[i]!(ctx, () => dispatch(i + 1))
531
- return renderCompiledRoute(route, ctx, cookieStore)
763
+ return renderCompiledRoute(route, ctx)
532
764
  }
533
765
  const res = await dispatch(0)
534
- return finalizeResponse(res, cookieStore, security)
766
+ return finalizeResponse(res, cookieStore, securityEntries)
535
767
  }
536
768
  catch (error) {
769
+ notifyError(error, request, 'route')
537
770
  return renderError(error, cookieStore, ctx.url)
538
771
  }
539
772
  }
540
773
 
541
- function serve(port = 3000) {
542
- const routes: Record<string, Response | ((req: Request) => Response | Promise<Response>)> = {}
774
+ function serve(port = 3000, hostname?: string) {
775
+ const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
543
776
 
544
- for (const [path, asset] of assetMap) {
545
- const headers = {
546
- 'content-type': asset.type,
547
- 'cache-control': 'public, max-age=31536000, immutable',
548
- }
549
- routes[path] = typeof asset.body === 'string'
550
- ? () => new Response(Bun.file(asset.body as string), { status: 200, headers })
551
- : new Response(asset.body, { status: 200, headers })
552
- }
777
+ for (const [path, asset] of assetMap)
778
+ routes[path] = req => serveAsset(req, path, asset)
553
779
 
554
- const pubCache = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
555
780
  for (const [path, pub] of publicMap) {
556
- if (!(path in routes)) {
557
- const headers = {
558
- 'content-type': pub.type,
559
- 'etag': pub.etag,
560
- 'cache-control': pubCache,
561
- }
562
- routes[path] = (req: Request) => {
563
- if (req.headers.get('if-none-match') === pub.etag)
564
- return new Response(null, { status: 304, headers: { 'etag': pub.etag, 'cache-control': pubCache } })
565
- const body = typeof pub.body === 'string' ? Bun.file(pub.body) : pub.body
566
- return new Response(req.method === 'HEAD' ? null : body, { status: 200, headers })
567
- }
568
- }
781
+ if (!(path in routes))
782
+ routes[path] = req => servePublic(req, path, pub)
569
783
  }
570
784
 
571
- if (!hasPluginRequestHooks) {
572
- for (const [path, pre] of prerenderedMap) {
573
- const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' })
574
- if (security !== false)
575
- applySecurityHeaders(headers, security)
576
- routes[path] = new Response(pre, { status: 200, headers })
785
+ for (const [path, pre] of fastPrerenderedMap) {
786
+ if (!(path in routes)) {
787
+ routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
788
+ ? servePrerendered(req, path, pre)
789
+ : handle(req)
577
790
  }
578
791
  }
579
792
 
580
793
  for (const [path, handler] of fastStaticPages) {
581
- if (!(path in routes))
582
- routes[path] = handler
794
+ if (!(path in routes)) {
795
+ routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
796
+ ? handler(req)
797
+ : handle(req)
798
+ }
583
799
  }
584
800
 
585
801
  return Bun.serve({
586
802
  port,
803
+ ...(hostname ? { hostname } : {}),
587
804
  idleTimeout: 0,
588
805
  routes,
589
806
  fetch: handle,
@@ -593,6 +810,87 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
593
810
  return { handle, serve }
594
811
  }
595
812
 
813
+ function createStaticDirServer(
814
+ outDir: string,
815
+ assetPrefix: string,
816
+ securityEntries: readonly [string, string][],
817
+ compressEnabled: boolean,
818
+ ): KayApp {
819
+ const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
820
+ const absRoot = resolve(outDir)
821
+ const compressCache = compressEnabled ? new CompressionCache() : undefined
822
+
823
+ function resolveStaticFile(pathname: string): string | undefined {
824
+ let decoded: string
825
+ try {
826
+ decoded = decodeURIComponent(pathname)
827
+ }
828
+ catch {
829
+ return undefined
830
+ }
831
+ const rel = decoded.replace(/^\/+/, '').replace(/\/+$/, '')
832
+ const candidates = rel === ''
833
+ ? ['index.html']
834
+ : [rel, `${rel}.html`, `${rel}/index.html`]
835
+ for (const c of candidates) {
836
+ const abs = resolve(absRoot, c)
837
+ if (abs !== absRoot && !abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
838
+ continue
839
+ if (existsSync(abs) && statSync(abs).isFile())
840
+ return abs
841
+ }
842
+ return undefined
843
+ }
844
+
845
+ const initHeaders = (): Headers => {
846
+ const headers = new Headers()
847
+ for (let i = 0; i < securityEntries.length; i++)
848
+ headers.set(securityEntries[i]![0], securityEntries[i]![1])
849
+ return headers
850
+ }
851
+
852
+ const handle = async (req: Request): Promise<Response> => {
853
+ if (req.method !== 'GET' && req.method !== 'HEAD')
854
+ return new Response('Method Not Allowed', { status: 405 })
855
+
856
+ const url = new URL(req.url)
857
+ const filePath = resolveStaticFile(url.pathname)
858
+ if (filePath === undefined) {
859
+ const notFoundPath = join(absRoot, '404.html')
860
+ if (existsSync(notFoundPath) && statSync(notFoundPath).isFile()) {
861
+ const headers = initHeaders()
862
+ headers.set('content-type', 'text/html; charset=utf-8')
863
+ return new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers })
864
+ }
865
+ return new Response('Not Found', { status: 404 })
866
+ }
867
+
868
+ const st = statSync(filePath)
869
+ const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
870
+ const isImmutable = url.pathname.startsWith(cleanPrefix)
871
+ const cacheControl = isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate'
872
+ const headers = initHeaders()
873
+ headers.set('content-type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream')
874
+ headers.set('cache-control', cacheControl)
875
+ headers.set('etag', etag)
876
+
877
+ if (req.headers.get('if-none-match') === etag)
878
+ return new Response(null, { status: 304, headers })
879
+
880
+ const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
881
+ if (!compressEnabled || req.method === 'HEAD')
882
+ return res
883
+ return maybeCompressResponse(res, req, compressCache)
884
+ }
885
+
886
+ return {
887
+ handle,
888
+ serve(port = 3000) {
889
+ return Bun.serve({ port, fetch: handle })
890
+ },
891
+ }
892
+ }
893
+
596
894
  export async function createServer(options: ServerOptions): Promise<KayApp> {
597
895
  const root = resolve(options.root)
598
896
  const fileConfig = await loadConfig(root)
@@ -601,28 +899,43 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
601
899
  const clientDir = join(outDir, 'client')
602
900
  const manifestPath = join(outDir, 'manifest.json')
603
901
 
604
- if (!existsSync(manifestPath))
902
+ if (!existsSync(manifestPath)) {
903
+ if (existsSync(outDir) && readdirSync(outDir).length > 0) {
904
+ const securityOpt = options.security ?? fileConfig.security
905
+ const securityEntries = securityOpt === false ? [] : buildSecurityHeaderEntries(securityOpt ?? {})
906
+ return createStaticDirServer(
907
+ outDir,
908
+ options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
909
+ securityEntries,
910
+ (options.compress ?? fileConfig.compress) !== false,
911
+ )
912
+ }
605
913
  throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
914
+ }
606
915
 
607
916
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
608
917
  const modules: Record<string, unknown> = {}
609
918
  const assets: Record<string, EmbeddedBody> = {}
610
919
  const publicAssets: Record<string, EmbeddedBody> = {}
611
- const prerendered: Record<string, string> = {}
612
- const isDev = process.env.KAY_DEV === '1'
920
+ const publicEtags: Record<string, string> = {}
921
+ const prerenderedFiles: Record<string, string> = {}
613
922
  const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
614
923
 
924
+ // Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
615
925
  for (const rel of manifest.assets) {
616
926
  const abs = join(clientDir, rel)
617
927
  if (existsSync(abs))
618
- assets[rel] = isDev ? abs : new Uint8Array(readFileSync(abs))
928
+ assets[rel] = abs
619
929
  }
620
930
 
621
931
  for (const rel of manifest.publicFiles ?? []) {
622
932
  const outAbs = join(outDir, 'public', rel)
623
933
  const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
624
- if (existsSync(abs))
625
- publicAssets[rel] = isDev ? abs : new Uint8Array(readFileSync(abs))
934
+ if (existsSync(abs)) {
935
+ publicAssets[rel] = abs
936
+ const st = statSync(abs)
937
+ publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
938
+ }
626
939
  }
627
940
 
628
941
  const loadStamp = Date.now()
@@ -639,7 +952,7 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
639
952
  for (const [, relHtml] of Object.entries(r.prerendered)) {
640
953
  const abs = join(outDir, relHtml)
641
954
  if (existsSync(abs))
642
- prerendered[relHtml] = readFileSync(abs, 'utf8')
955
+ prerenderedFiles[relHtml] = abs
643
956
  }
644
957
  }
645
958
  }
@@ -652,11 +965,15 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
652
965
  modules,
653
966
  assets,
654
967
  publicAssets,
655
- prerendered,
968
+ publicEtags,
969
+ prerendered: {},
970
+ prerenderedFiles,
656
971
  assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
657
972
  lang: options.lang ?? fileConfig.lang,
658
973
  security: options.security ?? fileConfig.security,
659
974
  trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
975
+ compress: options.compress ?? fileConfig.compress,
976
+ onError: options.onError ?? fileConfig.onError,
660
977
  plugins,
661
978
  })
662
979
  }