@kayjs/kay 2.0.0-beta.0 → 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 +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  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 +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  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 +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  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 +114 -18
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +2 -1
  55. package/src/unrenderable.ts +35 -0
package/src/dom/island.ts CHANGED
@@ -5,21 +5,24 @@ import { hydrate, mount } from './index'
5
5
  declare const KAY_DEFERRED: boolean | undefined
6
6
  declare const KAY_CLIENT_ONLY: boolean | undefined
7
7
 
8
+ const REVIVERS: Record<string, (v: never) => unknown> = {
9
+ __proto__: null as never,
10
+ D: (v: string) => new Date(v),
11
+ S: (v: unknown[]) => new Set(v),
12
+ M: (v: [unknown, unknown][]) => new Map(v),
13
+ U: (v: string) => new URL(v),
14
+ R: ([src, flags]: [string, string]) => new RegExp(src, flags),
15
+ B: (v: string) => BigInt(v),
16
+ }
17
+
8
18
  export function parseIslandProps(raw: string): Record<string, unknown> {
9
19
  if (!raw.includes('"__k":'))
10
20
  return JSON.parse(raw) as Record<string, unknown>
11
21
  return JSON.parse(raw, (_k, v: unknown) => {
12
22
  if (v !== null && typeof v === 'object' && '__k' in v && 'v' in v) {
13
- const tagged = v as { __k: string, v: unknown }
14
- if (tagged.__k === 'D') return new Date(tagged.v as string)
15
- if (tagged.__k === 'S') return new Set(tagged.v as unknown[])
16
- if (tagged.__k === 'M') return new Map(tagged.v as [unknown, unknown][])
17
- if (tagged.__k === 'U') return new URL(tagged.v as string)
18
- if (tagged.__k === 'R') {
19
- const [src, flags] = tagged.v as [string, string]
20
- return new RegExp(src, flags)
21
- }
22
- if (tagged.__k === 'B') return BigInt(tagged.v as string)
23
+ const revive = REVIVERS[(v as { __k: string }).__k]
24
+ if (revive !== undefined)
25
+ return revive((v as { v: never }).v)
23
26
  }
24
27
  return v
25
28
  }) as Record<string, unknown>
@@ -27,6 +30,40 @@ export function parseIslandProps(raw: string): Record<string, unknown> {
27
30
 
28
31
  type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
29
32
 
33
+ /** Finds this island's own `<kay-slot>` without descending into nested `<kay-island>` boundaries. */
34
+ function findOwnSlot(root: Element): Element | null {
35
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
36
+ const tag = child.tagName
37
+ if (tag === 'KAY-SLOT')
38
+ return child
39
+ if (tag === 'KAY-ISLAND')
40
+ continue
41
+ const nested = findOwnSlot(child)
42
+ if (nested !== null)
43
+ return nested
44
+ }
45
+ return null
46
+ }
47
+
48
+ function isAllowedChunkUrl(chunk: string): boolean {
49
+ if (chunk.startsWith('//'))
50
+ return false
51
+ if (chunk.startsWith('/'))
52
+ return true
53
+ if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
54
+ try {
55
+ const parsed = new URL(chunk, location.href)
56
+ return parsed.origin === location.origin
57
+ }
58
+ catch {
59
+ return false
60
+ }
61
+ }
62
+ return !/^(?:javascript|data|vbscript):/i.test(chunk)
63
+ }
64
+
65
+ let clientIslandIdSeq = 0
66
+
30
67
  export function defineIslandElement(): void {
31
68
  if (typeof customElements === 'undefined' || customElements.get('kay-island'))
32
69
  return
@@ -51,12 +88,11 @@ export function defineIslandElement(): void {
51
88
  const h = this.getAttribute('h')
52
89
  if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
53
90
  if (h === 'visible') {
54
- const target = this.firstElementChild ?? this
91
+ const first = this.firstElementChild
92
+ const target = first !== null && first.tagName !== 'SCRIPT' ? first : this
55
93
  const io = new IntersectionObserver((entries) => {
56
- if (entries.some(e => e.isIntersecting)) {
57
- this._clearStrategy()
94
+ if (entries.some(e => e.isIntersecting))
58
95
  void this._l(false, token)
59
- }
60
96
  }, { rootMargin: '200px' })
61
97
  this._c = () => io.disconnect()
62
98
  io.observe(target)
@@ -64,18 +100,13 @@ export function defineIslandElement(): void {
64
100
  }
65
101
  if (h === 'idle') {
66
102
  const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
103
+ const run = () => void this._l(false, token)
67
104
  if (g.requestIdleCallback) {
68
- const id = g.requestIdleCallback(() => {
69
- this._c = undefined
70
- void this._l(false, token)
71
- })
105
+ const id = g.requestIdleCallback(run)
72
106
  this._c = () => g.cancelIdleCallback?.(id)
73
107
  }
74
108
  else {
75
- const id = setTimeout(() => {
76
- this._c = undefined
77
- void this._l(false, token)
78
- }, 1)
109
+ const id = setTimeout(run, 1)
79
110
  this._c = () => clearTimeout(id)
80
111
  }
81
112
  return
@@ -85,11 +116,7 @@ export function defineIslandElement(): void {
85
116
  const stop = () => {
86
117
  for (const e of evs) this.removeEventListener(e, go, true)
87
118
  }
88
- const go = () => {
89
- this._c = undefined
90
- stop()
91
- void this._l(false, token)
92
- }
119
+ const go = () => void this._l(false, token)
93
120
  for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
94
121
  this._c = stop
95
122
  return
@@ -101,10 +128,8 @@ export function defineIslandElement(): void {
101
128
  }
102
129
  else {
103
130
  const go = () => {
104
- if (mq.matches) {
105
- this._clearStrategy()
131
+ if (mq.matches)
106
132
  void this._l(false, token)
107
- }
108
133
  }
109
134
  mq.addEventListener('change', go)
110
135
  this._c = () => mq.removeEventListener('change', go)
@@ -132,7 +157,7 @@ export function defineIslandElement(): void {
132
157
  async _l(clientOnly: boolean, token: number): Promise<void> {
133
158
  this._clearStrategy()
134
159
  const chunk = this.getAttribute('c')
135
- if (!chunk || token !== this._t || !this.isConnected || this._d !== undefined)
160
+ if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined)
136
161
  return
137
162
 
138
163
  let dispose: (() => void) | undefined
@@ -141,15 +166,25 @@ export function defineIslandElement(): void {
141
166
  if (!this.isConnected || token !== this._t || this._d !== undefined)
142
167
  return
143
168
 
144
- const p = this.getAttribute('p')
145
- const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
146
- const slot = this.querySelector('kay-slot')
169
+ let props: Record<string, unknown> = {}
170
+ const ps = this.lastElementChild
171
+ if (ps !== null && ps.tagName === 'SCRIPT' && ps.getAttribute('type') === 'application/json') {
172
+ props = parseIslandProps(ps.textContent || '{}')
173
+ ps.remove()
174
+ }
175
+ else {
176
+ const p = this.getAttribute('p')
177
+ if (p)
178
+ props = parseIslandProps(p)
179
+ }
180
+ const slot = findOwnSlot(this)
147
181
  if (slot !== null)
148
182
  props.children = slot
183
+ const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
149
184
  const render = () => mod.default(props)
150
185
  dispose = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
151
- ? mount(this, render)
152
- : hydrate(this, render)
186
+ ? mount(this, render, idPrefix)
187
+ : hydrate(this, render, idPrefix)
153
188
  if (!this.isConnected || token !== this._t) {
154
189
  dispose()
155
190
  return
package/src/dom/loop.ts CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  import type { Owner, Signal } from '../reactivity/index'
5
5
  import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
6
- import { claimLoop } from './index'
6
+ import { claimLoop, skipRange } from './index'
7
7
 
8
8
  interface Row<T> {
9
9
  key: unknown
@@ -16,6 +16,16 @@ interface Row<T> {
16
16
  const EMPTY: readonly never[] = []
17
17
  const EMPTY_NUMS: number[] = []
18
18
 
19
+ // A new rows array holding the kept prefix and suffix of the old one, with room for the middle.
20
+ function keepEnds<T>(rows: Row<T>[], start: number, oldEnd: number, newEnd: number, nextLen: number): Row<T>[] {
21
+ const result = new Array<Row<T>>(nextLen)
22
+ for (let i = 0; i < start; i++)
23
+ result[i] = rows[i]!
24
+ for (let i = newEnd; i < nextLen; i++)
25
+ result[i] = rows[oldEnd + (i - newEnd)]!
26
+ return result
27
+ }
28
+
19
29
  export function loop<T>(
20
30
  parent: Node,
21
31
  marker: Node | null,
@@ -27,6 +37,7 @@ export function loop<T>(
27
37
  const parentOwner = getOwner()
28
38
  const needsIndex = renderRow.length >= 2
29
39
  let rows: Row<T>[] = []
40
+ let firstRun = true
30
41
  if (parentOwner !== undefined) {
31
42
  onCleanup(() => {
32
43
  rows = []
@@ -42,6 +53,18 @@ export function loop<T>(
42
53
  }
43
54
 
44
55
  effect(() => {
56
+ let startMarker: Node | null | undefined
57
+ if (firstRun) {
58
+ firstRun = false
59
+ if (marker !== null && marker.nodeType === 8 && (marker as Comment).data === 'k[') {
60
+ const close = skipRange(marker)
61
+ if (close !== null) {
62
+ startMarker = marker
63
+ marker = close
64
+ }
65
+ }
66
+ }
67
+
45
68
  const list = each()
46
69
  const next = list === false || list == null ? EMPTY : list
47
70
  const nextLen = next.length
@@ -73,7 +96,7 @@ export function loop<T>(
73
96
  const item = next[i]!
74
97
  created[i] = makeRow(item, i, keyFn(item, i))
75
98
  }
76
- }, skip)) {
99
+ }, skip, startMarker)) {
77
100
  rows = created
78
101
  return
79
102
  }
@@ -129,10 +152,7 @@ export function loop<T>(
129
152
  // Fast path 4: Pure insertion (e.g. append 1,000 rows)
130
153
  if (start === oldEnd) {
131
154
  const addCount = newEnd - start
132
- const result = new Array<Row<T>>(nextLen)
133
- for (let i = 0; i < start; i++)
134
- result[i] = rows[i]!
135
-
155
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
136
156
  const frag = document.createDocumentFragment()
137
157
  for (let i = 0; i < addCount; i++) {
138
158
  const idx = start + i
@@ -142,9 +162,6 @@ export function loop<T>(
142
162
  frag.appendChild(row.node)
143
163
  }
144
164
  parent.insertBefore(frag, after)
145
-
146
- for (let i = newEnd; i < nextLen; i++)
147
- result[i] = rows[oldEnd + (i - newEnd)]!
148
165
  rows = result
149
166
  return
150
167
  }
@@ -156,12 +173,7 @@ export function loop<T>(
156
173
  disposeOwner(row.owner)
157
174
  parent.removeChild(row.node)
158
175
  }
159
- const result = new Array<Row<T>>(nextLen)
160
- for (let i = 0; i < start; i++)
161
- result[i] = rows[i]!
162
- for (let i = newEnd; i < nextLen; i++)
163
- result[i] = rows[oldEnd + (i - newEnd)]!
164
- rows = result
176
+ rows = keepEnds(rows, start, oldEnd, newEnd, nextLen)
165
177
  return
166
178
  }
167
179
 
@@ -171,11 +183,7 @@ export function loop<T>(
171
183
  oldMap.set(rows[i]!.key, i)
172
184
 
173
185
  const midLen = newEnd - start
174
- const result = new Array<Row<T>>(nextLen)
175
- for (let i = 0; i < start; i++)
176
- result[i] = rows[i]!
177
- for (let i = newEnd; i < nextLen; i++)
178
- result[i] = rows[oldEnd + (i - newEnd)]!
186
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
179
187
 
180
188
  const used = new Uint8Array(oldEnd - start)
181
189
  let reused = 0
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { createContext, Head, provideContext, Suspense, useContext, useId } from './context'
2
+ export type { Context } from './context'
1
3
  export {
2
4
  batch,
3
5
  computed,
@@ -13,7 +15,6 @@ export type { Owner, ReadonlySignal, Signal } from './reactivity/index'
13
15
  export { selector } from './reactivity/selector'
14
16
  export type { Selector } from './reactivity/selector'
15
17
  export { snapshot, store } from './reactivity/store'
16
- export { Head, Suspense } from './ssr/context'
17
18
  export type { Component, Html, HydrateStrategy, KayChild } from './jsx-runtime'
18
19
 
19
20
  import type { Component, HydrateStrategy } from './jsx-runtime'
@@ -20,8 +20,12 @@ export type KayChild =
20
20
  | Node
21
21
  | KayChild[]
22
22
 
23
+ declare const htmlBrand: unique symbol
24
+
25
+ /** HTML kay injects unescaped; only `raw()` makes one, so a plain `{ __html }` object is not an Html. */
23
26
  export interface Html {
24
27
  readonly __html: string
28
+ readonly [htmlBrand]: true
25
29
  }
26
30
 
27
31
  export type Component<P = Record<string, unknown>> = (props: P) => KayChild | Promise<KayChild>
@@ -58,6 +62,13 @@ interface CommonAttributes {
58
62
  key?: string | number | undefined
59
63
  ref?: ((el: Element) => void) | undefined
60
64
  $hydrate?: HydrateStrategy | undefined
65
+ innerHTML?: string | Html | null | undefined
66
+ // Spellings from React and Solid that kay refuses at compile time, refused here first.
67
+ dangerouslySetInnerHTML?: never
68
+ classList?: never
69
+ defaultValue?: never
70
+ defaultChecked?: never
71
+ onDoubleClick?: never
61
72
  // Events
62
73
  onClick?: ((e: MouseEvent) => void) | undefined
63
74
  onDblClick?: ((e: MouseEvent) => void) | undefined
@@ -0,0 +1,57 @@
1
+ // Per-build / per-server scoped runtime context (AsyncLocalStorage-backed, zero mutable process globals).
2
+
3
+ import { AsyncLocalStorage } from 'node:async_hooks'
4
+
5
+ export interface AppRuntimeContext {
6
+ readonly root: string
7
+ readonly outDir: string
8
+ readonly publicDir: string
9
+ readonly assetPrefix: string
10
+ readonly dev: boolean
11
+ provide<T>(key: string, value: T): void
12
+ inject<T>(key: string): T | undefined
13
+ registerPublicFile(relPath: string): void
14
+ }
15
+
16
+ export interface CreateAppContextOptions {
17
+ root: string
18
+ outDir: string
19
+ publicDir: string
20
+ assetPrefix: string
21
+ dev: boolean
22
+ onRegisterPublicFile?: ((relPath: string) => void) | undefined
23
+ }
24
+
25
+ const APP_STORAGE_KEY = Symbol.for('kay.app.storage')
26
+ const appStorage: AsyncLocalStorage<AppRuntimeContext> = (
27
+ (globalThis as Record<symbol, AsyncLocalStorage<AppRuntimeContext> | undefined>)[APP_STORAGE_KEY]
28
+ ??= new AsyncLocalStorage<AppRuntimeContext>()
29
+ )
30
+
31
+ export function createAppContext(options: CreateAppContextOptions): AppRuntimeContext {
32
+ const services = new Map<string, unknown>()
33
+ return {
34
+ root: options.root,
35
+ outDir: options.outDir,
36
+ publicDir: options.publicDir,
37
+ assetPrefix: options.assetPrefix,
38
+ dev: options.dev,
39
+ provide<T>(key: string, value: T): void {
40
+ services.set(key, value)
41
+ },
42
+ inject<T>(key: string): T | undefined {
43
+ return services.get(key) as T | undefined
44
+ },
45
+ registerPublicFile(relPath: string): void {
46
+ options.onRegisterPublicFile?.(relPath)
47
+ },
48
+ }
49
+ }
50
+
51
+ export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
52
+ return appStorage.run(ctx, fn)
53
+ }
54
+
55
+ export function getAppContext(): AppRuntimeContext | undefined {
56
+ return appStorage.getStore()
57
+ }
@@ -4,16 +4,26 @@
4
4
 
5
5
  import type { BunPlugin } from 'bun'
6
6
  import type { RouteManifestEntry } from '../build/index'
7
+ import type { ActionResult, ServerAction } from '../server/action'
7
8
  import type { Middleware, RequestContext } from '../server/index'
8
- import type { SecurityHeadersOptions } from '../server/security'
9
- import { existsSync } from 'node:fs'
9
+ import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
10
+ import type { AppRuntimeContext } from './context'
11
+ import { existsSync, readFileSync } from 'node:fs'
10
12
  import { join, resolve } from 'node:path'
13
+ import { createAppContext, getAppContext, runWithAppContext } from './context'
14
+
15
+ export { createAppContext, getAppContext, runWithAppContext } from './context'
16
+ export type { AppRuntimeContext, CreateAppContextOptions } from './context'
17
+
18
+ export type BuildPluginTarget = 'client' | 'server' | 'compile'
11
19
 
12
20
  export interface BuildPluginContext {
13
21
  readonly root: string
14
22
  readonly outDir: string
15
23
  readonly assetPrefix: string
16
24
  readonly minify: boolean
25
+ readonly isStatic: boolean
26
+ readonly dev: boolean
17
27
  readonly routes: readonly RouteManifestEntry[]
18
28
  /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
19
29
  emitAsset(relPath: string, content: string | Uint8Array): string
@@ -27,6 +37,35 @@ export interface BuildPluginContext {
27
37
  addHead(html: string): void
28
38
  /** Add raw HTML to <head> on a specific route path only. */
29
39
  addRouteHead(routePath: string, html: string): void
40
+ /** Register an explicit build-scoped service for other plugins or render-time helpers. */
41
+ provide<T>(key: string, value: T): void
42
+ /** Look up a build-scoped service registered by another plugin. */
43
+ inject<T>(key: string): T | undefined
44
+ /** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
45
+ setData(data: Record<string, unknown>): void
46
+ }
47
+
48
+ export interface FinalizeBuildContext {
49
+ readonly root: string
50
+ readonly outDir: string
51
+ readonly assetPrefix: string
52
+ readonly minify: boolean
53
+ readonly isStatic: boolean
54
+ readonly dev: boolean
55
+ /** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
56
+ readonly routes: readonly RouteManifestEntry[]
57
+ /** Relative paths of all public files known so far (including files registered during prerender). */
58
+ readonly publicFiles: readonly string[]
59
+ /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
60
+ emitAsset(relPath: string, content: string | Uint8Array): string
61
+ /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
62
+ emitPublic(relPath: string, content: string | Uint8Array): string
63
+ /** Register a build-scoped service. */
64
+ provide<T>(key: string, value: T): void
65
+ /** Look up a build-scoped service. */
66
+ inject<T>(key: string): T | undefined
67
+ /** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
68
+ setData(data: Record<string, unknown>): void
30
69
  }
31
70
 
32
71
  export interface CheckPluginContext {
@@ -37,17 +76,45 @@ export interface CheckPluginContext {
37
76
  }
38
77
 
39
78
  export interface PluginRouteOptions {
40
- /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks). */
79
+ /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
41
80
  csrf?: boolean | undefined
81
+ /** Additional trusted origins merged with `KayConfig.trustedOrigins` for this route's CSRF check. */
82
+ trustedOrigins?: readonly string[] | undefined
83
+ /** Override `KayConfig.trustProxy` for this route's CSRF check. */
84
+ trustProxy?: TrustProxy | undefined
85
+ }
86
+
87
+ export interface MiddlewareOptions {
88
+ /** `'all'` (default) runs on every route; `'dynamic'` skips static/prerendered fast paths; a string prefix scopes to matching pathnames. */
89
+ scope?: 'all' | 'dynamic' | string | undefined
42
90
  }
43
91
 
44
92
  export interface ServerPluginAPI {
45
- /** Register global middleware that runs before route handlers. */
46
- use(middleware: Middleware): void
93
+ readonly root: string
94
+ readonly outDir: string
95
+ readonly assetPrefix: string
96
+ readonly dev: boolean
97
+ /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
98
+ readonly trustProxy: TrustProxy
99
+ readonly trustedOrigins: readonly string[]
100
+ /** Readonly runtime config forwarded from `kay.config.ts` (minus build-only keys). */
101
+ readonly config?: Readonly<Record<string, unknown>> | undefined
102
+ /** Register global (or scoped) middleware that runs before route handlers. */
103
+ use(middleware: Middleware, options?: MiddlewareOptions): void
47
104
  /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
48
105
  route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
49
106
  /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
50
107
  rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
108
+ /** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
109
+ provide<T>(key: string, value: T): void
110
+ /** Look up a server-scoped service registered by another plugin. */
111
+ inject<T>(key: string): T | undefined
112
+ /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
113
+ getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
114
+ /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
115
+ onShutdown(fn: () => void | Promise<void>): void
116
+ /** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
117
+ invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
51
118
  }
52
119
 
53
120
  export interface ServerErrorInfo {
@@ -58,19 +125,23 @@ export interface ServerErrorInfo {
58
125
 
59
126
  export interface KayPlugin {
60
127
  name: string
61
- /** Register server routes, global middleware, or URL rewrites. */
128
+ /** Register server routes, global middleware, URL rewrites, or runtime services. */
62
129
  server?: (api: ServerPluginAPI) => void | Promise<void>
130
+ /** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
131
+ dispose?: () => void | Promise<void>
63
132
  /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
64
133
  onError?: (info: ServerErrorInfo) => void
65
134
  /** Build hook run after route compilation, before prerender / --static / --compile. */
66
135
  build?: (ctx: BuildPluginContext) => void | Promise<void>
67
- /** Code transform run during client & server compilation. */
136
+ /** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
137
+ afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
138
+ /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
68
139
  transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
69
- /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). */
70
- bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean }) => BunPlugin[]) | undefined
140
+ /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
141
+ bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
71
142
  /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
72
143
  css?: string[] | undefined
73
- /** Post-process rendered HTML before sending. */
144
+ /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
74
145
  transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
75
146
  /** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
76
147
  prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
@@ -93,8 +164,10 @@ export interface KayConfig {
93
164
  assetPrefix?: string | undefined
94
165
  security?: SecurityHeadersOptions | false | undefined
95
166
  trustedOrigins?: string[] | undefined
96
- trustProxy?: boolean | undefined
167
+ trustProxy?: TrustProxy | undefined
97
168
  maxRequestBodySize?: number | undefined
169
+ /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
170
+ streamTimeout?: number | undefined
98
171
  compress?: boolean | undefined
99
172
  onError?: ((info: ServerErrorInfo) => void) | undefined
100
173
  plugins?: KayPlugin[] | undefined
@@ -104,22 +177,45 @@ export function defineConfig(config: KayConfig): KayConfig {
104
177
  return config
105
178
  }
106
179
 
180
+ /** 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'> {
182
+ if (config === undefined)
183
+ return {}
184
+ const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, ...runtime } = config
185
+ return runtime
186
+ }
187
+
107
188
  export function definePlugin(plugin: KayPlugin): KayPlugin {
108
189
  return plugin
109
190
  }
110
191
 
111
- const KAY_ROOT_KEY = Symbol.for('kay.root')
112
192
  let configReloadSeq = 0
113
193
 
114
- export async function loadConfig(root: string, options?: { fresh?: boolean }): Promise<KayConfig> {
194
+ // 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.
195
+ function configSpecifier(configPath: string, fresh: boolean): string {
196
+ if (fresh)
197
+ return `${configPath}?v=fresh-${++configReloadSeq}`
198
+ if (process.env.KAY_DEV === '1')
199
+ return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
200
+ return configPath
201
+ }
202
+
203
+ export async function loadConfig(root: string, options?: { fresh?: boolean, appContext?: AppRuntimeContext }): Promise<KayConfig> {
115
204
  const absRoot = resolve(root)
116
- ;(globalThis as Record<symbol, unknown>)[KAY_ROOT_KEY] = absRoot
117
205
  const configPath = join(absRoot, 'kay.config.ts')
118
206
  if (!existsSync(configPath))
119
207
  return {}
120
- const spec = options?.fresh || process.env.KAY_DEV === '1'
121
- ? `${configPath}?v=${++configReloadSeq}-${Date.now()}`
122
- : configPath
123
- const mod = await import(spec) as { default?: KayConfig }
208
+ const spec = configSpecifier(configPath, options?.fresh === true)
209
+ const active = options?.appContext ?? getAppContext()
210
+ const ctx = active !== undefined && active.root === absRoot
211
+ ? active
212
+ : createAppContext({
213
+ root: absRoot,
214
+ outDir: join(absRoot, 'dist'),
215
+ publicDir: join(absRoot, 'dist', 'public'),
216
+ assetPrefix: '/_kay',
217
+ dev: process.env.KAY_DEV === '1',
218
+ })
219
+ const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
124
220
  return mod.default ?? {}
125
221
  }