crap-ts 0.1.1 → 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/src/cli.js CHANGED
@@ -6,7 +6,6 @@ import { fileURLToPath } from "node:url";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
8
  import { runCrapAudit } from "./crap-runner.js";
9
- import { buildCrapScores } from "./crap-score.js";
10
9
 
11
10
  const helpText = `crap-ts
12
11
 
@@ -14,24 +13,21 @@ Run a focused TypeScript quality audit.
14
13
 
15
14
  Usage:
16
15
  crap-ts score [--coverage-file coverage/unit/coverage-final.json] [--coverage-command "npm run test:coverage"]
17
- crap-ts score --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json [--max-crap 30]
18
-
19
- Legacy:
20
- crap-ts --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json
21
16
 
22
17
  Options:
23
18
  --config <path> Config file path. Defaults to .crap-ts.json when present.
24
19
  --coverage-file <path>
25
- Istanbul coverage JSON path.
20
+ Istanbul coverage-final.json path. Repeat to merge several runs.
26
21
  --coverage-command <cmd>
27
22
  Command to generate coverage before scoring.
28
23
  --all Print every analyzed function instead of applying --limit.
29
- --include <text> Only analyze coverage files whose path contains this text.
30
- --limit <n> Number of rows to print for direct CRAP audit. Defaults to 20.
31
- --metrics <path> JSON file with [{ "file", "name", "complexity" }] entries.
24
+ --include <text> Only analyze source files whose path contains this text.
25
+ --exclude <text> Skip source files whose path contains this text.
26
+ --json Print the full JSON report (schema version 1) instead of text.
27
+ --limit <n> Number of rows to print in the text report. Defaults to 20.
32
28
  --min-lines <n> Ignore functions shorter than this. Defaults to 10.
33
- --max <n> Fail direct CRAP audit when any row is above this score. Defaults to 30.
34
- --max-crap <n> Fail CRAP scoring when any row is above this score.
29
+ --max <n> Fail when any function's CRAP score is above this. Defaults to 30.
30
+ --warn <n> Warn, without failing, when any row is above this score.
35
31
  --report-only Print CRAP report without failing on threshold.
36
32
  --skip-coverage Do not run the coverage command.
37
33
  --help Show this help.
@@ -40,29 +36,27 @@ Options:
40
36
  const defaultConfigPath = ".crap-ts.json";
41
37
 
42
38
  export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
43
- const command = getCommand(argv);
44
- const args = command === "legacy" ? argv : argv.slice(1);
45
- const { positionals, values } = parseArgs({
39
+ const [command, ...args] = argv;
40
+ const { values } = parseArgs({
46
41
  args,
47
- allowPositionals: true,
48
42
  options: {
49
43
  all: { type: "boolean" },
50
44
  config: { type: "string" },
51
- "coverage-file": { type: "string" },
45
+ "coverage-file": { type: "string", multiple: true },
52
46
  "coverage-command": { type: "string" },
47
+ exclude: { type: "string", multiple: true },
53
48
  help: { type: "boolean", short: "h" },
54
49
  include: { type: "string", multiple: true },
50
+ json: { type: "boolean" },
55
51
  limit: { type: "string" },
56
52
  max: { type: "string" },
57
- "max-crap": { type: "string" },
58
- metrics: { type: "string" },
59
53
  "min-lines": { type: "string" },
60
54
  "report-only": { type: "boolean" },
61
55
  "skip-coverage": { type: "boolean" },
56
+ warn: { type: "string" },
62
57
  },
63
58
  });
64
- const config =
65
- command === "help" || values.help ? {} : readConfig(values.config, cwd);
59
+ const config = values.help ? {} : readConfig(values.config, cwd);
66
60
 
67
61
  return applyDefaults(
68
62
  mergeConfigWithCli(config, {
@@ -70,87 +64,56 @@ export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
70
64
  all: values.all,
71
65
  configPath: values.config,
72
66
  coverageCommand: values["coverage-command"],
73
- coveragePath: values["coverage-file"],
67
+ coveragePaths: values["coverage-file"],
68
+ excludes: values.exclude,
74
69
  help: values.help,
75
70
  includes: values.include,
71
+ json: values.json,
76
72
  limit: parseOptionalNumber(values.limit, "--limit"),
77
- maxCrap: parseOptionalNumber(values["max-crap"], "--max-crap"),
78
73
  maxScore: parseOptionalNumber(values.max, "--max"),
79
- metricsPath: values.metrics,
80
74
  minLines: parseOptionalNumber(values["min-lines"], "--min-lines"),
81
- paths: positionals,
82
75
  reportOnly: values["report-only"],
83
76
  skipCoverage: values["skip-coverage"],
77
+ warnScore: parseOptionalNumber(values.warn, "--warn"),
84
78
  }),
85
79
  );
86
80
  }
87
81
 
88
82
  export async function main(argv = process.argv.slice(2)) {
89
- const options = parseCliArgs(argv);
83
+ const [command] = argv;
90
84
 
91
- if (options.help || options.command === "help") {
85
+ if (!command || ["help", "--help", "-h"].includes(command)) {
92
86
  console.log(helpText);
93
87
  return 0;
94
88
  }
95
89
 
96
- if (
97
- options.command === "score" ||
98
- options.metricsPath ||
99
- options.coveragePath
100
- ) {
101
- return runScore(options);
102
- }
103
-
104
- if (options.command !== "legacy") {
105
- console.error(`Unknown command: ${options.command}`);
90
+ if (command !== "score") {
91
+ console.error(
92
+ `Unknown command: ${command}. Run \`crap-ts score\`; see \`crap-ts --help\`.`,
93
+ );
106
94
  return 2;
