olum-compiler 0.2.7 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +1 -1
  3. package/bin/build.js +9 -0
  4. package/bin/compiler.js +23 -0
  5. package/bin/copySrc.js +22 -0
  6. package/bin/dev.js +47 -0
  7. package/bin/index.js +1 -24
  8. package/bin/mimes.json +340 -0
  9. package/bin/server.js +77 -0
  10. package/bin/watcher.js +6 -0
  11. package/bin/ws.js +54 -0
  12. package/lib/attr.js +39 -0
  13. package/lib/clean.js +4 -0
  14. package/lib/colors.js +72 -0
  15. package/lib/compPlaceholder.js +10 -0
  16. package/lib/compiler.js +21 -0
  17. package/lib/cssParser.js +87 -0
  18. package/lib/domEvents.js +112 -0
  19. package/lib/events.js +48 -0
  20. package/lib/for.js +71 -0
  21. package/lib/getImports.js +48 -0
  22. package/lib/getTempPath.js +13 -0
  23. package/lib/helpers.js +509 -0
  24. package/lib/htmlParser.js +71 -0
  25. package/lib/if.js +65 -0
  26. package/lib/jsParser.js +31 -0
  27. package/lib/lineCounter.js +31 -0
  28. package/lib/log.txt +0 -0
  29. package/lib/mode.js +12 -0
  30. package/lib/models.js +51 -0
  31. package/lib/parser.js +170 -0
  32. package/lib/placeholder.js +76 -0
  33. package/lib/regex.js +12 -0
  34. package/lib/show.js +22 -0
  35. package/lib/sourcemap.js +34 -0
  36. package/lib/styles.js +32 -0
  37. package/lib/toJs.js +12 -0
  38. package/lib/tokens.js +14 -0
  39. package/package.json +8 -40
  40. package/babel.config.json +0 -4
  41. package/compiler.js +0 -486
  42. package/tasks/build.js +0 -24
  43. package/tasks/bundle.js +0 -33
  44. package/tasks/catchall.js +0 -39
  45. package/tasks/clean.js +0 -18
  46. package/tasks/compile.js +0 -32
  47. package/tasks/copy-build.js +0 -33
  48. package/tasks/desktop.js +0 -63
  49. package/tasks/dev.js +0 -18
  50. package/tasks/index.js +0 -12
  51. package/tasks/linux.js +0 -255
  52. package/tasks/logger.js +0 -19
  53. package/tasks/mac.js +0 -8
  54. package/tasks/reload.js +0 -7
  55. package/tasks/server.js +0 -26
  56. package/tasks/watch.js +0 -44
  57. package/tasks/windows.js +0 -8
  58. package/webpack.config.js +0 -152
