@sigil-dev/compiler 0.9.29 → 0.9.30

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 (38) hide show
  1. package/index.ts +6 -4
  2. package/package.json +1 -1
  3. package/src/babel/index.ts +763 -750
  4. package/src/babel/jsx/anchor-mount.ts +338 -333
  5. package/src/babel/jsx/children.ts +116 -116
  6. package/src/babel/jsx/element.ts +1040 -1034
  7. package/src/babel/jsx/fragment.ts +271 -271
  8. package/src/babel/jsx/keyed-list.ts +339 -339
  9. package/src/babel/jsx/utils.ts +356 -356
  10. package/src/babel/util/bind.ts +143 -143
  11. package/src/babel/util/css.ts +208 -208
  12. package/src/babel/util/dead-code.ts +94 -93
  13. package/src/babel/util/links.ts +101 -0
  14. package/src/babel/util/reactive-fns.ts +110 -110
  15. package/src/babel/util/runtime-names.ts +88 -0
  16. package/src/babel/util/state-imports.ts +122 -121
  17. package/src/babel/util/static-assertion.ts +51 -51
  18. package/src/babel/util/static-env.ts +84 -0
  19. package/src/vite/index.ts +61 -61
  20. package/test/bun-plugin.test.ts +45 -45
  21. package/test/context.test.ts +110 -102
  22. package/test/fixtures/stores/index.ts +2 -2
  23. package/test/hydration-analysis.test.ts +133 -133
  24. package/test/hydration.test.ts +315 -313
  25. package/test/jsx.test.ts +254 -254
  26. package/test/links.test.ts +57 -0
  27. package/test/reactive-helpers.test.ts +135 -135
  28. package/test/render-parity.test.ts +909 -907
  29. package/test/runtime-names.test.ts +60 -0
  30. package/test/scoped-css.test.ts +166 -166
  31. package/test/ssr-boolean-attrs.test.ts +56 -56
  32. package/test/ssr-raw-text.test.ts +68 -68
  33. package/test/ssr.test.ts +30 -0
  34. package/test/static-assertion.test.ts +123 -123
  35. package/test/static-env.test.ts +85 -0
  36. package/test/static-skip.test.ts +292 -292
  37. package/test/style-object.test.ts +36 -36
  38. package/test/tree-shaking.test.ts +122 -120
