@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.0

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.
@@ -26,6 +26,106 @@ const DELEGATED_EVENTS = new Set([
26
26
 
27
27
  const DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
28
28
  const EVENT_ATTR = /^on([A-Z]\w*)$/
29
+ const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
30
+ const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
31
+ const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
32
+
33
+ function isStringBoolAttr(name: string): boolean {
34
+ const lower = name.toLowerCase()
35
+ return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
36
+ }
37
+
38
+ function isUnsafeUrlAttr(name: string, value: unknown): boolean {
39
+ if (!URL_ATTRS.has(name.toLowerCase()))
40
+ return false
41
+ return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
42
+ }
43
+
44
+ const HTML_ENTITIES: Record<string, string> = {
45
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0',
46
+ ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019',
47
+ ldquo: '\u201C', rdquo: '\u201D', hellip: '\u2026', bull: '\u2022',
48
+ middot: '\u00B7', laquo: '\u00AB', raquo: '\u00BB', lsaquo: '\u2039',
49
+ rsaquo: '\u203A', shy: '\u00AD', ensp: '\u2002', emsp: '\u2003',
50
+ thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E',
51
+ rlm: '\u200F', prime: '\u2032', Prime: '\u2033', sect: '\u00A7',
52
+ para: '\u00B6', dagger: '\u2020', Dagger: '\u2021', permil: '\u2030',
53
+ copy: '\u00A9', reg: '\u00AE', trade: '\u2122', euro: '\u20AC',
54
+ pound: '\u00A3', yen: '\u00A5', cent: '\u00A2', curren: '\u00A4',
55
+ deg: '\u00B0', plusmn: '\u00B1', times: '\u00D7', divide: '\u00F7',
56
+ frac12: '\u00BD', frac14: '\u00BC', frac34: '\u00BE', sup1: '\u00B9',
57
+ sup2: '\u00B2', sup3: '\u00B3', micro: '\u00B5', minus: '\u2212',
58
+ ne: '\u2260', le: '\u2264', ge: '\u2265', approx: '\u2248', infin: '\u221E',
59
+ larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193',
60
+ harr: '\u2194', crarr: '\u21B5', check: '\u2713', cross: '\u2717',
61
+ }
62
+
63
+ const ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*));/g
64
+
65
+ function decodeHtmlEntities(str: string): string {
66
+ if (!str.includes('&'))
67
+ return str
68
+ return str.replace(ENTITY_RE, (match, dec: string | undefined, hex: string | undefined, named: string | undefined) => {
69
+ if (dec !== undefined) {
70
+ const cp = Number.parseInt(dec, 10)
71
+ return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
72
+ }
73
+ if (hex !== undefined) {
74
+ const cp = Number.parseInt(hex, 16)
75
+ return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
76
+ }
77
+ if (named !== undefined && Object.prototype.hasOwnProperty.call(HTML_ENTITIES, named))
78
+ return HTML_ENTITIES[named]!
79
+ return match
80
+ })
81
+ }
82
+
83
+ const PRIMITIVE_GLOBALS = new Set([
84
+ 'String', 'Number', 'Boolean', 'parseInt', 'parseFloat',
85
+ 'encodeURI', 'encodeURIComponent', 'decodeURI', 'decodeURIComponent',
86
+ ])
87
+
88
+ const PRIMITIVE_METHODS = new Set([
89
+ 'toString', 'toFixed', 'toPrecision', 'toExponential', 'toLocaleString',
90
+ 'toLocaleDateString', 'toLocaleTimeString', 'toISOString', 'toUpperCase',
91
+ 'toLowerCase', 'toLocaleUpperCase', 'toLocaleLowerCase', 'trim', 'trimStart',
92
+ 'trimEnd', 'join', 'padStart', 'padEnd', 'repeat', 'replace', 'replaceAll',
93
+ 'substring', 'substr', 'charAt', 'charCodeAt', 'codePointAt', 'indexOf',
94
+ 'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'getTime', 'getFullYear',
95
+ 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds',
96
+ ])
97
+
98
+ function isKnownPrimitiveCall(node: AstNode): boolean {
99
+ const callee = node.callee as AstNode | undefined
100
+ if (!callee)
101
+ return false
102
+ if (callee.type === 'Identifier' && PRIMITIVE_GLOBALS.has(callee.name as string))
103
+ return true
104
+ if (callee.type === 'MemberExpression' && !callee.computed && callee.property?.type === 'Identifier') {
105
+ const prop = callee.property.name as string
106
+ if (callee.object?.type === 'Identifier') {
107
+ const obj = callee.object.name as string
108
+ if (obj === 'Math' || (obj === 'JSON' && prop === 'stringify') || (obj === 'Date' && prop === 'now'))
109
+ return true
110
+ }
111
+ if (PRIMITIVE_METHODS.has(prop))
112
+ return true
113
+ }
114
+ return false
115
+ }
116
+
117
+ function mayReturnNode(node: AstNode): boolean {
118
+ const cur = unwrapParens(node)
119
+ if (cur.type === 'TSAsExpression' || cur.type === 'TSNonNullExpression' || cur.type === 'TSSatisfiesExpression' || cur.type === 'TSTypeAssertion')
120
+ return mayReturnNode(cur.expression as AstNode)
121
+ if (cur.type === 'CallExpression')
122
+ return !isKnownPrimitiveCall(cur)
123
+ if (cur.type === 'LogicalExpression')
124
+ return mayReturnNode(cur.left as AstNode) || mayReturnNode(cur.right as AstNode)
125
+ if (cur.type === 'ConditionalExpression')
126
+ return mayReturnNode(cur.consequent as AstNode) || mayReturnNode(cur.alternate as AstNode)
127
+ return false
128
+ }
29
129
 
30
130
  export interface CompileDomOptions {
31
131
  analysis?: ModuleAnalysis | undefined
@@ -442,7 +542,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
442
542
  if (meaningful.length === 1) {
443
543
  const child = meaningful[0]!
444
544
  if (child.type === 'JSXText')
445
- propEntries.push(`children: ${JSON.stringify(cleanJsxText(child.value as string))}`)
545
+ propEntries.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value as string)))}`)
446
546
  else if (child.type === 'JSXElement' || child.type === 'JSXFragment')
447
547
  propEntries.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
448
548
  else if (child.type === 'JSXExpressionContainer')
@@ -451,7 +551,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
451
551
  else if (meaningful.length > 1) {
452
552
  const items = meaningful.map((c) => {
453
553
  if (c.type === 'JSXText')
454
- return JSON.stringify(cleanJsxText(c.value as string))
554
+ return JSON.stringify(decodeHtmlEntities(cleanJsxText(c.value as string)))
455
555
  if (c.type === 'JSXElement' || c.type === 'JSXFragment')
456
556
  return compileRootJsx(c, scopeRewrites)
457
557
  return compileExpression(c.expression, scopeRewrites)
@@ -508,6 +608,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
508
608
 
509
609
  const walkPlan: { parentVar: string, index: number, varName: string }[] = []
510
610
  const dynamicTextSlots = new Set<string>() // "parentVar:textIndex" for optional SSR text between <!---->...<!---->
611
+ const dynamicRangeSlots = new Set<string>() // "parentVar:closeIndex" for SSR range between <!---->...<!---->
511
612
 
512
613
  function requestChild(parentVar: string, index: number): string {
513
614
  const key = `${parentVar}:${index}`
@@ -562,19 +663,25 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
562
663
 
563
664
  const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
564
665
  if (attr.value === null) {
565
- html += ` ${name}`
666
+ html += isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`
566
667
  }
567
668
  else if (attr.value.type === 'Literal') {
568
- html += ` ${name}="${escapeStaticAttr(String(attr.value.value))}"`
669
+ if (!isUnsafeUrlAttr(name, attr.value.value))
670
+ html += ` ${name}="${escapeStaticAttr(String(attr.value.value))}"`
569
671
  }
570
672
  else if (attr.value.type === 'JSXExpressionContainer') {
571
673
  const expr = attr.value.expression as AstNode
572
674
  const lit = !DOM_PROPS.has(name) && name !== 'style' ? staticLiteral(expr) : { ok: false as const }
573
675
  if (lit.ok) {
574
- if (lit.value === true)
575
- html += ` ${name}`
576
- else if (lit.value !== false && lit.value !== null)
676
+ if (typeof lit.value === 'boolean') {
677
+ if (isStringBoolAttr(name))
678
+ html += ` ${name}="${lit.value ? 'true' : 'false'}"`
679
+ else if (lit.value === true)
680
+ html += ` ${name}`
681
+ }
682
+ else if (lit.value !== null && !isUnsafeUrlAttr(name, lit.value)) {
577
683
  html += ` ${name}="${escapeStaticAttr(String(lit.value))}"`
684
+ }
578
685
  continue
579
686
  }
580
687
  const exprCode = compileExpression(expr, scopeRewrites)
@@ -654,6 +761,12 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
654
761
  dynamicTextSlots.add(`${realVar}:${slot.slice(prefix.length)}`)
655
762
  }
656
763
  }
764
+ for (const slot of [...dynamicRangeSlots]) {
765
+ if (slot.startsWith(prefix)) {
766
+ dynamicRangeSlots.delete(slot)
767
+ dynamicRangeSlots.add(`${realVar}:${slot.slice(prefix.length)}`)
768
+ }
769
+ }
657
770
  }
658
771
  html += subHtml
659
772
  domIndex++
@@ -808,17 +921,28 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
808
921
  }
809
922
  }
810
923
 
811
- // Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, or any expression containing JSX)
924
+ // Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, JSX expressions, or call expressions)
812
925
  const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
813
926
  || (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
814
927
  const exprCode = compileExpression(expr, scopeRewrites)
815
- if (isChildrenExpr || hasJsxDescendant(expr)) {
816
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
817
- if (!isLast) {
928
+ if (isChildrenExpr || hasJsxDescendant(expr) || mayReturnNode(expr)) {
929
+ if (meaningful.length === 1) {
930
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, null);`)
931
+ }
932
+ else if (isLast) {
933
+ const startVar = requestChild(elVar, domIndex)
818
934
  html += '<!---->'
819
935
  domIndex++
936
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, ${startVar});`)
937
+ }
938
+ else {
939
+ const startVar = requestChild(elVar, domIndex)
940
+ const endVar = requestChild(elVar, domIndex + 1)
941
+ html += '<!----><!---->'
942
+ dynamicRangeSlots.add(`${elVar}:${domIndex + 1}`)
943
+ domIndex += 2
944
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${endVar}, ${startVar});`)
820
945
  }
821
- ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${anchorVar});`)
822
946
  continue
823
947
  }
824
948
 
@@ -899,6 +1023,10 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
899
1023
  expr = `${use('skipText')}(${expr})`
900
1024
  pos += 2
901
1025
  }
1026
+ else if (dynamicRangeSlots.has(`${pVar}:${pos + 1}`)) {
1027
+ expr = `${use('skipRange')}(${expr})`
1028
+ pos += 1
1029
+ }
902
1030
  else {
903
1031
  expr = `${expr}.nextSibling`
904
1032
  pos += 1
@@ -932,7 +1060,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
932
1060
  if (child.type === 'JSXElement' || child.type === 'JSXFragment')
933
1061
  return compileRootJsx(child, scopeRewrites)
934
1062
  if (child.type === 'JSXText')
935
- return `document.createTextNode(${JSON.stringify(cleanJsxText(child.value as string))})`
1063
+ return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value as string)))})`
936
1064
  return `document.createTextNode(String(${compileExpression(child.expression, scopeRewrites)} ?? ""))`
937
1065
  })
938
1066
  return `${use('frag')}(${items.join(', ')})`
@@ -11,10 +11,14 @@ export function escapeStaticText(str: string): string {
11
11
 
12
12
  const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
13
13
  const CLOSE_STYLE_RE = /<\/(style)/gi
14
- const CLOSE_SCRIPT_RE = /<\/(script)/gi
14
+ const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
15
15
 
16
16
  function escapeRawText(str: string, tag: 'style' | 'script'): string {
17
- return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
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')
18
22
  }
19
23
 
20
24
  const VOID_ELEMENTS = new Set([
@@ -23,6 +27,41 @@ const VOID_ELEMENTS = new Set([
23
27
  ])
24
28
 
25
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 {
46
+ let found = false
47
+ walk(root, (child) => {
48
+ if (found)
49
+ return false
50
+ if (child !== root && (
51
+ child.type === 'FunctionDeclaration'
52
+ || child.type === 'FunctionExpression'
53
+ || child.type === 'ArrowFunctionExpression'
54
+ )) {
55
+ return false
56
+ }
57
+ if (child.type === 'AwaitExpression') {
58
+ found = true
59
+ return false
60
+ }
61
+ return undefined
62
+ })
63
+ return found
64
+ }
26
65
 
27
66
  export interface IslandBinding {
28
67
  id: string
@@ -33,6 +72,7 @@ export interface IslandBinding {
33
72
  export interface CompileSsrOptions {
34
73
  islands?: ReadonlyMap<string, IslandBinding> | undefined
35
74
  isIsland?: boolean | undefined
75
+ emitMarkers?: boolean | undefined
36
76
  analysis?: ModuleAnalysis | undefined
37
77
  }
38
78
 
@@ -138,17 +178,23 @@ function isSimpleLiteral(node: AstNode): { ok: true, value: string | number | bo
138
178
 
139
179
  function isStaticNullish(node: AstNode): boolean {
140
180
  return (node.type === 'Identifier' && node.name === 'undefined')
141
- || (node.type === 'Literal' && (node.value === null || node.value === false))
181
+ || (node.type === 'Literal' && node.value === null)
142
182
  }
143
183
 
144
184
  function formatStaticAttrBranch(attrName: string, node: AstNode): string | undefined {
145
185
  if (isStaticNullish(node))
146
186
  return '""'
147
187
  if (node.type === 'Literal') {
148
- if (node.value === true)
149
- return JSON.stringify(` ${attrName}`)
150
- if (typeof node.value === 'string' || typeof node.value === 'number')
188
+ if (typeof node.value === 'boolean') {
189
+ if (isStringBoolAttr(attrName))
190
+ return JSON.stringify(` ${attrName}="${node.value ? 'true' : 'false'}"`)
191
+ return node.value ? JSON.stringify(` ${attrName}`) : '""'
192
+ }
193
+ if (typeof node.value === 'string' || typeof node.value === 'number') {
194
+ if (isUnsafeUrlAttr(attrName, node.value))
195
+ return '""'
151
196
  return JSON.stringify(` ${attrName}="${escapeStaticAttr(String(node.value))}"`)
197
+ }
152
198
  }
153
199
  return undefined
154
200
  }
@@ -170,7 +216,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
170
216
  }
171
217
 
172
218
  const islands = options.islands
173
- const isIsland = options.isIsland ?? analysis.isInteractive
219
+ const emitMarkers = options.emitMarkers ?? options.isIsland ?? analysis.isInteractive
174
220
 
175
221
  function compileSubExpression(node: AstNode): string {
176
222
  let hasNestedJsx = false
@@ -230,10 +276,11 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
230
276
 
231
277
  const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
232
278
  if (attr.value === null) {
233
- parts.pushStatic(` ${name}`)
279
+ parts.pushStatic(isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`)
234
280
  }
235
281
  else if (attr.value.type === 'Literal') {
236
- parts.pushStatic(` ${name}="${escapeStaticAttr(String(attr.value.value))}"`)
282
+ if (!isUnsafeUrlAttr(name, attr.value.value))
283
+ parts.pushStatic(` ${name}="${escapeStaticAttr(String(attr.value.value))}"`)
237
284
  }
238
285
  else if (attr.value.type === 'JSXExpressionContainer') {
239
286
  const expr = attr.value.expression as AstNode
@@ -331,7 +378,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
331
378
  && expr.arguments?.length === 1
332
379
  ) {
333
380
  const cb = expr.arguments[0] as AstNode
334
- if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && cb.body !== null) {
381
+ if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && !cb.async && cb.body !== null) {
335
382
  const body = (cb.body.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body) as AstNode
336
383
  if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
337
384
  const target = compileSubExpression(expr.callee.object)
@@ -358,7 +405,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
358
405
  pushStmt(
359
406
  `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
360
407
  )
361
- if (isIsland && !isLast)
408
+ if (emitMarkers && !isLast)
362
409
  parts.pushStatic('<!---->')
363
410
  continue
364
411
  }
@@ -383,13 +430,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
383
430
  && expr.arguments?.length === 1
384
431
  ) {
385
432
  const cb = expr.arguments[0] as AstNode
386
- if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && cb.body !== null) {
433
+ if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && !cb.async && cb.body !== null) {
387
434
  const body = (cb.body.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body) as AstNode
388
435
  if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
389
436
  const target = compileSubExpression(expr.callee.object)
390
437
  const params = (cb.params as AstNode[]).map(p => code.slice(p.start, p.end)).join(', ')
391
438
  const rendered = `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
392
- return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
439
+ return emitMarkers && !isLast ? `(${rendered}) + "<!---->"` : rendered
393
440
  }
394
441
  if (body.type === 'BlockStatement') {
395
442
  let blockHasJsx = false
@@ -402,7 +449,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
402
449
  })
403
450
  if (blockHasJsx) {
404
451
  const rendered = `${use('esc')}(${compileSubExpression(expr)})`
405
- return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
452
+ return emitMarkers && !isLast ? `(${rendered}) + "<!---->"` : rendered
406
453
  }
407
454
  }
408
455
  }
@@ -412,7 +459,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
412
459
  const right = unwrapParens(expr.right)
413
460
  if (right.type === 'JSXElement' || right.type === 'JSXFragment') {
414
461
  const left = compileSubExpression(expr.left)
415
- const emptyVal = isIsland && !isLast ? '"<!---->"' : '""'
462
+ const emptyVal = emitMarkers && !isLast ? '"<!---->"' : '""'
416
463
  return `((${left}) ? (${compileJsxToStringExpr(right)}) : ${emptyVal})`
417
464
  }
418
465
  }
@@ -425,13 +472,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
425
472
  const cons = compileExpressionAsString(consNode, false, true)
426
473
  const alt = compileExpressionAsString(altNode, false, true)
427
474
  const base = `((${test}) ? (${cons}) : (${alt}))`
428
- return isIsland && !isLast ? `(${base} || "<!---->")` : base
475
+ return emitMarkers && !isLast ? `(${base} || "<!---->")` : base
429
476
  }
430
477
  }
431
478
 
432
479
  const exprCode = compileSubExpression(expr)
433
480
  const rendered = `${use('esc')}(${exprCode})`
434
- if (isIsland && hasSiblings)
481
+ if (emitMarkers && hasSiblings)
435
482
  return isLast ? `"<!---->" + ${rendered}` : `"<!---->" + ${rendered} + "<!---->"`
436
483
  return rendered
437
484
  }
@@ -526,7 +573,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
526
573
 
527
574
  const childExpr = hasChildren ? compileJsxToStringExpr({ type: 'JSXFragment', children: childNodes }) : '""'
528
575
 
529
- const islandInfo = !isIsland ? islands?.get(tag) : undefined
576
+ const islandInfo = islands?.get(tag)
530
577
  if (islandInfo !== undefined) {
531
578
  const propsCode = `{ ${propEntries.join(', ')} }`
532
579
  const callPropsCode = hasChildren
@@ -534,8 +581,9 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
534
581
  : propsCode
535
582
  const resolvedHydrate = staticHydrate ?? (hydrateExpr === undefined ? islandInfo.defaultHydrate : undefined)
536
583
 
537
- // Compile-time static island props fast path: 0 JSON.stringify / Object.keys / escAttr at runtime!
538
- if (allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
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)) {
539
587
  const pAttr = Object.keys(staticPropsObj).length > 0
540
588
  ? ` p="${escapeStaticAttr(JSON.stringify(staticPropsObj))}"`
541
589
  : ''
@@ -545,14 +593,43 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
545
593
  const openTag = `<kay-island c="${escapeStaticAttr(islandInfo.chunk)}"${pAttr}${hAttr}>`
546
594
  parts.pushStatic(openTag)
547
595
  if (resolvedHydrate !== 'client')
548
- parts.pushExpr(`${use('ssrChild')}(${tag}(${callPropsCode}))`)
596
+ parts.pushExpr(`${use('ssrInIsland')}(() => ${use('ssrChild')}(${tag}(${callPropsCode})))`)
549
597
  parts.pushStatic('</kay-island>')
550
598
  return
551
599
  }
552
600
 
553
601
  const hydrateArg = hydrateExpr ?? (islandInfo.defaultHydrate !== undefined ? JSON.stringify(islandInfo.defaultHydrate) : 'undefined')
