@sigil-dev/compiler 0.9.26 → 0.9.27

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,685 +1,750 @@
1
- import { type PluginObject, types as t, template } from "@babel/core";
2
- import { handleDerived } from "./handlers/dom/derived.ts";
3
- import { handleEffect } from "./handlers/dom/effect.ts";
4
- import { handleState } from "./handlers/dom/state.ts";
5
- import { handleDerivedSSR } from "./handlers/ssr/derived.ts";
6
- import { handleStateSSR } from "./handlers/ssr/state.ts";
7
- import { processElement, processFragment } from "./jsx/index.ts";
8
- import { processElementSSR, processFragmentSSR } from "./jsx/ssr.ts";
9
- import { markStaticUses } from "../analysis/hydration.ts";
10
- import { SignalScope } from "./jsx/utils.ts";
11
- import { warnDeadReactivity } from "./util/dead-code.ts";
12
- import { collectReactiveFns } from "./util/reactive-fns.ts";
13
- import { compileState } from "./util/compile-state.ts";
14
- import { applyStaticAssertions } from "./util/static-assertion.ts";
15
- import { getMacro } from "./util/helpers.ts";
16
- import { MAGIC } from "./util/magic.ts";
17
- import {
18
- collectImportRoots,
19
- importRoots,
20
- liftDestructuredProps,
21
- propObjects,
22
- rewriteImportReads,
23
- } from "./util/props.ts";
24
-
25
- const SSR_HELPERS = template.statements.ast(`
26
- const __SAFE = Symbol.for('sigil.safe');
27
- class __H {
28
- constructor(v) { this.v = v; this[__SAFE] = true; }
29
- toString() { return this.v; }
30
- }
31
- const __h = (v) => {
32
- if (v?.[__SAFE]) return v;
33
- if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
34
- return new __H(String(v ?? ''));
35
- };
36
- const __r = (v, tag) => {
37
- if (v === false || v === null || v === undefined) return '';
38
- return String(v).replace(new RegExp('</(' + tag + ')', 'gi'), '<\\\\/$1');
39
- };
40
- const __e = (v) => {
41
- if (v?.[__SAFE]) return v.v;
42
- if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
43
- if (v === false || v === null || v === undefined) return '';
44
- return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
45
- };
46
- // Keep in sync with cssName/cssValue/UNITLESS in @sigil-dev/runtime.
47
- const __UNITLESS = new Set(['animation-iteration-count','aspect-ratio','border-image-outset','border-image-slice','border-image-width','column-count','columns','fill-opacity','flex','flex-grow','flex-shrink','flood-opacity','font-weight','grid-area','grid-column','grid-column-end','grid-column-start','grid-row','grid-row-end','grid-row-start','line-clamp','line-height','opacity','order','orphans','scale','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-miterlimit','stroke-opacity','stroke-width','tab-size','widows','z-index','zoom']);
48
- const __css = (v) => {
49
- if (v === null || v === undefined || v === false) return '';
50
- if (typeof v !== 'object') return String(v);
51
- return Object.entries(v).map(([k, val]) => {
52
- let name = k.startsWith('--') ? k : k.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
53
- if (name.startsWith('ms-')) name = '-' + name;
54
- if (val === null || val === undefined || val === false || val === '') return '';
55
- if (typeof val === 'number' && val !== 0 && !name.startsWith('--') && !__UNITLESS.has(name)) val = val + 'px';
56
- return name + ':' + val;
57
- }).filter(Boolean).join(';');
58
- };
59
- // One attribute. null/undefined drop it; booleans are presence for plain
60
- // names (checked, hidden) and spelled out for dashed ones (aria-hidden).
61
- const __a = (n, v) => {
62
- if (v === null || v === undefined) return '';
63
- if (n === 'style') { const c = __css(v); return c ? ' style="' + __e(c) + '"' : ''; }
64
- if (typeof v === 'boolean') return n.includes('-') ? ' ' + n + '="' + v + '"' : v ? ' ' + n : '';
65
- return ' ' + n + '="' + __e(v) + '"';
66
- };
67
- const __SPREAD_ATTR = { className: 'class', htmlFor: 'for' };
68
- // <div {...props}>: what the client's spread() would set, as HTML.
69
- const __s = (o) => {
70
- if (!o) return '';
71
- let out = '';
72
- for (const [k, v] of Object.entries(o)) {
73
- if (typeof v === 'function' || k === 'children' || k === 'key' || k === 'innerHTML') continue;
74
- out += __a(__SPREAD_ATTR[k] ?? k, v);
75
- }
76
- return out;
77
- };
78
- // <select value={v}>: mark the matching <option>s selected.
79
- const __sel = (html, v) => {
80
- if (v === null || v === undefined) return html;
81
- const want = new Set((Array.isArray(v) ? v : [v]).map(__e));
82
- return html.replace(/<option\\b[^>]*>/g, (tag) => {
83
- const m = / value="([^"]*)"/.exec(tag);
84
- return m && want.has(m[1]) && !/ selected[ >=]/.test(tag) ? tag.slice(0, -1) + ' selected>' : tag;
85
- });
86
- };
87
- `);
88
- /**
89
- * Recursively convert key={expr} to data-key={expr} in JSX tree.
90
- * Needed for SSR output so hydration can map items by key.
91
- */
92
- function convertKeyToDataKey(node: t.JSXElement): void {
93
- for (let i = 0; i < node.openingElement.attributes.length; i++) {
94
- const attr = node.openingElement.attributes[i];
95
- if (
96
- t.isJSXAttribute(attr) &&
97
- t.isJSXIdentifier(attr.name) &&
98
- attr.name.name === "key"
99
- ) {
100
- node.openingElement.attributes[i] = t.jsxAttribute(
101
- t.jsxIdentifier("data-key"),
102
- attr.value,
103
- );
104
- }
105
- }
106
- for (const child of node.children) {
107
- if (t.isJSXElement(child)) {
108
- convertKeyToDataKey(child);
109
- } else if (
110
- t.isJSXExpressionContainer(child) &&
111
- t.isJSXElement(child.expression)
112
- ) {
113
- convertKeyToDataKey(child.expression);
114
- }
115
- }
116
- }
117
-
118
- interface SigilOptions {
119
- hash?: string;
120
- mode?: "dom" | "ssr" | "hydrate";
121
- dev?: boolean;
122
- }
123
-
124
- export default function sigilPlugin(): PluginObject {
125
- const signals = new SignalScope();
126
- const storeSignals = new Set<string>();
127
- const asyncFunctions = new Map<string, any>();
128
-
129
- let scopedHash: string | undefined;
130
- let isSSR = false;
131
- let isHydrate = false;
132
- let didTransform = false;
133
-
134
- let isDev = false;
135
- let filename = "";
136
-
137
- let asyncDefaultPath: any = null;
138
- let _asyncDefaultRef: string | null = null;
139
- let hasLoadingExport = false;
140
- let hasErrorExport = false;
141
-
142
- return {
143
- name: "sigil",
144
- visitor: {
145
- Program: {
146
- enter(path, state) {
147
- signals.clear();
148
- storeSignals.clear();
149
- propObjects.clear();
150
- importRoots.clear();
151
- const opts = (state.opts || {}) as SigilOptions;
152
- scopedHash = opts.hash;
153
- didTransform = false;
154
- isSSR = opts.mode === "ssr";
155
- isHydrate = opts.mode === "hydrate";
156
- isDev = opts.dev ?? false;
157
- filename = state.filename ?? "";
158
- asyncDefaultPath = null;
159
- hasLoadingExport = false;
160
- hasErrorExport = false;
161
- _asyncDefaultRef = null;
162
- asyncFunctions.clear();
163
-
164
- // Before any rewriting, and in every mode: server and browser
165
- // builds must agree on the verdict.
166
- applyStaticAssertions(path, filename, state.file.code);
167
- // Which uses produce only HTML: the server fences them, the
168
- // browser skips them. Not in `dom` mode, which hydrates nothing.
169
- compileState.dev = isDev;
170
- if (opts.mode === "ssr" || opts.mode === "hydrate") {
171
- markStaticUses(path, filename, state.file.code);
172
- }
173
-
174
- if (isSSR) {
175
- path.unshiftContainer("body", SSR_HELPERS);
176
- return;
177
- }
178
- liftDestructuredProps(path, signals);
179
- collectReactiveFns(path, signals);
180
- collectImportRoots(path);
181
- if (rewriteImportReads(path)) didTransform = true;
182
- },
183
- exit(path, state) {
184
- warnDeadReactivity(
185
- path,
186
- signals,
187
- new Set([...storeSignals, ...propObjects]),
188
- state.filename,
189
- );
190
-
191
- if (asyncDefaultPath && !isSSR) {
192
- let fnNode: t.FunctionDeclaration;
193
-
194
- if (asyncDefaultPath.isExportDefaultDeclaration()) {
195
- // export default async function Page() {}
196
- fnNode = asyncDefaultPath.get("declaration")
197
- .node as t.FunctionDeclaration;
198
- } else {
199
- // async function Page() {} + export default Page
200
- fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
201
- }
202
-
203
- const originalName = fnNode.id?.name ?? "Component";
204
- const privateName = `__${originalName}`;
205
- const propsId = t.identifier("__props");
206
-
207
- const privateFn = t.functionDeclaration(
208
- t.identifier(privateName),
209
- fnNode.params,
210
- fnNode.body,
211
- false,
212
- true,
213
- );
214
-
215
- const wrapperExport = t.exportDefaultDeclaration(
216
- t.functionDeclaration(
217
- t.identifier(originalName),
218
- [propsId],
219
- t.blockStatement([
220
- t.returnStatement(
221
- t.callExpression(t.identifier("__asyncBoundary"), [
222
- t.arrowFunctionExpression(
223
- [],
224
- t.callExpression(t.identifier(privateName), [propsId]),
225
- ),
226
- hasLoadingExport
227
- ? t.identifier("loading")
228
- : t.identifier("undefined"),
229
- hasErrorExport
230
- ? t.identifier("error")
231
- : t.identifier("undefined"),
232
- ]),
233
- ),
234
- ]),
235
- ),
236
- );
237
-
238
- asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
239
- didTransform = true;
240
- }
241
-
242
- // Only inject runtime import if this file actually used sigil transforms
243
- if (!didTransform || isSSR) return;
244
-
245
- const requiredSpecifiers = [
246
- "createSignal",
247
- "createRawSignal",
248
- "createEffect",
249
- "createMemo",
250
- "reconcile",
251
- "claim",
252
- "claimText",
253
- "claimComment",
254
- "hydrateKeyedList",
255
- "hydrateSlot",
256
- "insert",
257
- "applyDirective",
258
- "getHydrationNodes",
259
- "pushHydrationNodes",
260
- "popHydrationNodes",
261
- "snapshot",
262
- "tracking",
263
- "untrack",
264
- "createRoot",
265
- "createEffectPre",
266
- "createInspectEffect",
267
- "withEffectScope",
268
- "mountTransition",
269
- "removeAnimated",
270
- "setProp",
271
- "setStyleProp",
272
- "spread",
273
- "isClaimed",
274
- "liveSlot",
275
- "readStore",
276
- "skipStatic",
277
- "probeStatic",
278
- ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
279
- ];
280
- const runtimeImport = path.node.body.find(
281
- (n): n is t.ImportDeclaration =>
282
- t.isImportDeclaration(n) &&
283
- n.source.value === "@sigil-dev/runtime",
284
- );
285
-
286
- if (runtimeImport) {
287
- // console.log(
288
- // "[sigil exit] found existing import, specifier count:",
289
- // runtimeImport.specifiers.length,
290
- // );
291
- const existingNames = new Set(
292
- runtimeImport.specifiers
293
- .filter(t.isImportSpecifier)
294
- .map((s) =>
295
- t.isIdentifier(s.imported)
296
- ? s.imported.name
297
- : (s.imported as t.StringLiteral).value,
298
- ),
299
- );
300
- for (const name of requiredSpecifiers) {
301
- if (!existingNames.has(name)) {
302
- runtimeImport.specifiers.push(
303
- t.importSpecifier(t.identifier(name), t.identifier(name)),
304
- );
305
- }
306
- }
307
- } else {
308
- path.unshiftContainer(
309
- "body",
310
- t.importDeclaration(
311
- requiredSpecifiers.map((name) =>
312
- t.importSpecifier(t.identifier(name), t.identifier(name)),
313
- ),
314
- t.stringLiteral("@sigil-dev/runtime"),
315
- ),
316
- );
317
- }
318
- },
319
- },
320
- VariableDeclaration(path) {
321
- for (const declarator of path.get("declarations")) {
322
- const macro = getMacro(declarator);
323
- if (!macro) continue;
324
- didTransform = true;
325
- const { name, init } = macro;
326
- const varName = t.isIdentifier(declarator.node.id)
327
- ? declarator.node.id.name
328
- : null;
329
-
330
- if (name === "$state" || name === "$store" || name === "$state.raw") {
331
- isSSR
332
- ? handleStateSSR(path, declarator, init, signals)
333
- : handleState(
334
- path,
335
- declarator,
336
- init,
337
- signals,
338
- isDev,
339
- filename,
340
- name === "$state.raw",
341
- );
342
- if (name === "$store" && varName) {
343
- storeSignals.add(varName);
344
- }
345
- } else if (name === "$derived") {
346
- isSSR
347
- ? handleDerivedSSR(path, declarator, init, signals)
348
- : handleDerived(path, declarator, init, signals);
349
- }
350
- }
351
- },
352
- ExpressionStatement(path) {
353
- if (isSSR) {
354
- // drop $effect, $inspect, and $debug entirely in SSR
355
- const expr = path.get("expression");
356
- if (expr.isCallExpression()) {
357
- const callee = expr.get("callee");
358
- if (
359
- callee.isIdentifier() &&
360
- (callee.node.name === "$effect" ||
361
- callee.node.name === "$inspect" ||
362
- callee.node.name === "$debug")
363
- ) {
364
- didTransform = true;
365
- path.remove();
366
- }
367
- }
368
- return;
369
- }
370
- handleEffect(path);
371
- // Handle $debug(expr) expression statements
372
- const expr = path.get("expression");
373
- if (expr.isCallExpression()) {
374
- const callee = expr.get("callee");
375
- if (callee.isIdentifier({ name: "$debug" })) {
376
- didTransform = true;
377
- path.replaceWith(
378
- t.ifStatement(
379
- t.memberExpression(
380
- t.memberExpression(
381
- t.memberExpression(
382
- t.identifier("import"),
383
- t.identifier("meta"),
384
- ),
385
- t.identifier("env"),
386
- ),
387
- t.identifier("DEV"),
388
- ),
389
- t.blockStatement([
390
- t.debuggerStatement(),
391
- t.expressionStatement(
392
- t.callExpression(
393
- t.memberExpression(
394
- t.identifier("console"),
395
- t.identifier("log"),
396
- ),
397
- expr.node.arguments,
398
- ),
399
- ),
400
- ]),
401
- ),
402
- );
403
- }
404
- }
405
- },
406
- CallExpression(path) {
407
- if (isSSR) return;
408
- const callee = path.get("callee");
409
-
410
- // Helper: wrap signal identifiers in call expressions
411
- const wrapSignal = (expr: t.Expression): t.Expression => {
412
- if (t.isIdentifier(expr) && signals.has(expr.name)) {
413
- return t.callExpression(expr, []);
414
- }
415
- return expr;
416
- };
417
-
418
- // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
419
- if (callee.isMemberExpression()) {
420
- const object = callee.get("object");
421
- const property = callee.get("property");
422
- if (object.isIdentifier() && property.isIdentifier()) {
423
- const obj = object.node.name;
424
- const prop = property.node.name;
425
-
426
- if (obj === "$state" && prop === "snapshot") {
427
- didTransform = true;
428
- path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
429
- return;
430
- }
431
-
432
- if (obj === "$effect" && prop === "tracking") {
433
- didTransform = true;
434
- path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
435
- return;
436
- }
437
-
438
- if (obj === "$effect" && prop === "pre") {
439
- didTransform = true;
440
- path
441
- .get("callee")
442
- .replaceWith(t.identifier(MAGIC.createEffectPre));
443
- return;
444
- }
445
- }
446
- }
447
-
448
- // Handle $inspect(count).with(cb) chain
449
- if (callee.isMemberExpression()) {
450
- const property = callee.get("property");
451
- if (property.isIdentifier({ name: "with" })) {
452
- const object = callee.get("object");
453
- if (object.isCallExpression()) {
454
- const innerCallee = object.get("callee");
455
- if (innerCallee.isIdentifier({ name: "$inspect" })) {
456
- didTransform = true;
457
- //@ts-expect-error Bizzare but it works if you read LSP
458
- const args = object.node.arguments.map(wrapSignal);
459
- const cb = path.node.arguments[0];
460
- path.replaceWith(
461
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
462
- t.arrowFunctionExpression([], t.arrayExpression(args)),
463
- //@ts-expect-error Bizzare but it works if you read LSP
464
- cb,
465
- ]),
466
- );
467
- return;
468
- }
469
- }
470
- }
471
- }
472
-
473
- // Handle standalone $debug(...) — not as expression statement
474
- if (callee.isIdentifier({ name: "$debug" })) {
475
- didTransform = true;
476
- path.replaceWith(
477
- t.ifStatement(
478
- t.memberExpression(
479
- t.memberExpression(
480
- t.memberExpression(
481
- t.identifier("import"),
482
- t.identifier("meta"),
483
- ),
484
- t.identifier("env"),
485
- ),
486
- t.identifier("DEV"),
487
- ),
488
- t.blockStatement([
489
- t.debuggerStatement(),
490
- t.expressionStatement(
491
- t.callExpression(
492
- t.memberExpression(
493
- t.identifier("console"),
494
- t.identifier("log"),
495
- ),
496
- path.node.arguments,
497
- ),
498
- ),
499
- ]),
500
- ),
501
- );
502
- return;
503
- }
504
-
505
- // Handle standalone $inspect(...)
506
- if (callee.isIdentifier({ name: "$inspect" })) {
507
- didTransform = true;
508
- //@ts-expect-error Bizzare but it works if you read LSP
509
- const args = path.node.arguments.map(wrapSignal);
510
- path.replaceWith(
511
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
512
- t.arrowFunctionExpression([], t.arrayExpression(args)),
513
- ]),
514
- );
515
- return;
516
- }
517
- },
518
- JSXElement(path) {
519
- didTransform = true;
520
- // console.log(
521
- // "[sigil] JSXElement visitor fired, parent:",
522
- // path.parentPath?.type,
523
- // "isSSR:", isSSR
524
- // );
525
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
526
- return;
527
- if (isSSR) {
528
- try {
529
- convertKeyToDataKey(path.node);
530
- path.replaceWith(
531
- t.callExpression(t.identifier("__h"), [
532
- processElementSSR(path.node, signals, scopedHash),
533
- ]),
534
- );
535
- } catch (e) {
536
- console.error("[sigil] processElementSSR threw:", path.toString());
537
- console.error(e);
538
- throw e;
539
- }
540
- return;
541
- }
542
-
543
- const statements: t.Statement[] = [];
544
- const genId = (() => {
545
- let i = 0;
546
- return () => `_el${i++}`;
547
- })();
548
-
549
- const root = processElement(
550
- path.node,
551
- statements,
552
- genId,
553
- signals,
554
- scopedHash,
555
- isHydrate,
556
- isHydrate ? "__nodes" : undefined,
557
- );
558
-
559
- const body: t.Statement[] = [];
560
-
561
- if (isHydrate) {
562
- // DECLARE __nodes locally — every IIFE owns its own context
563
- body.push(
564
- t.variableDeclaration("const", [
565
- t.variableDeclarator(
566
- t.identifier("__nodes"),
567
- t.callExpression(t.identifier("getHydrationNodes"), []),
568
- ),
569
- ]),
570
- );
571
- }
572
-
573
- body.push(...statements);
574
- body.push(t.returnStatement(t.identifier(root)));
575
-
576
- path.replaceWith(
577
- t.callExpression(
578
- t.arrowFunctionExpression([], t.blockStatement(body)),
579
- [],
580
- ),
581
- );
582
- },
583
- JSXFragment(path) {
584
- didTransform = true;
585
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
586
- return;
587
- if (isSSR) {
588
- path.replaceWith(
589
- t.callExpression(t.identifier("__h"), [
590
- processFragmentSSR(path.node, signals, scopedHash),
591
- ]),
592
- );
593
- return;
594
- }
595
-
596
- const statements: t.Statement[] = [];
597
- const genId = (() => {
598
- let i = 0;
599
- return () => `_el${i++}`;
600
- })();
601
-
602
- const root = processFragment(
603
- path.node,
604
- statements,
605
- genId,
606
- signals,
607
- scopedHash,
608
- isHydrate,
609
- isHydrate ? "__nodes" : undefined,
610
- );
611
-
612
- const body: t.Statement[] = [];
613
-
614
- if (isHydrate) {
615
- // DECLARE __nodes locally — every IIFE owns its own context
616
- body.push(
617
- t.variableDeclaration("const", [
618
- t.variableDeclarator(
619
- t.identifier("__nodes"),
620
- t.callExpression(t.identifier("getHydrationNodes"), []),
621
- ),
622
- ]),
623
- );
624
- }
625
-
626
- body.push(...statements);
627
- body.push(t.returnStatement(t.identifier(root)));
628
-
629
- path.replaceWith(
630
- t.callExpression(
631
- t.arrowFunctionExpression([], t.blockStatement(body)),
632
- [],
633
- ),
634
- );
635
- },
636
- FunctionDeclaration(path) {
637
- if (isSSR) return;
638
- const node = path.node;
639
- if (node.async && node.id) {
640
- asyncFunctions.set(node.id.name, path);
641
- }
642
- },
643
-
644
- ExportDefaultDeclaration(path) {
645
- const decl = path.get("declaration");
646
-
647
- // export default async function Page() {}
648
- if (
649
- (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
650
- (decl.node as any).async &&
651
- !isSSR
652
- ) {
653
- asyncDefaultPath = path;
654
- return;
655
- }
656
-
657
- // export default Page
658
- if (decl.isIdentifier() && !isSSR) {
659
- const name = (decl.node as t.Identifier).name;
660
- if (asyncFunctions.has(name)) {
661
- asyncDefaultPath = asyncFunctions.get(name);
662
- _asyncDefaultRef = name;
663
- }
664
- }
665
- },
666
-
667
- ExportNamedDeclaration(path) {
668
- const decl = path.get("declaration");
669
- if (decl.isFunctionDeclaration()) {
670
- const name = (decl.node as t.FunctionDeclaration).id?.name;
671
- if (name === "loading") hasLoadingExport = true;
672
- if (name === "error") hasErrorExport = true;
673
- }
674
- if (decl.isVariableDeclaration()) {
675
- for (const d of decl.node.declarations) {
676
- if (t.isIdentifier(d.id)) {
677
- if (d.id.name === "loading") hasLoadingExport = true;
678
- if (d.id.name === "error") hasErrorExport = true;
679
- }
680
- }
681
- }
682
- },
683
- },
684
- };
685
- }
1
+ import { type PluginObject, types as t, template } from "@babel/core";
2
+ import { handleDerived } from "./handlers/dom/derived.ts";
3
+ import { handleEffect } from "./handlers/dom/effect.ts";
4
+ import { handleState } from "./handlers/dom/state.ts";
5
+ import { handleDerivedSSR } from "./handlers/ssr/derived.ts";
6
+ import { handleStateSSR } from "./handlers/ssr/state.ts";
7
+ import { processElement, processFragment } from "./jsx/index.ts";
8
+ import { processElementSSR, processFragmentSSR } from "./jsx/ssr.ts";
9
+ import { createResolver, markStaticUses } from "../analysis/hydration.ts";
10
+ import { SignalScope } from "./jsx/utils.ts";
11
+ import { warnDeadReactivity } from "./util/dead-code.ts";
12
+ import { beginWarnings } from "./util/warn.ts";
13
+ import { warnShadowedGlobals } from "./util/shadowed-globals.ts";
14
+ import { importedSignals, rewriteStateImports } from "./util/state-imports.ts";
15
+ import { keepOwnerAcrossAwaits } from "./util/owner-awaits.ts";
16
+ import { collectReactiveFns } from "./util/reactive-fns.ts";
17
+ import { compileState } from "./util/compile-state.ts";
18
+ import { applyStaticAssertions } from "./util/static-assertion.ts";
19
+ import { SVG_ATTR } from "./util/svg-attrs.ts";
20
+ import { getMacro } from "./util/helpers.ts";
21
+ import { MAGIC } from "./util/magic.ts";
22
+ import {
23
+ collectImportRoots,
24
+ importRoots,
25
+ liftDestructuredProps,
26
+ propObjects,
27
+ } from "./util/props.ts";
28
+
29
+ const SSR_HELPERS = template.statements.ast(`
30
+ const __SAFE = Symbol.for('sigil.safe');
31
+ class __H {
32
+ constructor(v) { this.v = v; this[__SAFE] = true; }
33
+ toString() { return this.v; }
34
+ }
35
+ // Component children: rendered when the component outputs them, so
36
+ // inside its call and under its owner (context it sets reaches them).
37
+ class __L {
38
+ constructor(f) { this.f = f; this[__SAFE] = true; }
39
+ get v() { if (this.f) { this.c = __h(this.f()).v; this.f = null; } return this.c; }
40
+ toString() { return this.v; }
41
+ }
42
+ const __lazy = (f) => new __L(f);
43
+ const __h = (v) => {
44
+ if (v?.[__SAFE]) return v;
45
+ if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
46
+ return new __H(String(v ?? ''));
47
+ };
48
+ const __r = (v, tag) => {
49
+ if (v === false || v === null || v === undefined) return '';
50
+ return String(v).replace(new RegExp('</(' + tag + ')', 'gi'), '<\\\\/$1');
51
+ };
52
+ const __e = (v) => {
53
+ if (v?.[__SAFE]) return v.v;
54
+ if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
55
+ if (v === false || v === null || v === undefined) return '';
56
+ return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
57
+ };
58
+ // Keep in sync with cssName/cssValue/UNITLESS in @sigil-dev/runtime.
59
+ const __UNITLESS = new Set(['animation-iteration-count','aspect-ratio','border-image-outset','border-image-slice','border-image-width','column-count','columns','fill-opacity','flex','flex-grow','flex-shrink','flood-opacity','font-weight','grid-area','grid-column','grid-column-end','grid-column-start','grid-row','grid-row-end','grid-row-start','line-clamp','line-height','opacity','order','orphans','scale','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-miterlimit','stroke-opacity','stroke-width','tab-size','widows','z-index','zoom']);
60
+ const __css = (v) => {
61
+ if (v === null || v === undefined || v === false) return '';
62
+ if (typeof v !== 'object') return String(v);
63
+ return Object.entries(v).map(([k, val]) => {
64
+ let name = k.startsWith('--') ? k : k.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
65
+ if (name.startsWith('ms-')) name = '-' + name;
66
+ if (val === null || val === undefined || val === false || val === '') return '';
67
+ if (typeof val === 'number' && val !== 0 && !name.startsWith('--') && !__UNITLESS.has(name)) val = val + 'px';
68
+ return name + ':' + val;
69
+ }).filter(Boolean).join(';');
70
+ };
71
+ // One attribute. null/undefined drop it; booleans are presence for plain
72
+ // names (checked, hidden) and spelled out for dashed ones (aria-hidden).
73
+ const __a = (n, v) => {
74
+ if (v === null || v === undefined) return '';
75
+ if (n === 'style') { const c = __css(v); return c ? ' style="' + __e(c) + '"' : ''; }
76
+ if (typeof v === 'boolean') return n.includes('-') ? ' ' + n + '="' + v + '"' : v ? ' ' + n : '';
77
+ return ' ' + n + '="' + __e(v) + '"';
78
+ };
79
+ const __SPREAD_ATTR = ${JSON.stringify({ className: "class", htmlFor: "for", ...SVG_ATTR })};
80
+ // <div {...props}>: what the client's spread() would set, as HTML.
81
+ const __s = (o) => {
82
+ if (!o) return '';
83
+ let out = '';
84
+ for (const [k, v] of Object.entries(o)) {
85
+ if (typeof v === 'function' || k === 'children' || k === 'key' || k === 'innerHTML') continue;
86
+ out += __a(__SPREAD_ATTR[k] ?? k, v);
87
+ }
88
+ return out;
89
+ };
90
+ // <select value={v}>: mark the matching <option>s selected.
91
+ const __sel = (html, v) => {
92
+ if (v === null || v === undefined) return html;
93
+ const want = new Set((Array.isArray(v) ? v : [v]).map(__e));
94
+ return html.replace(/<option\\b[^>]*>/g, (tag) => {
95
+ const m = / value="([^"]*)"/.exec(tag);
96
+ return m && want.has(m[1]) && !/ selected[ >=]/.test(tag) ? tag.slice(0, -1) + ' selected>' : tag;
97
+ });
98
+ };
99
+ `);
100
+ /**
101
+ * Recursively convert key={expr} to data-key={expr} in JSX tree.
102
+ * Needed for SSR output so hydration can map items by key.
103
+ */
104
+ function convertKeyToDataKey(node: t.JSXElement): void {
105
+ for (let i = 0; i < node.openingElement.attributes.length; i++) {
106
+ const attr = node.openingElement.attributes[i];
107
+ if (
108
+ t.isJSXAttribute(attr) &&
109
+ t.isJSXIdentifier(attr.name) &&
110
+ attr.name.name === "key"
111
+ ) {
112
+ node.openingElement.attributes[i] = t.jsxAttribute(
113
+ t.jsxIdentifier("data-key"),
114
+ attr.value,
115
+ );
116
+ }
117
+ }
118
+ for (const child of node.children) {
119
+ if (t.isJSXElement(child)) {
120
+ convertKeyToDataKey(child);
121
+ } else if (
122
+ t.isJSXExpressionContainer(child) &&
123
+ t.isJSXElement(child.expression)
124
+ ) {
125
+ convertKeyToDataKey(child.expression);
126
+ }
127
+ }
128
+ }
129
+
130
+ interface SigilOptions {
131
+ hash?: string;
132
+ mode?: "dom" | "ssr" | "hydrate";
133
+ dev?: boolean;
134
+ /** Import aliases, prefix to absolute directory (`{ $lib: "/app/src/lib" }`). */
135
+ aliases?: Record<string, string>;
136
+ }
137
+
138
+ export default function sigilPlugin(): PluginObject {
139
+ const signals = new SignalScope();
140
+ const storeSignals = new Set<string>();
141
+ const asyncFunctions = new Map<string, any>();
142
+
143
+ let scopedHash: string | undefined;
144
+ let isSSR = false;
145
+ let isHydrate = false;
146
+ let didTransform = false;
147
+
148
+ let isDev = false;
149
+ let filename = "";
150
+
151
+ let asyncDefaultPath: any = null;
152
+ let _asyncDefaultRef: string | null = null;
153
+ let hasLoadingExport = false;
154
+ let hasErrorExport = false;
155
+
156
+ return {
157
+ name: "sigil",
158
+ visitor: {
159
+ Program: {
160
+ enter(path, state) {
161
+ signals.clear();
162
+ storeSignals.clear();
163
+ propObjects.clear();
164
+ importRoots.clear();
165
+ const opts = (state.opts || {}) as SigilOptions;
166
+ scopedHash = opts.hash;
167
+ didTransform = false;
168
+ isSSR = opts.mode === "ssr";
169
+ isHydrate = opts.mode === "hydrate";
170
+ isDev = opts.dev ?? false;
171
+ filename = state.filename ?? "";
172
+ compileState.file = filename;
173
+ beginWarnings(filename, opts.mode ?? "dom");
174
+ asyncDefaultPath = null;
175
+ hasLoadingExport = false;
176
+ hasErrorExport = false;
177
+ _asyncDefaultRef = null;
178
+ asyncFunctions.clear();
179
+
180
+ // Before any rewriting, and in every mode: server and browser
181
+ // builds must agree on the verdict.
182
+ applyStaticAssertions(path, filename, state.file.code);
183
+ warnShadowedGlobals(path, filename);
184
+ // Which uses produce only HTML: the server fences them, the
185
+ // browser skips them. Not in `dom` mode, which hydrates nothing.
186
+ compileState.dev = isDev;
187
+ const resolve = createResolver(opts.aliases);
188
+ if (opts.mode === "ssr" || opts.mode === "hydrate") {
189
+ markStaticUses(path, filename, state.file.code, resolve);
190
+ }
191
+ compileState.ssrImports.clear();
192
+ // an async component's code after an await keeps its owner
193
+ const ownerNames = keepOwnerAcrossAwaits(path);
194
+ if (ownerNames.length) {
195
+ didTransform = true;
196
+ for (const n of ownerNames) compileState.ssrImports.add(n);
197
+ }
198
+ // imported state reads like local state: `count` → `count()`
199
+ if (
200
+ rewriteStateImports(path, filename, signals, resolve, {
201
+ ssr: isSSR,
202
+ dev: isDev,
203
+ })
204
+ )
205
+ didTransform = true;
206
+
207
+ if (isSSR) {
208
+ path.unshiftContainer("body", SSR_HELPERS);
209
+ return;
210
+ }
211
+ liftDestructuredProps(path, signals);
212
+ collectReactiveFns(path, signals);
213
+ collectImportRoots(path);
214
+ },
215
+ exit(path, state) {
216
+ warnDeadReactivity(
217
+ path,
218
+ new Set([...storeSignals, ...propObjects, ...importedSignals]),
219
+ );
220
+
221
+ if (asyncDefaultPath && !isSSR) {
222
+ let fnNode: t.FunctionDeclaration;
223
+
224
+ if (asyncDefaultPath.isExportDefaultDeclaration()) {
225
+ // export default async function Page() {}
226
+ fnNode = asyncDefaultPath.get("declaration")
227
+ .node as t.FunctionDeclaration;
228
+ } else {
229
+ // async function Page() {} + export default Page
230
+ fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
231
+ }
232
+
233
+ const originalName = fnNode.id?.name ?? "Component";
234
+ const privateName = `__${originalName}`;
235
+ const propsId = t.identifier("__props");
236
+
237
+ const privateFn = t.functionDeclaration(
238
+ t.identifier(privateName),
239
+ fnNode.params,
240
+ fnNode.body,
241
+ false,
242
+ true,
243
+ );
244
+
245
+ const wrapperExport = t.exportDefaultDeclaration(
246
+ t.functionDeclaration(
247
+ t.identifier(originalName),
248
+ [propsId],
249
+ t.blockStatement([
250
+ t.returnStatement(
251
+ t.callExpression(t.identifier("__asyncBoundary"), [
252
+ t.arrowFunctionExpression(
253
+ [],
254
+ t.callExpression(t.identifier(privateName), [propsId]),
255
+ ),
256
+ hasLoadingExport
257
+ ? t.identifier("loading")
258
+ : t.identifier("undefined"),
259
+ hasErrorExport
260
+ ? t.identifier("error")
261
+ : t.identifier("undefined"),
262
+ ]),
263
+ ),
264
+ ]),
265
+ ),
266
+ );
267
+
268
+ asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
269
+ didTransform = true;
270
+ }
271
+
272
+ // Server output only needs the ownership helpers it calls
273
+ if (isSSR) {
274
+ const existing = path.node.body.find(
275
+ (n): n is t.ImportDeclaration =>
276
+ t.isImportDeclaration(n) &&
277
+ n.source.value === "@sigil-dev/runtime" &&
278
+ n.importKind !== "type",
279
+ );
280
+ const have = new Set(
281
+ existing?.specifiers.map((sp) => sp.local.name) ?? [],
282
+ );
283
+ const names = [...compileState.ssrImports].filter(
284
+ (n) => !have.has(n),
285
+ );
286
+ if (existing) {
287
+ for (const n of names)
288
+ existing.specifiers.push(
289
+ t.importSpecifier(t.identifier(n), t.identifier(n)),
290
+ );
291
+ } else if (names.length) {
292
+ path.unshiftContainer(
293
+ "body",
294
+ t.importDeclaration(
295
+ names.map((n) =>
296
+ t.importSpecifier(t.identifier(n), t.identifier(n)),
297
+ ),
298
+ t.stringLiteral("@sigil-dev/runtime"),
299
+ ),
300
+ );
301
+ }
302
+ return;
303
+ }
304
+ // Only inject runtime import if this file actually used sigil transforms
305
+ if (!didTransform) return;
306
+
307
+ const requiredSpecifiers = [
308
+ "createSignal",
309
+ "createRawSignal",
310
+ "createEffect",
311
+ "createMemo",
312
+ "reconcile",
313
+ "claim",
314
+ "claimText",
315
+ "claimComment",
316
+ "claimSlot",
317
+ "hydrateKeyedList",
318
+ "hydrateSlot",
319
+ "insert",
320
+ "applyDirective",
321
+ "getHydrationNodes",
322
+ "pushHydrationNodes",
323
+ "popHydrationNodes",
324
+ "snapshot",
325
+ "tracking",
326
+ "untrack",
327
+ "createRoot",
328
+ "createEffectPre",
329
+ "createInspectEffect",
330
+ "withEffectScope",
331
+ "mountTransition",
332
+ "removeAnimated",
333
+ "setProp",
334
+ "setStyleProp",
335
+ "spread",
336
+ "isClaimed",
337
+ "liveSlot",
338
+ "skipStatic",
339
+ "probeStatic",
340
+ "__component",
341
+ "getOwner",
342
+ "__resume",
343
+ ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
344
+ ];
345
+ const runtimeImport = path.node.body.find(
346
+ (n): n is t.ImportDeclaration =>
347
+ t.isImportDeclaration(n) &&
348
+ n.source.value === "@sigil-dev/runtime",
349
+ );
350
+
351
+ if (runtimeImport) {
352
+ // console.log(
353
+ // "[sigil exit] found existing import, specifier count:",
354
+ // runtimeImport.specifiers.length,
355
+ // );
356
+ const existingNames = new Set(
357
+ runtimeImport.specifiers
358
+ .filter(t.isImportSpecifier)
359
+ .map((s) =>
360
+ t.isIdentifier(s.imported)
361
+ ? s.imported.name
362
+ : (s.imported as t.StringLiteral).value,
363
+ ),
364
+ );
365
+ for (const name of requiredSpecifiers) {
366
+ if (!existingNames.has(name)) {
367
+ runtimeImport.specifiers.push(
368
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
369
+ );
370
+ }
371
+ }
372
+ } else {
373
+ path.unshiftContainer(
374
+ "body",
375
+ t.importDeclaration(
376
+ requiredSpecifiers.map((name) =>
377
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
378
+ ),
379
+ t.stringLiteral("@sigil-dev/runtime"),
380
+ ),
381
+ );
382
+ }
383
+ },
384
+ },
385
+ VariableDeclaration(path) {
386
+ for (const declarator of path.get("declarations")) {
387
+ const macro = getMacro(declarator);
388
+ if (!macro) continue;
389
+ didTransform = true;
390
+ const { name, init } = macro;
391
+ const varName = t.isIdentifier(declarator.node.id)
392
+ ? declarator.node.id.name
393
+ : null;
394
+
395
+ if (name === "$state" || name === "$store" || name === "$state.raw") {
396
+ isSSR
397
+ ? handleStateSSR(path, declarator, init, signals)
398
+ : handleState(
399
+ path,
400
+ declarator,
401
+ init,
402
+ signals,
403
+ isDev,
404
+ filename,
405
+ name === "$state.raw",
406
+ );
407
+ if (name === "$store" && varName) {
408
+ storeSignals.add(varName);
409
+ }
410
+ } else if (name === "$derived") {
411
+ isSSR
412
+ ? handleDerivedSSR(path, declarator, init, signals)
413
+ : handleDerived(path, declarator, init, signals);
414
+ }
415
+ }
416
+ },
417
+ ExpressionStatement(path) {
418
+ if (isSSR) {
419
+ // drop $effect, $inspect, and $debug entirely in SSR
420
+ const expr = path.get("expression");
421
+ if (expr.isCallExpression()) {
422
+ const callee = expr.get("callee");
423
+ if (
424
+ callee.isIdentifier() &&
425
+ (callee.node.name === "$effect" ||
426
+ callee.node.name === "$inspect" ||
427
+ callee.node.name === "$debug")
428
+ ) {
429
+ didTransform = true;
430
+ path.remove();
431
+ }
432
+ }
433
+ return;
434
+ }
435
+ handleEffect(path);
436
+ // Handle $debug(expr) expression statements
437
+ const expr = path.get("expression");
438
+ if (expr.isCallExpression()) {
439
+ const callee = expr.get("callee");
440
+ if (callee.isIdentifier({ name: "$debug" })) {
441
+ didTransform = true;
442
+ path.replaceWith(
443
+ t.ifStatement(
444
+ t.memberExpression(
445
+ t.memberExpression(
446
+ t.memberExpression(
447
+ t.identifier("import"),
448
+ t.identifier("meta"),
449
+ ),
450
+ t.identifier("env"),
451
+ ),
452
+ t.identifier("DEV"),
453
+ ),
454
+ t.blockStatement([
455
+ t.debuggerStatement(),
456
+ t.expressionStatement(
457
+ t.callExpression(
458
+ t.memberExpression(
459
+ t.identifier("console"),
460
+ t.identifier("log"),
461
+ ),
462
+ expr.node.arguments,
463
+ ),
464
+ ),
465
+ ]),
466
+ ),
467
+ );
468
+ }
469
+ }
470
+ },
471
+ CallExpression(path) {
472
+ if (isSSR) return;
473
+ const callee = path.get("callee");
474
+
475
+ // Helper: wrap signal identifiers in call expressions
476
+ const wrapSignal = (expr: t.Expression): t.Expression => {
477
+ if (t.isIdentifier(expr) && signals.has(expr.name)) {
478
+ return t.callExpression(expr, []);
479
+ }
480
+ return expr;
481
+ };
482
+
483
+ // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
484
+ if (callee.isMemberExpression()) {
485
+ const object = callee.get("object");
486
+ const property = callee.get("property");
487
+ if (object.isIdentifier() && property.isIdentifier()) {
488
+ const obj = object.node.name;
489
+ const prop = property.node.name;
490
+
491
+ if (obj === "$state" && prop === "snapshot") {
492
+ didTransform = true;
493
+ path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
494
+ return;
495
+ }
496
+
497
+ if (obj === "$effect" && prop === "tracking") {
498
+ didTransform = true;
499
+ path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
500
+ return;
501
+ }
502
+
503
+ if (obj === "$effect" && prop === "pre") {
504
+ didTransform = true;
505
+ path
506
+ .get("callee")
507
+ .replaceWith(t.identifier(MAGIC.createEffectPre));
508
+ return;
509
+ }
510
+ }
511
+ }
512
+
513
+ // Handle $inspect(count).with(cb) chain
514
+ if (callee.isMemberExpression()) {
515
+ const property = callee.get("property");
516
+ if (property.isIdentifier({ name: "with" })) {
517
+ const object = callee.get("object");
518
+ if (object.isCallExpression()) {
519
+ const innerCallee = object.get("callee");
520
+ if (innerCallee.isIdentifier({ name: "$inspect" })) {
521
+ didTransform = true;
522
+ //@ts-expect-error Bizzare but it works if you read LSP
523
+ const args = object.node.arguments.map(wrapSignal);
524
+ const cb = path.node.arguments[0];
525
+ path.replaceWith(
526
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
527
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
528
+ //@ts-expect-error Bizzare but it works if you read LSP
529
+ cb,
530
+ ]),
531
+ );
532
+ return;
533
+ }
534
+ }
535
+ }
536
+ }
537
+
538
+ // Handle standalone $debug(...) — not as expression statement
539
+ if (callee.isIdentifier({ name: "$debug" })) {
540
+ didTransform = true;
541
+ path.replaceWith(
542
+ t.ifStatement(
543
+ t.memberExpression(
544
+ t.memberExpression(
545
+ t.memberExpression(
546
+ t.identifier("import"),
547
+ t.identifier("meta"),
548
+ ),
549
+ t.identifier("env"),
550
+ ),
551
+ t.identifier("DEV"),
552
+ ),
553
+ t.blockStatement([
554
+ t.debuggerStatement(),
555
+ t.expressionStatement(
556
+ t.callExpression(
557
+ t.memberExpression(
558
+ t.identifier("console"),
559
+ t.identifier("log"),
560
+ ),
561
+ path.node.arguments,
562
+ ),
563
+ ),
564
+ ]),
565
+ ),
566
+ );
567
+ return;
568
+ }
569
+
570
+ // Handle standalone $inspect(...)
571
+ if (callee.isIdentifier({ name: "$inspect" })) {
572
+ didTransform = true;
573
+ //@ts-expect-error Bizzare but it works if you read LSP
574
+ const args = path.node.arguments.map(wrapSignal);
575
+ path.replaceWith(
576
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
577
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
578
+ ]),
579
+ );
580
+ return;
581
+ }
582
+ },
583
+ JSXElement(path) {
584
+ didTransform = true;
585
+ // console.log(
586
+ // "[sigil] JSXElement visitor fired, parent:",
587
+ // path.parentPath?.type,
588
+ // "isSSR:", isSSR
589
+ // );
590
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
591
+ return;
592
+ if (isSSR) {
593
+ try {
594
+ convertKeyToDataKey(path.node);
595
+ path.replaceWith(
596
+ t.callExpression(t.identifier("__h"), [
597
+ processElementSSR(path.node, signals, scopedHash),
598
+ ]),
599
+ );
600
+ } catch (e) {
601
+ console.error("[sigil] processElementSSR threw:", path.toString());
602
+ console.error(e);
603
+ throw e;
604
+ }
605
+ return;
606
+ }
607
+
608
+ const statements: t.Statement[] = [];
609
+ const genId = (() => {
610
+ let i = 0;
611
+ return () => `_el${i++}`;
612
+ })();
613
+
614
+ const root = processElement(
615
+ path.node,
616
+ statements,
617
+ genId,
618
+ signals,
619
+ scopedHash,
620
+ isHydrate,
621
+ isHydrate ? "__nodes" : undefined,
622
+ );
623
+
624
+ const body: t.Statement[] = [];
625
+
626
+ if (isHydrate) {
627
+ // DECLARE __nodes locally — every IIFE owns its own context
628
+ body.push(
629
+ t.variableDeclaration("const", [
630
+ t.variableDeclarator(
631
+ t.identifier("__nodes"),
632
+ t.callExpression(t.identifier("getHydrationNodes"), []),
633
+ ),
634
+ ]),
635
+ );
636
+ }
637
+
638
+ body.push(...statements);
639
+ body.push(t.returnStatement(t.identifier(root)));
640
+
641
+ path.replaceWith(
642
+ t.callExpression(
643
+ t.arrowFunctionExpression([], t.blockStatement(body)),
644
+ [],
645
+ ),
646
+ );
647
+ },
648
+ JSXFragment(path) {
649
+ didTransform = true;
650
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
651
+ return;
652
+ if (isSSR) {
653
+ path.replaceWith(
654
+ t.callExpression(t.identifier("__h"), [
655
+ processFragmentSSR(path.node, signals, scopedHash),
656
+ ]),
657
+ );
658
+ return;
659
+ }
660
+
661
+ const statements: t.Statement[] = [];
662
+ const genId = (() => {
663
+ let i = 0;
664
+ return () => `_el${i++}`;
665
+ })();
666
+
667
+ const root = processFragment(
668
+ path.node,
669
+ statements,
670
+ genId,
671
+ signals,
672
+ scopedHash,
673
+ isHydrate,
674
+ isHydrate ? "__nodes" : undefined,
675
+ );
676
+
677
+ const body: t.Statement[] = [];
678
+
679
+ if (isHydrate) {
680
+ // DECLARE __nodes locally — every IIFE owns its own context
681
+ body.push(
682
+ t.variableDeclaration("const", [
683
+ t.variableDeclarator(
684
+ t.identifier("__nodes"),
685
+ t.callExpression(t.identifier("getHydrationNodes"), []),
686
+ ),
687
+ ]),
688
+ );
689
+ }
690
+
691
+ body.push(...statements);
692
+ body.push(t.returnStatement(t.identifier(root)));
693
+
694
+ path.replaceWith(
695
+ t.callExpression(
696
+ t.arrowFunctionExpression([], t.blockStatement(body)),
697
+ [],
698
+ ),
699
+ );
700
+ },
701
+ FunctionDeclaration(path) {
702
+ if (isSSR) return;
703
+ const node = path.node;
704
+ if (node.async && node.id) {
705
+ asyncFunctions.set(node.id.name, path);
706
+ }
707
+ },
708
+
709
+ ExportDefaultDeclaration(path) {
710
+ const decl = path.get("declaration");
711
+
712
+ // export default async function Page() {}
713
+ if (
714
+ (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
715
+ (decl.node as any).async &&
716
+ !isSSR
717
+ ) {
718
+ asyncDefaultPath = path;
719
+ return;
720
+ }
721
+
722
+ // export default Page
723
+ if (decl.isIdentifier() && !isSSR) {
724
+ const name = (decl.node as t.Identifier).name;
725
+ if (asyncFunctions.has(name)) {
726
+ asyncDefaultPath = asyncFunctions.get(name);
727
+ _asyncDefaultRef = name;
728
+ }
729
+ }
730
+ },
731
+
732
+ ExportNamedDeclaration(path) {
733
+ const decl = path.get("declaration");
734
+ if (decl.isFunctionDeclaration()) {
735
+ const name = (decl.node as t.FunctionDeclaration).id?.name;
736
+ if (name === "loading") hasLoadingExport = true;
737
+ if (name === "error") hasErrorExport = true;
738
+ }
739
+ if (decl.isVariableDeclaration()) {
740
+ for (const d of decl.node.declarations) {
741
+ if (t.isIdentifier(d.id)) {
742
+ if (d.id.name === "loading") hasLoadingExport = true;
743
+ if (d.id.name === "error") hasErrorExport = true;
744
+ }
745
+ }
746
+ }
747
+ },
748
+ },
749
+ };
750
+ }