@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
@@ -1,12 +1,12 @@
1
- // Per-test-block rule pass: assertion quality (no-assertions, trivial, snapshot-only,
2
- // no-throw-only, exception-type-only, magic-number), mock quality (unused-mock, mock-only-test),
3
- // global-state-mutation, and structural checks (sleep/loop/conditional/only-skip).
4
- // Invoked from the analyseBlocks orchestrator when `block.isTest` is true.
1
+ // Evaluates test-quality rules on each parsed `test(...)` or `it(...)` block in a project scan.
2
+ //
3
+ // Checks for unlabeled loops inside tests and overly broad test structure patterns while exempting clear table-driven tests.
4
+ // Called by the block orchestrator whenever a discovered callable is flagged as a test registration.
5
5
  import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion } from "./blocks.ts";
6
6
  import { type SourceFile } from "./discovery.ts";
7
7
  import { escapeRegex } from "./findings-helpers.ts";
8
8
  import { pushStaticAnalysisRedundantTestFindings, type StaticAnalysisSourceContext } from "./static-analysis-redundant-rules.ts";
9
- import { countMatches } from "./text-scans.ts";
9
+ import { countMatches, matchingCloseParen } from "./text-scans.ts";
10
10
  import type { Finding, Severity } from "./types.ts";
11
11
 
12
12
  // Provisional rule output gathered during a test-block walk. Built before the surrounding context
@@ -17,17 +17,14 @@ interface TestBlockCheck {
17
17
  severity: Severity;
18
18
  }
19
19
 
20
- // Captures one assertion matcher plus the capture indexes that hold actual expression and literal.
21
- interface MagicNumberAssertionPattern {
22
- pattern: RegExp;
23
- expressionIndex: number;
24
- matcherIndex?: number;
25
- valueIndex: number;
26
- }
27
-
28
- /*
29
- * Reached when `block.isTest` is true. Four sub-passes in a stable, deterministic order: assertion
30
- * quality, mock quality, global-state-mutation, structural rules.
20
+ /**
21
+ * Check a test block in stable order: assertion quality, mock quality, shared-state mutation, and loop structure.
22
+ *
23
+ * @param file - source file used to locate findings
24
+ * @param block - test block whose executable text and location the checks use
25
+ * @param findings - caller's list that receives findings from every check
26
+ * @param staticContext - surrounding source for assertion analysis; omission limits it to the block's own source and starting line
27
+ * @returns Nothing. Appends the findings from this test block to the supplied list.
31
28
  */
32
29
  export function analyseTestBlock(file: SourceFile, block: FunctionBlock, findings: Finding[], staticContext?: StaticAnalysisSourceContext): void {
33
30
  const body = block.codeBody;
@@ -38,55 +35,49 @@ export function analyseTestBlock(file: SourceFile, block: FunctionBlock, finding
38
35
  analyseTestStructureChecks(file, block, body, findings);
39
36
  }
40
37
 
41
- // Five assertion-shape checks (no-assertions, trivial, snapshot-only, no-throw-only, exception-type-only)
42
- // plus the magic-number sub-pass. Reports findings with stable test-block metadata.
38
+ /**
39
+ * Checks the test body for assertion-quality problems and static-analysis redundancy.
40
+ * Uses the block's original text and staticContext to assess whether static evidence makes an assertion redundant.
41
+ *
42
+ * @param file - source file used to anchor stable findings
43
+ * @param block - test block providing original text and location metadata for findings
44
+ * @param body - masked test body scanned by assertion-quality checks
45
+ * @param staticContext - surrounding source context used to evaluate redundant assertions
46
+ * @param findings - caller's list that receives findings from both checks
47
+ * @returns Nothing. Appends stable findings from both assertion-quality checks to the supplied list.
48
+ */
43
49
  function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
44
50
  for (const check of assertionQualityChecks(block, body)) {
45
51
  findings.push(blockFinding({ ruleId: check.ruleId, message: check.message, file, block, severity: check.severity, pillar: "test-quality" }));
46
52
  }
47
- pushMagicNumberAssertionFindings(file, block, body, findings);
48
53
  pushStaticAnalysisRedundantTestFindings(file, block, block.body, body, staticContext, findings);
49
54
  }
50
55
 
51
- // Lazy evaluation: only checks whose `active` predicate fired are returned. The five rule IDs are
52
- // part of the public test-quality pillar; their ordering here is the stable emission order.
56
+ /**
57
+ * Return active assertion-quality checks for the masked test body.
58
+ * Predicates are evaluated before filtering, and retained checks keep their declared emission order.
59
+ *
60
+ * @param block - test block whose name appears in emitted check messages
61
+ * @param body - masked test body scanned for trivial assertions
62
+ * @returns Matched assertion-quality checks in declared order, or an empty list when none matched.
63
+ */
53
64
  function assertionQualityChecks(block: FunctionBlock, body: string): TestBlockCheck[] {
54
65
  const testName = block.name;
55
66
  const checks: Array<TestBlockCheck & { active: boolean }> = [
56
- { active: !hasAssertion(body), ruleId: "test-quality.no-assertions", message: `Test \`${testName}\` does not appear to make an assertion.`, severity: "warning" },
57
67
  { active: hasTrivialAssertion(body), ruleId: "test-quality.trivial-assertion", message: `Test \`${testName}\` contains an assertion that compares a value to itself.`, severity: "warning" },
58
- { active: isSnapshotOnlyTest(body), ruleId: "test-quality.snapshot-only-test", message: `Test \`${testName}\` relies only on snapshot assertions.`, severity: "advisory" },
59
- { active: isNoThrowOnlyTest(body), ruleId: "test-quality.no-throw-only-test", message: `Test \`${testName}\` only verifies that code does not throw.`, severity: "advisory" },
60
- { active: hasExceptionTypeOnlyAssertion(body), ruleId: "test-quality.exception-type-only", message: `Test \`${testName}\` checks only the exception type.`, severity: "advisory" },
61
68
  ];
62
69
  return checks.filter((check) => check.active).map(({ active: _active, ...check }) => check);
63
70
  }
