-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransform.js
More file actions
65 lines (53 loc) · 1.71 KB
/
Copy pathtransform.js
File metadata and controls
65 lines (53 loc) · 1.71 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const { parse } = require("./@babel_parser");
const generate = require('./@babel_generator').default;
var fs = require('fs');
var log = null;
if (global.__DEBUGJUPNODE) {
log = fs.createWriteStream('./transform.log')
}
module.exports = (code) => {
const ast = parse(code, { errorRecovery: false, allowAwaitOutsideFunction: true, allowReturnOutsideFunction: true });
let body = ast.program.body;
if (global.__DEBUGJUPNODE) {
log.write(JSON.stringify(body, null, ' '))
}
//set all var variables in top level as global variables
body.forEach(expr => {
if (expr.type === 'VariableDeclaration') {
expr.kind = ''
}
})
// print last variable or expression
if (
body[body.length - 1].type === 'ExpressionStatement'
) {
let expr = body[body.length - 1].expression;
body[body.length - 1] = {
type: "ReturnStatement",
start: expr.start,
end: expr.end,
"argument": expr
}
}
let funcAndClassDeclarations = [];
let asyncExpressions = []
body.forEach(astBranch => {
ast.program.body = [astBranch]
let generated = generate(ast, {});
if (
astBranch.type === 'FunctionDeclaration' ||
astBranch.type === 'ClassDeclaration'
) {
funcAndClassDeclarations.push(generated.code)
} else {
asyncExpressions.push(generated.code)
}
})
let outProgram = ''
outProgram += funcAndClassDeclarations.join('\n')
outProgram += '(async()=>{\n' + asyncExpressions.join('\n') + '\n})();'
if (global.__DEBUGJUPNODE) {
log.write(outProgram)
}
return outProgram;
}