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

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 (101) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +15 -53
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +9 -44
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +45 -25
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +9 -4
  10. package/src/build/prerender.ts +15 -7
  11. package/src/build/report.ts +82 -13
  12. package/src/build/resolve.ts +6 -7
  13. package/src/build/routes.ts +12 -21
  14. package/src/build/server-entry.ts +38 -0
  15. package/src/cli/check.ts +49 -43
  16. package/src/cli/commands.ts +224 -0
  17. package/src/cli/index.ts +46 -302
  18. package/src/cli/new.ts +15 -509
  19. package/src/cli/upgrade-plugins.ts +168 -0
  20. package/src/cli/upgrade.ts +220 -0
  21. package/src/compiler/analyze.ts +319 -565
  22. package/src/compiler/ast.ts +39 -0
  23. package/src/compiler/data-keys.ts +233 -0
  24. package/src/compiler/dom.ts +18 -15
  25. package/src/compiler/interactivity.ts +174 -0
  26. package/src/compiler/mistakes.ts +19 -1
  27. package/src/compiler/server-only.ts +4 -1
  28. package/src/compiler/shared.ts +1 -1
  29. package/src/compiler/ssr.ts +28 -28
  30. package/src/context.ts +1 -1
  31. package/src/dev/index.ts +19 -46
  32. package/src/dom/extras.ts +43 -12
  33. package/src/dom/index.ts +25 -1
  34. package/src/index.ts +0 -13
  35. package/src/jsx-runtime.ts +1 -1
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +8 -28
  38. package/src/plugins/index.ts +10 -385
  39. package/src/plugins/load.ts +61 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/public.ts +6 -0
  42. package/src/plugins/services.ts +35 -0
  43. package/src/plugins/types.ts +193 -0
  44. package/src/server/action-registry.ts +78 -0
  45. package/src/server/action.ts +8 -2
  46. package/src/server/app-entry.ts +23 -0
  47. package/src/server/assets.ts +182 -0
  48. package/src/server/document.ts +204 -0
  49. package/src/server/errors.ts +125 -0
  50. package/src/server/http.ts +14 -0
  51. package/src/server/index.ts +66 -766
  52. package/src/server/lifecycle.ts +22 -0
  53. package/src/server/loader.ts +60 -85
  54. package/src/server/page.ts +107 -0
  55. package/src/server/plugin-host.ts +165 -0
  56. package/src/server/public.ts +15 -0
  57. package/src/server/request-scope.ts +22 -0
  58. package/src/server/security.ts +40 -1
  59. package/src/server/static-dir.ts +22 -3
  60. package/src/server/stream.ts +95 -0
  61. package/src/ssr/context.ts +25 -0
  62. package/src/ssr/index.ts +10 -7
  63. package/src/test/browser.ts +180 -0
  64. package/src/test/index.ts +25 -6
  65. package/templates/_shared/AGENTS.md +5 -0
  66. package/templates/_shared/CLAUDE.md +1 -0
  67. package/templates/_shared/public/robots.txt +2 -0
  68. package/templates/_shared/tsconfig.json +19 -0
  69. package/templates/app/.env.example +4 -0
  70. package/templates/app/kay.config.ts +11 -0
  71. package/templates/app/package.json +20 -0
  72. package/templates/app/src/auth.ts +14 -0
  73. package/templates/app/src/routes/_layout.tsx +32 -0
  74. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  75. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  76. package/templates/app/src/routes/index.tsx +15 -0
  77. package/templates/app/src/routes/login.tsx +34 -0
  78. package/templates/app/src/styles/app.css +7 -0
  79. package/templates/blog/content/posts/welcome.md +9 -0
  80. package/templates/blog/kay.config.ts +23 -0
  81. package/templates/blog/package.json +21 -0
  82. package/templates/blog/src/posts.ts +26 -0
  83. package/templates/blog/src/routes/_layout.tsx +20 -0
  84. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  85. package/templates/blog/src/routes/index.tsx +29 -0
  86. package/templates/blog/src/styles/app.css +10 -0
  87. package/templates/fullstack/kay.config.ts +6 -0
  88. package/templates/fullstack/package.json +18 -0
  89. package/templates/fullstack/src/actions/greet.ts +19 -0
  90. package/templates/fullstack/src/components/Counter.tsx +10 -0
  91. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  92. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  93. package/templates/fullstack/src/routes/api/health.ts +5 -0
  94. package/templates/fullstack/src/routes/index.tsx +13 -0
  95. package/templates/fullstack/src/styles/app.css +29 -0
  96. package/templates/minimal/kay.config.ts +6 -0
  97. package/templates/minimal/package.json +18 -0
  98. package/templates/minimal/src/components/Counter.tsx +10 -0
  99. package/templates/minimal/src/routes/_layout.tsx +14 -0
  100. package/templates/minimal/src/routes/index.tsx +11 -0
  101. package/templates/minimal/src/styles/app.css +22 -0
