|
1
|
import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils" |
|
2
|
import { createRule } from "../../create-rule" |
|
3
|
import { |
|
4
|
FunctionNode, |
|
5
|
isFunctionNode, |
|
6
|
resolveFunctionFromIdentifier, |
|
7
|
} from "../../util/ast" |
|
8
|
|
|
9
|
type MessageIds = "mustBeAsync" |
|
10
|
|
|
11
|
export const rule = createRule<[], MessageIds>({ |
|
12
|
name: "subscriber-default-export-must-be-async", |
|
13
|
meta: { |
|
14
|
type: "problem", |
|
15
|
docs: { |
|
16
|
description: |
|
17
|
"The default-exported subscriber handler function must be async.", |
|
18
|
}, |
|
19
|
fixable: "code", |
|
20
|
messages: { |
|
21
|
mustBeAsync: |
|
22
|
"The default-exported subscriber handler must be an async function. Subscribers receive an event and are always awaited by the framework.", |
|
23
|
}, |
|
24
|
schema: [], |
|
25
|
}, |
|
26
|
defaultOptions: [], |
|
27
|
create(context) { |
|
28
|
const sourceCode = context.sourceCode ?? context.getSourceCode() |
|
29
|
|
|
30
|
function checkFunction(fn: FunctionNode) { |
|
31
|
if (fn.async) { |
|
32
|
return |
|
33
|
} |
|
34
|
context.report({ |
|
35
|
node: fn, |
|
36
|
messageId: "mustBeAsync", |
|
37
|
fix(fixer) { |
|
38
|
return fixer.insertTextBefore(fn, "async ") |
|
39
|
}, |
|
40
|
}) |
|
41
|
} |
|
42
|
|
|
43
|
return { |
|
44
|
ExportDefaultDeclaration(node: TSESTree.ExportDefaultDeclaration) { |
|
45
|
const decl = node.declaration |
|
46
|
|
|
47
|
// export default (async) function () {} | export default (async) () => {} |
|
48
|
if (isFunctionNode(decl)) { |
|
49
|
checkFunction(decl) |
|
50
|
return |
|
51
|
} |
|
52
|
|
|
53
|
// export default handler — resolve the binding to its function. |
|
54
|
if (decl.type === AST_NODE_TYPES.Identifier) { |
|
55
|
const fn = resolveFunctionFromIdentifier( |
|
56
|
sourceCode.getScope(node), |
|
57
|
decl |
|
58
|
) |
|
59
|
if (fn) { |
|
60
|
checkFunction(fn) |
|
61
|
} |
|
62
|
} |
|
63
|
}, |
|
64
|
ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration) { |
|
65
|
// `export { default } from "./impl"` re-exports another module's |
|
66
|
// binding — we can't resolve it locally, so skip (no false positive). |
|
67
|
if (node.source) { |
|
68
|
return |
|
69
|
} |
|
70
|
|
|
71
|
for (const spec of node.specifiers) { |
|
72
|
if ( |
|
73
|
spec.exported.type !== AST_NODE_TYPES.Identifier || |
|
74
|
spec.exported.name !== "default" |
|
75
|
) { |
|
76
|
continue |
|
77
|
} |
|
78
|
|
|
79
|
// `export { handler as default }` — resolve `handler`. |
|
80
|
const fn = resolveFunctionFromIdentifier( |
|
81
|
sourceCode.getScope(node), |
|
82
|
spec.local |
|
83
|
) |
|
84
|
if (fn) { |
|
85
|
checkFunction(fn) |
|
86
|
} |
|
87
|
return |
|
88
|
} |
|
89
|
}, |
|
90
|
} |
|
91
|
}, |
|
92
|
}) |
|
93
|
|
|
94
|
export default rule |