@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,432 +1,55 @@
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.
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
5
  import { exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
6
6
  import { type SourceFile } from "./discovery.ts";
7
7
  import { makeFinding } from "./findings.ts";
8
- import { fileBaseName, finding, normalizedIdentifier, parameterNames } from "./findings-helpers.ts";
9
- import { pushBooleanPrefixAt, pushNegativeBooleanAt, type NamingSurface } from "./naming-pushers.ts";
10
- import { callableMatchPoints, declarationOwnershipPoints, type IdentifierOwner, type OwnedDeclarationPoint, type ParsedScript } from "./parsed-script.ts";
8
+ import { fileBaseName, normalizedIdentifier } from "./findings-helpers.ts";
9
+ import { type ParsedScript } from "./parsed-script.ts";
11
10
  import { publicExportDeclarations, type PublicExportDeclaration } from "./public-exports.ts";
12
11
  import { byteLine } from "./text-scans.ts";
13
12
  import type { Config, Finding } from "./types.ts";
14
-
15
- /*
16
- * One shared naming observation used by casing and acronym diagnostics. Name, line, and surface
17
- * preserve the report rows users already saw, while syntax-derived owner fields explain which
18
- * declaration or lexical scope the casing rule compares.
19
- */
20
- interface DeclaredIdentifier extends IdentifierOwner {
21
- name: string;
22
- line: number;
23
- surface: NamingSurface;
24
- }
25
-
26
- const MODULE_NAMING_OWNER: IdentifierOwner = { ownerId: "module", ownerKind: "module" };
27
-
28
- // Adds shared syntax owners to the existing text inventory, preserving every name/line/surface row.
29
- // The casing and acronym rules receive one ordered inventory without another parse or AST walk.
30
- export function collectDeclaredIdentifiers(source: string, codeSource: string, parsed: ParsedScript): DeclaredIdentifier[] {
31
- const inventory: DeclaredIdentifier[] = [];
32
- const seenIdentifiers = new Set<string>();
33
- // Records one identifier per (name, line, surface) so overlapping scans stay de-duplicated.
34
- const recordIdentifier = (name: string, line: number, surface: NamingSurface, owner: IdentifierOwner): void => {
35
- // Recovered or unsupported declarations can have no simple name, so users see no row for them.
36
- if (!name) {
37
- return;
38
- }
39
- const observationKey = `${name}@${line}@${surface}`;
40
- // Overlapping syntax shapes must still produce only one acronym and casing observation.
41
- if (seenIdentifiers.has(observationKey)) {
42
- return;
43
- }
44
- seenIdentifiers.add(observationKey);
45
- // Module and anonymous-function rows omit ownerName instead of exposing an undefined field.
46
- inventory.push({
47
- name,
48
- line,
49
- surface,
50
- ownerId: owner.ownerId,
51
- ownerKind: owner.ownerKind,
52
- ...(owner.ownerName === undefined ? {} : { ownerName: owner.ownerName }),
53
- });
54
- };
55
-
56
- const declarationOwnership = declarationOwnershipPoints(parsed);
57
- const variableOwners = declarationOwnerLookup(declarationOwnership.variableDeclarations);
58
- const contractFieldOwners = declarationOwnerLookup(declarationOwnership.contractFields);
59
- // The legacy text matcher remains authoritative so acronym inventory contents do not change.
60
- for (const match of codeSource.matchAll(/\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) {
61
- // A recovered match without a capture becomes empty and is rejected by recordIdentifier.
62
- const name = match[1] ?? "";
63
- // A missing regex index is a recovered start-of-file match, so line one is the safe anchor.
64
- const line = byteLine(source, match.index ?? 0);
65
- // A legacy-only text token has no syntax declaration; module ownership preserves acronym input.
66
- const declarationOwner = variableOwners.get(declarationOwnerKey(name, line)) ?? MODULE_NAMING_OWNER;
67
- recordIdentifier(name, line, "declaration", declarationOwner);
68
- }
69
- // Shared callable points retain one-block-per-line order and the existing parameter text policy.
70
- for (const callable of callableMatchPoints(parsed)) {
71
- // Every simple parameter belongs to the callable users see as its nearest naming boundary.
72
- for (const parameter of parameterNames(callable.params)) {
73
- recordIdentifier(parameter.name, callable.lineIndex + 1, "parameter", callable);
74
- }
75
- }
76
- // The existing contract walker remains last, preserving the shared inventory sequence exactly.
77
- for (const field of collectInterfaceFieldDeclarations(source, codeSource)) {
78
- // A recovered field without an AST point stays visible to acronym checks under module fallback.
79
- const contractFieldOwner = contractFieldOwners.get(declarationOwnerKey(field.name, field.line)) ?? MODULE_NAMING_OWNER;
80
- recordIdentifier(field.name, field.line, "interface-field", contractFieldOwner);
81
- }
82
- return inventory;
83
- }
84
-
85
- // Indexes syntax owners by the legacy name/line tuple so text observations gain stable ownership.
86
- function declarationOwnerLookup(declarations: OwnedDeclarationPoint[]): Map<string, IdentifierOwner> {
87
- const owners = new Map<string, IdentifierOwner>();
88
- // Source order wins when recovered syntax produces duplicate name/line rows, matching de-duplication.
89
- for (const declaration of declarations) {
90
- const ownerKey = declarationOwnerKey(declaration.name, declaration.line);
91
- // The first syntax declaration is the same observation the legacy inventory retains.
92
- if (!owners.has(ownerKey)) {
93
- owners.set(ownerKey, declaration);
94
- }
95
- }
96
- return owners;
97
- }
98
-
99
- // Builds the stable lookup tuple shared by syntax owner rows and legacy text observations.
100
- function declarationOwnerKey(name: string, line: number): string {
101
- return `${name}@${line}`;
102
- }
103
-
104
- // Walks existing interface/type body lines so owner enrichment cannot expand acronym coverage.
105
- function collectInterfaceFieldDeclarations(source: string, codeSource: string): Array<{ name: string; line: number }> {
106
- const fieldRegex = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/;
107
- const declarations: Array<{ name: string; line: number }> = [];
108
- // Each direct body line retains the same source order and line anchor as previous reports.
109
- for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
110
- // A line without the supported field prefix produces an empty name and no inventory row.
111
- const name = sourceLine.match(fieldRegex)?.[1] ?? "";
112
- // Unsupported or recovered field syntax has no user-facing identifier row.
113
- if (name) {
114
- declarations.push({ name, line: lineIndex + 1 });
115
- }
116
- }
117
- return declarations;
118
- }
119
-
120
- // Strips separators only so `userId`, `user_id`, and `userID` collapse, while `adr013` and
121
- // `adr020` remain distinct domain tokens instead of fake casing variants.
122
- // Two names sharing this key but differing in original form are the casing-drift signal.
123
- function casingCanonicalKey(name: string): string {
124
- return name.toLowerCase().replace(/[_\-]/g, "");
125
- }
126
-
127
- /*
128
- * Groups identifiers by owner and canonical key, then filters boundary surfaces before reporting.
129
- * The split flow preserves drift inside one user-reviewed scope while refusing to command rewrites
130
- * across DTO/UI contracts, functions, constants, or intentionally-unused `_` names. Error behavior:
131
- * never throws; it appends findings only. Invariant: one owner-key group yields at most one finding.
132
- */
133
- export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
134
- // Each owner-key group can produce at most one actionable diagnostic for the CLI user.
135
- for (const entries of declaredIdentifierGroups(inventory).values()) {
136
- const candidate = inconsistentCasingCandidate(entries, config.acceptedCasingPairs);
137
- // A single spelling after boundary filtering means the reviewed scope is already consistent.
138
- if (!candidate) {
139
- continue;
140
- }
141
- findings.push(inconsistentCasingFinding(file, candidate));
142
- }
143
- }
144
-
145
- // Exact pair exemptions are case-insensitive but retain separators.
146
- function isAcceptedCasingPair(first: DeclaredIdentifier, second: DeclaredIdentifier, acceptedPairs: Set<string>): boolean {
147
- const forward = `${first.name}:${second.name}`.toLowerCase();
148
- const reverse = `${second.name}:${first.name}`.toLowerCase();
149
- return acceptedPairs.has(forward) || acceptedPairs.has(reverse);
150
- }
151
-
152
- // Builds owner-plus-canonical groups once so the reporting pass cannot compare unrelated surfaces.
153
- function declaredIdentifierGroups(inventory: DeclaredIdentifier[]): Map<string, DeclaredIdentifier[]> {
154
- const groups = new Map<string, DeclaredIdentifier[]>();
155
- // Every inventory row keeps its existing source order inside its deterministic owner boundary.
156
- for (const entry of inventory) {
157
- const canonicalKey = casingCanonicalKey(entry.name);
158
- // A recovered empty identifier has no comparison key and cannot help a user fix casing.
159
- if (!canonicalKey) {
160
- continue;
161
- }
162
- const ownerKey = `${entry.ownerId}\0${canonicalKey}`;
163
- const list = groups.get(ownerKey) ?? [];
164
- list.push(entry);
165
- groups.set(ownerKey, list);
166
- }
167
- return groups;
168
- }
169
-
170
- // Invariant: returns the exact variant pair to report after boundary-aware suppression has run.
171
- function inconsistentCasingCandidate(entries: DeclaredIdentifier[], acceptedPairs: Set<string>): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
172
- const reportableEntries = casingReportableEntries(entries);
173
- const sameSurfaceEntries = sameCasingSurfaceEntries(reportableEntries);
174
- const surfaces = [...new Set(sameSurfaceEntries.map((entry) => entry.name))].sort();
175
- if (surfaces.length < 2) {
176
- return undefined;
177
- }
178
- const sorted = [...sameSurfaceEntries].sort((a, b) => a.line - b.line);
179
- for (let firstIndex = 0; firstIndex < sorted.length; firstIndex += 1) {
180
- const first = sorted[firstIndex];
181
- if (!first) {
182
- continue;
183
- }
184
- const second = sorted.find((entry, secondIndex) => secondIndex > firstIndex && entry.name !== first.name && !isAcceptedCasingPair(first, entry, acceptedPairs));
185
- if (second) {
186
- return { first, second, surfaces };
187
- }
188
- }
189
- return undefined;
190
- }
191
-
192
- // Builds the stable finding after candidate selection so fingerprint shape stays in one place.
193
- function inconsistentCasingFinding(file: SourceFile, candidate: { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] }): Finding {
194
- const ownerLabel = casingOwnerLabel(candidate.first);
195
- return makeFinding({
196
- ruleId: "naming.inconsistent-casing",
197
- message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` within ${ownerLabel}.`,
198
- filePath: file.displayPath,
199
- line: candidate.second.line,
200
- severity: "advisory",
201
- pillar: "naming",
202
- confidence: "medium",
203
- symbol: candidate.second.name,
204
- remediation: `Choose one form within ${ownerLabel}, or add the exact alias pair to allowlists.acceptedCasingPairs.`,
205
- metadata: {
206
- variants: candidate.surfaces,
207
- ownerId: candidate.first.ownerId,
208
- ownerKind: candidate.first.ownerKind,
209
- ...(candidate.first.ownerName === undefined ? {} : { ownerName: candidate.first.ownerName }),
210
- },
211
- });
212
- }
213
-
214
- // Describes the comparison boundary in the same language a CLI user sees in source and reports.
215
- function casingOwnerLabel(owner: IdentifierOwner): string {
216
- switch (owner.ownerKind) {
217
- case "module":
218
- return "the module scope";
219
- case "function":
220
- // Anonymous callbacks still give users a precise lexical boundary without a made-up name.
221
- return owner.ownerName ? `function \`${owner.ownerName}\`` : "the containing function";
222
- case "interface":
223
- // Recovered contract names are absent only on malformed source, where a neutral label is safer.
224
- return `interface \`${owner.ownerName ?? "anonymous"}\``;
225
- case "type-literal":
226
- // Named aliases normally supply this label; malformed source falls back without throwing.
227
- return `type literal \`${owner.ownerName ?? "anonymous"}\``;
228
- }
229
- }
230
-
231
- // `_event` is the standard intentionally-unused spelling; comparing it with `event` would tell an
232
- // agent to remove useful boundary information rather than fix casing drift.
233
- function casingReportableEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
234
- return entries.filter((entry) => !entry.name.startsWith("_"));
235
- }
236
-
237
- // Contract fields and SCREAMING_SNAKE constants are boundary surfaces; remove only those entries so
238
- // they do not mask real local drift elsewhere in the same canonical group.
239
- function sameCasingSurfaceEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
240
- const hasLocalSurface = entries.some((entry) => entry.surface !== "interface-field" && !isScreamingConstant(entry.name));
241
- return entries.filter((entry) => {
242
- if (hasLocalSurface && entry.surface === "interface-field") {
243
- return false;
244
- }
245
- return !(hasLocalSurface && isScreamingConstant(entry.name));
246
- });
247
- }
248
-
249
- // Recognises constant-style identifiers without stripping digits, so `V110` remains one token.
250
- function isScreamingConstant(name: string): boolean {
251
- return /^[A-Z][A-Z0-9_]*$/.test(name) && /[A-Z]/.test(name);
252
- }
253
-
254
- // Splits camelCase, PascalCase, snake_case, and kebab-case into tokens. The regex preserves
255
- // uppercase runs as a single token so the acronym detector sees `URL` and `url` as the same word.
256
- function tokensForAcronymCheck(name: string): string[] {
257
- const split = name.split(/[_\-]+/).filter(Boolean);
258
- const tokens: string[] = [];
259
- for (const part of split) {
260
- const matches = part.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z0-9]+|[A-Z]+/g);
261
- if (matches) tokens.push(...matches);
262
- else tokens.push(part);
263
- }
264
- return tokens;
265
- }
266
-
267
- // Three-bucket classification used to detect when one project uses both `URL` and `Url` styles -
268
- // the rule flags drift when two of the three buckets are seen for the same acronym in one file.
269
- function acronymCaseClass(token: string): "upper" | "lower" | "title" {
270
- if (token === token.toUpperCase()) return "upper";
271
- if (token === token.toLowerCase()) return "lower";
272
- return "title";
273
- }
274
-
275
- /*
276
- * Reports when an acronym from `config.knownAcronyms` appears as all-caps plus another case form
277
- * among names whose casing the author chose. SCREAMING_SNAKE constants and all-lower names are
278
- * excluded because their convention fixes the acronym's case - a `RAW_HTML_TAGS` constant beside
279
- * `startsHtmlBlock` is standard TypeScript, not drift. The all-caps gate exists because
280
- * lower/title-only forms like `apiToken` beside `googleApiKey` are idiomatic enough to avoid
281
- * noisy findings. Like `analyseInconsistentCasing`, the finding anchors on the second occurrence
282
- * so the stable fingerprint sticks to the divergence.
283
- */
284
- export function analyseAcronymCase(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
285
- const observed = new Map<string, Map<string, { name: string; line: number }>>();
286
- for (const entry of inventory) {
287
- recordAcronymCases(observed, config, entry);
288
- }
289
- for (const [acronym, cases] of observed) {
290
- pushAcronymCaseFinding(file, acronym, cases, findings);
291
- }
292
- }
293
-
294
- // Adds one identifier's acronym tokens to the observed case map, skipping fixture-only constants
295
- // and names whose acronym casing the convention already fixes.
296
- function recordAcronymCases(observed: Map<string, Map<string, { name: string; line: number }>>, config: Config, entry: DeclaredIdentifier): void {
297
- if (isFixtureIdentifier(entry.name) || isConventionForcedAcronymCasing(entry.name)) {
298
- return;
299
- }
300
- for (const token of tokensForAcronymCheck(entry.name)) {
301
- const lower = token.toLowerCase();
302
- if (!config.knownAcronyms.has(lower)) continue;
303
- const cases = observed.get(lower) ?? new Map();
304
- const caseKey = acronymCaseClass(token);
305
- if (!cases.has(caseKey)) cases.set(caseKey, { name: entry.name, line: entry.line });
306
- observed.set(lower, cases);
307
- }
308
- }
309
-
310
- // Reports the stable acronym-case finding only after the all-caps-vs-other drift gate passes.
311
- function pushAcronymCaseFinding(file: SourceFile, acronym: string, cases: Map<string, { name: string; line: number }>, findings: Finding[]): void {
312
- if (!shouldReportAcronymCase(cases)) {
313
- return;
314
- }
315
- const occurrences = [...cases.values()].sort((a, b) => a.line - b.line);
316
- const second = occurrences[1];
317
- if (!second) {
318
- return;
319
- }
320
- findings.push(
321
- makeFinding({
322
- ruleId: "naming.acronym-case",
323
- message: `Acronym \`${acronym.toUpperCase()}\` appears in multiple cases in this file.`,
324
- filePath: file.displayPath,
325
- line: second.line,
326
- severity: "advisory",
327
- pillar: "naming",
328
- confidence: "medium",
329
- symbol: second.name,
330
- remediation: "Use one casing for each acronym throughout the file.",
331
- metadata: { acronym: acronym.toUpperCase(), variants: [...cases.keys()].sort() },
332
- }),
333
- );
334
- }
335
-
336
- // Requires an upper-case acronym plus a different case; lower/title-only mixes stay quiet.
337
- function shouldReportAcronymCase(cases: Map<string, { name: string; line: number }>): boolean {
338
- return cases.has("upper") && cases.size >= 2;
339
- }
340
-
341
- // Fixture constants often use SCREAMING_SNAKE vendor token names that should not force local
342
- // camelCase variables to adopt the same acronym style.
343
- function isFixtureIdentifier(name: string): boolean {
344
- return /(?:^|[_-])fixture(?:[_-]|$)/i.test(name);
345
- }
346
-
347
- // SCREAMING_SNAKE constants and all-lower names cannot choose an acronym casing - the convention
348
- // fixes it - so they carry no drift signal against camelCase/PascalCase names, where the author
349
- // does choose (`parsedHtml` versus `rawHTML`). Only chosen casings are compared file-wide.
350
- function isConventionForcedAcronymCasing(name: string): boolean {
351
- return isScreamingConstant(name) || name === name.toLowerCase();
352
- }
353
-
354
- /*
355
- * Walks every interface field and runs two checks per boolean field: boolean prefix and
356
- * negative boolean. The stable ordering matches `pushBooleanPrefixAt` → `pushNegativeBooleanAt`
357
- * so multiple findings on one field surface in a deterministic sequence.
358
- */
359
- export function analyseInterfaceFields(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[]): void {
360
- const fieldRegex = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:\s*([^;]+)/;
361
- for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
362
- const match = sourceLine.match(fieldRegex);
363
- const name = match?.[1] ?? "";
364
- if (!name) continue;
365
- if (/^\s*boolean\b/.test(match?.[2] ?? "")) {
366
- pushBooleanPrefixAt(file, lineIndex + 1, name, config, findings, "interface-field");
367
- pushNegativeBooleanAt(file, lineIndex + 1, name, config, findings, "interface-field");
368
- }
369
- }
370
- }
371
-
372
- const INTERFACE_HEADER_REGEX = /\b(?:export\s+)?(?:interface\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?(?:\s+extends\s+[^{]+)?|type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*)\s*\{/g;
373
-
374
- // Streams the depth-1 member lines of every interface/type-literal body so the field rules see
375
- // each declaration exactly once. Mapped types (`{ [K in ...] }`) are skipped - no field names there.
376
- function* walkInterfaceBodyLines(source: string, codeSource: string): Generator<{ lineIndex: number; sourceLine: string }> {
377
- const codeLines = codeSource.split(/\r?\n/);
378
- const sourceLines = source.split(/\r?\n/);
379
- for (const header of codeSource.matchAll(INTERFACE_HEADER_REGEX)) {
380
- const headerEnd = (header.index ?? 0) + header[0].length;
381
- // An index-signature-first body is a mapped type, not a field list the naming rules can judge.
382
- if (codeSource.slice(headerEnd, headerEnd + 30).trimStart().startsWith("[")) {
383
- continue;
384
- }
385
- yield* interfaceBodyMemberLines(codeLines, sourceLines, byteLine(source, headerEnd - 1) - 1);
386
- }
387
- }
388
-
389
- // Walks one body from its header line, yielding lines while brace depth stays at the member level.
390
- function* interfaceBodyMemberLines(codeLines: string[], sourceLines: string[], headerLineIndex: number): Generator<{ lineIndex: number; sourceLine: string }> {
391
- const headerLine = codeLines[headerLineIndex] ?? "";
392
- let depth = 1 + countBraceChange(headerLine.slice(headerLine.lastIndexOf("{") + 1));
393
- for (let lineIndex = headerLineIndex + 1; depth > 0 && lineIndex < codeLines.length; lineIndex += 1) {
394
- const codeLine = codeLines[lineIndex] ?? "";
395
- // Depth 1 means we are directly inside the declaration body, where the member lines live.
396
- if (depth === 1) {
397
- yield { lineIndex, sourceLine: sourceLines[lineIndex] ?? "" };
398
- }
399
- depth += countBraceChange(codeLine);
400
- }
401
- }
402
-
403
- // Net brace delta (`{` minus `}`) for a slice of text. Used by the interface-body walker to track
404
- // nesting depth without parsing the source twice.
405
- function countBraceChange(text: string): number {
406
- let delta = 0;
407
- for (const character of text) {
408
- if (character === "{") {
409
- delta += 1;
410
- } else if (character === "}") {
411
- delta -= 1;
412
- }
413
- }
414
- return delta;
415
- }
416
-
417
- /*
418
- * Three class-pillar rules in their stable, deterministic emission order: exported-declaration
419
- * docs and file-name mismatch, public-property, readonly candidates.
13
+ import { createRequire } from "node:module";
14
+
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");
20
+
21
+ type TsSourceFile = import("typescript").SourceFile;
22
+ type TsNode = import("typescript").Node;
23
+ type TsExpression = import("typescript").Expression;
24
+ type TsClassLike = import("typescript").ClassLikeDeclaration;
25
+
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.
420
36
  */
421
37
  export function analyseClassRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
422
38
  analyseExportedDeclarations(file, source, codeSource, config, findings, parsed);
423
- analysePublicProperties(file, source, codeSource, findings);
424
- analyseReadonlyCandidates(file, source, codeSource, findings);
425
- }
426
-
427
- /*
428
- * Keeps public-doc checks on direct exports, then evaluates class/file naming against the complete
429
- * syntax inventory so reports cover default/re-export forms without changing the documentation contract.
39
+ analyseReadonlyCandidates(file, source, codeSource, findings, parsed);
40
+ }
41
+
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.
430
53
  */
431
54
  function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
432
55
  const directlyExportedDeclarations = exportedDeclarations(source, codeSource);
@@ -441,9 +64,14 @@ function analyseExportedDeclarations(file: SourceFile, source: string, codeSourc
441
64
  pushClassFileMismatchFinding(file, modulePublicDeclarations, config, findings);
442
65
  }
443
66
 
444
- /*
445
- * Reports a normalized class/file mismatch only when one named class is the module's sole public
446
- * declaration, keeping feature modules quiet while preserving the stable finding anchor.
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.
447
75
  */
448
76
  function pushClassFileMismatchFinding(file: SourceFile, publicDeclarations: PublicExportDeclaration[], config: Config, findings: Finding[]): void {
449
77
  // Feature modules with a second public declaration do not claim one primary class-to-file convention.
@@ -489,22 +117,31 @@ function pushClassFileMismatchFinding(file: SourceFile, publicDeclarations: Publ
489
117
  );
490
118
  }
491
119
 
492
- // Targets `public foo =` and `public foo:` patterns. The rule message recommends `readonly` or
493
- // accessors because both preserve the field's invariant better than a raw public field, and
494
- // reports each match as a stable `modernisation.public-property` finding.
495
- function analysePublicProperties(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
496
- const publicProperty = /\bpublic\s+[A-Za-z_$][A-Za-z0-9_$]*\s*[=:]/g;
497
- for (const match of codeSource.matchAll(publicProperty)) {
498
- 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" }));
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.
130
+ */
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;
499
135
  }
500
- }
501
-
502
- // Visibility-modifier fields without `readonly`. The negative lookahead skips already-readonly
503
- // properties; each remaining match reports a stable `modernisation.readonly-property-candidate`.
504
- function analyseReadonlyCandidates(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
505
- const readonlyCandidate = /\b(?:public|private|protected)\s+(?!readonly\b)([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^;=\n]+;/g;
136
+ const constructionOnlyNames = constructionOnlyFieldNameStarts(syntax);
137
+ const readonlyCandidate = /\bprivate\s+(?!readonly\b)([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^;=\n]+;/g;
506
138
  for (const match of codeSource.matchAll(readonlyCandidate)) {
507
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)) {
143
+ continue;
144
+ }
508
145
  findings.push(
509
146
  makeFinding({
510
147
  ruleId: "modernisation.readonly-property-candidate",
@@ -520,3 +157,375 @@ function analyseReadonlyCandidates(file: SourceFile, source: string, codeSource:
520
157
  );
521
158
  }
522
159
  }
160
+
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;
184
+ }
185
+
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;
199
+ }
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));
204
+ }
205
+ }
206
+ }
207
+
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);
219
+ }
220
+
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;
291
+ }
292
+
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.
299
+ */
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));
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
+ });
319
+ }
320
+
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
+ }
338
+ }
339
+ return false;
340
+ }
341
+
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;
351
+ }
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);
356
+ }
357
+
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;
366
+ }
367
+
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;
376
+ }
377
+
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.
384
+ */
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;
392
+ }
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) {
400
+ continue;
401
+ }
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;
406
+ }
407
+ }
408
+ return undefined;
409
+ }
410
+
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));
420
+ }
421
+
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.
428
+ */
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));
441
+ }
442
+
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.
449
+ */
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;
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));
457
+ }
458
+
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.
464
+ */
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;
470
+ }
471
+ return undefined;
472
+ }
473
+
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
+ }
513
+ }
514
+ return { found: false };
515
+ }
516
+
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;
529
+ }
530
+ return current;
531
+ }