-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbuild.js
101 lines (87 loc) · 2.91 KB
/
build.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
Modifies the typescript output so it can be easily pasted into a Scripter instance
*/
const fs = require("fs-extra");
const path = require("path");
const prettier = require("prettier");
const j = require("jscodeshift");
const IGNORE_RE = /^(__tests__|test-helpers\.js)$/;
const PLUGIN_DIRECTORY = path.join(__dirname, "plugins");
function buildPlugin(filename) {
const { ext, name } = path.parse(filename);
if (ext !== ".js") {
throw Error("Unexpected file type");
}
const dir = path.join(PLUGIN_DIRECTORY, name);
fs.mkdirSync(dir);
var source = fs.readFileSync(path.join(__dirname, "js/", filename)).toString();
// Remove "use strict"
source = j(source)
.find(j.ExpressionStatement)
.filter(p => p.node.expression.value === "use strict")
.forEach(p => {
j(p).remove();
})
.toSource();
// Make README.md from first comment
var readme = null;
j(source)
.find(j.Comment)
.filter(p => p.value.type === "CommentBlock")
.at(0)
.forEach(p => {
readme = p.value.value.trim() + "\n";
fs.writeFileSync(path.join(dir, "README.md"), readme);
j(p).remove();
});
// Make things global
j(source)
.find(j.MemberExpression)
.filter(p => p.node.object.name === "exports" && p.node.property.name === "plugin")
.forEach(p => {
p.parentPath.node.right.properties.forEach(property => {
var globalExpression;
if (property.value.type === "FunctionExpression") {
property.value.id = property.key.name;
globalExpression = property.value;
} else {
globalExpression = j.assignmentExpression("=", j.identifier(property.key.name), property.value);
}
source = `${source}\n\n${j(globalExpression).toSource()}`;
});
});
// Remove references to `exports`
source = j(source)
.find(j.Identifier)
.filter(p => p.node.name === "exports")
.forEach(p => {
j(p.parentPath.parentPath).remove();
})
.toSource();
// Remove @ts-ignore comments
source = j(source)
.find(j.Comment)
.filter(p => p.value.value.trim() === "@ts-ignore")
.forEach(p => {
j(p).remove();
})
.toSource();
if (readme) {
source = `/*\n${readme}\n*/\n\n${source}`;
}
fs.writeFileSync(
path.join(dir, "plugin.js"),
prettier.format(source, prettier.resolveConfig.sync(__filename, "utf8"))
);
}
function run() {
fs.removeSync(PLUGIN_DIRECTORY);
fs.mkdirSync(PLUGIN_DIRECTORY);
const filenames = fs.readdirSync(path.join(__dirname, "js/"));
filenames.forEach(filename => {
if (!filename.match(IGNORE_RE)) {
buildPlugin(filename);
}
});
}
run();