@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.3

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 (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
package/src/dev/index.ts CHANGED
@@ -1,11 +1,14 @@
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'
5
+ import type { BuildCacheStats } from '../build/graph'
4
6
  import type { KayApp } from '../server/index'
5
- import { existsSync, rmSync, statSync, watch } from 'node:fs'
6
- import { join, resolve } from 'node:path'
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
8
+ import { dirname, join, relative, resolve } from 'node:path'
9
+ import { clearBuildCache } from '../build/graph'
7
10
  import { build, createBuildCache } from '../build/index'
8
- import { loadConfig } from '../plugins/index'
11
+ import { createAppContext, loadConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
9
12
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
10
13
  import { createServer, withCspHashes } from '../server/index'
11
14
 
@@ -17,31 +20,249 @@ export interface DevServerOptions {
17
20
  maxRequestBodySize?: number | undefined
18
21
  }
19
22
 
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')}'`
23
+ function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
24
+ const prefix = assetPrefix.replace(/\/$/, '')
25
+ const eventsPath = `${prefix}/dev-events`
26
+ 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();}};})();`
27
+ const hash = `'sha256-${new Bun.CryptoHasher('sha256').update(js).digest('base64')}'`
28
+ return { script: `<script>${js}</script>`, hash, eventsPath }
29
+ }
23
30
 
24
- function renderErrorOverlay(errText: string): string {
31
+ function renderErrorOverlay(errText: string, reloadScript: string): string {
25
32
  const escaped = errText
26
33
  .replaceAll('&', '&amp;')
27
34
  .replaceAll('<', '&lt;')
28
35
  .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>`
36
+ 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>`
30
37
  }
31
38
 
32
- type ChangeKind = 'css' | 'full' | 'config'
39
+ type ChangeKind = 'css' | 'code' | 'full' | 'config'
40
+
41
+ // A source edit changes the bundled bytes; any other file (content, data, public/) may be read when a module loads.
42
+ const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|css)$/
43
+
44
+ function srcChangeKind(name: string): ChangeKind {
45
+ if (name.endsWith('.css') && !name.endsWith('.module.css'))
46
+ return 'css'
47
+ return CODE_FILE_RE.test(name) ? 'code' : 'full'
48
+ }
33
49
 
34
- export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
50
+ // Injects the dev reload script into an HTML response while preserving streaming (<Suspense>).
51
+ function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: string): ReadableStream<Uint8Array> {
52
+ const decoder = new TextDecoder()
53
+ const encoder = new TextEncoder()
54
+ let injected = false
55
+ let tail = ''
56
+ const KEEP = 16 // enough to span a split `</body>` tag across chunk boundaries
57
+
58
+ return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
59
+ transform(chunk, controller) {
60
+ if (injected) {
61
+ controller.enqueue(chunk)
62
+ return
63
+ }
64
+ const text = tail + decoder.decode(chunk, { stream: true })
65
+ const idx = text.indexOf('</body>')
66
+ if (idx !== -1) {
67
+ injected = true
68
+ tail = ''
69
+ controller.enqueue(encoder.encode(`${text.slice(0, idx)}${reloadScript}${text.slice(idx)}`))
70
+ return
71
+ }
72
+ if (text.length > KEEP) {
73
+ const split = text.length - KEEP
74
+ controller.enqueue(encoder.encode(text.slice(0, split)))
75
+ tail = text.slice(split)
76
+ }
77
+ else {
78
+ tail = text
79
+ }
80
+ },
81
+ flush(controller) {
82
+ const rest = tail + decoder.decode()
83
+ if (injected) {
84
+ if (rest.length > 0)
85
+ controller.enqueue(encoder.encode(rest))
86
+ return
87
+ }
88
+ const idx = rest.indexOf('</body>')
89
+ if (idx !== -1)
90
+ controller.enqueue(encoder.encode(`${rest.slice(0, idx)}${reloadScript}${rest.slice(idx)}`))
91
+ else
92
+ controller.enqueue(encoder.encode(rest + reloadScript))
93
+ },
94
+ }))
95
+ }
96
+
97
+ // Bun never unloads a module, so each build's server files are copied into a generation store.
98
+ // Only `_entry.js` is imported, with its hash: the code lives in content-named chunks, so an unchanged chunk keeps its loaded instance across saves.
99
+ // A failed import starts a new generation, since Bun keeps a module that failed to evaluate.
100
+ function createModuleStore(storeRoot: string) {
101
+ const hashes = new Map<string, string>()
102
+ let generation = 0
103
+ let stale = false
104
+ const generationDir = (g: number): string => join(storeRoot, `g${g}`)
105
+ return {
106
+ reloadAll(): void {
107
+ stale = true
108
+ },
109
+ sync(serverDir: string): void {
110
+ const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
111
+ for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
112
+ if (!entry.isFile())
113
+ continue
114
+ const from = join(entry.parentPath, entry.name)
115
+ const rel = relative(serverDir, from).replaceAll('\\', '/')
116
+ const bytes = readFileSync(from)
117
+ const hash = Bun.hash(bytes).toString(36)
118
+ nextFiles.set(rel, { bytes, hash })
119
+ }
120
+
121
+ if (stale) {
122
+ stale = false
123
+ hashes.clear()
124
+ generation++
125
+ // The previous generation stays for requests the old app is still serving.
126
+ rmSync(generationDir(generation - 2), { recursive: true, force: true })
127
+ }
128
+ const storeDir = generationDir(generation)
129
+ for (const [rel, { bytes, hash }] of nextFiles) {
130
+ if (hashes.get(rel) === hash)
131
+ continue
132
+ const to = join(storeDir, rel)
133
+ mkdirSync(dirname(to), { recursive: true })
134
+ writeFileSync(to, bytes)
135
+ hashes.set(rel, hash)
136
+ }
137
+ // Prune removed chunk files from current generation to avoid unbounded disk/map growth.
138
+ for (const rel of [...hashes.keys()]) {
139
+ if (!nextFiles.has(rel)) {
140
+ hashes.delete(rel)
141
+ rmSync(join(storeDir, rel), { force: true })
142
+ }
143
+ }
144
+ },
145
+ importFrom(serverDir: string) {
146
+ const storeDir = generationDir(generation)
147
+ return async (path: string): Promise<Record<string, unknown>> => {
148
+ const rel = relative(serverDir, path).replaceAll('\\', '/')
149
+ try {
150
+ return await import(`${join(storeDir, rel)}?v=${hashes.get(rel)}`)
151
+ }
152
+ catch (err) {
153
+ stale = true
154
+ throw err
155
+ }
156
+ }
157
+ },
158
+ }
159
+ }
160
+
161
+ export async function devServer(options: DevServerOptions): Promise<{
162
+ url: string
163
+ stop: () => void
164
+ rebuild: () => Promise<void>
165
+ stats: () => BuildCacheStats
166
+ }> {
35
167
  const prevKayDev = process.env.KAY_DEV
36
168
  process.env.KAY_DEV = '1'
37
169
  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
170
  const devRoot = join(root, '.kay-dev')
42
- const port = options.port ?? 3000
171
+ let initialConfigFailed = false
172
+ const initialCfg = await loadConfig(root).catch((err) => {
173
+ initialConfigFailed = true
174
+ console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
175
+ return {} as Awaited<ReturnType<typeof loadConfig>>
176
+ })
177
+ const assetPrefix = (initialCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
178
+ let reloadAssets = makeDevReloadAssets(assetPrefix)
179
+ const srcDir = resolve(root, 'src')
180
+ const routesDir = resolve(root, options.routesDir ?? initialCfg.routesDir ?? 'src/routes')
181
+ const publicDir = resolve(root, initialCfg.publicDir ?? 'public')
182
+ const port = options.port ?? initialCfg.port ?? 3000
43
183
  const hostname = options.hostname ?? '127.0.0.1'
44
184
  const buildCache = createBuildCache()
185
+ const modules = createModuleStore(join(devRoot, 'server'))
186
+ const watchers: FSWatcher[] = []
187
+ const watchedDirs = new Set<string>()
188
+ const pluginWatchers: FSWatcher[] = []
189
+ const graphWatchers = new Map<string, FSWatcher>()
190
+ let activeAssetPrefix = assetPrefix
191
+ let pluginWatchersAttached = false
192
+
193
+ const isInsideDir = (parent: string, target: string): boolean =>
194
+ target === parent || target.startsWith(`${parent}/`) || target.startsWith(`${parent}\\`)
195
+
196
+ function isCoveredByStaticWatchers(dir: string): boolean {
197
+ if (dir === root)
198
+ return false
199
+ for (const base of watchedDirs) {
200
+ if (isInsideDir(base, dir))
201
+ return true
202
+ }
203
+ return false
204
+ }
205
+
206
+ function syncBuildWatchers(watchedFiles: ReadonlySet<string>): void {
207
+ const nextDirs = new Set<string>()
208
+ let realRoot = root
209
+ try {
210
+ realRoot = realpathSync(root)
211
+ }
212
+ catch {}
213
+ for (const file of watchedFiles) {
214
+ if (file.includes('/node_modules/') || file.includes('\\node_modules\\'))
215
+ continue
216
+ if (isInsideDir(devRoot, file) || isInsideDir(join(root, '.kay-cache'), file))
217
+ continue
218
+ const dir = dirname(file)
219
+ // Root is already watched non-recursively for `kay.config.ts`; skip if it's only kay.config.ts itself.
220
+ if (dir === root || dir === realRoot) {
221
+ if (file === join(root, 'kay.config.ts') || file === join(realRoot, 'kay.config.ts'))
222
+ continue
223
+ }
224
+ if (isCoveredByStaticWatchers(dir))
225
+ continue
226
+ nextDirs.add(dir)
227
+ }
228
+ for (const [dir, watcher] of graphWatchers) {
229
+ if (!nextDirs.has(dir)) {
230
+ watcher.close()
231
+ graphWatchers.delete(dir)
232
+ }
233
+ }
234
+ for (const dir of nextDirs) {
235
+ if (graphWatchers.has(dir) || !existsSync(dir))
236
+ continue
237
+ try {
238
+ graphWatchers.set(dir, watch(dir, (_ev, filename) => {
239
+ const name = typeof filename === 'string' ? filename : ''
240
+ scheduleRebuild(srcChangeKind(name))
241
+ }))
242
+ }
243
+ catch {}
244
+ }
245
+ }
246
+
247
+ function refreshPluginWatchers(cfg: Awaited<ReturnType<typeof loadConfig>>): void {
248
+ for (const w of pluginWatchers)
249
+ w.close()
250
+ pluginWatchers.length = 0
251
+ const seen = new Set<string>(watchedDirs)
252
+ const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, site: cfg.site, dev: true })
253
+ for (const plugin of resolvePlugins(cfg.plugins)) {
254
+ const paths = runWithAppContext(watchCtx, () =>
255
+ typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
256
+ for (const p of paths) {
257
+ const abs = resolve(root, p)
258
+ if (seen.has(abs) || !existsSync(abs))
259
+ continue
260
+ seen.add(abs)
261
+ const isDir = statSync(abs).isDirectory()
262
+ pluginWatchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
263
+ }
264
+ }
265
+ }
45
266
 
46
267
  let buildNum = 0
47
268
  let currentApp: KayApp | undefined
@@ -53,13 +274,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
53
274
  let pending = false
54
275
  let pendingCssOnly = true
55
276
  let pendingConfigReset = false
277
+ let pendingReloadAll = false
56
278
  let inFlight: Promise<void> | undefined
57
279
 
58
280
  const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
59
281
  const encoder = new TextEncoder()
60
282
 
61
- function broadcast(payload: string): void {
62
- const chunk = encoder.encode(`data: ${payload}\n\n`)
283
+ function pushToClients(chunk: Uint8Array): void {
63
284
  for (const c of clients) {
64
285
  try {
65
286
  c.enqueue(chunk)
@@ -70,20 +291,26 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
70
291
  }
71
292
  }
72
293
 
73
- async function runSingleBuild(cssOnly: boolean, resetCache: boolean): Promise<void> {
294
+ const broadcast = (payload: string): void => pushToClients(encoder.encode(`data: ${payload}\n\n`))
295
+
296
+ async function runSingleBuild(cssOnly: boolean, resetCache: boolean, reloadAll: boolean): Promise<void> {
74
297
  if (stopped)
75
298
  return
76
- if (resetCache) {
77
- buildCache.analyses.clear()
78
- buildCache.domCompiled.clear()
79
- buildCache.ssrCompiled.clear()
80
- }
81
299
  const hadError = lastError !== undefined
82
300
  const hadApp = currentApp !== undefined
83
301
  const n = ++buildNum
84
302
  const outDir = `.kay-dev/b${n}`
85
303
  const t0 = performance.now()
86
304
  try {
305
+ if (resetCache) {
306
+ clearBuildCache(buildCache)
307
+ const freshCfg = await loadConfig(root, { fresh: true })
308
+ activeAssetPrefix = (freshCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
309
+ reloadAssets = makeDevReloadAssets(activeAssetPrefix)
310
+ refreshPluginWatchers(freshCfg)
311
+ }
312
+ if (reloadAll)
313
+ modules.reloadAll()
87
314
  const manifest = await build({
88
315
  root,
89
316
  routesDir: options.routesDir,
@@ -91,10 +318,44 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
91
318
  minify: false,
92
319
  prerender: false,
93
320
  copyPublic: false,
321
+ dev: true,
94
322
  cache: buildCache,
95
323
  })
96
- currentApp = await createServer({ root, outDir })
324
+ if (stopped) {
325
+ rmSync(join(root, outDir), { recursive: true, force: true })
326
+ return
327
+ }
328
+ const serverDir = join(root, outDir, 'server')
329
+ modules.sync(serverDir)
330
+ const nextApp = await createServer({
331
+ root,
332
+ outDir,
333
+ dev: true,
334
+ compress: false,
335
+ importModule: modules.importFrom(serverDir),
336
+ })
337
+ if (stopped) {
338
+ await nextApp.dispose?.()
339
+ rmSync(join(root, outDir), { recursive: true, force: true })
340
+ return
341
+ }
342
+ const prevApp = currentApp
343
+ currentApp = nextApp
344
+ await prevApp?.dispose?.()
97
345
  lastError = undefined
346
+ syncBuildWatchers(buildCache.watchedFiles)
347
+ if (!pluginWatchersAttached && !initialConfigFailed) {
348
+ pluginWatchersAttached = true
349
+ }
350
+ else if (initialConfigFailed) {
351
+ initialConfigFailed = false
352
+ try {
353
+ const recoveredCfg = await loadConfig(root)
354
+ refreshPluginWatchers(recoveredCfg)
355
+ pluginWatchersAttached = true
356
+ }
357
+ catch {}
358
+ }
98
359
  if (n > 2)
99
360
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
100
361
  console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
@@ -104,6 +365,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
104
365
  broadcast('reload')
105
366
  }
106
367
  catch (err) {
368
+ if (stopped)
369
+ return
107
370
  lastError = err instanceof Error ? err.stack ?? err.message : String(err)
108
371
  console.error(`[kay dev] build error:\n${lastError}`)
109
372
  // Push reload over SSE so open browser tabs immediately display the error overlay
@@ -111,7 +374,10 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
111
374
  }
112
375
  }
113
376
 
377
+ let timer: ReturnType<typeof setTimeout> | undefined
378
+
114
379
  function drainRebuilds(): Promise<void> {
380
+ clearTimeout(timer)
115
381
  if (building) {
116
382
  pending = true
117
383
  return inFlight ?? Promise.resolve()
@@ -120,12 +386,15 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
120
386
  const run = (async () => {
121
387
  try {
122
388
  do {
389
+ clearTimeout(timer)
123
390
  const cssOnly = pendingCssOnly
124
391
  const resetCache = pendingConfigReset
392
+ const reloadAll = pendingReloadAll
125
393
  pending = false
126
394
  pendingCssOnly = true
127
395
  pendingConfigReset = false
128
- await runSingleBuild(cssOnly, resetCache)
396
+ pendingReloadAll = false
397
+ await runSingleBuild(cssOnly, resetCache, reloadAll)
129
398
  } while (pending && !stopped)
130
399
  }
131
400
  finally {
@@ -141,67 +410,55 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
141
410
  pendingCssOnly = false
142
411
  await drainRebuilds()
143
412
 
144
- let timer: ReturnType<typeof setTimeout> | undefined
145
413
  const scheduleRebuild = (kind: ChangeKind) => {
146
414
  if (stopped)
147
415
  return
148
- if (kind === 'config') {
416
+ if (kind === 'config')
149
417
  pendingConfigReset = true
418
+ if (kind === 'config' || kind === 'full')
419
+ pendingReloadAll = true
420
+ if (kind !== 'css')
150
421
  pendingCssOnly = false
151
- }
152
- else if (kind === 'full') {
153
- pendingCssOnly = false
154
- }
155
422
  clearTimeout(timer)
156
423
  timer = setTimeout(() => {
157
424
  void drainRebuilds()
158
425
  }, 40)
159
426
  }
160
427
 
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')
428
+ const addDirWatch = (dir: string, handler: (filename: string) => void) => {
429
+ if (watchedDirs.has(dir) || !existsSync(dir))
430
+ return
431
+ watchedDirs.add(dir)
432
+ watchers.push(watch(dir, { recursive: true }, (_ev, filename) => {
433
+ handler(typeof filename === 'string' ? filename : '')
167
434
  }))
168
435
  }
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
436
 
174
- // Watch plugin-declared extra paths (e.g. content/ or messages/ directories)
437
+ addDirWatch(srcDir, name => scheduleRebuild(srcChangeKind(name)))
438
+ // If routesDir sits outside src/, watch it too!
439
+ if (!routesDir.startsWith(`${srcDir}/`) && !routesDir.startsWith(`${srcDir}\\`) && routesDir !== srcDir)
440
+ addDirWatch(routesDir, name => scheduleRebuild(srcChangeKind(name)))
441
+ addDirWatch(publicDir, () => scheduleRebuild('full'))
442
+
443
+ // Watch root (non-recursive) for kay.config.ts so atomic editor saves (temp + rename) still fire events.
444
+ watchers.push(watch(root, (_ev, filename) => {
445
+ if (filename === 'kay.config.ts')
446
+ scheduleRebuild('config')
447
+ }))
448
+
449
+ // Watch plugin-declared extra paths (e.g. content/ or messages/ directories); refreshed on kay.config.ts edits.
175
450
  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
- }
451
+ refreshPluginWatchers(initialCfg)
452
+ }
453
+ catch (err) {
454
+ console.warn(`[kay dev] could not attach plugin watchers: ${err instanceof Error ? err.message : String(err)}`)
189
455
  }
190
- catch {}
191
456
 
192
457
  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)
458
+ const pingInterval = setInterval(() => pushToClients(pingChunk), 15_000)
203
459
 
204
- const maxRequestBodySize = options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
460
+ const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
461
+ const maxRequestBodySize = runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
205
462
 
206
463
  const server = Bun.serve({
207
464
  port,
@@ -211,7 +468,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
211
468
  async fetch(request, srv) {
212
469
  const url = new URL(request.url)
213
470
 
214
- if (url.pathname === '/_kay/dev-events') {
471
+ if (url.pathname === reloadAssets.eventsPath) {
215
472
  srv.timeout(request, 0)
216
473
  let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
217
474
  const stream = new ReadableStream<Uint8Array>({
@@ -242,7 +499,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
242
499
  }
243
500
 
244
501
  if (lastError !== undefined) {
245
- return new Response(renderErrorOverlay(lastError), {
502
+ return new Response(renderErrorOverlay(lastError, reloadAssets.script), {
246
503
  status: 500,
247
504
  headers: { 'content-type': 'text/html; charset=utf-8' },
248
505
  })
@@ -253,16 +510,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
253
510
  const ct = res.headers.get('content-type') ?? ''
254
511
  if (ct.includes('text/event-stream'))
255
512
  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
513
+ if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-encoding')) {
261
514
  const headers = new Headers(res.headers)
515
+ headers.delete('content-length')
262
516
  const existingCsp = headers.get('content-security-policy')
263
517
  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 })
518
+ headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [reloadAssets.hash] }))
519
+ return new Response(injectReloadStream(res.body, reloadAssets.script), { status: res.status, headers })
266
520
  }
267
521
  return res
268
522
  },
@@ -278,13 +532,22 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
278
532
  pendingCssOnly = false
279
533
  return drainRebuilds()
280
534
  },
535
+ stats() {
536
+ return { ...buildCache.stats }
537
+ },
281
538
  stop() {
282
539
  stopped = true
283
540
  clearTimeout(timer)
284
541
  clearInterval(pingInterval)
285
542
  for (const w of watchers)
286
543
  w.close()
544
+ for (const w of pluginWatchers)
545
+ w.close()
546
+ for (const w of graphWatchers.values())
547
+ w.close()
548
+ graphWatchers.clear()
287
549
  server.stop(true)
550
+ void currentApp?.dispose?.()
288
551
  rmSync(devRoot, { recursive: true, force: true })
289
552
  if (prevKayDev === undefined)
290
553
  delete process.env.KAY_DEV