@trackunit/eslint-plugin-trackunit 0.8.8 → 0.9.0

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.
Files changed (33) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +7 -9
  3. package/package.json +3 -2
  4. package/src/lib/config/index.d.ts +2 -8
  5. package/src/lib/config/plugins.d.ts +2 -8
  6. package/src/lib/config/plugins.js +0 -4
  7. package/src/lib/config/presets/react.d.ts +2 -8
  8. package/src/lib/rules/one-component-per-file/one-component-per-file.js +1 -0
  9. package/src/lib/rules/require-component-directory/require-component-directory.js +26 -197
  10. package/src/lib/rules/require-component-directory/utils/component-directory-structure-utils/component-directory-structure-utils.d.ts +25 -25
  11. package/src/lib/rules/require-component-directory/utils/component-directory-structure-utils/component-directory-structure-utils.js +178 -78
  12. package/src/lib/rules/require-hook-util-directory/require-hook-util-directory.d.ts +5 -3
  13. package/src/lib/rules/require-hook-util-directory/require-hook-util-directory.js +17 -13
  14. package/src/lib/rules/require-hook-util-directory/utils/hook-util-directory-structure-utils/hook-util-directory-structure-utils.d.ts +13 -4
  15. package/src/lib/rules/require-hook-util-directory/utils/hook-util-directory-structure-utils/hook-util-directory-structure-utils.js +31 -15
  16. package/src/lib/rules/require-nested-components-directory/require-nested-components-directory.d.ts +2 -1
  17. package/src/lib/rules/require-nested-components-directory/require-nested-components-directory.js +7 -6
  18. package/src/lib/rules/require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils.d.ts +13 -9
  19. package/src/lib/rules/require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils.js +46 -162
  20. package/src/lib/utils/component-utils.d.ts +13 -4
  21. package/src/lib/utils/component-utils.js +170 -64
  22. package/src/lib/utils/react-module-summary/react-module-summary.d.ts +26 -0
  23. package/src/lib/utils/react-module-summary/react-module-summary.js +84 -0
  24. package/src/lib/utils/source-tree-utils/source-tree-utils.d.ts +0 -37
  25. package/src/lib/utils/source-tree-utils/source-tree-utils.js +6 -109
  26. package/src/lib/rules/require-nested-components-privacy/require-nested-components-privacy.d.ts +0 -9
  27. package/src/lib/rules/require-nested-components-privacy/require-nested-components-privacy.js +0 -63
  28. package/src/lib/rules/require-nested-components-privacy/utils/nested-component-privacy-utils/nested-component-privacy-utils.d.ts +0 -14
  29. package/src/lib/rules/require-nested-components-privacy/utils/nested-component-privacy-utils/nested-component-privacy-utils.js +0 -62
  30. package/src/lib/rules/require-page-directory/require-page-directory.d.ts +0 -8
  31. package/src/lib/rules/require-page-directory/require-page-directory.js +0 -44
  32. package/src/lib/rules/require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils.d.ts +0 -18
  33. package/src/lib/rules/require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils.js +0 -159
@@ -1,121 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSuggestedNestedComponentsPath = exports.analyzeNestedComponentsFolderStructure = exports.isParentComponentModule = void 0;
3
+ exports.getSuggestedNestedComponentsPath = exports.analyzeNestedComponentsFolderStructure = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
- const ts = tslib_1.__importStar(require("typescript"));
7
+ const react_module_summary_1 = require("../../../../utils/react-module-summary/react-module-summary");
8
8
  const source_tree_utils_1 = require("../../../../utils/source-tree-utils/source-tree-utils");
9
- const page_directory_structure_utils_1 = require("../../../require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils");
10
- const ROLE_SUBFOLDERS = new Set([
11
- "hooks",
12
- "utils",
13
- "types",
14
- "components",
15
- "features",
16
- "context",
17
- "services",
18
- "assets",
19
- "api",
20
- ]);
21
- const AGGREGATION_FOLDERS = new Set(["shared"]);
22
9
  const PASCAL_CASE_TSX_FILE_PATTERN = /^[A-Z][a-zA-Z0-9]*\.tsx$/;
23
- const REACT_WRAPPER_NAMES = new Set(["memo", "forwardRef"]);
24
- const isComponentInitializer = (expression) => {
25
- if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) {
26
- return true;
27
- }
28
- return (ts.isCallExpression(expression) &&
29
- ts.isIdentifier(expression.expression) &&
30
- REACT_WRAPPER_NAMES.has(expression.expression.text));
31
- };
32
- /**
33
- * Same idea as `one-component-per-file`: a sibling counts only when it exports a
34
- * PascalCase function component. A context object or reducer value does not.
35
- */
36
- const hasExportModifier = (node) => ts.canHaveModifiers(node) &&
37
- ts.getModifiers(node)?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword || modifier.kind === ts.SyntaxKind.DefaultKeyword) === true;
38
- const sourceExportsComponent = (filePath) => {
39
- let content;
40
- try {
41
- content = fs.readFileSync(filePath, "utf8");
42
- }
43
- catch {
44
- return false;
45
- }
46
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
47
- const localComponentNames = new Set();
48
- const exportedNames = [];
49
- let exportsComponent = false;
50
- let defaultExportName;
51
- let defaultExportIsComponent = false;
52
- const rememberComponent = (name) => {
53
- if (!source_tree_utils_1.PASCAL_CASE_PATTERN.test(name)) {
54
- return false;
55
- }
56
- localComponentNames.add(name);
57
- return true;
58
- };
59
- for (const statement of sourceFile.statements) {
60
- if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name !== undefined) {
61
- if (rememberComponent(statement.name.text) && hasExportModifier(statement)) {
62
- exportsComponent = true;
63
- }
64
- }
65
- if (ts.isVariableStatement(statement)) {
66
- for (const declaration of statement.declarationList.declarations) {
67
- if (ts.isIdentifier(declaration.name) &&
68
- declaration.initializer !== undefined &&
69
- isComponentInitializer(declaration.initializer) &&
70
- rememberComponent(declaration.name.text) &&
71
- hasExportModifier(statement)) {
72
- exportsComponent = true;
73
- }
74
- }
75
- }
76
- if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
77
- if (ts.isIdentifier(statement.expression)) {
78
- defaultExportName = statement.expression.text;
79
- }
80
- if (isComponentInitializer(statement.expression)) {
81
- defaultExportIsComponent = true;
82
- }
83
- }
84
- if (ts.isExportDeclaration(statement) &&
85
- statement.exportClause !== undefined &&
86
- ts.isNamedExports(statement.exportClause)) {
87
- for (const element of statement.exportClause.elements) {
88
- const localName = element.propertyName ?? element.name;
89
- if (ts.isIdentifier(localName)) {
90
- exportedNames.push(localName.text);
91
- }
92
- }
93
- }
94
- }
95
- if (defaultExportIsComponent || (defaultExportName !== undefined && localComponentNames.has(defaultExportName))) {
96
- return true;
97
- }
98
- return exportsComponent || exportedNames.some(name => localComponentNames.has(name));
99
- };
100
- const startsNewPascalWord = (character) => character !== character.toLowerCase() && character === character.toUpperCase();
101
- /** `Card` + `CardBody` stays beside the parent, whether the part is a file or a folder. */
102
- const extendsParentName = (parentComponentName, childComponentName) => childComponentName.startsWith(parentComponentName) && childComponentName.length > parentComponentName.length;
10
+ const PASCAL_CASE_WORD_START_PATTERN = /^[A-Z0-9]/;
103
11
  /**
104
- * A plural parent (`Tabs`) keeps flat files that extend the singular stem
105
- * (`Tab.tsx`, `TabList.tsx`, `TabContent.tsx`). Child folders do not use this
106
- * exemption, so `Services/ServiceCard/` is still a private child.
12
+ * Compound-family convention: `<Parent><Word>` (`Card` + `CardBody`, `Map` + `Map3D`) is a part of
13
+ * the parent and stays beside it. `Map` + `Mapping` is not, because `ping` does not start a new word.
107
14
  */
