@venizia/dev-configs 0.4.8-9 → 0.4.8

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/README.md CHANGED
@@ -405,8 +405,9 @@ The package installs a `devz` binary. Run `devz --help` for the list, and `devz
405
405
  The codemods are `drop-redundant-casts` (removes `as X` casts the compiler no longer needs),
406
406
  `const-classes` (turns a string-literal union into a const class), `async-style` (applies the async style
407
407
  fixers and lists the rest), `namespace-functions` (moves calls of a function that moved into a class to the
408
- class form) and `connector-imports` (moves `@venizia/ignis/<connector sub-path>` imports to
409
- `@venizia/ignis-connectors`).
408
+ class form), `connector-imports` (moves `@venizia/ignis/<connector sub-path>` imports to
409
+ `@venizia/ignis-connectors`) and `env-get` (strips the type arguments of `applicationEnvironment.get()`
410
+ for the string-reading `get()`; the receiver is a name the call's scope resolves to an import of `applicationEnvironment` or `AppEnvs` from the store module, or a const initialised from one; every other `get<...>(key)` call is listed as skipped, and a call it cannot place as manual, with its file and line) and `any-aliases` (replaces the removed `AnyType` and `AnyObject` aliases by what they stood for, `any` and `Record<string | symbol | number, any>`, so no type changes, and drops them from the imports; `--strict` writes `unknown` and `Record<string, unknown>` instead; it reads imports from `@venizia/ignis`, `-helpers`, `-inversion`, and from `@venizia/ardor` and `-kernel`, which re-exported them).
410
411
 
411
412
  ## Where it sits
412
413
 
@@ -0,0 +1,35 @@
1
+ export interface IAnyAliasesResult {
2
+ output: string;
3
+ changed: boolean;
4
+ /** How many type references were rewritten. */
5
+ rewritten: number;
6
+ /** What the codemod cannot place: file line (1-based) and why. */
7
+ manual: Array<{
8
+ line: number;
9
+ reason: string;
10
+ }>;
11
+ /** Same-named types that are not the IGNIS aliases: file line (1-based) and the name. */
12
+ local: Array<{
13
+ line: number;
14
+ name: string;
15
+ }>;
16
+ }
17
+ /** Replaces the deleted `AnyType` and `AnyObject` aliases by what they stood for (`any`), or with `isStrict` by the tighter types. */
18
+ export declare class AnyAliases {
19
+ static rewrite(opts: {
20
+ typescript: typeof import('typescript');
21
+ fileName: string;
22
+ source: string;
23
+ /** Write `unknown` and `Record<string, unknown>` instead of `any`. */
24
+ isStrict?: boolean;
25
+ }): IAnyAliasesResult;
26
+ }
27
+ /** `devz codemod any-aliases`: reads the sources, prints what changes, writes with `--write`. */
28
+ export declare class AnyAliasesCommand {
29
+ static readonly USAGE = "Usage: devz codemod any-aliases [paths...] [--strict] [--write [--all] | --check]\n\nReplaces the AnyType and AnyObject aliases the @venizia/ignis-helpers and @venizia/ignis-inversion\nreleases deleted, by what they stood for, so a bump changes no type in your code:\n\n AnyType becomes any\n AnyObject becomes Record<string | symbol | number, any>\n\nin every file that imports them from @venizia/ignis, @venizia/ignis-helpers, @venizia/ignis-inversion,\n@venizia/ardor or @venizia/ardor-kernel (ARDOR re-exported the same two names; a sub-path such as\n@venizia/ignis-helpers/common too), whatever local name the import gives them\n(import { AnyType as Loose } ...). The names leave the import, and an import left empty is dropped.\n\nWith --strict it writes the tighter types instead of the default ones, for code that wants to stop using any:\n\n AnyType becomes unknown\n AnyObject becomes Record<string, unknown>\n\n--strict surfaces errors that any hid: an unknown value cannot be read, or passed as a narrower type, without a\ncheck; an interface-typed value is not assignable to Record<string, unknown> (an interface has no implicit\nindex signature); and a symbol key on a former AnyObject fails (TS2538). Declare the shape as a type\nalias, spread the value, or narrow it; run your typecheck after it.\n--strict acts only on the alias names: a file already rewritten to any is left alone, so run it instead of\nthe default run, on a path at a time, and tighten the rest by hand.\n\nIt lists, and leaves alone:\n manual a re-export (export { AnyType }, export type { AnyObject } from ...), an import(\"...\").AnyType\n type, and AnyType in a heritage clause (extends any and extends unknown are not valid)\n local a same-named type the file declares (in any scope: a namespace, a function, a block, a type\n parameter) or imports from somewhere else; a use that such a declaration shadows is left alone\n\nA name used in a heritage clause keeps its import, and so keeps all its other uses in that file: once you\nreplace the heritage use by hand, run the codemod again and the other uses are rewritten.\n\nIt reads TypeScript files (.ts, .tsx, .mts, .cts) and is idempotent: a second run changes nothing.\n\n --strict write unknown and Record<string, unknown> instead of any\n --write write the changed files (without it, nothing is written); it needs a path, or --all\n --all with --write and no path: rewrite every source file under the working directory\n --check dry run that exits 1 while a file would change or a manual case is left (for CI)\n --help print this text and exit\n\nWith no flag it lists what would change and writes nothing. Inside a git repository it reads the files\ngit knows, and --write refuses a file with local changes: commit or stash it first, so git can undo it.\nThere is no --reverse: a downgrade restores the files from git.";
30
+ static run(opts: {
31
+ root: string;
32
+ args: string[];
33
+ }): Promise<number>;
34
+ }
35
+ //# sourceMappingURL=any-aliases.d.ts.map
@@ -0,0 +1,544 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AnyAliasesCommand = exports.AnyAliases = 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
+ const USAGE = `Usage: devz codemod any-aliases [paths...] [--strict] [--write [--all] | --check]
8
+
9
+ Replaces the AnyType and AnyObject aliases the @venizia/ignis-helpers and @venizia/ignis-inversion
10
+ releases deleted, by what they stood for, so a bump changes no type in your code:
11
+
12
+ AnyType becomes any
13
+ AnyObject becomes Record<string | symbol | number, any>
14
+
15
+ in every file that imports them from @venizia/ignis, @venizia/ignis-helpers, @venizia/ignis-inversion,
16
+ @venizia/ardor or @venizia/ardor-kernel (ARDOR re-exported the same two names; a sub-path such as
17
+ @venizia/ignis-helpers/common too), whatever local name the import gives them
18
+ (import { AnyType as Loose } ...). The names leave the import, and an import left empty is dropped.
19
+
20
+ With --strict it writes the tighter types instead of the default ones, for code that wants to stop using any:
21
+
22
+ AnyType becomes unknown
23
+ AnyObject becomes Record<string, unknown>
24
+
25
+ --strict surfaces errors that any hid: an unknown value cannot be read, or passed as a narrower type, without a
26
+ check; an interface-typed value is not assignable to Record<string, unknown> (an interface has no implicit
27
+ index signature); and a symbol key on a former AnyObject fails (TS2538). Declare the shape as a type
28
+ alias, spread the value, or narrow it; run your typecheck after it.
29
+ --strict acts only on the alias names: a file already rewritten to any is left alone, so run it instead of
30
+ the default run, on a path at a time, and tighten the rest by hand.
31
+
32
+ It lists, and leaves alone:
33
+ manual a re-export (export { AnyType }, export type { AnyObject } from ...), an import("...").AnyType
34
+ type, and AnyType in a heritage clause (extends any and extends unknown are not valid)
35
+ local a same-named type the file declares (in any scope: a namespace, a function, a block, a type
36
+ parameter) or imports from somewhere else; a use that such a declaration shadows is left alone
37
+
38
+ A name used in a heritage clause keeps its import, and so keeps all its other uses in that file: once you
39
+ replace the heritage use by hand, run the codemod again and the other uses are rewritten.
40
+
41
+ It reads TypeScript files (.ts, .tsx, .mts, .cts) and is idempotent: a second run changes nothing.
42
+
43
+ --strict write unknown and Record<string, unknown> instead of any
44
+ --write write the changed files (without it, nothing is written); it needs a path, or --all
45
+ --all with --write and no path: rewrite every source file under the working directory
46
+ --check dry run that exits 1 while a file would change or a manual case is left (for CI)
47
+ --help print this text and exit
48
+
49
+ With no flag it lists what would change and writes nothing. Inside a git repository it reads the files
50
+ git knows, and --write refuses a file with local changes: commit or stash it first, so git can undo it.
51
+ There is no --reverse: a downgrade restores the files from git.`;
52
+ /** A usage error: nothing was read or written. */
53
+ const USAGE_ERROR_CODE = 2;
54
+ /**
55
+ * The packages the aliases were exported from, each with or without a sub-path: the IGNIS root package, helpers and
56
+ * inversion, and the ARDOR packages that re-exported the same two names (same names, same meaning).
57
+ */
58
+ const ALIAS_PACKAGES = [
59
+ '@venizia/ignis',
60
+ '@venizia/ignis-helpers',
61
+ '@venizia/ignis-inversion',
62
+ '@venizia/ardor',
63
+ '@venizia/ardor-kernel',
64
+ ];
65
+ const ALIAS_MODULE = new RegExp(`^(?:${ALIAS_PACKAGES.map((name) => name.replace(/[/.-]/g, '\\$&')).join('|')})(?:/.*)?$`);
66
+ /** The deleted aliases and what each becomes by default: what they stood for, so the types of the code do not change. */
67
+ const REPLACEMENTS = new Map([
68
+ ['AnyType', 'any'],
69
+ ['AnyObject', 'Record<string | symbol | number, any>'],
70
+ ]);
71
+ /** With `--strict`: the tighter types, for code that wants to stop using `any`. */
72
+ const STRICT_REPLACEMENTS = new Map([
73
+ ['AnyType', 'unknown'],
74
+ ['AnyObject', 'Record<string, unknown>'],
75
+ ]);
76
+ /** What `AnyType` becomes in either mode: neither `extends any` nor `extends unknown` is valid, so a heritage use is left. */
77
+ const HERITAGE_BLOCKED = new Set(['any', 'unknown']);
78
+ class AnyAliasesFlags {
79
+ static { this.WRITE = '--write'; }
80
+ static { this.ALL = '--all'; }
81
+ static { this.CHECK = '--check'; }
82
+ static { this.STRICT = '--strict'; }
83
+ static { this.HELP = '--help'; }
84
+ static { this.HELP_SHORT = '-h'; }
85
+ static { this.SCHEME_SET = new Set([
86
+ this.WRITE,
87
+ this.ALL,
88
+ this.CHECK,
89
+ this.STRICT,
90
+ this.HELP,
91
+ this.HELP_SHORT,
92
+ ]); }
93
+ static isValid(value) {
94
+ return this.SCHEME_SET.has(value);
95
+ }
96
+ }
97
+ /** Replaces the deleted `AnyType` and `AnyObject` aliases by what they stood for (`any`), or with `isStrict` by the tighter types. */
98
+ class AnyAliases {
99
+ static rewrite(opts) {
100
+ const { typescript: ts, fileName, source, isStrict = false } = opts;
101
+ const replacements = isStrict ? STRICT_REPLACEMENTS : REPLACEMENTS;
102
+ const language = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
103
+ const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, language);
104
+ const edits = [];
105
+ const manual = [];
106
+ const local = [];
107
+ let rewritten = 0;
108
+ const lineOf = (node) => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1;
109
+ const addReplacement = (node, replacement) => {
110
+ edits.push({ start: node.getStart(file), end: node.getEnd(), text: replacement });
111
+ rewritten += 1;
112
+ };
113
+ // The local names bound to an alias (name -> replacement), the namespace imports of a module that held them
114
+ // and the names the file exports.
115
+ const aliasNames = new Map();
116
+ const namespaces = new Set();
117
+ const exportedNames = new Set();
118
+ /**
119
+ * Whether a declaration in a scope that encloses `node` (below the file: a namespace, a function, a block, a
120
+ * type parameter) binds `name`, so the name there is not the file-level import. `isNamespace` is what the use needs:
121
+ * a namespace (the left side of `H.AnyType`) rather than a type.
122
+ */
123
+ const isShadowed = (node, name, isNamespace) => {
124
+ const hasInfer = (type) => (ts.isInferTypeNode(type) && type.typeParameter.name.text === name) ||
125
+ ts.forEachChild(type, (child) => (hasInfer(child) ? true : undefined)) === true;
126
+ // `child` is the node the walk came from: an `infer` name is bound in the true branch of its conditional type only.
127
+ let child = node;
128
+ for (let scope = node.parent; scope !== undefined;) {
129
+ if (ts.isSourceFile(scope)) {
130
+ return false;
131
+ }
132
+ if (!isNamespace) {
133
+ if ((ts.isFunctionLike(scope) ||
134
+ ts.isClassLike(scope) ||
135
+ ts.isInterfaceDeclaration(scope) ||
136
+ ts.isTypeAliasDeclaration(scope)) &&
137
+ scope.typeParameters?.some((parameter) => parameter.name.text === name)) {
138
+ return true;
139
+ }
140
+ if (ts.isMappedTypeNode(scope) && scope.typeParameter.name.text === name) {
141
+ return true;
142
+ }
143
+ if (ts.isConditionalTypeNode(scope) &&
144
+ child === scope.trueType &&
145
+ hasInfer(scope.extendsType)) {
146
+ return true;
147
+ }
148
+ }
149
+ if (ts.isBlock(scope) ||
150
+ ts.isModuleBlock(scope) ||
151
+ ts.isCaseClause(scope) ||
152
+ ts.isDefaultClause(scope)) {
153
+ for (const statement of scope.statements) {
154
+ let declared;
155
+ if (ts.isTypeAliasDeclaration(statement) ||
156
+ ts.isInterfaceDeclaration(statement) ||
157
+ ts.isClassDeclaration(statement)) {
158
+ declared = !isNamespace ? statement.name : undefined;
159
+ }
160
+ else if (ts.isEnumDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) {
161
+ declared = statement.name;
162
+ }
163
+ else if (ts.isModuleDeclaration(statement)) {
164
+ declared = isNamespace ? statement.name : undefined;
165
+ }
166
+ if (declared !== undefined && ts.isIdentifier(declared) && declared.text === name) {
167
+ return true;
168
+ }
169
+ }
170
+ }
171
+ child = scope;
172
+ scope = scope.parent;
173
+ }
174
+ return false;
175
+ };
176
+ // `export { AnyType }` keeps the import alive: that name is left to the user (reported below).
177
+ for (const statement of file.statements) {
178
+ if (ts.isExportDeclaration(statement) &&
179
+ statement.moduleSpecifier === undefined &&
180
+ statement.exportClause !== undefined &&
181
+ ts.isNamedExports(statement.exportClause)) {
182
+ for (const element of statement.exportClause.elements) {
183
+ exportedNames.add((element.propertyName ?? element.name).text);
184
+ }
185
+ }
186
+ }
187
+ // `extends any`, `extends unknown` and `implements` of either are not valid TypeScript: an alias used in a heritage
188
+ // clause whose replacement is `any` or `unknown` is left (import and references) and reported where it is used.
189
+ const heritageBlocked = new Set();
190
+ const importedReplacement = new Map();
191
+ for (const statement of file.statements) {
192
+ if (ts.isImportDeclaration(statement) &&
193
+ ts.isStringLiteral(statement.moduleSpecifier) &&
194
+ ALIAS_MODULE.test(statement.moduleSpecifier.text) &&
195
+ statement.importClause?.namedBindings !== undefined &&
196
+ ts.isNamedImports(statement.importClause.namedBindings)) {
197
+ for (const element of statement.importClause.namedBindings.elements) {
198
+ const replacement = replacements.get((element.propertyName ?? element.name).text);
199
+ if (replacement !== undefined) {
200
+ importedReplacement.set(element.name.text, replacement);
201
+ }
202
+ }
203
+ }
204
+ }
205
+ const scanHeritage = (node) => {
206
+ if (ts.isExpressionWithTypeArguments(node) &&
207
+ ts.isIdentifier(node.expression) &&
208
+ HERITAGE_BLOCKED.has(importedReplacement.get(node.expression.text) ?? '') &&
209
+ !isShadowed(node, node.expression.text, false)) {
210
+ heritageBlocked.add(node.expression.text);
211
+ }
212
+ ts.forEachChild(node, scanHeritage);
213
+ };
214
+ scanHeritage(file);
215
+ const removedRanges = [];
216
+ // Imports: which local names are the aliases, and how each import is rewritten.
217
+ for (const statement of file.statements) {
218
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {
219
+ continue;
220
+ }
221
+ const clause = statement.importClause;
222
+ const isAliasSource = ALIAS_MODULE.test(statement.moduleSpecifier.text);
223
+ if (clause === undefined) {
224
+ continue;
225
+ }
226
+ if (clause.namedBindings !== undefined && ts.isNamespaceImport(clause.namedBindings)) {
227
+ if (isAliasSource) {
228
+ namespaces.add(clause.namedBindings.name.text);
229
+ }
230
+ continue;
231
+ }
232
+ if (clause.namedBindings === undefined || !ts.isNamedImports(clause.namedBindings)) {
233
+ if (clause.name !== undefined && replacements.has(clause.name.text) && !isAliasSource) {
234
+ local.push({ line: lineOf(clause.name), name: clause.name.text });
235
+ }
236
+ continue;
237
+ }
238
+ const named = clause.namedBindings;
239
+ const kept = [];
240
+ // A comment that follows an element on its line (after its comma) belongs to that element: it goes with it
241
+ // when the element is removed, and it is not part of the next element's leading comments.
242
+ const trailings = named.elements.map((element) => {
243
+ const match = /^[ \t]*,?[ \t]*(\/\/[^\r\n]*|\/\*[^\r\n]*?\*\/)/.exec(source.slice(element.getEnd()));
244
+ return { comment: match?.[1] ?? '', end: element.getEnd() + (match?.[0].length ?? 0) };
245
+ });
246
+ /** An element as it is kept: its text with its own leading comments, and the comment that follows it on its line. */
247
+ const keep = (element, index) => {
248
+ const previous = trailings[index - 1];
249
+ const from = previous === undefined || previous.comment === ''
250
+ ? element.getFullStart()
251
+ : Math.max(element.getFullStart(), previous.end);
252
+ kept.push({
253
+ text: source.slice(from, element.getEnd()).trim(),
254
+ trailing: trailings[index]?.comment ?? '',
255
+ });
256
+ };
257
+ let removed = 0;
258
+ for (const [index, element] of named.elements.entries()) {
259
+ const imported = (element.propertyName ?? element.name).text;
260
+ const localName = element.name.text;
261
+ const replacement = replacements.get(imported);
262
+ if (replacement === undefined) {
263
+ keep(element, index);
264
+ continue;
265
+ }
266
+ if (!isAliasSource) {
267
+ keep(element, index);
268
+ local.push({ line: lineOf(element), name: localName });
269
+ continue;
270
+ }
271
+ if (exportedNames.has(localName)) {
272
+ keep(element, index);
273
+ manual.push({
274
+ line: lineOf(element),
275
+ reason: `${localName}${localName === imported ? '' : ` (the alias ${imported})`} is re-exported by this file: the alias is gone, export the type you meant`,
276
+ });
277
+ continue;
278
+ }
279
+ if (heritageBlocked.has(localName)) {
280
+ keep(element, index);
281
+ continue;
282
+ }
283
+ aliasNames.set(localName, replacement);
284
+ removed += 1;
285
+ }
286
+ if (removed === 0) {
287
+ continue;
288
+ }
289
+ if (kept.length === 0 && clause.name === undefined) {
290
+ const start = statement.getStart(file);
291
+ let end = statement.getEnd();
292
+ if (source.startsWith('\r\n', end)) {
293
+ end += 2;
294
+ }
295
+ else if (source[end] === '\n') {
296
+ end += 1;
297
+ }
298
+ // A blank line that only separated this import from the next code (or from the top of the file) goes with it.
299
+ // The imports removed before this one are not there any more: a file that starts with a removed import
300
+ // must not start with a blank line.
301
+ let before = source.slice(0, start);
302
+ for (const range of [...removedRanges].reverse()) {
303
+ before = before.slice(0, range.start) + before.slice(range.end);
304
+ }
305
+ const isOnlyLeading = before.trim() === '' || /\n\s*\n$/.test(before);
306
+ const blank = /^[ \t]*\r?\n/.exec(source.slice(end));
307
+ if (isOnlyLeading && blank !== null) {
308
+ end += blank[0].length;
309
+ }
310
+ edits.push({ start, end, text: '' });
311
+ removedRanges.push({ start, end });
312
+ }
313
+ else if (kept.length === 0 && clause.name !== undefined) {
314
+ // A default import stays: `import Default, { AnyType } from ...` -> `import Default from ...`.
315
+ edits.push({ start: clause.name.getEnd(), end: named.getEnd(), text: '' });
316
+ }
317
+ else {
318
+ const isMultiline = /\r?\n/.test(source.slice(named.getStart(file), named.getEnd()));
319
+ const hasTrailingComma = named.elements.hasTrailingComma;
320
+ const lines = kept.map((item, index) => {
321
+ const comma = index < kept.length - 1 || hasTrailingComma ? ',' : '';
322
+ return ` ${item.text}${comma}${item.trailing === '' ? '' : ` ${item.trailing}`}`;
323
+ });
324
+ const text = isMultiline
325
+ ? `{\n${lines.join('\n')}\n}`
326
+ : `{ ${kept.map((item) => item.text).join(', ')} }`;
327
+ edits.push({ start: named.getStart(file), end: named.getEnd(), text });
328
+ }
329
+ }
330
+ // Declarations of a same-named type that is not an import of the aliases.
331
+ for (const statement of file.statements) {
332
+ if ((ts.isTypeAliasDeclaration(statement) ||
333
+ ts.isInterfaceDeclaration(statement) ||
334
+ ts.isClassDeclaration(statement) ||
335
+ ts.isEnumDeclaration(statement)) &&
336
+ statement.name !== undefined &&
337
+ replacements.has(statement.name.text) &&
338
+ !aliasNames.has(statement.name.text)) {
339
+ local.push({ line: lineOf(statement.name), name: statement.name.text });
340
+ }
341
+ }
342
+ const visit = (node) => {
343
+ // A same-named type declared below the file level (a namespace, a function, a block, a type parameter) is a
344
+ // different type: it is listed, and the uses it shadows are left alone (see isShadowed).
345
+ if ((ts.isTypeAliasDeclaration(node) ||
346
+ ts.isInterfaceDeclaration(node) ||
347
+ ts.isClassDeclaration(node) ||
348
+ ts.isEnumDeclaration(node) ||
349
+ ts.isTypeParameterDeclaration(node)) &&
350
+ node.name !== undefined &&
351
+ replacements.has(node.name.text) &&
352
+ !ts.isSourceFile(node.parent)) {
353
+ local.push({ line: lineOf(node.name), name: node.name.text });
354
+ }
355
+ if (ts.isTypeReferenceNode(node) && node.typeArguments === undefined) {
356
+ const { typeName } = node;
357
+ const byName = ts.isIdentifier(typeName) && !isShadowed(node, typeName.text, false)
358
+ ? aliasNames.get(typeName.text)
359
+ : undefined;
360
+ const byNamespace = ts.isQualifiedName(typeName) &&
361
+ ts.isIdentifier(typeName.left) &&
362
+ namespaces.has(typeName.left.text) &&
363
+ !isShadowed(node, typeName.left.text, true)
364
+ ? replacements.get(typeName.right.text)
365
+ : undefined;
366
+ const replacement = byName ?? byNamespace;
367
+ if (replacement !== undefined) {
368
+ addReplacement(node, replacement);
369
+ return;
370
+ }
371
+ }
372
+ if (ts.isExpressionWithTypeArguments(node) && node.typeArguments === undefined) {
373
+ const { expression } = node;
374
+ const byName = ts.isIdentifier(expression) && !isShadowed(node, expression.text, false)
375
+ ? aliasNames.get(expression.text)
376
+ : undefined;
377
+ const byNamespace = ts.isPropertyAccessExpression(expression) &&
378
+ ts.isIdentifier(expression.expression) &&
379
+ namespaces.has(expression.expression.text) &&
380
+ !isShadowed(node, expression.expression.text, true)
381
+ ? replacements.get(expression.name.text)
382
+ : undefined;
383
+ const replacement = byName ?? byNamespace;
384
+ if (replacement !== undefined && HERITAGE_BLOCKED.has(replacement)) {
385
+ manual.push({
386
+ line: lineOf(node),
387
+ reason: `${node.getText(file)} in a heritage clause: extends any, extends unknown and implements are not valid, name the members you mean`,
388
+ });
389
+ return;
390
+ }
391
+ if (replacement !== undefined) {
392
+ addReplacement(node, replacement);
393
+ return;
394
+ }
395
+ if (ts.isIdentifier(expression) &&
396
+ heritageBlocked.has(expression.text) &&
397
+ !isShadowed(node, expression.text, false)) {
398
+ manual.push({
399
+ line: lineOf(node),
400
+ reason: `${expression.text} in a heritage clause: extends any, extends unknown and implements are not valid, name the members you mean`,
401
+ });
402
+ return;
403
+ }
404
+ }
405
+ if (ts.isImportTypeNode(node) &&
406
+ node.qualifier !== undefined &&
407
+ ts.isIdentifier(node.qualifier) &&
408
+ replacements.has(node.qualifier.text) &&
409
+ ts.isLiteralTypeNode(node.argument) &&
410
+ ts.isStringLiteral(node.argument.literal) &&
411
+ ALIAS_MODULE.test(node.argument.literal.text)) {
412
+ manual.push({
413
+ line: lineOf(node),
414
+ reason: `import("${node.argument.literal.text}").${node.qualifier.text}: replace the whole type by hand`,
415
+ });
416
+ }
417
+ if (ts.isExportDeclaration(node) &&
418
+ node.exportClause !== undefined &&
419
+ ts.isNamedExports(node.exportClause)) {
420
+ const isIgnisSource = node.moduleSpecifier !== undefined &&
421
+ ts.isStringLiteral(node.moduleSpecifier) &&
422
+ ALIAS_MODULE.test(node.moduleSpecifier.text);
423
+ for (const element of node.exportClause.elements) {
424
+ const exported = (element.propertyName ?? element.name).text;
425
+ if (replacements.has(exported) && isIgnisSource) {
426
+ manual.push({
427
+ line: lineOf(element),
428
+ reason: `a re-export of ${exported}: the alias is gone, export the type you meant`,
429
+ });
430
+ }
431
+ }
432
+ }
433
+ ts.forEachChild(node, visit);
434
+ };
435
+ visit(file);
436
+ if (edits.length === 0) {
437
+ return { output: source, changed: false, rewritten: 0, manual, local };
438
+ }
439
+ let output = source;
440
+ for (const edit of [...edits].sort((left, right) => right.start - left.start)) {
441
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
442
+ }
443
+ return { output, changed: output !== source, rewritten, manual, local };
444
+ }
445
+ }
446
+ exports.AnyAliases = AnyAliases;
447
+ /** `devz codemod any-aliases`: reads the sources, prints what changes, writes with `--write`. */
448
+ class AnyAliasesCommand {
449
+ static { this.USAGE = USAGE; }
450
+ static async run(opts) {
451
+ const { root, args } = opts;
452
+ if (args.includes(AnyAliasesFlags.HELP) || args.includes(AnyAliasesFlags.HELP_SHORT)) {
453
+ console.log(USAGE);
454
+ return 0;
455
+ }
456
+ const flags = args.filter((argument) => argument.startsWith('-'));
457
+ const paths = args.filter((argument) => !argument.startsWith('-'));
458
+ const unknown = flags.filter((flag) => !AnyAliasesFlags.isValid(flag));
459
+ if (unknown.length > 0) {
460
+ console.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
461
+ return USAGE_ERROR_CODE;
462
+ }
463
+ const isWrite = flags.includes(AnyAliasesFlags.WRITE);
464
+ const isCheck = flags.includes(AnyAliasesFlags.CHECK);
465
+ const isStrict = flags.includes(AnyAliasesFlags.STRICT);
466
+ if (isWrite && isCheck) {
467
+ console.error(`devz codemod: ${AnyAliasesFlags.WRITE} and ${AnyAliasesFlags.CHECK} contradict each other\n${USAGE}`);
468
+ return USAGE_ERROR_CODE;
469
+ }
470
+ const refusal = files_1.CodemodFiles.refusal({
471
+ command: 'any-aliases',
472
+ isWrite,
473
+ isAll: flags.includes(AnyAliasesFlags.ALL),
474
+ paths,
475
+ });
476
+ if (refusal) {
477
+ console.error(`${refusal}\n${USAGE}`);
478
+ return USAGE_ERROR_CODE;
479
+ }
480
+ let typescript;
481
+ try {
482
+ const loaded = await import('typescript');
483
+ typescript = loaded.default;
484
+ }
485
+ catch {
486
+ console.error('devz codemod: the "typescript" package is required to read your sources');
487
+ return 1;
488
+ }
489
+ const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
490
+ let changedCount = 0;
491
+ let referenceCount = 0;
492
+ let manualCount = 0;
493
+ let localCount = 0;
494
+ let refusedCount = 0;
495
+ for (const target of targets) {
496
+ const files = files_1.CodemodFiles.collect({ target });
497
+ const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
498
+ if (files.length === 0 && paths.length > 0) {
499
+ 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`);
500
+ }
501
+ for (const file of files) {
502
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
503
+ if (!/\bAny(?:Type|Object)\b/.test(source)) {
504
+ continue;
505
+ }
506
+ const result = AnyAliases.rewrite({ typescript, fileName: file, source, isStrict });
507
+ const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
508
+ for (const item of result.manual) {
509
+ manualCount += 1;
510
+ console.warn(`manual ${shown}:${item.line} ${item.reason}`);
511
+ }
512
+ for (const item of result.local) {
513
+ localCount += 1;
514
+ console.warn(`local ${shown}:${item.line} ${item.name} is not the IGNIS alias (declared here or imported from elsewhere): left alone`);
515
+ }
516
+ if (!result.changed) {
517
+ continue;
518
+ }
519
+ if (dirty?.has(file)) {
520
+ refusedCount += 1;
521
+ console.warn(`refused ${shown} has local changes (commit or stash them, then run again)`);
522
+ continue;
523
+ }
524
+ changedCount += 1;
525
+ referenceCount += result.rewritten;
526
+ console.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} reference(s))`);
527
+ if (isWrite) {
528
+ (0, node_fs_1.writeFileSync)(file, result.output);
529
+ }
530
+ }
531
+ }
532
+ console.log(`devz codemod any-aliases: ${changedCount} file(s) ${isWrite ? 'changed' : 'would change'}, ${referenceCount} reference(s) ${isWrite ? 'rewritten' : 'would be rewritten'}, ${manualCount} manual, ${localCount} local` +
533
+ (refusedCount > 0 ? `, ${refusedCount} refused` : ''));
534
+ if (!isWrite && changedCount > 0) {
535
+ console.log(`Nothing was written. Run again with ${AnyAliasesFlags.WRITE} to apply, then run your typecheck${isStrict ? ': a value an alias used to accept may need a type alias, a spread or a narrowing' : ''}.`);
536
+ }
537
+ if (isWrite && refusedCount > 0) {
538
+ return 1;
539
+ }
540
+ return isCheck && (changedCount > 0 || manualCount > 0) ? 1 : 0;
541
+ }
542
+ }
543
+ exports.AnyAliasesCommand = AnyAliasesCommand;
544
+ //# sourceMappingURL=any-aliases.js.map