@@ -9,7 +9,8 @@ import type {
9
9
  Node,
10
10
  } from 'oxc-parser'
11
11
  import type { ModuleAnalysis } from './analyze'
12
- import { analyzeModule, parseTsx, walk } from './analyze'
12
+ import { analyzeModule, parseTsx } from './analyze'
13
+ import { walk } from './ast'
13
14
  import { mistake } from './mistakes'
14
15
  import { SourceEditor } from './patch'
15
16
  import {
@@ -247,7 +248,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
247
248
  // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
248
249
  function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void): void {
249
250
  if (node.type === 'JSXFragment') {
250
- emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt)
251
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, emitMarkers, true)
251
252
  return
252
253
  }
253
254
 
@@ -327,10 +328,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
327
328
  pushStmt: (stmt: string) => void,
328
329
  rawTextTag?: 'style' | 'script',
329
330
  slotMarkers = emitMarkers,
331
+ inFragment = false,
330
332
  ): void {
331
333
  const meaningful = filterMeaningfulChildren(children)
332
334
  const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c, jsxNodes) })).filter(s => s.slot !== undefined)
333
335
  const hasSiblings = slots.length > 1
336
+ // A fragment may sit inside another range, so its dynamic slots are bracketed even alone and always closed, for the markers to balance (#3596).
337
+ const bracketed = slotMarkers && (hasSiblings || inFragment)
334
338
  let hadVariableRange = false
335
339
 
