@ts-stack/cycle-detector 1.0.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.
- package/LICENSE +19 -0
- package/README.md +25 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +183 -0
- package/dist/index.js.map +1 -0
- package/eslint.config.mjs +60 -0
- package/package.json +49 -0
- package/src/index.ts +212 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2026 Костя Третяк.
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
19
|
+
THE SOFTWARE
|
package/README.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# @ts-stack/cycle-detector
|
|
2
|
+
|
|
3
|
+
A blistering fast, lightweight, zero-dependency CLI utility designed to detect circular dependencies in TypeScript (ESM) projects.
|
|
4
|
+
|
|
5
|
+
Unlike other tools, it uses the native TypeScript Compiler API for smart path resolution (respecting your `tsconfig.json` paths/aliases) and **completely ignores type-only imports** (`import type`), as they don't cause actual runtime issues in Node.js.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- ⚡ **Blazing Fast**: Uses static AST parsing without full type-checking overhead.
|
|
10
|
+
- 🧠 **Smart Resolution**: Fully supports `tsconfig.json` `paths`, path mappings, and ESM extensions out of the box.
|
|
11
|
+
- 🧱 **Monorepo & Glob Support**: Can check multiple packages at once using wildcards.
|
|
12
|
+
- 🛑 **Type-Safe**: Intelligently skips `import type` and type-only named bindings.
|
|
13
|
+
- 🤖 **CI/CD Ready**: Returns non-zero exit codes when cycles are found.
|
|
14
|
+
|
|
15
|
+
Note: required Node.js >= v22.0.0.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
You don't even need to install it! Just run it via `npx`:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx @ts-stack/cycle-detector src/index.ts
|
|
23
|
+
# OR
|
|
24
|
+
npx @ts-stack/cycle-detector packages/*/src/index.ts
|
|
25
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
const graph = new Map();
|
|
6
|
+
const visited = new Map();
|
|
7
|
+
const currentStack = [];
|
|
8
|
+
const detectedCycles = [];
|
|
9
|
+
/**
|
|
10
|
+
* Parses command line arguments to separate options from entry point patterns.
|
|
11
|
+
*/
|
|
12
|
+
function parseArgs() {
|
|
13
|
+
const args = [...process.argv.slice(2)];
|
|
14
|
+
let projectPath;
|
|
15
|
+
const entryPatterns = [];
|
|
16
|
+
for (let i = 0; i < args.length; i++) {
|
|
17
|
+
if (args[i] === '--project' || args[i] === '-p') {
|
|
18
|
+
projectPath = args[i + 1];
|
|
19
|
+
i++;
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
entryPatterns.push(args[i]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return { entryPatterns, projectPath };
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Checks if an import/export declaration is type-only.
|
|
29
|
+
* Type-only imports are stripped during compilation and don't cause runtime cycles.
|
|
30
|
+
*/
|
|
31
|
+
function isRuntimeImport(node) {
|
|
32
|
+
if (ts.isExportDeclaration(node)) {
|
|
33
|
+
if (!node.moduleSpecifier)
|
|
34
|
+
return false;
|
|
35
|
+
return !node.isTypeOnly;
|
|
36
|
+
}
|
|
37
|
+
if (ts.isImportDeclaration(node)) {
|
|
38
|
+
if (!node.importClause)
|
|
39
|
+
return true; // Side-effect import: import './foo'
|
|
40
|
+
if (node.importClause.isTypeOnly)
|
|
41
|
+
return false; // import type { X } from './foo'
|
|
42
|
+
// Check individual specifiers: import { type A, B } from './foo'
|
|
43
|
+
const namedBindings = node.importClause.namedBindings;
|
|
44
|
+
if (namedBindings && ts.isNamedImports(namedBindings)) {
|
|
45
|
+
return !namedBindings.elements.every((el) => el.isTypeOnly);
|
|
46
|
+
}
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Resolves module paths using the TypeScript Compiler API.
|
|
53
|
+
* Respects tsconfig paths/aliases and ESM extensions.
|
|
54
|
+
*/
|
|
55
|
+
function resolveModule(moduleName, containingFile, options) {
|
|
56
|
+
const result = ts.resolveModuleName(moduleName, containingFile, options, ts.sys);
|
|
57
|
+
if (result.resolvedModule && !result.resolvedModule.isExternalLibraryImport) {
|
|
58
|
+
return result.resolvedModule.resolvedFileName;
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Analyzes a single entry point, builds its dependency graph, and detects cycles.
|
|
64
|
+
*/
|
|
65
|
+
function analyzeEntryPoint(entryPoint, projectPath) {
|
|
66
|
+
graph.clear();
|
|
67
|
+
visited.clear();
|
|
68
|
+
currentStack.length = 0;
|
|
69
|
+
detectedCycles.length = 0;
|
|
70
|
+
// Locate tsconfig.json automatically if not explicitly provided
|
|
71
|
+
const configPath = projectPath
|
|
72
|
+
? path.resolve(projectPath)
|
|
73
|
+
: ts.findConfigFile(path.dirname(entryPoint), ts.sys.fileExists, 'tsconfig.json');
|
|
74
|
+
let compilerOptions = {};
|
|
75
|
+
if (configPath && fs.existsSync(configPath)) {
|
|
76
|
+
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
77
|
+
const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath));
|
|
78
|
+
compilerOptions = parsedConfig.options;
|
|
79
|
+
}
|
|
80
|
+
// Recursive AST parsing to build the graph
|
|
81
|
+
function parseFile(filePath) {
|
|
82
|
+
if (graph.has(filePath) || !fs.existsSync(filePath))
|
|
83
|
+
return;
|
|
84
|
+
graph.set(filePath, []);
|
|
85
|
+
const content = fs.readFileSync(filePath, 'utf8');
|
|
86
|
+
const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
|
|
87
|
+
const imports = [];
|
|
88
|
+
function walk(node) {
|
|
89
|
+
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
|
|
90
|
+
if (isRuntimeImport(node)) {
|
|
91
|
+
const specifier = node.moduleSpecifier;
|
|
92
|
+
if (specifier && ts.isStringLiteral(specifier)) {
|
|
93
|
+
const resolved = resolveModule(specifier.text, filePath, compilerOptions);
|
|
94
|
+
if (resolved && !imports.includes(resolved))
|
|
95
|
+
imports.push(resolved);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
ts.forEachChild(node, walk);
|
|
100
|
+
}
|
|
101
|
+
walk(sourceFile);
|
|
102
|
+
graph.set(filePath, imports);
|
|
103
|
+
for (const dep of imports)
|
|
104
|
+
parseFile(dep);
|
|
105
|
+
}
|
|
106
|
+
// Graph coloring DFS algorithm for cycle detection
|
|
107
|
+
function findCycles(node) {
|
|
108
|
+
visited.set(node, 'VISITING');
|
|
109
|
+
currentStack.push(node);
|
|
110
|
+
for (const neighbor of graph.get(node) || []) {
|
|
111
|
+
const state = visited.get(neighbor);
|
|
112
|
+
if (state === 'VISITING') {
|
|
113
|
+
const startIdx = currentStack.indexOf(neighbor);
|
|
114
|
+
const cycle = currentStack.slice(startIdx);
|
|
115
|
+
cycle.push(neighbor);
|
|
116
|
+
detectedCycles.push(cycle);
|
|
117
|
+
}
|
|
118
|
+
else if (!state) {
|
|
119
|
+
findCycles(neighbor);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
currentStack.pop();
|
|
123
|
+
visited.set(node, 'VISITED');
|
|
124
|
+
}
|
|
125
|
+
parseFile(entryPoint);
|
|
126
|
+
findCycles(entryPoint);
|
|
127
|
+
return detectedCycles;
|
|
128
|
+
}
|
|
129
|
+
function main() {
|
|
130
|
+
const { entryPatterns, projectPath } = parseArgs();
|
|
131
|
+
if (entryPatterns.length == 0) {
|
|
132
|
+
console.error('❌ Error: Please specify at least one entry point or glob pattern (e.g., packages/*/src/index.ts)');
|
|
133
|
+
process.exit(1);
|
|
134
|
+
}
|
|
135
|
+
const entryPoints = [];
|
|
136
|
+
// Expand glob patterns or fall back to direct paths
|
|
137
|
+
for (const pattern of entryPatterns) {
|
|
138
|
+
const matches = fs.globSync ? fs.globSync(pattern) : [pattern];
|
|
139
|
+
for (const match of matches) {
|
|
140
|
+
let fullPath = path.resolve(match);
|
|
141
|
+
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
|
|
142
|
+
const indexTs = path.join(fullPath, 'index.ts');
|
|
143
|
+
const indexTsx = path.join(fullPath, 'index.tsx');
|
|
144
|
+
fullPath = fs.existsSync(indexTs) ? indexTs : indexTsx;
|
|
145
|
+
}
|
|
146
|
+
if (fs.existsSync(fullPath) && !entryPoints.includes(fullPath)) {
|
|
147
|
+
entryPoints.push(fullPath);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (entryPoints.length === 0) {
|
|
152
|
+
console.error('❌ Error: No entry files found matching the provided paths or patterns.');
|
|
153
|
+
process.exit(1);
|
|
154
|
+
}
|
|
155
|
+
console.log(`🔍 Found ${entryPoints.length} entry point(s) for analysis...\n`);
|
|
156
|
+
let globalHasCycles = false;
|
|
157
|
+
for (const entryPoint of entryPoints) {
|
|
158
|
+
const relativeEntry = path.relative(process.cwd(), entryPoint);
|
|
159
|
+
const cycles = analyzeEntryPoint(entryPoint, projectPath);
|
|
160
|
+
if (cycles.length > 0) {
|
|
161
|
+
globalHasCycles = true;
|
|
162
|
+
console.error(`❌ [${relativeEntry}] — Found ${cycles.length} circular dependencies:`);
|
|
163
|
+
cycles.forEach((cycle, index) => {
|
|
164
|
+
const readableCycle = cycle.map((p) => path.relative(process.cwd(), p)).join(' -> ');
|
|
165
|
+
console.error(` ${index + 1}) ${readableCycle}`);
|
|
166
|
+
});
|
|
167
|
+
console.error('');
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
console.log(`✅ [${relativeEntry}] — Clean!`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (globalHasCycles) {
|
|
174
|
+
console.error('💥 Validation failed. Circular dependencies detected.');
|
|
175
|
+
process.exit(1);
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
console.log('🎉 All packages checked. No circular dependencies found!');
|
|
179
|
+
process.exit(0);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
main();
|
|
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AC,IAAI,CAAC,MAAM,CAAC,CAAC;gBACrF,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,GAAG,CAAC,KAAK,aAAa,EAAE,CAAC,CAAC;YACpD,CAAC,CAAC,CAAC;YACH,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACpB,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,GAAG,CAAC,MAAM,aAAa,YAAY,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;IAED,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAC;QACvE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAC;QACxE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import eslint from '@eslint/js';
|
|
4
|
+
import { defineConfig } from 'eslint/config';
|
|
5
|
+
import tseslint from 'typescript-eslint';
|
|
6
|
+
|
|
7
|
+
export default defineConfig([
|
|
8
|
+
eslint.configs.recommended,
|
|
9
|
+
...tseslint.configs.recommended,
|
|
10
|
+
{
|
|
11
|
+
languageOptions: {
|
|
12
|
+
parserOptions: {
|
|
13
|
+
projectService: true,
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
rules: {
|
|
19
|
+
semi: ['error', 'always'],
|
|
20
|
+
quotes: ['error', 'single', { avoidEscape: true }],
|
|
21
|
+
'@typescript-eslint/no-floating-promises': 'error',
|
|
22
|
+
'@typescript-eslint/no-misused-promises': 1,
|
|
23
|
+
'@typescript-eslint/no-unused-expressions': 'warn',
|
|
24
|
+
'@typescript-eslint/consistent-type-imports': 1,
|
|
25
|
+
'@typescript-eslint/no-empty-object-type': 0,
|
|
26
|
+
'@typescript-eslint/no-non-null-assertion': 0,
|
|
27
|
+
'@typescript-eslint/no-empty-function': 0,
|
|
28
|
+
'@typescript-eslint/no-empty-interface': 0,
|
|
29
|
+
'@typescript-eslint/explicit-function-return-type': 0,
|
|
30
|
+
'@typescript-eslint/explicit-module-boundary-types': 0,
|
|
31
|
+
'@typescript-eslint/no-explicit-any': 0,
|
|
32
|
+
'@typescript-eslint/no-inferrable-types': 0,
|
|
33
|
+
'@typescript-eslint/no-non-null-asserted-optional-chain': 0,
|
|
34
|
+
'@typescript-eslint/no-unused-vars': 0,
|
|
35
|
+
'@typescript-eslint/triple-slash-reference': 0,
|
|
36
|
+
'@typescript-eslint/no-unsafe-function-type': 0,
|
|
37
|
+
'no-unused-private-class-members': 'warn',
|
|
38
|
+
'no-useless-assignment': 'warn',
|
|
39
|
+
'no-restricted-imports': ['error', 'fs'],
|
|
40
|
+
'prefer-const': 'warn',
|
|
41
|
+
'no-async-promise-executor': 0,
|
|
42
|
+
'no-prototype-builtins': 0,
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
ignores: [
|
|
47
|
+
'**/dist*',
|
|
48
|
+
'**/*.d.ts',
|
|
49
|
+
'website/*',
|
|
50
|
+
'node_modules/*',
|
|
51
|
+
'eslint.config.mjs',
|
|
52
|
+
'**/jest.config.ts',
|
|
53
|
+
'**/vitest.config.ts',
|
|
54
|
+
'**/jest.setup.js',
|
|
55
|
+
'**/jest.d.ts',
|
|
56
|
+
'**/jest.matchers.ts',
|
|
57
|
+
'packages/openapi/ui/*',
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
]);
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ts-stack/cycle-detector",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"description": "A fast, zero-dependency CLI tool to detect circular dependencies in TypeScript ESM projects, ignoring type-only imports.",
|
|
6
|
+
"repository": "https://github.com/ts-stack/cycle-detector",
|
|
7
|
+
"exports": {
|
|
8
|
+
"./package.json": {
|
|
9
|
+
"default": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"imports": {
|
|
17
|
+
"#lib/*": "./dist/*"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"start": "npm run build && node dist/index.js",
|
|
21
|
+
"test": "npm run build-test && npm run esm-jest",
|
|
22
|
+
"esm-jest": "node --experimental-vm-modules --no-warnings=ExperimentalWarning node_modules/jest/bin/jest.js",
|
|
23
|
+
"build": "tsc -b tsconfig.build.json",
|
|
24
|
+
"build-test": "tsc -b tsconfig.unit.json",
|
|
25
|
+
"clean": "rimraf dist*"
|
|
26
|
+
},
|
|
27
|
+
"keywords": ["lint", "circular dependencies"],
|
|
28
|
+
"author": "Kostia Tretiak",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@eslint/js": "^10.0.1",
|
|
32
|
+
"@types/jest": "^29.5.14",
|
|
33
|
+
"@types/node": "^26.0.0",
|
|
34
|
+
"eslint": "^10.5.0",
|
|
35
|
+
"jest": "^29.7.0",
|
|
36
|
+
"nodemon": "^3.1.14",
|
|
37
|
+
"prettier": "^3.8.4",
|
|
38
|
+
"rimraf": "^5.0.10",
|
|
39
|
+
"ts-node": "^10.9.2",
|
|
40
|
+
"typescript": "^5.9.3",
|
|
41
|
+
"typescript-eslint": "^8.62.0"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">= 22.0.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import ts from 'typescript';
|
|
6
|
+
|
|
7
|
+
type NodeState = 'VISITING' | 'VISITED';
|
|
8
|
+
|
|
9
|
+
const graph = new Map<string, string[]>();
|
|
10
|
+
const visited = new Map<string, NodeState>();
|
|
11
|
+
const currentStack: string[] = [];
|
|
12
|
+
const detectedCycles: string[][] = [];
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Parses command line arguments to separate options from entry point patterns.
|
|
16
|
+
*/
|
|
17
|
+
function parseArgs() {
|
|
18
|
+
const args = [...process.argv.slice(2)];
|
|
19
|
+
let projectPath: string | undefined;
|
|
20
|
+
const entryPatterns: string[] = [];
|
|
21
|
+
|
|
22
|
+
for (let i = 0; i < args.length; i++) {
|
|
23
|
+
if (args[i] === '--project' || args[i] === '-p') {
|
|
24
|
+
projectPath = args[i + 1];
|
|
25
|
+
i++;
|
|
26
|
+
} else {
|
|
27
|
+
entryPatterns.push(args[i]);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return { entryPatterns, projectPath };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Checks if an import/export declaration is type-only.
|
|
36
|
+
* Type-only imports are stripped during compilation and don't cause runtime cycles.
|
|
37
|
+
*/
|
|
38
|
+
function isRuntimeImport(node: ts.ImportDeclaration | ts.ExportDeclaration): boolean {
|
|
39
|
+
if (ts.isExportDeclaration(node)) {
|
|
40
|
+
if (!node.moduleSpecifier) return false;
|
|
41
|
+
return !node.isTypeOnly;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (ts.isImportDeclaration(node)) {
|
|
45
|
+
if (!node.importClause) return true; // Side-effect import: import './foo'
|
|
46
|
+
if (node.importClause.isTypeOnly) return false; // import type { X } from './foo'
|
|
47
|
+
|
|
48
|
+
// Check individual specifiers: import { type A, B } from './foo'
|
|
49
|
+
const namedBindings = node.importClause.namedBindings;
|
|
50
|
+
if (namedBindings && ts.isNamedImports(namedBindings)) {
|
|
51
|
+
return !namedBindings.elements.every((el) => el.isTypeOnly);
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolves module paths using the TypeScript Compiler API.
|
|
61
|
+
* Respects tsconfig paths/aliases and ESM extensions.
|
|
62
|
+
*/
|
|
63
|
+
function resolveModule(moduleName: string, containingFile: string, options: ts.CompilerOptions): string | null {
|
|
64
|
+
const result = ts.resolveModuleName(moduleName, containingFile, options, ts.sys);
|
|
65
|
+
if (result.resolvedModule && !result.resolvedModule.isExternalLibraryImport) {
|
|
66
|
+
return result.resolvedModule.resolvedFileName;
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Analyzes a single entry point, builds its dependency graph, and detects cycles.
|
|
73
|
+
*/
|
|
74
|
+
function analyzeEntryPoint(entryPoint: string, projectPath?: string): string[][] {
|
|
75
|
+
graph.clear();
|
|
76
|
+
visited.clear();
|
|
77
|
+
currentStack.length = 0;
|
|
78
|
+
detectedCycles.length = 0;
|
|
79
|
+
|
|
80
|
+
// Locate tsconfig.json automatically if not explicitly provided
|
|
81
|
+
const configPath = projectPath
|
|
82
|
+
? path.resolve(projectPath)
|
|
83
|
+
: ts.findConfigFile(path.dirname(entryPoint), ts.sys.fileExists, 'tsconfig.json');
|
|
84
|
+
|
|
85
|
+
let compilerOptions: ts.CompilerOptions = {};
|
|
86
|
+
|
|
87
|
+
if (configPath && fs.existsSync(configPath)) {
|
|
88
|
+
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
89
|
+
const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(configPath));
|
|
90
|
+
compilerOptions = parsedConfig.options;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Recursive AST parsing to build the graph
|
|
94
|
+
function parseFile(filePath: string) {
|
|
95
|
+
if (graph.has(filePath) || !fs.existsSync(filePath)) return;
|
|
96
|
+
graph.set(filePath, []);
|
|
97
|
+
|
|
98
|
+
const content = fs.readFileSync(filePath, 'utf8');
|
|
99
|
+
const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
|
|
100
|
+
const imports: string[] = [];
|
|
101
|
+
|
|
102
|
+
function walk(node: ts.Node) {
|
|
103
|
+
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
|
|
104
|
+
if (isRuntimeImport(node)) {
|
|
105
|
+
const specifier = node.moduleSpecifier;
|
|
106
|
+
if (specifier && ts.isStringLiteral(specifier)) {
|
|
107
|
+
const resolved = resolveModule(specifier.text, filePath, compilerOptions);
|
|
108
|
+
if (resolved && !imports.includes(resolved)) imports.push(resolved);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
ts.forEachChild(node, walk);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
walk(sourceFile);
|
|
116
|
+
graph.set(filePath, imports);
|
|
117
|
+
|
|
118
|
+
for (const dep of imports) parseFile(dep);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Graph coloring DFS algorithm for cycle detection
|
|
122
|
+
function findCycles(node: string) {
|
|
123
|
+
visited.set(node, 'VISITING');
|
|
124
|
+
currentStack.push(node);
|
|
125
|
+
|
|
126
|
+
for (const neighbor of graph.get(node) || []) {
|
|
127
|
+
const state = visited.get(neighbor);
|
|
128
|
+
if (state === 'VISITING') {
|
|
129
|
+
const startIdx = currentStack.indexOf(neighbor);
|
|
130
|
+
const cycle = currentStack.slice(startIdx);
|
|
131
|
+
cycle.push(neighbor);
|
|
132
|
+
detectedCycles.push(cycle);
|
|
133
|
+
} else if (!state) {
|
|
134
|
+
findCycles(neighbor);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
currentStack.pop();
|
|
139
|
+
visited.set(node, 'VISITED');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
parseFile(entryPoint);
|
|
143
|
+
findCycles(entryPoint);
|
|
144
|
+
|
|
145
|
+
return detectedCycles;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function main() {
|
|
149
|
+
const { entryPatterns, projectPath } = parseArgs();
|
|
150
|
+
|
|
151
|
+
if (entryPatterns.length == 0) {
|
|
152
|
+
console.error('❌ Error: Please specify at least one entry point or glob pattern (e.g., packages/*/src/index.ts)');
|
|
153
|
+
process.exit(1);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const entryPoints: string[] = [];
|
|
157
|
+
|
|
158
|
+
// Expand glob patterns or fall back to direct paths
|
|
159
|
+
for (const pattern of entryPatterns) {
|
|
160
|
+
const matches = fs.globSync ? fs.globSync(pattern) : [pattern];
|
|
161
|
+
|
|
162
|
+
for (const match of matches) {
|
|
163
|
+
let fullPath = path.resolve(match);
|
|
164
|
+
|
|
165
|
+
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
|
|
166
|
+
const indexTs = path.join(fullPath, 'index.ts');
|
|
167
|
+
const indexTsx = path.join(fullPath, 'index.tsx');
|
|
168
|
+
fullPath = fs.existsSync(indexTs) ? indexTs : indexTsx;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (fs.existsSync(fullPath) && !entryPoints.includes(fullPath)) {
|
|
172
|
+
entryPoints.push(fullPath);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (entryPoints.length === 0) {
|
|
178
|
+
console.error('❌ Error: No entry files found matching the provided paths or patterns.');
|
|
179
|
+
process.exit(1);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
console.log(`🔍 Found ${entryPoints.length} entry point(s) for analysis...\n`);
|
|
183
|
+
|
|
184
|
+
let globalHasCycles = false;
|
|
185
|
+
|
|
186
|
+
for (const entryPoint of entryPoints) {
|
|
187
|
+
const relativeEntry = path.relative(process.cwd(), entryPoint);
|
|
188
|
+
const cycles = analyzeEntryPoint(entryPoint, projectPath);
|
|
189
|
+
|
|
190
|
+
if (cycles.length > 0) {
|
|
191
|
+
globalHasCycles = true;
|
|
192
|
+
console.error(`❌ [${relativeEntry}] — Found ${cycles.length} circular dependencies:`);
|
|
193
|
+
cycles.forEach((cycle, index) => {
|
|
194
|
+
const readableCycle = cycle.map((p) => path.relative(process.cwd(), p)).join(' -> ');
|
|
195
|
+
console.error(` ${index + 1}) ${readableCycle}`);
|
|
196
|
+
});
|
|
197
|
+
console.error('');
|
|
198
|
+
} else {
|
|
199
|
+
console.log(`✅ [${relativeEntry}] — Clean!`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (globalHasCycles) {
|
|
204
|
+
console.error('💥 Validation failed. Circular dependencies detected.');
|
|
205
|
+
process.exit(1);
|
|
206
|
+
} else {
|
|
207
|
+
console.log('🎉 All packages checked. No circular dependencies found!');
|
|
208
|
+
process.exit(0);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
main();
|