consistent-type-imports.js
22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const util = __importStar(require("../util"));
function isImportToken(token) {
return token.type === experimental_utils_1.AST_TOKEN_TYPES.Keyword && token.value === 'import';
}
function isTypeToken(token) {
return token.type === experimental_utils_1.AST_TOKEN_TYPES.Identifier && token.value === 'type';
}
exports.default = util.createRule({
name: 'consistent-type-imports',
meta: {
type: 'suggestion',
docs: {
description: 'Enforces consistent usage of type imports',
category: 'Stylistic Issues',
recommended: false,
},
messages: {
typeOverValue: 'All imports in the declaration are only used as types. Use `import type`',
someImportsAreOnlyTypes: 'Imports {{typeImports}} are only used as types',
aImportIsOnlyTypes: 'Import {{typeImports}} is only used as types',
valueOverType: 'Use an `import` instead of an `import type`.',
noImportTypeAnnotations: '`import()` type annotations are forbidden.',
},
schema: [
{
type: 'object',
properties: {
prefer: {
enum: ['type-imports', 'no-type-imports'],
},
disallowTypeAnnotations: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
fixable: 'code',
},
defaultOptions: [
{
prefer: 'type-imports',
disallowTypeAnnotations: true,
},
],
create(context, [option]) {
var _a;
const prefer = (_a = option.prefer) !== null && _a !== void 0 ? _a : 'type-imports';
const disallowTypeAnnotations = option.disallowTypeAnnotations !== false;
const sourceCode = context.getSourceCode();
const sourceImportsMap = {};
return Object.assign(Object.assign({}, (prefer === 'type-imports'
? {
// prefer type imports
ImportDeclaration(node) {
var _a;
const source = node.source.value;
const sourceImports = (_a = sourceImportsMap[source]) !== null && _a !== void 0 ? _a : (sourceImportsMap[source] = {
source,
reportValueImports: [],
typeOnlyNamedImport: null,
});
if (node.importKind === 'type') {
if (!sourceImports.typeOnlyNamedImport &&
node.specifiers.every(specifier => specifier.type === experimental_utils_1.AST_NODE_TYPES.ImportSpecifier)) {
sourceImports.typeOnlyNamedImport = node;
}
return;
}
// if importKind === 'value'
const typeSpecifiers = [];
const valueSpecifiers = [];
const unusedSpecifiers = [];
for (const specifier of node.specifiers) {
const [variable] = context.getDeclaredVariables(specifier);
if (variable.references.length === 0) {
unusedSpecifiers.push(specifier);
}
else {
const onlyHasTypeReferences = variable.references.every(ref => {
if (ref.isValueReference) {
// `type T = typeof foo` will create a value reference because "foo" must be a value type
// however this value reference is safe to use with type-only imports
let parent = ref.identifier.parent;
while (parent) {
if (parent.type === experimental_utils_1.AST_NODE_TYPES.TSTypeQuery) {
return true;
}
// TSTypeQuery must have a TSESTree.EntityName as its child, so we can filter here and break early
if (parent.type !== experimental_utils_1.AST_NODE_TYPES.TSQualifiedName) {
break;
}
parent = parent.parent;
}
return false;
}
return ref.isTypeReference;
});
if (onlyHasTypeReferences) {
typeSpecifiers.push(specifier);
}
else {
valueSpecifiers.push(specifier);
}
}
}
if (typeSpecifiers.length) {
sourceImports.reportValueImports.push({
node,
typeSpecifiers,
valueSpecifiers,
unusedSpecifiers,
});
}
},
'Program:exit'() {
for (const sourceImports of Object.values(sourceImportsMap)) {
if (sourceImports.reportValueImports.length === 0) {
continue;
}
for (const report of sourceImports.reportValueImports) {
if (report.valueSpecifiers.length === 0 &&
report.unusedSpecifiers.length === 0) {
// import is all type-only, convert the entire import to `import type`
context.report({
node: report.node,
messageId: 'typeOverValue',
*fix(fixer) {
yield* fixToTypeImport(fixer, report, sourceImports);
},
});
}
else {
// we have a mixed type/value import, so we need to split them out into multiple exports
const typeImportNames = report.typeSpecifiers.map(specifier => `"${specifier.local.name}"`);
context.report({
node: report.node,
messageId: typeImportNames.length === 1
? 'aImportIsOnlyTypes'
: 'someImportsAreOnlyTypes',
data: {
typeImports: typeImportNames.length === 1
? typeImportNames[0]
: [
typeImportNames.slice(0, -1).join(', '),
typeImportNames.slice(-1)[0],
].join(' and '),
},
*fix(fixer) {
yield* fixToTypeImport(fixer, report, sourceImports);
},
});
}
}
}
},
}
: {
// prefer no type imports
'ImportDeclaration[importKind = "type"]'(node) {
context.report({
node,
messageId: 'valueOverType',
fix(fixer) {
return fixToValueImport(fixer, node);
},
});
},
})), (disallowTypeAnnotations
? {
// disallow `import()` type
TSImportType(node) {
context.report({
node,
messageId: 'noImportTypeAnnotations',
});
},
}
: {}));
function* fixToTypeImport(fixer, report, sourceImports) {
var _a;
const { node } = report;
const defaultSpecifier = node.specifiers[0].type === experimental_utils_1.AST_NODE_TYPES.ImportDefaultSpecifier
? node.specifiers[0]
: null;
const namespaceSpecifier = (_a = node.specifiers.find((specifier) => specifier.type === experimental_utils_1.AST_NODE_TYPES.ImportNamespaceSpecifier)) !== null && _a !== void 0 ? _a : null;
const namedSpecifiers = node.specifiers.filter((specifier) => specifier.type === experimental_utils_1.AST_NODE_TYPES.ImportSpecifier);
if (namespaceSpecifier && !defaultSpecifier) {
// e.g.
// import * as types from 'foo'
yield* fixToTypeImportByInsertType(fixer, node, false);
return;
}
else if (defaultSpecifier) {
if (report.typeSpecifiers.includes(defaultSpecifier) &&
namedSpecifiers.length === 0 &&
!namespaceSpecifier) {
// e.g.
// import Type from 'foo'
yield* fixToTypeImportByInsertType(fixer, node, true);
return;
}
}
else {
if (namedSpecifiers.every(specifier => report.typeSpecifiers.includes(specifier)) &&
!namespaceSpecifier) {
// e.g.
// import {Type1, Type2} from 'foo'
yield* fixToTypeImportByInsertType(fixer, node, false);
return;
}
}
const typeNamedSpecifiers = namedSpecifiers.filter(specifier => report.typeSpecifiers.includes(specifier));
const fixesNamedSpecifiers = getFixesNamedSpecifiers(typeNamedSpecifiers, namedSpecifiers);
const afterFixes = [];
if (typeNamedSpecifiers.length) {
if (sourceImports.typeOnlyNamedImport) {
const closingBraceToken = util.nullThrows(sourceCode.getFirstTokenBetween(sourceCode.getFirstToken(sourceImports.typeOnlyNamedImport), sourceImports.typeOnlyNamedImport.source, util.isClosingBraceToken), util.NullThrowsReasons.MissingToken('}', sourceImports.typeOnlyNamedImport.type));
let insertText = fixesNamedSpecifiers.typeNamedSpecifiersText;
const before = sourceCode.getTokenBefore(closingBraceToken);
if (!util.isCommaToken(before) && !util.isOpeningBraceToken(before)) {
insertText = ',' + insertText;
}
// import type { Already, Type1, Type2 } from 'foo'
// ^^^^^^^^^^^^^ insert
const insertTypeNamedSpecifiers = fixer.insertTextBefore(closingBraceToken, insertText);
if (sourceImports.typeOnlyNamedImport.range[1] <= node.range[0]) {
yield insertTypeNamedSpecifiers;
}
else {
afterFixes.push(insertTypeNamedSpecifiers);
}
}
else {
yield fixer.insertTextBefore(node, `import type {${fixesNamedSpecifiers.typeNamedSpecifiersText}} from ${sourceCode.getText(node.source)};\n`);
}
}
const fixesRemoveTypeNamespaceSpecifier = [];
if (namespaceSpecifier &&
report.typeSpecifiers.includes(namespaceSpecifier)) {
// e.g.
// import Foo, * as Type from 'foo'
// import DefType, * as Type from 'foo'
// import DefType, * as Type from 'foo'
const commaToken = util.nullThrows(sourceCode.getTokenBefore(namespaceSpecifier, util.isCommaToken), util.NullThrowsReasons.MissingToken(',', node.type));
// import Def, * as Ns from 'foo'
// ^^^^^^^^^ remove
fixesRemoveTypeNamespaceSpecifier.push(fixer.removeRange([commaToken.range[0], namespaceSpecifier.range[1]]));
// import type * as Ns from 'foo'
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ insert
yield fixer.insertTextBefore(node, `import type ${sourceCode.getText(namespaceSpecifier)} from ${sourceCode.getText(node.source)};\n`);
}
if (defaultSpecifier &&
report.typeSpecifiers.includes(defaultSpecifier)) {
if (report.typeSpecifiers.length === node.specifiers.length) {
const importToken = util.nullThrows(sourceCode.getFirstToken(node, isImportToken), util.NullThrowsReasons.MissingToken('import', node.type));
// import type Type from 'foo'
// ^^^^ insert
yield fixer.insertTextAfter(importToken, ' type');
}
else {
const commaToken = util.nullThrows(sourceCode.getTokenAfter(defaultSpecifier, util.isCommaToken), util.NullThrowsReasons.MissingToken(',', defaultSpecifier.type));
// import Type , {...} from 'foo'
// ^^^^^ pick
const defaultText = sourceCode.text
.slice(defaultSpecifier.range[0], commaToken.range[0])
.trim();
yield fixer.insertTextBefore(node, `import type ${defaultText} from ${sourceCode.getText(node.source)};\n`);
const afterToken = util.nullThrows(sourceCode.getTokenAfter(commaToken, { includeComments: true }), util.NullThrowsReasons.MissingToken('any token', node.type));
// import Type , {...} from 'foo'
// ^^^^^^^ remove
yield fixer.removeRange([
defaultSpecifier.range[0],
afterToken.range[0],
]);
}
}
yield* fixesNamedSpecifiers.removeTypeNamedSpecifiers;
yield* fixesRemoveTypeNamespaceSpecifier;
yield* afterFixes;
/**
* Returns information for fixing named specifiers.
*/
function getFixesNamedSpecifiers(typeNamedSpecifiers, allNamedSpecifiers) {
if (allNamedSpecifiers.length === 0) {
return {
typeNamedSpecifiersText: '',
removeTypeNamedSpecifiers: [],
};
}
const typeNamedSpecifiersTexts = [];
const removeTypeNamedSpecifiers = [];
if (typeNamedSpecifiers.length === allNamedSpecifiers.length) {
// e.g.
// import Foo, {Type1, Type2} from 'foo'
// import DefType, {Type1, Type2} from 'foo'
const openingBraceToken = util.nullThrows(sourceCode.getTokenBefore(typeNamedSpecifiers[0], util.isOpeningBraceToken), util.NullThrowsReasons.MissingToken('{', node.type));
const commaToken = util.nullThrows(sourceCode.getTokenBefore(openingBraceToken, util.isCommaToken), util.NullThrowsReasons.MissingToken(',', node.type));
const closingBraceToken = util.nullThrows(sourceCode.getFirstTokenBetween(openingBraceToken, node.source, util.isClosingBraceToken), util.NullThrowsReasons.MissingToken('}', node.type));
// import DefType, {...} from 'foo'
// ^^^^^^^ remove
removeTypeNamedSpecifiers.push(fixer.removeRange([
commaToken.range[0],
closingBraceToken.range[1],
]));
typeNamedSpecifiersTexts.push(sourceCode.text.slice(openingBraceToken.range[1], closingBraceToken.range[0]));
}
else {
const typeNamedSpecifierGroups = [];
let group = [];
for (const namedSpecifier of allNamedSpecifiers) {
if (typeNamedSpecifiers.includes(namedSpecifier)) {
group.push(namedSpecifier);
}
else if (group.length) {
typeNamedSpecifierGroups.push(group);
group = [];
}
}
if (group.length) {
typeNamedSpecifierGroups.push(group);
}
for (const namedSpecifiers of typeNamedSpecifierGroups) {
const { removeRange, textRange } = getNamedSpecifierRanges(namedSpecifiers, allNamedSpecifiers);
removeTypeNamedSpecifiers.push(fixer.removeRange(removeRange));
typeNamedSpecifiersTexts.push(sourceCode.text.slice(...textRange));
}
}
return {
typeNamedSpecifiersText: typeNamedSpecifiersTexts.join(','),
removeTypeNamedSpecifiers,
};
}
/**
* Returns ranges for fixing named specifier.
*/
function getNamedSpecifierRanges(namedSpecifierGroup, allNamedSpecifiers) {
const first = namedSpecifierGroup[0];
const last = namedSpecifierGroup[namedSpecifierGroup.length - 1];
const removeRange = [first.range[0], last.range[1]];
const textRange = [...removeRange];
const before = sourceCode.getTokenBefore(first);
textRange[0] = before.range[1];
if (util.isCommaToken(before)) {
removeRange[0] = before.range[0];
}
else {
removeRange[0] = before.range[1];
}
const isFirst = allNamedSpecifiers[0] === first;
const isLast = allNamedSpecifiers[allNamedSpecifiers.length - 1] === last;
const after = sourceCode.getTokenAfter(last);
textRange[1] = after.range[0];
if (isFirst || isLast) {
if (util.isCommaToken(after)) {
removeRange[1] = after.range[1];
}
}
return {
textRange,
removeRange,
};
}
}
function* fixToTypeImportByInsertType(fixer, node, isDefaultImport) {
// import type Foo from 'foo'
// ^^^^^ insert
const importToken = util.nullThrows(sourceCode.getFirstToken(node, isImportToken), util.NullThrowsReasons.MissingToken('import', node.type));
yield fixer.insertTextAfter(importToken, ' type');
if (isDefaultImport) {
// Has default import
const openingBraceToken = sourceCode.getFirstTokenBetween(importToken, node.source, util.isOpeningBraceToken);
if (openingBraceToken) {
// Only braces. e.g. import Foo, {} from 'foo'
const commaToken = util.nullThrows(sourceCode.getTokenBefore(openingBraceToken, util.isCommaToken), util.NullThrowsReasons.MissingToken(',', node.type));
const closingBraceToken = util.nullThrows(sourceCode.getFirstTokenBetween(openingBraceToken, node.source, util.isClosingBraceToken), util.NullThrowsReasons.MissingToken('}', node.type));
// import type Foo, {} from 'foo'
// ^^ remove
yield fixer.removeRange([
commaToken.range[0],
closingBraceToken.range[1],
]);
const specifiersText = sourceCode.text.slice(commaToken.range[1], closingBraceToken.range[1]);
if (node.specifiers.length > 1) {
// import type Foo from 'foo'
// import type {...} from 'foo' // <- insert
yield fixer.insertTextAfter(node, `\nimport type${specifiersText} from ${sourceCode.getText(node.source)};`);
}
}
}
}
function fixToValueImport(fixer, node) {
var _a, _b;
// import type Foo from 'foo'
// ^^^^ remove
const importToken = util.nullThrows(sourceCode.getFirstToken(node, isImportToken), util.NullThrowsReasons.MissingToken('import', node.type));
const typeToken = util.nullThrows(sourceCode.getFirstTokenBetween(importToken, (_b = (_a = node.specifiers[0]) === null || _a === void 0 ? void 0 : _a.local) !== null && _b !== void 0 ? _b : node.source, isTypeToken), util.NullThrowsReasons.MissingToken('type', node.type));
const afterToken = util.nullThrows(sourceCode.getTokenAfter(typeToken, { includeComments: true }), util.NullThrowsReasons.MissingToken('any token', node.type));
return fixer.removeRange([typeToken.range[0], afterToken.range[0]]);
}
},
});
//# sourceMappingURL=consistent-type-imports.js.map