forked from windycom/windy-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.js
executable file
·265 lines (215 loc) · 6.48 KB
/
compiler.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env node --no-warnings
/**
* This is plugin building script. Feel free to modify it
* All is MIT licenced
*/
const prog = require('commander'),
{ join } = require('path'),
c = require('consola'),
fs = require('fs-extra'),
{ yellow, gray } = require('colorette'),
riot = require('riot-compiler'),
assert = require('assert'),
express = require('express'),
app = express(),
less = require('less'),
chokidar = require('chokidar'),
decache = require('decache'),
https = require('https'),
babel = require('@babel/core');
const utils = require('./dev/utils.js');
const port = 9999;
const {
version,
name,
author,
repository,
description,
} = require('./package.json');
prog.option(
'-b, --build',
'Build the plugin in required directory (default src)'
)
.option(
'-w, --watch',
'Build plugin and watch file changes in required directory'
)
.option('-s, --serve', `Serve dist directory on port ${port}`)
.option('-p, --prompt', 'Show command line promt with all the examples')
.option('-t, --transpile', 'Transpile your code with Babel')
.parse(process.argv);
if (!process.argv.slice(2).length) {
prog.outputHelp();
process.exit();
}
let config,
srcDir = 'src';
// Main
(async () => {
console.log(`\nBuilding ${yellow(name)}, version ${yellow(version)}`);
// Beginners example selection
if (prog.prompt) {
srcDir = await utils.prompt();
}
c.info(`Compiler will compile ${yellow(`./${srcDir}/plugin.html`)}`);
reloadConfig();
try {
// Basic assertions
assert(
typeof config === 'object',
'Missing basic config object. Make sure you have valid ' +
'config.js in src dir'
);
assert(
/^windy-plugin-/.test(name),
'Your repository (and also your published npm package) ' +
'must be named "windy-plugin-AnyOfYourName".' +
' Change the name in your package.json'
);
// Tasks
if (prog.watch || prog.build) {
await build();
}
if (prog.serve) {
await startServer();
}
if (prog.watch) {
c.start(`Staring watch on ${gray(srcDir)} and ${gray('package.json')}...`);
chokidar.watch([srcDir, 'package.json']).on('change', onChange);
}
} catch (e) {
c.error(`Error\u0007`, e);
}
})();
function startServer() {
return new Promise(resolve => {
const httpsOptions = {
// https://www.ibm.com/support/knowledgecenter/en/SSWHYP_4.0.0/com.ibm.apimgmt.cmc.doc/task_apionprem_gernerate_self_signed_openSSL.html
key: fs.readFileSync(join(__dirname, 'dev', 'key.pem'), 'utf8'),
cert: fs.readFileSync(
join(__dirname, 'dev', 'certificate.pem'),
'utf8'
),
};
app.use(express.static('dist'));
https.createServer(httpsOptions, app).listen(port, () => {
c.success(`Your plugin is published at ${gray(
`https://localhost:${port}/plugin.js`
)}.
Use ${yellow('https://www.windy.com/dev')} to test it\n`);
resolve();
});
});
}
/* This is main build function
Feel free to to use your own builder, transpiler, minifier or whatever
The result must be a single .js file with single W.loadPlugin() function
Make sure to replace import XY from '@windy/XY' with W.require(XY)
*/
async function build() {
// Riot parser options
const riotOpts = {
entities: true,
compact: false,
expr: true,
type: null,
template: null,
fileConfig: null,
concat: false,
modular: false,
debug: true,
};
// Compile less - feel free to code your SCSS here
let css = await compileLess();
// Load source code of a plugin
const tagSrc = await fs.readFile(join(srcDir, 'plugin.html'), 'utf8');
// Compile it via riot compiler
// See: https://github.com/riot/compiler
const [compiled] = riot.compile(tagSrc, riotOpts);
let { html, js, imports } = compiled;
const options = Object.assign(
{},
{
name,
version,
author,
repository,
description,
},
config
);
const internalModules = {};
//
// Rewrite imports into W.require
//
if (imports) {
let match,
importsRegEx = /import\s+(\S+)\s+from\s+['"](@windy\/)?([^'"']+)['"]/g;
while ((match = importsRegEx.exec(imports)) !== null) {
let [, lex, isCore, module] = match;
// detect syntax "import graph from './soundingGraph.mjs'"
// and loads external module
if (!isCore) {
module = await utils.externalMjs(
srcDir,
internalModules,
module,
name
);
}
js = `\tconst ${lex} = W.require('${module}');\n${js}`;
}
}
// Stringify output
let output = utils.stringifyPlugin(options, html, css, js);
// Add external modules
for (let ext in internalModules) {
output += `\n\n${internalModules[ext]}`;
}
// Save plugin to dest directory
const destination = join(__dirname, 'dist', 'plugin.js');
// Babel traspile
if (prog.transpile) {
c.info('Transpiling with babel');
let res = await babel.transformAsync(output, {
presets: ['@babel/preset-env'],
}); // => Promise<{ code, map, ast }>
output = res.code;
}
await fs.outputFile(destination, output);
c.success(
`Your plugin ${gray(name)} has been compiled to ${gray(destination)}`
);
}
//
// L E S S compiler
//
async function compileLess() {
const lessOptions = {
cleancss: true,
compress: true,
};
const lessFile = join(srcDir, 'plugin.less');
if (!fs.existsSync(lessFile)) {
return null;
}
const lessSrc = await fs.readFile(lessFile, 'utf8');
let { css } = await less.render(lessSrc, lessOptions);
return css;
}
//
// Reload config
//
function reloadConfig() {
const dir = join(__dirname, srcDir, 'config.js');
decache(dir);
config = require(dir);
}
//
// Watch change of file
//
const onChange = async fullPath => {
c.info(`watch: File changed ${gray(fullPath)}`);
reloadConfig();
await build();
};