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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +114 -18
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +2 -1
  55. package/src/unrenderable.ts +35 -0
@@ -1,21 +1,57 @@
1
1
  // Kay v2 Client DOM compiler: compiles TSX to hoisted template() clones, child-path walks,
2
- // delegated events, compiler-safe destructured props, and fine-grained keyed .map() loops.
3
-
4
- import type { AstNode, ModuleAnalysis } from './analyze'
5
- import { analyzeModule, parseTsx, walk } from './analyze'
2
+ // delegated events, compiler-safe destructured props, reactive spreads, and shared balanced hydration markers.
3
+
4
+ import type {
5
+ ArrowFunctionExpression,
6
+ BlockStatement,
7
+ Function as OxcFunction,
8
+ JSXElement,
9
+ JSXFragment,
10
+ Node,
11
+ ObjectPattern,
12
+ ParamPattern,
13
+ Program,
14
+ } from 'oxc-parser'
15
+ import type { ModuleAnalysis } from './analyze'
16
+ import { analyzeModule, loadDeclarations, parseTsx, walk } from './analyze'
6
17
  import { SourceEditor } from './patch'
7
- import { cleanJsxText, escapeStaticText } from './ssr'
8
-
9
- const VOID_ELEMENTS = new Set([
10
- 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
11
- 'link', 'meta', 'param', 'source', 'track', 'wbr',
12
- ])
18
+ import {
19
+ classifyJsxChild,
20
+ cleanJsxText,
21
+ collectPatternNames,
22
+ containsJsx,
23
+ decodeHtmlEntities,
24
+ DOM_PROPS,
25
+ escapeRawText,
26
+ escapeStaticAttr,
27
+ escapeStaticText,
28
+ EVENT_ATTR,
29
+ filterMeaningfulChildren,
30
+ isBlockedAttr,
31
+ isComponentTag,
32
+ isJsxNode,
33
+ isNodeCapableExpr,
34
+ isStringBoolAttr,
35
+ isUnsafeUrlAttr,
36
+ jsxTagName,
37
+ RAW_TEXT_ELEMENTS,
38
+ staticLiteral,
39
+ unwrapParens,
40
+ unwrapTsExpr,
41
+ VOID_ELEMENTS,
42
+ } from './shared'
13
43
 
14
44
  const SVG_CHILD_TAGS = new Set([
15
45
  'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'ellipse',
16
- 'g', 'defs', 'use', 'text', 'tspan', 'clipPath', 'mask',
17
- 'linearGradient', 'radialGradient', 'stop', 'pattern', 'symbol',
18
- 'marker', 'filter', 'feGaussianBlur', 'foreignObject', 'animate',
46
+ 'g', 'defs', 'use', 'text', 'tspan', 'textPath', 'clipPath', 'mask',
47
+ 'linearGradient', 'radialGradient', 'stop', 'pattern', 'symbol', 'image',
48
+ 'marker', 'filter', 'feBlend', 'feColorMatrix', 'feComponentTransfer',
49
+ 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
50
+ 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG',
51
+ 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode',
52
+ 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting',
53
+ 'feSpotLight', 'feTile', 'feTurbulence', 'foreignObject', 'animate',
54
+ 'animateMotion', 'animateTransform', 'set', 'mpath', 'desc', 'metadata', 'switch',
19
55
  ])
20
56
 
21
57
  const DELEGATED_EVENTS = new Set([
@@ -24,109 +60,6 @@ const DELEGATED_EVENTS = new Set([
24
60
  'pointerdown', 'pointerup', 'touchstart', 'touchend',
25
61
  ])
26
62
 
27
- const DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
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
- }
129
-
130
63
  export interface CompileDomOptions {
131
64
  analysis?: ModuleAnalysis | undefined
132
65
  }
@@ -136,95 +69,187 @@ export interface CompileDomResult {
136
69
  analysis: ModuleAnalysis
137
70
  }
138
71
 
139
- function jsxTagName(node: AstNode): string {
140
- if (node.type === 'JSXIdentifier')
141
- return node.name as string
142
- if (node.type === 'JSXMemberExpression')
143
- return `${jsxTagName(node.object)}.${node.property.name}`
144
- if (node.type === 'JSXNamespacedName')
145
- return `${node.namespace.name}:${node.name.name}`
146
- return ''
147
- }
148
-
149
- function isComponentTag(tag: string): boolean {
150
- const first = tag.charCodeAt(0)
151
- return (first >= 65 && first <= 90) || tag.includes('.')
152
- }
153
-
154
- function unwrapParens(node: AstNode): AstNode {
155
- let cur = node
156
- while (cur.type === 'ParenthesizedExpression')
157
- cur = cur.expression as AstNode
158
- return cur
159
- }
160
-
161
- function escapeStaticAttr(str: string): string {
162
- return str
163
- .replaceAll('&', '&amp;')
164
- .replaceAll('"', '&quot;')
165
- .replaceAll('<', '&lt;')
166
- .replaceAll('>', '&gt;')
72
+ function withoutBindings(rewrites: ReadonlyMap<string, string>, patterns: readonly Node[]): Map<string, string> {
73
+ const names = new Set<string>()
74
+ for (const pattern of patterns)
75
+ collectPatternNames(pattern, names)
76
+ const kept = new Map(rewrites)
77
+ for (const name of names)
78
+ kept.delete(name)
79
+ return kept
167
80
  }
168
81
 
169
- function staticLiteral(node: AstNode): { ok: true, value: string | number | boolean | null } | { ok: false } {
170
- const n = unwrapParens(node)
171
- if (n.type === 'Literal') {
172
- const v = n.value
173
- if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null)
174
- return { ok: true, value: v }
82
+ // Names whose every binding in the file is a `const` holding an array literal: only those can be looped once without tracking.
83
+ function literalArrayConsts(program: Program): Set<string> {
84
+ const literal = new Set<string>()
85
+ const other = new Set<string>()
86
+ const bindOther = (pattern: Node | null | undefined): void => {
87
+ if (pattern !== null && pattern !== undefined)
88
+ collectPatternNames(pattern, other)
175
89
  }
176
- if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument?.type === 'Literal' && typeof n.argument.value === 'number')
177
- return { ok: true, value: -n.argument.value }
178
- return { ok: false }
90
+ walk(program, (node) => {
91
+ if (node.type === 'VariableDeclaration') {
92
+ for (const decl of node.declarations) {
93
+ const init = decl.init !== null ? unwrapTsExpr(decl.init) : null
94
+ if (node.kind === 'const' && decl.id.type === 'Identifier' && init?.type === 'ArrayExpression')
95
+ literal.add(decl.id.name)
96
+ else
97
+ bindOther(decl.id)
98
+ }
99
+ }
100
+ else if (node.type === 'ImportSpecifier' || node.type === 'ImportDefaultSpecifier' || node.type === 'ImportNamespaceSpecifier') {
101
+ bindOther(node.local)
102
+ }
103
+ else if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') {
104
+ bindOther(node.id)
105
+ }
106
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
107
+ for (const param of node.params)
108
+ bindOther(param)
109
+ }
110
+ else if (node.type === 'CatchClause') {
111
+ bindOther(node.param)
112
+ }
113
+ })
114
+ for (const name of other)
115
+ literal.delete(name)
116
+ return literal
179
117
  }
180
118
 
181
- function collectPatternNames(pattern: AstNode, out: Set<string>): void {
182
- if (!pattern)
183
- return
184
- if (pattern.type === 'Identifier') {
185
- out.add(pattern.name as string)
186
- }
187
- else if (pattern.type === 'AssignmentPattern') {
188
- collectPatternNames(pattern.left, out)
189
- }
190
- else if (pattern.type === 'RestElement') {
191
- collectPatternNames(pattern.argument, out)
192
- }
193
- else if (pattern.type === 'ArrayPattern') {
194
- for (const el of pattern.elements as (AstNode | null)[]) {
195
- if (el !== null)
196
- collectPatternNames(el, out)
197
- }
198
- }
199
- else if (pattern.type === 'ObjectPattern') {
200
- for (const prop of pattern.properties as AstNode[]) {
201
- if (prop.type === 'RestElement')
202
- collectPatternNames(prop.argument, out)
203
- else
204
- collectPatternNames(prop.value, out)
119
+ /** Collects free identifier references inside a node (ignoring shadowed locals and property keys). */
120
+ function referencesAny(rootNode: Node, names: ReadonlySet<string>): boolean {
121
+ if (names.size === 0)
122
+ return false
123
+ let found = false
124
+ function visit(node: Node | null | undefined, shadowed: Set<string>): void {
125
+ if (found || node === null || node === undefined)
126
+ return
127
+ switch (node.type) {
128
+ case 'Identifier':
129
+ if (!shadowed.has(node.name) && names.has(node.name))
130
+ found = true
131
+ return
132
+ case 'MemberExpression':
133
+ visit(node.object, shadowed)
134
+ if (node.computed)
135
+ visit(node.property, shadowed)
136
+ return
137
+ case 'Property':
138
+ if (node.computed)
139
+ visit(node.key, shadowed)
140
+ visit(node.value, shadowed)
141
+ return
142
+ case 'ArrowFunctionExpression':
143
+ case 'FunctionExpression':
144
+ case 'FunctionDeclaration': {
145
+ const next = new Set(shadowed)
146
+ if (node.type !== 'ArrowFunctionExpression' && node.id !== null)
147
+ next.add(node.id.name)
148
+ for (const p of node.params)
149
+ collectPatternNames(p, next)
150
+ visit(node.body, next)
151
+ return
152
+ }
153
+ case 'BlockStatement': {
154
+ const next = new Set(shadowed)
155
+ for (const stmt of node.body) {
156
+ if (stmt.type === 'VariableDeclaration') {
157
+ for (const d of stmt.declarations) {
158
+ visit(d.init, next)
159
+ collectPatternNames(d.id, next)
160
+ }
161
+ }
162
+ else {
163
+ visit(stmt, next)
164
+ }
165
+ }
166
+ return
167
+ }
168
+ default: {
169
+ if (node.type.startsWith('TS'))
170
+ return
171
+ for (const [k, v] of Object.entries(node)) {
172
+ if (k === 'start' || k === 'end' || k === 'type')
173
+ continue
174
+ if (Array.isArray(v)) {
175
+ for (const item of v) {
176
+ if (item !== null && typeof item === 'object' && 'type' in item)
177
+ visit(item as Node, shadowed)
178
+ }
179
+ }
180
+ else if (v !== null && typeof v === 'object' && 'type' in v) {
181
+ visit(v as Node, shadowed)
182
+ }
183
+ }
184
+ }
205
185
  }
206
186
  }
187
+ visit(rootNode, new Set())
188
+ return found
207
189
  }
208
190
 
209
- /** Rewrites free identifier reads inside an AST node while respecting shadowing and property keys. */
191
+ /** Rewrites free identifier reads inside an AST node while respecting lexical scopes, class/object keys, labels, and nested JSX/components. */
210
192
  function rewriteFreeIdentifiers(
211
193
  source: string,
212
- rootNode: AstNode,
194
+ rootNode: Node,
213
195
  replacements: ReadonlyMap<string, string>,
196
+ onJsx?: (node: JSXElement | JSXFragment, rewrites: ReadonlyMap<string, string>) => string,
197
+ onFunction?: (fn: ArrowFunctionExpression | OxcFunction, rewrites: ReadonlyMap<string, string>) => string | undefined,
214
198
  ): string {
215
- if (replacements.size === 0)
199
+ if (replacements.size === 0 && (onJsx === undefined || !containsJsx(rootNode)))
216
200
  return source.slice(rootNode.start, rootNode.end)
217
201
 
218
- const offset = rootNode.start as number
202
+ const offset = rootNode.start
219
203
  const editor = new SourceEditor(source.slice(rootNode.start, rootNode.end))
220
204
 
221
- function visit(node: AstNode | null | undefined, shadowed: Set<string>): void {
222
- if (!node || typeof node !== 'object')
205
+ function visitPatternDefaults(pattern: Node | null | undefined, shadowed: Set<string>): void {
206
+ if (pattern === null || pattern === undefined)
223
207
  return
208
+ switch (pattern.type) {
209
+ case 'AssignmentPattern':
210
+ visitPatternDefaults(pattern.left, shadowed)
211
+ visit(pattern.right, shadowed)
212
+ return
213
+ case 'RestElement':
214
+ visitPatternDefaults(pattern.argument, shadowed)
215
+ return
216
+ case 'TSParameterProperty':
217
+ visitPatternDefaults(pattern.parameter, shadowed)
218
+ return
219
+ case 'ArrayPattern':
220
+ for (const el of pattern.elements)
221
+ visitPatternDefaults(el, shadowed)
222
+ return
223
+ case 'ObjectPattern':
224
+ for (const prop of pattern.properties) {
225
+ if (prop.type === 'RestElement') {
226
+ visitPatternDefaults(prop.argument, shadowed)
227
+ }
228
+ else {
229
+ if (prop.computed)
230
+ visit(prop.key, shadowed)
231
+ visitPatternDefaults(prop.value, shadowed)
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ function activeMap(shadowed: Set<string>): ReadonlyMap<string, string> {
238
+ return shadowed.size === 0 ? replacements : new Map([...replacements].filter(([k]) => !shadowed.has(k)))
239
+ }
240
+
241
+ function visit(node: Node | null | undefined, shadowed: Set<string>): void {
242
+ if (node === null || node === undefined)
243
+ return
244
+
245
+ if (onJsx !== undefined && isJsxNode(node)) {
246
+ editor.replace(node.start - offset, node.end - offset, onJsx(node, activeMap(shadowed)))
247
+ return
248
+ }
224
249
 
225
250
  switch (node.type) {
226
251
  case 'Identifier': {
227
- const name = node.name as string
252
+ const name = node.name
228
253
  if (!shadowed.has(name)) {
229
254
  const rep = replacements.get(name)
230
255
  if (rep !== undefined)
@@ -238,11 +263,19 @@ function rewriteFreeIdentifiers(
238
263
  visit(node.property, shadowed)
239
264
  return
240
265
  }
266
+ case 'MetaProperty':
267
+ case 'BreakStatement':
268
+ case 'ContinueStatement':
269
+ return
270
+ case 'LabeledStatement': {
271
+ visit(node.body, shadowed)
272
+ return
273
+ }
241
274
  case 'Property': {
242
275
  if (node.computed)
243
276
  visit(node.key, shadowed)
244
- if (node.shorthand && node.value?.type === 'Identifier') {
245
- const name = node.value.name as string
277
+ if (node.shorthand && node.value.type === 'Identifier') {
278
+ const name = node.value.name
246
279
  if (!shadowed.has(name) && replacements.has(name)) {
247
280
  editor.replace(node.start - offset, node.end - offset, `${name}: ${replacements.get(name)}`)
248
281
  return
@@ -251,31 +284,100 @@ function rewriteFreeIdentifiers(
251
284
  visit(node.value, shadowed)
252
285
  return
253
286
  }
287
+ case 'MethodDefinition':
288
+ case 'PropertyDefinition': {
289
+ if (node.computed)
290
+ visit(node.key, shadowed)
291
+ visit(node.value, shadowed)
292
+ return
293
+ }
294
+ case 'ClassDeclaration':
295
+ case 'ClassExpression': {
296
+ const next = new Set(shadowed)
297
+ if (node.id !== null)
298
+ next.add(node.id.name)
299
+ visit(node.superClass, shadowed)
300
+ visit(node.body, next)
301
+ return
302
+ }
303
+ case 'CatchClause': {
304
+ const next = new Set(shadowed)
305
+ visitPatternDefaults(node.param, next)
306
+ collectPatternNames(node.param, next)
307
+ visit(node.body, next)
308
+ return
309
+ }
310
+ case 'ForStatement': {
311
+ const next = new Set(shadowed)
312
+ if (node.init !== null) {
313
+ if (node.init.type === 'VariableDeclaration') {
314
+ for (const d of node.init.declarations) {
315
+ visit(d.init, next)
316
+ visitPatternDefaults(d.id, next)
317
+ collectPatternNames(d.id, next)
318
+ }
319
+ }
320
+ else {
321
+ visit(node.init, next)
322
+ }
323
+ }
324
+ visit(node.test, next)
325
+ visit(node.update, next)
326
+ visit(node.body, next)
327
+ return
328
+ }
329
+ case 'ForInStatement':
330
+ case 'ForOfStatement': {
331
+ visit(node.right, shadowed)
332
+ const next = new Set(shadowed)
333
+ if (node.left.type === 'VariableDeclaration') {
334
+ for (const d of node.left.declarations) {
335
+ visitPatternDefaults(d.id, next)
336
+ collectPatternNames(d.id, next)
337
+ }
338
+ }
339
+ else {
340
+ visit(node.left, next)
341
+ }
342
+ visit(node.body, next)
343
+ return
344
+ }
254
345
  case 'ArrowFunctionExpression':
255
346
  case 'FunctionExpression':
256
347
  case 'FunctionDeclaration': {
348
+ if (node !== rootNode && onFunction !== undefined) {
349
+ const compiled = onFunction(node, activeMap(shadowed))
350
+ if (compiled !== undefined) {
351
+ editor.replace(node.start - offset, node.end - offset, compiled)
352
+ return
353
+ }
354
+ }
257
355
  const nextShadow = new Set(shadowed)
258
- if (node.id?.name)
259
- nextShadow.add(node.id.name as string)
260
- for (const p of node.params as AstNode[])
356
+ if (node.type !== 'ArrowFunctionExpression' && node.id !== null)
357
+ nextShadow.add(node.id.name)
358
+ for (const p of node.params) {
359
+ visitPatternDefaults(p, nextShadow)
261
360
  collectPatternNames(p, nextShadow)
361
+ }
262
362
  visit(node.body, nextShadow)
263
363
  return
264
364
  }
265
365
  case 'BlockStatement': {
266
366
  const nextShadow = new Set(shadowed)
267
- for (const stmt of node.body as AstNode[]) {
367
+ for (const stmt of node.body) {
368
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
369
+ nextShadow.add(stmt.id.name)
370
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
371
+ nextShadow.add(stmt.id.name)
372
+ }
373
+ for (const stmt of node.body) {
268
374
  if (stmt.type === 'VariableDeclaration') {
269
- for (const d of stmt.declarations as AstNode[]) {
375
+ for (const d of stmt.declarations) {
270
376
  visit(d.init, nextShadow)
377
+ visitPatternDefaults(d.id, nextShadow)
271
378
  collectPatternNames(d.id, nextShadow)
272
379
  }
273
380
  }
274
- else if (stmt.type === 'FunctionDeclaration') {
275
- if (stmt.id?.name)
276
- nextShadow.add(stmt.id.name as string)
277
- visit(stmt, nextShadow)
278
- }
279
381
  else {
280
382
  visit(stmt, nextShadow)
281
383
  }
@@ -284,15 +386,7 @@ function rewriteFreeIdentifiers(
284
386
  }
285
387
  case 'VariableDeclarator': {
286
388
  visit(node.init, shadowed)
287
- return
288
- }
289
- case 'JSXAttribute': {
290
- visit(node.value, shadowed)
291
- return
292
- }
293
- case 'JSXOpeningElement': {
294
- for (const attr of node.attributes as AstNode[])
295
- visit(attr, shadowed)
389
+ visitPatternDefaults(node.id, shadowed)
296
390
  return
297
391
  }
298
392
  case 'TSAsExpression':
@@ -304,19 +398,20 @@ function rewriteFreeIdentifiers(
304
398
  return
305
399
  }
306
400
  default: {
307
- // Skip pure TypeScript type annotation nodes
308
- if (typeof node.type === 'string' && node.type.startsWith('TS'))
401
+ if (node.type.startsWith('TS'))
309
402
  return
310
- for (const key of Object.keys(node)) {
403
+ for (const [key, val] of Object.entries(node)) {
311
404
  if (key === 'start' || key === 'end' || key === 'type')
312
405
  continue
313
- const val = node[key]
314
406
  if (Array.isArray(val)) {
315
- for (let i = 0; i < val.length; i++)
316
- visit(val[i] as AstNode, shadowed)
407
+ for (let i = 0; i < val.length; i++) {
408
+ const item = val[i]
409
+ if (item !== null && typeof item === 'object' && 'type' in item)
410
+ visit(item as Node, shadowed)
411
+ }
317
412
  }
318
- else if (val !== null && typeof val === 'object') {
319
- visit(val as AstNode, shadowed)
413
+ else if (val !== null && typeof val === 'object' && 'type' in val) {
414
+ visit(val as Node, shadowed)
320
415
  }
321
416
  }
322
417
  }
@@ -334,11 +429,16 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
334
429
  if (!analysis.hasJsx && !analysis.hasLoadExport)
335
430
  return { code, analysis }
336
431
 
432
+ const staticArrays = literalArrayConsts(program)
433
+ const loadNodes = new Set<Node>(loadDeclarations(program))
434
+
337
435
  const editor = new SourceEditor(code)
338
436
  const used = new Set<string>()
339
437
  const templates: { name: string, html: string, isSvg?: boolean }[] = []
340
438
  const delegatedEvents = new Set<string>()
341
439
  let varCounter = 0
440
+ // Tracks whether the current JSX tree is enclosed by `<svg>` (reset inside `<foreignObject>`).
441
+ let svgDepth = 0
342
442
 
343
443
  const use = (name: string): string => {
344
444
  used.add(name)
@@ -346,40 +446,82 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
346
446
  }
347
447
  const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
348
448
 
349
- // Strip `export async function load(...)` in client builds
350
- for (const stmt of program.body as AstNode[]) {
351
- if (stmt.type === 'ExportNamedDeclaration') {
352
- const decl = stmt.declaration as AstNode | null
353
- if (decl?.type === 'FunctionDeclaration' && decl.id?.name === 'load')
354
- editor.remove(stmt.start, stmt.end)
449
+ // How each name a destructuring pattern binds is read from `source` on every access, so reads stay reactive.
450
+ function patternReads(pattern: Node, source: string, outerRewrites: ReadonlyMap<string, string>): Map<string, string> {
451
+ const reads = new Map<string, string>()
452
+ const running = new Map(outerRewrites)
453
+ if (pattern.type === 'ObjectPattern') {
454
+ for (const prop of pattern.properties) {
455
+ if (prop.type !== 'Property' || prop.computed || prop.key.type !== 'Identifier')
456
+ continue
457
+ const read = `${source}.${prop.key.name}`
458
+ if (prop.value.type === 'Identifier') {
459
+ reads.set(prop.value.name, read)
460
+ running.set(prop.value.name, read)
461
+ }
462
+ else if (prop.value.type === 'AssignmentPattern' && prop.value.left.type === 'Identifier') {
463
+ const defExpr = compileExpression(prop.value.right, running)
464
+ const simpleDef = prop.value.right.type === 'Literal' || prop.value.right.type === 'Identifier'
465
+ const expr = `(${read} === undefined ? ${simpleDef ? defExpr : `(${defExpr})`} : ${read})`
466
+ reads.set(prop.value.left.name, expr)
467
+ running.set(prop.value.left.name, expr)
468
+ }
469
+ }
355
470
  }
471
+ const names = new Set<string>()
472
+ collectPatternNames(pattern, names)
473
+ const patCode = code.slice(pattern.start, pattern.end)
474
+ for (const name of names) {
475
+ if (!reads.has(name))
476
+ reads.set(name, `((${patCode}) => ${name})(${source})`)
477
+ }
478
+ return reads
356
479
  }
357
480
 
358
- function hasJsxDescendant(node: AstNode | null | undefined): boolean {
359
- if (!node)
360
- return false
361
- let found = false
362
- walk(node, (child) => {
363
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
364
- found = true
365
- return false
366
- }
481
+ // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
482
+ for (const node of loadNodes) {
483
+ if (node.type === 'FunctionDeclaration' && node.id !== null)
484
+ editor.replace(node.start, node.end, `const ${node.id.name} = undefined`)
485
+ else
486
+ editor.replace(node.start, node.end, 'undefined')
487
+ }
488
+
489
+ function extractKeyExpr(jsxEl: Node): Node | undefined {
490
+ if (jsxEl.type !== 'JSXElement')
367
491
  return undefined
368
- })
369
- return found
492
+ for (const attr of jsxEl.openingElement.attributes) {
493
+ if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier' && attr.name.name === 'key') {
494
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
495
+ return attr.value.expression
496
+ if (attr.value?.type === 'Literal')
497
+ return attr.value
498
+ }
499
+ }
500
+ return undefined
370
501
  }
371
502
 
372
- function extractBlockKeyExpr(block: AstNode): AstNode | undefined {
373
- let found: AstNode | undefined
503
+ function extractBlockKeyExpr(block: BlockStatement): Node | undefined {
504
+ const blockLocals = new Set<string>()
505
+ for (const stmt of block.body) {
506
+ if (stmt.type === 'VariableDeclaration') {
507
+ for (const d of stmt.declarations)
508
+ collectPatternNames(d.id, blockLocals)
509
+ }
510
+ else if ((stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') && stmt.id !== null) {
511
+ blockLocals.add(stmt.id.name)
512
+ }
513
+ }
514
+ let found: Node | undefined
374
515
  walk(block, (child) => {
375
516
  if (found !== undefined)
376
517
  return false
377
518
  if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
378
519
  return false
379
- if (child.type === 'ReturnStatement' && child.argument) {
380
- const arg = unwrapParens(child.argument as AstNode)
520
+ if (child.type === 'ReturnStatement' && child.argument !== null) {
521
+ const arg = unwrapParens(child.argument)
381
522
  const k = extractKeyExpr(arg)
382
- if (k !== undefined) {
523
+ // Only hoist key expressions that don't depend on block-local variables.
524
+ if (k !== undefined && !referencesAny(k, blockLocals)) {
383
525
  found = k
384
526
  return false
385
527
  }
@@ -389,128 +531,38 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
389
531
  return found
390
532
  }
391
533
 
392
- function compileExpression(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
393
- if (!hasJsxDescendant(node))
394
- return rewriteFreeIdentifiers(code, node, scopeRewrites)
395
-
396
- // Replace nested JSX roots AND rewrite free identifiers in all surrounding non-JSX spans (respecting shadowing)
397
- const offset = node.start as number
398
- const sub = new SourceEditor(code.slice(node.start, node.end))
399
-
400
- function visitExpr(cur: AstNode | null | undefined, shadowed: Set<string>): void {
401
- if (!cur || typeof cur !== 'object')
402
- return
403
-
404
- if (cur.type === 'JSXElement' || cur.type === 'JSXFragment') {
405
- const activeRewrites = shadowed.size === 0
406
- ? scopeRewrites
407
- : new Map([...scopeRewrites].filter(([k]) => !shadowed.has(k)))
408
- sub.replace(cur.start - offset, cur.end - offset, compileRootJsx(cur, activeRewrites))
409
- return
410
- }
411
-
412
- switch (cur.type) {
413
- case 'Identifier': {
414
- const name = cur.name as string
415
- if (!shadowed.has(name)) {
416
- const rep = scopeRewrites.get(name)
417
- if (rep !== undefined)
418
- sub.replace(cur.start - offset, cur.end - offset, rep)
419
- }
420
- return
421
- }
422
- case 'MemberExpression': {
423
- visitExpr(cur.object, shadowed)
424
- if (cur.computed)
425
- visitExpr(cur.property, shadowed)
426
- return
427
- }
428
- case 'Property': {
429
- if (cur.computed)
430
- visitExpr(cur.key, shadowed)
431
- if (cur.shorthand && cur.value?.type === 'Identifier') {
432
- const name = cur.value.name as string
433
- if (!shadowed.has(name) && scopeRewrites.has(name)) {
434
- sub.replace(cur.start - offset, cur.end - offset, `${name}: ${scopeRewrites.get(name)}`)
435
- return
436
- }
437
- }
438
- visitExpr(cur.value, shadowed)
439
- return
440
- }
441
- case 'ArrowFunctionExpression':
442
- case 'FunctionExpression':
443
- case 'FunctionDeclaration': {
444
- const nextShadow = new Set(shadowed)
445
- if (cur.id?.name)
446
- nextShadow.add(cur.id.name as string)
447
- for (const p of cur.params as AstNode[])
448
- collectPatternNames(p, nextShadow)
449
- visitExpr(cur.body, nextShadow)
450
- return
451
- }
452
- case 'BlockStatement': {
453
- const nextShadow = new Set(shadowed)
454
- for (const stmt of cur.body as AstNode[]) {
455
- if (stmt.type === 'VariableDeclaration') {
456
- for (const d of stmt.declarations as AstNode[]) {
457
- visitExpr(d.init, nextShadow)
458
- collectPatternNames(d.id, nextShadow)
459
- }
460
- }
461
- else if (stmt.type === 'FunctionDeclaration') {
462
- if (stmt.id?.name)
463
- nextShadow.add(stmt.id.name as string)
464
- visitExpr(stmt, nextShadow)
465
- }
466
- else {
467
- visitExpr(stmt, nextShadow)
468
- }
469
- }
470
- return
471
- }
472
- case 'VariableDeclarator': {
473
- visitExpr(cur.init, shadowed)
474
- return
475
- }
476
- case 'TSAsExpression':
477
- case 'TSNonNullExpression':
478
- case 'TSSatisfiesExpression':
479
- case 'TSTypeAssertion':
480
- case 'TSInstantiationExpression': {
481
- visitExpr(cur.expression, shadowed)
482
- return
483
- }
484
- default: {
485
- if (typeof cur.type === 'string' && cur.type.startsWith('TS'))
486
- return
487
- for (const key of Object.keys(cur)) {
488
- if (key === 'start' || key === 'end' || key === 'type')
489
- continue
490
- const val = cur[key]
491
- if (Array.isArray(val)) {
492
- for (let i = 0; i < val.length; i++)
493
- visitExpr(val[i] as AstNode, shadowed)
494
- }
495
- else if (val !== null && typeof val === 'object') {
496
- visitExpr(val as AstNode, shadowed)
497
- }
498
- }
499
- }
500
- }
501
- }
534
+ function compileNestedComponent(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string | undefined {
535
+ if (!containsJsx(fn.body))
536
+ return undefined
537
+ const firstParam = fn.params[0]
538
+ const destructured = extractDestructuredParam(firstParam)
539
+ if (destructured === undefined)
540
+ return undefined
541
+ return buildCompiledFunction(fn, outerRewrites)
542
+ }
502
543
 
503
- visitExpr(node, new Set())
504
- return sub.toString()
544
+ function compileExpression(node: Node, scopeRewrites: ReadonlyMap<string, string>): string {
545
+ return rewriteFreeIdentifiers(code, node, scopeRewrites, compileRootJsx, compileNestedComponent)
505
546
  }
506
547
 
507
- function compileComponentCall(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
548
+ function compileComponentCall(node: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
508
549
  const tag = jsxTagName(node.openingElement.name)
509
- const propEntries: string[] = []
550
+ const attrs = node.openingElement.attributes
551
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
552
+ const segments: string[] = []
553
+ let currentObj: string[] = []
554
+
555
+ const flushObj = () => {
556
+ if (currentObj.length > 0) {
557
+ segments.push(`{ ${currentObj.join(', ')} }`)
558
+ currentObj = []
559
+ }
560
+ }
510
561
 
511
- for (const attr of node.openingElement.attributes as AstNode[]) {
562
+ for (const attr of attrs) {
512
563
  if (attr.type === 'JSXSpreadAttribute') {
513
- propEntries.push(`...(${compileExpression(attr.argument, scopeRewrites)})`)
564
+ flushObj()
565
+ segments.push(`(${compileExpression(attr.argument, scopeRewrites)})`)
514
566
  continue
515
567
  }
516
568
  const name = jsxTagName(attr.name)
@@ -519,112 +571,103 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
519
571
 
520
572
  const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
521
573
  if (attr.value === null) {
522
- propEntries.push(`${propKey}: true`)
574
+ currentObj.push(`${propKey}: true`)
523
575
  }
524
576
  else if (attr.value.type === 'Literal') {
525
- propEntries.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
577
+ currentObj.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
526
578
  }
527
- else if (attr.value.type === 'JSXExpressionContainer') {
528
- const expr = attr.value.expression as AstNode
579
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
580
+ const expr = attr.value.expression
529
581
  const exprCode = compileExpression(expr, scopeRewrites)
530
- // Reactive getter for dynamic expressions; plain property for literals, functions, and bare identifiers (signals)
582
+ // Reactive getter for dynamic expressions; plain property for literals and inline functions.
531
583
  const isStatic = expr.type === 'Literal'
532
584
  || expr.type === 'ArrowFunctionExpression'
533
585
  || expr.type === 'FunctionExpression'
534
586
  if (isStatic)
535
- propEntries.push(`${propKey}: ${exprCode}`)
587
+ currentObj.push(`${propKey}: ${exprCode}`)
536
588
  else
537
- propEntries.push(`get ${propKey}() { return ${exprCode} }`)
589
+ currentObj.push(`get ${propKey}() { return ${exprCode} }`)
538
590
  }
539
591
  }
540
592
 
541
- const meaningful = filterChildren(node.children as AstNode[])
593
+ const meaningful = filterMeaningfulChildren(node.children)
542
594
  if (meaningful.length === 1) {
543
595
  const child = meaningful[0]!
544
596
  if (child.type === 'JSXText')
545
- propEntries.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value as string)))}`)
546
- else if (child.type === 'JSXElement' || child.type === 'JSXFragment')
547
- propEntries.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
548
- else if (child.type === 'JSXExpressionContainer')
549
- propEntries.push(`get children() { return ${compileExpression(child.expression, scopeRewrites)} }`)
597
+ currentObj.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))}`)
598
+ else if (isJsxNode(child))
599
+ currentObj.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
600
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
601
+ currentObj.push(`get children() { return ${compileExpression(child.expression, scopeRewrites)} }`)
550
602
  }
551
603
  else if (meaningful.length > 1) {
552
604
  const items = meaningful.map((c) => {
553
605
  if (c.type === 'JSXText')
554
- return JSON.stringify(decodeHtmlEntities(cleanJsxText(c.value as string)))
555
- if (c.type === 'JSXElement' || c.type === 'JSXFragment')
606
+ return JSON.stringify(decodeHtmlEntities(cleanJsxText(c.value)))
607
+ if (isJsxNode(c))
556
608
  return compileRootJsx(c, scopeRewrites)
557
- return compileExpression(c.expression, scopeRewrites)
609
+ if (c.type === 'JSXExpressionContainer' && c.expression.type !== 'JSXEmptyExpression')
610
+ return compileExpression(c.expression, scopeRewrites)
611
+ return 'null'
558
612
  })
559
- propEntries.push(`get children() { return [${items.join(', ')}] }`)
613
+ currentObj.push(`get children() { return [${items.join(', ')}] }`)
560
614
  }
561
615
 
562
- const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
563
- return `${tag}(${propsObj})`
564
- }
565
-
566
- function filterChildren(children: AstNode[]): AstNode[] {
567
- return children.filter((c) => {
568
- if (c.type === 'JSXText')
569
- return cleanJsxText(c.value as string) !== ''
570
- if (c.type === 'JSXExpressionContainer' && c.expression.type === 'JSXEmptyExpression')
571
- return false
572
- return true
573
- })
574
- }
616
+ flushObj()
575
617
 
576
- function extractKeyExpr(jsxEl: AstNode): AstNode | undefined {
577
- if (jsxEl.type !== 'JSXElement')
578
- return undefined
579
- for (const attr of jsxEl.openingElement.attributes as AstNode[]) {
580
- if (attr.type === 'JSXAttribute' && attr.name?.name === 'key') {
581
- if (attr.value?.type === 'JSXExpressionContainer')
582
- return attr.value.expression as AstNode
583
- if (attr.value?.type === 'Literal')
584
- return attr.value as AstNode
585
- }
618
+ if (!hasSpread) {
619
+ const propsObj = segments[0] ?? '{}'
620
+ return `${tag}(${propsObj})`
586
621
  }
587
- return undefined
622
+ if (segments.length === 1)
623
+ return `${tag}(${segments[0]!})`
624
+ return `${tag}(${use('mergeProps')}(${segments.join(', ')}))`
588
625
  }
589
626
 
590
- function compileElementTree(rootEl: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
627
+ function compileElementTree(rootEl: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
591
628
  const ops: string[] = []
592
629
  const rootVar = freshVar('_e')
593
630
  const childRefs = new Map<string, string>() // "parentVar:index" -> varName
594
- const childMaxIdx = new Map<string, number>()
595
631
 
596
- function ensureNode(parentVar: string, index: number): string {
597
- const key = `${parentVar}:${index}`
598
- const existing = childRefs.get(key)
599
- if (existing !== undefined)
600
- return existing
601
- const v = freshVar('_e')
602
- childRefs.set(key, v)
603
- const prevMax = childMaxIdx.get(parentVar) ?? -1
604
- if (index > prevMax)
605
- childMaxIdx.set(parentVar, index)
606
- return v
632
+ const walkPlan: { parentVar: string, index: number, varName: string }[] = []
633
+ const textSlotsByParent = new Map<string, Set<number>>()
634
+ const rangeSlotsByParent = new Map<string, Set<number>>()
635
+
636
+ const addTextSlot = (parentVar: string, idx: number) => {
637
+ let s = textSlotsByParent.get(parentVar)
638
+ if (s === undefined) {
639
+ s = new Set()
640
+ textSlotsByParent.set(parentVar, s)
641
+ }
642
+ s.add(idx)
607
643
  }
608
644
 
609
- const walkPlan: { parentVar: string, index: number, varName: string }[] = []
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 <!---->...<!---->
645
+ const addRangeSlot = (parentVar: string, idx: number) => {
646
+ let s = rangeSlotsByParent.get(parentVar)
647
+ if (s === undefined) {
648
+ s = new Set()
649
+ rangeSlotsByParent.set(parentVar, s)
650
+ }
651
+ s.add(idx)
652
+ }
612
653
 
613
654
  function requestChild(parentVar: string, index: number): string {
614
655
  const key = `${parentVar}:${index}`
615
656
  const existing = childRefs.get(key)
616
657
  if (existing !== undefined)
617
658
  return existing
618
- const v = ensureNode(parentVar, index)
659
+ const v = freshVar('_e')
660
+ childRefs.set(key, v)
619
661
  walkPlan.push({ parentVar, index, varName: v })
620
662
  return v
621
663
  }
622
664
 
623
- function buildHtml(el: AstNode, elVar: string): string {
665
+ function buildHtml(el: JSXElement, elVar: string): string {
624
666
  const tag = jsxTagName(el.openingElement.name)
667
+ const rawTextTag = RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined
625
668
  let html = `<${tag}`
626
669
 
627
- for (const attr of el.openingElement.attributes as AstNode[]) {
670
+ for (const attr of el.openingElement.attributes) {
628
671
  if (attr.type === 'JSXSpreadAttribute') {
629
672
  ops.push(`${use('spread')}(${elVar}, () => (${compileExpression(attr.argument, scopeRewrites)}));`)
630
673
  continue
@@ -633,35 +676,42 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
633
676
  if (rawName === 'key' || rawName === '$hydrate')
634
677
  continue
635
678
 
636
- if (rawName === 'ref' && attr.value?.type === 'JSXExpressionContainer') {
637
- const refCode = compileExpression(attr.value.expression, scopeRewrites)
638
- ops.push(`(${refCode})(${elVar});`)
679
+ if (rawName === 'ref') {
680
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
681
+ const refCode = compileExpression(attr.value.expression, scopeRewrites)
682
+ ops.push(`(${refCode})(${elVar});`)
683
+ }
639
684
  continue
640
685
  }
641
686
 
642
687
  if (rawName === 'innerHTML') {
643
688
  if (attr.value?.type === 'Literal')
644
689
  ops.push(`${use('setInnerHtml')}(${elVar}, ${JSON.stringify(String(attr.value.value))});`)
645
- else if (attr.value?.type === 'JSXExpressionContainer')
690
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
646
691
  ops.push(`${use('effect')}(() => ${use('setInnerHtml')}(${elVar}, ${compileExpression(attr.value.expression, scopeRewrites)}));`)
647
692
  continue
648
693
  }
649
694
 
650
695
  const eventMatch = EVENT_ATTR.exec(rawName)
651
- if (eventMatch !== null && attr.value?.type === 'JSXExpressionContainer') {
652
- const eventName = eventMatch[1]!.toLowerCase()
653
- const handlerCode = compileExpression(attr.value.expression, scopeRewrites)
654
- if (DELEGATED_EVENTS.has(eventName)) {
655
- delegatedEvents.add(eventName)
656
- ops.push(`${elVar}.$$${eventName} = ${handlerCode};`)
657
- }
658
- else {
659
- ops.push(`${use('on')}(${elVar}, ${JSON.stringify(eventName)}, ${handlerCode});`)
696
+ if (eventMatch !== null) {
697
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
698
+ const eventName = eventMatch[1]!.toLowerCase()
699
+ const handlerCode = compileExpression(attr.value.expression, scopeRewrites)
700
+ if (DELEGATED_EVENTS.has(eventName)) {
701
+ delegatedEvents.add(eventName)
702
+ ops.push(`${elVar}.$$${eventName} = ${handlerCode};`)
703
+ }
704
+ else {
705
+ ops.push(`${use('on')}(${elVar}, ${JSON.stringify(eventName)}, ${handlerCode});`)
706
+ }
660
707
  }
661
708
  continue
662
709
  }
663
710
 
664
711
  const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
712
+ if (isBlockedAttr(name))
713
+ continue
714
+
665
715
  if (attr.value === null) {
666
716
  html += isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`
667
717
  }
@@ -669,9 +719,9 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
669
719
  if (!isUnsafeUrlAttr(name, attr.value.value))
670
720
  html += ` ${name}="${escapeStaticAttr(String(attr.value.value))}"`
671
721
  }
672
- else if (attr.value.type === 'JSXExpressionContainer') {
673
- const expr = attr.value.expression as AstNode
674
- const lit = !DOM_PROPS.has(name) && name !== 'style' ? staticLiteral(expr) : { ok: false as const }
722
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
723
+ const expr = attr.value.expression
724
+ const lit = !DOM_PROPS.has(name) ? staticLiteral(expr) : { ok: false as const }
675
725
  if (lit.ok) {
676
726
  if (typeof lit.value === 'boolean') {
677
727
  if (isStringBoolAttr(name))
@@ -700,278 +750,248 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
700
750
  if (VOID_ELEMENTS.has(tag))
701
751
  return html
702
752
 
703
- const meaningful = filterChildren(el.children as AstNode[])
753
+ const meaningful = filterMeaningfulChildren(el.children)
754
+ const slots = meaningful.map(c => classifyJsxChild(c)).filter(s => s !== undefined)
755
+ const hasSiblings = slots.length > 1
704
756
  let domIndex = 0
705
757
  let prevWasStaticText = false
758
+ let hadVariableRange = false
759
+
760
+ const prevSvgDepth = svgDepth
761
+ if (tag === 'svg')
762
+ svgDepth = 1
763
+ else if (tag === 'foreignObject')
764
+ svgDepth = 0
765
+
766
+ try {
767
+ for (let i = 0; i < slots.length; i++) {
768
+ const slot = slots[i]!
769
+ const isLast = i === slots.length - 1
770
+
771
+ if (slot.kind === 'static-text') {
772
+ if (rawTextTag !== undefined)
773
+ html += escapeRawText(slot.text, rawTextTag)
774
+ else
775
+ html += escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text))
776
+ if (!prevWasStaticText) {
777
+ domIndex++
778
+ prevWasStaticText = true
779
+ }
780
+ continue
781
+ }
706
782
 
707
- for (let i = 0; i < meaningful.length; i++) {
708
- const child = meaningful[i]!
709
- const isLast = i === meaningful.length - 1
783
+ prevWasStaticText = false
710
784
 
711
- if (child.type === 'JSXText') {
712
- html += cleanJsxText(child.value as string)
713
- if (!prevWasStaticText) {
714
- domIndex++
715
- prevWasStaticText = true
785
+ if (slot.kind === 'element') {
786
+ const subOpsBefore = ops.length
787
+ const subWalkBefore = walkPlan.length
788
+ const placeholderVar = `__SUB_${varCounter++}`
789
+ const subHtml = buildHtml(slot.node, placeholderVar)
790
+ const needed = ops.length > subOpsBefore || walkPlan.length > subWalkBefore
791
+ if (needed) {
792
+ const realVar = requestChild(elVar, domIndex)
793
+ for (let k = subOpsBefore; k < ops.length; k++)
794
+ ops[k] = ops[k]!.replaceAll(placeholderVar, realVar)
795
+ for (let k = subWalkBefore; k < walkPlan.length; k++) {
796
+ if (walkPlan[k]!.parentVar === placeholderVar)
797
+ walkPlan[k]!.parentVar = realVar
798
+ }
799
+ const tSlots = textSlotsByParent.get(placeholderVar)
800
+ if (tSlots !== undefined) {
801
+ textSlotsByParent.delete(placeholderVar)
802
+ textSlotsByParent.set(realVar, tSlots)
803
+ }
804
+ const rSlots = rangeSlotsByParent.get(placeholderVar)
805
+ if (rSlots !== undefined) {
806
+ rangeSlotsByParent.delete(placeholderVar)
807
+ rangeSlotsByParent.set(realVar, rSlots)
808
+ }
716
809
  }
810
+ html += subHtml
811
+ domIndex++
717
812
  continue
718
813
  }
719
814
 
720
- if (child.type === 'JSXExpressionContainer' && child.expression?.type === 'Literal' && typeof child.expression.value === 'string') {
721
- html += escapeStaticText(child.expression.value)
722
- if (!prevWasStaticText) {
815
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
816
+ const renderedCode = slot.kind === 'component'
817
+ ? compileComponentCall(slot.node, scopeRewrites)
818
+ : compileRootJsx(slot.node, scopeRewrites)
819
+ if (!hasSiblings) {
820
+ ops.push(`${use('insert')}(${elVar}, () => ${renderedCode}, null, null);`)
821
+ }
822
+ else if (isLast) {
823
+ const startVar = requestChild(elVar, domIndex)
824
+ html += '<!--k[-->'
723
825
  domIndex++
724
- prevWasStaticText = true
826
+ ops.push(`${use('insert')}(${elVar}, () => ${renderedCode}, null, ${startVar});`)
827
+ }
828
+ else {
829
+ const startVar = requestChild(elVar, domIndex)
830
+ const endVar = requestChild(elVar, domIndex + 1)
831
+ html += '<!--k[--><!--k]-->'
832
+ addRangeSlot(elVar, domIndex + 1)
833
+ domIndex += 2
834
+ ops.push(`${use('insert')}(${elVar}, () => ${renderedCode}, ${endVar}, ${startVar});`)
725
835
  }
836
+ hadVariableRange = true
726
837
  continue
727
838
  }
728
839
 
729
- prevWasStaticText = false
840
+ if (slot.kind === 'loop') {
841
+ const { match } = slot
842
+ const needsBracket = !isLast || hadVariableRange
843
+ let anchorVar: string
844
+ let skipArg = ''
845
+ if (needsBracket) {
846
+ anchorVar = requestChild(elVar, domIndex)
847
+ html += '<!--k[--><!--k]-->'
848
+ addRangeSlot(elVar, domIndex + 1)
849
+ domIndex += 2
850
+ }
851
+ else {
852
+ anchorVar = 'null'
853
+ if (domIndex > 0)
854
+ skipArg = `, ${domIndex}`
855
+ }
730
856
 
731
- if (child.type === 'JSXElement') {
732
- const childTag = jsxTagName(child.openingElement.name)
733
- if (isComponentTag(childTag)) {
734
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
735
- if (!isLast) {
736
- html += '<!---->'
737
- domIndex++
738
- }
739
- const callCode = compileComponentCall(child, scopeRewrites)
740
- ops.push(`${use('insert')}(${elVar}, () => ${callCode}, ${anchorVar});`)
857
+ const eachCode = compileExpression(match.target, scopeRewrites)
858
+ const params = match.params
859
+ const firstParam = params[0]
860
+ const secondParam = params[1]
861
+ const idxParam = secondParam?.type === 'Identifier'
862
+ ? secondParam.name
863
+ : secondParam?.type === 'AssignmentPattern' && secondParam.left.type === 'Identifier'
864
+ ? secondParam.left.name
865
+ : undefined
866
+
867
+ // Fast path: a const array literal (e.g. `NAV.map(...)`) renders once through `eachStatic`.
868
+ const isStaticArr = match.target.type === 'Identifier' && staticArrays.has(match.target.name) && !scopeRewrites.has(match.target.name)
869
+ if (isStaticArr) {
870
+ const rawParams = params.map(p => code.slice(p.start, p.end)).join(', ')
871
+ const shadowed = withoutBindings(scopeRewrites, params)
872
+ const rowBody = match.isJsxBody ? compileRootJsx(match.body as JSXElement | JSXFragment, shadowed) : compileExpression(match.body, shadowed)
873
+ ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
874
+ hadVariableRange = true
875
+ continue
876
+ }
877
+
878
+ const keyAst = match.isJsxBody ? extractKeyExpr(match.body) : extractBlockKeyExpr(match.body as BlockStatement)
879
+ const rowSig = freshVar('_r')
880
+ const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
881
+ const rowRewrites = new Map(scopeRewrites)
882
+ const keyRewrites = withoutBindings(scopeRewrites, params)
883
+ let keyFn: string
884
+
885
+ if (firstParam !== undefined && firstParam.type !== 'Identifier') {
886
+ const patCode = code.slice(firstParam.start, firstParam.end)
887
+ keyFn = keyAst !== undefined
888
+ ? `(${patCode}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
889
+ : `(_item) => _item`
890
+ for (const [name, read] of patternReads(firstParam, `${rowSig}.value`, scopeRewrites))
891
+ rowRewrites.set(name, read)
741
892
  }
742
893
  else {
743
- // Check if child element (or any descendant) needs bindings before allocating a var
744
- const subOpsBefore = ops.length
745
- const subWalkBefore = walkPlan.length
746
- const placeholderVar = `__SUB_${varCounter++}`
747
- const subHtml = buildHtml(child, placeholderVar)
748
- const needed = ops.length > subOpsBefore || walkPlan.length > subWalkBefore
749
- if (needed) {
750
- const realVar = requestChild(elVar, domIndex)
751
- for (let k = subOpsBefore; k < ops.length; k++)
752
- ops[k] = ops[k]!.replaceAll(placeholderVar, realVar)
753
- for (let k = subWalkBefore; k < walkPlan.length; k++) {
754
- if (walkPlan[k]!.parentVar === placeholderVar)
755
- walkPlan[k]!.parentVar = realVar
756
- }
757
- const prefix = `${placeholderVar}:`
758
- for (const slot of [...dynamicTextSlots]) {
759
- if (slot.startsWith(prefix)) {
760
- dynamicTextSlots.delete(slot)
761
- dynamicTextSlots.add(`${realVar}:${slot.slice(prefix.length)}`)
762
- }
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
- }
770
- }
771
- html += subHtml
772
- domIndex++
894
+ const itemParam = firstParam?.type === 'Identifier' ? firstParam.name : '_item'
895
+ keyFn = keyAst !== undefined
896
+ ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
897
+ : `(${itemParam}) => ${itemParam}`
898
+ rowRewrites.set(itemParam, `${rowSig}.value`)
773
899
  }
900
+ if (idxParam !== undefined && idxSig !== undefined)
901
+ rowRewrites.set(idxParam, `${idxSig}.value`)
902
+
903
+ const rowBody = match.isJsxBody ? compileRootJsx(match.body as JSXElement | JSXFragment, rowRewrites) : compileExpression(match.body, rowRewrites)
904
+ const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
905
+ ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
906
+ hadVariableRange = true
774
907
  continue
775
908
  }
776
909
 
777
- if (child.type === 'JSXFragment') {
778
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
779
- if (!isLast) {
780
- html += '<!---->'
781
- domIndex++
910
+ if (slot.kind === 'and-show') {
911
+ let anchorVar = 'null'
912
+ if (hasSiblings) {
913
+ anchorVar = requestChild(elVar, domIndex)
914
+ html += '<!--k[--><!--k]-->'
915
+ addRangeSlot(elVar, domIndex + 1)
916
+ domIndex += 2
782
917
  }
783
- const fragCode = compileRootJsx(child, scopeRewrites)
784
- ops.push(`${use('insert')}(${elVar}, () => ${fragCode}, ${anchorVar});`)
918
+ const whenCode = compileExpression(slot.expr.left, scopeRewrites)
919
+ const trueCode = compileRootJsx(slot.right, scopeRewrites)
920
+ ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
921
+ hadVariableRange = true
785
922
  continue
786
923
  }
787
924
 
788
- if (child.type === 'JSXExpressionContainer') {
789
- const expr = child.expression as AstNode
790
-
791
- // Case 1: Keyed `.map((item, idx?) => <jsx> | { ... return <jsx> })` → `__loop(...)`
792
- if (
793
- expr.type === 'CallExpression'
794
- && expr.callee?.type === 'MemberExpression'
795
- && !expr.callee.computed
796
- && expr.callee.property?.name === 'map'
797
- && expr.arguments?.length === 1
798
- ) {
799
- const cb = expr.arguments[0] as AstNode
800
- const cbBody = cb.body?.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body
801
- const isJsxBody = cbBody?.type === 'JSXElement' || cbBody?.type === 'JSXFragment'
802
- const isBlockJsxBody = cbBody?.type === 'BlockStatement' && hasJsxDescendant(cbBody)
803
- if (
804
- (cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression')
805
- && (isJsxBody || isBlockJsxBody)
806
- ) {
807
- const loopSkip = domIndex
808
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
809
- if (!isLast) {
810
- html += '<!---->'
811
- domIndex++
812
- }
813
-
814
- const eachCode = compileExpression(expr.callee.object, scopeRewrites)
815
- const params = cb.params as AstNode[]
816
- const firstParam = params[0]
817
- const idxParam = params[1]?.type === 'Identifier' ? params[1].name as string : undefined
818
- const skipArg = loopSkip > 0 ? `, ${loopSkip}` : ''
819
-
820
- // Fast path: provably static constant array (e.g. `NAV.map(...)`) -> lightweight `eachStatic` (0 bytes of LIS reconciler!)
821
- const isStaticArr = expr.callee.object.type === 'Identifier' && !scopeRewrites.has(expr.callee.object.name as string)
822
- if (isStaticArr) {
823
- const rawParams = params.map(p => code.slice(p.start, p.end)).join(', ')
824
- const shadowed = new Map(scopeRewrites)
825
- for (const p of params) {
826
- const names = new Set<string>()
827
- collectPatternNames(p, names)
828
- for (const n of names)
829
- shadowed.delete(n)
830
- }
831
- const rowBody = isJsxBody ? compileRootJsx(cbBody, shadowed) : compileExpression(cbBody, shadowed)
832
- ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
833
- continue
834
- }
835
-
836
- const keyAst = isJsxBody ? extractKeyExpr(cbBody) : extractBlockKeyExpr(cbBody)
837
-
838
- const rowSig = freshVar('_r')
839
- const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
840
- const rowRewrites = new Map(scopeRewrites)
841
- let keyFn: string
842
-
843
- const keyRewrites = new Map(scopeRewrites)
844
- for (const p of params) {
845
- const names = new Set<string>()
846
- collectPatternNames(p, names)
847
- for (const n of names)
848
- keyRewrites.delete(n)
849
- }
850
-
851
- if (firstParam?.type === 'ObjectPattern') {
852
- const patCode = code.slice(firstParam.start, firstParam.end)
853
- keyFn = keyAst !== undefined
854
- ? `(${patCode}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
855
- : `(_item) => _item`
856
- for (const prop of firstParam.properties as AstNode[]) {
857
- if (prop.type === 'Property' && prop.key?.type === 'Identifier') {
858
- const propKey = prop.key.name as string
859
- if (prop.value.type === 'Identifier') {
860
- rowRewrites.set(prop.value.name as string, `${rowSig}.value.${propKey}`)
861
- }
862
- else if (prop.value.type === 'AssignmentPattern' && prop.value.left?.type === 'Identifier') {
863
- const defCode = code.slice(prop.value.right.start, prop.value.right.end)
864
- rowRewrites.set(prop.value.left.name as string, `(${rowSig}.value.${propKey} === undefined ? ${defCode} : ${rowSig}.value.${propKey})`)
865
- }
866
- }
867
- }
868
- }
869
- else {
870
- const itemParam = firstParam?.type === 'Identifier' ? firstParam.name as string : '_item'
871
- keyFn = keyAst !== undefined
872
- ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
873
- : `(${itemParam}) => ${itemParam}`
874
- rowRewrites.set(itemParam, `${rowSig}.value`)
875
- }
876
- if (idxParam !== undefined && idxSig !== undefined)
877
- rowRewrites.set(idxParam, `${idxSig}.value`)
878
-
879
- const rowBody = isJsxBody ? compileRootJsx(cbBody, rowRewrites) : compileExpression(cbBody, rowRewrites)
880
- const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
881
- ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
882
- continue
883
- }
925
+ if (slot.kind === 'ternary-show') {
926
+ let anchorVar = 'null'
927
+ if (hasSiblings) {
928
+ anchorVar = requestChild(elVar, domIndex)
929
+ html += '<!--k[--><!--k]-->'
930
+ addRangeSlot(elVar, domIndex + 1)
931
+ domIndex += 2
884
932
  }
933
+ const whenCode = compileExpression(slot.expr.test, scopeRewrites)
934
+ const trueCode = isJsxNode(slot.cons)
935
+ ? compileRootJsx(slot.cons, scopeRewrites)
936
+ : compileExpression(slot.cons, scopeRewrites)
937
+ const falseCode = isJsxNode(slot.alt)
938
+ ? compileRootJsx(slot.alt, scopeRewrites)
939
+ : compileExpression(slot.alt, scopeRewrites)
940
+ ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
941
+ hadVariableRange = true
942
+ continue
943
+ }
885
944
 
886
- // Case 2: `cond && <jsx>` → `__show(...)`
887
- if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
888
- const right = unwrapParens(expr.right)
889
- if (right.type === 'JSXElement' || right.type === 'JSXFragment') {
890
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
891
- if (!isLast) {
892
- html += '<!---->'
893
- domIndex++
894
- }
895
- const whenCode = compileExpression(expr.left, scopeRewrites)
896
- const trueCode = compileRootJsx(right, scopeRewrites)
897
- ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
898
- continue
899
- }
945
+ // Generic expression slot
946
+ const exprCode = compileExpression(slot.expr, scopeRewrites)
947
+ if (isNodeCapableExpr(slot.expr)) {
948
+ if (!hasSiblings) {
949
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, null);`)
900
950
  }
901
-
902
- // Case 3: `cond ? <a/> : <b/>` → `__show(...)`
903
- if (expr.type === 'ConditionalExpression') {
904
- const consNode = unwrapParens(expr.consequent)
905
- const altNode = unwrapParens(expr.alternate)
906
- if (consNode.type === 'JSXElement' || consNode.type === 'JSXFragment' || altNode.type === 'JSXElement' || altNode.type === 'JSXFragment') {
907
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
908
- if (!isLast) {
909
- html += '<!---->'
910
- domIndex++
911
- }
912
- const whenCode = compileExpression(expr.test, scopeRewrites)
913
- const trueCode = consNode.type === 'JSXElement' || consNode.type === 'JSXFragment'
914
- ? compileRootJsx(consNode, scopeRewrites)
915
- : compileExpression(consNode, scopeRewrites)
916
- const falseCode = altNode.type === 'JSXElement' || altNode.type === 'JSXFragment'
917
- ? compileRootJsx(altNode, scopeRewrites)
918
- : compileExpression(altNode, scopeRewrites)
919
- ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
920
- continue
921
- }
951
+ else if (isLast) {
952
+ const startVar = requestChild(elVar, domIndex)
953
+ html += '<!--k[-->'
954
+ domIndex++
955
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, ${startVar});`)
922
956
  }
923
-
924
- // Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, JSX expressions, or call expressions)
925
- const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
926
- || (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
927
- const exprCode = compileExpression(expr, scopeRewrites)
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)
934
- html += '<!---->'
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});`)
945
- }
946
- continue
957
+ else {
958
+ const startVar = requestChild(elVar, domIndex)
959
+ const endVar = requestChild(elVar, domIndex + 1)
960
+ html += '<!--k[--><!--k]-->'
961
+ addRangeSlot(elVar, domIndex + 1)
962
+ domIndex += 2
963
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${endVar}, ${startVar});`)
947
964
  }
948
-
949
- // Case 5: Dynamic text / expression binding
950
- if (meaningful.length === 1) {
951
- // Sole dynamic child: 0 comment markers!
952
- html += ' '
953
- domIndex++
954
- const txtVar = freshVar('_txt')
955
- ops.push(`const ${txtVar} = ${use('firstText')}(${elVar});`)
956
- ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
965
+ hadVariableRange = true
966
+ }
967
+ else if (!hasSiblings) {
968
+ // Sole dynamic child: 0 comment markers!
969
+ html += ' '
970
+ domIndex++
971
+ const txtVar = freshVar('_txt')
972
+ ops.push(`const ${txtVar} = ${use('firstText')}(${elVar});`)
973
+ ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
974
+ }
975
+ else {
976
+ // Sibling dynamic text: open comment + optional text (+ closing comment if followed by more siblings)
977
+ const markerVar = requestChild(elVar, domIndex)
978
+ if (isLast) {
979
+ html += '<!----> '
980
+ domIndex += 2
957
981
  }
958
982
  else {
959
- // Sibling dynamic child: open comment + optional text (+ closing comment if followed by more siblings)
960
- const markerVar = requestChild(elVar, domIndex)
961
- if (isLast) {
962
- html += '<!----> '
963
- domIndex += 2
964
- }
965
- else {
966
- html += '<!----> <!---->'
967
- dynamicTextSlots.add(`${elVar}:${domIndex + 1}`)
968
- domIndex += 3
969
- }
970
- const txtVar = freshVar('_txt')
971
- ops.push(`const ${txtVar} = ${use('textAfter')}(${markerVar});`)
972
- ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
983
+ html += '<!----> <!---->'
984
+ addTextSlot(elVar, domIndex + 1)
985
+ domIndex += 3
973
986
  }
987
+ const txtVar = freshVar('_txt')
988
+ ops.push(`const ${txtVar} = ${use('textAfter')}(${markerVar});`)
989
+ ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
974
990
  }
991
+ }
992
+ }
993
+ finally {
994
+ svgDepth = prevSvgDepth
975
995
  }
976
996
 
977
997
  html += `</${tag}>`
@@ -981,9 +1001,10 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
981
1001
  const html = buildHtml(rootEl, rootVar)
982
1002
  const rootTag = jsxTagName(rootEl.openingElement.name)
983
1003
  const tmplName = `_t${templates.length}`
984
- templates.push({ name: tmplName, html, isSvg: SVG_CHILD_TAGS.has(rootTag) })
1004
+ const isSvg = svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
1005
+ templates.push({ name: tmplName, html, isSvg })
985
1006
 
986
- // Emit efficient parent->child sibling walks grouped by parentVar (breadth-first / parent-first order)
1007
+ // Emit parent->child sibling walks grouped by parentVar (breadth-first / parent-first order)
987
1008
  const walkStmts: string[] = []
988
1009
  const byParent = new Map<string, { index: number, varName: string }[]>()
989
1010
  for (const item of walkPlan) {
@@ -995,7 +1016,6 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
995
1016
  arr.push({ index: item.index, varName: item.varName })
996
1017
  }
997
1018
 
998
- // Emit walks in topological order (root first)
999
1019
  const emittedParents = new Set<string>([rootVar])
1000
1020
  const queue = [rootVar]
1001
1021
  while (queue.length > 0) {
@@ -1005,6 +1025,8 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1005
1025
  continue
1006
1026
  list.sort((a, b) => a.index - b.index)
1007
1027
 
1028
+ const tSlots = textSlotsByParent.get(pVar)
1029
+ const rSlots = rangeSlotsByParent.get(pVar)
1008
1030
  let prevVar: string | undefined
1009
1031
  let prevIdx = -1
1010
1032
  for (const { index, varName } of list) {
@@ -1019,11 +1041,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1019
1041
  pos = prevIdx
1020
1042
  }
1021
1043
  while (pos < index) {
1022
- if (dynamicTextSlots.has(`${pVar}:${pos + 1}`) && pos + 2 <= index) {
1044
+ if (tSlots?.has(pos + 1) && pos + 2 <= index) {
1023
1045
  expr = `${use('skipText')}(${expr})`
1024
1046
  pos += 2
1025
1047
  }
1026
- else if (dynamicRangeSlots.has(`${pVar}:${pos + 1}`)) {
1048
+ else if (rSlots?.has(pos + 1)) {
1027
1049
  expr = `${use('skipRange')}(${expr})`
1028
1050
  pos += 1
1029
1051
  }
@@ -1048,20 +1070,35 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1048
1070
  return `(() => { const ${rootVar} = ${tmplName}(); ${walkStmts.join(' ')} ${ops.join(' ')} return ${rootVar}; })()`
1049
1071
  }
1050
1072
 
1051
- function compileRootJsx(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
1073
+ function compileRootJsx(node: JSXElement | JSXFragment, scopeRewrites: ReadonlyMap<string, string>): string {
1052
1074
  if (node.type === 'JSXFragment') {
1053
- const meaningful = filterChildren(node.children as AstNode[])
1075
+ const meaningful = filterMeaningfulChildren(node.children)
1054
1076
  if (meaningful.length === 0)
1055
1077
  return 'null'
1056
- if (meaningful.length === 1 && meaningful[0]!.type === 'JSXElement')
1057
- return compileRootJsx(meaningful[0]!, scopeRewrites)
1078
+ if (meaningful.length === 1) {
1079
+ const only = meaningful[0]!
1080
+ if (isJsxNode(only))
1081
+ return compileRootJsx(only, scopeRewrites)
1082
+ if (only.type === 'JSXText')
1083
+ return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(only.value)))})`
1084
+ if (only.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression') {
1085
+ const exprCode = compileExpression(only.expression, scopeRewrites)
1086
+ return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1087
+ }
1088
+ }
1058
1089
 
1059
1090
  const items = meaningful.map((child) => {
1060
- if (child.type === 'JSXElement' || child.type === 'JSXFragment')
1091
+ if (isJsxNode(child))
1061
1092
  return compileRootJsx(child, scopeRewrites)
1062
1093
  if (child.type === 'JSXText')
1063
- return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value as string)))})`
1064
- return `document.createTextNode(String(${compileExpression(child.expression, scopeRewrites)} ?? ""))`
1094
+ return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))})`
1095
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
1096
+ const exprCode = compileExpression(child.expression, scopeRewrites)
1097
+ if (isNodeCapableExpr(child.expression))
1098
+ return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1099
+ return `(() => { const _t = document.createTextNode(""); ${use('effect')}(() => ${use('setText')}(_t, (${exprCode}))); return _t; })()`
1100
+ }
1101
+ return 'document.createTextNode("")'
1065
1102
  })
1066
1103
  return `${use('frag')}(${items.join(', ')})`
1067
1104
  }
@@ -1073,98 +1110,126 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1073
1110
  return compileElementTree(node, scopeRewrites)
1074
1111
  }
1075
1112
 
1076
- // Handle component functions with destructured props + JSX compilation
1077
- function processFunction(fn: AstNode): void {
1078
- let fnHasJsx = false
1079
- walk(fn.body, (child) => {
1080
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
1081
- fnHasJsx = true
1082
- return false
1083
- }
1113
+ function extractDestructuredParam(firstParam: ParamPattern | undefined): {
1114
+ pattern: ObjectPattern
1115
+ defaultExpr: Node | undefined
1116
+ replaceStart: number
1117
+ replaceEnd: number
1118
+ typeAnn: string
1119
+ } | undefined {
1120
+ if (firstParam === undefined)
1084
1121
  return undefined
1085
- })
1086
- if (!fnHasJsx)
1087
- return
1088
-
1089
- const propRewrites = new Map<string, string>()
1090
- const firstParam = (fn.params as AstNode[])[0]
1091
- if (firstParam !== undefined && firstParam.type === 'ObjectPattern') {
1092
- const pVar = '__p'
1122
+ if (firstParam.type === 'ObjectPattern') {
1093
1123
  const typeAnn = firstParam.typeAnnotation ? code.slice(firstParam.typeAnnotation.start, firstParam.typeAnnotation.end) : ''
1094
- editor.replace(firstParam.start, firstParam.end, `${pVar}${typeAnn}`)
1124
+ return { pattern: firstParam, defaultExpr: undefined, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
1125
+ }
1126
+ if (firstParam.type === 'AssignmentPattern' && firstParam.left.type === 'ObjectPattern') {
1127
+ const pat = firstParam.left
1128
+ const typeAnn = pat.typeAnnotation ? code.slice(pat.typeAnnotation.start, pat.typeAnnotation.end) : ''
1129
+ return { pattern: pat, defaultExpr: firstParam.right, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
1130
+ }
1131
+ return undefined
1132
+ }
1095
1133
 
1096
- const extractedKeys: string[] = []
1097
- let restName: string | undefined
1134
+ function computePropRewrites(
1135
+ destructured: { pattern: ObjectPattern, defaultExpr: Node | undefined },
1136
+ pVar: string,
1137
+ outerRewrites: ReadonlyMap<string, string>,
1138
+ ): Map<string, string> {
1139
+ const propRewrites = new Map(outerRewrites)
1140
+ for (const [name, read] of patternReads(destructured.pattern, pVar, outerRewrites))
1141
+ propRewrites.set(name, read)
1142
+
1143
+ const extractedKeys: string[] = []
1144
+ let restName: string | undefined
1145
+ let staticKeys = true
1146
+ for (const prop of destructured.pattern.properties) {
1147
+ if (prop.type === 'RestElement')
1148
+ restName = prop.argument.type === 'Identifier' ? prop.argument.name : undefined
1149
+ else if (!prop.computed && prop.key.type === 'Identifier')
1150
+ extractedKeys.push(prop.key.name)
1151
+ else if (!prop.computed && prop.key.type === 'Literal' && typeof prop.key.value === 'string')
1152
+ extractedKeys.push(prop.key.value)
1153
+ else
1154
+ staticKeys = false
1155
+ }
1156
+ if (restName !== undefined && staticKeys)
1157
+ propRewrites.set(restName, `${use('omit')}(${pVar}, ${JSON.stringify(extractedKeys)})`)
1158
+ return propRewrites
1159
+ }
1098
1160
 
1099
- for (const prop of firstParam.properties as AstNode[]) {
1100
- if (prop.type === 'Property' && prop.key?.type === 'Identifier') {
1101
- const propKey = prop.key.name as string
1102
- extractedKeys.push(propKey)
1103
- if (prop.value.type === 'Identifier') {
1104
- propRewrites.set(prop.value.name as string, `${pVar}.${propKey}`)
1105
- }
1106
- else if (prop.value.type === 'AssignmentPattern' && prop.value.left?.type === 'Identifier') {
1107
- const defCode = code.slice(prop.value.right.start, prop.value.right.end)
1108
- propRewrites.set(prop.value.left.name as string, `(${pVar}.${propKey} === undefined ? ${defCode} : ${pVar}.${propKey})`)
1109
- }
1110
- }
1111
- else if (prop.type === 'RestElement' && prop.argument?.type === 'Identifier') {
1112
- restName = prop.argument.name as string
1113
- }
1114
- }
1161
+ function buildCompiledFunction(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string {
1162
+ const fnEditor = new SourceEditor(code.slice(fn.start, fn.end))
1163
+ const offset = fn.start
1164
+ const destructured = extractDestructuredParam(fn.params[0])
1165
+ const pVar = freshVar('__p')
1166
+ let propRewrites = new Map(outerRewrites)
1167
+
1168
+ if (destructured !== undefined) {
1169
+ const defSuffix = destructured.defaultExpr !== undefined
1170
+ ? ` = ${compileExpression(destructured.defaultExpr, outerRewrites)}`
1171
+ : ''
1172
+ fnEditor.replace(destructured.replaceStart - offset, destructured.replaceEnd - offset, `${pVar}${destructured.typeAnn}${defSuffix}`)
1173
+ propRewrites = computePropRewrites(destructured, pVar, outerRewrites)
1174
+ }
1175
+
1176
+ if (fn.body !== null)
1177
+ fnEditor.replace(fn.body.start - offset, fn.body.end - offset, compileExpression(fn.body, propRewrites))
1178
+ return fnEditor.toString()
1179
+ }
1180
+
1181
+ // Handle top-level component functions with destructured props + JSX compilation
1182
+ function processFunction(fn: ArrowFunctionExpression | OxcFunction): void {
1183
+ if (fn.body === null || !containsJsx(fn.body))
1184
+ return
1185
+
1186
+ const destructured = extractDestructuredParam(fn.params[0])
1187
+ let propRewrites = new Map<string, string>()
1115
1188
 
1116
- if (restName !== undefined)
1117
- propRewrites.set(restName, `${use('omit')}(${pVar}, ${JSON.stringify(extractedKeys)})`)
1189
+ if (destructured !== undefined) {
1190
+ const pVar = '__p'
1191
+ const defSuffix = destructured.defaultExpr !== undefined
1192
+ ? ` = ${compileExpression(destructured.defaultExpr, new Map())}`
1193
+ : ''
1194
+ editor.replace(destructured.replaceStart, destructured.replaceEnd, `${pVar}${destructured.typeAnn}${defSuffix}`)
1195
+ propRewrites = computePropRewrites(destructured, pVar, new Map())
1118
1196
  }
1119
1197
 
1120
- // Rewrite prop reads in non-JSX statements of the function body, and compile JSX roots with propRewrites
1121
- if (propRewrites.size > 0 && fn.body?.type === 'BlockStatement') {
1198
+ if (propRewrites.size > 0 && fn.body.type === 'BlockStatement') {
1122
1199
  const shadowed = new Set<string>()
1123
- for (const stmt of fn.body.body as AstNode[]) {
1124
- let stmtHasJsx = false
1125
- walk(stmt, (child) => {
1126
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
1127
- stmtHasJsx = true
1128
- return false
1129
- }
1130
- return undefined
1131
- })
1200
+ for (const stmt of fn.body.body) {
1201
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
1202
+ shadowed.add(stmt.id.name)
1203
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
1204
+ shadowed.add(stmt.id.name)
1205
+ }
1206
+ for (const stmt of fn.body.body) {
1132
1207
  const active = new Map<string, string>()
1133
1208
  for (const [k, v] of propRewrites) {
1134
1209
  if (!shadowed.has(k))
1135
1210
  active.set(k, v)
1136
1211
  }
1137
- // A statement holding JSX also reads props around it (`if (on) return <b/>`): compile both in one pass.
1138
- if (stmtHasJsx)
1212
+ if (active.size > 0 || containsJsx(stmt))
1139
1213
  editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
1140
- else if (active.size > 0)
1141
- editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
1142
1214
  if (stmt.type === 'VariableDeclaration') {
1143
- for (const d of stmt.declarations as AstNode[])
1215
+ for (const d of stmt.declarations)
1144
1216
  collectPatternNames(d.id, shadowed)
1145
1217
  }
1146
1218
  }
1147
1219
  }
1148
- else if (propRewrites.size > 0) {
1149
- editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
1150
- }
1151
1220
  else {
1152
- walk(fn.body, (child) => {
1153
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
1154
- editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
1155
- return false
1156
- }
1157
- return undefined
1158
- })
1221
+ editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
1159
1222
  }
1160
1223
  }
1161
1224
 
1162
1225
  walk(program, (node) => {
1226
+ if (loadNodes.has(node))
1227
+ return false
1163
1228
  if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
1164
1229
  processFunction(node)
1165
1230
  return false
1166
1231
  }
1167
- if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
1232
+ if (isJsxNode(node)) {
1168
1233
  editor.replace(node.start, node.end, compileRootJsx(node, new Map()))
1169
1234
  return false
1170
1235
  }
@@ -1180,7 +1245,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1180
1245
 
1181
1246
  if (used.size > 0) {
1182
1247
  const hasLoop = used.delete('loop')
1183
- const EXTRA_HELPERS = ['insert', 'omit', 'setInnerHtml', 'show', 'spread']
1248
+ const EXTRA_HELPERS = ['insert', 'mergeProps', 'omit', 'setInnerHtml', 'show', 'spread']
1184
1249
  const usedExtras: string[] = []
1185
1250
  for (const name of EXTRA_HELPERS) {
1186
1251
  if (used.delete(name))