@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/context.ts ADDED
@@ -0,0 +1,120 @@
1
+ // Universal component context (createContext / useContext) and hydration-safe useId().
2
+ // Browser-pure: zero Node imports. SSR wires its per-request AsyncLocalStorage bridge via registerServerContextBridge().
3
+
4
+ import type { KayChild } from './jsx-runtime'
5
+ import type { IdScope, Owner } from './reactivity/index'
6
+ import { createOwner, getOwner, runWithOwner } from './reactivity/index'
7
+
8
+ export interface ServerContextBridge {
9
+ getContext(key: symbol): { found: true, value: unknown } | undefined
10
+ runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
11
+ nextId(): string | undefined
12
+ head(props: { children?: KayChild }): KayChild
13
+ suspense(props: { fallback?: KayChild, error?: KayChild | ((error: unknown) => KayChild), children?: KayChild | Promise<KayChild> }): KayChild
14
+ }
15
+
16
+ const BRIDGE_KEY = Symbol.for('kay.server.context.bridge')
17
+
18
+ function getServerBridge(): ServerContextBridge | undefined {
19
+ return (globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY]
20
+ }
21
+
22
+ /** Internal: registered by `kay/ssr` on the server so `Head`, `Suspense`, `useContext`, and `useId` stay request-scoped without pulling `node:async_hooks` into client bundles. */
23
+ export function registerServerContextBridge(bridge: ServerContextBridge): void {
24
+ ;(globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY] = bridge
25
+ }
26
+
27
+ /** Collects document `<head>` tags during SSR; no-op in the browser. */
28
+ export function Head(props: { children?: KayChild }): KayChild {
29
+ const bridge = getServerBridge()
30
+ return bridge !== undefined ? bridge.head(props) : null
31
+ }
32
+
33
+ /** Streaming SSR boundary: flushes `fallback` immediately and streams resolved async children. */
34
+ export function Suspense(props: { fallback?: KayChild, error?: KayChild | ((error: unknown) => KayChild), children?: KayChild | Promise<KayChild> }): KayChild {
35
+ const bridge = getServerBridge()
36
+ if (bridge !== undefined)
37
+ return bridge.suspense(props)
38
+ return props.children instanceof Promise ? (props.fallback ?? null) : (props.children ?? null)
39
+ }
40
+
41
+ export interface Context<T> {
42
+ readonly id: symbol
43
+ readonly defaultValue: T
44
+ Provider: (props: { value: T, children?: KayChild | (() => KayChild) }) => KayChild
45
+ }
46
+
47
+ function findOwnerContext(owner: Owner | undefined, key: symbol): { found: true, value: unknown } | undefined {
48
+ for (let o = owner; o !== undefined; o = o.o) {
49
+ if (o.cx !== undefined && o.cx.has(key))
50
+ return { found: true, value: o.cx.get(key) }
51
+ }
52
+ return undefined
53
+ }
54
+
55
+ function findOwnerIdScope(owner: Owner | undefined): IdScope | undefined {
56
+ for (let o = owner; o !== undefined; o = o.o) {
57
+ if (o.id !== undefined)
58
+ return o.id
59
+ }
60
+ return undefined
61
+ }
62
+
63
+ /** Run `fn` with `ctx` bound to `value` on both server (SSR) and browser (reactive owner tree). */
64
+ export function provideContext<T, R>(ctx: Context<T>, value: T, fn: () => R): R {
65
+ const owner = getOwner()
66
+ if (owner !== undefined) {
67
+ const scope = createOwner(owner)
68
+ ;(scope.cx ??= new Map()).set(ctx.id, value)
69
+ return runWithOwner(scope, fn)
70
+ }
71
+ const bridge = getServerBridge()
72
+ if (bridge !== undefined)
73
+ return bridge.runWithContext(ctx.id, value, fn)
74
+ return fn()
75
+ }
76
+
77
+ export function createContext<T>(defaultValue: T): Context<T> {
78
+ const id = Symbol('kay.context')
79
+ const ctx: Context<T> = {
80
+ id,
81
+ defaultValue,
82
+ Provider(props) {
83
+ return provideContext(ctx, props.value, () => {
84
+ const c = props.children
85
+ return typeof c === 'function' ? (c as () => KayChild)() : c
86
+ })
87
+ },
88
+ }
89
+ return ctx
90
+ }
91
+
92
+ export function useContext<T>(ctx: Context<T>): T {
93
+ const owner = getOwner()
94
+ if (owner !== undefined) {
95
+ const hit = findOwnerContext(owner, ctx.id)
96
+ if (hit !== undefined)
97
+ return hit.value as T
98
+ }
99
+ const bridge = getServerBridge()
100
+ if (bridge !== undefined) {
101
+ const hit = bridge.getContext(ctx.id)
102
+ if (hit !== undefined)
103
+ return hit.value as T
104
+ }
105
+ return ctx.defaultValue
106
+ }
107
+
108
+ let fallbackIdSeq = 0
109
+
110
+ /** Generates a deterministic, hydration-safe unique ID scoped to the current island or SSR request. */
111
+ export function useId(prefix = 'k'): string {
112
+ const scope = findOwnerIdScope(getOwner())
113
+ if (scope !== undefined)
114
+ return `${prefix}-${scope.p}${scope.n++}`
115
+ const bridge = getServerBridge()
116
+ const serverId = bridge?.nextId()
117
+ if (serverId !== undefined)
118
+ return `${prefix}-${serverId}`
119
+ return `${prefix}-g${fallbackIdSeq++}`
120
+ }
package/src/dev/index.ts CHANGED
@@ -1,11 +1,13 @@
1
- // kay dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, SSE error push, and live config reload.
1
+ // kay dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, streaming reload injection,
2
+ // SSE error push, and live config reload.
2
3
 
