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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -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/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  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 +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -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 +5 -15
  55. package/src/unrenderable.ts +35 -0
@@ -1,48 +1,40 @@
1
1
  // Kay v2 SSR compiler: compiles TSX directly to flat string concatenation, inline for-loops,
2
- // static attribute literal folding, and compile-time static island props.
3
-
4
- import type { AstNode, ModuleAnalysis } from './analyze'
2
+ // static attribute literal folding, compile-time static island props, and shared balanced hydration markers.
3
+
4
+ import type {
5
+ JSXAttributeItem,
6
+ JSXChild,
7
+ JSXElement,
8
+ JSXFragment,
9
+ Node,
10
+ } from 'oxc-parser'
11
+ import type { ModuleAnalysis } from './analyze'
5
12
  import { analyzeModule, parseTsx, walk } from './analyze'
13
+ import { mistake } from './mistakes'
6
14
  import { SourceEditor } from './patch'
7
-
8
- export function escapeStaticText(str: string): string {
9
- return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
10
- }
11
-
12
- const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
13
- const CLOSE_STYLE_RE = /<\/(style)/gi
14
- const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
15
-
16
- function escapeRawText(str: string, tag: 'style' | 'script'): string {
17
- if (tag === 'script') {
18
- return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
19
- body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
20
- }
21
- return str.replace(CLOSE_STYLE_RE, '<\\/$1')
22
- }
23
-
24
- const VOID_ELEMENTS = new Set([
25
- 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
26
- 'link', 'meta', 'param', 'source', 'track', 'wbr',
27
- ])
28
-
29
- const EVENT_ATTR = /^on[A-Z]/
30
- const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
31
- const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
32
- const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
33
-
34
- function isStringBoolAttr(name: string): boolean {
35
- const lower = name.toLowerCase()
36
- return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
37
- }
38
-
39
- function isUnsafeUrlAttr(name: string, value: unknown): boolean {
40
- if (!URL_ATTRS.has(name.toLowerCase()))
41
- return false
42
- return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
43
- }
44
-
45
- function containsDirectAwait(root: AstNode): boolean {
15
+ import {
16
+ classifyJsxChild,
17
+ containsJsx,
18
+ decodeHtmlEntities,
19
+ escapeRawText,
20
+ escapeStaticAttr,
21
+ escapeStaticText,
22
+ EVENT_ATTR,
23
+ filterMeaningfulChildren,
24
+ isBlockedAttr,
25
+ isComponentTag,
26
+ isJsxNode,
27
+ isNodeCapableExpr,
28
+ isStringBoolAttr,
29
+ isUnsafeUrlAttr,
30
+ jsxTagName,
31
+ RAW_TEXT_ELEMENTS,
32
+ staticLiteral,
33
+ unwrapParens,
34
+ VOID_ELEMENTS,
35
+ } from './shared'
36
+
37
+ function containsDirectAwait(root: Node): boolean {
46
38
  let found = false
47
39
  walk(root, (child) => {
48
40
  if (found)
@@ -115,73 +107,14 @@ class StringParts {
115
107
  }
116
108
  }
117
109
 
118
- export function cleanJsxText(raw: string): string {
119
- if (!raw.includes('\n'))
120
- return raw
121
- const lines = raw.split(/\r\n|\n|\r/)
122
- let out = ''
123
- for (let i = 0; i < lines.length; i++) {
124
- let line = lines[i]!.replace(/\t/g, ' ')
125
- if (i > 0)
126
- line = line.replace(/^ +/, '')
127
- if (i < lines.length - 1)
128
- line = line.replace(/ +$/, '')
129
- if (line !== '') {
130
- if (out !== '')
131
- out += ' '
132
- out += line
133
- }
134
- }
135
- return out
136
- }
137
-
138
- function escapeStaticAttr(str: string): string {
139
- return str
140
- .replaceAll('&', '&amp;')
141
- .replaceAll('"', '&quot;')
142
- .replaceAll('<', '&lt;')
143
- .replaceAll('>', '&gt;')
144
- }
145
-
146
- function jsxTagName(node: AstNode): string {
147
- if (node.type === 'JSXIdentifier')
148
- return node.name as string
149
- if (node.type === 'JSXMemberExpression')
150
- return `${jsxTagName(node.object)}.${node.property.name}`
151
- if (node.type === 'JSXNamespacedName')
152
- return `${node.namespace.name}:${node.name.name}`
153
- return ''
154
- }
155
-
156
- function isComponentTag(tag: string): boolean {
157
- const first = tag.charCodeAt(0)
158
- return (first >= 65 && first <= 90) || tag.includes('.')
159
- }
160
-
161
- function unwrapParens(node: AstNode): AstNode {
162
- let cur = node
163
- while (cur.type === 'ParenthesizedExpression')
164
- cur = cur.expression as AstNode
165
- return cur
166
- }
167
-
168
- function isSimpleLiteral(node: AstNode): { ok: true, value: string | number | boolean | null } | { ok: false } {
169
- if (node.type === 'Literal') {
170
- const v = node.value
171
- if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null)
172
- return { ok: true, value: v }
173
- }
174
- if (node.type === 'UnaryExpression' && node.operator === '-' && node.argument?.type === 'Literal' && typeof node.argument.value === 'number')
175
- return { ok: true, value: -node.argument.value }
176
- return { ok: false }
177
- }
178
-
179
- function isStaticNullish(node: AstNode): boolean {
110
+ function isStaticNullish(node: Node): boolean {
180
111
  return (node.type === 'Identifier' && node.name === 'undefined')
181
112
  || (node.type === 'Literal' && node.value === null)
182
113
  }
183
114
 
184
- function formatStaticAttrBranch(attrName: string, node: AstNode): string | undefined {
115
+ function formatStaticAttrBranch(attrName: string, node: Node): string | undefined {
116
+ if (isBlockedAttr(attrName))
117
+ return '""'
185
118
  if (isStaticNullish(node))
186
119
  return '""'
187
120
  if (node.type === 'Literal') {
@@ -217,23 +150,16 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
217
150
 
218
151
  const islands = options.islands
219
152
  const emitMarkers = options.emitMarkers ?? options.isIsland ?? analysis.isInteractive
153
+ const jsxNodes = analysis.jsxNodes
220
154
 
221
- function compileSubExpression(node: AstNode): string {
222
- let hasNestedJsx = false
223
- walk(node, (child) => {
224
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
225
- hasNestedJsx = true
226
- return false
227
- }
228
- return undefined
229
- })
230
- if (!hasNestedJsx)
155
+ function compileSubExpression(node: Node): string {
156
+ if (!containsJsx(node, jsxNodes))
231
157
  return code.slice(node.start, node.end)
232
158
 
233
159
  const sub = new SourceEditor(code.slice(node.start, node.end))
234
- const offset = node.start as number
160
+ const offset = node.start
235
161
  walk(node, (child) => {
236
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
162
+ if (isJsxNode(child)) {
237
163
  sub.replace(child.start - offset, child.end - offset, compileRootJsx(child))
238
164
  return false
239
165
  }
@@ -242,10 +168,86 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
242
168
  return sub.toString()
243
169
  }
244
170
 
171
+ function serializeComponentProps(attrs: readonly JSXAttributeItem[]): {
172
+ propEntries: string[]
173
+ allStaticProps: boolean
174
+ staticPropsObj: Record<string, unknown>
175
+ hydrateExpr: string | undefined
176
+ staticHydrate: string | undefined
177
+ } {
178
+ const propEntries: string[] = []
179
+ let allStaticProps = true
180
+ const staticPropsObj: Record<string, unknown> = {}
181
+ let hydrateExpr: string | undefined
182
+ let staticHydrate: string | undefined
183
+
184
+ for (const attr of attrs) {
185
+ if (attr.type === 'JSXSpreadAttribute') {
186
+ allStaticProps = false
187
+ propEntries.push(`...(${compileSubExpression(attr.argument)})`)
188
+ continue
189
+ }
190
+ const name = jsxTagName(attr.name)
191
+ if (name === 'key')
192
+ continue
193
+ if (name === '$hydrate') {
194
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
195
+ staticHydrate = attr.value.value
196
+ hydrateExpr = JSON.stringify(attr.value.value)
197
+ }
198
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
199
+ hydrateExpr = compileSubExpression(attr.value.expression)
200
+ }
201
+ continue
202
+ }
203
+
204
+ const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
205
+ if (attr.value === null) {
206
+ propEntries.push(`${propKey}: true`)
207
+ staticPropsObj[name] = true
208
+ }
209
+ else if (attr.value.type === 'Literal') {
210
+ propEntries.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
211
+ staticPropsObj[name] = attr.value.value
212
+ }
213
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
214
+ const expr = attr.value.expression
215
+ const lit = staticLiteral(expr)
216
+ if (lit.ok)
217
+ staticPropsObj[name] = lit.value
218
+ else
219
+ allStaticProps = false
220
+ propEntries.push(`${propKey}: ${compileSubExpression(expr)}`)
221
+ }
222
+ }
223
+
224
+ return { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate }
225
+ }
226
+
227
+ function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = emitMarkers): string {
228
+ const bufVar = `_o${loopCounter++}`
229
+ const stmts: string[] = []
230
+ const parts = new StringParts()
231
+ const flush = () => {
232
+ if (!parts.isEmpty()) {
233
+ stmts.push(`${bufVar} += ${parts.toExpr()};`)
234
+ parts.clear()
235
+ }
236
+ }
237
+ emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), undefined, slotMarkers)
238
+ if (stmts.length === 0)
239
+ return parts.toExpr()
240
+ flush()
241
+ const hasAwait = children.some(c => containsDirectAwait(c))
242
+ if (hasAwait)
243
+ return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
244
+ return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
245
+ }
246
+
245
247
  // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
246
- function emitIntoBuffer(node: AstNode, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void): void {
248
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void): void {
247
249
  if (node.type === 'JSXFragment') {
248
- emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt)
250
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt)
249
251
  return
250
252
  }
251
253
 
@@ -258,7 +260,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
258
260
  parts.pushStatic(`<${tag}`)
259
261
  let innerHtmlExpr: string | undefined
260
262
 
261
- for (const attr of node.openingElement.attributes as AstNode[]) {
263
+ for (const attr of node.openingElement.attributes) {
262
264
  if (attr.type === 'JSXSpreadAttribute') {
263
265
  parts.pushExpr(`${use('ssrSpread')}(${compileSubExpression(attr.argument)})`)
264
266
  continue
@@ -269,12 +271,15 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
269
271
  if (rawName === 'innerHTML') {
270
272
  if (attr.value?.type === 'Literal')
271
273
  innerHtmlExpr = JSON.stringify(String(attr.value.value))
272
- else if (attr.value?.type === 'JSXExpressionContainer')
274
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
273
275
  innerHtmlExpr = `${use('ssrRaw')}(${compileSubExpression(attr.value.expression)})`
274
276
  continue
275
277
  }
276
278
 
277
279
  const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
280
+ if (isBlockedAttr(name))
281
+ continue
282
+
278
283
  if (attr.value === null) {
279
284
  parts.pushStatic(isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`)
280
285
  }
@@ -282,8 +287,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
282
287
  if (!isUnsafeUrlAttr(name, attr.value.value))
283
288
  parts.pushStatic(` ${name}="${escapeStaticAttr(String(attr.value.value))}"`)
284
289
  }
285
- else if (attr.value.type === 'JSXExpressionContainer') {
286
- const expr = attr.value.expression as AstNode
290
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
291
+ const expr = attr.value.expression
287
292
 
288
293
  // Fold static ternary attribute branches (`class={cond ? 'stock out' : 'stock in'}`) with 0 runtime escaping!
289
294
  if (name !== 'style' && expr.type === 'ConditionalExpression') {
@@ -310,259 +315,216 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
310
315
  if (innerHtmlExpr !== undefined)
311
316
  parts.pushExpr(innerHtmlExpr)
312
317
  else
313
- emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
318
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
314
319
  parts.pushStatic(`</${tag}>`)
315
320
  }
316
321
 
317
322
  function emitChildrenIntoBuffer(
318
- children: AstNode[],
323
+ children: readonly JSXChild[],
319
324
  bufVar: string,
320
325
  parts: StringParts,
321
326
  flushParts: () => void,
322
327
  pushStmt: (stmt: string) => void,
323
328
  rawTextTag?: 'style' | 'script',
329
+ slotMarkers = emitMarkers,
324
330
  ): void {
325
- const meaningful = children.filter((c) => {
326
- if (c.type === 'JSXText')
327
- return cleanJsxText(c.value as string) !== ''
328
- if (c.type === 'JSXExpressionContainer' && c.expression.type === 'JSXEmptyExpression')
329
- return false
330
- return true
331
- })
332
- const hasSiblings = meaningful.length > 1
333
-
334
- for (let i = 0; i < meaningful.length; i++) {
335
- const child = meaningful[i]!
336
- const isLast = i === meaningful.length - 1
337
- if (child.type === 'JSXText') {
338
- const text = cleanJsxText(child.value as string)
339
- parts.pushStatic(rawTextTag !== undefined ? escapeRawText(text, rawTextTag) : text)
340
- }
341
- else if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
342
- emitIntoBuffer(child, bufVar, parts, flushParts, pushStmt)
331
+ const meaningful = filterMeaningfulChildren(children)
332
+ const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c, jsxNodes) })).filter(s => s.slot !== undefined)
333
+ const hasSiblings = slots.length > 1
334
+ let hadVariableRange = false
335
+
336
+ for (let i = 0; i < slots.length; i++) {
337
+ const slot = slots[i]!.slot!
338
+ const isLast = i === slots.length - 1
339
+
340
+ if (slot.kind === 'static-text') {
341
+ if (rawTextTag !== undefined)
342
+ parts.pushStatic(escapeRawText(slot.text, rawTextTag))
343
+ else
344
+ parts.pushStatic(escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)))
345
+ continue
343
346
  }
344
- else if (child.type === 'JSXExpressionContainer') {
345
- const expr = child.expression as AstNode
346
347
 
347
- // Fold static string literal expressions like `{' '}` or `<style>{':root { ... }'}</style>` directly into static text
348
- if (expr.type === 'Literal' && typeof expr.value === 'string') {
349
- parts.pushStatic(rawTextTag !== undefined ? escapeRawText(expr.value, rawTextTag) : escapeStaticText(expr.value))
348
+ if (rawTextTag !== undefined) {
349
+ const rawChild = slots[i]!.child
350
+ if (rawChild.type === 'JSXExpressionContainer' && rawChild.expression.type !== 'JSXEmptyExpression') {
351
+ const expr = rawChild.expression
352
+ if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0 && expr.quasis.length === 1) {
353
+ const cooked = expr.quasis[0]?.value.cooked
354
+ if (typeof cooked === 'string') {
355
+ parts.pushStatic(escapeRawText(cooked, rawTextTag))
356
+ continue
357
+ }
358
+ }
359
+ parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
350
360
  continue
351
361
  }
362
+ }
352
363
 
353
- // Fold static no-substitution template literals inside `<style>`/`<script>` directly into raw text
354
- if (
355
- rawTextTag !== undefined
356
- && expr.type === 'TemplateLiteral'
357
- && (expr.expressions as AstNode[]).length === 0
358
- && (expr.quasis as AstNode[]).length === 1
359
- ) {
360
- const cooked = expr.quasis[0]?.value?.cooked
361
- if (typeof cooked === 'string') {
362
- parts.pushStatic(escapeRawText(cooked, rawTextTag))
363
- continue
364
- }
365
- }
364
+ if (slot.kind === 'element') {
365
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
366
+ continue
367
+ }
366
368
 
367
- if (rawTextTag !== undefined) {
368
- parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
369
- continue
369
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
370
+ if (slotMarkers && hasSiblings) {
371
+ parts.pushStatic('<!--k[-->')
372
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
373
+ if (!isLast)
374
+ parts.pushStatic('<!--k]-->')
375
+ }
376
+ else {
377
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
370
378
  }
379
+ hadVariableRange = true
380
+ continue
381
+ }
371
382
 
372
- // Inline `.map((item, idx?) => <jsx>)` directly into a flat `for` loop on `bufVar`!
373
- if (
374
- expr.type === 'CallExpression'
375
- && expr.callee?.type === 'MemberExpression'
376
- && !expr.callee.computed
377
- && expr.callee.property?.name === 'map'
378
- && expr.arguments?.length === 1
379
- ) {
380
- const cb = expr.arguments[0] as AstNode
381
- if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && !cb.async && cb.body !== null) {
382
- const body = (cb.body.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body) as AstNode
383
- if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
384
- const target = compileSubExpression(expr.callee.object)
385
- const params = cb.params as AstNode[]
386
- const itemParam = params[0]?.type === 'Identifier' ? params[0].name as string : undefined
387
- const idxParam = params[1]?.type === 'Identifier' ? params[1].name as string : undefined
388
-
389
- if (itemParam !== undefined) {
390
- flushParts()
391
- const n = loopCounter++
392
- const arrVar = `_a${n}`
393
- const idxVar = idxParam ?? `_i${n}`
394
- const innerStmts: string[] = []
395
- const innerParts = new StringParts()
396
- const flushInner = () => {
397
- if (!innerParts.isEmpty()) {
398
- innerStmts.push(`${bufVar} += ${innerParts.toExpr()};`)
399
- innerParts.clear()
400
- }
401
- }
402
- emitIntoBuffer(body, bufVar, innerParts, flushInner, s => innerStmts.push(s))
403
- flushInner()
404
-
405
- pushStmt(
406
- `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
407
- )
408
- if (emitMarkers && !isLast)
409
- parts.pushStatic('<!---->')
410
- continue
411
- }
383
+ if (slot.kind === 'loop') {
384
+ const { match } = slot
385
+ const needsBracket = slotMarkers && (!isLast || hadVariableRange)
386
+ if (needsBracket)
387
+ parts.pushStatic('<!--k[-->')
388
+
389
+ const itemParam = match.params[0]?.type === 'Identifier' ? match.params[0].name : undefined
390
+ const idxParam = match.params[1]?.type === 'Identifier' ? match.params[1].name : undefined
391
+
392
+ if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
393
+ flushParts()
394
+ const n = loopCounter++
395
+ const arrVar = `_a${n}`
396
+ const idxVar = idxParam ?? `_i${n}`
397
+ const innerStmts: string[] = []
398
+ const innerParts = new StringParts()
399
+ const flushInner = () => {
400
+ if (!innerParts.isEmpty()) {
401
+ innerStmts.push(`${bufVar} += ${innerParts.toExpr()};`)
402
+ innerParts.clear()
412
403
  }
413
404
  }
405
+ emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
406
+ flushInner()
407
+
408
+ const target = compileSubExpression(match.target)
409
+ pushStmt(
410
+ `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
411
+ )
412
+ }
413
+ else if (match.isJsxBody) {
414
+ const target = compileSubExpression(match.target)
415
+ const params = match.params.map(p => code.slice(p.start, p.end)).join(', ')
416
+ parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
417
+ }
418
+ else {
419
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(match.call)})`)
414
420
  }
415
421
 
416
- parts.pushExpr(compileExpressionAsString(expr, hasSiblings, isLast))
422
+ if (needsBracket)
423
+ parts.pushStatic('<!--k]-->')
424
+ hadVariableRange = true
425
+ continue
417
426
  }
418
- }
419
- }
420
427
 
421
- function compileExpressionAsString(expr: AstNode, hasSiblings: boolean, isLast = true): string {
422
- if (expr.type === 'JSXElement' || expr.type === 'JSXFragment')
423
- return compileJsxToStringExpr(expr)
428
+ if (slot.kind === 'and-show') {
429
+ const left = compileSubExpression(slot.expr.left)
430
+ const right = compileJsxToStringExpr(slot.right)
431
+ if (slotMarkers && hasSiblings) {
432
+ parts.pushStatic('<!--k[-->')
433
+ parts.pushExpr(`((${left}) ? (${right}) : "")`)
434
+ parts.pushStatic('<!--k]-->')
435
+ }
436
+ else {
437
+ parts.pushExpr(`((${left}) ? (${right}) : "")`)
438
+ }
439
+ hadVariableRange = true
440
+ continue
441
+ }
424
442
 
425
- if (
426
- expr.type === 'CallExpression'
427
- && expr.callee?.type === 'MemberExpression'
428
- && !expr.callee.computed
429
- && expr.callee.property?.name === 'map'
430
- && expr.arguments?.length === 1
431
- ) {
432
- const cb = expr.arguments[0] as AstNode
433
- if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && !cb.async && cb.body !== null) {
434
- const body = (cb.body.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body) as AstNode
435
- if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
436
- const target = compileSubExpression(expr.callee.object)
437
- const params = (cb.params as AstNode[]).map(p => code.slice(p.start, p.end)).join(', ')
438
- const rendered = `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
439
- return emitMarkers && !isLast ? `(${rendered}) + "<!---->"` : rendered
443
+ if (slot.kind === 'ternary-show') {
444
+ const test = compileSubExpression(slot.expr.test)
445
+ const cons = compileExpressionAsString(slot.cons)
446
+ const alt = compileExpressionAsString(slot.alt)
447
+ if (slotMarkers && hasSiblings) {
448
+ parts.pushStatic('<!--k[-->')
449
+ parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
450
+ parts.pushStatic('<!--k]-->')
440
451
  }
441
- if (body.type === 'BlockStatement') {
442
- let blockHasJsx = false
443
- walk(body, (c) => {
444
- if (c.type === 'JSXElement' || c.type === 'JSXFragment') {
445
- blockHasJsx = true
446
- return false
447
- }
448
- return undefined
449
- })
450
- if (blockHasJsx) {
451
- const rendered = `${use('esc')}(${compileSubExpression(expr)})`
452
- return emitMarkers && !isLast ? `(${rendered}) + "<!---->"` : rendered
453
- }
452
+ else {
453
+ parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
454
454
  }
455
+ hadVariableRange = true
456
+ continue
457
+ }
458
+
459
+ // Generic expression slot
460
+ const exprCode = compileSubExpression(slot.expr)
461
+ const rendered = `${use('esc')}(${exprCode})`
462
+ if (isNodeCapableExpr(slot.expr, jsxNodes)) {
463
+ if (slotMarkers && hasSiblings) {
464
+ parts.pushStatic('<!--k[-->')
465
+ parts.pushExpr(rendered)
466
+ if (!isLast)
467
+ parts.pushStatic('<!--k]-->')
468
+ }
469
+ else {
470
+ parts.pushExpr(rendered)
471
+ }
472
+ hadVariableRange = true
473
+ }
474
+ else if (slotMarkers && hasSiblings) {
475
+ parts.pushStatic('<!---->')
476
+ parts.pushExpr(rendered)
477
+ if (!isLast)
478
+ parts.pushStatic('<!---->')
479
+ }
480
+ else {
481
+ parts.pushExpr(rendered)
455
482
  }
456
483
  }
484
+ }
457
485
 
486
+ function compileExpressionAsString(expr: Node): string {
487
+ if (isJsxNode(expr))
488
+ return compileJsxToStringExpr(expr)
458
489
  if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
459
490
  const right = unwrapParens(expr.right)
460
- if (right.type === 'JSXElement' || right.type === 'JSXFragment') {
461
- const left = compileSubExpression(expr.left)
462
- const emptyVal = emitMarkers && !isLast ? '"<!---->"' : '""'
463
- return `((${left}) ? (${compileJsxToStringExpr(right)}) : ${emptyVal})`
464
- }
491
+ if (isJsxNode(right))
492
+ return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
465
493
  }
466
-
467
494
  if (expr.type === 'ConditionalExpression') {
468
495
  const consNode = unwrapParens(expr.consequent)
469
496
  const altNode = unwrapParens(expr.alternate)
470
- if (consNode.type === 'JSXElement' || consNode.type === 'JSXFragment' || altNode.type === 'JSXElement' || altNode.type === 'JSXFragment') {
471
- const test = compileSubExpression(expr.test)
472
- const cons = compileExpressionAsString(consNode, false, true)
473
- const alt = compileExpressionAsString(altNode, false, true)
474
- const base = `((${test}) ? (${cons}) : (${alt}))`
475
- return emitMarkers && !isLast ? `(${base} || "<!---->")` : base
476
- }
497
+ if (isJsxNode(consNode) || isJsxNode(altNode))
498
+ return `((${compileSubExpression(expr.test)}) ? (${compileExpressionAsString(consNode)}) : (${compileExpressionAsString(altNode)}))`
477
499
  }
478
-
479
- const exprCode = compileSubExpression(expr)
480
- const rendered = `${use('esc')}(${exprCode})`
481
- if (emitMarkers && hasSiblings)
482
- return isLast ? `"<!---->" + ${rendered}` : `"<!---->" + ${rendered} + "<!---->"`
483
- return rendered
500
+ return `${use('esc')}(${compileSubExpression(expr)})`
484
501
  }
485
502
 
486
- function emitComponent(node: AstNode, tag: string, parts: StringParts): void {
487
- const attrs = node.openingElement.attributes as AstNode[]
488
- const propEntries: string[] = []
489
- let allStaticProps = true
490
- const staticPropsObj: Record<string, unknown> = {}
491
- let hydrateExpr: string | undefined
492
- let staticHydrate: string | undefined
493
-
494
- for (const attr of attrs) {
495
- if (attr.type === 'JSXSpreadAttribute') {
496
- allStaticProps = false
497
- propEntries.push(`...(${compileSubExpression(attr.argument)})`)
498
- continue
499
- }
500
- const name = jsxTagName(attr.name)
501
- if (name === 'key')
502
- continue
503
- if (name === '$hydrate') {
504
- if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
505
- staticHydrate = attr.value.value
506
- hydrateExpr = JSON.stringify(attr.value.value)
507
- }
508
- else if (attr.value?.type === 'JSXExpressionContainer') {
509
- hydrateExpr = compileSubExpression(attr.value.expression)
510
- }
511
- continue
512
- }
513
-
514
- const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
515
- if (attr.value === null) {
516
- propEntries.push(`${propKey}: true`)
517
- staticPropsObj[name] = true
518
- }
519
- else if (attr.value.type === 'Literal') {
520
- propEntries.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
521
- staticPropsObj[name] = attr.value.value
522
- }
523
- else if (attr.value.type === 'JSXExpressionContainer') {
524
- const expr = attr.value.expression as AstNode
525
- const lit = isSimpleLiteral(expr)
526
- if (lit.ok)
527
- staticPropsObj[name] = lit.value
528
- else
529
- allStaticProps = false
530
- propEntries.push(`${propKey}: ${compileSubExpression(expr)}`)
531
- }
532
- }
533
-
534
- const childNodes = node.children as AstNode[]
535
- const meaningfulChildren = childNodes.filter(c =>
536
- !(c.type === 'JSXText' && cleanJsxText(c.value as string) === '')
537
- && !(c.type === 'JSXExpressionContainer' && c.expression.type === 'JSXEmptyExpression'),
538
- )
503
+ function emitComponent(node: JSXElement, tag: string, parts: StringParts): void {
504
+ const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes)
505
+ const childNodes = node.children
506
+ const meaningfulChildren = filterMeaningfulChildren(childNodes)
539
507
  const hasChildren = meaningfulChildren.length > 0
540
508
 
541
- // Special case: <Suspense fallback={...}><AsyncComp /></Suspense> passes the raw component call/Promise!
509
+ // Special case: <Suspense fallback={...}><AsyncComp .../></Suspense> passes the raw component call/Promise!
542
510
  if (tag === 'Suspense') {
543
511
  if (meaningfulChildren.length === 1) {
544
512
  const only = meaningfulChildren[0]!
545
513
  if (only.type === 'JSXElement' && isComponentTag(jsxTagName(only.openingElement.name))) {
546
514
  const innerTag = jsxTagName(only.openingElement.name)
547
- const innerProps: string[] = []
548
- for (const attr of only.openingElement.attributes as AstNode[]) {
549
- if (attr.type === 'JSXAttribute') {
550
- const n = jsxTagName(attr.name)
551
- const k = /^[A-Za-z_$][\w$]*$/.test(n) ? n : JSON.stringify(n)
552
- if (attr.value === null)
553
- innerProps.push(`${k}: true`)
554
- else if (attr.value.type === 'Literal')
555
- innerProps.push(`${k}: ${JSON.stringify(attr.value.value)}`)
556
- else if (attr.value.type === 'JSXExpressionContainer')
557
- innerProps.push(`${k}: ${compileSubExpression(attr.value.expression)}`)
558
- }
515
+ const inner = serializeComponentProps(only.openingElement.attributes)
516
+ const innerMeaningful = filterMeaningfulChildren(only.children)
517
+ if (innerMeaningful.length > 0) {
518
+ const innerChildExpr = compileChildrenListToStringExpr(only.children)
519
+ inner.propEntries.push(`children: ${use('raw')}(${innerChildExpr})`)
559
520
  }
560
- propEntries.push(`children: ${innerTag}({ ${innerProps.join(', ')} })`)
521
+ const innerObj = inner.propEntries.length > 0 ? `{ ${inner.propEntries.join(', ')} }` : '{}'
522
+ propEntries.push(`children: ${innerTag}(${innerObj})`)
561
523
  }
562
- else if (only.type === 'JSXExpressionContainer') {
524
+ else if (only.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression') {
563
525
  propEntries.push(`children: ${compileSubExpression(only.expression)}`)
564
526
  }
565
- else {
527
+ else if (isJsxNode(only)) {
566
528
  propEntries.push(`children: ${use('raw')}(${compileJsxToStringExpr(only)})`)
567
529
  }
568
530
  }
@@ -571,9 +533,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
571
533
  return
572
534
  }
573
535
 
574
- const childExpr = hasChildren ? compileJsxToStringExpr({ type: 'JSXFragment', children: childNodes }) : '""'
536
+ const childrenHaveAwait = hasChildren && childNodes.some(c => containsDirectAwait(c))
537
+ const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes, false) : '""'
575
538
 
576
539
  const islandInfo = islands?.get(tag)
540
+ if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
541
+ throw mistake(`$hydrate on <${tag}>`, filename, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`)
542
+
577
543
  if (islandInfo !== undefined) {
578
544
  const propsCode = `{ ${propEntries.join(', ')} }`
579
545
  const callPropsCode = hasChildren
@@ -581,9 +547,9 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
581
547
  : propsCode
582
548
  const resolvedHydrate = staticHydrate ?? (hydrateExpr === undefined ? islandInfo.defaultHydrate : undefined)
583
549
 
584
- // Compile-time static island props fast path (only when not inside an island-reachable component):
585
- // 0 JSON.stringify / Object.keys / escAttr at runtime, while still incrementing island depth!
586
- if (!emitMarkers && allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
550
+ // Compile-time static island props fast path (only when not inside an island-reachable component and children don't contain direct `await`):
551
+ // 0 JSON.stringify / Object.keys / escAttr at runtime, while still recording rendered islands & island ID scope!
552
+ if (!emitMarkers && !childrenHaveAwait && allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
587
553
  const pAttr = Object.keys(staticPropsObj).length > 0
588
554
  ? ` p="${escapeStaticAttr(JSON.stringify(staticPropsObj))}"`
589
555
  : ''
@@ -591,29 +557,30 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
591
557
  ? ` h="${escapeStaticAttr(resolvedHydrate)}"`
592
558
  : ''
593
559
  const openTag = `<kay-island c="${escapeStaticAttr(islandInfo.chunk)}"${pAttr}${hAttr}>`
594
- parts.pushStatic(openTag)
595
- if (resolvedHydrate !== 'client')
596
- parts.pushExpr(`${use('ssrInIsland')}(() => ${use('ssrChild')}(${tag}(${callPropsCode})))`)
597
- parts.pushStatic('</kay-island>')
560
+ const hydrateArg = resolvedHydrate !== undefined ? JSON.stringify(resolvedHydrate) : 'undefined'
561
+ const renderArg = resolvedHydrate === 'client'
562
+ ? 'undefined'
563
+ : `() => ${use('ssrChild')}(${tag}(${callPropsCode}))`
564
+ parts.pushExpr(`${use('ssrIslandStatic')}(${JSON.stringify(islandInfo.chunk)}, ${JSON.stringify(openTag)}, ${renderArg}, ${hydrateArg})`)
598
565
  return
599
566
  }
600
567
 
601
568
  const hydrateArg = hydrateExpr ?? (islandInfo.defaultHydrate !== undefined ? JSON.stringify(islandInfo.defaultHydrate) : 'undefined')
602
- if (allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
569
+ if (!childrenHaveAwait && allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
603
570
  parts.pushExpr(
604
- `${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
571
+ `${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
605
572
  )
606
573
  return
607
574
  }
608
575
 
609
- // Hoist dynamic island props into a single binding so expressions (side effects & await) evaluate once!
576
+ // Hoist dynamic island props / awaited children into a single binding so expressions evaluate once!
610
577
  const pVar = `_p${loopCounter++}`
611
578
  const argNames = [pVar]
612
579
  const argExprs = [propsCode]
613
580
  let callArg = pVar
614
581
  if (hasChildren) {
615
582
  let childSlotVal = childExpr
616
- if (containsDirectAwait({ type: 'JSXFragment', children: childNodes })) {
583
+ if (childrenHaveAwait) {
617
584
  const cVar = `_c${loopCounter++}`
618
585
  argNames.push(cVar)
619
586
  argExprs.push(childExpr)
@@ -629,11 +596,33 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
629
596
  hArg = hVar
630
597
  }
631
598
  parts.pushExpr(
632
- `((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${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}))(${argExprs.join(', ')})`,
633
600
  )
634
601
  return
635
602
  }
636
603
 
604
+ const childrenHaveDynamic = hasChildren && childNodes.some((c) => {
605
+ let dynamic = false
606
+ walk(c, (n) => {
607
+ if (dynamic)
608
+ return false
609
+ if (n.type === 'JSXExpressionContainer' && n.expression.type !== 'JSXEmptyExpression')
610
+ dynamic = true
611
+ else if (n.type === 'JSXElement' && isComponentTag(jsxTagName(n.openingElement.name)))
612
+ dynamic = true
613
+ return undefined
614
+ })
615
+ return dynamic
616
+ })
617
+
618
+ // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
619
+ if (childrenHaveDynamic && !childrenHaveAwait) {
620
+ const cVar = `_c${loopCounter++}`
621
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${use('raw')}(${childExpr})) : ${cVar} }`].join(', ')
622
+ parts.pushExpr(`${use('ssrChild')}(${tag}((() => { let ${cVar}; return { ${propsWithGetter} }; })()))`)
623
+ return
624
+ }
625
+
637
626
  if (hasChildren)
638
627
  propEntries.push(`children: ${use('raw')}(${childExpr})`)
639
628
 
@@ -641,7 +630,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
641
630
  parts.pushExpr(`${use('ssrChild')}(${tag}(${propsObj}))`)
642
631
  }
643
632
 
644
- function compileJsxToStringExpr(node: AstNode): string {
633
+ function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
645
634
  const bufVar = `_o${loopCounter++}`
646
635
  const stmts: string[] = []
647
636
  const parts = new StringParts()
@@ -665,12 +654,12 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
665
654
  return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
666
655
  }
667
656
 
668
- function compileRootJsx(node: AstNode): string {
657
+ function compileRootJsx(node: JSXElement | JSXFragment): string {
669
658
  return `${use('raw')}(${compileJsxToStringExpr(node)})`
670
659
  }
671
660
 
672
661
  walk(program, (node) => {
673
- if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
662
+ if (isJsxNode(node)) {
674
663
  editor.replace(node.start, node.end, compileRootJsx(node))
675
664
  return false
676
665
  }