-
Notifications
You must be signed in to change notification settings - Fork 320
/
async.ts
45 lines (40 loc) · 1.19 KB
/
async.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 * as babylon from "babylon";
import * as recast from "recast";
export function wrapInAsyncFunction(code: string): string {
const codeInAsyncFunction = `(async () => {
${code}
})()`;
const ast = recast.parse(codeInAsyncFunction, { parser: babylon });
const body = ast.program.body[0].expression.callee.body.body;
if (body.length !== 0) {
const last = body.pop();
if (last.type === "ExpressionStatement") {
body.push({
type: "ReturnStatement",
argument: last,
});
} else {
body.push(last);
}
}
// Remove var, let, const from variable declarations to make them available in context
ast.program.body[0].expression.callee.body.body = body.map((node: any) => {
if (node.type === "VariableDeclaration") {
return {
type: "ExpressionStatement",
expression: {
type: "SequenceExpression",
expressions: node.declarations.map((declaration: any) => ({
type: "AssignmentExpression",
operator: "=",
left: declaration.id,
right: declaration.init,
})),
},
};
} else {
return node;
}
});
return recast.print(ast).code;
}