@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,8 +12,8 @@ import { existsSync, readFileSync } from 'node:fs'
12
12
  import { join, resolve } from 'node:path'
13
13
  import { createAppContext, getAppContext, runWithAppContext } from './context'
14
14
 
15
- export { createAppContext, getAppContext, runWithAppContext } from './context'
16
- export type { AppRuntimeContext, CreateAppContextOptions } from './context'
15
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, getAppContext, I18N_CONFIG_SERVICE, runWithAppContext } from './context'
16
+ export type { ActiveI18nConfig, AppRuntimeContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions } from './context'
17
17
 
18
18
  export type BuildPluginTarget = 'client' | 'server' | 'compile'
19
19
 
@@ -21,6 +21,7 @@ export interface BuildPluginContext {
21
21
  readonly root: string
22
22
  readonly outDir: string
23
23
  readonly assetPrefix: string
24
+ readonly site?: string | undefined
24
25
  readonly minify: boolean
25
26
  readonly isStatic: boolean
26
27
  readonly dev: boolean
@@ -49,6 +50,7 @@ export interface FinalizeBuildContext {
49
50
  readonly root: string
50
51
  readonly outDir: string
51
52
  readonly assetPrefix: string
53
+ readonly site?: string | undefined
52
54
  readonly minify: boolean
53
55
  readonly isStatic: boolean
54
56
  readonly dev: boolean
@@ -93,6 +95,7 @@ export interface ServerPluginAPI {
93
95
  readonly root: string
94
96
  readonly outDir: string
95
97
  readonly assetPrefix: string
98
+ readonly site?: string | undefined
96
99
  readonly dev: boolean
97
100
  /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
98
101
  readonly trustProxy: TrustProxy
@@ -123,8 +126,29 @@ export interface ServerErrorInfo {
123
126
  source: 'route' | 'action' | 'plugin'
124
127
  }
125
128
 
129
+ export interface DocumentHeadContext {
130
+ /** Current document `lang` attribute (mutating sets `<html lang="...">`). */
131
+ lang: string
132
+ /** Extra attributes emitted on `<html>`. */
133
+ readonly htmlAttrs: Record<string, string>
134
+ /** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
135
+ title: string | undefined
136
+ /** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
137
+ readonly headHtml: string
138
+ /** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
139
+ add(html: string): void
140
+ }
141
+
126
142
  export interface KayPlugin {
127
143
  name: string
144
+ /** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
145
+ enforce?: 'pre' | 'post' | undefined
146
+ /** Names of plugins that must run before this plugin when present. */
147
+ after?: readonly string[] | undefined
148
+ /** `ctx.locals` keys this plugin populates (used for startup order validation). */
149
+ providesLocals?: readonly string[] | undefined
150
+ /** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
151
+ readsLocals?: readonly string[] | undefined
128
152
  /** Register server routes, global middleware, URL rewrites, or runtime services. */
129
153
  server?: (api: ServerPluginAPI) => void | Promise<void>
130
154
  /** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
@@ -141,6 +165,8 @@ export interface KayPlugin {
141
165
  bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
142
166
  /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
143
167
  css?: string[] | undefined
168
+ /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
169
+ head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
144
170
  /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
145
171
  transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
146
172
  /** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
@@ -155,12 +181,11 @@ export interface KayPlugin {
155
181
  commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
156
182
  }
157
183
 
158
- export interface KayConfig {
184
+ /** Shared runtime server options inherited from `kay.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
185
+ export interface ServerRuntimeConfig {
186
+ /** Public origin of the site (e.g. 'https://example.com'), inherited by @kayjs/seo, @kayjs/i18n, @kayjs/content, @kayjs/images, and @kayjs/auth. */
187
+ site?: string | undefined
159
188
  lang?: string | undefined
160
- port?: number | undefined
161
- routesDir?: string | undefined
162
- outDir?: string | undefined
163
- publicDir?: string | undefined
164
189
  assetPrefix?: string | undefined
165
190
  security?: SecurityHeadersOptions | false | undefined
166
191
  trustedOrigins?: string[] | undefined
@@ -173,22 +198,163 @@ export interface KayConfig {
173
198
  plugins?: KayPlugin[] | undefined
174
199
  }
175
200
 
201
+ export interface KayConfig extends ServerRuntimeConfig {
202
+ port?: number | undefined
203
+ routesDir?: string | undefined
204
+ outDir?: string | undefined
205
+ publicDir?: string | undefined
206
+ }
207
+
176
208
  export function defineConfig(config: KayConfig): KayConfig {
177
209
  return config
178
210
  }
179
211
 
180
212
  /** Forwards every runtime key from `kay.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`). */
181
- export function pickRuntimeConfig(config: KayConfig | undefined): Omit<KayConfig, 'routesDir' | 'outDir' | 'publicDir' | 'port'> {
213
+ export function pickRuntimeConfig(config: KayConfig | undefined): ServerRuntimeConfig {
182
214
  if (config === undefined)
183
215
  return {}
184
216
  const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, ...runtime } = config
185
217
  return runtime
186
218
  }
187
219
 
220
+ const RUNTIME_CONFIG_KEYS: readonly (keyof ServerRuntimeConfig)[] = [
221
+ 'site',
222
+ 'lang',
223
+ 'assetPrefix',
224
+ 'security',
225
+ 'trustedOrigins',
226
+ 'trustProxy',
227
+ 'maxRequestBodySize',
228
+ 'streamTimeout',
229
+ 'compress',
230
+ 'onError',
231
+ 'plugins',
232
+ ]
233
+
234
+ /** Merges runtime options from `kay.config.ts` with explicit caller overrides (ignoring `undefined` override fields). */
235
+ export function resolveServerConfig(
236
+ fileConfig: KayConfig | undefined,
237
+ overrides?: Partial<ServerRuntimeConfig> | undefined,
238
+ ): ServerRuntimeConfig {
239
+ const merged: Record<string, unknown> = { ...pickRuntimeConfig(fileConfig) }
240
+ if (overrides !== undefined) {
241
+ for (const key of RUNTIME_CONFIG_KEYS) {
242
+ const value = overrides[key]
243
+ if (value !== undefined)
244
+ merged[key] = value
245
+ }
246
+ }
247
+ return merged as ServerRuntimeConfig
248
+ }
249
+
188
250
  export function definePlugin(plugin: KayPlugin): KayPlugin {
189
251
  return plugin
190
252
  }
191
253
 
254
+ function enforceRank(plugin: KayPlugin): number {
255
+ return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
256
+ }
257
+
258
+ /**
259
+ * Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
260
+ * then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
261
+ */
262
+ export function resolvePlugins(plugins: readonly KayPlugin[] | undefined): KayPlugin[] {
263
+ if (plugins === undefined || plugins.length === 0)
264
+ return []
265
+
266
+ // Base stable order by `enforce` bucket, preserving config declaration order within each bucket.
267
+ const base = plugins
268
+ .map((plugin, index) => ({ plugin, index, rank: enforceRank(plugin) }))
269
+ .sort((a, b) => a.rank - b.rank || a.index - b.index)
270
+ .map(entry => entry.plugin)
271
+
272
+ const n = base.length
273
+ const indicesByName = new Map<string, number[]>()
274
+ for (let i = 0; i < n; i++) {
275
+ const name = base[i]!.name
276
+ const list = indicesByName.get(name)
277
+ if (list === undefined)
278
+ indicesByName.set(name, [i])
279
+ else
280
+ list.push(i)
281
+ }
282
+
283
+ // Kahn's topological sort using min-index priority so `enforce` + declaration order stays deterministic.
284
+ const inDegree = new Int32Array(n)
285
+ const edges: number[][] = Array.from({ length: n }, () => [])
286
+ for (let i = 0; i < n; i++) {
287
+ const deps = base[i]!.after
288
+ if (deps === undefined)
289
+ continue
290
+ const seen = new Set<number>()
291
+ for (const depName of deps) {
292
+ const targets = indicesByName.get(depName)
293
+ if (targets === undefined)
294
+ continue
295
+ for (const depIdx of targets) {
296
+ if (depIdx === i || seen.has(depIdx))
297
+ continue
298
+ seen.add(depIdx)
299
+ edges[depIdx]!.push(i)
300
+ inDegree[i] = (inDegree[i] ?? 0) + 1
301
+ }
302
+ }
303
+ }
304
+
305
+ const ready: number[] = []
306
+ for (let i = 0; i < n; i++) {
307
+ if (inDegree[i] === 0)
308
+ ready.push(i)
309
+ }
310
+
311
+ const sorted: KayPlugin[] = []
312
+ while (ready.length > 0) {
313
+ // Pick lowest base index so `enforce` and user declaration order are preserved whenever unconstrained.
314
+ let bestPos = 0
315
+ for (let k = 1; k < ready.length; k++) {
316
+ if (ready[k]! < ready[bestPos]!)
317
+ bestPos = k
318
+ }
319
+ const u = ready.splice(bestPos, 1)[0]!
320
+ sorted.push(base[u]!)
321
+ for (const v of edges[u]!) {
322
+ inDegree[v] = (inDegree[v] ?? 0) - 1
323
+ if (inDegree[v] === 0)
324
+ ready.push(v)
325
+ }
326
+ }
327
+
328
+ if (sorted.length !== n) {
329
+ const stuck = base.filter((_, idx) => (inDegree[idx] ?? 0) > 0).map(p => p.name)
330
+ throw new Error(`kay: circular plugin \`after\` dependency involving: ${stuck.join(', ')}`)
331
+ }
332
+
333
+ // Validate that no plugin reads a ctx.locals key before another active plugin provides it.
334
+ const providerByLocal = new Map<string, { name: string, index: number }>()
335
+ for (let i = 0; i < sorted.length; i++) {
336
+ const plugin = sorted[i]!
337
+ for (const key of plugin.providesLocals ?? []) {
338
+ if (!providerByLocal.has(key))
339
+ providerByLocal.set(key, { name: plugin.name, index: i })
340
+ }
341
+ }
342
+
343
+ for (let i = 0; i < sorted.length; i++) {
344
+ const plugin = sorted[i]!
345
+ for (const key of plugin.readsLocals ?? []) {
346
+ const provider = providerByLocal.get(key)
347
+ if (provider !== undefined && provider.index > i) {
348
+ throw new Error(
349
+ `kay: plugin "${plugin.name}" reads ctx.locals.${key} before "${provider.name}" provides it. Add \`after: [${JSON.stringify(provider.name)}]\` or adjust plugin order.`,
350
+ )
351
+ }
352
+ }
353
+ }
354
+
355
+ return sorted
356
+ }
357
+
192
358
  let configReloadSeq = 0
193
359
 
194
360
  // In dev the query follows the file content: a save elsewhere reuses the loaded config and its plugin instances instead of re-running every factory.
@@ -1,12 +1,19 @@
1
1
  // Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
2
2
 
3
3
  import type { Cookies } from './cookies'
4
- import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
4
+ import type { KayLocals } from './index'
5
5
  import type { TrustProxy } from './security'
6
+ import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
6
7
  import { wantsJson } from './http'
7
8
  import { isTrustedOrigin } from './security'
8
9
  import { validateSchema } from './standard-schema'
9
10
 
11
+ declare module './index' {
12
+ interface KayLocals {
13
+ actionError?: ActionErrorFlash | undefined
14
+ }
15
+ }
16
+
10
17
  export const ACTION_ERROR_COOKIE = '__kay_action_err'
11
18
 
12
19
  const MAX_FLASH_COOKIE_BYTES = 3500
@@ -25,15 +32,15 @@ export interface ActionErrorFlash {
25
32
  values?: Record<string, string> | undefined
26
33
  }
27
34
 
28
- export function getActionError(locals?: Record<string, unknown>): ActionErrorFlash | undefined {
29
- return locals?.actionError as ActionErrorFlash | undefined
35
+ export function getActionError(locals?: KayLocals): ActionErrorFlash | undefined {
36
+ return locals?.actionError
30
37
  }
31
38
 
32
39
  export interface ActionContext {
33
40
  request: Request
34
41
  url: URL
35
42
  cookies: Cookies
36
- locals: Record<string, unknown>
43
+ locals: KayLocals
37
44
  ip?: string | undefined
38
45
  redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
39
46
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
@@ -135,7 +142,7 @@ function isJsonBody(request: Request): boolean {
135
142
  }
136
143
 
137
144
  // The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
138
- function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy): URL | undefined {
145
+ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy, requestUrl?: URL): URL | undefined {
139
146
  const referer = request.headers.get('referer')
140
147
  if (!referer)
141
148
  return undefined
@@ -146,7 +153,7 @@ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> |
146
153
  catch {
147
154
  return undefined
148
155
  }
149
- return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy) ? refUrl : undefined
156
+ return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy, requestUrl) ? refUrl : undefined
150
157
  }
151
158
 
152
159
  function topLevelKey(issue: StandardSchemaIssue): string | undefined {
@@ -318,7 +325,7 @@ export async function executeAction(
318
325
  checked = await retryWithFormArrays(act.schema, rawBody as Record<string, unknown>, checked)
319
326
  if (!checked.ok) {
320
327
  // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
321
- const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
328
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
322
329
  if (back !== undefined) {
323
330
  ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields), {
324
331
  httpOnly: true,
@@ -339,7 +346,7 @@ export async function executeAction(
339
346
  if (result instanceof Response)
340
347
  return result
341
348
 
342
- const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
349
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
343
350
  if (back !== undefined)
344
351
  return new Response(null, { status: 303, headers: { location: back.href } })
345
352
 
@@ -88,17 +88,85 @@ function hasNoTransform(cacheControl: string | null | undefined): boolean {
88
88
  return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
89
89
  }
90
90
 
91
- // Bun exposes no way to tell a streamed body from a buffered one without reading it, so its inspect output decides. Checked once at load: if the output no longer tells them apart, every body without a length counts as streamed and goes out uncompressed.
92
- const STREAM_MARK = 'ReadableStream {'
93
- const inspectSeesStreams = typeof Bun !== 'undefined'
94
- && Bun.inspect(new Response(new ReadableStream())).includes(STREAM_MARK)
95
- && !Bun.inspect(new Response('')).includes(STREAM_MARK)
91
+ const PENDING: unique symbol = Symbol('pending')
92
+ const MAX_BUFFERED_PROBE_CHUNKS = 32
93
+ const MAX_BUFFERED_PROBE_BYTES = 4 * 1024 * 1024
94
+
95
+ function concatChunks(chunks: readonly Uint8Array[], totalBytes: number): Uint8Array<ArrayBuffer> {
96
+ if (chunks.length === 1) {
97
+ const only = chunks[0]!
98
+ if (only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength)
99
+ return only as Uint8Array<ArrayBuffer>
100
+ }
101
+ const out = new Uint8Array(totalBytes)
102
+ let offset = 0
103
+ for (const chunk of chunks) {
104
+ out.set(chunk, offset)
105
+ offset += chunk.byteLength
106
+ }
107
+ return out
108
+ }
96
109
 
97
- function isStreamingBody(res: Response): boolean {
110
+ // Microtask-only probe: buffered bodies (string, TypedArray, JSON, closed streams) settle all chunks
111
+ // within microtasks and can be compressed; open streams stay pending and pass straight through unbuffered.
112
+ async function readBufferedOrPassThrough(
113
+ res: Response,
114
+ ): Promise<{ buffered: Uint8Array<ArrayBuffer> } | { passthrough: Response }> {
98
115
  const te = res.headers.get('transfer-encoding')
99
- if (te && te.toLowerCase().includes('chunked'))
100
- return true
101
- return !inspectSeesStreams || Bun.inspect(res).includes(STREAM_MARK)
116
+ if (te !== null && te.toLowerCase().includes('chunked'))
117
+ return { passthrough: res }
118
+ if (res.body === null)
119
+ return { buffered: new Uint8Array(0) }
120
+
121
+ const reader = res.body.getReader()
122
+ const chunks: Uint8Array[] = []
123
+ let totalBytes = 0
124
+ let pendingRead: ReturnType<typeof reader.read> | undefined
125
+
126
+ while (true) {
127
+ const readPromise = reader.read()
128
+ const tick = Promise.resolve().then(() => Promise.resolve()).then((): typeof PENDING => PENDING)
129
+ const outcome = await Promise.race([readPromise, tick])
130
+ if (outcome === PENDING) {
131
+ pendingRead = readPromise
132
+ break
133
+ }
134
+ if (outcome.done) {
135
+ reader.releaseLock()
136
+ return { buffered: concatChunks(chunks, totalBytes) }
137
+ }
138
+ chunks.push(outcome.value)
139
+ totalBytes += outcome.value.byteLength
140
+ if (chunks.length >= MAX_BUFFERED_PROBE_CHUNKS || totalBytes > MAX_BUFFERED_PROBE_BYTES)
141
+ break
142
+ }
143
+
144
+ let chunkIdx = 0
145
+ const stream = new ReadableStream<Uint8Array>({
146
+ async pull(controller) {
147
+ if (chunkIdx < chunks.length) {
148
+ controller.enqueue(chunks[chunkIdx++]!)
149
+ return
150
+ }
151
+ const next = pendingRead !== undefined ? pendingRead : reader.read()
152
+ pendingRead = undefined
153
+ const { done, value } = await next
154
+ if (done)
155
+ controller.close()
156
+ else
157
+ controller.enqueue(value)
158
+ },
159
+ cancel(reason) {
160
+ return reader.cancel(reason)
161
+ },
162
+ })
163
+ return {
164
+ passthrough: new Response(stream, {
165
+ status: res.status,
166
+ statusText: res.statusText,
167
+ headers: res.headers,
168
+ }),
169
+ }
102
170
  }
103
171
 
104
172
  function hasToken(haystack: string, token: string): boolean {
@@ -300,10 +368,6 @@ export async function maybeCompressResponse(
300
368
  return res
301
369
 
302
370
  const cl = res.headers.get('content-length')
303
- // Never buffer streaming responses that have no Content-Length (e.g. chunked streams, ReadableStream)
304
- if (cl === null && isStreamingBody(res))
305
- return res
306
-
307
371
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
308
372
  if (enc === undefined) {
309
373
  try {
@@ -324,7 +388,16 @@ export async function maybeCompressResponse(
324
388
  if (res.body === null)
325
389
  return res
326
390
 
327
- const raw = new Uint8Array(await res.arrayBuffer())
391
+ let raw: Uint8Array<ArrayBuffer>
392
+ if (cl !== null) {
393
+ raw = new Uint8Array(await res.arrayBuffer())
394
+ }
395
+ else {
396
+ const probe = await readBufferedOrPassThrough(res)
397
+ if ('passthrough' in probe)
398
+ return probe.passthrough
399
+ raw = probe.buffered
400
+ }
328
401
  const compressed = cache.compress(raw, enc)
329
402
  const headers = new Headers(res.headers)
330
403
  appendVaryAcceptEncoding(headers)
@@ -1,41 +1,108 @@
1
1
  // HTTP helpers, MIME table, RequestContext factory, and island tag scanner for Kay v2 server.
2
2
 
3
3
  import type { BuildManifest } from '../build/index'
4
- import type { KayPlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { KayChild } from '../jsx-runtime'
5
+ import type { ServerRuntimeConfig } from '../plugins/index'
5
6
  import type { Cookies } from './cookies'
6
- import type { SecurityHeadersOptions, TrustProxy } from './security'
7
+ import type { KayLocals } from './index'
8
+ import type { TrustProxy } from './security'
7
9
  import { CookieStore } from './cookies'
8
10
  import { nodeEnv } from './env'
9
11
  import { getClientIp, isHttpsRequest } from './security'
10
12
 
11
13
  export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
12
14
 
13
- export interface ServerOptions {
15
+ const NOT_FOUND_SYMBOL = Symbol.for('kay.notFound')
16
+ declare const NOT_FOUND_BRAND: unique symbol
17
+
18
+ export interface NotFoundResult {
19
+ readonly [NOT_FOUND_BRAND]: true
20
+ }
21
+
22
+ /** Return (or throw) from `load()` to render `_404.tsx` with HTTP status 404. */
23
+ export function notFound(): NotFoundResult {
24
+ return { [NOT_FOUND_SYMBOL]: true } as unknown as NotFoundResult
25
+ }
26
+
27
+ export function isNotFound(value: unknown): value is NotFoundResult {
28
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
29
+ }
30
+
31
+ type SegmentParam<Seg extends string> =
32
+ Seg extends `[...${infer Name}]`
33
+ ? { [K in Name]: string }
34
+ : Seg extends `[${infer Name}]`
35
+ ? { [K in Name]: string }
36
+ : Seg extends `*${infer Name}`
37
+ ? { [K in Name extends '' ? 'rest' : Name]: string }
38
+ : Seg extends `:${infer Name}`
39
+ ? { [K in Name]: string }
40
+ : unknown
41
+
42
+ type MergeParams<A, B> = {
43
+ [K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never
44
+ }
45
+
46
+ type ExtractRouteParamsRec<Path extends string, Acc = {}> =
47
+ Path extends `${infer Seg}/${infer Rest}`
48
+ ? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
49
+ : Path extends ''
50
+ ? Acc
51
+ : MergeParams<Acc, SegmentParam<Path>>
52
+
53
+ /** Extracts typed route params from a Kay route path (`'/notices/[id]'` -> `{ id: string }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
54
+ export type ExtractRouteParams<Path extends string> =
55
+ string extends Path
56
+ ? Record<string, string>
57
+ : ExtractRouteParamsRec<Path>
58
+
59
+ export type LoaderFn = (...args: never[]) => unknown
60
+
61
+ /** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
62
+ export type LoaderData<T extends LoaderFn> = Exclude<Awaited<ReturnType<T>>, Response | NotFoundResult>
63
+
64
+ type InferLoaderParams<T extends LoaderFn> =
65
+ Parameters<T> extends [ctx: { params: infer P }, ...unknown[]]
66
+ ? P
67
+ : Record<string, string>
68
+
69
+ /** Props passed to a Kay route page component. Pass `typeof load` to infer `data` (and `params` when `load` uses `RouteContext<Path>`), or a route path string when there is no `load`. */
70
+ export type PageProps<
71
+ TLoadOrPath extends LoaderFn | string | undefined = undefined,
72
+ TPath extends string = string,
73
+ > = {
74
+ params: TLoadOrPath extends string
75
+ ? ExtractRouteParams<TLoadOrPath>
76
+ : string extends TPath
77
+ ? (TLoadOrPath extends LoaderFn ? InferLoaderParams<TLoadOrPath> : Record<string, string>)
78
+ : ExtractRouteParams<TPath>
79
+ locals: KayLocals
80
+ url: URL
81
+ } & (TLoadOrPath extends LoaderFn ? { data: LoaderData<TLoadOrPath> } : { data?: undefined })
82
+
83
+ /** Props passed to a Kay `_layout.tsx` component. */
84
+ export interface LayoutProps<Path extends string = string> {
85
+ children: KayChild
86
+ params: ExtractRouteParams<Path>
87
+ locals: KayLocals
88
+ url: URL
89
+ }
90
+
91
+ export interface ServerOptions extends ServerRuntimeConfig {
14
92
  root: string
15
93
  outDir?: string | undefined
16
- assetPrefix?: string | undefined
17
94
  port?: number | undefined
18
- lang?: string | undefined
19
- security?: SecurityHeadersOptions | false | undefined
20
- trustedOrigins?: string[] | undefined
21
- trustProxy?: TrustProxy | undefined
22
- maxRequestBodySize?: number | undefined
23
- /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
24
- streamTimeout?: number | undefined
25
- compress?: boolean | undefined
26
95
  dev?: boolean | undefined
27
- onError?: ((info: ServerErrorInfo) => void) | undefined
28
- plugins?: KayPlugin[] | undefined
29
96
  /** @internal Imports a built server module by absolute path; `kay dev` passes one that keeps unchanged modules loaded. */
30
97
  importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
31
98
  }
32
99
 
33
- export interface RequestContext {
100
+ export interface RequestContext<Params = Record<string, string>> {
34
101
  request: Request
35
102
  url: URL
36
- params: Record<string, string>
103
+ params: Params
37
104
  cookies: Cookies
38
- locals: Record<string, unknown>
105
+ locals: KayLocals
39
106
  ip?: string | undefined
40
107
  json: (data: unknown, init?: ResponseInit) => Response
41
108
  text: (body: string, init?: ResponseInit) => Response
@@ -43,6 +110,9 @@ export interface RequestContext {
43
110
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
44
111
  }
45
112
 
113
+ /** `RequestContext` with `params` inferred from a Kay route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
114
+ export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
115
+
46
116
  export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
47
117
 
48
118
  export interface KayApp {
@@ -54,29 +124,18 @@ export interface KayApp {
54
124
 
55
125
  export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
56
126
 
57
- export interface EmbeddedServerConfig {
127
+ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
58
128
  manifest: BuildManifest
59
129
  modules: Record<string, unknown>
60
130
  assets: Record<string, EmbeddedBody>
61
131
  publicAssets?: Record<string, EmbeddedBody> | undefined
62
132
  publicEtags?: Record<string, string> | undefined
63
- prerendered: Record<string, string>
133
+ prerendered?: Record<string, string> | undefined
64
134
  prerenderedFiles?: Record<string, string> | undefined
65
135
  root?: string | undefined
66
136
  outDir?: string | undefined
67
137
  publicDir?: string | undefined
68
- assetPrefix?: string | undefined
69
- lang?: string | undefined
70
- security?: SecurityHeadersOptions | false | undefined
71
- trustedOrigins?: string[] | undefined
72
- trustProxy?: TrustProxy | undefined
73
- maxRequestBodySize?: number | undefined
74
- /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
75
- streamTimeout?: number | undefined
76
- compress?: boolean | undefined
77
138
  dev?: boolean | undefined
78
- onError?: ((info: ServerErrorInfo) => void) | undefined
79
- plugins?: KayPlugin[] | undefined
80
139
  }
81
140
 
82
141
  export const MIME: Record<string, string> = {