olum-compiler 1.1.6 → 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.
@@ -3,7 +3,10 @@
3
3
  "allow": [
4
4
  "Bash(npm run *)",
5
5
  "Bash(cd *)",
6
- "Bash(echo \"exit: $?\")"
6
+ "Bash(echo \"exit: $?\")",
7
+ "Bash(git add *)",
8
+ "Bash(git commit *)",
9
+ "Bash(git check-ignore *)"
7
10
  ]
8
11
  }
9
12
  }
package/bin/build.js CHANGED
@@ -1,9 +1,15 @@
1
- const path = require("path");
2
- const mode = require("../lib/mode");
3
- console.log("build.js");
1
+ const bundle = require("./bundle");
2
+ const compile = require("./compiler");
3
+ const copySrc = require("./copySrc");
4
4
 
5
- const files = [
6
- path.resolve(__dirname, "../core/devtool.js"),
7
- path.resolve(__dirname, "../lib/parser.js")
8
- ];
9
- // mode(files, false); // related to isDev prop
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 = 0;
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
- const result = spawn.sync("node", [compilerPath], { stdio: "inherit" });
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
- console.log(colors("white", "Build no."), colors("yellow", num));
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, remove, compileRoutes } = require("../lib/helpers");
3
+ const { copy, compileRoutes } = require("../lib/helpers");
5
4
  const importMap = require("../lib/importMap");
