@sigil-dev/compiler 0.9.21 → 0.9.23

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