@blundergoat/gruff-ts 0.3.2 → 0.4.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.
@@ -0,0 +1,90 @@
1
+ // Baseline option handling for `analyse`: chooses explicit/default baselines, applies
2
+ // suppression, and writes generated baselines while preserving the report metadata shape.
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { applyBaseline, DEFAULT_BASELINE, writeBaseline } from "./baseline.ts";
6
+ import { absolutize, displayPath } from "./discovery.ts";
7
+ import type { AnalysisOptions, AnalysisReport, Finding } from "./types.ts";
8
+
9
+ /*
10
+ * Result of applying a baseline (suppression) or generating a new one. The optional `baseline`
11
+ * matches the `gruff.analysis.v2` schema's baseline metadata - present only when a baseline file
12
+ * was actually used or generated, so the report stays stable across baseline-disabled runs.
13
+ */
14
+ export interface BaselineApplication {
15
+ findings: Finding[];
16
+ baseline?: NonNullable<AnalysisReport["baseline"]>;
17
+ }
18
+
19
+ // Resolved baseline path plus the provenance string emitted in the report. `source` distinguishes
20
+ // "explicit" (--baseline flag) from "default" (auto-discovered gruff-baseline.json).
21
+ interface BaselineSelection {
22
+ path: string;
23
+ source: string;
24
+ }
25
+
26
+ /*
27
+ * Three-way baseline dispatcher. `--generate-baseline` wins (writes a new file, returns findings
28
+ * unchanged); `--no-baseline` skips entirely; otherwise look for an explicit or default baseline.
29
+ * The stable identity tuple (fingerprint, ruleId, filePath) drives suppression matching.
30
+ */
31
+ export function applyBaselineOptions(projectRoot: string, options: AnalysisOptions, findings: Finding[]): BaselineApplication {
32
+ if (options.generateBaseline) {
33
+ return generateBaselineResult(projectRoot, options.generateBaseline, findings);
34
+ }
35
+
36
+ if (options.shouldSkipBaseline) {
37
+ return { findings };
38
+ }
39
+
40
+ const selected = selectedBaseline(projectRoot, options);
41
+ if (!selected) {
42
+ return { findings };
43
+ }
44
+
45
+ return applySelectedBaseline(projectRoot, selected, findings);
46
+ }
47
+
48
+ /*
49
+ * Writes the baseline file via writeBaseline and returns the report-shaped metadata. `suppressed: 0`
50
+ * because generation does not filter findings - every current finding is captured in the stable baseline.
51
+ */
52
+ function generateBaselineResult(projectRoot: string, baselineFile: string, findings: Finding[]): BaselineApplication {
53
+ const baselinePath = absolutize(projectRoot, baselineFile);
54
+ writeBaseline(baselinePath, findings);
55
+ return {
56
+ findings,
57
+ baseline: {
58
+ path: displayPath(projectRoot, baselinePath),
59
+ source: "generated",
60
+ suppressed: 0,
61
+ generated: true,
62
+ },
63
+ };
64
+ }
65
+
66
+ // Loads the baseline file and filters findings whose identity tuple matches. `suppressed` is
67
+ // computed from the size delta so the stable baseline report metadata stays accurate.
68
+ function applySelectedBaseline(projectRoot: string, selected: BaselineSelection, findings: Finding[]): BaselineApplication {
69
+ const before = findings.length;
70
+ const filteredFindings = applyBaseline(selected.path, findings);
71
+ return {
72
+ findings: filteredFindings,
73
+ baseline: {
74
+ path: displayPath(projectRoot, selected.path),
75
+ source: selected.source,
76
+ suppressed: before - filteredFindings.length,
77
+ generated: false,
78
+ },
79
+ };
80
+ }
81
+
82
+ // Picks an explicit `--baseline` path first, then the conventional `gruff-baseline.json` at the
83
+ // project root. Returning undefined means "no baseline" - the stable contract preserves report shape.
84
+ function selectedBaseline(projectRoot: string, options: AnalysisOptions): BaselineSelection | undefined {
85
+ if (options.baseline) {
86
+ return { path: absolutize(projectRoot, options.baseline), source: "explicit" };
87
+ }
88
+ const defaultBaseline = join(projectRoot, DEFAULT_BASELINE);
89
+ return existsSync(defaultBaseline) ? { path: defaultBaseline, source: "default" } : undefined;
90
+ }
@@ -45,6 +45,10 @@ interface DiffParseState {
45
45
 
46
46
  const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
47
47
 
48
+ // Project-relationship rules anchor one canonical file but relate every member in `metadata.files`,
49
+ // so changed-region attribution must consult the member list, not only the anchor `filePath`.
50
+ const PROJECT_RELATIONSHIP_RULE_IDS = new Set(["design.circular-import"]);
51
+
48
52
  // Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
49
53
  export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
50
54
  if (options.changedRanges) {
@@ -94,6 +98,9 @@ function isFindingInChangedScope(
94
98
  sources: Map<string, SourceSnapshot>,
95
99
  declarationsByFile: Map<string, DeclarationRegion[]>,
96
100
  ): boolean {
101
+ if (PROJECT_RELATIONSHIP_RULE_IDS.has(finding.ruleId)) {
102
+ return projectRelationshipTouchesChange(finding, scope);
103
+ }
97
104
  if (scope.wholeFiles.has(finding.filePath)) {
98
105
  return true;
99
106
  }
@@ -122,6 +129,20 @@ function isFileWideFinding(finding: Finding): boolean {
122
129
  return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
123
130
  }
124
131
 
132
+ /*
133
+ * Keeps a project-relationship finding when any member file participates in the change, matching
134
+ * the documented contract "a project relationship that includes the requested file". Explicit
135
+ * `--changed-ranges` carry no per-file information (the ranges apply to every selected file), so
136
+ * they keep these findings by construction; narrow scans already filtered them to requested files.
137
+ */
138
+ function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegionScope): boolean {
139
+ if (scope.explicitRanges !== undefined) {
140
+ return true;
141
+ }
142
+ const files = Array.isArray(finding.metadata.files) ? finding.metadata.files : [finding.filePath];
143
+ return files.some((file) => typeof file === "string" && (scope.wholeFiles.has(file) || scope.changedFiles.has(file)));
144
+ }
145
+
125
146
  // Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
126
147
  function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): ChangedRange[] {
127
148
  return scope.explicitRanges ?? scope.rangesByFile.get(filePath) ?? [];
@@ -17,7 +17,10 @@ import { completionShell, getRuleDescriptor, renderCompletionScript, renderConso
17
17
  import { exitFor } from "./scoring.ts";
18
18
  import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
19
19
 
20
- type AnalyseRunner = (options: AnalysisOptions) => AnalysisReport;
20
+ type HookAnalysisViews = { currentReport: AnalysisReport; scopedReport: AnalysisReport };
21
+ type AnalyseRunner = ((options: AnalysisOptions) => AnalysisReport) & {
22
+ hookViews?: (currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean) => HookAnalysisViews;
23
+ };
21
24
 
22
25
  // The `report` command intentionally rejects `--baseline` because its output is meant to reflect
23
26
  // raw findings; this flag lets `normalizeOptions` enforce that without per-command branching.
package/src/cli.ts CHANGED
@@ -3,14 +3,15 @@
3
3
  // analyse pipeline itself lives in `./analyser.ts`; this file is just bootstrap plus re-exports.
4
4
  import { argv } from "node:process";
5
5
  import { pathToFileURL } from "node:url";
6
- import { analyse } from "./analyser.ts";
6
+ import { analyse, analyseHookReports } from "./analyser.ts";
7
7
  import { buildProgram as buildCliProgram } from "./cli-program.ts";
8
8
  import { absolutize, displayPath } from "./discovery.ts";
9
9
  import { renderReport } from "./report-renderers.ts";
10
10
  import { ruleDescriptors } from "./rules.ts";
11
11
  export type { AnalysisReport, Finding, OutputFormat, Pillar, RuleDescriptor, Severity } from "./types.ts";
12
12
 
13
- const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyse);
13
+ const analyseRunner = Object.assign(analyse, { hookViews: analyseHookReports });
14
+ const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyseRunner);
14
15
 
15
16
  if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
16
17
  // Action handlers in cli-program.ts are async (await maybePromptInitConfig). parseAsync is
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Shared release constants that keep CLI, reports, and rule catalogue output in sync.
2
- const VERSION = "0.3.2";
2
+ const VERSION = "0.4.0";
3
3
 
4
4
  /*
5
5
  * Threshold at which the `analyse` text renderer appends a one-line pointer to `gruff-ts summary`.
@@ -7,13 +7,20 @@ import { escapeRegex, finding } from "./findings-helpers.ts";
7
7
  import { byteLine, countMatches } from "./text-scans.ts";
8
8
  import type { Finding } from "./types.ts";
9
9
 
10
- // Deliberately single-file and low confidence because private methods can still be reached by
11
- // tests, decorators, framework hooks, or string-based reflection; reports stable advisory findings because removal still needs human confirmation.
10
+ /*
11
+ * Single-file, low-confidence dead-code pass. Contract invariant: removal candidates stay advisory
12
+ * because tests, decorators, framework hooks, or reflection may still reach a private method. It
13
+ * reports findings only and never throws for malformed snippets. Why two evidence counts:
14
+ * declarations contribute to `name(` matches, while bare method references such as `items.map(this.double)`
15
+ * appear only as `this.name` / `this?.name`, and either shape is enough usage evidence to suppress
16
+ * the finding. The reference count requires a `this` receiver so unrelated properties that share
17
+ * the name (for example `settings.refresh`) cannot mask a genuinely unused private method.
18
+ */
12
19
  export function analyseDeadCode(file: SourceFile, source: string, findings: Finding[]): void {
13
20
  for (const match of source.matchAll(/\bprivate\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
14
21
  const name = match[1] ?? "";
15
22
  const escaped = escapeRegex(name);
16
- if (countMatches(source, new RegExp(`${escaped}\\s*\\(`, "g")) <= 1) {
23
+ if (countMatches(source, new RegExp(`${escaped}\\s*\\(`, "g")) <= 1 && countMatches(source, new RegExp(`\\bthis\\??\\.${escaped}\\b`, "g")) === 0) {
17
24
  findings.push(
18
25
  makeFinding({
19
26
  ruleId: "dead-code.unused-private-method",
package/src/discovery.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Filesystem discovery, ignore-policy matching, and display-path normalization for deterministic scans.
2
2
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
4
- import type { AnalysisOptions, Config, IgnoreSource, SkippedPath } from "./types.ts";
4
+ import type { AnalysisOptions, Config, IgnoreSource, ScanSurfaceNote, SkippedPath } from "./types.ts";
5
5
 
6
6
  // `absolutePath` is what `node:fs` operates on; `displayPath` is the project-relative POSIX form
7
7
  // embedded in findings and baselines. They must stay aligned - diverging them breaks fingerprint stability.
@@ -22,12 +22,15 @@ interface SourceDiscovery {
22
22
  // Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths` (the
23
23
  // back-compatible string[] of excluded paths) and `skipped` (the same paths enriched with ignore
24
24
  // source + matched pattern) are sorted so reports stay deterministic even when the underlying
25
- // filesystem returns directory entries in arbitrary order.
25
+ // filesystem returns directory entries in arbitrary order. `notes` carries one entry per requested
26
+ // input that exists but contributed zero analysable files, so an all-skipped scan is never a
27
+ // silent zero-finding success.
26
28
  export interface SourceDiscoveryResult {
27
29
  files: SourceFile[];
28
30
  missingPaths: string[];
29
31
  ignoredPaths: string[];
30
32
  skipped: SkippedPath[];
33
+ notes: ScanSurfaceNote[];
31
34
  }
32
35
 
33
36
  // A single line from a `.gitignore`. The combination of `isAnchored`, `isDirectoryOnly`, and `hasSlash`
@@ -47,14 +50,35 @@ interface GitIgnoreRule {
47
50
  export function discoverSources(projectRoot: string, options: AnalysisOptions, config: Config): SourceDiscoveryResult {
48
51
  const discovery: SourceDiscovery = { files: [], missingPaths: [], skipped: new Map<string, SkippedPath>() };
49
52
  const inputs = options.paths.length > 0 ? options.paths : ["."];
53
+ const notes: ScanSurfaceNote[] = [];
50
54
 
51
55
  for (const input of inputs) {
56
+ const filesBefore = discovery.files.length;
57
+ const missingBefore = discovery.missingPaths.length;
58
+ const skippedBefore = discovery.skipped.size;
52
59
  discoverSourceInput(projectRoot, input, options, config, discovery);
60
+ if (discovery.missingPaths.length === missingBefore && discovery.files.length === filesBefore) {
61
+ notes.push(zeroFileInputNote(input, discovery.skipped.size - skippedBefore));
62
+ }
53
63
  }
54
64
 
55
65
  discovery.files.sort((left, right) => left.displayPath.localeCompare(right.displayPath));
56
66
  const skipped = [...discovery.skipped.values()].sort((left, right) => left.path.localeCompare(right.path));
57
- return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped };
67
+ return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped, notes };
68
+ }
69
+
70
+ // A requested input that exists but contributed no analysable files is a per-input note, never a
71
+ // diagnostic - exit codes stay unchanged. The skip count names the likely cause (parent gitignore
72
+ // or config ignore rules hiding the whole subtree) so the caller does not read 0 findings as clean.
73
+ function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote {
74
+ const cause = skippedCount > 0
75
+ ? `${skippedCount} path(s) under it were excluded by ignore rules`
76
+ : "it contains no analysable source files";
77
+ return {
78
+ noteType: "no-analysable-files",
79
+ path: input,
80
+ message: `Requested path '${input}' was not analysed: ${cause}. 0 findings here does not mean the path is clean.`,
81
+ };
58
82
  }
59
83
 
60
84
  // Resolves the input against `node:fs`. Missing inputs go into `missingPaths` so the CLI can
@@ -12,7 +12,10 @@ import type { AnalysisOptions, AnalysisReport, Finding, Severity, SkippedPath }
12
12
 
13
13
  type HookScope = "line" | "symbol" | "file" | "project";
14
14
  type FlagOrder = "any" | "flags-before-path";
15
- type HookAnalysisRunner = (options: AnalysisOptions) => AnalysisReport;
15
+ type HookAnalysisViews = { currentReport: AnalysisReport; scopedReport: AnalysisReport };
16
+ type HookAnalysisRunner = ((options: AnalysisOptions) => AnalysisReport) & {
17
+ hookViews?: (currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean) => HookAnalysisViews;
18
+ };
16
19
 
17
20
  // Inputs for one hook render: full-scan options, changed-region options, and optional baseline/diff
18
21
  // bases used for new-only filtering.
@@ -89,17 +92,26 @@ export function renderHookCapabilities(): string {
89
92
  }, null, 2) + "\n";
90
93
  }
91
94
 
92
- // Runs the analysis (twice when a changed region is requested) and projects it into the gruff.hook.v1
93
- // envelope: scoped findings, suppressed count, ignored paths, and a schema-ok config block.
95
+ // Runs the analysis and projects it into the gruff.hook.v1 envelope: scoped findings, suppressed
96
+ // count, ignored paths, and a schema-ok config block.
94
97
  export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
95
- const currentReport = runAnalyse(input.currentOptions);
96
- const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
98
+ const { currentReport, scopedReport } = hookAnalysisViews(runAnalyse, input);
97
99
  const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
98
100
  const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
99
101
  const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
100
102
  return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
101
103
  }
102
104
 
105
+ // Selects the optimized hook view when available, otherwise falls back to one or two analyse calls.
106
+ function hookAnalysisViews(runAnalyse: HookAnalysisRunner, input: HookReportInput): HookAnalysisViews {
107
+ if (runAnalyse.hookViews) {
108
+ return runAnalyse.hookViews(input.currentOptions, input.scopedOptions, input.hasChangedRegion);
109
+ }
110
+ const currentReport = runAnalyse(input.currentOptions);
111
+ const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
112
+ return { currentReport, scopedReport };
113
+ }
114
+
103
115
  // Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
104
116
  // error) so the consumer always receives JSON with config.error set instead of a crash.
105
117
  export function renderHookConfigError(message: string, remediation: string): string {
@@ -133,7 +145,7 @@ function hookFindings(
133
145
  ): HookFinding[] {
134
146
  const scopedFindings = scopedReport.findings
135
147
  .map(toHookFinding)
136
- .filter((finding) => !hasChangedRegion || (finding.scope !== "file" && finding.scope !== "project"));
148
+ .filter((finding) => !hasChangedRegion || finding.scope !== "file");
137
149
  const withNewFileAndProject = hasChangedRegion && baseIdentities
138
150
  ? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, baseIdentities)]
139
151
  : scopedFindings;
@@ -254,12 +266,9 @@ function stableIdentityComponent(finding: { message: string; ruleId: string; sym
254
266
  return scope;
255
267
  }
256
268
  if (scope === "project") {
257
- // Project rules are value-insensitive on their measurement, but one file can anchor several
258
- // distinct project findings: design.circular-import emits one finding per cycle and sorts each
259
- // cycle to its alphabetically-first member, so `a -> b` and `a -> c` both anchor `a.ts`. The
260
- // cycle path (carried in `symbol`) is the only discriminator; folding it in keeps distinct
261
- // cycles distinct so baselining one never suppresses a genuinely new one. A project finding with
262
- // no symbol falls back to the bare scope token, preserving its value-insensitive identity.
269
+ // Project rules are value-insensitive on their measurement, but component-level findings still
270
+ // need a stable occurrence key. design.circular-import carries the canonical sorted SCC member
271
+ // list in `symbol`; folding it in keeps independent components distinct without line sensitivity.
263
272
  return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
264
273
  }
265
274
  if (finding.symbol && finding.symbol.length > 0) {
@@ -270,7 +279,7 @@ function stableIdentityComponent(finding: { message: string; ruleId: string; sym
270
279
  // collapsed them all, letting one baselined finding suppress later new ones in the same file. The
271
280
  // message carries the per-occurrence discriminator (redacted preview) and no line number, so it
272
281
  // stays stable across surrounding edits. file scope above stays fully value-insensitive; project
273
- // scope folds in the cycle symbol when one is present.
282
+ // scope folds in a canonical symbol when one is present.
274
283
  return `message:${finding.message}`;
275
284
  }
276
285
 
@@ -347,7 +356,7 @@ function stableIdentitiesFromDiffBase(
347
356
  if (ref === undefined) {
348
357
  return new Set();
349
358
  }
350
- const files = [...new Set(currentReport.findings.map((finding) => finding.filePath))];
359
+ const files = [...new Set(currentReport.findings.flatMap(findingBasePaths))];
351
360
  if (files.length === 0) {
352
361
  return new Set();
353
362
  }
@@ -367,6 +376,19 @@ function stableIdentitiesFromDiffBase(
367
376
  }
368
377
  }
369
378
 
379
+ /*
380
+ * A finding's base context is its anchor plus any project-relationship members from
381
+ * `metadata.files`. Contract invariant: without every SCC member at the base ref, the replay
382
+ * cannot reconstruct the cycle identity and a pre-existing cycle would be reported as new.
383
+ */
384
+ function findingBasePaths(finding: Finding): string[] {
385
+ const memberFiles = finding.metadata.files;
386
+ if (!Array.isArray(memberFiles)) {
387
+ return [finding.filePath];
388
+ }
389
+ return [finding.filePath, ...memberFiles.filter((file): file is string => typeof file === "string")];
390
+ }
391
+
370
392
  // Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
371
393
  // the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
372
394
  // patch) has no materializable base. Returns undefined only when no base can be replayed.
package/src/line-rules.ts CHANGED
@@ -4,11 +4,12 @@
4
4
  // detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
5
5
  // invoked by the cli orchestrator before/after this module so the stable per-line emission order
6
6
  // stays a single contract.
7
- import { ruleSeverity } from "./config.ts";
7
+ import { ruleEnabled, ruleSeverity } from "./config.ts";
8
8
  import { type SourceFile } from "./discovery.ts";
9
9
  import { makeFinding } from "./findings.ts";
10
10
  import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
11
11
  import { type NamingSurface, pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
12
+ import { processExecMetadata } from "./process-exec-metadata.ts";
12
13
  import { analyseReliabilityLine, analyseSwallowedCatches, analyseTypeSafetyLine, analyseUselessCatches } from "./safety-rules.ts";
13
14
  import { analyseSecurityFlowLine } from "./security-flow-rules.ts";
14
15
  import { codeLineForMatching } from "./source-text.ts";
@@ -44,12 +45,61 @@ interface LineRuleContext {
44
45
  codeChecks: LineRuleCheck[];
45
46
  literalChecks: LineRuleCheck[];
46
47
  variables: RegExp;
48
+ gates: LineRuleGates;
47
49
  }
48
50
 
49
51
  const CODE_LINE_CHECKS = codeLineChecks();
50
52
  const LITERAL_LINE_CHECKS = literalLineChecks();
51
53
  const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g;
52
54
 
55
+ // Per-file rule-family switches. They avoid re-running helpers when every rule they emit is disabled.
56
+ interface LineRuleGates {
57
+ shouldRunTypeSafety: boolean;
58
+ shouldRunReliability: boolean;
59
+ shouldRunCommentedOutCode: boolean;
60
+ shouldRunBooleanNaming: boolean;
61
+ shouldRunHungarianNotation: boolean;
62
+ shouldRunOptionalChaining: boolean;
63
+ shouldRunNullishCoalescing: boolean;
64
+ shouldRunLooseEquality: boolean;
65
+ shouldRunStringTimer: boolean;
66
+ shouldRunSecurityFlow: boolean;
67
+ shouldRunVariableNaming: boolean;
68
+ shouldRunProcessExec: boolean;
69
+ shouldRunUselessCatch: boolean;
70
+ shouldRunSwallowedCatch: boolean;
71
+ }
72
+
73
+ const TYPE_SAFETY_RULE_IDS = [
74
+ "modernisation.double-cast",
75
+ "modernisation.non-null-assertion",
76
+ "modernisation.ts-comment-without-rationale",
77
+ "waste.exported-any",
78
+ ] as const;
79
+
80
+ const RELIABILITY_RULE_IDS = [
81
+ "security.async-foreach",
82
+ "security.floating-promise",
83
+ "security.throw-non-error",
84
+ ] as const;
85
+
86
+ const BOOLEAN_NAMING_RULE_IDS = [
87
+ "naming.boolean-prefix",
88
+ "naming.negative-boolean",
89
+ ] as const;
90
+
91
+ const SECURITY_FLOW_LINE_RULE_IDS = [
92
+ "security.dynamic-regexp",
93
+ "security.open-redirect-candidate",
94
+ "security.path-traversal-candidate",
95
+ "security.ssrf-candidate",
96
+ ] as const;
97
+
98
+ const VARIABLE_NAMING_RULE_IDS = [
99
+ "naming.identifier-quality",
100
+ "naming.short-variable",
101
+ ] as const;
102
+
53
103
  /*
54
104
  * Per-line rule pipeline plus the two multi-line catch detectors. Excludes analyseUnusedImports
55
105
  * and analyseUnreachable so the dead-code module can own them; the orchestrator in cli.ts wraps
@@ -58,6 +108,22 @@ const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s
58
108
  export function analyseLineRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[]): void {
59
109
  const sourceLines = source.split(/\r?\n/);
60
110
  const codeLines = codeSource.split(/\r?\n/);
111
+ const gates: LineRuleGates = {
112
+ shouldRunTypeSafety: TYPE_SAFETY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
113
+ shouldRunReliability: RELIABILITY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
114
+ shouldRunCommentedOutCode: ruleEnabled(config, "waste.commented-out-code"),
115
+ shouldRunBooleanNaming: BOOLEAN_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
116
+ shouldRunHungarianNotation: ruleEnabled(config, "naming.hungarian-notation"),
117
+ shouldRunOptionalChaining: ruleEnabled(config, "modernisation.optional-chaining-candidate"),
118
+ shouldRunNullishCoalescing: ruleEnabled(config, "modernisation.nullish-coalescing-candidate"),
119
+ shouldRunLooseEquality: ruleEnabled(config, "modernisation.loose-equality"),
120
+ shouldRunStringTimer: ruleEnabled(config, "security.string-timer"),
121
+ shouldRunSecurityFlow: SECURITY_FLOW_LINE_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
122
+ shouldRunVariableNaming: VARIABLE_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
123
+ shouldRunProcessExec: ruleEnabled(config, "security.process-exec"),
124
+ shouldRunUselessCatch: ruleEnabled(config, "waste.useless-catch"),
125
+ shouldRunSwallowedCatch: ruleEnabled(config, "waste.swallowed-catch"),
126
+ };
61
127
  const context: LineRuleContext = {
62
128
  file,
63
129
  line: "",
@@ -66,9 +132,10 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
66
132
  lineNumber: 0,
67
133
  config,
68
134
  findings,
69
- codeChecks: CODE_LINE_CHECKS,
70
- literalChecks: LITERAL_LINE_CHECKS,
135
+ codeChecks: CODE_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
136
+ literalChecks: LITERAL_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
71
137
  variables: VARIABLE_DECLARATIONS,
138
+ gates,
72
139
  };
73
140
  sourceLines.forEach((line, index) => {
74
141
  context.line = line;
@@ -78,26 +145,54 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
78
145
  analyseLineRuleContext(context);
79
146
  });
80
147
 
81
- analyseProcessExecCalls(file, source, codeSource, findings);
82
- analyseUselessCatches(file, codeSource, findings);
83
- analyseSwallowedCatches(file, source, codeSource, findings);
148
+ if (gates.shouldRunProcessExec) {
149
+ analyseProcessExecCalls(file, source, codeSource, findings);
150
+ }
151
+ if (gates.shouldRunUselessCatch) {
152
+ analyseUselessCatches(file, codeSource, findings);
153
+ }
154
+ if (gates.shouldRunSwallowedCatch) {
155
+ analyseSwallowedCatches(file, source, codeSource, findings);
156
+ }
84
157
  }
85
158
 
86
159
  // All per-line checks for a single line in their stable, deterministic emission order. Each helper
87
160
  // either no-ops (rule skipped or no match) or appends to `findings`.
88
161
  function analyseLineRuleContext(context: LineRuleContext): void {
89
- analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings);
90
- analyseReliabilityLine(context.file, context.codeLine, context.lineNumber, context.findings);
91
- pushCommentedOutCodeFinding(context);
92
- pushBooleanPrefixFinding(context);
93
- pushHungarianNotationFindings(context);
94
- pushOptionalChainingFindings(context);
95
- pushNullishCoalescingFindings(context);
96
- pushLooseEqualityFinding(context);
97
- pushStringTimerFinding(context);
98
- analyseSecurityFlowLine(context.file, context.codeLine, context.lineNumber, context.findings);
162
+ if (context.gates.shouldRunTypeSafety) {
163
+ analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings);
164
+ }
165
+ if (context.gates.shouldRunReliability) {
166
+ analyseReliabilityLine(context.file, context.codeLine, context.lineNumber, context.findings);
167
+ }
168
+ if (context.gates.shouldRunCommentedOutCode) {
169
+ pushCommentedOutCodeFinding(context);
170
+ }
171
+ if (context.gates.shouldRunBooleanNaming) {
172
+ pushBooleanPrefixFinding(context);
173
+ }
174
+ if (context.gates.shouldRunHungarianNotation) {
175
+ pushHungarianNotationFindings(context);
176
+ }
177
+ if (context.gates.shouldRunOptionalChaining) {
178
+ pushOptionalChainingFindings(context);
179
+ }
180
+ if (context.gates.shouldRunNullishCoalescing) {
181
+ pushNullishCoalescingFindings(context);
182
+ }
183
+ if (context.gates.shouldRunLooseEquality) {
184
+ pushLooseEqualityFinding(context);
185
+ }
186
+ if (context.gates.shouldRunStringTimer) {
187
+ pushStringTimerFinding(context);
188
+ }
189
+ if (context.gates.shouldRunSecurityFlow) {
190
+ analyseSecurityFlowLine(context.file, context.codeLine, context.lineNumber, context.findings);
191
+ }
99
192
  pushPatternCheckFindings(context);
100
- pushVariableNameFindings(context);
193
+ if (context.gates.shouldRunVariableNaming) {
194
+ pushVariableNameFindings(context);
195
+ }
101
196
  }
102
197
 
103
198
  // Code-shape rules: those that must match against the masked code (no comment or literal noise).
@@ -123,7 +218,7 @@ function literalLineChecks(): LineRuleCheck[] {
123
218
  { ruleId: "security.disabled-tls-verification", pattern: /\b(?:process\.env\.)?NODE_TLS_REJECT_UNAUTHORIZED\b\s*=\s*["']0["']|\brejectUnauthorized\s*:\s*false\b/i, message: "TLS certificate verification is disabled.", severity: "error", pillar: "security" },
124
219
  { ruleId: "security.javascript-url", pattern: /["'`]\s*javascript\s*:(?!\s+URL\b)/i, message: "javascript: URL literal can execute script.", severity: "error", pillar: "security" },
125
220
  { ruleId: "security.proto-access", pattern: /\[\s*["']__proto__["']\s*\]/, message: "Direct __proto__ access can enable prototype pollution.", severity: "warning", pillar: "security" },
126
- { ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
221
+ { ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw|prepare)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
127
222
  { ruleId: "modernisation.date-now-candidate", pattern: /\bnew\s+Date\s*\(\s*\)\s*\.getTime\s*\(\s*\)|\bNumber\s*\(\s*new\s+Date\s*\(\s*\)\s*\)/, message: "Current-time expression can use Date.now().", severity: "advisory", pillar: "modernisation" },
128
223
  { ruleId: "modernisation.object-spread-candidate", pattern: /\bObject\.assign\s*\(\s*\{\s*\}\s*,/, message: "Object.assign clone can usually use object spread.", severity: "advisory", pillar: "modernisation" },
129
224
  { ruleId: "waste.console-log", pattern: /\bconsole\.(log|debug)\s*\(/, message: "console logging is committed in source.", severity: "advisory", pillar: "maintainability" },
@@ -476,7 +571,19 @@ function analyseProcessExecCalls(file: SourceFile, rawSource: string, codeSource
476
571
  if (isSafeProcessExecCall(file, callName, rawSource, start, rawSegment, codeSegment)) {
477
572
  continue;
478
573
  }
479
- findings.push(finding({ ruleId: "security.process-exec", message: "Child-process execution is used; validate arguments are not user-controlled.", file, line: byteLine(codeSource, start), severity: "warning", pillar: "security" }));
574
+ findings.push(
575
+ makeFinding({
576
+ ruleId: "security.process-exec",
577
+ message: "Child-process execution is used; validate arguments are not user-controlled.",
578
+ filePath: file.displayPath,
579
+ line: byteLine(codeSource, start),
580
+ severity: "warning",
581
+ pillar: "security",
582
+ confidence: "high",
583
+ remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled.",
584
+ metadata: processExecMetadata(callName, rawSource, start, rawSegment, codeSegment),
585
+ }),
586
+ );
480
587
  }
481
588
  }
482
589