olum-compiler 0.7.0 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/copySrc.js CHANGED
@@ -1,10 +1,15 @@
1
1
  // todo check changed files only to be copied, use this project https://github.com/eissapk/diff
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
- const { copy, remove, rewriteImports, ls, generateRouteManifest, generateImports, generateRoutes } = require("../lib/helpers");
4
+ const { copy, remove, routerParamsParser, ls, generateRouteManifest, generateImports, generateRoutes } = require("../lib/helpers");
5
5
 
6
- const entryPoint = path.resolve(__dirname, "../../src");
7
- const entryPoint2 = path.resolve(__dirname, "../../public");
6
+
7
+ // for testing
8
+ // const entryPoint = path.resolve(__dirname, "../../src");
9
+ // const entryPoint2 = path.resolve(__dirname, "../../public");
10
+ // for production
11
+ const entryPoint = path.resolve(process.cwd(), "src");
12
+ const entryPoint2 = path.resolve(process.cwd(), "public");
8
13
  module.exports = function copySrc() {
9
14
  return new Promise((resolve, reject) => {
10
15
  try {
@@ -33,7 +38,8 @@ module.exports = function copySrc() {
33
38
  const manifest = generateRouteManifest(routes, entryPoint);
34
39
  let has404Page = false;
35
40
  if (manifest['not-found']) has404Page = true;
36
- const libImports = `import Olum from "/node_modules/olum/dist/olum.js";\nimport Router from "/node_modules/olum-router/dist/router.js";`;
41
+ const libImports = `import Olum from "/node_modules/olum/dist/olum.js";\nimport Router from "/node_modules/olum-router/dist/router.js";`; // for production
42
+ // const libImports = `import Olum from "../core/app.js";\nimport Router from "../core/router.js";`; // for testing
37
43
  const imports = generateImports(manifest).replace(/.html/g, ".js"); // fix extension by replacing .html with .js since components are js modules
38
44
  const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
39
45
  routes = generateRoutes(manifest);
@@ -46,7 +52,15 @@ module.exports = function copySrc() {
46
52
  const mainJsPath = path.resolve(__dirname, "../src/main.js");
47
53
  fs.writeFileSync(mainJsPath, `${libImports}\n${imports}\n${routes}\n${config}`);
48
54
  });
49
- copy(entryPoint2, path.resolve(__dirname, "../public"));
55
+ copy(entryPoint2, path.resolve(__dirname, "../public"), () => {
56
+ const indexHtmlPath = path.resolve(__dirname, "../public/index.html");
57
+ let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
58
+ // auto bind router params handler
59
+ indexHtmlContent = indexHtmlContent.replace(/<body>/, `\n<body>\n${routerParamsParser}`);
60
+ // auto bind div#app placeholder and mainjs script to index.html
61
+ indexHtmlContent = indexHtmlContent.replace(/<\/body>/, `\n<div id="app"></div>\n<script defer type="module" src="../src/main.js"></script>\n</body>`);
62
+ fs.writeFileSync(indexHtmlPath, indexHtmlContent);
63
+ });
50
64
  resolve();
51
65
  } catch (err) {
52
66
  reject();
package/bin/dev.js CHANGED
@@ -8,18 +8,25 @@ const fs = require("fs");
8
8
 
9
9
  let instance;
10
10
  const entryPoint = path.resolve(__dirname, "../public");
11
- serve(entryPoint).then(({ server, wsPort, PORT, log }) => {
11
+ serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
12
12
  // initial compiling
13
13
  copySrc().then(() => {
14
14
  compile().then(() => {
15
- server.listen(PORT, () => console.log(log));
16
- // console.log("initial compiling");
15
+ // EADDRINUSE is emitted as an 'error' event (not thrown), so retry on the next port
16
+ server.on("error", (e) => { if (e.code === "EADDRINUSE") server.listen(++PORT); });
17
+ server.listen(PORT, () => console.log(log.replace(/:\d+/, ":" + PORT)));
18
+
17
19
  watch.on("change", handleChange);
18
- const wss = new WebSocket.Server({ port: wsPort });
19
- wss.on("connection", (ws) => {
20
- instance = ws;
21
- ws.send(JSON.stringify({ msg: "connected" }));
22
- });
20
+
21
+ (function startWs(port) {
22
+ const wss = new WebSocket.Server({ port });
23
+ wss.on("listening", () => setWsPort(port)); // tell server.js the real ws port to inject
24
+ wss.on("error", (e) => { if (e.code === "EADDRINUSE") startWs(port + 1); });
25
+ wss.on("connection", (ws) => {
26
+ instance = ws;
27
+ ws.send(JSON.stringify({ msg: "connected" }));
28
+ });
29
+ })(wsPort);
23
30
  });
24
31
  });
25
32
  });
package/bin/server.js CHANGED
@@ -5,7 +5,7 @@ const http = require("http");
5
5
  const jsdom = require("jsdom");
6
6
  const colors = require("../lib/colors");
7
7
  const mimes = require("./mimes.json");
8
- const wsPort = 8090;
8
+ let wsPort = 8090;
9
9
 
10
10
  function handleWsFile() {
11
11
  let file = fs.readFileSync(path.resolve(__dirname, "./ws.js")).toString();
@@ -18,13 +18,30 @@ function getPath(entry, url) {
18
18
  entry = entry.endsWith("/") ? entry : entry + "/";
19
19
  url = url.startsWith("/") ? url.slice(1) : url;
20
20
 
21
- const paths = [
22
- path.resolve(entry, url),
23
- path.resolve(entry, "../", url),
24
- path.resolve(process.cwd(), url),
25
- ];
21
+ const resolve = candidate =>
22
+ [
23
+ path.resolve(entry, candidate),
24
+ path.resolve(entry, "../", candidate),
25
+ path.resolve(process.cwd(), candidate),
26
+ ].find(p => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
26
27
 
27
- return paths.find(fs.existsSync) || null;
28
+ // Exact match first (preserves the original behaviour).
29
+ const direct = resolve(url);
30
+ if (direct) return direct;
31
+
32
+ // Assets are referenced relatively in index.html (e.g. "./main.css"), so when
33
+ // a nested client-side route like /blog/x is open the browser requests them as
34
+ // /blog/main.css. Progressively drop leading route segments so the asset still
35
+ // resolves to its real location (/blog/main.css -> main.css).
36
+ if (path.extname(url)) {
37
+ const segments = url.split("/");
38
+ for (let i = 1; i < segments.length; i++) {
39
+ const found = resolve(segments.slice(i).join("/"));
40
+ if (found) return found;
41
+ }
42
+ }
43
+
44
+ return null;
28
45
  }
29
46
  // todo handle https
30
47
  /**
@@ -82,7 +99,10 @@ function serve(entry, port) {
82
99
  res.end("404 Not Found: " + urlPath);
83
100
  }
84
101
  const log = colors("cyan", "Serving ") + colors("green", domain);
85
- resolve({ server: server, wsPort: wsPort, PORT: PORT, log: log });
102
+ // setWsPort lets dev.js report the port the ws server actually bound to (it may
103
+ // retry off 8090 if that's taken) so handleWsFile injects the matching port.
104
+ const setWsPort = (port) => { wsPort = port; };
105
+ resolve({ server: server, wsPort: wsPort, PORT: PORT, log: log, setWsPort: setWsPort });
86
106
  });
87
107
  }
88
108
 
package/bin/watcher.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const chokidar = require("chokidar");
2
2
  const path = require("path");
3
- const entryPoint = path.resolve(__dirname, "../../../src");
3
+ const entryPoint = path.resolve(__dirname, "../../src");
4
+ const entryPoint2 = path.resolve(__dirname, "../../public");
4
5
  // let ignoreRegex = /\_\.js$/;
5
6
  // module.exports = chokidar.watch(entryPoint, {ignored: ignoreRegex, persistent: true });
6
- module.exports = chokidar.watch(entryPoint, { persistent: true });
7
+ module.exports = chokidar.watch([entryPoint, entryPoint2], { persistent: true });
package/lib/helpers.js CHANGED
@@ -663,6 +663,57 @@ ${routes
663
663
  ];`;
664
664
  }
665
665
 
666
+ // todo: move it to olum-router and bind it from there to window
667
+ const routerParamsParser = `<script>
668
+ /**
669
+ * Extract route params from a file path and pathname.
670
+ *
671
+ * @param {string} filePath
672
+ * @param {string} pathname
673
+ * @returns {Record<string, string | string[]>}
674
+ *
675
+ * Examples:
676
+ * extractParams("/blog/[slug]/page.html", "/blog/hello")
677
+ * -> { slug: "hello" }
678
+ *
679
+ * extractParams("/users/[id]/posts/[postId]/page.html", "/users/5/posts/10")
680
+ * -> { id: "5", postId: "10" }
681
+ */
682
+ function extractParams(filePath, pathname) {
683
+ const routeParts = filePath
684
+ .replace(/\\/page\\.[^/]+$/, "")
685
+ .split("/")
686
+ .filter(Boolean);
687
+
688
+ const pathParts = pathname.split("/").filter(Boolean);
689
+
690
+ const params = {};
691
+
692
+ let i = routeParts.length - 1;
693
+ let j = pathParts.length - 1;
694
+
695
+ while (i >= 0 && j >= 0) {
696
+ const part = routeParts[i];
697
+
698
+ // [...slug]
699
+ if (part.startsWith("[...") && part.endsWith("]")) {
700
+ params[part.slice(4, -1)] = pathParts.slice(0, j + 1);
701
+ break;
702
+ }
703
+
704
+ // [slug]
705
+ if (part.startsWith("[") && part.endsWith("]")) {
706
+ params[part.slice(1, -1)] = decodeURIComponent(pathParts[j]);
707
+ }
708
+
709
+ i--;
710
+ j--;
711
+ }
712
+
713
+ return params;
714
+ }
715
+ </script>`;
716
+
666
717
  module.exports.isNum = isNum;
667
718
  module.exports.id = id;
668
719
  module.exports.isUpper = isUpper;
@@ -688,3 +739,4 @@ module.exports.rewriteImports = rewriteImports;
688
739
  module.exports.generateRouteManifest = generateRouteManifest;
689
740
  module.exports.generateImports = generateImports;
690
741
  module.exports.generateRoutes = generateRoutes;
742
+ module.exports.routerParamsParser = routerParamsParser;
package/lib/parser.js CHANGED
@@ -122,9 +122,10 @@ const parser = (str, counter, filePath) => {
122
122
 
123
123
  // children is declared inside getElm (not at factory-call time) so it re-reads the store on every render
124
124
  const childrenVar = `const children=(olum.app.store[_storeKey]&&olum.app.store[_storeKey].children)||"";`;
125
+ const routerParamsProxy = `const params = new Proxy({},{ get(_, key) { const values = extractParams(currentFilePath, location.pathname); return values[key];}, ownKeys() { return Reflect.ownKeys(extractParams(currentFilePath, location.pathname));},getOwnPropertyDescriptor() {return {enumerable: true,configurable: true,};},});`;
125
126
 
126
127
  // bind props proxy at the top to be accessed by ${js} code
127
- return `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const _storeKey=_instanceKey||"${compName}";${minifyJS(propsProxy)}${js}
128
+ return `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const currentFilePath = "${filePath}"; ${routerParamsProxy} const _storeKey=_instanceKey||"${compName}"; ${minifyJS(propsProxy)}${js}
128
129
  var el_${currentID} = olum.mkElm("div", "${compName}", "${currentID}");
129
130
  var $0 = el_${currentID};
130
131
  var methods_${currentID} = {${globalMethods}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "0.7.0",
3
+ "version": "0.8.5",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {