@blundergoat/gruff-ts 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -11
- package/CONTRIBUTING.md +3 -3
- package/README.md +141 -183
- package/docs/README.md +23 -0
- package/docs/ci-integration.md +63 -0
- package/docs/{CONFIGURATION.md → configuration.md} +41 -20
- package/docs/dashboard.md +36 -0
- package/docs/output-formats.md +65 -0
- package/docs/{RELEASING.md → releasing.md} +17 -14
- package/docs/{REPORTS_AND_CI.md → reports-and-ci.md} +5 -2
- package/docs/rules.md +177 -0
- package/package.json +2 -2
- package/scripts/bump-version.sh +83 -18
- package/scripts/dependency-install.sh +96 -0
- package/scripts/dependency-update.sh +177 -0
- package/scripts/preflight-checks.sh +38 -0
- package/src/analyser.ts +9 -24
- package/src/blocks.ts +66 -12
- package/src/class-rules.ts +5 -6
- package/src/cli-program.ts +216 -39
- package/src/cli.ts +4 -1
- package/src/comment-rules.ts +2 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +155 -29
- package/src/constants.ts +10 -2
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +62 -16
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +17 -0
- package/src/init-config.ts +308 -0
- package/src/line-rules.ts +64 -12
- package/src/naming-pushers.ts +7 -32
- package/src/pillar-summary.ts +129 -0
- package/src/project-config-rules.ts +1 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -406
- package/src/rule-list.ts +65 -1
- package/src/rules.ts +36 -37
- package/src/safety-rules.ts +9 -4
- package/src/scoring.ts +41 -9
- package/src/test-block-rules.ts +43 -1
- package/src/test-fixtures.ts +13 -7
- package/src/text-scans.ts +1 -152
- package/src/types.ts +32 -6
package/src/config.ts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
// Config loading and YAML-subset parsing for the analyzer's zero-dependency rule defaults.
|
|
2
2
|
import { existsSync, readFileSync } from "node:fs";
|
|
3
3
|
import { extname, isAbsolute, join } from "node:path";
|
|
4
|
-
import
|
|
4
|
+
import { ConfigLoadError } from "./config-load-error.ts";
|
|
5
|
+
import type { AnalysisOptions, Config, FailThreshold, MinimumSeverityCommand, Severity } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
// Two common suggestion strings reused across the validators. Hoisted out so a future doc-link
|
|
8
|
+
// or wording tweak lands in one place instead of N throw sites.
|
|
9
|
+
const SUGGEST_INIT_FORCE = "Run `gruff-ts init --force` to regenerate the config from current defaults (preserves your `paths.ignore` and `minimumSeverity:` entries).";
|
|
10
|
+
const SUGGEST_EDIT_CONFIG = "Edit `.gruff-ts.yaml` to use a valid value, or run `gruff-ts init --force` to regenerate from defaults.";
|
|
5
11
|
|
|
6
12
|
type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
|
|
7
13
|
|
|
@@ -26,18 +32,20 @@ const UNMATCHED_YAML_SCALAR: ParsedYamlScalar = { isMatched: false, value: undef
|
|
|
26
32
|
// Built-in defaults applied before any user config overlays. The string lists here (accepted
|
|
27
33
|
// abbreviations, banned generic names, boolean prefixes, …) are the stable rule contract - they
|
|
28
34
|
// shape what every gruff scan emits by default and changing them shifts the public rule surface.
|
|
35
|
+
// schemaVersion is fixed at `gruff-ts.config.v0.1` as the schema invariant for this release.
|
|
29
36
|
function defaultConfig(): Config {
|
|
30
37
|
return {
|
|
38
|
+
schemaVersion: "gruff-ts.config.v0.1",
|
|
31
39
|
ignoredPaths: [],
|
|
32
|
-
acceptedAbbreviations: new Set(["
|
|
40
|
+
acceptedAbbreviations: new Set(["age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
|
|
33
41
|
secretPreviews: new Set(),
|
|
34
42
|
bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
|
|
35
|
-
booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires"]),
|
|
43
|
+
booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires", "allow", "check", "enable", "exclude", "include", "omit", "skip", "with", "without"]),
|
|
36
44
|
hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
|
|
37
45
|
placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
|
|
38
|
-
abbreviationDenylist: new Set(["ctx", "pkg", "opts", "fn", "idx", "cb"]),
|
|
39
46
|
negativeBooleanAllowed: new Set(["nostore", "nofollow", "noreferrer", "noscript", "noindex"]),
|
|
40
47
|
knownAcronyms: new Set(["url", "http", "https", "id", "xml", "json", "html", "css", "api", "sql", "db", "io", "ui", "uuid", "ip", "tcp", "udp", "ast", "cli", "npm"]),
|
|
48
|
+
minimumSeverity: new Map(),
|
|
41
49
|
rules: new Map(),
|
|
42
50
|
};
|
|
43
51
|
}
|
|
@@ -70,15 +78,87 @@ function selectedConfigPath(projectRoot: string, options: AnalysisOptions): stri
|
|
|
70
78
|
return options.config ? absolutize(projectRoot, options.config) : defaultConfigPath(projectRoot);
|
|
71
79
|
}
|
|
72
80
|
|
|
73
|
-
//
|
|
74
|
-
// rules.
|
|
75
|
-
//
|
|
81
|
+
// Top-level sections applied in a fixed order: schemaVersion → minimumSeverity → paths → allowlists
|
|
82
|
+
// → rules. schemaVersion runs first because every later parse depends on the contract version it
|
|
83
|
+
// declares, and minimumSeverity runs next so CLI consumers reading it during normalizeOptions see
|
|
84
|
+
// a populated map. Order does not affect correctness today but the stable application order keeps
|
|
85
|
+
// later overrides predictable if interdependencies are added.
|
|
76
86
|
function applyConfigValues(config: Config, raw: Record<string, unknown>): void {
|
|
87
|
+
applySchemaVersionConfig(raw);
|
|
88
|
+
applyMinimumSeverityConfig(config, raw);
|
|
77
89
|
applyPathConfig(config, raw);
|
|
78
90
|
applyAllowlistConfig(config, raw);
|
|
79
91
|
applyRuleConfig(config, raw);
|
|
80
92
|
}
|
|
81
93
|
|
|
94
|
+
/*
|
|
95
|
+
* Validates the required `schemaVersion` top-level field. Pre-1.0 break: configs missing the field
|
|
96
|
+
* or carrying any other version string are rejected (throws with a documented error listing the
|
|
97
|
+
* supported version) because there is no migration shim under the no-legacy-compat contract. The
|
|
98
|
+
* function does not mutate the loaded config because the only supported value matches
|
|
99
|
+
* `defaultConfig().schemaVersion` already; future versions would extend the union and require a
|
|
100
|
+
* write here. The schema invariant is fixed at `gruff-ts.config.v0.1`.
|
|
101
|
+
*/
|
|
102
|
+
function applySchemaVersionConfig(raw: Record<string, unknown>): void {
|
|
103
|
+
const schemaVersion = raw.schemaVersion;
|
|
104
|
+
if (schemaVersion === undefined) {
|
|
105
|
+
throw new ConfigLoadError('Config must include `schemaVersion: gruff-ts.config.v0.1` at the top.', SUGGEST_INIT_FORCE);
|
|
106
|
+
}
|
|
107
|
+
if (schemaVersion !== "gruff-ts.config.v0.1") {
|
|
108
|
+
throw new ConfigLoadError(`Unsupported schemaVersion: ${JSON.stringify(schemaVersion)}. Supported: "gruff-ts.config.v0.1".`, SUGGEST_INIT_FORCE);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Parses the `minimumSeverity:` block into a Map keyed by command name. Validation throws on
|
|
113
|
+
// `dashboard` specifically (no `--fail-on` flag exists for it), on unknown command keys, and on
|
|
114
|
+
// every non-canonical value. Missing block is allowed - it just leaves the map empty so CLI
|
|
115
|
+
// consumers fall through to the binary default.
|
|
116
|
+
function applyMinimumSeverityConfig(config: Config, raw: Record<string, unknown>): void {
|
|
117
|
+
const block = objectValue(raw.minimumSeverity);
|
|
118
|
+
if (!block) {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
for (const [commandName, value] of Object.entries(block)) {
|
|
122
|
+
config.minimumSeverity.set(assertMinimumSeverityCommand(commandName), parseFailThresholdConfig(value));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/*
|
|
127
|
+
* Validates one `minimumSeverity:` map key. Throws on `dashboard` specifically because the
|
|
128
|
+
* dashboard subcommand has no `--fail-on` flag; accepting the key would silently no-op and
|
|
129
|
+
* operators would expect a gate that never fires. Throws on unknown commands so typos surface at
|
|
130
|
+
* load time instead of as silent CI footguns.
|
|
131
|
+
*/
|
|
132
|
+
function assertMinimumSeverityCommand(commandName: string): MinimumSeverityCommand {
|
|
133
|
+
if (commandName === "dashboard") {
|
|
134
|
+
throw new ConfigLoadError('Unknown command in minimumSeverity: "dashboard". The dashboard subcommand does not currently expose a --fail-on flag; configuring its threshold is not supported.', "Remove the `dashboard:` line from `minimumSeverity:` in `.gruff-ts.yaml`, or open an issue if dashboard should gate.");
|
|
135
|
+
}
|
|
136
|
+
if (commandName === "analyse" || commandName === "summary" || commandName === "report") {
|
|
137
|
+
return commandName;
|
|
138
|
+
}
|
|
139
|
+
throw new ConfigLoadError(`Unknown command in minimumSeverity: ${JSON.stringify(commandName)}. Valid keys: analyse, summary, report.`, SUGGEST_EDIT_CONFIG);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/*
|
|
143
|
+
* Validates one `FailThreshold` value coming from YAML. Throws on every non-canonical value with a
|
|
144
|
+
* clear error listing the four supported strings. `never` is rejected explicitly because earlier
|
|
145
|
+
* cross-port drafts considered it as the off-switch value before the family converged on `none`;
|
|
146
|
+
* guarding against drift back to `never` keeps the cross-port vocabulary aligned.
|
|
147
|
+
*/
|
|
148
|
+
function parseFailThresholdConfig(rawValue: unknown): FailThreshold {
|
|
149
|
+
if (rawValue === "none" || rawValue === "advisory" || rawValue === "warning" || rawValue === "error") {
|
|
150
|
+
return rawValue;
|
|
151
|
+
}
|
|
152
|
+
throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(rawValue)}.`, SUGGEST_EDIT_CONFIG);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Per-command lookup used by the CLI precedence chain (CLI flag > config > binary default).
|
|
156
|
+
// Returns undefined when the user did not configure that command so the caller can fall through
|
|
157
|
+
// to the binary default. Exported so the CLI consumers in `cli-program.ts` can consult it.
|
|
158
|
+
function minimumSeverityFor(config: Config, command: MinimumSeverityCommand): FailThreshold | undefined {
|
|
159
|
+
return config.minimumSeverity.get(command);
|
|
160
|
+
}
|
|
161
|
+
|
|
82
162
|
// Replaces `ignoredPaths` with the user list. Non-string entries are silently dropped - invalid
|
|
83
163
|
// YAML shapes should not abort the analysis run.
|
|
84
164
|
function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
|
|
@@ -100,14 +180,13 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
100
180
|
applyNamingAllowlist(config, allowlists, "booleanPrefixes");
|
|
101
181
|
applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
|
|
102
182
|
applyNamingAllowlist(config, allowlists, "placeholderNames");
|
|
103
|
-
applyNamingAllowlist(config, allowlists, "abbreviationDenylist");
|
|
104
183
|
applyNamingAllowlist(config, allowlists, "negativeBooleanAllowed");
|
|
105
184
|
applyNamingAllowlist(config, allowlists, "knownAcronyms");
|
|
106
185
|
}
|
|
107
186
|
|
|
108
187
|
// Replaces the entire list when the user provides that key - there is no merge with defaults.
|
|
109
188
|
// The "set the whole list" semantic is intentional so users can deliberately empty a list.
|
|
110
|
-
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "
|
|
189
|
+
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
|
|
111
190
|
if (!allowlists || !(key in allowlists)) {
|
|
112
191
|
return;
|
|
113
192
|
}
|
|
@@ -141,18 +220,23 @@ function ruleConfigValue(rule: Record<string, unknown>): RuleOverride {
|
|
|
141
220
|
return ruleOverride;
|
|
142
221
|
}
|
|
143
222
|
|
|
144
|
-
|
|
223
|
+
/*
|
|
224
|
+
* Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
|
|
225
|
+
* many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
|
|
226
|
+
* "must be configured together" gate would block any severity-only override on those rules even
|
|
227
|
+
* though `gruff-ts list-rules <id>` advertises `rules.<id>.severity` as a public knob. Each field
|
|
228
|
+
* is independently optional and falls through to the descriptor default when absent.
|
|
229
|
+
*
|
|
230
|
+
* Throws ConfigLoadError when `threshold` is present but non-numeric, or when `severity` is
|
|
231
|
+
* present but not one of `advisory|warning|error`. Returns silently when both fields are absent
|
|
232
|
+
* (the common case for `enabled`-only or options-only overrides).
|
|
233
|
+
*/
|
|
145
234
|
function assertRuleThresholdConfig(rule: Record<string, unknown>): void {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
if (hasThreshold && typeof rule.threshold !== "number") {
|
|
149
|
-
throw new Error('Rule config key "threshold" must be numeric.');
|
|
150
|
-
}
|
|
151
|
-
if (hasSeverity && !isSeverity(rule.severity)) {
|
|
152
|
-
throw new Error('Rule config key "severity" must be "advisory", "warning", or "error".');
|
|
235
|
+
if ("threshold" in rule && typeof rule.threshold !== "number") {
|
|
236
|
+
throw new ConfigLoadError('Rule config key "threshold" must be numeric.', SUGGEST_EDIT_CONFIG);
|
|
153
237
|
}
|
|
154
|
-
if (
|
|
155
|
-
throw new
|
|
238
|
+
if ("severity" in rule && !isSeverity(rule.severity)) {
|
|
239
|
+
throw new ConfigLoadError('Rule config key "severity" must be "advisory", "warning", or "error".', SUGGEST_EDIT_CONFIG);
|
|
156
240
|
}
|
|
157
241
|
}
|
|
158
242
|
|
|
@@ -206,20 +290,62 @@ function defaultConfigPath(projectRoot: string): string | undefined {
|
|
|
206
290
|
}
|
|
207
291
|
|
|
208
292
|
/*
|
|
209
|
-
* Reads YAML or JSON config and rejects unknown extensions.
|
|
210
|
-
*
|
|
293
|
+
* Reads YAML or JSON config and rejects unknown extensions. Raw IO failures (e.g. `--config <path>`
|
|
294
|
+
* pointing at a missing file) and JSON parse failures are rewrapped as ConfigLoadError so the CLI
|
|
295
|
+
* surface stays uniform - a bare ENOENT or SyntaxError would otherwise bypass the formatted
|
|
296
|
+
* "gruff-ts: config error" stderr path in `runWithConfigErrorHandling`.
|
|
297
|
+
*
|
|
298
|
+
* Throws ConfigLoadError when: the file is missing (ENOENT), the contents are not valid JSON, the
|
|
299
|
+
* YAML subset rejects the file (see parseYamlConfig), or the top-level value is not a mapping.
|
|
211
300
|
*/
|
|
212
301
|
function parseConfigFile(path: string): Record<string, unknown> {
|
|
213
|
-
const source =
|
|
302
|
+
const source = readConfigSource(path);
|
|
214
303
|
const extension = extname(path).toLowerCase();
|
|
215
|
-
const parsed =
|
|
304
|
+
const parsed = parseConfigSource(source, extension, path);
|
|
216
305
|
const config = objectValue(parsed);
|
|
217
306
|
if (!config) {
|
|
218
|
-
throw new
|
|
307
|
+
throw new ConfigLoadError(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`, SUGGEST_INIT_FORCE);
|
|
219
308
|
}
|
|
220
309
|
return config;
|
|
221
310
|
}
|
|
222
311
|
|
|
312
|
+
/*
|
|
313
|
+
* Reads the raw config bytes. Explicit `--config <path>` skips the `defaultConfigPath` existence
|
|
314
|
+
* check, so a typo here would otherwise dump a raw Node stack. Throws ConfigLoadError on ENOENT
|
|
315
|
+
* with a user-actionable suggestion; rethrows every other filesystem error unchanged so an
|
|
316
|
+
* unexpected IO failure still surfaces its native stack for debugging.
|
|
317
|
+
*/
|
|
318
|
+
function readConfigSource(path: string): string {
|
|
319
|
+
try {
|
|
320
|
+
return readFileSync(path, "utf8").replace(/^\uFEFF/, "");
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") {
|
|
323
|
+
throw new ConfigLoadError(`Config file not found: ${path}.`, "Pass --config with an existing path, or omit the flag to use the default lookup.");
|
|
324
|
+
}
|
|
325
|
+
throw error;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Routes to the YAML subset parser or the native JSON parser. Wraps `JSON.parse`'s SyntaxError so
|
|
330
|
+
// a malformed `.gruff.json` surfaces through the same ConfigLoadError channel as YAML failures
|
|
331
|
+
// (parseYamlConfig already throws ConfigLoadError on its own malformed inputs).
|
|
332
|
+
function parseConfigSource(source: string, extension: string, path: string): unknown {
|
|
333
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
334
|
+
return parseYamlConfig(source);
|
|
335
|
+
}
|
|
336
|
+
if (extension !== ".json") {
|
|
337
|
+
return undefined;
|
|
338
|
+
}
|
|
339
|
+
try {
|
|
340
|
+
return JSON.parse(source) as unknown;
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (error instanceof SyntaxError) {
|
|
343
|
+
throw new ConfigLoadError(`Config file is not valid JSON: ${error.message} (${path}).`, SUGGEST_EDIT_CONFIG);
|
|
344
|
+
}
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
223
349
|
// One non-blank, comment-stripped YAML line. `indent` is the column count (spaces only - tabs are
|
|
224
350
|
// rejected upstream) and is the sole signal used to nest blocks. `content` is whitespace-trimmed.
|
|
225
351
|
interface YamlLine {
|
|
@@ -244,7 +370,7 @@ function parseYamlConfig(source: string): Record<string, unknown> {
|
|
|
244
370
|
const parsedDocument = parser.lines.length === 0 ? {} : parseYamlBlock(parser, parser.lines[0]?.indent ?? 0);
|
|
245
371
|
const config = objectValue(parsedDocument);
|
|
246
372
|
if (!config) {
|
|
247
|
-
throw new
|
|
373
|
+
throw new ConfigLoadError("Config YAML must contain a mapping object.", SUGGEST_INIT_FORCE);
|
|
248
374
|
}
|
|
249
375
|
return config;
|
|
250
376
|
}
|
|
@@ -335,7 +461,7 @@ function parseNestedYamlValue(parser: YamlParser, indent: number, fallback: unkn
|
|
|
335
461
|
function yamlKeyValuePair(content: string): [string, string] {
|
|
336
462
|
const pair = splitYamlKeyValue(content);
|
|
337
463
|
if (!pair) {
|
|
338
|
-
throw new
|
|
464
|
+
throw new ConfigLoadError(`Invalid YAML mapping line: "${content}".`, SUGGEST_INIT_FORCE);
|
|
339
465
|
}
|
|
340
466
|
return pair;
|
|
341
467
|
}
|
|
@@ -351,7 +477,7 @@ function isYamlArrayLine(line: YamlLine): boolean {
|
|
|
351
477
|
*/
|
|
352
478
|
function assertYamlIndent(line: YamlLine, indent: number): void {
|
|
353
479
|
if (line.indent > indent) {
|
|
354
|
-
throw new
|
|
480
|
+
throw new ConfigLoadError(`Invalid YAML indentation near "${line.content}".`, SUGGEST_INIT_FORCE);
|
|
355
481
|
}
|
|
356
482
|
}
|
|
357
483
|
|
|
@@ -369,7 +495,7 @@ function yamlLines(source: string): YamlLine[] {
|
|
|
369
495
|
}
|
|
370
496
|
const indentText = withoutComment.match(/^\s*/)?.[0] ?? "";
|
|
371
497
|
if (indentText.includes("\t")) {
|
|
372
|
-
throw new
|
|
498
|
+
throw new ConfigLoadError("Tabs are not supported in gruff YAML config indentation.", SUGGEST_INIT_FORCE);
|
|
373
499
|
}
|
|
374
500
|
lines.push({ indent: indentText.length, content: withoutComment.trimStart() });
|
|
375
501
|
}
|
|
@@ -619,4 +745,4 @@ function isSeverity(configValue: unknown): configValue is Severity {
|
|
|
619
745
|
return configValue === "advisory" || configValue === "warning" || configValue === "error";
|
|
620
746
|
}
|
|
621
747
|
|
|
622
|
-
export { isString, loadConfig, objectValue, optionNumber, ruleEnabled, ruleSeverity, threshold };
|
|
748
|
+
export { defaultConfigPath, isString, loadConfig, minimumSeverityFor, objectValue, optionNumber, parseConfigFile, ruleEnabled, ruleSeverity, threshold };
|
package/src/constants.ts
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
// Shared release constants that keep CLI, reports, and rule catalogue output in sync.
|
|
2
|
-
const VERSION = "0.
|
|
2
|
+
const VERSION = "0.2.0";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
/*
|
|
5
|
+
* Threshold at which the `analyse` text renderer appends a one-line pointer to `gruff-ts summary`.
|
|
6
|
+
* Below 50 a flat list is still browsable; above 50 the operator hits scroll fatigue and needs the
|
|
7
|
+
* per-rule digest. Calibrated against the gruff-ts self-scan (~8 findings) and the goat-flow scan
|
|
8
|
+
* in 2026-05-25 feedback (1643 findings) - the threshold earns its keep at the cross-over.
|
|
9
|
+
*/
|
|
10
|
+
const OUTPUT_VOLUME_HINT_THRESHOLD = 50;
|
|
11
|
+
|
|
12
|
+
export { OUTPUT_VOLUME_HINT_THRESHOLD, VERSION };
|
package/src/dashboard.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Loopback dashboard HTTP surface that renders live analyzer reports without exposing remote scans.
|
|
2
2
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
3
3
|
import { chdir, cwd, stdout } from "node:process";
|
|
4
|
-
import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-
|
|
4
|
+
import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-html.ts";
|
|
5
5
|
import type { AnalysisOptions, AnalysisReport } from "./types.ts";
|
|
6
6
|
|
|
7
7
|
type DashboardAnalyse = (options: AnalysisOptions) => AnalysisReport;
|
package/src/dead-code-rules.ts
CHANGED
|
@@ -31,29 +31,75 @@ export function analyseDeadCode(file: SourceFile, source: string, findings: Find
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
/*
|
|
35
|
+
* Line-by-line walker that resets the terminator flag at every `case:` / `default:` because
|
|
36
|
+
* dead-code detection must respect control-flow boundaries. Each line is walked once in source
|
|
37
|
+
* order; the per-line state-machine update is extracted into `advanceUnreachableState` to keep
|
|
38
|
+
* this loop's branching low. Reports `waste.unreachable-code` with stable, deterministic
|
|
39
|
+
* fingerprint anchors so baselines and report snapshots round-trip without churn.
|
|
40
|
+
*/
|
|
37
41
|
export function analyseUnreachable(file: SourceFile, source: string, findings: Finding[]): void {
|
|
38
|
-
let
|
|
39
|
-
let isInConditionalBranch = false;
|
|
42
|
+
let state: UnreachableScanState = { didPreviousTerminate: false, conditionalParenDepth: 0, isConsequentPending: false };
|
|
40
43
|
source.split(/\r?\n/).forEach((line, index) => {
|
|
41
44
|
const trimmed = line.trim();
|
|
42
45
|
const branchLabel = isBranchLabel(trimmed);
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (isUnreachableStatement(trimmed, didPreviousTerminate, branchLabel)) {
|
|
47
|
-
findings.push(finding({ ruleId: "waste.unreachable-code", message: "Statement appears after a terminating statement.", file, line: index + 1, severity: "warning", pillar: "waste" }));
|
|
46
|
+
const didPriorTerminate = branchLabel ? false : state.didPreviousTerminate;
|
|
47
|
+
if (isUnreachableStatement(trimmed, didPriorTerminate, branchLabel)) {
|
|
48
|
+
findings.push(finding({ ruleId: "waste.unreachable-code", message: "Statement appears after a terminating statement.", file, line: index + 1, severity: "warning", pillar: "maintainability" }));
|
|
48
49
|
}
|
|
49
|
-
|
|
50
|
-
// `if (x)\n return y;\nnextLine` - `nextLine` runs when `x` is falsy. Tracking the prior line's
|
|
51
|
-
// conditional-opener shape suppresses the false positive on compact guard clauses.
|
|
52
|
-
didPreviousTerminate = isTerminatingStatement(trimmed) && !isInConditionalBranch;
|
|
53
|
-
isInConditionalBranch = isBracelessConditionalOpener(trimmed);
|
|
50
|
+
state = advanceUnreachableState(trimmed, { ...state, didPreviousTerminate: didPriorTerminate });
|
|
54
51
|
});
|
|
55
52
|
}
|
|
56
53
|
|
|
54
|
+
// Working state for the unreachable walker. Tracking these three fields together keeps the
|
|
55
|
+
// state-machine transitions explicit and lets the per-line update return a fresh value rather
|
|
56
|
+
// than mutating shared scope.
|
|
57
|
+
interface UnreachableScanState {
|
|
58
|
+
didPreviousTerminate: boolean;
|
|
59
|
+
conditionalParenDepth: number;
|
|
60
|
+
isConsequentPending: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/*
|
|
64
|
+
* Computes the next walker state from the current line. The conditional-context check (inside the
|
|
65
|
+
* predicate parens, or on the consequent line) drives whether a terminator on this line counts as
|
|
66
|
+
* unconditional. Branching is intentional here because the multi-line predicate has three discrete
|
|
67
|
+
* cases: opener line, inside-predicate continuation, and "no longer in a predicate." Splitting
|
|
68
|
+
* them inline would invariably reintroduce the npath the wrapper was trying to avoid.
|
|
69
|
+
*/
|
|
70
|
+
function advanceUnreachableState(trimmed: string, state: UnreachableScanState): UnreachableScanState {
|
|
71
|
+
const isInConditionalBranch = state.conditionalParenDepth > 0 || state.isConsequentPending;
|
|
72
|
+
const didPreviousTerminate = isTerminatingStatement(trimmed) && !isInConditionalBranch;
|
|
73
|
+
if (isBracelessConditionalOpener(trimmed)) {
|
|
74
|
+
const balance = parenBalance(trimmed);
|
|
75
|
+
const conditionalParenDepth = balance > 0 ? balance : 0;
|
|
76
|
+
return { didPreviousTerminate, conditionalParenDepth, isConsequentPending: conditionalParenDepth === 0 };
|
|
77
|
+
}
|
|
78
|
+
if (state.conditionalParenDepth > 0) {
|
|
79
|
+
const conditionalParenDepth = Math.max(0, state.conditionalParenDepth + parenBalance(trimmed));
|
|
80
|
+
return { didPreviousTerminate, conditionalParenDepth, isConsequentPending: conditionalParenDepth === 0 };
|
|
81
|
+
}
|
|
82
|
+
return { didPreviousTerminate, conditionalParenDepth: 0, isConsequentPending: false };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Net paren balance for one line of masked code (opens minus closes). String-literal parens are
|
|
86
|
+
// already blanked upstream by the masker, so the count is reliable for predicate-depth tracking.
|
|
87
|
+
function parenBalance(text: string): number {
|
|
88
|
+
return countChar(text, "(") - countChar(text, ")");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Counts a single character's occurrences without allocating a match array. Used to balance parens
|
|
92
|
+
// across the lines of a multi-line conditional predicate in `analyseUnreachable`.
|
|
93
|
+
function countChar(text: string, character: string): number {
|
|
94
|
+
let count = 0;
|
|
95
|
+
for (const char of text) {
|
|
96
|
+
if (char === character) {
|
|
97
|
+
count += 1;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return count;
|
|
101
|
+
}
|
|
102
|
+
|
|
57
103
|
// Detects single-line conditional/loop openers that begin a one-statement body (no `{`). The next
|
|
58
104
|
// line is the conditional body, so any terminator there is conditional rather than unconditional.
|
|
59
105
|
function isBracelessConditionalOpener(trimmed: string): boolean {
|
|
@@ -165,7 +211,7 @@ function unusedImportFinding(file: SourceFile, name: string, line: number): Find
|
|
|
165
211
|
filePath: file.displayPath,
|
|
166
212
|
line,
|
|
167
213
|
severity: "advisory",
|
|
168
|
-
pillar: "
|
|
214
|
+
pillar: "maintainability",
|
|
169
215
|
confidence: "medium",
|
|
170
216
|
symbol: name,
|
|
171
217
|
remediation: "Remove the unused import.",
|
package/src/doc-rules.ts
CHANGED
|
@@ -50,9 +50,9 @@ export function exportedDeclarations(source: string, codeSource: string): Export
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/*
|
|
53
|
-
* Skips functions and interfaces - those have dedicated rules (`docs.missing-function-doc`,
|
|
54
|
-
* `docs.missing-
|
|
55
|
-
* classes/types/enums without a leading JSDoc-style block comment.
|
|
53
|
+
* Skips functions and interfaces - those have dedicated rules (`docs.missing-exported-function-doc`,
|
|
54
|
+
* `docs.missing-internal-function-doc`, `docs.missing-interface-doc`). Reports the stable
|
|
55
|
+
* `docs.missing-public-doc` finding for classes/types/enums without a leading JSDoc-style block comment.
|
|
56
56
|
*/
|
|
57
57
|
export function pushMissingPublicDocFinding(file: SourceFile, source: string, declaration: ExportedDeclaration, findings: Finding[]): void {
|
|
58
58
|
if (declaration.kind === "function" || declaration.kind === "interface") {
|
package/src/findings-helpers.ts
CHANGED
|
@@ -106,3 +106,20 @@ export function isGenericName(name: string, bannedNames: Set<string>): boolean {
|
|
|
106
106
|
export function escapeRegex(source: string): string {
|
|
107
107
|
return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
108
108
|
}
|
|
109
|
+
|
|
110
|
+
/*
|
|
111
|
+
* Per-rule severity tally for the `summary` Top-N rules block. Walks the findings once and returns
|
|
112
|
+
* a deterministic Map keyed by ruleId carrying total / error / warning / advisory counts. Lets the
|
|
113
|
+
* renderer surface "412 (0 err / 0 warn / 412 adv)" rows without re-scanning findings per row. The
|
|
114
|
+
* count shape mirrors the `summary` schema invariant - total must equal err + warn + adv.
|
|
115
|
+
*/
|
|
116
|
+
export function countRuleSeverities(findings: Finding[]): Map<string, { total: number; error: number; warning: number; advisory: number }> {
|
|
117
|
+
const counts = new Map<string, { total: number; error: number; warning: number; advisory: number }>();
|
|
118
|
+
for (const finding of findings) {
|
|
119
|
+
const entry = counts.get(finding.ruleId) ?? { total: 0, error: 0, warning: 0, advisory: 0 };
|
|
120
|
+
entry.total += 1;
|
|
121
|
+
entry[finding.severity] += 1;
|
|
122
|
+
counts.set(finding.ruleId, entry);
|
|
123
|
+
}
|
|
124
|
+
return counts;
|
|
125
|
+
}
|