@sigil-dev/compiler 0.9.26 → 0.9.28

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,5 +1,11 @@
1
- /**
2
- * Per-file flags the JSX codegen needs but is not handed as arguments. Set once
3
- * by the plugin when it enters a file.
4
- */
5
- export const compileState = { dev: false };
1
+ /**
2
+ * Per-file flags the JSX codegen needs but is not handed as arguments. Set once
3
+ * by the plugin when it enters a file.
4
+ */
5
+ export const compileState = {
6
+ dev: false,
7
+ /** The file being compiled, for warnings. */
8
+ file: "",
9
+ /** Runtime names server-rendered code calls (the server output imports them). */
10
+ ssrImports: new Set<string>(),
11
+ };
@@ -1,28 +1,93 @@
1
1
  import { type NodePath, types as t } from "@babel/core";
2
+ import { warn } from "./warn.ts";
2
3
 
4
+ const FACTORIES = new Set(["createSignal", "createRawSignal", "createMemo"]);
5
+
6
+ /** `x()` inside `x.set(…)`: the update reading its own old value (`x++`). */
7
+ function isSelfRead(call: NodePath<t.CallExpression>, name: string): boolean {
8
+ return !!call.findParent(
9
+ (p) =>
10
+ p.isCallExpression() &&
11
+ t.isMemberExpression(p.node.callee) &&
12
+ t.isIdentifier(p.node.callee.object, { name }) &&
13
+ t.isIdentifier(p.node.callee.property, { name: "set" }),
14
+ );
15
+ }
16
+
17
+ function isExported(decl: NodePath<t.VariableDeclarator>, name: string): boolean {
18
+ if (decl.parentPath.parentPath?.isExportNamedDeclaration()) return true;
19
+ const program = decl.findParent((p) => p.isProgram()) as NodePath<t.Program>;
20
+ return program.node.body.some(
21
+ (n) =>
22
+ t.isExportNamedDeclaration(n) &&
23
+ !n.source &&
24
+ n.specifiers.some(
25
+ (s) => t.isExportSpecifier(s) && t.isIdentifier(s.local, { name }),
26
+ ),
27
+ );
28
+ }
29
+
30
+ /**
31
+ * Warn about state nothing reacts to: declared and never read, or only ever
32
+ * written (`clicks++` with no `{clicks}` anywhere). Runs on the compiled
33
+ * program, where reads are calls (`x()`) and writes are `x.set(…)`.
34
+ * Exported state is read by other modules, so it is never reported.
35
+ */
3
36
  export function warnDeadReactivity(
4
- path: NodePath,
5
- signals: Set<string>,
6
- storeSignals: Set<string>,
7
- filename?: string,
37
+ path: NodePath<t.Program>,
38
+ exempt: Set<string>,
8
39
  ): void {
9
- const used = new Set<string>();
10
-
11
40
  path.traverse({
12
- CallExpression(innerPath: any) {
13
- if (t.isIdentifier(innerPath.node.callee)) {
14
- used.add(innerPath.node.callee.name);
15
- }
16
- },
17
- });
41
+ VariableDeclarator(decl) {
42
+ const { id, init } = decl.node;
43
+ if (!t.isIdentifier(id) || !t.isCallExpression(init)) return;
44
+ if (!t.isIdentifier(init.callee) || !FACTORIES.has(init.callee.name)) return;
45
+ const name = id.name;
46
+ if (exempt.has(name) || isExported(decl, name)) return;
18
47
 
19
- for (const name of signals) {
20
- if (storeSignals.has(name)) continue; // exported, used across files
21
- if (!used.has(name)) {
22
- const tag = filename ? `[${filename}]` : "[sigil]";
23
- console.warn(
24
- `${tag} unused reactive declaration: "${name}" is declared with $state or $derived but never read.`,
48
+ const scope = decl.scope.getBinding(name)?.scope ?? decl.scope;
49
+ let reads = 0;
50
+ let writes = 0;
51
+ let passed = false;
52
+ scope.path.traverse({
53
+ CallExpression(call) {
54
+ const c = call.node.callee;
55
+ if (t.isIdentifier(c, { name })) {
56
+ if (!isSelfRead(call, name)) reads++;
57
+ } else if (
58
+ t.isMemberExpression(c) &&
59
+ t.isIdentifier(c.object, { name }) &&
60
+ t.isIdentifier(c.property, { name: "set" })
61
+ ) {
62
+ writes++;
63
+ }
64
+ },
65
+ Identifier(ref) {
66
+ // handed on as the signal itself (HMR registry, a helper)
67
+ if (
68
+ ref.node.name === name &&
69
+ ref.node !== id &&
70
+ ref.isReferencedIdentifier() &&
71
+ !ref.parentPath.isCallExpression({ callee: ref.node }) &&
72
+ !ref.parentPath.isMemberExpression({ object: ref.node }) &&
73
+ !(
74
+ ref.parentPath.isCallExpression() &&
75
+ t.isIdentifier(ref.parentPath.node.callee, {
76
+ name: "__hmrRegister__",
77
+ })
78
+ )
79
+ )
80
+ passed = true;
81
+ },
82
+ });
83
+ if (reads > 0 || passed) return;
84
+ const kind = init.callee.name === "createMemo" ? "$derived" : "$state";
85
+ warn(
86
+ decl.node,
87
+ writes > 0
88
+ ? `"${name}" (${kind}) is written but never read: nothing reacts to it. Use a plain variable, or read it somewhere.`
89
+ : `"${name}" (${kind}) is never read.`,
25
90
  );
26
- }
27
- }
91
+ },
92
+ });
28
93
  }