108
- const extendsSingularStem = (parentComponentName, childComponentName) => {
109
- if (!parentComponentName.endsWith("s")) {
110
- return false;
111
- }
112
- const stem = parentComponentName.slice(0, -1);
113
- if (childComponentName === stem) {
114
- return true;
115
- }
116
- return (childComponentName.startsWith(stem) &&
117
- childComponentName.length > stem.length &&
118
- startsNewPascalWord(childComponentName.charAt(stem.length)));
15
+ const isCompoundPart = (parentComponentName, childComponentName) => childComponentName.startsWith(parentComponentName) &&
16
+ PASCAL_CASE_WORD_START_PATTERN.test(childComponentName.slice(parentComponentName.length));
17
+ /** A component module that is not a context module, judged by its own code. */
18
+ const isChildComponentModule = (filePath) => {
19
+ const summary = (0, react_module_summary_1.summarizeReactModuleFile)(filePath);
20
+ return summary.exportsComponent && !summary.createsContext;
119
21
  };
120
22
  const isComponentFolder = (directoryPath) => {
121
23
  try {
@@ -126,81 +28,63 @@ const isComponentFolder = (directoryPath) => {
126
28
  return false;
127
29
  }
128
30
  };
129
- const getDirectChildComponentNames = (parentDirectory) => {
31
+ const getDirectChildComponents = (parentDirectory) => {
32
+ let entries;
130
33
  try {
131
- const entries = fs.readdirSync(parentDirectory, { withFileTypes: true });
132
- const parentComponentName = path.basename(parentDirectory);
133
- const childNames = entries.flatMap(entry => {
134
- if (ROLE_SUBFOLDERS.has(entry.name)) {
135
- return [];
136
- }
137
- if (entry.isDirectory() &&
138
- source_tree_utils_1.PASCAL_CASE_PATTERN.test(entry.name) &&
139
- !extendsParentName(parentComponentName, entry.name) &&
140
- isComponentFolder(path.join(parentDirectory, entry.name)) &&
141
- !(0, page_directory_structure_utils_1.isRegisteredRouteComponentFile)(path.join(parentDirectory, entry.name, `${entry.name}.tsx`)) &&
142
- sourceExportsComponent(path.join(parentDirectory, entry.name, `${entry.name}.tsx`))) {
143
- return [entry.name];
144
- }
145
- if (entry.isFile() && PASCAL_CASE_TSX_FILE_PATTERN.test(entry.name)) {
146
- const componentName = (0, source_tree_utils_1.getBaseName)(entry.name);
147
- const childPath = path.join(parentDirectory, entry.name);
148
- if (componentName === parentComponentName ||
149
- extendsParentName(parentComponentName, componentName) ||
150
- extendsSingularStem(parentComponentName, componentName)) {
151
- return [];
152
- }
153
- if ((0, page_directory_structure_utils_1.isRegisteredRouteComponentFile)(childPath) || !sourceExportsComponent(childPath)) {
154
- return [];
155
- }
156
- return [componentName];
157
- }
158
- return [];
159
- });
160
- return [...new Set(childNames)].sort();
34
+ entries = fs.readdirSync(parentDirectory, { withFileTypes: true });
161
35
  }
162
36
  catch {
163
37
  return [];
164
38
  }
165
- };
166
- const isParentComponentModule = (parentDirectory) => {
167
39
  const parentComponentName = path.basename(parentDirectory);
168
- if (!source_tree_utils_1.PASCAL_CASE_PATTERN.test(parentComponentName) || AGGREGATION_FOLDERS.has(parentComponentName)) {
169
- return false;
170
- }
171
- return fs.existsSync(path.join(parentDirectory, `${parentComponentName}.tsx`));
40
+ const children = entries.flatMap((entry) => {
41
+ if (entry.isDirectory()) {
42
+ const folderPath = path.join(parentDirectory, entry.name);
43
+ const isChildFolder = source_tree_utils_1.PASCAL_CASE_PATTERN.test(entry.name) &&
44
+ !isCompoundPart(parentComponentName, entry.name) &&
45
+ isComponentFolder(folderPath) &&
46
+ isChildComponentModule(path.join(folderPath, `${entry.name}.tsx`));
47
+ return isChildFolder ? [{ name: entry.name, kind: "folder" }] : [];
48
+ }
49
+ if (!entry.isFile() || !PASCAL_CASE_TSX_FILE_PATTERN.test(entry.name)) {
50
+ return [];
51
+ }
52
+ const componentName = (0, source_tree_utils_1.getBaseName)(entry.name);
53
+ const isChildFile = componentName !== parentComponentName &&
54
+ !isCompoundPart(parentComponentName, componentName) &&
55
+ isChildComponentModule(path.join(parentDirectory, entry.name));
56
+ return isChildFile ? [{ name: componentName, kind: "file" }] : [];
57
+ });
58
+ return children.toSorted((first, second) => first.name.localeCompare(second.name));
172
59
  };
173
- exports.isParentComponentModule = isParentComponentModule;
174
60
  /**
175
- * Returns a violation when `filePath` belongs to a component module that keeps
176
- * a child component beside the parent instead of under `components/`.
177
- * A sibling counts only when it exports a component. Compound parts, whose names
178
- * extend the parent, stay beside the parent. Flat files that extend a plural
179
- * parent's singular stem stay too. A child folder is not exempted by that stem.
180
- * Route components are not children.
61
+ * Returns a violation when `filePath` is `<Parent>/<Parent>.tsx` and a sibling file or folder is a
62
+ * child component kept beside the parent instead of under `<Parent>/components/`.
63
+ *
64
+ * A sibling is a child when it exports a component (by `one-component-per-file`'s detection) and
65
+ * does not call React's `createContext` at top level. Compound parts stay beside the parent.
181
66
  */
182
67
  const analyzeNestedComponentsFolderStructure = (filePath) => {
183
68
  const normalizedPath = path.normalize(filePath);
184
69
  const parentDirectory = path.dirname(normalizedPath);
185
- const fileName = path.basename(normalizedPath);
186
70
  const parentComponentName = path.basename(parentDirectory);
187
- if (fileName !== `${parentComponentName}.tsx`) {
188
- return null;
189
- }
190
- if (!(0, exports.isParentComponentModule)(parentDirectory)) {
71
+ if (path.basename(normalizedPath) !== `${parentComponentName}.tsx` || !source_tree_utils_1.PASCAL_CASE_PATTERN.test(parentComponentName)) {
191
72
  return null;
192
73
  }
193
- const directChildComponentNames = getDirectChildComponentNames(parentDirectory);
194
- if (directChildComponentNames.length === 0) {
74
+ const childComponents = getDirectChildComponents(parentDirectory);
75
+ if (childComponents.length === 0) {
195
76
  return null;
196
77
  }
197
78
  return {
198
79
  kind: "nestedComponentsNotInSubfolder",
199
80
  parentComponentName,
200
- childComponentNames: directChildComponentNames,
81
+ childComponents,
201
82
  };
202
83
  };
203
84
  exports.analyzeNestedComponentsFolderStructure = analyzeNestedComponentsFolderStructure;
204
- const getSuggestedNestedComponentsPath = (parentDirectory, childComponentName) => path.join(parentDirectory, "components", childComponentName);
85
+ /** `Map` + file `Legend` → `Map/components/Legend/Legend.tsx`; folder `Legend` → `Map/components/Legend/`. */
86
+ const getSuggestedNestedComponentsPath = (parentComponentName, child) => child.kind === "file"
87
+ ? path.posix.join(parentComponentName, "components", child.name, `${child.name}.tsx`)
88
+ : `${path.posix.join(parentComponentName, "components", child.name)}/`;
205
89
  exports.getSuggestedNestedComponentsPath = getSuggestedNestedComponentsPath;
206
90
  //# sourceMappingURL=nested-component-directory-utils.js.map
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Shared utilities for detecting React components and their export status in a file.
3
3
  *
4
- * Used by `one-component-per-file` and `component-name-matches-filename` rules.
4
+ * Used by `one-component-per-file`, `component-name-matches-filename`, and the folder-structure
5
+ * rules (through `react-module-summary`).
5
6
  *
6
7
  * ## Handled patterns
7
8
  * - `export function Foo() {}`
@@ -11,12 +12,14 @@
11
12
  * - `const Foo = () => {}; export { Foo }`
12
13
  * - `const Foo = () => {}; export { Foo as Bar }`
13
14
  * - `export const Foo = forwardRef(...)` / `memo(...)` (React wrapper calls)
15
+ * - `export default memo(Foo)` / `forwardRef(...)` (counted as an anonymous default export)
16
+ * - `export class Foo extends Component {}` / `React.PureComponent<P>` (class components)
14
17
  */
15
18
  import { TSESTree } from "@typescript-eslint/utils";
16
19
  export type ComponentEntry = {
17
20
  /** The name as it appears in the export (null for anonymous default exports). */
18
21
  name: string | null;
19
- /** The declaration node to report on (FunctionDeclaration or VariableDeclarator). */
22
+ /** The declaration node to report on (FunctionDeclaration, ClassDeclaration, or VariableDeclarator). */
20
23
  node: TSESTree.Node;
21
24
  };
22
25
  /**
@@ -26,9 +29,15 @@ export type ComponentEntry = {
26
29
  */
27
30
  export declare const createComponentFileTracker: () => {
28
31
  onFunctionDeclaration(node: TSESTree.FunctionDeclaration): void;
32
+ onClassDeclaration(node: TSESTree.ClassDeclaration): void;
29
33
  onVariableDeclarator(node: TSESTree.VariableDeclarator): void;
30
- onExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void;
31
- onExportDefaultDeclaration(node: TSESTree.ExportDefaultDeclaration): void;
34
+ onExportNamedDeclaration: (node: TSESTree.ExportNamedDeclaration) => void;
35
+ onExportDefaultDeclaration: (node: TSESTree.ExportDefaultDeclaration) => void;
36
+ /**
37
+ * Records every top-level statement of `program` in one pass. For ASTs parsed outside
38
+ * an ESLint traversal, where `parent` is not set.
39
+ */
40
+ onProgramBody(program: TSESTree.Program): void;
32
41
  /** Returns all exported React component entries. Call from `Program:exit`. */
33
42
  getExportedComponents(): Array<ComponentEntry>;
34
43
  /** Returns all top-level React component entries, exported or not. Call from `Program:exit`. */
@@ -2,7 +2,8 @@
2
2
  /**
3
3
  * Shared utilities for detecting React components and their export status in a file.
4
4
  *
5
- * Used by `one-component-per-file` and `component-name-matches-filename` rules.
5
+ * Used by `one-component-per-file`, `component-name-matches-filename`, and the folder-structure
6
+ * rules (through `react-module-summary`).
6
7
  *
7
8
  * ## Handled patterns
8
9
  * - `export function Foo() {}`
@@ -12,6 +13,8 @@
12
13
  * - `const Foo = () => {}; export { Foo }`
13
14
  * - `const Foo = () => {}; export { Foo as Bar }`
14
15
  * - `export const Foo = forwardRef(...)` / `memo(...)` (React wrapper calls)
16
+ * - `export default memo(Foo)` / `forwardRef(...)` (counted as an anonymous default export)
17
+ * - `export class Foo extends Component {}` / `React.PureComponent<P>` (class components)
15
18
  */
16
19
  Object.defineProperty(exports, "__esModule", { value: true });
17
20
  exports.createComponentFileTracker = void 0;
@@ -48,6 +51,26 @@ const isFunctionLikeComponent = (fn, name) => {
48
51
  // Anonymous functions: fall back to JSX-return detection (e.g. `export default () => <div />`)
49
52
  return (0, ast_utils_1.functionReturnsJSX)(fn);
50
53
  };
54
+ const REACT_COMPONENT_BASE_CLASS_NAMES = new Set(["Component", "PureComponent"]);
55
+ /**
56
+ * A class is a component only when it extends `Component` or `PureComponent`, bare or as
57
+ * `React.Component` / `React.PureComponent` (type arguments allowed). A PascalCase name is not
58
+ * enough: `class FooError extends Error` and `class OemBrand {}` are not components.
59
+ */
60
+ const isClassComponent = (node) => {
61
+ const superClass = node.superClass;
62
+ if (superClass?.type === utils_1.AST_NODE_TYPES.Identifier) {
63
+ return REACT_COMPONENT_BASE_CLASS_NAMES.has(superClass.name);
64
+ }
65
+ return (superClass?.type === utils_1.AST_NODE_TYPES.MemberExpression &&
66
+ superClass.object.type === utils_1.AST_NODE_TYPES.Identifier &&
67
+ superClass.object.name === "React" &&
68
+ superClass.property.type === utils_1.AST_NODE_TYPES.Identifier &&
69
+ REACT_COMPONENT_BASE_CLASS_NAMES.has(superClass.property.name));
70
+ };
71
+ const isTopLevelClassDeclaration = (node) => node.parent.type === utils_1.AST_NODE_TYPES.Program ||
72
+ node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ||
73
+ node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration;
51
74
  const isTopLevelFunctionDeclaration = (node) => node.parent.type === utils_1.AST_NODE_TYPES.Program ||
52
75
  node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ||
53
76
  node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration;
@@ -66,84 +89,154 @@ const createComponentFileTracker = () => {
66
89
  // re-export specifiers: local name → exported name (`export { Foo as Bar }`)
67
90
  const reExportedNames = new Map();
68
91
  // default export tracking
69
- let defaultExportFunctionName = null; // `export default function Foo() {}`
92
+ let defaultExportFunctionName = null; // `export default function Foo() {}` / `class Foo`
70
93
  let defaultExportIdentifier = null; // `export default Foo`
71
94
  let anonymousDefaultExportNode = null; // `export default () => ...`
95
+ // `export default memo(Foo)` / `forwardRef(() => ...)`: exported without a name of its own
96
+ let defaultExportWrapper = null;
97
+ const recordFunctionDeclaration = (node, isDefaultExport) => {
98
+ const name = node.id?.name ?? null;
99
+ if (!isFunctionLikeComponent(node, name))
100
+ return;
101
+ if (name)
102
+ namedComponents.set(name, node);
103
+ if (isDefaultExport) {
104
+ defaultExportFunctionName = name;
105
+ }
106
+ };
107
+ const recordClassDeclaration = (node, isDefaultExport) => {
108
+ if (!isClassComponent(node))
109
+ return;
110
+ const name = node.id?.name ?? null;
111
+ if (name === null) {
112
+ if (isDefaultExport)
113
+ anonymousDefaultExportNode = node;
114
+ return;
115
+ }
116
+ namedComponents.set(name, node);
117
+ if (isDefaultExport) {
118
+ defaultExportFunctionName = name;
119
+ }
120
+ };
121
+ const recordVariableDeclarator = (node) => {
122
+ if (node.id.type !== utils_1.AST_NODE_TYPES.Identifier)
123
+ return;
124
+ const name = node.id.name;
125
+ const init = node.init;
126
+ if (!init)
127
+ return;
128
+ if (init.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || init.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
129
+ if (isFunctionLikeComponent(init, name)) {
130
+ namedComponents.set(name, node);
131
+ }
132
+ }
133
+ else if (init.type === utils_1.AST_NODE_TYPES.CallExpression && isReactWrapperCall(init)) {
134
+ // forwardRef / memo wrappers — always produce a component regardless of surrounding name
135
+ namedComponents.set(name, node);
136
+ }
137
+ };
138
+ const onExportNamedDeclaration = (node) => {
139
+ if (node.source !== null)
140
+ return; // skip `export { Foo } from './other'`
141
+ if (node.declaration) {
142
+ if (node.declaration.type === utils_1.AST_NODE_TYPES.FunctionDeclaration ||
143
+ node.declaration.type === utils_1.AST_NODE_TYPES.ClassDeclaration) {
144
+ const name = node.declaration.id?.name;
145
+ if (name)
146
+ inlineExportedNames.add(name);
147
+ }
148
+ else if (node.declaration.type === utils_1.AST_NODE_TYPES.VariableDeclaration) {
149
+ for (const decl of node.declaration.declarations) {
150
+ if (decl.id.type === utils_1.AST_NODE_TYPES.Identifier) {
151
+ inlineExportedNames.add(decl.id.name);
152
+ }
153
+ }
154
+ }
155
+ }
156
+ for (const specifier of node.specifiers) {
157
+ const localName = specifier.local.name;
158
+ const exportedName = specifier.exported.type === utils_1.AST_NODE_TYPES.Identifier ? specifier.exported.name : specifier.exported.value;
159
+ reExportedNames.set(localName, exportedName);
160
+ }
161
+ };
162
+ const onExportDefaultDeclaration = (node) => {
163
+ const decl = node.declaration;
164
+ if (decl.type === utils_1.AST_NODE_TYPES.Identifier) {
165
+ // `export default Foo` — resolved in getExportedComponents after full traversal
166
+ defaultExportIdentifier = decl.name;
167
+ return;
168
+ }
169
+ if (decl.type === utils_1.AST_NODE_TYPES.CallExpression && isReactWrapperCall(decl)) {
170
+ let [wrapped] = decl.arguments;
171
+ while (wrapped?.type === utils_1.AST_NODE_TYPES.CallExpression && isReactWrapperCall(wrapped)) {
172
+ [wrapped] = wrapped.arguments;
173
+ }
174
+ defaultExportWrapper = {
175
+ node,
176
+ wrappedName: wrapped?.type === utils_1.AST_NODE_TYPES.Identifier ? wrapped.name : null,
177
+ };
178
+ return;
179
+ }
180
+ // Named `export default function Foo() {}` — handled by onFunctionDeclaration
181
+ if (decl.type === utils_1.AST_NODE_TYPES.FunctionDeclaration && decl.id?.name)
182
+ return;
183
+ if (decl.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || decl.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
184
+ if (isFunctionLikeComponent(decl, null)) {
185
+ anonymousDefaultExportNode = node;
186
+ }
187
+ return;
188
+ }
189
+ // Anonymous function declaration: `export default function() {}`
190
+ if (decl.type === utils_1.AST_NODE_TYPES.FunctionDeclaration && !decl.id) {
191
+ if (isFunctionLikeComponent(decl, null)) {
192
+ anonymousDefaultExportNode = node;
193
+ }
194
+ }
195
+ };
72
196
  return {
73
197
  onFunctionDeclaration(node) {
74
198
  if (!isTopLevelFunctionDeclaration(node))
75
199
  return;
76
- const name = node.id?.name ?? null;
77
- if (!isFunctionLikeComponent(node, name))
200
+ recordFunctionDeclaration(node, node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration);
201
+ },
202
+ onClassDeclaration(node) {
203
+ if (!isTopLevelClassDeclaration(node))
78
204
  return;
79
- if (name)
80
- namedComponents.set(name, node);
81
- if (node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) {
82
- defaultExportFunctionName = name;
83
- }
205
+ recordClassDeclaration(node, node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration);
84
206
  },
85
207
  onVariableDeclarator(node) {
86
208
  if (!isTopLevelVariableDeclarator(node))
87
209
  return;
88
- if (node.id.type !== utils_1.AST_NODE_TYPES.Identifier)
89
- return;
90
- const name = node.id.name;
91
- const init = node.init;
92
- if (!init)
93
- return;
94
- if (init.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || init.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
95
- if (isFunctionLikeComponent(init, name)) {
96
- namedComponents.set(name, node);
97
- }
98
- }
99
- else if (init.type === utils_1.AST_NODE_TYPES.CallExpression && isReactWrapperCall(init)) {
100
- // forwardRef / memo wrappers — always produce a component regardless of surrounding name
101
- namedComponents.set(name, node);
102
- }
210
+ recordVariableDeclarator(node);
103
211
  },
104
- onExportNamedDeclaration(node) {
105
- if (node.source !== null)
106
- return; // skip `export { Foo } from './other'`
107
- if (node.declaration) {
108
- if (node.declaration.type === utils_1.AST_NODE_TYPES.FunctionDeclaration) {
109
- const name = node.declaration.id?.name;
110
- if (name)
111
- inlineExportedNames.add(name);
212
+ onExportNamedDeclaration,
213
+ onExportDefaultDeclaration,
214
+ /**
215
+ * Records every top-level statement of `program` in one pass. For ASTs parsed outside
216
+ * an ESLint traversal, where `parent` is not set.
217
+ */
218
+ onProgramBody(program) {
219
+ for (const statement of program.body) {
220
+ if (statement.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration) {
221
+ onExportNamedDeclaration(statement);
112
222
  }
113
- else if (node.declaration.type === utils_1.AST_NODE_TYPES.VariableDeclaration) {
114
- for (const decl of node.declaration.declarations) {
115
- if (decl.id.type === utils_1.AST_NODE_TYPES.Identifier) {
116
- inlineExportedNames.add(decl.id.name);
117
- }
118
- }
223
+ if (statement.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) {
224
+ onExportDefaultDeclaration(statement);
119
225
  }
120
- }
121
- for (const specifier of node.specifiers) {
122
- const localName = specifier.local.name;
123
- const exportedName = specifier.exported.type === utils_1.AST_NODE_TYPES.Identifier ? specifier.exported.name : specifier.exported.value;
124
- reExportedNames.set(localName, exportedName);
125
- }
126
- },
127
- onExportDefaultDeclaration(node) {
128
- const decl = node.declaration;
129
- if (decl.type === utils_1.AST_NODE_TYPES.Identifier) {
130
- // `export default Foo` — resolved in getExportedComponents after full traversal
131
- defaultExportIdentifier = decl.name;
132
- return;
133
- }
134
- // Named `export default function Foo() {}` — handled by onFunctionDeclaration
135
- if (decl.type === utils_1.AST_NODE_TYPES.FunctionDeclaration && decl.id?.name)
136
- return;
137
- if (decl.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || decl.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
138
- if (isFunctionLikeComponent(decl, null)) {
139
- anonymousDefaultExportNode = node;
226
+ const declaration = statement.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ||
227
+ statement.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration
228
+ ? statement.declaration
229
+ : statement;
230
+ if (declaration?.type === utils_1.AST_NODE_TYPES.FunctionDeclaration) {
231
+ recordFunctionDeclaration(declaration, statement.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration);
140
232
  }
141
- return;
142
- }
143
- // Anonymous function declaration: `export default function() {}`
144
- if (decl.type === utils_1.AST_NODE_TYPES.FunctionDeclaration && !decl.id) {
145
- if (isFunctionLikeComponent(decl, null)) {
146
- anonymousDefaultExportNode = node;
233
+ if (declaration?.type === utils_1.AST_NODE_TYPES.ClassDeclaration) {
234
+ recordClassDeclaration(declaration, statement.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration);
235
+ }
236
+ if (declaration?.type === utils_1.AST_NODE_TYPES.VariableDeclaration) {
237
+ for (const declarator of declaration.declarations) {
238
+ recordVariableDeclarator(declarator);
239
+ }
147
240
  }
148
241
  }
149
242
  },
@@ -173,6 +266,14 @@ const createComponentFileTracker = () => {
173
266
  if (anonymousDefaultExportNode !== null) {
174
267
  result.push({ name: null, node: anonymousDefaultExportNode });
175
268
  }
269
+ // `export const Foo = ...; export default memo(Foo)` exports one component, not two
270
+ if (defaultExportWrapper !== null) {
271
+ const { node, wrappedName } = defaultExportWrapper;
272
+ const wrappedNode = wrappedName === null ? undefined : namedComponents.get(wrappedName);
273
+ if (!result.some(entry => entry.node === wrappedNode)) {
274
+ result.push({ name: null, node });
275
+ }
276
+ }
176
277
  return result;
177
278
  },
178
279
  /** Returns all top-level React component entries, exported or not. Call from `Program:exit`. */
@@ -184,6 +285,11 @@ const createComponentFileTracker = () => {
184
285
  if (anonymousDefaultExportNode !== null) {
185
286
  result.push({ name: null, node: anonymousDefaultExportNode });
186
287
  }
288
+ // `export default memo(Foo)` wraps a component already counted above
289
+ if (defaultExportWrapper !== null &&
290
+ (defaultExportWrapper.wrappedName === null || !namedComponents.has(defaultExportWrapper.wrappedName))) {
291
+ result.push({ name: null, node: defaultExportWrapper.node });
292
+ }
187
293
  return result;
188
294
  },
189
295
  };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What a module exports, as the folder-structure rules and their codemods see it.
3
+ *
4
+ * Component detection is `createComponentFileTracker`, the same detection `one-component-per-file`
5
+ * uses, so a file counts as a component file exactly when that rule would count an exported
6
+ * component in it. A class counts only when it extends `Component` or `PureComponent` (bare or
7
+ * `React.*`).
8
+ *
9
+ * ## Main Functions
10
+ * - `summarizeReactModule()` - Summarize an already parsed program (inside a rule)
11
+ * - `summarizeReactModuleSource()` - Parse and summarize source text
12
+ * - `summarizeReactModuleFile()` - Read, parse, and summarize a file on disk
13
+ */
14
+ import { TSESTree } from "@typescript-eslint/utils";
15
+ export type ReactModuleSummary = {
16
+ /** Exported component names, in source order. Anonymous default exports are omitted. */
17
+ readonly exportedComponentNames: ReadonlyArray<string>;
18
+ readonly exportsComponent: boolean;
19
+ /** The module calls React's `createContext` at top level, so it is a context module. */
20
+ readonly createsContext: boolean;
21
+ };
22
+ export declare const summarizeReactModule: (program: TSESTree.Program) => ReactModuleSummary;
23
+ /** Unparsable source summarizes as an empty module. */
24
+ export declare const summarizeReactModuleSource: (sourceText: string, filePath?: string) => ReactModuleSummary;
25
+ /** An unreadable or unparsable file summarizes as an empty module. */
26
+ export declare const summarizeReactModuleFile: (filePath: string) => ReactModuleSummary;