@eduardbar/drift 1.0.0 → 1.2.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/.github/actions/drift-scan/README.md +61 -0
- package/.github/actions/drift-scan/action.yml +65 -0
- package/.github/workflows/publish-vscode.yml +3 -1
- package/.github/workflows/review-pr.yml +61 -0
- package/AGENTS.md +53 -11
- package/README.md +106 -1
- package/dist/analyzer.d.ts +6 -2
- package/dist/analyzer.js +116 -3
- package/dist/badge.js +40 -22
- package/dist/ci.js +32 -18
- package/dist/cli.js +179 -6
- package/dist/diff.d.ts +0 -7
- package/dist/diff.js +26 -25
- package/dist/fix.d.ts +4 -0
- package/dist/fix.js +59 -47
- package/dist/git/trend.js +1 -0
- package/dist/git.d.ts +0 -9
- package/dist/git.js +25 -19
- package/dist/index.d.ts +7 -1
- package/dist/index.js +4 -0
- package/dist/map.d.ts +4 -0
- package/dist/map.js +191 -0
- package/dist/metrics.d.ts +4 -0
- package/dist/metrics.js +176 -0
- package/dist/plugins.d.ts +6 -0
- package/dist/plugins.js +74 -0
- package/dist/printer.js +20 -0
- package/dist/report.js +34 -0
- package/dist/reporter.js +85 -2
- package/dist/review.d.ts +15 -0
- package/dist/review.js +80 -0
- package/dist/rules/comments.d.ts +4 -0
- package/dist/rules/comments.js +45 -0
- package/dist/rules/complexity.d.ts +4 -0
- package/dist/rules/complexity.js +51 -0
- package/dist/rules/coupling.d.ts +4 -0
- package/dist/rules/coupling.js +19 -0
- package/dist/rules/magic.d.ts +4 -0
- package/dist/rules/magic.js +33 -0
- package/dist/rules/nesting.d.ts +5 -0
- package/dist/rules/nesting.js +82 -0
- package/dist/rules/phase0-basic.js +14 -7
- package/dist/rules/phase1-complexity.d.ts +6 -30
- package/dist/rules/phase1-complexity.js +7 -276
- package/dist/rules/phase2-crossfile.d.ts +0 -4
- package/dist/rules/phase2-crossfile.js +52 -39
- package/dist/rules/phase3-arch.d.ts +0 -8
- package/dist/rules/phase3-arch.js +26 -23
- package/dist/rules/phase3-configurable.d.ts +6 -0
- package/dist/rules/phase3-configurable.js +97 -0
- package/dist/rules/phase8-semantic.d.ts +0 -5
- package/dist/rules/phase8-semantic.js +30 -29
- package/dist/rules/promise.d.ts +4 -0
- package/dist/rules/promise.js +24 -0
- package/dist/saas.d.ts +83 -0
- package/dist/saas.js +321 -0
- package/dist/snapshot.d.ts +19 -0
- package/dist/snapshot.js +119 -0
- package/dist/types.d.ts +75 -0
- package/dist/utils.d.ts +2 -1
- package/dist/utils.js +1 -0
- package/docs/AGENTS.md +146 -0
- package/docs/PRD.md +157 -0
- package/package.json +1 -1
- package/packages/eslint-plugin-drift/src/index.ts +1 -1
- package/packages/vscode-drift/package.json +1 -1
- package/packages/vscode-drift/src/analyzer.ts +2 -0
- package/packages/vscode-drift/src/code-actions.ts +53 -0
- package/packages/vscode-drift/src/extension.ts +98 -63
- package/packages/vscode-drift/src/statusbar.ts +13 -5
- package/packages/vscode-drift/src/treeview.ts +2 -0
- package/src/analyzer.ts +144 -12
- package/src/badge.ts +38 -16
- package/src/ci.ts +38 -17
- package/src/cli.ts +206 -7
- package/src/diff.ts +36 -30
- package/src/fix.ts +77 -53
- package/src/git/trend.ts +3 -2
- package/src/git.ts +31 -22
- package/src/index.ts +31 -1
- package/src/map.ts +219 -0
- package/src/metrics.ts +200 -0
- package/src/plugins.ts +76 -0
- package/src/printer.ts +20 -0
- package/src/report.ts +35 -0
- package/src/reporter.ts +95 -2
- package/src/review.ts +98 -0
- package/src/rules/comments.ts +56 -0
- package/src/rules/complexity.ts +57 -0
- package/src/rules/coupling.ts +23 -0
- package/src/rules/magic.ts +38 -0
- package/src/rules/nesting.ts +88 -0
- package/src/rules/phase0-basic.ts +14 -7
- package/src/rules/phase1-complexity.ts +8 -302
- package/src/rules/phase2-crossfile.ts +68 -40
- package/src/rules/phase3-arch.ts +34 -30
- package/src/rules/phase3-configurable.ts +132 -0
- package/src/rules/phase8-semantic.ts +33 -29
- package/src/rules/promise.ts +29 -0
- package/src/saas.ts +433 -0
- package/src/snapshot.ts +175 -0
- package/src/types.ts +81 -1
- package/src/utils.ts +3 -1
- package/tests/new-features.test.ts +180 -0
- package/tests/saas-foundation.test.ts +107 -0
|
@@ -1,277 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
function getCyclomaticComplexity(fn) {
|
|
9
|
-
let complexity = 1; // base path
|
|
10
|
-
const incrementKinds = [
|
|
11
|
-
SyntaxKind.IfStatement,
|
|
12
|
-
SyntaxKind.ForStatement,
|
|
13
|
-
SyntaxKind.ForInStatement,
|
|
14
|
-
SyntaxKind.ForOfStatement,
|
|
15
|
-
SyntaxKind.WhileStatement,
|
|
16
|
-
SyntaxKind.DoStatement,
|
|
17
|
-
SyntaxKind.CaseClause,
|
|
18
|
-
SyntaxKind.CatchClause,
|
|
19
|
-
SyntaxKind.ConditionalExpression, // ternary
|
|
20
|
-
SyntaxKind.AmpersandAmpersandToken,
|
|
21
|
-
SyntaxKind.BarBarToken,
|
|
22
|
-
SyntaxKind.QuestionQuestionToken, // ??
|
|
23
|
-
];
|
|
24
|
-
for (const kind of incrementKinds) {
|
|
25
|
-
complexity += fn.getDescendantsOfKind(kind).length;
|
|
26
|
-
}
|
|
27
|
-
return complexity;
|
|
28
|
-
}
|
|
29
|
-
export function detectHighComplexity(file) {
|
|
30
|
-
const issues = [];
|
|
31
|
-
const fns = [
|
|
32
|
-
...file.getFunctions(),
|
|
33
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
34
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
35
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
36
|
-
];
|
|
37
|
-
for (const fn of fns) {
|
|
38
|
-
const complexity = getCyclomaticComplexity(fn);
|
|
39
|
-
if (complexity > 10) {
|
|
40
|
-
const startLine = fn.getStartLineNumber();
|
|
41
|
-
if (hasIgnoreComment(file, startLine))
|
|
42
|
-
continue;
|
|
43
|
-
issues.push({
|
|
44
|
-
rule: 'high-complexity',
|
|
45
|
-
severity: 'error',
|
|
46
|
-
message: `Cyclomatic complexity is ${complexity} (threshold: 10). AI generates correct code, not simple code.`,
|
|
47
|
-
line: startLine,
|
|
48
|
-
column: fn.getStartLinePos(),
|
|
49
|
-
snippet: getSnippet(fn, file),
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return issues;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Deep nesting: count the maximum nesting depth of control flow inside a function.
|
|
57
|
-
* Counts: if, for, while, do, try, switch.
|
|
58
|
-
* Threshold: > 3 levels.
|
|
59
|
-
*/
|
|
60
|
-
function getMaxNestingDepth(fn) {
|
|
61
|
-
const nestingKinds = new Set([
|
|
62
|
-
SyntaxKind.IfStatement,
|
|
63
|
-
SyntaxKind.ForStatement,
|
|
64
|
-
SyntaxKind.ForInStatement,
|
|
65
|
-
SyntaxKind.ForOfStatement,
|
|
66
|
-
SyntaxKind.WhileStatement,
|
|
67
|
-
SyntaxKind.DoStatement,
|
|
68
|
-
SyntaxKind.TryStatement,
|
|
69
|
-
SyntaxKind.SwitchStatement,
|
|
70
|
-
]);
|
|
71
|
-
let maxDepth = 0;
|
|
72
|
-
function walk(node, depth) {
|
|
73
|
-
if (nestingKinds.has(node.getKind())) {
|
|
74
|
-
depth++;
|
|
75
|
-
if (depth > maxDepth)
|
|
76
|
-
maxDepth = depth;
|
|
77
|
-
}
|
|
78
|
-
for (const child of node.getChildren()) {
|
|
79
|
-
walk(child, depth);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
walk(fn, 0);
|
|
83
|
-
return maxDepth;
|
|
84
|
-
}
|
|
85
|
-
export function detectDeepNesting(file) {
|
|
86
|
-
const issues = [];
|
|
87
|
-
const fns = [
|
|
88
|
-
...file.getFunctions(),
|
|
89
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
90
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
91
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
92
|
-
];
|
|
93
|
-
for (const fn of fns) {
|
|
94
|
-
const depth = getMaxNestingDepth(fn);
|
|
95
|
-
if (depth > 3) {
|
|
96
|
-
const startLine = fn.getStartLineNumber();
|
|
97
|
-
if (hasIgnoreComment(file, startLine))
|
|
98
|
-
continue;
|
|
99
|
-
issues.push({
|
|
100
|
-
rule: 'deep-nesting',
|
|
101
|
-
severity: 'warning',
|
|
102
|
-
message: `Maximum nesting depth is ${depth} (threshold: 3). Deep nesting is the #1 readability killer.`,
|
|
103
|
-
line: startLine,
|
|
104
|
-
column: fn.getStartLinePos(),
|
|
105
|
-
snippet: getSnippet(fn, file),
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
return issues;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Too many parameters: functions with more than 4 parameters.
|
|
113
|
-
* AI avoids refactoring parameters into objects/options bags.
|
|
114
|
-
*/
|
|
115
|
-
export function detectTooManyParams(file) {
|
|
116
|
-
const issues = [];
|
|
117
|
-
const fns = [
|
|
118
|
-
...file.getFunctions(),
|
|
119
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
120
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
121
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
122
|
-
];
|
|
123
|
-
for (const fn of fns) {
|
|
124
|
-
const paramCount = fn.getParameters().length;
|
|
125
|
-
if (paramCount > 4) {
|
|
126
|
-
const startLine = fn.getStartLineNumber();
|
|
127
|
-
if (hasIgnoreComment(file, startLine))
|
|
128
|
-
continue;
|
|
129
|
-
issues.push({
|
|
130
|
-
rule: 'too-many-params',
|
|
131
|
-
severity: 'warning',
|
|
132
|
-
message: `Function has ${paramCount} parameters (threshold: 4). AI avoids refactoring into options objects.`,
|
|
133
|
-
line: startLine,
|
|
134
|
-
column: fn.getStartLinePos(),
|
|
135
|
-
snippet: getSnippet(fn, file),
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
return issues;
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* High coupling: files with more than 10 distinct import sources.
|
|
143
|
-
* AI imports broadly without considering module cohesion.
|
|
144
|
-
*/
|
|
145
|
-
export function detectHighCoupling(file) {
|
|
146
|
-
const imports = file.getImportDeclarations();
|
|
147
|
-
const sources = new Set(imports.map((i) => i.getModuleSpecifierValue()));
|
|
148
|
-
if (sources.size > 10) {
|
|
149
|
-
return [
|
|
150
|
-
{
|
|
151
|
-
rule: 'high-coupling',
|
|
152
|
-
severity: 'warning',
|
|
153
|
-
message: `File imports from ${sources.size} distinct modules (threshold: 10). High coupling makes refactoring dangerous.`,
|
|
154
|
-
line: 1,
|
|
155
|
-
column: 1,
|
|
156
|
-
snippet: `// ${sources.size} import sources`,
|
|
157
|
-
},
|
|
158
|
-
];
|
|
159
|
-
}
|
|
160
|
-
return [];
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Promise style mix: async/await and .then()/.catch() used in the same file.
|
|
164
|
-
* AI generates both styles without consistency.
|
|
165
|
-
*/
|
|
166
|
-
export function detectPromiseStyleMix(file) {
|
|
167
|
-
const text = file.getFullText();
|
|
168
|
-
// detect .then( or .catch( calls (property access on a promise)
|
|
169
|
-
const hasThen = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).some((node) => {
|
|
170
|
-
const name = node.getName();
|
|
171
|
-
return name === 'then' || name === 'catch';
|
|
172
|
-
});
|
|
173
|
-
// detect async keyword usage
|
|
174
|
-
const hasAsync = file.getDescendantsOfKind(SyntaxKind.AsyncKeyword).length > 0 ||
|
|
175
|
-
/\bawait\b/.test(text);
|
|
176
|
-
if (hasThen && hasAsync) {
|
|
177
|
-
return [
|
|
178
|
-
{
|
|
179
|
-
rule: 'promise-style-mix',
|
|
180
|
-
severity: 'warning',
|
|
181
|
-
message: `File mixes async/await with .then()/.catch(). AI generates both styles without picking one.`,
|
|
182
|
-
line: 1,
|
|
183
|
-
column: 1,
|
|
184
|
-
snippet: `// mixed promise styles detected`,
|
|
185
|
-
},
|
|
186
|
-
];
|
|
187
|
-
}
|
|
188
|
-
return [];
|
|
189
|
-
}
|
|
190
|
-
/**
|
|
191
|
-
* Magic numbers: numeric literals used directly in logic outside of named constants.
|
|
192
|
-
* Excludes 0, 1, -1 (universally understood) and array indices in obvious patterns.
|
|
193
|
-
*/
|
|
194
|
-
export function detectMagicNumbers(file) {
|
|
195
|
-
const issues = [];
|
|
196
|
-
const ALLOWED = new Set([0, 1, -1, 2, 100]);
|
|
197
|
-
for (const node of file.getDescendantsOfKind(SyntaxKind.NumericLiteral)) {
|
|
198
|
-
const value = Number(node.getLiteralValue());
|
|
199
|
-
if (ALLOWED.has(value))
|
|
200
|
-
continue;
|
|
201
|
-
// Skip: variable/const initializers at top level (those ARE the named constants)
|
|
202
|
-
const parent = node.getParent();
|
|
203
|
-
if (!parent)
|
|
204
|
-
continue;
|
|
205
|
-
const parentKind = parent.getKind();
|
|
206
|
-
if (parentKind === SyntaxKind.VariableDeclaration ||
|
|
207
|
-
parentKind === SyntaxKind.PropertyAssignment ||
|
|
208
|
-
parentKind === SyntaxKind.EnumMember ||
|
|
209
|
-
parentKind === SyntaxKind.Parameter)
|
|
210
|
-
continue;
|
|
211
|
-
const line = node.getStartLineNumber();
|
|
212
|
-
if (hasIgnoreComment(file, line))
|
|
213
|
-
continue;
|
|
214
|
-
issues.push({
|
|
215
|
-
rule: 'magic-number',
|
|
216
|
-
severity: 'info',
|
|
217
|
-
message: `Magic number ${value} used directly in logic. Extract to a named constant.`,
|
|
218
|
-
line,
|
|
219
|
-
column: node.getStartLinePos(),
|
|
220
|
-
snippet: getSnippet(node, file),
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
return issues;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Comment contradiction: comments that restate exactly what the code does.
|
|
227
|
-
* Classic AI pattern — documents the obvious instead of the why.
|
|
228
|
-
* Detects: "// increment counter" above counter++, "// return x" above return x, etc.
|
|
229
|
-
*/
|
|
230
|
-
export function detectCommentContradiction(file) {
|
|
231
|
-
const issues = [];
|
|
232
|
-
const lines = file.getFullText().split('\n');
|
|
233
|
-
// Patterns: comment that is a near-literal restatement of the next line
|
|
234
|
-
const trivialCommentPatterns = [
|
|
235
|
-
// "// return ..." above a return statement
|
|
236
|
-
{ comment: /\/\/\s*return\b/i, code: /^\s*return\b/ },
|
|
237
|
-
// "// increment ..." or "// increase ..." above x++ or x += 1
|
|
238
|
-
{ comment: /\/\/\s*(increment|increase|add\s+1|plus\s+1)\b/i, code: /\+\+|(\+= ?1)\b/ },
|
|
239
|
-
// "// decrement ..." above x-- or x -= 1
|
|
240
|
-
{ comment: /\/\/\s*(decrement|decrease|subtract\s+1|minus\s+1)\b/i, code: /--|(-= ?1)\b/ },
|
|
241
|
-
// "// log ..." above console.log
|
|
242
|
-
{ comment: /\/\/\s*log\b/i, code: /console\.(log|warn|error)/ },
|
|
243
|
-
// "// set ... to ..." or "// assign ..." above assignment
|
|
244
|
-
{ comment: /\/\/\s*(set|assign)\b/i, code: /^\s*\w[\w.[\]]*\s*=(?!=)/ },
|
|
245
|
-
// "// call ..." above a function call
|
|
246
|
-
{ comment: /\/\/\s*call\b/i, code: /^\s*\w[\w.]*\(/ },
|
|
247
|
-
// "// declare ..." or "// define ..." or "// create ..." above const/let/var
|
|
248
|
-
{ comment: /\/\/\s*(declare|define|create|initialize)\b/i, code: /^\s*(const|let|var)\b/ },
|
|
249
|
-
// "// check if ..." above an if statement
|
|
250
|
-
{ comment: /\/\/\s*check\s+if\b/i, code: /^\s*if\s*\(/ },
|
|
251
|
-
// "// loop ..." or "// iterate ..." above for/while
|
|
252
|
-
{ comment: /\/\/\s*(loop|iterate|for each|foreach)\b/i, code: /^\s*(for|while)\b/ },
|
|
253
|
-
// "// import ..." above an import
|
|
254
|
-
{ comment: /\/\/\s*import\b/i, code: /^\s*import\b/ },
|
|
255
|
-
];
|
|
256
|
-
for (let i = 0; i < lines.length - 1; i++) {
|
|
257
|
-
const commentLine = lines[i].trim();
|
|
258
|
-
const nextLine = lines[i + 1];
|
|
259
|
-
for (const { comment, code } of trivialCommentPatterns) {
|
|
260
|
-
if (comment.test(commentLine) && code.test(nextLine)) {
|
|
261
|
-
if (hasIgnoreComment(file, i + 1))
|
|
262
|
-
continue;
|
|
263
|
-
issues.push({
|
|
264
|
-
rule: 'comment-contradiction',
|
|
265
|
-
severity: 'warning',
|
|
266
|
-
message: `Comment restates what the code already says. AI documents the obvious instead of the why.`,
|
|
267
|
-
line: i + 1,
|
|
268
|
-
column: 1,
|
|
269
|
-
snippet: `${commentLine.slice(0, 60)}\n${nextLine.trim().slice(0, 60)}`,
|
|
270
|
-
});
|
|
271
|
-
break; // one issue per comment line max
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
return issues;
|
|
276
|
-
}
|
|
1
|
+
// drift-ignore-file
|
|
2
|
+
export { detectHighComplexity } from './complexity.js';
|
|
3
|
+
export { detectDeepNesting, detectTooManyParams } from './nesting.js';
|
|
4
|
+
export { detectHighCoupling } from './coupling.js';
|
|
5
|
+
export { detectPromiseStyleMix } from './promise.js';
|
|
6
|
+
export { detectMagicNumbers } from './magic.js';
|
|
7
|
+
export { detectCommentContradiction } from './comments.js';
|
|
277
8
|
//# sourceMappingURL=phase1-complexity.js.map
|
|
@@ -8,10 +8,6 @@ export declare function detectDeadFiles(sourceFiles: SourceFile[], allImportedPa
|
|
|
8
8
|
severity: DriftIssue['severity'];
|
|
9
9
|
weight: number;
|
|
10
10
|
}>): Map<string, DriftIssue>;
|
|
11
|
-
/**
|
|
12
|
-
* Detect named exports that are never imported by any other file.
|
|
13
|
-
* Barrel files (index.*) are excluded since their entire surface is the public API.
|
|
14
|
-
*/
|
|
15
11
|
export declare function detectUnusedExports(sourceFiles: SourceFile[], allImportedNames: Map<string, Set<string>>, ruleWeights: Record<string, {
|
|
16
12
|
severity: DriftIssue['severity'];
|
|
17
13
|
weight: number;
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
// drift-ignore-file
|
|
1
2
|
import * as fs from 'node:fs';
|
|
2
3
|
import * as path from 'node:path';
|
|
4
|
+
const SNIPPET_LENGTH = 80;
|
|
5
|
+
// drift-ignore
|
|
6
|
+
const BIN_DIR = '/bin/';
|
|
3
7
|
/**
|
|
4
8
|
* Detect files that are never imported by any other file in the project.
|
|
5
9
|
* Entry-point files (index, main, cli, app, bin/) are excluded.
|
|
@@ -9,7 +13,7 @@ export function detectDeadFiles(sourceFiles, allImportedPaths, ruleWeights) {
|
|
|
9
13
|
for (const sf of sourceFiles) {
|
|
10
14
|
const sfPath = sf.getFilePath();
|
|
11
15
|
const basename = path.basename(sfPath);
|
|
12
|
-
const isBinFile = sfPath.replace(/\\/g, '/').includes(
|
|
16
|
+
const isBinFile = sfPath.replace(/\\/g, '/').includes(BIN_DIR);
|
|
13
17
|
const isEntryPoint = /^(index|main|cli|app)\.(ts|tsx|js|jsx)$/.test(basename) || isBinFile;
|
|
14
18
|
if (!isEntryPoint && !allImportedPaths.has(sfPath)) {
|
|
15
19
|
issues.set(sfPath, {
|
|
@@ -28,6 +32,49 @@ export function detectDeadFiles(sourceFiles, allImportedPaths, ruleWeights) {
|
|
|
28
32
|
* Detect named exports that are never imported by any other file.
|
|
29
33
|
* Barrel files (index.*) are excluded since their entire surface is the public API.
|
|
30
34
|
*/
|
|
35
|
+
function checkExportDeclarations(sf, sfPath, importedNamesForFile, ruleWeights) {
|
|
36
|
+
const issues = [];
|
|
37
|
+
for (const exportDecl of sf.getExportDeclarations()) {
|
|
38
|
+
for (const namedExport of exportDecl.getNamedExports()) {
|
|
39
|
+
const name = namedExport.getName();
|
|
40
|
+
if (!importedNamesForFile?.has(name)) {
|
|
41
|
+
issues.push({
|
|
42
|
+
rule: 'unused-export',
|
|
43
|
+
severity: ruleWeights['unused-export'].severity,
|
|
44
|
+
message: `'${name}' is exported but never imported`,
|
|
45
|
+
line: namedExport.getStartLineNumber(),
|
|
46
|
+
column: 1,
|
|
47
|
+
snippet: namedExport.getText().slice(0, SNIPPET_LENGTH),
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return issues;
|
|
53
|
+
}
|
|
54
|
+
function checkInlineExports(sf, sfPath, importedNamesForFile, ruleWeights) {
|
|
55
|
+
const issues = [];
|
|
56
|
+
for (const exportSymbol of sf.getExportedDeclarations()) {
|
|
57
|
+
const [exportName, declarations] = [exportSymbol[0], exportSymbol[1]];
|
|
58
|
+
if (exportName === 'default')
|
|
59
|
+
continue;
|
|
60
|
+
if (importedNamesForFile?.has(exportName))
|
|
61
|
+
continue;
|
|
62
|
+
for (const decl of declarations) {
|
|
63
|
+
if (decl.getSourceFile().getFilePath() !== sfPath)
|
|
64
|
+
continue;
|
|
65
|
+
issues.push({
|
|
66
|
+
rule: 'unused-export',
|
|
67
|
+
severity: ruleWeights['unused-export'].severity,
|
|
68
|
+
message: `'${exportName}' is exported but never imported`,
|
|
69
|
+
line: decl.getStartLineNumber(),
|
|
70
|
+
column: 1,
|
|
71
|
+
snippet: decl.getText().split('\n')[0].slice(0, SNIPPET_LENGTH),
|
|
72
|
+
});
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return issues;
|
|
77
|
+
}
|
|
31
78
|
export function detectUnusedExports(sourceFiles, allImportedNames, ruleWeights) {
|
|
32
79
|
const result = new Map();
|
|
33
80
|
for (const sf of sourceFiles) {
|
|
@@ -38,44 +85,10 @@ export function detectUnusedExports(sourceFiles, allImportedNames, ruleWeights)
|
|
|
38
85
|
const hasNamespaceImport = importedNamesForFile?.has('*') ?? false;
|
|
39
86
|
if (isBarrel || hasNamespaceImport)
|
|
40
87
|
continue;
|
|
41
|
-
const issues = [
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (!importedNamesForFile?.has(name)) {
|
|
46
|
-
issues.push({
|
|
47
|
-
rule: 'unused-export',
|
|
48
|
-
severity: ruleWeights['unused-export'].severity,
|
|
49
|
-
message: `'${name}' is exported but never imported`,
|
|
50
|
-
line: namedExport.getStartLineNumber(),
|
|
51
|
-
column: 1,
|
|
52
|
-
snippet: namedExport.getText().slice(0, 80),
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
// Also check inline export declarations (export function foo, export const bar)
|
|
58
|
-
for (const exportSymbol of sf.getExportedDeclarations()) {
|
|
59
|
-
const [exportName, declarations] = [exportSymbol[0], exportSymbol[1]];
|
|
60
|
-
if (exportName === 'default')
|
|
61
|
-
continue;
|
|
62
|
-
if (importedNamesForFile?.has(exportName))
|
|
63
|
-
continue;
|
|
64
|
-
for (const decl of declarations) {
|
|
65
|
-
// Skip if this is a re-export from another file
|
|
66
|
-
if (decl.getSourceFile().getFilePath() !== sfPath)
|
|
67
|
-
continue;
|
|
68
|
-
issues.push({
|
|
69
|
-
rule: 'unused-export',
|
|
70
|
-
severity: ruleWeights['unused-export'].severity,
|
|
71
|
-
message: `'${exportName}' is exported but never imported`,
|
|
72
|
-
line: decl.getStartLineNumber(),
|
|
73
|
-
column: 1,
|
|
74
|
-
snippet: decl.getText().split('\n')[0].slice(0, 80),
|
|
75
|
-
});
|
|
76
|
-
break; // one issue per export name is enough
|
|
77
|
-
}
|
|
78
|
-
}
|
|
88
|
+
const issues = [
|
|
89
|
+
...checkExportDeclarations(sf, sfPath, importedNamesForFile, ruleWeights),
|
|
90
|
+
...checkInlineExports(sf, sfPath, importedNamesForFile, ruleWeights),
|
|
91
|
+
];
|
|
79
92
|
if (issues.length > 0) {
|
|
80
93
|
result.set(sfPath, issues);
|
|
81
94
|
}
|
|
@@ -12,18 +12,10 @@ export declare function detectCircularDependencies(importGraph: Map<string, Set<
|
|
|
12
12
|
severity: DriftIssue['severity'];
|
|
13
13
|
weight: number;
|
|
14
14
|
}>): Map<string, DriftIssue>;
|
|
15
|
-
/**
|
|
16
|
-
* Detect layer violations based on user-defined layer configuration.
|
|
17
|
-
* Returns a map of filePath → issues[].
|
|
18
|
-
*/
|
|
19
15
|
export declare function detectLayerViolations(importGraph: Map<string, Set<string>>, layers: LayerDefinition[], targetPath: string, ruleWeights: Record<string, {
|
|
20
16
|
severity: DriftIssue['severity'];
|
|
21
17
|
weight: number;
|
|
22
18
|
}>): Map<string, DriftIssue[]>;
|
|
23
|
-
/**
|
|
24
|
-
* Detect cross-boundary imports based on user-defined module boundary configuration.
|
|
25
|
-
* Returns a map of filePath → issues[].
|
|
26
|
-
*/
|
|
27
19
|
export declare function detectCrossBoundaryImports(importGraph: Map<string, Set<string>>, modules: ModuleBoundary[], targetPath: string, ruleWeights: Record<string, {
|
|
28
20
|
severity: DriftIssue['severity'];
|
|
29
21
|
weight: number;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// drift-ignore-file
|
|
1
2
|
import * as path from 'node:path';
|
|
2
3
|
/**
|
|
3
4
|
* DFS cycle detection in a directed import graph.
|
|
@@ -66,26 +67,26 @@ export function detectCircularDependencies(importGraph, ruleWeights) {
|
|
|
66
67
|
* Detect layer violations based on user-defined layer configuration.
|
|
67
68
|
* Returns a map of filePath → issues[].
|
|
68
69
|
*/
|
|
70
|
+
function matchLayer(filePath, layers) {
|
|
71
|
+
const rel = filePath.replace(/\\/g, '/');
|
|
72
|
+
return layers.find(layer => layer.patterns.some(pattern => {
|
|
73
|
+
const regexStr = pattern
|
|
74
|
+
.replace(/\\/g, '/')
|
|
75
|
+
.replace(/[.+^${}()|[\]]/g, '\\$&')
|
|
76
|
+
.replace(/\*\*/g, '###DOUBLESTAR###')
|
|
77
|
+
.replace(/\*/g, '[^/]*')
|
|
78
|
+
.replace(/###DOUBLESTAR###/g, '.*');
|
|
79
|
+
return new RegExp(`^${regexStr}`).test(rel);
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
69
82
|
export function detectLayerViolations(importGraph, layers, targetPath, ruleWeights) {
|
|
70
83
|
const result = new Map();
|
|
71
|
-
function getLayer(filePath) {
|
|
72
|
-
const rel = filePath.replace(/\\/g, '/');
|
|
73
|
-
return layers.find(layer => layer.patterns.some(pattern => {
|
|
74
|
-
const regexStr = pattern
|
|
75
|
-
.replace(/\\/g, '/')
|
|
76
|
-
.replace(/[.+^${}()|[\]]/g, '\\$&')
|
|
77
|
-
.replace(/\*\*/g, '###DOUBLESTAR###')
|
|
78
|
-
.replace(/\*/g, '[^/]*')
|
|
79
|
-
.replace(/###DOUBLESTAR###/g, '.*');
|
|
80
|
-
return new RegExp(`^${regexStr}`).test(rel);
|
|
81
|
-
}));
|
|
82
|
-
}
|
|
83
84
|
for (const [filePath, imports] of importGraph.entries()) {
|
|
84
|
-
const fileLayer =
|
|
85
|
+
const fileLayer = matchLayer(filePath, layers);
|
|
85
86
|
if (!fileLayer)
|
|
86
87
|
continue;
|
|
87
88
|
for (const importedPath of imports) {
|
|
88
|
-
const importedLayer =
|
|
89
|
+
const importedLayer = matchLayer(importedPath, layers);
|
|
89
90
|
if (!importedLayer)
|
|
90
91
|
continue;
|
|
91
92
|
if (importedLayer.name === fileLayer.name)
|
|
@@ -110,26 +111,28 @@ export function detectLayerViolations(importGraph, layers, targetPath, ruleWeigh
|
|
|
110
111
|
* Detect cross-boundary imports based on user-defined module boundary configuration.
|
|
111
112
|
* Returns a map of filePath → issues[].
|
|
112
113
|
*/
|
|
114
|
+
function matchModule(filePath, modules) {
|
|
115
|
+
const rel = filePath.replace(/\\/g, '/');
|
|
116
|
+
return modules.find(m => rel.startsWith(m.root.replace(/\\/g, '/')));
|
|
117
|
+
}
|
|
118
|
+
function isAllowedImport(importedPath, allowedImports) {
|
|
119
|
+
const relImported = importedPath.replace(/\\/g, '/');
|
|
120
|
+
return allowedImports.some(allowed => relImported.startsWith(allowed.replace(/\\/g, '/')));
|
|
121
|
+
}
|
|
113
122
|
export function detectCrossBoundaryImports(importGraph, modules, targetPath, ruleWeights) {
|
|
114
123
|
const result = new Map();
|
|
115
|
-
function getModule(filePath) {
|
|
116
|
-
const rel = filePath.replace(/\\/g, '/');
|
|
117
|
-
return modules.find(m => rel.startsWith(m.root.replace(/\\/g, '/')));
|
|
118
|
-
}
|
|
119
124
|
for (const [filePath, imports] of importGraph.entries()) {
|
|
120
|
-
const fileModule =
|
|
125
|
+
const fileModule = matchModule(filePath, modules);
|
|
121
126
|
if (!fileModule)
|
|
122
127
|
continue;
|
|
123
128
|
for (const importedPath of imports) {
|
|
124
|
-
const importedModule =
|
|
129
|
+
const importedModule = matchModule(importedPath, modules);
|
|
125
130
|
if (!importedModule)
|
|
126
131
|
continue;
|
|
127
132
|
if (importedModule.name === fileModule.name)
|
|
128
133
|
continue;
|
|
129
134
|
const allowedImports = fileModule.allowedExternalImports ?? [];
|
|
130
|
-
|
|
131
|
-
const isAllowed = allowedImports.some(allowed => relImported.startsWith(allowed.replace(/\\/g, '/')));
|
|
132
|
-
if (!isAllowed) {
|
|
135
|
+
if (!isAllowedImport(importedPath, allowedImports)) {
|
|
133
136
|
if (!result.has(filePath))
|
|
134
137
|
result.set(filePath, []);
|
|
135
138
|
result.get(filePath).push({
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type SourceFile } from 'ts-morph';
|
|
2
|
+
import type { DriftConfig, DriftIssue } from '../types.js';
|
|
3
|
+
export declare function detectControllerNoDb(file: SourceFile, config?: DriftConfig): DriftIssue[];
|
|
4
|
+
export declare function detectServiceNoHttp(file: SourceFile, config?: DriftConfig): DriftIssue[];
|
|
5
|
+
export declare function detectMaxFunctionLines(file: SourceFile, config?: DriftConfig): DriftIssue[];
|
|
6
|
+
//# sourceMappingURL=phase3-configurable.d.ts.map
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { SyntaxKind } from 'ts-morph';
|
|
2
|
+
const DB_IMPORT_PATTERNS = [
|
|
3
|
+
/\bprisma\b/i,
|
|
4
|
+
/\btypeorm\b/i,
|
|
5
|
+
/\bsequelize\b/i,
|
|
6
|
+
/\bmongoose\b/i,
|
|
7
|
+
/\bknex\b/i,
|
|
8
|
+
/\brepository\b/i,
|
|
9
|
+
/\/db\//i,
|
|
10
|
+
/\/database\//i,
|
|
11
|
+
];
|
|
12
|
+
const HTTP_IMPORT_PATTERNS = [
|
|
13
|
+
/\bexpress\b/i,
|
|
14
|
+
/\bfastify\b/i,
|
|
15
|
+
/\bkoa\b/i,
|
|
16
|
+
/\bhono\b/i,
|
|
17
|
+
/^http$/i,
|
|
18
|
+
/^https$/i,
|
|
19
|
+
];
|
|
20
|
+
function isControllerFile(filePath) {
|
|
21
|
+
const normalized = filePath.replace(/\\/g, '/').toLowerCase();
|
|
22
|
+
return normalized.includes('/controller/') || normalized.includes('/controllers/') || normalized.endsWith('controller.ts') || normalized.endsWith('controller.js');
|
|
23
|
+
}
|
|
24
|
+
function isServiceFile(filePath) {
|
|
25
|
+
const normalized = filePath.replace(/\\/g, '/').toLowerCase();
|
|
26
|
+
return normalized.includes('/service/') || normalized.includes('/services/') || normalized.endsWith('service.ts') || normalized.endsWith('service.js');
|
|
27
|
+
}
|
|
28
|
+
function createIssue(rule, message, line, snippet) {
|
|
29
|
+
return {
|
|
30
|
+
rule,
|
|
31
|
+
severity: 'warning',
|
|
32
|
+
message,
|
|
33
|
+
line,
|
|
34
|
+
column: 1,
|
|
35
|
+
snippet,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export function detectControllerNoDb(file, config) {
|
|
39
|
+
if (!config?.architectureRules?.controllerNoDb)
|
|
40
|
+
return [];
|
|
41
|
+
if (!isControllerFile(file.getFilePath()))
|
|
42
|
+
return [];
|
|
43
|
+
const issues = [];
|
|
44
|
+
for (const decl of file.getImportDeclarations()) {
|
|
45
|
+
const value = decl.getModuleSpecifierValue();
|
|
46
|
+
if (DB_IMPORT_PATTERNS.some((pattern) => pattern.test(value))) {
|
|
47
|
+
issues.push(createIssue('controller-no-db', `Controller imports database module '${value}'. Controllers should delegate persistence through services.`, decl.getStartLineNumber(), value));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return issues;
|
|
51
|
+
}
|
|
52
|
+
export function detectServiceNoHttp(file, config) {
|
|
53
|
+
if (!config?.architectureRules?.serviceNoHttp)
|
|
54
|
+
return [];
|
|
55
|
+
if (!isServiceFile(file.getFilePath()))
|
|
56
|
+
return [];
|
|
57
|
+
const issues = [];
|
|
58
|
+
for (const decl of file.getImportDeclarations()) {
|
|
59
|
+
const value = decl.getModuleSpecifierValue();
|
|
60
|
+
if (HTTP_IMPORT_PATTERNS.some((pattern) => pattern.test(value))) {
|
|
61
|
+
issues.push(createIssue('service-no-http', `Service imports HTTP framework '${value}'. Keep transport concerns outside service layer.`, decl.getStartLineNumber(), value));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
65
|
+
const expressionText = call.getExpression().getText();
|
|
66
|
+
if (/\bfetch\b/.test(expressionText)) {
|
|
67
|
+
issues.push(createIssue('service-no-http', 'Service executes HTTP call directly (fetch). Move this to an adapter/client.', call.getStartLineNumber(), expressionText));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return issues;
|
|
71
|
+
}
|
|
72
|
+
export function detectMaxFunctionLines(file, config) {
|
|
73
|
+
const maxLines = config?.architectureRules?.maxFunctionLines;
|
|
74
|
+
if (!maxLines || maxLines <= 0)
|
|
75
|
+
return [];
|
|
76
|
+
const issues = [];
|
|
77
|
+
for (const fn of file.getFunctions()) {
|
|
78
|
+
const body = fn.getBody();
|
|
79
|
+
if (!body)
|
|
80
|
+
continue;
|
|
81
|
+
const lines = body.getEndLineNumber() - body.getStartLineNumber() - 1;
|
|
82
|
+
if (lines > maxLines) {
|
|
83
|
+
issues.push(createIssue('max-function-lines', `Function '${fn.getName() ?? '(anonymous)'}' has ${lines} lines (max: ${maxLines}).`, fn.getStartLineNumber(), fn.getName() ?? '(anonymous)'));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const method of file.getDescendantsOfKind(SyntaxKind.MethodDeclaration)) {
|
|
87
|
+
const body = method.getBody();
|
|
88
|
+
if (!body)
|
|
89
|
+
continue;
|
|
90
|
+
const lines = body.getEndLineNumber() - body.getStartLineNumber() - 1;
|
|
91
|
+
if (lines > maxLines) {
|
|
92
|
+
issues.push(createIssue('max-function-lines', `Method '${method.getName()}' has ${lines} lines (max: ${maxLines}).`, method.getStartLineNumber(), method.getName()));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return issues;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=phase3-configurable.js.map
|
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
import { SourceFile, FunctionDeclaration, ArrowFunction, FunctionExpression, MethodDeclaration } from 'ts-morph';
|
|
2
2
|
import type { DriftIssue } from '../types.js';
|
|
3
3
|
export type FunctionLikeNode = FunctionDeclaration | ArrowFunction | FunctionExpression | MethodDeclaration;
|
|
4
|
-
/** Normalize a function body to a canonical string (Type-2 clone detection).
|
|
5
|
-
* Variable names, parameter names, and numeric/string literals are replaced
|
|
6
|
-
* with canonical tokens so that two functions with identical logic but
|
|
7
|
-
* different identifiers produce the same fingerprint.
|
|
8
|
-
*/
|
|
9
4
|
export declare function normalizeFunctionBody(fn: FunctionLikeNode): string;
|
|
10
5
|
/** Return a SHA-256 fingerprint for a function body (normalized). */
|
|
11
6
|
export declare function fingerprintFunction(fn: FunctionLikeNode): string;
|