107
95
  }
108
96
 
109
- console.error(
110
- "Usage error: run `crap-ts score --help` for supported commands.",
111
- );
112
- return 2;
113
- }
114
-
115
- async function runScore(options) {
116
- if (!options.metricsPath) {
117
- return runCrapAudit(options);
118
- }
97
+ let options;
119
98
 
120
- if (!options.coveragePath) {
121
- console.error("CRAP scoring requires both --metrics and --coverage-file.");
99
+ try {
100
+ options = parseCliArgs(argv);
101
+ } catch (error) {
102
+ console.error(`Usage error: ${error.message}`);
122
103
  return 2;
123
104
  }
124
105
 
125
- const metrics = JSON.parse(readFileSync(options.metricsPath, "utf8"));
126
- const coverageSummary = JSON.parse(
127
- readFileSync(options.coveragePath, "utf8"),
128
- );
129
- const scores = buildCrapScores({ coverageSummary, metrics });
130
- const failingScores = options.maxCrap
131
- ? scores.filter((score) => score.crap > options.maxCrap)
132
- : [];
133
-
134
- console.log(JSON.stringify(scores, null, 2));
135
-
136
- if (failingScores.length > 0) {
137
- console.error(
138
- `CRAP threshold failed: ${failingScores.length} row(s) exceeded ${options.maxCrap}.`,
139
- );
140
- return 1;
106
+ if (options.help) {
107
+ console.log(helpText);
108
+ return 0;
141
109
  }
142
110
 
143
- return 0;
144
- }
145
-
146
- function getCommand(argv) {
147
- const firstArg = argv[0];
148
-
149
- if (firstArg === "score" || firstArg === "help") {
150
- return firstArg;
111
+ try {
112
+ return await runCrapAudit(options);
113
+ } catch (error) {
114
+ console.error(`Error: ${error.message}`);
115
+ return 1;
151
116
  }
152
-
153
- return "legacy";
154
117
  }
155
118
 
156
119
  function parseOptionalNumber(value, label) {
@@ -193,19 +156,55 @@ function mergeConfigWithCli(config, cliOptions) {
193
156
  };
194
157
  }
195
158
 
159
+ const configKeys = new Set([
160
+ "all",
161
+ "coverageCommand",
162
+ "coverageFile",
163
+ "exclude",
164
+ "include",
165
+ "json",
166
+ "limit",
167
+ "max",
168
+ "minLines",
169
+ "reportOnly",
170
+ "skipCoverage",
171
+ "warn",
172
+ ]);
173
+
196
174
  function normalizeConfig(config) {
175
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
176
+ throw new TypeError(`${defaultConfigPath} must contain a JSON object.`);
177
+ }
178
+
179
+ const unknownKeys = Object.keys(config).filter((key) => !configKeys.has(key));
180
+
181
+ if (unknownKeys.length > 0) {
182
+ throw new TypeError(
183
+ `Unknown ${defaultConfigPath} key(s): ${unknownKeys.join(", ")}.`,
184
+ );
185
+ }
186
+
197
187
  return stripUndefined({
198
- all: config.all,
199
- coverageCommand: config.coverageCommand,
200
- coveragePath: config.coverageFile,
188
+ all: parseConfigType(config.all, "all", "boolean"),
189
+ coverageCommand: parseConfigType(
190
+ config.coverageCommand,
191
+ "coverageCommand",
192
+ "string",
193
+ ),
194
+ coveragePaths: normalizeConfigList(config.coverageFile, "coverageFile"),
195
+ excludes: normalizeConfigList(config.exclude, "exclude"),
201
196
  includes: normalizeConfigList(config.include, "include"),
197
+ json: parseConfigType(config.json, "json", "boolean"),
202
198
  limit: parseConfigNumber(config.limit, "limit"),
203
- maxCrap: parseConfigNumber(config.maxCrap, "maxCrap"),
204
199
  maxScore: parseConfigNumber(config.max, "max"),
205
- metricsPath: config.metrics,
206
200
  minLines: parseConfigNumber(config.minLines, "minLines"),
207
- reportOnly: config.reportOnly,
208
- skipCoverage: config.skipCoverage,
201
+ reportOnly: parseConfigType(config.reportOnly, "reportOnly", "boolean"),
202
+ skipCoverage: parseConfigType(
203
+ config.skipCoverage,
204
+ "skipCoverage",
205
+ "boolean",
206
+ ),
207
+ warnScore: parseConfigNumber(config.warn, "warn"),
209
208
  });
210
209
  }
211
210
 
@@ -223,6 +222,14 @@ function parseConfigNumber(value, label) {
223
222
  return value;
224
223
  }
225
224
 
225
+ function parseConfigType(value, label, type) {
226
+ if (value !== undefined && typeof value !== type) {
227
+ throw new TypeError(`${label} must be a ${type} in ${defaultConfigPath}.`);
228
+ }
229
+
230
+ return value;
231
+ }
232
+
226
233
  function normalizeConfigList(value, label) {
227
234
  if (value === undefined) {
228
235
  return undefined;
@@ -246,7 +253,9 @@ function applyDefaults(options) {
246
253
  ...options,
247
254
  all: options.all ?? false,
248
255
  help: options.help ?? false,
256
+ excludes: options.excludes ?? [],
249
257
  includes: options.includes ?? [],
258
+ json: options.json ?? false,
250
259
  reportOnly: options.reportOnly ?? false,
251
260
  skipCoverage: options.skipCoverage ?? false,
252
261
  };
@@ -1,33 +1,54 @@
1
+ interface SourcePosition {
2
+ line: number;
3
+ column: number;
4
+ }
5
+
6
+ interface SourceRange {
7
+ start: SourcePosition;
8
+ end: { line: number; column: number | null };
9
+ }
10
+
11
+ /** One file's entry from an Istanbul `coverage-final.json`. Branch data is ignored. */
12
+ export interface FileCoverage {
13
+ statementMap: Record<string, SourceRange>;
14
+ s: Record<string, number>;
15
+ fnMap: Record<string, { loc: SourceRange }>;
16
+ f: Record<string, number>;
17
+ }
18
+
1
19
  export interface FunctionRisk {
2
- complexity: number;
3
- coveragePercent: number;
4
- crapScore: number;
5
- endLine: number;
6
20
  filePath: string;
7
- lineCount: number;
8
21
  name: string;
22
+ /** One-based line of the function's first token. */
9
23
  startLine: number;
10
- }
11
-
12
- export interface CoverageFunction {
13
- coveragePercent: number;
14
- declarationLine: number;
24
+ /** One-based column of the function's first token. */
25
+ startColumn: number;
15
26
  endLine: number;
16
- startLine: number;
27
+ lineCount: number;
28
+ complexity: number;
29
+ /** Percentage in [0, 100]. */
30
+ coveragePercent: number;
31
+ /** Statements whose start lies in this function and not in a nested one. */
32
+ statements: number;
33
+ coveredStatements: number;
34
+ /** `statements`: owned statement counters; `function`: the function's own counter (no owned statements); `ignored`: no counter, under a coverage ignore comment; `missing`: no counter and no ignore comment (no coverage entry, or added after the coverage run). */
35
+ evidence: "statements" | "function" | "ignored" | "missing";
36
+ crapScore: number;
17
37
  }
18
38
 
19
- export function extractCoverageFunctions(
20
- coverageJson: Record<string, unknown>,
21
- ): Map<string, CoverageFunction[]>;
22
-
39
+ /**
40
+ * Score every function with a body in one source file.
41
+ * A function without counters (or without `coverage`) reports 0% coverage and
42
+ * `evidence: "missing"`, or `"ignored"` when a coverage ignore comment covers it.
43
+ */
23
44
  export function analyzeFileRisk(input: {
24
- coverageFunctions: CoverageFunction[];
45
+ coverage?: FileCoverage;
25
46
  filePath: string;
26
- minLines: number;
47
+ /** Drop functions shorter than this many lines. Defaults to 1. */
48
+ minLines?: number;
27
49
  sourceFilePath?: string;
28
50
  sourceText: string;
29
51
  }): Promise<FunctionRisk[]>;
30
52
 
31
- export function formatRiskLine(risk: FunctionRisk): string;
32
-
53
+ /** 1 plus one per decision point in `node`, excluding nested functions. */
33
54
  export function calculateCyclomaticComplexity(node: unknown): number;