@@ -0,0 +1,64 @@
1
+ import { type NodePath, types as t } from "@babel/core";
2
+ import { type Fn, isComponent } from "./props.ts";
3
+
4
+ /**
5
+ * Keep an async component's owner across its awaits.
6
+ *
7
+ * Code after `await` runs in a later microtask, when whatever was rendering
8
+ * then is the current owner (or nothing), so components it creates would hang
9
+ * off the wrong parent and miss their context. This captures the owner when
10
+ * the component starts and restores it at each resumption:
11
+ *
12
+ * async function Page() { const d = await load(); return <Card d={d} />; }
13
+ * async function Page() {
14
+ * const _owner = getOwner();
15
+ * const d = __resume(await load(), _owner);
16
+ * return <Card d={d} />;
17
+ * }
18
+ *
19
+ * Returns the runtime names it used.
20
+ */
21
+ export function keepOwnerAcrossAwaits(program: NodePath<t.Program>): string[] {
22
+ let used = false;
23
+ program.traverse({
24
+ "ArrowFunctionExpression|FunctionExpression|FunctionDeclaration"(
25
+ path: NodePath<Fn>,
26
+ ) {
27
+ if (!path.node.async || path.node.generator) return;
28
+ if (!isComponent(path)) return;
29
+ const awaits: NodePath<t.AwaitExpression>[] = [];
30
+ path.traverse({
31
+ AwaitExpression(p) {
32
+ if (p.getFunctionParent() === path) awaits.push(p);
33
+ },
34
+ // `for await` resumes per item; not rewritten, it is rare in components
35
+ });
36
+ if (awaits.length === 0) return;
37
+
38
+ const owner = path.scope.generateUidIdentifier("owner");
39
+ for (const a of awaits) {
40
+ a.replaceWith(
41
+ t.callExpression(t.identifier("__resume"), [
42
+ a.node,
43
+ t.identifier(owner.name),
44
+ ]),
45
+ );
46
+ a.skip();
47
+ }
48
+ const capture = t.variableDeclaration("const", [
49
+ t.variableDeclarator(
50
+ owner,
51
+ t.callExpression(t.identifier("getOwner"), []),
52
+ ),
53
+ ]);
54
+ const body = path.node.body;
55
+ if (t.isBlockStatement(body)) {
56
+ body.body.unshift(capture);
57
+ } else {
58
+ path.node.body = t.blockStatement([capture, t.returnStatement(body)]);
59
+ }
60
+ used = true;
61
+ },
62
+ });
63
+ return used ? ["getOwner", "__resume"] : [];
64
+ }
@@ -1,256 +1,202 @@
1
- import { type NodePath, types as t } from "@babel/core";
2
-
3
- /**
4
- * Names of props objects in the file being compiled (reset per file by the
5
- * plugin). Children code uses it to tell `{title}`, a prop that may hold
6
- * nodes, from `{count}`, which is always text.
7
- */
8
- export const propObjects = new Set<string>();
9
-
10
- /**
11
- * Values imported from the project's own modules (relative or alias paths),
12
- * reset per file. `cart.items.length` where `cart` is an exported `$store`
13
- * must update like local state; the store's proxy tracks the read, so the
14
- * compiler only has to give the expression an effect. Components (PascalCase)
15
- * and type imports aren't included, and neither are calls: `format(x)` may
16
- * return nodes and keeps its old handling.
17
- */
18
- export const importRoots = new Set<string>();
19
-
20
- export function collectImportRoots(program: NodePath<t.Program>): void {
21
- importRoots.clear();
22
- for (const node of program.node.body) {
23
- if (!t.isImportDeclaration(node) || node.importKind === "type") continue;
24
- if (!/^[./$~@]/.test(node.source.value)) continue;
25
- // @scope/package imports are npm packages, not project modules
26
- if (
27
- /^@[^/]+\/[^/]/.test(node.source.value) &&
28
- !node.source.value.startsWith("@/")
29
- )
30
- continue;
31
- for (const spec of node.specifiers) {
32
- if (t.isImportSpecifier(spec) && spec.importKind === "type") continue;
33
- const name = spec.local.name;
34
- if (/^[A-Z]/.test(name)) continue;
35
- importRoots.add(name);
36
- }
37
- }
38
- }
39
-
40
- function rootName(expr: t.Node): string | null {
41
- let node = expr;
42
- while (t.isMemberExpression(node)) node = node.object;
43
- return t.isIdentifier(node) ? node.name : null;
44
- }
45
-
46
- /** `cart.items.length` where `cart` is imported from the project. */
47
- export function isImportRead(expr: t.Node): boolean {
48
- if (!t.isMemberExpression(expr)) return false;
49
- const root = rootName(expr);
50
- return root !== null && importRoots.has(root);
51
- }
52
-
53
- /** `readStore(count)`, inserted by `rewriteImportReads`. */
54
- export function isStoreRead(expr: t.Node): boolean {
55
- return (
56
- t.isCallExpression(expr) &&
57
- t.isIdentifier(expr.callee, { name: "readStore" }) &&
58
- expr.arguments.length === 1 &&
59
- t.isIdentifier(expr.arguments[0]) &&
60
- importRoots.has(expr.arguments[0].name)
61
- );
62
- }
63
-
64
- /**
65
- * Wrap bare reads of project imports in `readStore(…)`.
66
- *
67
- * An exported `$store` holding a primitive reaches other modules as its
68
- * signal getter, since the compiler only rewrites reads in the declaring
69
- * file. `readStore` calls a signal and returns anything else unchanged, so
70
- * `{count}` and `count * 2` see the number and track it. Callees, member
71
- * objects (object stores forward member reads already), JSX tags, exports
72
- * and types are left alone. Returns whether anything changed.
73
- */
74
- export function rewriteImportReads(program: NodePath<t.Program>): boolean {
75
- if (importRoots.size === 0) return false;
76
- let changed = false;
77
- program.traverse({
78
- Identifier(path) {
79
- const name = path.node.name;
80
- if (!importRoots.has(name)) return;
81
- if (!path.isReferencedIdentifier()) return;
82
- const binding = path.scope.getBinding(name);
83
- if (binding?.kind !== "module") return;
84
- const parent = path.parent;
85
- if (
86
- (t.isCallExpression(parent) || t.isNewExpression(parent)) &&
87
- parent.callee === path.node
88
- )
89
- return;
90
- if (t.isMemberExpression(parent) && parent.object === path.node) return;
91
- if (t.isOptionalMemberExpression(parent) && parent.object === path.node)
92
- return;
93
- if (t.isTaggedTemplateExpression(parent)) return;
94
- if (t.isExportSpecifier(parent)) return;
95
- if (path.findParent((p) => p.isTSType())) return;
96
- if (t.isCallExpression(parent) && isStoreRead(parent)) return;
97
- path.replaceWith(
98
- t.callExpression(t.identifier("readStore"), [t.identifier(name)]),
99
- );
100
- path.skip();
101
- changed = true;
102
- },
103
- });
104
- return changed;
105
- }
106
-
107
- /**
108
- * A read whose value may be text or nodes and may change: `props.title`,
109
- * `_props.item.name`, or a member read on an imported store.
110
- */
111
- export function isPropRead(expr: t.Node): boolean {
112
- if (isStoreRead(expr)) return true;
113
- const root = rootName(expr);
114
- if (root === null) return false;
115
- return propObjects.has(root) || isImportRead(expr);
116
- }
117
-
118
- type Fn =
119
- | t.ArrowFunctionExpression
120
- | t.FunctionExpression
121
- | t.FunctionDeclaration;
122
-
123
- interface Prop {
124
- key: string;
125
- local: string;
126
- fallback?: t.Expression;
127
- }
128
-
129
- /**
130
- * Keep destructured props live.
131
- *
132
- * `({ title }) => <h1>{title}</h1>` reads `title` once, when the component is
133
- * called, so a prop the caller passes as a getter (see element.ts) would
134
- * freeze at its first value. This rewrites the pattern into reads through the
135
- * props object, `(_props) => <h1>{_props.title}</h1>`, and registers
136
- * `_props` as reactive so JSX that reads it gets an effect.
137
- *
138
- * A plain `(props) =>` parameter needs no rewrite, only the registration.
139
- *
140
- * Only simple patterns are rewritten: `{ a, b: c, d = 1 }`. Anything else (a
141
- * rest element, nested patterns, computed keys, a prop reassigned in the body,
142
- * a prop used as a JSX tag) is left as it was, with the old read-once
143
- * behaviour.
144
- */
145
- export function liftDestructuredProps(
146
- program: NodePath<t.Program>,
147
- reactive: Set<string>,
148
- ): void {
149
- program.traverse({
150
- "ArrowFunctionExpression|FunctionExpression|FunctionDeclaration"(
151
- path: NodePath<Fn>,
152
- ) {
153
- const param = path.node.params[0];
154
- if (!param || !isComponent(path) || !returnsJsx(path)) return;
155
- // `(props) => <p>{props.title}</p>` is already a live read
156
- if (t.isIdentifier(param)) {
157
- reactive.add(param.name);
158
- propObjects.add(param.name);
159
- return;
160
- }
161
- if (!t.isObjectPattern(param)) return;
162
-
163
- const props: Prop[] = [];
164
- for (const p of param.properties) {
165
- if (!t.isObjectProperty(p) || p.computed || !t.isIdentifier(p.key))
166
- return;
167
- if (t.isIdentifier(p.value)) {
168
- props.push({ key: p.key.name, local: p.value.name });
169
- } else if (
170
- t.isAssignmentPattern(p.value) &&
171
- t.isIdentifier(p.value.left)
172
- ) {
173
- props.push({
174
- key: p.key.name,
175
- local: p.value.left.name,
176
- fallback: p.value.right,
177
- });
178
- } else return;
179
- }
180
-
181
- const bindings = props.map((p) => path.scope.getBinding(p.local));
182
- for (const b of bindings) {
183
- if (!b?.constant) return;
184
- if (b.referencePaths.some((r) => r.isJSXIdentifier())) return;
185
- }
186
-
187
- const propsId = path.scope.generateUidIdentifier("props");
188
- if (param.typeAnnotation) propsId.typeAnnotation = param.typeAnnotation;
189
-
190
- props.forEach((prop, i) => {
191
- for (const ref of bindings[i]!.referencePaths) {
192
- const read = () =>
193
- t.memberExpression(
194
- t.identifier(propsId.name),
195
- t.identifier(prop.key),
196
- );
197
- const value = prop.fallback
198
- ? t.conditionalExpression(
199
- t.binaryExpression("===", read(), t.identifier("undefined")),
200
- t.cloneNode(prop.fallback),
201
- read(),
202
- )
203
- : read();
204
- const parent = ref.parentPath;
205
- if (parent?.isObjectProperty() && parent.node.shorthand) {
206
- parent.node.shorthand = false;
207
- }
208
- ref.replaceWith(value);
209
- }
210
- });
211
-
212
- path.node.params[0] = propsId;
213
- path.scope.crawl();
214
- reactive.add(propsId.name);
215
- propObjects.add(propsId.name);
216
- },
217
- });
218
- }
219
-
220
- /**
221
- * Components are PascalCase functions (`function Card`, `const Card = …`) or
222
- * a module's default export (route components are often anonymous). A
223
- * lowercase callback such as `items.map((item) => <li>…</li>)` is not one;
224
- * list rows get their own item reactivity in keyed-list.ts.
225
- */
226
- function isComponent(path: NodePath<Fn>): boolean {
227
- const pascal = (name?: string) => !!name && /^[A-Z]/.test(name);
228
- if (path.isFunctionDeclaration()) {
229
- return (
230
- pascal(path.node.id?.name) || path.parentPath.isExportDefaultDeclaration()
231
- );
232
- }
233
- const parent = path.parentPath;
234
- if (parent.isExportDefaultDeclaration()) return true;
235
- if (parent.isVariableDeclarator() && t.isIdentifier(parent.node.id)) {
236
- return pascal(parent.node.id.name);
237
- }
238
- if (path.isFunctionExpression() && pascal(path.node.id?.name)) return true;
239
- return false;
240
- }
241
-
242
- /** A function whose own body (not a nested function) produces JSX. */
243
- function returnsJsx(path: NodePath<Fn>): boolean {
244
- let found = false;
245
- path.traverse({
246
- JSXElement(p) {
247
- if (p.getFunctionParent() === path) found = true;
248
- p.skip();
249
- },
250
- JSXFragment(p) {
251
- if (p.getFunctionParent() === path) found = true;
252
- p.skip();
253
- },
254
- });
255
- return found;
256
- }
1
+ import { type NodePath, types as t } from "@babel/core";
2
+
3
+ /**
4
+ * Names of props objects in the file being compiled (reset per file by the
5
+ * plugin). Children code uses it to tell `{title}`, a prop that may hold
6
+ * nodes, from `{count}`, which is always text.
7
+ */
8
+ export const propObjects = new Set<string>();
9
+
10
+ /**
11
+ * Values imported from the project's own modules (relative or alias paths),
12
+ * reset per file. Imports that are state are compiled to calls (see
13
+ * state-imports.ts); a member read on any other project import, such as an
14
+ * object exported with a getter over state, still gets an effect, since the
15
+ * compiler cannot see what the read does. Components (PascalCase) and type
16
+ * imports aren't included, and neither are calls: `format(x)` may return
17
+ * nodes and keeps its old handling.
18
+ */
19
+ export const importRoots = new Set<string>();
20
+
21
+ export function collectImportRoots(program: NodePath<t.Program>): void {
22
+ importRoots.clear();
23
+ for (const node of program.node.body) {
24
+ if (!t.isImportDeclaration(node) || node.importKind === "type") continue;
25
+ if (!/^[./$~@]/.test(node.source.value)) continue;
26
+ // @scope/package imports are npm packages, not project modules
27
+ if (
28
+ /^@[^/]+\/[^/]/.test(node.source.value) &&
29
+ !node.source.value.startsWith("@/")
30
+ )
31
+ continue;
32
+ for (const spec of node.specifiers) {
33
+ if (t.isImportSpecifier(spec) && spec.importKind === "type") continue;
34
+ const name = spec.local.name;
35
+ if (/^[A-Z]/.test(name)) continue;
36
+ importRoots.add(name);
37
+ }
38
+ }
39
+ }
40
+
41
+ function rootName(expr: t.Node): string | null {
42
+ let node = expr;
43
+ while (t.isMemberExpression(node)) node = node.object;
44
+ return t.isIdentifier(node) ? node.name : null;
45
+ }
46
+
47
+ /** `cart.items.length` where `cart` is imported from the project. */
48
+ export function isImportRead(expr: t.Node): boolean {
49
+ if (!t.isMemberExpression(expr)) return false;
50
+ const root = rootName(expr);
51
+ return root !== null && importRoots.has(root);
52
+ }
53
+
54
+ /**
55
+ * A read whose value may be text or nodes and may change: `props.title`,
56
+ * `_props.item.name`, or a member read on an imported store.
57
+ */
58
+ export function isPropRead(expr: t.Node): boolean {
59
+ const root = rootName(expr);
60
+ if (root === null) return false;
61
+ return propObjects.has(root) || isImportRead(expr);
62
+ }
63
+
64
+ export type Fn =
65
+ | t.ArrowFunctionExpression
66
+ | t.FunctionExpression
67
+ | t.FunctionDeclaration;
68
+
69
+ interface Prop {
70
+ key: string;
71
+ local: string;
72
+ fallback?: t.Expression;
73
+ }
74
+
75
+ /**
76
+ * Keep destructured props live.
77
+ *
78
+ * `({ title }) => <h1>{title}</h1>` reads `title` once, when the component is
79
+ * called, so a prop the caller passes as a getter (see element.ts) would
80
+ * freeze at its first value. This rewrites the pattern into reads through the
81
+ * props object, `(_props) => <h1>{_props.title}</h1>`, and registers
82
+ * `_props` as reactive so JSX that reads it gets an effect.
83
+ *
84
+ * A plain `(props) =>` parameter needs no rewrite, only the registration.
85
+ *
86
+ * Only simple patterns are rewritten: `{ a, b: c, d = 1 }`. Anything else (a
87
+ * rest element, nested patterns, computed keys, a prop reassigned in the body,
88
+ * a prop used as a JSX tag) is left as it was, with the old read-once
89
+ * behaviour.
90
+ */
91
+ export function liftDestructuredProps(
92
+ program: NodePath<t.Program>,
93
+ reactive: Set<string>,
94
+ ): void {
95
+ program.traverse({
96
+ "ArrowFunctionExpression|FunctionExpression|FunctionDeclaration"(
97
+ path: NodePath<Fn>,
98
+ ) {
99
+ const param = path.node.params[0];
100
+ if (!param || !isComponent(path) || !returnsJsx(path)) return;
101
+ // `(props) => <p>{props.title}</p>` is already a live read
102
+ if (t.isIdentifier(param)) {
103
+ reactive.add(param.name);
104
+ propObjects.add(param.name);
105
+ return;
106
+ }
107
+ if (!t.isObjectPattern(param)) return;
108
+
109
+ const props: Prop[] = [];
110
+ for (const p of param.properties) {
111
+ if (!t.isObjectProperty(p) || p.computed || !t.isIdentifier(p.key))
112
+ return;
113
+ if (t.isIdentifier(p.value)) {
114
+ props.push({ key: p.key.name, local: p.value.name });
115
+ } else if (
116
+ t.isAssignmentPattern(p.value) &&
117
+ t.isIdentifier(p.value.left)
118
+ ) {
119
+ props.push({
120
+ key: p.key.name,
121
+ local: p.value.left.name,
122
+ fallback: p.value.right,
123
+ });
124
+ } else return;
125
+ }
126
+
127
+ const bindings = props.map((p) => path.scope.getBinding(p.local));
128
+ for (const b of bindings) {
129
+ if (!b?.constant) return;
130
+ if (b.referencePaths.some((r) => r.isJSXIdentifier())) return;
131
+ }
132
+
133
+ const propsId = path.scope.generateUidIdentifier("props");
134
+ if (param.typeAnnotation) propsId.typeAnnotation = param.typeAnnotation;
135
+
136
+ props.forEach((prop, i) => {
137
+ for (const ref of bindings[i]!.referencePaths) {
138
+ const read = () =>
139
+ t.memberExpression(
140
+ t.identifier(propsId.name),
141
+ t.identifier(prop.key),
142
+ );
143
+ const value = prop.fallback
144
+ ? t.conditionalExpression(
145
+ t.binaryExpression("===", read(), t.identifier("undefined")),
146
+ t.cloneNode(prop.fallback),
147
+ read(),
148
+ )
149
+ : read();
150
+ const parent = ref.parentPath;
151
+ if (parent?.isObjectProperty() && parent.node.shorthand) {
152
+ parent.node.shorthand = false;
153
+ }
154
+ ref.replaceWith(value);
155
+ }
156
+ });
157
+
158
+ path.node.params[0] = propsId;
159
+ path.scope.crawl();
160
+ reactive.add(propsId.name);
161
+ propObjects.add(propsId.name);
162
+ },
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Components are PascalCase functions (`function Card`, `const Card = …`) or
168
+ * a module's default export (route components are often anonymous). A
169
+ * lowercase callback such as `items.map((item) => <li>…</li>)` is not one;
170
+ * list rows get their own item reactivity in keyed-list.ts.
171
+ */
172
+ export function isComponent(path: NodePath<Fn>): boolean {
173
+ const pascal = (name?: string) => !!name && /^[A-Z]/.test(name);
174
+ if (path.isFunctionDeclaration()) {
175
+ return (
176
+ pascal(path.node.id?.name) || path.parentPath.isExportDefaultDeclaration()
177
+ );
178
+ }
179
+ const parent = path.parentPath;
180
+ if (parent.isExportDefaultDeclaration()) return true;
181
+ if (parent.isVariableDeclarator() && t.isIdentifier(parent.node.id)) {
182
+ return pascal(parent.node.id.name);
183
+ }
184
+ if (path.isFunctionExpression() && pascal(path.node.id?.name)) return true;
185
+ return false;
186
+ }
187
+
188
+ /** A function whose own body (not a nested function) produces JSX. */
189
+ function returnsJsx(path: NodePath<Fn>): boolean {
190
+ let found = false;
191
+ path.traverse({
192
+ JSXElement(p) {
193
+ if (p.getFunctionParent() === path) found = true;
194
+ p.skip();
195
+ },
196
+ JSXFragment(p) {
197
+ if (p.getFunctionParent() === path) found = true;
198
+ p.skip();
199
+ },
200
+ });
201
+ return found;
202
+ }