crap-ts 0.1.0 → 0.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.
@@ -1,173 +1,305 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, join } from "node:path";
4
+
1
5
  import ts from "typescript";
2
6
 
3
7
  import { calculateCrapScoreFromPercent } from "./crap-score.js";
4
8
 
5
9
  export function extractCoverageFunctions(coverageJson) {
6
- const coverageByFile = new Map();
7
-
8
- for (const [filePath, coverage] of Object.entries(coverageJson)) {
9
- const functions = Object.entries(coverage.fnMap ?? {}).flatMap(([id, metadata]) => {
10
- const startLine = metadata.loc?.start?.line;
11
- const endLine = metadata.loc?.end?.line;
12
-
13
- if (!startLine || !endLine) {
14
- return [];
15
- }
16
-
17
- return [
18
- {
19
- coveragePercent: (coverage.f?.[id] ?? 0) > 0 ? 100 : 0,
20
- declarationLine: metadata.line ?? startLine,
21
- endLine,
22
- startLine,
23
- },
24
- ];
25
- });
26
-
27
- coverageByFile.set(filePath, functions);
28
- }
29
-
30
- return coverageByFile;
10
+ const coverageByFile = new Map();
11
+
12
+ for (const [filePath, coverage] of Object.entries(coverageJson)) {
13
+ const functions = Object.entries(coverage.fnMap ?? {}).flatMap(
14
+ ([id, metadata]) => {
15
+ const startLine = metadata.loc?.start?.line;
16
+ const endLine = metadata.loc?.end?.line;
17
+
18
+ if (!startLine || !endLine) {
19
+ return [];
20
+ }
21
+
22
+ return [
23
+ {
24
+ coveragePercent: (coverage.f?.[id] ?? 0) > 0 ? 100 : 0,
25
+ declarationLine: metadata.line ?? startLine,
26
+ endLine,
27
+ startLine,
28
+ },
29
+ ];
30
+ },
31
+ );
32
+
33
+ coverageByFile.set(filePath, functions);
34
+ }
35
+
36
+ return coverageByFile;
31
37
  }
32
38
 
33
- export function analyzeFileRisk({ coverageFunctions, filePath, minLines, sourceText }) {
34
- const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true);
35
- const risks = [];
36
-
37
- function visit(node) {
38
- if (isFunctionLikeNode(node) && node.body) {
39
- const startLine =
40
- sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
41
- const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
42
- const lineCount = endLine - startLine + 1;
43
-
44
- if (lineCount >= minLines) {
45
- const complexity = calculateCyclomaticComplexity(node.body);
46
- const coveragePercent = getFunctionCoveragePercent({
47
- coverageFunctions,
48
- endLine,
49
- startLine,
50
- });
51
-
52
- risks.push({
53
- complexity,
54
- coveragePercent,
55
- crapScore: calculateCrapScoreFromPercent(complexity, coveragePercent),
56
- endLine,
57
- filePath,
58
- lineCount,
59
- name: getFunctionName(node, sourceFile),
60
- startLine,
61
- });
62
- }
63
- }
64
-
65
- ts.forEachChild(node, visit);
66
- }
67
-
68
- visit(sourceFile);
69
-
70
- return risks;
39
+ export async function analyzeFileRisk({
40
+ coverageFunctions,
41
+ filePath,
42
+ minLines,
43
+ sourceFilePath,
44
+ sourceText,
45
+ }) {
46
+ const adapter = await getTypescriptAdapter({
47
+ filePath,
48
+ sourceFilePath,
49
+ sourceText,
50
+ });
51
+ const { sourceFile } = adapter;
52
+ const risks = [];
53
+
54
+ function visit(node) {
55
+ if (isFunctionLikeNode(adapter, node) && node.body) {
56
+ const startLine =
57
+ sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
58
+ .line + 1;
59
+ const endLine =
60
+ sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
61
+ const lineCount = endLine - startLine + 1;
62
+
63
+ if (lineCount >= minLines) {
64
+ const complexity = calculateCyclomaticComplexity(node.body, adapter);
65
+ const coveragePercent = getFunctionCoveragePercent({
66
+ coverageFunctions,
67
+ endLine,
68
+ startLine,
69
+ });
70
+
71
+ risks.push({
72
+ complexity,
73
+ coveragePercent,
74
+ crapScore: calculateCrapScoreFromPercent(complexity, coveragePercent),
75
+ endLine,
76
+ filePath,
77
+ lineCount,
78
+ name: getFunctionName(adapter, node, sourceFile),
79
+ startLine,
80
+ });
81
+ }
82
+ }
83
+
84
+ adapter.forEachChild(node, visit);
85
+ }
86
+
87
+ visit(sourceFile);
88
+
89
+ return risks;
71
90
  }
