-
Notifications
You must be signed in to change notification settings - Fork 0
/
distruct.js
334 lines (238 loc) · 12.1 KB
/
distruct.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
const
fs = require('fs'),
path = require('path'),
url = require('url'),
ejs = require('ejs'),
child_process = require('child_process'),
express = require('express'),
mkdirp = require('mkdirp'),
rimraf = require('rimraf'),
mime = require('mime-types'),
strip = require('strip-comments'),
JavaScriptObfuscator = require('javascript-obfuscator');
var config = {delimiter: "*"}, configFile = null;
const fn = {
"directory": function(){
var args = [];
for (let each in arguments) args.push(arguments[each]);
return fs.readdirSync(args.join('/'));
},
"exists": function(path){
var args = [];
for (let each in arguments) args.push(arguments[each]);
return fs.existsSync(args.join('/'));
},
"read": function(){
var args = [];
for (let each in arguments) args.push(arguments[each]);
return fs.readFileSync(args.join('/'));
},
"uncomment": function(text, options){
return strip(text, (options||{keepProtected: true}));
}
};
// Compare wildcard urls for ignore rules.
function compare(str, rule) {
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}
var Distruct = {
"config": (configuration) => {
var cfg = null;
if (typeof configuration == 'string') {
if ( fs.existsSync(configuration) ) {
try {
cfg = JSON.parse(fs.readFileSync(configuration).toString());
configFile = configuration;
} catch (ParseError) {
console.error(`Could not parse config from file '${configuration}'`);
}
} else {
console.error(`File '${configuration}' does not exist.`);
}
} else if (typeof configuration == 'object') cfg = configuration;
if (cfg) for (let each in cfg) {
config[each] = cfg[each];
}
return configuration;
},
"build": (callback) => {
ejs.delimiter = config.delimiter || '*';
if (!config.directories) return console.error("config.directories needs to be an object.");
if (typeof config.directories.source !== 'string') return console.error("config.directories.source needs to be a filepath.");
if (typeof config.directories.builds !== 'string') return console.error("config.directories.builds needs to be a filepath.");
var
srcdir = path.resolve(config.directories.source),
distdir = path.resolve(config.directories.builds);
function Build(cb){
console.log(`Building from ${srcdir}`);
fs.readdirSync(srcdir).forEach(filename=>{
var p = path.resolve(srcdir, filename);
Migrate(p);
});
if (typeof cb == 'function') cb();
}
// Migrate a file over to distribution.
function Migrate(p){
var ext = path.extname(p),
type = mime.lookup(p);
if (ext) ext = ext.substring(1);
config.builds.forEach(distribution=>{
if (fs.existsSync(p) && fs.lstatSync(p).isDirectory()) {
console.group(`(${ext}) ${p}`);
fs.readdirSync(p).forEach(f=>
Migrate(path.resolve(p, f))
);
console.groupEnd();
} else {
console.log(`(${ext}) ${p}`);
var contents = fs.readFileSync(p);
var s = Date.now();
var shouldRender = false,
shouldDist = true;
if(distribution.extensions) distribution.extensions.forEach(x=>{
if (ext.toLowerCase() == x.toLowerCase()) shouldRender = true;
});
var raw = p.replace(srcdir, '').substring(1).replace(/\\/gi, '/');
if (config.ignore) config.ignore.forEach(function(path){
if (compare(raw, path.replace(/\\/gi, '/'))) shouldDist = false;
});
if (distribution.ignore) distribution.ignore.forEach(function(path){
if (compare(raw, path.replace(/\\/gi, '/'))) shouldDist = false;
});
var variables = {distribution:{}};
if (config.variables) for (let attr in config.variables){
for (let v in config.variables)
variables[v] = config.variables[v];
}
for(let attr in distribution){
if (attr == 'variables') {
for (let v in distribution.variables)
variables[v] = distribution.variables[v];
} else variables.distribution[attr] = distribution[attr];
}
variables.dir = srcdir;
if (shouldRender) try {
ejs.delimiter = config.delimiter || '*';
variables.dir = srcdir;
console.log(variables);
variables.product = config.product;
variables.fn = fn;
contents = ejs.render(contents.toString(), variables);
console.log('Rendered', p, 'in', `${Date.now()-s}ms.`);
} catch (e) {
console.error(`[!] Could not render ${p}`, e.message);
}
var distpath = p.replace(srcdir, path.resolve(distdir, distribution.name));
if (shouldDist) mkdirp(path.dirname(distpath), ()=>{
fs.writeFileSync(distpath, contents);
});
}
})
}
// Remove distribution path to rebuild it.
rimraf(distdir, function(){
Build(callback);
});
},
"serve": (configuration) => {
console.log(`Starting static file server...`);
ejs.delimiter = config.delimiter || '*';
if (!config.directories) return console.error("config.directories needs to be an object.");
if (typeof config.directories.source !== 'string') return console.error("config.directories.source needs to be a filepath.");
if (typeof config.directories.builds !== 'string') return console.error("config.directories.builds needs to be a filepath.");
var
srcdir = path.resolve(config.directories.source),
distdir = path.resolve(config.directories.builds);
var server = express();
config.builds.forEach(distribution=>{
console.log('opened: ' + '/' + distribution.name + '/*');
server.get('/' + distribution.name + '/*', (req,res)=>{
if (typeof configFile == 'string') Distruct.config(configFile);
console.log(configFile, config.builds[0]);
config.builds.forEach(dist=>{
if (dist.name == distribution.name) distribution = dist;
});
var p = url.parse(req.url).pathname.substring(('/' + distribution.name + '/').length);
var shouldRender = false, shouldDist = true;
if (fs.lstatSync(config.directories.source + '/' + p).isDirectory()) {
if (p.length>2 && p[p.length-1]!=='/') {
res.redirect(p + '/');
}
console.log('(dir)');
p = path.join(p,'index.html');
}
var ext = path.extname(p).substring(1),
type = mime.lookup(p);
console.log('viewing:', config.directories.source + '/' + p);
if(distribution.extensions) distribution.extensions.forEach(x=>{
if (ext.toLowerCase() == x.toLowerCase()) shouldRender = true;
});
var raw = p.replace(srcdir, '').substring(1).replace(/\\/gi, '/');
if (config.ignore) config.ignore.forEach(function(path){
if (compare(raw, path.replace(/\\/gi, '/'))) shouldDist = false;
});
if (distribution.ignore) distribution.ignore.forEach(function(path){
if (compare(raw, path.replace(/\\/gi, '/'))) shouldDist = false;
});
var variables = {distribution:{}};
if (config.variables) for (let attr in config.variables) {
for (let v in config.variables)
variables[v] = config.variables[v];
}
for(let attr in distribution){
if (attr == 'variables') {
for (let v in distribution.variables)
variables[v] = distribution.variables[v];
} else variables.distribution[attr] = distribution[attr];
}
variables.dir = srcdir;
if (!fs.existsSync(path.resolve(config.directories.source,p))) return res.sendStatus(404);
if (shouldRender) {
res.setHeader('content-type', type);
ejs.delimiter = config.delimiter || '*';
variables.fn = fn;
variables.product = config.product;
res.send(ejs.render(fs.readFileSync(path.resolve(config.directories.source,p)).toString(), variables));
}
else res.sendFile(path.resolve(config.directories.source,p));
});
});
if (!config.server) config.server = {};
server.listen(config.server.port || 3000);
},
"deploy": () => {
console.log('Deploying builds...');
if (!config.directories) return console.error("config.directories needs to be an object.");
if (typeof config.directories.builds !== 'string') return console.error("config.directories.builds needs to be a filepath.");
var TODO = [];
config.deployments.forEach(deployment => {
deployment.builds.forEach(build=>{
var addition = JSON.parse(JSON.stringify(deployment));
addition.name = build;
addition.path = path.resolve(config.directories.builds, build);
TODO.push(addition);
});
});
var curr = 0;
function deploy(){
if (TODO[curr]) {
console.log('Deploying ' + TODO[curr].name + '(' + TODO[curr].script + ')');
var worker = child_process.spawn('node ' + path.resolve(TODO[curr].script) + ' ' + encodeURIComponent(JSON.stringify(TODO[curr])), {shell:true});
worker.stdout.on('data', data=>{
console.log(`[${TODO[curr].name}] ${data}`);
});
worker.stderr.on('data', data=>{
console.error(`[${TODO[curr].name}] ${data}`);
});
worker.on('exit', code=>{
console.log(`${TODO[curr].name} exited with code: ${code}`);
curr++;
deploy();
})
} else console.log('done.');
}
deploy();
},
}
module.exports = Distruct;