3
4
  import type { FSWatcher } from 'node:fs'
4
5
  import type { KayApp } from '../server/index'
5
- import { existsSync, rmSync, statSync, watch } from 'node:fs'
6
- import { join, resolve } from 'node:path'
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
7
+ import { dirname, join, relative, resolve } from 'node:path'
8
+ import { clearBuildCache } from '../build/graph'
7
9
  import { build, createBuildCache } from '../build/index'
8
- import { loadConfig } from '../plugins/index'
10
+ import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
9
11
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
10
12
  import { createServer, withCspHashes } from '../server/index'
11
13
 
@@ -17,31 +19,196 @@ export interface DevServerOptions {
17
19
  maxRequestBodySize?: number | undefined
18
20
  }
19
21
 
20
- const DEV_RELOAD_JS = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource('/_kay/dev-events');s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^="/_kay/"]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();`
21
- const DEV_RELOAD_SCRIPT = `<script>${DEV_RELOAD_JS}</script>`
22
- const DEV_RELOAD_SCRIPT_HASH = `'sha256-${new Bun.CryptoHasher('sha256').update(DEV_RELOAD_JS).digest('base64')}'`
22
+ function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
23
+ const prefix = assetPrefix.replace(/\/$/, '')
24
+ const eventsPath = `${prefix}/dev-events`
25
+ const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();`
26
+ const hash = `'sha256-${new Bun.CryptoHasher('sha256').update(js).digest('base64')}'`
27
+ return { script: `<script>${js}</script>`, hash, eventsPath }
28
+ }
23
29
 
24
- function renderErrorOverlay(errText: string): string {
30
+ function renderErrorOverlay(errText: string, reloadScript: string): string {
25
31
  const escaped = errText
26
32
  .replaceAll('&', '&amp;')
27
33
  .replaceAll('<', '&lt;')
28
34
  .replaceAll('>', '&gt;')
29
- return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Kay Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Kay Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${DEV_RELOAD_SCRIPT}</body></html>`
35
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Kay Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Kay Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${reloadScript}</body></html>`
36
+ }
37
+
38
+ type ChangeKind = 'css' | 'code' | 'full' | 'config'
39
+
40
+ // A source edit changes the bundled bytes; any other file (content, data, public/) may be read when a module loads.
41
+ const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|css)$/
42
+
43
+ function srcChangeKind(name: string): ChangeKind {
44
+ if (name.endsWith('.css') && !name.endsWith('.module.css'))
45
+ return 'css'
46
+ return CODE_FILE_RE.test(name) ? 'code' : 'full'
30
47
  }
31
48
 