602
+ if (allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
603
+ parts.pushExpr(
604
+ `${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
605
+ )
606
+ return
607
+ }
608
+
609
+ // Hoist dynamic island props into a single binding so expressions (side effects & await) evaluate once!
610
+ const pVar = `_p${loopCounter++}`
611
+ const argNames = [pVar]
612
+ const argExprs = [propsCode]
613
+ let callArg = pVar
614
+ if (hasChildren) {
615
+ let childSlotVal = childExpr
616
+ if (containsDirectAwait({ type: 'JSXFragment', children: childNodes })) {
617
+ const cVar = `_c${loopCounter++}`
618
+ argNames.push(cVar)
619
+ argExprs.push(childExpr)
620
+ childSlotVal = cVar
621
+ }
622
+ callArg = `{ ...${pVar}, children: ${use('raw')}("<kay-slot>" + (${childSlotVal}) + "</kay-slot>") }`
623
+ }
624
+ let hArg = hydrateArg
625
+ if (hydrateExpr !== undefined && staticHydrate === undefined) {
626
+ const hVar = `_h${loopCounter++}`
627
+ argNames.push(hVar)
628
+ argExprs.push(hydrateExpr)
629
+ hArg = hVar
630
+ }
554
631
  parts.pushExpr(
555
- `${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
632
+ `((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callArg})), ${pVar}, ${hArg}))(${argExprs.join(', ')})`,
556
633
  )
557
634
  return
558
635
  }
@@ -583,6 +660,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
583
660
  return parts.toExpr()
584
661
 
585
662
  flush()
663
+ if (containsDirectAwait(node))
664
+ return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
586
665
  return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
587
666
  }
588
667
 
package/src/dev/index.ts CHANGED
@@ -6,15 +6,20 @@ import { existsSync, rmSync, statSync, watch } from 'node:fs'
6
6
  import { join, resolve } from 'node:path'
7
7
  import { build, createBuildCache } from '../build/index'
8
8
  import { loadConfig } from '../plugins/index'
9
- import { createServer } from '../server/index'
9
+ import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
10
+ import { createServer, withCspHashes } from '../server/index'
10
11
 
11
12
  export interface DevServerOptions {
12
13
  root: string
13
14
  port?: number | undefined
15
+ hostname?: string | undefined
14
16
  routesDir?: string | undefined
17
+ maxRequestBodySize?: number | undefined
15
18
  }
16
19
 
17
- const DEV_RELOAD_SCRIPT = `<script>(()=>{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();}};})();</script>`
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')}'`
18
23
 
19
24
  function renderErrorOverlay(errText: string): string {
20
25
  const escaped = errText
@@ -35,6 +40,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
35
40
  const configPath = join(root, 'kay.config.ts')
36
41
  const devRoot = join(root, '.kay-dev')
37
42
  const port = options.port ?? 3000
43
+ const hostname = options.hostname ?? '127.0.0.1'
38
44
  const buildCache = createBuildCache()
39
45
 
40
46
  let buildNum = 0
@@ -195,13 +201,18 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
195
201
  }
196
202
  }, 15_000)
197
203
 
204
+ const maxRequestBodySize = options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
205
+
198
206
  const server = Bun.serve({
199
207
  port,
200
- idleTimeout: 0,
201
- async fetch(request) {
208
+ hostname,
209
+ idleTimeout: 30,
210
+ maxRequestBodySize,
211
+ async fetch(request, srv) {
202
212
  const url = new URL(request.url)
203
213
 
204
214
  if (url.pathname === '/_kay/dev-events') {
215
+ srv.timeout(request, 0)
205
216
  let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
206
217
  const stream = new ReadableStream<Uint8Array>({
207
218
  start(controller) {
@@ -237,20 +248,28 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
237
248
  })
238
249
  }
239
250
 
240
- const res = await currentApp!.handle(request)
251
+ const remoteIp = srv.requestIP(request)?.address
252
+ const res = await currentApp!.handle(request, remoteIp)
241
253
  const ct = res.headers.get('content-type') ?? ''
254
+ if (ct.includes('text/event-stream'))
255
+ srv.timeout(request, 0)
242
256
  if (ct.includes('text/html')) {
243
257
  const html = await res.text()
244
258
  const injected = html.includes('</body>')
245
259
  ? html.replace('</body>', `${DEV_RELOAD_SCRIPT}</body>`)
246
260
  : html + DEV_RELOAD_SCRIPT
247
- return new Response(injected, { status: res.status, headers: res.headers })
261
+ const headers = new Headers(res.headers)
262
+ const existingCsp = headers.get('content-security-policy')
263
+ 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 })
248
266
  }
249
267
  return res
250
268
  },
251
269
  })
252
270
 
253
- const url = `http://localhost:${server.port}`
271
+ const displayHost = hostname === '0.0.0.0' ? '127.0.0.1' : hostname
272
+ const url = `http://${displayHost}:${server.port}`
254
273
  console.log(`[kay dev] listening on ${url}`)
255
274
 
256
275
  return {