@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

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