ts-codemod-lib 3.2.0 → 3.3.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.
@@ -0,0 +1,565 @@
1
+ /* eslint-disable tree-shakable/import-star */
2
+ /* eslint-disable vitest/expect-expect */
3
+ import dedent from 'dedent';
4
+ import * as prettierPluginEstree from 'prettier/plugins/estree';
5
+ import * as prettierPluginTypeScript from 'prettier/plugins/typescript';
6
+ import * as prettier from 'prettier/standalone';
7
+ import * as tsm from 'ts-morph';
8
+ import { enableNoUncheckedIndexedAccessTransformer } from './enable-no-unchecked-indexed-access.mjs';
9
+ import { transformSourceCode } from './transform-source-code.mjs';
10
+
11
+ /**
12
+ * Declarations every case is prefixed with, so that each `source` can be a
13
+ * single expression statement. `declare const` keeps them free of index
14
+ * accesses of their own.
15
+ */
16
+ const preamble = dedent`
17
+ declare const xs: readonly number[];
18
+ declare const mut_ys: number[];
19
+ declare const pair: readonly [number, number];
20
+ declare const rest: readonly [number, number, ...(readonly number[])];
21
+ declare const known: { readonly a: number };
22
+ declare const rec: Record<string, number>;
23
+ declare const loose: { readonly a: number; readonly [k: string]: number };
24
+ declare const nested: Record<string, readonly number[]>;
25
+ declare const sparse: readonly (number | undefined)[];
26
+ declare const fns: readonly ((x: number) => void)[];
27
+ declare const ctors: readonly (new () => object)[];
28
+ declare const str: string;
29
+ declare const i: number;
30
+ declare const k: string;
31
+ `;
32
+
33
+ const testFn = async ({
34
+ source,
35
+ expected,
36
+ options,
37
+ debug,
38
+ }: Readonly<{
39
+ source: string;
40
+ expected: string;
41
+ options?: Parameters<typeof enableNoUncheckedIndexedAccessTransformer>[0];
42
+ debug?: boolean;
43
+ }>): Promise<void> => {
44
+ if (debug !== true) {
45
+ // eslint-disable-next-line vitest/no-restricted-vi-methods
46
+ vi.spyOn(console, 'debug').mockImplementation(() => {});
47
+ }
48
+
49
+ const transformed = await formatter(
50
+ transformSourceCode(`${preamble}\n\n${source}`, false, [
51
+ enableNoUncheckedIndexedAccessTransformer({ ...options, debug }),
52
+ ]),
53
+ );
54
+
55
+ const expectedFormatted = await formatter(`${preamble}\n\n${expected}`);
56
+
57
+ expect(transformed).toBe(expectedFormatted);
58
+ };
59
+
60
+ const formatter = (code: string): Promise<string> =>
61
+ prettier.format(code, {
62
+ parser: 'typescript',
63
+ plugins: [prettierPluginTypeScript, prettierPluginEstree],
64
+ });
65
+
66
+ describe(enableNoUncheckedIndexedAccessTransformer, () => {
67
+ describe('accesses the option widens with undefined', () => {
68
+ test.each([
69
+ {
70
+ name: 'array with a literal index',
71
+ source: 'console.log(xs[0].toFixed());',
72
+ expected: 'console.log(xs[0]!.toFixed());',
73
+ },
74
+ {
75
+ name: 'array with a computed index',
76
+ source: 'console.log(xs[i] + 1);',
77
+ expected: 'console.log(xs[i]! + 1);',
78
+ },
79
+ {
80
+ name: 'index signature record',
81
+ source: "console.log(rec['a'].toFixed());",
82
+ expected: "console.log(rec['a']!.toFixed());",
83
+ },
84
+ {
85
+ name: 'index signature record with a computed key',
86
+ source: 'console.log(rec[k].toFixed());',
87
+ expected: 'console.log(rec[k]!.toFixed());',
88
+ },
89
+ {
90
+ name: 'dotted read of an index signature',
91
+ source: 'console.log(rec.a.toFixed());',
92
+ expected: 'console.log(rec.a!.toFixed());',
93
+ },
94
+ {
95
+ name: 'dotted read of an undeclared key of a type with an index signature',
96
+ source: 'console.log(loose.b.toFixed());',
97
+ expected: 'console.log(loose.b!.toFixed());',
98
+ },
99
+ {
100
+ name: 'string index',
101
+ source: 'console.log(str[0].charCodeAt(0));',
102
+ expected: 'console.log(str[0]!.charCodeAt(0));',
103
+ },
104
+ {
105
+ name: 'tuple index past its fixed part',
106
+ source: 'console.log(rest[9].toFixed());',
107
+ expected: 'console.log(rest[9]!.toFixed());',
108
+ },
109
+ {
110
+ name: 'chained accesses are asserted at every step',
111
+ source: "console.log(nested['k'][0].toFixed());",
112
+ expected: "console.log(nested['k']![0]!.toFixed());",
113
+ },
114
+ {
115
+ name: 'callee position',
116
+ source: 'fns[0](1);',
117
+ expected: 'fns[0]!(1);',
118
+ },
119
+ {
120
+ name: 'constructor position',
121
+ source: 'console.log(new ctors[0]());',
122
+ expected: 'console.log(new ctors[0]!());',
123
+ },
124
+ {
125
+ name: 'spread element',
126
+ source: "console.log(...nested['k']);",
127
+ expected: "console.log(...nested['k']!);",
128
+ },
129
+ {
130
+ name: 'for-of iterable',
131
+ source: "for (const v of nested['k']) { console.log(v); }",
132
+ expected: "for (const v of nested['k']!) { console.log(v); }",
133
+ },
134
+ {
135
+ name: 'unary minus operand',
136
+ source: 'console.log(-xs[0]);',
137
+ expected: 'console.log(-xs[0]!);',
138
+ },
139
+ {
140
+ name: 'index argument of another access',
141
+ source: 'console.log(rec[String(xs[0])].toFixed());',
142
+ expected: 'console.log(rec[String(xs[0]!)]!.toFixed());',
143
+ },
144
+ {
145
+ name: 'initializer of an untyped const, where the error surfaces later',
146
+ source: dedent`
147
+ const head = xs[0];
148
+ console.log(head.toFixed());
149
+ `,
150
+ expected: dedent`
151
+ const head = xs[0]!;
152
+ console.log(head.toFixed());
153
+ `,
154
+ },
155
+ ])('$name', testFn);
156
+ });
157
+
158
+ describe('indices whose presence the type guarantees', () => {
159
+ test.each([
160
+ {
161
+ name: 'tuple index within its length',
162
+ source: 'console.log(pair[1].toFixed());',
163
+ expected: 'console.log(pair[1].toFixed());',
164
+ },
165
+ {
166
+ name: 'fixed part of a tuple with a rest element',
167
+ source: 'console.log(rest[1].toFixed());',
168
+ expected: 'console.log(rest[1].toFixed());',
169
+ },
170
+ {
171
+ name: 'declared property of an object without an index signature',
172
+ source: "console.log(known['a'].toFixed());",
173
+ expected: "console.log(known['a'].toFixed());",
174
+ },
175
+ {
176
+ name: 'declared property of a type that also has an index signature',
177
+ source: 'console.log(loose.a.toFixed());',
178
+ expected: 'console.log(loose.a.toFixed());',
179
+ },
180
+ {
181
+ name: 'ordinary property access',
182
+ source: 'console.log(known.a.toFixed());',
183
+ expected: 'console.log(known.a.toFixed());',
184
+ },
185
+ {
186
+ name: 'element type that already contained undefined',
187
+ source: 'console.log(sparse[0]?.toFixed());',
188
+ expected: 'console.log(sparse[0]?.toFixed());',
189
+ },
190
+ {
191
+ name: 'access already narrowed by a guard',
192
+ source: dedent`
193
+ if (xs[0] !== undefined) {
194
+ console.log(xs[0].toFixed());
195
+ }
196
+ `,
197
+ expected: dedent`
198
+ if (xs[0] !== undefined) {
199
+ console.log(xs[0].toFixed());
200
+ }
201
+ `,
202
+ },
203
+ {
204
+ name: 'value of unresolvable type',
205
+ source: dedent`
206
+ import { imported } from './other.mjs';
207
+
208
+ console.log(imported[0].toFixed());
209
+ `,
210
+ expected: dedent`
211
+ import { imported } from './other.mjs';
212
+
213
+ console.log(imported[0].toFixed());
214
+ `,
215
+ },
216
+ ])('$name', testFn);
217
+ });
218
+
219
+ describe('positions that cannot take an assertion', () => {
220
+ test.each([
221
+ {
222
+ name: 'assignment target',
223
+ source: 'mut_ys[0] = 1;',
224
+ expected: 'mut_ys[0] = 1;',
225
+ },
226
+ {
227
+ name: 'compound assignment target',
228
+ source: 'mut_ys[0] += 1;',
229
+ expected: 'mut_ys[0] += 1;',
230
+ },
231
+ {
232
+ name: 'logical assignment target',
233
+ source: 'mut_ys[0] ??= 1;',
234
+ expected: 'mut_ys[0] ??= 1;',
235
+ },
236
+ {
237
+ name: 'increment target',
238
+ source: 'mut_ys[0]++;',
239
+ expected: 'mut_ys[0]++;',
240
+ },
241
+ {
242
+ name: 'decrement target',
243
+ source: '--mut_ys[0];',
244
+ expected: '--mut_ys[0];',
245
+ },
246
+ {
247
+ name: 'delete target',
248
+ source: "delete rec['a'];",
249
+ expected: "delete rec['a'];",
250
+ },
251
+ {
252
+ name: 'dotted delete target',
253
+ source: 'delete rec.a;',
254
+ expected: 'delete rec.a;',
255
+ },
256
+ {
257
+ name: 'destructuring assignment target',
258
+ source: '[mut_ys[0]] = [1];',
259
+ expected: '[mut_ys[0]] = [1];',
260
+ },
261
+ {
262
+ name: 'for-of loop target',
263
+ source: 'for (mut_ys[0] of xs) { break; }',
264
+ expected: 'for (mut_ys[0] of xs) { break; }',
265
+ },
266
+ ])('$name', testFn);
267
+ });
268
+
269
+ describe('positions that already account for undefined', () => {
270
+ test.each([
271
+ {
272
+ name: 'existing non-null assertion',
273
+ source: 'console.log(xs[0]!.toFixed());',
274
+ expected: 'console.log(xs[0]!.toFixed());',
275
+ },
276
+ {
277
+ name: 'type assertion',
278
+ source: 'console.log((xs[0] as number).toFixed());',
279
+ expected: 'console.log((xs[0] as number).toFixed());',
280
+ },
281
+ {
282
+ name: 'optional property access',
283
+ source: 'console.log(xs[0]?.toFixed());',
284
+ expected: 'console.log(xs[0]?.toFixed());',
285
+ },
286
+ {
287
+ name: 'property access further along an optional chain',
288
+ source: 'console.log(nested?.k[0]);',
289
+ expected: 'console.log(nested?.k[0]);',
290
+ },
291
+ {
292
+ name: 'optional call',
293
+ source: 'fns[0]?.(1);',
294
+ expected: 'fns[0]?.(1);',
295
+ },
296
+ {
297
+ name: 'nullish coalescing',
298
+ source: 'console.log(xs[0] ?? 0);',
299
+ expected: 'console.log(xs[0] ?? 0);',
300
+ },
301
+ {
302
+ name: 'logical and',
303
+ source: 'console.log(xs[0] && 1);',
304
+ expected: 'console.log(xs[0] && 1);',
305
+ },
306
+ {
307
+ name: 'typeof',
308
+ source: 'console.log(typeof xs[0]);',
309
+ expected: 'console.log(typeof xs[0]);',
310
+ },
311
+ {
312
+ name: 'equality against undefined',
313
+ source: 'console.log(xs[0] === undefined);',
314
+ expected: 'console.log(xs[0] === undefined);',
315
+ },
316
+ {
317
+ name: 'if condition',
318
+ source: 'if (xs[0]) { console.log(1); }',
319
+ expected: 'if (xs[0]) { console.log(1); }',
320
+ },
321
+ {
322
+ name: 'while condition',
323
+ source: 'while (xs[0]) { break; }',
324
+ expected: 'while (xs[0]) { break; }',
325
+ },
326
+ {
327
+ name: 'negation',
328
+ source: 'console.log(!xs[0]);',
329
+ expected: 'console.log(!xs[0]);',
330
+ },
331
+ {
332
+ name: 'switch subject, where an asserted subject would reject `case undefined`',
333
+ source: 'switch (xs[0]) { case undefined: break; default: break; }',
334
+ expected: 'switch (xs[0]) { case undefined: break; default: break; }',
335
+ },
336
+ {
337
+ name: 'ternary condition',
338
+ source: 'console.log(xs[0] ? 1 : 2);',
339
+ expected: 'console.log(xs[0] ? 1 : 2);',
340
+ },
341
+ ])('$name', testFn);
342
+ });
343
+
344
+ describe('applyLevel: "avoidWhereUndefinedIsAllowed"', () => {
345
+ test.each([
346
+ {
347
+ name: 'skips an annotation that accepts undefined',
348
+ source: 'const a: number | undefined = xs[0];',
349
+ expected: 'const a: number | undefined = xs[0];',
350
+ options: { applyLevel: 'avoidWhereUndefinedIsAllowed' },
351
+ },
352
+ {
353
+ name: 'keeps an annotation that does not',
354
+ source: 'const a: number = xs[0];',
355
+ expected: 'const a: number = xs[0]!;',
356
+ options: { applyLevel: 'avoidWhereUndefinedIsAllowed' },
357
+ },
358
+ {
359
+ name: 'keeps a position with no contextual type',
360
+ source: 'console.log(xs[0].toFixed());',
361
+ expected: 'console.log(xs[0]!.toFixed());',
362
+ options: { applyLevel: 'avoidWhereUndefinedIsAllowed' },
363
+ },
364
+ {
365
+ name: 'the default level asserts even where undefined is allowed',
366
+ source: 'const a: number | undefined = xs[0];',
367
+ expected: 'const a: number | undefined = xs[0]!;',
368
+ },
369
+ ] as const)('$name', testFn);
370
+ });
371
+
372
+ describe('ignore comments', () => {
373
+ test.each([
374
+ {
375
+ name: 'transformer-ignore-next-line above the statement',
376
+ source: dedent`
377
+ // transformer-ignore-next-line
378
+ console.log(xs[0].toFixed());
379
+ `,
380
+ expected: dedent`
381
+ // transformer-ignore-next-line
382
+ console.log(xs[0].toFixed());
383
+ `,
384
+ },
385
+ {
386
+ name: 'transformer-ignore-next-line naming this transformer',
387
+ source: dedent`
388
+ // transformer-ignore-next-line enable-no-unchecked-indexed-access
389
+ console.log(xs[0].toFixed());
390
+ `,
391
+ expected: dedent`
392
+ // transformer-ignore-next-line enable-no-unchecked-indexed-access
393
+ console.log(xs[0].toFixed());
394
+ `,
395
+ },
396
+ {
397
+ name: 'transformer-ignore-next-line naming a different transformer',
398
+ source: dedent`
399
+ // transformer-ignore-next-line append-as-const
400
+ console.log(xs[0].toFixed());
401
+ `,
402
+ expected: dedent`
403
+ // transformer-ignore-next-line append-as-const
404
+ console.log(xs[0]!.toFixed());
405
+ `,
406
+ },
407
+ ])('$name', testFn);
408
+ });
409
+
410
+ test('a file-level transformer-ignore comment skips the file', () => {
411
+ const source = dedent`
412
+ /* transformer-ignore */
413
+ declare const xs: readonly number[];
414
+
415
+ console.log(xs[0].toFixed());
416
+ `;
417
+
418
+ expect(
419
+ transformSourceCode(source, false, [
420
+ enableNoUncheckedIndexedAccessTransformer(),
421
+ ]),
422
+ ).toBe(source);
423
+ });
424
+
425
+ test('the surrounding formatting is left byte-for-byte alone', () => {
426
+ const source = [
427
+ 'declare const xs: readonly number[];',
428
+ '',
429
+ 'const value = xs[ 0 ] . toFixed( ) ; // trailing comment',
430
+ '',
431
+ '/* a block comment */',
432
+ 'console.log(value);',
433
+ '',
434
+ ].join('\n');
435
+
436
+ expect(
437
+ transformSourceCode(source, false, [
438
+ enableNoUncheckedIndexedAccessTransformer(),
439
+ ]),
440
+ ).toBe(source.replace('xs[ 0 ]', 'xs[ 0 ]!'));
441
+ });
442
+
443
+ test('JSX files are transformed as well', () => {
444
+ const source = dedent`
445
+ declare const xs: readonly (readonly number[])[];
446
+
447
+ export const C = (): JSX.Element => <div>{xs[0].length}</div>;
448
+ `;
449
+
450
+ expect(
451
+ transformSourceCode(source, true, [
452
+ enableNoUncheckedIndexedAccessTransformer(),
453
+ ]),
454
+ ).toBe(source.replace('xs[0]', 'xs[0]!'));
455
+ });
456
+
457
+ test('the errors the option introduces are gone from the result', () => {
458
+ const source = dedent`
459
+ const parseRoute = (path: string): string => {
460
+ const parts = path.split('/');
461
+
462
+ const head = parts[0];
463
+
464
+ return head.toUpperCase() + parts[parts.length - 1].toLowerCase();
465
+ };
466
+
467
+ const counts: Record<string, number> = {};
468
+
469
+ const bump = (key: string): void => {
470
+ counts[key] = (counts[key] ?? 0) + 1;
471
+ };
472
+
473
+ const table: readonly (readonly string[])[] = [['a']];
474
+
475
+ const cell = (r: number, c: number): string => table[r][c];
476
+
477
+ const pair: readonly [number, number] = [1, 2];
478
+
479
+ const sum = pair[0] + pair[1];
480
+
481
+ console.log(parseRoute, bump, cell, sum);
482
+ `;
483
+
484
+ expect(diagnosticsUnderTheOption(source).length).toBeGreaterThan(0);
485
+
486
+ assert.deepStrictEqual(
487
+ diagnosticsUnderTheOption(
488
+ transformSourceCode(source, false, [
489
+ enableNoUncheckedIndexedAccessTransformer(),
490
+ ]),
491
+ ),
492
+ [],
493
+ );
494
+ });
495
+
496
+ test('array destructuring is left alone, since `!` has nowhere to go there', () => {
497
+ const source = dedent`
498
+ declare const xs: readonly number[];
499
+
500
+ const [head] = xs;
501
+
502
+ console.log(head);
503
+ `;
504
+
505
+ expect(
506
+ transformSourceCode(source, false, [
507
+ enableNoUncheckedIndexedAccessTransformer(),
508
+ ]),
509
+ ).toBe(source);
510
+ });
511
+
512
+ test('the compiler options it overrides are restored afterwards', () => {
513
+ const mut_seen: {
514
+ noUncheckedIndexedAccess: boolean | undefined;
515
+ strictNullChecks: boolean | undefined;
516
+ }[] = [];
517
+
518
+ transformSourceCode(
519
+ 'declare const xs: readonly number[];\nconsole.log(xs[0]);\n',
520
+ false,
521
+ [
522
+ enableNoUncheckedIndexedAccessTransformer(),
523
+ {
524
+ name: 'record-compiler-options',
525
+ transform: (sourceAst) => {
526
+ const compilerOptions = sourceAst.getProject().getCompilerOptions();
527
+
528
+ mut_seen.push({
529
+ noUncheckedIndexedAccess:
530
+ compilerOptions.noUncheckedIndexedAccess,
531
+ strictNullChecks: compilerOptions.strictNullChecks,
532
+ });
533
+ },
534
+ },
535
+ ],
536
+ );
537
+
538
+ assert.deepStrictEqual(mut_seen, [
539
+ { noUncheckedIndexedAccess: undefined, strictNullChecks: undefined },
540
+ ]);
541
+ });
542
+ });
543
+
544
+ /** The compiler's own verdict on the code, with the option this transformer prepares for turned on. */
545
+ const diagnosticsUnderTheOption = (code: string): readonly string[] => {
546
+ const project = new tsm.Project({
547
+ useInMemoryFileSystem: true,
548
+ compilerOptions: {
549
+ target: tsm.ts.ScriptTarget.ESNext,
550
+ module: tsm.ts.ModuleKind.ESNext,
551
+ strict: true,
552
+ noUncheckedIndexedAccess: true,
553
+ },
554
+ });
555
+
556
+ return project
557
+ .createSourceFile('source.ts', code)
558
+ .getPreEmitDiagnostics()
559
+ .map((diagnostic) => diagnostic.getMessageText())
560
+ .map((messageText) =>
561
+ typeof messageText === 'string'
562
+ ? messageText
563
+ : messageText.getMessageText(),
564
+ );
565
+ };
@@ -1,6 +1,7 @@
1
1
  export * from './append-as-const.mjs';
2
2
  export * from './convert-interface-to-type.mjs';
3
3
  export * from './convert-to-readonly.mjs';
4
+ export * from './enable-no-unchecked-indexed-access.mjs';
4
5
  export * from './readonly-transformer-helpers/index.mjs';
5
6
  export * from './replace-any-with-unknown.mjs';
6
7
  export * from './replace-record-with-unknown-record.mjs';