@blundergoat/gruff-ts 0.5.0 → 0.6.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -0,0 +1,359 @@
1
+ // Finds file-local groups of three or more structurally identical tests that can be consolidated into a table-driven test.
2
+ //
3
+ // Follows FAMILY-CONTRACT section 16 using the shared syntax tree so existing callable discovery stays unchanged.
4
+ // Emits advisory, low-confidence consolidation candidates anchored at the first test while listing every group member in order.
5
+ import { createRequire } from "node:module";
6
+ import type { Node, Expression, CallExpression, ArrowFunction, FunctionExpression, SourceFile as SyntaxFile } from "typescript";
7
+ import type { SourceFile } from "./discovery.ts";
8
+ import { makeFinding } from "./findings.ts";
9
+ import type { ParsedScript } from "./parsed-script.ts";
10
+ import type { Finding } from "./types.ts";
11
+
12
+ const require = createRequire(import.meta.url);
13
+ const syntax = require("typescript") as typeof import("typescript");
14
+ const MINIMUM_GROUP_SIZE = 3;
15
+ // Section 16's TypeScript member minimum: a one- or two-statement test is one named case whose table form reads no better.
16
+ const MINIMUM_STATEMENTS = 3;
17
+ const TEST_NAMES = new Set(["test", "it"]);
18
+ const SUITE_NAMES = new Set(["describe", "context", "suite"]);
19
+ const TEST_MODIFIERS = new Set(["skip", "only", "todo", "concurrent", "fails", "failing", "serial", "sequential", "skipIf", "runIf"]);
20
+ const TABLE_MODIFIERS = new Set(["each", "for"]);
21
+ const TABLE_ITERATORS = new Set(["forEach", "map", "flatMap"]);
22
+
23
+ // Supported runner root and ordered modifier evidence; a table target never joins a group.
24
+ interface CallTarget {
25
+ name: string;
26
+ modifiers: string[];
27
+ isTable: boolean;
28
+ }
29
+
30
+ // Every member carries its native title and complete location for group review.
31
+ interface TestMember {
32
+ name: string;
33
+ qualifiedName: string;
34
+ line: number;
35
+ column: number;
36
+ endLine: number;
37
+ }
38
+
39
+ type TestCallback = ArrowFunction | FunctionExpression;
40
+
41
+ /**
42
+ * Appends one finding for every qualifying group, retaining every member in source order.
43
+ * Contract: the first member owns the native identity and every member remains visible.
44
+ *
45
+ * @param file - discovered file identity for native findings
46
+ * @param parsed - shared syntax tree; malformed files provide no reliable groups
47
+ * @param findings - destination for complete native findings
48
+ * @returns no value. Appends in place and leaves findings unchanged when parsing reports diagnostics or no group qualifies.
49
+ */
50
+ export function analyseDuplicateTestGroups(file: SourceFile, parsed: ParsedScript, findings: Finding[]): void {
51
+ if (parsed.diagnostics.length > 0) {
52
+ return;
53
+ }
54
+ const groups = new Map<string, TestMember[]>();
55
+ /**
56
+ * Walks node and its descendants without another parse and adds qualifying tests to the shared groups map.
57
+ *
58
+ * @param node - syntax node whose subtree is walked for call expressions
59
+ * @returns Nothing. Adds qualifying tests to the shared groups map in place.
60
+ */
61
+ const visit = (node: Node): void => {
62
+ if (syntax.isCallExpression(node)) {
63
+ collectTestMember(node, parsed.sourceFile, groups);
64
+ }
65
+ node.forEachChild(visit);
66
+ };
67
+ parsed.sourceFile.forEachChild(visit);
68
+ for (const members of groups.values()) {
69
+ const first = members[0];
70
+ if (!first || members.length < MINIMUM_GROUP_SIZE) {
71
+ continue;
72
+ }
73
+ findings.push(makeFinding({
74
+ ruleId: "test-quality.duplicate-test-body",
75
+ message: `${members.length} tests share a body: ${members.map((member) => `${member.qualifiedName} (${member.line}:${member.column})`).join(", ")}. Consider the test runner's table form with a descriptive label per row.`,
76
+ filePath: file.displayPath,
77
+ line: first.line,
78
+ column: first.column,
79
+ endLine: first.endLine,
80
+ symbol: first.name,
81
+ severity: "advisory",
82
+ pillar: "test-quality",
83
+ confidence: "low",
84
+ remediation: "Review the cases as a consolidation candidate; use the test runner's table form with a descriptive label per row when it keeps each case clear.",
85
+ metadata: { groupSize: members.length, members },
86
+ }));
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Adds a supported registration to its exact container, attributes and normalized-body group.
92
+ * Group boundaries must preserve differences in scope and runner options before cases can be compared.
93
+ *
94
+ * @param call - possible test registration
95
+ * @param sourceFile - shared tree used for source locations and enclosing declaration names
96
+ * @param groups - shared membership map updated in traversal order
97
+ * @returns no value. Adds a member in place only when the registration, callback and container qualify.
98
+ */
99
+ function collectTestMember(call: CallExpression, sourceFile: SyntaxFile, groups: Map<string, TestMember[]>): void {
100
+ const target = callTarget(call.expression);
101
+ const title = call.arguments[0];
102
+ if (!target || !TEST_NAMES.has(target.name) || target.isTable || !title || !syntax.isStringLiteralLike(title)) {
103
+ return;
104
+ }
105
+ const callbacks = call.arguments.filter(isTestCallback);
106
+ const callback = callbacks[0];
107
+ if (callbacks.length !== 1 || !callback || call.arguments.length > 3 || !syntax.isBlock(callback.body)) {
108
+ return;
109
+ }
110
+ if (callback.body.statements.filter((statement) => !syntax.isEmptyStatement(statement)).length < MINIMUM_STATEMENTS) {
111
+ return;
112
+ }
113
+ const container = enclosingContainer(call, sourceFile);
114
+ if (!container) {
115
+ return;
116
+ }
117
+ const options = call.arguments.slice(1).filter((argument) => argument !== callback);
118
+ const attributes = [
119
+ target.modifiers,
120
+ options.map((option) => syntaxIdentity(option, false)),
121
+ callback.kind,
122
+ syntax.isFunctionExpression(callback) ? (callback.name?.text ?? null) : null,
123
+ syntax.isFunctionExpression(callback) && callback.asteriskToken !== undefined,
124
+ callback.modifiers?.map((modifier) => modifier.kind) ?? [],
125
+ callback.parameters.map((parameter) => syntaxIdentity(parameter, false)),
126
+ ];
127
+ const key = JSON.stringify([container.positions, attributes, syntaxIdentity(callback.body, true)]);
128
+ const start = sourceFile.getLineAndCharacterOfPosition(call.getStart(sourceFile));
129
+ const member: TestMember = {
130
+ name: title.text,
131
+ qualifiedName: [...container.names, title.text].join(" > "),
132
+ line: start.line + 1,
133
+ column: start.character + 1,
134
+ endLine: sourceFile.getLineAndCharacterOfPosition(call.getEnd()).line + 1,
135
+ };
136
+ const members = groups.get(key) ?? [];
137
+ members.push(member);
138
+ groups.set(key, members);
139
+ }
140
+
141
+ /**
142
+ * Recognizes literal test/suite roots and preserves the order and arguments of modifiers.
143
+ * The walk must retain both property and call steps because either can change a runner modifier.
144
+ *
145
+ * @param expression - callee, including modifier calls such as skipIf(condition)
146
+ * @returns root, ordered modifier identities and a table flag, or undefined for unsupported callee forms
147
+ */
148
+ function callTarget(expression: Expression): CallTarget | undefined {
149
+ if (syntax.isIdentifier(expression)) {
150
+ return TEST_NAMES.has(expression.text) || SUITE_NAMES.has(expression.text)
151
+ ? { name: expression.text, modifiers: [], isTable: false } : undefined;
152
+ }
153
+ if (syntax.isPropertyAccessExpression(expression)) {
154
+ const target = callTarget(expression.expression);
155
+ const modifier = expression.name.text;
156
+ if (!target || (!TEST_MODIFIERS.has(modifier) && !TABLE_MODIFIERS.has(modifier))) {
157
+ return undefined;
158
+ }
159
+ return { ...target, modifiers: [...target.modifiers, modifier], isTable: target.isTable || TABLE_MODIFIERS.has(modifier) };
160
+ }
161
+ if (syntax.isCallExpression(expression) || syntax.isTaggedTemplateExpression(expression)) {
162
+ const target = callTarget(syntax.isCallExpression(expression) ? expression.expression : expression.tag);
163
+ if (!target) {
164
+ return undefined;
165
+ }
166
+ const argumentsIdentity = syntax.isCallExpression(expression)
167
+ ? expression.arguments.map((argument) => syntaxIdentity(argument, false))
168
+ : syntaxIdentity(expression.template, false);
169
+ return { ...target, modifiers: [...target.modifiers, JSON.stringify(argumentsIdentity)] };
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ /**
175
+ * Separates lexical declarations and rejects registrations already inside table iteration.
176
+ * Declaration positions must stay distinct because same-named sibling suites are separate containers.
177
+ *
178
+ * @param call - test registration whose ancestor declarations define its container
179
+ * @param sourceFile - shared source for enclosing declaration names
180
+ * @returns positions and names, with line labels for unnamed declarations, empty arrays at file scope, or undefined in loops or table/iterator calls
181
+ */
182
+ function enclosingContainer(call: CallExpression, sourceFile: SyntaxFile): { positions: number[]; names: string[] } | undefined {
183
+ const positions: number[] = [];
184
+ const names: string[] = [];
185
+ for (let node = call.parent; node && !syntax.isSourceFile(node); node = node.parent) {
186
+ if (syntax.isIterationStatement(node, false) || isTableIterationCall(node)) {
187
+ return undefined;
188
+ }
189
+ if (syntax.isBlock(node) && !syntax.isFunctionLike(node.parent)) {
190
+ // Keep sibling `{ const fixture = ...; test(...); }` lexical blocks separate without polluting qualified display names.
191
+ positions.unshift(node.getStart(sourceFile));
192
+ continue;
193
+ }
194
+ if (syntax.isFunctionLike(node) || syntax.isClassLike(node) || syntax.isModuleDeclaration(node)) {
195
+ positions.unshift(node.getStart(sourceFile));
196
+ names.unshift(enclosingDeclarationLabel(node, sourceFile));
197
+ }
198
+ }
199
+ return { positions, names };
200
+ }
201
+
202
+ /**
203
+ * Checks whether an enclosing AST node is already a table-driven test call (`test.each`, `forEach`, `map`, or `flatMap`).
204
+ *
205
+ * @param node - ancestor syntax node walked upward from a candidate test registration
206
+ * @returns True when `node` is a table-modifier test call or collection iterator call; otherwise false.
207
+ */
208
+ function isTableIterationCall(node: Node): boolean {
209
+ if (!syntax.isCallExpression(node)) {
210
+ return false;
211
+ }
212
+ const target = callTarget(node.expression);
213
+ return target?.isTable === true || (syntax.isPropertyAccessExpression(node.expression) && TABLE_ITERATORS.has(node.expression.name.text));
214
+ }
215
+
216
+ /**
217
+ * Derives the display label for an enclosing suite, function, class, or namespace declaration.
218
+ *
219
+ * @param node - enclosing declaration or callback node
220
+ * @param sourceFile - shared syntax tree supplying line numbers and identifier text
221
+ * @returns Suite title, declaration name, or `<anonymous@line>` fallback label.
222
+ */
223
+ function enclosingDeclarationLabel(node: Node, sourceFile: SyntaxFile): string {
224
+ const parentCall = isTestCallback(node) && syntax.isCallExpression(node.parent) ? node.parent : undefined;
225
+ const title = parentCall?.arguments[0];
226
+ if (title && syntax.isStringLiteralLike(title)) {
227
+ return title.text;
228
+ }
229
+ const declarationName = (node as { name?: Node }).name?.getText(sourceFile);
230
+ return declarationName ?? `<anonymous@${sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1}>`;
231
+ }
232
+
233
+ /**
234
+ * Recognizes inline callback functions so the duplicate-test rule can inspect them without resolving references.
235
+ *
236
+ * @param node - candidate callback argument or enclosing declaration
237
+ * @returns whether the node is an arrow function or function expression, regardless of its body form
238
+ */
239
+ function isTestCallback(node: Node): node is TestCallback {
240
+ return syntax.isArrowFunction(node) || syntax.isFunctionExpression(node);
241
+ }
242
+
243
+ /**
244
+ * Builds a comparison key for test bodies, retaining keys, indices and decoded text containing ASCII whitespace.
245
+ * The token walk must retain operators, declaration keywords and empty for-loop clauses that
246
+ * forEachChild omits, while allowing optional statement semicolons and trailing commas.
247
+ *
248
+ * @param node - syntax subtree to compare
249
+ * @param normalize - whether eligible literal values may become same-kind placeholders
250
+ * @param exact - whether the subtree sits inside a declaration or decorator that keeps its documentation
251
+ * @returns deterministic syntax identity, with no local-name renaming
252
+ */
253
+ function syntaxIdentity(node: Node, normalize: boolean, exact = false): unknown {
254
+ // Preserve literals and documentation in exact subtrees because a shared case body could otherwise hide declaration or decorator differences.
255
+ // Outside those subtrees, const initializers can use the same literal normalization as other statements.
256
+ const inExact = exact || isExactDeclaration(node);
257
+ const literal = literalIdentity(node, normalize && !inExact);
258
+ if (literal !== undefined) {
259
+ return literal;
260
+ }
261
+ const children: unknown[] = inExact ? [leadingDocumentation(node)] : [];
262
+ const syntaxChildren = node.getChildren();
263
+ for (const [index, child] of syntaxChildren.entries()) {
264
+ if (!isComparisonChild(node, child, index, syntaxChildren.length)) {
265
+ continue;
266
+ }
267
+ const isKey = "name" in node && node.name === child;
268
+ const isIndex = syntax.isElementAccessExpression(node) && node.argumentExpression === child;
269
+ children.push(syntaxIdentity(child, normalize && !inExact && !isKey && !isIndex, inExact));
270
+ }
271
+ return [node.kind, children];
272
+ }
273
+
274
+ /**
275
+ * Identifies function, class, interface, type, enum and module declarations, plus decorators, for exact comparison.
276
+ *
277
+ * @param node - syntax node inside a compared test body
278
+ * @returns whether its literals and documentation must stay exact
279
+ */
280
+ function isExactDeclaration(node: Node): boolean {
281
+ return syntax.isFunctionDeclaration(node) || syntax.isClassDeclaration(node) || syntax.isInterfaceDeclaration(node)
282
+ || syntax.isTypeAliasDeclaration(node) || syntax.isEnumDeclaration(node) || syntax.isModuleDeclaration(node)
283
+ || syntax.isDecorator(node);
284
+ }
285
+
286
+ /**
287
+ * Reads raw JSDoc for a node in an exact subtree so documentation differences can keep test bodies apart.
288
+ *
289
+ * @param node - declaration or one of its descendants
290
+ * @returns the raw documentation comments in source order, or an empty array when the node has no JSDoc to compare
291
+ */
292
+ function leadingDocumentation(node: Node): string[] {
293
+ const text = node.getSourceFile().text;
294
+ // Trailing ranges hold comments on the previous token's line; leading ranges start after the next line break.
295
+ const ranges = [...syntax.getTrailingCommentRanges(text, node.pos) ?? [], ...syntax.getLeadingCommentRanges(text, node.pos) ?? []];
296
+ return ranges.map((range) => text.slice(range.pos, range.end))
297
+ .filter((comment) => comment.startsWith("/**"));
298
+ }
299
+
300
+ /**
301
+ * Ignores statement semicolons, empty statements in blocks and trailing commas when comparing syntax.
302
+ * For-loop semicolons must remain because they identify initializer, condition and increment clauses.
303
+ * Skips parsed JSDoc because syntaxIdentity handles raw documentation for exact subtrees.
304
+ *
305
+ * @param owner - syntax node whose immediate children are compared
306
+ * @param child - candidate token or nested syntax node
307
+ * @param index - child's position in the owner's token sequence
308
+ * @param count - number of immediate children, used to recognize a trailing comma
309
+ * @returns whether this child contributes to the comparison
310
+ */
311
+ function isComparisonChild(owner: Node, child: Node, index: number, count: number): boolean {
312
+ if (syntax.isEmptyStatement(child) && syntax.isBlock(child.parent)) {
313
+ return false;
314
+ }
315
+ if (child.kind >= syntax.SyntaxKind.FirstJSDocNode && child.kind <= syntax.SyntaxKind.LastJSDocNode) {
316
+ return false;
317
+ }
318
+ if (child.kind === syntax.SyntaxKind.SemicolonToken) {
319
+ return syntax.isForStatement(owner);
320
+ }
321
+ return !(child.kind === syntax.SyntaxKind.CommaToken && owner.kind === syntax.SyntaxKind.SyntaxList && index === count - 1);
322
+ }
323
+
324
+ /**
325
+ * Builds comparison identities for leaf nodes, preserving JSX text and decoded string or template text containing ASCII whitespace.
326
+ * Quoted strings and templates without substitutions share a text kind; true and false share a boolean kind.
327
+ *
328
+ * @param node - possible literal or identifier leaf
329
+ * @param normalize - whether eligible values become placeholders; callers disable this for keys, indices, options and exact declarations
330
+ * @returns leaf identity, or undefined when child structure must be compared
331
+ */
332
+ function literalIdentity(node: Node, normalize: boolean): unknown {
333
+ switch (node.kind) {
334
+ case syntax.SyntaxKind.JsxText:
335
+ case syntax.SyntaxKind.JsxTextAllWhiteSpaces:
336
+ return [node.kind, (node as import("typescript").JsxText).text];
337
+ case syntax.SyntaxKind.StringLiteral:
338
+ case syntax.SyntaxKind.NoSubstitutionTemplateLiteral:
339
+ case syntax.SyntaxKind.TemplateHead:
340
+ case syntax.SyntaxKind.TemplateMiddle:
341
+ case syntax.SyntaxKind.TemplateTail: {
342
+ const text = (node as import("typescript").LiteralLikeNode).text;
343
+ const kind = syntax.isStringLiteralLike(node) ? "text" : node.kind;
344
+ return [kind, normalize && !/[\t-\r ]/.test(text) ? "<literal>" : text];
345
+ }
346
+ case syntax.SyntaxKind.NumericLiteral:
347
+ case syntax.SyntaxKind.BigIntLiteral:
348
+ case syntax.SyntaxKind.RegularExpressionLiteral:
349
+ return [node.kind, normalize ? "<literal>" : (node as import("typescript").LiteralLikeNode).text];
350
+ case syntax.SyntaxKind.TrueKeyword:
351
+ case syntax.SyntaxKind.FalseKeyword:
352
+ return ["boolean", normalize ? "<literal>" : node.kind];
353
+ case syntax.SyntaxKind.Identifier:
354
+ case syntax.SyntaxKind.PrivateIdentifier:
355
+ return [node.kind, (node as import("typescript").Identifier).text];
356
+ default:
357
+ return undefined;
358
+ }
359
+ }