olum-compiler 1.0.1 → 1.1.6
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.
- package/bin/copySrc.js +7 -34
- package/bin/server.js +1 -0
- package/lib/boolAttr.js +27 -0
- package/lib/coreLibs.js +14 -0
- package/lib/cssParser.js +20 -1
- package/lib/events.js +36 -3
- package/lib/helpers.js +76 -73
- package/lib/htmlParser.js +10 -4
- package/lib/importMap.js +106 -0
- package/lib/parser.js +6 -10
- package/lib/placeholder.js +15 -5
- package/lib/toJs.js +2 -0
- package/package.json +1 -1
- package/tests/compiler.test.js +152 -4
package/bin/copySrc.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// todo check changed files only to be copied, use this project https://github.com/eissapk/diff
|
|
2
2
|
const path = require("path");
|
|
3
3
|
const fs = require("fs");
|
|
4
|
-
const { copy, remove,
|
|
4
|
+
const { copy, remove, compileRoutes } = require("../lib/helpers");
|
|
5
|
+
const importMap = require("../lib/importMap");
|
|
5
6
|
const entryPoint = path.resolve(process.cwd(), "src").replace(/\/module/, "");
|
|
6
7
|
const entryPoint2 = path.resolve(process.cwd(), "public").replace(/\/module/, "");
|
|
7
8
|
|
|
@@ -13,45 +14,17 @@ module.exports = function copySrc() {
|
|
|
13
14
|
if (fs.existsSync(path.resolve(__dirname, "../src"))) remove(path.resolve(__dirname, "../src"));
|
|
14
15
|
// copy
|
|
15
16
|
copy(entryPoint, path.resolve(__dirname, "../src"), () => {
|
|
16
|
-
|
|
17
|
-
// const mainJsPath = path.resolve(__dirname, "../src/main.js");
|
|
18
|
-
// if (fs.existsSync(mainJsPath)) {
|
|
19
|
-
// let mainJsContent = fs.readFileSync(mainJsPath).toString();
|
|
20
|
-
// mainJsContent = rewriteImports(mainJsContent);
|
|
21
|
-
// fs.writeFileSync(mainJsPath, mainJsContent);
|
|
22
|
-
// }
|
|
23
|
-
|
|
24
|
-
// clean routes
|
|
25
|
-
let routes = ls(entryPoint, { absolute: true });
|
|
26
|
-
routes = routes.filter((item) => {
|
|
27
|
-
const extension = path.extname(item);
|
|
28
|
-
const isDir = fs.lstatSync(item).isDirectory();
|
|
29
|
-
const isHtml = fs.lstatSync(item).isFile() && extension == ".html";
|
|
30
|
-
if (isDir || isHtml && !item.includes("components")) return item;
|
|
31
|
-
});
|
|
32
|
-
// generate routes manifest
|
|
33
|
-
const manifest = generateRouteManifest(routes, entryPoint);
|
|
34
|
-
let has404Page = false;
|
|
35
|
-
if (manifest['not-found']) has404Page = true;
|
|
36
|
-
const libImports = `import Olum from "/node_modules/olum/dist/olum.js";\nimport Router from "/node_modules/olum-router/dist/router.js";`;
|
|
37
|
-
// const libImports = `import Olum from "../core/olum.js";\nimport Router from "../core/router.js";`; // for testing
|
|
38
|
-
const imports = generateImports(manifest).replace(/.html/g, ".js"); // fix extension by replacing .html with .js since components are js modules
|
|
39
|
-
const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
|
|
40
|
-
routes = generateRoutes(manifest);
|
|
41
|
-
// console.log(libImports);
|
|
42
|
-
// console.log(imports);
|
|
43
|
-
// console.log(routes);
|
|
44
|
-
// console.log(config);
|
|
45
|
-
|
|
17
|
+
const mainJsContent = compileRoutes(entryPoint);
|
|
46
18
|
// automated main.js -- new concept
|
|
47
19
|
const mainJsPath = path.resolve(__dirname, "../src/main.js");
|
|
48
|
-
fs.writeFileSync(mainJsPath,
|
|
20
|
+
fs.writeFileSync(mainJsPath, mainJsContent);
|
|
49
21
|
});
|
|
50
22
|
copy(entryPoint2, path.resolve(__dirname, "../public"), () => {
|
|
51
23
|
const indexHtmlPath = path.resolve(__dirname, "../public/index.html");
|
|
52
24
|
let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
|
|
53
|
-
// auto bind div#app placeholder and mainjs script to index.html
|
|
54
|
-
|
|
25
|
+
// auto bind div#app placeholder, import map and mainjs script to index.html
|
|
26
|
+
// (import map must precede the module script so bare imports resolve)
|
|
27
|
+
indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n${importMap(entryPoint)}\n<script defer type="module" src="../src/main.js"></script>\n</body>`);
|
|
55
28
|
fs.writeFileSync(indexHtmlPath, indexHtmlContent);
|
|
56
29
|
});
|
|
57
30
|
resolve();
|
package/bin/server.js
CHANGED
|
@@ -23,6 +23,7 @@ function getPath(entry, url) {
|
|
|
23
23
|
path.resolve(entry, candidate),
|
|
24
24
|
path.resolve(entry, "../", candidate),
|
|
25
25
|
path.resolve(process.cwd(), candidate),
|
|
26
|
+
path.resolve(entry, "../../", candidate), // project root — app deps (/node_modules/*) install there
|
|
26
27
|
].find(p => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
|
|
27
28
|
|
|
28
29
|
// Exact match first (preserves the original behaviour).
|
package/lib/boolAttr.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const { RAW_OPEN, RAW_CLOSE } = require("./tokens");
|
|
2
|
+
|
|
3
|
+
// Boolean attributes are truthy by PRESENCE: the browser treats checked="false" as checked and
|
|
4
|
+
// disabled="false" as disabled. So value interpolation (checked="${olum.esc(expr)}") can never
|
|
5
|
+
// turn them off. For these attributes, attr="{expr}" compiles to a conditional that emits the
|
|
6
|
+
// bare attribute name or nothing at all: ${(expr) ? "checked" : ""}.
|
|
7
|
+
//
|
|
8
|
+
// Runs on the serialized markup string, BEFORE the generic {expr} escape pass (which would
|
|
9
|
+
// otherwise claim these braces) and emitted with RAW sentinels so the code is not esc-wrapped.
|
|
10
|
+
// Only fires when the ENTIRE value is a single {expr}; mixed values (checked="a {b}") are
|
|
11
|
+
// meaningless for boolean attributes and fall through to the generic pass. Component props are
|
|
12
|
+
// already packed into data-o-props by placeholder() and can't match here.
|
|
13
|
+
const BOOL_ATTRS = [
|
|
14
|
+
"checked", "disabled", "selected", "readonly", "required", "hidden",
|
|
15
|
+
"autofocus", "multiple", "open", "loop", "muted", "controls", "autoplay",
|
|
16
|
+
"novalidate", "default", "defer", "ismap", "reversed",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const boolAttrRegex = new RegExp("(\\s)(" + BOOL_ATTRS.join("|") + ")=([\"'])\\{([^{}]+)\\}\\3", "gi");
|
|
20
|
+
|
|
21
|
+
function handleBoolAttrs(content) {
|
|
22
|
+
return content.replace(boolAttrRegex, (match, ws, name, quote, expr) => {
|
|
23
|
+
return ws + RAW_OPEN + "(" + expr.trim() + ') ? "' + name.toLowerCase() + '" : ""' + RAW_CLOSE;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = handleBoolAttrs;
|
package/lib/coreLibs.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// single switch for where the framework runtime loads from:
|
|
2
|
+
// true -> the local copies in module/core, served at /core by the dev server (framework development)
|
|
3
|
+
// false -> the published npm packages ("olum", "olum-router") installed at the project root
|
|
4
|
+
// both the generated main.js (helpers.js compileRoutes) and the import map (importMap.js)
|
|
5
|
+
// read this flag — they must agree, otherwise two runtime copies load and fight over window.olum
|
|
6
|
+
const useLocalCore = process?.env?.LOCAL_CORE == 'true';
|
|
7
|
+
|
|
8
|
+
// import-map entries for the local mode
|
|
9
|
+
const localLibs = {
|
|
10
|
+
olum: "/core/olum.js",
|
|
11
|
+
"olum-router": "/core/router.js",
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
module.exports = { useLocalCore, localLibs };
|
package/lib/cssParser.js
CHANGED
|
@@ -49,7 +49,26 @@ function scopeCSS(css, scopeAttr, compName) {
|
|
|
49
49
|
s = s.trim();
|
|
50
50
|
if (!s) return "";
|
|
51
51
|
if (/^(:root|html|body)\b/.test(s)) return s;
|
|
52
|
-
|
|
52
|
+
// attach the scope attr to the selector's last compound (p:hover -> p[data-o-x]:hover),
|
|
53
|
+
// not as a descendant combinator — a descendant rule would also match nested components'
|
|
54
|
+
// elements, which sit inside this component's DOM but carry their own scope attr
|
|
55
|
+
let depth = 0, start = 0;
|
|
56
|
+
for (let j = 0; j < s.length; j++) {
|
|
57
|
+
const c = s[j];
|
|
58
|
+
if (c === "(" || c === "[") depth++;
|
|
59
|
+
else if (c === ")" || c === "]") depth--;
|
|
60
|
+
else if (depth === 0 && (c === " " || c === ">" || c === "+" || c === "~")) start = j + 1;
|
|
61
|
+
}
|
|
62
|
+
const compound = s.slice(start);
|
|
63
|
+
let k = 0;
|
|
64
|
+
depth = 0;
|
|
65
|
+
for (; k < compound.length; k++) {
|
|
66
|
+
const c = compound[k];
|
|
67
|
+
if (c === "(" || c === "[") depth++;
|
|
68
|
+
else if (c === ")" || c === "]") depth--;
|
|
69
|
+
else if (c === ":" && depth === 0) break;
|
|
70
|
+
}
|
|
71
|
+
return s.slice(0, start) + compound.slice(0, k) + scope + compound.slice(k);
|
|
53
72
|
}).filter(Boolean).join(", ");
|
|
54
73
|
}
|
|
55
74
|
|
package/lib/events.js
CHANGED
|
@@ -27,7 +27,39 @@ function isSimpleCallList(str) {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
// True when the expression references a name destructured from props() — e.g.
|
|
31
|
+
// `const { onclick } = props()` + onclick="onclick()". Such a call CAN'T go through the
|
|
32
|
+
// data-o-event chain (the runtime resolves chain names against methodsRef, and a destructured
|
|
33
|
+
// prop isn't a method), so the caller wraps it in an anon handler whose closure holds the prop.
|
|
34
|
+
function referencesPropsAlias(str, propsAliases) {
|
|
35
|
+
const names = propsAliases ? Object.keys(propsAliases) : [];
|
|
36
|
+
if (!names.length) return false;
|
|
37
|
+
try {
|
|
38
|
+
const acorn = require("acorn");
|
|
39
|
+
const node = acorn.parseExpressionAt(str, 0, { ecmaVersion: "latest" });
|
|
40
|
+
let found = false;
|
|
41
|
+
(function walk(n, parent, key) {
|
|
42
|
+
if (found || !n || typeof n.type !== "string") return;
|
|
43
|
+
if (n.type === "Identifier" && names.includes(n.name)) {
|
|
44
|
+
// skip non-value positions: obj.onclick (member property) / { onclick: x } (literal key)
|
|
45
|
+
const isStaticProp =
|
|
46
|
+
parent && !parent.computed && ((parent.type === "MemberExpression" && key === "property") || (parent.type === "Property" && key === "key"));
|
|
47
|
+
if (!isStaticProp) found = true;
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
for (const k of Object.keys(n)) {
|
|
51
|
+
const v = n[k];
|
|
52
|
+
if (Array.isArray(v)) v.forEach((item) => item && typeof item === "object" && walk(item, n, k));
|
|
53
|
+
else if (v && typeof v === "object") walk(v, n, k);
|
|
54
|
+
}
|
|
55
|
+
})(node, null, null);
|
|
56
|
+
return found;
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
|
|
31
63
|
let name = path.basename(filePath).replace(/\.html/i, "");
|
|
32
64
|
name = name.slice(0, 1).toLowerCase() + name.slice(1); // make compName camel case
|
|
33
65
|
|
|
@@ -42,9 +74,10 @@ function handleEvents(body, counter, filePath, anonHandlers) {
|
|
|
42
74
|
const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
|
|
43
75
|
if (anonHandlers) anonHandlers.push(`const ${handlerName} = ${attrValue};`);
|
|
44
76
|
attrValue = handlerName + "($event)";
|
|
45
|
-
} else if (!isSimpleCallList(attrValue)) {
|
|
77
|
+
} else if (!isSimpleCallList(attrValue) || referencesPropsAlias(attrValue, propsAliases)) {
|
|
46
78
|
// not a plain `name(args)` call list — e.g. a function prop call props().toggle(id)
|
|
47
|
-
// or a statement like state.count++ —
|
|
79
|
+
// or a statement like state.count++ — OR a call touching a destructured prop
|
|
80
|
+
// (onclick="onclick()") — wrap the whole expression in an anon handler
|
|
48
81
|
// so it executes as-is in component scope ($event = the DOM event)
|
|
49
82
|
const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
|
|
50
83
|
if (anonHandlers) anonHandlers.push(`const ${handlerName} = ($event) => { ${attrValue} };`);
|
package/lib/helpers.js
CHANGED
|
@@ -18,6 +18,24 @@ const stringToBase64 = (str) => Buffer.from(str).toString('base64');
|
|
|
18
18
|
const base64ToString = (base64) => Buffer.from(base64, 'base64').toString('ascii');
|
|
19
19
|
const acorn = require("acorn");
|
|
20
20
|
|
|
21
|
+
const cleanParentheses = (filePath, type="name") => {
|
|
22
|
+
if (type == "name") {
|
|
23
|
+
return filePath.replace(/\([^)]*\)/g, "")
|
|
24
|
+
} else if (type == "url"){ // clean slash after it also e.g. (main)/
|
|
25
|
+
return filePath.replace(/\([^)]*\)\//g, "")
|
|
26
|
+
}
|
|
27
|
+
return filePath;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const cleanNumbersPrefix = (name, type = "name") => {
|
|
31
|
+
if (type === "url") {
|
|
32
|
+
// only the NN- ordering prefix at a segment start — a blanket digit strip would
|
|
33
|
+
// corrupt legit digit segments ("/404" -> "/", "/7guis" -> "/guis")
|
|
34
|
+
return name.replace(/(^|\/)\d+-/g, "$1");
|
|
35
|
+
}
|
|
36
|
+
return name.replace(/\d+-?/g, "");
|
|
37
|
+
}
|
|
38
|
+
|
|
21
39
|
function isUpper(char) {
|
|
22
40
|
const upperChar = char.toUpperCase();
|
|
23
41
|
const regex = new RegExp(upperChar);
|
|
@@ -393,6 +411,33 @@ function getGlobalMethods(str) {
|
|
|
393
411
|
.filter((item) => item);
|
|
394
412
|
}
|
|
395
413
|
|
|
414
|
+
// top-level bindings destructured from props(): const { onMessage, onSave: save } = props()
|
|
415
|
+
// returns a localName -> propKey map so placeholder.js can flag bare-identifier prop forwards
|
|
416
|
+
// (onMessage="{onMessage}") as kind "props" src entries — functions can't cross the JSON channel
|
|
417
|
+
function getPropsAliases(str) {
|
|
418
|
+
const aliases = {};
|
|
419
|
+
acorn.parse(str, { ecmaVersion: "latest", sourceType: "module" }).body.forEach((obj) => {
|
|
420
|
+
if (obj.type !== "VariableDeclaration" || !Array.isArray(obj.declarations)) return;
|
|
421
|
+
obj.declarations.forEach((decl) => {
|
|
422
|
+
if (
|
|
423
|
+
decl.id &&
|
|
424
|
+
decl.id.type === "ObjectPattern" &&
|
|
425
|
+
decl.init &&
|
|
426
|
+
decl.init.type === "CallExpression" &&
|
|
427
|
+
decl.init.callee &&
|
|
428
|
+
decl.init.callee.name === "props"
|
|
429
|
+
) {
|
|
430
|
+
decl.id.properties.forEach((prop) => {
|
|
431
|
+
if (prop.type === "Property" && prop.key && prop.key.name && prop.value && prop.value.type === "Identifier") {
|
|
432
|
+
aliases[prop.value.name] = prop.key.name; // localName -> original prop key (handles renames)
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
});
|
|
438
|
+
return aliases;
|
|
439
|
+
}
|
|
440
|
+
|
|
396
441
|
// get props names
|
|
397
442
|
function getGlobalProps(str) {
|
|
398
443
|
return acorn
|
|
@@ -486,64 +531,6 @@ function minifyJS(src) {
|
|
|
486
531
|
return out;
|
|
487
532
|
}
|
|
488
533
|
|
|
489
|
-
function resolvePackage(pkgName) {
|
|
490
|
-
const pkgJsonPath = path.join(
|
|
491
|
-
process.cwd(),
|
|
492
|
-
"node_modules",
|
|
493
|
-
pkgName,
|
|
494
|
-
"package.json"
|
|
495
|
-
);
|
|
496
|
-
|
|
497
|
-
if (!fs.existsSync(pkgJsonPath)) {
|
|
498
|
-
throw new Error(`Package "${pkgName}" not found`);
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
const pkg = JSON.parse(
|
|
502
|
-
fs.readFileSync(pkgJsonPath, "utf8")
|
|
503
|
-
);
|
|
504
|
-
|
|
505
|
-
let entry;
|
|
506
|
-
|
|
507
|
-
if (typeof pkg.exports === "string") {
|
|
508
|
-
entry = pkg.exports;
|
|
509
|
-
} else if (pkg.exports?.["."]?.import) {
|
|
510
|
-
entry = pkg.exports["."].import;
|
|
511
|
-
} else if (pkg.exports?.["."]?.default) {
|
|
512
|
-
entry = pkg.exports["."].default;
|
|
513
|
-
} else if (typeof pkg.exports?.["."] === "string") {
|
|
514
|
-
entry = pkg.exports["."];
|
|
515
|
-
} else {
|
|
516
|
-
entry = pkg.module || pkg.main || "index.js";
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
entry = entry.replace(/^\.?\//, "");
|
|
520
|
-
|
|
521
|
-
return `/node_modules/${pkgName}/${entry}`;
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
function rewriteImports(code) {
|
|
525
|
-
return code.replace(
|
|
526
|
-
/from\s+["']([^"']+)["']/g,
|
|
527
|
-
(match, specifier) => {
|
|
528
|
-
if (
|
|
529
|
-
specifier.startsWith(".") ||
|
|
530
|
-
specifier.startsWith("/") ||
|
|
531
|
-
specifier.startsWith("http:")
|
|
532
|
-
|| specifier.startsWith("https:")
|
|
533
|
-
) {
|
|
534
|
-
return match;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
try {
|
|
538
|
-
return `from "${resolvePackage(specifier)}"`;
|
|
539
|
-
} catch (err) {
|
|
540
|
-
console.warn(err.message);
|
|
541
|
-
return match;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
);
|
|
545
|
-
}
|
|
546
|
-
|
|
547
534
|
// handle routing based on files
|
|
548
535
|
function generateRouteManifest(paths, rootDir) {
|
|
549
536
|
const routes = {};
|
|
@@ -565,9 +552,10 @@ function generateRouteManifest(paths, rootDir) {
|
|
|
565
552
|
}
|
|
566
553
|
|
|
567
554
|
// Remove "/page.html" or "page.html"
|
|
568
|
-
|
|
555
|
+
let routePath = relative
|
|
569
556
|
.replace(/\/page\.html$/, "")
|
|
570
557
|
.replace(/^page\.html$/, "");
|
|
558
|
+
routePath = cleanParentheses(routePath, "url")
|
|
571
559
|
|
|
572
560
|
const segments = routePath
|
|
573
561
|
.split("/")
|
|
@@ -598,6 +586,7 @@ function generateRouteManifest(paths, rootDir) {
|
|
|
598
586
|
}
|
|
599
587
|
|
|
600
588
|
function toComponentName(file) {
|
|
589
|
+
file = cleanParentheses(file, "name");
|
|
601
590
|
if (file === "page.html") return "App";
|
|
602
591
|
if (file === "not-found.html") return "NotFound";
|
|
603
592
|
|
|
@@ -621,8 +610,8 @@ function toComponentName(file) {
|
|
|
621
610
|
function generateImports(manifest) {
|
|
622
611
|
return Object.values(manifest)
|
|
623
612
|
.map(({ page }) => {
|
|
624
|
-
const component = toComponentName(page);
|
|
625
|
-
return `import ${component} from "./${page}";`;
|
|
613
|
+
const component = cleanNumbersPrefix(toComponentName(page));
|
|
614
|
+
return `import ${component} from "./${page.replace(/.html$/, ".js")}";`;
|
|
626
615
|
})
|
|
627
616
|
.join("\n");
|
|
628
617
|
}
|
|
@@ -658,20 +647,34 @@ function generateRoutes(manifest) {
|
|
|
658
647
|
|
|
659
648
|
return `export const routes = [
|
|
660
649
|
${routes
|
|
661
|
-
.map(({ path, comp }) => ` { path: "${path}", comp: ${comp} }`)
|
|
650
|
+
.map(({ path, comp }) => ` { path: "${cleanNumbersPrefix(path, "url")}", comp: ${cleanNumbersPrefix(comp)} }`)
|
|
662
651
|
.join(",\n")}
|
|
663
652
|
];`;
|
|
664
653
|
}
|
|
665
654
|
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
655
|
+
const compileRoutes = (entryPoint) => {
|
|
656
|
+
let routes = ls(entryPoint, { absolute: true });
|
|
657
|
+
routes = routes.filter((item) => {
|
|
658
|
+
const extension = path.extname(item);
|
|
659
|
+
const isDir = fs.lstatSync(item).isDirectory();
|
|
660
|
+
const isHtml = fs.lstatSync(item).isFile() && extension == ".html";
|
|
661
|
+
const segments = path.relative(entryPoint, item).split(path.sep);
|
|
662
|
+
const inExcludedDir = segments.some((seg) => ["components", "utils"].includes(seg) || seg.startsWith("_"));
|
|
663
|
+
if (isDir || (isHtml && !inExcludedDir)) return item;
|
|
664
|
+
});
|
|
665
|
+
// generate routes manifest
|
|
666
|
+
const manifest = generateRouteManifest(routes, entryPoint);
|
|
667
|
+
let has404Page = false;
|
|
668
|
+
if (manifest['not-found']) has404Page = true;
|
|
669
|
+
const libImports = `import Olum from "olum";\nimport Router from "olum-router";`;
|
|
670
|
+
const imports = generateImports(manifest)
|
|
671
|
+
const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
|
|
672
|
+
routes = generateRoutes(manifest);
|
|
673
|
+
// console.log(libImports);
|
|
674
|
+
// console.log(imports);
|
|
675
|
+
// console.log(routes);
|
|
676
|
+
// console.log(config);
|
|
677
|
+
return `${libImports}\n${imports}\n${routes}\n${config}`;
|
|
675
678
|
}
|
|
676
679
|
|
|
677
680
|
module.exports.isNum = isNum;
|
|
@@ -693,10 +696,10 @@ module.exports.stringToBase64 = stringToBase64;
|
|
|
693
696
|
module.exports.base64ToString = base64ToString;
|
|
694
697
|
module.exports.createScopeHandler = createScopeHandler;
|
|
695
698
|
module.exports.getGlobalMethods = getGlobalMethods;
|
|
699
|
+
module.exports.getPropsAliases = getPropsAliases;
|
|
696
700
|
module.exports.getGlobalProps = getGlobalProps;
|
|
697
701
|
module.exports.minifyJS = minifyJS;
|
|
698
|
-
module.exports.rewriteImports = rewriteImports;
|
|
699
702
|
module.exports.generateRouteManifest = generateRouteManifest;
|
|
700
703
|
module.exports.generateImports = generateImports;
|
|
701
704
|
module.exports.generateRoutes = generateRoutes;
|
|
702
|
-
module.exports.
|
|
705
|
+
module.exports.compileRoutes = compileRoutes;
|
package/lib/htmlParser.js
CHANGED
|
@@ -11,13 +11,14 @@ const handleEvents = require("./events");
|
|
|
11
11
|
// const handleAttr = require("./attr");
|
|
12
12
|
const handleCompPlaceholder = require("./compPlaceholder");
|
|
13
13
|
const handleHtml = require("./html");
|
|
14
|
+
const handleBoolAttrs = require("./boolAttr");
|
|
14
15
|
const { RAW_OPEN, RAW_CLOSE, LT, GT } = require("./tokens");
|
|
15
16
|
|
|
16
|
-
function htmlparser(str, counter, filePath, parentMethods) {
|
|
17
|
+
function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
|
|
17
18
|
let content = str.replace(script, "").replace(style, "");
|
|
18
19
|
content = clean(content); // clean html comments to avoid runtime errors
|
|
19
|
-
content = placeholder(content, selfClosingTag, "self", parentMethods);
|
|
20
|
-
content = placeholder(content, normalTag, "normal", parentMethods);
|
|
20
|
+
content = placeholder(content, selfClosingTag, "self", parentMethods, propsAliases);
|
|
21
|
+
content = placeholder(content, normalTag, "normal", parentMethods, propsAliases);
|
|
21
22
|
|
|
22
23
|
// Inline arrow/function event handlers (oninput="(e)=> expr") are extracted into named
|
|
23
24
|
// __olumAnon_ methods inside handleEvents (collected here, injected into the component JS later).
|
|
@@ -26,7 +27,7 @@ function htmlparser(str, counter, filePath, parentMethods) {
|
|
|
26
27
|
// using dom parser
|
|
27
28
|
const body = new jsdom.JSDOM(content).window.document.body;
|
|
28
29
|
handleHtml(body); // html="expr" -> unescaped ${expr} content (before control-flow dissolves elements)
|
|
29
|
-
handleEvents(body, counter, filePath, anonHandlers);
|
|
30
|
+
handleEvents(body, counter, filePath, anonHandlers, propsAliases);
|
|
30
31
|
// DISABLED — :style object binding. Colon attributes are gone; use a string style with
|
|
31
32
|
// {expr} interpolation instead, e.g. style="color:{state.color}". Uncomment to re-enable.
|
|
32
33
|
// handleStyles(body, counter, filePath);
|
|
@@ -41,6 +42,11 @@ function htmlparser(str, counter, filePath, parentMethods) {
|
|
|
41
42
|
|
|
42
43
|
content = body.innerHTML;
|
|
43
44
|
|
|
45
|
+
// presence-based boolean attributes: checked="{expr}" -> ${(expr) ? "checked" : ""}.
|
|
46
|
+
// Must run before the {expr} escape pass below, which would otherwise interpolate the VALUE
|
|
47
|
+
// (checked="false" is still checked — the browser only checks attribute presence).
|
|
48
|
+
content = handleBoolAttrs(content);
|
|
49
|
+
|
|
44
50
|
// #2 (escape-by-default): at this point every literal `{expr}` left in the markup is a USER value
|
|
45
51
|
// interpolation (text like `{props.todo.text}` or a simple attribute like `id="todo-{x.id}"`).
|
|
46
52
|
// Control-flow interpolations were emitted with RAW_OPEN/RAW_CLOSE sentinels instead of braces,
|
package/lib/importMap.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const fs = require("fs");
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const colors = require("./colors");
|
|
4
|
+
const { ls, isFile } = require("./helpers");
|
|
5
|
+
|
|
6
|
+
const { useLocalCore, localLibs } = require("./coreLibs"); // shared flag — keeps main.js and the import map on the same runtime copy
|
|
7
|
+
|
|
8
|
+
// pick the browser-usable file from a package.json "exports" condition tree
|
|
9
|
+
function pickEntry(exp) {
|
|
10
|
+
if (typeof exp === "string") return exp;
|
|
11
|
+
if (Array.isArray(exp)) {
|
|
12
|
+
for (const item of exp) {
|
|
13
|
+
const found = pickEntry(item);
|
|
14
|
+
if (found) return found;
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
if (exp && typeof exp === "object") {
|
|
19
|
+
for (const key of ["browser", "import", "module", "default"]) {
|
|
20
|
+
if (exp[key]) {
|
|
21
|
+
const found = pickEntry(exp[key]);
|
|
22
|
+
if (found) return found;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function resolvePackage(rootDir, pkgName) {
|
|
30
|
+
const pkgJsonPath = path.join(rootDir, "node_modules", pkgName, "package.json");
|
|
31
|
+
if (!fs.existsSync(pkgJsonPath)) return null;
|
|
32
|
+
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8"));
|
|
33
|
+
let exp = pkg.exports;
|
|
34
|
+
// subpath map ("." keys) vs plain condition object — take the root subpath
|
|
35
|
+
if (exp && typeof exp === "object" && !Array.isArray(exp)) {
|
|
36
|
+
const keys = Object.keys(exp);
|
|
37
|
+
if (keys.some((k) => k.startsWith("."))) exp = exp["."];
|
|
38
|
+
}
|
|
39
|
+
let entry = pickEntry(exp) || pkg.module || pkg.main || "index.js";
|
|
40
|
+
entry = entry.replace(/^\.?\//, "");
|
|
41
|
+
return "/node_modules/" + pkgName + "/" + entry;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// collect bare specifiers used in src: from "pkg" | import "pkg" | import("pkg")
|
|
45
|
+
function getBareSpecifiers(srcDir) {
|
|
46
|
+
const specifiers = new Set();
|
|
47
|
+
const files = ls(srcDir, { absolute: true }).filter((p) => isFile(p) && /\.(html|js)$/i.test(p));
|
|
48
|
+
const regex = /(?:from\s+|import\s+|import\s*\(\s*)["']([^"'\n]+)["']/g;
|
|
49
|
+
files.forEach((file) => {
|
|
50
|
+
const content = fs.readFileSync(file, "utf8");
|
|
51
|
+
let match;
|
|
52
|
+
while ((match = regex.exec(content))) {
|
|
53
|
+
const spec = match[1];
|
|
54
|
+
if (spec.startsWith(".") || spec.startsWith("/") || /^https?:/.test(spec)) continue;
|
|
55
|
+
specifiers.add(spec);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
return [...specifiers];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function toPkgName(specifier) {
|
|
62
|
+
const segments = specifier.split("/");
|
|
63
|
+
return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Build the <script type="importmap"> tag injected into index.html so bare imports
|
|
68
|
+
* (e.g. import { marked } from "marked") resolve in the browser without a bundler.
|
|
69
|
+
* App deps install at the project root (rootDir = srcDir/..); framework libs map to /core.
|
|
70
|
+
* @param {*} srcDir absolute path of the project's src directory
|
|
71
|
+
*/
|
|
72
|
+
function importMap(srcDir) {
|
|
73
|
+
const rootDir = path.resolve(srcDir, "..");
|
|
74
|
+
const imports = {};
|
|
75
|
+
|
|
76
|
+
// handle internal libs
|
|
77
|
+
if (useLocalCore) {
|
|
78
|
+
Object.assign(imports, localLibs);
|
|
79
|
+
} else {
|
|
80
|
+
// npm mode: the framework resolves like any other root dependency
|
|
81
|
+
Object.keys(localLibs).forEach((pkgName) => {
|
|
82
|
+
const entry = resolvePackage(rootDir, pkgName);
|
|
83
|
+
if (!entry) {
|
|
84
|
+
console.warn(colors("yellow", 'Can\'t resolve "' + pkgName + '" — install it at the project root: npm i ' + pkgName));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
imports[pkgName] = entry;
|
|
88
|
+
imports[pkgName + "/"] = "/node_modules/" + pkgName + "/";
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
getBareSpecifiers(srcDir).forEach((spec) => {
|
|
93
|
+
const pkgName = toPkgName(spec);
|
|
94
|
+
if (pkgName in localLibs || imports[pkgName]) return;
|
|
95
|
+
const entry = resolvePackage(rootDir, pkgName);
|
|
96
|
+
if (!entry) {
|
|
97
|
+
console.warn(colors("yellow", 'Can\'t resolve "' + pkgName + '" — install it at the project root: npm i ' + pkgName));
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
imports[pkgName] = entry;
|
|
101
|
+
imports[pkgName + "/"] = "/node_modules/" + pkgName + "/"; // subpath imports e.g. "pkg/x.js"
|
|
102
|
+
});
|
|
103
|
+
return '<script type="importmap">' + JSON.stringify({ imports }, null, 2) + "</script>";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = importMap;
|
package/lib/parser.js
CHANGED
|
@@ -5,7 +5,7 @@ const jsParser = require("./jsParser");
|
|
|
5
5
|
const getImports = require("./getImports");
|
|
6
6
|
const toJs = require("./toJs");
|
|
7
7
|
const path = require("path");
|
|
8
|
-
const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps,
|
|
8
|
+
const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, getPropsAliases } = require("./helpers");
|
|
9
9
|
const createSourceMap = require("./sourcemap");
|
|
10
10
|
|
|
11
11
|
const parser = (str, counter, filePath) => {
|
|
@@ -22,8 +22,12 @@ const parser = (str, counter, filePath) => {
|
|
|
22
22
|
// can't cross the JSON data-o-props channel, so they travel via data-o-props-src kind "method"
|
|
23
23
|
let parentMethods = [];
|
|
24
24
|
try { parentMethods = getGlobalMethods(js); } catch (e) {}
|
|
25
|
+
// names destructured from props() — forwarding them (onMessage="{onMessage}") must travel via
|
|
26
|
+
// data-o-props-src kind "props" so function props survive intermediate components at any depth
|
|
27
|
+
let propsAliases = {};
|
|
28
|
+
try { propsAliases = getPropsAliases(js); } catch (e) {}
|
|
25
29
|
|
|
26
|
-
let {html, comps, anonHandlers} = htmlParser(str, counter, filePath, parentMethods); // html content and all components tags <olum></olum>
|
|
30
|
+
let {html, comps, anonHandlers} = htmlParser(str, counter, filePath, parentMethods, propsAliases); // html content and all components tags <olum></olum>
|
|
27
31
|
html = html.replace(/\"\-\[\[\-/g, "'").replace(/\-\]\]\-\"/g, "'"); // fix json in attribute issue
|
|
28
32
|
|
|
29
33
|
// Inject anonymous handler declarations so getGlobalMethods picks them up as regular methods
|
|
@@ -34,14 +38,6 @@ const parser = (str, counter, filePath) => {
|
|
|
34
38
|
if (imports) {
|
|
35
39
|
const importRegex = /(import)(\s+)?(?!from)/g;
|
|
36
40
|
imports.forEach((item) => {
|
|
37
|
-
// resolve imported libs: olum, olum-router
|
|
38
|
-
if (/from\s+(['"])olum\1/.test(item.statement)) {
|
|
39
|
-
item.statement = item.statement.replace(new RegExp(item.regex, ""), `from "${libsMap[process.env.NODE_ENV].olum}"`)
|
|
40
|
-
}
|
|
41
|
-
if (/from\s+(['"])olum-router\1/.test(item.statement)) {
|
|
42
|
-
item.statement = item.statement.replace(new RegExp(item.regex, ""), `from "${libsMap[process.env.NODE_ENV].olum}"`)
|
|
43
|
-
}
|
|
44
|
-
|
|
45
41
|
if (item.type && item.type == "noFrom") js = js.replace(new RegExp(item.regex, "gm"), "");
|
|
46
42
|
if (!item.type) js = js.replace(new RegExp(item.regex, "g"), "*/");
|
|
47
43
|
});
|
package/lib/placeholder.js
CHANGED
|
@@ -16,7 +16,7 @@ function literalExpr(raw) {
|
|
|
16
16
|
return "'" + raw.replace(/'/g, "\\'") + "'";
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
function parseProps(attrsStr, parentMethods) {
|
|
19
|
+
function parseProps(attrsStr, parentMethods, propsAliases) {
|
|
20
20
|
const entries = [];
|
|
21
21
|
const srcEntries = []; // prop-name:state-key pairs for setter write-back
|
|
22
22
|
// six alternatives in priority order (groups kept intact for easy toggling):
|
|
@@ -57,6 +57,16 @@ function parseProps(attrsStr, parentMethods) {
|
|
|
57
57
|
srcEntries.push(propName + ':method:' + bare);
|
|
58
58
|
continue;
|
|
59
59
|
}
|
|
60
|
+
// PROP FORWARD: a bare identifier destructured from props() in THIS (parent) component,
|
|
61
|
+
// e.g. `const { onMessage } = props()` + onMessage="{onMessage}". Emit both the JSON entry
|
|
62
|
+
// (carries serializable values) and a kind "props" src entry keyed by the ORIGINAL prop name
|
|
63
|
+
// — buildTree falls back to the parent's own incomingProps when JSON dropped the value
|
|
64
|
+
// (it was a function), so function props survive any nesting depth.
|
|
65
|
+
if (propsAliases && Object.prototype.hasOwnProperty.call(propsAliases, bare) && /^[A-Za-z_$][\w$]*$/.test(bare)) {
|
|
66
|
+
entries.push(propName + ': ' + bare);
|
|
67
|
+
srcEntries.push(propName + ':props:' + propsAliases[bare]);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
60
70
|
// object literal: restore {} wrappers, escaping { so htmlParser won't turn it into ${
|
|
61
71
|
const entryExpr = /^\s*\w+\s*:/.test(expr) ? ESC + expr + '}' : expr;
|
|
62
72
|
entries.push(propName + ': ' + entryExpr);
|
|
@@ -75,8 +85,8 @@ function parseProps(attrsStr, parentMethods) {
|
|
|
75
85
|
return { entries, srcEntries };
|
|
76
86
|
}
|
|
77
87
|
|
|
78
|
-
function buildPropsAttr(attrsStr, parentMethods) {
|
|
79
|
-
const { entries, srcEntries } = parseProps(attrsStr, parentMethods);
|
|
88
|
+
function buildPropsAttr(attrsStr, parentMethods, propsAliases) {
|
|
89
|
+
const { entries, srcEntries } = parseProps(attrsStr, parentMethods, propsAliases);
|
|
80
90
|
|
|
81
91
|
// emit the two attributes independently: a component may receive only function props
|
|
82
92
|
// (src entries, no JSON payload) or only data props (JSON payload, no src entries)
|
|
@@ -90,14 +100,14 @@ function buildPropsAttr(attrsStr, parentMethods) {
|
|
|
90
100
|
}
|
|
91
101
|
|
|
92
102
|
// handle components placeholders with olum tag <olum></olum>
|
|
93
|
-
function placeholder(content, regex, type, parentMethods) {
|
|
103
|
+
function placeholder(content, regex, type, parentMethods, propsAliases) {
|
|
94
104
|
return content.replace(regex, (str, $1, $2) => {
|
|
95
105
|
let data = $1.split(" ");
|
|
96
106
|
if (isFullArr(data)) {
|
|
97
107
|
let name = data[0].trim();
|
|
98
108
|
if (isUpper(name[0])) {
|
|
99
109
|
name = "name='" + name + "'";
|
|
100
|
-
const propsAttr = data.length > 1 ? buildPropsAttr(data.slice(1).join(" "), parentMethods) : "";
|
|
110
|
+
const propsAttr = data.length > 1 ? buildPropsAttr(data.slice(1).join(" "), parentMethods, propsAliases) : "";
|
|
101
111
|
const slot = type === "normal" ? $2 : "";
|
|
102
112
|
return "<olum " + name + propsAttr + ">" + slot + "</olum>";
|
|
103
113
|
}
|
package/lib/toJs.js
CHANGED
|
@@ -3,6 +3,8 @@ const path = require("path");
|
|
|
3
3
|
function toJs(statement) {
|
|
4
4
|
return statement.replace(/(from)(\s+)?.*/g, (str) => {
|
|
5
5
|
let _path = str.replace(/from|'|"/g, "").trim();
|
|
6
|
+
// bare specifiers (npm pkgs, olum) resolve via the import map in index.html — don't touch them
|
|
7
|
+
if (!/^\.{0,2}\//.test(_path)) return 'from "' + _path + '";';
|
|
6
8
|
const extname = path.extname(_path);
|
|
7
9
|
const newPath = extname ? _path.replace(extname, "") : _path;
|
|
8
10
|
return 'from "' + newPath + '.js";';
|
package/package.json
CHANGED
package/tests/compiler.test.js
CHANGED
|
@@ -170,6 +170,32 @@ check(
|
|
|
170
170
|
(out) => /style="color:\$\{olum\.esc\(state\.color\)\}; padding:8px;"/.test(tmpl(out)) && parses(out)
|
|
171
171
|
);
|
|
172
172
|
|
|
173
|
+
// boolean attributes are truthy by PRESENCE (checked="false" is still checked), so
|
|
174
|
+
// attr="{expr}" must toggle the attribute's existence, never interpolate its value
|
|
175
|
+
check(
|
|
176
|
+
"boolean attribute compiles to a presence toggle (checked)",
|
|
177
|
+
comp(`<input type="checkbox" checked="{state.count}" />`),
|
|
178
|
+
(out) => /\$\{\(state\.count\) \? "checked" : ""\}/.test(tmpl(out)) && !/checked="\$\{olum\.esc/.test(tmpl(out)) && parses(out)
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
check(
|
|
182
|
+
"boolean attribute with an expression (disabled)",
|
|
183
|
+
comp(`<button disabled="{!state.count}">Go</button>`),
|
|
184
|
+
(out) => /\$\{\(!state\.count\) \? "disabled" : ""\}/.test(tmpl(out)) && parses(out)
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
check(
|
|
188
|
+
"static boolean attribute is left alone",
|
|
189
|
+
comp(`<input type="text" disabled />`),
|
|
190
|
+
(out) => /disabled/.test(tmpl(out)) && !/\? "disabled"/.test(tmpl(out)) && parses(out)
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
check(
|
|
194
|
+
"boolean attribute inside <for> stays a presence toggle",
|
|
195
|
+
comp(`<for each="x of state.items"><option selected="{x.id === state.count}">{x.name}</option></for>`),
|
|
196
|
+
(out) => /\$\{\(x\.id === state\.count\) \? "selected" : ""\}/.test(tmpl(out)) && parses(out)
|
|
197
|
+
);
|
|
198
|
+
|
|
173
199
|
// ── §6 Events on* (code in "") ─────────────────────────────────────────────
|
|
174
200
|
section("§6 Events");
|
|
175
201
|
|
|
@@ -323,6 +349,26 @@ check(
|
|
|
323
349
|
(out) => /item: item/.test(out) && !/item:method/.test(out) && parses(out)
|
|
324
350
|
);
|
|
325
351
|
|
|
352
|
+
check(
|
|
353
|
+
"forwarding a destructured prop emits a kind-props source (function props survive nesting)",
|
|
354
|
+
comp(`<C onMessage="{onMessage}" />`, `import C from "./C";\nconst { onMessage } = props();`),
|
|
355
|
+
(out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && /onMessage: onMessage/.test(out) && !/onMessage:method/.test(out) && parses(out)
|
|
356
|
+
);
|
|
357
|
+
|
|
358
|
+
check(
|
|
359
|
+
"forwarding a RENAMED destructured prop keys the source by the original prop name",
|
|
360
|
+
comp(`<C onMessage="{om}" />`, `import C from "./C";\nconst { onMessage: om } = props();`),
|
|
361
|
+
(out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && parses(out)
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
check(
|
|
365
|
+
// a destructured prop isn't in methodsRef, so the data-o-event chain can't dispatch it by
|
|
366
|
+
// name — the compiler must wrap the call in an anon handler whose closure holds the prop
|
|
367
|
+
"calling a destructured prop in an event handler wraps it in an anon method",
|
|
368
|
+
comp(`<button onclick="onclick()">x</button>`, `const { onclick } = props();`),
|
|
369
|
+
(out) => /__olumAnon_\w+ = \(\$event\) => \{ onclick\(\) \}/.test(out) && /onclick\|__olumAnon_/.test(out) && parses(out)
|
|
370
|
+
);
|
|
371
|
+
|
|
326
372
|
check(
|
|
327
373
|
"forwarding a function prop records a props source (resolved live at runtime)",
|
|
328
374
|
comp(`<C fn="{props().onSave}" />`, `import C from "./C";\nimport { props } from "../core/olum.js";`),
|
|
@@ -384,9 +430,12 @@ check(
|
|
|
384
430
|
section("§16 Scoped CSS");
|
|
385
431
|
|
|
386
432
|
check(
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
433
|
+
// the scope attr attaches to the selector's LAST COMPOUND (.box[data-o-x], p[data-o-x]:hover),
|
|
434
|
+
// not as a `[data-o-x] .box` descendant prefix — a descendant rule would also match nested
|
|
435
|
+
// components' elements, which sit inside this component's DOM but carry their own scope attr
|
|
436
|
+
"styles are scoped onto the selector's last compound and injected",
|
|
437
|
+
comp(`<div class="box"></div>`).replace("</script>", "</script>\n<style>.box{color:red}\np:hover{color:blue}</style>"),
|
|
438
|
+
(out) => /\.box\[data-o-\w+\]/.test(out) && /p\[data-o-\w+\]:hover/.test(out) && /olum\.injectStyle\(/.test(out) && parses(out)
|
|
390
439
|
);
|
|
391
440
|
|
|
392
441
|
// ── §17 Imports ─────────────────────────────────────────────────────────────
|
|
@@ -418,6 +467,105 @@ check(
|
|
|
418
467
|
(out) => /<olum name="C"/.test(tmpl(out)) && !/data-o-props=/.test(tmpl(out)) && parses(out)
|
|
419
468
|
);
|
|
420
469
|
|
|
470
|
+
// ── §20 File-based routing (compileRoutes) ──────────────────────────────────
|
|
471
|
+
// compileRoutes(entryPoint) scans a src tree and emits the router entry module:
|
|
472
|
+
// imports + `export const routes = [...]` + Router/Olum bootstrap. Unlike the
|
|
473
|
+
// parser checks above it reads the filesystem, so each check builds a throwaway
|
|
474
|
+
// fixture tree in the OS temp dir and removes it afterwards.
|
|
475
|
+
section("§20 File-based routing (compileRoutes)");
|
|
476
|
+
|
|
477
|
+
const { compileRoutes } = require("../lib/helpers");
|
|
478
|
+
const fs = require("fs");
|
|
479
|
+
const os = require("os");
|
|
480
|
+
const nodePath = require("path");
|
|
481
|
+
|
|
482
|
+
// like check() but for units that aren't parser(template): producer() returns
|
|
483
|
+
// the value under test (and owns its fixture setup/teardown)
|
|
484
|
+
function checkFn(name, producer, assertion) {
|
|
485
|
+
let out;
|
|
486
|
+
try {
|
|
487
|
+
out = producer();
|
|
488
|
+
} catch (e) {
|
|
489
|
+
recordFail(name);
|
|
490
|
+
console.log(" " + FAIL_ICON + " " + name + dim(" (threw: " + e.message + ")"));
|
|
491
|
+
console.log(" " + dim("↳ in " + currentSection));
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
let ok = false;
|
|
495
|
+
let detail = "";
|
|
496
|
+
try {
|
|
497
|
+
ok = assertion(out);
|
|
498
|
+
} catch (e) {
|
|
499
|
+
detail = dim(" (" + e.message + ")");
|
|
500
|
+
}
|
|
501
|
+
if (ok) {
|
|
502
|
+
passed++;
|
|
503
|
+
console.log(" " + PASS_ICON + " " + name);
|
|
504
|
+
} else {
|
|
505
|
+
recordFail(name);
|
|
506
|
+
if (!detail) detail = "\n " + dim(String(out).replace(/\s+/g, " ").slice(0, 200));
|
|
507
|
+
console.log(" " + FAIL_ICON + " " + red(name) + detail);
|
|
508
|
+
console.log(" " + dim("↳ in " + currentSection));
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function withRouteTree(files, fn) {
|
|
513
|
+
const root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "olum-routes-"));
|
|
514
|
+
try {
|
|
515
|
+
files.forEach((f) => {
|
|
516
|
+
const abs = nodePath.join(root, f);
|
|
517
|
+
fs.mkdirSync(nodePath.dirname(abs), { recursive: true });
|
|
518
|
+
fs.writeFileSync(abs, "<div></div>");
|
|
519
|
+
});
|
|
520
|
+
return fn(root);
|
|
521
|
+
} finally {
|
|
522
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
checkFn(
|
|
527
|
+
"route tree compiles: / first, /404 last, [param] -> :param, (group) and NN- prefixes stripped",
|
|
528
|
+
() =>
|
|
529
|
+
withRouteTree(
|
|
530
|
+
[
|
|
531
|
+
"page.html",
|
|
532
|
+
"not-found.html",
|
|
533
|
+
"about/page.html",
|
|
534
|
+
"(main)/club/page.html",
|
|
535
|
+
"01-blog/[slug]/page.html",
|
|
536
|
+
"components/Widget.html", // excluded dir — never a route
|
|
537
|
+
"_drafts/page.html", // _-prefixed dir — excluded
|
|
538
|
+
],
|
|
539
|
+
(root) => compileRoutes(root)
|
|
540
|
+
),
|
|
541
|
+
(out) => {
|
|
542
|
+
const paths = [...out.matchAll(/path: "([^"]+)"/g)].map((m) => m[1]);
|
|
543
|
+
return (
|
|
544
|
+
/import App from "\.\/page\.js";/.test(out) &&
|
|
545
|
+
/import NotFound from "\.\/not-found\.js";/.test(out) &&
|
|
546
|
+
/import About from "\.\/about\/page\.js";/.test(out) &&
|
|
547
|
+
// imports keep the REAL file location; only route path/comp are cleaned
|
|
548
|
+
/import Club from "\.\/\(main\)\/club\/page\.js";/.test(out) &&
|
|
549
|
+
/import BlogSlug from "\.\/01-blog\/\[slug\]\/page\.js";/.test(out) &&
|
|
550
|
+
/\{ path: "\/club", comp: Club \}/.test(out) &&
|
|
551
|
+
/\{ path: "\/blog\/:slug", comp: BlogSlug \}/.test(out) &&
|
|
552
|
+
/\{ path: "\/about", comp: About \}/.test(out) &&
|
|
553
|
+
paths[0] === "/" &&
|
|
554
|
+
paths[paths.length - 1] === "/404" &&
|
|
555
|
+
/err: "\/404",/.test(out) && // not-found.html wires the router's 404 redirect
|
|
556
|
+
!/Widget|_drafts|Drafts/.test(out) && // excluded dirs leave no trace
|
|
557
|
+
/new Router\(config\)/.test(out) &&
|
|
558
|
+
/new Olum\(\)\.\$\("#app"\)\.use\(router\)/.test(out)
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
);
|
|
562
|
+
|
|
563
|
+
checkFn(
|
|
564
|
+
"no not-found.html -> no /404 route and no err in the router config",
|
|
565
|
+
() => withRouteTree(["page.html", "about/page.html"], (root) => compileRoutes(root)),
|
|
566
|
+
(out) => !/\/404/.test(out) && !/err:/.test(out) && /\{ path: "\/", comp: App \}/.test(out) && /\{ path: "\/about", comp: About \}/.test(out)
|
|
567
|
+
);
|
|
568
|
+
|
|
421
569
|
console.log("\n========================");
|
|
422
570
|
const summary = `${passed} passed, ${failed} failed`;
|
|
423
571
|
console.log((failed ? red(bold(summary)) : green(bold(summary))) + "\n");
|
|
@@ -439,7 +587,7 @@ if (failed) {
|
|
|
439
587
|
|
|
440
588
|
// Guard against a whole section silently disappearing (a bad merge, a `check` that
|
|
441
589
|
// throws before registering, etc.). Bump EXPECTED_CHECKS when you add/remove tests.
|
|
442
|
-
const EXPECTED_CHECKS =
|
|
590
|
+
const EXPECTED_CHECKS = 51;
|
|
443
591
|
const total = passed + failed;
|
|
444
592
|
if (total !== EXPECTED_CHECKS) {
|
|
445
593
|
console.log(yellow(`⚠ ran ${total} checks but expected ${EXPECTED_CHECKS} — did a test get dropped?`) + "\n");
|