package/compiler.js DELETED
@@ -1,486 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * @name olum-compiler
5
- * @copyright 2021
6
- * @author Eissa Saber
7
- * @license MIT
8
- */
9
- const commander = require("commander");
10
- const cmd = new commander.Command();
11
- const sass = require("sass");
12
- const autoprefixer = require("autoprefixer");
13
- const cssnano = require('cssnano');
14
- const postcss = require("postcss");
15
- const fs = require("fs");
16
- const extra = require("fs-extra");
17
- const path = require("path");
18
- const colors = require("colors");
19
-
20
- // helpers
21
- const isDebugging = false;
22
- const debugLib = arg => (isDebugging ? console.log(arg) : "");
23
- const quotes = (msg, color = "grey") => `'${colors[color].bold(msg)}'`;
24
- const log = (type, path, err) => quotes(`\n${type} : ${path.replace(/[\/|\\]node_modules[\/|\\]olum-compiler/g,"")}`, "white") + "\n" + colors.red.bold(err);
25
- const isObj = obj => !!(obj !== null && typeof obj === "object");
26
- const isFullArr = arr => !!(isObj(arr) && Array.isArray(arr) && arr.length);
27
- const isDef = val => !!(val !== undefined && val !== null);
28
- const flatten = lists => lists.reduce((a, b) => a.concat(b), []);
29
- const mkRegex = arr => {
30
- const pattern = arr.map(str => `${str.toLowerCase().trim()}|`).join("").slice(0, -1);
31
- const regex = new RegExp(pattern, "gi");
32
- return regex;
33
- };
34
-
35
- class Compiler {
36
- regex = {
37
- template: {
38
- all: /<template[\s\S]*?>[\s\S]*?<\/template>/gi,
39
- tag: /<template[\s\S]*?>|<\/template>/gi,
40
- component: /(?<=<)[A-Z]([^/>]+)(?=\/>)/g, // detect <App/> or <App-Nav/>
41
- comment: /\<\!\-\-(.|\s)*?\-\-\>/gi
42
- },
43
- script: {
44
- all: /<script[\s\S]*?>[\s\S]*?<\/script>/gi,
45
- tag: /<script[\s\S]*?>|<\/script>/gi,
46
- classStartPoint: /(class .*)(\{)/,
47
- },
48
- style: {
49
- all: /<style[\s\S]*?>[\s\S]*?<\/style>/gi,
50
- tag: /<style[\s\S]*?>|<\/style>/gi,
51
- openTag: /<style[\s\S]*?>/gi,
52
- comment: /(\/\*)([\s\S]*?)(\*\/)|(\/\/.*)/gi
53
- },
54
- };
55
-
56
- constructor() {
57
- cmd.command("clean [dir]").action(this.clean.bind(this));
58
- cmd.command("compile [mode]").action(this.init.bind(this));
59
- cmd.parse(process.argv);
60
- }
61
-
62
- isHTML(path) {
63
- const arr = path.split(".");
64
- const lastItem = arr[arr.length-1];
65
- if (lastItem.trim().toLowerCase() === "html") return true;
66
- return false;
67
- }
68
-
69
- getPaths(base = "../../src") {
70
- return new Promise((resolve, reject) => {
71
- const dirs = src => fs.readdirSync(src).map(item => path.join(src, item)).filter(item => fs.statSync(item).isDirectory());
72
- const recursive = src => [src, ...flatten(dirs(src).map(recursive))];
73
- const directories = recursive(base);
74
- debugLib(["all directories", directories]);
75
-
76
- if (!isFullArr(directories)) return reject("No directories found !");
77
- const lastDir = directories[directories.length - 1];
78
-
79
- // get all html files
80
- this.paths = [];
81
- [...directories].forEach((dir, index) => {
82
- fs.readdir(path.resolve(dir), (err, files) => {
83
- if (err) return reject(err);
84
-
85
- files.forEach((file, ind) => {
86
- const lastFile = files[files.length - 1];
87
- const item = path.join(dir, file);
88
- if (!fs.statSync(item).isDirectory() && this.isHTML(item)) this.paths.push(item.trim().replace(/src/, "node_modules/olum-compiler/"+"src")); // push files only and exclude directories
89
- if (directories.indexOf(lastDir) === index && files.indexOf(lastFile) === ind) {
90
- const msg = `Created ${quotes("Paths", "blue")} Tree.`;
91
- debugLib(["Final paths",this.paths]);
92
- debugLib(msg);
93
- resolve();
94
- }
95
- });
96
- });
97
- })
98
-
99
- });
100
- }
101
-
102
- clean(dir) {
103
- return new Promise((resolve, reject) => {
104
- if (dir === "src") { // clean src folder which is ".pre-build"
105
- if (fs.existsSync("src")) { // if folder exists
106
- extra.remove(path.resolve(__dirname, "src"), err => {
107
- if (err) return reject(err);
108
- const msg = `Deleted ${quotes("src", "red")} Directory.`;
109
- debugLib(msg);
110
- resolve();
111
- });
112
- } else resolve();
113
- } else if (dir === "dest") { // clean dest folder which is "build"
114
- if (fs.existsSync("build")) { // if folder exists
115
- extra.remove(path.resolve(__dirname, "build"), err => {
116
- if (err) return reject(err);
117
- const msg = `Deleted ${quotes("build", "red")} Directory.`;
118
- debugLib(msg);
119
- resolve();
120
- });
121
- } else resolve();
122
- }
123
- });
124
- }
125
-
126
- copy() {
127
- return new Promise((resolve, reject) => {
128
- extra.copy(path.resolve(__dirname, "../../src"), path.resolve(__dirname, "src"), err => {
129
- if (err) return reject(err);
130
- const msg = `Copied & renamed ${quotes("src", "green")} Directory → ${quotes("src", "yellow")}`;
131
- debugLib(msg);
132
- // delete public folder if it exists
133
- if (fs.existsSync(path.resolve(__dirname,"./public"))) {
134
- extra.remove(path.resolve(__dirname,"./public"), err => {
135
- if (err) return reject(err);
136
- // copy public from root to node_module/olum-compiler
137
- extra.copy(path.resolve(__dirname, "../../public"), path.resolve(__dirname,"./public"), err => {
138
- if (err) return reject(err);
139
- const msg = `Copied & renamed ${quotes("public", "green")} Directory`;
140
- debugLib(msg);
141
- resolve();
142
- });
143
- });
144
- } else {
145
- // copy public from root to node_module/olum-compiler
146
- extra.copy(path.resolve(__dirname, "../../public"), path.resolve(__dirname,"./public"), err => {
147
- if (err) return reject(err);
148
- const msg = `Copied & renamed ${quotes("public", "green")} Directory`;
149
- debugLib(msg);
150
- resolve();
151
- });
152
- }
153
- });
154
- });
155
- }
156
-
157
- sharedStyle() {
158
- const file = path.resolve(__dirname, "../../src/styles/shared.scss");
159
- return new Promise((resolve, reject) => {
160
- if (fs.existsSync(file)) {
161
- fs.readFile(file, "utf8", (err, data) => {
162
- if (err) return reject(err);
163
- const msg = `Copied ${quotes("shared", "green")} Style.`;
164
- debugLib(msg);
165
- resolve(data.trim());
166
- });
167
- } else {
168
- resolve("");
169
- }
170
- });
171
- }
172
-
173
- compiledSharedStyle(shared) {
174
- const file = path.resolve(__dirname, "../../src/styles/shared.scss");
175
- return new Promise((resolve, reject) => {
176
- try {
177
- // compile sass to css
178
- const compiled = sass.renderSync({
179
- data: shared
180
- }).css.toString();
181
- const msg = `Compiled ${quotes("shared", "green")} Style.`;
182
- debugLib(msg);
183
- resolve(compiled);
184
- } catch (err) { // error related to Sass
185
- reject(log("Sass Compiler", file, err));
186
- }
187
- });
188
- }
189
-
190
- hasSASS(style) {
191
- const regex = new RegExp("lang=['\"]scss|sass['\"]", "gi");
192
- const openTagArr = style.match(this.regex.style.openTag);
193
- const openTag = isFullArr(openTagArr) ? openTagArr[0] : "";
194
- return regex.test(openTag);
195
- }
196
-
197
- /* stringify template litrals placeholder ${} before sass/postcss */
198
- stringify(string, file) {
199
- const regex = new RegExp(`(\\$\\{+[\\w|\\.]+\\})`, "gi"); // detects => ${}
200
- let arr = string.match(regex);
201
- arr = isFullArr(arr) ? arr : [];
202
- arr.forEach(item => {
203
- debugLib(`Stringified template litrals placeholder ${quotes(item, "red")} in <style> : ${quotes(file.trim().replace("src", "src"), "yellow")}`);
204
- string = string.replace(regex, `"$1"`);
205
- });
206
- return string;
207
- }
208
-
209
- /* parse template litrals placeholder ${} after sass/postcss */
210
- parse(string, file) {
211
- const regex = new RegExp(`(\\s?\\"(\\$\\{+[\\w|\\.]+\\})\\"\\s?)`, "gi"); // detects => "${}"
212
- let arr = string.match(regex);
213
- arr = isFullArr(arr) ? arr : [];
214
- arr.forEach(item => {
215
- debugLib(`Parsed template litrals placeholder ${quotes(item, "green")} in <style> : ${quotes(file.trim().replace("src", "src"), "yellow")}`);
216
- string = string.replace(regex, "$2");
217
- });
218
- return string;
219
- }
220
-
221
- styleImporter(file, scss) {
222
- return new Promise ((resolve, reject) => {
223
- // extend css to outside component file - initial test
224
- const importRegex = /(\/*|\/\/)=?.*(@import)\s+((\'|\").*(\'|\"));?/gi;
225
- const imports = scss.match(importRegex);
226
- debugLib(["Style Import statements\n", imports]);
227
-
228
- if (isFullArr(imports)) {
229
- imports.map(imp => {
230
- if (!imp.trim().startsWith("/")) { // detect non-commented @import
231
- const scssPath = imp.replace(/\@import|\s|'|"|;/g, "").trim();
232
- const scssFullPath = file.replace(path.basename(file), "") + scssPath;
233
- debugLib(["Style paths\n", {imp, scssPath, scssFullPath}]);
234
-
235
- if (fs.existsSync(scssFullPath)) {
236
- fs.readFile(scssFullPath, "utf8", (err, data) => {
237
- if (err) return reject(err);
238
- debugLib(["Style module content\n", data]);
239
-
240
- scss = scss.replace(imp, data); // substitute with import statement content
241
- return resolve(scss);
242
- });
243
-
244
- } else {
245
- return reject("Style file doesn't exist in this path '" + scssPath + "'");
246
- }
247
- }
248
- });
249
- } else {
250
- return resolve(scss);
251
- }
252
-
253
- });
254
- }
255
-
256
- css(file, data, shared, compiledShared) {
257
- return new Promise((resolve, reject) => {
258
- const styleArr = data.match(this.regex.style.all);
259
- const style = isFullArr(styleArr) ? styleArr[styleArr.length - 1] : ""; // get last style tag as the order of component file | because you may have style tag inside the class "script tag"
260
- let scss = style.replace(this.regex.style.tag, ""); // remove style tag
261
- scss = scss.replace(this.regex.style.comment, ""); // remove block/inline comments
262
-
263
- this.styleImporter(file, scss).then(_scss => {
264
- _scss = this.stringify(_scss, file);
265
-
266
- try {
267
- // compile sass to css
268
- const css = this.hasSASS(style) ? sass.renderSync({
269
- data: shared + _scss
270
- }).css.toString() : compiledShared + _scss;
271
-
272
- if (this.mode === "development") { // development
273
- const parsedDev = this.parse(css, file);
274
- resolve("\n style() { \n return `" + parsedDev + "`;\n}\n");
275
-
276
- } else if (this.mode === "production") { // production
277
- // prefix & minify css
278
- postcss([autoprefixer, cssnano]).process(css, {
279
- from: undefined
280
- }).then(result => {
281
- result.warnings().forEach(warn => console.warn(colors.yellow.bold(warn.toString())));
282
- const parsedBuild = this.parse(result.css, file);
283
- resolve("\n style() { \n return `" + parsedBuild + "`;\n}\n");
284
- }).catch(err => reject(log("PostCSS - [autoprefixer, cssnano]", file, err.reason + "\n" + err.showSourceCode())));
285
- }
286
-
287
- } catch (err) { // error related to Sass
288
- reject(log("Sass Compiler", file, err));
289
- }
290
-
291
- }).catch(err => reject(log("Style Importer", file, err)));
292
-
293
- });
294
- }
295
-
296
- html(data) {
297
- return new Promise(resolve => {
298
- const tempArr = data.match(this.regex.template.all);
299
- const template = isFullArr(tempArr) ? tempArr[0] : ""; // get 1st template tag as the order of component file
300
- const markup = template.replace(this.regex.template.tag, "");
301
- const cleanHTML = markup.replace(this.regex.template.comment, ""); // clean html from comments
302
- const html = `
303
- template(arg) {
304
- var olumTempOpeningTag = new RegExp("<[aA-zZ][\\\\s\\\\S]*?>");
305
- var olumTempClosingTag = new RegExp("(</[aA-zZ]+>)$", "g");
306
- var olumTemp = \`\n${cleanHTML}\n\`;
307
- if (arg && arg === true) olumTemp = olumTemp.trim().replace(olumTempOpeningTag, '').replace(olumTempClosingTag, '');
308
- return olumTemp;
309
- }
310
- `;
311
- resolve(html);
312
- });
313
- }
314
-
315
- js(file, data) {
316
- return new Promise((resolve, reject) => {
317
- const scriptArr = data.match(this.regex.script.all);
318
- const script = isFullArr(scriptArr) ? scriptArr[0] : ""; // get 1st script tag as the order of component file
319
- let js = script.replace(this.regex.script.tag, "");
320
-
321
- // start replace .html extension from import statements with .js
322
- const imports = this.getImportStatement(js); // get all import statements
323
- const htmlExtRegex = /\.html/gi;
324
- imports.forEach(imp => {
325
- if (htmlExtRegex.test(imp)) {
326
- debugLib({imp})
327
- js = js.replace(htmlExtRegex, ".js");
328
- }
329
- });
330
- // end replace .html extension from import statements with .js
331
-
332
- const hasJsClass = this.regex.script.classStartPoint.test(js);
333
- if (hasJsClass) resolve(js);
334
- else reject(log("JS Class", file, "Couldn't find a class"));
335
- });
336
- }
337
-
338
- modifyExt(file) {
339
- const arr = file.split(".");
340
- const ext = arr[arr.length - 1];
341
- return file.replace(ext, "") + "js";
342
- }
343
-
344
- // start auto inject data method
345
- getModuleName(str) {
346
- return str.replace(/import|from|\;|("|').*("|')|\s/gi, "").trim();
347
- }
348
-
349
- getImportStatement(str) {
350
- return str.match(/(import).*/g) || [];
351
- }
352
-
353
- getClassName(js) {
354
- let str = js.match(this.regex.script.classStartPoint)[0].replace(/\{/g, "");
355
- let arr = str.split(" ");
356
- arr = arr.filter(item => item.trim() != "");
357
- const classIndex = arr.indexOf("class");
358
- const name = arr[classIndex+1];
359
- return name;
360
- }
361
- // end auto inject data method
362
-
363
- merge(html, css, js) {
364
- // start auto inject data method
365
- const imports = this.getImportStatement(js); // get all import statements
366
- const modulesNames = imports.map(statement => this.getModuleName(statement)); // extract modules names
367
- const cleanHTML = html.replace(this.regex.template.comment, ""); // clean html from comments
368
- const components = cleanHTML.match(this.regex.template.component) || []; // get components tags
369
- const componentsNames = components.map(name => name.replace(/(.*)(\-)/, "").trim()); // remove prefix
370
- const className = this.getClassName(js);
371
-
372
- let dataMethod;
373
- if (isFullArr(modulesNames) && isFullArr(componentsNames)) { // there are components
374
- debugLib("components exist");
375
- const finalNames = [];
376
- modulesNames.forEach(moduleName => componentsNames.forEach(compName => (moduleName !== "" && moduleName === compName) ? finalNames.push("{"+moduleName+"}") : null));
377
- dataMethod = `
378
- olumCompData() {
379
- return {
380
- name: "${className}",
381
- components: [ ${finalNames.join(", ")} ],
382
- template: this.template(),
383
- style: this.style(),
384
- render: this.render.bind(this),
385
- };
386
- }
387
- `;
388
- } else { // NO components
389
- debugLib("components DON'T exist");
390
- dataMethod = `
391
- olumCompData() {
392
- return {
393
- name: "${className}",
394
- components: [],
395
- template: this.template(),
396
- style: this.style(),
397
- render: this.render.bind(this),
398
- };
399
- }
400
- `;
401
- }
402
-
403
- debugLib({ html });
404
- debugLib({ componentsNames });
405
- debugLib({ modulesNames });
406
- debugLib({ dataMethod });
407
- // end auto inject data method
408
-
409
- return new Promise((resolve, reject) => {
410
- let classSentence = js.match(this.regex.script.classStartPoint);
411
- if (isFullArr(classSentence)) {
412
- classSentence = classSentence[0];
413
- const file = js.replace(classSentence, classSentence + dataMethod + html + css);
414
- return resolve(file);
415
- } else {
416
- return reject("Couldn't find a JS Class");
417
- }
418
- });
419
- }
420
-
421
- createFile(oldPath, newPath, compiledFile) {
422
- return new Promise((resolve, reject) => {
423
- fs.rename(oldPath, newPath, err => {
424
- if (err) return reject(err);
425
- fs.writeFile(newPath, compiledFile, err => {
426
- if (err) return reject(err);
427
- // debugLib("Created " + quotes(path.basename(newPath), "green"));
428
- resolve();
429
- });
430
- });
431
- });
432
- }
433
-
434
- update(shared, compiledShared) {
435
- if (isDef(this.paths) && isFullArr(this.paths)) {
436
- const recursive = num => {
437
- const file = this.paths[num].trim();
438
- const newPath = this.modifyExt(file);
439
-
440
- fs.readFile(file, "utf8", (err, data) => {
441
- if (err) return console.error(colors.red.bold(err));
442
-
443
- (async () => {
444
- try {
445
- const html = await this.html(data);
446
- const css = await this.css(file, data, shared, compiledShared);
447
- const js = await this.js(file, data);
448
- const compiledFile = await this.merge(html, css, js);
449
- await this.createFile(file, newPath, compiledFile);
450
-
451
- if (num + 1 <= this.paths.length - 1) recursive(num + 1); // next
452
- } catch (err) {
453
- console.error(err);
454
- }
455
- })();
456
-
457
- });
458
- };
459
- recursive(0);
460
- } else {
461
- const msg = `No ${quotes("components", "red")} to compile.`;
462
- console.warn(msg);
463
- }
464
- }
465
-
466
- async init(mode) {
467
- // detect mode
468
- mode = typeof mode != "undefined" && mode === "dev" ? "development" : "production";
469
- this.mode = mode;
470
- debugLib(`Compiling in ${quotes(this.mode, "green")} mode...`);
471
-
472
- try {
473
- await this.getPaths(path.resolve(__dirname,"../../src"));
474
- await this.clean("src"); // clean src folder which is ".pre-build"
475
- await this.copy();
476
- const shared = await this.sharedStyle();
477
- const compiledShared = await this.compiledSharedStyle(shared);
478
- this.update(shared, compiledShared);
479
- debugLib(`Updated ${quotes("Components", "green")}`);
480
- } catch (err) {
481
- console.error(colors.red.bold(err));
482
- }
483
- }
484
- }
485
-
486
- new Compiler();
package/tasks/build.js DELETED
@@ -1,24 +0,0 @@
1
- const compile = require("./compile");
2
- const bundle = require("./bundle");
3
- const clean = require("./clean");
4
- const catchall = require("./catchall");
5
- const desktop = require("./desktop");
6
- const colors = require("colors");
7
- const copyBuild = require("./copy-build");
8
-
9
- async function renderBuild() {
10
- try {
11
- await clean("dest"); // remove 'build' folder
12
- await compile("production");
13
- await bundle("production");
14
- await clean("src"); // remove '.pre-build' folder
15
- await catchall(); // catch all routes to fallback to root
16
- await copyBuild(); // copy build folder to project root after finishing builing for production
17
- await desktop(); // package desktop app
18
- // process.exitCode = 1;
19
- } catch (err) {
20
- console.log(colors.red.bold(err));
21
- }
22
- }
23
-
24
- module.exports = renderBuild;
package/tasks/bundle.js DELETED
@@ -1,33 +0,0 @@
1
- const logger = require("./logger");
2
- const reload = require("./reload");
3
- const { exec } = require("child_process");
4
- const colors = require("colors");
5
-
6
- const bundle = mode => {
7
- const taskName = "bundle";
8
- return new Promise((resolve, reject) => {
9
- logger(taskName, "start");
10
- if (mode === "development") {
11
- exec("webpack --env dev", (error, stdout, stderr) => {
12
- if (stdout.toLowerCase().includes("error")) console.log(colors.red.bold(stdout));
13
- else if (stdout.trim() !== "") console.log(stdout);
14
- if (error) return reject(error);
15
- if (stderr) return reject(stderr);
16
- reload();
17
- resolve();
18
- logger(taskName, "end");
19
- });
20
- } else if (mode === "production") {
21
- exec("webpack", (error, stdout, stderr) => {
22
- if (stdout.toLowerCase().includes("error")) console.log(colors.red.bold(stdout));
23
- else if (stdout.trim() !== "") console.log(stdout);
24
- if (error) return reject(error);
25
- if (stderr) return reject(stderr);
26
- resolve();
27
- logger(taskName, "end");
28
- });
29
- }
30
- });
31
- };
32
-
33
- module.exports = bundle;
package/tasks/catchall.js DELETED
@@ -1,39 +0,0 @@
1
- const inquirer = require("inquirer");
2
- const fs = require("fs");
3
- const path = require("path");
4
-
5
- // Questions
6
- const q1 = { type: "confirm", name: "catch", message: "Do you want to catch all routes to fall back to root" };
7
- const q2 = { type: "input", name: "routes", message: "Add the desired routes separated by a comma" };
8
-
9
- const catchAll = () => {
10
- const taskName = "catchall";
11
- return new Promise((resolve, reject) => {
12
- inquirer.prompt([q1]).then(ans => {
13
- if (!ans.catch) return resolve();
14
- inquirer.prompt([q2]).then(ans2 => {
15
- const file = path.resolve(__dirname, `../build/index.html`);
16
- if (fs.existsSync(file)) {
17
- fs.readFile(file, "utf8", (err, data) => {
18
- if (err) return reject(err);
19
-
20
- const routes = ans2.routes.split(",");
21
- routes.forEach(route => {
22
- route = route.trim();
23
- const newFile = path.resolve(__dirname, `../build/${route}.html`);
24
- fs.writeFile(newFile, data, err => {
25
- if (err) return reject(err);
26
- resolve();
27
- });
28
- });
29
-
30
- });
31
- } else {
32
- reject(`index.html doesn't exist in build directory!`);
33
- }
34
- }).catch(reject);
35
- }).catch(reject);
36
- });
37
- };
38
-
39
- module.exports = catchAll;
package/tasks/clean.js DELETED
@@ -1,18 +0,0 @@
1
- const {exec} = require("child_process");
2
- const logger = require("./logger");
3
- const path = require("path");
4
-
5
- const clean = dir => {
6
- const taskName = "clean";
7
- const file = path.resolve(__dirname, "../compiler.js");
8
- return new Promise((resolve, reject) => {
9
- logger(taskName, "start");
10
- exec(`node ${file} clean ${dir}`, (error, stdout, stderr) => {
11
- if (error) return reject(error);
12
- resolve();
13
- logger(taskName, "end");
14
- });
15
- });
16
- };
17
-
18
- module.exports = clean;
package/tasks/compile.js DELETED
@@ -1,32 +0,0 @@
1
- const { exec } = require("child_process");
2
- const logger = require("./logger");
3
- const path = require("path");
4
-
5
- const compile = mode => {
6
- const taskName = "compile";
7
- return new Promise((resolve, reject) => {
8
- const file = path.resolve(__dirname, "../compiler.js");
9
- logger(taskName, "start");
10
- if (mode === "development") {
11
- exec(`node ${file} compile dev`, (error, stdout, stderr) => {
12
- if (stdout.toLowerCase().includes("error")) console.log(colors.red.bold(stdout));
13
- else if (stdout.trim() !== "") console.log(stdout);
14
- if (error) return reject(error);
15
- if (stderr) return reject(stderr);
16
- resolve();
17
- logger(taskName, "end");
18
- });
19
- } else if (mode === "production") {
20
- exec(`node ${file} compile`, (error, stdout, stderr) => {
21
- if (stdout.toLowerCase().includes("error")) console.log(colors.red.bold(stdout));
22
- else if (stdout.trim() !== "") console.log(stdout);
23
- if (error) return reject(error);
24
- if (stderr) return reject(stderr);
25
- resolve();
26
- logger(taskName, "end");
27
- });
28
- }
29
- });
30
- };
31
-
32
- module.exports = compile;
@@ -1,33 +0,0 @@
1
- const logger = require("./logger");
2
- const extra = require("fs-extra");
3
- const path = require("path");
4
- const fs = require("fs");
5
-
6
- const copyBuild = () => {
7
- const taskName = "copyBuild";
8
- return new Promise((resolve, reject) => {
9
- logger(taskName, "start");
10
- // delete build folder if it exists
11
- const dest = path.resolve(__dirname, "../../../build");
12
- if (fs.existsSync(dest)) {
13
- extra.remove(dest, err => {
14
- if (err) return reject(err);
15
- // copy folder to project root
16
- extra.copy(path.resolve(__dirname, "../build"), path.resolve(__dirname, "../../../build"), err => {
17
- if (err) return reject(err);
18
- resolve();
19
- logger(taskName, "end");
20
- });
21
- });
22
- } else {
23
- // copy folder to project root
24
- extra.copy(path.resolve(__dirname, "../build"), path.resolve(__dirname, "../../../build"), err => {
25
- if (err) return reject(err);
26
- resolve();
27
- logger(taskName, "end");
28
- });
29
- }
30
- });
31
- };
32
-
33
- module.exports = copyBuild;