@@ -1,1034 +1,1040 @@
1
- import { types as t } from "@babel/core";
2
- //@ts-expect-error Not our problem babel forgot tp export types.
3
- import { generate } from "@babel/generator";
4
- import {
5
- handleGlobalComponent,
6
- isGlobalComponent,
7
- } from "../handlers/dom/globals";
8
- import { STATIC_USES } from "../../analysis/hydration.ts";
9
- import { buildBind, buildProxyBind } from "../util/bind";
10
- import { compileState } from "../util/compile-state.ts";
11
- import { isPropRead } from "../util/props.ts";
12
- import { warn } from "../util/warn.ts";
13
- import { buildAnchorMount } from "./anchor-mount";
14
- import { collectChildren } from "./children";
15
- import { processFragment } from "./fragment";
16
- import { buildKeyedList, findKeyedMapExpr } from "./keyed-list";
17
- import { buildTextNode } from "./text-node";
18
- import {
19
- ATTR_MAP,
20
- buildHydrationScope,
21
- containsSignal,
22
- getCreateElement,
23
- hasJSX,
24
- isPrimitive,
25
- jsxText,
26
- } from "./utils";
27
-
28
- /**
29
- * Dashed names (data-*, aria-*, custom attributes) have no IDL property —
30
- * `el["data-x"] = v` sets a bare JS property the DOM never reflects, so the
31
- * attribute is invisible to selectors, getAttribute, and CSS. They must go
32
- * through setAttribute.
33
- */
34
- function isDashedAttr(attrName: string): boolean {
35
- return attrName.includes("-");
36
- }
37
-
38
- function setAttrCall(
39
- varName: string,
40
- attrName: string,
41
- value: t.Expression,
42
- ): t.CallExpression {
43
- return t.callExpression(
44
- t.memberExpression(t.identifier(varName), t.identifier("setAttribute")),
45
- [t.stringLiteral(attrName), value],
46
- );
47
- }
48
-
49
- /**
50
- * Route a prop write through the runtime setProp() helper. On HTML elements
51
- * this is today's blind `el[name] = value`; on SVG-namespace elements it
52
- * goes through setAttribute instead — IDL property assignment throws on real
53
- * SVG elements (`svg.width = 15` hits a getter-only property), which crashed
54
- * CSR renders the moment claim() started creating true-namespaced SVG.
55
- */
56
- function setPropCall(
57
- varName: string,
58
- attrName: string,
59
- value: t.Expression,
60
- ): t.CallExpression {
61
- return t.callExpression(t.identifier("setProp"), [
62
- t.identifier(varName),
63
- t.stringLiteral(attrName),
64
- value,
65
- ]);
66
- }
67
-
68
- function isClaimedCall(varName: string): t.CallExpression {
69
- return t.callExpression(t.identifier("isClaimed"), [t.identifier(varName)]);
70
- }
71
-
72
- function effect(body: t.Statement[]): t.ExpressionStatement {
73
- return t.expressionStatement(
74
- t.callExpression(t.identifier("createEffect"), [
75
- t.arrowFunctionExpression([], t.blockStatement(body)),
76
- ]),
77
- );
78
- }
79
-
80
- /** Emit fresh-element-only writes; hydration guards them with isClaimed(). */
81
- function pushInit(
82
- varName: string,
83
- init: t.Statement[],
84
- statements: t.Statement[],
85
- hydrate?: boolean,
86
- ): void {
87
- if (!init.length) return;
88
- if (hydrate) {
89
- statements.push(
90
- t.ifStatement(
91
- t.unaryExpression("!", isClaimedCall(varName)),
92
- t.blockStatement(init),
93
- ),
94
- );
95
- } else {
96
- statements.push(...init);
97
- }
98
- }
99
-
100
- /** A <script>'s children as one string expression, or null if it has none. */
101
- function scriptText(node: t.JSXElement): t.Expression | null {
102
- const parts: t.Expression[] = [];
103
- for (const child of node.children) {
104
- if (t.isJSXText(child)) {
105
- const text = jsxText(child);
106
- if (text !== null) parts.push(t.stringLiteral(text));
107
- } else if (
108
- t.isJSXExpressionContainer(child) &&
109
- !t.isJSXEmptyExpression(child.expression)
110
- ) {
111
- parts.push(
112
- t.logicalExpression("??", child.expression, t.stringLiteral("")),
113
- );
114
- }
115
- }
116
- if (!parts.length) return null;
117
- return parts.reduce(
118
- (a, b) => t.binaryExpression("+", a, b),
119
- t.stringLiteral(""),
120
- );
121
- }
122
-
123
- /**
124
- * Build an object property key (identifier for valid names, string literal for dashed).
125
- */
126
- function attrKey(attrName: string): t.Identifier | t.StringLiteral {
127
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName)) {
128
- return t.identifier(attrName);
129
- }
130
- return t.stringLiteral(attrName);
131
- }
132
-
133
- /**
134
- * Add classList.add(hash) statement for scoped CSS.
135
- */
136
- function addScopedClass(
137
- varName: string,
138
- hash: string,
139
- statements: t.Statement[],
140
- ): void {
141
- statements.push(
142
- t.expressionStatement(
143
- t.callExpression(
144
- t.memberExpression(
145
- t.memberExpression(t.identifier(varName), t.identifier("classList")),
146
- t.identifier("add"),
147
- ),
148
- [t.stringLiteral(hash)],
149
- ),
150
- ),
151
- );
152
- }
153
-
154
- export function processElement(
155
- node: t.JSXElement,
156
- statements: t.Statement[],
157
- genId: () => string,
158
- signals: Set<string>,
159
- hash?: string,
160
- hydrate?: boolean,
161
- nodesVar?: string,
162
- parentVar?: string,
163
- ): string {
164
- const varName = genId();
165
- const tag = (node.openingElement.name as t.JSXIdentifier).name;
166
- const isComponent = /^[A-Z]/.test(tag);
167
-
168
- if (isComponent) {
169
- // Global components: Window, Document, Body
170
- if (isGlobalComponent(tag)) {
171
- return handleGlobalComponent(tag, node, statements, genId);
172
- }
173
-
174
- // Component: call the function with a props object
175
- const propsObj = t.objectExpression([]);
176
-
177
- // Add attributes to props (including spread)
178
- for (const attr of node.openingElement.attributes) {
179
- if (t.isJSXSpreadAttribute(attr)) {
180
- // {…obj} — spread into props
181
- propsObj.properties.push(t.spreadElement(attr.argument));
182
- continue;
183
- }
184
- if (!t.isJSXAttribute(attr)) continue;
185
- const attrName = (attr.name as t.JSXIdentifier).name;
186
-
187
- if (attr.value === null) {
188
- // <Comp disabled /> → { disabled: true }
189
- propsObj.properties.push(
190
- t.objectProperty(attrKey(attrName), t.booleanLiteral(true)),
191
- );
192
- } else if (t.isStringLiteral(attr.value)) {
193
- propsObj.properties.push(
194
- t.objectProperty(attrKey(attrName), attr.value),
195
- );
196
- } else if (t.isJSXExpressionContainer(attr.value)) {
197
- const expr = attr.value.expression as t.Expression;
198
- // JSX in a prop (icon={<Icon />}, actions={<>…</>}) belongs
199
- // wherever the component puts it, inside its own root. Built
200
- // now, during hydration, it would claim from the caller's pool
201
- // and could take the component's root element. Defer it like
202
- // children: the component's {prop} slot runs the thunk against
203
- // the right nodes.
204
- if (hydrate && hasJSX(expr)) {
205
- propsObj.properties.push(
206
- t.objectProperty(
207
- attrKey(attrName),
208
- t.arrowFunctionExpression([], expr),
209
- ),
210
- );
211
- } else if (containsSignal(expr, signals)) {
212
- // a prop that reads state is passed as a getter, so the
213
- // component reads the current value wherever it uses it
214
- propsObj.properties.push(
215
- t.objectMethod(
216
- "get",
217
- attrKey(attrName),
218
- [],
219
- t.blockStatement([t.returnStatement(expr)]),
220
- ),
221
- );
222
- } else {
223
- propsObj.properties.push(t.objectProperty(attrKey(attrName), expr));
224
- }
225
- }
226
- }
227
-
228
- // Add children to props
229
- const childrenExpr = collectChildren(
230
- node,
231
- statements,
232
- genId,
233
- signals,
234
- hash,
235
- hydrate,
236
- nodesVar,
237
- );
238
- if (childrenExpr) {
239
- propsObj.properties.push(
240
- t.objectProperty(t.identifier("children"), childrenExpr),
241
- );
242
- }
243
-
244
- // through __component, so the call gets an owner for context
245
- const componentCall = t.callExpression(t.identifier("__component"), [
246
- t.identifier(tag),
247
- propsObj,
248
- ]);
249
-
250
- if (hydrate && nodesVar && STATIC_USES.has(node)) {
251
- // The analysis proved this use produces only HTML, and the server
252
- // fenced it in <!--s-->…<!--/s-->. Cut that run out of the pool and
253
- // never call the component: no claiming, no effects, no listeners.
254
- // With nothing to skip (a client render, an empty pool) skipStatic
255
- // returns null and the component runs as it always did.
256
- statements.push(
257
- t.variableDeclaration("let", [
258
- t.variableDeclarator(
259
- t.identifier(varName),
260
- t.callExpression(t.identifier("skipStatic"), [t.identifier(nodesVar)]),
261
- ),
262
- ]),
263
- );
264
- const render: t.Statement[] = [
265
- t.expressionStatement(
266
- t.callExpression(t.identifier("pushHydrationNodes"), [t.identifier(nodesVar)]),
267
- ),
268
- t.expressionStatement(
269
- t.assignmentExpression("=", t.identifier(varName), componentCall),
270
- ),
271
- t.expressionStatement(
272
- t.callExpression(t.identifier("popHydrationNodes"), []),
273
- ),
274
- ];
275
- if (parentVar) {
276
- render.push(
277
- t.ifStatement(
278
- t.binaryExpression(
279
- "===",
280
- t.memberExpression(t.identifier(nodesVar), t.identifier("length")),
281
- t.numericLiteral(0),
282
- ),
283
- t.expressionStatement(
284
- t.callExpression(t.identifier("insert"), [
285
- t.identifier(parentVar),
286
- t.identifier(varName),
287
- ]),
288
- ),
289
- ),
290
- );
291
- }
292
- // Dev: render the skipped component once, detached, and throw if it was
293
- // not really static. The analysis is conservative, and this is how a
294
- // mistake in it shows up before it reaches production.
295
- const probe = compileState.dev
296
- ? t.blockStatement([
297
- t.expressionStatement(
298
- t.callExpression(t.identifier("probeStatic"), [
299
- t.stringLiteral(tag),
300
- t.arrowFunctionExpression([], t.cloneNode(componentCall, true)),
301
- ]),
302
- ),
303
- ])
304
- : null;
305
- statements.push(
306
- t.ifStatement(
307
- t.unaryExpression("!", t.identifier(varName)),
308
- t.blockStatement(render),
309
- probe,
310
- ),
311
- );
312
- return varName;
313
- }
314
-
315
- if (hydrate && nodesVar) {
316
- // Push the parent's child pool before calling the component so that
317
- // getHydrationNodes() inside the component returns the right scope.
318
- // In SSR hydration the component claims its root node from that pool
319
- // (it's already in the DOM). In empty-pool / SPA mode the component
320
- // creates a fresh node, so we explicitly insert it when the pool is empty.
321
- statements.push(
322
- t.expressionStatement(
323
- t.callExpression(t.identifier("pushHydrationNodes"), [
324
- t.identifier(nodesVar),
325
- ]),
326
- ),
327
- );
328
- statements.push(
329
- t.variableDeclaration("const", [
330
- t.variableDeclarator(t.identifier(varName), componentCall),
331
- ]),
332
- );
333
- statements.push(
334
- t.expressionStatement(
335
- t.callExpression(t.identifier("popHydrationNodes"), []),
336
- ),
337
- );
338
- if (parentVar) {
339
- // Insert only when the pool was empty (fresh DOM); if the pool had
340
- // nodes the component already claimed its SSR element (already in DOM).
341
- statements.push(
342
- t.ifStatement(
343
- t.binaryExpression(
344
- "===",
345
- t.memberExpression(
346
- t.identifier(nodesVar),
347
- t.identifier("length"),
348
- ),
349
- t.numericLiteral(0),
350
- ),
351
- t.expressionStatement(
352
- t.callExpression(t.identifier("insert"), [
353
- t.identifier(parentVar),
354
- t.identifier(varName),
355
- ]),
356
- ),
357
- ),
358
- );
359
- }
360
- } else {
361
- statements.push(
362
- t.variableDeclaration("const", [
363
- t.variableDeclarator(t.identifier(varName), componentCall),
364
- ]),
365
- );
366
- }
367
-
368
- return varName;
369
- }
370
-
371
- // Native element: claim (hydrate) or create (dom)
372
- const currentNodesVar = nodesVar ?? "__nodes";
373
- statements.push(
374
- t.variableDeclaration("const", [
375
- t.variableDeclarator(
376
- t.identifier(varName),
377
- getCreateElement(
378
- tag,
379
- !!hydrate,
380
- currentNodesVar,
381
- hydrate ? parentVar : undefined,
382
- ),
383
- ),
384
- ]),
385
- );
386
-
387
- // In hydrate mode, scope to this element's children for descendants
388
- let childNodesVar: string | undefined;
389
- if (hydrate) {
390
- childNodesVar = genId();
391
- buildHydrationScope(varName, statements, childNodesVar);
392
- }
393
-
394
- // Attribute writes that only matter on a fresh element. When hydration
395
- // claims server HTML they already happened there, and redoing them would
396
- // wipe whatever a page script changed in the meantime.
397
- const init: t.Statement[] = [];
398
- // <select value> needs its options to exist first.
399
- const initAfter: t.Statement[] = [];
400
- const liveAfter: t.Statement[] = [];
401
-
402
- // attributes
403
- const seenAttrs = new Set<string>();
404
- for (const attr of node.openingElement.attributes) {
405
- if (t.isJSXSpreadAttribute(attr)) {
406
- // {…obj}: listeners always, attributes unless hydration claimed
407
- // the element (then the server already rendered them)
408
- const args: t.Expression[] = [t.identifier(varName), attr.argument];
409
- if (hydrate) args.push(t.unaryExpression("!", isClaimedCall(varName)));
410
- statements.push(
411
- t.expressionStatement(t.callExpression(t.identifier("spread"), args)),
412
- );
413
- continue;
414
- }
415
- if (!t.isJSXAttribute(attr)) continue;
416
- let attrName: string;
417
- let attrNamespace: string | undefined;
418
- if (t.isJSXNamespacedName(attr.name)) {
419
- attrNamespace = attr.name.namespace.name;
420
- attrName = attr.name.name.name;
421
- } else {
422
- attrName = (attr.name as t.JSXIdentifier).name;
423
- // bindValue -> bind:value, bindChecked -> bind:checked
424
- if (/^bind[A-Z]/.test(attrName)) {
425
- attrNamespace = "bind";
426
- // bindScrollTop -> bind:scrollTop: only the first letter lowers
427
- attrName = attrName.charAt(4).toLowerCase() + attrName.slice(5);
428
- }
429
- }
430
- const realAttr = ATTR_MAP[attrName] ?? attrName;
431
-
432
- if (seenAttrs.has(realAttr)) {
433
- throw new TypeError(
434
- `Duplicate attribute "${realAttr}" (via "${attrName}"). Use class or className, not both.`,
435
- );
436
- }
437
- seenAttrs.add(realAttr);
438
- if (
439
- (attrNamespace === "transition" ||
440
- attrNamespace === "in" ||
441
- attrNamespace === "out") &&
442
- t.isJSXExpressionContainer(attr.value)
443
- ) {
444
- // transition:fade={fade} / in:appear={x} / out:leave={[y, params]}
445
- const expr = attr.value.expression as t.Expression;
446
- statements.push(
447
- t.expressionStatement(
448
- t.callExpression(t.identifier("mountTransition"), [
449
- t.identifier(varName),
450
- expr,
451
- t.stringLiteral(attrNamespace as "transition" | "in" | "out"),
452
- ]),
453
- ),
454
- );
455
- } else if (attrName === "use") {
456
- // use={directive} or use={[directive, params]}
457
- const expr = (attr.value as t.JSXExpressionContainer)
458
- .expression as t.Expression;
459
- statements.push(
460
- t.expressionStatement(
461
- t.callExpression(t.identifier("applyDirective"), [
462
- t.identifier(varName),
463
- expr,
464
- ]),
465
- ),
466
- );
467
- } else if (/^on[A-Z]/.test(attrName)) {
468
- // Standard JSX: onClick, onSubmit, onMouseenter, etc.
469
- // Convert camelCase to lowercase: onClick -> click, onMouseenter -> mouseenter
470
- const event = attrName.slice(2).toLowerCase();
471
- const handler = (attr.value as t.JSXExpressionContainer)
472
- .expression as t.Expression;
473
- statements.push(
474
- t.expressionStatement(
475
- t.callExpression(
476
- t.memberExpression(
477
- t.identifier(varName),
478
- t.identifier("addEventListener"),
479
- ),
480
- [t.stringLiteral(event), handler],
481
- ),
482
- ),
483
- );
484
- } else if (attrNamespace === "bind") {
485
- const bindProp = attrName;
486
- const signal = (attr.value as t.JSXExpressionContainer)
487
- .expression as t.Expression;
488
-
489
- if (bindProp === "this") {
490
- statements.push(
491
- t.expressionStatement(
492
- t.callExpression(
493
- t.memberExpression(
494
- (signal as t.CallExpression).callee as t.Expression,
495
- t.identifier("set"),
496
- ),
497
- [t.identifier(varName)],
498
- ),
499
- ),
500
- );
501
- continue;
502
- }
503
-
504
- if (bindProp === "group") {
505
- // Scan element attributes for type and value
506
- let inputType = "";
507
- let _inputValue: t.StringLiteral | undefined;
508
- for (const a of node.openingElement.attributes) {
509
- if (t.isJSXAttribute(a) && t.isJSXIdentifier(a.name)) {
510
- if (a.name.name === "type" && t.isStringLiteral(a.value)) {
511
- inputType = a.value.value;
512
- }
513
- if (a.name.name === "value" && t.isStringLiteral(a.value)) {
514
- _inputValue = a.value;
515
- }
516
- }
517
- }
518
-
519
- if (inputType === "radio" || inputType === "") {
520
- const isTopLevel =
521
- t.isCallExpression(signal) &&
522
- t.isIdentifier((signal as t.CallExpression).callee) &&
523
- signals.has(
524
- ((signal as t.CallExpression).callee as t.Identifier).name,
525
- );
526
-
527
- if (isTopLevel) {
528
- const signalId = (signal as t.CallExpression)
529
- .callee as t.Identifier;
530
- statements.push(
531
- t.expressionStatement(
532
- t.callExpression(
533
- t.memberExpression(
534
- t.identifier(varName),
535
- t.identifier("addEventListener"),
536
- ),
537
- [
538
- t.stringLiteral("change"),
539
- t.arrowFunctionExpression(
540
- [],
541
- t.callExpression(
542
- t.memberExpression(signalId, t.identifier("set")),
543
- [
544
- t.memberExpression(
545
- t.identifier(varName),
546
- t.identifier("value"),
547
- ),
548
- ],
549
- ),
550
- ),
551
- ],
552
- ),
553
- ),
554
- );
555
- }
556
- } else if (inputType === "checkbox") {
557
- const isTopLevel =
558
- t.isCallExpression(signal) &&
559
- t.isIdentifier((signal as t.CallExpression).callee) &&
560
- signals.has(
561
- ((signal as t.CallExpression).callee as t.Identifier).name,
562
- );
563
-
564
- if (isTopLevel) {
565
- const callExpr = signal as t.CallExpression;
566
- statements.push(
567
- t.expressionStatement(
568
- t.callExpression(
569
- t.memberExpression(
570
- t.identifier(varName),
571
- t.identifier("addEventListener"),
572
- ),
573
- [
574
- t.stringLiteral("change"),
575
- t.arrowFunctionExpression(
576
- [],
577
- t.blockStatement([
578
- t.ifStatement(
579
- t.memberExpression(
580
- t.identifier(varName),
581
- t.identifier("checked"),
582
- ),
583
- // checked: push value into array
584
- t.blockStatement([
585
- t.expressionStatement(
586
- t.callExpression(
587
- t.memberExpression(
588
- t.callExpression(callExpr, []),
589
- t.identifier("push"),
590
- ),
591
- [
592
- t.memberExpression(
593
- t.identifier(varName),
594
- t.identifier("value"),
595
- ),
596
- ],
597
- ),
598
- ),
599
- ]),
600
- // unchecked: splice value out of array
601
- t.blockStatement([
602
- t.expressionStatement(
603
- t.callExpression(
604
- t.memberExpression(
605
- t.callExpression(callExpr, []),
606
- t.identifier("splice"),
607
- ),
608
- [
609
- t.callExpression(
610
- t.memberExpression(
611
- t.callExpression(callExpr, []),
612
- t.identifier("indexOf"),
613
- ),
614
- [
615
- t.memberExpression(
616
- t.identifier(varName),
617
- t.identifier("value"),
618
- ),
619
- ],
620
- ),
621
- t.numericLiteral(1),
622
- ],
623
- ),
624
- ),
625
- ]),
626
- ),
627
- ]),
628
- ),
629
- ],
630
- ),
631
- ),
632
- );
633
- }
634
- } else {
635
- warn(
636
- attr,
637
- `bind:group requires type="radio" or type="checkbox" on the element. ` +
638
- `Got: type="${inputType}".`,
639
- );
640
- }
641
- continue;
642
- }
643
-
644
- // Generic bind:innerHTML, bind:textContent, bind:value, bind:checked, etc.
645
- const isTopLevelSignal =
646
- t.isCallExpression(signal) &&
647
- t.isIdentifier((signal as t.CallExpression).callee) &&
648
- signals.has(((signal as t.CallExpression).callee as t.Identifier).name);
649
-
650
- const isMemberOfSignal =
651
- t.isMemberExpression(signal) &&
652
- t.isCallExpression((signal as t.MemberExpression).object) &&
653
- t.isIdentifier(
654
- ((signal as t.MemberExpression).object as t.CallExpression).callee,
655
- ) &&
656
- signals.has(
657
- (
658
- ((signal as t.MemberExpression).object as t.CallExpression)
659
- .callee as t.Identifier
660
- ).name,
661
- );
662
-
663
- // bind:checked={item.done} in a list row, or {book.read} where `book`
664
- // is a prop: the chain is rooted at a row item or a props object,
665
- // and what it ends in is a property of a $state proxy
666
- let root: t.Node = signal;
667
- while (t.isMemberExpression(root)) root = root.object;
668
- const isMemberOfItem =
669
- t.isMemberExpression(signal) &&
670
- t.isIdentifier(root) &&
671
- signals.has(root.name);
672
-
673
- if (isTopLevelSignal) {
674
- buildBind(varName, bindProp, attr, statements);
675
- } else if (isMemberOfSignal || isMemberOfItem) {
676
- buildProxyBind(varName, bindProp, attr, statements, signal);
677
- } else {
678
- warn(
679
- attr,
680
- `bind:${bindProp}={...} requires a $state signal or $state object property. ` +
681
- `Got: ${generate(signal).code}. ` +
682
- `Hint: change to a $state() call.`,
683
- );
684
- }
685
- } else if (attr.value === null) {
686
- // bare attribute (<input disabled>, <div data-beacon>)
687
- init.push(
688
- t.expressionStatement(
689
- isDashedAttr(realAttr)
690
- ? setAttrCall(varName, realAttr, t.stringLiteral(""))
691
- : setPropCall(varName, realAttr, t.booleanLiteral(true)),
692
- ),
693
- );
694
- } else if (t.isStringLiteral(attr.value)) {
695
- const stmt = t.expressionStatement(
696
- setPropCall(varName, realAttr, t.stringLiteral(attr.value.value)),
697
- );
698
- (tag === "select" && realAttr === "value" ? initAfter : init).push(stmt);
699
- } else if (t.isJSXExpressionContainer(attr.value)) {
700
- const expr = attr.value.expression as t.Expression;
701
- const afterChildren = tag === "select" && realAttr === "value";
702
- // style={{ color: "red", fontSize: val }} — per-property writes
703
- if (attrName === "style" && t.isObjectExpression(expr)) {
704
- for (const prop of expr.properties) {
705
- if (!t.isObjectProperty(prop)) continue;
706
- const key = t.isIdentifier(prop.key)
707
- ? prop.key.name
708
- : t.isStringLiteral(prop.key)
709
- ? prop.key.value
710
- : null;
711
- if (!key) continue;
712
- const val = prop.value as t.Expression;
713
- const write = t.expressionStatement(
714
- t.callExpression(t.identifier("setStyleProp"), [
715
- t.identifier(varName),
716
- t.stringLiteral(key),
717
- val,
718
- ]),
719
- );
720
- if (containsSignal(val, signals)) {
721
- statements.push(effect([write]));
722
- } else {
723
- init.push(write);
724
- }
725
- }
726
- } else if (containsSignal(expr, signals)) {
727
- // Dynamic class with scoped CSS: use classList.value to preserve hash
728
- if (attrName === "class" && hash) {
729
- statements.push(
730
- effect([
731
- t.expressionStatement(
732
- t.assignmentExpression(
733
- "=",
734
- t.memberExpression(
735
- t.memberExpression(
736
- t.identifier(varName),
737
- t.identifier("classList"),
738
- ),
739
- t.identifier("value"),
740
- ),
741
- expr,
742
- ),
743
- ),
744
- t.expressionStatement(
745
- t.callExpression(
746
- t.memberExpression(
747
- t.memberExpression(
748
- t.identifier(varName),
749
- t.identifier("classList"),
750
- ),
751
- t.identifier("add"),
752
- ),
753
- [t.stringLiteral(hash)],
754
- ),
755
- ),
756
- ]),
757
- );
758
- } else {
759
- const stmt = effect([
760
- t.expressionStatement(setPropCall(varName, realAttr, expr)),
761
- ]);
762
- (afterChildren ? liveAfter : statements).push(stmt);
763
- }
764
- } else {
765
- const stmt = t.expressionStatement(
766
- setPropCall(varName, realAttr, expr),
767
- );
768
- (afterChildren ? initAfter : init).push(stmt);
769
- }
770
- }
771
- }
772
-
773
- pushInit(varName, init, statements, hydrate);
774
-
775
- // Add scoped CSS hash to classList (if hash is present)
776
- if (hash) {
777
- addScopedClass(varName, hash, statements);
778
- }
779
-
780
- // children. <script> text is already in the server HTML, raw and unmarked
781
- // (see ssr.ts), so hydration has nothing to claim there: the marker search
782
- // would miss and append a second copy of the code.
783
- if (hydrate && tag === "script") {
784
- // ...but SPA navigation creates the element fresh and needs the text.
785
- const text = scriptText(node);
786
- if (text) {
787
- const write = [
788
- t.expressionStatement(
789
- t.assignmentExpression(
790
- "=",
791
- t.memberExpression(
792
- t.identifier(varName),
793
- t.identifier("textContent"),
794
- ),
795
- text,
796
- ),
797
- ),
798
- ];
799
- pushInit(varName, write, statements, hydrate);
800
- }
801
- }
802
- for (const child of hydrate && tag === "script" ? [] : node.children) {
803
- if (t.isJSXElement(child)) {
804
- const childVar = processElement(
805
- child,
806
- statements,
807
- genId,
808
- signals,
809
- hash,
810
- hydrate,
811
- childNodesVar,
812
- hydrate ? varName : undefined,
813
- );
814
- if (!hydrate) {
815
- statements.push(
816
- t.expressionStatement(
817
- t.callExpression(
818
- t.memberExpression(t.identifier(varName), t.identifier("append")),
819
- [t.identifier(childVar)],
820
- ),
821
- ),
822
- );
823
- }
824
- } else if (t.isJSXFragment(child)) {
825
- const childVar = processFragment(
826
- child,
827
- statements,
828
- genId,
829
- signals,
830
- hash,
831
- hydrate,
832
- childNodesVar,
833
- hydrate ? varName : undefined,
834
- );
835
- if (!hydrate) {
836
- statements.push(
837
- t.expressionStatement(
838
- t.callExpression(
839
- t.memberExpression(t.identifier(varName), t.identifier("append")),
840
- [t.identifier(childVar)],
841
- ),
842
- ),
843
- );
844
- }
845
- } else if (t.isJSXText(child)) {
846
- const text = jsxText(child, node.children);
847
- if (text === null) continue;
848
- if (hydrate) {
849
- // SSR hydration: text already in DOM from SSR, do nothing.
850
- // SPA navigation: childNodesVar pool is empty, create text node.
851
- const poolLen = t.memberExpression(
852
- t.identifier(childNodesVar!),
853
- t.identifier("length"),
854
- );
855
- statements.push(
856
- t.ifStatement(
857
- t.binaryExpression("===", poolLen, t.numericLiteral(0)),
858
- t.expressionStatement(
859
- t.callExpression(
860
- t.memberExpression(
861
- t.identifier(varName),
862
- t.identifier("append"),
863
- ),
864
- [
865
- t.callExpression(
866
- t.memberExpression(
867
- t.identifier("document"),
868
- t.identifier("createTextNode"),
869
- ),
870
- [t.stringLiteral(text)],
871
- ),
872
- ],
873
- ),
874
- ),
875
- ),
876
- );
877
- } else {
878
- statements.push(
879
- t.expressionStatement(
880
- t.callExpression(
881
- t.memberExpression(t.identifier(varName), t.identifier("append")),
882
- [
883
- t.callExpression(
884
- t.memberExpression(
885
- t.identifier("document"),
886
- t.identifier("createTextNode"),
887
- ),
888
- [t.stringLiteral(text)],
889
- ),
890
- ],
891
- ),
892
- ),
893
- );
894
- }
895
- } else if (t.isJSXExpressionContainer(child)) {
896
- if (t.isJSXEmptyExpression(child.expression)) continue;
897
- const expr = child.expression as t.Expression;
898
- if (t.isJSXElement(expr)) {
899
- const childVar = processElement(
900
- expr,
901
- statements,
902
- genId,
903
- signals,
904
- hash,
905
- hydrate,
906
- childNodesVar,
907
- hydrate ? varName : undefined,
908
- );
909
- if (!hydrate) {
910
- statements.push(
911
- t.expressionStatement(
912
- t.callExpression(
913
- t.memberExpression(
914
- t.identifier(varName),
915
- t.identifier("append"),
916
- ),
917
- [t.identifier(childVar)],
918
- ),
919
- ),
920
- );
921
- }
922
- } else if (t.isJSXFragment(expr)) {
923
- const childVar = processFragment(
924
- expr,
925
- statements,
926
- genId,
927
- signals,
928
- hash,
929
- hydrate,
930
- childNodesVar,
931
- hydrate ? varName : undefined,
932
- );
933
- if (!hydrate) {
934
- statements.push(
935
- t.expressionStatement(
936
- t.callExpression(
937
- t.memberExpression(
938
- t.identifier(varName),
939
- t.identifier("append"),
940
- ),
941
- [t.identifier(childVar)],
942
- ),
943
- ),
944
- );
945
- }
946
- } else if (isPropRead(expr)) {
947
- // a prop may hold text, nodes or a deferred child, and may be a
948
- // getter over state: a live slot handles all of them
949
- statements.push(
950
- t.expressionStatement(
951
- t.callExpression(t.identifier("liveSlot"), [
952
- hydrate ? t.identifier(childNodesVar!) : t.arrayExpression([]),
953
- t.identifier(varName),
954
- t.arrowFunctionExpression([], expr),
955
- ]),
956
- ),
957
- );
958
- } else if (containsSignal(expr, signals)) {
959
- if (isPrimitive(expr)) {
960
- // fast path: text node + textContent
961
- buildTextNode(
962
- varName,
963
- expr,
964
- statements,
965
- genId,
966
- hydrate,
967
- childNodesVar,
968
- hydrate ? varName : undefined,
969
- );
970
- } else {
971
- // Check for keyed list pattern
972
- const keyed = findKeyedMapExpr(expr, signals);
973
- if (keyed) {
974
- buildKeyedList(
975
- varName,
976
- keyed,
977
- statements,
978
- genId,
979
- signals,
980
- processElement,
981
- hash,
982
- hydrate,
983
- childNodesVar,
984
- hydrate ? varName : undefined,
985
- );
986
- } else {
987
- buildAnchorMount(
988
- varName,
989
- expr,
990
- statements,
991
- genId,
992
- hydrate,
993
- childNodesVar,
994
- hydrate ? varName : undefined,
995
- );
996
- }
997
- }
998
- } else {
999
- // non-reactive: set once
1000
- if (hydrate) {
1001
- // hydrateSlot consumes the <!--g-->…<!--/g--> run and runs the
1002
- // value against the content SSR put inside it, so both deferred
1003
- // component children and inline JSX (`{list.map(…)}`) claim that
1004
- // subtree. The value must stay lazy: evaluating it as an argument
1005
- // would claim from the enclosing pool instead. Empty pool
1006
- // (SPA nav) falls back to a fresh insert.
1007
- statements.push(
1008
- t.expressionStatement(
1009
- t.callExpression(t.identifier("hydrateSlot"), [
1010
- t.identifier(childNodesVar!),
1011
- t.identifier(varName),
1012
- t.arrowFunctionExpression([], expr),
1013
- ]),
1014
- ),
1015
- );
1016
- } else {
1017
- statements.push(
1018
- t.expressionStatement(
1019
- t.callExpression(t.identifier("insert"), [
1020
- t.identifier(varName),
1021
- expr,
1022
- ]),
1023
- ),
1024
- );
1025
- }
1026
- }
1027
- }
1028
- }
1029
-
1030
- pushInit(varName, initAfter, statements, hydrate);
1031
- statements.push(...liveAfter);
1032
-
1033
- return varName;
1034
- }
1
+ import { types as t } from "@babel/core";
2
+ import { generate } from "@babel/generator";
3
+ import { STATIC_USES } from "../../analysis/hydration.ts";
4
+ import {
5
+ handleGlobalComponent,
6
+ isGlobalComponent,
7
+ } from "../handlers/dom/globals";
8
+ import { buildBind, buildProxyBind } from "../util/bind";
9
+ import { compileState } from "../util/compile-state.ts";
10
+ import { isPropRead } from "../util/props.ts";
11
+ import { warn } from "../util/warn.ts";
12
+ import { buildAnchorMount } from "./anchor-mount";
13
+ import { collectChildren } from "./children";
14
+ import { processFragment } from "./fragment";
15
+ import { buildKeyedList, findKeyedMapExpr } from "./keyed-list";
16
+ import { buildTextNode } from "./text-node";
17
+ import {
18
+ ATTR_MAP,
19
+ buildHydrationScope,
20
+ containsSignal,
21
+ getCreateElement,
22
+ hasJSX,
23
+ isPrimitive,
24
+ jsxText,
25
+ } from "./utils";
26
+
27
+ /**
28
+ * Dashed names (data-*, aria-*, custom attributes) have no IDL property —
29
+ * `el["data-x"] = v` sets a bare JS property the DOM never reflects, so the
30
+ * attribute is invisible to selectors, getAttribute, and CSS. They must go
31
+ * through setAttribute.
32
+ */
33
+ function isDashedAttr(attrName: string): boolean {
34
+ return attrName.includes("-");
35
+ }
36
+
37
+ function setAttrCall(
38
+ varName: string,
39
+ attrName: string,
40
+ value: t.Expression,
41
+ ): t.CallExpression {
42
+ return t.callExpression(
43
+ t.memberExpression(t.identifier(varName), t.identifier("setAttribute")),
44
+ [t.stringLiteral(attrName), value],
45
+ );
46
+ }
47
+
48
+ /**
49
+ * Route a prop write through the runtime setProp() helper. On HTML elements
50
+ * this is today's blind `el[name] = value`; on SVG-namespace elements it
51
+ * goes through setAttribute instead — IDL property assignment throws on real
52
+ * SVG elements (`svg.width = 15` hits a getter-only property), which crashed
53
+ * CSR renders the moment claim() started creating true-namespaced SVG.
54
+ */
55
+ function setPropCall(
56
+ varName: string,
57
+ attrName: string,
58
+ value: t.Expression,
59
+ ): t.CallExpression {
60
+ return t.callExpression(t.identifier("setProp"), [
61
+ t.identifier(varName),
62
+ t.stringLiteral(attrName),
63
+ value,
64
+ ]);
65
+ }
66
+
67
+ function isClaimedCall(varName: string): t.CallExpression {
68
+ return t.callExpression(t.identifier("isClaimed"), [t.identifier(varName)]);
69
+ }
70
+
71
+ function effect(body: t.Statement[]): t.ExpressionStatement {
72
+ return t.expressionStatement(
73
+ t.callExpression(t.identifier("createEffect"), [
74
+ t.arrowFunctionExpression([], t.blockStatement(body)),
75
+ ]),
76
+ );
77
+ }
78
+
79
+ /** Emit fresh-element-only writes; hydration guards them with isClaimed(). */
80
+ function pushInit(
81
+ varName: string,
82
+ init: t.Statement[],
83
+ statements: t.Statement[],
84
+ hydrate?: boolean,
85
+ ): void {
86
+ if (!init.length) return;
87
+ if (hydrate) {
88
+ statements.push(
89
+ t.ifStatement(
90
+ t.unaryExpression("!", isClaimedCall(varName)),
91
+ t.blockStatement(init),
92
+ ),
93
+ );
94
+ } else {
95
+ statements.push(...init);
96
+ }
97
+ }
98
+
99
+ /** A <script>'s children as one string expression, or null if it has none. */
100
+ function scriptText(node: t.JSXElement): t.Expression | null {
101
+ const parts: t.Expression[] = [];
102
+ for (const child of node.children) {
103
+ if (t.isJSXText(child)) {
104
+ const text = jsxText(child);
105
+ if (text !== null) parts.push(t.stringLiteral(text));
106
+ } else if (
107
+ t.isJSXExpressionContainer(child) &&
108
+ !t.isJSXEmptyExpression(child.expression)
109
+ ) {
110
+ parts.push(
111
+ t.logicalExpression("??", child.expression, t.stringLiteral("")),
112
+ );
113
+ }
114
+ }
115
+ if (!parts.length) return null;
116
+ return parts.reduce(
117
+ (a, b) => t.binaryExpression("+", a, b),
118
+ t.stringLiteral(""),
119
+ );
120
+ }
121
+
122
+ /**
123
+ * Build an object property key (identifier for valid names, string literal for dashed).
124
+ */
125
+ function attrKey(attrName: string): t.Identifier | t.StringLiteral {
126
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName)) {
127
+ return t.identifier(attrName);
128
+ }
129
+ return t.stringLiteral(attrName);
130
+ }
131
+
132
+ /**
133
+ * Add classList.add(hash) statement for scoped CSS.
134
+ */
135
+ function addScopedClass(
136
+ varName: string,
137
+ hash: string,
138
+ statements: t.Statement[],
139
+ ): void {
140
+ statements.push(
141
+ t.expressionStatement(
142
+ t.callExpression(
143
+ t.memberExpression(
144
+ t.memberExpression(t.identifier(varName), t.identifier("classList")),
145
+ t.identifier("add"),
146
+ ),
147
+ [t.stringLiteral(hash)],
148
+ ),
149
+ ),
150
+ );
151
+ }
152
+
153
+ export function processElement(
154
+ node: t.JSXElement,
155
+ statements: t.Statement[],
156
+ genId: () => string,
157
+ signals: Set<string>,
158
+ hash?: string,
159
+ hydrate?: boolean,
160
+ nodesVar?: string,
161
+ parentVar?: string,
162
+ ): string {
163
+ const varName = genId();
164
+ const tag = (node.openingElement.name as t.JSXIdentifier).name;
165
+ const isComponent = /^[A-Z]/.test(tag);
166
+
167
+ if (isComponent) {
168
+ // Global components: Window, Document, Body
169
+ if (isGlobalComponent(tag)) {
170
+ return handleGlobalComponent(tag, node, statements, genId);
171
+ }
172
+
173
+ // Component: call the function with a props object
174
+ const propsObj = t.objectExpression([]);
175
+
176
+ // Add attributes to props (including spread)
177
+ for (const attr of node.openingElement.attributes) {
178
+ if (t.isJSXSpreadAttribute(attr)) {
179
+ // {…obj} — spread into props
180
+ propsObj.properties.push(t.spreadElement(attr.argument));
181
+ continue;
182
+ }
183
+ if (!t.isJSXAttribute(attr)) continue;
184
+ const attrName = (attr.name as t.JSXIdentifier).name;
185
+
186
+ if (attr.value === null) {
187
+ // <Comp disabled /> → { disabled: true }
188
+ propsObj.properties.push(
189
+ t.objectProperty(attrKey(attrName), t.booleanLiteral(true)),
190
+ );
191
+ } else if (t.isStringLiteral(attr.value)) {
192
+ propsObj.properties.push(
193
+ t.objectProperty(attrKey(attrName), attr.value),
194
+ );
195
+ } else if (t.isJSXExpressionContainer(attr.value)) {
196
+ const expr = attr.value.expression as t.Expression;
197
+ // JSX in a prop (icon={<Icon />}, actions={<>…</>}) belongs
198
+ // wherever the component puts it, inside its own root. Built
199
+ // now, during hydration, it would claim from the caller's pool
200
+ // and could take the component's root element. Defer it like
201
+ // children: the component's {prop} slot runs the thunk against
202
+ // the right nodes.
203
+ if (hydrate && hasJSX(expr)) {
204
+ propsObj.properties.push(
205
+ t.objectProperty(
206
+ attrKey(attrName),
207
+ t.arrowFunctionExpression([], expr),
208
+ ),
209
+ );
210
+ } else if (containsSignal(expr, signals)) {
211
+ // a prop that reads state is passed as a getter, so the
212
+ // component reads the current value wherever it uses it
213
+ propsObj.properties.push(
214
+ t.objectMethod(
215
+ "get",
216
+ attrKey(attrName),
217
+ [],
218
+ t.blockStatement([t.returnStatement(expr)]),
219
+ ),
220
+ );
221
+ } else {
222
+ propsObj.properties.push(t.objectProperty(attrKey(attrName), expr));
223
+ }
224
+ }
225
+ }
226
+
227
+ // Add children to props
228
+ const childrenExpr = collectChildren(
229
+ node,
230
+ statements,
231
+ genId,
232
+ signals,
233
+ hash,
234
+ hydrate,
235
+ nodesVar,
236
+ );
237
+ if (childrenExpr) {
238
+ propsObj.properties.push(
239
+ t.objectProperty(t.identifier("children"), childrenExpr),
240
+ );
241
+ }
242
+
243
+ // through __component, so the call gets an owner for context
244
+ const componentCall = t.callExpression(t.identifier("__component"), [
245
+ t.identifier(tag),
246
+ propsObj,
247
+ ]);
248
+
249
+ if (hydrate && nodesVar && STATIC_USES.has(node)) {
250
+ // The analysis proved this use produces only HTML, and the server
251
+ // fenced it in <!--s-->…<!--/s-->. Cut that run out of the pool and
252
+ // never call the component: no claiming, no effects, no listeners.
253
+ // With nothing to skip (a client render, an empty pool) skipStatic
254
+ // returns null and the component runs as it always did.
255
+ statements.push(
256
+ t.variableDeclaration("let", [
257
+ t.variableDeclarator(
258
+ t.identifier(varName),
259
+ t.callExpression(t.identifier("skipStatic"), [
260
+ t.identifier(nodesVar),
261
+ ]),
262
+ ),
263
+ ]),
264
+ );
265
+ const render: t.Statement[] = [
266
+ t.expressionStatement(
267
+ t.callExpression(t.identifier("pushHydrationNodes"), [
268
+ t.identifier(nodesVar),
269
+ ]),
270
+ ),
271
+ t.expressionStatement(
272
+ t.assignmentExpression("=", t.identifier(varName), componentCall),
273
+ ),
274
+ t.expressionStatement(
275
+ t.callExpression(t.identifier("popHydrationNodes"), []),
276
+ ),
277
+ ];
278
+ if (parentVar) {
279
+ render.push(
280
+ t.ifStatement(
281
+ t.binaryExpression(
282
+ "===",
283
+ t.memberExpression(
284
+ t.identifier(nodesVar),
285
+ t.identifier("length"),
286
+ ),
287
+ t.numericLiteral(0),
288
+ ),
289
+ t.expressionStatement(
290
+ t.callExpression(t.identifier("insert"), [
291
+ t.identifier(parentVar),
292
+ t.identifier(varName),
293
+ ]),
294
+ ),
295
+ ),
296
+ );
297
+ }
298
+ // Dev: render the skipped component once, detached, and throw if it was
299
+ // not really static. The analysis is conservative, and this is how a
300
+ // mistake in it shows up before it reaches production.
301
+ const probe = compileState.dev
302
+ ? t.blockStatement([
303
+ t.expressionStatement(
304
+ t.callExpression(t.identifier("probeStatic"), [
305
+ t.stringLiteral(tag),
306
+ t.arrowFunctionExpression([], t.cloneNode(componentCall, true)),
307
+ ]),
308
+ ),
309
+ ])
310
+ : null;
311
+ statements.push(
312
+ t.ifStatement(
313
+ t.unaryExpression("!", t.identifier(varName)),
314
+ t.blockStatement(render),
315
+ probe,
316
+ ),
317
+ );
318
+ return varName;
319
+ }
320
+
321
+ if (hydrate && nodesVar) {
322
+ // Push the parent's child pool before calling the component so that
323
+ // getHydrationNodes() inside the component returns the right scope.
324
+ // In SSR hydration the component claims its root node from that pool
325
+ // (it's already in the DOM). In empty-pool / SPA mode the component
326
+ // creates a fresh node, so we explicitly insert it when the pool is empty.
327
+ statements.push(
328
+ t.expressionStatement(
329
+ t.callExpression(t.identifier("pushHydrationNodes"), [
330
+ t.identifier(nodesVar),
331
+ ]),
332
+ ),
333
+ );
334
+ statements.push(
335
+ t.variableDeclaration("const", [
336
+ t.variableDeclarator(t.identifier(varName), componentCall),
337
+ ]),
338
+ );
339
+ statements.push(
340
+ t.expressionStatement(
341
+ t.callExpression(t.identifier("popHydrationNodes"), []),
342
+ ),
343
+ );
344
+ if (parentVar) {
345
+ // Insert only when the pool was empty (fresh DOM); if the pool had
346
+ // nodes the component already claimed its SSR element (already in DOM).
347
+ statements.push(
348
+ t.ifStatement(
349
+ t.binaryExpression(
350
+ "===",
351
+ t.memberExpression(
352
+ t.identifier(nodesVar),
353
+ t.identifier("length"),
354
+ ),
355
+ t.numericLiteral(0),
356
+ ),
357
+ t.expressionStatement(
358
+ t.callExpression(t.identifier("insert"), [
359
+ t.identifier(parentVar),
360
+ t.identifier(varName),
361
+ ]),
362
+ ),
363
+ ),
364
+ );
365
+ }
366
+ } else {
367
+ statements.push(
368
+ t.variableDeclaration("const", [
369
+ t.variableDeclarator(t.identifier(varName), componentCall),
370
+ ]),
371
+ );
372
+ }
373
+
374
+ return varName;
375
+ }
376
+
377
+ // Native element: claim (hydrate) or create (dom)
378
+ const currentNodesVar = nodesVar ?? "__nodes";
379
+ statements.push(
380
+ t.variableDeclaration("const", [
381
+ t.variableDeclarator(
382
+ t.identifier(varName),
383
+ getCreateElement(
384
+ tag,
385
+ !!hydrate,
386
+ currentNodesVar,
387
+ hydrate ? parentVar : undefined,
388
+ ),
389
+ ),
390
+ ]),
391
+ );
392
+
393
+ // In hydrate mode, scope to this element's children for descendants
394
+ let childNodesVar: string | undefined;
395
+ if (hydrate) {
396
+ childNodesVar = genId();
397
+ buildHydrationScope(varName, statements, childNodesVar);
398
+ }
399
+
400
+ // Attribute writes that only matter on a fresh element. When hydration
401
+ // claims server HTML they already happened there, and redoing them would
402
+ // wipe whatever a page script changed in the meantime.
403
+ const init: t.Statement[] = [];
404
+ // <select value> needs its options to exist first.
405
+ const initAfter: t.Statement[] = [];
406
+ const liveAfter: t.Statement[] = [];
407
+
408
+ // attributes
409
+ const seenAttrs = new Set<string>();
410
+ for (const attr of node.openingElement.attributes) {
411
+ if (t.isJSXSpreadAttribute(attr)) {
412
+ // {…obj}: listeners always, attributes unless hydration claimed
413
+ // the element (then the server already rendered them)
414
+ const args: t.Expression[] = [t.identifier(varName), attr.argument];
415
+ if (hydrate) args.push(t.unaryExpression("!", isClaimedCall(varName)));
416
+ statements.push(
417
+ t.expressionStatement(t.callExpression(t.identifier("spread"), args)),
418
+ );
419
+ continue;
420
+ }
421
+ if (!t.isJSXAttribute(attr)) continue;
422
+ let attrName: string;
423
+ let attrNamespace: string | undefined;
424
+ if (t.isJSXNamespacedName(attr.name)) {
425
+ attrNamespace = attr.name.namespace.name;
426
+ attrName = attr.name.name.name;
427
+ } else {
428
+ attrName = (attr.name as t.JSXIdentifier).name;
429
+ // bindValue -> bind:value, bindChecked -> bind:checked
430
+ if (/^bind[A-Z]/.test(attrName)) {
431
+ attrNamespace = "bind";
432
+ // bindScrollTop -> bind:scrollTop: only the first letter lowers
433
+ attrName = attrName.charAt(4).toLowerCase() + attrName.slice(5);
434
+ }
435
+ }
436
+ const realAttr = ATTR_MAP[attrName] ?? attrName;
437
+
438
+ if (seenAttrs.has(realAttr)) {
439
+ throw new TypeError(
440
+ `Duplicate attribute "${realAttr}" (via "${attrName}"). Use class or className, not both.`,
441
+ );
442
+ }
443
+ seenAttrs.add(realAttr);
444
+ if (
445
+ (attrNamespace === "transition" ||
446
+ attrNamespace === "in" ||
447
+ attrNamespace === "out") &&
448
+ t.isJSXExpressionContainer(attr.value)
449
+ ) {
450
+ // transition:fade={fade} / in:appear={x} / out:leave={[y, params]}
451
+ const expr = attr.value.expression as t.Expression;
452
+ statements.push(
453
+ t.expressionStatement(
454
+ t.callExpression(t.identifier("mountTransition"), [
455
+ t.identifier(varName),
456
+ expr,
457
+ t.stringLiteral(attrNamespace as "transition" | "in" | "out"),
458
+ ]),
459
+ ),
460
+ );
461
+ } else if (attrName === "use") {
462
+ // use={directive} or use={[directive, params]}
463
+ const expr = (attr.value as t.JSXExpressionContainer)
464
+ .expression as t.Expression;
465
+ statements.push(
466
+ t.expressionStatement(
467
+ t.callExpression(t.identifier("applyDirective"), [
468
+ t.identifier(varName),
469
+ expr,
470
+ ]),
471
+ ),
472
+ );
473
+ } else if (/^on[A-Z]/.test(attrName)) {
474
+ // Standard JSX: onClick, onSubmit, onMouseenter, etc.
475
+ // Convert camelCase to lowercase: onClick -> click, onMouseenter -> mouseenter
476
+ const event = attrName.slice(2).toLowerCase();
477
+ const handler = (attr.value as t.JSXExpressionContainer)
478
+ .expression as t.Expression;
479
+ statements.push(
480
+ t.expressionStatement(
481
+ t.callExpression(
482
+ t.memberExpression(
483
+ t.identifier(varName),
484
+ t.identifier("addEventListener"),
485
+ ),
486
+ [t.stringLiteral(event), handler],
487
+ ),
488
+ ),
489
+ );
490
+ } else if (attrNamespace === "bind") {
491
+ const bindProp = attrName;
492
+ const signal = (attr.value as t.JSXExpressionContainer)
493
+ .expression as t.Expression;
494
+
495
+ if (bindProp === "this") {
496
+ statements.push(
497
+ t.expressionStatement(
498
+ t.callExpression(
499
+ t.memberExpression(
500
+ (signal as t.CallExpression).callee as t.Expression,
501
+ t.identifier("set"),
502
+ ),
503
+ [t.identifier(varName)],
504
+ ),
505
+ ),
506
+ );
507
+ continue;
508
+ }
509
+
510
+ if (bindProp === "group") {
511
+ // Scan element attributes for type and value
512
+ let inputType = "";
513
+ let _inputValue: t.StringLiteral | undefined;
514
+ for (const a of node.openingElement.attributes) {
515
+ if (t.isJSXAttribute(a) && t.isJSXIdentifier(a.name)) {
516
+ if (a.name.name === "type" && t.isStringLiteral(a.value)) {
517
+ inputType = a.value.value;
518
+ }
519
+ if (a.name.name === "value" && t.isStringLiteral(a.value)) {
520
+ _inputValue = a.value;
521
+ }
522
+ }
523
+ }
524
+
525
+ if (inputType === "radio" || inputType === "") {
526
+ const isTopLevel =
527
+ t.isCallExpression(signal) &&
528
+ t.isIdentifier((signal as t.CallExpression).callee) &&
529
+ signals.has(
530
+ ((signal as t.CallExpression).callee as t.Identifier).name,
531
+ );
532
+
533
+ if (isTopLevel) {
534
+ const signalId = (signal as t.CallExpression)
535
+ .callee as t.Identifier;
536
+ statements.push(
537
+ t.expressionStatement(
538
+ t.callExpression(
539
+ t.memberExpression(
540
+ t.identifier(varName),
541
+ t.identifier("addEventListener"),
542
+ ),
543
+ [
544
+ t.stringLiteral("change"),
545
+ t.arrowFunctionExpression(
546
+ [],
547
+ t.callExpression(
548
+ t.memberExpression(signalId, t.identifier("set")),
549
+ [
550
+ t.memberExpression(
551
+ t.identifier(varName),
552
+ t.identifier("value"),
553
+ ),
554
+ ],
555
+ ),
556
+ ),
557
+ ],
558
+ ),
559
+ ),
560
+ );
561
+ }
562
+ } else if (inputType === "checkbox") {
563
+ const isTopLevel =
564
+ t.isCallExpression(signal) &&
565
+ t.isIdentifier((signal as t.CallExpression).callee) &&
566
+ signals.has(
567
+ ((signal as t.CallExpression).callee as t.Identifier).name,
568
+ );
569
+
570
+ if (isTopLevel) {
571
+ const callExpr = signal as t.CallExpression;
572
+ statements.push(
573
+ t.expressionStatement(
574
+ t.callExpression(
575
+ t.memberExpression(
576
+ t.identifier(varName),
577
+ t.identifier("addEventListener"),
578
+ ),
579
+ [
580
+ t.stringLiteral("change"),
581
+ t.arrowFunctionExpression(
582
+ [],
583
+ t.blockStatement([
584
+ t.ifStatement(
585
+ t.memberExpression(
586
+ t.identifier(varName),
587
+ t.identifier("checked"),
588
+ ),
589
+ // checked: push value into array
590
+ t.blockStatement([
591
+ t.expressionStatement(
592
+ t.callExpression(
593
+ t.memberExpression(
594
+ t.callExpression(callExpr, []),
595
+ t.identifier("push"),
596
+ ),
597
+ [
598
+ t.memberExpression(
599
+ t.identifier(varName),
600
+ t.identifier("value"),
601
+ ),
602
+ ],
603
+ ),
604
+ ),
605
+ ]),
606
+ // unchecked: splice value out of array
607
+ t.blockStatement([
608
+ t.expressionStatement(
609
+ t.callExpression(
610
+ t.memberExpression(
611
+ t.callExpression(callExpr, []),
612
+ t.identifier("splice"),
613
+ ),
614
+ [
615
+ t.callExpression(
616
+ t.memberExpression(
617
+ t.callExpression(callExpr, []),
618
+ t.identifier("indexOf"),
619
+ ),
620
+ [
621
+ t.memberExpression(
622
+ t.identifier(varName),
623
+ t.identifier("value"),
624
+ ),
625
+ ],
626
+ ),
627
+ t.numericLiteral(1),
628
+ ],
629
+ ),
630
+ ),
631
+ ]),
632
+ ),
633
+ ]),
634
+ ),
635
+ ],
636
+ ),
637
+ ),
638
+ );
639
+ }
640
+ } else {
641
+ warn(
642
+ attr,
643
+ `bind:group requires type="radio" or type="checkbox" on the element. ` +
644
+ `Got: type="${inputType}".`,
645
+ );
646
+ }
647
+ continue;
648
+ }
649
+
650
+ // Generic bind:innerHTML, bind:textContent, bind:value, bind:checked, etc.
651
+ const isTopLevelSignal =
652
+ t.isCallExpression(signal) &&
653
+ t.isIdentifier((signal as t.CallExpression).callee) &&
654
+ signals.has(((signal as t.CallExpression).callee as t.Identifier).name);
655
+
656
+ const isMemberOfSignal =
657
+ t.isMemberExpression(signal) &&
658
+ t.isCallExpression((signal as t.MemberExpression).object) &&
659
+ t.isIdentifier(
660
+ ((signal as t.MemberExpression).object as t.CallExpression).callee,
661
+ ) &&
662
+ signals.has(
663
+ (
664
+ ((signal as t.MemberExpression).object as t.CallExpression)
665
+ .callee as t.Identifier
666
+ ).name,
667
+ );
668
+
669
+ // bind:checked={item.done} in a list row, or {book.read} where `book`
670
+ // is a prop: the chain is rooted at a row item or a props object,
671
+ // and what it ends in is a property of a $state proxy
672
+ let root: t.Node = signal;
673
+ while (t.isMemberExpression(root)) root = root.object;
674
+ const isMemberOfItem =
675
+ t.isMemberExpression(signal) &&
676
+ t.isIdentifier(root) &&
677
+ signals.has(root.name);
678
+
679
+ if (isTopLevelSignal) {
680
+ buildBind(varName, bindProp, attr, statements);
681
+ } else if (isMemberOfSignal || isMemberOfItem) {
682
+ buildProxyBind(varName, bindProp, attr, statements, signal);
683
+ } else {
684
+ warn(
685
+ attr,
686
+ `bind:${bindProp}={...} requires a $state signal or $state object property. ` +
687
+ `Got: ${generate(signal).code}. ` +
688
+ `Hint: change to a $state() call.`,
689
+ );
690
+ }
691
+ } else if (attr.value === null) {
692
+ // bare attribute (<input disabled>, <div data-beacon>)
693
+ init.push(
694
+ t.expressionStatement(
695
+ isDashedAttr(realAttr)
696
+ ? setAttrCall(varName, realAttr, t.stringLiteral(""))
697
+ : setPropCall(varName, realAttr, t.booleanLiteral(true)),
698
+ ),
699
+ );
700
+ } else if (t.isStringLiteral(attr.value)) {
701
+ const stmt = t.expressionStatement(
702
+ setPropCall(varName, realAttr, t.stringLiteral(attr.value.value)),
703
+ );
704
+ (tag === "select" && realAttr === "value" ? initAfter : init).push(stmt);
705
+ } else if (t.isJSXExpressionContainer(attr.value)) {
706
+ const expr = attr.value.expression as t.Expression;
707
+ const afterChildren = tag === "select" && realAttr === "value";
708
+ // style={{ color: "red", fontSize: val }} — per-property writes
709
+ if (attrName === "style" && t.isObjectExpression(expr)) {
710
+ for (const prop of expr.properties) {
711
+ if (!t.isObjectProperty(prop)) continue;
712
+ const key = t.isIdentifier(prop.key)
713
+ ? prop.key.name
714
+ : t.isStringLiteral(prop.key)
715
+ ? prop.key.value
716
+ : null;
717
+ if (!key) continue;
718
+ const val = prop.value as t.Expression;
719
+ const write = t.expressionStatement(
720
+ t.callExpression(t.identifier("setStyleProp"), [
721
+ t.identifier(varName),
722
+ t.stringLiteral(key),
723
+ val,
724
+ ]),
725
+ );
726
+ if (containsSignal(val, signals)) {
727
+ statements.push(effect([write]));
728
+ } else {
729
+ init.push(write);
730
+ }
731
+ }
732
+ } else if (containsSignal(expr, signals)) {
733
+ // Dynamic class with scoped CSS: use classList.value to preserve hash
734
+ if (attrName === "class" && hash) {
735
+ statements.push(
736
+ effect([
737
+ t.expressionStatement(
738
+ t.assignmentExpression(
739
+ "=",
740
+ t.memberExpression(
741
+ t.memberExpression(
742
+ t.identifier(varName),
743
+ t.identifier("classList"),
744
+ ),
745
+ t.identifier("value"),
746
+ ),
747
+ expr,
748
+ ),
749
+ ),
750
+ t.expressionStatement(
751
+ t.callExpression(
752
+ t.memberExpression(
753
+ t.memberExpression(
754
+ t.identifier(varName),
755
+ t.identifier("classList"),
756
+ ),
757
+ t.identifier("add"),
758
+ ),
759
+ [t.stringLiteral(hash)],
760
+ ),
761
+ ),
762
+ ]),
763
+ );
764
+ } else {
765
+ const stmt = effect([
766
+ t.expressionStatement(setPropCall(varName, realAttr, expr)),
767
+ ]);
768
+ (afterChildren ? liveAfter : statements).push(stmt);
769
+ }
770
+ } else {
771
+ const stmt = t.expressionStatement(
772
+ setPropCall(varName, realAttr, expr),
773
+ );
774
+ (afterChildren ? initAfter : init).push(stmt);
775
+ }
776
+ }
777
+ }
778
+
779
+ pushInit(varName, init, statements, hydrate);
780
+
781
+ // Add scoped CSS hash to classList (if hash is present)
782
+ if (hash) {
783
+ addScopedClass(varName, hash, statements);
784
+ }
785
+
786
+ // children. <script> text is already in the server HTML, raw and unmarked
787
+ // (see ssr.ts), so hydration has nothing to claim there: the marker search
788
+ // would miss and append a second copy of the code.
789
+ if (hydrate && tag === "script") {
790
+ // ...but SPA navigation creates the element fresh and needs the text.
791
+ const text = scriptText(node);
792
+ if (text) {
793
+ const write = [
794
+ t.expressionStatement(
795
+ t.assignmentExpression(
796
+ "=",
797
+ t.memberExpression(
798
+ t.identifier(varName),
799
+ t.identifier("textContent"),
800
+ ),
801
+ text,
802
+ ),
803
+ ),
804
+ ];
805
+ pushInit(varName, write, statements, hydrate);
806
+ }
807
+ }
808
+ for (const child of hydrate && tag === "script" ? [] : node.children) {
809
+ if (t.isJSXElement(child)) {
810
+ const childVar = processElement(
811
+ child,
812
+ statements,
813
+ genId,
814
+ signals,
815
+ hash,
816
+ hydrate,
817
+ childNodesVar,
818
+ hydrate ? varName : undefined,
819
+ );
820
+ if (!hydrate) {
821
+ statements.push(
822
+ t.expressionStatement(
823
+ t.callExpression(
824
+ t.memberExpression(t.identifier(varName), t.identifier("append")),
825
+ [t.identifier(childVar)],
826
+ ),
827
+ ),
828
+ );
829
+ }
830
+ } else if (t.isJSXFragment(child)) {
831
+ const childVar = processFragment(
832
+ child,
833
+ statements,
834
+ genId,
835
+ signals,
836
+ hash,
837
+ hydrate,
838
+ childNodesVar,
839
+ hydrate ? varName : undefined,
840
+ );
841
+ if (!hydrate) {
842
+ statements.push(
843
+ t.expressionStatement(
844
+ t.callExpression(
845
+ t.memberExpression(t.identifier(varName), t.identifier("append")),
846
+ [t.identifier(childVar)],
847
+ ),
848
+ ),
849
+ );
850
+ }
851
+ } else if (t.isJSXText(child)) {
852
+ const text = jsxText(child, node.children);
853
+ if (text === null) continue;
854
+ if (hydrate) {
855
+ // SSR hydration: text already in DOM from SSR, do nothing.
856
+ // SPA navigation: childNodesVar pool is empty, create text node.
857
+ const poolLen = t.memberExpression(
858
+ t.identifier(childNodesVar!),
859
+ t.identifier("length"),
860
+ );
861
+ statements.push(
862
+ t.ifStatement(
863
+ t.binaryExpression("===", poolLen, t.numericLiteral(0)),
864
+ t.expressionStatement(
865
+ t.callExpression(
866
+ t.memberExpression(
867
+ t.identifier(varName),
868
+ t.identifier("append"),
869
+ ),
870
+ [
871
+ t.callExpression(
872
+ t.memberExpression(
873
+ t.identifier("document"),
874
+ t.identifier("createTextNode"),
875
+ ),
876
+ [t.stringLiteral(text)],
877
+ ),
878
+ ],
879
+ ),
880
+ ),
881
+ ),
882
+ );
883
+ } else {
884
+ statements.push(
885
+ t.expressionStatement(
886
+ t.callExpression(
887
+ t.memberExpression(t.identifier(varName), t.identifier("append")),
888
+ [
889
+ t.callExpression(
890
+ t.memberExpression(
891
+ t.identifier("document"),
892
+ t.identifier("createTextNode"),
893
+ ),
894
+ [t.stringLiteral(text)],
895
+ ),
896
+ ],
897
+ ),
898
+ ),
899
+ );
900
+ }
901
+ } else if (t.isJSXExpressionContainer(child)) {
902
+ if (t.isJSXEmptyExpression(child.expression)) continue;
903
+ const expr = child.expression as t.Expression;
904
+ if (t.isJSXElement(expr)) {
905
+ const childVar = processElement(
906
+ expr,
907
+ statements,
908
+ genId,
909
+ signals,
910
+ hash,
911
+ hydrate,
912
+ childNodesVar,
913
+ hydrate ? varName : undefined,
914
+ );
915
+ if (!hydrate) {
916
+ statements.push(
917
+ t.expressionStatement(
918
+ t.callExpression(
919
+ t.memberExpression(
920
+ t.identifier(varName),
921
+ t.identifier("append"),
922
+ ),
923
+ [t.identifier(childVar)],
924
+ ),
925
+ ),
926
+ );
927
+ }
928
+ } else if (t.isJSXFragment(expr)) {
929
+ const childVar = processFragment(
930
+ expr,
931
+ statements,
932
+ genId,
933
+ signals,
934
+ hash,
935
+ hydrate,
936
+ childNodesVar,
937
+ hydrate ? varName : undefined,
938
+ );
939
+ if (!hydrate) {
940
+ statements.push(
941
+ t.expressionStatement(
942
+ t.callExpression(
943
+ t.memberExpression(
944
+ t.identifier(varName),
945
+ t.identifier("append"),
946
+ ),
947
+ [t.identifier(childVar)],
948
+ ),
949
+ ),
950
+ );
951
+ }
952
+ } else if (isPropRead(expr)) {
953
+ // a prop may hold text, nodes or a deferred child, and may be a
954
+ // getter over state: a live slot handles all of them
955
+ statements.push(
956
+ t.expressionStatement(
957
+ t.callExpression(t.identifier("liveSlot"), [
958
+ hydrate ? t.identifier(childNodesVar!) : t.arrayExpression([]),
959
+ t.identifier(varName),
960
+ t.arrowFunctionExpression([], expr),
961
+ ]),
962
+ ),
963
+ );
964
+ } else if (containsSignal(expr, signals)) {
965
+ if (isPrimitive(expr)) {
966
+ // fast path: text node + textContent
967
+ buildTextNode(
968
+ varName,
969
+ expr,
970
+ statements,
971
+ genId,
972
+ hydrate,
973
+ childNodesVar,
974
+ hydrate ? varName : undefined,
975
+ );
976
+ } else {
977
+ // Check for keyed list pattern
978
+ const keyed = findKeyedMapExpr(expr, signals);
979
+ if (keyed) {
980
+ buildKeyedList(
981
+ varName,
982
+ keyed,
983
+ statements,
984
+ genId,
985
+ signals,
986
+ processElement,
987
+ hash,
988
+ hydrate,
989
+ childNodesVar,
990
+ hydrate ? varName : undefined,
991
+ );
992
+ } else {
993
+ buildAnchorMount(
994
+ varName,
995
+ expr,
996
+ statements,
997
+ genId,
998
+ hydrate,
999
+ childNodesVar,
1000
+ hydrate ? varName : undefined,
1001
+ );
1002
+ }
1003
+ }
1004
+ } else {
1005
+ // non-reactive: set once
1006
+ if (hydrate) {
1007
+ // hydrateSlot consumes the <!--g-->…<!--/g--> run and runs the
1008
+ // value against the content SSR put inside it, so both deferred
1009
+ // component children and inline JSX (`{list.map(…)}`) claim that
1010
+ // subtree. The value must stay lazy: evaluating it as an argument
1011
+ // would claim from the enclosing pool instead. Empty pool
1012
+ // (SPA nav) falls back to a fresh insert.
1013
+ statements.push(
1014
+ t.expressionStatement(
1015
+ t.callExpression(t.identifier("hydrateSlot"), [
1016
+ t.identifier(childNodesVar!),
1017
+ t.identifier(varName),
1018
+ t.arrowFunctionExpression([], expr),
1019
+ ]),
1020
+ ),
1021
+ );
1022
+ } else {
1023
+ statements.push(
1024
+ t.expressionStatement(
1025
+ t.callExpression(t.identifier("insert"), [
1026
+ t.identifier(varName),
1027
+ expr,
1028
+ ]),
1029
+ ),
1030
+ );
1031
+ }
1032
+ }
1033
+ }
1034
+ }
1035
+
1036
+ pushInit(varName, initAfter, statements, hydrate);
1037
+ statements.push(...liveAfter);
1038
+
1039
+ return varName;
1040
+ }