@sigil-dev/compiler 0.9.20 → 0.9.22

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