@sigil-dev/compiler 0.10.2 → 0.10.3

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,380 +1,380 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { transformSync } from "@babel/core";
3
- import * as runtime from "../../runtime/index.ts";
4
- import sigilPlugin from "../src/babel/index.ts";
5
-
6
- function transform(
7
- source: string,
8
- opts?: { mode?: "dom" | "ssr" | "hydrate" },
9
- ) {
10
- const result = transformSync(source, {
11
- plugins: [
12
- "@babel/plugin-syntax-jsx",
13
- [sigilPlugin, { mode: opts?.mode ?? "dom" }],
14
- ],
15
- filename: "test.tsx",
16
- });
17
- return result!.code!;
18
- }
19
-
20
- /**
21
- * Evaluate compiled output and return its exported `App`. SSR output carries
22
- * its own `__h`/`__e` helpers; hydrate output imports from the runtime, which
23
- * is injected as plain parameters instead.
24
- */
25
- function evalApp(code: string): () => unknown {
26
- const body = code
27
- .replace(/import\s*\{[^}]*\}\s*from\s*["']@sigil-dev\/runtime["'];?/g, "")
28
- .replace(/^export\s+/gm, "");
29
- const factory = new Function(
30
- "document",
31
- ...Object.keys(runtime),
32
- `${body};\nreturn App;`,
33
- );
34
- return factory(globalThis.document, ...Object.values(runtime));
35
- }
36
-
37
- describe("Hydration", () => {
38
- test("element uses claim instead of createElement", () => {
39
- const code = transform(`const el = <div></div>`, { mode: "hydrate" });
40
- expect(code).toContain("claim(");
41
- expect(code).not.toContain("createElement");
42
- });
43
-
44
- test("nested elements use claim with scoped pools", () => {
45
- const code = transform(`const el = <div><span></span></div>`, {
46
- mode: "hydrate",
47
- });
48
- // Should claim div from root __nodes pool (no parent for root)
49
- expect(code).toContain('claim(__nodes, "div")');
50
- // Should scope to div's children (genId produces _el1 for pool)
51
- expect(code).toContain("Array.from(_el0.childNodes)");
52
- // Should claim span from div's child pool with parent for SPA fallback
53
- expect(code).toContain('claim(_el1, "span", _el0)');
54
- });
55
-
56
- test("static text creates text node only when pool is empty (SPA nav)", () => {
57
- const code = transform(`const el = <div>Hello</div>`, { mode: "hydrate" });
58
- // Static text: SSR hydration leaves it in DOM; SPA nav creates it when pool is empty
59
- expect(code).not.toContain("claimText(");
60
- // Should emit a conditional createTextNode guarded by pool.length === 0
61
- expect(code).toContain("createTextNode");
62
- expect(code).toContain(".length === 0");
63
- });
64
-
65
- test("reactive text node uses claimComment anchor + Text check for hydration", () => {
66
- const code = transform(
67
- `let name = $state('Alice'); const el = <span>{name}</span>`,
68
- { mode: "hydrate" },
69
- );
70
- // Dynamic text: claims <!--g--> as anchor (fixes adjacent-text bug vs DOM walk)
71
- // then gets nextSibling; creates text node if it's not a Text (SPA navigation)
72
- expect(code).toContain("claimComment(");
73
- expect(code).toContain("createEffect");
74
- expect(code).toContain("instanceof globalThis.Text");
75
- });
76
-
77
- test("attributes still work in hydrate mode", () => {
78
- const code = transform(`const el = <div class="foo" id="bar"></div>`, {
79
- mode: "hydrate",
80
- });
81
- expect(code).toContain("claim(");
82
- expect(code).toContain('setProp(_el0, "className", "foo")');
83
- expect(code).toContain('setProp(_el0, "id", "bar")');
84
- });
85
-
86
- test("event handlers still attached in hydrate mode", () => {
87
- const code = transform(
88
- `const el = <button onClick={() => {}}>Click</button>`,
89
- { mode: "hydrate" },
90
- );
91
- expect(code).toContain("claim(");
92
- expect(code).toContain("addEventListener");
93
- });
94
-
95
- test("no unconditional append calls in hydrate mode", () => {
96
- const code = transform(`const el = <div><span></span></div>`, {
97
- mode: "hydrate",
98
- });
99
- // Elements are claimed from pool — no unconditional appends for elements
100
- // (static text does emit a conditional .append guarded by pool.length === 0)
101
- expect(code).not.toContain('claim(__nodes, "div").append(');
102
- });
103
-
104
- test("dom mode still uses createElement (no regression)", () => {
105
- const code = transform(`const el = <div></div>`, { mode: "dom" });
106
- expect(code).toContain("createElement");
107
- expect(code).not.toContain("claim(");
108
- });
109
-
110
- test("dom mode still appends children (no regression)", () => {
111
- const code = transform(`const el = <div><span></span></div>`, {
112
- mode: "dom",
113
- });
114
- expect(code).toContain(".append(");
115
- });
116
-
117
- test("three levels deep: div > p > span", () => {
118
- const code = transform(`const el = <div><p><span></span></p></div>`, {
119
- mode: "hydrate",
120
- });
121
- // Three scopes (Array.from)
122
- const scopes = code.match(/Array\.from\(.*\.childNodes\)/g);
123
- expect(scopes?.length).toBe(3);
124
- // Root claims from __nodes (no parent), children use generated pool names with parent
125
- expect(code).toContain('claim(__nodes, "div")');
126
- expect(code).toContain('claim(_el1, "p", _el0)');
127
- expect(code).toContain('claim(_el3, "span", _el2)');
128
- });
129
-
130
- test("imports claim and claimText from @sigil-dev/runtime", () => {
131
- const code = transform(`const el = <div></div>`, { mode: "hydrate" });
132
- expect(code).toContain(
133
- "createSignal, createRawSignal, createEffect, createMemo, reconcile, claim, claimText, claimComment, claimSlot, hydrateKeyedList, hydrateSlot, insert, applyDirective, getHydrationNodes, pushHydrationNodes, popHydrationNodes, snapshot, tracking, untrack, createRoot, createEffectPre, createInspectEffect, withEffectScope, mountTransition, removeAnimated",
134
- );
135
- });
136
-
137
- test("dom mode does not import claim/claimText", () => {
138
- const code = transform(`const el = <div></div>`, { mode: "dom" });
139
- // claim/claimText are imported but unused — tree-shaking removes them
140
- // Actually, they're always imported. That's fine — bundlers tree-shake.
141
- // Just verify createElement is used
142
- expect(code).toContain("createElement");
143
- });
144
-
145
- test("reactive attribute still wraps in createEffect", () => {
146
- const code = transform(
147
- `let cls = $state('a'); const el = <div class={cls}></div>`,
148
- { mode: "hydrate" },
149
- );
150
- expect(code).toContain("claim(");
151
- expect(code).toContain("createEffect");
152
- });
153
-
154
- test("components in hydrate mode pass children as props", () => {
155
- const code = transform(
156
- `const App = (props) => <div>{props.children}</div>;
157
- const el = <App><span>Hi</span></App>`,
158
- { mode: "hydrate" },
159
- );
160
- // Component still calls function
161
- expect(code).toContain("__component(App,");
162
- // Inner div uses claim
163
- expect(code).toContain('claim(__nodes, "div")');
164
- });
165
-
166
- test("component children are deferred thunks in hydrate mode", () => {
167
- const code = transform(
168
- `const Wrap = ({ children }) => <div>{children}</div>;
169
- const el = <Wrap><span>Hi</span></Wrap>`,
170
- { mode: "hydrate" },
171
- );
172
- // children must not be evaluated at the call site — they claim from the
173
- // component's own slot, which the caller cannot see
174
- expect(code).toMatch(/children:\s*\[\(\)\s*=>\s*\{/);
175
- // the {children} site consumes the SSR slot and hydrates against it;
176
- // it's a live slot because props are read through the props object
177
- expect(code).toContain("liveSlot(_el1, _el0, () => _props.children)");
178
- });
179
-
180
- test("dom mode still evaluates component children eagerly", () => {
181
- const code = transform(
182
- `const Wrap = ({ children }) => <div>{children}</div>;
183
- const el = <Wrap><span>Hi</span></Wrap>`,
184
- { mode: "dom" },
185
- );
186
- expect(code).toMatch(/children:\s*\[\(\(\)\s*=>\s*\{/);
187
- expect(code).not.toContain("hydrateSlot(");
188
- });
189
-
190
- test("hydrating a component with children leaves the SSR DOM untouched", () => {
191
- // Regression: children were claimed from the caller's pool, so a nested
192
- // component found no match, built a fresh subtree, and the sibling
193
- // element stole the wrapper's own SSR root — every child rendered twice.
194
- const src = `
195
- function Wrap({ children }) { return <div class="wrap">{children}</div>; }
196
- function Item({ label }) { return <p class="item">{label}</p>; }
197
- export const App = () => (
198
- <section class="sec">
199
- <Wrap>
200
- <Item label="alpha" />
201
- <div class="grid">grid</div>
202
- </Wrap>
203
- </section>
204
- );
205
- `;
206
- const html = String(evalApp(transform(src, { mode: "ssr" }))());
207
- const host = document.createElement("div");
208
- host.innerHTML = html;
209
-
210
- const app = evalApp(transform(src, { mode: "hydrate" }));
211
- runtime.pushHydrationNodes(Array.from(host.childNodes));
212
- app();
213
- runtime.popHydrationNodes();
214
-
215
- expect(host.querySelectorAll("div.wrap").length).toBe(1);
216
- expect(host.querySelectorAll("p.item").length).toBe(1);
217
- expect(host.querySelectorAll("div.grid").length).toBe(1);
218
- // perfect hydration: claims only, no re-render
219
- expect(host.innerHTML).toBe(html);
220
- });
221
-
222
- test("component children render once on an empty pool (SPA navigation)", () => {
223
- const src = `
224
- function Wrap({ children }) { return <div class="wrap">{children}</div>; }
225
- function Item({ label }) { return <p class="item">{label}</p>; }
226
- export const App = () => (
227
- <section class="sec">
228
- <Wrap>
229
- <Item label="alpha" />
230
- </Wrap>
231
- </section>
232
- );
233
- `;
234
- const app = evalApp(transform(src, { mode: "hydrate" }));
235
- const host = document.createElement("div");
236
- runtime.pushHydrationNodes([]);
237
- runtime.insert(host, app());
238
- runtime.popHydrationNodes();
239
-
240
- expect(host.querySelectorAll("div.wrap").length).toBe(1);
241
- expect(host.querySelectorAll("p.item").length).toBe(1);
242
- expect(host.querySelector("p.item")?.textContent).toBe("alpha");
243
- });
244
-
245
- test("a static list inside a slot hydrates its SSR items in place", () => {
246
- // The slot value must stay lazy: evaluated as a call argument the map
247
- // bodies claimed from the enclosing pool, missed the SSR items and
248
- // appended fresh copies next to them.
249
- const src = `
250
- function Wrap({ children }) { return <div class="wrap">{children}</div>; }
251
- export const App = () => (
252
- <section class="sec">
253
- <Wrap>
254
- <div class="grid">
255
- {["a", "b", "c"].map((c) => <span class="cell">{c}</span>)}
256
- </div>
257
- </Wrap>
258
- </section>
259
- );
260
- `;
261
- const html = String(evalApp(transform(src, { mode: "ssr" }))());
262
- const host = document.createElement("div");
263
- host.innerHTML = html;
264
-
265
- const app = evalApp(transform(src, { mode: "hydrate" }));
266
- runtime.pushHydrationNodes(Array.from(host.childNodes));
267
- app();
268
- runtime.popHydrationNodes();
269
-
270
- expect(host.querySelectorAll("span.cell").length).toBe(3);
271
- expect(
272
- Array.from(host.querySelectorAll("span.cell")).map(
273
- (el) => el.textContent,
274
- ),
275
- ).toEqual(["a", "b", "c"]);
276
- });
277
-
278
- test("a fragment branch with an empty dynamic child hydrates once", () => {
279
- // Regression: the slot's SSR content was removed up to the first <!--/g-->,
280
- // which belonged to the nested empty slot ({maybe ? … : null}) inside the
281
- // fragment. Everything after it stayed in the DOM and was mounted again.
282
- const src = `
283
- export const App = ({ empty, maybe }) => (
284
- <main class="m">
285
- {empty ? (
286
- <p class="empty">none</p>
287
- ) : (
288
- <>
289
- <h1>title</h1>
290
- {maybe ? <b class="note">note</b> : null}
291
- <div class="card">card</div>
292
- <p class="hint">hint</p>
293
- </>
294
- )}
295
- </main>
296
- );
297
- `;
298
- const props = { empty: false, maybe: null };
299
- const html = String(evalApp(transform(src, { mode: "ssr" }))(props));
300
- const host = document.createElement("div");
301
- host.innerHTML = html;
302
-
303
- const app = evalApp(transform(src, { mode: "hydrate" })) as (
304
- p: typeof props,
305
- ) => unknown;
306
- runtime.pushHydrationNodes(Array.from(host.childNodes));
307
- app(props);
308
- runtime.popHydrationNodes();
309
-
310
- expect(host.querySelectorAll("h1").length).toBe(1);
311
- expect(host.querySelectorAll("div.card").length).toBe(1);
312
- expect(host.querySelectorAll("p.hint").length).toBe(1);
313
- expect(host.querySelectorAll("b.note").length).toBe(0);
314
- });
315
-
316
- test("a keyed list doesn't rebuild the branch around it", async () => {
317
- // Regression: hydrateKeyedList read the list source tracked, so the
318
- // enclosing {open ? … : null} re-ran on every change and remade the
319
- // whole branch (an <input> next to the list lost focus per keystroke).
320
- const src = `
321
- export function App() {
322
- let items = $state(["a", "b"]);
323
- let open = $state(true);
324
- globalThis.__keyedSet = (v) => (items = v);
325
- return (
326
- <main>
327
- {open ? (
328
- <div class="box">
329
- <input class="q" />
330
- {items.map((i) => <a key={i}>{i}</a>)}
331
- </div>
332
- ) : null}
333
- </main>
334
- );
335
- }
336
- `;
337
- const app = evalApp(transform(src, { mode: "hydrate" }));
338
- runtime.pushHydrationNodes([]);
339
- const root = app() as Element;
340
- runtime.popHydrationNodes();
341
- const host = document.createElement("div");
342
- host.append(root);
343
- const input = host.querySelector("input.q");
344
- expect(host.querySelectorAll("a").length).toBe(2);
345
- (globalThis as { __keyedSet?: (v: string[]) => void }).__keyedSet!(["a", "b", "c"]);
346
- await new Promise((r) => setTimeout(r, 0));
347
- expect(host.querySelectorAll("a").length).toBe(3);
348
- expect(host.querySelector("input.q")).toBe(input);
349
- });
350
-
351
- test("a helper that builds JSX, called with a prop, hydrates as nodes", () => {
352
- // Regression: {tab("a", props.count)} read a prop, so it was taken for
353
- // text and hydrated as textContent = String(<a>): the link's URL
354
- // appeared next to it
355
- const src = `
356
- export const App = (props) => {
357
- const tab = (id, label, count) => (
358
- <a href={"/x/" + id} class="tab">
359
- {label} {count !== undefined ? <span class="count">{count}</span> : null}
360
- </a>
361
- );
362
- return <nav>{tab("a", "First", props.count)}{tab("b", "Second", 2)}</nav>;
363
- };
364
- `;
365
- const props = { count: 3 };
366
- const html = String(evalApp(transform(src, { mode: "ssr" }))(props));
367
- const host = document.createElement("div");
368
- host.innerHTML = html;
369
- const app = evalApp(transform(src, { mode: "hydrate" })) as (p: typeof props) => unknown;
370
- runtime.pushHydrationNodes(Array.from(host.childNodes));
371
- app(props);
372
- runtime.popHydrationNodes();
373
- runtime.flushDeferredEffects?.();
374
- expect(host.textContent).not.toContain("/x/");
375
- expect(host.querySelectorAll("a.tab").length).toBe(2);
376
- expect(host.querySelector("a.tab")!.textContent).toContain("First");
377
- // and the call isn't a text node in the output any more
378
- expect(transform(src, { mode: "hydrate" })).not.toContain("String(tab(");
379
- });
380
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { transformSync } from "@babel/core";
3
+ import * as runtime from "../../runtime/index.ts";
4
+ import sigilPlugin from "../src/babel/index.ts";
5
+
6
+ function transform(
7
+ source: string,
8
+ opts?: { mode?: "dom" | "ssr" | "hydrate" },
9
+ ) {
10
+ const result = transformSync(source, {
11
+ plugins: [
12
+ "@babel/plugin-syntax-jsx",
13
+ [sigilPlugin, { mode: opts?.mode ?? "dom" }],
14
+ ],
15
+ filename: "test.tsx",
16
+ });
17
+ return result!.code!;
18
+ }
19
+
20
+ /**
21
+ * Evaluate compiled output and return its exported `App`. SSR output carries
22
+ * its own `__h`/`__e` helpers; hydrate output imports from the runtime, which
23
+ * is injected as plain parameters instead.
24
+ */
25
+ function evalApp(code: string): () => unknown {
26
+ const body = code
27
+ .replace(/import\s*\{[^}]*\}\s*from\s*["']@sigil-dev\/runtime["'];?/g, "")
28
+ .replace(/^export\s+/gm, "");
29
+ const factory = new Function(
30
+ "document",
31
+ ...Object.keys(runtime),
32
+ `${body};\nreturn App;`,
33
+ );
34
+ return factory(globalThis.document, ...Object.values(runtime));
35
+ }
36
+
37
+ describe("Hydration", () => {
38
+ test("element uses claim instead of createElement", () => {
39
+ const code = transform(`const el = <div></div>`, { mode: "hydrate" });
40
+ expect(code).toContain("claim(");
41
+ expect(code).not.toContain("createElement");
42
+ });
43
+
44
+ test("nested elements use claim with scoped pools", () => {
45
+ const code = transform(`const el = <div><span></span></div>`, {
46
+ mode: "hydrate",
47
+ });
48
+ // Should claim div from root __nodes pool (no parent for root)
49
+ expect(code).toContain('claim(__nodes, "div")');
50
+ // Should scope to div's children (genId produces _el1 for pool)
51
+ expect(code).toContain("Array.from(_el0.childNodes)");
52
+ // Should claim span from div's child pool with parent for SPA fallback
53
+ expect(code).toContain('claim(_el1, "span", _el0)');
54
+ });
55
+
56
+ test("static text creates text node only when pool is empty (SPA nav)", () => {
57
+ const code = transform(`const el = <div>Hello</div>`, { mode: "hydrate" });
58
+ // Static text: SSR hydration leaves it in DOM; SPA nav creates it when pool is empty
59
+ expect(code).not.toContain("claimText(");
60
+ // Should emit a conditional createTextNode guarded by pool.length === 0
61
+ expect(code).toContain("createTextNode");
62
+ expect(code).toContain(".length === 0");
63
+ });
64
+
65
+ test("reactive text node uses claimComment anchor + Text check for hydration", () => {
66
+ const code = transform(
67
+ `let name = $state('Alice'); const el = <span>{name}</span>`,
68
+ { mode: "hydrate" },
69
+ );
70
+ // Dynamic text: claims <!--g--> as anchor (fixes adjacent-text bug vs DOM walk)
71
+ // then gets nextSibling; creates text node if it's not a Text (SPA navigation)
72
+ expect(code).toContain("claimComment(");
73
+ expect(code).toContain("createEffect");
74
+ expect(code).toContain("instanceof globalThis.Text");
75
+ });
76
+
77
+ test("attributes still work in hydrate mode", () => {
78
+ const code = transform(`const el = <div class="foo" id="bar"></div>`, {
79
+ mode: "hydrate",
80
+ });
81
+ expect(code).toContain("claim(");
82
+ expect(code).toContain('setProp(_el0, "className", "foo")');
83
+ expect(code).toContain('setProp(_el0, "id", "bar")');
84
+ });
85
+
86
+ test("event handlers still attached in hydrate mode", () => {
87
+ const code = transform(
88
+ `const el = <button onClick={() => {}}>Click</button>`,
89
+ { mode: "hydrate" },
90
+ );
91
+ expect(code).toContain("claim(");
92
+ expect(code).toContain("addEventListener");
93
+ });
94
+
95
+ test("no unconditional append calls in hydrate mode", () => {
96
+ const code = transform(`const el = <div><span></span></div>`, {
97
+ mode: "hydrate",
98
+ });
99
+ // Elements are claimed from pool — no unconditional appends for elements
100
+ // (static text does emit a conditional .append guarded by pool.length === 0)
101
+ expect(code).not.toContain('claim(__nodes, "div").append(');
102
+ });
103
+
104
+ test("dom mode still uses createElement (no regression)", () => {
105
+ const code = transform(`const el = <div></div>`, { mode: "dom" });
106
+ expect(code).toContain("createElement");
107
+ expect(code).not.toContain("claim(");
108
+ });
109
+
110
+ test("dom mode still appends children (no regression)", () => {
111
+ const code = transform(`const el = <div><span></span></div>`, {
112
+ mode: "dom",
113
+ });
114
+ expect(code).toContain(".append(");
115
+ });
116
+
117
+ test("three levels deep: div > p > span", () => {
118
+ const code = transform(`const el = <div><p><span></span></p></div>`, {
119
+ mode: "hydrate",
120
+ });
121
+ // Three scopes (Array.from)
122
+ const scopes = code.match(/Array\.from\(.*\.childNodes\)/g);
123
+ expect(scopes?.length).toBe(3);
124
+ // Root claims from __nodes (no parent), children use generated pool names with parent
125
+ expect(code).toContain('claim(__nodes, "div")');
126
+ expect(code).toContain('claim(_el1, "p", _el0)');
127
+ expect(code).toContain('claim(_el3, "span", _el2)');
128
+ });
129
+
130
+ test("imports claim and claimText from @sigil-dev/runtime", () => {
131
+ const code = transform(`const el = <div></div>`, { mode: "hydrate" });
132
+ expect(code).toContain(
133
+ "createSignal, createRawSignal, createEffect, createMemo, reconcile, claim, claimText, claimComment, claimSlot, hydrateKeyedList, hydrateSlot, insert, applyDirective, getHydrationNodes, pushHydrationNodes, popHydrationNodes, snapshot, tracking, untrack, createRoot, createEffectPre, createInspectEffect, withEffectScope, mountTransition, removeAnimated",
134
+ );
135
+ });
136
+
137
+ test("dom mode does not import claim/claimText", () => {
138
+ const code = transform(`const el = <div></div>`, { mode: "dom" });
139
+ // claim/claimText are imported but unused — tree-shaking removes them
140
+ // Actually, they're always imported. That's fine — bundlers tree-shake.
141
+ // Just verify createElement is used
142
+ expect(code).toContain("createElement");
143
+ });
144
+
145
+ test("reactive attribute still wraps in createEffect", () => {
146
+ const code = transform(
147
+ `let cls = $state('a'); const el = <div class={cls}></div>`,
148
+ { mode: "hydrate" },
149
+ );
150
+ expect(code).toContain("claim(");
151
+ expect(code).toContain("createEffect");
152
+ });
153
+
154
+ test("components in hydrate mode pass children as props", () => {
155
+ const code = transform(
156
+ `const App = (props) => <div>{props.children}</div>;
157
+ const el = <App><span>Hi</span></App>`,
158
+ { mode: "hydrate" },
159
+ );
160
+ // Component still calls function
161
+ expect(code).toContain("__component(App,");
162
+ // Inner div uses claim
163
+ expect(code).toContain('claim(__nodes, "div")');
164
+ });
165
+
166
+ test("component children are deferred thunks in hydrate mode", () => {
167
+ const code = transform(
168
+ `const Wrap = ({ children }) => <div>{children}</div>;
169
+ const el = <Wrap><span>Hi</span></Wrap>`,
170
+ { mode: "hydrate" },
171
+ );
172
+ // children must not be evaluated at the call site — they claim from the
173
+ // component's own slot, which the caller cannot see
174
+ expect(code).toMatch(/children:\s*\[\(\)\s*=>\s*\{/);
175
+ // the {children} site consumes the SSR slot and hydrates against it;
176
+ // it's a live slot because props are read through the props object
177
+ expect(code).toContain("liveSlot(_el1, _el0, () => _props.children)");
178
+ });
179
+
180
+ test("dom mode still evaluates component children eagerly", () => {
181
+ const code = transform(
182
+ `const Wrap = ({ children }) => <div>{children}</div>;
183
+ const el = <Wrap><span>Hi</span></Wrap>`,
184
+ { mode: "dom" },
185
+ );
186
+ expect(code).toMatch(/children:\s*\[\(\(\)\s*=>\s*\{/);
187
+ expect(code).not.toContain("hydrateSlot(");
188
+ });
189
+
190
+ test("hydrating a component with children leaves the SSR DOM untouched", () => {
191
+ // Regression: children were claimed from the caller's pool, so a nested
192
+ // component found no match, built a fresh subtree, and the sibling
193
+ // element stole the wrapper's own SSR root — every child rendered twice.
194
+ const src = `
195
+ function Wrap({ children }) { return <div class="wrap">{children}</div>; }
196
+ function Item({ label }) { return <p class="item">{label}</p>; }
197
+ export const App = () => (
198
+ <section class="sec">
199
+ <Wrap>
200
+ <Item label="alpha" />
201
+ <div class="grid">grid</div>
202
+ </Wrap>
203
+ </section>
204
+ );
205
+ `;
206
+ const html = String(evalApp(transform(src, { mode: "ssr" }))());
207
+ const host = document.createElement("div");
208
+ host.innerHTML = html;
209
+
210
+ const app = evalApp(transform(src, { mode: "hydrate" }));
211
+ runtime.pushHydrationNodes(Array.from(host.childNodes));
212
+ app();
213
+ runtime.popHydrationNodes();
214
+
215
+ expect(host.querySelectorAll("div.wrap").length).toBe(1);
216
+ expect(host.querySelectorAll("p.item").length).toBe(1);
217
+ expect(host.querySelectorAll("div.grid").length).toBe(1);
218
+ // perfect hydration: claims only, no re-render
219
+ expect(host.innerHTML).toBe(html);
220
+ });
221
+
222
+ test("component children render once on an empty pool (SPA navigation)", () => {
223
+ const src = `
224
+ function Wrap({ children }) { return <div class="wrap">{children}</div>; }
225
+ function Item({ label }) { return <p class="item">{label}</p>; }
226
+ export const App = () => (
227
+ <section class="sec">
228
+ <Wrap>
229
+ <Item label="alpha" />
230
+ </Wrap>
231
+ </section>
232
+ );
233
+ `;
234
+ const app = evalApp(transform(src, { mode: "hydrate" }));
235
+ const host = document.createElement("div");
236
+ runtime.pushHydrationNodes([]);
237
+ runtime.insert(host, app());
238
+ runtime.popHydrationNodes();
239
+
240
+ expect(host.querySelectorAll("div.wrap").length).toBe(1);
241
+ expect(host.querySelectorAll("p.item").length).toBe(1);
242
+ expect(host.querySelector("p.item")?.textContent).toBe("alpha");
243
+ });
244
+
245
+ test("a static list inside a slot hydrates its SSR items in place", () => {
246
+ // The slot value must stay lazy: evaluated as a call argument the map
247
+ // bodies claimed from the enclosing pool, missed the SSR items and
248
+ // appended fresh copies next to them.
249
+ const src = `
250
+ function Wrap({ children }) { return <div class="wrap">{children}</div>; }
251
+ export const App = () => (
252
+ <section class="sec">
253
+ <Wrap>
254
+ <div class="grid">
255
+ {["a", "b", "c"].map((c) => <span class="cell">{c}</span>)}
256
+ </div>
257
+ </Wrap>
258
+ </section>
259
+ );
260
+ `;
261
+ const html = String(evalApp(transform(src, { mode: "ssr" }))());
262
+ const host = document.createElement("div");
263
+ host.innerHTML = html;
264
+
265
+ const app = evalApp(transform(src, { mode: "hydrate" }));
266
+ runtime.pushHydrationNodes(Array.from(host.childNodes));
267
+ app();
268
+ runtime.popHydrationNodes();
269
+
270
+ expect(host.querySelectorAll("span.cell").length).toBe(3);
271
+ expect(
272
+ Array.from(host.querySelectorAll("span.cell")).map(
273
+ (el) => el.textContent,
274
+ ),
275
+ ).toEqual(["a", "b", "c"]);
276
+ });
277
+
278
+ test("a fragment branch with an empty dynamic child hydrates once", () => {
279
+ // Regression: the slot's SSR content was removed up to the first <!--/g-->,
280
+ // which belonged to the nested empty slot ({maybe ? … : null}) inside the
281
+ // fragment. Everything after it stayed in the DOM and was mounted again.
282
+ const src = `
283
+ export const App = ({ empty, maybe }) => (
284
+ <main class="m">
285
+ {empty ? (
286
+ <p class="empty">none</p>
287
+ ) : (
288
+ <>
289
+ <h1>title</h1>
290
+ {maybe ? <b class="note">note</b> : null}
291
+ <div class="card">card</div>
292
+ <p class="hint">hint</p>
293
+ </>
294
+ )}
295
+ </main>
296
+ );
297
+ `;
298
+ const props = { empty: false, maybe: null };
299
+ const html = String(evalApp(transform(src, { mode: "ssr" }))(props));
300
+ const host = document.createElement("div");
301
+ host.innerHTML = html;
302
+
303
+ const app = evalApp(transform(src, { mode: "hydrate" })) as (
304
+ p: typeof props,
305
+ ) => unknown;
306
+ runtime.pushHydrationNodes(Array.from(host.childNodes));
307
+ app(props);
308
+ runtime.popHydrationNodes();
309
+
310
+ expect(host.querySelectorAll("h1").length).toBe(1);
311
+ expect(host.querySelectorAll("div.card").length).toBe(1);
312
+ expect(host.querySelectorAll("p.hint").length).toBe(1);
313
+ expect(host.querySelectorAll("b.note").length).toBe(0);
314
+ });
315
+
316
+ test("a keyed list doesn't rebuild the branch around it", async () => {
317
+ // Regression: hydrateKeyedList read the list source tracked, so the
318
+ // enclosing {open ? … : null} re-ran on every change and remade the
319
+ // whole branch (an <input> next to the list lost focus per keystroke).
320
+ const src = `
321
+ export function App() {
322
+ let items = $state(["a", "b"]);
323
+ let open = $state(true);
324
+ globalThis.__keyedSet = (v) => (items = v);
325
+ return (
326
+ <main>
327
+ {open ? (
328
+ <div class="box">
329
+ <input class="q" />
330
+ {items.map((i) => <a key={i}>{i}</a>)}
331
+ </div>
332
+ ) : null}
333
+ </main>
334
+ );
335
+ }
336
+ `;
337
+ const app = evalApp(transform(src, { mode: "hydrate" }));
338
+ runtime.pushHydrationNodes([]);
339
+ const root = app() as Element;
340
+ runtime.popHydrationNodes();
341
+ const host = document.createElement("div");
342
+ host.append(root);
343
+ const input = host.querySelector("input.q");
344
+ expect(host.querySelectorAll("a").length).toBe(2);
345
+ (globalThis as { __keyedSet?: (v: string[]) => void }).__keyedSet!(["a", "b", "c"]);
346
+ await new Promise((r) => setTimeout(r, 0));
347
+ expect(host.querySelectorAll("a").length).toBe(3);
348
+ expect(host.querySelector("input.q")).toBe(input);
349
+ });
350
+
351
+ test("a helper that builds JSX, called with a prop, hydrates as nodes", () => {
352
+ // Regression: {tab("a", props.count)} read a prop, so it was taken for
353
+ // text and hydrated as textContent = String(<a>): the link's URL
354
+ // appeared next to it
355
+ const src = `
356
+ export const App = (props) => {
357
+ const tab = (id, label, count) => (
358
+ <a href={"/x/" + id} class="tab">
359
+ {label} {count !== undefined ? <span class="count">{count}</span> : null}
360
+ </a>
361
+ );
362
+ return <nav>{tab("a", "First", props.count)}{tab("b", "Second", 2)}</nav>;
363
+ };
364
+ `;
365
+ const props = { count: 3 };
366
+ const html = String(evalApp(transform(src, { mode: "ssr" }))(props));
367
+ const host = document.createElement("div");
368
+ host.innerHTML = html;
369
+ const app = evalApp(transform(src, { mode: "hydrate" })) as (p: typeof props) => unknown;
370
+ runtime.pushHydrationNodes(Array.from(host.childNodes));
371
+ app(props);
372
+ runtime.popHydrationNodes();
373
+ runtime.flushDeferredEffects?.();
374
+ expect(host.textContent).not.toContain("/x/");
375
+ expect(host.querySelectorAll("a.tab").length).toBe(2);
376
+ expect(host.querySelector("a.tab")!.textContent).toContain("First");
377
+ // and the call isn't a text node in the output any more
378
+ expect(transform(src, { mode: "hydrate" })).not.toContain("String(tab(");
379
+ });
380
+ });