32
- type ChangeKind = 'css' | 'full' | 'config'
49
+ // Injects the dev reload script into an HTML response while preserving streaming (<Suspense>).
50
+ function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: string): ReadableStream<Uint8Array> {
51
+ const decoder = new TextDecoder()
52
+ const encoder = new TextEncoder()
53
+ let injected = false
54
+ let tail = ''
55
+ const KEEP = 16 // enough to span a split `</body>` tag across chunk boundaries
56
+
57
+ return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
58
+ transform(chunk, controller) {
59
+ if (injected) {
60
+ controller.enqueue(chunk)
61
+ return
62
+ }
63
+ const text = tail + decoder.decode(chunk, { stream: true })
64
+ const idx = text.indexOf('</body>')
65
+ if (idx !== -1) {
66
+ injected = true
67
+ tail = ''
68
+ controller.enqueue(encoder.encode(`${text.slice(0, idx)}${reloadScript}${text.slice(idx)}`))
69
+ return
70
+ }
71
+ if (text.length > KEEP) {
72
+ const split = text.length - KEEP
73
+ controller.enqueue(encoder.encode(text.slice(0, split)))
74
+ tail = text.slice(split)
75
+ }
76
+ else {
77
+ tail = text
78
+ }
79
+ },
80
+ flush(controller) {
81
+ const rest = tail + decoder.decode()
82
+ if (injected) {
83
+ if (rest.length > 0)
84
+ controller.enqueue(encoder.encode(rest))
85
+ return
86
+ }
87
+ const idx = rest.indexOf('</body>')
88
+ if (idx !== -1)
89
+ controller.enqueue(encoder.encode(`${rest.slice(0, idx)}${reloadScript}${rest.slice(idx)}`))
90
+ else
91
+ controller.enqueue(encoder.encode(rest + reloadScript))
92
+ },
93
+ }))
94
+ }
95
+
96
+ // Bun never unloads a module, so each build's server files are copied into a generation store.
97
+ // If any non-chunk module that other entries may statically import changes (e.g. standalone actions), bump generation so static importers re-resolve cleanly.
98
+ function createModuleStore(storeRoot: string) {
99
+ const hashes = new Map<string, string>()
100
+ let generation = 0
101
+ let stale = false
102
+ const generationDir = (g: number): string => join(storeRoot, `g${g}`)
103
+ return {
104
+ reloadAll(): void {
105
+ stale = true
106
+ },
107
+ sync(serverDir: string, sharedRelFiles: ReadonlySet<string>): void {
108
+ const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
109
+ for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
110
+ if (!entry.isFile())
111
+ continue
112
+ const from = join(entry.parentPath, entry.name)
113
+ const rel = relative(serverDir, from).replaceAll('\\', '/')
114
+ const bytes = readFileSync(from)
115
+ const hash = Bun.hash(bytes).toString(36)
116
+ nextFiles.set(rel, { bytes, hash })
117
+ }
118
+
119
+ // If an already-loaded standalone action file (statically imported by routes) changed, bump generation so static importers re-resolve cleanly.
120
+ if (!stale && hashes.size > 0) {
121
+ for (const [rel, { hash }] of nextFiles) {
122
+ const prev = hashes.get(rel)
123
+ if (prev !== undefined && prev !== hash && sharedRelFiles.has(rel)) {
124
+ stale = true
125
+ break
126
+ }
127
+ }
128
+ }
129
+
130
+ if (stale) {
131
+ stale = false
132
+ hashes.clear()
133
+ generation++
134
+ // The previous generation stays for requests the old app is still serving.
135
+ rmSync(generationDir(generation - 2), { recursive: true, force: true })
136
+ }
137
+ const storeDir = generationDir(generation)
138
+ for (const [rel, { bytes, hash }] of nextFiles) {
139
+ if (hashes.get(rel) === hash)
140
+ continue
141
+ const to = join(storeDir, rel)
142
+ mkdirSync(dirname(to), { recursive: true })
143
+ writeFileSync(to, bytes)
144
+ hashes.set(rel, hash)
145
+ }
146
+ // Prune removed chunk files from current generation to avoid unbounded disk/map growth.
147
+ for (const rel of [...hashes.keys()]) {
148
+ if (!nextFiles.has(rel)) {
149
+ hashes.delete(rel)
150
+ rmSync(join(storeDir, rel), { force: true })
151
+ }
152
+ }
153
+ },
154
+ importFrom(serverDir: string) {
155
+ const storeDir = generationDir(generation)
156
+ return async (path: string): Promise<Record<string, unknown>> => {
157
+ const rel = relative(serverDir, path).replaceAll('\\', '/')
158
+ try {
159
+ return await import(`${join(storeDir, rel)}?v=${hashes.get(rel)}`)
160
+ }
161
+ catch (err) {
162
+ stale = true
163
+ throw err
164
+ }
165
+ }
166
+ },
167
+ }
168
+ }
33
169
 
