/
sort-type-union-intersection-members.ts
272 lines (246 loc) · 7.61 KB
/
sort-type-union-intersection-members.ts
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
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as util from '../util';
import { getEnumNames } from '../util';
enum Group {
conditional = 'conditional',
function = 'function',
import = 'import',
intersection = 'intersection',
keyword = 'keyword',
nullish = 'nullish',
literal = 'literal',
named = 'named',
object = 'object',
operator = 'operator',
tuple = 'tuple',
union = 'union',
}
function getGroup(node: TSESTree.TypeNode): Group {
switch (node.type) {
case AST_NODE_TYPES.TSConditionalType:
return Group.conditional;
case AST_NODE_TYPES.TSConstructorType:
case AST_NODE_TYPES.TSFunctionType:
return Group.function;
case AST_NODE_TYPES.TSImportType:
return Group.import;
case AST_NODE_TYPES.TSIntersectionType:
return Group.intersection;
case AST_NODE_TYPES.TSAnyKeyword:
case AST_NODE_TYPES.TSBigIntKeyword:
case AST_NODE_TYPES.TSBooleanKeyword:
case AST_NODE_TYPES.TSNeverKeyword:
case AST_NODE_TYPES.TSNumberKeyword:
case AST_NODE_TYPES.TSObjectKeyword:
case AST_NODE_TYPES.TSStringKeyword:
case AST_NODE_TYPES.TSSymbolKeyword:
case AST_NODE_TYPES.TSThisType:
case AST_NODE_TYPES.TSUnknownKeyword:
case AST_NODE_TYPES.TSIntrinsicKeyword:
return Group.keyword;
case AST_NODE_TYPES.TSNullKeyword:
case AST_NODE_TYPES.TSUndefinedKeyword:
case AST_NODE_TYPES.TSVoidKeyword:
return Group.nullish;
case AST_NODE_TYPES.TSLiteralType:
case AST_NODE_TYPES.TSTemplateLiteralType:
return Group.literal;
case AST_NODE_TYPES.TSArrayType:
case AST_NODE_TYPES.TSIndexedAccessType:
case AST_NODE_TYPES.TSInferType:
case AST_NODE_TYPES.TSTypeReference:
case AST_NODE_TYPES.TSQualifiedName:
return Group.named;
case AST_NODE_TYPES.TSMappedType:
case AST_NODE_TYPES.TSTypeLiteral:
return Group.object;
case AST_NODE_TYPES.TSTypeOperator:
case AST_NODE_TYPES.TSTypeQuery:
return Group.operator;
case AST_NODE_TYPES.TSTupleType:
return Group.tuple;
case AST_NODE_TYPES.TSUnionType:
return Group.union;
// These types should never occur as part of a union/intersection
case AST_NODE_TYPES.TSAbstractKeyword:
case AST_NODE_TYPES.TSAsyncKeyword:
case AST_NODE_TYPES.TSDeclareKeyword:
case AST_NODE_TYPES.TSExportKeyword:
case AST_NODE_TYPES.TSNamedTupleMember:
case AST_NODE_TYPES.TSOptionalType:
case AST_NODE_TYPES.TSPrivateKeyword:
case AST_NODE_TYPES.TSProtectedKeyword:
case AST_NODE_TYPES.TSPublicKeyword:
case AST_NODE_TYPES.TSReadonlyKeyword:
case AST_NODE_TYPES.TSRestType:
case AST_NODE_TYPES.TSStaticKeyword:
case AST_NODE_TYPES.TSTypePredicate:
/* istanbul ignore next */
throw new Error(`Unexpected Type ${node.type}`);
}
}
function requiresParentheses(node: TSESTree.TypeNode): boolean {
return (
node.type === AST_NODE_TYPES.TSFunctionType ||
node.type === AST_NODE_TYPES.TSConstructorType
);
}
export type Options = [
{
checkIntersections?: boolean;
checkUnions?: boolean;
groupOrder?: string[];
},
];
export type MessageIds = 'notSorted' | 'notSortedNamed' | 'suggestFix';
export default util.createRule<Options, MessageIds>({
name: 'sort-type-union-intersection-members',
meta: {
deprecated: true,
type: 'suggestion',
docs: {
description:
'Enforce members of a type union/intersection to be sorted alphabetically',
recommended: false,
},
fixable: 'code',
hasSuggestions: true,
messages: {
notSorted: '{{type}} type members must be sorted.',
notSortedNamed: '{{type}} type {{name}} members must be sorted.',
suggestFix: 'Sort members of type (removes all comments).',
},
replacedBy: ['@typescript-eslint/sort-type-constituents'],
schema: [
{
type: 'object',
properties: {
checkIntersections: {
description: 'Whether to check intersection types.',
type: 'boolean',
},
checkUnions: {
description: 'Whether to check union types.',
type: 'boolean',
},
groupOrder: {
description: 'Ordering of the groups.',
type: 'array',
items: {
type: 'string',
enum: getEnumNames(Group),
},
},
},
},
],
},
defaultOptions: [
{
checkIntersections: true,
checkUnions: true,
groupOrder: [
Group.named,
Group.keyword,
Group.operator,
Group.literal,
Group.function,
Group.import,
Group.conditional,
Group.object,
Group.tuple,
Group.intersection,
Group.union,
Group.nullish,
],
},
],
create(context, [{ checkIntersections, checkUnions, groupOrder }]) {
const sourceCode = context.getSourceCode();
const collator = new Intl.Collator('en', {
sensitivity: 'base',
numeric: true,
});
function checkSorting(
node: TSESTree.TSIntersectionType | TSESTree.TSUnionType,
): void {
const sourceOrder = node.types.map(type => {
const group = groupOrder?.indexOf(getGroup(type)) ?? -1;
return {
group: group === -1 ? Number.MAX_SAFE_INTEGER : group,
node: type,
text: sourceCode.getText(type),
};
});
const expectedOrder = [...sourceOrder].sort((a, b) => {
if (a.group !== b.group) {
return a.group - b.group;
}
return (
collator.compare(a.text, b.text) ||
(a.text < b.text ? -1 : a.text > b.text ? 1 : 0)
);
});
const hasComments = node.types.some(type => {
const count =
sourceCode.getCommentsBefore(type).length +
sourceCode.getCommentsAfter(type).length;
return count > 0;
});
for (let i = 0; i < expectedOrder.length; i += 1) {
if (expectedOrder[i].node !== sourceOrder[i].node) {
let messageId: MessageIds = 'notSorted';
const data = {
name: '',
type:
node.type === AST_NODE_TYPES.TSIntersectionType
? 'Intersection'
: 'Union',
};
if (node.parent?.type === AST_NODE_TYPES.TSTypeAliasDeclaration) {
messageId = 'notSortedNamed';
data.name = node.parent.id.name;
}
const fix: TSESLint.ReportFixFunction = fixer => {
const sorted = expectedOrder
.map(t => (requiresParentheses(t.node) ? `(${t.text})` : t.text))
.join(
node.type === AST_NODE_TYPES.TSIntersectionType ? ' & ' : ' | ',
);
return fixer.replaceText(node, sorted);
};
return context.report({
node,
messageId,
data,
// don't autofix if any of the types have leading/trailing comments
// the logic for preserving them correctly is a pain - we may implement this later
...(hasComments
? {
suggest: [
{
messageId: 'suggestFix',
fix,
},
],
}
: { fix }),
});
}
}
}
return {
...(checkIntersections && {
TSIntersectionType(node): void {
checkSorting(node);
},
}),
...(checkUnions && {
TSUnionType(node): void {
checkSorting(node);
},
}),
};
},
});