72
91
 
73
92
  export function formatRiskLine(risk) {
74
- return [
75
- `${risk.filePath}:${risk.startLine}`,
76
- risk.name,
77
- `CRAP ${risk.crapScore.toFixed(1)}`,
78
- `complexity ${risk.complexity}`,
79
- `coverage ${risk.coveragePercent.toFixed(0)}%`,
80
- `${risk.lineCount} lines`,
81
- ].join(" | ");
93
+ return [
94
+ `${risk.filePath}:${risk.startLine}`,
95
+ risk.name,
96
+ `CRAP ${risk.crapScore.toFixed(1)}`,
97
+ `complexity ${risk.complexity}`,
98
+ `coverage ${risk.coveragePercent.toFixed(0)}%`,
99
+ `${risk.lineCount} lines`,
100
+ ].join(" | ");
82
101
  }
83
102
 
84
- export function calculateCyclomaticComplexity(node) {
85
- let complexity = 1;
103
+ export function calculateCyclomaticComplexity(
104
+ node,
105
+ adapter = getDefaultComplexityAdapter(),
106
+ ) {
107
+ let complexity = 1;
86
108
 
87
- function visit(child) {
88
- if (addsDecisionPath(child)) {
89
- complexity += 1;
90
- }
109
+ function visit(child) {
110
+ if (addsDecisionPath(adapter, child)) {
111
+ complexity += 1;
112
+ }
91
113
 
92
- ts.forEachChild(child, visit);
93
- }
114
+ adapter.forEachChild(child, visit);
115
+ }
94
116
 
95
- visit(node);
117
+ visit(node);
96
118
 
97
- return complexity;
119
+ return complexity;
98
120
  }
99
121
 
100
- function addsDecisionPath(node) {
101
- if (
102
- ts.isIfStatement(node) ||
103
- ts.isForStatement(node) ||
104
- ts.isForInStatement(node) ||
105
- ts.isForOfStatement(node) ||
106
- ts.isWhileStatement(node) ||
107
- ts.isDoStatement(node) ||
108
- ts.isCaseClause(node) ||
109
- ts.isCatchClause(node) ||
110
- ts.isConditionalExpression(node)
111
- ) {
112
- return true;
113
- }
114
-
115
- return (
116
- ts.isBinaryExpression(node) &&
117
- (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
118
- node.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
119
- node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)
120
- );
122
+ function addsDecisionPath(adapter, node) {
123
+ if (
124
+ adapter.isIfStatement(node) ||
125
+ adapter.isForStatement(node) ||
126
+ adapter.isForInStatement(node) ||
127
+ adapter.isForOfStatement(node) ||
128
+ adapter.isWhileStatement(node) ||
129
+ adapter.isDoStatement(node) ||
130
+ adapter.isCaseClause(node) ||
131
+ adapter.isCatchClause(node) ||
132
+ adapter.isConditionalExpression(node)
133
+ ) {
134
+ return true;
135
+ }
136
+
137
+ return (
138
+ adapter.isBinaryExpression(node) &&
139
+ (node.operatorToken.kind === adapter.SyntaxKind.AmpersandAmpersandToken ||
140
+ node.operatorToken.kind === adapter.SyntaxKind.BarBarToken ||
141
+ node.operatorToken.kind === adapter.SyntaxKind.QuestionQuestionToken)
142
+ );
121
143
  }
122
144
 
123
145
  function getFunctionCoveragePercent({ coverageFunctions, endLine, startLine }) {
124
- const exactMatch = coverageFunctions.find(
125
- (coverageFunction) =>
126
- coverageFunction.declarationLine === startLine ||
127
- (coverageFunction.startLine === startLine && coverageFunction.endLine === endLine),
128
- );
129
-
130
- if (exactMatch) {
131
- return exactMatch.coveragePercent;
132
- }
133
-
134
- const containingMatch = coverageFunctions.find(
135
- (coverageFunction) =>
136
- (coverageFunction.declarationLine >= startLine &&
137
- coverageFunction.declarationLine <= endLine) ||
138
- (coverageFunction.startLine <= endLine && coverageFunction.endLine >= startLine),
139
- );
140
-
141
- return containingMatch?.coveragePercent ?? 0;
146
+ const exactMatch = coverageFunctions.find(
147
+ (coverageFunction) =>
148
+ coverageFunction.declarationLine === startLine ||
149
+ (coverageFunction.startLine === startLine &&
150
+ coverageFunction.endLine === endLine),
151
+ );
152
+
153
+ if (exactMatch) {
154
+ return exactMatch.coveragePercent;
155
+ }
156
+
157
+ const containingMatch = coverageFunctions.find(
158
+ (coverageFunction) =>
159
+ (coverageFunction.declarationLine >= startLine &&
160
+ coverageFunction.declarationLine <= endLine) ||
161
+ (coverageFunction.startLine <= endLine &&
162
+ coverageFunction.endLine >= startLine),
163
+ );
164
+
165
+ return containingMatch?.coveragePercent ?? 0;
166
+ }
167
+
168
+ function getFunctionName(adapter, node, sourceFile) {
169
+ if (
170
+ (adapter.isFunctionDeclaration(node) ||
171
+ adapter.isFunctionExpression(node)) &&
172
+ node.name
173
+ ) {
174
+ return node.name.getText(sourceFile);
175
+ }
176
+
177
+ if (adapter.isMethodDeclaration(node) && node.name) {
178
+ return node.name.getText(sourceFile);
179
+ }
180
+
181
+ const parent = node.parent;
182
+
183
+ if (adapter.isVariableDeclaration(parent) && parent.name) {
184
+ return parent.name.getText(sourceFile);
185
+ }
186
+
187
+ if (adapter.isPropertyAssignment(parent) && parent.name) {
188
+ return parent.name.getText(sourceFile);
189
+ }
190
+
191
+ return "<anonymous>";
142
192
  }
143
193
 
144
- function getFunctionName(node, sourceFile) {
145
- if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name) {
146
- return node.name.getText(sourceFile);
147
- }
194
+ function isFunctionLikeNode(adapter, node) {
195
+ return (
196
+ adapter.isFunctionDeclaration(node) ||
197
+ adapter.isFunctionExpression(node) ||
198
+ adapter.isArrowFunction(node) ||
199
+ adapter.isMethodDeclaration(node)
200
+ );
201
+ }
148
202
 
149
- if (ts.isMethodDeclaration(node) && node.name) {
150
- return node.name.getText(sourceFile);
151
- }
203
+ function getTs5Adapter() {
204
+ return {
205
+ ...ts,
206
+ forEachChild: ts.forEachChild,
207
+ };
208
+ }
152
209
 
153
- const parent = node.parent;
210
+ function getDefaultComplexityAdapter() {
211
+ if (ts.createSourceFile) {
212
+ return getTs5Adapter();
213
+ }
154
214
 
155
- if (ts.isVariableDeclaration(parent) && parent.name) {
156
- return parent.name.getText(sourceFile);
157
- }
215
+ return getTs7NodeAdapter();
216
+ }
158
217
 
159
- if (ts.isPropertyAssignment(parent) && parent.name) {
160
- return parent.name.getText(sourceFile);
161
- }
218
+ function getTs7NodeAdapter() {
219
+ return {
220
+ SyntaxKind: ts7SyntaxKind,
221
+ forEachChild(node, visitor) {
222
+ node.forEachChild?.(visitor);
223
+ },
224
+ isBinaryExpression: isSyntaxKind(ts7SyntaxKind.BinaryExpression),
225
+ isCaseClause: isSyntaxKind(ts7SyntaxKind.CaseClause),
226
+ isCatchClause: isSyntaxKind(ts7SyntaxKind.CatchClause),
227
+ isConditionalExpression: isSyntaxKind(ts7SyntaxKind.ConditionalExpression),
228
+ isDoStatement: isSyntaxKind(ts7SyntaxKind.DoStatement),
229
+ isForInStatement: isSyntaxKind(ts7SyntaxKind.ForInStatement),
230
+ isForOfStatement: isSyntaxKind(ts7SyntaxKind.ForOfStatement),
231
+ isForStatement: isSyntaxKind(ts7SyntaxKind.ForStatement),
232
+ isIfStatement: isSyntaxKind(ts7SyntaxKind.IfStatement),
233
+ isWhileStatement: isSyntaxKind(ts7SyntaxKind.WhileStatement),
234
+ };
235
+ }
162
236
 
163
- return "<anonymous>";
237
+ function isSyntaxKind(kind) {
238
+ return (node) => node?.kind === kind;
164
239
  }
165
240
 
166
- function isFunctionLikeNode(node) {
167
- return (
168
- ts.isFunctionDeclaration(node) ||
169
- ts.isFunctionExpression(node) ||
170
- ts.isArrowFunction(node) ||
171
- ts.isMethodDeclaration(node)
172
- );
241
+ const ts7SyntaxKind = {
242
+ AmpersandAmpersandToken: 55,
243
+ BarBarToken: 56,
244
+ BinaryExpression: 227,
245
+ CaseClause: 297,
246
+ CatchClause: 300,
247
+ ConditionalExpression: 228,
248
+ DoStatement: 247,
249
+ ForInStatement: 250,
250
+ ForOfStatement: 251,
251
+ ForStatement: 249,
252
+ IfStatement: 246,
253
+ QuestionQuestionToken: 60,
254
+ WhileStatement: 248,
255
+ };
256
+
257
+ async function getTypescriptAdapter({ filePath, sourceFilePath, sourceText }) {
258
+ if (ts.createSourceFile) {
259
+ return {
260
+ ...getTs5Adapter(),
261
+ sourceFile: ts.createSourceFile(
262
+ filePath,
263
+ sourceText,
264
+ ts.ScriptTarget.Latest,
265
+ true,
266
+ ),
267
+ };
268
+ }
269
+
270
+ const [{ API }, ast] = await Promise.all([
271
+ import("typescript/unstable/sync"),
272
+ import("typescript/unstable/ast"),
273
+ ]);
274
+ const temporaryDirectory = mkdtempSync(join(tmpdir(), "crap-ts-"));
275
+ const resolvedPath = join(
276
+ temporaryDirectory,
277
+ basename(sourceFilePath ?? filePath),
278
+ );
279
+
280
+ writeFileSync(resolvedPath, sourceText);
281
+
282
+ const api = new API();
283
+
284
+ try {
285
+ const snapshot = api.updateSnapshot({ openFiles: [resolvedPath] });
286
+ const project = snapshot.getDefaultProjectForFile(resolvedPath);
287
+ const sourceFile = project?.program.getSourceFile(resolvedPath);
288
+
289
+ if (!sourceFile) {
290
+ throw new Error(`Unable to parse TypeScript source file: ${filePath}`);
291
+ }
292
+
293
+ return {
294
+ ...ast,
295
+ forEachChild(node, visitor) {
296
+ ast.visitEachChild(node, visitor, null);
297
+ },
298
+ sourceFile,
299
+ };
300
+ } finally {
301
+ api.close();
302
+
303
+ rmSync(temporaryDirectory, { force: true, recursive: true });
304
+ }
173
305
  }
@@ -1,14 +1,16 @@
1
1
  export interface CrapAuditOptions {
2
- all?: boolean;
3
- coverageCommand?: string;
4
- coveragePath?: string;
5
- cwd?: string;
6
- includes?: string[];
7
- limit?: number;
8
- maxScore?: number;
9
- minLines?: number;
10
- reportOnly?: boolean;
11
- skipCoverage?: boolean;
2
+ all?: boolean;
3
+ coverageCommand?: string;
4
+ coveragePath?: string;
5
+ cwd?: string;
6
+ includes?: string[];
7
+ limit?: number;
8
+ maxScore?: number;
9
+ minLines?: number;
10
+ reportOnly?: boolean;
11
+ skipCoverage?: boolean;
12
+ /** Report, without failing, functions whose CRAP score is above this and at or below `maxScore`. */
13
+ warnScore?: number;
12
14
  }
13
15
 
14
- export function runCrapAudit(options?: CrapAuditOptions): number;
16
+ export function runCrapAudit(options?: CrapAuditOptions): Promise<number>;