@trackunit/eslint-plugin-trackunit 0.7.13 → 0.7.14

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 (37) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +12 -0
  3. package/package.json +2 -2
  4. package/src/index.d.ts +1 -1
  5. package/src/index.js +2 -1
  6. package/src/lib/config/index.d.ts +20 -0
  7. package/src/lib/config/plugins.d.ts +23 -0
  8. package/src/lib/config/plugins.js +19 -1
  9. package/src/lib/config/presets/react.d.ts +20 -0
  10. package/src/lib/config/presets/react.js +4 -0
  11. package/src/lib/rules/no-unused-translation-key/used-strings.js +1 -1
  12. package/src/lib/{utils → rules/no-unused-translation-key/utils/program-utils}/program-utils.js +1 -1
  13. package/src/lib/rules/require-component-directory/require-component-directory.d.ts +16 -0
  14. package/src/lib/rules/require-component-directory/require-component-directory.js +240 -0
  15. package/src/lib/rules/require-component-directory/utils/component-directory-structure-utils/component-directory-structure-utils.d.ts +34 -0
  16. package/src/lib/rules/require-component-directory/utils/component-directory-structure-utils/component-directory-structure-utils.js +114 -0
  17. package/src/lib/rules/require-hook-util-directory/require-hook-util-directory.d.ts +9 -0
  18. package/src/lib/rules/require-hook-util-directory/require-hook-util-directory.js +50 -0
  19. package/src/lib/rules/require-hook-util-directory/utils/hook-util-directory-structure-utils/hook-util-directory-structure-utils.d.ts +15 -0
  20. package/src/lib/rules/require-hook-util-directory/utils/hook-util-directory-structure-utils/hook-util-directory-structure-utils.js +44 -0
  21. package/src/lib/rules/require-nested-components-directory/require-nested-components-directory.d.ts +9 -0
  22. package/src/lib/rules/require-nested-components-directory/require-nested-components-directory.js +44 -0
  23. package/src/lib/rules/require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils.d.ts +17 -0
  24. package/src/lib/rules/require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils.js +206 -0
  25. package/src/lib/rules/require-nested-components-privacy/require-nested-components-privacy.d.ts +9 -0
  26. package/src/lib/rules/require-nested-components-privacy/require-nested-components-privacy.js +63 -0
  27. package/src/lib/rules/require-nested-components-privacy/utils/nested-component-privacy-utils/nested-component-privacy-utils.d.ts +14 -0
  28. package/src/lib/rules/require-nested-components-privacy/utils/nested-component-privacy-utils/nested-component-privacy-utils.js +62 -0
  29. package/src/lib/rules/require-page-directory/require-page-directory.d.ts +8 -0
  30. package/src/lib/rules/require-page-directory/require-page-directory.js +44 -0
  31. package/src/lib/rules/require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils.d.ts +18 -0
  32. package/src/lib/rules/require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils.js +159 -0
  33. package/src/lib/utils/create-rule/create-rule.d.ts +7 -0
  34. package/src/lib/utils/create-rule/create-rule.js +9 -0
  35. package/src/lib/utils/source-tree-utils/source-tree-utils.d.ts +43 -0
  36. package/src/lib/utils/source-tree-utils/source-tree-utils.js +136 -0
  37. /package/src/lib/{utils → rules/no-unused-translation-key/utils/program-utils}/program-utils.d.ts +0 -0
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyzeNestedComponentImport = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
6
+ const source_tree_utils_1 = require("../../../../utils/source-tree-utils/source-tree-utils");
7
+ const nested_component_directory_utils_1 = require("../../../require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils");
8
+ const AGGREGATION_FOLDERS = new Set(["shared"]);
9
+ /**
10
+ * Returns a violation when `importerFilePath` imports a component from another
11
+ * component module's private `components/` subfolder via a relative specifier.
12
+ *
13
+ * Scope (by design):
14
+ * - Only `components/<Parent>/<Parent>.tsx` modules that contain a matching component file count as owners.
15
+ * - Only paths under `…/<Parent>/components/<Child>/` are treated as private children.
16
+ * - Does not cover `pages/`, `hooks/`, `utils/`, or package imports — promote shared UI to module `components/`.
17
+ */
18
+ const analyzeNestedComponentImport = (importerFilePath, importSource) => {
19
+ if (!importSource.startsWith(".")) {
20
+ return null;
21
+ }
22
+ const normalizedImporterPath = path.normalize(importerFilePath);
23
+ const importerDirectory = path.dirname(normalizedImporterPath);
24
+ const resolvedImportPath = path.normalize(path.resolve(importerDirectory, importSource));
25
+ const segments = resolvedImportPath.split(path.sep);
26
+ let parentComponentName;
27
+ let childComponentName;
28
+ let parentComponentDirectory = "";
29
+ for (let index = 1; index < segments.length - 1; index += 1) {
30
+ const childName = segments[index + 1];
31
+ const parentName = segments[index - 1];
32
+ if (segments[index] !== "components" || parentName === undefined || childName === undefined) {
33
+ continue;
34
+ }
35
+ if (!source_tree_utils_1.PASCAL_CASE_PATTERN.test(childName) || !source_tree_utils_1.PASCAL_CASE_PATTERN.test(parentName)) {
36
+ continue;
37
+ }
38
+ const ownerComponentDirectory = segments.slice(0, index).join(path.sep);
39
+ if (path.basename(path.dirname(ownerComponentDirectory)) !== "components" ||
40
+ !(0, nested_component_directory_utils_1.isParentComponentModule)(ownerComponentDirectory) ||
41
+ AGGREGATION_FOLDERS.has(parentName)) {
42
+ continue;
43
+ }
44
+ parentComponentName = parentName;
45
+ childComponentName = childName;
46
+ parentComponentDirectory = ownerComponentDirectory;
47
+ }
48
+ if (parentComponentName === undefined || childComponentName === undefined) {
49
+ return null;
50
+ }
51
+ const importerWithinParent = normalizedImporterPath === parentComponentDirectory ||
52
+ normalizedImporterPath.startsWith(`${parentComponentDirectory}${path.sep}`);
53
+ if (importerWithinParent) {
54
+ return null;
55
+ }
56
+ return {
57
+ parentComponentName,
58
+ childComponentName,
59
+ };
60
+ };
61
+ exports.analyzeNestedComponentImport = analyzeNestedComponentImport;
62
+ //# sourceMappingURL=nested-component-privacy-utils.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * ESLint rule: require-page-directory
3
+ *
4
+ * Components passed to a route as `component` must live under a `pages/` directory.
5
+ */
6
+ export declare const requirePageDirectory: import("@typescript-eslint/utils/ts-eslint").RuleModule<"routeComponentOutsidePagesFolder", [], unknown, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
7
+ name: string;
8
+ };
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ /**
3
+ * ESLint rule: require-page-directory
4
+ *
5
+ * Components passed to a route as `component` must live under a `pages/` directory.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.requirePageDirectory = void 0;
9
+ const create_rule_1 = require("../../utils/create-rule/create-rule");
10
+ const page_directory_structure_utils_1 = require("./utils/page-directory-structure-utils/page-directory-structure-utils");
11
+ exports.requirePageDirectory = (0, create_rule_1.createRule)({
12
+ name: "require-page-directory",
13
+ meta: {
14
+ type: "suggestion",
15
+ docs: {
16
+ description: "Require route components to live under a `pages/` directory.",
17
+ },
18
+ schema: [],
19
+ messages: {
20
+ routeComponentOutsidePagesFolder: "`{{pageComponentName}}` is used as a route component in `{{routeFilePath}}`. Move it to `{{suggestedRelativePath}}`.",
21
+ },
22
+ },
23
+ defaultOptions: [],
24
+ create(context) {
25
+ return {
26
+ Program(node) {
27
+ const violation = (0, page_directory_structure_utils_1.analyzePageFolderStructure)(context.filename);
28
+ if (violation?.kind !== "routeComponentOutsidePagesFolder") {
29
+ return;
30
+ }
31
+ context.report({
32
+ node,
33
+ messageId: "routeComponentOutsidePagesFolder",
34
+ data: {
35
+ pageComponentName: violation.pageComponentName,
36
+ routeFilePath: violation.routeFilePath,
37
+ suggestedRelativePath: violation.suggestedRelativePath,
38
+ },
39
+ });
40
+ },
41
+ };
42
+ },
43
+ });
44
+ //# sourceMappingURL=require-page-directory.js.map
@@ -0,0 +1,18 @@
1
+ type PageFolderViolation = {
2
+ readonly kind: "routeComponentOutsidePagesFolder";
3
+ readonly pageComponentName: string;
4
+ readonly routeFilePath: string;
5
+ readonly suggestedRelativePath: string;
6
+ };
7
+ /** True when `filePath` is the file a route registers as `component`. */
8
+ export declare const isRegisteredRouteComponentFile: (filePath: string) => boolean;
9
+ /**
10
+ * Returns a violation when `filePath` is the `component` of a route but does not
11
+ * live in `pages/<Name>/<Name>.tsx` (including `<Scope>/pages/<Name>/`).
12
+ *
13
+ * `App` is not treated as a page. A nested file stays exempt only while the route
14
+ * component file is still in that folder. After the page moves, a child left
15
+ * behind is outside `pages/`.
16
+ */
17
+ export declare const analyzePageFolderStructure: (filePath: string) => PageFolderViolation | null;
18
+ export {};
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyzePageFolderStructure = exports.isRegisteredRouteComponentFile = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
6
+ const ts = tslib_1.__importStar(require("typescript"));
7
+ const source_tree_utils_1 = require("../../../../utils/source-tree-utils/source-tree-utils");
8
+ const ROUTE_FILE_NAMES = new Set(["router.tsx", "routeTree.tsx", "routes.tsx"]);
9
+ const isRouteDefinitionFile = (filePath) => {
10
+ const fileName = path.basename(filePath);
11
+ return (ROUTE_FILE_NAMES.has(fileName) ||
12
+ fileName.endsWith(".routes.ts") ||
13
+ fileName.endsWith(".routes.tsx") ||
14
+ fileName.endsWith("Routes.tsx") ||
15
+ fileName.endsWith("Route.tsx"));
16
+ };
17
+ const isPageComponentName = (componentName) => componentName !== "App";
18
+ const isNamedPageFile = (srcRoot, filePath) => {
19
+ const segments = path.relative(srcRoot, filePath).split(path.sep);
20
+ const pagesIndex = segments.lastIndexOf("pages");
21
+ const fileName = segments.at(-1);
22
+ const folderName = segments.at(-2);
23
+ if (pagesIndex === -1 || fileName === undefined || folderName === undefined) {
24
+ return false;
25
+ }
26
+ return folderName === (0, source_tree_utils_1.getBaseName)(fileName);
27
+ };
28
+ const parseRouteFile = (filePath, content) => {
29
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
30
+ const importMap = new Map();
31
+ const localComponentBindings = new Map();
32
+ const componentNames = [];
33
+ const visit = (node) => {
34
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && node.importClause !== undefined) {
35
+ const source = node.moduleSpecifier.text;
36
+ if (node.importClause.name !== undefined) {
37
+ importMap.set(node.importClause.name.text, source);
38
+ }
39
+ const bindings = node.importClause.namedBindings;
40
+ if (bindings !== undefined && ts.isNamedImports(bindings)) {
41
+ for (const element of bindings.elements) {
42
+ importMap.set(element.name.text, source);
43
+ }
44
+ }
45
+ }
46
+ if (ts.isVariableDeclaration(node) &&
47
+ ts.isIdentifier(node.name) &&
48
+ node.initializer !== undefined &&
49
+ ts.isIdentifier(node.initializer)) {
50
+ localComponentBindings.set(node.name.text, node.initializer.text);
51
+ }
52
+ if (ts.isPropertyAssignment(node) &&
53
+ ts.isIdentifier(node.name) &&
54
+ node.name.text === "component" &&
55
+ ts.isIdentifier(node.initializer)) {
56
+ componentNames.push(node.initializer.text);
57
+ }
58
+ if (ts.isShorthandPropertyAssignment(node) && node.name.text === "component") {
59
+ const resolvedName = localComponentBindings.get("component") ?? node.name.text;
60
+ componentNames.push(resolvedName);
61
+ }
62
+ ts.forEachChild(node, visit);
63
+ };
64
+ visit(sourceFile);
65
+ return { importMap, componentNames };
66
+ };
67
+ const buildRouteComponentIndex = (srcRoot) => {
68
+ const routeFileByComponent = new Map();
69
+ for (const sourceFile of (0, source_tree_utils_1.walkSourceFiles)(srcRoot)) {
70
+ if (!isRouteDefinitionFile(sourceFile)) {
71
+ continue;
72
+ }
73
+ const content = (0, source_tree_utils_1.readSourceFile)(sourceFile);
74
+ if (content === null) {
75
+ continue;
76
+ }
77
+ const { importMap, componentNames } = parseRouteFile(sourceFile, content);
78
+ for (const componentName of componentNames) {
79
+ if (!isPageComponentName(componentName)) {
80
+ continue;
81
+ }
82
+ const importSource = importMap.get(componentName);
83
+ const resolvedPath = importSource === undefined ? null : (0, source_tree_utils_1.resolveRelativeImportPath)(sourceFile, importSource);
84
+ if (resolvedPath !== null && !routeFileByComponent.has(resolvedPath)) {
85
+ routeFileByComponent.set(resolvedPath, sourceFile);
86
+ }
87
+ }
88
+ }
89
+ return routeFileByComponent;
90
+ };
91
+ const routeComponentIndexCache = (0, source_tree_utils_1.createSrcRootCache)(buildRouteComponentIndex);
92
+ /** True when `filePath` is the file a route registers as `component`. */
93
+ const isRegisteredRouteComponentFile = (filePath) => {
94
+ const srcRoot = (0, source_tree_utils_1.getSrcRoot)(filePath);
95
+ if (srcRoot === null) {
96
+ return false;
97
+ }
98
+ return routeComponentIndexCache.get(srcRoot).has(path.normalize(filePath));
99
+ };
100
+ exports.isRegisteredRouteComponentFile = isRegisteredRouteComponentFile;
101
+ const isNestedUnderRouteComponentModuleFolder = (srcRoot, filePath, routeFileByComponent) => {
102
+ const routeComponentNames = new Set();
103
+ for (const routeComponentPath of routeFileByComponent.keys()) {
104
+ routeComponentNames.add((0, source_tree_utils_1.getBaseName)(path.basename(routeComponentPath)));
105
+ }
106
+ const relativeDirectory = path.relative(srcRoot, path.dirname(filePath));
107
+ const segments = relativeDirectory.split(path.sep).filter(segment => segment.length > 0);
108
+ for (let index = 0; index < segments.length; index += 1) {
109
+ const segment = segments[index];
110
+ if (segment === undefined || !routeComponentNames.has(segment)) {
111
+ continue;
112
+ }
113
+ const moduleFolder = path.join(srcRoot, ...segments.slice(0, index + 1));
114
+ const routeComponentFile = path.join(moduleFolder, `${segment}.tsx`);
115
+ if (!routeFileByComponent.has(routeComponentFile)) {
116
+ continue;
117
+ }
118
+ if (filePath !== routeComponentFile && filePath.startsWith(`${moduleFolder}${path.sep}`)) {
119
+ return true;
120
+ }
121
+ }
122
+ return false;
123
+ };
124
+ const getSuggestedPagePath = (srcRoot, componentFilePath) => {
125
+ const relativeSegments = path.relative(srcRoot, componentFilePath).split(path.sep);
126
+ const fileName = path.basename(componentFilePath);
127
+ const componentsIndex = relativeSegments.indexOf("components");
128
+ const scope = componentsIndex > 0 ? relativeSegments.slice(0, componentsIndex) : [];
129
+ return path.join(...scope, "pages", (0, source_tree_utils_1.getBaseName)(fileName), fileName);
130
+ };
131
+ /**
132
+ * Returns a violation when `filePath` is the `component` of a route but does not
133
+ * live in `pages/<Name>/<Name>.tsx` (including `<Scope>/pages/<Name>/`).
134
+ *
135
+ * `App` is not treated as a page. A nested file stays exempt only while the route
136
+ * component file is still in that folder. After the page moves, a child left
137
+ * behind is outside `pages/`.
138
+ */
139
+ const analyzePageFolderStructure = (filePath) => {
140
+ const normalizedPath = path.normalize(filePath);
141
+ const srcRoot = (0, source_tree_utils_1.getSrcRoot)(normalizedPath);
142
+ if (srcRoot === null || isNamedPageFile(srcRoot, normalizedPath)) {
143
+ return null;
144
+ }
145
+ const routeFileByComponent = routeComponentIndexCache.get(srcRoot);
146
+ const routeFilePath = routeFileByComponent.get(normalizedPath);
147
+ if (routeFilePath === undefined ||
148
+ isNestedUnderRouteComponentModuleFolder(srcRoot, normalizedPath, routeFileByComponent)) {
149
+ return null;
150
+ }
151
+ return {
152
+ kind: "routeComponentOutsidePagesFolder",
153
+ pageComponentName: (0, source_tree_utils_1.getBaseName)(path.basename(normalizedPath)),
154
+ routeFilePath: path.relative(srcRoot, routeFilePath),
155
+ suggestedRelativePath: getSuggestedPagePath(srcRoot, normalizedPath),
156
+ };
157
+ };
158
+ exports.analyzePageFolderStructure = analyzePageFolderStructure;
159
+ //# sourceMappingURL=page-directory-structure-utils.js.map
@@ -0,0 +1,7 @@
1
+ import { ESLintUtils } from "@typescript-eslint/utils";
2
+ /**
3
+ * Shared rule factory so every rule links to its own source on the default branch.
4
+ */
5
+ export declare const createRule: <Options extends readonly unknown[], MessageIds extends string>({ meta, name, ...rule }: Readonly<ESLintUtils.RuleWithMetaAndName<Options, MessageIds, unknown>>) => ESLintUtils.RuleModule<MessageIds, Options, unknown, ESLintUtils.RuleListener> & {
6
+ name: string;
7
+ };
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRule = void 0;
4
+ const utils_1 = require("@typescript-eslint/utils");
5
+ /**
6
+ * Shared rule factory so every rule links to its own source on the default branch.
7
+ */
8
+ exports.createRule = utils_1.ESLintUtils.RuleCreator(name => `https://github.com/Trackunit/manager/blob/master/libs/eslint/plugin-trackunit/src/lib/rules/${name}/${name}.ts`);
9
+ //# sourceMappingURL=create-rule.js.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Shared helpers for folder-structure rules that need to look beyond the file
3
+ * ESLint is currently linting: walking a library's `src/` tree and resolving
4
+ * relative imports.
5
+ *
6
+ * ## Main Functions
7
+ * - `getSrcRoot()` - Locate the `src/` directory that owns a file
8
+ * - `walkSourceFiles()` - List every non-spec/story source file under a directory
9
+ * - `resolveRelativeImportPath()` - Resolve `./foo` the way TypeScript would (`.ts`, `.tsx`, `index.*`)
10
+ * - `createSrcRootCache()` - Memoise an expensive per-`src/`-root computation
11
+ * - `clearSourceTreeCaches()` - Reset every cache created here. Useful for testing.
12
+ */
13
+ export declare const SOURCE_FILE_EXTENSIONS: readonly [".ts", ".tsx", ".js", ".jsx"];
14
+ export declare const PASCAL_CASE_PATTERN: RegExp;
15
+ export declare const isSourceFile: (filePath: string) => boolean;
16
+ /** `useFoo.spec.tsx` → `useFoo.spec`; `Button.tsx` → `Button`. */
17
+ export declare const getBaseName: (fileName: string) => string;
18
+ /** The innermost `…/src` directory containing `filePath`, or `null` when there is none. */
19
+ export declare const getSrcRoot: (filePath: string) => string | null;
20
+ export declare const readSourceFile: (filePath: string) => string | null;
21
+ export declare const walkSourceFiles: (directory: string) => ReadonlyArray<string>;
22
+ /**
23
+ * Resolve a relative import the way TypeScript does: exact path, then each
24
+ * source extension, then a directory `index.*`. Non-relative specifiers
25
+ * (packages, path aliases) resolve to `null`.
26
+ */
27
+ export declare const resolveRelativeImportPath: (importerFilePath: string, importSource: string) => string | null;
28
+ type SrcRootCache<TValue> = {
29
+ readonly get: (srcRoot: string) => TValue;
30
+ };
31
+ /**
32
+ * Memoise `compute` per `src/` root for the lifetime of the ESLint process.
33
+ *
34
+ * Rules that inspect the whole tree would otherwise redo the same walk for every
35
+ * file they lint. The trade-off is that a long-lived editor ESLint server sees a
36
+ * snapshot from its first lint of each library until it is restarted.
37
+ */
38
+ export declare const createSrcRootCache: <TValue>(compute: (srcRoot: string) => TValue) => SrcRootCache<TValue>;
39
+ /**
40
+ * Clear every cache created with `createSrcRootCache`. Useful for testing.
41
+ */
42
+ export declare const clearSourceTreeCaches: () => void;
43
+ export {};
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clearSourceTreeCaches = exports.createSrcRootCache = exports.resolveRelativeImportPath = exports.walkSourceFiles = exports.readSourceFile = exports.getSrcRoot = exports.getBaseName = exports.isSourceFile = exports.PASCAL_CASE_PATTERN = exports.SOURCE_FILE_EXTENSIONS = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const path = tslib_1.__importStar(require("path"));
7
+ /**
8
+ * Shared helpers for folder-structure rules that need to look beyond the file
9
+ * ESLint is currently linting: walking a library's `src/` tree and resolving
10
+ * relative imports.
11
+ *
12
+ * ## Main Functions
13
+ * - `getSrcRoot()` - Locate the `src/` directory that owns a file
14
+ * - `walkSourceFiles()` - List every non-spec/story source file under a directory
15
+ * - `resolveRelativeImportPath()` - Resolve `./foo` the way TypeScript would (`.ts`, `.tsx`, `index.*`)
16
+ * - `createSrcRootCache()` - Memoise an expensive per-`src/`-root computation
17
+ * - `clearSourceTreeCaches()` - Reset every cache created here. Useful for testing.
18
+ */
19
+ exports.SOURCE_FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
20
+ exports.PASCAL_CASE_PATTERN = /^[A-Z][a-zA-Z0-9]*$/;
21
+ const TEST_OR_STORY_FILE_PATTERN = /\.(spec|stories)\.(tsx?|jsx?)$/;
22
+ const IGNORED_DIRECTORY_NAMES = new Set(["node_modules", "dist", "generated"]);
23
+ const isSourceExtension = (extension) => exports.SOURCE_FILE_EXTENSIONS.some(sourceExtension => sourceExtension === extension);
24
+ const isSourceFile = (filePath) => isSourceExtension(path.extname(filePath)) && !TEST_OR_STORY_FILE_PATTERN.test(filePath);
25
+ exports.isSourceFile = isSourceFile;
26
+ /** `useFoo.spec.tsx` → `useFoo.spec`; `Button.tsx` → `Button`. */
27
+ const getBaseName = (fileName) => fileName.slice(0, -path.extname(fileName).length);
28
+ exports.getBaseName = getBaseName;
29
+ /** The innermost `…/src` directory containing `filePath`, or `null` when there is none. */
30
+ const getSrcRoot = (filePath) => {
31
+ const parts = path.normalize(filePath).split(path.sep);
32
+ const srcIndex = parts.lastIndexOf("src");
33
+ if (srcIndex === -1) {
34
+ return null;
35
+ }
36
+ return parts.slice(0, srcIndex + 1).join(path.sep);
37
+ };
38
+ exports.getSrcRoot = getSrcRoot;
39
+ const readSourceFile = (filePath) => {
40
+ try {
41
+ return fs.readFileSync(filePath, "utf8");
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ };
47
+ exports.readSourceFile = readSourceFile;
48
+ const walkSourceFiles = (directory) => {
49
+ const files = [];
50
+ const visit = (currentDirectory) => {
51
+ let entries;
52
+ try {
53
+ entries = fs.readdirSync(currentDirectory, { withFileTypes: true });
54
+ }
55
+ catch {
56
+ return;
57
+ }
58
+ for (const entry of entries) {
59
+ const entryPath = path.join(currentDirectory, entry.name);
60
+ if (entry.isDirectory()) {
61
+ if (!IGNORED_DIRECTORY_NAMES.has(entry.name)) {
62
+ visit(entryPath);
63
+ }
64
+ continue;
65
+ }
66
+ if (entry.isFile() && (0, exports.isSourceFile)(entryPath)) {
67
+ files.push(entryPath);
68
+ }
69
+ }
70
+ };
71
+ visit(directory);
72
+ return files;
73
+ };
74
+ exports.walkSourceFiles = walkSourceFiles;
75
+ /**
76
+ * Resolve a relative import the way TypeScript does: exact path, then each
77
+ * source extension, then a directory `index.*`. Non-relative specifiers
78
+ * (packages, path aliases) resolve to `null`.
79
+ */
80
+ const resolveRelativeImportPath = (importerFilePath, importSource) => {
81
+ if (!importSource.startsWith(".")) {
82
+ return null;
83
+ }
84
+ const resolvedBase = path.normalize(path.resolve(path.dirname(importerFilePath), importSource));
85
+ const candidates = [
86
+ resolvedBase,
87
+ ...exports.SOURCE_FILE_EXTENSIONS.map(extension => `${resolvedBase}${extension}`),
88
+ ...exports.SOURCE_FILE_EXTENSIONS.map(extension => path.join(resolvedBase, `index${extension}`)),
89
+ ];
90
+ for (const candidate of candidates) {
91
+ try {
92
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
93
+ return path.normalize(candidate);
94
+ }
95
+ }
96
+ catch {
97
+ continue;
98
+ }
99
+ }
100
+ return null;
101
+ };
102
+ exports.resolveRelativeImportPath = resolveRelativeImportPath;
103
+ const cacheResets = [];
104
+ /**
105
+ * Memoise `compute` per `src/` root for the lifetime of the ESLint process.
106
+ *
107
+ * Rules that inspect the whole tree would otherwise redo the same walk for every
108
+ * file they lint. The trade-off is that a long-lived editor ESLint server sees a
109
+ * snapshot from its first lint of each library until it is restarted.
110
+ */
111
+ const createSrcRootCache = (compute) => {
112
+ const cache = new Map();
113
+ cacheResets.push(() => cache.clear());
114
+ return {
115
+ get: srcRoot => {
116
+ const cached = cache.get(srcRoot);
117
+ if (cached !== undefined) {
118
+ return cached;
119
+ }
120
+ const computed = compute(srcRoot);
121
+ cache.set(srcRoot, computed);
122
+ return computed;
123
+ },
124
+ };
125
+ };
126
+ exports.createSrcRootCache = createSrcRootCache;
127
+ /**
128
+ * Clear every cache created with `createSrcRootCache`. Useful for testing.
129
+ */
130
+ const clearSourceTreeCaches = () => {
131
+ for (const reset of cacheResets) {
132
+ reset();
133
+ }
134
+ };
135
+ exports.clearSourceTreeCaches = clearSourceTreeCaches;
136
+ //# sourceMappingURL=source-tree-utils.js.map