64
71
 
65
- /*
66
- * Targets `expect(x).toBe(42)` / `assert.equal(x, 42)` patterns where 42 has no name. Reports
67
- * `test-quality.magic-number-assertion` with stable literal metadata for downstream review tools.
72
+ /**
73
+ * Checks the test body for unused mock variables.
74
+ *
75
+ * @param file - source file used to locate each advisory
76
+ * @param block - test block used to anchor each advisory
77
+ * @param body - masked test body scanned for unused mock declarations
78
+ * @param findings - caller's list that receives one advisory per unused mock
79
+ * @returns Nothing. Appends one stable test-quality.unused-mock finding with the mock name to the supplied list for each match.
68
80
  */
69
- function pushMagicNumberAssertionFindings(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
70
- if (isConstantContractTestName(block.name)) {
71
- return;
72
- }
73
- for (const assertion of magicNumberAssertions(body)) {
74
- findings.push(
75
- blockFindingWithMetadata({
76
- ruleId: "test-quality.magic-number-assertion",
77
- message: `Test \`${block.name}\` asserts against unexplained numeric literal ${assertion.value}.`,
78
- file,
79
- block,
80
- severity: "advisory",
81
- pillar: "test-quality",
82
- metadata: { value: assertion.value },
83
- }),
84
- );
85
- }
86
- }
87
-
88
- // Two distinct findings emitted from one walk: per-unused-mock and a single mock-only flag.
89
- // Reports `test-quality.unused-mock` / `test-quality.mock-only-test` with stable test-block metadata.
90
81
  function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
91
82
  const unusedMocks = unusedMockVariables(body);
92
83
  for (const mock of unusedMocks) {
@@ -102,45 +93,44 @@ function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string
102
93
  }),
103
94
  );
104
95
  }
105
- if (isMockOnlyTest(body)) {
106
- findings.push(blockFinding({ ruleId: "test-quality.mock-only-test", message: `Test \`${block.name}\` only verifies mock interaction.`, file, block, severity: "advisory", pillar: "test-quality" }));
107
- }
108
96
  }
109
97
 
110
- // Reports the stable `test-quality.global-state-mutation` finding contract for state leaks.
98
+ /**
99
+ * Checks the test body for changes to process or runtime state that other tests may share.
100
+ *
101
+ * @param file - source file used to locate the warning
102
+ * @param block - test block used to anchor and name the warning
103
+ * @param body - masked test body checked for shared-state assignments
104
+ * @param findings - caller's list that receives the warning when a mutation matches
105
+ * @returns Nothing. On a match, appends a stable test-quality.global-state-mutation warning for the supplied file and block to findings.
106
+ */
111
107
  function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
112
108
  if (hasGlobalStateMutation(body)) {
113
109
  findings.push(blockFinding({ ruleId: "test-quality.global-state-mutation", message: `Test \`${block.name}\` mutates global process or runtime state.`, file, block, severity: "warning", pillar: "test-quality" }));
114
110
  }
115
111
  }
116
112
 
117
- // Pattern-driven checks for sleep/loop/conditional logic plus the `.only`/`.skip` commit gate.
118
- // Reports each detected structural issue as a stable test-quality finding.
113
+ /**
114
+ * Flag loops that may hide which test iteration failed. Confidence is medium because the label heuristic can miss indirect messages.
115
+ *
116
+ * @param file - source file used to locate the advisory
117
+ * @param block - test block used to anchor and name the advisory
118
+ * @param body - test code checked for loops the heuristic considers reportable
119
+ * @param findings - caller's list that receives the advisory
120
+ * @returns Nothing. Appends a stable test-quality.loop-in-test finding when the heuristic matches.
121
+ */
119
122
  function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
