forked from graphql/graphql-js
/
inline-invariant.js
45 lines (39 loc) · 920 Bytes
/
inline-invariant.js
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
// @noflow
'use strict';
/**
* Eliminates function call to `invariant` if the condition is met.
*
* Transforms:
*
* invariant(<cond>, ...)
*
* to:
*
* !<cond> ? invariant(0, ...) : undefined;
*/
module.exports = function inlineInvariant(context) {
const replaceTemplate = context.template(`
(%%cond%%) || invariant(0, %%args%%)
`);
return {
visitor: {
CallExpression(path) {
const node = path.node;
const parent = path.parent;
if (!isAppropriateInvariantCall(node, parent)) {
return;
}
const [cond, args] = node.arguments;
path.replaceWith(replaceTemplate({ cond, args }));
},
},
};
};
function isAppropriateInvariantCall(node, parent) {
return (
parent.type === 'ExpressionStatement' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'invariant' &&
node.arguments.length > 0
);
}