336
340
  for (let i = 0; i < slots.length; i++) {
@@ -370,7 +374,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
370
374
  if (slotMarkers && hasSiblings) {
371
375
  parts.pushStatic('<!--k[-->')
372
376
  emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
373
- if (!isLast)
377
+ if (!isLast || inFragment)
374
378
  parts.pushStatic('<!--k]-->')
375
379
  }
376
380
  else {
@@ -382,7 +386,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
382
386
 
383
387
  if (slot.kind === 'loop') {
384
388
  const { match } = slot
385
- const needsBracket = slotMarkers && (!isLast || hadVariableRange)
389
+ const needsBracket = slotMarkers && (inFragment || !isLast || hadVariableRange)
386
390
  if (needsBracket)
387
391
  parts.pushStatic('<!--k[-->')
388
392
 
@@ -428,7 +432,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
428
432
  if (slot.kind === 'and-show') {
429
433
  const left = compileSubExpression(slot.expr.left)
430
434
  const right = compileJsxToStringExpr(slot.right)
431
- if (slotMarkers && hasSiblings) {
435
+ if (bracketed) {
432
436
  parts.pushStatic('<!--k[-->')
433
437
  parts.pushExpr(`((${left}) ? (${right}) : "")`)
434
438
  parts.pushStatic('<!--k]-->')
@@ -444,7 +448,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
444
448
  const test = compileSubExpression(slot.expr.test)
445
449
  const cons = compileExpressionAsString(slot.cons)
446
450
  const alt = compileExpressionAsString(slot.alt)
447
- if (slotMarkers && hasSiblings) {
451
+ if (bracketed) {
448
452
  parts.pushStatic('<!--k[-->')
449
453
  parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
450
454
  parts.pushStatic('<!--k]-->')
@@ -460,10 +464,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
460
464
  const exprCode = compileSubExpression(slot.expr)
461
465
  const rendered = `${use('esc')}(${exprCode})`
462
466
  if (isNodeCapableExpr(slot.expr, jsxNodes)) {
463
- if (slotMarkers && hasSiblings) {
467
+ if (bracketed) {
464
468
  parts.pushStatic('<!--k[-->')
465
469
  parts.pushExpr(rendered)
466
- if (!isLast)
470
+ if (!isLast || inFragment)
467
471
  parts.pushStatic('<!--k]-->')
468
472
  }
469
473
  else {
@@ -471,10 +475,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
471
475
  }
472
476
  hadVariableRange = true
473
477
  }
474
- else if (slotMarkers && hasSiblings) {
478
+ else if (bracketed) {
475
479
  parts.pushStatic('<!---->')
476
480
  parts.pushExpr(rendered)
477
- if (!isLast)
481
+ if (!isLast || inFragment)
478
482
  parts.pushStatic('<!---->')
479
483
  }
480
484
  else {
@@ -542,9 +546,11 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
542
546
 
543
547
  if (islandInfo !== undefined) {
544
548
  const propsCode = `{ ${propEntries.join(', ')} }`
545
- const callPropsCode = hasChildren
546
- ? `{ ${[...propEntries, `children: ${use('raw')}("<kay-slot>" + (${childExpr}) + "</kay-slot>")`].join(', ')} }`
547
- : propsCode
549
+ // The server children an island is handed render before it, outside its contexts and ids, as the browser never re-renders them.
550
+ const slotVar = hasChildren ? `_c${loopCounter++}` : undefined
551
+ const slotProp = slotVar === undefined ? '' : `children: ${use('raw')}("<kay-slot>" + ${slotVar} + "</kay-slot>")`
552
+ const callPropsCode = slotVar === undefined ? propsCode : `{ ${[...propEntries, slotProp].join(', ')} }`
553
+ const withSlot = (expr: string): string => slotVar === undefined ? expr : `((${slotVar}) => ${expr})(${childExpr})`
548
554
  const resolvedHydrate = staticHydrate ?? (hydrateExpr === undefined ? islandInfo.defaultHydrate : undefined)
549
555
 
550
556
  // Compile-time static island props fast path (only when not inside an island-reachable component and children don't contain direct `await`):
@@ -561,15 +567,14 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
561
567
  const renderArg = resolvedHydrate === 'client'
562
568
  ? 'undefined'
563
569
  : `() => ${use('ssrChild')}(${tag}(${callPropsCode}))`
564
- parts.pushExpr(`${use('ssrIslandStatic')}(${JSON.stringify(islandInfo.chunk)}, ${JSON.stringify(openTag)}, ${renderArg}, ${hydrateArg})`)
570
+ const expr = `${use('ssrIslandStatic')}(${JSON.stringify(islandInfo.chunk)}, ${JSON.stringify(openTag)}, ${renderArg}, ${hydrateArg}, ${JSON.stringify(tag)})`
571
+ parts.pushExpr(resolvedHydrate === 'client' ? expr : withSlot(expr))
565
572
  return
566
573
  }
567
574
 
568
575
  const hydrateArg = hydrateExpr ?? (islandInfo.defaultHydrate !== undefined ? JSON.stringify(islandInfo.defaultHydrate) : 'undefined')
569
576
  if (!childrenHaveAwait && allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
570
- parts.pushExpr(
571
- `${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
572
- )
577
+ parts.pushExpr(withSlot(`${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg}, false, ${JSON.stringify(tag)})`))
573
578
  return
574
579
  }
575
580
 
@@ -578,15 +583,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
578
583
  const argNames = [pVar]
579
584
  const argExprs = [propsCode]
580
585
  let callArg = pVar
581
- if (hasChildren) {
582
- let childSlotVal = childExpr
583
- if (childrenHaveAwait) {
584
- const cVar = `_c${loopCounter++}`
585
- argNames.push(cVar)
586
- argExprs.push(childExpr)
587
- childSlotVal = cVar
588
- }
589
- callArg = `{ ...${pVar}, children: ${use('raw')}("<kay-slot>" + (${childSlotVal}) + "</kay-slot>") }`
586
+ if (slotVar !== undefined) {
587
+ argNames.push(slotVar)
588
+ argExprs.push(childExpr)
589
+ callArg = `{ ...${pVar}, ${slotProp} }`
590
590
  }
591
591
  let hArg = hydrateArg
592
592
  if (hydrateExpr !== undefined && staticHydrate === undefined) {
@@ -596,7 +596,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
596
596
  hArg = hVar
597
597
  }
598
598
  parts.pushExpr(
599
- `((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callArg})), ${pVar}, ${hArg}))(${argExprs.join(', ')})`,
599
+ `((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callArg})), ${pVar}, ${hArg}, false, ${JSON.stringify(tag)}))(${argExprs.join(', ')})`,
600
600
  )
601
601
  return
602
602
  }
@@ -668,7 +668,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
668
668
 
669
669
  if (used.size > 0) {
670
670
  const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
671
- editor.prepend(`import { ${specifiers} } from 'kay/ssr';\n`)
671
+ editor.prepend(`import { ${specifiers} } from '@kayjs/kay/internal/ssr';\n`)
672
672
  }
673
673
 
674
674
  return { code: editor.toString(), analysis }
package/src/context.ts CHANGED
@@ -19,7 +19,7 @@ function getServerBridge(): ServerContextBridge | undefined {
19
19
  return (globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY]
20
20
  }
21
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. */
22
+ /** Internal: registered by kay's SSR runtime on the server so `Head`, `Suspense`, `useContext`, and `useId` stay request-scoped without pulling `node:async_hooks` into client bundles. */
23
23
  export function registerServerContextBridge(bridge: ServerContextBridge): void {
24
24
  ;(globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY] = bridge
25
25
  }
package/src/dev/index.ts CHANGED
@@ -95,7 +95,8 @@ function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: stri
95
95
  }
96
96
 
97
97
  // Bun never unloads a module, so each build's server files are copied into a generation store.
98
- // 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
+ // 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.
99
100
  function createModuleStore(storeRoot: string) {
100
101
  const hashes = new Map<string, string>()
101
102
  let generation = 0
@@ -105,7 +106,7 @@ function createModuleStore(storeRoot: string) {
105
106
  reloadAll(): void {
106
107
  stale = true
107
108
  },
108
- sync(serverDir: string, sharedRelFiles: ReadonlySet<string>): void {
109
+ sync(serverDir: string): void {
109
110
  const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
110
111
  for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
111
112
  if (!entry.isFile())
@@ -117,17 +118,6 @@ function createModuleStore(storeRoot: string) {
117
118
  nextFiles.set(rel, { bytes, hash })
118
119
  }
119
120
 
120
- // If an already-loaded standalone action file (statically imported by routes) changed, bump generation so static importers re-resolve cleanly.
121
- if (!stale && hashes.size > 0) {
122
- for (const [rel, { hash }] of nextFiles) {
123
- const prev = hashes.get(rel)
124
- if (prev !== undefined && prev !== hash && sharedRelFiles.has(rel)) {
125
- stale = true
126
- break
127
- }
128
- }
129
- }
130
-
131
121
  if (stale) {
132
122
  stale = false
133
123
  hashes.clear()
@@ -175,15 +165,23 @@ export async function devServer(options: DevServerOptions): Promise<{
175
165
  stats: () => BuildCacheStats
176
166
  }> {
177
167
  const prevKayDev = process.env.KAY_DEV
168
+ const restoreKayDev = (): void => {
169
+ if (prevKayDev === undefined)
170
+ delete process.env.KAY_DEV
171
+ else
172
+ process.env.KAY_DEV = prevKayDev
173
+ }
178
174
  process.env.KAY_DEV = '1'
179
175
  const root = resolve(options.root)
180
176
  const devRoot = join(root, '.kay-dev')
181
- let initialConfigFailed = false
182
- const initialCfg = await loadConfig(root).catch((err) => {
183
- initialConfigFailed = true
184
- console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
185
- return {} as Awaited<ReturnType<typeof loadConfig>>
186
- })
177
+ let initialCfg: Awaited<ReturnType<typeof loadConfig>>
178
+ try {
179
+ initialCfg = await loadConfig(root)
180
+ }
181
+ catch (error) {
182
+ restoreKayDev()
183
+ throw error
184
+ }
187
185
  const assetPrefix = (initialCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
188
186
  let reloadAssets = makeDevReloadAssets(assetPrefix)
189
187
  const srcDir = resolve(root, 'src')
@@ -198,7 +196,6 @@ export async function devServer(options: DevServerOptions): Promise<{
198
196
  const pluginWatchers: FSWatcher[] = []
199
197
  const graphWatchers = new Map<string, FSWatcher>()
200
198
  let activeAssetPrefix = assetPrefix
201
- let pluginWatchersAttached = false
202
199
 
203
200
  const isInsideDir = (parent: string, target: string): boolean =>
204
201
  target === parent || target.startsWith(`${parent}/`) || target.startsWith(`${parent}\\`)
@@ -336,16 +333,7 @@ export async function devServer(options: DevServerOptions): Promise<{
336
333
  return
337
334
  }
338
335
  const serverDir = join(root, outDir, 'server')
339
- const routeFiles = new Set(manifest.routes.map(r => r.file.replace(/^server\//, '')))
340
- const sharedRelFiles = new Set<string>()
341
- if (manifest.configFile !== undefined)
342
- sharedRelFiles.add(manifest.configFile.replace(/^server\//, ''))
343
- for (const a of manifest.actions) {
344
- const rel = a.file.replace(/^server\//, '')
345
- if (!routeFiles.has(rel))
346
- sharedRelFiles.add(rel)
347
- }
348
- modules.sync(serverDir, sharedRelFiles)
336
+ modules.sync(serverDir)
349
337
  const nextApp = await createServer({
350
338
  root,
351
339
  outDir,
@@ -363,18 +351,6 @@ export async function devServer(options: DevServerOptions): Promise<{
363
351
  await prevApp?.dispose?.()
364
352
  lastError = undefined
365
353
  syncBuildWatchers(buildCache.watchedFiles)
366
- if (!pluginWatchersAttached && !initialConfigFailed) {
367
- pluginWatchersAttached = true
368
- }
369
- else if (initialConfigFailed) {
370
- initialConfigFailed = false
371
- try {
372
- const recoveredCfg = await loadConfig(root)
373
- refreshPluginWatchers(recoveredCfg)
374
- pluginWatchersAttached = true
375
- }
376
- catch {}
377
- }
378
354
  if (n > 2)
379
355
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
380
356
  console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
@@ -568,10 +544,7 @@ export async function devServer(options: DevServerOptions): Promise<{
568
544
  server.stop(true)
569
545
  void currentApp?.dispose?.()
570
546
  rmSync(devRoot, { recursive: true, force: true })
571
- if (prevKayDev === undefined)
572
- delete process.env.KAY_DEV
573
- else
574
- process.env.KAY_DEV = prevKayDev
547
+ restoreKayDev()
575
548
  },
576
549
  }
577
550
  }
package/src/dom/extras.ts CHANGED
@@ -5,7 +5,7 @@ import type { Owner } from '../reactivity/index'
5
5
  import { DOM_PROPS } from '../attrs'
6
6
  import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, untrack } from '../reactivity/index'
7
7
  import { assertRenderable } from '../unrenderable'
8
- import { claimInsert, isBlockedAttr, setAttr, setClass, setProp, setStyle, skipRange } from './index'
8
+ import { claimInsert, claimRange, isBlockedAttr, setAttr, setClass, setProp, setStyle, skipRange } from './index'
9
9
 
10
10
  const RAW_HTML = Symbol.for('kay.html')
11
11
 
@@ -147,6 +147,23 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
147
147
  })
148
148
  }
149
149
 
150
+ // Removes rendered nodes; an array is a run of siblings, removed whole with what inner inserts added between its ends since.
151
+ function clearRendered(current: Node | Node[] | null): void {
152
+ if (Array.isArray(current) && current.length > 1) {
153
+ const last = current[current.length - 1]!
154
+ let node: Node | null = current[0]!
155
+ if (last.parentNode !== null && node.parentNode === last.parentNode) {
156
+ while (node !== null) {
157
+ const next: Node | null = node === last ? null : node.nextSibling
158
+ node.parentNode!.removeChild(node)
159
+ node = next
160
+ }
161
+ return
162
+ }
163
+ }
164
+ clearInserted(current)
165
+ }
166
+
150
167
  function clearInserted(current: Node | Node[] | null): void {
151
168
  if (current === null)
152
169
  return
@@ -218,6 +235,8 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
218
235
  }
219
236
  const next = res.result
220
237
  const ssrNodes = res.nodes
238
+ // An insert born in a fragment follows its marker into the parent the fragment was appended to.
239
+ const host = marker?.parentNode ?? parent
221
240
 
222
241
  if (next == null && ssrNodes !== undefined) {
223
242
  current = ssrNodes
@@ -225,7 +244,7 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
225
244
  }
226
245
 
227
246
  if (next == null || typeof next === 'boolean') {
228
- clearInserted(current)
247
+ clearRendered(current)
229
248
  if (ssrNodes !== undefined)
230
249
  clearInserted(ssrNodes)
231
250
  current = null
@@ -237,7 +256,7 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
237
256
  if (typeof next === 'string' || typeof next === 'number') {
238
257
  const str = String(next)
239
258
  if (current !== null) {
240
- clearInserted(current)
259
+ clearRendered(current)
241
260
  current = null
242
261
  }
243
262
  if (textNode === undefined) {
@@ -251,7 +270,7 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
251
270
  if (ssrNodes !== undefined)
252
271
  clearInserted(ssrNodes)
253
272
  textNode = document.createTextNode(str)
254
- parent.insertBefore(textNode, marker)
273
+ host.insertBefore(textNode, marker)
255
274
  }
256
275
  }
257
276
  else if (textNode.data !== str) {
@@ -274,38 +293,51 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
274
293
  if (next instanceof Node) {
275
294
  if (current === next)
276
295
  return
277
- if (current === null && next.parentNode === parent) {
296
+ if (current === null && next.parentNode === host) {
278
297
  if (ssrNodes !== undefined)
279
298
  clearInserted(ssrNodes.filter(n => n !== next))
280
299
  current = next
281
300
  return
282
301
  }
283
- clearInserted(current)
302
+ clearRendered(current)
284
303
  if (ssrNodes !== undefined)
285
304
  clearInserted(ssrNodes)
286
305
  if (next.nodeType === 11) {
287
306
  const nodes = Array.from(next.childNodes)
288
- parent.insertBefore(next, marker)
307
+ host.insertBefore(next, marker)
289
308
  current = nodes
290
309
  }
291
310
  else {
292
- parent.insertBefore(next, marker)
311
+ host.insertBefore(next, marker)
293
312
  current = next
294
313
  }
295
314
  return
296
315
  }
297
316
 
298
317
  if (Array.isArray(next)) {
299
- clearInserted(current)
318
+ clearRendered(current)
300
319
  if (ssrNodes !== undefined) {
301
320
  const kept = new Set(next)
302
321
  clearInserted(ssrNodes.filter(n => !kept.has(n)))
303
322
  }
304
- current = insertAll(parent, marker, next)
323
+ current = insertAll(host, marker, next)
305
324
  }
306
325
  })
307
326
  }
308
327
 
328
+ // A dynamic child of a root fragment: hydrates against its SSR range, or renders between two comments that travel with the fragment, so whoever removes the fragment's nodes removes what it renders later.
329
+ export function fragInsert(value: () => unknown): Node | null {
330
+ const start = claimRange()
331
+ if (start !== null) {
332
+ insert(start.parentNode!, value, skipRange(start), start)
333
+ return null
334
+ }
335
+ const f = document.createDocumentFragment()
336
+ f.appendChild(document.createComment(''))
337
+ insert(f, value, f.appendChild(document.createComment('')))
338
+ return f
339
+ }
340
+
309
341
  export function show(
310
342
  parent: Node,
311
343
  marker: Node | null,
@@ -324,8 +356,7 @@ export function show(
324
356
  disposeOwner(owner)
325
357
  owner = undefined
326
358
  }
327
- for (let i = 0; i < nodes.length; i++)
328
- nodes[i]!.parentNode?.removeChild(nodes[i]!)
359
+ clearRendered(nodes)
329
360
  nodes = []
330
361
  }
331
362
 
package/src/dom/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Kay v2 minimal DOM & hydration core (loop -> kay/dom-loop, extras -> kay/dom-extras for fine-grained chunk splitting).
1
+ // Kay v2 minimal DOM & hydration core (loop -> @kayjs/kay/internal/dom-loop, extras -> @kayjs/kay/internal/dom-extras for fine-grained chunk splitting).
2
2
 
3
3
  import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
4
4
  import { batch, createOwner, disposeOwner, runWithOwner } from '../reactivity/index'
@@ -188,6 +188,30 @@ export function template(html: string, isSvg?: boolean): () => Node {
188
188
  }
189
189
  }
190
190
 
191
+ // Moves the hydration cursor past the SSR range of a root fragment's dynamic child (`<!--k[-->...<!--k]-->` or `<!---->text<!---->`) and returns its opening marker; null when not hydrating.
192
+ export function claimRange(): Node | null {
193
+ const start = hydrating ? hydrateNode : null
194
+ if (start === null || start.nodeType !== 8)
195
+ return null
196
+ hydrateNode = skipRange(start)?.nextSibling ?? null
197
+ return start
198
+ }
199
+
200
+ // A text child of a root fragment, claimed from the SSR markup while hydrating; a dynamic one sits between `<!---->` markers.
201
+ export function fragText(data: string, dynamic?: boolean): Text {
202
+ if (dynamic) {
203
+ const start = claimRange()
204
+ if (start !== null)
205
+ return textAfter(start)
206
+ }
207
+ else if (hydrating && hydrateNode !== null && hydrateNode.nodeType === 3) {
208
+ const text = hydrateNode as Text
209
+ hydrateNode = text.nextSibling
210
+ return text
211
+ }
212
+ return document.createTextNode(data)
213
+ }
214
+
191
215
  export function frag(...nodes: Node[]): Node | null {
192
216
  if (hydrating)
193
217
  return null
package/src/index.ts CHANGED
@@ -20,16 +20,3 @@ export type { ActionForm, ClientAction, UseActionOptions } from './dom/action'
20
20
  export type { Component, Html, HydrateStrategy, KayChild } from './jsx-runtime'
21
21
  export type { ExtractRouteParams, KayLocals, LayoutProps, LoaderData, LoaderFn, NotFoundResult, PageProps, RouteContext } from './server/index'
22
22
 
23
- import type { Component, HydrateStrategy } from './jsx-runtime'
24
-
25
- export interface IslandOptions {
26
- hydrate?: HydrateStrategy | undefined
27
- }
28
-
29
- /** Optional component-level hydration metadata helper. */
30
- export function island<P>(component: Component<P>, options: IslandOptions = {}): Component<P> & { $hydrate?: HydrateStrategy } {
31
- const tagged = component as Component<P> & { $hydrate?: HydrateStrategy }
32
- if (options.hydrate !== undefined)
33
- tagged.$hydrate = options.hydrate
34
- return tagged
35
- }
@@ -509,7 +509,7 @@ export namespace JSX {
509
509
  export interface ElementChildrenAttribute {
510
510
  children: object
511
511
  }
512
- /** Augment this interface via `declare module 'kay/jsx-runtime'` to register custom elements (`<my-widget>`). */
512
+ /** Augment this interface via `declare module '@kayjs/kay/jsx-runtime'` to register custom elements (`<my-widget>`). */
513
513
  export interface CustomElements {}
514
514
  export interface IntrinsicElements extends HtmlIntrinsicElements, SvgIntrinsicElements, CustomElements {}
515
515
  }
@@ -0,0 +1,49 @@
1
+ // Config helpers: `defineConfig`, `definePlugin`, and the merge of `kay.config.ts` runtime keys with caller overrides.
2
+
3
+ import type { KayConfig, KayPlugin, ServerRuntimeConfig } from './types'
4
+
5
+ export function defineConfig(config: KayConfig): KayConfig {
6
+ return config
7
+ }
8
+
9
+ /** Forwards every runtime key from `kay.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`). */
10
+ export function pickRuntimeConfig(config: KayConfig | undefined): ServerRuntimeConfig {
11
+ if (config === undefined)
12
+ return {}
13
+ const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, ...runtime } = config
14
+ return runtime
15
+ }
16
+
17
+ const RUNTIME_CONFIG_KEYS: readonly (keyof ServerRuntimeConfig)[] = [
18
+ 'site',
19
+ 'lang',
20
+ 'assetPrefix',
21
+ 'security',
22
+ 'trustedOrigins',
23
+ 'trustProxy',
24
+ 'maxRequestBodySize',
25
+ 'streamTimeout',
26
+ 'compress',
27
+ 'onError',
28
+ 'plugins',
29
+ ]
30
+
31
+ /** Merges runtime options from `kay.config.ts` with explicit caller overrides (ignoring `undefined` override fields). */
32
+ export function resolveServerConfig(
33
+ fileConfig: KayConfig | undefined,
34
+ overrides?: Partial<ServerRuntimeConfig> | undefined,
35
+ ): ServerRuntimeConfig {
36
+ const merged: Record<string, unknown> = { ...pickRuntimeConfig(fileConfig) }
37
+ if (overrides !== undefined) {
38
+ for (const key of RUNTIME_CONFIG_KEYS) {
39
+ const value = overrides[key]
40
+ if (value !== undefined)
41
+ merged[key] = value
42
+ }
43
+ }
44
+ return merged as ServerRuntimeConfig
45
+ }
46
+
47
+ export function definePlugin(plugin: KayPlugin): KayPlugin {
48
+ return plugin
49
+ }
@@ -1,29 +1,8 @@
1
1
  // Per-build / per-server scoped runtime context (AsyncLocalStorage-backed, zero mutable process globals).
2
2
 
3
+ import type { ServiceKey } from './services'
3
4
  import { AsyncLocalStorage } from 'node:async_hooks'
4
5
 
5
- export interface ActiveI18nConfig {
6
- readonly locales: readonly string[]
7
- readonly defaultLocale: string
8
- readonly prefixDefault: boolean
9
- }
10
-
11
- export const I18N_CONFIG_SERVICE = 'kay.i18n.config'
12
-
13
- export interface ContentImageResult {
14
- src: string
15
- srcset?: string | undefined
16
- avifSrcset?: string | undefined
17
- sizes?: string | undefined
18
- width?: number | undefined
19
- height?: number | undefined
20
- loading?: 'lazy' | 'eager' | undefined
21
- }
22
-
23
- export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
24
-
25
- export const CONTENT_IMAGE_RESOLVER_SERVICE = 'kay.content.imageResolver'
26
-
27
6
  export interface AppRuntimeContext {
28
7
  readonly root: string
29
8
  readonly outDir: string
@@ -31,8 +10,8 @@ export interface AppRuntimeContext {
31
10
  readonly assetPrefix: string
32
11
  readonly site?: string | undefined
33
12
  readonly dev: boolean
34
- provide<T>(key: string, value: T): void
35
- inject<T>(key: string): T | undefined
13
+ provide<T>(key: ServiceKey<T>, value: T): void
14
+ inject<T>(key: ServiceKey<T>): T | undefined
36
15
  registerPublicFile(relPath: string): void
37
16
  }
38
17
 
@@ -62,11 +41,12 @@ export function createAppContext(options: CreateAppContextOptions): AppRuntimeCo
62
41
  assetPrefix: options.assetPrefix,
63
42
  ...(site !== undefined && site !== '' ? { site } : {}),
64
43
  dev: options.dev,
65
- provide<T>(key: string, value: T): void {
66
- services.set(key, value)
44
+ // Keyed by name: the natively loaded config and the bundled app each hold their own key object.
45
+ provide<T>(key: ServiceKey<T>, value: T): void {
46
+ services.set(key.name, value)
67
47
  },
68
- inject<T>(key: string): T | undefined {
69
- return services.get(key) as T | undefined
48
+ inject<T>(key: ServiceKey<T>): T | undefined {
49
+ return services.get(key.name) as T | undefined
70
50
  },
71
51
  registerPublicFile(relPath: string): void {
72
52
  options.onRegisterPublicFile?.(relPath)