olum-compiler 1.2.0 → 1.5.0
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/.claude/settings.local.json +2 -1
- package/bin/build.js +14 -8
- package/bin/bundle.js +106 -0
- package/bin/compiler.js +12 -4
- package/bin/copySrc.js +68 -24
- package/bin/dev.js +29 -16
- package/bin/server.js +1 -2
- package/bin/watcher.js +10 -3
- package/lib/changes.txt +0 -0
- package/lib/compiler.js +10 -4
- package/lib/coreLibs.js +6 -2
- package/lib/helpers.js +3 -3
- package/lib/liveProps.js +220 -0
- package/lib/parser.js +10 -3
- package/package.json +1 -1
- package/tests/compiler.test.js +46 -3
package/bin/build.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
-
const
|
|
2
|
-
const
|
|
3
|
-
|
|
1
|
+
const bundle = require("./bundle");
|
|
2
|
+
const compile = require("./compiler");
|
|
3
|
+
const copySrc = require("./copySrc");
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
(async function () {
|
|
6
|
+
const bootAt = Date.now();
|
|
7
|
+
try {
|
|
8
|
+
await copySrc();
|
|
9
|
+
await compile();
|
|
10
|
+
await bundle(bootAt);
|
|
11
|
+
} catch (error) {
|
|
12
|
+
console.error(error);
|
|
13
|
+
process.exitCode = 1; // a failed build must not report success to CI
|
|
14
|
+
}
|
|
15
|
+
})();
|
package/bin/bundle.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// vite task to compile from main.js as entrypoint and outputs dist dir as final vite output
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const colors = require("../lib/colors");
|
|
5
|
+
const spawn = require("../lib/cross-spawn");
|
|
6
|
+
const { useLocalCore, localLibs } = require("../lib/coreLibs"); // same runtime switch the dev import map uses
|
|
7
|
+
|
|
8
|
+
// compiled files paths
|
|
9
|
+
const cwd = process.cwd();
|
|
10
|
+
const public = path.resolve(__dirname, "../public"); // node_modules path
|
|
11
|
+
const root = cwd.replace(/\/module$/, ""); // project root path
|
|
12
|
+
const outDir = path.resolve(root, "dist");
|
|
13
|
+
|
|
14
|
+
function getLogs() {
|
|
15
|
+
const logFilePath = path.resolve(__dirname, "../lib/log.txt");
|
|
16
|
+
if (fs.existsSync(logFilePath)) {
|
|
17
|
+
return fs.readFileSync(logFilePath).toString();
|
|
18
|
+
} else {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// vite only emits assets it can trace from the bundle graph — URLs living inside compiled
|
|
24
|
+
// component strings (scoped CSS url(), template paths) are invisible to it. Dev serves all
|
|
25
|
+
// of public/ verbatim at /, so prod mirrors the rest of it into dist — skipping files vite
|
|
26
|
+
// already absorbed under hashed names, and never overwriting what it emitted.
|
|
27
|
+
function copyStatic(from, to, absorbed) {
|
|
28
|
+
for (const name of fs.readdirSync(from)) {
|
|
29
|
+
const src = path.join(from, name);
|
|
30
|
+
const dest = path.join(to, name);
|
|
31
|
+
if (fs.statSync(src).isDirectory()) {
|
|
32
|
+
copyStatic(src, dest, absorbed);
|
|
33
|
+
} else if (!absorbed.has(src) && !fs.existsSync(dest)) {
|
|
34
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
35
|
+
fs.copyFileSync(src, dest);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// public files vite already bundled (e.g. favicon.svg, main.css → hashed copies in dist/assets):
|
|
41
|
+
// every emitted asset lists the source files it came from, relative to the vite root
|
|
42
|
+
function absorbedFiles(buildResult) {
|
|
43
|
+
const absorbed = new Set();
|
|
44
|
+
for (const res of [buildResult].flat()) {
|
|
45
|
+
for (const item of res.output || []) {
|
|
46
|
+
for (const orig of item.originalFileNames || []) absorbed.add(path.resolve(public, orig));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// processed stylesheets don't report their origin (they're merged into a renamed css chunk),
|
|
50
|
+
// but everything index.html links to is by definition handled by vite
|
|
51
|
+
const html = fs.readFileSync(path.join(public, "index.html"), "utf8");
|
|
52
|
+
const attrRegex = /(?:href|src)=["']([^"']+)["']/g;
|
|
53
|
+
let match;
|
|
54
|
+
while ((match = attrRegex.exec(html))) {
|
|
55
|
+
const url = match[1];
|
|
56
|
+
if (/^(https?:)?\/\//.test(url)) continue; // external URLs aren't public files
|
|
57
|
+
absorbed.add(path.resolve(public, url.replace(/^\//, "")));
|
|
58
|
+
}
|
|
59
|
+
return absorbed;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// vite is build-only, so it installs lazily into the project root on first build — dev installs stay lean
|
|
63
|
+
function ensureVite() {
|
|
64
|
+
if (fs.existsSync(path.join(root, "node_modules/vite/package.json"))) return;
|
|
65
|
+
console.log(colors("white", "vite not found — installing it into the project root (one-time)..."));
|
|
66
|
+
// --include=dev: the build runs with NODE_ENV=production, which npm inherits as omit=dev and would skip the install
|
|
67
|
+
const result = spawn.sync("npm", ["install", "--save-dev", "--include=dev", "vite"], { cwd: root, stdio: "inherit" });
|
|
68
|
+
if (result.status !== 0) throw new Error("Failed to install vite — run `npm i -D vite` in " + root + " then re-run the build.");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function bundle(bootAt) {
|
|
72
|
+
const logs = getLogs();
|
|
73
|
+
if (logs) {
|
|
74
|
+
// stop bundler to fix compiler errors first
|
|
75
|
+
console.error(colors("red", "Bundle skipped — fix the compiler errors above first."));
|
|
76
|
+
process.exitCode = 1;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
ensureVite();
|
|
81
|
+
const { build } = await import("vite"); // vite 5+ is ESM-only → dynamic import from CJS
|
|
82
|
+
|
|
83
|
+
// LOCAL_CORE=true → bundle the framework from module/core (like the dev import map);
|
|
84
|
+
// otherwise bare "olum"/"olum-router"/"olum-store" resolve from the project root's node_modules
|
|
85
|
+
const alias = {};
|
|
86
|
+
if (useLocalCore) {
|
|
87
|
+
for (const [pkgName, corePath] of Object.entries(localLibs)) {
|
|
88
|
+
alias[pkgName] = path.resolve(__dirname, ".." + corePath); // "/core/olum.js" → module/core/olum.js
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const buildResult = await build({
|
|
93
|
+
root: public, // index.html here is the entry; its ../src/main.js script gets pulled in and bundled
|
|
94
|
+
resolve: { alias },
|
|
95
|
+
build: {
|
|
96
|
+
outDir,
|
|
97
|
+
emptyOutDir: true, // outDir sits outside vite's root, so emptying it must be opted into explicitly
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
copyStatic(public, outDir, absorbedFiles(buildResult));
|
|
102
|
+
|
|
103
|
+
// console.log("compile + bundle in", colors("white", `${Date.now() - bootAt}ms`));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = bundle;
|
package/bin/compiler.js
CHANGED
|
@@ -3,21 +3,29 @@ const path = require("path");
|
|
|
3
3
|
const fs = require("fs");
|
|
4
4
|
const colors = require("../lib/colors");
|
|
5
5
|
|
|
6
|
-
let num =
|
|
7
|
-
module.exports = function () {
|
|
6
|
+
let num = -1;
|
|
7
|
+
module.exports = function (file, startedAt) {
|
|
8
8
|
num++;
|
|
9
|
+
const t0 = startedAt || Date.now(); // build timing — callers pass their copySrc start so the line shows the whole copy+compile
|
|
10
|
+
const done = () => num && console.log(colors("white", "Build no."), colors("yellow", num), colors("white", "in"), colors("green", Date.now() - t0 + "ms"));
|
|
9
11
|
return new Promise(resolve => {
|
|
10
12
|
// wipeout log.txt
|
|
11
13
|
const logFilePath = path.resolve(__dirname, "../lib/log.txt");
|
|
12
14
|
fs.writeFileSync(logFilePath, "");
|
|
13
15
|
// compile
|
|
14
16
|
const compilerPath = path.resolve(__dirname, "../lib/compiler.js");
|
|
15
|
-
|
|
17
|
+
if (file) { // single file → compile in-process: jsdom/acorn are already loaded, so this is ~ms instead of a ~400ms node spawn
|
|
18
|
+
try { require(compilerPath)(file); }
|
|
19
|
+
catch (err) { console.error(err); } // a broken component must not kill the dev server
|
|
20
|
+
resolve();
|
|
21
|
+
return done();
|
|
22
|
+
}
|
|
23
|
+
const result = spawn.sync("node", [compilerPath], { stdio: "inherit" }); // full compile stays in a child (startup / fallback / build)
|
|
16
24
|
if (result.signal) {
|
|
17
25
|
if (result.signal === "SIGKILL" || result.signal === "SIGTERM") console.log("Failed to run compiler @ " + compilerPath);
|
|
18
26
|
process.exit(1);
|
|
19
27
|
}
|
|
20
28
|
resolve();
|
|
21
|
-
|
|
29
|
+
done();
|
|
22
30
|
});
|
|
23
31
|
};
|
package/bin/copySrc.js
CHANGED
|
@@ -1,35 +1,79 @@
|
|
|
1
|
-
// todo check changed files only to be copied, use this project https://github.com/eissapk/diff
|
|
2
1
|
const path = require("path");
|
|
3
2
|
const fs = require("fs");
|
|
4
|
-
const { copy,
|
|
3
|
+
const { copy, compileRoutes } = require("../lib/helpers");
|
|
5
4
|
const importMap = require("../lib/importMap");
|
|
6
|
-
|
|
7
|
-
const
|
|
5
|
+
// src paths (inside user project root path)
|
|
6
|
+
const cwd = process.cwd();
|
|
7
|
+
const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src")
|
|
8
|
+
const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public")
|
|
9
|
+
// dest paths (inside node_modules)
|
|
10
|
+
const srcDest = path.resolve(__dirname, "../src");
|
|
11
|
+
const publicDest = path.resolve(__dirname, "../public");
|
|
12
|
+
const indexHtmlDest = path.resolve(__dirname, "../public/index.html");
|
|
13
|
+
const mainJsPathDest = path.resolve(__dirname, "../src/main.js");
|
|
8
14
|
|
|
9
|
-
|
|
15
|
+
// auto bind div#app placeholder, import map and mainjs script to index.html
|
|
16
|
+
// (import map must precede the module script so bare imports resolve)
|
|
17
|
+
function injectIndexHtml(indexHtmlPath) {
|
|
18
|
+
let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
|
|
19
|
+
// production bundles bare imports, so the dev-only import map never enters the build output
|
|
20
|
+
const importMapTag = process.env.NODE_ENV === "production" ? "" : `${importMap(entryPoint)}\n`;
|
|
21
|
+
indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n</body>`);
|
|
22
|
+
fs.writeFileSync(indexHtmlPath, indexHtmlContent);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function handleMainJs () {
|
|
26
|
+
if (fs.existsSync(mainJsPathDest)) return; // skip main.js automation since user wants to drop router
|
|
27
|
+
const mainJsContent = compileRoutes(entryPoint);
|
|
28
|
+
// automated main.js -- new concept
|
|
29
|
+
fs.writeFileSync(mainJsPathDest, mainJsContent);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Mirror one watcher event into module/{src,public} and keep the automated
|
|
33
|
+
// main.js in step. Returns the mirrored path — or null when only the full
|
|
34
|
+
// flow can help (path outside both roots, or dest scaffolding deleted by hand).
|
|
35
|
+
function syncFile(event, file) {
|
|
36
|
+
if (!fs.existsSync(mainJsPathDest) || !fs.existsSync(indexHtmlDest)) return null; // dest scaffolding deleted by hand → full flow
|
|
37
|
+
const inSrc = file.startsWith(entryPoint + path.sep); // src/... → module/src/...
|
|
38
|
+
const inPublic = !inSrc && file.startsWith(entryPoint2 + path.sep); // public/... → module/public/...
|
|
39
|
+
if (!inSrc && !inPublic) return null; // outside both roots → full flow
|
|
40
|
+
const dest = inSrc ? path.join(srcDest, path.relative(entryPoint, file)) : path.join(publicDest, path.relative(entryPoint2, file));
|
|
41
|
+
if (event.startsWith("unlink")) { // file or dir was deleted → remove its mirror
|
|
42
|
+
fs.rmSync(dest, { recursive: true, force: true }); // file or dir alike (helpers.remove is dir-only and crashes on empty dirs)
|
|
43
|
+
if (inSrc && dest.endsWith(".html")) fs.rmSync(dest.replace(/\.html$/, ".js"), { force: true }); // and the compiled .js twin of a src component
|
|
44
|
+
} else { // file was added or edited → copy just it
|
|
45
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true }); // make sure the mirror folder exists (mkdir, NOT remove!)
|
|
46
|
+
fs.copyFileSync(file, dest); // copy just this one file
|
|
47
|
+
if (dest === indexHtmlDest) injectIndexHtml(dest); // re-inject #app + import map + main.js script
|
|
48
|
+
}
|
|
49
|
+
// routes only change when a page (.html), a whole dir, or main.js itself is added/removed under src —
|
|
50
|
+
// anything narrower (assets, utils, edits) skips the compileRoutes tree scan entirely
|
|
51
|
+
const affectsRoutes = inSrc && event !== "change" && (dest.endsWith(".html") || event === "unlinkDir" || dest === mainJsPathDest);
|
|
52
|
+
if (affectsRoutes && !fs.existsSync(path.join(entryPoint, "main.js"))) fs.writeFileSync(mainJsPathDest, compileRoutes(entryPoint)); // refresh automated main.js (skipped when user owns it)
|
|
53
|
+
return dest; // tell the caller what was mirrored
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// copySrc() → full flow: wipe dest, clone src+public (first build / fallback)
|
|
57
|
+
// copySrc(event, file) → incremental: mirror that one watcher event only
|
|
58
|
+
// Resolves with the mirrored dest path, or null when the full flow ran.
|
|
59
|
+
module.exports = function copySrc(event, file) {
|
|
10
60
|
return new Promise((resolve, reject) => {
|
|
11
61
|
try {
|
|
12
|
-
//
|
|
13
|
-
|
|
14
|
-
|
|
62
|
+
if (event) { // watcher event → try the incremental path first
|
|
63
|
+
const dest = syncFile(event, file); // mirror just this one change
|
|
64
|
+
if (dest) return resolve(dest); // done — falls through to the full flow otherwise
|
|
65
|
+
}
|
|
66
|
+
// clean (rmSync handles missing, empty and nested dirs alike —
|
|
67
|
+
// helpers.remove crashes on missing/empty dirs)
|
|
68
|
+
fs.rmSync(publicDest, { recursive: true, force: true });
|
|
69
|
+
fs.rmSync(srcDest, { recursive: true, force: true });
|
|
15
70
|
// copy
|
|
16
|
-
copy(entryPoint,
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
fs.writeFileSync(mainJsPath, mainJsContent);
|
|
21
|
-
});
|
|
22
|
-
copy(entryPoint2, path.resolve(__dirname, "../public"), () => {
|
|
23
|
-
const indexHtmlPath = path.resolve(__dirname, "../public/index.html");
|
|
24
|
-
let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
|
|
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>`);
|
|
28
|
-
fs.writeFileSync(indexHtmlPath, indexHtmlContent);
|
|
29
|
-
});
|
|
30
|
-
resolve();
|
|
71
|
+
copy(entryPoint, srcDest, () => handleMainJs());
|
|
72
|
+
copy(entryPoint2, publicDest, () => injectIndexHtml(indexHtmlDest));
|
|
73
|
+
|
|
74
|
+
resolve(null);
|
|
31
75
|
} catch (err) {
|
|
32
|
-
reject();
|
|
76
|
+
reject(err);
|
|
33
77
|
}
|
|
34
78
|
});
|
|
35
79
|
};
|
package/bin/dev.js
CHANGED
|
@@ -3,6 +3,7 @@ const watch = require("./watcher");
|
|
|
3
3
|
const compile = require("./compiler");
|
|
4
4
|
const copySrc = require("./copySrc");
|
|
5
5
|
const WebSocket = require("../lib/websocket");
|
|
6
|
+
const colors = require("../lib/colors");
|
|
6
7
|
const path = require("path");
|
|
7
8
|
const fs = require("fs");
|
|
8
9
|
|
|
@@ -10,18 +11,18 @@ let instance;
|
|
|
10
11
|
const entryPoint = path.resolve(__dirname, "../public");
|
|
11
12
|
serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
|
|
12
13
|
// initial compiling
|
|
14
|
+
const bootAt = Date.now(); // Build-line timing covers copy + compile
|
|
13
15
|
copySrc().then(() => {
|
|
14
|
-
compile().then(() => {
|
|
16
|
+
compile(undefined, bootAt).then(() => {
|
|
15
17
|
// EADDRINUSE is emitted as an 'error' event (not thrown), so retry on the next port
|
|
16
18
|
server.on("error", (e) => { if (e.code === "EADDRINUSE") server.listen(++PORT); });
|
|
17
|
-
server.listen(PORT, () => console.log(log.replace(
|
|
19
|
+
server.listen(PORT, () => console.log(log.replace(/port \d+/, "port " + PORT), colors("white", `(ready in ${Date.now() - bootAt}ms)`))); // boot = clean + copy + first compile + listen; replace keeps the log right after EADDRINUSE port bumps
|
|
18
20
|
|
|
19
21
|
// Listen for adds, edits and deletes. Editors that save atomically
|
|
20
22
|
// (temp file + rename) surface edits as unlink+add rather than change,
|
|
21
23
|
// so watching only "change" misses new files and many edits.
|
|
22
|
-
watch.on(
|
|
23
|
-
|
|
24
|
-
watch.on("unlink", handleChange);
|
|
24
|
+
["add", "change", "unlink", "unlinkDir"].forEach((event) => watch.on(event, (file) => handleChange(event, file)));
|
|
25
|
+
require("../lib/compiler"); // preload jsdom/acorn now so even the first save compiles in-process instantly
|
|
25
26
|
|
|
26
27
|
(function startWs(port) {
|
|
27
28
|
// const wss = new WebSocket.Server({ port });
|
|
@@ -34,7 +35,7 @@ serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
|
|
|
34
35
|
});
|
|
35
36
|
})(wsPort);
|
|
36
37
|
});
|
|
37
|
-
});
|
|
38
|
+
}).catch(console.error);
|
|
38
39
|
});
|
|
39
40
|
|
|
40
41
|
function getLogs() {
|
|
@@ -46,15 +47,27 @@ function getLogs() {
|
|
|
46
47
|
}
|
|
47
48
|
}
|
|
48
49
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
50
|
+
const send = (data) => instance && instance.send(JSON.stringify(data)); // push a message to the browser (if one is connected)
|
|
51
|
+
|
|
52
|
+
// after compiling: surface compiler warnings, otherwise reload the page
|
|
53
|
+
function notify() {
|
|
54
|
+
const logs = getLogs(); // warnings written by the compiler child to lib/log.txt
|
|
55
|
+
logs ? send({ msg: "warn", data: logs }) : send({ msg: "reload" }); // warn overlay or plain reload
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// compilable component: .html under module/src, not a _-partial
|
|
59
|
+
const isComp = (dest) => dest.endsWith(".html") && !path.basename(dest).startsWith("_") && dest.startsWith(path.resolve(__dirname, "../src") + path.sep);
|
|
60
|
+
|
|
61
|
+
// copySrc mirrors the change (or falls back to its full flow), then:
|
|
62
|
+
// full flow → compile all / css → hot-swap / component → compile it / else → reload
|
|
63
|
+
function handleChange(event, file) {
|
|
64
|
+
const t0 = Date.now(); // Build-line timing covers copy + compile
|
|
65
|
+
copySrc(event, file) // mirror this one change into module/ (dest = mirrored path, null = full flow ran)
|
|
66
|
+
.then((dest) => {
|
|
67
|
+
if (dest === null) return compile(undefined, t0).then(notify); // full rebuild → compile every component
|
|
68
|
+
if (file.endsWith("css")) return send({ msg: "css" }); // css → hot-swap styles, no reload
|
|
69
|
+
if (!event.startsWith("unlink") && isComp(dest)) return compile(dest, t0).then(notify); // component → compile only this file
|
|
70
|
+
send({ msg: "reload" }); // anything else (asset/js/partial/removal) → copy was enough, just reload
|
|
58
71
|
})
|
|
59
|
-
.catch(console.error);
|
|
72
|
+
.catch(console.error); // watcher must survive a failed build
|
|
60
73
|
}
|
package/bin/server.js
CHANGED
|
@@ -53,7 +53,6 @@ function getPath(entry, url) {
|
|
|
53
53
|
function serve(entry, port) {
|
|
54
54
|
return new Promise((resolve, reject) => {
|
|
55
55
|
const PORT = Number(port || process.env.PORT || 3000);
|
|
56
|
-
const domain = `http://localhost:${PORT}`;
|
|
57
56
|
|
|
58
57
|
const server = http.createServer(handler);
|
|
59
58
|
function handler(req, res) {
|
|
@@ -101,7 +100,7 @@ function serve(entry, port) {
|
|
|
101
100
|
res.writeHead(404, { "content-type": "text/plain" });
|
|
102
101
|
res.end("404 Not Found: " + urlPath);
|
|
103
102
|
}
|
|
104
|
-
const log = colors("cyan", "Serving ") + colors("green",
|
|
103
|
+
const log = colors("cyan", "Serving ") + colors("green", "port " + PORT); // port only — a URL would show "localhost" even on a live server
|
|
105
104
|
// setWsPort lets dev.js report the port the ws server actually bound to (it may
|
|
106
105
|
// retry off 8090 if that's taken) so handleWsFile injects the matching port.
|
|
107
106
|
const setWsPort = (port) => { wsPort = port; };
|
package/bin/watcher.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
const chokidar = require("../lib/chokidar");
|
|
2
2
|
const path = require("path");
|
|
3
|
+
const fs = require("fs");
|
|
3
4
|
// Resolve against the project root (process.cwd()), same as copySrc.js.
|
|
4
5
|
// The old "../../src" pointed at node_modules/src, which doesn't exist, so
|
|
5
6
|
// chokidar watched 0 directories and never detected any changes.
|
|
6
|
-
const
|
|
7
|
-
const
|
|
7
|
+
const cwd = process.cwd();
|
|
8
|
+
const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src")
|
|
9
|
+
const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public")
|
|
8
10
|
// let ignoreRegex = /\_\.js$/;
|
|
9
11
|
// module.exports = chokidar.watch(entryPoint, {ignored: ignoreRegex, persistent: true });
|
|
10
12
|
// ignoreInitial: don't fire "add" for every existing file on startup (initial
|
|
@@ -14,4 +16,9 @@ module.exports = chokidar.watch([entryPoint, entryPoint2], {
|
|
|
14
16
|
persistent: true,
|
|
15
17
|
ignoreInitial: true,
|
|
16
18
|
awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
|
|
17
|
-
});
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// Debug trail: log every event of this session to lib/changes.txt (newest last)
|
|
22
|
+
const changesLog = path.resolve(__dirname, "../lib/changes.txt"); // e.g. "add /path/to/src/page.html"
|
|
23
|
+
fs.writeFileSync(changesLog, ""); // start fresh each session
|
|
24
|
+
["add", "change", "unlink", "addDir", "unlinkDir"].forEach((event) => module.exports.on(event, (file) => fs.appendFileSync(changesLog, `${event} ${file}\n`))); // one line per event
|
package/lib/changes.txt
ADDED
|
File without changes
|
package/lib/compiler.js
CHANGED
|
@@ -5,8 +5,7 @@ const { lineCounter } = require("./lineCounter");
|
|
|
5
5
|
const { compExt } = require("./regex");
|
|
6
6
|
|
|
7
7
|
// todo handle the component when it has these cases [null, only html, html + css, html+js, html+css+js, only css, only js]
|
|
8
|
-
|
|
9
|
-
pathsArr.forEach((filePath) => {
|
|
8
|
+
function compileFile(filePath) {
|
|
10
9
|
// console.warn("final: ", filePath);
|
|
11
10
|
if (fs.existsSync(filePath)) {
|
|
12
11
|
const fileContent = fs.readFileSync(filePath).toString();
|
|
@@ -16,6 +15,13 @@ pathsArr.forEach((filePath) => {
|
|
|
16
15
|
// create .js module
|
|
17
16
|
fs.writeFileSync(newFilePath, parsedData);
|
|
18
17
|
// remove .html template
|
|
19
|
-
fs.unlinkSync(filePath);
|
|
18
|
+
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
|
20
19
|
}
|
|
21
|
-
}
|
|
20
|
+
}
|
|
21
|
+
module.exports = compileFile; // required in-process by the dev server (jsdom/acorn load once)
|
|
22
|
+
|
|
23
|
+
// script mode (npm run build / full compile): compile one file (arg) or all
|
|
24
|
+
if (require.main === module) {
|
|
25
|
+
const pathsArr = process.argv[2] ? [process.argv[2]] : getTempPath();
|
|
26
|
+
pathsArr.forEach(compileFile);
|
|
27
|
+
}
|
package/lib/coreLibs.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
// single switch for where the framework runtime loads from:
|
|
2
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
|
|
3
|
+
// false -> the published npm packages ("olum", "olum-router", "olum-store") installed at the project root
|
|
4
4
|
// both the generated main.js (helpers.js compileRoutes) and the import map (importMap.js)
|
|
5
5
|
// read this flag — they must agree, otherwise two runtime copies load and fight over window.olum
|
|
6
6
|
const useLocalCore = process?.env?.LOCAL_CORE == 'true';
|
|
7
7
|
|
|
8
|
-
// import-map entries for the local mode
|
|
8
|
+
// import-map entries for the local mode. "olum-store" must be listed even though no app file
|
|
9
|
+
// imports it directly: olum.js loads it via a bare dynamic import("olum-store"), which the
|
|
10
|
+
// importMap.js src scan never sees — without this entry the import rejects (silently) and
|
|
11
|
+
// store() throws "store is unavailable".
|
|
9
12
|
const localLibs = {
|
|
10
13
|
olum: "/core/olum.js",
|
|
11
14
|
"olum-router": "/core/router.js",
|
|
15
|
+
"olum-store": "/core/store.js",
|
|
12
16
|
};
|
|
13
17
|
|
|
14
18
|
module.exports = { useLocalCore, localLibs };
|
package/lib/helpers.js
CHANGED
|
@@ -312,7 +312,7 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
|
|
|
312
312
|
.filter((item) => item);
|
|
313
313
|
if (hasState && isFullArr(stateProps)) {
|
|
314
314
|
let fragments = stateProps.map((prop) => prop + ": state." + prop);
|
|
315
|
-
arr.push(`get state(){return window.olum.
|
|
315
|
+
arr.push(`get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`);
|
|
316
316
|
}
|
|
317
317
|
return arr;
|
|
318
318
|
}
|
|
@@ -345,7 +345,7 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
|
|
|
345
345
|
}
|
|
346
346
|
if (isFullArr(publicPropsInState)) {
|
|
347
347
|
let fragments = publicPropsInState.map((prop) => prop + ": state." + prop);
|
|
348
|
-
arr.push(`get state(){return window.olum.
|
|
348
|
+
arr.push(`get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`);
|
|
349
349
|
}
|
|
350
350
|
}
|
|
351
351
|
if (!newArr.length && !arr.length) return toObj();
|
|
@@ -372,7 +372,7 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
|
|
|
372
372
|
}
|
|
373
373
|
if (isFullArr(publicPropsInState)) {
|
|
374
374
|
let fragments = publicPropsInState.map((prop) => prop + ": state." + prop);
|
|
375
|
-
arr.push(`get state(){return window.olum.
|
|
375
|
+
arr.push(`get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`);
|
|
376
376
|
}
|
|
377
377
|
}
|
|
378
378
|
return arr.length ? toObj(arr) : toObj();
|
package/lib/liveProps.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// liveProps.js — compiler pass: LIVE destructured props.
|
|
2
|
+
//
|
|
3
|
+
// `const { color, size = "md", theme: t } = props()` normally freezes values at factory
|
|
4
|
+
// time (destructuring copies). This pass injects ONE shared live accessor per instance —
|
|
5
|
+
// `const __props = props(_storeKey);` (the props proxy is stateless, so one allocation
|
|
6
|
+
// serves every read) — and rewrites every later REFERENCE to those bindings into a live
|
|
7
|
+
// read through it:
|
|
8
|
+
// color -> __props.color
|
|
9
|
+
// size -> (__props.size === undefined ? ("md") : __props.size)
|
|
10
|
+
// t -> __props.theme
|
|
11
|
+
// so destructured props are always current — in templates, methods, and closures alike.
|
|
12
|
+
//
|
|
13
|
+
// Runs on the fully-assembled compiled module (after parser.js has already rewritten
|
|
14
|
+
// props() -> props(_storeKey)), so template interpolations, anonymous event handlers and
|
|
15
|
+
// generated scope getters are all covered by a single AST walk.
|
|
16
|
+
//
|
|
17
|
+
// SAFETY MODEL — degrade to the old snapshot semantics, never break the build:
|
|
18
|
+
// - the original declaration is KEPT (its bindings just become unused); if a reference
|
|
19
|
+
// is skipped for any reason the code still runs with the old snapshot value.
|
|
20
|
+
// - a reference is rewritten only when NO scope between it and the factory body
|
|
21
|
+
// redeclares the name (function params, hoisted var/function names, let/const/class
|
|
22
|
+
// in ancestor blocks, catch params, loop heads) — shadowed names are left alone.
|
|
23
|
+
// - unsupported pattern parts (rest `...r`, nested `{ a: { b } }`, computed keys) keep
|
|
24
|
+
// snapshot semantics for those bindings only.
|
|
25
|
+
// - every edit is inline (line count unchanged), so the identity source map stays aligned.
|
|
26
|
+
// - any parse failure returns the input untouched.
|
|
27
|
+
|
|
28
|
+
const acorn = require("acorn");
|
|
29
|
+
const walk = require("acorn-walk");
|
|
30
|
+
|
|
31
|
+
// all names bound by a declaration pattern (id of a declarator, a param, a catch param)
|
|
32
|
+
function patternNames(node, set) {
|
|
33
|
+
if (!node) return;
|
|
34
|
+
switch (node.type) {
|
|
35
|
+
case "Identifier":
|
|
36
|
+
set.add(node.name);
|
|
37
|
+
break;
|
|
38
|
+
case "ObjectPattern":
|
|
39
|
+
node.properties.forEach((p) => patternNames(p.type === "Property" ? p.value : p.argument, set));
|
|
40
|
+
break;
|
|
41
|
+
case "ArrayPattern":
|
|
42
|
+
node.elements.forEach((el) => patternNames(el, set));
|
|
43
|
+
break;
|
|
44
|
+
case "AssignmentPattern":
|
|
45
|
+
patternNames(node.left, set);
|
|
46
|
+
break;
|
|
47
|
+
case "RestElement":
|
|
48
|
+
patternNames(node.argument, set);
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// names hoisted to a FUNCTION scope: `var` declarations and function declarations
|
|
54
|
+
// anywhere inside, without descending into nested functions (their own scopes)
|
|
55
|
+
function hoistedNames(node, set) {
|
|
56
|
+
(function rec(n) {
|
|
57
|
+
if (!n || typeof n !== "object") return;
|
|
58
|
+
if (Array.isArray(n)) return n.forEach(rec);
|
|
59
|
+
if (typeof n.type !== "string") return;
|
|
60
|
+
if (n.type === "FunctionDeclaration") {
|
|
61
|
+
if (n.id) set.add(n.id.name);
|
|
62
|
+
return; // the body is a new scope
|
|
63
|
+
}
|
|
64
|
+
if (n.type === "FunctionExpression" || n.type === "ArrowFunctionExpression") return;
|
|
65
|
+
if (n.type === "VariableDeclaration" && n.kind === "var") n.declarations.forEach((d) => patternNames(d.id, set));
|
|
66
|
+
for (const k in n) {
|
|
67
|
+
if (k === "type" || k === "start" || k === "end") continue;
|
|
68
|
+
rec(n[k]);
|
|
69
|
+
}
|
|
70
|
+
})(node);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// names declared DIRECTLY in a lexical scope node (block, loop head, catch, switch)
|
|
74
|
+
function lexicalNames(node, set) {
|
|
75
|
+
const fromStatements = (stmts) =>
|
|
76
|
+
stmts.forEach((st) => {
|
|
77
|
+
if (st.type === "VariableDeclaration" && (st.kind === "let" || st.kind === "const")) st.declarations.forEach((d) => patternNames(d.id, set));
|
|
78
|
+
else if (st.type === "FunctionDeclaration" || st.type === "ClassDeclaration") st.id && set.add(st.id.name);
|
|
79
|
+
});
|
|
80
|
+
switch (node.type) {
|
|
81
|
+
case "BlockStatement":
|
|
82
|
+
case "StaticBlock":
|
|
83
|
+
fromStatements(node.body);
|
|
84
|
+
break;
|
|
85
|
+
case "ForStatement":
|
|
86
|
+
if (node.init && node.init.type === "VariableDeclaration") node.init.declarations.forEach((d) => patternNames(d.id, set));
|
|
87
|
+
break;
|
|
88
|
+
case "ForInStatement":
|
|
89
|
+
case "ForOfStatement":
|
|
90
|
+
if (node.left.type === "VariableDeclaration") node.left.declarations.forEach((d) => patternNames(d.id, set));
|
|
91
|
+
break;
|
|
92
|
+
case "CatchClause":
|
|
93
|
+
patternNames(node.param, set);
|
|
94
|
+
break;
|
|
95
|
+
case "SwitchStatement":
|
|
96
|
+
node.cases.forEach((c) => fromStatements(c.consequent));
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const isFn = (t) => t === "FunctionDeclaration" || t === "FunctionExpression" || t === "ArrowFunctionExpression";
|
|
102
|
+
const within = (node, container) => container && node.start >= container.start && node.end <= container.end;
|
|
103
|
+
|
|
104
|
+
function transform(code) {
|
|
105
|
+
// fast path: no `const { ... } = props(_storeKey)` destructure anywhere
|
|
106
|
+
if (!/\}\s*=\s*props\(_storeKey\)/.test(code)) return code;
|
|
107
|
+
|
|
108
|
+
let ast;
|
|
109
|
+
try {
|
|
110
|
+
ast = acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" });
|
|
111
|
+
} catch (e) {
|
|
112
|
+
return code;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 1 ── locate the compiled factory: `export default (_instanceKey) => { ... }`
|
|
116
|
+
let factory = null;
|
|
117
|
+
ast.body.forEach((st) => {
|
|
118
|
+
if (st.type === "ExportDefaultDeclaration" && isFn(st.declaration.type)) factory = st.declaration;
|
|
119
|
+
});
|
|
120
|
+
if (!factory || factory.body.type !== "BlockStatement") return code;
|
|
121
|
+
const factoryBody = factory.body;
|
|
122
|
+
|
|
123
|
+
// 2 ── collect target bindings from DIRECT statements of the factory body
|
|
124
|
+
const bindings = {}; // localName -> { key, dflt }
|
|
125
|
+
const declPatterns = []; // ObjectPattern nodes of the target declarations (skip refs inside)
|
|
126
|
+
factoryBody.body.forEach((st) => {
|
|
127
|
+
if (st.type !== "VariableDeclaration") return;
|
|
128
|
+
st.declarations.forEach((decl) => {
|
|
129
|
+
if (!decl.id || decl.id.type !== "ObjectPattern") return;
|
|
130
|
+
if (!decl.init || decl.init.type !== "CallExpression" || !decl.init.callee || decl.init.callee.name !== "props") return;
|
|
131
|
+
declPatterns.push(decl.id);
|
|
132
|
+
decl.id.properties.forEach((p) => {
|
|
133
|
+
if (p.type !== "Property" || p.computed || !p.key || !p.key.name) return; // rest / computed key -> snapshot
|
|
134
|
+
if (p.value.type === "Identifier") bindings[p.value.name] = { key: p.key.name, dflt: null };
|
|
135
|
+
else if (p.value.type === "AssignmentPattern" && p.value.left.type === "Identifier")
|
|
136
|
+
bindings[p.value.left.name] = { key: p.key.name, dflt: code.slice(p.value.right.start, p.value.right.end) };
|
|
137
|
+
// nested { a: { b } } patterns -> snapshot
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
if (!Object.keys(bindings).length) return code;
|
|
142
|
+
|
|
143
|
+
// one shared live accessor per instance; suffix the name on the off chance it collides
|
|
144
|
+
let propsRef = "__props";
|
|
145
|
+
while (code.indexOf(propsRef) !== -1) propsRef += "$";
|
|
146
|
+
|
|
147
|
+
const repl = (name) => {
|
|
148
|
+
const b = bindings[name];
|
|
149
|
+
const read = propsRef + "." + b.key;
|
|
150
|
+
return b.dflt === null ? read : "(" + read + " === undefined ? (" + b.dflt + ") : " + read + ")";
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// 3 ── walk every identifier, classify, shadow-check, collect edits
|
|
154
|
+
const edits = [];
|
|
155
|
+
walk.fullAncestor(ast, (node, state, ancestors) => {
|
|
156
|
+
if (node.type !== "Identifier" || !bindings[node.name]) return;
|
|
157
|
+
const parent = ancestors[ancestors.length - 2];
|
|
158
|
+
if (!parent) return;
|
|
159
|
+
|
|
160
|
+
// inside one of the target destructure patterns (the kept declaration itself)
|
|
161
|
+
if (declPatterns.some((dp) => within(node, dp))) return;
|
|
162
|
+
|
|
163
|
+
// non-reference positions
|
|
164
|
+
if (parent.type === "Property" && parent.key === node && !parent.computed && !parent.shorthand) return;
|
|
165
|
+
if (parent.type === "MemberExpression" && parent.property === node && !parent.computed) return;
|
|
166
|
+
if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) return;
|
|
167
|
+
if (parent.type.indexOf("Import") === 0 || parent.type === "ExportSpecifier") return;
|
|
168
|
+
if ((parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement") && parent.label === node) return;
|
|
169
|
+
if (isFn(parent.type) && parent.id === node) return;
|
|
170
|
+
if (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") {
|
|
171
|
+
if (parent.id === node) return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// binding positions & shadow scopes — walk ancestors innermost -> factory body
|
|
175
|
+
let inFactory = false;
|
|
176
|
+
for (let i = ancestors.length - 2; i >= 0; i--) {
|
|
177
|
+
const a = ancestors[i];
|
|
178
|
+
if (a === factoryBody) {
|
|
179
|
+
inFactory = true;
|
|
180
|
+
break; // the factory body holds the (kept) target declaration — not a shadow
|
|
181
|
+
}
|
|
182
|
+
// binding position?
|
|
183
|
+
if (a.type === "VariableDeclarator" && within(node, a.id)) return;
|
|
184
|
+
if (isFn(a.type) && a.params.length && node.start >= a.params[0].start && node.end <= a.params[a.params.length - 1].end) return;
|
|
185
|
+
if (a.type === "CatchClause" && a.param && within(node, a.param)) return;
|
|
186
|
+
// shadowed by this scope?
|
|
187
|
+
const declared = new Set();
|
|
188
|
+
if (isFn(a.type)) {
|
|
189
|
+
a.params.forEach((p) => patternNames(p, declared));
|
|
190
|
+
hoistedNames(a.body, declared);
|
|
191
|
+
} else {
|
|
192
|
+
lexicalNames(a, declared);
|
|
193
|
+
}
|
|
194
|
+
if (declared.has(node.name)) return;
|
|
195
|
+
}
|
|
196
|
+
if (!inFactory) return; // reference outside the factory (imports area) — leave it
|
|
197
|
+
|
|
198
|
+
// `({ color })` shorthand in an object EXPRESSION needs the key spelled out
|
|
199
|
+
const grand = ancestors[ancestors.length - 3];
|
|
200
|
+
if (parent.type === "Property" && parent.shorthand && parent.value === node && grand && grand.type === "ObjectExpression") {
|
|
201
|
+
edits.push({ start: node.start, end: node.end, text: node.name + ": " + repl(node.name) });
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (parent.type === "Property" && parent.shorthand && parent.value === node) return; // shorthand inside a pattern
|
|
205
|
+
|
|
206
|
+
edits.push({ start: node.start, end: node.end, text: repl(node.name) });
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
if (!edits.length) return code;
|
|
210
|
+
// inject the shared accessor right after the factory's first statement
|
|
211
|
+
// (`const _storeKey = ...;`) — same line, so line numbering is unchanged
|
|
212
|
+
const anchor = factoryBody.body[0];
|
|
213
|
+
edits.push({ start: anchor.end, end: anchor.end, text: " const " + propsRef + " = props(_storeKey);" });
|
|
214
|
+
edits.sort((a, b) => b.start - a.start);
|
|
215
|
+
let out = code;
|
|
216
|
+
edits.forEach((e) => (out = out.slice(0, e.start) + e.text + out.slice(e.end)));
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
module.exports = transform;
|
package/lib/parser.js
CHANGED
|
@@ -7,6 +7,7 @@ const toJs = require("./toJs");
|
|
|
7
7
|
const path = require("path");
|
|
8
8
|
const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, getPropsAliases } = require("./helpers");
|
|
9
9
|
const createSourceMap = require("./sourcemap");
|
|
10
|
+
const liveProps = require("./liveProps");
|
|
10
11
|
|
|
11
12
|
const parser = (str, counter, filePath) => {
|
|
12
13
|
// start: calc lines above script tag (from line 1 to script tag)
|
|
@@ -113,7 +114,7 @@ const parser = (str, counter, filePath) => {
|
|
|
113
114
|
js = js.replace(/props\(\s*\)/g, "props(_storeKey)");
|
|
114
115
|
html = html.replace(/props\(\s*\)/g, "props(_storeKey)");
|
|
115
116
|
|
|
116
|
-
|
|
117
|
+
let out = `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const _storeKey=_instanceKey||"${compName}"; ${js}
|
|
117
118
|
var el_${currentID} = olum.mkElm("div", "${compName}", "${currentID}");
|
|
118
119
|
var host = el_${currentID};
|
|
119
120
|
var methods_${currentID} = {${globalMethods}};
|
|
@@ -142,7 +143,6 @@ const parser = (str, counter, filePath) => {
|
|
|
142
143
|
props: olum_${currentID}.props,
|
|
143
144
|
__OLUM__: olum_${currentID},
|
|
144
145
|
el: el_${currentID},
|
|
145
|
-
incomingPropsProxy: olum.props(_storeKey),
|
|
146
146
|
methodsRef: methods_${currentID},
|
|
147
147
|
${isDev ? `stateProps: ${hasState ? "state" : "null"},` : ""}
|
|
148
148
|
hooks: {
|
|
@@ -152,7 +152,14 @@ const parser = (str, counter, filePath) => {
|
|
|
152
152
|
isUnMounted: false,
|
|
153
153
|
}
|
|
154
154
|
};
|
|
155
|
-
}
|
|
155
|
+
};`;
|
|
156
|
+
// LIVE destructured props: rewrite references to `const { x } = props()` bindings into
|
|
157
|
+
// live props(_storeKey).x reads. Runs on the assembled module (inline edits only, so
|
|
158
|
+
// line numbering — and therefore the identity source map below — stays aligned).
|
|
159
|
+
try {
|
|
160
|
+
out = liveProps(out);
|
|
161
|
+
} catch (e) {}
|
|
162
|
+
return out + `
|
|
156
163
|
//# sourceMappingURL=data:application/json;charset=utf-8;base64,${createSourceMap(str, filePath)}`;
|
|
157
164
|
};
|
|
158
165
|
|
package/package.json
CHANGED
package/tests/compiler.test.js
CHANGED
|
@@ -409,7 +409,7 @@ check(
|
|
|
409
409
|
check(
|
|
410
410
|
"forwarding a destructured prop emits a kind-props source (function props survive nesting)",
|
|
411
411
|
comp(`<C onMessage="{onMessage}" />`, `import C from "./C";\nconst { onMessage } = props();`),
|
|
412
|
-
(out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && /onMessage: onMessage/.test(out) && !/onMessage:method/.test(out) && parses(out)
|
|
412
|
+
(out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && /onMessage: __props\.onMessage/.test(out) && !/onMessage:method/.test(out) && parses(out)
|
|
413
413
|
);
|
|
414
414
|
|
|
415
415
|
check(
|
|
@@ -423,7 +423,8 @@ check(
|
|
|
423
423
|
// name — the compiler must wrap the call in an anon handler whose closure holds the prop
|
|
424
424
|
"calling a destructured prop in an event handler wraps it in an anon method",
|
|
425
425
|
comp(`<button onclick="onclick()">x</button>`, `const { onclick } = props();`),
|
|
426
|
-
|
|
426
|
+
// liveProps also rewrites the closure body to a live read: { props(_storeKey).onclick() }
|
|
427
|
+
(out) => /__olumAnon_\w+ = \(\$event\) => \{ __props\.onclick\(\) \}/.test(out) && /onclick\|__olumAnon_/.test(out) && parses(out)
|
|
427
428
|
);
|
|
428
429
|
|
|
429
430
|
check(
|
|
@@ -623,6 +624,48 @@ checkFn(
|
|
|
623
624
|
(out) => !/\/404/.test(out) && !/err:/.test(out) && /\{ path: "\/", comp: App \}/.test(out) && /\{ path: "\/about", comp: About \}/.test(out)
|
|
624
625
|
);
|
|
625
626
|
|
|
627
|
+
// ── §21 live destructured props (lib/liveProps.js) ────────────────────────────
|
|
628
|
+
// `const { x } = props()` bindings are rewritten at every reference into live
|
|
629
|
+
// props(_storeKey).x reads — templates, methods, and anonymous handlers alike.
|
|
630
|
+
section("§21 Live destructured props");
|
|
631
|
+
|
|
632
|
+
const LIVE_FIXTURE = `<script>
|
|
633
|
+
import { props } from "olum";
|
|
634
|
+
const { color, size = "md", theme: t } = props();
|
|
635
|
+
const shout = () => color + "!";
|
|
636
|
+
const shadowed = (color) => color.trim();
|
|
637
|
+
const payload = () => ({ color });
|
|
638
|
+
const keyed = { color: 1 };
|
|
639
|
+
const member = (o) => o.color;
|
|
640
|
+
</script>
|
|
641
|
+
<p>{color} {size} {t}</p>
|
|
642
|
+
<for each="color of [1,2]"><i>{color}</i></for>`;
|
|
643
|
+
|
|
644
|
+
check("template reference becomes a live read", LIVE_FIXTURE, (out) => /esc\(__props\.color\)/.test(tmpl(out)));
|
|
645
|
+
|
|
646
|
+
check("method body reference is rewritten too", LIVE_FIXTURE, (out) => /__props\.color \+ "!"/.test(out));
|
|
647
|
+
|
|
648
|
+
check("a default becomes an undefined-guarded ternary", LIVE_FIXTURE, (out) =>
|
|
649
|
+
/__props\.size === undefined \? \("md"\) : __props\.size/.test(out)
|
|
650
|
+
);
|
|
651
|
+
|
|
652
|
+
check("an alias reads its original prop key", LIVE_FIXTURE, (out) => /esc\(__props\.theme\)/.test(tmpl(out)));
|
|
653
|
+
|
|
654
|
+
check("a shadowing param is left alone", LIVE_FIXTURE, (out) => /\(color\) => color\.trim\(\)/.test(out));
|
|
655
|
+
|
|
656
|
+
// the <for> compiles color into a callback param; the inner {color} must stay bare
|
|
657
|
+
check("a loop variable shadowing the prop is left alone", LIVE_FIXTURE, (out) =>
|
|
658
|
+
/map\(function\(color\)/.test(tmpl(out)) && /<i>\$\{olum\.esc\(color\)\}<\/i>/.test(tmpl(out))
|
|
659
|
+
);
|
|
660
|
+
|
|
661
|
+
check("object-expression shorthand expands with its key; keys and members untouched", LIVE_FIXTURE, (out) =>
|
|
662
|
+
/\(\{ color: __props\.color \}\)/.test(out) && /\{ color: 1 \}/.test(out) && /o\.color/.test(out)
|
|
663
|
+
);
|
|
664
|
+
|
|
665
|
+
check("the declaration is kept and the output still parses", LIVE_FIXTURE, (out) =>
|
|
666
|
+
/\{ color, size = "md", theme: t \} = props\(_storeKey\)/.test(out) && parses(out)
|
|
667
|
+
);
|
|
668
|
+
|
|
626
669
|
console.log("\n========================");
|
|
627
670
|
const summary = `${passed} passed, ${failed} failed`;
|
|
628
671
|
console.log((failed ? red(bold(summary)) : green(bold(summary))) + "\n");
|
|
@@ -644,7 +687,7 @@ if (failed) {
|
|
|
644
687
|
|
|
645
688
|
// Guard against a whole section silently disappearing (a bad merge, a `check` that
|
|
646
689
|
// throws before registering, etc.). Bump EXPECTED_CHECKS when you add/remove tests.
|
|
647
|
-
const EXPECTED_CHECKS =
|
|
690
|
+
const EXPECTED_CHECKS = 66;
|
|
648
691
|
const total = passed + failed;
|
|
649
692
|
if (total !== EXPECTED_CHECKS) {
|
|
650
693
|
console.log(yellow(`⚠ ran ${total} checks but expected ${EXPECTED_CHECKS} — did a test get dropped?`) + "\n");
|