120
- const checks: Array<[string, boolean, string]> = [
121
- ["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
122
- ["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic that hides which iteration failed."],
123
- ["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
124
- ["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
125
- ];
126
- for (const [ruleId, active, message] of checks) {
127
- if (!active) {
128
- continue;
129
- }
130
- // Loop findings report at medium confidence: parametrized tests are a legitimate pattern and
131
- // the label heuristic cannot see every message shape (multi-line assertion calls, helpers).
132
- if (ruleId === "test-quality.loop-in-test") {
133
- findings.push(blockFindingWithMetadata({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
134
- continue;
135
- }
136
- findings.push(blockFinding({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality" }));
123
+ if (controlFlowContainsNonFixtureLoop(body)) {
124
+ findings.push(blockFindingWithMetadata({ ruleId: "test-quality.loop-in-test", message: "Test contains loop logic that hides which iteration failed.", file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
137
125
  }
138
126
  }
139
127
 
140
- // Loop variant of `controlFlowContainsAssertion` that suppresses fixture loops (table-test pattern):
141
- // loops over a literal array or `Object.entries|keys|values` of a literal where every code path
142
- // inside the body reaches an assertion. The existing rule fires on ANY loop wrapping an assertion;
143
- // this widens the precision so parametric coverage doesn't read as control-flow noise.
128
+ /**
129
+ * Checks whether masked source contains a reportable for or while loop with an assertion.
130
+ *
131
+ * @param source - masked test body scanned for loop segments
132
+ * @returns True when a loop with an assertion is exempt by neither fixture nor labeled-case checks; false otherwise.
133
+ */
144
134
  function controlFlowContainsNonFixtureLoop(source: string): boolean {
145
135
  for (const match of source.matchAll(/\b(?:for|while)\b/g)) {
146
136
  const start = match.index ?? 0;
@@ -159,50 +149,163 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
159
149
  return false;
160
150
  }
161
151
 
162
- /*
163
- * A data-driven loop whose assertions each carry a per-case template message referencing a
164
- * loop-bound name keeps a failing row identifiable - the failure mode this rule exists to catch -
165
- * so it opts out even when the case table is built dynamically. Multi-line assertion calls fall
166
- * outside the statement split and stay reported; the rule's medium confidence reflects that.
152
+ /**
153
+ * Checks whether a loop can skip the loop-in-test finding because its recognized assertions identify the failed case.
154
+ * A multiline message can mention the label. A supported expected operand must equal the label name after trimming.
155
+ * A label can be a loop binding or a const whose initializer mentions that binding directly.
156
+ *
157
+ * @param segment - masked loop text containing the header and body to check
158
+ * @returns True if each recognized chain has a label. False for an unrecognized loop, an unsafe branch, or missing bindings or recognized calls.
167
159
  */
168
160
  function isLabeledCaseLoop(segment: string): boolean {
169
161
  const parts = loopSegmentParts(segment);
170
162
  if (!parts) {
171
163
  return false;
172
164
  }
165
+ if (hasUnsafeFixtureLoopBranch("", parts.body)) {
166
+ return false;
167
+ }
173
168
  const boundNames = loopBoundNames(parts.header);
174
169
  if (boundNames.length === 0) {
175
170
  return false;
176
171
  }
177
- const assertionStatements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && hasAssertion(statement));
178
- if (assertionStatements.length === 0) {
172
+ // Reject the exemption when the loop mixes in assertion forms (`should.be`, `.resolves`/`.rejects`) that have no verified per-case label.
173
+ if (/\.\s*should\s*\.\s*be\s*\./.test(parts.body) || /\.\s*(?:rejects|resolves)\b/.test(parts.body)) {
179
174
  return false;
180
175
  }
181
- return assertionStatements.every((statement) => hasLoopCaseLabel(statement, boundNames));
176
+ const assertionCalls = assertionCallChains(parts.body);
177
+ if (assertionCalls.length === 0) {
178
+ return false;
179
+ }
180
+ const labelNames = [...boundNames, ...loopDerivedLocalNames(parts.body, boundNames)];
181
+ return assertionCalls.every((call) => hasLoopCaseLabel(call, labelNames));
182
+ }
183
+
184
+ // Only call forms with supported per-case label arguments can clear a loop warning; `.should.be` matchers have no proved label form.
185
+ const ASSERTION_CALL_OPENER = /\b(?:assert(?:\.[A-Za-z]+|[A-Z][A-Za-z0-9_$]*)?|expect(?:\.(?:assertions|hasAssertions)|[A-Z][A-Za-z0-9_$]*)?|[A-Za-z_$][A-Za-z0-9_$]*Check)\s*(?:<(?!\s)(?:(?!&&|\|\|)[^;\r\n])+>\s*)?\(/g;
186
+ // One chained call such as `.toBe(` after a closed call.
187
+ const CHAINED_CALL_LINK = /^\s*\.\s*[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^;]*?>\s*)?\(/;
188
+
189
+ /**
190
+ * Return recognized assertion-chain slices from the masked loop body, including nested assertion calls inside outer assertion arguments.
191
+ * Skip an unmatched opening call or member-chained property call; if a later chained call is unclosed, retain the complete prefix already measured.
192
+ *
193
+ * @param body - masked loop body scanned for assertion openers and chained calls
194
+ * @returns Matched assertion-chain slices in source order, or an empty list when no opener can be matched.
195
+ */
196
+ function assertionCallChains(body: string): string[] {
197
+ const calls: string[] = [];
198
+ for (const match of body.matchAll(ASSERTION_CALL_OPENER)) {
199
+ const start = match.index ?? 0;
200
+ // Skip member calls chained onto an earlier expression (such as `foo.expectCheck(`), while keeping nested standalone assertions checked.
201
+ if (start > 0 && body[start - 1] === ".") {
202
+ continue;
203
+ }
204
+ let close = matchingCloseParen(body, start + match[0].length - 1);
205
+ if (close === undefined) {
206
+ continue;
207
+ }
208
+ for (let link = body.slice(close + 1).match(CHAINED_CALL_LINK); link; link = body.slice(close + 1).match(CHAINED_CALL_LINK)) {
209
+ const linkClose = matchingCloseParen(body, close + link[0].length);
210
+ if (linkClose === undefined) {
211
+ break;
212
+ }
213
+ close = linkClose;
214
+ }
215
+ calls.push(body.slice(start, close + 1));
216
+ }
217
+ return calls;
182
218
  }
183
219
 
184
- // Identifier names bound by a for..of header - `for (const { name, input } of cases)` binds both.
185
- // While-loops bind nothing here, so they never take the labeled opt-out.
220
+ /**
221
+ * Return const-local names whose initializer text in body has a whole-word match from boundNames, for use as assertion labels.
222
+ * Follow one level only; locals derived solely from other derived locals and unmatched declarations are excluded.
223
+ *
224
+ * @param body - masked loop body searched for const declarations
225
+ * @param boundNames - loop-bound identifier names tested against each const initializer
226
+ * @returns Derived local names eligible as assertion labels.
227
+ */
228
+ function loopDerivedLocalNames(body: string, boundNames: string[]): string[] {
229
+ const derived: string[] = [];
230
+ for (const match of body.matchAll(/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*([^;\n]+)/g)) {
231
+ const initializer = match[2] ?? "";
232
+ if (boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(initializer))) {
233
+ derived.push(match[1] ?? "");
234
+ }
235
+ }
236
+ return derived.filter(Boolean);
237
+ }
238
+
239
+ /**
240
+ * Extract identifier names bound by for-of, for-in or C-style headers.
241
+ * While-loops bind nothing here, so they never take the labeled opt-out.
242
+ *
243
+ * @param header - loop header text preceding the body brace
244
+ * @returns Bound identifier names from the loop header, or an empty list when none are declared.
245
+ */
186
246
  function loopBoundNames(header: string): string[] {
187
- const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+of\b/)?.[1] ?? "";
247
+ const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+(?:of|in)\b/)?.[1]
248
+ ?? header.match(/\b(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/)?.[1]
249
+ ?? "";
188
250
  return [...binding.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)].map((match) => match[0] ?? "").filter(Boolean);
189
251
  }
190
252
 
191
- // The per-case label: a template interpolation in the assertion statement naming a bound
192
- // identifier. Masked source keeps `${...}` expressions intact, so this works on codeBody.
253
+ /**
254
+ * Return whether the assertion call text in statement labels a case with one of the loop bindings or derived locals.
255
+ * Looks for a whole-word match in argument three for binary assert calls or argument two otherwise, plus bare expected operands.
256
+ *
257
+ * @param statement - recognized assertion-chain text from a loop body
258
+ * @param boundNames - loop bindings and derived local names accepted as case labels
259
+ * @returns True when the assertion message or expected operand matches a label name; false otherwise.
260
+ */
193
261
  function hasLoopCaseLabel(statement: string, boundNames: string[]): boolean {
194
- for (const interpolation of statement.matchAll(/\$\{([^}]*)\}/g)) {
195
- const expressionText = interpolation[1] ?? "";
196
- if (boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(expressionText))) {
197
- return true;
262
+ const argumentsList = assertionArguments(statement);
263
+ const isBinaryAssert = /^assert\.(?:(?:not)?(?:strictEqual|deepStrictEqual|equal|deepEqual)|throws|rejects|match|doesNotMatch)\b/i.test(statement);
264
+ const isExpect = /^expect\s*\(/.test(statement);
265
+ const message = argumentsList[isBinaryAssert ? 2 : 1] ?? "";
266
+ const matcher = isExpect ? statement.slice((matchingCloseParen(statement, statement.indexOf("(")) ?? statement.length) + 1) : "";
267
+ const expected = isBinaryAssert ? argumentsList[1] ?? "" : isExpect ? assertionArguments(matcher)[0] ?? "" : "";
268
+ return boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(message) || expected.trim() === name);
269
+ }
270
+
271
+ /**
272
+ * Return comma-separated argument slices from statement's outer call; strings and comments must already be masked.
273
+ * Nested delimiters stay within a slice.
274
+ *
275
+ * @param statement - masked call expression whose outer argument list is split
276
+ * @returns Argument slices from the outer call (retaining an interior slice on an empty call), or an empty list if parentheses are unmatched.
277
+ */
278
+ function assertionArguments(statement: string): string[] {
279
+ const open = statement.indexOf("(");
280
+ const close = matchingCloseParen(statement, open);
281
+ if (open < 0 || close === undefined) {
282
+ return [];
283
+ }
284
+ const argumentsList: string[] = [];
285
+ let depth = 0;
286
+ let start = open + 1;
287
+ for (let index = start; index < close; index += 1) {
288
+ const character = statement[index] ?? "";
289
+ if ("([{".includes(character)) depth += 1;
290
+ else if (")]}".includes(character)) depth -= 1;
291
+ else if (character === "," && depth === 0) {
292
+ argumentsList.push(statement.slice(start, index));
293
+ start = index + 1;
198
294
  }
199
295
  }
200
- return false;
296
+ argumentsList.push(statement.slice(start, close));
297
+ return argumentsList;
201
298
  }
202
299
 
203
- // A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
204
- // fixture table, AND every path through the body terminates in an assertion call. Guard branches
205
- // without assertions are allowed, but assertion-bearing branches still opt out.
300
+ /**
301
+ * Return whether segment has an accepted fixture iterable and a final non-ignored statement starting with a recognized assertion.
302
+ * Switch, case, or default markers disqualify the loop; an assertion-bearing if disqualifies it unless matched as a fixture guard.
303
+ *
304
+ * @param source - masked source surrounding the loop for preceding declaration lookup
305
+ * @param start - character offset in source where the loop keyword begins
306
+ * @param segment - bounded loop text containing header and body
307
+ * @returns True when the loop iterates an accepted fixture table safely and ends with a recognized assertion; false otherwise.
308
+ */
206
309
  function isFixtureLoop(source: string, start: number, segment: string): boolean {
207
310
  const parts = loopSegmentParts(segment);
208
311
  if (!parts || !hasFixtureIterable(source, start, parts.header)) {
@@ -211,16 +314,19 @@ function isFixtureLoop(source: string, start: number, segment: string): boolean
211
314
  if (hasUnsafeFixtureLoopBranch(source.slice(0, start + parts.bodyBraceIndex + 1), parts.body)) {
212
315
  return false;
213
316
  }
214
- // Bare `void identifier` lines are lint pacifiers, not work, so they cannot be the loop's
215
- // terminal action; `void call()` still counts as a real trailing statement.
317
+ // A bare void-name marker can follow the terminal assertion without disqualifying the loop. A void-wrapped call still counts.
216
318
  const statements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement) && !/^void\s+[A-Za-z_$][A-Za-z0-9_$]*$/.test(statement));
217
319
  const lastStatement = statements[statements.length - 1] ?? "";
218
320
  return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
219
321
  }
220
322
 
221
- // Splits a loop segment into header and body at the body-opening brace, walking past the header's
222
- // balanced parentheses first so that a destructured binding such as `for (const { name } of rows)`
223
- // does not end the header at the destructuring brace. Braceless bodies return undefined.
323
+ /**
324
+ * Splits a loop segment into header and body at the body-opening brace, walking past the header's balanced parentheses first
325
+ * so that a destructured binding such as `for (const { name } of rows)` does not end the header at the destructuring brace.
326
+ *
327
+ * @param segment - bounded loop text beginning at the loop keyword
328
+ * @returns Header slice, body interior slice, and body-brace offset, or undefined for braceless or unclosed headers.
329
+ */
224
330
  function loopSegmentParts(segment: string): { header: string; body: string; bodyBraceIndex: number } | undefined {
225
331
  const parenIndex = segment.indexOf("(");
226
332
  if (parenIndex === -1) {
@@ -237,8 +343,13 @@ function loopSegmentParts(segment: string): { header: string; body: string; body
237
343
  return { header: segment.slice(0, bodyBraceIndex), body: segment.slice(bodyBraceIndex + 1, segment.length - 1), bodyBraceIndex };
238
344
  }
239
345
 
240
- // Walks a header's parentheses to the close of the outermost group, tolerating nested calls such
241
- // as `of Object.entries({ a: 1 })` inside the loop header.
346
+ /**
347
+ * Find the closing-parenthesis index for the loop-header opener at parenIndex in segment, counting nested parentheses.
348
+ *
349
+ * @param segment - loop text containing the header parentheses
350
+ * @param parenIndex - offset of the header's opening parenthesis inside segment
351
+ * @returns Closing-parenthesis offset in segment, or undefined if the outer group does not close before segment ends.
352
+ */
242
353
  function matchingHeaderCloseParen(segment: string, parenIndex: number): number | undefined {
243
354
  let depth = 0;
244
355
  for (let index = parenIndex; index < segment.length; index += 1) {
@@ -255,8 +366,14 @@ function matchingHeaderCloseParen(segment: string, parenIndex: number): number |
255
366
  return undefined;
256
367
  }
257
368
 
258
- // Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
259
- // still opt out because they can hide case-specific expectations inside the loop.
369
+ /**
370
+ * Return whether loop body contains a switch-like construct or an assertion-bearing if segment without a recognized fixture-membership guard.
371
+ * Other if segments without assertions do not reject the fixture loop.
372
+ *
373
+ * @param sourceBeforeLoopBody - preceding source text supplying declarations for fixture guard lookup
374
+ * @param body - loop body text checked for switch markers and conditional assertions
375
+ * @returns True when an unsafe switch or unguarded assertion branch is found; false otherwise.
376
+ */
260
377
  function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
261
378
  if (/\bswitch\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
262
379
  return true;
@@ -272,9 +389,14 @@ function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string):
272
389
  return false;
273
390
  }
274
391
 
275
- // Inline fixture tables cover `for (... of [...])` and `Object.entries({ ... })`. Const-bound
276
- // tables cover the common contract-test shape where the named case table is declared immediately
277
- // before the sweep for readability.
392
+ /**
393
+ * Return whether header looks like an inline fixture iterable or names a recognized fixture constant or const-bound table.
394
+ *
395
+ * @param source - masked source providing preceding declarations for const-bound lookup
396
+ * @param start - character offset in source where the loop begins
397
+ * @param header - loop header text inspected for an inline or named fixture iterable
398
+ * @returns True when the header iterates a recognized fixture iterable; false when no accepted shape was found.
399
+ */
278
400
  function hasFixtureIterable(source: string, start: number, header: string): boolean {
279
401
  if (/\bof\s*\[/.test(header) || /\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
280
402
  return true;
@@ -283,8 +405,14 @@ function hasFixtureIterable(source: string, start: number, header: string): bool
283
405
  return iterableName !== "" && (isFixtureConstantIterableName(iterableName) || hasConstBoundFixtureIterable(source.slice(0, start), iterableName));
284
406
  }
285
407
 
286
- // Accepts const-bound fixture loops only when the iterable name and initializer both look like a
287
- // deterministic case table or discovered fixture set.
408
+ /**
409
+ * Return whether iterableName has fixture vocabulary and a const assignment in sourceBeforeLoop with an accepted initializer shape.
410
+ * The assignment text must reach a semicolon at the end of the prefix; arrays, Object.entries/keys/values, or discovery calls qualify.
411
+ *
412
+ * @param sourceBeforeLoop - source prefix preceding the loop header
413
+ * @param iterableName - identifier bound by the loop's `of` clause
414
+ * @returns True when the identifier matches fixture vocabulary and an accepted const initializer; false otherwise.
415
+ */
288
416
  function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: string): boolean {
289
417
  if (!isFixtureIterableName(iterableName)) {
290
418
  return false;
@@ -294,41 +422,58 @@ function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: st
294
422
  return initializer.startsWith("[") || /^Object\.(?:entries|keys|values)\s*\(/.test(initializer) || isFixtureDiscoveryCall(initializer);
295
423
  }
296
424
 
297
- // Limits const-bound loop suppression to table/sweep vocabulary rather than arbitrary arrays.
425
+ /**
426
+ * Check whether an identifier carries a recognized fixture-table suffix for the loop-exemption heuristic.
427
+ *
428
+ * @param name - identifier name from a loop iterable
429
+ * @returns True when the name ends with an accepted fixture-table suffix; false otherwise.
430
+ */
298
431
  function isFixtureIterableName(name: string): boolean {
299
432
  return /(?:agents|cases|checks|entries|examples|fixtures|files|ids|paths|records|scenarios|scores|snapshots)$/i.test(name);
300
433
  }
301
434
 
302
- // UPPER_CASE fixture constants such as HARNESS_CHECKS are named case tables even when imported.
435
+ /**
436
+ * Check whether an identifier uses only uppercase letters, digits and underscores and has a fixture suffix; no local declaration is required.
437
+ *
438
+ * @param name - identifier name from a loop iterable
439
+ * @returns True when the name matches constant-case naming and a fixture suffix; false otherwise.
440
+ */
303
441
  function isFixtureConstantIterableName(name: string): boolean {
304
442
  return /^[A-Z0-9_]+$/.test(name) && isFixtureIterableName(name);
305
443
  }
306
444
 
307
- // Recognises local fixture discovery calls used by contract sweeps without accepting unknown calls.
445
+ /**
446
+ * Check whether initializer contains a call named glob, globSync, readdir, readdirSync, or beginning with discover, find or list.
447
+ * This name heuristic does not verify where the function was declared or whether it discovers fixtures.
448
+ *
449
+ * @param initializer - trimmed initializer expression from a const fixture binding
450
+ * @returns True when a recognized discovery call pattern appears in the initializer; false otherwise.
451
+ */
308
452
  function isFixtureDiscoveryCall(initializer: string): boolean {
309
453
  return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
310
454
  }
311
455
 
312
- // Structural loop/branch findings now require the control flow to wrap an assertion; setup-only
313
- // conditionals and fixture-building loops are noisy but not direct test-quality failures.
314
- function controlFlowContainsAssertion(source: string, pattern: RegExp): boolean {
315
- for (const match of source.matchAll(pattern)) {
316
- const start = match.index ?? 0;
317
- const segment = controlFlowSegment(source, start);
318
- if (hasAssertion(segment) && !isInvariantAssertionConditional(source, start, segment)) {
319
- return true;
320
- }
321
- }
322
- return false;
323
- }
324
-
325
- // Accepts guard conditionals whose assertion proves a shared invariant rather than branch policy.
456
+ /**
457
+ * Check whether segment's condition matches the fixture-membership guard heuristic using source text before offset start.
458
+ * The invariant heuristic checks text before the first opening brace as the condition; with no brace, the guard cannot qualify.
459
+ *
460
+ * @param source - preceding source text containing declarations visible before the conditional
461
+ * @param start - character offset in source where the conditional segment starts
462
+ * @param segment - conditional segment text beginning at `if`
463
+ * @returns True when the condition matches the fixture-membership guard heuristic; false otherwise.
464
+ */
326
465
  function isInvariantAssertionConditional(source: string, start: number, segment: string): boolean {
327
466
  const condition = segment.slice(0, Math.max(0, segment.indexOf("{"))).trim();
328
467
  return isFixtureMembershipGuard(source.slice(0, start), condition);
329
468
  }
330
469
 
331
- // Membership guards over const-bound fixtures keep invariant sweeps readable.
470
+ /**
471
+ * Check whether condition's first has/includes target is declared as a const with a new Set or array initializer in sourceBeforeCondition.
472
+ *
473
+ * @param sourceBeforeCondition - source prefix preceding the conditional statement
474
+ * @param condition - conditional header text before the opening brace
475
+ * @returns True when the guarded target is declared as a const Set or array; false when the target or declaration cannot be matched.
476
+ */
332
477
  function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: string): boolean {
333
478
  const guardTarget = condition.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\.(?:has|includes)\s*\(/)?.[1] ?? "";
334
479
  if (!guardTarget) {
@@ -337,7 +482,14 @@ function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: stri
337
482
  return new RegExp(`\\bconst\\s+${escapeRegex(guardTarget)}\\s*=\\s*(?:new\\s+Set\\s*\\(|\\[)`).test(sourceBeforeCondition);
338
483
  }
339
484
 
340
- // Captures the smallest control-flow segment so assertion detection does not scan the whole test.
485
+ /**
486
+ * Extract bounded control-flow text in masked source beginning at keyword offset start for assertion detection.
487
+ * With no same-line body brace, returns the rest of that line; an unmatched brace limits the result to the header and opening brace.
488
+ *
489
+ * @param source - masked source text containing the control-flow construct
490
+ * @param start - character offset in source where the control-flow keyword begins
491
+ * @returns Bounded control-flow slice starting at the keyword offset.
492
+ */
341
493
  function controlFlowSegment(source: string, start: number): string {
342
494
  const lineEnd = source.indexOf("\n", start);
343
495
  const openBrace = controlFlowBodyBraceIndex(source, start, lineEnd);
@@ -348,9 +500,14 @@ function controlFlowSegment(source: string, start: number): string {
348
500
  return source.slice(start, closeBrace === undefined ? openBrace + 1 : closeBrace + 1);
349
501
  }
350
502
 
351
- // Finds the body-opening brace for a control-flow keyword: the first `{` at parenthesis depth zero
352
- // on the keyword's line. Braces inside the header parens - destructured bindings such as
353
- // `for (const { name } of rows)` - belong to the header, not the body.
503
+ /**
504
+ * In masked source, scan from the keyword offset start up to lineEnd for the first opening brace outside parentheses.
505
+ *
506
+ * @param source - masked source text being scanned
507
+ * @param start - character offset of the control-flow keyword
508
+ * @param lineEnd - end-of-line offset bounding the scan, or -1 to scan to the end of source
509
+ * @returns Offset of the first body-opening brace outside parentheses, or undefined if none is found.
510
+ */
354
511
  function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: number): number | undefined {
355
512
  const limit = lineEnd === -1 ? source.length : lineEnd;
356
513
  let parenDepth = 0;
@@ -367,7 +524,13 @@ function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: numbe
367
524
  return undefined;
368
525
  }
369
526
 
370
- // Lightweight brace matcher for already-isolated test block text; enough to bound loop/if bodies.
527
+ /**
528
+ * Find the closing-brace index for the opening-brace offset openBrace in masked source, to bound a loop or conditional body.
529
+ *
530
+ * @param source - masked source text containing the braced block
531
+ * @param openBrace - offset of the opening brace in source
532
+ * @returns Offset of the matching closing brace, or undefined when the braces never balance before source ends.
533
+ */
371
534
  function matchingCloseBrace(source: string, openBrace: number): number | undefined {
372
535
  let depth = 0;
373
536
  for (let index = openBrace; index < source.length; index += 1) {
@@ -384,16 +547,22 @@ function matchingCloseBrace(source: string, openBrace: number): number | undefin
384
547
  return undefined;
385
548
  }
386
549
 
387
- // Aggregator over the three trivial-assertion shapes - literal-comparison, mirrored-`assert`
388
- // arguments, mirrored-`expect` arguments. Splitting the checks keeps each regex focused and
389
- // debuggable while this top-level keeps the call site for `test-quality.trivial-assertion` short.
550
+ /**
551
+ * Check whether the test source contains assert.ok(true) or matching operands in supported assert or expect equality checks.
552
+ *
553
+ * @param source - masked test body scanned for trivial assertions
554
+ * @returns True when a trivial assertion form matches; false when none match, so the caller can skip `test-quality.trivial-assertion`.
555
+ */
390
556
  function hasTrivialAssertion(source: string): boolean {
391
557
  return hasLiteralTrivialAssertion(source) || hasRepeatedAssertArgument(source) || hasRepeatedExpectArgument(source);
392
558
  }
393
559
 
394
- // Targets `assert.ok(true)` and `assert.equal(literal, sameLiteral)` shapes - both prove nothing
395
- // at runtime. The backreference `\1` is what makes the second pattern detect mirrored literals
396
- // across the supported `equal` / `strictEqual` / `deepEqual` variants.
560
+ /**
561
+ * Check for supported assert.ok(true) or identical-literal equality patterns in source.
562
+ *
563
+ * @param source - masked test body scanned for literal trivial assertions
564
+ * @returns True when a literal trivial assertion matches; false otherwise.
565
+ */
397
566
  function hasLiteralTrivialAssertion(source: string): boolean {
398
567
  return (
399
568
  /\bassert\.ok\s*\(\s*true\s*\)/.test(source) ||
@@ -401,9 +570,13 @@ function hasLiteralTrivialAssertion(source: string): boolean {
401
570
  );
402
571
  }
403
572
 
404
- // Walks every `assert.equal(a, b)` call and normalises both arguments before comparison so that
405
- // `foo;` and `foo` collapse to the same key. Mirrored expressions indicate the assertion would
406
- // pass regardless of behaviour - reports as a trivial assertion.
573
+ /**
574
+ * Walks every `assert.equal(a, b)` call and normalises both arguments before comparison so that
575
+ * `foo;` and `foo` collapse to the same key, because mirrored expressions pass regardless of behaviour.
576
+ *
577
+ * @param source - masked test body scanned for repeated assert arguments
578
+ * @returns True when an assert equality call compares identical normalized arguments; false otherwise.
579
+ */
407
580
  function hasRepeatedAssertArgument(source: string): boolean {
408
581
  for (const match of source.matchAll(/\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*([^,\n)]+?)(?:\s*,|\s*\))/g)) {
409
582
  if (normalizeAssertionExpression(match[1] ?? "") === normalizeAssertionExpression(match[2] ?? "")) {
@@ -413,9 +586,13 @@ function hasRepeatedAssertArgument(source: string): boolean {
413
586
  return false;
414
587
  }
415
588
 
416
- // Jest/Vitest counterpart to `hasRepeatedAssertArgument`. Targets `expect(a).toBe(b)` and the
417
- // equality variants; the matcher set is intentionally narrow so async / negation forms don't
418
- // produce false positives on argument equality.
589
+ /**
590
+ * Check whether source contains a direct expect equality call using toBe, toEqual or toStrictEqual with identical normalized argument text.
591
+ * Async and negated matcher chains do not match.
592
+ *
593
+ * @param source - masked test body scanned for repeated expect arguments
594
+ * @returns True when a direct expect equality call has identical normalized operands; false means no supported pair was found.
595
+ */
419
596
  function hasRepeatedExpectArgument(source: string): boolean {
420
597
  for (const match of source.matchAll(/\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*to(?:Be|Equal|StrictEqual)\s*\(\s*([^)]+?)\s*\)/g)) {
421
598
  if (normalizeAssertionExpression(match[1] ?? "") === normalizeAssertionExpression(match[2] ?? "")) {
@@ -425,94 +602,23 @@ function hasRepeatedExpectArgument(source: string): boolean {
425
602
  return false;
426
603
  }
427
604
 
428
- // Trims whitespace and strips a trailing semicolon so that `foo;` and `foo` compare as equal -
429
- // preserves the deterministic mirrored-argument detection across whitespace variations.
605
+ /**
606
+ * Build expression's comparison key after trimming surrounding whitespace and one trailing semicolon, so mirrored arguments compare equally.
607
+ *
608
+ * @param expression - raw operand text captured from an assertion call
609
+ * @returns Normalized comparison key for the assertion operand.
610
+ */
430
611
  function normalizeAssertionExpression(expression: string): string {
431
612
  return expression.trim().replace(/;$/, "");
432
613
  }
433
614
 
434
- // Strips every snapshot-shaped assertion plus `expect.assertions(...)` and re-checks whether any
435
- // assertion remains. A body that empties out is flagged for `test-quality.snapshot-only-test`,
436
- // since snapshot fixtures alone don't constrain behaviour.
437
- function isSnapshotOnlyTest(source: string): boolean {
438
- if (!/\.\s*toMatch(?:Inline)?Snapshot\s*\(/.test(source)) {
439
- return false;
440
- }
441
- const withoutSnapshots = source
442
- .replace(/\bexpect\s*\([\s\S]*?\)\s*\.\s*toMatch(?:Inline)?Snapshot\s*\([^)]*\)\s*;?/g, "")
443
- .replace(/\bexpect\.(?:assertions|hasAssertions)\s*\([^)]*\)\s*;?/g, "");
444
- return !hasAssertion(withoutSnapshots);
445
- }
446
-
447
- // Same shape as `isSnapshotOnlyTest` but for `doesNotThrow` / `not.toThrow`. A test that asserts
448
- // only the absence of an exception is weak - `test-quality.no-throw-only-test` reports it so
449
- // authors can add a real behaviour assertion alongside.
450
- function isNoThrowOnlyTest(source: string): boolean {
451
- if (!/\bassert\.doesNotThrow\s*\(|\.\s*not\s*\.\s*toThrow\s*\(/.test(source)) {
452
- return false;
453
- }
454
- const withoutNoThrow = source
455
- .replace(/\bassert\.doesNotThrow\s*\([\s\S]*?\)\s*;?/g, "")
456
- .replace(/\bexpect\s*\([\s\S]*?\)\s*\.\s*not\s*\.\s*toThrow\s*\([^)]*\)\s*;?/g, "")
457
- .replace(/\bexpect\.(?:assertions|hasAssertions)\s*\([^)]*\)\s*;?/g, "");
458
- return !hasAssertion(withoutNoThrow);
459
- }
460
-
461
- // Pulls every numeric expected value out of `expect(...).toBe(n)` and `assert.equal(actual, n)`
462
- // shapes. Small cardinalities and length/count matchers are excluded because the literal often is
463
- // the test contract; larger opaque values still surface for naming or rationale.
464
- function magicNumberAssertions(source: string): Array<{ value: number }> {
465
- return MAGIC_NUMBER_ASSERTION_PATTERNS.flatMap((candidate) => magicNumberAssertionMatches(source, candidate));
466
- }
467
-
468
- const MAGIC_NUMBER_ASSERTION_PATTERNS: MagicNumberAssertionPattern[] = [
469
- { pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*(to(?:Be|Equal|HaveLength|HaveCount))\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, matcherIndex: 2, valueIndex: 3 },
470
- { pattern: /\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*(-?\d+(?:\.\d+)?)(?:\s*,|\s*\))/g, expressionIndex: 1, valueIndex: 2 },
471
- ];
472
-
473
- // Extracts reportable numeric literals for one assertion grammar while keeping HTTP statuses quiet.
474
- function magicNumberAssertionMatches(source: string, candidate: MagicNumberAssertionPattern): Array<{ value: number }> {
475
- const results: Array<{ value: number }> = [];
476
- for (const match of source.matchAll(candidate.pattern)) {
477
- const expression = match[candidate.expressionIndex] ?? "";
478
- const matcher = candidate.matcherIndex === undefined ? "" : match[candidate.matcherIndex] ?? "";
479
- const expectedNumber = Number(match[candidate.valueIndex] ?? "0");
480
- if (!isIgnoredMagicNumberAssertion(expression, matcher, expectedNumber)) {
481
- results.push({ value: expectedNumber });
482
- }
483
- }
484
- return results;
485
- }
486
-
487
- // Centralises the rule's non-findings so cardinal, count, and HTTP-status exemptions stay aligned.
488
- function isIgnoredMagicNumberAssertion(expression: string, matcher: string, expectedNumber: number): boolean {
489
- return isSmallCardinal(expectedNumber) || isLengthOrCountMatcher(matcher) || isHttpStatusAssertion(expression, expectedNumber);
490
- }
491
-
492
- // Small integer cardinals usually express the expected case count directly.
493
- function isSmallCardinal(cardinal: number): boolean {
494
- return Number.isInteger(cardinal) && cardinal >= -1 && cardinal <= 3;
495
- }
496
-
497
- // Length/count matchers already name the measurement, so the numeric literal is the assertion.
498
- function isLengthOrCountMatcher(matcher: string): boolean {
499
- return matcher === "toHaveLength" || matcher === "toHaveCount";
500
- }
501
-
502
- // Contract-named tests may assert the documented number directly; the name supplies the rationale.
503
- function isConstantContractTestName(name: string): boolean {
504
- return /\b(?:constant|threshold|limit|budget|default|contract)\b/i.test(name);
505
- }
506
-
507
- // HTTP response status codes are intentionally numeric at assertion sites; naming every 200/404
508
- // would add ceremony without making the test clearer.
509
- function isHttpStatusAssertion(expression: string, expectedNumber: number): boolean {
510
- return Number.isInteger(expectedNumber) && expectedNumber >= 100 && expectedNumber <= 599 && /\b(?:status|statusCode)\b/.test(expression);
511
- }
512
-
513
- // `const mockX = vi.fn(...)` declarations whose binding appears only once in the body - that one
514
- // occurrence is the declaration itself, so the mock is created but never wired in. Reports the
515
- // names for `test-quality.unused-mock` to anchor on.
615
+ /**
616
+ * Find `const mockX = vi.fn(...)` declarations whose binding appears only once in the body,
617
+ * because that single occurrence is the declaration itself and the mock is never wired in.
618
+ *
619
+ * @param source - masked test body scanned for mock variable declarations and references
620
+ * @returns Unused mock variable names for `test-quality.unused-mock` to anchor on.
621
+ */
516
622
  function unusedMockVariables(source: string): string[] {
517
623
  const names: string[] = [];
518
624
  for (const match of source.matchAll(/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:(?:vi|jest)\.fn|sinon\.stub|createMock|mock)\s*\(/g)) {
@@ -527,29 +633,13 @@ function unusedMockVariables(source: string): string[] {
527
633
  return names;
528
634
  }
529
635
 
530
- // Three gates in order: a mock factory must exist, a mock-call matcher must be asserted, and
531
- // *every* `expect(target)` argument must look like a mock/stub/spy name. All three together
532
- // signal a test that only verifies its own scaffolding - flagged for `test-quality.mock-only-test`.
533
- function isMockOnlyTest(source: string): boolean {
534
- if (!/\b(?:vi|jest)\.fn\s*\(|\b(?:createMock|mock|sinon\.stub)\s*\(/.test(source)) {
535
- return false;
536
- }
537
- if (!/\.(?:toHaveBeenCalled|toHaveBeenCalledWith|toHaveBeenNthCalledWith|toBeCalled|toBeCalledWith)\s*\(/.test(source)) {
538
- return false;
539
- }
540
- const targets = [...source.matchAll(/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\)/g)].map((match) => match[1] ?? "");
541
- return targets.length > 0 && targets.every((target) => /(?:mock|stub|spy)$/i.test(target));
542
- }
543
-
544
- // `toThrow(Error)` / `assert.throws(fn, Error)` constrain only the constructor, not the message
545
- // or properties. Reports `test-quality.exception-type-only` so authors tighten the assertion.
546
- function hasExceptionTypeOnlyAssertion(source: string): boolean {
547
- return /\.toThrow\s*\(\s*(?:Error|[A-Z][A-Za-z0-9_$]*Error)\s*\)/.test(source) || /\bassert\.throws\s*\([^,\n]+,\s*(?:Error|[A-Z][A-Za-z0-9_$]*Error)\s*\)/.test(source);
548
- }
549
-
550
- // Three known anti-patterns: writing to `process.env`, writing to `globalThis.*`, or reassigning
551
- // `Date.now` / `Math.random`. Each leaks state across tests; reports
552
- // `test-quality.global-state-mutation` so the author isolates the fixture.
636
+ /**
637
+ * Check whether source matches the supported process.env, globalThis, Date.now or Math.random assignment patterns.
638
+ * This textual check does not establish whether state is restored.
639
+ *
640
+ * @param source - masked test body scanned for shared-state assignments
641
+ * @returns True when a supported shared-state assignment pattern matches, used to report possible mutation; false otherwise.
642
+ */
553
643
  function hasGlobalStateMutation(source: string): boolean {
554
644
  return /\bprocess\.env\.[A-Za-z0-9_]+\s*=/.test(source) || /\bglobalThis\.[A-Za-z0-9_$]+\s*=/.test(source) || /\b(?:Date\.now|Math\.random)\s*=/.test(source);
555
645
  }