-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcred-class-field-authenticate-type-assertion.ts
81 lines (75 loc) · 2.35 KB
/
cred-class-field-authenticate-type-assertion.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
import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils";
import { utils } from "../ast/utils";
export default utils.createRule({
name: utils.getRuleName(module),
meta: {
type: "problem",
docs: {
description:
"In a credential class, the field `authenticate` must be typed `IAuthenticateGeneric`",
recommended: "strict",
},
fixable: "code",
schema: [],
messages: {
removeAssertionAndType:
"Remove assertion and type field `authenticate` with `IAuthenticateGeneric` [autofixable]",
removeAssertion: "Remove assertion [autofixable]",
},
},
defaultOptions: [],
create(context) {
return {
TSAsExpression(node) {
if (!utils.isCredentialFile(context.getFilename())) return;
if (
node.typeAnnotation.type === AST_NODE_TYPES.TSTypeReference &&
node.typeAnnotation.typeName.type === AST_NODE_TYPES.Identifier &&
node.typeAnnotation.typeName.name === "IAuthenticateGeneric" &&
node.parent !== undefined &&
node.parent.type === AST_NODE_TYPES.PropertyDefinition &&
node.parent.key.type === AST_NODE_TYPES.Identifier &&
node.parent.key.name === "authenticate"
) {
const removalNode = node.typeAnnotation.typeName;
const insertionNode = node.parent.key;
const rangeToRemove = utils.getRangeOfAssertion(removalNode);
if (isAlreadyTyped(insertionNode)) {
return context.report({
messageId: "removeAssertion",
node,
fix: (fixer) => fixer.removeRange(rangeToRemove),
});
}
context.report({
messageId: "removeAssertionAndType",
node,
fix: (fixer) => {
// double fix
return [
fixer.removeRange(rangeToRemove),
fixer.insertTextAfterRange(
insertionNode.range,
": IAuthenticateGeneric"
),
];
},
});
}
},
};
},
});
function isAlreadyTyped(node: TSESTree.Identifier) {
if (!node.typeAnnotation) return false;
return (
node.typeAnnotation.type === AST_NODE_TYPES.TSTypeAnnotation &&
node.typeAnnotation.typeAnnotation.type === AST_NODE_TYPES.TSArrayType &&
node.typeAnnotation.typeAnnotation.elementType.type ===
AST_NODE_TYPES.TSTypeReference &&
node.typeAnnotation.typeAnnotation.elementType.typeName.type ===
AST_NODE_TYPES.Identifier &&
node.typeAnnotation.typeAnnotation.elementType.typeName.name ===
"IAuthenticateGeneric"
);
}