-
Notifications
You must be signed in to change notification settings - Fork 801
/
Copy pathvarify.mjs
62 lines (59 loc) · 2.5 KB
/
varify.mjs
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
import {parse} from "acorn"
export default function(code) {
let ast
try { ast = parse(code, {sourceType: "module", ecmaVersion: 2022}) }
catch(_) { return code }
let patches = []
ast.body.forEach(node => {
if (node.type == "VariableDeclaration" && node.kind != "var") {
patches.push({from: node.start, to: node.start + node.kind.length, text: "var"})
} else if (node.type == "ClassDeclaration") {
patches.push({from: node.start, to: node.start, text: "var " + node.id.name + " = "})
} else if (node.type == "ImportDeclaration") {
let req = "require(" + node.source.raw + ")", text
if (node.specifiers.length == 0) {
text = req
} else if (node.specifiers.length > 1 || node.specifiers[0].type == "ImportDefaultSpecifier") {
let name = "m_" + node.source.value.replace(/\W+/g, "_") + "__"
text = "var " + name + " = " + req
node.specifiers.forEach(spec => {
if (spec.type == "ImportDefaultSpecifier")
text += ", " + spec.local.name + " = " + name + ".default || " + name
else if (name != null)
text += ", " + spec.local.name + " = " + name + "." + spec.imported.name
})
} else {
text = "var "
node.specifiers.forEach(spec => {
if (spec.type == "ImportNamespaceSpecifier")
text += spec.local.name + " = " + req
else
text += spec.local.name + " = " + req + "." + spec.imported.name
})
}
patches.push({from: node.start, to: node.end, text: text + ";"})
} else if (node.type == "ExportNamedDeclaration") {
if (node.source || !node.declaration)
patches.push({from: node.start, to: node.end, text: ""})
else
patches.push({from: node.start, to: node.declaration.start, text: ""})
} else if (node.type == "ExportDefaultDeclaration") {
if (/Declaration/.test(node.declaration.type)) {
patches.push({from: node.start, to: node.declaration.start, text: ""})
} else {
patches.push({from: node.start, to: node.declaration.start, text: ";("},
{from: node.declaration.end, text: ")"})
}
} else if (node.type == "ExportAllDeclaration") {
patches.push({from: node.start, to: node.end, text: ""})
}
})
patches.sort((a, b) => a.from - b.from || (a.to || a.from) - (b.to || b.from))
let out = "", pos = 0
patches.forEach(({from, to, text}) => {
out += code.slice(pos, from) + text
pos = to
})
out += code.slice(pos)
return out
}