34
170
  export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
35
171
  const prevKayDev = process.env.KAY_DEV
36
172
  process.env.KAY_DEV = '1'
37
173
  const root = resolve(options.root)
38
- const srcDir = resolve(root, 'src')
39
- const publicDir = resolve(root, 'public')
40
- const configPath = join(root, 'kay.config.ts')
41
174
  const devRoot = join(root, '.kay-dev')
42
- const port = options.port ?? 3000
175
+ const initialCfg = await loadConfig(root).catch((err) => {
176
+ console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
177
+ return {} as Awaited<ReturnType<typeof loadConfig>>
178
+ })
179
+ const assetPrefix = (initialCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
180
+ let reloadAssets = makeDevReloadAssets(assetPrefix)
181
+ const srcDir = resolve(root, 'src')
182
+ const routesDir = resolve(root, options.routesDir ?? initialCfg.routesDir ?? 'src/routes')
183
+ const publicDir = resolve(root, initialCfg.publicDir ?? 'public')
184
+ const port = options.port ?? initialCfg.port ?? 3000
43
185
  const hostname = options.hostname ?? '127.0.0.1'
44
186
  const buildCache = createBuildCache()
187
+ const modules = createModuleStore(join(devRoot, 'server'))
188
+ const watchers: FSWatcher[] = []
189
+ const watchedDirs = new Set<string>()
190
+ const pluginWatchers: FSWatcher[] = []
191
+ let activeAssetPrefix = assetPrefix
192
+
193
+ function refreshPluginWatchers(cfg: Awaited<ReturnType<typeof loadConfig>>): void {
194
+ for (const w of pluginWatchers)
195
+ w.close()
196
+ pluginWatchers.length = 0
197
+ const seen = new Set<string>(watchedDirs)
198
+ const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, dev: true })
199
+ for (const plugin of cfg.plugins ?? []) {
200
+ const paths = runWithAppContext(watchCtx, () =>
201
+ typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
202
+ for (const p of paths) {
203
+ const abs = resolve(root, p)
204
+ if (seen.has(abs) || !existsSync(abs))
205
+ continue
206
+ seen.add(abs)
207
+ const isDir = statSync(abs).isDirectory()
208
+ pluginWatchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
209
+ }
210
+ }
211
+ }
45
212
 
46
213
  let buildNum = 0
47
214
  let currentApp: KayApp | undefined
@@ -53,13 +220,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
53
220
  let pending = false
54
221
  let pendingCssOnly = true
55
222
  let pendingConfigReset = false
223
+ let pendingReloadAll = false
56
224
  let inFlight: Promise<void> | undefined
57
225
 
58
226
  const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
59
227
  const encoder = new TextEncoder()
60
228
 