6
- const entryPoint = path.resolve(process.cwd(), "src").replace(/\/module/, "");
7
- const entryPoint2 = path.resolve(process.cwd(), "public").replace(/\/module/, "");
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
- module.exports = function copySrc() {
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
- // clean
13
- if (fs.existsSync(path.resolve(__dirname, "../public"))) remove(path.resolve(__dirname, "../public"));
14
- if (fs.existsSync(path.resolve(__dirname, "../src"))) remove(path.resolve(__dirname, "../src"));
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, path.resolve(__dirname, "../src"), () => {
17
- const mainJsContent = compileRoutes(entryPoint);
18
- // automated main.js -- new concept
19
- const mainJsPath = path.resolve(__dirname, "../src/main.js");
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(/:\d+/, ":" + PORT)));
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("add", handleChange);
23
- watch.on("change", handleChange);
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
- function handleChange(file) {
50
- copySrc()
51
- .then(() => {
52
- if (file.endsWith("css") && instance) return instance.send(JSON.stringify({ msg: "css" }));
53
- compile().then(() => {
54
- const logs = getLogs();
55
- if (logs && instance) return instance.send(JSON.stringify({ msg: "warn", data: logs }));
56
- instance ? instance.send(JSON.stringify({ msg: "reload" })) : null;
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) {
@@ -74,7 +73,7 @@ function serve(entry, port) {
74
73
  const html = dom.querySelector("html");
75
74
  const wsContent = handleWsFile();
76
75
  dom.body.insertAdjacentHTML("beforeend", wsContent);
77
- res.writeHead(200, { "content-type": "text/html" });
76
+ res.writeHead(200, { "content-type": "text/html", "cache-control": "no-cache" });
78
77
  res.end("<!DOCTYPE html>" + html.outerHTML);
79
78
  });
80
79
  }
@@ -86,7 +85,9 @@ function serve(entry, port) {
86
85
  if (finalPath && fs.statSync(finalPath).isFile()) {
87
86
  const ext = path.extname(finalPath).toLowerCase();
88
87
  const obj = mimes.find(item => ext === item.ext.toLowerCase());
89
- res.writeHead(200, { "Content-Type": obj ? obj.mime : "application/octet-stream" });
88
+ // no-cache: without it browsers heuristically cache served JS (no headers at all),
89
+ // so a framework/runtime edit keeps running stale code until a hard refresh
90
+ res.writeHead(200, { "Content-Type": obj ? obj.mime : "application/octet-stream", "Cache-Control": "no-cache" });
90
91
  fs.createReadStream(finalPath).pipe(res);
91
92
  return;
92
93
  }
@@ -99,7 +100,7 @@ function serve(entry, port) {
99
100
  res.writeHead(404, { "content-type": "text/plain" });
100
101
  res.end("404 Not Found: " + urlPath);
101
102
  }
102
- const log = colors("cyan", "Serving ") + colors("green", domain);
103
+ const log = colors("cyan", "Serving ") + colors("green", "port " + PORT); // port only — a URL would show "localhost" even on a live server
103
104
  // setWsPort lets dev.js report the port the ws server actually bound to (it may
104
105
  // retry off 8090 if that's taken) so handleWsFile injects the matching port.
105
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 entryPoint = path.resolve(process.cwd(), "src").replace(/\/module/, "");
7
- const entryPoint2 = path.resolve(process.cwd(), "public").replace(/\/module/, "");
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
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
- const pathsArr = getTempPath();
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/events.js CHANGED
@@ -59,6 +59,31 @@ function referencesPropsAlias(str, propsAliases) {
59
59
  }
60
60
  }
61
61
 
62
+ // Loop variables in scope for an element: params of every ancestor <for each="..."> —
63
+ // "flavour of state.menu" / "(x, i) of ..." / "(key, i, value) in ...". handleEvents runs
64
+ // BEFORE handleForStatement, so the <for> ancestors still exist in the DOM.
65
+ function loopVarNames(item) {
66
+ const vars = [];
67
+ let cur = item;
68
+ while ((cur = cur.parentElement)) {
69
+ if (cur.tagName.toLowerCase() === "for" && cur.hasAttribute("each")) {
70
+ const m = cur.getAttribute("each").trim().match(/(.*)( of | in )/);
71
+ if (m) m[1].replace(/\(|\)/g, "").split(",").forEach((p) => {
72
+ p = p.trim();
73
+ if (p && !vars.includes(p)) vars.push(p);
74
+ });
75
+ }
76
+ }
77
+ return vars;
78
+ }
79
+
80
+ // Which loop variables the handler expression actually references (bare identifier,
81
+ // not a property access like obj.flavour). Over-matching is harmless — it only adds
82
+ // an unused parameter — so a word-boundary test is enough.
83
+ function usedLoopVars(str, item) {
84
+ return loopVarNames(item).filter((v) => new RegExp("(?<![.\\w$])" + v + "\\b").test(str));
85
+ }
86
+
62
87
  function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
63
88
  let name = path.basename(filePath).replace(/\.html/i, "");
64
89
  name = name.slice(0, 1).toLowerCase() + name.slice(1); // make compName camel case
@@ -69,19 +94,30 @@ function handleEvents(body, counter, filePath, anonHandlers, propsAliases) {
69
94
  if (item.hasAttribute(e)) {
70
95
  let attrValue = item.getAttribute(e).trim();
71
96
 
97
+ // Anon handlers are hoisted to component scope, where <for> loop variables don't
98
+ // exist — so any loop variable the expression references becomes an extra PARAMETER
99
+ // of the anon handler. The call site (rendered inside the loop's map callback)
100
+ // serializes the per-item value into data-o-event args, and the runtime passes it
101
+ // back on dispatch — same mechanism simple calls like onclick="remove(flavour)" use.
102
+ const loopArgs = usedLoopVars(attrValue, item);
103
+ const params = ["$event"].concat(loopArgs).join(", ");
104
+
72
105
  // inline arrow/function handler -> extract to a named method, then parse the call below
73
106
  if (looksLikeFunction(attrValue)) {
74
107
  const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
75
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = ${attrValue};`);
76
- attrValue = handlerName + "($event)";
108
+ if (anonHandlers) {
109
+ if (loopArgs.length) anonHandlers.push(`const ${handlerName} = (${params}) => (${attrValue})($event);`);
110
+ else anonHandlers.push(`const ${handlerName} = ${attrValue};`);
111
+ }
112
+ attrValue = handlerName + "(" + params + ")";
77
113
  } else if (!isSimpleCallList(attrValue) || referencesPropsAlias(attrValue, propsAliases)) {
78
114
  // not a plain `name(args)` call list — e.g. a function prop call props().toggle(id)
79
115
  // or a statement like state.count++ — OR a call touching a destructured prop
80
116
  // (onclick="onclick()") — wrap the whole expression in an anon handler
81
117
  // so it executes as-is in component scope ($event = the DOM event)
82
118
  const handlerName = "__olumAnon_" + Math.random().toString(36).slice(2, 9);
83
- if (anonHandlers) anonHandlers.push(`const ${handlerName} = ($event) => { ${attrValue} };`);
84
- attrValue = handlerName + "($event)";
119
+ if (anonHandlers) anonHandlers.push(`const ${handlerName} = (${params}) => { ${attrValue} };`);
120
+ attrValue = handlerName + "(" + params + ")";
85
121
  }
86
122
 
87
123
  let methods = attrValue.split("),");
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.proxyHandlerForStore(${"{" + fragments.join(",") + "}"}, state);}`);
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.proxyHandlerForStore(${"{" + fragments.join(",") + "}"}, state);}`);
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.proxyHandlerForStore(${"{" + fragments.join(",") + "}"}, state);}`);
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/htmlParser.js CHANGED
@@ -12,7 +12,8 @@ const handleEvents = require("./events");
12
12
  const handleCompPlaceholder = require("./compPlaceholder");
13
13
  const handleHtml = require("./html");
14
14
  const handleBoolAttrs = require("./boolAttr");
15
- const { RAW_OPEN, RAW_CLOSE, LT, GT } = require("./tokens");
15
+ const handleTextarea = require("./textarea");
16
+ const { RAW_OPEN, RAW_CLOSE, LT, GT, shieldTags, unshieldTags } = require("./tokens");
16
17
 
17
18
  function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
18
19
  let content = str.replace(script, "").replace(style, "");
@@ -24,9 +25,11 @@ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
24
25
  // __olumAnon_ methods inside handleEvents (collected here, injected into the component JS later).
25
26
  const anonHandlers = [];
26
27
 
27
- // using dom parser
28
- const body = new jsdom.JSDOM(content).window.document.body;
28
+ // using dom parser — shieldTags renames parser-restricted containers (select/table/tr/…) to
29
+ // unknown elements so a <for>/<if>/<show> inside them survives the parse; restored after serialize
30
+ const body = new jsdom.JSDOM(shieldTags(content)).window.document.body;
29
31
  handleHtml(body); // html="expr" -> unescaped ${expr} content (before control-flow dissolves elements)
32
+ handleTextarea(body); // textarea value="..." -> text content (no value attribute exists on textarea)
30
33
  handleEvents(body, counter, filePath, anonHandlers, propsAliases);
31
34
  // DISABLED — :style object binding. Colon attributes are gone; use a string style with
32
35
  // {expr} interpolation instead, e.g. style="color:{state.color}". Uncomment to re-enable.
@@ -40,7 +43,7 @@ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
40
43
  handleShowStatement(body, counter, filePath);
41
44
  const comps = handleCompPlaceholder(body, counter, filePath);
42
45
 
43
- content = body.innerHTML;
46
+ content = unshieldTags(body.innerHTML);
44
47
 
45
48
  // presence-based boolean attributes: checked="{expr}" -> ${(expr) ? "checked" : ""}.
46
49
  // Must run before the {expr} escape pass below, which would otherwise interpolate the VALUE
@@ -60,7 +63,10 @@ function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
60
63
  const raw = expr.trim();
61
64
  if (raw === "children") return "${children}";
62
65
  if (/^props\(\s*\)\.children$/.test(raw)) return "${" + raw + "}";
63
- return "${olum.esc(" + expr + ")}";
66
+ // the captured expr is JS, but if it sat in a TEXT node jsdom entity-encoded its <,>,& on
67
+ // serialize — decode them back so comparisons like {width > 380 ? a : b} stay valid JS
68
+ const js = expr.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
69
+ return "${olum.esc(" + js + ")}";
64
70
  });
65
71
 
66
72
  content = content.replace(/&amp;/g, "&"); // fix entity
package/lib/importMap.js CHANGED
@@ -63,6 +63,22 @@ function toPkgName(specifier) {
63
63
  return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
64
64
  }
65
65
 
66
+ // map a package AND its transitive deps — a package's own ESM files import their deps as bare
67
+ // specifiers too (d3-scale imports "d3-array"), and the browser resolves those via the import map
68
+ function addPackage(rootDir, pkgName, imports) {
69
+ if (imports[pkgName]) return;
70
+ const entry = resolvePackage(rootDir, pkgName);
71
+ if (!entry) {
72
+ console.warn(colors("yellow", 'Can\'t resolve "' + pkgName + '" — install it at the project root: npm i ' + pkgName));
73
+ return;
74
+ }
75
+ imports[pkgName] = entry;
76
+ imports[pkgName + "/"] = "/node_modules/" + pkgName + "/"; // subpath imports e.g. "pkg/x.js"
77
+ const pkgJsonPath = path.join(rootDir, "node_modules", pkgName, "package.json");
78
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8"));
79
+ Object.keys(pkg.dependencies || {}).forEach((dep) => addPackage(rootDir, dep, imports));
80
+ }
81
+
66
82
  /**
67
83
  * Build the <script type="importmap"> tag injected into index.html so bare imports
68
84
  * (e.g. import { marked } from "marked") resolve in the browser without a bundler.
@@ -91,14 +107,8 @@ function importMap(srcDir) {
91
107
 
92
108
  getBareSpecifiers(srcDir).forEach((spec) => {
93
109
  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"
110
+ if (pkgName in localLibs) return;
111
+ addPackage(rootDir, pkgName, imports);
102
112
  });
103
113
  return '<script type="importmap">' + JSON.stringify({ imports }, null, 2) + "</script>";
104
114
  }
@@ -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
- return `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const _storeKey=_instanceKey||"${compName}"; ${js}
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
 
@@ -0,0 +1,14 @@
1
+ // <textarea value="..."> — HTML has no `value` attribute on textarea (its value is its text
2
+ // content), so a serialized value="..." would be silently ignored by the browser's parser.
3
+ // Move the attribute into the element's content, where the later {expr} escape pass
4
+ // interpolates it exactly like regular text. If the textarea also has authored content,
5
+ // the value attribute wins (they'd be two sources of truth otherwise).
6
+ function handleTextarea(body) {
7
+ const elms = Array.prototype.slice.call(body.querySelectorAll("textarea[value]"));
8
+ elms.forEach((item) => {
9
+ item.textContent = item.getAttribute("value");
10
+ item.removeAttribute("value");
11
+ });
12
+ }
13
+
14
+ module.exports = handleTextarea;
package/lib/tokens.js CHANGED
@@ -15,10 +15,21 @@
15
15
  const LT = "OLUM_LT";
16
16
  const GT = "OLUM_GT";
17
17
 
18
+ // Tag shield: the HTML5 parser restricts what these containers may hold — unknown tags are DROPPED
19
+ // inside <select> and foster-parented out of <table>/<tr> — so a <for>/<if>/<show> placed there is
20
+ // destroyed before the directive passes run. Renaming the containers to unknown elements
21
+ // (olum-select, olum-tr, …) makes the parser treat them as generic containers that keep any child;
22
+ // htmlParser restores the real names after serialization.
23
+ const restrictedTags = "select|table|caption|colgroup|col|thead|tbody|tfoot|tr|td|th";
24
+ const shieldRe = new RegExp("<(\\/?)(" + restrictedTags + ")(?=[\\s/>])", "gi");
25
+ const unshieldRe = new RegExp("<(\\/?)olum-(" + restrictedTags + ")(?=[\\s/>])", "gi");
26
+
18
27
  module.exports = {
19
28
  RAW_OPEN: "OLUM_RAW_OPEN",
20
29
  RAW_CLOSE: "OLUM_RAW_CLOSE",
21
30
  LT,
22
31
  GT,
23
32
  shieldOps: (s) => String(s).split("<").join(LT).split(">").join(GT),
33
+ shieldTags: (s) => s.replace(shieldRe, "<$1olum-$2"),
34
+ unshieldTags: (s) => s.replace(unshieldRe, "<$1$2"),
24
35
  };
package/lib/websocket.js CHANGED
@@ -81,7 +81,9 @@ class WebSocket extends EventEmitter {
81
81
  socket.end();
82
82
  });
83
83
  socket.on("error", err => {
84
- this.emit("error", err);
84
+ // only forward if someone listens — an unhandled 'error' on an EventEmitter
85
+ // would throw and take down the whole process on any abrupt disconnect
86
+ if (this.listenerCount("error") > 0) this.emit("error", err);
85
87
  socket.destroy();
86
88
  });
87
89
  socket.on("close", () => {
@@ -141,7 +143,7 @@ class WebSocket extends EventEmitter {
141
143
  payload.writeUInt16BE(code, 0);
142
144
  reason.copy(payload, 2);
143
145
  }
144
- this._socket.write(encodeFrame(0x8, payload));
146
+ if (this._socket.writable && !this._socket.writableEnded) this._socket.write(encodeFrame(0x8, payload));
145
147
  // close handshake complete → shut down the tcp stream
146
148
  if (this._closeReceived) this._socket.end();
147
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "1.1.6",
3
+ "version": "1.5.0",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -149,6 +149,14 @@ check(
149
149
  (out) => /\$\{olum\.esc\(state\.count \+ 1\)\}/.test(tmpl(out)) && parses(out)
150
150
  );
151
151
 
152
+ // jsdom entity-encodes <,>,& in text nodes on serialize — the escape pass must decode them
153
+ // back inside the captured expr or the emitted JS is broken (`width &gt; 380` → SyntaxError)
154
+ check(
155
+ "comparison operators in a text {expr} survive the jsdom round-trip",
156
+ comp(`<p>{state.width > 380 && state.width < 800 ? 'mid' : 'other'}</p>`),
157
+ (out) => /olum\.esc\(state\.width > 380 && state\.width < 800 \? 'mid' : 'other'\)/.test(tmpl(out)) && parses(out)
158
+ );
159
+
152
160
  // ── §5 String attributes (literal + {expr}) ────────────────────────────────
153
161
  section("§5 String attributes");
154
162
 
@@ -170,6 +178,21 @@ check(
170
178
  (out) => /style="color:\$\{olum\.esc\(state\.color\)\}; padding:8px;"/.test(tmpl(out)) && parses(out)
171
179
  );
172
180
 
181
+ // textarea has no `value` attribute in HTML (its value is its text content), so a
182
+ // serialized value="..." would be silently dropped by the browser's parser —
183
+ // the compiler must move it into the element's content
184
+ check(
185
+ "textarea value attribute becomes text content",
186
+ comp(`<textarea value="{state.cls}"></textarea>`),
187
+ (out) => /<textarea[^>]*>\$\{olum\.esc\(state\.cls\)\}<\/textarea>/.test(tmpl(out)) && !/value=/.test(tmpl(out)) && parses(out)
188
+ );
189
+
190
+ check(
191
+ "textarea value attribute wins over authored content",
192
+ comp(`<textarea value="{state.cls}">stale</textarea>`),
193
+ (out) => /<textarea[^>]*>\$\{olum\.esc\(state\.cls\)\}<\/textarea>/.test(tmpl(out)) && !/stale/.test(tmpl(out)) && parses(out)
194
+ );
195
+
173
196
  // boolean attributes are truthy by PRESENCE (checked="false" is still checked), so
174
197
  // attr="{expr}" must toggle the attribute's existence, never interpolate its value
175
198
  check(
@@ -216,13 +239,33 @@ check(
216
239
  comp(`<input oninput="setVal($event)" />`, `const setVal = (e) => 0;`),
217
240
  (out) => /oninput\|setVal=\$\{JSON\.stringify\(\['\$event'\]\)\}/.test(tmpl(out)) && parses(out)
218
241
  );
219
-
220
242
  check(
221
243
  "inline arrow handler becomes a named __olumAnon_ method",
222
244
  comp(`<input oninput="(e) => state.name = e.target.value" />`),
223
245
  (out) => /__olumAnon_\w+/.test(out) && /data-o-event/.test(tmpl(out)) && parses(out)
224
246
  );
225
247
 
248
+ // anon handlers are hoisted to component scope where <for> loop variables don't exist,
249
+ // so a referenced loop variable must become a handler parameter whose per-item value
250
+ // is serialized into the data-o-event args at render time
251
+ check(
252
+ "anon handler inside <for> receives the loop variable as an argument",
253
+ comp(
254
+ `<for each="flavour of state.items"><input type="checkbox" onchange="toggle(flavour)($event)" /></for>`,
255
+ `const toggle = (f) => (e) => 0;`
256
+ ),
257
+ (out) =>
258
+ /const __olumAnon_\w+ = \(\$event, flavour\) => \{ toggle\(flavour\)\(\$event\) \}/.test(out) &&
259
+ /JSON\.stringify\(\['\$event', flavour\]\)/.test(tmpl(out)) &&
260
+ parses(out)
261
+ );
262
+
263
+ check(
264
+ "inline arrow handler inside <for> receives the loop variable as an argument",
265
+ comp(`<for each="(x, i) of state.items"><button onclick="(e) => state.count = i">x</button></for>`),
266
+ (out) => /const __olumAnon_\w+ = \(\$event, i\) =>/.test(out) && /JSON\.stringify\(\['\$event', i\]\)/.test(tmpl(out)) && parses(out)
267
+ );
268
+
226
269
  // ── §7 Conditionals <if>/<else-if>/<else> ──────────────────────────────────
227
270
  section("§7 Conditionals");
228
271
 
@@ -274,6 +317,20 @@ check(
274
317
  (out) => /data-o-key/.test(tmpl(out)) && parses(out)
275
318
  );
276
319
 
320
+ // the HTML parser drops unknown tags inside <select> and foster-parents them out of tables —
321
+ // the tag shield (tokens.js) must keep <for>/<if> alive in these containers
322
+ check(
323
+ "<for> inside <select> survives the parse and scopes the loop variable",
324
+ comp(`<select><for each="q of state.questions"><option value="{q.id}">{q.text}</option></for></select>`),
325
+ (out) => /<select>\$\{state\.questions\.map\(function\(q\)/.test(tmpl(out)) && !/<olum-select/.test(tmpl(out)) && parses(out)
326
+ );
327
+
328
+ check(
329
+ "<for> inside <table>/<tbody> is not foster-parented out",
330
+ comp(`<table><tbody><for each="row of state.rows"><tr><td>{row.a}</td></tr></for></tbody></table>`),
331
+ (out) => /<tbody>\$\{state\.rows\.map\(function\(row\)/.test(tmpl(out)) && /<tr><td>/.test(tmpl(out)) && parses(out)
332
+ );
333
+
277
334
  // ── §10 Raw HTML (html="expr" + olum.html()) ───────────────────────────────
278
335
  section("§10 Raw HTML");
279
336
 
@@ -352,7 +409,7 @@ check(
352
409
  check(
353
410
  "forwarding a destructured prop emits a kind-props source (function props survive nesting)",
354
411
  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)
412
+ (out) => /data-o-props-src="onMessage:props:onMessage"/.test(out) && /onMessage: __props\.onMessage/.test(out) && !/onMessage:method/.test(out) && parses(out)
356
413
  );
357
414
 
358
415
  check(
@@ -366,7 +423,8 @@ check(
366
423
  // name — the compiler must wrap the call in an anon handler whose closure holds the prop
367
424
  "calling a destructured prop in an event handler wraps it in an anon method",
368
425
  comp(`<button onclick="onclick()">x</button>`, `const { onclick } = props();`),
369
- (out) => /__olumAnon_\w+ = \(\$event\) => \{ onclick\(\) \}/.test(out) && /onclick\|__olumAnon_/.test(out) && parses(out)
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)
370
428
  );
371
429
 
372
430
  check(
@@ -566,6 +624,48 @@ checkFn(
566
624
  (out) => !/\/404/.test(out) && !/err:/.test(out) && /\{ path: "\/", comp: App \}/.test(out) && /\{ path: "\/about", comp: About \}/.test(out)
567
625
  );
568
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
+
569
669
  console.log("\n========================");
570
670
  const summary = `${passed} passed, ${failed} failed`;
571
671
  console.log((failed ? red(bold(summary)) : green(bold(summary))) + "\n");
@@ -587,7 +687,7 @@ if (failed) {
587
687
 
588
688
  // Guard against a whole section silently disappearing (a bad merge, a `check` that
589
689
  // throws before registering, etc.). Bump EXPECTED_CHECKS when you add/remove tests.
590
- const EXPECTED_CHECKS = 51;
690
+ const EXPECTED_CHECKS = 66;
591
691
  const total = passed + failed;
592
692
  if (total !== EXPECTED_CHECKS) {
593
693
  console.log(yellow(`⚠ ran ${total} checks but expected ${EXPECTED_CHECKS} — did a test get dropped?`) + "\n");