-
Notifications
You must be signed in to change notification settings - Fork 5
/
rewrite.js
40 lines (37 loc) · 1.07 KB
/
rewrite.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
const recast = require('recast');
const parser = require('babylon');
function withinAsyncContext(c) {
return `(async () => { ${c} })()`;
}
function leakLocals(nodes) {
return nodes.map(node => {
if (node.type !== 'VariableDeclaration') {
return node;
}
return {
type: 'ExpressionStatement',
expression: {
type: 'SequenceExpression',
expressions: node.declarations.map(declaration => ({
type: 'AssignmentExpression',
operator: '=',
left: declaration.id,
right: declaration.init
}))
}
};
});
}
module.exports = function(code) {
let ast = recast.parse(withinAsyncContext(code), { parser });
let userBlock = ast.program.body[0].expression.callee.body;
let userCode = userBlock.body;
if (userCode.length > 0 && userCode[userCode.length - 1].type === 'ExpressionStatement') {
userCode[userCode.length - 1] = {
type: 'ReturnStatement',
argument: userCode[userCode.length - 1]
};
}
userBlock.body = leakLocals(userCode);
return recast.print(ast).code;
};