61
- function broadcast(payload: string): void {
62
- const chunk = encoder.encode(`data: ${payload}\n\n`)
229
+ function pushToClients(chunk: Uint8Array): void {
63
230
  for (const c of clients) {
64
231
  try {
65
232
  c.enqueue(chunk)
@@ -70,20 +237,26 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
70
237
  }
71
238
  }
72
239
 
73
- async function runSingleBuild(cssOnly: boolean, resetCache: boolean): Promise<void> {
240
+ const broadcast = (payload: string): void => pushToClients(encoder.encode(`data: ${payload}\n\n`))
241
+
242
+ async function runSingleBuild(cssOnly: boolean, resetCache: boolean, reloadAll: boolean): Promise<void> {
74
243
  if (stopped)
75
244
  return
76
- if (resetCache) {
77
- buildCache.analyses.clear()
78
- buildCache.domCompiled.clear()
79
- buildCache.ssrCompiled.clear()
80
- }
81
245
  const hadError = lastError !== undefined
82
246
  const hadApp = currentApp !== undefined
83
247
  const n = ++buildNum
84
248
  const outDir = `.kay-dev/b${n}`
85
249
  const t0 = performance.now()
86
250
  try {
251
+ if (resetCache) {
252
+ clearBuildCache(buildCache)
253
+ const freshCfg = await loadConfig(root, { fresh: true })
254
+ activeAssetPrefix = (freshCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
255
+ reloadAssets = makeDevReloadAssets(activeAssetPrefix)
256
+ refreshPluginWatchers(freshCfg)
257
+ }
258
+ if (reloadAll)
259
+ modules.reloadAll()
87
260
  const manifest = await build({
88
261
  root,
89
262
  routesDir: options.routesDir,
@@ -91,9 +264,37 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
91
264
  minify: false,
92
265
  prerender: false,
93
266
  copyPublic: false,
267
+ dev: true,
94
268
  cache: buildCache,
95
269
  })
96
- currentApp = await createServer({ root, outDir })
270
+ if (stopped) {
271
+ rmSync(join(root, outDir), { recursive: true, force: true })
272
+ return
273
+ }
274
+ const serverDir = join(root, outDir, 'server')
275
+ const routeFiles = new Set(manifest.routes.map(r => r.file.replace(/^server\//, '')))
276
+ const sharedRelFiles = new Set<string>()
277
+ for (const a of manifest.actions) {
278
+ const rel = a.file.replace(/^server\//, '')
279
+ if (!routeFiles.has(rel))
280
+ sharedRelFiles.add(rel)
281
+ }
282
+ modules.sync(serverDir, sharedRelFiles)
283
+ const nextApp = await createServer({
284
+ root,
285
+ outDir,
286
+ dev: true,
287
+ compress: false,
288
+ importModule: modules.importFrom(serverDir),
289
+ })
290
+ if (stopped) {
291
+ await nextApp.dispose?.()
292
+ rmSync(join(root, outDir), { recursive: true, force: true })
293
+ return
294
+ }
295
+ const prevApp = currentApp
296
+ currentApp = nextApp
297
+ void prevApp?.dispose?.()
97
298
  lastError = undefined
98
299
  if (n > 2)
99
300
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
@@ -104,6 +305,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
104
305
  broadcast('reload')
105
306
  }
106
307
  catch (err) {
308
+ if (stopped)
309
+ return
107
310
  lastError = err instanceof Error ? err.stack ?? err.message : String(err)
108
311
  console.error(`[kay dev] build error:\n${lastError}`)
109
312
  // Push reload over SSE so open browser tabs immediately display the error overlay
@@ -111,7 +314,10 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
111
314
  }
112
315
  }
113
316
 
317
+ let timer: ReturnType<typeof setTimeout> | undefined
318
+
114
319
  function drainRebuilds(): Promise<void> {
320
+ clearTimeout(timer)
115
321
  if (building) {
116
322
  pending = true
117
323
  return inFlight ?? Promise.resolve()
@@ -120,12 +326,15 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
120
326
  const run = (async () => {
121
327
  try {
122
328
  do {
329
+ clearTimeout(timer)
123
330
  const cssOnly = pendingCssOnly
124
331
  const resetCache = pendingConfigReset
332
+ const reloadAll = pendingReloadAll
125
333
  pending = false
126
334
  pendingCssOnly = true
127
335
  pendingConfigReset = false
128
- await runSingleBuild(cssOnly, resetCache)
336
+ pendingReloadAll = false
337
+ await runSingleBuild(cssOnly, resetCache, reloadAll)
129
338
  } while (pending && !stopped)
130
339
  }
131
340
  finally {
@@ -141,67 +350,54 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
141
350
  pendingCssOnly = false
142
351
  await drainRebuilds()
143
352
 
144
- let timer: ReturnType<typeof setTimeout> | undefined
145
353
  const scheduleRebuild = (kind: ChangeKind) => {
146
354
  if (stopped)
147
355
  return
148
- if (kind === 'config') {
356
+ if (kind === 'config')
149
357
  pendingConfigReset = true
358
+ if (kind === 'config' || kind === 'full')
359
+ pendingReloadAll = true
360
+ if (kind !== 'css')
150
361
  pendingCssOnly = false
151
- }
152
- else if (kind === 'full') {
153
- pendingCssOnly = false
154
- }
155
362
  clearTimeout(timer)
156
363
  timer = setTimeout(() => {
157
364
  void drainRebuilds()
158
365
  }, 40)
159
366
  }
160
367
 
161
- const watchers: FSWatcher[] = []
162
- if (existsSync(srcDir)) {
163
- watchers.push(watch(srcDir, { recursive: true }, (_ev, filename) => {
164
- const name = typeof filename === 'string' ? filename : ''
165
- const isCss = name.endsWith('.css') && !name.endsWith('.module.css')
166
- scheduleRebuild(isCss ? 'css' : 'full')
368
+ const addDirWatch = (dir: string, handler: (filename: string) => void) => {
369
+ if (watchedDirs.has(dir) || !existsSync(dir))
370
+ return
371
+ watchedDirs.add(dir)
372
+ watchers.push(watch(dir, { recursive: true }, (_ev, filename) => {
373
+ handler(typeof filename === 'string' ? filename : '')
167
374
  }))
168
375
  }
169
- if (existsSync(publicDir))
170
- watchers.push(watch(publicDir, { recursive: true }, () => scheduleRebuild('full')))
171
- if (existsSync(configPath))
172
- watchers.push(watch(configPath, () => scheduleRebuild('config')))
173
376
 
174
- // Watch plugin-declared extra paths (e.g. content/ or messages/ directories)
377
+ addDirWatch(srcDir, name => scheduleRebuild(srcChangeKind(name)))
378
+ // If routesDir sits outside src/, watch it too!
379
+ if (!routesDir.startsWith(`${srcDir}/`) && !routesDir.startsWith(`${srcDir}\\`) && routesDir !== srcDir)
380
+ addDirWatch(routesDir, name => scheduleRebuild(srcChangeKind(name)))
381
+ addDirWatch(publicDir, () => scheduleRebuild('full'))
382
+
383
+ // Watch root (non-recursive) for kay.config.ts so atomic editor saves (temp + rename) still fire events.
384
+ watchers.push(watch(root, (_ev, filename) => {
385
+ if (filename === 'kay.config.ts')
386
+ scheduleRebuild('config')
387
+ }))
388
+
389
+ // Watch plugin-declared extra paths (e.g. content/ or messages/ directories); refreshed on kay.config.ts edits.
175
390
  try {
176
- const cfg = await loadConfig(root)
177
- const watchedExtra = new Set<string>([srcDir, publicDir, configPath])
178
- for (const plugin of cfg.plugins ?? []) {
179
- const paths = typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? [])
180
- for (const p of paths) {
181
- const abs = resolve(root, p)
182
- if (watchedExtra.has(abs) || !existsSync(abs))
183
- continue
184
- watchedExtra.add(abs)
185
- const isDir = statSync(abs).isDirectory()
186
- watchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
187
- }
188
- }
391
+ refreshPluginWatchers(initialCfg)
392
+ }
393
+ catch (err) {
394
+ console.warn(`[kay dev] could not attach plugin watchers: ${err instanceof Error ? err.message : String(err)}`)
189
395
  }
190
- catch {}
191
396
 
192
397
  const pingChunk = encoder.encode(': ping\n\n')
193
- const pingInterval = setInterval(() => {
194
- for (const c of clients) {
195
- try {
196
- c.enqueue(pingChunk)
197
- }
198
- catch {
199
- clients.delete(c)
200
- }
201
- }
202
- }, 15_000)
398
+ const pingInterval = setInterval(() => pushToClients(pingChunk), 15_000)
203
399
 
204
- const maxRequestBodySize = options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
400
+ const maxRequestBodySize = options.maxRequestBodySize ?? initialCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
205
401
 
206
402
  const server = Bun.serve({
207
403
  port,
@@ -211,7 +407,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
211
407
  async fetch(request, srv) {
212
408
  const url = new URL(request.url)
213
409
 
214
- if (url.pathname === '/_kay/dev-events') {
410
+ if (url.pathname === reloadAssets.eventsPath) {
215
411
  srv.timeout(request, 0)
216
412
  let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
217
413
  const stream = new ReadableStream<Uint8Array>({
@@ -242,7 +438,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
242
438
  }
243
439
 
244
440
  if (lastError !== undefined) {
245
- return new Response(renderErrorOverlay(lastError), {
441
+ return new Response(renderErrorOverlay(lastError, reloadAssets.script), {
246
442
  status: 500,
247
443
  headers: { 'content-type': 'text/html; charset=utf-8' },
248
444
  })
@@ -253,16 +449,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
253
449
  const ct = res.headers.get('content-type') ?? ''
254
450
  if (ct.includes('text/event-stream'))
255
451
  srv.timeout(request, 0)
256
- if (ct.includes('text/html')) {
257
- const html = await res.text()
258
- const injected = html.includes('</body>')
259
- ? html.replace('</body>', `${DEV_RELOAD_SCRIPT}</body>`)
260
- : html + DEV_RELOAD_SCRIPT
452
+ if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null) {
261
453
  const headers = new Headers(res.headers)
454
+ headers.delete('content-length')
262
455
  const existingCsp = headers.get('content-security-policy')
263
456
  if (existingCsp !== null)
264
- headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [DEV_RELOAD_SCRIPT_HASH] }))
265
- return new Response(injected, { status: res.status, headers })
457
+ headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [reloadAssets.hash] }))
458
+ return new Response(injectReloadStream(res.body, reloadAssets.script), { status: res.status, headers })
266
459
  }
267
460
  return res
268
461
  },
@@ -284,7 +477,10 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
284
477
  clearInterval(pingInterval)
285
478
  for (const w of watchers)
286
479
  w.close()
480
+ for (const w of pluginWatchers)
481
+ w.close()
287
482
  server.stop(true)
483
+ void currentApp?.dispose?.()
288
484
  rmSync(devRoot, { recursive: true, force: true })
289
485
  if (prevKayDev === undefined)
290
486
  delete process.env.KAY_DEV
package/src/dom/action.ts CHANGED
@@ -3,30 +3,40 @@
3
3
  import type { ActionResult } from '../server/action'
4
4
 
5
5
  export interface ClientAction<Input, Output> {
6
- (input: Input): Promise<ActionResult<Output>>
6
+ /** A FormData input is sent as multipart, so it can carry files. */
7
+ (input: Input | FormData): Promise<ActionResult<Output>>
7
8
  readonly url: string
8
9
  toString(): string
9
10
  }
10
11
 
11
12
  export function actionStub<Input = unknown, Output = unknown>(url: string): ClientAction<Input, Output> {
12
- const call = (async (input: Input): Promise<ActionResult<Output>> => {
13
- const res = await fetch(url, {
14
- method: 'POST',
15
- headers: {
16
- 'content-type': 'application/json',
17
- 'accept': 'application/json',
18
- },
19
- body: input === undefined ? '{}' : JSON.stringify(input),
20
- })
13
+ const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
14
+ const isForm = typeof FormData !== 'undefined' && input instanceof FormData
15
+ let res: Response
16
+ try {
17
+ res = await fetch(url, {
18
+ method: 'POST',
19
+ headers: isForm ? { accept: 'application/json' } : { 'content-type': 'application/json', 'accept': 'application/json' },
20
+ body: isForm ? input : input === undefined ? '{}' : JSON.stringify(input),
21
+ })
22
+ }
23
+ catch (error) {
24
+ return { ok: false, status: 0, error: error instanceof Error ? error.message : String(error) }
25
+ }
21
26
 
27
+ // The action answered with a redirect: the page navigates there and the call never settles, so no caller acts on data it did not get.
22
28
  if (res.redirected) {
23
29
  if (typeof location !== 'undefined')
24
30
  location.assign(res.url)
25
- return { ok: true, data: undefined as Output }
31
+ return new Promise<never>(() => {})
26
32
  }
27
33
 
28
- const body = await res.json().catch(() => ({ ok: false, status: res.status, error: res.statusText }))
29
- return body as ActionResult<Output>
34
+ try {
35
+ return await res.json() as ActionResult<Output>
36
+ }
37
+ catch {
38
+ return { ok: false, status: res.status, error: res.statusText }
39
+ }
30
40
  }) as unknown as ClientAction<Input, Output>
31
41
 
32
42
  Object.defineProperties(call, {