@sigil-dev/compiler 0.9.5 → 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,607 +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
- "insert",
186
- "applyDirective",
187
- "getHydrationNodes",
188
- "pushHydrationNodes",
189
- "popHydrationNodes",
190
- "snapshot",
191
- "tracking",
192
- "untrack",
193
- "createRoot",
194
- "createEffectPre",
195
- "createInspectEffect",
196
- "withEffectScope",
197
- "mountTransition",
198
- "removeAnimated",
199
- ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
200
- ];
201
- const runtimeImport = path.node.body.find(
202
- (n): n is t.ImportDeclaration =>
203
- t.isImportDeclaration(n) &&
204
- n.source.value === "@sigil-dev/runtime",
205
- );
206
-
207
- if (runtimeImport) {
208
- // console.log(
209
- // "[sigil exit] found existing import, specifier count:",
210
- // runtimeImport.specifiers.length,
211
- // );
212
- const existingNames = new Set(
213
- runtimeImport.specifiers
214
- .filter(t.isImportSpecifier)
215
- .map((s) =>
216
- t.isIdentifier(s.imported)
217
- ? s.imported.name
218
- : (s.imported as t.StringLiteral).value,
219
- ),
220
- );
221
- for (const name of requiredSpecifiers) {
222
- if (!existingNames.has(name)) {
223
- runtimeImport.specifiers.push(
224
- t.importSpecifier(t.identifier(name), t.identifier(name)),
225
- );
226
- }
227
- }
228
- } else {
229
- path.unshiftContainer(
230
- "body",
231
- t.importDeclaration(
232
- requiredSpecifiers.map((name) =>
233
- t.importSpecifier(t.identifier(name), t.identifier(name)),
234
- ),
235
- t.stringLiteral("@sigil-dev/runtime"),
236
- ),
237
- );
238
- }
239
- },
240
- },
241
- VariableDeclaration(path) {
242
- for (const declarator of path.get("declarations")) {
243
- const macro = getMacro(declarator);
244
- if (!macro) continue;
245
- didTransform = true;
246
- const { name, init } = macro;
247
- const varName = t.isIdentifier(declarator.node.id)
248
- ? declarator.node.id.name
249
- : null;
250
-
251
- if (name === "$state" || name === "$store" || name === "$state.raw") {
252
- if (name === "$state.raw") {
253
- if (!isSSR) {
254
- const args = init.node.arguments;
255
- init.replaceWith(
256
- t.callExpression(t.identifier(MAGIC.createRawSignal), args),
257
- );
258
- }
259
- continue;
260
- }
261
- isSSR
262
- ? handleStateSSR(path, declarator, init, signals)
263
- : handleState(path, declarator, init, signals, isDev, filename); // ← add
264
- if (name === "$store" && varName) {
265
- storeSignals.add(varName);
266
- }
267
- } else if (name === "$derived") {
268
- isSSR
269
- ? handleDerivedSSR(path, declarator, init, signals)
270
- : handleDerived(path, declarator, init, signals);
271
- }
272
- }
273
- },
274
- ExpressionStatement(path) {
275
- if (isSSR) {
276
- // drop $effect, $inspect, and $debug entirely in SSR
277
- const expr = path.get("expression");
278
- if (expr.isCallExpression()) {
279
- const callee = expr.get("callee");
280
- if (
281
- callee.isIdentifier() &&
282
- (callee.node.name === "$effect" ||
283
- callee.node.name === "$inspect" ||
284
- callee.node.name === "$debug")
285
- ) {
286
- didTransform = true;
287
- path.remove();
288
- }
289
- }
290
- return;
291
- }
292
- handleEffect(path);
293
- // Handle $debug(expr) expression statements
294
- const expr = path.get("expression");
295
- if (expr.isCallExpression()) {
296
- const callee = expr.get("callee");
297
- if (callee.isIdentifier({ name: "$debug" })) {
298
- didTransform = true;
299
- path.replaceWith(
300
- t.ifStatement(
301
- t.memberExpression(
302
- t.memberExpression(
303
- t.memberExpression(
304
- t.identifier("import"),
305
- t.identifier("meta"),
306
- ),
307
- t.identifier("env"),
308
- ),
309
- t.identifier("DEV"),
310
- ),
311
- t.blockStatement([
312
- t.debuggerStatement(),
313
- t.expressionStatement(
314
- t.callExpression(
315
- t.memberExpression(
316
- t.identifier("console"),
317
- t.identifier("log"),
318
- ),
319
- expr.node.arguments,
320
- ),
321
- ),
322
- ]),
323
- ),
324
- );
325
- }
326
- }
327
- },
328
- CallExpression(path) {
329
- if (isSSR) return;
330
- const callee = path.get("callee");
331
-
332
- // Helper: wrap signal identifiers in call expressions
333
- const wrapSignal = (expr: t.Expression): t.Expression => {
334
- if (t.isIdentifier(expr) && signals.has(expr.name)) {
335
- return t.callExpression(expr, []);
336
- }
337
- return expr;
338
- };
339
-
340
- // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
341
- if (callee.isMemberExpression()) {
342
- const object = callee.get("object");
343
- const property = callee.get("property");
344
- if (object.isIdentifier() && property.isIdentifier()) {
345
- const obj = object.node.name;
346
- const prop = property.node.name;
347
-
348
- if (obj === "$state" && prop === "snapshot") {
349
- didTransform = true;
350
- path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
351
- return;
352
- }
353
-
354
- if (obj === "$effect" && prop === "tracking") {
355
- didTransform = true;
356
- path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
357
- return;
358
- }
359
-
360
- if (obj === "$effect" && prop === "pre") {
361
- didTransform = true;
362
- path
363
- .get("callee")
364
- .replaceWith(t.identifier(MAGIC.createEffectPre));
365
- return;
366
- }
367
- }
368
- }
369
-
370
- // Handle $inspect(count).with(cb) chain
371
- if (callee.isMemberExpression()) {
372
- const property = callee.get("property");
373
- if (property.isIdentifier({ name: "with" })) {
374
- const object = callee.get("object");
375
- if (object.isCallExpression()) {
376
- const innerCallee = object.get("callee");
377
- if (innerCallee.isIdentifier({ name: "$inspect" })) {
378
- didTransform = true;
379
- //@ts-expect-error Bizzare but it works if you read LSP
380
- const args = object.node.arguments.map(wrapSignal);
381
- const cb = path.node.arguments[0];
382
- path.replaceWith(
383
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
384
- t.arrowFunctionExpression([], t.arrayExpression(args)),
385
- //@ts-expect-error Bizzare but it works if you read LSP
386
- cb,
387
- ]),
388
- );
389
- return;
390
- }
391
- }
392
- }
393
- }
394
-
395
- // Handle standalone $debug(...) — not as expression statement
396
- if (callee.isIdentifier({ name: "$debug" })) {
397
- didTransform = true;
398
- path.replaceWith(
399
- t.ifStatement(
400
- t.memberExpression(
401
- t.memberExpression(
402
- t.memberExpression(
403
- t.identifier("import"),
404
- t.identifier("meta"),
405
- ),
406
- t.identifier("env"),
407
- ),
408
- t.identifier("DEV"),
409
- ),
410
- t.blockStatement([
411
- t.debuggerStatement(),
412
- t.expressionStatement(
413
- t.callExpression(
414
- t.memberExpression(
415
- t.identifier("console"),
416
- t.identifier("log"),
417
- ),
418
- path.node.arguments,
419
- ),
420
- ),
421
- ]),
422
- ),
423
- );
424
- return;
425
- }
426
-
427
- // Handle standalone $inspect(...)
428
- if (callee.isIdentifier({ name: "$inspect" })) {
429
- didTransform = true;
430
- //@ts-expect-error Bizzare but it works if you read LSP
431
- const args = path.node.arguments.map(wrapSignal);
432
- path.replaceWith(
433
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
434
- t.arrowFunctionExpression([], t.arrayExpression(args)),
435
- ]),
436
- );
437
- return;
438
- }
439
- },
440
- JSXElement(path) {
441
- didTransform = true;
442
- // console.log(
443
- // "[sigil] JSXElement visitor fired, parent:",
444
- // path.parentPath?.type,
445
- // "isSSR:", isSSR
446
- // );
447
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
448
- return;
449
- if (isSSR) {
450
- try {
451
- convertKeyToDataKey(path.node);
452
- path.replaceWith(
453
- t.callExpression(t.identifier("__h"), [
454
- processElementSSR(path.node, signals),
455
- ]),
456
- );
457
- } catch (e) {
458
- console.error("[sigil] processElementSSR threw:", path.toString());
459
- console.error(e);
460
- throw e;
461
- }
462
- return;
463
- }
464
-
465
- const statements: t.Statement[] = [];
466
- const genId = (() => {
467
- let i = 0;
468
- return () => `_el${i++}`;
469
- })();
470
-
471
- const root = processElement(
472
- path.node,
473
- statements,
474
- genId,
475
- signals,
476
- scopedHash,
477
- isHydrate,
478
- isHydrate ? "__nodes" : undefined,
479
- );
480
-
481
- const body: t.Statement[] = [];
482
-
483
- if (isHydrate) {
484
- // DECLARE __nodes locally — every IIFE owns its own context
485
- body.push(
486
- t.variableDeclaration("const", [
487
- t.variableDeclarator(
488
- t.identifier("__nodes"),
489
- t.callExpression(t.identifier("getHydrationNodes"), []),
490
- ),
491
- ]),
492
- );
493
- }
494
-
495
- body.push(...statements);
496
- body.push(t.returnStatement(t.identifier(root)));
497
-
498
- path.replaceWith(
499
- t.callExpression(
500
- t.arrowFunctionExpression([], t.blockStatement(body)),
501
- [],
502
- ),
503
- );
504
- },
505
- JSXFragment(path) {
506
- didTransform = true;
507
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
508
- return;
509
- if (isSSR) {
510
- path.replaceWith(
511
- t.callExpression(t.identifier("__h"), [
512
- processFragmentSSR(path.node, signals),
513
- ]),
514
- );
515
- return;
516
- }
517
-
518
- const statements: t.Statement[] = [];
519
- const genId = (() => {
520
- let i = 0;
521
- return () => `_el${i++}`;
522
- })();
523
-
524
- const root = processFragment(
525
- path.node,
526
- statements,
527
- genId,
528
- signals,
529
- scopedHash,
530
- isHydrate,
531
- isHydrate ? "__nodes" : undefined,
532
- );
533
-
534
- const body: t.Statement[] = [];
535
-
536
- if (isHydrate) {
537
- // DECLARE __nodes locally — every IIFE owns its own context
538
- body.push(
539
- t.variableDeclaration("const", [
540
- t.variableDeclarator(
541
- t.identifier("__nodes"),
542
- t.callExpression(t.identifier("getHydrationNodes"), []),
543
- ),
544
- ]),
545
- );
546
- }
547
-
548
- body.push(...statements);
549
- body.push(t.returnStatement(t.identifier(root)));
550
-
551
- path.replaceWith(
552
- t.callExpression(
553
- t.arrowFunctionExpression([], t.blockStatement(body)),
554
- [],
555
- ),
556
- );
557
- },
558
- FunctionDeclaration(path) {
559
- if (isSSR) return;
560
- const node = path.node;
561
- if (node.async && node.id) {
562
- asyncFunctions.set(node.id.name, path);
563
- }
564
- },
565
-
566
- ExportDefaultDeclaration(path) {
567
- const decl = path.get("declaration");
568
-
569
- // export default async function Page() {}
570
- if (
571
- (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
572
- (decl.node as any).async &&
573
- !isSSR
574
- ) {
575
- asyncDefaultPath = path;
576
- return;
577
- }
578
-
579
- // export default Page
580
- if (decl.isIdentifier() && !isSSR) {
581
- const name = (decl.node as t.Identifier).name;
582
- if (asyncFunctions.has(name)) {
583
- asyncDefaultPath = asyncFunctions.get(name);
584
- _asyncDefaultRef = name;
585
- }
586
- }
587
- },
588
-
589
- ExportNamedDeclaration(path) {
590
- const decl = path.get("declaration");
591
- if (decl.isFunctionDeclaration()) {
592
- const name = (decl.node as t.FunctionDeclaration).id?.name;
593
- if (name === "loading") hasLoadingExport = true;
594
- if (name === "error") hasErrorExport = true;
595
- }
596
- if (decl.isVariableDeclaration()) {
597
- for (const d of decl.node.declarations) {
598
- if (t.isIdentifier(d.id)) {
599
- if (d.id.name === "loading") hasLoadingExport = true;
600
- if (d.id.name === "error") hasErrorExport = true;
601
- }
602
- }
603
- }
604
- },
605
- },
606
- };
607
- }
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
+ }