@venizia/dev-configs 0.4.2 → 0.4.4
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/LICENSE.md +2 -5
- package/README.md +20 -5
- package/dist/checks/catalog.d.ts +39 -0
- package/dist/checks/catalog.d.ts.map +1 -0
- package/dist/checks/catalog.js +94 -0
- package/dist/checks/catalog.js.map +1 -0
- package/dist/checks/index.d.ts +11 -0
- package/dist/checks/index.d.ts.map +1 -0
- package/dist/checks/index.js +27 -0
- package/dist/checks/index.js.map +1 -0
- package/dist/checks/module-cycles.d.ts +22 -0
- package/dist/checks/module-cycles.d.ts.map +1 -0
- package/dist/checks/module-cycles.js +149 -0
- package/dist/checks/module-cycles.js.map +1 -0
- package/dist/checks/purity/manifest.d.ts +94 -0
- package/dist/checks/purity/manifest.d.ts.map +1 -0
- package/dist/checks/purity/manifest.js +177 -0
- package/dist/checks/purity/manifest.js.map +1 -0
- package/dist/checks/purity/probe.d.ts +68 -0
- package/dist/checks/purity/probe.d.ts.map +1 -0
- package/dist/checks/purity/probe.js +295 -0
- package/dist/checks/purity/probe.js.map +1 -0
- package/dist/checks/purity/run.d.ts +47 -0
- package/dist/checks/purity/run.d.ts.map +1 -0
- package/dist/checks/purity/run.js +121 -0
- package/dist/checks/purity/run.js.map +1 -0
- package/dist/checks/split-report.d.ts +19 -0
- package/dist/checks/split-report.d.ts.map +1 -0
- package/dist/checks/split-report.js +123 -0
- package/dist/checks/split-report.js.map +1 -0
- package/dist/cli/check.d.ts +10 -0
- package/dist/cli/check.d.ts.map +1 -0
- package/dist/cli/check.js +206 -0
- package/dist/cli/check.js.map +1 -0
- package/dist/cli/clean.d.ts +2 -1
- package/dist/cli/clean.d.ts.map +1 -1
- package/dist/cli/clean.js +18 -1
- package/dist/cli/clean.js.map +1 -1
- package/dist/cli/codemod/const-classes.d.ts +80 -0
- package/dist/cli/codemod/const-classes.d.ts.map +1 -0
- package/dist/cli/codemod/const-classes.js +603 -0
- package/dist/cli/codemod/const-classes.js.map +1 -0
- package/dist/cli/codemod/drop-redundant-casts.d.ts +112 -0
- package/dist/cli/codemod/drop-redundant-casts.d.ts.map +1 -0
- package/dist/cli/codemod/drop-redundant-casts.js +780 -0
- package/dist/cli/codemod/drop-redundant-casts.js.map +1 -0
- package/dist/cli/codemod/files.d.ts +22 -0
- package/dist/cli/codemod/files.d.ts.map +1 -0
- package/dist/cli/codemod/files.js +68 -0
- package/dist/cli/codemod/files.js.map +1 -0
- package/dist/cli/codemod/index.d.ts +5 -4
- package/dist/cli/codemod/index.d.ts.map +1 -1
- package/dist/cli/codemod/index.js +77 -36
- package/dist/cli/codemod/index.js.map +1 -1
- package/dist/cli/codemod/model-settings.d.ts +2 -1
- package/dist/cli/codemod/model-settings.d.ts.map +1 -1
- package/dist/cli/codemod/model-settings.js +77 -3
- package/dist/cli/codemod/model-settings.js.map +1 -1
- package/dist/cli/index.js +21 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/linters/house/common.d.ts +1 -0
- package/dist/linters/house/common.d.ts.map +1 -1
- package/dist/linters/house/common.js +1 -0
- package/dist/linters/house/common.js.map +1 -1
- package/dist/linters/house/configs.d.ts.map +1 -1
- package/dist/linters/house/configs.js +20 -1
- package/dist/linters/house/configs.js.map +1 -1
- package/dist/linters/house/const-class-values.rule.d.ts +7 -4
- package/dist/linters/house/const-class-values.rule.d.ts.map +1 -1
- package/dist/linters/house/const-class-values.rule.js +73 -21
- package/dist/linters/house/const-class-values.rule.js.map +1 -1
- package/dist/linters/rules/common.d.ts +48 -1
- package/dist/linters/rules/common.d.ts.map +1 -1
- package/dist/linters/rules/common.js +53 -0
- package/dist/linters/rules/common.js.map +1 -1
- package/dist/linters/rules/eqeqeq.rule.d.ts +2 -2
- package/dist/linters/rules/eqeqeq.rule.d.ts.map +1 -1
- package/dist/linters/rules/eqeqeq.rule.js +2 -1
- package/dist/linters/rules/eqeqeq.rule.js.map +1 -1
- package/dist/linters/rules/no-unused-vars.rule.d.ts +3 -3
- package/dist/linters/rules/no-unused-vars.rule.d.ts.map +1 -1
- package/dist/linters/rules/no-unused-vars.rule.js +2 -1
- package/dist/linters/rules/no-unused-vars.rule.js.map +1 -1
- package/dist/linters/rules/switch-case-braces.rule.d.ts +2 -2
- package/dist/linters/rules/switch-case-braces.rule.d.ts.map +1 -1
- package/dist/linters/rules/switch-case-braces.rule.js +2 -1
- package/dist/linters/rules/switch-case-braces.rule.js.map +1 -1
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/repo-tmp.d.ts +12 -0
- package/dist/testing/repo-tmp.d.ts.map +1 -0
- package/dist/testing/repo-tmp.js +67 -0
- package/dist/testing/repo-tmp.js.map +1 -0
- package/dist/testing/spawn.helper.d.ts +13 -0
- package/dist/testing/spawn.helper.d.ts.map +1 -0
- package/dist/testing/spawn.helper.js +22 -0
- package/dist/testing/spawn.helper.js.map +1 -0
- package/dist/testing/tmpdir-preload.d.ts +2 -0
- package/dist/testing/tmpdir-preload.d.ts.map +1 -0
- package/dist/testing/tmpdir-preload.js +9 -0
- package/dist/testing/tmpdir-preload.js.map +1 -0
- package/package.json +9 -1
- package/src/tsconfig/tsconfig.base.json +5 -2
- package/src/tsconfig/tsconfig.common.json +2 -2
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DropRedundantCastsCommand = exports.RedundantCasts = exports.CastKeepReasons = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const files_1 = require("./files");
|
|
7
|
+
/** Why a cast is still there after the codemod ran. */
|
|
8
|
+
class CastKeepReasons {
|
|
9
|
+
/** Taking it out makes the package fail its typecheck. */
|
|
10
|
+
static { this.NEEDED = 'needed'; }
|
|
11
|
+
/** `as const` is a narrowing the codemod never touches. */
|
|
12
|
+
static { this.AS_CONST = 'as-const'; }
|
|
13
|
+
/** `x as unknown as T`: a deliberate escape that only a person can judge. */
|
|
14
|
+
static { this.DOUBLE_CAST = 'double-cast'; }
|
|
15
|
+
/** `x as unknown` widens on purpose. */
|
|
16
|
+
static { this.UNKNOWN_TARGET = 'unknown-target'; }
|
|
17
|
+
/** The expression is `any`: the cast is the only type it has, so it is not redundant. */
|
|
18
|
+
static { this.ANY_EXPRESSION = 'any-expression'; }
|
|
19
|
+
/** The expression is `unknown`: the cast is the only type it has. */
|
|
20
|
+
static { this.UNKNOWN_EXPRESSION = 'unknown-expression'; }
|
|
21
|
+
/** Test files are skipped unless `--include-tests` is given. */
|
|
22
|
+
static { this.TEST_FILE = 'test-file'; }
|
|
23
|
+
/** The file is not part of the package's tsconfig, so nothing can check it. */
|
|
24
|
+
static { this.NOT_IN_PROJECT = 'not-in-project'; }
|
|
25
|
+
static { this.SCHEME_SET = new Set([
|
|
26
|
+
this.NEEDED,
|
|
27
|
+
this.AS_CONST,
|
|
28
|
+
this.DOUBLE_CAST,
|
|
29
|
+
this.UNKNOWN_TARGET,
|
|
30
|
+
this.ANY_EXPRESSION,
|
|
31
|
+
this.UNKNOWN_EXPRESSION,
|
|
32
|
+
this.TEST_FILE,
|
|
33
|
+
this.NOT_IN_PROJECT,
|
|
34
|
+
]); }
|
|
35
|
+
static isValid(value) {
|
|
36
|
+
return this.SCHEME_SET.has(value);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
exports.CastKeepReasons = CastKeepReasons;
|
|
40
|
+
const MAX_ROUNDS = 50;
|
|
41
|
+
/** How many times the new errors are used to name culprits before the rest is halved. */
|
|
42
|
+
const MAX_NAMED_ATTEMPTS = 8;
|
|
43
|
+
/** A file that can hold a cast: `as`, or an angle-bracket assertion. */
|
|
44
|
+
const CAST_TEXT = /\bas\b|<[A-Za-z_$][^<>]*>\s*[A-Za-z_$(]/;
|
|
45
|
+
const TEST_FILE_PATTERN = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[cm]?tsx?$/;
|
|
46
|
+
/**
|
|
47
|
+
* The compiler's own view of a package, with the text of some files replaced in memory. It uses the
|
|
48
|
+
* compiler's incremental builder: a check after an edit revisits only the files whose exported types
|
|
49
|
+
* changed and the files that import them, and the parsed files are kept between checks.
|
|
50
|
+
*/
|
|
51
|
+
class TypecheckSession {
|
|
52
|
+
constructor(typescript, options, rootNames, root) {
|
|
53
|
+
this.typescript = typescript;
|
|
54
|
+
this.options = options;
|
|
55
|
+
this.rootNames = rootNames;
|
|
56
|
+
this.root = root;
|
|
57
|
+
this.parsed = new Map();
|
|
58
|
+
this.disk = new Map();
|
|
59
|
+
this.checks = 0;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Typechecks the package with `texts` replacing the files on disk and returns the errors as a count
|
|
63
|
+
* per message key. With `asReference`, the result becomes the state later checks are measured from.
|
|
64
|
+
*/
|
|
65
|
+
check(texts, opts = {}) {
|
|
66
|
+
const { typescript, options, rootNames } = this;
|
|
67
|
+
const host = typescript.createCompilerHost(options, true);
|
|
68
|
+
host.getSourceFile = (fileName, languageVersionOrOptions) => {
|
|
69
|
+
const key = (0, node_path_1.resolve)(fileName);
|
|
70
|
+
let source = texts.get(key);
|
|
71
|
+
if (source === undefined) {
|
|
72
|
+
if (!this.disk.has(key)) {
|
|
73
|
+
this.disk.set(key, typescript.sys.readFile(fileName));
|
|
74
|
+
}
|
|
75
|
+
source = this.disk.get(key);
|
|
76
|
+
}
|
|
77
|
+
if (source === undefined) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
const version = typescript.sys.createHash?.(source) ?? `${source.length}`;
|
|
81
|
+
const cacheKey = `${key}\0${version}`;
|
|
82
|
+
const cached = this.parsed.get(cacheKey);
|
|
83
|
+
if (cached) {
|
|
84
|
+
return cached;
|
|
85
|
+
}
|
|
86
|
+
const sourceFile = typescript.createSourceFile(fileName, source, languageVersionOrOptions, true);
|
|
87
|
+
// The builder reads a file's version to tell a changed file from an unchanged one; the type leaves it out.
|
|
88
|
+
Object.assign(sourceFile, { version });
|
|
89
|
+
this.parsed.set(cacheKey, sourceFile);
|
|
90
|
+
return sourceFile;
|
|
91
|
+
};
|
|
92
|
+
const builder = typescript.createSemanticDiagnosticsBuilderProgram(rootNames, options, host, this.reference);
|
|
93
|
+
this.program = builder.getProgram();
|
|
94
|
+
this.checks += 1;
|
|
95
|
+
if (opts.asReference) {
|
|
96
|
+
this.reference = builder;
|
|
97
|
+
}
|
|
98
|
+
const counts = new Map();
|
|
99
|
+
const items = [];
|
|
100
|
+
const diagnostics = [
|
|
101
|
+
...builder.getOptionsDiagnostics(),
|
|
102
|
+
...builder.getGlobalDiagnostics(),
|
|
103
|
+
...builder.getSyntacticDiagnostics(),
|
|
104
|
+
...builder.getSemanticDiagnostics(),
|
|
105
|
+
];
|
|
106
|
+
for (const diagnostic of diagnostics) {
|
|
107
|
+
if (diagnostic.category !== typescript.DiagnosticCategory.Error) {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const where = diagnostic.file ? (0, node_path_1.relative)(this.root, diagnostic.file.fileName) : '';
|
|
111
|
+
const message = typescript.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
|
|
112
|
+
const key = `${where}|${diagnostic.code}|${message}`;
|
|
113
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
114
|
+
items.push({
|
|
115
|
+
key,
|
|
116
|
+
file: diagnostic.file ? (0, node_path_1.resolve)(diagnostic.file.fileName) : '',
|
|
117
|
+
start: diagnostic.start ?? 0,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return { counts, items };
|
|
121
|
+
}
|
|
122
|
+
getProgram() {
|
|
123
|
+
if (!this.program) {
|
|
124
|
+
// eslint-disable-next-line venizia/no-new-error -- getError would be a dev-configs -> inversion cycle
|
|
125
|
+
throw new Error('[TypecheckSession][getProgram] check() has not run yet');
|
|
126
|
+
}
|
|
127
|
+
return this.program;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Removes the `as X` casts a package no longer needs. Every removal of a package is tried together
|
|
132
|
+
* in memory and compared with the errors the package had before; when new errors appear, the
|
|
133
|
+
* candidates are halved until the ones that break the typecheck are found, so the cost is a handful
|
|
134
|
+
* of checks, not one per cast.
|
|
135
|
+
*/
|
|
136
|
+
class RedundantCasts {
|
|
137
|
+
/** The casts of one project: which are removed, which stay and why. */
|
|
138
|
+
static run(opts) {
|
|
139
|
+
const { typescript, tsconfigPath, root, files, includeTests = false } = opts;
|
|
140
|
+
const loaded = RedundantCasts.loadProject({ typescript, tsconfigPath });
|
|
141
|
+
const session = new TypecheckSession(typescript, loaded.options, loaded.fileNames, root);
|
|
142
|
+
const original = new Map();
|
|
143
|
+
const current = new Map();
|
|
144
|
+
const results = new Map();
|
|
145
|
+
const members = new Set(loaded.fileNames.map((name) => (0, node_path_1.resolve)(name)));
|
|
146
|
+
for (const file of files.map((name) => (0, node_path_1.resolve)(name))) {
|
|
147
|
+
if (!members.has(file)) {
|
|
148
|
+
results.set(file, {
|
|
149
|
+
file,
|
|
150
|
+
output: (0, node_fs_1.readFileSync)(file, 'utf8'),
|
|
151
|
+
changed: false,
|
|
152
|
+
removed: 0,
|
|
153
|
+
importsRemoved: 0,
|
|
154
|
+
kept: [{ line: 0, column: 0, reason: CastKeepReasons.NOT_IN_PROJECT }],
|
|
155
|
+
});
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const text = (0, node_fs_1.readFileSync)(file, 'utf8');
|
|
159
|
+
original.set(file, text);
|
|
160
|
+
current.set(file, text);
|
|
161
|
+
}
|
|
162
|
+
const baseline = session.check(new Map(), { asReference: true }).counts;
|
|
163
|
+
const baselineErrors = [...baseline.values()].reduce((sum, count) => sum + count, 0);
|
|
164
|
+
const rejected = new Set();
|
|
165
|
+
const removedPerFile = new Map();
|
|
166
|
+
/** The errors `texts` adds to what the package already had. */
|
|
167
|
+
const newErrors = (texts) => {
|
|
168
|
+
const report = session.check(texts);
|
|
169
|
+
const budget = new Map(baseline);
|
|
170
|
+
const added = [];
|
|
171
|
+
for (const item of report.items) {
|
|
172
|
+
const left = budget.get(item.key) ?? 0;
|
|
173
|
+
if (left > 0) {
|
|
174
|
+
budget.set(item.key, left - 1);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
added.push(item);
|
|
178
|
+
}
|
|
179
|
+
return added;
|
|
180
|
+
};
|
|
181
|
+
const isBroken = (texts) => newErrors(texts).length > 0;
|
|
182
|
+
for (let round = 0; round < MAX_ROUNDS; round += 1) {
|
|
183
|
+
session.check(current, { asReference: true });
|
|
184
|
+
const candidates = RedundantCasts.collectCandidates({
|
|
185
|
+
typescript,
|
|
186
|
+
program: session.getProgram(),
|
|
187
|
+
texts: current,
|
|
188
|
+
includeTests,
|
|
189
|
+
rejected,
|
|
190
|
+
});
|
|
191
|
+
if (candidates.length === 0) {
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
const accepted = RedundantCasts.search({
|
|
195
|
+
candidates,
|
|
196
|
+
base: [],
|
|
197
|
+
newErrors: (chosen) => newErrors(RedundantCasts.apply({ texts: current, chosen })),
|
|
198
|
+
suspectsOf: (chosen, found) => RedundantCasts.suspectsOf({ typescript, program: session.getProgram(), chosen, found }),
|
|
199
|
+
});
|
|
200
|
+
const acceptedKeys = new Set(accepted);
|
|
201
|
+
for (const candidate of candidates) {
|
|
202
|
+
if (!acceptedKeys.has(candidate)) {
|
|
203
|
+
rejected.add(`${candidate.file}|${candidate.key}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
for (const candidate of accepted) {
|
|
207
|
+
removedPerFile.set(candidate.file, (removedPerFile.get(candidate.file) ?? 0) + 1);
|
|
208
|
+
}
|
|
209
|
+
const next = RedundantCasts.apply({ texts: current, chosen: accepted });
|
|
210
|
+
for (const [file, text] of next) {
|
|
211
|
+
current.set(file, text);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const cleaned = RedundantCasts.dropUnusedImports({ typescript, original, current });
|
|
215
|
+
const finalTexts = isBroken(cleaned.texts) ? current : cleaned.texts;
|
|
216
|
+
const importsRemoved = finalTexts === cleaned.texts ? cleaned.removed : new Map();
|
|
217
|
+
session.check(finalTexts);
|
|
218
|
+
const program = session.getProgram();
|
|
219
|
+
for (const [file, text] of original) {
|
|
220
|
+
const output = finalTexts.get(file) ?? text;
|
|
221
|
+
const sourceFile = program.getSourceFile(file);
|
|
222
|
+
const kept = sourceFile
|
|
223
|
+
? RedundantCasts.describeKept({
|
|
224
|
+
typescript,
|
|
225
|
+
sourceFile,
|
|
226
|
+
checker: program.getTypeChecker(),
|
|
227
|
+
includeTests,
|
|
228
|
+
rejected,
|
|
229
|
+
})
|
|
230
|
+
: [];
|
|
231
|
+
results.set(file, {
|
|
232
|
+
file,
|
|
233
|
+
output,
|
|
234
|
+
changed: output !== text,
|
|
235
|
+
removed: removedPerFile.get(file) ?? 0,
|
|
236
|
+
importsRemoved: importsRemoved.get(file) ?? 0,
|
|
237
|
+
kept,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
return { files: [...results.values()], checks: session.checks, baselineErrors };
|
|
241
|
+
}
|
|
242
|
+
static loadProject(opts) {
|
|
243
|
+
const { typescript, tsconfigPath } = opts;
|
|
244
|
+
const read = typescript.readConfigFile(tsconfigPath, typescript.sys.readFile);
|
|
245
|
+
if (read.error) {
|
|
246
|
+
// eslint-disable-next-line venizia/no-new-error -- getError would be a dev-configs -> inversion cycle
|
|
247
|
+
throw new Error(`[loadProject] cannot read ${tsconfigPath} | ${typescript.flattenDiagnosticMessageText(read.error.messageText, '\n')}`);
|
|
248
|
+
}
|
|
249
|
+
const parsed = typescript.parseJsonConfigFileContent(read.config, typescript.sys, (0, node_path_1.dirname)(tsconfigPath), undefined, tsconfigPath);
|
|
250
|
+
return {
|
|
251
|
+
fileNames: parsed.fileNames,
|
|
252
|
+
options: {
|
|
253
|
+
...parsed.options,
|
|
254
|
+
noEmit: true,
|
|
255
|
+
incremental: false,
|
|
256
|
+
composite: false,
|
|
257
|
+
emitDeclarationOnly: false,
|
|
258
|
+
declaration: false,
|
|
259
|
+
declarationMap: false,
|
|
260
|
+
tsBuildInfoFile: undefined,
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Finds the casts worth trying: not `as const`, not a double cast, not a cast of `any` or
|
|
266
|
+
* `unknown`, and not one already rejected. A cast inside another candidate waits for the next
|
|
267
|
+
* round, so the edits of one round never overlap.
|
|
268
|
+
*/
|
|
269
|
+
static collectCandidates(opts) {
|
|
270
|
+
const { typescript, program, texts, includeTests, rejected } = opts;
|
|
271
|
+
const checker = program.getTypeChecker();
|
|
272
|
+
const found = [];
|
|
273
|
+
for (const [file, text] of texts) {
|
|
274
|
+
if (!includeTests && TEST_FILE_PATTERN.test(file)) {
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const sourceFile = program.getSourceFile(file);
|
|
278
|
+
if (!sourceFile) {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
RedundantCasts.walkCasts({
|
|
282
|
+
typescript,
|
|
283
|
+
sourceFile,
|
|
284
|
+
visit: (node) => {
|
|
285
|
+
if (RedundantCasts.classify({ typescript, node, checker }) !== undefined) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const inner = node.expression;
|
|
289
|
+
const key = text.slice(node.getStart(sourceFile), node.end);
|
|
290
|
+
if (rejected.has(`${file}|${key}`)) {
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
found.push({
|
|
294
|
+
file,
|
|
295
|
+
start: node.getStart(sourceFile),
|
|
296
|
+
end: node.end,
|
|
297
|
+
replacement: text.slice(inner.getStart(sourceFile), inner.end),
|
|
298
|
+
key,
|
|
299
|
+
});
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
found.sort((a, b) => a.file.localeCompare(b.file) || a.start - b.start || b.end - a.end);
|
|
304
|
+
const outermost = [];
|
|
305
|
+
let last;
|
|
306
|
+
for (const candidate of found) {
|
|
307
|
+
const isInside = last !== undefined &&
|
|
308
|
+
last.file === candidate.file &&
|
|
309
|
+
candidate.start >= last.start &&
|
|
310
|
+
candidate.end <= last.end;
|
|
311
|
+
if (isInside) {
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
outermost.push(candidate);
|
|
315
|
+
last = candidate;
|
|
316
|
+
}
|
|
317
|
+
return outermost;
|
|
318
|
+
}
|
|
319
|
+
/** The reason a cast is never tried, or `undefined` when it is worth trying. */
|
|
320
|
+
static classify(opts) {
|
|
321
|
+
const { typescript, node, checker } = opts;
|
|
322
|
+
const target = node.type;
|
|
323
|
+
if (typescript.isTypeReferenceNode(target) &&
|
|
324
|
+
typescript.isIdentifier(target.typeName) &&
|
|
325
|
+
target.typeName.text === 'const') {
|
|
326
|
+
return CastKeepReasons.AS_CONST;
|
|
327
|
+
}
|
|
328
|
+
if (target.kind === typescript.SyntaxKind.UnknownKeyword) {
|
|
329
|
+
return CastKeepReasons.UNKNOWN_TARGET;
|
|
330
|
+
}
|
|
331
|
+
let inner = node.expression;
|
|
332
|
+
while (typescript.isParenthesizedExpression(inner)) {
|
|
333
|
+
inner = inner.expression;
|
|
334
|
+
}
|
|
335
|
+
if (typescript.isAsExpression(inner) || typescript.isTypeAssertionExpression(inner)) {
|
|
336
|
+
return CastKeepReasons.DOUBLE_CAST;
|
|
337
|
+
}
|
|
338
|
+
const flags = checker.getTypeAtLocation(node.expression).flags;
|
|
339
|
+
if (flags & typescript.TypeFlags.Any) {
|
|
340
|
+
return CastKeepReasons.ANY_EXPRESSION;
|
|
341
|
+
}
|
|
342
|
+
if (flags & typescript.TypeFlags.Unknown) {
|
|
343
|
+
return CastKeepReasons.UNKNOWN_EXPRESSION;
|
|
344
|
+
}
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
static walkCasts(opts) {
|
|
348
|
+
const { typescript, sourceFile, visit } = opts;
|
|
349
|
+
const walk = (node) => {
|
|
350
|
+
if (typescript.isAsExpression(node) || typescript.isTypeAssertionExpression(node)) {
|
|
351
|
+
visit(node);
|
|
352
|
+
}
|
|
353
|
+
typescript.forEachChild(node, walk);
|
|
354
|
+
};
|
|
355
|
+
walk(sourceFile);
|
|
356
|
+
}
|
|
357
|
+
/** The casts that remain in a file, each with the reason it stayed. */
|
|
358
|
+
static describeKept(opts) {
|
|
359
|
+
const { typescript, sourceFile, checker, includeTests, rejected } = opts;
|
|
360
|
+
const kept = [];
|
|
361
|
+
const isTest = TEST_FILE_PATTERN.test(sourceFile.fileName);
|
|
362
|
+
RedundantCasts.walkCasts({
|
|
363
|
+
typescript,
|
|
364
|
+
sourceFile,
|
|
365
|
+
visit: (node) => {
|
|
366
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
367
|
+
const text = sourceFile.text.slice(node.getStart(sourceFile), node.end);
|
|
368
|
+
const reason = (isTest && !includeTests ? CastKeepReasons.TEST_FILE : undefined) ??
|
|
369
|
+
RedundantCasts.classify({ typescript, node, checker }) ??
|
|
370
|
+
(rejected.has(`${(0, node_path_1.resolve)(sourceFile.fileName)}|${text}`)
|
|
371
|
+
? CastKeepReasons.NEEDED
|
|
372
|
+
: undefined);
|
|
373
|
+
if (reason !== undefined) {
|
|
374
|
+
kept.push({ line: line + 1, column: character + 1, reason });
|
|
375
|
+
}
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
return kept;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* The candidates whose removal, together with `base`, adds no error. When a try fails, the places
|
|
382
|
+
* of the new errors name the casts most likely to blame; those are set aside and the rest is tried
|
|
383
|
+
* again. What cannot be named is halved until the breaking casts stand alone. Whatever is accepted
|
|
384
|
+
* was checked together with everything else accepted, so a wrong guess can only keep a cast.
|
|
385
|
+
*/
|
|
386
|
+
static search(opts) {
|
|
387
|
+
const { base, newErrors, suspectsOf } = opts;
|
|
388
|
+
let remaining = [...opts.candidates];
|
|
389
|
+
for (let attempt = 0; attempt < MAX_NAMED_ATTEMPTS && remaining.length > 0; attempt += 1) {
|
|
390
|
+
const chosen = [...base, ...remaining];
|
|
391
|
+
const found = newErrors(chosen);
|
|
392
|
+
if (found.length === 0) {
|
|
393
|
+
return remaining;
|
|
394
|
+
}
|
|
395
|
+
const suspects = suspectsOf(chosen, found);
|
|
396
|
+
if (suspects.length === 0) {
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
const named = new Set(suspects);
|
|
400
|
+
remaining = remaining.filter((candidate) => !named.has(candidate));
|
|
401
|
+
}
|
|
402
|
+
return RedundantCasts.halve({ candidates: remaining, base, newErrors });
|
|
403
|
+
}
|
|
404
|
+
static halve(opts) {
|
|
405
|
+
const { candidates, base, newErrors } = opts;
|
|
406
|
+
if (candidates.length === 0) {
|
|
407
|
+
return [];
|
|
408
|
+
}
|
|
409
|
+
if (newErrors([...base, ...candidates]).length === 0) {
|
|
410
|
+
return candidates;
|
|
411
|
+
}
|
|
412
|
+
if (candidates.length === 1) {
|
|
413
|
+
return [];
|
|
414
|
+
}
|
|
415
|
+
const middle = Math.ceil(candidates.length / 2);
|
|
416
|
+
const first = RedundantCasts.halve({
|
|
417
|
+
candidates: candidates.slice(0, middle),
|
|
418
|
+
base,
|
|
419
|
+
newErrors,
|
|
420
|
+
});
|
|
421
|
+
const second = RedundantCasts.halve({
|
|
422
|
+
candidates: candidates.slice(middle),
|
|
423
|
+
base: [...base, ...first],
|
|
424
|
+
newErrors,
|
|
425
|
+
});
|
|
426
|
+
return [...first, ...second];
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* The casts a set of new errors most likely comes from: for each error, the chosen cast nearest to
|
|
430
|
+
* it inside the same statement, else the nearest one before it in the same file. An error in a file
|
|
431
|
+
* with no chosen cast (an importer) names nothing; the halving deals with what stays.
|
|
432
|
+
*/
|
|
433
|
+
static suspectsOf(opts) {
|
|
434
|
+
const { typescript, program, chosen, found } = opts;
|
|
435
|
+
const suspects = new Set();
|
|
436
|
+
for (const error of found) {
|
|
437
|
+
const inFile = chosen
|
|
438
|
+
.filter((candidate) => candidate.file === error.file)
|
|
439
|
+
.sort((a, b) => a.start - b.start);
|
|
440
|
+
const sourceFile = program.getSourceFile(error.file);
|
|
441
|
+
if (inFile.length === 0 || !sourceFile) {
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
let shift = 0;
|
|
445
|
+
const placed = inFile.map((candidate) => {
|
|
446
|
+
const start = candidate.start - shift;
|
|
447
|
+
shift += candidate.end - candidate.start - candidate.replacement.length;
|
|
448
|
+
return { candidate, start, end: start + candidate.replacement.length };
|
|
449
|
+
});
|
|
450
|
+
const statement = RedundantCasts.enclosingStatement({
|
|
451
|
+
typescript,
|
|
452
|
+
sourceFile,
|
|
453
|
+
position: error.start,
|
|
454
|
+
});
|
|
455
|
+
const distance = (item) => error.start < item.start
|
|
456
|
+
? item.start - error.start
|
|
457
|
+
: error.start > item.end
|
|
458
|
+
? error.start - item.end
|
|
459
|
+
: 0;
|
|
460
|
+
const inside = placed.filter((item) => statement && item.start >= statement.pos && item.end <= statement.end);
|
|
461
|
+
const before = placed.filter((item) => item.start <= error.start);
|
|
462
|
+
const pool = inside.length > 0 ? inside : before;
|
|
463
|
+
const nearest = [...pool].sort((a, b) => distance(a) - distance(b))[0];
|
|
464
|
+
if (nearest) {
|
|
465
|
+
suspects.add(nearest.candidate);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return [...suspects];
|
|
469
|
+
}
|
|
470
|
+
/** The smallest statement that holds `position`. */
|
|
471
|
+
static enclosingStatement(opts) {
|
|
472
|
+
const { typescript, sourceFile, position } = opts;
|
|
473
|
+
let found;
|
|
474
|
+
const walk = (node) => {
|
|
475
|
+
if (position < node.pos || position >= node.end) {
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
const parent = node.parent;
|
|
479
|
+
const isStatement = parent !== undefined &&
|
|
480
|
+
(typescript.isSourceFile(parent) ||
|
|
481
|
+
typescript.isBlock(parent) ||
|
|
482
|
+
typescript.isModuleBlock(parent) ||
|
|
483
|
+
typescript.isCaseClause(parent) ||
|
|
484
|
+
typescript.isDefaultClause(parent));
|
|
485
|
+
if (isStatement) {
|
|
486
|
+
found = node;
|
|
487
|
+
}
|
|
488
|
+
typescript.forEachChild(node, walk);
|
|
489
|
+
};
|
|
490
|
+
walk(sourceFile);
|
|
491
|
+
return found;
|
|
492
|
+
}
|
|
493
|
+
/** The texts with `chosen` removed, each file edited from the end so earlier offsets stay valid. */
|
|
494
|
+
static apply(opts) {
|
|
495
|
+
const { texts, chosen } = opts;
|
|
496
|
+
const output = new Map(texts);
|
|
497
|
+
const byFile = new Map();
|
|
498
|
+
for (const candidate of chosen) {
|
|
499
|
+
byFile.set(candidate.file, [...(byFile.get(candidate.file) ?? []), candidate]);
|
|
500
|
+
}
|
|
501
|
+
for (const [file, edits] of byFile) {
|
|
502
|
+
let text = output.get(file) ?? '';
|
|
503
|
+
for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
|
|
504
|
+
text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
|
|
505
|
+
}
|
|
506
|
+
output.set(file, text);
|
|
507
|
+
}
|
|
508
|
+
return output;
|
|
509
|
+
}
|
|
510
|
+
/** Removes a named import the removals left unused; an import that was already unused is left alone. */
|
|
511
|
+
static dropUnusedImports(opts) {
|
|
512
|
+
const { typescript, original, current } = opts;
|
|
513
|
+
const texts = new Map(current);
|
|
514
|
+
const removed = new Map();
|
|
515
|
+
for (const [file, after] of current) {
|
|
516
|
+
const before = original.get(file);
|
|
517
|
+
if (before === undefined || before === after) {
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
const usedBefore = RedundantCasts.identifiersOutsideImports({
|
|
521
|
+
typescript,
|
|
522
|
+
text: before,
|
|
523
|
+
file,
|
|
524
|
+
});
|
|
525
|
+
const usedAfter = RedundantCasts.identifiersOutsideImports({ typescript, text: after, file });
|
|
526
|
+
const sourceFile = typescript.createSourceFile(file, after, typescript.ScriptTarget.Latest, true);
|
|
527
|
+
const edits = [];
|
|
528
|
+
let count = 0;
|
|
529
|
+
for (const statement of sourceFile.statements) {
|
|
530
|
+
if (!typescript.isImportDeclaration(statement)) {
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
const clause = statement.importClause;
|
|
534
|
+
const bindings = clause?.namedBindings;
|
|
535
|
+
if (!clause || !bindings || !typescript.isNamedImports(bindings)) {
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
const stale = bindings.elements.filter((element) => usedBefore.has(element.name.text) && !usedAfter.has(element.name.text));
|
|
539
|
+
if (stale.length === 0) {
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
count += stale.length;
|
|
543
|
+
const remaining = bindings.elements.filter((element) => !stale.includes(element));
|
|
544
|
+
const start = statement.getStart(sourceFile);
|
|
545
|
+
if (remaining.length === 0 && !clause.name) {
|
|
546
|
+
const lineEnd = after.indexOf('\n', statement.end);
|
|
547
|
+
edits.push({ start, end: lineEnd === -1 ? statement.end : lineEnd + 1, text: '' });
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
const typeKeyword = clause.isTypeOnly ? 'type ' : '';
|
|
551
|
+
const names = remaining.map((element) => after.slice(element.getStart(sourceFile), element.end));
|
|
552
|
+
const head = clause.name ? `${clause.name.text}${names.length > 0 ? ', ' : ''}` : '';
|
|
553
|
+
const named = names.length > 0 ? `{ ${names.join(', ')} }` : '';
|
|
554
|
+
const from = after.slice(statement.moduleSpecifier.getStart(sourceFile), statement.end);
|
|
555
|
+
edits.push({
|
|
556
|
+
start,
|
|
557
|
+
end: statement.end,
|
|
558
|
+
text: `import ${typeKeyword}${head}${named} from ${from}`,
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
if (edits.length === 0) {
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
let text = after;
|
|
565
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
566
|
+
text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
567
|
+
}
|
|
568
|
+
texts.set(file, text);
|
|
569
|
+
removed.set(file, count);
|
|
570
|
+
}
|
|
571
|
+
return { texts, removed };
|
|
572
|
+
}
|
|
573
|
+
/** Every identifier text outside the import declarations: a name that appears here is in use. */
|
|
574
|
+
static identifiersOutsideImports(opts) {
|
|
575
|
+
const { typescript, text, file } = opts;
|
|
576
|
+
const sourceFile = typescript.createSourceFile(file, text, typescript.ScriptTarget.Latest, true);
|
|
577
|
+
const names = new Set();
|
|
578
|
+
const walk = (node) => {
|
|
579
|
+
if (typescript.isImportDeclaration(node)) {
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (typescript.isIdentifier(node)) {
|
|
583
|
+
names.add(node.text);
|
|
584
|
+
}
|
|
585
|
+
typescript.forEachChild(node, walk);
|
|
586
|
+
};
|
|
587
|
+
walk(sourceFile);
|
|
588
|
+
return names;
|
|
589
|
+
}
|
|
590
|
+
/** The nearest `tsconfig.json` at or above `file`, stopping at `root`. */
|
|
591
|
+
static findTsconfig(opts) {
|
|
592
|
+
const { root } = opts;
|
|
593
|
+
let directory = (0, node_path_1.dirname)((0, node_path_1.resolve)(opts.file));
|
|
594
|
+
const top = (0, node_path_1.resolve)(root);
|
|
595
|
+
for (;;) {
|
|
596
|
+
const candidate = (0, node_path_1.join)(directory, 'tsconfig.json');
|
|
597
|
+
if ((0, node_fs_1.existsSync)(candidate)) {
|
|
598
|
+
return candidate;
|
|
599
|
+
}
|
|
600
|
+
const parent = (0, node_path_1.dirname)(directory);
|
|
601
|
+
if (directory === top || parent === directory) {
|
|
602
|
+
return undefined;
|
|
603
|
+
}
|
|
604
|
+
directory = parent;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
exports.RedundantCasts = RedundantCasts;
|
|
609
|
+
const USAGE = `Usage: devz codemod drop-redundant-casts [paths...] [--write | --check] [--project <tsconfig>] [--include-tests]
|
|
610
|
+
|
|
611
|
+
Removes \`as X\` casts the compiler no longer needs. A removal is kept only if the package still
|
|
612
|
+
typechecks: all removals of a package are tried together in memory and the failing ones are found
|
|
613
|
+
by halving, so the package is checked a handful of times, not once per cast.
|
|
614
|
+
|
|
615
|
+
--write write the changed files (without it, nothing is written)
|
|
616
|
+
--check dry run that exits 1 while a removable cast remains (for CI)
|
|
617
|
+
--project <file> the tsconfig to check against (default: the nearest tsconfig.json of each file)
|
|
618
|
+
--include-tests also try casts in test files (skipped by default)
|
|
619
|
+
--help print this text and exit
|
|
620
|
+
|
|
621
|
+
A cast stays when its removal breaks the typecheck, and always for \`as const\`, \`as unknown\`,
|
|
622
|
+
\`x as unknown as T\` and a cast of an \`any\` or \`unknown\` expression: the cast is the only type
|
|
623
|
+
there. The report lists how many casts stayed and why. Run your own typecheck after --write.`;
|
|
624
|
+
/** A usage error: nothing was read or written. */
|
|
625
|
+
const USAGE_ERROR_CODE = 2;
|
|
626
|
+
class CastFlags {
|
|
627
|
+
static { this.WRITE = '--write'; }
|
|
628
|
+
static { this.CHECK = '--check'; }
|
|
629
|
+
static { this.PROJECT = '--project'; }
|
|
630
|
+
static { this.INCLUDE_TESTS = '--include-tests'; }
|
|
631
|
+
static { this.HELP = '--help'; }
|
|
632
|
+
static { this.HELP_SHORT = '-h'; }
|
|
633
|
+
static { this.SCHEME_SET = new Set([
|
|
634
|
+
this.WRITE,
|
|
635
|
+
this.CHECK,
|
|
636
|
+
this.PROJECT,
|
|
637
|
+
this.INCLUDE_TESTS,
|
|
638
|
+
this.HELP,
|
|
639
|
+
this.HELP_SHORT,
|
|
640
|
+
]); }
|
|
641
|
+
static isValid(value) {
|
|
642
|
+
return this.SCHEME_SET.has(value);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/** `devz codemod drop-redundant-casts [paths...] [--write | --check]`. */
|
|
646
|
+
class DropRedundantCastsCommand {
|
|
647
|
+
static { this.USAGE = USAGE; }
|
|
648
|
+
static async run(opts) {
|
|
649
|
+
const { root, args } = opts;
|
|
650
|
+
if (args.includes(CastFlags.HELP) || args.includes(CastFlags.HELP_SHORT)) {
|
|
651
|
+
console.log(USAGE);
|
|
652
|
+
return 0;
|
|
653
|
+
}
|
|
654
|
+
const flags = [];
|
|
655
|
+
const paths = [];
|
|
656
|
+
let project;
|
|
657
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
658
|
+
const argument = args[index] ?? '';
|
|
659
|
+
if (argument === CastFlags.PROJECT) {
|
|
660
|
+
project = args[index + 1];
|
|
661
|
+
index += 1;
|
|
662
|
+
if (!project || project.startsWith('-')) {
|
|
663
|
+
console.error(`devz codemod: ${CastFlags.PROJECT} needs a tsconfig path\n${USAGE}`);
|
|
664
|
+
return USAGE_ERROR_CODE;
|
|
665
|
+
}
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
if (argument.startsWith(`${CastFlags.PROJECT}=`)) {
|
|
669
|
+
project = argument.slice(CastFlags.PROJECT.length + 1);
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
if (argument.startsWith('-')) {
|
|
673
|
+
flags.push(argument);
|
|
674
|
+
}
|
|
675
|
+
else {
|
|
676
|
+
paths.push(argument);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
const unknown = flags.filter((flag) => !CastFlags.isValid(flag));
|
|
680
|
+
if (unknown.length > 0) {
|
|
681
|
+
console.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
|
|
682
|
+
return USAGE_ERROR_CODE;
|
|
683
|
+
}
|
|
684
|
+
const isWrite = flags.includes(CastFlags.WRITE);
|
|
685
|
+
const isCheck = flags.includes(CastFlags.CHECK);
|
|
686
|
+
const includeTests = flags.includes(CastFlags.INCLUDE_TESTS);
|
|
687
|
+
if (isWrite && isCheck) {
|
|
688
|
+
console.error(`devz codemod: ${CastFlags.WRITE} and ${CastFlags.CHECK} contradict each other\n${USAGE}`);
|
|
689
|
+
return USAGE_ERROR_CODE;
|
|
690
|
+
}
|
|
691
|
+
let typescript;
|
|
692
|
+
try {
|
|
693
|
+
typescript = (await import('typescript')).default;
|
|
694
|
+
}
|
|
695
|
+
catch {
|
|
696
|
+
console.error('devz codemod: the "typescript" package is required to check your sources');
|
|
697
|
+
return 1;
|
|
698
|
+
}
|
|
699
|
+
const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
|
|
700
|
+
const byProject = new Map();
|
|
701
|
+
for (const target of targets) {
|
|
702
|
+
const collected = files_1.CodemodFiles.collect({ target });
|
|
703
|
+
if (collected.length === 0 && paths.length > 0) {
|
|
704
|
+
console.warn(`devz codemod: no source files under "${(0, node_path_1.relative)(root, target) || target}" (git ignores the path, or it holds none): nothing was read`);
|
|
705
|
+
}
|
|
706
|
+
for (const file of collected) {
|
|
707
|
+
if (!CAST_TEXT.test((0, node_fs_1.readFileSync)(file, 'utf8'))) {
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
const tsconfig = project
|
|
711
|
+
? (0, node_path_1.resolve)(root, project)
|
|
712
|
+
: RedundantCasts.findTsconfig({ file, root });
|
|
713
|
+
if (!tsconfig) {
|
|
714
|
+
console.warn(`${(0, node_path_1.relative)(root, file)} no tsconfig.json at or above this file; skipped`);
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
byProject.set(tsconfig, [...(byProject.get(tsconfig) ?? []), file]);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
let removed = 0;
|
|
721
|
+
let kept = 0;
|
|
722
|
+
let importsRemoved = 0;
|
|
723
|
+
let changedFiles = 0;
|
|
724
|
+
const reasons = new Map();
|
|
725
|
+
const verb = isWrite ? 'removed' : 'would remove';
|
|
726
|
+
for (const [tsconfig, files] of byProject) {
|
|
727
|
+
let result;
|
|
728
|
+
try {
|
|
729
|
+
result = RedundantCasts.run({
|
|
730
|
+
typescript,
|
|
731
|
+
tsconfigPath: tsconfig,
|
|
732
|
+
root,
|
|
733
|
+
files,
|
|
734
|
+
includeTests,
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
catch (error) {
|
|
738
|
+
console.error(`devz codemod: ${(0, node_path_1.relative)(root, tsconfig)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
739
|
+
return 1;
|
|
740
|
+
}
|
|
741
|
+
console.log(`${(0, node_path_1.relative)(root, tsconfig)}: ${files.length} file(s) read, typechecked ${result.checks} time(s)` +
|
|
742
|
+
(result.baselineErrors > 0
|
|
743
|
+
? `, ${result.baselineErrors} error(s) were there before and are ignored`
|
|
744
|
+
: ''));
|
|
745
|
+
for (const file of result.files) {
|
|
746
|
+
removed += file.removed;
|
|
747
|
+
importsRemoved += file.importsRemoved;
|
|
748
|
+
kept += file.kept.length;
|
|
749
|
+
for (const entry of file.kept) {
|
|
750
|
+
reasons.set(entry.reason, (reasons.get(entry.reason) ?? 0) + 1);
|
|
751
|
+
}
|
|
752
|
+
if (file.removed === 0 && file.kept.length === 0) {
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
const shown = (0, node_path_1.relative)(root, file.file);
|
|
756
|
+
const detail = [...new Set(file.kept.map((entry) => entry.reason))]
|
|
757
|
+
.map((reason) => `${file.kept.filter((entry) => entry.reason === reason).length} ${reason}`)
|
|
758
|
+
.join(', ');
|
|
759
|
+
console.log(`${file.removed > 0 ? verb : 'unchanged'} ${shown} (${file.removed} removed, ${file.kept.length} kept${detail ? `: ${detail}` : ''}${file.importsRemoved > 0 ? `, ${file.importsRemoved} import(s) dropped` : ''})`);
|
|
760
|
+
if (file.changed) {
|
|
761
|
+
changedFiles += 1;
|
|
762
|
+
if (isWrite) {
|
|
763
|
+
(0, node_fs_1.writeFileSync)(file.file, file.output);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
console.log(`devz codemod drop-redundant-casts: ${removed} cast(s) ${isWrite ? 'removed' : 'would be removed'} in ${changedFiles} file(s), ${kept} kept` +
|
|
769
|
+
(reasons.size > 0
|
|
770
|
+
? ` (${[...reasons].map(([reason, count]) => `${count} ${reason}`).join(', ')})`
|
|
771
|
+
: '') +
|
|
772
|
+
(importsRemoved > 0 ? `, ${importsRemoved} unused import(s) dropped` : ''));
|
|
773
|
+
if (!isWrite && changedFiles > 0) {
|
|
774
|
+
console.log(`Nothing was written. Run again with ${CastFlags.WRITE} to apply, then run your typecheck.`);
|
|
775
|
+
}
|
|
776
|
+
return isCheck && removed > 0 ? 1 : 0;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
exports.DropRedundantCastsCommand = DropRedundantCastsCommand;
|
|
780
|
+
//# sourceMappingURL=drop-redundant-casts.js.map
|