circular-dependency-check 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +93 -2
- package/bin/circular-dependency-check.js +49 -0
- package/package.json +17 -4
- package/src/check.js +81 -0
- package/src/policy.js +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mujan5427
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# circular-dependency-check
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## Installation
|
|
4
|
+
|
|
5
|
+
Requires Node.js 22.x, 24.x, or 26 and later.
|
|
6
|
+
|
|
7
|
+
Install the package as a development dependency in your project:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --save-dev circular-dependency-check
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
Run the CLI from the root of the project you want to check:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx circular-dependency-check
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### Checked and excluded paths
|
|
22
|
+
|
|
23
|
+
Analysis starts from `src/` in the project root, including its subdirectories and local modules reached through imports.
|
|
24
|
+
|
|
25
|
+
The following directories are excluded at any depth:
|
|
26
|
+
|
|
27
|
+
- `dist/`
|
|
28
|
+
- `coverage/`
|
|
29
|
+
- `.git/`
|
|
30
|
+
|
|
31
|
+
Imports into `node_modules/` are retained as dependency targets so forbidden-package imports can be checked, but files inside `node_modules/` are not analyzed or followed.
|
|
32
|
+
|
|
33
|
+
Test code is also excluded:
|
|
34
|
+
|
|
35
|
+
- Files ending in `.test` or `.spec` before a JavaScript or TypeScript extension, such as `example.test.ts`, `example.spec.tsx`, or `example.test.cjs`.
|
|
36
|
+
- `__tests__/` directories at any depth.
|
|
37
|
+
- The project-root `test/` and `tests/` directories, including modules imported from those directories.
|
|
38
|
+
|
|
39
|
+
Other directories named `tests`, such as `src/app/tests/`, remain in scope unless their files match the patterns above. Excluded test code is not analyzed for cycles or other dependency violations. If no non-test modules remain to analyze, the CLI exits with `2`.
|
|
40
|
+
|
|
41
|
+
### Built-in checks
|
|
42
|
+
|
|
43
|
+
All checks below are built into the package and cannot be overridden by project configuration.
|
|
44
|
+
|
|
45
|
+
| Check | Enforced behavior |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| No circular dependencies | Rejects dependency cycles between analyzed modules, including cycles inside the same feature or layer. |
|
|
48
|
+
| No cross-feature dependencies | Rejects direct imports between different immediate subdirectories of `src/features/`. |
|
|
49
|
+
| Shared cannot depend on features | Rejects imports from `src/shared/` into `src/features/`. |
|
|
50
|
+
| Layer dependency direction | Allows `app → features → shared` and `app → shared`; rejects `features → app`, `shared → app`, and `shared → features`. Layers correspond to `src/app/`, `src/features/`, and `src/shared/`. |
|
|
51
|
+
| No forbidden imports | Only `src/lib/http.ts` may directly import or re-export `axios`, including its subpaths and type-only imports. Other production modules under `src/` must use that wrapper. |
|
|
52
|
+
|
|
53
|
+
Layer and forbidden-import violations fail even when no cycle exists. Other directory layouts and additional restricted packages have no extra layer or package restrictions in this preset; circular dependency checks still apply to all analyzed modules. This is a top-level layer policy, with no additional UI/Hook/Store/Socket rules inside a feature.
|
|
54
|
+
|
|
55
|
+
### TypeScript aliases
|
|
56
|
+
|
|
57
|
+
When `tsconfig.json` exists in the project root, the CLI automatically uses its `compilerOptions.baseUrl` and `compilerOptions.paths` to resolve imports such as `@/shared/helper`. No additional CLI arguments are required.
|
|
58
|
+
|
|
59
|
+
The tsconfig is used for module resolution only. Its `files`, `include`, and `exclude` settings do not change the CLI's checked paths, test exclusions, or built-in rules. Without a tsconfig, the CLI uses normal module resolution. Invalid configuration or imports that still cannot be resolved cause exit code `2`.
|
|
60
|
+
|
|
61
|
+
### Run through an npm script
|
|
62
|
+
|
|
63
|
+
Add the following script to your project's `package.json`:
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{
|
|
67
|
+
"scripts": {
|
|
68
|
+
"check:deps": "circular-dependency-check"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Then run:
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
npm run check:deps
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### CLI options
|
|
80
|
+
|
|
81
|
+
Output results as JSON:
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
npx circular-dependency-check --format json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Show help or the installed version:
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
npx circular-dependency-check --help
|
|
91
|
+
npx circular-dependency-check --version
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The CLI exits with `0` when checks pass, `1` when a circular dependency or another architecture violation is found, and `2` when usage or analysis fails.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { check } from '../src/check.js';
|
|
5
|
+
|
|
6
|
+
const help = `Usage: circular-dependency-check [options]
|
|
7
|
+
|
|
8
|
+
Check circular dependencies and architecture boundaries using dependency-cruiser.
|
|
9
|
+
Always checks src in the current directory using the built-in rules.
|
|
10
|
+
External configuration and path overrides are not supported.
|
|
11
|
+
|
|
12
|
+
-f, --format <type> text or json (default: text)
|
|
13
|
+
-h, --help Show help
|
|
14
|
+
-v, --version Show version
|
|
15
|
+
|
|
16
|
+
Exit status: 0 passed; 1 architecture violations; 2 usage/analysis failure.
|
|
17
|
+
`;
|
|
18
|
+
let format = 'text';
|
|
19
|
+
try {
|
|
20
|
+
const { values } = parseArgs({
|
|
21
|
+
allowPositionals: false,
|
|
22
|
+
options: {
|
|
23
|
+
format: { type: 'string', short: 'f' },
|
|
24
|
+
help: { type: 'boolean', short: 'h' },
|
|
25
|
+
version: { type: 'boolean', short: 'v' },
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
format = values.format ?? 'text';
|
|
29
|
+
if (!['text', 'json'].includes(format)) throw new Error('--format must be text or json');
|
|
30
|
+
if (values.help) console.log(help);
|
|
31
|
+
else if (values.version) {
|
|
32
|
+
console.log(JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version);
|
|
33
|
+
} else {
|
|
34
|
+
const result = await check();
|
|
35
|
+
if (format === 'json') console.log(JSON.stringify(result, null, 2));
|
|
36
|
+
else {
|
|
37
|
+
for (const violation of result.violations) {
|
|
38
|
+
console.error(`ERROR ${violation.rule.name}: ${violation.from} -> ${violation.to}`);
|
|
39
|
+
if (violation.cycle) console.error(` cycle: ${violation.cycle.map(step => typeof step === 'string' ? step : step.name).join(' -> ')}`);
|
|
40
|
+
}
|
|
41
|
+
console.log(`${result.ok ? 'PASS' : 'FAIL'}: ${result.modules} modules analyzed, ${result.violations.length} violations.`);
|
|
42
|
+
}
|
|
43
|
+
process.exitCode = result.exitCode;
|
|
44
|
+
}
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (format === 'json') console.log(JSON.stringify({ ok: false, exitCode: 2, error: error.message }));
|
|
47
|
+
else console.error(`Analysis failed: ${error.message}`);
|
|
48
|
+
process.exitCode = 2;
|
|
49
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "circular-dependency-check",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Dependency-cruiser powered CLI for circular dependencies and architecture boundaries",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": { "circular-dependency-check": "bin/circular-dependency-check.js" },
|
|
7
|
+
"files": ["bin/", "src/", "LICENSE"],
|
|
8
|
+
"engines": { "node": "^22.0.0 || ^24.0.0 || >=26.0.0" },
|
|
9
|
+
"scripts": {
|
|
10
|
+
"check": "node bin/circular-dependency-check.js",
|
|
11
|
+
"prepublishOnly": "npm run check"
|
|
12
|
+
},
|
|
13
|
+
"repository": { "type": "git", "url": "git+https://github.com/mujan5427/circular-dependency-check.git" },
|
|
14
|
+
"bugs": { "url": "https://github.com/mujan5427/circular-dependency-check/issues" },
|
|
15
|
+
"homepage": "https://github.com/mujan5427/circular-dependency-check",
|
|
16
|
+
"keywords": ["circular-dependency", "dependency-cruiser", "cli", "architecture", "pre-commit"],
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"dependencies": { "dependency-cruiser": "^18.9.0", "typescript": "^5.9.3" }
|
|
19
|
+
}
|
package/src/check.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { readdir, stat, readFile } from 'node:fs/promises';
|
|
2
|
+
import { cruise } from 'dependency-cruiser';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { policy } from './policy.js';
|
|
5
|
+
|
|
6
|
+
const escape = value => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
7
|
+
const prefix = value => `^${escape(value)}(?:/|$)`;
|
|
8
|
+
const rule = (name, from, to) => ({ name, severity: 'error', from, to });
|
|
9
|
+
|
|
10
|
+
async function createRules() {
|
|
11
|
+
const rules = [
|
|
12
|
+
rule('no-circular-dependencies', {}, { circular: true }),
|
|
13
|
+
rule('no-unresolved-imports', {}, { couldNotResolve: true }),
|
|
14
|
+
rule('shared-cannot-depend-on-features', { path: prefix(policy.shared) }, { path: prefix(policy.features) }),
|
|
15
|
+
];
|
|
16
|
+
let features = [];
|
|
17
|
+
try { features = await readdir(policy.features, { withFileTypes: true }); }
|
|
18
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
19
|
+
for (const feature of features) {
|
|
20
|
+
if (!feature.isDirectory() && !feature.isSymbolicLink()) continue;
|
|
21
|
+
const own = prefix(`${policy.features}/${feature.name}`);
|
|
22
|
+
rules.push(rule(`no-cross-feature-dependencies:${feature.name}`, { path: own }, {
|
|
23
|
+
path: `^${escape(policy.features)}/[^/]+/`, pathNot: own,
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
// Layers are ordered from highest to lowest. Lower layers cannot import higher ones.
|
|
27
|
+
policy.layers.forEach((lower, index) => {
|
|
28
|
+
for (const higher of policy.layers.slice(0, index)) {
|
|
29
|
+
rules.push(rule(`layer-dependency-direction:${lower.name}->${higher.name}`, { path: lower.path }, { path: higher.path }));
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
for (const forbidden of policy.forbiddenImports) {
|
|
33
|
+
rules.push(rule(`no-forbidden-imports:${forbidden.name}`, { path: forbidden.from }, { path: forbidden.to }));
|
|
34
|
+
}
|
|
35
|
+
return rules;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function projectResolutionOptions() {
|
|
39
|
+
try {
|
|
40
|
+
const config = await stat('tsconfig.json');
|
|
41
|
+
if (!config.isFile()) throw new Error('tsconfig.json must be a file.');
|
|
42
|
+
// Only the resolver reads this file; source selection and rules stay internal.
|
|
43
|
+
return { tsConfig: { fileName: 'tsconfig.json' } };
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error.code === 'ENOENT') return {};
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function check() {
|
|
51
|
+
for (const target of policy.paths) await stat(target);
|
|
52
|
+
const forbidden = await createRules();
|
|
53
|
+
const resolutionOptions = await projectResolutionOptions();
|
|
54
|
+
const result = await cruise(policy.paths, {
|
|
55
|
+
outputType: 'json',
|
|
56
|
+
validate: true,
|
|
57
|
+
ruleSet: { forbidden },
|
|
58
|
+
exclude: { path: policy.exclude },
|
|
59
|
+
doNotFollow: { path: '(^|/)node_modules/' },
|
|
60
|
+
tsPreCompilationDeps: true,
|
|
61
|
+
...resolutionOptions,
|
|
62
|
+
});
|
|
63
|
+
const graph = typeof result.output === 'string' ? JSON.parse(result.output) : result.output;
|
|
64
|
+
if (!graph.modules?.length) throw new Error('No modules analyzed. Expected supported source files in src.');
|
|
65
|
+
// dependency-cruiser's tolerant parser can recover from malformed syntax.
|
|
66
|
+
// Reject syntax diagnostics so incomplete graphs never count as a pass.
|
|
67
|
+
for (const module of graph.modules) {
|
|
68
|
+
if (module.coreModule || module.couldNotResolve || /(^|\/)node_modules\//.test(module.source)) continue;
|
|
69
|
+
if (!/\.(?:[cm]?[jt]s|[jt]sx)$/.test(module.source)) continue;
|
|
70
|
+
const source = ts.createSourceFile(module.source, await readFile(module.source, 'utf8'), ts.ScriptTarget.Latest, true);
|
|
71
|
+
const diagnostic = source.parseDiagnostics[0];
|
|
72
|
+
if (diagnostic) {
|
|
73
|
+
const location = source.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
|
|
74
|
+
throw new Error(`${module.source}:${location.line + 1}:${location.character + 1}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const violations = graph.summary.violations ?? [];
|
|
78
|
+
const unresolved = violations.some(v => v.rule.name === 'no-unresolved-imports');
|
|
79
|
+
const exitCode = unresolved ? 2 : violations.length ? 1 : 0;
|
|
80
|
+
return { ok: exitCode === 0, exitCode, modules: graph.modules.length, violations };
|
|
81
|
+
}
|
package/src/policy.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Package-owned policy. Project configuration cannot override analysis scope or rules.
|
|
2
|
+
export const policy = Object.freeze({
|
|
3
|
+
paths: Object.freeze(['src']),
|
|
4
|
+
features: 'src/features',
|
|
5
|
+
shared: 'src/shared',
|
|
6
|
+
// Ordered from highest to lowest. Lower layers cannot import higher layers.
|
|
7
|
+
layers: Object.freeze([
|
|
8
|
+
Object.freeze({ name: 'app', path: '^src/app/' }),
|
|
9
|
+
Object.freeze({ name: 'features', path: '^src/features/' }),
|
|
10
|
+
Object.freeze({ name: 'shared', path: '^src/shared/' }),
|
|
11
|
+
]),
|
|
12
|
+
forbiddenImports: Object.freeze([
|
|
13
|
+
Object.freeze({
|
|
14
|
+
name: 'axios-only-through-http',
|
|
15
|
+
from: '^src/(?!lib/http\\.ts$)',
|
|
16
|
+
to: '(?:^|/)node_modules/axios(?:/|$)|^axios(?:/|$)',
|
|
17
|
+
}),
|
|
18
|
+
]),
|
|
19
|
+
// Keep external package targets, even when their entry point is under dist/.
|
|
20
|
+
// doNotFollow still prevents scanning anything inside node_modules.
|
|
21
|
+
exclude: [
|
|
22
|
+
'^(?!.*(?:^|/)node_modules/)(?:',
|
|
23
|
+
'.*(?:^|/)(?:dist|coverage|\\.git)(?:/|$)',
|
|
24
|
+
'|(?:test|tests)/',
|
|
25
|
+
'|.*(?:^|/)__tests__/',
|
|
26
|
+
'|.*\\.(?:test|spec)\\.[cm]?[jt]sx?$',
|
|
27
|
+
')',
|
|
28
|
+
].join(''),
|
|
29
|
+
});
|