@blundergoat/gruff-ts 0.3.2 → 0.5.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/CHANGELOG.md +54 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +15 -3
- package/docs/configuration.md +47 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +36 -0
- package/docs/rules.md +52 -37
- package/package.json +1 -1
- package/src/analyser.ts +540 -154
- package/src/baseline-options.ts +90 -0
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +80 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +65 -15
- package/src/cli.ts +4 -2
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/dead-code-rules.ts +10 -3
- package/src/discovery.ts +66 -22
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +120 -27
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +175 -19
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +163 -0
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +36 -18
- package/src/project-rules.ts +159 -42
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +58 -4
- package/src/rules.ts +15 -15
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +256 -80
- package/src/source-text.ts +9 -26
- package/src/static-analysis-redundant-rules.ts +46 -2
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +17 -0
package/src/analyser.ts
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
// Analyser pipeline: walks discovered sources, runs every rule pass (complexity, dead-code, design,
|
|
2
2
|
// documentation, maintainability, modernisation, naming, security, sensitive-data, size, test-quality),
|
|
3
3
|
// aggregates findings into the `gruff.analysis.v2` schema, and exposes `analyse` to the CLI shell.
|
|
4
|
-
import {
|
|
4
|
+
import { Buffer, isUtf8 } from "node:buffer";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
5
6
|
import { cwd } from "node:process";
|
|
6
|
-
import { basename,
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
7
|
+
import { basename, extname } from "node:path";
|
|
8
|
+
import { recordHistory, sortedUniqueFindings } from "./baseline.ts";
|
|
9
|
+
import { applyBaselineOptions, type BaselineApplication } from "./baseline-options.ts";
|
|
10
|
+
import { changedRegionScope, filterChangedFindings, filterScopedDiagnostics } from "./changed-regions.ts";
|
|
9
11
|
import { loadConfig, optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
|
|
10
12
|
import { VERSION } from "./constants.ts";
|
|
11
13
|
import { absolutize, discoverSources, displayPath, type SourceFile } from "./discovery.ts";
|
|
12
14
|
import { makeFinding } from "./findings.ts";
|
|
13
|
-
import { finding } from "./findings-helpers.ts";
|
|
14
|
-
import { commentRecords } from "./comment-scanner.ts";
|
|
15
|
-
import { analyseArchitectureRules, buildProjectIndex, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
|
|
16
|
-
import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks
|
|
15
|
+
import { applyConfiguredSeverity, finding, parameterNames } from "./findings-helpers.ts";
|
|
16
|
+
import { commentRecords, type CommentRecord } from "./comment-scanner.ts";
|
|
17
|
+
import { analyseArchitectureRules, analyseCircularImportRule, buildProjectIndex, CIRCULAR_IMPORT_RULE_ID, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
|
|
18
|
+
import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks } from "./blocks.ts";
|
|
17
19
|
import { analyseClassRules, analyseAcronymCase, analyseInconsistentCasing, analyseInterfaceFields, collectDeclaredIdentifiers } from "./class-rules.ts";
|
|
18
20
|
import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
|
|
19
21
|
import { analyseCommentQualityRules } from "./comment-rules.ts";
|
|
@@ -24,10 +26,21 @@ import { pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pu
|
|
|
24
26
|
import { analyseTestBlock } from "./test-block-rules.ts";
|
|
25
27
|
import { analyseGithubActionsRules } from "./github-actions-rules.ts";
|
|
26
28
|
import { analyseProjectConfigRules } from "./project-config-rules.ts";
|
|
29
|
+
import { ruleDescriptors } from "./rules.ts";
|
|
27
30
|
import { scoreReport, summarize } from "./scoring.ts";
|
|
28
31
|
import { analyseSensitiveData } from "./sensitive-data-rules.ts";
|
|
29
|
-
import {
|
|
30
|
-
import
|
|
32
|
+
import { parseScript, type ParsedScript } from "./parsed-script.ts";
|
|
33
|
+
import { maskNonCode, maskTemplateLiteralBodies } from "./source-text.ts";
|
|
34
|
+
import type { AnalysisOptions, AnalysisReport, Config, Finding, Pillar, RunDiagnostic, ScanSurfaceNote, SkippedPath } from "./types.ts";
|
|
35
|
+
|
|
36
|
+
/*
|
|
37
|
+
* Internal hook view contract: both reports come from one current-tree scan so full-file and
|
|
38
|
+
* changed-region rendering stay stable and cannot drift.
|
|
39
|
+
*/
|
|
40
|
+
export interface HookAnalysisReports {
|
|
41
|
+
currentReport: AnalysisReport;
|
|
42
|
+
scopedReport: AnalysisReport;
|
|
43
|
+
}
|
|
31
44
|
|
|
32
45
|
/**
|
|
33
46
|
* Analyse the configured paths and return the stable gruff.analysis.v2 report contract.
|
|
@@ -36,34 +49,71 @@ import type { AnalysisOptions, AnalysisReport, Config, Finding, RunDiagnostic, S
|
|
|
36
49
|
* @returns Versioned report with fingerprinted findings, diagnostics, paths, and score data.
|
|
37
50
|
*/
|
|
38
51
|
export function analyse(options: AnalysisOptions): AnalysisReport {
|
|
52
|
+
const preparation = prepareAnalysis(options);
|
|
53
|
+
const changedScope = changedRegionScope(options);
|
|
54
|
+
const run = completeAnalysis(preparation, options);
|
|
55
|
+
const changedResult = filterChangedFindings(run.baselineResult.findings, changedScope, run.scanned.sources);
|
|
56
|
+
|
|
57
|
+
if (options.historyFile) {
|
|
58
|
+
recordHistory(run.projectRoot, options.historyFile, changedResult.findings, run.diagnostics);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// File-scoped policy: diff runs report and fail on diagnostics from changed target files only.
|
|
62
|
+
return reportFromRun({ ...run, diagnostics: filterScopedDiagnostics(run.diagnostics, changedScope) }, options, { ...run.baselineResult, findings: changedResult.findings }, changedResult.suppressedCount);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Builds the hook's full and changed-region reports from one scan. The diff-base replay still uses
|
|
66
|
+
// the ordinary runner because it analyses different file contents.
|
|
67
|
+
export function analyseHookReports(currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean): HookAnalysisReports {
|
|
68
|
+
const run = completeAnalysis(prepareAnalysis(currentOptions), currentOptions);
|
|
69
|
+
const currentReport = reportFromRun(run, currentOptions, run.baselineResult);
|
|
70
|
+
if (!hasChangedRegion) {
|
|
71
|
+
return { currentReport, scopedReport: currentReport };
|
|
72
|
+
}
|
|
73
|
+
const scopedChangedScope = changedRegionScope(scopedOptions);
|
|
74
|
+
const scopedChangedResult = filterChangedFindings(run.baselineResult.findings, scopedChangedScope, run.scanned.sources);
|
|
75
|
+
// Same file-scoped diagnostics policy as diff-scoped analyse, so both surfaces agree.
|
|
76
|
+
const scopedReport = reportFromRun({ ...run, diagnostics: filterScopedDiagnostics(run.diagnostics, scopedChangedScope) }, scopedOptions, { ...run.baselineResult, findings: scopedChangedResult.findings }, scopedChangedResult.suppressedCount);
|
|
77
|
+
return { currentReport, scopedReport };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Loads config and discovers inputs once so direct analysis and hook reuse share the same setup.
|
|
81
|
+
function prepareAnalysis(options: AnalysisOptions): AnalysisPreparation {
|
|
39
82
|
const projectRoot = cwd();
|
|
40
83
|
const config = loadConfig(projectRoot, options);
|
|
41
84
|
const diagnostics: RunDiagnostic[] = [];
|
|
42
85
|
const discovery = discoverSources(projectRoot, options, config);
|
|
43
|
-
|
|
86
|
+
return { projectRoot, config, diagnostics, discovery };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Runs per-file and project-level rules before applying baseline suppression; finding order remains stable.
|
|
90
|
+
function completeAnalysis(preparation: AnalysisPreparation, options: AnalysisOptions): AnalysisRun {
|
|
91
|
+
const { projectRoot, config, diagnostics, discovery } = preparation;
|
|
44
92
|
pushMissingPathDiagnostics(discovery.missingPaths, diagnostics);
|
|
45
93
|
|
|
46
94
|
const scanned = scanDiscoveredSources(discovery.files, config, diagnostics);
|
|
47
95
|
const allFindings = sortedUniqueFindings([
|
|
48
96
|
...scanned.findings,
|
|
49
|
-
...analyseProjectIndex(scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
|
|
50
|
-
]);
|
|
97
|
+
...analyseProjectIndex(projectRoot, options, discovery.files, scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
|
|
98
|
+
].map((finding) => applyConfiguredSeverity(config, finding)));
|
|
51
99
|
const baselineResult = applyBaselineOptions(projectRoot, options, allFindings);
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
recordHistory(projectRoot, options.historyFile, changedResult.findings, diagnostics);
|
|
56
|
-
}
|
|
100
|
+
const notes = [...discovery.notes, ...scanned.notes];
|
|
101
|
+
return { projectRoot, discovery, diagnostics, scanned, baselineResult, notes };
|
|
102
|
+
}
|
|
57
103
|
|
|
58
|
-
|
|
104
|
+
// Converts a completed run into a stable report contract or changed-region projection.
|
|
105
|
+
function reportFromRun(run: AnalysisRun, options: AnalysisOptions, baselineResult: BaselineApplication, suppressedCount?: number): AnalysisReport {
|
|
106
|
+
return buildAnalysisReport(run.projectRoot, options, run.discovery, run.diagnostics, baselineResult, run.notes, suppressedCount);
|
|
59
107
|
}
|
|
60
108
|
|
|
109
|
+
// Assembles the run's payload; the field shape is the stable gruff.analysis.v2 schema contract.
|
|
61
110
|
function buildAnalysisReport(
|
|
62
111
|
projectRoot: string,
|
|
63
112
|
options: AnalysisOptions,
|
|
64
113
|
discovery: DiscoverySummary,
|
|
65
114
|
diagnostics: RunDiagnostic[],
|
|
66
115
|
baselineResult: BaselineApplication,
|
|
116
|
+
notes: ScanSurfaceNote[],
|
|
67
117
|
suppressedCount?: number,
|
|
68
118
|
): AnalysisReport {
|
|
69
119
|
const findings = baselineResult.findings;
|
|
@@ -84,6 +134,7 @@ function buildAnalysisReport(
|
|
|
84
134
|
missingPaths: discovery.missingPaths,
|
|
85
135
|
},
|
|
86
136
|
diagnostics,
|
|
137
|
+
...(notes.length === 0 ? {} : { notes }),
|
|
87
138
|
findings,
|
|
88
139
|
...(suppressedCount === undefined ? {} : { suppressedCount }),
|
|
89
140
|
score: scoreReport(findings),
|
|
@@ -98,31 +149,37 @@ interface DiscoverySummary {
|
|
|
98
149
|
ignoredPaths: string[];
|
|
99
150
|
skipped: SkippedPath[];
|
|
100
151
|
missingPaths: string[];
|
|
152
|
+
notes: ScanSurfaceNote[];
|
|
101
153
|
}
|
|
102
154
|
|
|
103
155
|
// Output of the per-file scan pass - both the findings produced and the cached source bodies that
|
|
104
156
|
// later project-level rules need to operate against the deterministic stable shape used by baselines.
|
|
157
|
+
// Contract invariant: `notes` records bounded deep scans without changing finding order.
|
|
105
158
|
interface SourceScanResult {
|
|
106
159
|
findings: Finding[];
|
|
107
160
|
projectSources: ProjectSource[];
|
|
108
|
-
sources: Map<string, { file: SourceFile; source: string }>;
|
|
161
|
+
sources: Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>;
|
|
162
|
+
notes: ScanSurfaceNote[];
|
|
109
163
|
}
|
|
110
164
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
baseline?: NonNullable<AnalysisReport["baseline"]>;
|
|
165
|
+
// Prepared inputs for one analysis run. Discovery stays separate from scanning so hook mode can
|
|
166
|
+
// reuse setup without re-reading config.
|
|
167
|
+
interface AnalysisPreparation {
|
|
168
|
+
projectRoot: string;
|
|
169
|
+
config: Config;
|
|
170
|
+
diagnostics: RunDiagnostic[];
|
|
171
|
+
discovery: DiscoverySummary;
|
|
119
172
|
}
|
|
120
173
|
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
interface
|
|
124
|
-
|
|
125
|
-
|
|
174
|
+
// Completed scan state before final report rendering. The baseline result is carried separately so
|
|
175
|
+
// changed-region filtering can project findings without losing baseline metadata.
|
|
176
|
+
interface AnalysisRun {
|
|
177
|
+
projectRoot: string;
|
|
178
|
+
discovery: DiscoverySummary;
|
|
179
|
+
diagnostics: RunDiagnostic[];
|
|
180
|
+
scanned: SourceScanResult;
|
|
181
|
+
baselineResult: BaselineApplication;
|
|
182
|
+
notes: ScanSurfaceNote[];
|
|
126
183
|
}
|
|
127
184
|
|
|
128
185
|
// Emits a `missing-path` diagnostic per path that the user requested but discovery could not
|
|
@@ -145,16 +202,34 @@ function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiag
|
|
|
145
202
|
function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics: RunDiagnostic[]): SourceScanResult {
|
|
146
203
|
const findings: Finding[] = [];
|
|
147
204
|
const projectSources: ProjectSource[] = [];
|
|
148
|
-
const sources = new Map<string, { file: SourceFile; source: string }>();
|
|
205
|
+
const sources = new Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>();
|
|
206
|
+
const notes: ScanSurfaceNote[] = [];
|
|
149
207
|
for (const file of files) {
|
|
150
208
|
try {
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
if (
|
|
154
|
-
|
|
209
|
+
const fileBytes = readFileSync(file.absolutePath);
|
|
210
|
+
// Non-text bytes cannot produce trustworthy findings; the note explains why the file was skipped.
|
|
211
|
+
if (!isUtf8(fileBytes) || fileBytes.includes(0)) {
|
|
212
|
+
notes.push({
|
|
213
|
+
noteType: "non-text-file",
|
|
214
|
+
path: file.displayPath,
|
|
215
|
+
message: "File was skipped before parsing because it contains invalid UTF-8 or NUL bytes.",
|
|
216
|
+
});
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const source = fileBytes.toString("utf8");
|
|
220
|
+
const budgetNote = deepScanBudgetNote(file, source);
|
|
221
|
+
// One parse per script per run: every deep consumer shares this result; over-budget files skip it.
|
|
222
|
+
const parsed = budgetNote ? undefined : parseScript(file, source);
|
|
223
|
+
sources.set(file.displayPath, { file, source, ...(parsed ? { parsed } : {}) });
|
|
224
|
+
if (budgetNote) {
|
|
225
|
+
notes.push(budgetNote);
|
|
226
|
+
} else {
|
|
227
|
+
if (shouldRetainProjectSource(file, source)) {
|
|
228
|
+
projectSources.push(projectSource(file, source));
|
|
229
|
+
}
|
|
230
|
+
diagnostics.push(...(parsed?.diagnostics ?? []));
|
|
155
231
|
}
|
|
156
|
-
|
|
157
|
-
findings.push(...analyseSource(file, source, config));
|
|
232
|
+
findings.push(...analyseSource(file, source, config, budgetNote === undefined, parsed));
|
|
158
233
|
} catch (error) {
|
|
159
234
|
diagnostics.push({
|
|
160
235
|
diagnosticType: "read-error",
|
|
@@ -164,7 +239,30 @@ function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics:
|
|
|
164
239
|
});
|
|
165
240
|
}
|
|
166
241
|
}
|
|
167
|
-
return { findings, projectSources, sources };
|
|
242
|
+
return { findings, projectSources, sources, notes };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Scan budget for deep (masking, block-parsing, AST-walking) script analysis. Copied perf-test
|
|
246
|
+
// fixtures of 100k+ lines time out whole scans, so files above either bound keep text-level rules.
|
|
247
|
+
const DEEP_SCAN_MAX_LINES = 20_000; // Budget limit: bounds copied perf fixtures before deep passes.
|
|
248
|
+
const DEEP_SCAN_MAX_BYTES = 2_000_000; // Budget limit: catches minified/long-line scripts too.
|
|
249
|
+
|
|
250
|
+
// Returns the bounded-deep-scan note when a script file exceeds the budget, undefined otherwise.
|
|
251
|
+
// The file still counts as analysed - silence is the failure mode this guard exists to remove.
|
|
252
|
+
function deepScanBudgetNote(file: SourceFile, source: string): ScanSurfaceNote | undefined {
|
|
253
|
+
if (!file.isScript) {
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
const lines = lineCount(source);
|
|
257
|
+
const bytes = Buffer.byteLength(source, "utf8");
|
|
258
|
+
if (lines <= DEEP_SCAN_MAX_LINES && bytes <= DEEP_SCAN_MAX_BYTES) {
|
|
259
|
+
return undefined;
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
noteType: "bounded-deep-scan",
|
|
263
|
+
path: file.displayPath,
|
|
264
|
+
message: `File exceeds the deep-scan budget (${lines} lines, ${bytes} bytes; limits ${DEEP_SCAN_MAX_LINES} lines / ${DEEP_SCAN_MAX_BYTES} bytes). Text-level rules (size, sensitive-data, config) still ran; deep script analysis was skipped.`,
|
|
265
|
+
};
|
|
168
266
|
}
|
|
169
267
|
|
|
170
268
|
// Retains production files for exported-surface checks, tests for central-suite import coverage,
|
|
@@ -187,103 +285,265 @@ function hasImportSyntaxCandidate(source: string): boolean {
|
|
|
187
285
|
return source.includes("import") || source.includes("from");
|
|
188
286
|
}
|
|
189
287
|
|
|
190
|
-
//
|
|
191
|
-
//
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
);
|
|
200
|
-
|
|
288
|
+
// Per-file rule pipeline. Text rules run on every file (including config/yaml); TypeScript rules
|
|
289
|
+
// run only on scripts within the deep-scan budget. Fixed order is part of the stable fingerprint
|
|
290
|
+
// contract. Generated/copied files keep every security and sensitive-data finding but drop
|
|
291
|
+
// documentation and naming findings - generated code is not maintainer-authored source, so pushing
|
|
292
|
+
// doc/naming work at a human reviewer is unactionable noise.
|
|
293
|
+
// Contract invariant: doc/naming skips must not suppress safety pillars or change rule order.
|
|
294
|
+
function analyseSource(file: SourceFile, source: string, config: Config, isWithinDeepScanBudget: boolean, parsed?: ParsedScript): Finding[] {
|
|
295
|
+
const findings: Finding[] = [];
|
|
296
|
+
// Size and documentation rules share one comment scan so code-only line counts do not add a second pass.
|
|
297
|
+
const comments = (ruleEnabled(config, "size.file-length") && usesCStyleComments(file)) || (file.isScript && isAnyRuleEnabled(config, COMMENT_QUALITY_RULE_IDS)) ? commentRecords(source) : [];
|
|
298
|
+
analyseTextRules(file, source, comments, config, findings);
|
|
299
|
+
if (file.isScript && isWithinDeepScanBudget) {
|
|
300
|
+
analyseTypeScriptRules(file, source, comments, config, findings, parsed);
|
|
301
|
+
}
|
|
302
|
+
const isGenerated = isGeneratedSource(source);
|
|
303
|
+
return findings.filter((finding) => ruleEnabled(config, finding.ruleId) && !(isGenerated && GENERATED_SKIPPED_PILLARS.has(finding.pillar)));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// D6 generated-surface policy: docs/naming findings are skipped for generated files because no
|
|
307
|
+
// maintainer authors that text; every other pillar (security, sensitive-data, size, complexity,
|
|
308
|
+
// test-quality...) still applies - a generated file can leak a real credential.
|
|
309
|
+
const GENERATED_SKIPPED_PILLARS = new Set<Pillar>(["documentation", "naming"]);
|
|
310
|
+
|
|
311
|
+
// Marker-based generated/copied classification over the file's opening lines. Deliberately
|
|
312
|
+
// requires an explicit marker rather than path hints - a `fixtures/` path alone must never change
|
|
313
|
+
// rule behaviour, and `isDefaultIgnoredDir` stays the only directory-level exclusion surface.
|
|
314
|
+
function isGeneratedSource(source: string): boolean {
|
|
315
|
+
return source.split(/\r?\n/, 10).some((line) => /AUTO-?GENERATED|@generated\b|GENERATED FILE|Code generated|Generated by|DO NOT EDIT|Copied from/i.test(line));
|
|
201
316
|
}
|
|
202
317
|
|
|
203
318
|
/*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
319
|
+
* Cross-file rule pipeline. Contract invariant: scoped runs keep `paths.analysedFiles` scoped while
|
|
320
|
+
* circular-import may build root graph context so cycles through requested files stay visible. It
|
|
321
|
+
* swallows hidden root-context read failures in `graphProjectSources` so unrelated unreadable files
|
|
322
|
+
* do not break a narrow scan.
|
|
207
323
|
*/
|
|
208
|
-
function
|
|
209
|
-
|
|
210
|
-
|
|
324
|
+
function analyseProjectIndex(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[], projectSources: ProjectSource[], config: Config): Finding[] {
|
|
325
|
+
const shouldUseRootCircularContext = ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID) && shouldBuildRootCircularContext(projectRoot, options, scopedFiles);
|
|
326
|
+
const shouldUseScopedIndex = isAnyRuleEnabled(config, SCOPED_PROJECT_INDEX_RULE_IDS) || (ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID) && !shouldUseRootCircularContext);
|
|
327
|
+
if (!shouldUseScopedIndex && !shouldUseRootCircularContext) {
|
|
328
|
+
return [];
|
|
211
329
|
}
|
|
212
|
-
|
|
213
|
-
if (
|
|
214
|
-
|
|
330
|
+
const findings: Finding[] = [];
|
|
331
|
+
if (shouldUseScopedIndex) {
|
|
332
|
+
const index = buildProjectIndex(projectSources);
|
|
333
|
+
analyseArchitectureRules(index, config, findings, { shouldSkipCircularImports: shouldUseRootCircularContext });
|
|
215
334
|
}
|
|
335
|
+
if (shouldUseRootCircularContext) {
|
|
336
|
+
findings.push(...rootCircularImportFindings(projectRoot, options, scopedFiles, config));
|
|
337
|
+
}
|
|
338
|
+
return findings;
|
|
339
|
+
}
|
|
216
340
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
341
|
+
const PROJECT_INDEX_RULE_IDS = [
|
|
342
|
+
"design.deep-relative-import",
|
|
343
|
+
CIRCULAR_IMPORT_RULE_ID,
|
|
344
|
+
"design.large-module-concentration",
|
|
345
|
+
] as const;
|
|
346
|
+
const SCOPED_PROJECT_INDEX_RULE_IDS = [
|
|
347
|
+
"design.deep-relative-import",
|
|
348
|
+
"design.large-module-concentration",
|
|
349
|
+
] as const;
|
|
350
|
+
|
|
351
|
+
// Root graph context is needed only for narrow path operands; full-root scans already have context.
|
|
352
|
+
function shouldBuildRootCircularContext(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[]): boolean {
|
|
353
|
+
if (scopedFiles.length === 0 || options.paths.length === 0) {
|
|
354
|
+
return false;
|
|
220
355
|
}
|
|
356
|
+
return options.paths.every((input) => displayPath(projectRoot, absolutize(projectRoot, input)) !== ".");
|
|
357
|
+
}
|
|
221
358
|
|
|
222
|
-
|
|
359
|
+
// Builds stable circular-import findings from the repository root, then filters back to requested files.
|
|
360
|
+
function rootCircularImportFindings(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[], config: Config): Finding[] {
|
|
361
|
+
const requestedFiles = new Set(scopedFiles.map((file) => file.displayPath));
|
|
362
|
+
const rootDiscovery = discoverSources(projectRoot, { ...options, paths: [] }, config);
|
|
363
|
+
const rootProjectSources = graphProjectSources(rootDiscovery.files);
|
|
364
|
+
const findings: Finding[] = [];
|
|
365
|
+
analyseCircularImportRule(buildProjectIndex(rootProjectSources), findings);
|
|
366
|
+
return findings.filter((finding) => circularImportFindingTouchesRequestedFile(finding, requestedFiles));
|
|
223
367
|
}
|
|
224
368
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
},
|
|
240
|
-
};
|
|
369
|
+
// Reads just the root files needed for import graph context and swallows unrelated read failures.
|
|
370
|
+
function graphProjectSources(files: SourceFile[]): ProjectSource[] {
|
|
371
|
+
const projectSources: ProjectSource[] = [];
|
|
372
|
+
for (const file of files) {
|
|
373
|
+
try {
|
|
374
|
+
const source = readFileSync(file.absolutePath, "utf8");
|
|
375
|
+
if (!deepScanBudgetNote(file, source) && shouldRetainProjectSource(file, source)) {
|
|
376
|
+
projectSources.push(projectSource(file, source));
|
|
377
|
+
}
|
|
378
|
+
} catch {
|
|
379
|
+
// ignore hidden root-context read failures; scoped scans still report requested-file errors.
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return projectSources;
|
|
241
383
|
}
|
|
242
384
|
|
|
243
|
-
//
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
const filteredFindings = applyBaseline(selected.path, findings);
|
|
248
|
-
return {
|
|
249
|
-
findings: filteredFindings,
|
|
250
|
-
baseline: {
|
|
251
|
-
path: displayPath(projectRoot, selected.path),
|
|
252
|
-
source: selected.source,
|
|
253
|
-
suppressed: before - filteredFindings.length,
|
|
254
|
-
generated: false,
|
|
255
|
-
},
|
|
256
|
-
};
|
|
385
|
+
// Contract filter: root-context circular findings survive only when the SCC contains a requested file.
|
|
386
|
+
function circularImportFindingTouchesRequestedFile(finding: Finding, requestedFiles: Set<string>): boolean {
|
|
387
|
+
const files = Array.isArray(finding.metadata.files) ? finding.metadata.files : [finding.filePath];
|
|
388
|
+
return files.some((file) => typeof file === "string" && requestedFiles.has(file));
|
|
257
389
|
}
|
|
258
390
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
391
|
+
const RULE_IDS_BY_PILLAR = ruleIdsByPillar();
|
|
392
|
+
const COMPLEXITY_RULE_IDS = ruleIdsForPillar("complexity");
|
|
393
|
+
const DEAD_CODE_RULE_IDS = ruleIdsForPillar("dead-code");
|
|
394
|
+
const DOCUMENTATION_RULE_IDS = ruleIdsForPillar("documentation");
|
|
395
|
+
const MAINTAINABILITY_RULE_IDS = ruleIdsForPillar("maintainability");
|
|
396
|
+
const MODERNISATION_RULE_IDS = ruleIdsForPillar("modernisation");
|
|
397
|
+
const NAMING_RULE_IDS = ruleIdsForPillar("naming");
|
|
398
|
+
const SECURITY_RULE_IDS = ruleIdsForPillar("security");
|
|
399
|
+
const SENSITIVE_DATA_RULE_IDS = ruleIdsForPillar("sensitive-data");
|
|
400
|
+
const SIZE_RULE_IDS = ruleIdsForPillar("size");
|
|
401
|
+
const TEST_QUALITY_RULE_IDS = ruleIdsForPillar("test-quality");
|
|
402
|
+
|
|
403
|
+
/*
|
|
404
|
+
* Sensitive-data rules that infer a secret from shape rather than value, so generated
|
|
405
|
+
* dependency metadata defeats them: every integrity digest looks high-entropy, and a package
|
|
406
|
+
* named `gtoken` turns `gtoken: 8.0.0(supports-color@11.0.0)` into a credential assignment.
|
|
407
|
+
* Suppressed for lockfiles only. Every value-shaped detector still runs there.
|
|
408
|
+
*/
|
|
409
|
+
const LOCKFILE_SUPPRESSED_SENSITIVE_RULE_IDS = new Set([
|
|
410
|
+
"sensitive-data.high-entropy-string",
|
|
411
|
+
"sensitive-data.hardcoded-env-value",
|
|
412
|
+
]);
|
|
413
|
+
|
|
414
|
+
const GITHUB_ACTIONS_RULE_IDS = [
|
|
415
|
+
"security.github-actions-broad-permissions",
|
|
416
|
+
"security.github-actions-pull-request-target",
|
|
417
|
+
"security.github-actions-remote-shell",
|
|
418
|
+
"security.github-actions-secrets-in-pr",
|
|
419
|
+
"security.github-actions-unpinned-action",
|
|
420
|
+
] as const;
|
|
421
|
+
|
|
422
|
+
const PROJECT_CONFIG_RULE_IDS = [
|
|
423
|
+
"security.remote-install-script",
|
|
424
|
+
"security.risky-lifecycle-script",
|
|
425
|
+
"security.url-dependency",
|
|
426
|
+
"waste.broad-runtime-version",
|
|
427
|
+
"design.package-bin-missing",
|
|
428
|
+
"design.package-bin-not-executable",
|
|
429
|
+
] as const;
|
|
430
|
+
|
|
431
|
+
const BLOCK_RULE_IDS = [
|
|
432
|
+
"size.function-length",
|
|
433
|
+
"size.parameter-count",
|
|
434
|
+
"complexity.cyclomatic",
|
|
435
|
+
"complexity.cognitive",
|
|
436
|
+
"naming.generic-function",
|
|
437
|
+
"docs.missing-exported-function-doc",
|
|
438
|
+
"docs.missing-internal-function-doc",
|
|
439
|
+
"waste.empty-function",
|
|
440
|
+
"waste.unused-parameter",
|
|
441
|
+
"waste.redundant-variable",
|
|
442
|
+
"waste.useless-return",
|
|
443
|
+
] as const;
|
|
444
|
+
|
|
445
|
+
const PARAMETER_NAMING_RULE_IDS = [
|
|
446
|
+
"naming.boolean-prefix",
|
|
447
|
+
"naming.generic-parameter",
|
|
448
|
+
"naming.identifier-quality",
|
|
449
|
+
"naming.negative-boolean",
|
|
450
|
+
"naming.short-variable",
|
|
451
|
+
] as const;
|
|
452
|
+
|
|
453
|
+
const DOCBLOCK_RULE_IDS = [
|
|
454
|
+
"docs.missing-param-tag",
|
|
455
|
+
"docs.missing-return-tag",
|
|
456
|
+
"docs.stale-param-tag",
|
|
457
|
+
"docs.useless-docblock",
|
|
458
|
+
] as const;
|
|
459
|
+
|
|
460
|
+
const INTERFACE_FIELD_RULE_IDS = [
|
|
461
|
+
"naming.boolean-prefix",
|
|
462
|
+
"naming.negative-boolean",
|
|
463
|
+
] as const;
|
|
464
|
+
|
|
465
|
+
// Every rule id `analyseCommentQualityRules` can emit - including `docs.fixture-purpose-missing`
|
|
466
|
+
// via `pushFixturePurposeFindings` - so the group gate never silences an enabled rule.
|
|
467
|
+
const COMMENT_QUALITY_RULE_IDS = [
|
|
468
|
+
"docs.fixture-purpose-missing",
|
|
469
|
+
"docs.magic-threshold-without-rationale",
|
|
470
|
+
"docs.missing-error-behavior-doc",
|
|
471
|
+
"docs.missing-invariant-doc",
|
|
472
|
+
"docs.missing-side-effect-doc",
|
|
473
|
+
"docs.missing-why-for-complex-code",
|
|
474
|
+
"docs.stale-comment",
|
|
475
|
+
"docs.suppression-without-rationale",
|
|
476
|
+
"docs.todo-without-tracking",
|
|
477
|
+
"docs.useless-docblock",
|
|
478
|
+
] as const;
|
|
479
|
+
|
|
480
|
+
const CLASS_RULE_IDS = [
|
|
481
|
+
"docs.missing-public-doc",
|
|
482
|
+
"naming.class-file-mismatch",
|
|
483
|
+
"modernisation.public-property",
|
|
484
|
+
"modernisation.readonly-property-candidate",
|
|
485
|
+
] as const;
|
|
486
|
+
|
|
487
|
+
const IDENTIFIER_INVENTORY_RULE_IDS = [
|
|
488
|
+
"naming.acronym-case",
|
|
489
|
+
"naming.inconsistent-casing",
|
|
490
|
+
] as const;
|
|
491
|
+
|
|
492
|
+
const SECURITY_FLOW_RULE_IDS = [
|
|
493
|
+
"security.dynamic-regexp",
|
|
494
|
+
"security.open-redirect-candidate",
|
|
495
|
+
"security.path-traversal-candidate",
|
|
496
|
+
"security.ssrf-candidate",
|
|
497
|
+
"security.unsafe-deserialization",
|
|
498
|
+
"security.xxe-candidate",
|
|
499
|
+
] as const;
|
|
500
|
+
|
|
501
|
+
const LINE_RULE_IDS = [
|
|
502
|
+
...SECURITY_RULE_IDS,
|
|
503
|
+
...MAINTAINABILITY_RULE_IDS,
|
|
504
|
+
...MODERNISATION_RULE_IDS,
|
|
505
|
+
...NAMING_RULE_IDS,
|
|
506
|
+
];
|
|
507
|
+
|
|
508
|
+
const BLOCK_DEPENDENT_RULE_IDS = [
|
|
509
|
+
...BLOCK_RULE_IDS,
|
|
510
|
+
...PARAMETER_NAMING_RULE_IDS,
|
|
511
|
+
...TEST_QUALITY_RULE_IDS,
|
|
512
|
+
...COMMENT_QUALITY_RULE_IDS,
|
|
513
|
+
...IDENTIFIER_INVENTORY_RULE_IDS,
|
|
514
|
+
];
|
|
515
|
+
|
|
516
|
+
const TYPESCRIPT_RULE_IDS = [
|
|
517
|
+
...COMPLEXITY_RULE_IDS,
|
|
518
|
+
...DEAD_CODE_RULE_IDS,
|
|
519
|
+
...DOCUMENTATION_RULE_IDS,
|
|
520
|
+
...MAINTAINABILITY_RULE_IDS,
|
|
521
|
+
...MODERNISATION_RULE_IDS,
|
|
522
|
+
...NAMING_RULE_IDS,
|
|
523
|
+
...SECURITY_RULE_IDS,
|
|
524
|
+
...SIZE_RULE_IDS,
|
|
525
|
+
...TEST_QUALITY_RULE_IDS,
|
|
526
|
+
];
|
|
527
|
+
|
|
528
|
+
// Groups rule ids from the public catalogue once so broad pass gates stay aligned with profiles.
|
|
529
|
+
function ruleIdsByPillar(): ReadonlyMap<Pillar, readonly string[]> {
|
|
530
|
+
const byPillar = new Map<Pillar, string[]>();
|
|
531
|
+
for (const descriptor of ruleDescriptors()) {
|
|
532
|
+
const ruleIds = byPillar.get(descriptor.pillar) ?? [];
|
|
533
|
+
ruleIds.push(descriptor.ruleId);
|
|
534
|
+
byPillar.set(descriptor.pillar, ruleIds);
|
|
264
535
|
}
|
|
265
|
-
|
|
266
|
-
return existsSync(defaultBaseline) ? { path: defaultBaseline, source: "default" } : undefined;
|
|
536
|
+
return byPillar;
|
|
267
537
|
}
|
|
268
538
|
|
|
269
|
-
//
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const findings: Finding[] = [];
|
|
273
|
-
analyseTextRules(file, source, config, findings);
|
|
274
|
-
if (file.isScript) {
|
|
275
|
-
analyseTypeScriptRules(file, source, config, findings);
|
|
276
|
-
}
|
|
277
|
-
return findings.filter((finding) => ruleEnabled(config, finding.ruleId));
|
|
539
|
+
// Looks up a precomputed pillar group; missing groups are empty so callers can stay branch-free.
|
|
540
|
+
function ruleIdsForPillar(pillar: Pillar): readonly string[] {
|
|
541
|
+
return RULE_IDS_BY_PILLAR.get(pillar) ?? [];
|
|
278
542
|
}
|
|
279
543
|
|
|
280
|
-
//
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
const index = buildProjectIndex(projectSources);
|
|
284
|
-
const findings: Finding[] = [];
|
|
285
|
-
analyseArchitectureRules(index, config, findings);
|
|
286
|
-
return findings;
|
|
544
|
+
// Checks a rule-id group through the resolved config map so profiles and explicit overrides share one gate.
|
|
545
|
+
function isAnyRuleEnabled(config: Config, ruleIds: readonly string[]): boolean {
|
|
546
|
+
return ruleIds.some((ruleId) => ruleEnabled(config, ruleId));
|
|
287
547
|
}
|
|
288
548
|
|
|
289
549
|
/*
|
|
@@ -291,18 +551,18 @@ function analyseProjectIndex(projectSources: ProjectSource[], config: Config): F
|
|
|
291
551
|
* secret surfaces are not TypeScript. The order is a stable baseline contract: reshuffling these
|
|
292
552
|
* checks changes same-line finding order for machine reports.
|
|
293
553
|
*/
|
|
294
|
-
function analyseTextRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
const fileLengthThreshold = threshold(config, "size.file-length",
|
|
554
|
+
function analyseTextRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[]): void {
|
|
555
|
+
if (ruleEnabled(config, "size.file-length") && !isGeneratedLockfile(file.displayPath)) {
|
|
556
|
+
const lines = substantiveLineCount(file, source, comments);
|
|
557
|
+
const fileLengthThreshold = threshold(config, "size.file-length", 1000);
|
|
298
558
|
if (lines > fileLengthThreshold) {
|
|
299
559
|
findings.push(
|
|
300
560
|
makeFinding({
|
|
301
561
|
ruleId: "size.file-length",
|
|
302
|
-
message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`,
|
|
562
|
+
message: `File has ${lines} substantive lines, above the threshold of ${fileLengthThreshold}.`,
|
|
303
563
|
filePath: file.displayPath,
|
|
304
564
|
line: 1,
|
|
305
|
-
severity: ruleSeverity(config, "size.file-length", "
|
|
565
|
+
severity: ruleSeverity(config, "size.file-length", "error"),
|
|
306
566
|
pillar: "size",
|
|
307
567
|
confidence: "high",
|
|
308
568
|
remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.",
|
|
@@ -312,9 +572,79 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
|
|
|
312
572
|
}
|
|
313
573
|
}
|
|
314
574
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
575
|
+
if (isAnyRuleEnabled(config, SENSITIVE_DATA_RULE_IDS)) {
|
|
576
|
+
const sensitiveFindings: Finding[] = [];
|
|
577
|
+
analyseSensitiveData(file, source, config, sensitiveFindings);
|
|
578
|
+
// Generated dependency metadata defeats the two shape-based detectors: integrity digests
|
|
579
|
+
// look high-entropy, and a package whose name contains `token`/`key`/`secret` makes its
|
|
580
|
+
// version spec look like a credential assignment. The value-shaped detectors still run,
|
|
581
|
+
// because a credential in a `resolved` URL is the real leak vector for this file family.
|
|
582
|
+
const isLockfile = isGeneratedLockfile(file.displayPath);
|
|
583
|
+
for (const sensitiveFinding of sensitiveFindings) {
|
|
584
|
+
if (!isLockfile || !LOCKFILE_SUPPRESSED_SENSITIVE_RULE_IDS.has(sensitiveFinding.ruleId)) {
|
|
585
|
+
findings.push(sensitiveFinding);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
if (isAnyRuleEnabled(config, GITHUB_ACTIONS_RULE_IDS)) {
|
|
590
|
+
analyseGithubActionsRules(file, source, findings);
|
|
591
|
+
}
|
|
592
|
+
if (isAnyRuleEnabled(config, PROJECT_CONFIG_RULE_IDS)) {
|
|
593
|
+
analyseProjectConfigRules(file, source, findings);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// Counts nonblank lines after removing C-style and XML comments, then applies config-format
|
|
598
|
+
// full-line markers. Strings remain intact, so a line containing only a string literal still counts.
|
|
599
|
+
function substantiveLineCount(file: SourceFile, source: string, comments: CommentRecord[]): number {
|
|
600
|
+
const withoutCStyleComments = maskRecordedComments(source, comments);
|
|
601
|
+
const withoutComments = extname(file.displayPath).toLowerCase() === ".xml" ? maskXmlComments(withoutCStyleComments) : withoutCStyleComments;
|
|
602
|
+
return withoutComments
|
|
603
|
+
.split(/\r?\n/)
|
|
604
|
+
.filter((line) => isSubstantiveLine(file, line))
|
|
605
|
+
.length;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// C-style comments are valid on script/CSS surfaces and common in JSON-with-comments configs.
|
|
609
|
+
// Other supported text formats use their own full-line markers and must keep literal slash pairs.
|
|
610
|
+
function usesCStyleComments(file: SourceFile): boolean {
|
|
611
|
+
const extension = extname(file.displayPath).toLowerCase();
|
|
612
|
+
return file.isScript || extension === ".css" || extension === ".json";
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Replaces comment text with spaces while retaining newlines and UTF-16 offsets from CommentRecord.
|
|
616
|
+
function maskRecordedComments(source: string, comments: CommentRecord[]): string {
|
|
617
|
+
let cursor = 0;
|
|
618
|
+
let masked = "";
|
|
619
|
+
for (const comment of comments) {
|
|
620
|
+
const end = comment.kind === "block" ? Math.min(source.length, comment.endIndex + 1) : comment.endIndex;
|
|
621
|
+
masked += source.slice(cursor, comment.startIndex);
|
|
622
|
+
masked += source.slice(comment.startIndex, end).replace(/[^\r\n]/g, " ");
|
|
623
|
+
cursor = end;
|
|
624
|
+
}
|
|
625
|
+
return masked + source.slice(cursor);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// XML comments are outside the JavaScript lexer; preserving their newlines keeps line accounting stable.
|
|
629
|
+
function maskXmlComments(source: string): string {
|
|
630
|
+
return source.replace(/<!--[\s\S]*?(?:-->|$)/g, (comment) => comment.replace(/[^\r\n]/g, " "));
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Hash and semicolon markers are restricted to formats where they are comments, so TypeScript
|
|
634
|
+
// private fields and ordinary semicolon statements remain substantive.
|
|
635
|
+
function isSubstantiveLine(file: SourceFile, line: string): boolean {
|
|
636
|
+
const trimmed = line.trim();
|
|
637
|
+
if (!trimmed) {
|
|
638
|
+
return false;
|
|
639
|
+
}
|
|
640
|
+
const name = basename(file.displayPath).toLowerCase();
|
|
641
|
+
const extension = extname(name);
|
|
642
|
+
const usesHashComments = [".yaml", ".yml", ".toml"].includes(extension) || name === ".npmrc" || name.startsWith(".env");
|
|
643
|
+
if ((usesHashComments || (file.isScript && trimmed.startsWith("#!"))) && trimmed.startsWith("#")) {
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
const usesSemicolonComments = extension === ".ini" || name === ".npmrc";
|
|
647
|
+
return !(usesSemicolonComments && trimmed.startsWith(";"));
|
|
318
648
|
}
|
|
319
649
|
|
|
320
650
|
// Counts the same logical lines as `source.split(/\r?\n/)` without allocating the full line array.
|
|
@@ -328,49 +658,86 @@ function lineCount(source: string): number {
|
|
|
328
658
|
return count;
|
|
329
659
|
}
|
|
330
660
|
|
|
331
|
-
//
|
|
332
|
-
//
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
661
|
+
// Package-manager lockfiles contain generated dependency metadata, including public integrity digests.
|
|
662
|
+
// Discovery retains them; `size.file-length` skips them outright and the sensitive-data pass uses this
|
|
663
|
+
// predicate to drop only `sensitive-data.high-entropy-string`, so lockfile credentials still report.
|
|
664
|
+
function isGeneratedLockfile(filePath: string): boolean {
|
|
665
|
+
const fileName = basename(filePath);
|
|
666
|
+
return fileName === "package-lock.json" || fileName === "npm-shrinkwrap.json" || fileName === "yarn.lock" || fileName === "pnpm-lock.yaml" || fileName === "bun.lockb";
|
|
336
667
|
}
|
|
337
668
|
|
|
338
669
|
/*
|
|
339
670
|
* TypeScript-only rule pipeline. Masks comments and literals once, parses callable blocks once,
|
|
340
671
|
* then walks every rule pack in a stable, deterministic order so reports and baselines remain reproducible.
|
|
341
672
|
*/
|
|
342
|
-
function analyseTypeScriptRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
673
|
+
function analyseTypeScriptRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[], parsed?: ParsedScript): void {
|
|
674
|
+
if (!isAnyRuleEnabled(config, TYPESCRIPT_RULE_IDS)) {
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
343
677
|
const codeSource = maskNonCode(source);
|
|
344
|
-
const blocks = functionBlocks(source, codeSource);
|
|
345
|
-
|
|
346
|
-
analyseFileOverviewDoc(file, source, findings);
|
|
678
|
+
const blocks = isAnyRuleEnabled(config, BLOCK_DEPENDENT_RULE_IDS) ? functionBlocks(source, codeSource, parsed) : [];
|
|
679
|
+
runRulePass(config, "docs.missing-file-overview", () => analyseFileOverviewDoc(file, source, findings));
|
|
347
680
|
analyseBlocks(file, source, codeSource, blocks, config, findings);
|
|
348
|
-
analyseUnusedImports(file, codeSource, source, findings);
|
|
349
|
-
analyseLineRules(file, source, codeSource, config, findings);
|
|
350
|
-
analyseSecurityFlow(file, source, findings);
|
|
351
|
-
analyseUnreachable(file, codeSource, findings);
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
681
|
+
runRulePass(config, "waste.unused-import", () => analyseUnusedImports(file, codeSource, source, findings));
|
|
682
|
+
runRuleGroupPass(config, LINE_RULE_IDS, () => analyseLineRules(file, source, codeSource, config, findings));
|
|
683
|
+
runRuleGroupPass(config, SECURITY_FLOW_RULE_IDS, () => analyseSecurityFlow(file, source, findings, parsed?.sourceFile));
|
|
684
|
+
runRulePass(config, "waste.unreachable-code", () => analyseUnreachable(file, codeSource, findings));
|
|
685
|
+
// Docblock rules read real AST signatures; a bounded-deep-scan file without a parse skips them
|
|
686
|
+
// like the other syntax-backed passes instead of falling back to a lossy regex walk.
|
|
687
|
+
runRuleGroupPass(config, DOCBLOCK_RULE_IDS, () => {
|
|
688
|
+
if (parsed) {
|
|
689
|
+
analyseDocRules(file, findings, parsed);
|
|
690
|
+
}
|
|
691
|
+
});
|
|
692
|
+
runRulePass(config, "docs.missing-interface-doc", () => analyseInterfaceDocs(file, source, codeSource, findings));
|
|
693
|
+
runRuleGroupPass(config, INTERFACE_FIELD_RULE_IDS, () => analyseInterfaceFields(file, source, codeSource, config, findings));
|
|
694
|
+
runRuleGroupPass(config, COMMENT_QUALITY_RULE_IDS, () => analyseCommentQualityRules({ file, source, codeSource, blocks, comments, config, findings }));
|
|
695
|
+
runRuleGroupPass(config, CLASS_RULE_IDS, () => analyseClassRules(file, source, codeSource, config, findings, parsed));
|
|
696
|
+
runRulePass(config, "dead-code.unused-private-method", () => analyseDeadCode(file, codeSource, findings));
|
|
697
|
+
runRuleGroupPass(config, IDENTIFIER_INVENTORY_RULE_IDS, () => {
|
|
698
|
+
// A normal deep script scan always supplies the shared parse; a missing result must not reparse.
|
|
699
|
+
if (!parsed) {
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const inventory = collectDeclaredIdentifiers(source, codeSource, parsed);
|
|
703
|
+
runRulePass(config, "naming.inconsistent-casing", () => analyseInconsistentCasing(file, inventory, config, findings));
|
|
704
|
+
runRulePass(config, "naming.acronym-case", () => analyseAcronymCase(file, inventory, config, findings));
|
|
705
|
+
});
|
|
361
706
|
}
|
|
362
707
|
|
|
708
|
+
// Runs a single-rule pass only when that exact resolved rule id is enabled.
|
|
709
|
+
function runRulePass(config: Config, ruleId: string, action: () => void): void {
|
|
710
|
+
if (ruleEnabled(config, ruleId)) {
|
|
711
|
+
action();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// Runs a shared pass only when at least one rule it can emit is enabled.
|
|
716
|
+
function runRuleGroupPass(config: Config, ruleIds: readonly string[], action: () => void): void {
|
|
717
|
+
if (isAnyRuleEnabled(config, ruleIds)) {
|
|
718
|
+
action();
|
|
719
|
+
}
|
|
720
|
+
}
|
|
363
721
|
|
|
364
722
|
// One pass over the file's parsed callables. The naming and test-block fanouts are dispatched
|
|
365
723
|
// separately so blocks.ts can stay independent of the naming-pusher and test-block-rule modules;
|
|
366
724
|
// the per-rule emission order from `analyseBlockRules` is the stable fingerprint contract every
|
|
367
725
|
// Finding depends on for deterministic baseline matching.
|
|
368
726
|
function analyseBlocks(file: SourceFile, source: string, codeSource: string, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
|
|
727
|
+
const shouldAnalyseBlockRules = isAnyRuleEnabled(config, BLOCK_RULE_IDS);
|
|
728
|
+
const shouldAnalyseParameterNaming = isAnyRuleEnabled(config, PARAMETER_NAMING_RULE_IDS);
|
|
729
|
+
const shouldAnalyseTestQuality = isAnyRuleEnabled(config, TEST_QUALITY_RULE_IDS);
|
|
369
730
|
for (const block of blocks) {
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
731
|
+
let context: BlockRuleContext | undefined;
|
|
732
|
+
if (shouldAnalyseBlockRules) {
|
|
733
|
+
context = blockRuleContext(file, block, config, findings);
|
|
734
|
+
analyseBlockRules(context);
|
|
735
|
+
}
|
|
736
|
+
if (shouldAnalyseParameterNaming) {
|
|
737
|
+
context ??= blockRuleContext(file, block, config, findings);
|
|
738
|
+
pushParameterNamingFindings(context);
|
|
739
|
+
}
|
|
740
|
+
if (shouldAnalyseTestQuality && block.isTest) {
|
|
374
741
|
analyseTestBlock(file, block, findings, { source, codeSource, startLine: 1 });
|
|
375
742
|
}
|
|
376
743
|
}
|
|
@@ -383,8 +750,9 @@ function analyseBlocks(file: SourceFile, source: string, codeSource: string, blo
|
|
|
383
750
|
function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
384
751
|
const line = context.block.declarationLine;
|
|
385
752
|
const params = parameterNames(context.block.params);
|
|
753
|
+
const hasLocallyBoundParameters = isLocallyBoundParameterOwner(context.block);
|
|
386
754
|
for (const parameter of params) {
|
|
387
|
-
if (!isComparatorShortParameter(context, params, parameter.name)) {
|
|
755
|
+
if (!hasLocallyBoundParameters && !isComparatorShortParameter(context, params, parameter.name)) {
|
|
388
756
|
pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
389
757
|
}
|
|
390
758
|
pushIdentifierQualityAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
@@ -398,6 +766,24 @@ function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
|
398
766
|
}
|
|
399
767
|
}
|
|
400
768
|
|
|
769
|
+
// Variable-bound callables and test callbacks keep their parameters beside the implementation,
|
|
770
|
+
// so short closure names do not create the cross-file review cost this rule is meant to surface.
|
|
771
|
+
// Declared functions and methods remain covered. Other parameter naming rules still run here.
|
|
772
|
+
function isLocallyBoundParameterOwner(block: FunctionBlock): boolean {
|
|
773
|
+
if (block.isTest) {
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
// An exported binding is the cross-file API this exemption exists to keep covered, so
|
|
777
|
+
// `export const transform = (x) => ...` is judged like `export function transform(x)`.
|
|
778
|
+
if (block.isExported) {
|
|
779
|
+
return false;
|
|
780
|
+
}
|
|
781
|
+
const declarationOffset = block.declarationLine - block.startLine;
|
|
782
|
+
const declarationLine = block.codeBody.split(/\r?\n/)[declarationOffset] ?? "";
|
|
783
|
+
const bindingName = declarationLine.match(/\b(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/)?.[1];
|
|
784
|
+
return bindingName === block.name;
|
|
785
|
+
}
|
|
786
|
+
|
|
401
787
|
// `(a, b)` is a conventional comparator pair when the callable is explicitly shaped like sorting.
|
|
402
788
|
// Keep the exemption narrow so arbitrary two-parameter helpers still need domain names.
|
|
403
789
|
function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ name: string; raw: string }>, name: string): boolean {
|