@blundergoat/gruff-ts 0.4.0 → 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 +41 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +32 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +15 -0
- package/docs/rules.md +35 -29
- package/package.json +1 -1
- package/src/analyser.ts +163 -53
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +59 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +61 -14
- package/src/cli.ts +1 -0
- 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/discovery.ts +39 -19
- 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 +85 -14
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +54 -5
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +16 -6
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +15 -10
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +55 -4
- package/src/rules.ts +11 -11
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +132 -78
- package/src/source-text.ts +4 -46
- 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 +5 -3
package/src/class-rules.ts
CHANGED
|
@@ -2,60 +2,119 @@
|
|
|
2
2
|
// public-property + readonly candidates, inconsistent casing, acronym case, interface fields.
|
|
3
3
|
// Pulls the declaration walkers and casing helpers out of cli.ts so the orchestrator just calls
|
|
4
4
|
// the entry points.
|
|
5
|
-
import {
|
|
6
|
-
import { type ExportedDeclaration, exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
|
|
5
|
+
import { exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
|
|
7
6
|
import { type SourceFile } from "./discovery.ts";
|
|
8
7
|
import { makeFinding } from "./findings.ts";
|
|
9
|
-
import { fileBaseName, finding, normalizedIdentifier } from "./findings-helpers.ts";
|
|
8
|
+
import { fileBaseName, finding, normalizedIdentifier, parameterNames } from "./findings-helpers.ts";
|
|
10
9
|
import { pushBooleanPrefixAt, pushNegativeBooleanAt, type NamingSurface } from "./naming-pushers.ts";
|
|
10
|
+
import { callableMatchPoints, declarationOwnershipPoints, type IdentifierOwner, type OwnedDeclarationPoint, type ParsedScript } from "./parsed-script.ts";
|
|
11
|
+
import { publicExportDeclarations, type PublicExportDeclaration } from "./public-exports.ts";
|
|
11
12
|
import { byteLine } from "./text-scans.ts";
|
|
12
13
|
import type { Config, Finding } from "./types.ts";
|
|
13
14
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
/*
|
|
16
|
+
* One shared naming observation used by casing and acronym diagnostics. Name, line, and surface
|
|
17
|
+
* preserve the report rows users already saw, while syntax-derived owner fields explain which
|
|
18
|
+
* declaration or lexical scope the casing rule compares.
|
|
19
|
+
*/
|
|
20
|
+
interface DeclaredIdentifier extends IdentifierOwner {
|
|
17
21
|
name: string;
|
|
18
22
|
line: number;
|
|
19
23
|
surface: NamingSurface;
|
|
20
24
|
}
|
|
21
25
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
26
|
+
const MODULE_NAMING_OWNER: IdentifierOwner = { ownerId: "module", ownerKind: "module" };
|
|
27
|
+
|
|
28
|
+
// Adds shared syntax owners to the existing text inventory, preserving every name/line/surface row.
|
|
29
|
+
// The casing and acronym rules receive one ordered inventory without another parse or AST walk.
|
|
30
|
+
export function collectDeclaredIdentifiers(source: string, codeSource: string, parsed: ParsedScript): DeclaredIdentifier[] {
|
|
25
31
|
const inventory: DeclaredIdentifier[] = [];
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
const seenIdentifiers = new Set<string>();
|
|
33
|
+
// Records one identifier per (name, line, surface) so overlapping scans stay de-duplicated.
|
|
34
|
+
const recordIdentifier = (name: string, line: number, surface: NamingSurface, owner: IdentifierOwner): void => {
|
|
35
|
+
// Recovered or unsupported declarations can have no simple name, so users see no row for them.
|
|
36
|
+
if (!name) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const observationKey = `${name}@${line}@${surface}`;
|
|
40
|
+
// Overlapping syntax shapes must still produce only one acronym and casing observation.
|
|
41
|
+
if (seenIdentifiers.has(observationKey)) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
seenIdentifiers.add(observationKey);
|
|
45
|
+
// Module and anonymous-function rows omit ownerName instead of exposing an undefined field.
|
|
46
|
+
inventory.push({
|
|
47
|
+
name,
|
|
48
|
+
line,
|
|
49
|
+
surface,
|
|
50
|
+
ownerId: owner.ownerId,
|
|
51
|
+
ownerKind: owner.ownerKind,
|
|
52
|
+
...(owner.ownerName === undefined ? {} : { ownerName: owner.ownerName }),
|
|
53
|
+
});
|
|
33
54
|
};
|
|
34
55
|
|
|
56
|
+
const declarationOwnership = declarationOwnershipPoints(parsed);
|
|
57
|
+
const variableOwners = declarationOwnerLookup(declarationOwnership.variableDeclarations);
|
|
58
|
+
const contractFieldOwners = declarationOwnerLookup(declarationOwnership.contractFields);
|
|
59
|
+
// The legacy text matcher remains authoritative so acronym inventory contents do not change.
|
|
35
60
|
for (const match of codeSource.matchAll(/\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) {
|
|
36
|
-
|
|
61
|
+
// A recovered match without a capture becomes empty and is rejected by recordIdentifier.
|
|
62
|
+
const name = match[1] ?? "";
|
|
63
|
+
// A missing regex index is a recovered start-of-file match, so line one is the safe anchor.
|
|
64
|
+
const line = byteLine(source, match.index ?? 0);
|
|
65
|
+
// A legacy-only text token has no syntax declaration; module ownership preserves acronym input.
|
|
66
|
+
const declarationOwner = variableOwners.get(declarationOwnerKey(name, line)) ?? MODULE_NAMING_OWNER;
|
|
67
|
+
recordIdentifier(name, line, "declaration", declarationOwner);
|
|
37
68
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
69
|
+
// Shared callable points retain one-block-per-line order and the existing parameter text policy.
|
|
70
|
+
for (const callable of callableMatchPoints(parsed)) {
|
|
71
|
+
// Every simple parameter belongs to the callable users see as its nearest naming boundary.
|
|
72
|
+
for (const parameter of parameterNames(callable.params)) {
|
|
73
|
+
recordIdentifier(parameter.name, callable.lineIndex + 1, "parameter", callable);
|
|
41
74
|
}
|
|
42
75
|
}
|
|
43
|
-
|
|
44
|
-
|
|
76
|
+
// The existing contract walker remains last, preserving the shared inventory sequence exactly.
|
|
77
|
+
for (const field of collectInterfaceFieldDeclarations(source, codeSource)) {
|
|
78
|
+
// A recovered field without an AST point stays visible to acronym checks under module fallback.
|
|
79
|
+
const contractFieldOwner = contractFieldOwners.get(declarationOwnerKey(field.name, field.line)) ?? MODULE_NAMING_OWNER;
|
|
80
|
+
recordIdentifier(field.name, field.line, "interface-field", contractFieldOwner);
|
|
45
81
|
}
|
|
46
82
|
return inventory;
|
|
47
83
|
}
|
|
48
84
|
|
|
49
|
-
//
|
|
50
|
-
|
|
51
|
-
|
|
85
|
+
// Indexes syntax owners by the legacy name/line tuple so text observations gain stable ownership.
|
|
86
|
+
function declarationOwnerLookup(declarations: OwnedDeclarationPoint[]): Map<string, IdentifierOwner> {
|
|
87
|
+
const owners = new Map<string, IdentifierOwner>();
|
|
88
|
+
// Source order wins when recovered syntax produces duplicate name/line rows, matching de-duplication.
|
|
89
|
+
for (const declaration of declarations) {
|
|
90
|
+
const ownerKey = declarationOwnerKey(declaration.name, declaration.line);
|
|
91
|
+
// The first syntax declaration is the same observation the legacy inventory retains.
|
|
92
|
+
if (!owners.has(ownerKey)) {
|
|
93
|
+
owners.set(ownerKey, declaration);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return owners;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Builds the stable lookup tuple shared by syntax owner rows and legacy text observations.
|
|
100
|
+
function declarationOwnerKey(name: string, line: number): string {
|
|
101
|
+
return `${name}@${line}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Walks existing interface/type body lines so owner enrichment cannot expand acronym coverage.
|
|
105
|
+
function collectInterfaceFieldDeclarations(source: string, codeSource: string): Array<{ name: string; line: number }> {
|
|
52
106
|
const fieldRegex = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/;
|
|
53
|
-
const
|
|
107
|
+
const declarations: Array<{ name: string; line: number }> = [];
|
|
108
|
+
// Each direct body line retains the same source order and line anchor as previous reports.
|
|
54
109
|
for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
|
|
110
|
+
// A line without the supported field prefix produces an empty name and no inventory row.
|
|
55
111
|
const name = sourceLine.match(fieldRegex)?.[1] ?? "";
|
|
56
|
-
|
|
112
|
+
// Unsupported or recovered field syntax has no user-facing identifier row.
|
|
113
|
+
if (name) {
|
|
114
|
+
declarations.push({ name, line: lineIndex + 1 });
|
|
115
|
+
}
|
|
57
116
|
}
|
|
58
|
-
return
|
|
117
|
+
return declarations;
|
|
59
118
|
}
|
|
60
119
|
|
|
61
120
|
// Strips separators only so `userId`, `user_id`, and `userID` collapse, while `adr013` and
|
|
@@ -66,14 +125,16 @@ function casingCanonicalKey(name: string): string {
|
|
|
66
125
|
}
|
|
67
126
|
|
|
68
127
|
/*
|
|
69
|
-
* Groups identifiers by canonical key, then filters
|
|
70
|
-
* split
|
|
71
|
-
*
|
|
72
|
-
* never throws; it
|
|
128
|
+
* Groups identifiers by owner and canonical key, then filters boundary surfaces before reporting.
|
|
129
|
+
* The split flow preserves drift inside one user-reviewed scope while refusing to command rewrites
|
|
130
|
+
* across DTO/UI contracts, functions, constants, or intentionally-unused `_` names. Error behavior:
|
|
131
|
+
* never throws; it appends findings only. Invariant: one owner-key group yields at most one finding.
|
|
73
132
|
*/
|
|
74
|
-
export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], findings: Finding[]): void {
|
|
133
|
+
export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
|
|
134
|
+
// Each owner-key group can produce at most one actionable diagnostic for the CLI user.
|
|
75
135
|
for (const entries of declaredIdentifierGroups(inventory).values()) {
|
|
76
|
-
const candidate = inconsistentCasingCandidate(entries);
|
|
136
|
+
const candidate = inconsistentCasingCandidate(entries, config.acceptedCasingPairs);
|
|
137
|
+
// A single spelling after boundary filtering means the reviewed scope is already consistent.
|
|
77
138
|
if (!candidate) {
|
|
78
139
|
continue;
|
|
79
140
|
}
|
|
@@ -81,21 +142,33 @@ export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredI
|
|
|
81
142
|
}
|
|
82
143
|
}
|
|
83
144
|
|
|
84
|
-
//
|
|
145
|
+
// Exact pair exemptions are case-insensitive but retain separators.
|
|
146
|
+
function isAcceptedCasingPair(first: DeclaredIdentifier, second: DeclaredIdentifier, acceptedPairs: Set<string>): boolean {
|
|
147
|
+
const forward = `${first.name}:${second.name}`.toLowerCase();
|
|
148
|
+
const reverse = `${second.name}:${first.name}`.toLowerCase();
|
|
149
|
+
return acceptedPairs.has(forward) || acceptedPairs.has(reverse);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Builds owner-plus-canonical groups once so the reporting pass cannot compare unrelated surfaces.
|
|
85
153
|
function declaredIdentifierGroups(inventory: DeclaredIdentifier[]): Map<string, DeclaredIdentifier[]> {
|
|
86
154
|
const groups = new Map<string, DeclaredIdentifier[]>();
|
|
155
|
+
// Every inventory row keeps its existing source order inside its deterministic owner boundary.
|
|
87
156
|
for (const entry of inventory) {
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
157
|
+
const canonicalKey = casingCanonicalKey(entry.name);
|
|
158
|
+
// A recovered empty identifier has no comparison key and cannot help a user fix casing.
|
|
159
|
+
if (!canonicalKey) {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const ownerKey = `${entry.ownerId}\0${canonicalKey}`;
|
|
163
|
+
const list = groups.get(ownerKey) ?? [];
|
|
91
164
|
list.push(entry);
|
|
92
|
-
groups.set(
|
|
165
|
+
groups.set(ownerKey, list);
|
|
93
166
|
}
|
|
94
167
|
return groups;
|
|
95
168
|
}
|
|
96
169
|
|
|
97
170
|
// Invariant: returns the exact variant pair to report after boundary-aware suppression has run.
|
|
98
|
-
function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
|
|
171
|
+
function inconsistentCasingCandidate(entries: DeclaredIdentifier[], acceptedPairs: Set<string>): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
|
|
99
172
|
const reportableEntries = casingReportableEntries(entries);
|
|
100
173
|
const sameSurfaceEntries = sameCasingSurfaceEntries(reportableEntries);
|
|
101
174
|
const surfaces = [...new Set(sameSurfaceEntries.map((entry) => entry.name))].sort();
|
|
@@ -103,27 +176,58 @@ function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: De
|
|
|
103
176
|
return undefined;
|
|
104
177
|
}
|
|
105
178
|
const sorted = [...sameSurfaceEntries].sort((a, b) => a.line - b.line);
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
179
|
+
for (let firstIndex = 0; firstIndex < sorted.length; firstIndex += 1) {
|
|
180
|
+
const first = sorted[firstIndex];
|
|
181
|
+
if (!first) {
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
const second = sorted.find((entry, secondIndex) => secondIndex > firstIndex && entry.name !== first.name && !isAcceptedCasingPair(first, entry, acceptedPairs));
|
|
185
|
+
if (second) {
|
|
186
|
+
return { first, second, surfaces };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
109
190
|
}
|
|
110
191
|
|
|
111
192
|
// Builds the stable finding after candidate selection so fingerprint shape stays in one place.
|
|
112
193
|
function inconsistentCasingFinding(file: SourceFile, candidate: { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] }): Finding {
|
|
194
|
+
const ownerLabel = casingOwnerLabel(candidate.first);
|
|
113
195
|
return makeFinding({
|
|
114
196
|
ruleId: "naming.inconsistent-casing",
|
|
115
|
-
message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\`
|
|
197
|
+
message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` within ${ownerLabel}.`,
|
|
116
198
|
filePath: file.displayPath,
|
|
117
199
|
line: candidate.second.line,
|
|
118
200
|
severity: "advisory",
|
|
119
201
|
pillar: "naming",
|
|
120
202
|
confidence: "medium",
|
|
121
203
|
symbol: candidate.second.name,
|
|
122
|
-
remediation:
|
|
123
|
-
metadata: {
|
|
204
|
+
remediation: `Choose one form within ${ownerLabel}, or add the exact alias pair to allowlists.acceptedCasingPairs.`,
|
|
205
|
+
metadata: {
|
|
206
|
+
variants: candidate.surfaces,
|
|
207
|
+
ownerId: candidate.first.ownerId,
|
|
208
|
+
ownerKind: candidate.first.ownerKind,
|
|
209
|
+
...(candidate.first.ownerName === undefined ? {} : { ownerName: candidate.first.ownerName }),
|
|
210
|
+
},
|
|
124
211
|
});
|
|
125
212
|
}
|
|
126
213
|
|
|
214
|
+
// Describes the comparison boundary in the same language a CLI user sees in source and reports.
|
|
215
|
+
function casingOwnerLabel(owner: IdentifierOwner): string {
|
|
216
|
+
switch (owner.ownerKind) {
|
|
217
|
+
case "module":
|
|
218
|
+
return "the module scope";
|
|
219
|
+
case "function":
|
|
220
|
+
// Anonymous callbacks still give users a precise lexical boundary without a made-up name.
|
|
221
|
+
return owner.ownerName ? `function \`${owner.ownerName}\`` : "the containing function";
|
|
222
|
+
case "interface":
|
|
223
|
+
// Recovered contract names are absent only on malformed source, where a neutral label is safer.
|
|
224
|
+
return `interface \`${owner.ownerName ?? "anonymous"}\``;
|
|
225
|
+
case "type-literal":
|
|
226
|
+
// Named aliases normally supply this label; malformed source falls back without throwing.
|
|
227
|
+
return `type literal \`${owner.ownerName ?? "anonymous"}\``;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
127
231
|
// `_event` is the standard intentionally-unused spelling; comparing it with `event` would tell an
|
|
128
232
|
// agent to remove useful boundary information rather than fix casing drift.
|
|
129
233
|
function casingReportableEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
|
|
@@ -169,10 +273,13 @@ function acronymCaseClass(token: string): "upper" | "lower" | "title" {
|
|
|
169
273
|
}
|
|
170
274
|
|
|
171
275
|
/*
|
|
172
|
-
* Reports when an acronym from `config.knownAcronyms` appears as all-caps plus another case form
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
276
|
+
* Reports when an acronym from `config.knownAcronyms` appears as all-caps plus another case form
|
|
277
|
+
* among names whose casing the author chose. SCREAMING_SNAKE constants and all-lower names are
|
|
278
|
+
* excluded because their convention fixes the acronym's case - a `RAW_HTML_TAGS` constant beside
|
|
279
|
+
* `startsHtmlBlock` is standard TypeScript, not drift. The all-caps gate exists because
|
|
280
|
+
* lower/title-only forms like `apiToken` beside `googleApiKey` are idiomatic enough to avoid
|
|
281
|
+
* noisy findings. Like `analyseInconsistentCasing`, the finding anchors on the second occurrence
|
|
282
|
+
* so the stable fingerprint sticks to the divergence.
|
|
176
283
|
*/
|
|
177
284
|
export function analyseAcronymCase(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
|
|
178
285
|
const observed = new Map<string, Map<string, { name: string; line: number }>>();
|
|
@@ -184,9 +291,10 @@ export function analyseAcronymCase(file: SourceFile, inventory: DeclaredIdentifi
|
|
|
184
291
|
}
|
|
185
292
|
}
|
|
186
293
|
|
|
187
|
-
// Adds one identifier's acronym tokens to the observed case map, skipping fixture-only constants
|
|
294
|
+
// Adds one identifier's acronym tokens to the observed case map, skipping fixture-only constants
|
|
295
|
+
// and names whose acronym casing the convention already fixes.
|
|
188
296
|
function recordAcronymCases(observed: Map<string, Map<string, { name: string; line: number }>>, config: Config, entry: DeclaredIdentifier): void {
|
|
189
|
-
if (isFixtureIdentifier(entry.name)) {
|
|
297
|
+
if (isFixtureIdentifier(entry.name) || isConventionForcedAcronymCasing(entry.name)) {
|
|
190
298
|
return;
|
|
191
299
|
}
|
|
192
300
|
for (const token of tokensForAcronymCheck(entry.name)) {
|
|
@@ -236,6 +344,13 @@ function isFixtureIdentifier(name: string): boolean {
|
|
|
236
344
|
return /(?:^|[_-])fixture(?:[_-]|$)/i.test(name);
|
|
237
345
|
}
|
|
238
346
|
|
|
347
|
+
// SCREAMING_SNAKE constants and all-lower names cannot choose an acronym casing - the convention
|
|
348
|
+
// fixes it - so they carry no drift signal against camelCase/PascalCase names, where the author
|
|
349
|
+
// does choose (`parsedHtml` versus `rawHTML`). Only chosen casings are compared file-wide.
|
|
350
|
+
function isConventionForcedAcronymCasing(name: string): boolean {
|
|
351
|
+
return isScreamingConstant(name) || name === name.toLowerCase();
|
|
352
|
+
}
|
|
353
|
+
|
|
239
354
|
/*
|
|
240
355
|
* Walks every interface field and runs two checks per boolean field: boolean prefix and
|
|
241
356
|
* negative boolean. The stable ordering matches `pushBooleanPrefixAt` → `pushNegativeBooleanAt`
|
|
@@ -256,24 +371,32 @@ export function analyseInterfaceFields(file: SourceFile, source: string, codeSou
|
|
|
256
371
|
|
|
257
372
|
const INTERFACE_HEADER_REGEX = /\b(?:export\s+)?(?:interface\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?(?:\s+extends\s+[^{]+)?|type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*)\s*\{/g;
|
|
258
373
|
|
|
374
|
+
// Streams the depth-1 member lines of every interface/type-literal body so the field rules see
|
|
375
|
+
// each declaration exactly once. Mapped types (`{ [K in ...] }`) are skipped - no field names there.
|
|
259
376
|
function* walkInterfaceBodyLines(source: string, codeSource: string): Generator<{ lineIndex: number; sourceLine: string }> {
|
|
260
377
|
const codeLines = codeSource.split(/\r?\n/);
|
|
261
378
|
const sourceLines = source.split(/\r?\n/);
|
|
262
379
|
for (const header of codeSource.matchAll(INTERFACE_HEADER_REGEX)) {
|
|
263
380
|
const headerEnd = (header.index ?? 0) + header[0].length;
|
|
381
|
+
// An index-signature-first body is a mapped type, not a field list the naming rules can judge.
|
|
264
382
|
if (codeSource.slice(headerEnd, headerEnd + 30).trimStart().startsWith("[")) {
|
|
265
383
|
continue;
|
|
266
384
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
385
|
+
yield* interfaceBodyMemberLines(codeLines, sourceLines, byteLine(source, headerEnd - 1) - 1);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// Walks one body from its header line, yielding lines while brace depth stays at the member level.
|
|
390
|
+
function* interfaceBodyMemberLines(codeLines: string[], sourceLines: string[], headerLineIndex: number): Generator<{ lineIndex: number; sourceLine: string }> {
|
|
391
|
+
const headerLine = codeLines[headerLineIndex] ?? "";
|
|
392
|
+
let depth = 1 + countBraceChange(headerLine.slice(headerLine.lastIndexOf("{") + 1));
|
|
393
|
+
for (let lineIndex = headerLineIndex + 1; depth > 0 && lineIndex < codeLines.length; lineIndex += 1) {
|
|
394
|
+
const codeLine = codeLines[lineIndex] ?? "";
|
|
395
|
+
// Depth 1 means we are directly inside the declaration body, where the member lines live.
|
|
396
|
+
if (depth === 1) {
|
|
397
|
+
yield { lineIndex, sourceLine: sourceLines[lineIndex] ?? "" };
|
|
276
398
|
}
|
|
399
|
+
depth += countBraceChange(codeLine);
|
|
277
400
|
}
|
|
278
401
|
}
|
|
279
402
|
|
|
@@ -295,32 +418,54 @@ function countBraceChange(text: string): number {
|
|
|
295
418
|
* Three class-pillar rules in their stable, deterministic emission order: exported-declaration
|
|
296
419
|
* docs and file-name mismatch, public-property, readonly candidates.
|
|
297
420
|
*/
|
|
298
|
-
export function analyseClassRules(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
|
|
299
|
-
analyseExportedDeclarations(file, source, codeSource, findings);
|
|
421
|
+
export function analyseClassRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
|
|
422
|
+
analyseExportedDeclarations(file, source, codeSource, config, findings, parsed);
|
|
300
423
|
analysePublicProperties(file, source, codeSource, findings);
|
|
301
424
|
analyseReadonlyCandidates(file, source, codeSource, findings);
|
|
302
425
|
}
|
|
303
426
|
|
|
304
427
|
/*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
* findings per declaration.
|
|
428
|
+
* Keeps public-doc checks on direct exports, then evaluates class/file naming against the complete
|
|
429
|
+
* syntax inventory so reports cover default/re-export forms without changing the documentation contract.
|
|
308
430
|
*/
|
|
309
|
-
function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
|
|
310
|
-
|
|
431
|
+
function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
|
|
432
|
+
const directlyExportedDeclarations = exportedDeclarations(source, codeSource);
|
|
433
|
+
// Public-doc findings retain their existing direct-export policy and deterministic source order.
|
|
434
|
+
for (const declaration of directlyExportedDeclarations) {
|
|
311
435
|
pushMissingPublicDocFinding(file, source, declaration, findings);
|
|
312
|
-
pushClassFileMismatchFinding(file, declaration, findings);
|
|
313
436
|
}
|
|
437
|
+
// Direct internal callers without a parse retain the legacy five-kind inventory; normal scans use syntax.
|
|
438
|
+
const modulePublicDeclarations = parsed
|
|
439
|
+
? publicExportDeclarations(parsed)
|
|
440
|
+
: directlyExportedDeclarations.map((declaration) => ({ ...declaration, kind: declaration.kind as PublicExportDeclaration["kind"] }));
|
|
441
|
+
pushClassFileMismatchFinding(file, modulePublicDeclarations, config, findings);
|
|
314
442
|
}
|
|
315
443
|
|
|
316
444
|
/*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
* from the file name.
|
|
445
|
+
* Reports a normalized class/file mismatch only when one named class is the module's sole public
|
|
446
|
+
* declaration, keeping feature modules quiet while preserving the stable finding anchor.
|
|
320
447
|
*/
|
|
321
|
-
function pushClassFileMismatchFinding(file: SourceFile,
|
|
448
|
+
function pushClassFileMismatchFinding(file: SourceFile, publicDeclarations: PublicExportDeclaration[], config: Config, findings: Finding[]): void {
|
|
449
|
+
// Feature modules with a second public declaration do not claim one primary class-to-file convention.
|
|
450
|
+
if (publicDeclarations.length !== 1) {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
const declaration = publicDeclarations[0];
|
|
454
|
+
// Anonymous defaults and non-class exports have no named class for a user to align with the file.
|
|
455
|
+
if (!declaration || declaration.kind !== "class" || declaration.name === "default") {
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
322
458
|
const fileName = fileBaseName(file.displayPath);
|
|
323
|
-
|
|
459
|
+
const acceptedPair = `${fileName}:${declaration.name}`.toLowerCase();
|
|
460
|
+
// Pair-level configuration preserves an intentional feature-file/class-role convention narrowly.
|
|
461
|
+
if (config.acceptedClassFilePairs.has(acceptedPair)) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
// A normalized name match already lets a report user locate the class from the file name. An
|
|
465
|
+
// alias counts too: `export { Foo as Bar }` in `bar.ts` already advertises the matching name, so
|
|
466
|
+
// telling the reader to rename would undo an alignment they have made.
|
|
467
|
+
const publicNames = declaration.exportedName === undefined ? [declaration.name] : [declaration.name, declaration.exportedName];
|
|
468
|
+
if (publicNames.some((publicName) => normalizedIdentifier(publicName) === normalizedIdentifier(fileName))) {
|
|
324
469
|
return;
|
|
325
470
|
}
|
|
326
471
|
findings.push(
|
|
@@ -333,8 +478,13 @@ function pushClassFileMismatchFinding(file: SourceFile, declaration: ExportedDec
|
|
|
333
478
|
pillar: "naming",
|
|
334
479
|
confidence: "medium",
|
|
335
480
|
symbol: declaration.name,
|
|
336
|
-
remediation: "Rename the class or file
|
|
337
|
-
metadata: {
|
|
481
|
+
remediation: "Rename the class or file, or add the exact fileBase:ClassName pair to allowlists.acceptedClassFilePairs.",
|
|
482
|
+
metadata: {
|
|
483
|
+
className: declaration.name,
|
|
484
|
+
fileName,
|
|
485
|
+
candidatePrimaryExport: true,
|
|
486
|
+
publicExports: publicDeclarations.map((publicDeclaration) => `${publicDeclaration.kind}:${publicDeclaration.name}`).sort(),
|
|
487
|
+
},
|
|
338
488
|
}),
|
|
339
489
|
);
|
|
340
490
|
}
|
package/src/cli-program.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { ConfigLoadError } from "./config-load-error.ts";
|
|
|
10
10
|
import { loadConfig, minimumSeverityFor } from "./config.ts";
|
|
11
11
|
import { VERSION } from "./constants.ts";
|
|
12
12
|
import { startDashboard } from "./dashboard.ts";
|
|
13
|
-
import { renderHookCapabilities, renderHookConfigError, renderHookReport } from "./hook-contract.ts";
|
|
13
|
+
import { hookRenderedDiagnosticsCount, renderHookCapabilities, renderHookConfigError, renderHookReport } from "./hook-contract.ts";
|
|
14
14
|
import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
|
|
15
15
|
import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
|
|
16
16
|
import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
@@ -183,14 +183,14 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
183
183
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
184
184
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
185
185
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
186
|
-
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", "text")
|
|
187
|
-
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
186
|
+
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", parseAnalyseFormat, "text")
|
|
187
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "advisory")
|
|
188
188
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
189
189
|
.option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
|
|
190
190
|
.option("--since <ref>", "Filter findings to regions changed against a git base ref.")
|
|
191
191
|
.option("--diff [mode]", "Filter findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
192
|
-
.option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", "symbol")
|
|
193
|
-
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
192
|
+
.option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", parseChangedScope, "symbol")
|
|
193
|
+
.option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff, --since, and --changed-ranges).")
|
|
194
194
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
195
195
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
196
196
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
@@ -246,6 +246,7 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
|
|
|
246
246
|
.option("--since <ref>", "Filter hook findings to regions changed against a git base ref and compare against that ref.")
|
|
247
247
|
.option("--diff [mode]", "Filter hook findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
248
248
|
.option("--baseline <path>", "Compare hook findings against a gruff baseline JSON file using stableIdentity.")
|
|
249
|
+
.option("--fail-on-diagnostics", "Exit 2 when parse/read diagnostics affect the analysed change; the default reports them in-band with exit 0.")
|
|
249
250
|
.action((paths: string[], rawOptions: Record<string, unknown>) => {
|
|
250
251
|
if (rawOptions.capabilities === true) {
|
|
251
252
|
writeCommandOutput(program, renderHookCapabilities());
|
|
@@ -255,14 +256,17 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
|
|
|
255
256
|
try {
|
|
256
257
|
const scopedOptions = hookScopedOptions(paths, rawOptions);
|
|
257
258
|
const currentOptions = hookCurrentOptions(scopedOptions);
|
|
258
|
-
|
|
259
|
+
const rendered = renderHookReport(runAnalyse, {
|
|
259
260
|
currentOptions,
|
|
260
261
|
scopedOptions,
|
|
261
262
|
...hookBaselinePath(rawOptions),
|
|
262
263
|
...hookDiffBase(scopedOptions),
|
|
263
264
|
hasChangedRegion: hasHookChangedRegion(scopedOptions),
|
|
264
|
-
})
|
|
265
|
-
|
|
265
|
+
});
|
|
266
|
+
writeCommandOutput(program, rendered);
|
|
267
|
+
// Explicit consumer request (gruff.hook.v1): only --fail-on-diagnostics turns in-band
|
|
268
|
+
// diagnostics into exit 2; every other successful hook run keeps the documented exit 0.
|
|
269
|
+
process.exitCode = rawOptions.failOnDiagnostics === true && hookRenderedDiagnosticsCount(rendered) > 0 ? 2 : 0;
|
|
266
270
|
} catch (error) {
|
|
267
271
|
if (error instanceof ConfigLoadError) {
|
|
268
272
|
writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
|
|
@@ -320,6 +324,7 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
|
|
|
320
324
|
.option("--port <port>", "Port to bind.", "8767")
|
|
321
325
|
.option("--project-root <path>", "Default project root.", ".")
|
|
322
326
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
327
|
+
.option("--scan-timeout <seconds>", "Accepted for cross-port compatibility; not implemented in gruff-ts.")
|
|
323
328
|
.action(async (rawOptions: Record<string, unknown>) => {
|
|
324
329
|
const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
|
|
325
330
|
await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
|
|
@@ -418,12 +423,12 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
|
|
|
418
423
|
.command("report")
|
|
419
424
|
.description("Render a gruff report to stdout or a file.")
|
|
420
425
|
.argument("[paths...]", "Files or directories to analyse.")
|
|
421
|
-
.option("--format <format>", "Report format: html or json.", "html")
|
|
426
|
+
.option("--format <format>", "Report format: html or json.", parseReportFormat, "html")
|
|
422
427
|
.option("--output <path>", "Write report to a file.")
|
|
423
428
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
424
429
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
425
430
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
426
|
-
.option("--fail-on <severity>", "Finding severity that fails the run.", "none")
|
|
431
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "none")
|
|
427
432
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
428
433
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
429
434
|
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
@@ -457,10 +462,10 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
457
462
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
458
463
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
459
464
|
.option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
|
|
460
|
-
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
465
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "advisory")
|
|
461
466
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
462
467
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
463
|
-
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
468
|
+
.option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff).")
|
|
464
469
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
465
470
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
466
471
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
@@ -505,6 +510,27 @@ function parseHookFormat(rawFormat: string): "json" {
|
|
|
505
510
|
throw new InvalidArgumentError("must be json");
|
|
506
511
|
}
|
|
507
512
|
|
|
513
|
+
/*
|
|
514
|
+
* Builds a commander argParser for one constrained-choice option. Governance controls (format,
|
|
515
|
+
* failure severity, diff scope) must reject a misspelled value as a usage error before analysis
|
|
516
|
+
* starts - a silent fallback would let CI pass under semantics the caller never asked for.
|
|
517
|
+
*/
|
|
518
|
+
function parseChoiceOf(choices: readonly string[]): (rawValue: string) => string {
|
|
519
|
+
// Validates one raw CLI value against the documented set; throws InvalidArgumentError otherwise.
|
|
520
|
+
return (rawValue: string): string => {
|
|
521
|
+
// A value outside the documented set is a caller mistake, never a silent default.
|
|
522
|
+
if (choices.includes(rawValue)) {
|
|
523
|
+
return rawValue;
|
|
524
|
+
}
|
|
525
|
+
throw new InvalidArgumentError(`must be one of: ${choices.join(", ")}`);
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const parseAnalyseFormat = parseChoiceOf(["text", "json", "html", "markdown", "github", "hotspot", "sarif"]);
|
|
530
|
+
const parseReportFormat = parseChoiceOf(["html", "json"]);
|
|
531
|
+
const parseFailOn = parseChoiceOf(["none", "advisory", "warning", "error"]);
|
|
532
|
+
const parseChangedScope = parseChoiceOf(["symbol", "hunk", "file"]);
|
|
533
|
+
|
|
508
534
|
/*
|
|
509
535
|
* Commander argParser for `--top`-style numeric flags. Throws `InvalidArgumentError` on non-integer
|
|
510
536
|
* or negative input so commander reports a usage error and exits non-zero before the command runs.
|
|
@@ -530,6 +556,7 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
|
530
556
|
// two CLI invocations producing identical AnalysisOptions must produce identical, stable findings -
|
|
531
557
|
// adding new fields here without folding them into that hash is a deterministic-output regression.
|
|
532
558
|
function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
|
|
559
|
+
assertFullScanHistoryOptions(rawOptions);
|
|
533
560
|
const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
|
|
534
561
|
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
|
|
535
562
|
const diffInput = diffOption(paths, rawOptions);
|
|
@@ -559,6 +586,24 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
559
586
|
};
|
|
560
587
|
}
|
|
561
588
|
|
|
589
|
+
/*
|
|
590
|
+
* Rejects a history path paired with any changed-region selector before analysis or rendering.
|
|
591
|
+
* Throws ConfigLoadError so analyse and summary emit the same exit-2 guidance with no stdout.
|
|
592
|
+
*/
|
|
593
|
+
function assertFullScanHistoryOptions(rawOptions: Record<string, unknown>): void {
|
|
594
|
+
const hasChangedRegionSelector = rawOptions.diff === true
|
|
595
|
+
|| typeof rawOptions.diff === "string"
|
|
596
|
+
|| typeof rawOptions.since === "string"
|
|
597
|
+
|| typeof rawOptions.changedRanges === "string";
|
|
598
|
+
// A filtered request would mix partial scores into the full-project trend users review.
|
|
599
|
+
if (typeof rawOptions.historyFile === "string" && hasChangedRegionSelector) {
|
|
600
|
+
throw new ConfigLoadError(
|
|
601
|
+
"`--history-file` requires a full scan and cannot be combined with `--diff`, `--since`, or `--changed-ranges`.",
|
|
602
|
+
"Remove the changed-region option, or omit `--history-file` for this filtered scan.",
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
562
607
|
// Builds the scoped (changed-region) analysis options for the hook: JSON output, no fail-on gate,
|
|
563
608
|
// symbol scope, and no analysis baseline.
|
|
564
609
|
function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
@@ -654,8 +699,10 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
|
|
|
654
699
|
return rawOptions.generateBaseline === true ? { generateBaseline: DEFAULT_BASELINE } : {};
|
|
655
700
|
}
|
|
656
701
|
|
|
657
|
-
|
|
658
|
-
|
|
702
|
+
// Last-resort choice normalizer for programmatic option bags; the CLI surfaces validate the same
|
|
703
|
+
// sets at parse time, so this fallback only guards direct `normalizeOptions` callers.
|
|
704
|
+
function stringChoice<T extends string>(rawValue: unknown, choices: readonly T[], fallback: T): T {
|
|
705
|
+
return typeof rawValue === "string" && choices.includes(rawValue as T) ? (rawValue as T) : fallback;
|
|
659
706
|
}
|
|
660
707
|
|
|
661
708
|
/*
|
package/src/cli.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { ruleDescriptors } from "./rules.ts";
|
|
|
11
11
|
export type { AnalysisReport, Finding, OutputFormat, Pillar, RuleDescriptor, Severity } from "./types.ts";
|
|
12
12
|
|
|
13
13
|
const analyseRunner = Object.assign(analyse, { hookViews: analyseHookReports });
|
|
14
|
+
// Builds the commander program with the optimized hook-view runner already attached.
|
|
14
15
|
const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyseRunner);
|
|
15
16
|
|
|
16
17
|
if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
|