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/lib/helpers.js ADDED
@@ -0,0 +1,509 @@
1
+ const { compExt } = require("./regex");
2
+ const colors = require("./colors");
3
+ const path = require("path");
4
+ const fs = require("fs");
5
+ const process = require("process");
6
+ const id = () => "_" + Math.random().toString(36).slice(2);
7
+ const isObj = obj => !!(obj !== null && typeof obj === "object");
8
+ const isFullArr = arr => !!(isObj(arr) && Array.isArray(arr) && arr.length);
9
+ const isDef = val => !!(val !== undefined && val !== null);
10
+ const flatten = lists => lists.reduce((a, b) => a.concat(b), []);
11
+ const isHTML = str => compExt.test(str);
12
+ const isFile = item => !fs.statSync(item).isDirectory();
13
+ const isDir = item => fs.statSync(item).isDirectory();
14
+ const isWin = () => !["linux", "darwin"].includes(process.platform);
15
+ const hasForwardSlash = (paths) => paths.find((item) => /\//g.test(item));
16
+ const hasSlash = (paths) => paths.find((item) => /\//g.test(item) || /\\/g.test(item));
17
+ const stringToBase64 = (str) => Buffer.from(str).toString('base64');
18
+ const base64ToString = (base64) => Buffer.from(base64, 'base64').toString('ascii');
19
+ const esprima = require("esprima");
20
+
21
+ function isUpper(char) {
22
+ const upperChar = char.toUpperCase();
23
+ const regex = new RegExp(upperChar);
24
+ return regex.test(char);
25
+ }
26
+ function isNum(str) {
27
+ if (["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].includes(str.trim()[0])) return true;
28
+ return false;
29
+ }
30
+ function toLower(str) {
31
+ return str.toLowerCase();
32
+ }
33
+ function toUpper(str) {
34
+ return str.toUpperCase();
35
+ }
36
+
37
+ // takes absolute path
38
+ // e.g. ls(src, { absolute: false })
39
+ function ls(src, opt) {
40
+ let paths = [];
41
+
42
+ if (!fs.existsSync(src)) {
43
+ console.error(colors("red", src + " doesn't exist!"));
44
+ return paths;
45
+ }
46
+
47
+ if (!fs.statSync(src).isDirectory()) {
48
+ console.error(colors("red", src + " is NOT a directory!"));
49
+ return paths;
50
+ }
51
+
52
+ let items = fs.readdirSync(src);
53
+ items = items.map((item) => path.join(src, item));
54
+ recursive(items);
55
+
56
+ function recursive(arr) {
57
+ if (!arr.length) return paths;
58
+ arr.forEach(function (item) {
59
+ paths.push(item);
60
+ if (isDir(item)) {
61
+ let newItems = fs.readdirSync(item);
62
+ newItems = newItems.map((newItem) => path.join(item, newItem));
63
+ recursive(newItems);
64
+ }
65
+ });
66
+ }
67
+
68
+ // handle options
69
+ if (opt && opt.hasOwnProperty("absolute") && opt.absolute === false) paths = paths.map((item) => item.replace(src + "/", ""));
70
+
71
+ // handle slashes
72
+ if (hasSlash(paths)) {
73
+ const hasForward = hasForwardSlash(paths);
74
+ const win = isWin();
75
+ if (win && hasForward) {
76
+ paths = paths.map((item) => item.replace(/\//g, "\\"));
77
+ } else if (!win && !hasForward) {
78
+ paths = paths.map((item) => item.replace(/\\/g, "/"));
79
+ }
80
+ }
81
+
82
+ return paths;
83
+ }
84
+
85
+ // todo make other tests
86
+ // e.g. copy("path/to/src", "path/to/dest");
87
+ function copy(src, dest, cb) {
88
+ const files = ls(src);
89
+ let srcDir = path.basename(src);
90
+ let destDir = path.basename(dest);
91
+ let destDirChunck = dest.replace(destDir, "");
92
+ let cleanDirs = [];
93
+ let cleanFiles = [];
94
+ let dirs = [];
95
+ files.forEach((file) => {
96
+ const dir = path.dirname(file);
97
+ if (!dirs.includes(dir)) dirs.push(dir);
98
+ });
99
+
100
+ dirs.forEach((dir) => dir.replace(new RegExp(`${srcDir}.*`), (str) => cleanDirs.push(destDirChunck + str.replace(new RegExp(`${srcDir}`), destDir))));
101
+ files.forEach((dir) => dir.replace(new RegExp(`${srcDir}.*`), (str) => cleanFiles.push(destDirChunck + str.replace(new RegExp(`${srcDir}`), destDir))));
102
+
103
+ // console.log({ dirs });
104
+ // console.log({ cleanDirs });
105
+ // console.log({ cleanFiles });
106
+ // console.log({ srcDir });
107
+ // console.log({ destDir });
108
+ // console.log({ files });
109
+ // console.log({ destDirChunck });
110
+ // make dirs
111
+ cleanDirs.forEach((dir) => {
112
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir);
113
+ });
114
+ // copy files to pre-made dirs above
115
+ files.forEach((file, index) => {
116
+ if (fs.lstatSync(file).isFile()) {
117
+ const fileDest = cleanFiles[index];
118
+ fs.copyFileSync(file, fileDest);
119
+ }
120
+ });
121
+ if (cb) cb();
122
+ }
123
+
124
+ // e.g. remove("path/to/dir");
125
+ function remove(src, cb) {
126
+ const files = ls(src);
127
+ // console.log({ files });
128
+
129
+ const upDir = path.resolve(files[0] , "..");
130
+ files.unshift(upDir);
131
+ // console.log(upDir);
132
+ // console.log({ files });
133
+
134
+ files.forEach((dir) => {
135
+ if (fs.existsSync(dir) && fs.lstatSync(dir).isFile()) fs.unlinkSync(dir);
136
+ });
137
+
138
+ files.reverse().forEach((dir) => {
139
+ if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory()) fs.rmdirSync(dir);
140
+ });
141
+ if (cb) cb();
142
+ }
143
+
144
+ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs: attributes }) {
145
+ /*
146
+
147
+ // must type the attribute as kebab-case if it was camel-case in the logic. e.g.: you have method/prop called getAge, then it will be: exclude-get-age
148
+ private
149
+ private-props
150
+ private-methods
151
+ ----------
152
+ public
153
+ public-props
154
+ public-methods
155
+ ----------
156
+ exclude-prop-name
157
+ exclude-method-name
158
+
159
+ convert above attributes to below query syntax:
160
+
161
+ all=private&except=['age','name']
162
+
163
+ ----------
164
+
165
+ Order matters:
166
+
167
+ ['public-props', 'exclude-age', 'exclude-name', 'private-methods', 'exclude-get-age']
168
+ ↓ ↓ ↓ ↓ ↓
169
+ open props → age → name close props → getAge
170
+ open methods close methods (end)
171
+
172
+ */
173
+
174
+ function scopePolyfill(attrs) {
175
+ const SCOPES = ["public", "public-props", "public-methods", "private", "private-props", "private-methods"];
176
+ const toCamel = str => str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
177
+ const results = {};
178
+
179
+ let current = null;
180
+ let except = [];
181
+
182
+ function flush() {
183
+ if (!current) return;
184
+ const [visibility, dimension] = current.split("-");
185
+ const query = `all=${visibility}&except=[${except.map((e) => `'${e}'`).join(",")}]`;
186
+ if (dimension === "props") results["props-scope"] = query;
187
+ else if (dimension === "methods") results["methods-scope"] = query;
188
+ else {
189
+ results["props-scope"] = query;
190
+ results["methods-scope"] = query;
191
+ }
192
+ }
193
+
194
+ for (const attr of attrs) {
195
+ if (SCOPES.includes(attr)) {
196
+ flush();
197
+ current = attr;
198
+ except = [];
199
+ } else if (attr.startsWith("exclude-")) {
200
+ except.push(toCamel(attr.replace("exclude-", "")));
201
+ }
202
+ }
203
+ flush();
204
+
205
+ return results;
206
+ }
207
+
208
+ const jsAttrs = scopePolyfill(Object.keys(attributes))
209
+ const scope = {
210
+ methods: { all: null, except: null },
211
+ props: { all: null, except: null },
212
+ };
213
+
214
+ function toObj(arr = []) {
215
+ return "{" + arr.join(",") + "}";
216
+ }
217
+
218
+ function hasStateDot(arr) {
219
+ return !!arr.find((str) => str.startsWith("state."));
220
+ }
221
+
222
+ function getStateProps(exceptArr, type) {
223
+ let propsInExcept = [];
224
+ let arr = [];
225
+ exceptArr.forEach((name) => {
226
+ if (name.startsWith("state.")) {
227
+ const propsInState = name.split(".")[1];
228
+ if (stateProps.includes(propsInState)) propsInExcept.push(propsInState);
229
+ }
230
+ });
231
+ if (type === "public") arr = stateProps.filter((prop) => !propsInExcept.includes(prop));
232
+ else if (type === "private") arr = stateProps.filter((prop) => propsInExcept.includes(prop));
233
+ return arr;
234
+ }
235
+
236
+ function getProps(exceptArr, globalNamesArr, type) {
237
+ let namesInExcept = [];
238
+ let arr = [];
239
+ exceptArr.forEach((name) => {
240
+ if (globalNamesArr.includes(name)) {
241
+ if (name !== "state" && !name.startsWith("state.")) namesInExcept.push(name);
242
+ }
243
+ });
244
+ if (type === "public") arr = globalNamesArr.filter((prop) => !namesInExcept.includes(prop) && prop !== "state");
245
+ if (type === "private") arr = globalNamesArr.filter((prop) => namesInExcept.includes(prop) && prop !== "state");
246
+ return arr;
247
+ }
248
+
249
+ function getMethods(exceptArr, globalNamesArr, type) {
250
+ let namesInExcept = [];
251
+ let arr = [];
252
+ exceptArr.forEach((name) => {
253
+ if (globalNamesArr.includes(name)) namesInExcept.push(name);
254
+ });
255
+ if (type === "public") arr = globalNamesArr.filter((method) => !namesInExcept.includes(method));
256
+ if (type === "private") arr = globalNamesArr.filter((method) => namesInExcept.includes(method));
257
+ return arr;
258
+ }
259
+
260
+ function parseScope(query) {
261
+ const obj = {};
262
+ query = query.replace(/'/g, '"');
263
+ const arr = query.split("&");
264
+ if (Array.isArray(arr) && arr.length) {
265
+ arr.forEach((fragment) => {
266
+ const [key, value] = fragment.split("=");
267
+ if (value.startsWith("[")) obj[key] = JSON.parse(value);
268
+ else obj[key] = value;
269
+ });
270
+ }
271
+ return obj;
272
+ }
273
+
274
+ function validateScope(type) {
275
+ if (!jsAttrs[type + "-scope"]) return;
276
+ const currentScope = parseScope(jsAttrs[type + "-scope"]);
277
+ if (currentScope) {
278
+ if (currentScope.all && currentScope.all.trim() !== "") {
279
+ if (["public", "private"].includes(toLower(currentScope.all))) scope[type].all = toLower(currentScope.all).trim();
280
+ }
281
+ if (currentScope.except && isFullArr(currentScope.except)) {
282
+ currentScope.except = currentScope.except.filter((item) => item && item.trim() !== "").map((item) => item.trim());
283
+ if (isFullArr(currentScope.except)) scope[type].except = currentScope.except;
284
+ }
285
+ }
286
+ }
287
+
288
+ function shareAllProps(globalNamesArr) {
289
+ let arr = [];
290
+ arr = globalNamesArr
291
+ .map((name) => {
292
+ if (!["state", ...propsTobeExcluded].includes(name)) return `get ${name}(){return ${name}},set ${name}(val){return ${name} = val}`;
293
+ })
294
+ .filter((item) => item);
295
+ if (hasState && isFullArr(stateProps)) {
296
+ let fragments = stateProps.map((prop) => prop + ": state." + prop);
297
+ arr.push(`get state(){return window.olum.proxyHandlerForStore(${"{" + fragments.join(",") + "}"}, state);}`);
298
+ }
299
+ return arr;
300
+ }
301
+
302
+ // all methods/props are private by default
303
+ function handleScope(globalNamesArr, type) {
304
+ if (globalNamesArr && isFullArr(globalNamesArr) && type) {
305
+ if (!scope[type]) return toObj();
306
+ if (!scope[type].all) return toObj();
307
+ if (scope[type].all === "public") {
308
+ if (!scope[type].except) return type === "methods" ? toObj(globalNamesArr) : toObj(shareAllProps(globalNamesArr));
309
+ if (scope[type].except && isFullArr(scope[type].except)) {
310
+ if (type === "methods") {
311
+ let arr = [];
312
+ let newArr = getMethods(scope[type].except, globalNamesArr, "public");
313
+ if (newArr.length) arr = newArr;
314
+ else return toObj();
315
+ return arr.length ? toObj(arr) : toObj(globalNamesArr);
316
+ } else if (type === "props") {
317
+ const hasStateKeywordInExcecpt = scope[type].except.find((name) => name === "state");
318
+ let arr = [];
319
+ let newArr = getProps(scope[type].except, globalNamesArr, "public");
320
+ if (newArr.length) arr = newArr;
321
+ arr = arr.map((item) => `get ${item}(){return ${item}},set ${item}(val){return ${item} = val}`);
322
+ if (hasState && isFullArr(stateProps)) {
323
+ let publicPropsInState = [];
324
+ if (!hasStateKeywordInExcecpt) {
325
+ if (!hasStateDot(scope[type].except)) publicPropsInState = stateProps;
326
+ else publicPropsInState = getStateProps(scope[type].except, "public");
327
+ }
328
+ if (isFullArr(publicPropsInState)) {
329
+ let fragments = publicPropsInState.map((prop) => prop + ": state." + prop);
330
+ arr.push(`get state(){return window.olum.proxyHandlerForStore(${"{" + fragments.join(",") + "}"}, state);}`);
331
+ }
332
+ }
333
+ if (!newArr.length && !arr.length) return toObj();
334
+ return arr.length ? toObj(arr) : toObj(shareAllProps(globalNamesArr));
335
+ }
336
+ }
337
+ } else if (scope[type].all === "private") {
338
+ if (!scope[type].except) return toObj();
339
+ if (scope[type].except && isFullArr(scope[type].except)) {
340
+ if (type === "methods") {
341
+ let arr = [];
342
+ arr = getMethods(scope[type].except, globalNamesArr, "private");
343
+ return arr.length ? toObj(arr) : toObj();
344
+ } else if (type === "props") {
345
+ const hasStateKeywordInExcecpt = scope[type].except.find((name) => name === "state");
346
+ let arr = [];
347
+ arr = getProps(scope[type].except, globalNamesArr, "private");
348
+ arr = arr.map((item) => `get ${item}(){return ${item}},set ${item}(val){return ${item} = val}`);
349
+ if (hasState && isFullArr(stateProps)) {
350
+ let publicPropsInState = [];
351
+ if (hasStateKeywordInExcecpt) publicPropsInState = stateProps;
352
+ else {
353
+ if (hasStateDot(scope[type].except)) publicPropsInState = getStateProps(scope[type].except, "private");
354
+ }
355
+ if (isFullArr(publicPropsInState)) {
356
+ let fragments = publicPropsInState.map((prop) => prop + ": state." + prop);
357
+ arr.push(`get state(){return window.olum.proxyHandlerForStore(${"{" + fragments.join(",") + "}"}, state);}`);
358
+ }
359
+ }
360
+ return arr.length ? toObj(arr) : toObj();
361
+ }
362
+ }
363
+ }
364
+ }
365
+ return toObj();
366
+ }
367
+
368
+ validateScope("props");
369
+ validateScope("methods");
370
+ return handleScope;
371
+ }
372
+
373
+ // get methods names
374
+ function getGlobalMethods(str) {
375
+ return esprima
376
+ .parse(str, { sourceType: "module" })
377
+ .body.map((obj) => {
378
+ if (obj.type === "FunctionDeclaration") return obj.id.name;
379
+ if (
380
+ obj.type === "VariableDeclaration" &&
381
+ obj.declarations &&
382
+ Array.isArray(obj.declarations) &&
383
+ obj.declarations.length &&
384
+ obj.declarations[0].id &&
385
+ obj.declarations[0].id.name &&
386
+ obj.declarations[0].init &&
387
+ obj.declarations[0].init.type &&
388
+ (obj.declarations[0].init.type === "FunctionExpression" || obj.declarations[0].init.type === "ArrowFunctionExpression")
389
+ ) {
390
+ return obj.declarations[0].id.name;
391
+ }
392
+ })
393
+ .filter((item) => item);
394
+ }
395
+
396
+ // get props names
397
+ function getGlobalProps(str) {
398
+ return esprima
399
+ .parse(str, { sourceType: "module" })
400
+ .body.map((obj) => {
401
+ if (
402
+ obj.type === "VariableDeclaration" &&
403
+ obj.declarations &&
404
+ Array.isArray(obj.declarations) &&
405
+ obj.declarations.length &&
406
+ obj.declarations[0].id &&
407
+ obj.declarations[0].id.name &&
408
+ obj.declarations[0].init &&
409
+ obj.declarations[0].init.type &&
410
+ (obj.declarations[0].init.type === "Literal" ||
411
+ obj.declarations[0].init.type === "ObjectExpression" ||
412
+ obj.declarations[0].init.type === "ArrayExpression" ||
413
+ obj.declarations[0].init.type === "ConditionalExpression" ||
414
+ obj.declarations[0].init.type === "Identifier")
415
+ ) {
416
+ const name = obj.declarations[0].id.name;
417
+ // get all props names inside state object
418
+ if (obj.declarations[0].id.name === "state") {
419
+ if (Array.isArray(obj.declarations) && obj.declarations.length) {
420
+ if (obj.declarations[0].init && obj.declarations[0].init.properties && Array.isArray(obj.declarations[0].init.properties) && obj.declarations[0].init.properties.length) {
421
+ const arr = obj.declarations[0].init.properties;
422
+ stateProps = arr.map((item) => item && item.key && item.key.name);
423
+ }
424
+ }
425
+ }
426
+ return name;
427
+ }
428
+ })
429
+ .filter((item) => item);
430
+ }
431
+
432
+ // minify js as string into one line without changing the js content
433
+ function minifyJS(src) {
434
+ let out = '';
435
+ let i = 0;
436
+ const n = src.length;
437
+
438
+ while (i < n) {
439
+ // Line comment — strip until end of line
440
+ if (src[i] === '/' && src[i+1] === '/') {
441
+ while (i < n && src[i] !== '\n') i++;
442
+ out += ' ';
443
+ continue;
444
+ }
445
+
446
+ // Block comment — strip entirely
447
+ if (src[i] === '/' && src[i+1] === '*') {
448
+ i += 2;
449
+ while (i < n && !(src[i] === '*' && src[i+1] === '/')) i++;
450
+ i += 2;
451
+ out += ' ';
452
+ continue;
453
+ }
454
+
455
+ // Quoted string — copy verbatim (respect escapes)
456
+ if (src[i] === '"' || src[i] === "'") {
457
+ const q = src[i++];
458
+ out += q;
459
+ while (i < n) {
460
+ const c = src[i++];
461
+ out += c;
462
+ if (c === '\\' && i < n) { out += src[i++]; continue; }
463
+ if (c === q) break;
464
+ }
465
+ continue;
466
+ }
467
+
468
+ // Whitespace — collapse to single space
469
+ if (/\s/.test(src[i])) {
470
+ while (i < n && /\s/.test(src[i])) i++;
471
+ out += ' ';
472
+ continue;
473
+ }
474
+
475
+ // Everything else — copy as-is
476
+ out += src[i++];
477
+ }
478
+
479
+ // Remove spaces around punctuation, restore keyword spacing, collapse multi-spaces
480
+ out = out
481
+ .replace(/ *([=+\-*/%&|^~<>!?,;:{}()[\]]) */g, '$1')
482
+ .replace(/\b(const|let|var|return|if|else|for|while|do|switch|case|new|delete|typeof|instanceof|in|of|void|throw|catch|finally|function|class|import|export|from|async|await)\b/g, '$1 ')
483
+ .replace(/ {2,}/g, ' ')
484
+ .trim();
485
+
486
+ return out;
487
+ }
488
+
489
+ module.exports.isNum = isNum;
490
+ module.exports.id = id;
491
+ module.exports.isUpper = isUpper;
492
+ module.exports.toLower = toLower;
493
+ module.exports.toUpper = toUpper;
494
+ module.exports.isObj = isObj;
495
+ module.exports.isFullArr = isFullArr;
496
+ module.exports.isDef = isDef;
497
+ module.exports.flatten = flatten;
498
+ module.exports.isHTML = isHTML;
499
+ module.exports.ls = ls;
500
+ module.exports.copy = copy;
501
+ module.exports.remove = remove;
502
+ module.exports.isFile = isFile;
503
+ module.exports.isDir = isDir;
504
+ module.exports.stringToBase64 = stringToBase64;
505
+ module.exports.base64ToString = base64ToString;
506
+ module.exports.createScopeHandler = createScopeHandler;
507
+ module.exports.getGlobalMethods = getGlobalMethods;
508
+ module.exports.getGlobalProps = getGlobalProps;
509
+ module.exports.minifyJS = minifyJS;
@@ -0,0 +1,71 @@
1
+ const jsdom = require("jsdom");
2
+ const { script, style, selfClosingTag, normalTag } = require("./regex");
3
+ const placeholder = require("./placeholder");
4
+ const clean = require("./clean");
5
+ const handleIfStatement = require("./if");
6
+ const handleForStatement = require("./for");
7
+ const handleShowStatement = require("./show");
8
+ const handleEvents = require("./events");
9
+ const handleStyles = require("./styles");
10
+ const handleModels = require("./models");
11
+ const handleAttr = require("./attr");
12
+ const handleCompPlaceholder = require("./compPlaceholder");
13
+ const { RAW_OPEN, RAW_CLOSE } = require("./tokens");
14
+
15
+ function htmlparser(str, counter, filePath) {
16
+ let content = str.replace(script, "").replace(style, "");
17
+ content = clean(content); // clean html comments to avoid runtime errors
18
+ content = placeholder(content, selfClosingTag, "self");
19
+ content = placeholder(content, normalTag, "normal");
20
+ // Allow unquoted each={expr} / when={expr} / key={expr} — wrap in quotes so jsdom can parse the
21
+ // attribute. `key` is part of #3 (keyed <for>): <for each={t of arr} key={t.id}>.
22
+ content = content.replace(/\b(each|when|key)=\{([^}]+)\}/g, '$1="{$2}"');
23
+
24
+ // Anonymous function event handlers: on<event>={(e)=> expr} → on<event>="__olumAnon_id($event)"
25
+ // The extracted function body is collected and later injected into the component JS as a named method.
26
+ const anonHandlers = [];
27
+ content = content.replace(/(on[a-z]+)=\{((?:[^{}]|\{[^{}]*\})*)\}/g, (match, attr, fn) => {
28
+ const trimmed = fn.trim();
29
+ if (/^(?:\([^)]*\)|\w+)\s*=>|^function[\s(]/.test(trimmed)) {
30
+ const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
31
+ anonHandlers.push(`const ${handlerName} = ${trimmed};`);
32
+ return `${attr}="${handlerName}($event)"`;
33
+ }
34
+ return match;
35
+ });
36
+
37
+ // using dom parser
38
+ const body = new jsdom.JSDOM(content).window.document.body;
39
+ handleEvents(body, counter, filePath);
40
+ handleStyles(body, counter, filePath);
41
+ handleAttr(body, counter, filePath);
42
+ handleModels(body, counter, filePath);
43
+ handleIfStatement(body, counter, filePath);
44
+ handleForStatement(body, counter, filePath);
45
+ handleShowStatement(body, counter, filePath);
46
+ const comps = handleCompPlaceholder(body, counter, filePath);
47
+
48
+ content = body.innerHTML;
49
+
50
+ // #2 (escape-by-default): at this point every literal `{expr}` left in the markup is a USER value
51
+ // interpolation (text like `{props.todo.text}` or a simple attribute like `id="todo-{x.id}"`).
52
+ // Control-flow interpolations were emitted with RAW_OPEN/RAW_CLOSE sentinels instead of braces,
53
+ // and nested function-body / object-literal braces are entity-encoded as `<-olum->`, so neither
54
+ // appears as a literal `{` here. Wrapping each remaining `{expr}` in `olum.esc(...)` therefore
55
+ // escapes user-facing output (preventing XSS and "special characters break the page" bugs) while
56
+ // leaving structural code untouched. `[^{}]+` keeps each match to a single, non-nested pair.
57
+ content = content.replace(/\{([^{}]+)\}/g, (match, expr) => expr.trim() === "children" ? "${children}" : "${olum.esc(" + expr + ")}");
58
+
59
+ content = content.replace(/&amp;/g, "&"); // fix entity
60
+ content = content.replace(/=&gt;/g, "=>"); // preserve arrow functions
61
+ content = content.replace(/&lt;-olum-&gt;|&amp;lt;-olum-&amp;gt;/g, "{"); // fix curly braces sign
62
+
63
+ // #2: structural (compiler-generated) interpolations produce raw HTML, so emit them as plain
64
+ // `${...}` WITHOUT esc(). Done after the escape pass so user braces are already handled.
65
+ content = content.split(RAW_OPEN).join("${").split(RAW_CLOSE).join("}");
66
+ // todo check if var html is empty string then return nothing for better performance
67
+ // return "__template__() {\n var html = `\n" + content.trim() + "`;\nvar data = olum.lifeCycle.temp(this, html);\nolum.handelEvents(data.$wrapper,this);\nreturn data;\n},";
68
+ return {html: content.trim(), comps, anonHandlers};
69
+ }
70
+
71
+ module.exports = htmlparser;
package/lib/if.js ADDED
@@ -0,0 +1,65 @@
1
+ const { getLineInfo } = require("./lineCounter");
2
+ const { RAW_OPEN, RAW_CLOSE } = require("./tokens");
3
+
4
+ function hasElseIfOrElse(node) {
5
+ const nextNode = node.nextElementSibling;
6
+ if (nextNode && (nextNode.nodeName === "ELSE-IF" || nextNode.nodeName === "ELSE")) {
7
+ return nextNode;
8
+ }
9
+ return false;
10
+ }
11
+
12
+ function handleIfStatement(body, counter, filePath) {
13
+ const ifElms = new Array().slice.call(body.querySelectorAll("if")).reverse(); // we must reverse to start with the very deep if tag which doesn't have nested if tags inside it
14
+ ifElms.forEach(item => {
15
+ // console.log(item.outerHTML + "\n----------");
16
+ if (item.hasAttribute("when")) {
17
+ const condition = item.getAttribute("when").replace(/^\{|\}$/g, "");
18
+
19
+ // start: store if statement value in olum tag
20
+ const olums = item.querySelectorAll("olum");
21
+ // Structural interpolation -> RAW_OPEN/RAW_CLOSE so #2's escape pass leaves it raw (it yields
22
+ // the JSON "true"/"false" the runtime reads from the `if` attribute, not user-facing text).
23
+ olums.forEach(olum => olum.setAttribute("if","-[[-"+ RAW_OPEN +"JSON.stringify(!!"+ condition + ")"+ RAW_CLOSE +"-]]-")); // convert condition value to truthy/falsy value
24
+ // end: store if statement value in olum tag
25
+
26
+ const innerContent = item.innerHTML;
27
+
28
+ if (hasElseIfOrElse(item)) {
29
+ const toBeRemovedArr = [];
30
+ let nodesArr = [{ content: innerContent, when: condition }];
31
+ function recursive(item) {
32
+ const node = hasElseIfOrElse(item);
33
+ nodesArr.push({ content: node.innerHTML, when: (node.getAttribute("when") || "").replace(/^\{|\}$/g, "") });
34
+ toBeRemovedArr.push(node);
35
+ if (hasElseIfOrElse(node)) recursive(node);
36
+ }
37
+ recursive(item);
38
+ // console.log(nodesArr);
39
+ // RAW_OPEN/RAW_CLOSE mark the structural interpolation braces so #2's escape pass keeps the
40
+ // ternary raw (its branches return HTML). User braces inside each branch are still escaped.
41
+ let ternaryOperator = RAW_OPEN;
42
+ nodesArr.forEach((node, index) => {
43
+ if (index === nodesArr.length - 1) {
44
+ if (node.when) ternaryOperator += node.when + "?`" + node.content + "`:''" + RAW_CLOSE;
45
+ else ternaryOperator += "`" + node.content + "`" + RAW_CLOSE;
46
+ } else {
47
+ ternaryOperator += node.when + "?`" + node.content + "`:";
48
+ }
49
+ });
50
+ // console.log(ternaryOperator);
51
+ item.insertAdjacentHTML("beforebegin", ternaryOperator);
52
+ toBeRemovedArr.forEach(item => item.remove());
53
+ } else {
54
+ // RAW_OPEN/RAW_CLOSE: structural ternary (raw HTML); user braces in innerContent stay escaped.
55
+ item.insertAdjacentHTML("beforebegin", RAW_OPEN + condition + "?" + "`" + innerContent + "`" + ":''" + RAW_CLOSE);
56
+ }
57
+ item.remove();
58
+ } else {
59
+ const msg = "Missing 'when' attribute:";
60
+ getLineInfo(counter, item, filePath, msg);
61
+ }
62
+ });
63
+ }
64
+
65
+ module.exports = handleIfStatement;
@@ -0,0 +1,31 @@
1
+ const { script, exportDefault } = require("./regex");
2
+ const jsdom = require("jsdom");
3
+
4
+ const clean = require("./clean");
5
+ function jsParser(str) {
6
+ str = clean(str);
7
+ const arr = str.match(script);
8
+ let content = Array.isArray(arr) && arr.length ? arr[0] : "";
9
+
10
+ // fill empty logic to make component works if there is no script tag
11
+ // if (content === "") return `__isInitial__: true,\n__render__(obj, prop) { olum.lifeCycle.render(obj, prop); },\n};`;
12
+
13
+ // handle script tag attributes
14
+ const attrsObj = {};
15
+ if(content !== "") {
16
+ const dom = new jsdom.JSDOM(content).window.document;
17
+ const scriptElm = dom.querySelector("script");
18
+ const attrs = scriptElm.getAttributeNames();
19
+ if (attrs.length) attrs.forEach(key =>attrsObj[key] = scriptElm.getAttribute(key))
20
+ // console.warn(attrsObj);
21
+ }
22
+
23
+ content = content.replace(/(<script.*>)/, "");
24
+ content = content.replace(/(<\/script>)$/, "");
25
+ // content = content.replace(exportDefault, "").trim();
26
+ // return "__isInitial__: true,\n__render__(obj, prop) { olum.lifeCycle.render(obj, prop); },\n" + content;
27
+ content = content.replace(/const state/g, "var state"); // todo make this solid
28
+ return {js: content, jsAttrs: attrsObj};
29
+ }
30
+
31
+ module.exports = jsParser;