• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    const fixId = "removeUnnecessaryAwait";
4    const errorCodes = [
5        Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code,
6    ];
7
8    registerCodeFix({
9        errorCodes,
10        getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) {
11            const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span));
12            if (changes.length > 0) {
13                return [createCodeFixAction(fixId, changes, Diagnostics.Remove_unnecessary_await, fixId, Diagnostics.Remove_all_unnecessary_uses_of_await)];
14            }
15        },
16        fixIds: [fixId],
17        getAllCodeActions: context => {
18            return codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag));
19        },
20    });
21
22    function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, span: TextSpan) {
23        const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node): node is AwaitKeywordToken => node.kind === SyntaxKind.AwaitKeyword);
24        const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression);
25        if (!awaitExpression) {
26            return;
27        }
28
29        let expressionToReplace: Node = awaitExpression;
30        const hasSurroundingParens = isParenthesizedExpression(awaitExpression.parent);
31        if (hasSurroundingParens) {
32            const leftMostExpression = getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ false);
33            if (isIdentifier(leftMostExpression)) {
34                const precedingToken = findPrecedingToken(awaitExpression.parent.pos, sourceFile);
35                if (precedingToken && precedingToken.kind !== SyntaxKind.NewKeyword) {
36                    expressionToReplace = awaitExpression.parent;
37                }
38            }
39        }
40
41        changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression);
42    }
43}
44