@blundergoat/gruff-ts 0.4.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 +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  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 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  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 +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  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 +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  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 +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,372 +1,531 @@
1
- // Class + naming-inventory rules: exported-declaration docs, class/file-name mismatch,
2
- // public-property + readonly candidates, inconsistent casing, acronym case, interface fields.
3
- // Pulls the declaration walkers and casing helpers out of cli.ts so the orchestrator just calls
4
- // the entry points.
5
- import { type FunctionBlock, parameterNames } from "./blocks.ts";
6
- import { type ExportedDeclaration, exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
1
+ // Evaluates class-level documentation, class/file naming alignment, and `readonly` property candidates.
2
+ //
3
+ // Walks the shared syntax tree (ADR-012) to verify whether private instance fields are written outside the constructor.
4
+ // Invoked by `analyser.ts` per script when any class-level rule is enabled.
5
+ import { exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
7
6
  import { type SourceFile } from "./discovery.ts";
8
7
  import { makeFinding } from "./findings.ts";
9
- import { fileBaseName, finding, normalizedIdentifier } from "./findings-helpers.ts";
10
- import { pushBooleanPrefixAt, pushNegativeBooleanAt, type NamingSurface } from "./naming-pushers.ts";
8
+ import { fileBaseName, normalizedIdentifier } from "./findings-helpers.ts";
9
+ import { type ParsedScript } from "./parsed-script.ts";
10
+ import { publicExportDeclarations, type PublicExportDeclaration } from "./public-exports.ts";
11
11
  import { byteLine } from "./text-scans.ts";
12
12
  import type { Config, Finding } from "./types.ts";
13
+ import { createRequire } from "node:module";
13
14
 
14
- // One identifier observation. `line` is the declaration line in the original source so the casing
15
- // and acronym rules can report a stable, reproducible location.
16
- interface DeclaredIdentifier {
17
- name: string;
18
- line: number;
19
- surface: NamingSurface;
20
- }
15
+ // Syntax-only TypeScript parser (ADR-012): node guards for walking the shared parse - no type
16
+ // checker, program, language service, or emit. Loaded via createRequire because typescript ships
17
+ // as CommonJS.
18
+ const require = createRequire(import.meta.url);
19
+ const typescriptSyntax = require("typescript") as typeof import("typescript");
21
20
 
22
- // Aggregates `const`/`let`/`var` declarations, callable parameters, and interface fields into a
23
- // single de-duplicated list. The naming rules walk this once instead of re-parsing the file.
24
- export function collectDeclaredIdentifiers(source: string, codeSource: string, blocks: FunctionBlock[]): DeclaredIdentifier[] {
25
- const inventory: DeclaredIdentifier[] = [];
26
- const seen = new Set<string>();
27
- const push = (name: string, line: number, surface: NamingSurface): void => {
28
- if (!name) return;
29
- const key = `${name}@${line}@${surface}`;
30
- if (seen.has(key)) return;
31
- seen.add(key);
32
- inventory.push({ name, line, surface });
33
- };
21
+ type TsSourceFile = import("typescript").SourceFile;
22
+ type TsNode = import("typescript").Node;
23
+ type TsExpression = import("typescript").Expression;
24
+ type TsClassLike = import("typescript").ClassLikeDeclaration;
34
25
 
35
- for (const match of codeSource.matchAll(/\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) {
36
- push(match[1] ?? "", byteLine(source, match.index ?? 0), "declaration");
37
- }
38
- for (const block of blocks) {
39
- for (const parameter of parameterNames(block.params)) {
40
- push(parameter.name, block.declarationLine, "parameter");
41
- }
42
- }
43
- for (const fieldMatch of collectInterfaceFieldDeclarations(source, codeSource)) {
44
- push(fieldMatch.name, fieldMatch.line, "interface-field");
45
- }
46
- return inventory;
26
+ /**
27
+ * Runs class rules in stable order, checking export documentation and file naming before readonly candidates.
28
+ *
29
+ * @param file - source file used for finding anchors and class/file name comparisons
30
+ * @param source - original text used for source lines and documentation checks
31
+ * @param codeSource - masked text searched for declarations and fields
32
+ * @param config - naming configuration, including accepted class/file pairs
33
+ * @param findings - shared collector that receives the class rule findings
34
+ * @param parsed - shared syntax tree. Without it, naming uses direct exports and the readonly check is skipped.
35
+ * @returns Nothing. It appends any findings from the class rules.
36
+ */
37
+ export function analyseClassRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
38
+ analyseExportedDeclarations(file, source, codeSource, config, findings, parsed);
39
+ analyseReadonlyCandidates(file, source, codeSource, findings, parsed);
47
40
  }
48
41
 
49
- // Walks every interface body line and matches the field declaration regex. Used both for the
50
- // naming inventory (above) and for the per-field interface rules (boolean prefix, negative-boolean).
51
- function collectInterfaceFieldDeclarations(source: string, codeSource: string): DeclaredIdentifier[] {
52
- const fieldRegex = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/;
53
- const out: DeclaredIdentifier[] = [];
54
- for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
55
- const name = sourceLine.match(fieldRegex)?.[1] ?? "";
56
- if (name) out.push({ name, line: lineIndex + 1, surface: "interface-field" });
42
+ /**
43
+ * Checks documentation on direct exports, then uses the syntax inventory when available to cover default exports and re-exports in naming checks.
44
+ * This preserves the direct-export documentation contract.
45
+ *
46
+ * @param file - source file used for finding anchors and the class/file name comparison
47
+ * @param source - original text used to locate declarations and leading documentation
48
+ * @param codeSource - masked text searched for direct exports
49
+ * @param config - naming configuration, including accepted class/file pairs
50
+ * @param findings - shared collector for documentation and naming findings
51
+ * @param parsed - shared export syntax. When absent, the naming check uses the direct-export inventory.
52
+ * @returns Nothing. It appends any documentation and class/file naming findings to the collector.
53
+ */
54
+ function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
55
+ const directlyExportedDeclarations = exportedDeclarations(source, codeSource);
56
+ // Public-doc findings retain their existing direct-export policy and deterministic source order.
57
+ for (const declaration of directlyExportedDeclarations) {
58
+ pushMissingPublicDocFinding(file, source, declaration, findings);
57
59
  }
58
- return out;
60
+ // Direct internal callers without a parse retain the legacy five-kind inventory; normal scans use syntax.
61
+ const modulePublicDeclarations = parsed
62
+ ? publicExportDeclarations(parsed)
63
+ : directlyExportedDeclarations.map((declaration) => ({ ...declaration, kind: declaration.kind as PublicExportDeclaration["kind"] }));
64
+ pushClassFileMismatchFinding(file, modulePublicDeclarations, config, findings);
59
65
  }
60
66
 
61
- // Strips separators only so `userId`, `user_id`, and `userID` collapse, while `adr013` and
62
- // `adr020` remain distinct domain tokens instead of fake casing variants.
63
- // Two names sharing this key but differing in original form are the casing-drift signal.
64
- function casingCanonicalKey(name: string): string {
65
- return name.toLowerCase().replace(/[_\-]/g, "");
67
+ /**
68
+ * Reports a class/file mismatch for a sole named public class, using normalized names to avoid warnings for equivalent spellings.
69
+ *
70
+ * @param file - file whose base name is compared and whose path anchors a stable finding
71
+ * @param publicDeclarations - module exports used to decide whether one class represents the file and whether its alias matches
72
+ * @param config - configured class/file pairs that are accepted even when the names differ
73
+ * @param findings - collector that receives the mismatch when the class and its alias differ from the file name
74
+ * @returns Nothing. It appends at most one class/file mismatch finding.
75
+ */
76
+ function pushClassFileMismatchFinding(file: SourceFile, publicDeclarations: PublicExportDeclaration[], config: Config, findings: Finding[]): void {
77
+ // Feature modules with a second public declaration do not claim one primary class-to-file convention.
78
+ if (publicDeclarations.length !== 1) {
79
+ return;
80
+ }
81
+ const declaration = publicDeclarations[0];
82
+ // Anonymous defaults and non-class exports have no named class for a user to align with the file.
83
+ if (!declaration || declaration.kind !== "class" || declaration.name === "default") {
84
+ return;
85
+ }
86
+ const fileName = fileBaseName(file.displayPath);
87
+ const acceptedPair = `${fileName}:${declaration.name}`.toLowerCase();
88
+ // Pair-level configuration preserves an intentional feature-file/class-role convention narrowly.
89
+ if (config.acceptedClassFilePairs.has(acceptedPair)) {
90
+ return;
91
+ }
92
+ // A normalized name match already lets a report user locate the class from the file name. An
93
+ // alias counts too: `export { Foo as Bar }` in `bar.ts` already advertises the matching name, so
94
+ // telling the reader to rename would undo an alignment they have made.
95
+ const publicNames = declaration.exportedName === undefined ? [declaration.name] : [declaration.name, declaration.exportedName];
96
+ if (publicNames.some((publicName) => normalizedIdentifier(publicName) === normalizedIdentifier(fileName))) {
97
+ return;
98
+ }
99
+ findings.push(
100
+ makeFinding({
101
+ ruleId: "naming.class-file-mismatch",
102
+ message: `Exported class \`${declaration.name}\` does not match file name \`${fileName}\`.`,
103
+ filePath: file.displayPath,
104
+ line: declaration.line,
105
+ severity: "advisory",
106
+ pillar: "naming",
107
+ confidence: "medium",
108
+ symbol: declaration.name,
109
+ remediation: "Rename the class or file, or add the exact fileBase:ClassName pair to allowlists.acceptedClassFilePairs.",
110
+ metadata: {
111
+ className: declaration.name,
112
+ fileName,
113
+ candidatePrimaryExport: true,
114
+ publicExports: publicDeclarations.map((publicDeclaration) => `${publicDeclaration.kind}:${publicDeclaration.name}`).sort(),
115
+ },
116
+ }),
117
+ );
66
118
  }
67
119
 
68
- /*
69
- * Groups identifiers by canonical key, then filters out boundary surfaces before reporting. The
70
- * split helper flow is intentional: the rule must preserve same-scope drift signal while refusing
71
- * to command rewrites of constants, DTO fields, or intentionally-unused `_` names. Error behavior:
72
- * never throws; it reports drift by appending findings only.
120
+ /**
121
+ * Suggests readonly for typed private instance fields without an initializer when the syntax scan detects no writes outside construction.
122
+ * Restricts candidates to private fields because writes to public or protected fields can occur outside the scanned file.
123
+ *
124
+ * @param file - source file whose display path anchors any finding
125
+ * @param source - original text used to retain stable finding lines
126
+ * @param codeSource - masked text searched for field declarations
127
+ * @param findings - collector that receives readonly candidate findings
128
+ * @param parsed - shared syntax tree used to check writes. A missing parse or syntax diagnostics skip the rule.
129
+ * @returns Nothing. It appends findings for qualifying fields.
73
130
  */
74
- export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], findings: Finding[]): void {
75
- for (const entries of declaredIdentifierGroups(inventory).values()) {
76
- const candidate = inconsistentCasingCandidate(entries);
77
- if (!candidate) {
131
+ function analyseReadonlyCandidates(file: SourceFile, source: string, codeSource: string, findings: Finding[], parsed?: ParsedScript): void {
132
+ const syntax = parsed?.diagnostics.length === 0 ? parsed.sourceFile : undefined;
133
+ if (syntax === undefined) {
134
+ return;
135
+ }
136
+ const constructionOnlyNames = constructionOnlyFieldNameStarts(syntax);
137
+ const readonlyCandidate = /\bprivate\s+(?!readonly\b)([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^;=\n]+;/g;
138
+ for (const match of codeSource.matchAll(readonlyCandidate)) {
139
+ const name = match[1] ?? "";
140
+ const nameStart = (match.index ?? 0) + match[0].indexOf(name, "private".length);
141
+ // A match that is not a field declaration, or a field written after construction, is no candidate.
142
+ if (!constructionOnlyNames.has(nameStart)) {
78
143
  continue;
79
144
  }
80
- findings.push(inconsistentCasingFinding(file, candidate));
145
+ findings.push(
146
+ makeFinding({
147
+ ruleId: "modernisation.readonly-property-candidate",
148
+ message: `Property \`${name}\` can be marked readonly if it is only assigned during construction.`,
149
+ filePath: file.displayPath,
150
+ line: byteLine(source, match.index ?? 0),
151
+ severity: "advisory",
152
+ pillar: "modernisation",
153
+ confidence: "medium",
154
+ symbol: name,
155
+ remediation: "Mark the property readonly when mutation is not part of the type contract.",
156
+ }),
157
+ );
81
158
  }
82
159
  }
83
160
 
84
- // Builds canonical-key groups once so the reporting pass can stay focused on rule semantics.
85
- function declaredIdentifierGroups(inventory: DeclaredIdentifier[]): Map<string, DeclaredIdentifier[]> {
86
- const groups = new Map<string, DeclaredIdentifier[]>();
87
- for (const entry of inventory) {
88
- const key = casingCanonicalKey(entry.name);
89
- if (!key) continue;
90
- const list = groups.get(key) ?? [];
91
- list.push(entry);
92
- groups.set(key, list);
93
- }
94
- return groups;
161
+ /**
162
+ * Scans the AST for mutable private instance fields that can proceed to the readonly check.
163
+ * Skips classes with bracket writes on this or Object.assign calls targeting this because the scan treats their targets as uncertain.
164
+ *
165
+ * @param sourceFile - parsed syntax tree whose class declarations and expressions are inspected
166
+ * @returns Name start offsets for fields without disqualifying writes, allowing direct `this.name` writes in the class's own constructor.
167
+ */
168
+ function constructionOnlyFieldNameStarts(sourceFile: TsSourceFile): Set<number> {
169
+ const starts = new Set<number>();
170
+ /**
171
+ * Visits a syntax subtree and collects readonly candidate field offsets for any class-like declarations or expressions.
172
+ *
173
+ * @param node - syntax node whose subtree is traversed for class-like nodes
174
+ * @returns Nothing. Adds candidate field name offsets to `starts` for classes and class expressions in the subtree rooted at `node`.
175
+ */
176
+ const visit = (node: TsNode): void => {
177
+ if (typescriptSyntax.isClassLike(node)) {
178
+ addConstructionOnlyFields(sourceFile, node, starts);
179
+ }
180
+ node.forEachChild(visit);
181
+ };
182
+ sourceFile.forEachChild(visit);
183
+ return starts;
95
184
  }
96
185
 
97
- // Invariant: returns the exact variant pair to report after boundary-aware suppression has run.
98
- function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
99
- const reportableEntries = casingReportableEntries(entries);
100
- const sameSurfaceEntries = sameCasingSurfaceEntries(reportableEntries);
101
- const surfaces = [...new Set(sameSurfaceEntries.map((entry) => entry.name))].sort();
102
- if (surfaces.length < 2) {
103
- return undefined;
186
+ /**
187
+ * Collects the source start offsets of mutable private instance fields in a class that have no disqualifying writes.
188
+ *
189
+ * @param sourceFile - syntax tree used to resolve each candidate property name's start offset
190
+ * @param classNode - class declaration or expression whose members are checked for writes
191
+ * @param starts - set receiving the name start offsets of qualifying readonly candidate fields
192
+ * @returns Nothing. Adds the `sourceFile` name offsets of `classNode`'s readonly candidates to `starts`.
193
+ */
194
+ function addConstructionOnlyFields(sourceFile: TsSourceFile, classNode: TsClassLike, starts: Set<number>): void {
195
+ const written = writtenMemberNames(classNode);
196
+ // Skip readonly suggestions for this class when a bracket write on this or Object.assign(this, ...) leaves the target members uncertain.
197
+ if (written === undefined) {
198
+ return;
104
199
  }
105
- const sorted = [...sameSurfaceEntries].sort((a, b) => a.line - b.line);
106
- const first = sorted[0];
107
- const second = sorted.find((entry, index) => index > 0 && entry.name !== first?.name);
108
- return first && second ? { first, second, surfaces } : undefined;
109
- }
110
-
111
- // Builds the stable finding after candidate selection so fingerprint shape stays in one place.
112
- function inconsistentCasingFinding(file: SourceFile, candidate: { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] }): Finding {
113
- return makeFinding({
114
- ruleId: "naming.inconsistent-casing",
115
- message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` in the same file.`,
116
- filePath: file.displayPath,
117
- line: candidate.second.line,
118
- severity: "advisory",
119
- pillar: "naming",
120
- confidence: "medium",
121
- symbol: candidate.second.name,
122
- remediation: "Choose one form and use it consistently within the file.",
123
- metadata: { variants: candidate.surfaces },
124
- });
125
- }
126
-
127
- // `_event` is the standard intentionally-unused spelling; comparing it with `event` would tell an
128
- // agent to remove useful boundary information rather than fix casing drift.
129
- function casingReportableEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
130
- return entries.filter((entry) => !entry.name.startsWith("_"));
131
- }
132
-
133
- // Contract fields and SCREAMING_SNAKE constants are boundary surfaces; remove only those entries so
134
- // they do not mask real local drift elsewhere in the same canonical group.
135
- function sameCasingSurfaceEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
136
- const hasLocalSurface = entries.some((entry) => entry.surface !== "interface-field" && !isScreamingConstant(entry.name));
137
- return entries.filter((entry) => {
138
- if (hasLocalSurface && entry.surface === "interface-field") {
139
- return false;
200
+ for (const member of classNode.members) {
201
+ if (typescriptSyntax.isPropertyDeclaration(member) && typescriptSyntax.isIdentifier(member.name)
202
+ && isMutablePrivateInstanceField(member) && !written.has(member.name.text)) {
203
+ starts.add(member.name.getStart(sourceFile));
140
204
  }
141
- return !(hasLocalSurface && isScreamingConstant(entry.name));
142
- });
143
- }
144
-
145
- // Recognises constant-style identifiers without stripping digits, so `V110` remains one token.
146
- function isScreamingConstant(name: string): boolean {
147
- return /^[A-Z][A-Z0-9_]*$/.test(name) && /[A-Z]/.test(name);
205
+ }
148
206
  }
149
207
 
150
- // Splits camelCase, PascalCase, snake_case, and kebab-case into tokens. The regex preserves
151
- // uppercase runs as a single token so the acronym detector sees `URL` and `url` as the same word.
152
- function tokensForAcronymCheck(name: string): string[] {
153
- const split = name.split(/[_\-]+/).filter(Boolean);
154
- const tokens: string[] = [];
155
- for (const part of split) {
156
- const matches = part.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z0-9]+|[A-Z]+/g);
157
- if (matches) tokens.push(...matches);
158
- else tokens.push(part);
159
- }
160
- return tokens;
208
+ /**
209
+ * Checks whether a property declaration is a `private` instance field that is neither `static` nor already `readonly`.
210
+ *
211
+ * @param member - property declaration whose modifiers are inspected
212
+ * @returns True when `member` has the `private` modifier and lacks both `readonly` and `static`.
213
+ */
214
+ function isMutablePrivateInstanceField(member: import("typescript").PropertyDeclaration): boolean {
215
+ const kinds = new Set((member.modifiers ?? []).map((modifier) => modifier.kind));
216
+ return kinds.has(typescriptSyntax.SyntaxKind.PrivateKeyword)
217
+ && !kinds.has(typescriptSyntax.SyntaxKind.ReadonlyKeyword)
218
+ && !kinds.has(typescriptSyntax.SyntaxKind.StaticKeyword);
161
219
  }
162
220
 
163
- // Three-bucket classification used to detect when one project uses both `URL` and `Url` styles -
164
- // the rule flags drift when two of the three buckets are seen for the same acronym in one file.
165
- function acronymCaseClass(token: string): "upper" | "lower" | "title" {
166
- if (token === token.toUpperCase()) return "upper";
167
- if (token === token.toLowerCase()) return "lower";
168
- return "title";
221
+ /**
222
+ * Scans `classNode` for identifiable member writes, including writes on other receivers and inside nested functions.
223
+ * Excludes direct `this.name` writes in the class's own constructor. An empty set rules out no fields.
224
+ *
225
+ * @param classNode - class declaration or expression whose subtree is scanned for member writes
226
+ * @returns Written member names, or `undefined` on bracket writes to `this` or `Object.assign` targeting `this` so the caller skips the class.
227
+ */
228
+ function writtenMemberNames(classNode: TsClassLike): Set<string> | undefined {
229
+ const written = new Set<string>();
230
+ let writesDynamically = false;
231
+ /**
232
+ * Updates `written` for property targets in `target`, excluding direct `this.name` writes in `classNode`'s own constructor.
233
+ * Sets `writesDynamically` instead on `this[...]` targets, recurses into destructuring, and records static string keys on other receivers.
234
+ *
235
+ * @param target - left-hand expression or destructuring pattern being written to
236
+ * @param write - enclosing write AST node used to check whether the write occurs in `classNode`'s own constructor
237
+ * @returns Nothing. Updates `written` or `writesDynamically` based on the resolved targets.
238
+ */
239
+ const record = (target: TsExpression, write: TsNode): void => {
240
+ const inner = withoutWrappers(target);
241
+ if (typescriptSyntax.isPropertyAccessExpression(inner)) {
242
+ if (!(isThisKeyword(inner.expression) && isInOwnConstructor(write, classNode))) {
243
+ written.add(inner.name.text);
244
+ }
245
+ } else if (typescriptSyntax.isElementAccessExpression(inner)) {
246
+ const keyExpression = withoutWrappers(inner.argumentExpression);
247
+ if (isThisKeyword(inner.expression)) {
248
+ writesDynamically = true;
249
+ } else if (typescriptSyntax.isStringLiteralLike(keyExpression)) {
250
+ // A quoted key such as `other["label"] = value` writes that named property.
251
+ written.add(keyExpression.text);
252
+ } else if (typescriptSyntax.isIdentifier(keyExpression)) {
253
+ // A key held in a local constant, such as `other[key] = value`, writes the property that constant names.
254
+ const resolvedKey = resolvedConstStringLiteral(keyExpression);
255
+ // A key that is not a known string constant could be anything, so no property is recorded as written.
256
+ if (resolvedKey !== undefined) {
257
+ written.add(resolvedKey);
258
+ }
259
+ }
260
+ } else if (typescriptSyntax.isObjectLiteralExpression(inner) || typescriptSyntax.isArrayLiteralExpression(inner)) {
261
+ for (const element of destructuringTargets(inner)) {
262
+ record(element, write);
263
+ }
264
+ }
265
+ };
266
+ /**
267
+ * Scans `node` and its descendants for writes, updating `written` and `writesDynamically` through `record`.
268
+ * Marks `Object.assign(this, ...)` as dynamic writes because its sources may supply keys known only at runtime.
269
+ *
270
+ * @param node - syntax node whose subtree is inspected for assignments, updates, deletions, loop targets, and `Object.assign`
271
+ * @returns Nothing. Records member writes into `written` or sets `writesDynamically`.
272
+ */
273
+ const visit = (node: TsNode): void => {
274
+ if (typescriptSyntax.isBinaryExpression(node) && isAssignmentOperator(node.operatorToken.kind)) {
275
+ record(node.left, node);
276
+ } else if ((typescriptSyntax.isPrefixUnaryExpression(node) || typescriptSyntax.isPostfixUnaryExpression(node))
277
+ && (node.operator === typescriptSyntax.SyntaxKind.PlusPlusToken || node.operator === typescriptSyntax.SyntaxKind.MinusMinusToken)) {
278
+ record(node.operand, node);
279
+ } else if (typescriptSyntax.isDeleteExpression(node)) {
280
+ record(node.expression, node);
281
+ } else if ((typescriptSyntax.isForOfStatement(node) || typescriptSyntax.isForInStatement(node))
282
+ && !typescriptSyntax.isVariableDeclarationList(node.initializer)) {
283
+ record(node.initializer, node);
284
+ } else if (isObjectAssignToThis(node)) {
285
+ writesDynamically = true;
286
+ }
287
+ node.forEachChild(visit);
288
+ };
289
+ classNode.forEachChild(visit);
290
+ return writesDynamically ? undefined : written;
169
291
  }
170
292
 
171
- /*
172
- * Reports when an acronym from `config.knownAcronyms` appears as all-caps plus another case form.
173
- * The all-caps gate exists because lower/title-only forms like `apiToken` beside `googleApiKey`
174
- * are idiomatic enough to avoid noisy findings. Like `analyseInconsistentCasing`, the finding
175
- * anchors on the second occurrence so the stable fingerprint sticks to the divergence.
293
+ /**
294
+ * Extracts explicit property-value, array, and rest targets from a destructuring pattern for the member-write scan.
295
+ * Defaults contribute only the assigned target; array holes and shorthand object properties contribute no member target.
296
+ *
297
+ * @param pattern - object or array literal representing a destructuring assignment target
298
+ * @returns Target expressions extracted from `pattern` without default value expressions.
176
299
  */
177
- export function analyseAcronymCase(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
178
- const observed = new Map<string, Map<string, { name: string; line: number }>>();
179
- for (const entry of inventory) {
180
- recordAcronymCases(observed, config, entry);
181
- }
182
- for (const [acronym, cases] of observed) {
183
- pushAcronymCaseFinding(file, acronym, cases, findings);
300
+ function destructuringTargets(pattern: import("typescript").ObjectLiteralExpression | import("typescript").ArrayLiteralExpression): TsExpression[] {
301
+ /**
302
+ * Unwraps a destructuring default assignment to return only its target expression.
303
+ *
304
+ * @param element - destructuring element expression that may be a `target = default` binary expression
305
+ * @returns The assigned side of `element`: the left of `target = default`, otherwise `element` itself.
306
+ */
307
+ const withoutDefault = (element: TsExpression): TsExpression =>
308
+ typescriptSyntax.isBinaryExpression(element) && element.operatorToken.kind === typescriptSyntax.SyntaxKind.EqualsToken ? element.left : element;
309
+ if (typescriptSyntax.isArrayLiteralExpression(pattern)) {
310
+ return pattern.elements.filter((element) => !typescriptSyntax.isOmittedExpression(element))
311
+ .map((element) => withoutDefault(typescriptSyntax.isSpreadElement(element) ? element.expression : element));
184
312
  }
313
+ return pattern.properties.flatMap((property) => {
314
+ if (typescriptSyntax.isPropertyAssignment(property)) {
315
+ return [withoutDefault(property.initializer)];
316
+ }
317
+ return typescriptSyntax.isSpreadAssignment(property) ? [property.expression] : [];
318
+ });
185
319
  }
186
320
 
187
- // Adds one identifier's acronym tokens to the observed case map, skipping fixture-only constants.
188
- function recordAcronymCases(observed: Map<string, Map<string, { name: string; line: number }>>, config: Config, entry: DeclaredIdentifier): void {
189
- if (isFixtureIdentifier(entry.name)) {
190
- return;
191
- }
192
- for (const token of tokensForAcronymCheck(entry.name)) {
193
- const lower = token.toLowerCase();
194
- if (!config.knownAcronyms.has(lower)) continue;
195
- const cases = observed.get(lower) ?? new Map();
196
- const caseKey = acronymCaseClass(token);
197
- if (!cases.has(caseKey)) cases.set(caseKey, { name: entry.name, line: entry.line });
198
- observed.set(lower, cases);
321
+ /**
322
+ * Checks whether a write node belongs directly to `classNode`'s own constructor rather than a nested scope.
323
+ * This ancestry check also includes writes in constructor parameter initializers.
324
+ *
325
+ * @param write - syntax node representing the member write expression
326
+ * @param classNode - owning class declaration or expression to match against the enclosing constructor
327
+ * @returns True when `write` reaches a constructor owned by `classNode` before crossing another function, class, field, or static block.
328
+ */
329
+ function isInOwnConstructor(write: TsNode, classNode: TsClassLike): boolean {
330
+ for (let current = write.parent; current !== undefined; current = current.parent) {
331
+ if (typescriptSyntax.isConstructorDeclaration(current)) {
332
+ return current.parent === classNode;
333
+ }
334
+ if (typescriptSyntax.isFunctionLike(current) || typescriptSyntax.isClassLike(current)
335
+ || typescriptSyntax.isPropertyDeclaration(current) || typescriptSyntax.isClassStaticBlockDeclaration(current)) {
336
+ return false;
337
+ }
199
338
  }
339
+ return false;
200
340
  }
201
341
 
202
- // Reports the stable acronym-case finding only after the all-caps-vs-other drift gate passes.
203
- function pushAcronymCaseFinding(file: SourceFile, acronym: string, cases: Map<string, { name: string; line: number }>, findings: Finding[]): void {
204
- if (!shouldReportAcronymCase(cases)) {
205
- return;
206
- }
207
- const occurrences = [...cases.values()].sort((a, b) => a.line - b.line);
208
- const second = occurrences[1];
209
- if (!second) {
210
- return;
342
+ /**
343
+ * Detects a call spelled `Object.assign` with `this` as its first argument so the caller can treat member writes as uncertain.
344
+ *
345
+ * @param node - syntax node tested for an `Object.assign(this, ...)` call expression
346
+ * @returns True when `node` calls `Object.assign` with a wrapped or bare `this` as its first argument.
347
+ */
348
+ function isObjectAssignToThis(node: TsNode): boolean {
349
+ if (!typescriptSyntax.isCallExpression(node) || !typescriptSyntax.isPropertyAccessExpression(node.expression)) {
350
+ return false;
211
351
  }
212
- findings.push(
213
- makeFinding({
214
- ruleId: "naming.acronym-case",
215
- message: `Acronym \`${acronym.toUpperCase()}\` appears in multiple cases in this file.`,
216
- filePath: file.displayPath,
217
- line: second.line,
218
- severity: "advisory",
219
- pillar: "naming",
220
- confidence: "medium",
221
- symbol: second.name,
222
- remediation: "Use one casing for each acronym throughout the file.",
223
- metadata: { acronym: acronym.toUpperCase(), variants: [...cases.keys()].sort() },
224
- }),
225
- );
352
+ const callee = node.expression;
353
+ const firstArgument = node.arguments[0];
354
+ return typescriptSyntax.isIdentifier(callee.expression) && callee.expression.text === "Object" && callee.name.text === "assign"
355
+ && firstArgument !== undefined && isThisKeyword(firstArgument);
226
356
  }
227
357
 
228
- // Requires an upper-case acronym plus a different case; lower/title-only mixes stay quiet.
229
- function shouldReportAcronymCase(cases: Map<string, { name: string; line: number }>): boolean {
230
- return cases.has("upper") && cases.size >= 2;
358
+ /**
359
+ * Checks whether an expression resolves to the `this` keyword once type and grouping wrappers are stripped.
360
+ *
361
+ * @param expression - syntax expression to unwrap and inspect
362
+ * @returns True when `expression` is `this` after looking through parentheses, non-null assertions, type assertions, and satisfies expressions.
363
+ */
364
+ function isThisKeyword(expression: TsExpression): boolean {
365
+ return withoutWrappers(expression).kind === typescriptSyntax.SyntaxKind.ThisKeyword;
231
366
  }
232
367
 
233
- // Fixture constants often use SCREAMING_SNAKE vendor token names that should not force local
234
- // camelCase variables to adopt the same acronym style.
235
- function isFixtureIdentifier(name: string): boolean {
236
- return /(?:^|[_-])fixture(?:[_-]|$)/i.test(name);
368
+ /**
369
+ * Checks whether a syntax token kind represents an assignment operator.
370
+ *
371
+ * @param kind - TypeScript syntax token kind to test against the assignment operator range
372
+ * @returns True when `kind` is `=` or a compound assignment such as `+=` or `??=`.
373
+ */
374
+ function isAssignmentOperator(kind: import("typescript").SyntaxKind): boolean {
375
+ return kind >= typescriptSyntax.SyntaxKind.FirstAssignment && kind <= typescriptSyntax.SyntaxKind.LastAssignment;
237
376
  }
238
377
 
239
- /*
240
- * Walks every interface field and runs two checks per boolean field: boolean prefix and
241
- * negative boolean. The stable ordering matches `pushBooleanPrefixAt` → `pushNegativeBooleanAt`
242
- * so multiple findings on one field surface in a deterministic sequence.
378
+ /**
379
+ * Resolves a lexically visible `const` string-literal binding for an identifier key (such as `const key = "label" as const; other[key] = ...`)
380
+ * so computed bracket writes on sibling instances mark that property written without treating arbitrary dynamic map writes as uncertain.
381
+ *
382
+ * @param identifier - identifier node used as a bracket access key
383
+ * @returns The bound string literal text when the nearest lexical declaration is a `const` initialized to a string literal; otherwise undefined.
243
384
  */
244
- export function analyseInterfaceFields(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[]): void {
245
- const fieldRegex = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:\s*([^;]+)/;
246
- for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
247
- const match = sourceLine.match(fieldRegex);
248
- const name = match?.[1] ?? "";
249
- if (!name) continue;
250
- if (/^\s*boolean\b/.test(match?.[2] ?? "")) {
251
- pushBooleanPrefixAt(file, lineIndex + 1, name, config, findings, "interface-field");
252
- pushNegativeBooleanAt(file, lineIndex + 1, name, config, findings, "interface-field");
385
+ function resolvedConstStringLiteral(identifier: import("typescript").Identifier): string | undefined {
386
+ const targetName = identifier.text;
387
+ // Walk outward from the key to the nearest declaration of its name.
388
+ for (let current = identifier.parent; current !== undefined; current = current.parent) {
389
+ // A parameter with the same name hides any outer constant, so the key's value is unknown.
390
+ if (typescriptSyntax.isFunctionLike(current) && hasNamedParameter(current, targetName)) {
391
+ return undefined;
253
392
  }
254
- }
255
- }
256
-
257
- const INTERFACE_HEADER_REGEX = /\b(?:export\s+)?(?:interface\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?(?:\s+extends\s+[^{]+)?|type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*)\s*\{/g;
258
-
259
- function* walkInterfaceBodyLines(source: string, codeSource: string): Generator<{ lineIndex: number; sourceLine: string }> {
260
- const codeLines = codeSource.split(/\r?\n/);
261
- const sourceLines = source.split(/\r?\n/);
262
- for (const header of codeSource.matchAll(INTERFACE_HEADER_REGEX)) {
263
- const headerEnd = (header.index ?? 0) + header[0].length;
264
- if (codeSource.slice(headerEnd, headerEnd + 30).trimStart().startsWith("[")) {
393
+ // A loop or catch variable with the same name, as in `for (const key of keys)`, hides an outer constant the same way.
394
+ if (declaresHeaderBinding(current, targetName)) {
395
+ return undefined;
396
+ }
397
+ const statements = scopedStatements(current);
398
+ // Only blocks, files and switch cases hold declarations; other ancestors are passed through.
399
+ if (statements === undefined) {
265
400
  continue;
266
401
  }
267
- const headerLineIndex = byteLine(source, headerEnd - 1) - 1;
268
- const headerLine = codeLines[headerLineIndex] ?? "";
269
- let depth = 1 + countBraceChange(headerLine.slice(headerLine.lastIndexOf("{") + 1));
270
- for (let lineIndex = headerLineIndex + 1; depth > 0 && lineIndex < codeLines.length; lineIndex += 1) {
271
- const codeLine = codeLines[lineIndex] ?? "";
272
- if (depth === 1) {
273
- yield { lineIndex, sourceLine: sourceLines[lineIndex] ?? "" };
274
- }
275
- depth += countBraceChange(codeLine);
402
+ const lookup = constStringInStatements(statements, targetName);
403
+ // The nearest declaration decides: a string constant gives the key, anything else gives no key.
404
+ if (lookup.found) {
405
+ return lookup.value;
276
406
  }
277
407
  }
408
+ return undefined;
278
409
  }
279
410
 
280
- // Net brace delta (`{` minus `}`) for a slice of text. Used by the interface-body walker to track
281
- // nesting depth without parsing the source twice.
282
- function countBraceChange(text: string): number {
283
- let delta = 0;
284
- for (const character of text) {
285
- if (character === "{") {
286
- delta += 1;
287
- } else if (character === "}") {
288
- delta -= 1;
289
- }
290
- }
291
- return delta;
411
+ /**
412
+ * Checks whether a function-like node declares a parameter with `targetName`, shadowing any outer `const` string binding.
413
+ *
414
+ * @param callable - enclosing function, method, constructor, or accessor node
415
+ * @param targetName - identifier name to match against parameter bindings
416
+ * @returns True when any parameter binds `targetName`, including inside a destructured parameter such as `{ key }`; otherwise false.
417
+ */
418
+ function hasNamedParameter(callable: import("typescript").SignatureDeclarationBase, targetName: string): boolean {
419
+ return callable.parameters.some((parameter) => bindingNameIncludes(parameter.name, targetName));
292
420
  }
293
421
 
294
- /*
295
- * Three class-pillar rules in their stable, deterministic emission order: exported-declaration
296
- * docs and file-name mismatch, public-property, readonly candidates.
422
+ /**
423
+ * Checks whether a `for`, `for...of`, `for...in` or `catch` header declares `targetName`, shadowing any outer `const` key.
424
+ *
425
+ * @param node - ancestor node of the bracket key being resolved
426
+ * @param targetName - identifier name to match against the header's bindings
427
+ * @returns True when the node is a loop or catch clause whose header binds `targetName`; false for every other node.
297
428
  */
298
- export function analyseClassRules(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
299
- analyseExportedDeclarations(file, source, codeSource, findings);
300
- analysePublicProperties(file, source, codeSource, findings);
301
- analyseReadonlyCandidates(file, source, codeSource, findings);
429
+ function declaresHeaderBinding(node: TsNode, targetName: string): boolean {
430
+ // A catch clause binds its error variable, which may be destructured as in `catch ({ key })`.
431
+ if (typescriptSyntax.isCatchClause(node)) {
432
+ return node.variableDeclaration !== undefined && bindingNameIncludes(node.variableDeclaration.name, targetName);
433
+ }
434
+ const isLoop = typescriptSyntax.isForStatement(node) || typescriptSyntax.isForOfStatement(node) || typescriptSyntax.isForInStatement(node);
435
+ const initializer = isLoop ? node.initializer : undefined;
436
+ // Only a loop header that declares variables, as in `for (const key of keys)`, can hide the outer name.
437
+ if (initializer === undefined || !typescriptSyntax.isVariableDeclarationList(initializer)) {
438
+ return false;
439
+ }
440
+ return initializer.declarations.some((declaration) => bindingNameIncludes(declaration.name, targetName));
302
441
  }
303
442
 
304
- /*
305
- * Two rules per exported declaration. Both fire from one walk so the file isn't re-scanned for
306
- * each rule. Reports the stable `docs.missing-public-doc` and `naming.class-file-mismatch`
307
- * findings per declaration.
443
+ /**
444
+ * Checks whether a binding name, or any name inside a destructuring pattern, is `targetName`.
445
+ *
446
+ * @param name - identifier or object/array binding pattern from a parameter, variable or catch clause
447
+ * @param targetName - identifier name being looked for
448
+ * @returns True when the binding introduces `targetName` anywhere in the pattern; otherwise false.
308
449
  */
309
- function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
310
- for (const declaration of exportedDeclarations(source, codeSource)) {
311
- pushMissingPublicDocFinding(file, source, declaration, findings);
312
- pushClassFileMismatchFinding(file, declaration, findings);
450
+ function bindingNameIncludes(name: import("typescript").BindingName, targetName: string): boolean {
451
+ // A plain name, as in `(key) => ...`, matches by its text.
452
+ if (typescriptSyntax.isIdentifier(name)) {
453
+ return name.text === targetName;
313
454
  }
455
+ // Destructured names, as in `({ key }) => ...` or `([key]) => ...`, are checked element by element; array holes bind nothing.
456
+ return name.elements.some((element) => typescriptSyntax.isBindingElement(element) && bindingNameIncludes(element.name, targetName));
314
457
  }
315
458
 
316
- /*
317
- * Compares normalised forms (lowercased, no underscores) so `UserProfile` and `user-profile.ts`
318
- * match. Reports the stable `naming.class-file-mismatch` finding when the exported class diverges
319
- * from the file name.
459
+ /**
460
+ * Extracts direct statement lists from block, source-file, or switch-clause lexical containers.
461
+ *
462
+ * @param node - candidate ancestor AST node
463
+ * @returns The node's direct `statements` list when it introduces a statement list, or undefined otherwise.
320
464
  */
321
- function pushClassFileMismatchFinding(file: SourceFile, declaration: ExportedDeclaration, findings: Finding[]): void {
322
- const fileName = fileBaseName(file.displayPath);
323
- if (declaration.kind !== "class" || normalizedIdentifier(declaration.name) === normalizedIdentifier(fileName)) {
324
- return;
465
+ function scopedStatements(node: TsNode): import("typescript").NodeArray<import("typescript").Statement> | undefined {
466
+ // These nodes own the statement lists where a constant key can be declared.
467
+ if (typescriptSyntax.isBlock(node) || typescriptSyntax.isSourceFile(node)
468
+ || typescriptSyntax.isCaseClause(node) || typescriptSyntax.isDefaultClause(node)) {
469
+ return node.statements;
325
470
  }
326
- findings.push(
327
- makeFinding({
328
- ruleId: "naming.class-file-mismatch",
329
- message: `Exported class \`${declaration.name}\` does not match file name \`${fileName}\`.`,
330
- filePath: file.displayPath,
331
- line: declaration.line,
332
- severity: "advisory",
333
- pillar: "naming",
334
- confidence: "medium",
335
- symbol: declaration.name,
336
- remediation: "Rename the class or file so the primary export is easy to locate.",
337
- metadata: { className: declaration.name, fileName },
338
- }),
339
- );
471
+ return undefined;
340
472
  }
341
473
 
342
- // Targets `public foo =` and `public foo:` patterns. The rule message recommends `readonly` or
343
- // accessors because both preserve the field's invariant better than a raw public field, and
344
- // reports each match as a stable `modernisation.public-property` finding.
345
- function analysePublicProperties(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
346
- const publicProperty = /\bpublic\s+[A-Za-z_$][A-Za-z0-9_$]*\s*[=:]/g;
347
- for (const match of codeSource.matchAll(publicProperty)) {
348
- findings.push(finding({ ruleId: "modernisation.public-property", message: "Public class property exposes representation; prefer readonly or accessors when invariants matter.", file, line: byteLine(source, match.index ?? 0), severity: "advisory", pillar: "modernisation" }));
474
+ /**
475
+ * Searches direct variable statements in one lexical block for `targetName` so computed bracket keys resolve to the nearest declaration.
476
+ * Destructured declarations such as `const { key } = opts` still shadow outer constants and stop the outward search with no known value.
477
+ *
478
+ * @param statements - statements belonging to one lexical scope; an empty list reports `{ found: false }`
479
+ * @param targetName - variable identifier being resolved
480
+ * @returns `{ found: true, value }` for a `const` string literal, `{ found: true }` for any other shadowing declaration, or `{ found: false }`.
481
+ */
482
+ function constStringInStatements(
483
+ statements: import("typescript").NodeArray<import("typescript").Statement>,
484
+ targetName: string,
485
+ ): { found: boolean; value?: string } {
486
+ // Look through this scope's statements for a declaration of the key's name.
487
+ for (const statement of statements) {
488
+ // Only variable statements can declare the key's name.
489
+ if (!typescriptSyntax.isVariableStatement(statement)) {
490
+ continue;
491
+ }
492
+ const isConst = (statement.declarationList.flags & typescriptSyntax.NodeFlags.Const) !== 0;
493
+ // One statement can declare several names, as in `const first = "a", second = "b"`.
494
+ for (const declaration of statement.declarationList.declarations) {
495
+ // A destructured binding such as `const { key } = opts` shadows an outer constant with an unknown runtime value.
496
+ if (!typescriptSyntax.isIdentifier(declaration.name)) {
497
+ if (bindingNameIncludes(declaration.name, targetName)) {
498
+ return { found: true };
499
+ }
500
+ continue;
501
+ }
502
+ // Skip declarations that bind a different variable name.
503
+ if (declaration.name.text !== targetName) {
504
+ continue;
505
+ }
506
+ const unwrapped = declaration.initializer === undefined ? undefined : withoutWrappers(declaration.initializer);
507
+ // Only a `const` set to a string literal keeps the same value until the write.
508
+ if (isConst && unwrapped !== undefined && typescriptSyntax.isStringLiteralLike(unwrapped)) {
509
+ return { found: true, value: unwrapped.text };
510
+ }
511
+ return { found: true };
512
+ }
349
513
  }
514
+ return { found: false };
350
515
  }
351
516
 
352
- // Visibility-modifier fields without `readonly`. The negative lookahead skips already-readonly
353
- // properties; each remaining match reports a stable `modernisation.readonly-property-candidate`.
354
- function analyseReadonlyCandidates(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
355
- const readonlyCandidate = /\b(?:public|private|protected)\s+(?!readonly\b)([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^;=\n]+;/g;
356
- for (const match of codeSource.matchAll(readonlyCandidate)) {
357
- const name = match[1] ?? "";
358
- findings.push(
359
- makeFinding({
360
- ruleId: "modernisation.readonly-property-candidate",
361
- message: `Property \`${name}\` can be marked readonly if it is only assigned during construction.`,
362
- filePath: file.displayPath,
363
- line: byteLine(source, match.index ?? 0),
364
- severity: "advisory",
365
- pillar: "modernisation",
366
- confidence: "medium",
367
- symbol: name,
368
- remediation: "Mark the property readonly when mutation is not part of the type contract.",
369
- }),
370
- );
517
+ /**
518
+ * Unwraps transparent grouping and type-level expressions around a write target or receiver.
519
+ *
520
+ * @param expression - expression potentially wrapped in parentheses, non-null assertions, type assertions, or satisfies expressions
521
+ * @returns The underlying write target or receiver after stripping all wrapper expressions.
522
+ */
523
+ function withoutWrappers(expression: TsExpression): TsExpression {
524
+ let current = expression;
525
+ while (typescriptSyntax.isParenthesizedExpression(current) || typescriptSyntax.isNonNullExpression(current)
526
+ || typescriptSyntax.isAsExpression(current) || typescriptSyntax.isTypeAssertionExpression(current)
527
+ || typescriptSyntax.isSatisfiesExpression(current)) {
528
+ current = current.expression;
371
529
  }
530
+ return current;
372
531
  }