@sigil-dev/compiler 0.9.6 → 0.9.7

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,608 +1,614 @@
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 { warnDeadReactivity } from "./util/dead-code.ts";
10
- import { getMacro } from "./util/helpers.ts";
11
- import { MAGIC } from "./util/magic.ts";
12
-
13
- const SSR_HELPERS = template.statements.ast(`
14
- const __SAFE = Symbol.for('sigil.safe');
15
- class __H {
16
- constructor(v) { this.v = v; this[__SAFE] = true; }
17
- toString() { return this.v; }
18
- }
19
- const __h = (v) => {
20
- if (v?.[__SAFE]) return v;
21
- if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
22
- return new __H(String(v ?? ''));
23
- };
24
- const __e = (v) => {
25
- if (v?.[__SAFE]) return v.v;
26
- if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
27
- if (v === false || v === null || v === undefined) return '';
28
- if (typeof v === 'object' && v.constructor === Object) {
29
- const UNITLESS = new Set(['animationIterationCount','borderImageOutset','borderImageSlice','borderImageWidth','boxFlex','boxFlexGroup','boxSnapAfterPatch','boxSupress','columnCount','columnFlex','columnFlexGrow','columns','flexGrow','flexPositive','flexShrink','flexNegative','fontWeight','gridArea','gridRow','gridRowEnd','gridRowSpan','gridRowStart','gridColumn','gridColumnEnd','gridColumnSpan','gridColumnStart','lineClamp','lineHeight','opacity','order','orphans','tabSize','widows','zIndex','zoom','fillOpacity','floodOpacity','stopOpacity','strokeDasharray','strokeDashoffset','strokeMiterlimit','strokeOpacity','strokeWidth']);
30
- return Object.entries(v).map(([k, val]) => {
31
- const prop = k.replace(/([A-Z])/g, '-$1').toLowerCase();
32
- if (typeof val === 'number' && !UNITLESS.has(k)) return prop + ':' + val + 'px';
33
- return prop + ':' + val;
34
- }).join(';');
35
- }
36
- return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
37
- };
38
- `);
39
- /**
40
- * Recursively convert key={expr} to data-key={expr} in JSX tree.
41
- * Needed for SSR output so hydration can map items by key.
42
- */
43
- function convertKeyToDataKey(node: t.JSXElement): void {
44
- for (let i = 0; i < node.openingElement.attributes.length; i++) {
45
- const attr = node.openingElement.attributes[i];
46
- if (
47
- t.isJSXAttribute(attr) &&
48
- t.isJSXIdentifier(attr.name) &&
49
- attr.name.name === "key"
50
- ) {
51
- node.openingElement.attributes[i] = t.jsxAttribute(
52
- t.jsxIdentifier("data-key"),
53
- attr.value,
54
- );
55
- }
56
- }
57
- for (const child of node.children) {
58
- if (t.isJSXElement(child)) {
59
- convertKeyToDataKey(child);
60
- } else if (
61
- t.isJSXExpressionContainer(child) &&
62
- t.isJSXElement(child.expression)
63
- ) {
64
- convertKeyToDataKey(child.expression);
65
- }
66
- }
67
- }
68
-
69
- interface SigilOptions {
70
- hash?: string;
71
- mode?: "dom" | "ssr" | "hydrate";
72
- dev?: boolean;
73
- }
74
-
75
- export default function sigilPlugin(): PluginObject {
76
- const signals = new Set<string>();
77
- const storeSignals = new Set<string>();
78
- const asyncFunctions = new Map<string, any>();
79
-
80
- let scopedHash: string | undefined;
81
- let isSSR = false;
82
- let isHydrate = false;
83
- let didTransform = false;
84
-
85
- let isDev = false;
86
- let filename = "";
87
-
88
- let asyncDefaultPath: any = null;
89
- let _asyncDefaultRef: string | null = null;
90
- let hasLoadingExport = false;
91
- let hasErrorExport = false;
92
-
93
- return {
94
- name: "sigil",
95
- visitor: {
96
- Program: {
97
- enter(path, state) {
98
- signals.clear();
99
- storeSignals.clear();
100
- const opts = (state.opts || {}) as SigilOptions;
101
- scopedHash = opts.hash;
102
- didTransform = false;
103
- isSSR = opts.mode === "ssr";
104
- isHydrate = opts.mode === "hydrate";
105
- isDev = opts.dev ?? false;
106
- filename = state.filename ?? "";
107
- asyncDefaultPath = null;
108
- hasLoadingExport = false;
109
- hasErrorExport = false;
110
- _asyncDefaultRef = null;
111
- asyncFunctions.clear();
112
-
113
- if (isSSR) {
114
- path.unshiftContainer("body", SSR_HELPERS);
115
- return;
116
- }
117
- },
118
- exit(path, state) {
119
- warnDeadReactivity(path, signals, storeSignals, state.filename);
120
-
121
- if (asyncDefaultPath && !isSSR) {
122
- let fnNode: t.FunctionDeclaration;
123
-
124
- if (asyncDefaultPath.isExportDefaultDeclaration()) {
125
- // export default async function Page() {}
126
- fnNode = asyncDefaultPath.get("declaration")
127
- .node as t.FunctionDeclaration;
128
- } else {
129
- // async function Page() {} + export default Page
130
- fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
131
- }
132
-
133
- const originalName = fnNode.id?.name ?? "Component";
134
- const privateName = `__${originalName}`;
135
- const propsId = t.identifier("__props");
136
-
137
- const privateFn = t.functionDeclaration(
138
- t.identifier(privateName),
139
- fnNode.params,
140
- fnNode.body,
141
- false,
142
- true,
143
- );
144
-
145
- const wrapperExport = t.exportDefaultDeclaration(
146
- t.functionDeclaration(
147
- t.identifier(originalName),
148
- [propsId],
149
- t.blockStatement([
150
- t.returnStatement(
151
- t.callExpression(t.identifier("__asyncBoundary"), [
152
- t.arrowFunctionExpression(
153
- [],
154
- t.callExpression(t.identifier(privateName), [propsId]),
155
- ),
156
- hasLoadingExport
157
- ? t.identifier("loading")
158
- : t.identifier("undefined"),
159
- hasErrorExport
160
- ? t.identifier("error")
161
- : t.identifier("undefined"),
162
- ]),
163
- ),
164
- ]),
165
- ),
166
- );
167
-
168
- asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
169
- didTransform = true;
170
- }
171
-
172
- // Only inject runtime import if this file actually used sigil transforms
173
- if (!didTransform || isSSR) return;
174
-
175
- const requiredSpecifiers = [
176
- "createSignal",
177
- "createRawSignal",
178
- "createEffect",
179
- "createMemo",
180
- "reconcile",
181
- "claim",
182
- "claimText",
183
- "claimComment",
184
- "hydrateKeyedList",
185
- "hydrateSlot",
186
- "insert",
187
- "applyDirective",
188
- "getHydrationNodes",
189
- "pushHydrationNodes",
190
- "popHydrationNodes",
191
- "snapshot",
192
- "tracking",
193
- "untrack",
194
- "createRoot",
195
- "createEffectPre",
196
- "createInspectEffect",
197
- "withEffectScope",
198
- "mountTransition",
199
- "removeAnimated",
200
- ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
201
- ];
202
- const runtimeImport = path.node.body.find(
203
- (n): n is t.ImportDeclaration =>
204
- t.isImportDeclaration(n) &&
205
- n.source.value === "@sigil-dev/runtime",
206
- );
207
-
208
- if (runtimeImport) {
209
- // console.log(
210
- // "[sigil exit] found existing import, specifier count:",
211
- // runtimeImport.specifiers.length,
212
- // );
213
- const existingNames = new Set(
214
- runtimeImport.specifiers
215
- .filter(t.isImportSpecifier)
216
- .map((s) =>
217
- t.isIdentifier(s.imported)
218
- ? s.imported.name
219
- : (s.imported as t.StringLiteral).value,
220
- ),
221
- );
222
- for (const name of requiredSpecifiers) {
223
- if (!existingNames.has(name)) {
224
- runtimeImport.specifiers.push(
225
- t.importSpecifier(t.identifier(name), t.identifier(name)),
226
- );
227
- }
228
- }
229
- } else {
230
- path.unshiftContainer(
231
- "body",
232
- t.importDeclaration(
233
- requiredSpecifiers.map((name) =>
234
- t.importSpecifier(t.identifier(name), t.identifier(name)),
235
- ),
236
- t.stringLiteral("@sigil-dev/runtime"),
237
- ),
238
- );
239
- }
240
- },
241
- },
242
- VariableDeclaration(path) {
243
- for (const declarator of path.get("declarations")) {
244
- const macro = getMacro(declarator);
245
- if (!macro) continue;
246
- didTransform = true;
247
- const { name, init } = macro;
248
- const varName = t.isIdentifier(declarator.node.id)
249
- ? declarator.node.id.name
250
- : null;
251
-
252
- if (name === "$state" || name === "$store" || name === "$state.raw") {
253
- if (name === "$state.raw") {
254
- if (!isSSR) {
255
- const args = init.node.arguments;
256
- init.replaceWith(
257
- t.callExpression(t.identifier(MAGIC.createRawSignal), args),
258
- );
259
- }
260
- continue;
261
- }
262
- isSSR
263
- ? handleStateSSR(path, declarator, init, signals)
264
- : handleState(path, declarator, init, signals, isDev, filename); // ← add
265
- if (name === "$store" && varName) {
266
- storeSignals.add(varName);
267
- }
268
- } else if (name === "$derived") {
269
- isSSR
270
- ? handleDerivedSSR(path, declarator, init, signals)
271
- : handleDerived(path, declarator, init, signals);
272
- }
273
- }
274
- },
275
- ExpressionStatement(path) {
276
- if (isSSR) {
277
- // drop $effect, $inspect, and $debug entirely in SSR
278
- const expr = path.get("expression");
279
- if (expr.isCallExpression()) {
280
- const callee = expr.get("callee");
281
- if (
282
- callee.isIdentifier() &&
283
- (callee.node.name === "$effect" ||
284
- callee.node.name === "$inspect" ||
285
- callee.node.name === "$debug")
286
- ) {
287
- didTransform = true;
288
- path.remove();
289
- }
290
- }
291
- return;
292
- }
293
- handleEffect(path);
294
- // Handle $debug(expr) expression statements
295
- const expr = path.get("expression");
296
- if (expr.isCallExpression()) {
297
- const callee = expr.get("callee");
298
- if (callee.isIdentifier({ name: "$debug" })) {
299
- didTransform = true;
300
- path.replaceWith(
301
- t.ifStatement(
302
- t.memberExpression(
303
- t.memberExpression(
304
- t.memberExpression(
305
- t.identifier("import"),
306
- t.identifier("meta"),
307
- ),
308
- t.identifier("env"),
309
- ),
310
- t.identifier("DEV"),
311
- ),
312
- t.blockStatement([
313
- t.debuggerStatement(),
314
- t.expressionStatement(
315
- t.callExpression(
316
- t.memberExpression(
317
- t.identifier("console"),
318
- t.identifier("log"),
319
- ),
320
- expr.node.arguments,
321
- ),
322
- ),
323
- ]),
324
- ),
325
- );
326
- }
327
- }
328
- },
329
- CallExpression(path) {
330
- if (isSSR) return;
331
- const callee = path.get("callee");
332
-
333
- // Helper: wrap signal identifiers in call expressions
334
- const wrapSignal = (expr: t.Expression): t.Expression => {
335
- if (t.isIdentifier(expr) && signals.has(expr.name)) {
336
- return t.callExpression(expr, []);
337
- }
338
- return expr;
339
- };
340
-
341
- // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
342
- if (callee.isMemberExpression()) {
343
- const object = callee.get("object");
344
- const property = callee.get("property");
345
- if (object.isIdentifier() && property.isIdentifier()) {
346
- const obj = object.node.name;
347
- const prop = property.node.name;
348
-
349
- if (obj === "$state" && prop === "snapshot") {
350
- didTransform = true;
351
- path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
352
- return;
353
- }
354
-
355
- if (obj === "$effect" && prop === "tracking") {
356
- didTransform = true;
357
- path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
358
- return;
359
- }
360
-
361
- if (obj === "$effect" && prop === "pre") {
362
- didTransform = true;
363
- path
364
- .get("callee")
365
- .replaceWith(t.identifier(MAGIC.createEffectPre));
366
- return;
367
- }
368
- }
369
- }
370
-
371
- // Handle $inspect(count).with(cb) chain
372
- if (callee.isMemberExpression()) {
373
- const property = callee.get("property");
374
- if (property.isIdentifier({ name: "with" })) {
375
- const object = callee.get("object");
376
- if (object.isCallExpression()) {
377
- const innerCallee = object.get("callee");
378
- if (innerCallee.isIdentifier({ name: "$inspect" })) {
379
- didTransform = true;
380
- //@ts-expect-error Bizzare but it works if you read LSP
381
- const args = object.node.arguments.map(wrapSignal);
382
- const cb = path.node.arguments[0];
383
- path.replaceWith(
384
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
385
- t.arrowFunctionExpression([], t.arrayExpression(args)),
386
- //@ts-expect-error Bizzare but it works if you read LSP
387
- cb,
388
- ]),
389
- );
390
- return;
391
- }
392
- }
393
- }
394
- }
395
-
396
- // Handle standalone $debug(...) — not as expression statement
397
- if (callee.isIdentifier({ name: "$debug" })) {
398
- didTransform = true;
399
- path.replaceWith(
400
- t.ifStatement(
401
- t.memberExpression(
402
- t.memberExpression(
403
- t.memberExpression(
404
- t.identifier("import"),
405
- t.identifier("meta"),
406
- ),
407
- t.identifier("env"),
408
- ),
409
- t.identifier("DEV"),
410
- ),
411
- t.blockStatement([
412
- t.debuggerStatement(),
413
- t.expressionStatement(
414
- t.callExpression(
415
- t.memberExpression(
416
- t.identifier("console"),
417
- t.identifier("log"),
418
- ),
419
- path.node.arguments,
420
- ),
421
- ),
422
- ]),
423
- ),
424
- );
425
- return;
426
- }
427
-
428
- // Handle standalone $inspect(...)
429
- if (callee.isIdentifier({ name: "$inspect" })) {
430
- didTransform = true;
431
- //@ts-expect-error Bizzare but it works if you read LSP
432
- const args = path.node.arguments.map(wrapSignal);
433
- path.replaceWith(
434
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
435
- t.arrowFunctionExpression([], t.arrayExpression(args)),
436
- ]),
437
- );
438
- return;
439
- }
440
- },
441
- JSXElement(path) {
442
- didTransform = true;
443
- // console.log(
444
- // "[sigil] JSXElement visitor fired, parent:",
445
- // path.parentPath?.type,
446
- // "isSSR:", isSSR
447
- // );
448
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
449
- return;
450
- if (isSSR) {
451
- try {
452
- convertKeyToDataKey(path.node);
453
- path.replaceWith(
454
- t.callExpression(t.identifier("__h"), [
455
- processElementSSR(path.node, signals),
456
- ]),
457
- );
458
- } catch (e) {
459
- console.error("[sigil] processElementSSR threw:", path.toString());
460
- console.error(e);
461
- throw e;
462
- }
463
- return;
464
- }
465
-
466
- const statements: t.Statement[] = [];
467
- const genId = (() => {
468
- let i = 0;
469
- return () => `_el${i++}`;
470
- })();
471
-
472
- const root = processElement(
473
- path.node,
474
- statements,
475
- genId,
476
- signals,
477
- scopedHash,
478
- isHydrate,
479
- isHydrate ? "__nodes" : undefined,
480
- );
481
-
482
- const body: t.Statement[] = [];
483
-
484
- if (isHydrate) {
485
- // DECLARE __nodes locally — every IIFE owns its own context
486
- body.push(
487
- t.variableDeclaration("const", [
488
- t.variableDeclarator(
489
- t.identifier("__nodes"),
490
- t.callExpression(t.identifier("getHydrationNodes"), []),
491
- ),
492
- ]),
493
- );
494
- }
495
-
496
- body.push(...statements);
497
- body.push(t.returnStatement(t.identifier(root)));
498
-
499
- path.replaceWith(
500
- t.callExpression(
501
- t.arrowFunctionExpression([], t.blockStatement(body)),
502
- [],
503
- ),
504
- );
505
- },
506
- JSXFragment(path) {
507
- didTransform = true;
508
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
509
- return;
510
- if (isSSR) {
511
- path.replaceWith(
512
- t.callExpression(t.identifier("__h"), [
513
- processFragmentSSR(path.node, signals),
514
- ]),
515
- );
516
- return;
517
- }
518
-
519
- const statements: t.Statement[] = [];
520
- const genId = (() => {
521
- let i = 0;
522
- return () => `_el${i++}`;
523
- })();
524
-
525
- const root = processFragment(
526
- path.node,
527
- statements,
528
- genId,
529
- signals,
530
- scopedHash,
531
- isHydrate,
532
- isHydrate ? "__nodes" : undefined,
533
- );
534
-
535
- const body: t.Statement[] = [];
536
-
537
- if (isHydrate) {
538
- // DECLARE __nodes locally — every IIFE owns its own context
539
- body.push(
540
- t.variableDeclaration("const", [
541
- t.variableDeclarator(
542
- t.identifier("__nodes"),
543
- t.callExpression(t.identifier("getHydrationNodes"), []),
544
- ),
545
- ]),
546
- );
547
- }
548
-
549
- body.push(...statements);
550
- body.push(t.returnStatement(t.identifier(root)));
551
-
552
- path.replaceWith(
553
- t.callExpression(
554
- t.arrowFunctionExpression([], t.blockStatement(body)),
555
- [],
556
- ),
557
- );
558
- },
559
- FunctionDeclaration(path) {
560
- if (isSSR) return;
561
- const node = path.node;
562
- if (node.async && node.id) {
563
- asyncFunctions.set(node.id.name, path);
564
- }
565
- },
566
-
567
- ExportDefaultDeclaration(path) {
568
- const decl = path.get("declaration");
569
-
570
- // export default async function Page() {}
571
- if (
572
- (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
573
- (decl.node as any).async &&
574
- !isSSR
575
- ) {
576
- asyncDefaultPath = path;
577
- return;
578
- }
579
-
580
- // export default Page
581
- if (decl.isIdentifier() && !isSSR) {
582
- const name = (decl.node as t.Identifier).name;
583
- if (asyncFunctions.has(name)) {
584
- asyncDefaultPath = asyncFunctions.get(name);
585
- _asyncDefaultRef = name;
586
- }
587
- }
588
- },
589
-
590
- ExportNamedDeclaration(path) {
591
- const decl = path.get("declaration");
592
- if (decl.isFunctionDeclaration()) {
593
- const name = (decl.node as t.FunctionDeclaration).id?.name;
594
- if (name === "loading") hasLoadingExport = true;
595
- if (name === "error") hasErrorExport = true;
596
- }
597
- if (decl.isVariableDeclaration()) {
598
- for (const d of decl.node.declarations) {
599
- if (t.isIdentifier(d.id)) {
600
- if (d.id.name === "loading") hasLoadingExport = true;
601
- if (d.id.name === "error") hasErrorExport = true;
602
- }
603
- }
604
- }
605
- },
606
- },
607
- };
608
- }
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 { warnDeadReactivity } from "./util/dead-code.ts";
10
+ import { getMacro } from "./util/helpers.ts";
11
+ import { MAGIC } from "./util/magic.ts";
12
+
13
+ const SSR_HELPERS = template.statements.ast(`
14
+ const __SAFE = Symbol.for('sigil.safe');
15
+ class __H {
16
+ constructor(v) { this.v = v; this[__SAFE] = true; }
17
+ toString() { return this.v; }
18
+ }
19
+ const __h = (v) => {
20
+ if (v?.[__SAFE]) return v;
21
+ if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
22
+ return new __H(String(v ?? ''));
23
+ };
24
+ const __b = (n, v) => {
25
+ if (v === true) return ' ' + n;
26
+ if (v === false || v === null || v === undefined) return '';
27
+ return ' ' + n + '="' + __e(v) + '"';
28
+ };
29
+ const __e = (v) => {
30
+ if (v?.[__SAFE]) return v.v;
31
+ if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
32
+ if (v === false || v === null || v === undefined) return '';
33
+ if (typeof v === 'object' && v.constructor === Object) {
34
+ const UNITLESS = new Set(['animationIterationCount','borderImageOutset','borderImageSlice','borderImageWidth','boxFlex','boxFlexGroup','boxSnapAfterPatch','boxSupress','columnCount','columnFlex','columnFlexGrow','columns','flexGrow','flexPositive','flexShrink','flexNegative','fontWeight','gridArea','gridRow','gridRowEnd','gridRowSpan','gridRowStart','gridColumn','gridColumnEnd','gridColumnSpan','gridColumnStart','lineClamp','lineHeight','opacity','order','orphans','tabSize','widows','zIndex','zoom','fillOpacity','floodOpacity','stopOpacity','strokeDasharray','strokeDashoffset','strokeMiterlimit','strokeOpacity','strokeWidth']);
35
+ return Object.entries(v).map(([k, val]) => {
36
+ const prop = k.replace(/([A-Z])/g, '-$1').toLowerCase();
37
+ if (typeof val === 'number' && !UNITLESS.has(k)) return prop + ':' + val + 'px';
38
+ return prop + ':' + val;
39
+ }).join(';');
40
+ }
41
+ return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
42
+ };
43
+ `);
44
+ /**
45
+ * Recursively convert key={expr} to data-key={expr} in JSX tree.
46
+ * Needed for SSR output so hydration can map items by key.
47
+ */
48
+ function convertKeyToDataKey(node: t.JSXElement): void {
49
+ for (let i = 0; i < node.openingElement.attributes.length; i++) {
50
+ const attr = node.openingElement.attributes[i];
51
+ if (
52
+ t.isJSXAttribute(attr) &&
53
+ t.isJSXIdentifier(attr.name) &&
54
+ attr.name.name === "key"
55
+ ) {
56
+ node.openingElement.attributes[i] = t.jsxAttribute(
57
+ t.jsxIdentifier("data-key"),
58
+ attr.value,
59
+ );
60
+ }
61
+ }
62
+ for (const child of node.children) {
63
+ if (t.isJSXElement(child)) {
64
+ convertKeyToDataKey(child);
65
+ } else if (
66
+ t.isJSXExpressionContainer(child) &&
67
+ t.isJSXElement(child.expression)
68
+ ) {
69
+ convertKeyToDataKey(child.expression);
70
+ }
71
+ }
72
+ }
73
+
74
+ interface SigilOptions {
75
+ hash?: string;
76
+ mode?: "dom" | "ssr" | "hydrate";
77
+ dev?: boolean;
78
+ }
79
+
80
+ export default function sigilPlugin(): PluginObject {
81
+ const signals = new Set<string>();
82
+ const storeSignals = new Set<string>();
83
+ const asyncFunctions = new Map<string, any>();
84
+
85
+ let scopedHash: string | undefined;
86
+ let isSSR = false;
87
+ let isHydrate = false;
88
+ let didTransform = false;
89
+
90
+ let isDev = false;
91
+ let filename = "";
92
+
93
+ let asyncDefaultPath: any = null;
94
+ let _asyncDefaultRef: string | null = null;
95
+ let hasLoadingExport = false;
96
+ let hasErrorExport = false;
97
+
98
+ return {
99
+ name: "sigil",
100
+ visitor: {
101
+ Program: {
102
+ enter(path, state) {
103
+ signals.clear();
104
+ storeSignals.clear();
105
+ const opts = (state.opts || {}) as SigilOptions;
106
+ scopedHash = opts.hash;
107
+ didTransform = false;
108
+ isSSR = opts.mode === "ssr";
109
+ isHydrate = opts.mode === "hydrate";
110
+ isDev = opts.dev ?? false;
111
+ filename = state.filename ?? "";
112
+ asyncDefaultPath = null;
113
+ hasLoadingExport = false;
114
+ hasErrorExport = false;
115
+ _asyncDefaultRef = null;
116
+ asyncFunctions.clear();
117
+
118
+ if (isSSR) {
119
+ path.unshiftContainer("body", SSR_HELPERS);
120
+ return;
121
+ }
122
+ },
123
+ exit(path, state) {
124
+ warnDeadReactivity(path, signals, storeSignals, state.filename);
125
+
126
+ if (asyncDefaultPath && !isSSR) {
127
+ let fnNode: t.FunctionDeclaration;
128
+
129
+ if (asyncDefaultPath.isExportDefaultDeclaration()) {
130
+ // export default async function Page() {}
131
+ fnNode = asyncDefaultPath.get("declaration")
132
+ .node as t.FunctionDeclaration;
133
+ } else {
134
+ // async function Page() {} + export default Page
135
+ fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
136
+ }
137
+
138
+ const originalName = fnNode.id?.name ?? "Component";
139
+ const privateName = `__${originalName}`;
140
+ const propsId = t.identifier("__props");
141
+
142
+ const privateFn = t.functionDeclaration(
143
+ t.identifier(privateName),
144
+ fnNode.params,
145
+ fnNode.body,
146
+ false,
147
+ true,
148
+ );
149
+
150
+ const wrapperExport = t.exportDefaultDeclaration(
151
+ t.functionDeclaration(
152
+ t.identifier(originalName),
153
+ [propsId],
154
+ t.blockStatement([
155
+ t.returnStatement(
156
+ t.callExpression(t.identifier("__asyncBoundary"), [
157
+ t.arrowFunctionExpression(
158
+ [],
159
+ t.callExpression(t.identifier(privateName), [propsId]),
160
+ ),
161
+ hasLoadingExport
162
+ ? t.identifier("loading")
163
+ : t.identifier("undefined"),
164
+ hasErrorExport
165
+ ? t.identifier("error")
166
+ : t.identifier("undefined"),
167
+ ]),
168
+ ),
169
+ ]),
170
+ ),
171
+ );
172
+
173
+ asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
174
+ didTransform = true;
175
+ }
176
+
177
+ // Only inject runtime import if this file actually used sigil transforms
178
+ if (!didTransform || isSSR) return;
179
+
180
+ const requiredSpecifiers = [
181
+ "createSignal",
182
+ "createRawSignal",
183
+ "createEffect",
184
+ "createMemo",
185
+ "reconcile",
186
+ "claim",
187
+ "claimText",
188
+ "claimComment",
189
+ "hydrateKeyedList",
190
+ "hydrateSlot",
191
+ "insert",
192
+ "applyDirective",
193
+ "getHydrationNodes",
194
+ "pushHydrationNodes",
195
+ "popHydrationNodes",
196
+ "snapshot",
197
+ "tracking",
198
+ "untrack",
199
+ "createRoot",
200
+ "createEffectPre",
201
+ "createInspectEffect",
202
+ "withEffectScope",
203
+ "mountTransition",
204
+ "removeAnimated",
205
+ "setProp",
206
+ ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
207
+ ];
208
+ const runtimeImport = path.node.body.find(
209
+ (n): n is t.ImportDeclaration =>
210
+ t.isImportDeclaration(n) &&
211
+ n.source.value === "@sigil-dev/runtime",
212
+ );
213
+
214
+ if (runtimeImport) {
215
+ // console.log(
216
+ // "[sigil exit] found existing import, specifier count:",
217
+ // runtimeImport.specifiers.length,
218
+ // );
219
+ const existingNames = new Set(
220
+ runtimeImport.specifiers
221
+ .filter(t.isImportSpecifier)
222
+ .map((s) =>
223
+ t.isIdentifier(s.imported)
224
+ ? s.imported.name
225
+ : (s.imported as t.StringLiteral).value,
226
+ ),
227
+ );
228
+ for (const name of requiredSpecifiers) {
229
+ if (!existingNames.has(name)) {
230
+ runtimeImport.specifiers.push(
231
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
232
+ );
233
+ }
234
+ }
235
+ } else {
236
+ path.unshiftContainer(
237
+ "body",
238
+ t.importDeclaration(
239
+ requiredSpecifiers.map((name) =>
240
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
241
+ ),
242
+ t.stringLiteral("@sigil-dev/runtime"),
243
+ ),
244
+ );
245
+ }
246
+ },
247
+ },
248
+ VariableDeclaration(path) {
249
+ for (const declarator of path.get("declarations")) {
250
+ const macro = getMacro(declarator);
251
+ if (!macro) continue;
252
+ didTransform = true;
253
+ const { name, init } = macro;
254
+ const varName = t.isIdentifier(declarator.node.id)
255
+ ? declarator.node.id.name
256
+ : null;
257
+
258
+ if (name === "$state" || name === "$store" || name === "$state.raw") {
259
+ if (name === "$state.raw") {
260
+ if (!isSSR) {
261
+ const args = init.node.arguments;
262
+ init.replaceWith(
263
+ t.callExpression(t.identifier(MAGIC.createRawSignal), args),
264
+ );
265
+ }
266
+ continue;
267
+ }
268
+ isSSR
269
+ ? handleStateSSR(path, declarator, init, signals)
270
+ : handleState(path, declarator, init, signals, isDev, filename); // ← add
271
+ if (name === "$store" && varName) {
272
+ storeSignals.add(varName);
273
+ }
274
+ } else if (name === "$derived") {
275
+ isSSR
276
+ ? handleDerivedSSR(path, declarator, init, signals)
277
+ : handleDerived(path, declarator, init, signals);
278
+ }
279
+ }
280
+ },
281
+ ExpressionStatement(path) {
282
+ if (isSSR) {
283
+ // drop $effect, $inspect, and $debug entirely in SSR
284
+ const expr = path.get("expression");
285
+ if (expr.isCallExpression()) {
286
+ const callee = expr.get("callee");
287
+ if (
288
+ callee.isIdentifier() &&
289
+ (callee.node.name === "$effect" ||
290
+ callee.node.name === "$inspect" ||
291
+ callee.node.name === "$debug")
292
+ ) {
293
+ didTransform = true;
294
+ path.remove();
295
+ }
296
+ }
297
+ return;
298
+ }
299
+ handleEffect(path);
300
+ // Handle $debug(expr) expression statements
301
+ const expr = path.get("expression");
302
+ if (expr.isCallExpression()) {
303
+ const callee = expr.get("callee");
304
+ if (callee.isIdentifier({ name: "$debug" })) {
305
+ didTransform = true;
306
+ path.replaceWith(
307
+ t.ifStatement(
308
+ t.memberExpression(
309
+ t.memberExpression(
310
+ t.memberExpression(
311
+ t.identifier("import"),
312
+ t.identifier("meta"),
313
+ ),
314
+ t.identifier("env"),
315
+ ),
316
+ t.identifier("DEV"),
317
+ ),
318
+ t.blockStatement([
319
+ t.debuggerStatement(),
320
+ t.expressionStatement(
321
+ t.callExpression(
322
+ t.memberExpression(
323
+ t.identifier("console"),
324
+ t.identifier("log"),
325
+ ),
326
+ expr.node.arguments,
327
+ ),
328
+ ),
329
+ ]),
330
+ ),
331
+ );
332
+ }
333
+ }
334
+ },
335
+ CallExpression(path) {
336
+ if (isSSR) return;
337
+ const callee = path.get("callee");
338
+
339
+ // Helper: wrap signal identifiers in call expressions
340
+ const wrapSignal = (expr: t.Expression): t.Expression => {
341
+ if (t.isIdentifier(expr) && signals.has(expr.name)) {
342
+ return t.callExpression(expr, []);
343
+ }
344
+ return expr;
345
+ };
346
+
347
+ // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
348
+ if (callee.isMemberExpression()) {
349
+ const object = callee.get("object");
350
+ const property = callee.get("property");
351
+ if (object.isIdentifier() && property.isIdentifier()) {
352
+ const obj = object.node.name;
353
+ const prop = property.node.name;
354
+
355
+ if (obj === "$state" && prop === "snapshot") {
356
+ didTransform = true;
357
+ path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
358
+ return;
359
+ }
360
+
361
+ if (obj === "$effect" && prop === "tracking") {
362
+ didTransform = true;
363
+ path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
364
+ return;
365
+ }
366
+
367
+ if (obj === "$effect" && prop === "pre") {
368
+ didTransform = true;
369
+ path
370
+ .get("callee")
371
+ .replaceWith(t.identifier(MAGIC.createEffectPre));
372
+ return;
373
+ }
374
+ }
375
+ }
376
+
377
+ // Handle $inspect(count).with(cb) chain
378
+ if (callee.isMemberExpression()) {
379
+ const property = callee.get("property");
380
+ if (property.isIdentifier({ name: "with" })) {
381
+ const object = callee.get("object");
382
+ if (object.isCallExpression()) {
383
+ const innerCallee = object.get("callee");
384
+ if (innerCallee.isIdentifier({ name: "$inspect" })) {
385
+ didTransform = true;
386
+ //@ts-expect-error Bizzare but it works if you read LSP
387
+ const args = object.node.arguments.map(wrapSignal);
388
+ const cb = path.node.arguments[0];
389
+ path.replaceWith(
390
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
391
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
392
+ //@ts-expect-error Bizzare but it works if you read LSP
393
+ cb,
394
+ ]),
395
+ );
396
+ return;
397
+ }
398
+ }
399
+ }
400
+ }
401
+
402
+ // Handle standalone $debug(...) — not as expression statement
403
+ if (callee.isIdentifier({ name: "$debug" })) {
404
+ didTransform = true;
405
+ path.replaceWith(
406
+ t.ifStatement(
407
+ t.memberExpression(
408
+ t.memberExpression(
409
+ t.memberExpression(
410
+ t.identifier("import"),
411
+ t.identifier("meta"),
412
+ ),
413
+ t.identifier("env"),
414
+ ),
415
+ t.identifier("DEV"),
416
+ ),
417
+ t.blockStatement([
418
+ t.debuggerStatement(),
419
+ t.expressionStatement(
420
+ t.callExpression(
421
+ t.memberExpression(
422
+ t.identifier("console"),
423
+ t.identifier("log"),
424
+ ),
425
+ path.node.arguments,
426
+ ),
427
+ ),
428
+ ]),
429
+ ),
430
+ );
431
+ return;
432
+ }
433
+
434
+ // Handle standalone $inspect(...)
435
+ if (callee.isIdentifier({ name: "$inspect" })) {
436
+ didTransform = true;
437
+ //@ts-expect-error Bizzare but it works if you read LSP
438
+ const args = path.node.arguments.map(wrapSignal);
439
+ path.replaceWith(
440
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
441
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
442
+ ]),
443
+ );
444
+ return;
445
+ }
446
+ },
447
+ JSXElement(path) {
448
+ didTransform = true;
449
+ // console.log(
450
+ // "[sigil] JSXElement visitor fired, parent:",
451
+ // path.parentPath?.type,
452
+ // "isSSR:", isSSR
453
+ // );
454
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
455
+ return;
456
+ if (isSSR) {
457
+ try {
458
+ convertKeyToDataKey(path.node);
459
+ path.replaceWith(
460
+ t.callExpression(t.identifier("__h"), [
461
+ processElementSSR(path.node, signals),
462
+ ]),
463
+ );
464
+ } catch (e) {
465
+ console.error("[sigil] processElementSSR threw:", path.toString());
466
+ console.error(e);
467
+ throw e;
468
+ }
469
+ return;
470
+ }
471
+
472
+ const statements: t.Statement[] = [];
473
+ const genId = (() => {
474
+ let i = 0;
475
+ return () => `_el${i++}`;
476
+ })();
477
+
478
+ const root = processElement(
479
+ path.node,
480
+ statements,
481
+ genId,
482
+ signals,
483
+ scopedHash,
484
+ isHydrate,
485
+ isHydrate ? "__nodes" : undefined,
486
+ );
487
+
488
+ const body: t.Statement[] = [];
489
+
490
+ if (isHydrate) {
491
+ // DECLARE __nodes locally — every IIFE owns its own context
492
+ body.push(
493
+ t.variableDeclaration("const", [
494
+ t.variableDeclarator(
495
+ t.identifier("__nodes"),
496
+ t.callExpression(t.identifier("getHydrationNodes"), []),
497
+ ),
498
+ ]),
499
+ );
500
+ }
501
+
502
+ body.push(...statements);
503
+ body.push(t.returnStatement(t.identifier(root)));
504
+
505
+ path.replaceWith(
506
+ t.callExpression(
507
+ t.arrowFunctionExpression([], t.blockStatement(body)),
508
+ [],
509
+ ),
510
+ );
511
+ },
512
+ JSXFragment(path) {
513
+ didTransform = true;
514
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
515
+ return;
516
+ if (isSSR) {
517
+ path.replaceWith(
518
+ t.callExpression(t.identifier("__h"), [
519
+ processFragmentSSR(path.node, signals),
520
+ ]),
521
+ );
522
+ return;
523
+ }
524
+
525
+ const statements: t.Statement[] = [];
526
+ const genId = (() => {
527
+ let i = 0;
528
+ return () => `_el${i++}`;
529
+ })();
530
+
531
+ const root = processFragment(
532
+ path.node,
533
+ statements,
534
+ genId,
535
+ signals,
536
+ scopedHash,
537
+ isHydrate,
538
+ isHydrate ? "__nodes" : undefined,
539
+ );
540
+
541
+ const body: t.Statement[] = [];
542
+
543
+ if (isHydrate) {
544
+ // DECLARE __nodes locally — every IIFE owns its own context
545
+ body.push(
546
+ t.variableDeclaration("const", [
547
+ t.variableDeclarator(
548
+ t.identifier("__nodes"),
549
+ t.callExpression(t.identifier("getHydrationNodes"), []),
550
+ ),
551
+ ]),
552
+ );
553
+ }
554
+
555
+ body.push(...statements);
556
+ body.push(t.returnStatement(t.identifier(root)));
557
+
558
+ path.replaceWith(
559
+ t.callExpression(
560
+ t.arrowFunctionExpression([], t.blockStatement(body)),
561
+ [],
562
+ ),
563
+ );
564
+ },
565
+ FunctionDeclaration(path) {
566
+ if (isSSR) return;
567
+ const node = path.node;
568
+ if (node.async && node.id) {
569
+ asyncFunctions.set(node.id.name, path);
570
+ }
571
+ },
572
+
573
+ ExportDefaultDeclaration(path) {
574
+ const decl = path.get("declaration");
575
+
576
+ // export default async function Page() {}
577
+ if (
578
+ (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
579
+ (decl.node as any).async &&
580
+ !isSSR
581
+ ) {
582
+ asyncDefaultPath = path;
583
+ return;
584
+ }
585
+
586
+ // export default Page
587
+ if (decl.isIdentifier() && !isSSR) {
588
+ const name = (decl.node as t.Identifier).name;
589
+ if (asyncFunctions.has(name)) {
590
+ asyncDefaultPath = asyncFunctions.get(name);
591
+ _asyncDefaultRef = name;
592
+ }
593
+ }
594
+ },
595
+
596
+ ExportNamedDeclaration(path) {
597
+ const decl = path.get("declaration");
598
+ if (decl.isFunctionDeclaration()) {
599
+ const name = (decl.node as t.FunctionDeclaration).id?.name;
600
+ if (name === "loading") hasLoadingExport = true;
601
+ if (name === "error") hasErrorExport = true;
602
+ }
603
+ if (decl.isVariableDeclaration()) {
604
+ for (const d of decl.node.declarations) {
605
+ if (t.isIdentifier(d.id)) {
606
+ if (d.id.name === "loading") hasLoadingExport = true;
607
+ if (d.id.name === "error") hasErrorExport = true;
608
+ }
609
+ }
610
+ }
611
+ },
612
+ },
613
+ };
614
+ }