forked from graphql/graphql-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinline-invariant.ts
45 lines (39 loc) · 1.17 KB
/
inline-invariant.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
import ts from 'typescript';
/**
* Eliminates function call to `invariant` if the condition is met.
*
* Transforms:
*
* invariant(<cond>, ...)
*
* to:
*
* (<cond>) || invariant(false ...)
*/
export function inlineInvariant(context: ts.TransformationContext) {
const { factory } = context;
return visitSourceFile;
function visitSourceFile(sourceFile: ts.SourceFile) {
return ts.visitNode(sourceFile, visitNode);
}
function visitNode(node: ts.Node): ts.Node {
if (ts.isCallExpression(node)) {
const { expression, arguments: args } = node;
if (ts.isIdentifier(expression) && args.length > 0) {
const funcName = expression.escapedText;
if (funcName === 'invariant' || funcName === 'devAssert') {
const [condition, ...otherArgs] = args;
return factory.createBinaryExpression(
factory.createParenthesizedExpression(condition),
ts.SyntaxKind.BarBarToken,
factory.createCallExpression(expression, undefined, [
factory.createFalse(),
...otherArgs,
]),
);
}
}
}
return ts.visitEachChild(node, visitNode, context);
}
}