@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.
- package/CHANGELOG.md +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/class-rules.ts
CHANGED
|
@@ -1,372 +1,531 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
import {
|
|
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,
|
|
10
|
-
import {
|
|
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
|
-
//
|
|
15
|
-
//
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
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
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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(
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
|
|
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
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
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
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if (
|
|
198
|
-
|
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
if (!
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
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
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
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
|
-
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
if (
|
|
250
|
-
|
|
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
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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
|
-
*
|
|
296
|
-
*
|
|
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
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
*
|
|
306
|
-
*
|
|
307
|
-
*
|
|
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
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
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
|
|
322
|
-
|
|
323
|
-
if (
|
|
324
|
-
|
|
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
|
-
|
|
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
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
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
|
}
|