@sigil-dev/compiler 0.9.26 → 0.9.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,899 +1,1012 @@
1
- /**
2
- * Which components need JavaScript in the browser, and why.
3
- *
4
- * A component that has no state, effects, handlers, bindings or refs, and
5
- * whose every child is also like that, only produces HTML. Hydrating it means
6
- * claiming nodes and attaching nothing, so it is work the browser could skip.
7
- *
8
- * This module only *decides and explains*. It changes no generated code; the
9
- * report (`sigil explain`) and the `static` assertion use it, so the analysis
10
- * can be checked against real projects before anything relies on it.
11
- *
12
- * The rule is conservative: **hydrate when unsure.** A wrong "static" is a
13
- * page that looks right and does nothing, which is much worse than shipping a
14
- * little JavaScript, so anything the analysis cannot see into counts as
15
- * dynamic, and says what it could not see:
16
- *
17
- * - a function imported from a package, or from a project file that reads
18
- * state (`calls formatDate, which reads state`)
19
- * - a component from a package, from props, or `Window`/`Head` and friends
20
- * - a spread, a directive, a ref
21
- *
22
- * Whether a particular *use* of a static component is static also depends on
23
- * what the use passes it (a reactive prop makes that use dynamic). That is the
24
- * use-site check, `useSiteReasons`.
25
- */
26
-
27
- import { existsSync, readFileSync } from "node:fs";
28
- import { dirname, resolve as resolvePath } from "node:path";
29
- import type { NodePath } from "@babel/core";
30
- import { parseSync, types as t, traverse } from "@babel/core";
31
-
32
- export type ReasonKind =
33
- | "state"
34
- | "effect"
35
- | "handler"
36
- | "directive"
37
- | "ref"
38
- | "spread"
39
- | "imported-state"
40
- | "imported-call"
41
- | "unknown-import"
42
- | "child"
43
- | "unknown-child"
44
- | "global"
45
- | "async"
46
- | "recursive"
47
- | "reactive-prop"
48
- | "parent-prop";
49
-
50
- export interface Reason {
51
- kind: ReasonKind;
52
- line: number;
53
- detail: string;
54
- /** The file the reason is in, when it is not the component's own. */
55
- file?: string;
56
- }
57
-
58
- /**
59
- * - `static`: produces only HTML.
60
- * - `conditional`: static as long as the children it is given are. It renders
61
- * `children`, so each use decides.
62
- * - `dynamic`: needs JavaScript; `reasons` says why.
63
- */
64
- export type Verdict = "static" | "conditional" | "dynamic";
65
-
66
- export interface ComponentReport {
67
- name: string;
68
- file: string;
69
- line: number;
70
- verdict: Verdict;
71
- reasons: Reason[];
72
- }
73
-
74
- /** Resolve an import specifier from a file to a project file, or null. */
75
- export type Resolver = (spec: string, from: string) => string | null;
76
-
77
- const EXTENSIONS = [
78
- "",
79
- ".tsx",
80
- ".ts",
81
- ".jsx",
82
- ".js",
83
- "/index.tsx",
84
- "/index.ts",
85
- ];
86
-
87
- /**
88
- * Relative imports, then whatever Bun resolves (tsconfig `paths` such as
89
- * `$lib`). Anything that lands in `node_modules`, or does not resolve, is a
90
- * package: the analysis cannot see inside it.
91
- */
92
- export const defaultResolver: Resolver = (spec, from) => {
93
- if (spec.startsWith(".")) {
94
- for (const ext of EXTENSIONS) {
95
- const candidate = resolvePath(dirname(from), spec + ext);
96
- if (/\.[jt]sx?$/.test(candidate) && existsSync(candidate))
97
- return candidate;
98
- }
99
- return null;
100
- }
101
- try {
102
- const found = (
103
- globalThis as { Bun?: { resolveSync(s: string, d: string): string } }
104
- ).Bun?.resolveSync(spec, dirname(from));
105
- if (!found || found.replace(/\\/g, "/").includes("/node_modules/"))
106
- return null;
107
- return /\.[jt]sx?$/.test(found) ? found : null;
108
- } catch {
109
- return null;
110
- }
111
- };
112
-
113
- const LIFECYCLE_MACROS = new Set(["$effect", "$inspect", "$debug"]);
114
- const GLOBAL_COMPONENTS = new Set(["Window", "Document", "Body"]);
115
-
116
- /**
117
- * `<Head>` from grimoire only puts its children in `<head>`, and the server
118
- * already did that, so for hydration it is as inert as a native element: only
119
- * its children can need JavaScript. Matched on where it was imported from, so a
120
- * component of the same name that is the project's own is analysed like any
121
- * other.
122
- */
123
- const isGrimoireHead = (info: ModuleInfo, tag: string): boolean =>
124
- tag === "Head" &&
125
- !!info.imports.get("Head")?.source.startsWith("@sigil-dev/grimoire");
126
-
127
- interface ImportInfo {
128
- source: string;
129
- imported: string;
130
- typeOnly: boolean;
131
- }
132
-
133
- interface ModuleInfo {
134
- file: string;
135
- ast: t.File;
136
- imports: Map<string, ImportInfo>;
137
- /** Names declared with a state macro anywhere in the file. */
138
- stateNames: Set<string>;
139
- /** Module-level state that is exported, by exported name. */
140
- exportedState: Set<string>;
141
- /** Functions that read state (directly or through another such function). */
142
- reactiveFns: Set<string>;
143
- /** Exported name to local name. */
144
- exports: Map<string, string>;
145
- components: Map<string, NodePath<t.Function>>;
146
- }
147
-
148
- const modules = new Map<string, ModuleInfo | null>();
149
-
150
- /** Forget cached modules, for a long-lived process (dev server) after a file changes. */
151
- export function clearAnalysisCache(file?: string): void {
152
- if (file) modules.delete(file);
153
- else modules.clear();
154
- }
155
-
156
- function parse(code: string, file: string): t.File | null {
157
- try {
158
- return parseSync(code, {
159
- filename: file,
160
- babelrc: false,
161
- configFile: false,
162
- parserOpts: {
163
- // @ts-expect-error babel's option type does not list the tuple form
164
- plugins: [["typescript", { isTSX: true }], "jsx"],
165
- },
166
- }) as t.File | null;
167
- } catch {
168
- return null;
169
- }
170
- }
171
-
172
- const isMacroName = (name: string) =>
173
- name === "$state" ||
174
- name === "$state.raw" ||
175
- name === "$store" ||
176
- name === "$derived" ||
177
- name === "$derived.by";
178
-
179
- function macroNameOf(init: t.Node | null | undefined): string | null {
180
- if (!init || !t.isCallExpression(init)) return null;
181
- const c = init.callee;
182
- if (t.isIdentifier(c)) return c.name;
183
- if (
184
- t.isMemberExpression(c) &&
185
- t.isIdentifier(c.object) &&
186
- t.isIdentifier(c.property)
187
- ) {
188
- return `${c.object.name}.${c.property.name}`;
189
- }
190
- return null;
191
- }
192
-
193
- function lineOf(node: t.Node): number {
194
- return node.loc?.start.line ?? 0;
195
- }
196
-
197
- function loadModule(file: string, source?: string): ModuleInfo | null {
198
- if (source === undefined && modules.has(file)) return modules.get(file)!;
199
- let code = source;
200
- if (code === undefined) {
201
- try {
202
- code = readFileSync(file, "utf8");
203
- } catch {
204
- modules.set(file, null);
205
- return null;
206
- }
207
- }
208
- const ast = parse(code, file);
209
- if (!ast) {
210
- if (source === undefined) modules.set(file, null);
211
- return null;
212
- }
213
-
214
- const info: ModuleInfo = {
215
- file,
216
- ast,
217
- imports: new Map(),
218
- stateNames: new Set(),
219
- exportedState: new Set(),
220
- reactiveFns: new Set(),
221
- exports: new Map(),
222
- components: new Map(),
223
- };
224
- const fns = new Map<string, NodePath>();
225
-
226
- traverse(ast, {
227
- ImportDeclaration(path) {
228
- const typeOnly = path.node.importKind === "type";
229
- for (const s of path.node.specifiers) {
230
- const imported = t.isImportDefaultSpecifier(s)
231
- ? "default"
232
- : t.isImportNamespaceSpecifier(s)
233
- ? "*"
234
- : t.isIdentifier(s.imported)
235
- ? s.imported.name
236
- : s.imported.value;
237
- info.imports.set(s.local.name, {
238
- source: path.node.source.value,
239
- imported,
240
- typeOnly:
241
- typeOnly || (t.isImportSpecifier(s) && s.importKind === "type"),
242
- });
243
- }
244
- },
245
- VariableDeclarator(path) {
246
- const id = path.node.id;
247
- if (!t.isIdentifier(id)) return;
248
- const macro = macroNameOf(path.node.init);
249
- if (macro && isMacroName(macro)) {
250
- info.stateNames.add(id.name);
251
- if (
252
- path.parentPath.parentPath?.isProgram() ||
253
- path.parentPath.parentPath?.isExportNamedDeclaration()
254
- ) {
255
- info.exportedState.add(id.name);
256
- }
257
- }
258
- const init = path.get("init");
259
- if (init.isArrowFunctionExpression() || init.isFunctionExpression()) {
260
- fns.set(id.name, init);
261
- if (/^[A-Z]/.test(id.name))
262
- info.components.set(id.name, init as NodePath<t.Function>);
263
- }
264
- },
265
- FunctionDeclaration(path) {
266
- if (!path.node.id) return;
267
- fns.set(path.node.id.name, path);
268
- if (/^[A-Z]/.test(path.node.id.name))
269
- info.components.set(path.node.id.name, path);
270
- },
271
- ExportNamedDeclaration(path) {
272
- const d = path.node.declaration;
273
- if (d && t.isVariableDeclaration(d)) {
274
- for (const decl of d.declarations) {
275
- if (t.isIdentifier(decl.id))
276
- info.exports.set(decl.id.name, decl.id.name);
277
- }
278
- } else if (d && t.isFunctionDeclaration(d) && d.id) {
279
- info.exports.set(d.id.name, d.id.name);
280
- }
281
- if (!path.node.source) {
282
- for (const s of path.node.specifiers) {
283
- if (t.isExportSpecifier(s)) {
284
- const exported = t.isIdentifier(s.exported)
285
- ? s.exported.name
286
- : s.exported.value;
287
- info.exports.set(exported, s.local.name);
288
- }
289
- }
290
- }
291
- },
292
- ExportDefaultDeclaration(path) {
293
- const d = path.node.declaration;
294
- if (t.isIdentifier(d)) info.exports.set("default", d.name);
295
- else if (
296
- (t.isFunctionDeclaration(d) || t.isClassDeclaration(d)) &&
297
- d.id
298
- ) {
299
- info.exports.set("default", d.id.name);
300
- }
301
- },
302
- });
303
-
304
- // functions that read state, to a fixed point (a helper may be declared later)
305
- const readsState = (fn: NodePath): boolean => {
306
- let found = false;
307
- fn.traverse({
308
- Identifier(p) {
309
- if (
310
- !found &&
311
- p.isReferencedIdentifier() &&
312
- info.stateNames.has(p.node.name)
313
- )
314
- found = true;
315
- },
316
- CallExpression(p) {
317
- const c = p.node.callee;
318
- if (!found && t.isIdentifier(c) && info.reactiveFns.has(c.name))
319
- found = true;
320
- },
321
- });
322
- return found;
323
- };
324
- let changed = true;
325
- while (changed) {
326
- changed = false;
327
- for (const [name, fn] of fns) {
328
- if (info.reactiveFns.has(name) || /^[A-Z]/.test(name)) continue;
329
- if (readsState(fn)) {
330
- info.reactiveFns.add(name);
331
- changed = true;
332
- }
333
- }
334
- }
335
-
336
- if (source === undefined) modules.set(file, info);
337
- return info;
338
- }
339
-
340
- // ---------------------------------------------------------------------------
341
-
342
- interface Ctx {
343
- resolve: Resolver;
344
- /** `file#Name` in progress, to stop a cycle. */
345
- stack: Set<string>;
346
- memo: Map<string, ComponentReport>;
347
- }
348
-
349
- const newCtx = (resolve: Resolver): Ctx => ({
350
- resolve,
351
- stack: new Set(),
352
- memo: new Map(),
353
- });
354
-
355
- /**
356
- * The report for `<Tag>` as written in `info`'s file: a component declared
357
- * there, or one imported from a project file. Anything else is a reason the
358
- * analysis cannot see in.
359
- */
360
- function reportForTag(
361
- info: ModuleInfo,
362
- tag: string,
363
- ctx: Ctx,
364
- ): ComponentReport | { kind: ReasonKind; detail: string } {
365
- if (info.components.has(tag)) return analyzeIn(info, tag, ctx);
366
- const imp = info.imports.get(tag);
367
- if (!imp) {
368
- return {
369
- kind: "unknown-child",
370
- detail: `renders <${tag}>, which is not declared in this file`,
371
- };
372
- }
373
- const target = ctx.resolve(imp.source, info.file);
374
- const mod = target ? loadModule(target) : null;
375
- if (!mod) {
376
- return {
377
- kind: "unknown-child",
378
- detail: `renders <${tag}> from '${imp.source}', which the analysis cannot see inside`,
379
- };
380
- }
381
- return analyzeIn(mod, mod.exports.get(imp.imported) ?? imp.imported, ctx);
382
- }
383
-
384
- function analyzeIn(info: ModuleInfo, name: string, ctx: Ctx): ComponentReport {
385
- const key = `${info.file}#${name}`;
386
- const cached = ctx.memo.get(key);
387
- if (cached) return cached;
388
- const fn = info.components.get(name);
389
- const line = fn ? lineOf(fn.node) : 0;
390
- if (!fn) {
391
- return {
392
- name,
393
- file: info.file,
394
- line,
395
- verdict: "dynamic",
396
- reasons: [
397
- {
398
- kind: "unknown-child",
399
- line,
400
- detail: `${name} is not a component the analysis can find in ${info.file}`,
401
- },
402
- ],
403
- };
404
- }
405
- if (ctx.stack.has(key)) {
406
- return {
407
- name,
408
- file: info.file,
409
- line,
410
- verdict: "dynamic",
411
- reasons: [{ kind: "recursive", line, detail: `${name} renders itself` }],
412
- };
413
- }
414
- ctx.stack.add(key);
415
-
416
- const reasons: Reason[] = [];
417
- let conditional = false;
418
- const add = (kind: ReasonKind, node: t.Node, detail: string, file?: string) =>
419
- reasons.push({
420
- kind,
421
- line: lineOf(node),
422
- detail,
423
- ...(file ? { file } : {}),
424
- });
425
-
426
- if (fn.node.async) add("async", fn.node, `${name} is async`);
427
-
428
- // the props parameter: reads of it are fine, and its names are not "imports"
429
- const propNames = new Set<string>();
430
- for (const p of fn.node.params) {
431
- if (t.isIdentifier(p)) propNames.add(p.name);
432
- }
433
-
434
- /** True when `path` sits inside a function that is not the component itself. */
435
- const inNested = (path: NodePath): boolean => {
436
- const f = path.getFunctionParent();
437
- return !!f && f.node !== fn.node;
438
- };
439
-
440
- fn.traverse({
441
- VariableDeclarator(p) {
442
- const macro = macroNameOf(p.node.init);
443
- if (macro && isMacroName(macro))
444
- add(
445
- "state",
446
- p.node,
447
- `declares ${macro} \`${t.isIdentifier(p.node.id) ? p.node.id.name : "…"}\``,
448
- );
449
- },
450
- CallExpression(p) {
451
- const c = p.node.callee;
452
- if (t.isIdentifier(c) && LIFECYCLE_MACROS.has(c.name)) {
453
- add("effect", p.node, `calls ${c.name}`);
454
- }
455
- },
456
- JSXAttribute(p) {
457
- const n = p.node.name;
458
- if (t.isJSXNamespacedName(n)) {
459
- add(
460
- "directive",
461
- p.node,
462
- `uses the \`${n.namespace.name}:${n.name.name}\` directive`,
463
- );
464
- } else if (/^on[A-Z]/.test(n.name)) {
465
- add("handler", p.node, `has an ${n.name} handler`);
466
- } else if (n.name === "ref") {
467
- add("ref", p.node, "has a ref");
468
- }
469
- },
470
- JSXSpreadAttribute(p) {
471
- add("spread", p.node, "spreads props");
472
- },
473
- JSXOpeningElement(p) {
474
- const nameNode = p.node.name;
475
- if (t.isJSXMemberExpression(nameNode)) {
476
- add(
477
- "unknown-child",
478
- p.node,
479
- "renders a component from a member expression, which the analysis cannot resolve",
480
- );
481
- return;
482
- }
483
- if (!t.isJSXIdentifier(nameNode) || !/^[A-Z]/.test(nameNode.name)) return;
484
- const tag = nameNode.name;
485
- if (isGrimoireHead(info, tag)) return;
486
- if (GLOBAL_COMPONENTS.has(tag)) {
487
- add("global", p.node, `renders <${tag}>, which touches the browser`);
488
- return;
489
- }
490
- if (propNames.has(tag)) {
491
- add(
492
- "unknown-child",
493
- p.node,
494
- `renders <${tag}>, a component from props`,
495
- );
496
- return;
497
- }
498
- const found = reportForTag(info, tag, ctx);
499
- if ("detail" in found) add(found.kind, p.node, found.detail);
500
- else absorb(found, p.node, tag);
501
- },
502
- MemberExpression(p) {
503
- // props.children: what this renders depends on what each use passes
504
- const prop = p.node.property;
505
- if (
506
- !p.node.computed &&
507
- t.isIdentifier(prop) &&
508
- prop.name === "children"
509
- ) {
510
- conditional = true;
511
- }
512
- },
513
- Identifier(p) {
514
- const name = p.node.name;
515
- if (!p.isReferencedIdentifier()) return;
516
- if (name === "children") conditional = true;
517
- if (propNames.has(name)) return;
518
- // module-level state read while rendering
519
- if (
520
- info.stateNames.has(name) &&
521
- !p.scope.getBinding(name)?.path.findParent((x) => x === fn)
522
- ) {
523
- add("state", p.node, `reads state \`${name}\``);
524
- return;
525
- }
526
- const imp = info.imports.get(name);
527
- if (!imp || imp.typeOnly) return;
528
- if (p.findParent((x) => x.isTSType())) return;
529
- // used as a JSX tag is a child component, handled above
530
- if (
531
- p.parentPath.isJSXOpeningElement() ||
532
- p.parentPath.isJSXClosingElement()
533
- )
534
- return;
535
- if (inNested(p) && !p.parentPath.isCallExpression()) return;
536
- const target = ctx.resolve(imp.source, info.file);
537
- const mod = target ? loadModule(target) : null;
538
- if (!mod) {
539
- // A bare value from a package could be anything. Calls are the
540
- // risk (they may read state); a plain value is a constant.
541
- if (p.parentPath.isCallExpression({ callee: p.node })) {
542
- add(
543
- "unknown-import",
544
- p.node,
545
- `calls \`${name}\` from '${imp.source}', which the analysis cannot see inside`,
546
- );
547
- }
548
- return;
549
- }
550
- const exportedAs = mod.exports.get(imp.imported) ?? imp.imported;
551
- if (mod.exportedState.has(exportedAs) || mod.stateNames.has(exportedAs)) {
552
- add(
553
- "imported-state",
554
- p.node,
555
- `reads \`${name}\`, which is state in ${shortFile(mod.file)}`,
556
- mod.file,
557
- );
558
- } else if (mod.reactiveFns.has(exportedAs)) {
559
- add(
560
- "imported-call",
561
- p.node,
562
- `uses \`${name}\`, which reads state in ${shortFile(mod.file)}`,
563
- mod.file,
564
- );
565
- }
566
- },
567
- });
568
-
569
- function absorb(sub: ComponentReport, node: t.Node, tag: string) {
570
- if (sub.verdict === "dynamic") {
571
- const first = sub.reasons[0];
572
- add(
573
- "child",
574
- node,
575
- `renders <${tag}>, which hydrates: ${first ? first.detail : "needs JavaScript"}`,
576
- sub.file,
577
- );
578
- } else if (sub.verdict === "conditional") {
579
- conditional = true;
580
- }
581
- }
582
-
583
- ctx.stack.delete(key);
584
- const verdict: Verdict = reasons.length
585
- ? "dynamic"
586
- : conditional
587
- ? "conditional"
588
- : "static";
589
- const report: ComponentReport = {
590
- name,
591
- file: info.file,
592
- line,
593
- verdict,
594
- reasons,
595
- };
596
- ctx.memo.set(key, report);
597
- return report;
598
- }
599
-
600
- const shortFile = (f: string) =>
601
- f.replace(/\\/g, "/").split("/").slice(-2).join("/");
602
-
603
- /**
604
- * Analyse every component declared in `file`.
605
- *
606
- * `source` overrides what is on disk, for code that is not saved yet or for
607
- * tests; imports are still resolved against the real file system.
608
- */
609
- export function analyzeFile(
610
- file: string,
611
- options: { resolve?: Resolver; source?: string } = {},
612
- ): ComponentReport[] {
613
- const info = loadModule(file, options.source);
614
- if (!info) return [];
615
- const ctx = newCtx(options.resolve ?? defaultResolver);
616
- return [...info.components.keys()].map((name) => analyzeIn(info, name, ctx));
617
- }
618
-
619
- // ---------------------------------------------------------------------------
620
- // use sites
621
- // ---------------------------------------------------------------------------
622
-
623
- /**
624
- * Why *this use* of a component cannot be static, whatever the component is.
625
- *
626
- * A static component given a reactive prop still changes, so each use is
627
- * checked on what it passes: a spread, a prop that reads state, a prop that
628
- * comes from the enclosing component's own props (which its parent may be
629
- * driving), and children that are not static themselves.
630
- */
631
- export function useSiteReasons(
632
- element: t.JSXElement,
633
- scope: {
634
- stateNames: Set<string>;
635
- reactiveFns: Set<string>;
636
- propNames: Set<string>;
637
- /** Describes an imported name that reads state, or null. */
638
- importedReactive?: (name: string) => string | null;
639
- },
640
- ): Reason[] {
641
- const reasons: Reason[] = [];
642
- const reads = (expr: t.Node): string | null => {
643
- let found: string | null = null;
644
- const visit = (n: t.Node | null | undefined): void => {
645
- if (!n || found) return;
646
- if (t.isArrowFunctionExpression(n) || t.isFunctionExpression(n)) return;
647
- if (t.isIdentifier(n)) {
648
- if (scope.stateNames.has(n.name)) found = `state \`${n.name}\``;
649
- else if (scope.propNames.has(n.name))
650
- found = `prop object \`${n.name}\``;
651
- else found = scope.importedReactive?.(n.name) ?? null;
652
- return;
653
- }
654
- if (
655
- t.isCallExpression(n) &&
656
- t.isIdentifier(n.callee) &&
657
- scope.reactiveFns.has(n.callee.name)
658
- ) {
659
- found = `\`${n.callee.name}()\`, which reads state`;
660
- return;
661
- }
662
- for (const key of t.VISITOR_KEYS[n.type] ?? []) {
663
- const child = (n as unknown as Record<string, unknown>)[key];
664
- if (Array.isArray(child)) for (const c of child) visit(c as t.Node);
665
- else visit(child as t.Node);
666
- }
667
- };
668
- visit(expr);
669
- return found;
670
- };
671
- for (const attr of element.openingElement.attributes) {
672
- if (t.isJSXSpreadAttribute(attr)) {
673
- reasons.push({
674
- kind: "spread",
675
- line: lineOf(attr),
676
- detail: "passes a spread",
677
- });
678
- } else if (
679
- t.isJSXAttribute(attr) &&
680
- t.isJSXExpressionContainer(attr.value)
681
- ) {
682
- const hit = reads(attr.value.expression);
683
- if (hit) {
684
- const name = t.isJSXIdentifier(attr.name) ? attr.name.name : "prop";
685
- reasons.push({
686
- kind: hit.startsWith("prop") ? "parent-prop" : "reactive-prop",
687
- line: lineOf(attr),
688
- detail: `passes \`${name}\` from ${hit}, which can change`,
689
- });
690
- }
691
- }
692
- }
693
- for (const child of element.children) {
694
- if (
695
- t.isJSXExpressionContainer(child) &&
696
- !t.isJSXEmptyExpression(child.expression)
697
- ) {
698
- const hit = reads(child.expression);
699
- if (hit) {
700
- reasons.push({
701
- kind: "reactive-prop",
702
- line: lineOf(child),
703
- detail: `has a child that reads ${hit}`,
704
- });
705
- }
706
- }
707
- }
708
- return reasons;
709
- }
710
-
711
- /**
712
- * Everything that stops `<X static />` being true, as reasons. Empty means the
713
- * assertion holds.
714
- *
715
- * Three things have to be static together: the component, what this use passes
716
- * it, and every element written inside the use. The inside matters because a
717
- * static `<Card>` wrapping a `<Counter>` would otherwise skip Counter's
718
- * hydration and leave it dead.
719
- */
720
- export function checkStaticUse(
721
- element: NodePath<t.JSXElement>,
722
- file: string,
723
- source: string,
724
- resolve: Resolver = defaultResolver,
725
- ): Reason[] {
726
- const info = loadModule(file, source);
727
- if (!info) {
728
- return [
729
- {
730
- kind: "unknown-child",
731
- line: lineOf(element.node),
732
- detail: "the file could not be analysed",
733
- },
734
- ];
735
- }
736
- return useProblems(info, newCtx(resolve), element, resolve);
737
- }
738
-
739
- function useProblems(
740
- info: ModuleInfo,
741
- ctx: Ctx,
742
- element: NodePath<t.JSXElement>,
743
- resolve: Resolver,
744
- ): Reason[] {
745
- const file = info.file;
746
- const at = (kind: ReasonKind, node: t.Node, detail: string): Reason => ({
747
- kind,
748
- line: lineOf(node),
749
- detail,
750
- });
751
-
752
- const nameNode = element.node.openingElement.name;
753
- if (!t.isJSXIdentifier(nameNode) || !/^[A-Z]/.test(nameNode.name)) {
754
- return [
755
- at(
756
- "unknown-child",
757
- element.node,
758
- "`static` applies to components, not to HTML elements",
759
- ),
760
- ];
761
- }
762
-
763
- // the enclosing component's own props: a value from them may be driven by its parent
764
- const propNames = new Set<string>();
765
- const fn = element.getFunctionParent();
766
- for (const p of fn?.node.params ?? []) {
767
- if (t.isIdentifier(p)) propNames.add(p.name);
768
- else if (t.isObjectPattern(p)) {
769
- for (const prop of p.properties) {
770
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value))
771
- propNames.add(prop.value.name);
772
- else if (t.isRestElement(prop) && t.isIdentifier(prop.argument))
773
- propNames.add(prop.argument.name);
774
- }
775
- }
776
- }
777
- const importedReactive = (name: string): string | null => {
778
- const imp = info.imports.get(name);
779
- if (!imp || imp.typeOnly) return null;
780
- const target = resolve(imp.source, file);
781
- const mod = target ? loadModule(target) : null;
782
- if (!mod) return null;
783
- const exported = mod.exports.get(imp.imported) ?? imp.imported;
784
- if (mod.exportedState.has(exported) || mod.stateNames.has(exported))
785
- return `imported state \`${name}\``;
786
- if (mod.reactiveFns.has(exported)) return `\`${name}\`, which reads state`;
787
- return null;
788
- };
789
- const scope = {
790
- stateNames: info.stateNames,
791
- reactiveFns: info.reactiveFns,
792
- propNames,
793
- importedReactive,
794
- };
795
-
796
- const problems: Reason[] = [];
797
- const checkElement = (el: t.JSXElement) => {
798
- const open = el.openingElement;
799
- problems.push(...useSiteReasons(el, scope));
800
- for (const attr of open.attributes) {
801
- if (t.isJSXAttribute(attr)) {
802
- const n = attr.name;
803
- if (t.isJSXNamespacedName(n))
804
- problems.push(
805
- at(
806
- "directive",
807
- attr,
808
- `uses the \`${n.namespace.name}:${n.name.name}\` directive`,
809
- ),
810
- );
811
- else if (/^on[A-Z]/.test(n.name))
812
- problems.push(at("handler", attr, `has an ${n.name} handler`));
813
- else if (n.name === "ref") problems.push(at("ref", attr, "has a ref"));
814
- }
815
- }
816
- const name = open.name;
817
- if (!t.isJSXIdentifier(name) || !/^[A-Z]/.test(name.name)) return;
818
- if (isGrimoireHead(info, name.name)) return;
819
- if (GLOBAL_COMPONENTS.has(name.name)) {
820
- problems.push(
821
- at("global", el, `renders <${name.name}>, which touches the browser`),
822
- );
823
- return;
824
- }
825
- const found = reportForTag(info, name.name, ctx);
826
- if ("detail" in found) {
827
- problems.push(at(found.kind, el, found.detail));
828
- } else if (found.verdict === "dynamic") {
829
- const first = found.reasons[0];
830
- problems.push(
831
- at(
832
- "child",
833
- el,
834
- `<${name.name}> hydrates: ${first ? first.detail : "needs JavaScript"}`,
835
- ),
836
- );
837
- }
838
- };
839
-
840
- checkElement(element.node);
841
- t.traverseFast(element.node, (n) => {
842
- if (n !== element.node && t.isJSXElement(n)) checkElement(n);
843
- });
844
- return problems;
845
- }
846
-
847
- export type { ModuleInfo };
848
- /**
849
- * The component uses in this file that produce only HTML, by node.
850
- *
851
- * Both the server and the browser build of a file ask this, and must get the
852
- * same answer, because the server wraps exactly these uses in markers and the
853
- * browser skips exactly these uses. It is computed from the file's own source
854
- * and what it imports, never from the mode, so the two builds cannot drift.
855
- *
856
- * Only a use that is a direct child of an HTML element qualifies. That is the
857
- * one position where hydration holds the server's nodes in a pool the use can
858
- * be cut out of: a use inside a condition, a list, a component's children or a
859
- * fragment hydrates through other machinery and is left alone.
860
- */
861
- export const STATIC_USES = new WeakSet<t.JSXElement>();
862
-
863
- /** Uses marked `static={false}`: the author's override, so they always hydrate. */
864
- export const FORCE_HYDRATE = new WeakSet<t.JSXElement>();
865
-
866
- const NO_SKIP_PARENTS = new Set(["script", "style", "textarea"]);
867
-
868
- export function markStaticUses(
869
- program: NodePath<t.Program>,
870
- file: string,
871
- source: string,
872
- resolve: Resolver = defaultResolver,
873
- ): void {
874
- const info = loadModule(file, source);
875
- if (!info) return;
876
- const ctx = newCtx(resolve);
877
- program.traverse({
878
- JSXElement(path) {
879
- const name = path.node.openingElement.name;
880
- if (!t.isJSXIdentifier(name) || !/^[A-Z]/.test(name.name)) return;
881
- const parent = path.parent;
882
- if (!t.isJSXElement(parent)) return;
883
- const pn = parent.openingElement.name;
884
- if (
885
- !t.isJSXIdentifier(pn) ||
886
- !/^[a-z]/.test(pn.name) ||
887
- NO_SKIP_PARENTS.has(pn.name)
888
- )
889
- return;
890
- if (isGrimoireHead(info, name.name)) return;
891
- if (FORCE_HYDRATE.has(path.node)) return;
892
- if (useProblems(info, ctx, path, resolve).length === 0) {
893
- STATIC_USES.add(path.node);
894
- }
895
- },
896
- });
897
- }
898
-
899
- export { loadModule as _loadModule };
1
+ /**
2
+ * Which components need JavaScript in the browser, and why.
3
+ *
4
+ * A component that has no state, effects, handlers, bindings or refs, and
5
+ * whose every child is also like that, only produces HTML. Hydrating it means
6
+ * claiming nodes and attaching nothing, so it is work the browser could skip.
7
+ *
8
+ * This module only *decides and explains*. It changes no generated code; the
9
+ * report (`sigil explain`) and the `static` assertion use it, so the analysis
10
+ * can be checked against real projects before anything relies on it.
11
+ *
12
+ * The rule is conservative: **hydrate when unsure.** A wrong "static" is a
13
+ * page that looks right and does nothing, which is much worse than shipping a
14
+ * little JavaScript, so anything the analysis cannot see into counts as
15
+ * dynamic, and says what it could not see:
16
+ *
17
+ * - a function imported from a package, or from a project file that reads
18
+ * state (`calls formatDate, which reads state`)
19
+ * - a component from a package, from props, or `Window`/`Head` and friends
20
+ * - a spread, a directive, a ref
21
+ *
22
+ * Whether a particular *use* of a static component is static also depends on
23
+ * what the use passes it (a reactive prop makes that use dynamic). That is the
24
+ * use-site check, `useSiteReasons`.
25
+ */
26
+
27
+ import { existsSync, readFileSync, statSync } from "node:fs";
28
+ import { dirname, join, resolve as resolvePath } from "node:path";
29
+ import type { NodePath } from "@babel/core";
30
+ import { parseSync, types as t, traverse } from "@babel/core";
31
+
32
+ export type ReasonKind =
33
+ | "state"
34
+ | "effect"
35
+ | "handler"
36
+ | "directive"
37
+ | "ref"
38
+ | "spread"
39
+ | "imported-state"
40
+ | "imported-call"
41
+ | "unknown-import"
42
+ | "child"
43
+ | "unknown-child"
44
+ | "global"
45
+ | "async"
46
+ | "recursive"
47
+ | "reactive-prop"
48
+ | "parent-prop";
49
+
50
+ export interface Reason {
51
+ kind: ReasonKind;
52
+ line: number;
53
+ detail: string;
54
+ /** The file the reason is in, when it is not the component's own. */
55
+ file?: string;
56
+ }
57
+
58
+ /**
59
+ * - `static`: produces only HTML.
60
+ * - `conditional`: static as long as the children it is given are. It renders
61
+ * `children`, so each use decides.
62
+ * - `dynamic`: needs JavaScript; `reasons` says why.
63
+ */
64
+ export type Verdict = "static" | "conditional" | "dynamic";
65
+
66
+ export interface ComponentReport {
67
+ name: string;
68
+ file: string;
69
+ line: number;
70
+ verdict: Verdict;
71
+ reasons: Reason[];
72
+ }
73
+
74
+ /** Resolve an import specifier from a file to a project file, or null. */
75
+ export type Resolver = (spec: string, from: string) => string | null;
76
+
77
+ const EXTENSIONS = [
78
+ "",
79
+ ".tsx",
80
+ ".ts",
81
+ ".jsx",
82
+ ".js",
83
+ "/index.tsx",
84
+ "/index.ts",
85
+ ];
86
+
87
+ /**
88
+ * Relative imports, then whatever Bun resolves (tsconfig `paths` such as
89
+ * `$lib`). Anything that lands in `node_modules`, or does not resolve, is a
90
+ * package: the analysis cannot see inside it.
91
+ */
92
+ function probe(base: string): string | null {
93
+ for (const ext of EXTENSIONS) {
94
+ const candidate = base + ext;
95
+ if (/\.[jt]sx?$/.test(candidate) && existsSync(candidate)) return candidate;
96
+ }
97
+ return null;
98
+ }
99
+
100
+ export const defaultResolver: Resolver = (spec, from) => {
101
+ if (spec.startsWith(".")) return probe(resolvePath(dirname(from), spec));
102
+ try {
103
+ const found = (
104
+ globalThis as { Bun?: { resolveSync(s: string, d: string): string } }
105
+ ).Bun?.resolveSync(spec, dirname(from));
106
+ if (!found || found.replace(/\\/g, "/").includes("/node_modules/"))
107
+ return null;
108
+ return /\.[jt]sx?$/.test(found) ? found : null;
109
+ } catch {
110
+ return null;
111
+ }
112
+ };
113
+
114
+ /**
115
+ * The default resolver plus import aliases (`$lib` and friends): prefix to
116
+ * absolute directory, as grimoire's config defines them. Bun has no alias
117
+ * option of its own, so these are not visible to `Bun.resolveSync`.
118
+ */
119
+ export function createResolver(aliases: Record<string, string> = {}): Resolver {
120
+ const entries = Object.entries(aliases);
121
+ if (entries.length === 0) return defaultResolver;
122
+ return (spec, from) => {
123
+ for (const [prefix, dir] of entries) {
124
+ if (spec !== prefix && !spec.startsWith(`${prefix}/`)) continue;
125
+ return probe(join(dir, spec.slice(prefix.length)));
126
+ }
127
+ return defaultResolver(spec, from);
128
+ };
129
+ }
130
+
131
+ const LIFECYCLE_MACROS = new Set(["$effect", "$inspect", "$debug"]);
132
+ const GLOBAL_COMPONENTS = new Set(["Window", "Document", "Body"]);
133
+
134
+ /**
135
+ * `<Head>` from grimoire only puts its children in `<head>`, and the server
136
+ * already did that, so for hydration it is as inert as a native element: only
137
+ * its children can need JavaScript. Matched on where it was imported from, so a
138
+ * component of the same name that is the project's own is analysed like any
139
+ * other.
140
+ */
141
+ const isGrimoireHead = (info: ModuleInfo, tag: string): boolean =>
142
+ tag === "Head" &&
143
+ !!info.imports.get("Head")?.source.startsWith("@sigil-dev/grimoire");
144
+
145
+ interface ImportInfo {
146
+ source: string;
147
+ imported: string;
148
+ typeOnly: boolean;
149
+ }
150
+
151
+ interface ModuleInfo {
152
+ file: string;
153
+ ast: t.File;
154
+ imports: Map<string, ImportInfo>;
155
+ /** Names declared with a state macro anywhere in the file. */
156
+ stateNames: Set<string>;
157
+ /** Module-level state that is exported, by exported name. */
158
+ exportedState: Set<string>;
159
+ /** Module-level `$derived` names (a subset of exportedState). */
160
+ derivedNames: Set<string>;
161
+ /** `export { a as b } from "./x"` and `export * from "./x"` ("*"). */
162
+ reexports: { source: string; imported: string; exported: string }[];
163
+ /** Functions that read state (directly or through another such function). */
164
+ reactiveFns: Set<string>;
165
+ /** Exported name to local name. */
166
+ exports: Map<string, string>;
167
+ components: Map<string, NodePath<t.Function>>;
168
+ }
169
+
170
+ const modules = new Map<string, ModuleInfo | null>();
171
+ const mtimes = new Map<string, number>();
172
+
173
+ function mtimeOf(file: string): number {
174
+ try {
175
+ return statSync(file).mtimeMs;
176
+ } catch {
177
+ return -1;
178
+ }
179
+ }
180
+
181
+ /** Forget cached modules, for a long-lived process (dev server) after a file changes. */
182
+ export function clearAnalysisCache(file?: string): void {
183
+ if (file) modules.delete(file);
184
+ else modules.clear();
185
+ }
186
+
187
+ function parse(code: string, file: string): t.File | null {
188
+ try {
189
+ return parseSync(code, {
190
+ filename: file,
191
+ babelrc: false,
192
+ configFile: false,
193
+ parserOpts: {
194
+ // @ts-expect-error babel's option type does not list the tuple form
195
+ plugins: [["typescript", { isTSX: true }], "jsx"],
196
+ },
197
+ }) as t.File | null;
198
+ } catch {
199
+ return null;
200
+ }
201
+ }
202
+
203
+ const isMacroName = (name: string) =>
204
+ name === "$state" ||
205
+ name === "$state.raw" ||
206
+ name === "$store" ||
207
+ name === "$derived" ||
208
+ name === "$derived.by";
209
+
210
+ function macroNameOf(init: t.Node | null | undefined): string | null {
211
+ if (!init || !t.isCallExpression(init)) return null;
212
+ const c = init.callee;
213
+ if (t.isIdentifier(c)) return c.name;
214
+ if (
215
+ t.isMemberExpression(c) &&
216
+ t.isIdentifier(c.object) &&
217
+ t.isIdentifier(c.property)
218
+ ) {
219
+ return `${c.object.name}.${c.property.name}`;
220
+ }
221
+ return null;
222
+ }
223
+
224
+ function lineOf(node: t.Node): number {
225
+ return node.loc?.start.line ?? 0;
226
+ }
227
+
228
+ function loadModule(file: string, source?: string): ModuleInfo | null {
229
+ if (source === undefined && modules.has(file)) {
230
+ // a long-lived process (dev server) sees files change under it
231
+ if (mtimes.get(file) === mtimeOf(file)) return modules.get(file)!;
232
+ modules.delete(file);
233
+ }
234
+ let code = source;
235
+ if (code === undefined) {
236
+ try {
237
+ code = readFileSync(file, "utf8");
238
+ } catch {
239
+ modules.set(file, null);
240
+ return null;
241
+ }
242
+ }
243
+ const ast = parse(code, file);
244
+ if (!ast) {
245
+ if (source === undefined) modules.set(file, null);
246
+ return null;
247
+ }
248
+
249
+ const info: ModuleInfo = {
250
+ file,
251
+ ast,
252
+ imports: new Map(),
253
+ stateNames: new Set(),
254
+ exportedState: new Set(),
255
+ derivedNames: new Set(),
256
+ reexports: [],
257
+ reactiveFns: new Set(),
258
+ exports: new Map(),
259
+ components: new Map(),
260
+ };
261
+ const fns = new Map<string, NodePath>();
262
+
263
+ traverse(ast, {
264
+ ImportDeclaration(path) {
265
+ const typeOnly = path.node.importKind === "type";
266
+ for (const s of path.node.specifiers) {
267
+ const imported = t.isImportDefaultSpecifier(s)
268
+ ? "default"
269
+ : t.isImportNamespaceSpecifier(s)
270
+ ? "*"
271
+ : t.isIdentifier(s.imported)
272
+ ? s.imported.name
273
+ : s.imported.value;
274
+ info.imports.set(s.local.name, {
275
+ source: path.node.source.value,
276
+ imported,
277
+ typeOnly:
278
+ typeOnly || (t.isImportSpecifier(s) && s.importKind === "type"),
279
+ });
280
+ }
281
+ },
282
+ VariableDeclarator(path) {
283
+ const id = path.node.id;
284
+ if (!t.isIdentifier(id)) return;
285
+ const macro = macroNameOf(path.node.init);
286
+ if (macro && isMacroName(macro)) {
287
+ info.stateNames.add(id.name);
288
+ if (
289
+ path.parentPath.parentPath?.isProgram() ||
290
+ path.parentPath.parentPath?.isExportNamedDeclaration()
291
+ ) {
292
+ info.exportedState.add(id.name);
293
+ if (macro === "$derived") info.derivedNames.add(id.name);
294
+ }
295
+ }
296
+ const init = path.get("init");
297
+ if (init.isArrowFunctionExpression() || init.isFunctionExpression()) {
298
+ fns.set(id.name, init);
299
+ if (/^[A-Z]/.test(id.name))
300
+ info.components.set(id.name, init as NodePath<t.Function>);
301
+ }
302
+ },
303
+ FunctionDeclaration(path) {
304
+ if (!path.node.id) return;
305
+ fns.set(path.node.id.name, path);
306
+ if (/^[A-Z]/.test(path.node.id.name))
307
+ info.components.set(path.node.id.name, path);
308
+ },
309
+ ExportNamedDeclaration(path) {
310
+ const d = path.node.declaration;
311
+ if (d && t.isVariableDeclaration(d)) {
312
+ for (const decl of d.declarations) {
313
+ if (t.isIdentifier(decl.id))
314
+ info.exports.set(decl.id.name, decl.id.name);
315
+ }
316
+ } else if (d && t.isFunctionDeclaration(d) && d.id) {
317
+ info.exports.set(d.id.name, d.id.name);
318
+ }
319
+ if (path.node.source) {
320
+ for (const s of path.node.specifiers) {
321
+ if (!t.isExportSpecifier(s) || s.exportKind === "type") continue;
322
+ info.reexports.push({
323
+ source: path.node.source.value,
324
+ imported: t.isIdentifier(s.local) ? s.local.name : s.local.value,
325
+ exported: t.isIdentifier(s.exported)
326
+ ? s.exported.name
327
+ : s.exported.value,
328
+ });
329
+ }
330
+ }
331
+ if (!path.node.source) {
332
+ for (const s of path.node.specifiers) {
333
+ if (t.isExportSpecifier(s)) {
334
+ const exported = t.isIdentifier(s.exported)
335
+ ? s.exported.name
336
+ : s.exported.value;
337
+ info.exports.set(
338
+ exported,
339
+ t.isIdentifier(s.local) ? s.local.name : s.local.value,
340
+ );
341
+ }
342
+ }
343
+ }
344
+ },
345
+ ExportAllDeclaration(path) {
346
+ if (path.node.exportKind === "type") return;
347
+ info.reexports.push({
348
+ source: path.node.source.value,
349
+ imported: "*",
350
+ exported: "*",
351
+ });
352
+ },
353
+ ExportDefaultDeclaration(path) {
354
+ const d = path.node.declaration;
355
+ if (t.isIdentifier(d)) info.exports.set("default", d.name);
356
+ else if (
357
+ (t.isFunctionDeclaration(d) || t.isClassDeclaration(d)) &&
358
+ d.id
359
+ ) {
360
+ info.exports.set("default", d.id.name);
361
+ }
362
+ },
363
+ });
364
+
365
+ // functions that read state, to a fixed point (a helper may be declared later)
366
+ const readsState = (fn: NodePath): boolean => {
367
+ let found = false;
368
+ fn.traverse({
369
+ Identifier(p) {
370
+ if (
371
+ !found &&
372
+ p.isReferencedIdentifier() &&
373
+ info.stateNames.has(p.node.name)
374
+ )
375
+ found = true;
376
+ },
377
+ CallExpression(p) {
378
+ const c = p.node.callee;
379
+ if (!found && t.isIdentifier(c) && info.reactiveFns.has(c.name))
380
+ found = true;
381
+ },
382
+ });
383
+ return found;
384
+ };
385
+ let changed = true;
386
+ while (changed) {
387
+ changed = false;
388
+ for (const [name, fn] of fns) {
389
+ if (info.reactiveFns.has(name) || /^[A-Z]/.test(name)) continue;
390
+ if (readsState(fn)) {
391
+ info.reactiveFns.add(name);
392
+ changed = true;
393
+ }
394
+ }
395
+ }
396
+
397
+ if (source === undefined) {
398
+ modules.set(file, info);
399
+ mtimes.set(file, mtimeOf(file));
400
+ }
401
+ return info;
402
+ }
403
+
404
+ // ---------------------------------------------------------------------------
405
+
406
+ interface Ctx {
407
+ resolve: Resolver;
408
+ /** `file#Name` in progress, to stop a cycle. */
409
+ stack: Set<string>;
410
+ memo: Map<string, ComponentReport>;
411
+ }
412
+
413
+ const newCtx = (resolve: Resolver): Ctx => ({
414
+ resolve,
415
+ stack: new Set(),
416
+ memo: new Map(),
417
+ });
418
+
419
+ /**
420
+ * The report for `<Tag>` as written in `info`'s file: a component declared
421
+ * there, or one imported from a project file. Anything else is a reason the
422
+ * analysis cannot see in.
423
+ */
424
+ function reportForTag(
425
+ info: ModuleInfo,
426
+ tag: string,
427
+ ctx: Ctx,
428
+ ): ComponentReport | { kind: ReasonKind; detail: string } {
429
+ if (info.components.has(tag)) return analyzeIn(info, tag, ctx);
430
+ const imp = info.imports.get(tag);
431
+ if (!imp) {
432
+ return {
433
+ kind: "unknown-child",
434
+ detail: `renders <${tag}>, which is not declared in this file`,
435
+ };
436
+ }
437
+ const target = ctx.resolve(imp.source, info.file);
438
+ const mod = target ? loadModule(target) : null;
439
+ if (!mod) {
440
+ return {
441
+ kind: "unknown-child",
442
+ detail: `renders <${tag}> from '${imp.source}', which the analysis cannot see inside`,
443
+ };
444
+ }
445
+ return analyzeIn(mod, mod.exports.get(imp.imported) ?? imp.imported, ctx);
446
+ }
447
+
448
+ function analyzeIn(info: ModuleInfo, name: string, ctx: Ctx): ComponentReport {
449
+ const key = `${info.file}#${name}`;
450
+ const cached = ctx.memo.get(key);
451
+ if (cached) return cached;
452
+ const fn = info.components.get(name);
453
+ const line = fn ? lineOf(fn.node) : 0;
454
+ if (!fn) {
455
+ return {
456
+ name,
457
+ file: info.file,
458
+ line,
459
+ verdict: "dynamic",
460
+ reasons: [
461
+ {
462
+ kind: "unknown-child",
463
+ line,
464
+ detail: `${name} is not a component the analysis can find in ${info.file}`,
465
+ },
466
+ ],
467
+ };
468
+ }
469
+ if (ctx.stack.has(key)) {
470
+ return {
471
+ name,
472
+ file: info.file,
473
+ line,
474
+ verdict: "dynamic",
475
+ reasons: [{ kind: "recursive", line, detail: `${name} renders itself` }],
476
+ };
477
+ }
478
+ ctx.stack.add(key);
479
+
480
+ const reasons: Reason[] = [];
481
+ let conditional = false;
482
+ const add = (kind: ReasonKind, node: t.Node, detail: string, file?: string) =>
483
+ reasons.push({
484
+ kind,
485
+ line: lineOf(node),
486
+ detail,
487
+ ...(file ? { file } : {}),
488
+ });
489
+
490
+ if (fn.node.async) add("async", fn.node, `${name} is async`);
491
+
492
+ // the props parameter: reads of it are fine, and its names are not "imports"
493
+ const propNames = new Set<string>();
494
+ for (const p of fn.node.params) {
495
+ if (t.isIdentifier(p)) propNames.add(p.name);
496
+ }
497
+
498
+ /** True when `path` sits inside a function that is not the component itself. */
499
+ const inNested = (path: NodePath): boolean => {
500
+ const f = path.getFunctionParent();
501
+ return !!f && f.node !== fn.node;
502
+ };
503
+
504
+ fn.traverse({
505
+ VariableDeclarator(p) {
506
+ const macro = macroNameOf(p.node.init);
507
+ if (macro && isMacroName(macro))
508
+ add(
509
+ "state",
510
+ p.node,
511
+ `declares ${macro} \`${t.isIdentifier(p.node.id) ? p.node.id.name : "…"}\``,
512
+ );
513
+ },
514
+ CallExpression(p) {
515
+ const c = p.node.callee;
516
+ if (t.isIdentifier(c) && LIFECYCLE_MACROS.has(c.name)) {
517
+ add("effect", p.node, `calls ${c.name}`);
518
+ }
519
+ },
520
+ JSXAttribute(p) {
521
+ const n = p.node.name;
522
+ if (t.isJSXNamespacedName(n)) {
523
+ add(
524
+ "directive",
525
+ p.node,
526
+ `uses the \`${n.namespace.name}:${n.name.name}\` directive`,
527
+ );
528
+ } else if (/^on[A-Z]/.test(n.name)) {
529
+ add("handler", p.node, `has an ${n.name} handler`);
530
+ } else if (n.name === "ref") {
531
+ add("ref", p.node, "has a ref");
532
+ }
533
+ },
534
+ JSXSpreadAttribute(p) {
535
+ add("spread", p.node, "spreads props");
536
+ },
537
+ JSXOpeningElement(p) {
538
+ const nameNode = p.node.name;
539
+ if (t.isJSXMemberExpression(nameNode)) {
540
+ add(
541
+ "unknown-child",
542
+ p.node,
543
+ "renders a component from a member expression, which the analysis cannot resolve",
544
+ );
545
+ return;
546
+ }
547
+ if (!t.isJSXIdentifier(nameNode) || !/^[A-Z]/.test(nameNode.name)) return;
548
+ const tag = nameNode.name;
549
+ if (isGrimoireHead(info, tag)) return;
550
+ if (GLOBAL_COMPONENTS.has(tag)) {
551
+ add("global", p.node, `renders <${tag}>, which touches the browser`);
552
+ return;
553
+ }
554
+ if (propNames.has(tag)) {
555
+ add(
556
+ "unknown-child",
557
+ p.node,
558
+ `renders <${tag}>, a component from props`,
559
+ );
560
+ return;
561
+ }
562
+ const found = reportForTag(info, tag, ctx);
563
+ if ("detail" in found) add(found.kind, p.node, found.detail);
564
+ else absorb(found, p.node, tag);
565
+ },
566
+ MemberExpression(p) {
567
+ // props.children: what this renders depends on what each use passes
568
+ const prop = p.node.property;
569
+ if (
570
+ !p.node.computed &&
571
+ t.isIdentifier(prop) &&
572
+ prop.name === "children"
573
+ ) {
574
+ conditional = true;
575
+ }
576
+ },
577
+ Identifier(p) {
578
+ const name = p.node.name;
579
+ if (!p.isReferencedIdentifier()) return;
580
+ if (name === "children") conditional = true;
581
+ if (propNames.has(name)) return;
582
+ // module-level state read while rendering
583
+ if (
584
+ info.stateNames.has(name) &&
585
+ !p.scope.getBinding(name)?.path.findParent((x) => x === fn)
586
+ ) {
587
+ add("state", p.node, `reads state \`${name}\``);
588
+ return;
589
+ }
590
+ const imp = info.imports.get(name);
591
+ if (!imp || imp.typeOnly) return;
592
+ if (p.findParent((x) => x.isTSType())) return;
593
+ // used as a JSX tag is a child component, handled above
594
+ if (
595
+ p.parentPath.isJSXOpeningElement() ||
596
+ p.parentPath.isJSXClosingElement()
597
+ )
598
+ return;
599
+ if (inNested(p) && !p.parentPath.isCallExpression()) return;
600
+ const target = ctx.resolve(imp.source, info.file);
601
+ const mod = target ? loadModule(target) : null;
602
+ if (!mod) {
603
+ // A bare value from a package could be anything. Calls are the
604
+ // risk (they may read state); a plain value is a constant.
605
+ if (p.parentPath.isCallExpression({ callee: p.node })) {
606
+ add(
607
+ "unknown-import",
608
+ p.node,
609
+ `calls \`${name}\` from '${imp.source}', which the analysis cannot see inside`,
610
+ );
611
+ }
612
+ return;
613
+ }
614
+ const exportedAs = mod.exports.get(imp.imported) ?? imp.imported;
615
+ if (mod.exportedState.has(exportedAs) || mod.stateNames.has(exportedAs)) {
616
+ add(
617
+ "imported-state",
618
+ p.node,
619
+ `reads \`${name}\`, which is state in ${shortFile(mod.file)}`,
620
+ mod.file,
621
+ );
622
+ } else if (mod.reactiveFns.has(exportedAs)) {
623
+ add(
624
+ "imported-call",
625
+ p.node,
626
+ `uses \`${name}\`, which reads state in ${shortFile(mod.file)}`,
627
+ mod.file,
628
+ );
629
+ }
630
+ },
631
+ });
632
+
633
+ function absorb(sub: ComponentReport, node: t.Node, tag: string) {
634
+ if (sub.verdict === "dynamic") {
635
+ const first = sub.reasons[0];
636
+ add(
637
+ "child",
638
+ node,
639
+ `renders <${tag}>, which hydrates: ${first ? first.detail : "needs JavaScript"}`,
640
+ sub.file,
641
+ );
642
+ } else if (sub.verdict === "conditional") {
643
+ conditional = true;
644
+ }
645
+ }
646
+
647
+ ctx.stack.delete(key);
648
+ const verdict: Verdict = reasons.length
649
+ ? "dynamic"
650
+ : conditional
651
+ ? "conditional"
652
+ : "static";
653
+ const report: ComponentReport = {
654
+ name,
655
+ file: info.file,
656
+ line,
657
+ verdict,
658
+ reasons,
659
+ };
660
+ ctx.memo.set(key, report);
661
+ return report;
662
+ }
663
+
664
+ const shortFile = (f: string) =>
665
+ f.replace(/\\/g, "/").split("/").slice(-2).join("/");
666
+
667
+ /**
668
+ * Analyse every component declared in `file`.
669
+ *
670
+ * `source` overrides what is on disk, for code that is not saved yet or for
671
+ * tests; imports are still resolved against the real file system.
672
+ */
673
+ export function analyzeFile(
674
+ file: string,
675
+ options: { resolve?: Resolver; source?: string } = {},
676
+ ): ComponentReport[] {
677
+ const info = loadModule(file, options.source);
678
+ if (!info) return [];
679
+ const ctx = newCtx(options.resolve ?? defaultResolver);
680
+ return [...info.components.keys()].map((name) => analyzeIn(info, name, ctx));
681
+ }
682
+
683
+ // ---------------------------------------------------------------------------
684
+ // use sites
685
+ // ---------------------------------------------------------------------------
686
+
687
+ /**
688
+ * Why *this use* of a component cannot be static, whatever the component is.
689
+ *
690
+ * A static component given a reactive prop still changes, so each use is
691
+ * checked on what it passes: a spread, a prop that reads state, a prop that
692
+ * comes from the enclosing component's own props (which its parent may be
693
+ * driving), and children that are not static themselves.
694
+ */
695
+ export function useSiteReasons(
696
+ element: t.JSXElement,
697
+ scope: {
698
+ stateNames: Set<string>;
699
+ reactiveFns: Set<string>;
700
+ propNames: Set<string>;
701
+ /** Describes an imported name that reads state, or null. */
702
+ importedReactive?: (name: string) => string | null;
703
+ },
704
+ ): Reason[] {
705
+ const reasons: Reason[] = [];
706
+ const reads = (expr: t.Node): string | null => {
707
+ let found: string | null = null;
708
+ const visit = (n: t.Node | null | undefined): void => {
709
+ if (!n || found) return;
710
+ if (t.isArrowFunctionExpression(n) || t.isFunctionExpression(n)) return;
711
+ if (t.isIdentifier(n)) {
712
+ if (scope.stateNames.has(n.name)) found = `state \`${n.name}\``;
713
+ else if (scope.propNames.has(n.name))
714
+ found = `prop object \`${n.name}\``;
715
+ else found = scope.importedReactive?.(n.name) ?? null;
716
+ return;
717
+ }
718
+ if (
719
+ t.isCallExpression(n) &&
720
+ t.isIdentifier(n.callee) &&
721
+ scope.reactiveFns.has(n.callee.name)
722
+ ) {
723
+ found = `\`${n.callee.name}()\`, which reads state`;
724
+ return;
725
+ }
726
+ for (const key of t.VISITOR_KEYS[n.type] ?? []) {
727
+ const child = (n as unknown as Record<string, unknown>)[key];
728
+ if (Array.isArray(child)) for (const c of child) visit(c as t.Node);
729
+ else visit(child as t.Node);
730
+ }
731
+ };
732
+ visit(expr);
733
+ return found;
734
+ };
735
+ for (const attr of element.openingElement.attributes) {
736
+ if (t.isJSXSpreadAttribute(attr)) {
737
+ reasons.push({
738
+ kind: "spread",
739
+ line: lineOf(attr),
740
+ detail: "passes a spread",
741
+ });
742
+ } else if (
743
+ t.isJSXAttribute(attr) &&
744
+ t.isJSXExpressionContainer(attr.value)
745
+ ) {
746
+ const hit = reads(attr.value.expression);
747
+ if (hit) {
748
+ const name = t.isJSXIdentifier(attr.name) ? attr.name.name : "prop";
749
+ reasons.push({
750
+ kind: hit.startsWith("prop") ? "parent-prop" : "reactive-prop",
751
+ line: lineOf(attr),
752
+ detail: `passes \`${name}\` from ${hit}, which can change`,
753
+ });
754
+ }
755
+ }
756
+ }
757
+ for (const child of element.children) {
758
+ if (
759
+ t.isJSXExpressionContainer(child) &&
760
+ !t.isJSXEmptyExpression(child.expression)
761
+ ) {
762
+ const hit = reads(child.expression);
763
+ if (hit) {
764
+ reasons.push({
765
+ kind: "reactive-prop",
766
+ line: lineOf(child),
767
+ detail: `has a child that reads ${hit}`,
768
+ });
769
+ }
770
+ }
771
+ }
772
+ return reasons;
773
+ }
774
+
775
+ /**
776
+ * Everything that stops `<X static />` being true, as reasons. Empty means the
777
+ * assertion holds.
778
+ *
779
+ * Three things have to be static together: the component, what this use passes
780
+ * it, and every element written inside the use. The inside matters because a
781
+ * static `<Card>` wrapping a `<Counter>` would otherwise skip Counter's
782
+ * hydration and leave it dead.
783
+ */
784
+ export function checkStaticUse(
785
+ element: NodePath<t.JSXElement>,
786
+ file: string,
787
+ source: string,
788
+ resolve: Resolver = defaultResolver,
789
+ ): Reason[] {
790
+ const info = loadModule(file, source);
791
+ if (!info) {
792
+ return [
793
+ {
794
+ kind: "unknown-child",
795
+ line: lineOf(element.node),
796
+ detail: "the file could not be analysed",
797
+ },
798
+ ];
799
+ }
800
+ return useProblems(info, newCtx(resolve), element, resolve);
801
+ }
802
+
803
+ function useProblems(
804
+ info: ModuleInfo,
805
+ ctx: Ctx,
806
+ element: NodePath<t.JSXElement>,
807
+ resolve: Resolver,
808
+ ): Reason[] {
809
+ const file = info.file;
810
+ const at = (kind: ReasonKind, node: t.Node, detail: string): Reason => ({
811
+ kind,
812
+ line: lineOf(node),
813
+ detail,
814
+ });
815
+
816
+ const nameNode = element.node.openingElement.name;
817
+ if (!t.isJSXIdentifier(nameNode) || !/^[A-Z]/.test(nameNode.name)) {
818
+ return [
819
+ at(
820
+ "unknown-child",
821
+ element.node,
822
+ "`static` applies to components, not to HTML elements",
823
+ ),
824
+ ];
825
+ }
826
+
827
+ // the enclosing component's own props: a value from them may be driven by its parent
828
+ const propNames = new Set<string>();
829
+ const fn = element.getFunctionParent();
830
+ for (const p of fn?.node.params ?? []) {
831
+ if (t.isIdentifier(p)) propNames.add(p.name);
832
+ else if (t.isObjectPattern(p)) {
833
+ for (const prop of p.properties) {
834
+ if (t.isObjectProperty(prop) && t.isIdentifier(prop.value))
835
+ propNames.add(prop.value.name);
836
+ else if (t.isRestElement(prop) && t.isIdentifier(prop.argument))
837
+ propNames.add(prop.argument.name);
838
+ }
839
+ }
840
+ }
841
+ const importedReactive = (name: string): string | null => {
842
+ const imp = info.imports.get(name);
843
+ if (!imp || imp.typeOnly) return null;
844
+ const target = resolve(imp.source, file);
845
+ const mod = target ? loadModule(target) : null;
846
+ if (!mod) return null;
847
+ const exported = mod.exports.get(imp.imported) ?? imp.imported;
848
+ if (mod.exportedState.has(exported) || mod.stateNames.has(exported))
849
+ return `imported state \`${name}\``;
850
+ if (mod.reactiveFns.has(exported)) return `\`${name}\`, which reads state`;
851
+ return null;
852
+ };
853
+ const scope = {
854
+ stateNames: info.stateNames,
855
+ reactiveFns: info.reactiveFns,
856
+ propNames,
857
+ importedReactive,
858
+ };
859
+
860
+ const problems: Reason[] = [];
861
+ const checkElement = (el: t.JSXElement) => {
862
+ const open = el.openingElement;
863
+ problems.push(...useSiteReasons(el, scope));
864
+ for (const attr of open.attributes) {
865
+ if (t.isJSXAttribute(attr)) {
866
+ const n = attr.name;
867
+ if (t.isJSXNamespacedName(n))
868
+ problems.push(
869
+ at(
870
+ "directive",
871
+ attr,
872
+ `uses the \`${n.namespace.name}:${n.name.name}\` directive`,
873
+ ),
874
+ );
875
+ else if (/^on[A-Z]/.test(n.name))
876
+ problems.push(at("handler", attr, `has an ${n.name} handler`));
877
+ else if (n.name === "ref") problems.push(at("ref", attr, "has a ref"));
878
+ }
879
+ }
880
+ const name = open.name;
881
+ if (!t.isJSXIdentifier(name) || !/^[A-Z]/.test(name.name)) return;
882
+ if (isGrimoireHead(info, name.name)) return;
883
+ if (GLOBAL_COMPONENTS.has(name.name)) {
884
+ problems.push(
885
+ at("global", el, `renders <${name.name}>, which touches the browser`),
886
+ );
887
+ return;
888
+ }
889
+ const found = reportForTag(info, name.name, ctx);
890
+ if ("detail" in found) {
891
+ problems.push(at(found.kind, el, found.detail));
892
+ } else if (found.verdict === "dynamic") {
893
+ const first = found.reasons[0];
894
+ problems.push(
895
+ at(
896
+ "child",
897
+ el,
898
+ `<${name.name}> hydrates: ${first ? first.detail : "needs JavaScript"}`,
899
+ ),
900
+ );
901
+ }
902
+ };
903
+
904
+ checkElement(element.node);
905
+ t.traverseFast(element.node, (n) => {
906
+ if (n !== element.node && t.isJSXElement(n)) checkElement(n);
907
+ });
908
+ return problems;
909
+ }
910
+
911
+ export type { ModuleInfo };
912
+ /**
913
+ * The component uses in this file that produce only HTML, by node.
914
+ *
915
+ * Both the server and the browser build of a file ask this, and must get the
916
+ * same answer, because the server wraps exactly these uses in markers and the
917
+ * browser skips exactly these uses. It is computed from the file's own source
918
+ * and what it imports, never from the mode, so the two builds cannot drift.
919
+ *
920
+ * Only a use that is a direct child of an HTML element qualifies. That is the
921
+ * one position where hydration holds the server's nodes in a pool the use can
922
+ * be cut out of: a use inside a condition, a list, a component's children or a
923
+ * fragment hydrates through other machinery and is left alone.
924
+ */
925
+ export const STATIC_USES = new WeakSet<t.JSXElement>();
926
+
927
+ /** Uses marked `static={false}`: the author's override, so they always hydrate. */
928
+ export const FORCE_HYDRATE = new WeakSet<t.JSXElement>();
929
+
930
+ const NO_SKIP_PARENTS = new Set(["script", "style", "textarea"]);
931
+
932
+ export function markStaticUses(
933
+ program: NodePath<t.Program>,
934
+ file: string,
935
+ source: string,
936
+ resolve: Resolver = defaultResolver,
937
+ ): void {
938
+ const info = loadModule(file, source);
939
+ if (!info) return;
940
+ const ctx = newCtx(resolve);
941
+ program.traverse({
942
+ JSXElement(path) {
943
+ const name = path.node.openingElement.name;
944
+ if (!t.isJSXIdentifier(name) || !/^[A-Z]/.test(name.name)) return;
945
+ const parent = path.parent;
946
+ if (!t.isJSXElement(parent)) return;
947
+ const pn = parent.openingElement.name;
948
+ if (
949
+ !t.isJSXIdentifier(pn) ||
950
+ !/^[a-z]/.test(pn.name) ||
951
+ NO_SKIP_PARENTS.has(pn.name)
952
+ )
953
+ return;
954
+ if (isGrimoireHead(info, name.name)) return;
955
+ if (FORCE_HYDRATE.has(path.node)) return;
956
+ if (useProblems(info, ctx, path, resolve).length === 0) {
957
+ STATIC_USES.add(path.node);
958
+ }
959
+ },
960
+ });
961
+ }
962
+
963
+ export { loadModule as _loadModule };
964
+
965
+ /**
966
+ * What an import binds to, looked up in the module that declares it:
967
+ * `state` (a module-level `$state`/`$store`, read through a call),
968
+ * `derived` (a module-level `$derived`), `reactive-fn` (a function that
969
+ * reads state), or null. Follows `export { x }`, `export { x } from`,
970
+ * `export * from` and re-exported imports.
971
+ */
972
+ export type ExportKind = "state" | "derived" | "reactive-fn" | null;
973
+
974
+ export function exportKind(
975
+ file: string,
976
+ name: string,
977
+ resolve: Resolver,
978
+ seen = new Set<string>(),
979
+ ): ExportKind {
980
+ const key = `${file}#${name}`;
981
+ if (seen.has(key)) return null;
982
+ seen.add(key);
983
+ const mod = loadModule(file);
984
+ if (!mod) return null;
985
+
986
+ const local = mod.exports.get(name);
987
+ if (local !== undefined) {
988
+ if (mod.derivedNames.has(local)) return "derived";
989
+ if (mod.exportedState.has(local)) return "state";
990
+ if (mod.reactiveFns.has(local)) return "reactive-fn";
991
+ // `import { x } from "./a"; export { x }`
992
+ const imp = mod.imports.get(local);
993
+ if (imp && !imp.typeOnly && imp.imported !== "*") {
994
+ const target = resolve(imp.source, file);
995
+ if (target) return exportKind(target, imp.imported, resolve, seen);
996
+ }
997
+ return null;
998
+ }
999
+ for (const re of mod.reexports) {
1000
+ if (re.exported !== name && re.exported !== "*") continue;
1001
+ const target = resolve(re.source, file);
1002
+ if (!target) continue;
1003
+ const kind = exportKind(
1004
+ target,
1005
+ re.exported === "*" ? name : re.imported,
1006
+ resolve,
1007
+ seen,
1008
+ );
1009
+ if (kind) return kind;
1010
+ }
1011
+ return null;
1012
+ }