@sigil-dev/compiler 0.7.4 → 0.7.6

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,257 +1,430 @@
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 { getMacro } from "./util/helpers.ts";
10
- import { warnDeadReactivity } from "./util/dead-code.ts";
11
-
12
- const SSR_HELPERS = template.statements.ast(`
13
- const __SAFE = Symbol.for('sigil.safe');
14
- class __H {
15
- constructor(v) { this.v = v; this[__SAFE] = true; }
16
- toString() { return this.v; }
17
- }
18
- const __h = (v) => {
19
- if (v?.[__SAFE]) return v;
20
- if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
21
- return new __H(String(v ?? ''));
22
- };
23
- const __e = (v) => {
24
- if (v?.[__SAFE]) return v.v;
25
- if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
26
- if (v === false || v === null || v === undefined) return '';
27
- return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
28
- };
29
- `);
30
-
31
- /**
32
- * Recursively convert key={expr} to data-key={expr} in JSX tree.
33
- * Needed for SSR output so hydration can map items by key.
34
- */
35
- function convertKeyToDataKey(node: t.JSXElement): void {
36
- for (let i = 0; i < node.openingElement.attributes.length; i++) {
37
- const attr = node.openingElement.attributes[i];
38
- if (
39
- t.isJSXAttribute(attr) &&
40
- t.isJSXIdentifier(attr.name) &&
41
- attr.name.name === "key"
42
- ) {
43
- node.openingElement.attributes[i] = t.jsxAttribute(
44
- t.jsxIdentifier("data-key"),
45
- attr.value,
46
- );
47
- }
48
- }
49
- for (const child of node.children) {
50
- if (t.isJSXElement(child)) {
51
- convertKeyToDataKey(child);
52
- } else if (
53
- t.isJSXExpressionContainer(child) &&
54
- t.isJSXElement(child.expression)
55
- ) {
56
- convertKeyToDataKey(child.expression);
57
- }
58
- }
59
- }
60
-
61
- interface SigilOptions {
62
- hash?: string;
63
- mode?: "dom" | "ssr" | "hydrate";
64
- }
65
-
66
- export default function sigilPlugin(): PluginObject {
67
- const signals = new Set<string>();
68
- const storeSignals = new Set<string>();
69
- let scopedHash: string | undefined;
70
- let isSSR = false;
71
- let isHydrate = false;
72
-
73
- return {
74
- name: "sigil",
75
- visitor: {
76
- Program: {
77
- enter(path, state) {
78
- signals.clear();
79
- storeSignals.clear();
80
- const opts = (state.opts || {}) as SigilOptions;
81
- scopedHash = opts.hash;
82
- isSSR = opts.mode === "ssr";
83
- isHydrate = opts.mode === "hydrate";
84
-
85
- // SSR doesn't need any runtime imports except the `escape` utility.
86
- if (isSSR) {
87
- path.unshiftContainer("body", SSR_HELPERS);
88
- return;
89
- }
90
-
91
- path.unshiftContainer(
92
- "body",
93
- t.importDeclaration(
94
- [
95
- t.importSpecifier(
96
- t.identifier("createSignal"),
97
- t.identifier("createSignal"),
98
- ),
99
- t.importSpecifier(
100
- t.identifier("createEffect"),
101
- t.identifier("createEffect"),
102
- ),
103
- t.importSpecifier(
104
- t.identifier("createMemo"),
105
- t.identifier("createMemo"),
106
- ),
107
- t.importSpecifier(
108
- t.identifier("reconcile"),
109
- t.identifier("reconcile"),
110
- ),
111
- t.importSpecifier(t.identifier("claim"), t.identifier("claim")),
112
- t.importSpecifier(
113
- t.identifier("claimText"),
114
- t.identifier("claimText"),
115
- ),
116
- t.importSpecifier(
117
- t.identifier("claimComment"),
118
- t.identifier("claimComment"),
119
- ),
120
- t.importSpecifier(
121
- t.identifier("hydrateKeyedList"),
122
- t.identifier("hydrateKeyedList"),
123
- ),
124
- t.importSpecifier(
125
- t.identifier("insert"),
126
- t.identifier("insert"),
127
- ),
128
-
129
- t.importSpecifier(
130
- t.identifier("getHydrationNodes"),
131
- t.identifier("getHydrationNodes"),
132
- ),
133
- ],
134
- t.stringLiteral("@sigil-dev/runtime"),
135
- ),
136
- );
137
- },
138
- exit(path, state) {
139
- warnDeadReactivity(path, signals, storeSignals, state.filename)
140
- }
141
- },
142
- VariableDeclaration(path) {
143
- for (const declarator of path.get("declarations")) {
144
- const macro = getMacro(declarator);
145
- if (!macro) continue;
146
- const { name, init } = macro;
147
- const varName = t.isIdentifier(declarator.node.id)
148
- ? declarator.node.id.name
149
- : null;
150
-
151
- if (name === "$state" || name === "$store") {
152
- isSSR
153
- ? handleStateSSR(path, declarator, init)
154
- : handleState(path, declarator, init, signals);
155
- if (name === "$store" && varName) {
156
- storeSignals.add(varName);
157
- }
158
- } else if (name === "$derived") {
159
- isSSR
160
- ? handleDerivedSSR(path, declarator, init)
161
- : handleDerived(path, declarator, init, signals);
162
- }
163
- }
164
- },
165
- ExpressionStatement(path) {
166
- if (isSSR) {
167
- // drop $effect entirely in SSR
168
- const expr = path.get("expression");
169
- if (expr.isCallExpression()) {
170
- const callee = expr.get("callee");
171
- if (callee.isIdentifier() && callee.node.name === "$effect") {
172
- path.remove();
173
- }
174
- }
175
- return;
176
- }
177
- handleEffect(path);
178
- },
179
- JSXElement(path) {
180
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
181
- return;
182
- if (isSSR) { /* ... existing ... */ return; }
183
-
184
- const statements: t.Statement[] = [];
185
- const genId = (() => { let i = 0; return () => `_el${i++}`; })();
186
-
187
- const root = processElement(
188
- path.node, statements, genId, signals, scopedHash,
189
- isHydrate,
190
- isHydrate ? "__nodes" : undefined,
191
- );
192
-
193
- const body: t.Statement[] = [];
194
-
195
- if (isHydrate) {
196
- // DECLARE __nodes locally — every IIFE owns its own context
197
- body.push(
198
- t.variableDeclaration("const", [
199
- t.variableDeclarator(
200
- t.identifier("__nodes"),
201
- t.callExpression(t.identifier("getHydrationNodes"), [])
202
- )
203
- ])
204
- );
205
- }
206
-
207
- body.push(...statements);
208
- body.push(t.returnStatement(t.identifier(root)));
209
-
210
- path.replaceWith(
211
- t.callExpression(
212
- t.arrowFunctionExpression([], t.blockStatement(body)),
213
- []
214
- )
215
- );
216
- },
217
- JSXFragment(path) {
218
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
219
- return;
220
- if (isSSR) { /* ... existing ... */ return; }
221
-
222
- const statements: t.Statement[] = [];
223
- const genId = (() => { let i = 0; return () => `_el${i++}`; })();
224
-
225
- const root = processFragment(
226
- path.node, statements, genId, signals, scopedHash,
227
- isHydrate,
228
- isHydrate ? "__nodes" : undefined,
229
- );
230
-
231
- const body: t.Statement[] = [];
232
-
233
- if (isHydrate) {
234
- // DECLARE __nodes locally — every IIFE owns its own context
235
- body.push(
236
- t.variableDeclaration("const", [
237
- t.variableDeclarator(
238
- t.identifier("__nodes"),
239
- t.callExpression(t.identifier("getHydrationNodes"), [])
240
- )
241
- ])
242
- );
243
- }
244
-
245
- body.push(...statements);
246
- body.push(t.returnStatement(t.identifier(root)));
247
-
248
- path.replaceWith(
249
- t.callExpression(
250
- t.arrowFunctionExpression([], t.blockStatement(body)),
251
- []
252
- )
253
- );
254
- },
255
- },
256
- };
257
- }
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 { getMacro } from "./util/helpers.ts";
10
+ import { MAGIC } from "./util/magic.ts";
11
+ import { warnDeadReactivity } from "./util/dead-code.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
+ return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
29
+ };
30
+ `);
31
+ /**
32
+ * Recursively convert key={expr} to data-key={expr} in JSX tree.
33
+ * Needed for SSR output so hydration can map items by key.
34
+ */
35
+ function convertKeyToDataKey(node: t.JSXElement): void {
36
+ for (let i = 0; i < node.openingElement.attributes.length; i++) {
37
+ const attr = node.openingElement.attributes[i];
38
+ if (
39
+ t.isJSXAttribute(attr) &&
40
+ t.isJSXIdentifier(attr.name) &&
41
+ attr.name.name === "key"
42
+ ) {
43
+ node.openingElement.attributes[i] = t.jsxAttribute(
44
+ t.jsxIdentifier("data-key"),
45
+ attr.value,
46
+ );
47
+ }
48
+ }
49
+ for (const child of node.children) {
50
+ if (t.isJSXElement(child)) {
51
+ convertKeyToDataKey(child);
52
+ } else if (
53
+ t.isJSXExpressionContainer(child) &&
54
+ t.isJSXElement(child.expression)
55
+ ) {
56
+ convertKeyToDataKey(child.expression);
57
+ }
58
+ }
59
+ }
60
+
61
+ interface SigilOptions {
62
+ hash?: string;
63
+ mode?: "dom" | "ssr" | "hydrate";
64
+ }
65
+
66
+ export default function sigilPlugin(): PluginObject {
67
+ const signals = new Set<string>();
68
+ const storeSignals = new Set<string>();
69
+ let scopedHash: string | undefined;
70
+ let isSSR = false;
71
+ let isHydrate = false;
72
+ let didTransform = false;
73
+
74
+ return {
75
+ name: "sigil",
76
+ visitor: {
77
+ Program: {
78
+ enter(path, state) {
79
+ signals.clear();
80
+ storeSignals.clear();
81
+ const opts = (state.opts || {}) as SigilOptions;
82
+ scopedHash = opts.hash;
83
+ didTransform = false;
84
+ isSSR = opts.mode === "ssr";
85
+ isHydrate = opts.mode === "hydrate";
86
+
87
+ if (isSSR) {
88
+ path.unshiftContainer("body", SSR_HELPERS);
89
+ return;
90
+ }
91
+
92
+
93
+
94
+ },
95
+ exit(path, state) {
96
+ warnDeadReactivity(path, signals, storeSignals, state.filename);
97
+
98
+ // Only inject runtime import if this file actually used sigil transforms
99
+ if (!didTransform || isSSR) return;
100
+
101
+ const requiredSpecifiers = [
102
+ "createSignal", "createRawSignal", "createEffect", "createMemo", "reconcile",
103
+ "claim", "claimText", "claimComment", "hydrateKeyedList",
104
+ "insert", "getHydrationNodes", "pushHydrationNodes", "popHydrationNodes",
105
+ "snapshot", "tracking", "createEffectPre", "createInspectEffect",
106
+ ];
107
+
108
+ const runtimeImport = path.node.body.find(
109
+ (n): n is t.ImportDeclaration => t.isImportDeclaration(n) && n.source.value === "@sigil-dev/runtime"
110
+ );
111
+
112
+ if (runtimeImport) {
113
+ const existingNames = new Set(
114
+ runtimeImport.specifiers
115
+ .filter(t.isImportSpecifier)
116
+ .map(s => t.isIdentifier(s.imported) ? s.imported.name : (s.imported as t.StringLiteral).value)
117
+ );
118
+ for (const name of requiredSpecifiers) {
119
+ if (!existingNames.has(name)) {
120
+ runtimeImport.specifiers.push(
121
+ t.importSpecifier(t.identifier(name), t.identifier(name))
122
+ );
123
+ }
124
+ }
125
+ } else {
126
+ path.unshiftContainer("body", t.importDeclaration(
127
+ requiredSpecifiers.map(name =>
128
+ t.importSpecifier(t.identifier(name), t.identifier(name))
129
+ ),
130
+ t.stringLiteral("@sigil-dev/runtime"),
131
+ ));
132
+ }
133
+ }
134
+ },
135
+ VariableDeclaration(path) {
136
+ for (const declarator of path.get("declarations")) {
137
+ const macro = getMacro(declarator);
138
+ if (!macro) continue;
139
+ didTransform = true;
140
+ const { name, init } = macro;
141
+ const varName = t.isIdentifier(declarator.node.id)
142
+ ? declarator.node.id.name
143
+ : null;
144
+
145
+ if (name === "$state" || name === "$store" || name === "$state.raw") {
146
+ if (name === "$state.raw") {
147
+ if (!isSSR) {
148
+ const args = init.node.arguments;
149
+ init.replaceWith(
150
+ t.callExpression(t.identifier(MAGIC.createRawSignal), args),
151
+ );
152
+ }
153
+ continue;
154
+ }
155
+ isSSR
156
+ ? handleStateSSR(path, declarator, init, signals)
157
+ : handleState(path, declarator, init, signals);
158
+ if (name === "$store" && varName) {
159
+ storeSignals.add(varName);
160
+ }
161
+ } else if (name === "$derived") {
162
+ isSSR
163
+ ? handleDerivedSSR(path, declarator, init, signals)
164
+ : handleDerived(path, declarator, init, signals);
165
+ }
166
+ }
167
+ },
168
+ ExpressionStatement(path) {
169
+ if (isSSR) {
170
+ // drop $effect, $inspect, and $debug entirely in SSR
171
+ const expr = path.get("expression");
172
+ if (expr.isCallExpression()) {
173
+ const callee = expr.get("callee");
174
+ if (callee.isIdentifier() && (callee.node.name === "$effect" || callee.node.name === "$inspect" || callee.node.name === "$debug")) {
175
+ didTransform = true;
176
+ path.remove();
177
+ }
178
+ }
179
+ return;
180
+ }
181
+ handleEffect(path);
182
+ // Handle $debug(expr) expression statements
183
+ const expr = path.get("expression");
184
+ if (expr.isCallExpression()) {
185
+ const callee = expr.get("callee");
186
+ if (callee.isIdentifier({ name: "$debug" })) {
187
+ didTransform = true;
188
+ path.replaceWith(
189
+ t.ifStatement(
190
+ t.memberExpression(
191
+ t.memberExpression(
192
+ t.memberExpression(
193
+ t.identifier("import"),
194
+ t.identifier("meta"),
195
+ ),
196
+ t.identifier("env"),
197
+ ),
198
+ t.identifier("DEV"),
199
+ ),
200
+ t.blockStatement([
201
+ t.debuggerStatement(),
202
+ t.expressionStatement(
203
+ t.callExpression(
204
+ t.memberExpression(
205
+ t.identifier("console"),
206
+ t.identifier("log"),
207
+ ),
208
+ expr.node.arguments,
209
+ ),
210
+ ),
211
+ ]),
212
+ ),
213
+ );
214
+ }
215
+ }
216
+ },
217
+ CallExpression(path) {
218
+ if (isSSR) return;
219
+ const callee = path.get("callee");
220
+
221
+ // Helper: wrap signal identifiers in call expressions
222
+ const wrapSignal = (expr: t.Expression): t.Expression => {
223
+ if (t.isIdentifier(expr) && signals.has(expr.name)) {
224
+ return t.callExpression(expr, []);
225
+ }
226
+ return expr;
227
+ };
228
+
229
+ // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
230
+ if (callee.isMemberExpression()) {
231
+ const object = callee.get("object");
232
+ const property = callee.get("property");
233
+ if (object.isIdentifier() && property.isIdentifier()) {
234
+ const obj = object.node.name;
235
+ const prop = property.node.name;
236
+
237
+ if (obj === "$state" && prop === "snapshot") {
238
+ didTransform = true;
239
+ path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
240
+ return;
241
+ }
242
+
243
+ if (obj === "$effect" && prop === "tracking") {
244
+ didTransform = true;
245
+ path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
246
+ return;
247
+ }
248
+
249
+ if (obj === "$effect" && prop === "pre") {
250
+ didTransform = true;
251
+ path.get("callee").replaceWith(t.identifier(MAGIC.createEffectPre));
252
+ return;
253
+ }
254
+ }
255
+ }
256
+
257
+ // Handle $inspect(count).with(cb) chain
258
+ if (callee.isMemberExpression()) {
259
+ const property = callee.get("property");
260
+ if (property.isIdentifier({ name: "with" })) {
261
+ const object = callee.get("object");
262
+ if (object.isCallExpression()) {
263
+ const innerCallee = object.get("callee");
264
+ if (innerCallee.isIdentifier({ name: "$inspect" })) {
265
+ didTransform = true;
266
+ const args = object.node.arguments.map(wrapSignal);
267
+ const cb = path.node.arguments[0];
268
+ path.replaceWith(
269
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
270
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
271
+ cb,
272
+ ]),
273
+ );
274
+ return;
275
+ }
276
+ }
277
+ }
278
+ }
279
+
280
+ // Handle standalone $debug(...) — not as expression statement
281
+ if (callee.isIdentifier({ name: "$debug" })) {
282
+ didTransform = true;
283
+ path.replaceWith(
284
+ t.ifStatement(
285
+ t.memberExpression(
286
+ t.memberExpression(
287
+ t.memberExpression(
288
+ t.identifier("import"),
289
+ t.identifier("meta"),
290
+ ),
291
+ t.identifier("env"),
292
+ ),
293
+ t.identifier("DEV"),
294
+ ),
295
+ t.blockStatement([
296
+ t.debuggerStatement(),
297
+ t.expressionStatement(
298
+ t.callExpression(
299
+ t.memberExpression(
300
+ t.identifier("console"),
301
+ t.identifier("log"),
302
+ ),
303
+ path.node.arguments,
304
+ ),
305
+ ),
306
+ ]),
307
+ ),
308
+ );
309
+ return;
310
+ }
311
+
312
+ // Handle standalone $inspect(...)
313
+ if (callee.isIdentifier({ name: "$inspect" })) {
314
+ didTransform = true;
315
+ const args = path.node.arguments.map(wrapSignal);
316
+ path.replaceWith(
317
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
318
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
319
+ ]),
320
+ );
321
+ return;
322
+ }
323
+ },
324
+ JSXElement(path) {
325
+ didTransform = true;
326
+ // console.log(
327
+ // "[sigil] JSXElement visitor fired, parent:",
328
+ // path.parentPath?.type,
329
+ // "isSSR:", isSSR
330
+ // );
331
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
332
+ return;
333
+ if (isSSR) {
334
+ try {
335
+ convertKeyToDataKey(path.node);
336
+ path.replaceWith(
337
+ t.callExpression(t.identifier("__h"), [
338
+ processElementSSR(path.node, signals),
339
+ ]),
340
+ );
341
+ } catch (e) {
342
+ console.error("[sigil] processElementSSR threw:", path.toString());
343
+ console.error(e);
344
+ throw e;
345
+ }
346
+ return;
347
+ }
348
+
349
+ const statements: t.Statement[] = [];
350
+ const genId = (() => { let i = 0; return () => `_el${i++}`; })();
351
+
352
+ const root = processElement(
353
+ path.node, statements, genId, signals, scopedHash,
354
+ isHydrate,
355
+ isHydrate ? "__nodes" : undefined,
356
+ );
357
+
358
+ const body: t.Statement[] = [];
359
+
360
+ if (isHydrate) {
361
+ // DECLARE __nodes locally — every IIFE owns its own context
362
+ body.push(
363
+ t.variableDeclaration("const", [
364
+ t.variableDeclarator(
365
+ t.identifier("__nodes"),
366
+ t.callExpression(t.identifier("getHydrationNodes"), [])
367
+ )
368
+ ])
369
+ );
370
+ }
371
+
372
+ body.push(...statements);
373
+ body.push(t.returnStatement(t.identifier(root)));
374
+
375
+ path.replaceWith(
376
+ t.callExpression(
377
+ t.arrowFunctionExpression([], t.blockStatement(body)),
378
+ []
379
+ )
380
+ );
381
+ },
382
+ JSXFragment(path) {
383
+ didTransform = true;
384
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
385
+ return;
386
+ if (isSSR) {
387
+ path.replaceWith(
388
+ t.callExpression(t.identifier("__h"), [
389
+ processFragmentSSR(path.node, signals),
390
+ ]),
391
+ );
392
+ return;
393
+ }
394
+
395
+ const statements: t.Statement[] = [];
396
+ const genId = (() => { let i = 0; return () => `_el${i++}`; })();
397
+
398
+ const root = processFragment(
399
+ path.node, statements, genId, signals, scopedHash,
400
+ isHydrate,
401
+ isHydrate ? "__nodes" : undefined,
402
+ );
403
+
404
+ const body: t.Statement[] = [];
405
+
406
+ if (isHydrate) {
407
+ // DECLARE __nodes locally — every IIFE owns its own context
408
+ body.push(
409
+ t.variableDeclaration("const", [
410
+ t.variableDeclarator(
411
+ t.identifier("__nodes"),
412
+ t.callExpression(t.identifier("getHydrationNodes"), [])
413
+ )
414
+ ])
415
+ );
416
+ }
417
+
418
+ body.push(...statements);
419
+ body.push(t.returnStatement(t.identifier(root)));
420
+
421
+ path.replaceWith(
422
+ t.callExpression(
423
+ t.arrowFunctionExpression([], t.blockStatement(body)),
424
+ []
425
+ )
426
+ );
427
+ },
428
+ },
429
+ };
430
+ }