olum-compiler 1.7.0 → 1.8.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/bin/bundle.js CHANGED
@@ -2,7 +2,7 @@ const path = require("path");
2
2
  const fs = require("fs");
3
3
  const colors = require("../lib/colors");
4
4
  const spawn = require("../lib/cross-spawn");
5
- const { useLocalCore, localLibs } = require("../lib/coreLibs");
5
+ const { useLocalCore, localLibs, optionalLibs } = require("../lib/coreLibs");
6
6
 
7
7
  const cwd = process.cwd();
8
8
  const public = path.resolve(__dirname, "../public");
@@ -93,6 +93,12 @@ async function bundle(bootAt) {
93
93
  }
94
94
  }
95
95
 
96
+ const external = useLocalCore
97
+ ? []
98
+ : optionalLibs.filter(
99
+ (pkgName) => !fs.existsSync(path.join(root, "node_modules", pkgName)),
100
+ );
101
+
96
102
  const buildResult = await build({
97
103
  root: public,
98
104
  resolve: { alias },
@@ -102,6 +108,7 @@ async function bundle(bootAt) {
102
108
 
103
109
  assetsInlineLimit: 0,
104
110
  rollupOptions: {
111
+ external,
105
112
  output: {
106
113
  assetFileNames(info) {
107
114
  const orig = (info.originalFileNames || [])[0];
package/bin/copySrc.js CHANGED
@@ -2,11 +2,20 @@ const path = require("path");
2
2
  const fs = require("fs");
3
3
  const { copy, compileRoutes } = require("../lib/helpers");
4
4
  const importMap = require("../lib/importMap");
5
+ const usage = require("../lib/usage");
5
6
 
6
7
  const cwd = process.cwd();
7
8
  const entryPoint = path.resolve(cwd.replace(/\/module$/, ""), "src");
8
9
  const entryPoint2 = path.resolve(cwd.replace(/\/module$/, ""), "public");
9
10
 
11
+ const devtoolSrc = path.resolve(
12
+ cwd.replace(/\/module$/, ""),
13
+ "node_modules/olum-devtool/dist",
14
+ );
15
+ const devtoolScript = path.resolve(devtoolSrc, "./script.js");
16
+ const devtoolEnabled =
17
+ process.env.NODE_ENV === "development" && fs.existsSync(devtoolScript);
18
+
10
19
  const srcDest = path.resolve(__dirname, "../src");
11
20
  const publicDest = path.resolve(__dirname, "../public");
12
21
  const indexHtmlDest = path.resolve(__dirname, "../public/index.html");
@@ -14,12 +23,15 @@ const mainJsPathDest = path.resolve(__dirname, "../src/main.js");
14
23
 
15
24
  function injectIndexHtml(indexHtmlPath) {
16
25
  let indexHtmlContent = fs.readFileSync(indexHtmlPath).toString();
26
+ const devtoolScriptContent = devtoolEnabled
27
+ ? "<script>" + fs.readFileSync(devtoolScript).toString() + "</script>\n"
28
+ : "";
17
29
 
18
30
  const importMapTag =
19
31
  process.env.NODE_ENV === "production" ? "" : `${importMap(entryPoint)}\n`;
20
32
  indexHtmlContent = indexHtmlContent.replace(
21
33
  /<\/body>/,
22
- `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n</body>`,
34
+ `\n<div id="app"></div>\n${importMapTag}<script defer type="module" src="../src/main.js"></script>\n${devtoolScriptContent}</body>`,
23
35
  );
24
36
  fs.writeFileSync(indexHtmlPath, indexHtmlContent);
25
37
  }
@@ -42,8 +54,10 @@ function syncFile(event, file) {
42
54
  : path.join(publicDest, path.relative(entryPoint2, file));
43
55
  if (event.startsWith("unlink")) {
44
56
  fs.rmSync(dest, { recursive: true, force: true });
45
- if (inSrc && dest.endsWith(".html"))
57
+ if (inSrc && dest.endsWith(".html")) {
46
58
  fs.rmSync(dest.replace(/\.html$/, ".js"), { force: true });
59
+ usage.drop(dest);
60
+ }
47
61
  } else {
48
62
  fs.mkdirSync(path.dirname(dest), { recursive: true });
49
63
  fs.copyFileSync(file, dest);
@@ -75,6 +89,14 @@ module.exports = function copySrc(event, file) {
75
89
  copy(entryPoint, srcDest, () => handleMainJs());
76
90
  copy(entryPoint2, publicDest, () => injectIndexHtml(indexHtmlDest));
77
91
 
92
+ if (devtoolEnabled) {
93
+ fs.mkdirSync(publicDest + "/__olum_devtool", {
94
+ recursive: true,
95
+ force: true,
96
+ });
97
+ copy(devtoolSrc, publicDest + "/__olum_devtool");
98
+ }
99
+
78
100
  resolve(null);
79
101
  } catch (err) {
80
102
  reject(err);
package/bin/dev.js CHANGED
@@ -7,8 +7,49 @@ const colors = require("../lib/colors");
7
7
  const path = require("path");
8
8
  const fs = require("fs");
9
9
 
10
- let instance;
10
+ let sockets;
11
11
  const entryPoint = path.resolve(__dirname, "../public");
12
+
13
+ const lockFile = path.resolve(__dirname, "../.dev.lock");
14
+ const me = String(process.pid);
15
+ const read = () => {
16
+ try {
17
+ return fs.readFileSync(lockFile, "utf8").trim();
18
+ } catch (e) {
19
+ return "";
20
+ }
21
+ };
22
+ const alive = (pid) => {
23
+ try {
24
+ return !!process.kill(pid, 0);
25
+ } catch (e) {
26
+ return e.code === "EPERM";
27
+ }
28
+ };
29
+
30
+ const holder = Number(read());
31
+ if (holder && holder !== process.pid && alive(holder)) {
32
+ console.error(
33
+ colors(
34
+ "red",
35
+ `A dev server for this project is already running (pid ${holder}).`,
36
+ ),
37
+ );
38
+ console.error(
39
+ colors(
40
+ "white",
41
+ `Stop it first — two of them share one build output and will overwrite each other's work.\n kill ${holder} # or delete ${lockFile} if that process is gone`,
42
+ ),
43
+ );
44
+ process.exit(1);
45
+ }
46
+
47
+ fs.writeFileSync(lockFile, me);
48
+ process.on("exit", () => read() === me && fs.rmSync(lockFile, { force: true }));
49
+ ["SIGINT", "SIGTERM", "SIGHUP"].forEach((signal) =>
50
+ process.on(signal, () => process.exit(0)),
51
+ );
52
+
12
53
  serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
13
54
  const bootAt = Date.now();
14
55
  copySrc()
@@ -31,34 +72,32 @@ serve(entryPoint).then(({ server, wsPort, PORT, log, setWsPort }) => {
31
72
 
32
73
  (function startWs(port) {
33
74
  const wss = new WebSocket.Server({ server });
75
+ sockets = wss.clients;
34
76
  wss.on("listening", () => setWsPort(port));
35
77
  wss.on("error", (e) => {
36
78
  if (e.code === "EADDRINUSE") startWs(port + 1);
37
79
  });
38
- wss.on("connection", (ws) => {
39
- instance = ws;
40
- ws.send(JSON.stringify({ msg: "connected" }));
41
- });
80
+ wss.on("connection", (ws) =>
81
+ ws.send(JSON.stringify({ msg: "connected" })),
82
+ );
42
83
  })(wsPort);
43
84
  });
44
85
  })
45
86
  .catch(console.error);
46
87
  });
47
88
 
89
+ const send = (data) =>
90
+ sockets && sockets.forEach((ws) => ws.send(JSON.stringify(data)));
91
+
92
+ const logFile = path.resolve(__dirname, "../lib/log.txt");
48
93
  function getLogs() {
49
- const logFilePath = path.resolve(__dirname, "../lib/log.txt");
50
- if (fs.existsSync(logFilePath)) {
51
- return fs.readFileSync(logFilePath).toString();
52
- } else {
53
- return null;
54
- }
94
+ return fs.existsSync(logFile) ? fs.readFileSync(logFile).toString() : null;
55
95
  }
56
96
 
57
- const send = (data) => instance && instance.send(JSON.stringify(data));
58
-
59
97
  function notify() {
60
98
  const logs = getLogs();
61
- logs ? send({ msg: "warn", data: logs }) : send({ msg: "reload" });
99
+
100
+ send(logs && logs.trim() ? { msg: "warn", data: logs } : { msg: "reload" });
62
101
  }
63
102
 
64
103
  const isComp = (dest) =>
package/bin/server.js CHANGED
@@ -72,8 +72,34 @@ function serve(entry, port, mode = "development") {
72
72
  });
73
73
  }
74
74
 
75
+ function serveDevtools() {
76
+ const devtoolsPath = path.join(entry, "__olum_devtool", "index.html");
77
+
78
+ fs.readFile(devtoolsPath, (err, content) => {
79
+ if (err) {
80
+ res.writeHead(404, { "content-type": "text/plain" });
81
+ res.end("404 Not Found: " + urlPath);
82
+ return;
83
+ }
84
+ const dom = parseDOM(content.toString());
85
+ const html = dom.querySelector("html");
86
+ if (mode == "development") {
87
+ const wsContent = handleWsFile();
88
+ dom.body.insertAdjacentHTML("beforeend", wsContent);
89
+ }
90
+ res.writeHead(200, {
91
+ "content-type": "text/html",
92
+ "cache-control": "no-cache",
93
+ });
94
+ res.end("<!DOCTYPE html>" + html.outerHTML);
95
+ });
96
+ }
97
+
75
98
  if (urlPath === "/") return serveIndex();
76
99
 
100
+ if (urlPath === "/__olum_devtool" || urlPath === "/__olum_devtool/")
101
+ return serveDevtools();
102
+
77
103
  const finalPath = getPath(entry, urlPath);
78
104
  if (finalPath && fs.statSync(finalPath).isFile()) {
79
105
  const ext = path.extname(finalPath).toLowerCase();
package/bin/ws.js CHANGED
@@ -1,61 +1,67 @@
1
1
  (() => {
2
- if ("WebSocket" in window) {
3
- const parse = (str) => str.replace(/>/g, "&gt;").replace(/</g, "&lt;");
4
- const interval = 500;
5
- const maxAttempts = 30;
6
- let attempts = 0;
7
- const wsProtocol = location.protocol === "https:" ? "wss:" : "ws:";
2
+ if (!("WebSocket" in window))
3
+ return console.error(
4
+ "Upgrade your browser. This Browser is doesn't support WebSocket for Live-Reloading.",
5
+ );
8
6
 
9
- const socketUrl = `${wsProtocol}//${location.host}`;
10
- let socket = new WebSocket(socketUrl);
7
+ const url = `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}`;
8
+ const esc = (str) => str.replace(/>/g, "&gt;").replace(/</g, "&lt;");
9
+ const retry = 500;
10
+ const maxAttempts = 30;
11
+ let attempts = 0;
12
+ let dropped = false;
11
13
 
12
- socket.onmessage = function (res) {
13
- const obj = JSON.parse(res.data);
14
- if (obj.msg === "connected") enabled();
15
- if (obj.msg === "reload") window.location.reload();
16
- else if (obj.msg === "css") css();
17
- else if (obj.msg === "warn") {
18
- const stderr = obj.data.trim();
19
- const arr = stderr.split("<<Olum Warning>>");
20
- const markup = arr
21
- .map((item) => {
22
- if (item.trim() !== "")
23
- return `<pre style="border-bottom: 1px solid #ccc; padding-bottom:10px;">${parse(item)}</pre>`;
24
- })
25
- .join("");
26
- document.body.innerHTML = markup;
27
- }
28
- };
14
+ const show = (data) => {
15
+ const blocks = data
16
+ .split("<<Olum Warning>>")
17
+ .map((item) => item.trim())
18
+ .filter(Boolean);
19
+ if (!blocks.length) return;
29
20
 
30
- function enabled() {
31
- let key = "IS_FIRST_TIME_OLUM_HOT_RELOAD";
32
- if (sessionStorage && !sessionStorage.getItem(key)) {
33
- sessionStorage.setItem(key, true);
21
+ const box =
22
+ document.getElementById("olum-warning") ||
23
+ document.body.appendChild(document.createElement("div"));
24
+ box.id = "olum-warning";
25
+ box.style.cssText =
26
+ "position:fixed;top:0;left:0;right:0;z-index:2147483001;max-height:60vh;overflow:auto;padding:12px 16px;" +
27
+ "background:#1c1917;color:#fde68a;box-shadow:0 2px 12px rgba(0,0,0,.35);font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace";
28
+ box.innerHTML =
29
+ '<button style="float:right;border:0;background:none;color:inherit;font:inherit;cursor:pointer">dismiss ✕</button>' +
30
+ blocks
31
+ .map(
32
+ (item) =>
33
+ `<pre style="margin:0 0 8px;white-space:pre-wrap">${esc(item)}</pre>`,
34
+ )
35
+ .join("");
36
+ box.querySelector("button").onclick = () => box.remove();
37
+ };
34
38
 
35
- console.log("Olum hot-reload enabled.");
36
- }
37
- }
39
+ const enabled = () => {
40
+ const key = "IS_FIRST_TIME_OLUM_HOT_RELOAD";
41
+ if (!sessionStorage || sessionStorage.getItem(key)) return;
42
+ sessionStorage.setItem(key, true);
43
+ console.log("Olum hot-reload enabled.");
44
+ };
38
45
 
39
- function css() {
40
- const sheets = document.querySelectorAll("link[rel='stylesheet']");
41
- sheets.forEach((sheet) => sheet.replaceWith(sheet));
42
- }
46
+ const attach = (socket) => {
47
+ socket.onopen = () => (dropped ? location.reload() : (attempts = 0));
48
+ socket.onmessage = (event) => {
49
+ const { msg, data } = JSON.parse(event.data);
50
+ if (msg === "connected") enabled();
51
+ else if (msg === "reload") location.reload();
52
+ else if (msg === "css")
53
+ document
54
+ .querySelectorAll("link[rel='stylesheet']")
55
+ .forEach((sheet) => sheet.replaceWith(sheet));
56
+ else if (msg === "warn") show(data);
57
+ };
58
+ socket.onclose = () => {
59
+ dropped = true;
60
+ if (++attempts > maxAttempts)
61
+ return console.error("Could not reconnect to dev server.");
62
+ setTimeout(() => attach(new WebSocket(url)), retry);
63
+ };
64
+ };
43
65
 
44
- socket.addEventListener("close", () => {
45
- const reloadIfCanConnect = () => {
46
- attempts++;
47
- if (attempts > maxAttempts)
48
- return console.error("Could not reconnect to dev server.");
49
- socket = new WebSocket(socketUrl);
50
- socket.addEventListener("error", () =>
51
- setTimeout(reloadIfCanConnect, interval),
52
- );
53
- };
54
- reloadIfCanConnect();
55
- });
56
- } else {
57
- console.error(
58
- "Upgrade your browser. This Browser is doesn't support WebSocket for Live-Reloading.",
59
- );
60
- }
66
+ attach(new WebSocket(url));
61
67
  })();
package/lib/coreLibs.js CHANGED
@@ -4,6 +4,9 @@ const localLibs = {
4
4
  olum: "/core/olum.js",
5
5
  "olum-router": "/core/router.js",
6
6
  "olum-store": "/core/store.js",
7
+ "olum-transition": "/core/transition.js",
7
8
  };
8
9
 
9
- module.exports = { useLocalCore, localLibs };
10
+ const optionalLibs = ["olum-store", "olum-transition"];
11
+
12
+ module.exports = { useLocalCore, localLibs, optionalLibs };
package/lib/cssParser.js CHANGED
@@ -1,5 +1,3 @@
1
- const { style } = require("./regex");
2
-
3
1
  function escapeRe(str) {
4
2
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
3
  }
@@ -116,12 +114,8 @@ function scopeCSS(css, scopeAttr, compName) {
116
114
  return out;
117
115
  }
118
116
 
119
- function cssParser(str, scopeAttr, compName) {
120
- const arr = str.match(style);
121
- let content = Array.isArray(arr) && arr.length ? arr[arr.length - 1] : "";
122
- content = content.replace(/(<style.*?>)/, "");
123
- content = content.replace(/(<\/style>)$/, "");
124
- content = content.trim();
117
+ function cssParser(content, scopeAttr, compName) {
118
+ content = (content || "").trim();
125
119
  if (scopeAttr && compName && content)
126
120
  content = scopeCSS(content, scopeAttr, compName);
127
121
  return "__style__() { return `" + content + "`;},\n";
package/lib/htmlParser.js CHANGED
@@ -1,7 +1,6 @@
1
1
  const { parseDOM } = require("./dom");
2
- const { script, style, selfClosingTag, normalTag } = require("./regex");
2
+ const { selfClosingTag, normalTag } = require("./regex");
3
3
  const placeholder = require("./placeholder");
4
- const clean = require("./clean");
5
4
  const handleIfStatement = require("./if");
6
5
  const handleForStatement = require("./for");
7
6
  const handleShowStatement = require("./show");
@@ -23,9 +22,7 @@ const {
23
22
  unshieldTags,
24
23
  } = require("./tokens");
25
24
 
26
- function htmlparser(str, counter, filePath, parentMethods, propsAliases) {
27
- let content = clean(str);
28
- content = content.replace(script, "").replace(style, "");
25
+ function htmlparser(content, counter, filePath, parentMethods, propsAliases) {
29
26
  content = placeholder(
30
27
  content,
31
28
  selfClosingTag,
package/lib/importMap.js CHANGED
@@ -3,7 +3,7 @@ const path = require("path");
3
3
  const colors = require("./colors");
4
4
  const { ls, isFile } = require("./helpers");
5
5
 
6
- const { useLocalCore, localLibs } = require("./coreLibs");
6
+ const { useLocalCore, localLibs, optionalLibs } = require("./coreLibs");
7
7
 
8
8
  function pickEntry(exp) {
9
9
  if (typeof exp === "string") return exp;
@@ -110,15 +110,16 @@ function importMap(srcDir) {
110
110
  Object.keys(localLibs).forEach((pkgName) => {
111
111
  const entry = resolvePackage(rootDir, pkgName);
112
112
  if (!entry) {
113
- console.warn(
114
- colors(
115
- "yellow",
116
- "Can't resolve \"" +
117
- pkgName +
118
- '" — install it at the project root: npm i ' +
119
- pkgName,
120
- ),
121
- );
113
+ if (!optionalLibs.includes(pkgName))
114
+ console.warn(
115
+ colors(
116
+ "yellow",
117
+ "Can't resolve \"" +
118
+ pkgName +
119
+ '" — install it at the project root: npm i ' +
120
+ pkgName,
121
+ ),
122
+ );
122
123
  return;
123
124
  }
124
125
  imports[pkgName] = entry;
package/lib/jsParser.js CHANGED
@@ -1,27 +1,9 @@
1
- const { script, exportDefault } = require("./regex");
2
- const { parseDOM } = require("./dom");
3
-
4
- const clean = require("./clean");
5
- function jsParser(str) {
6
- str = clean(str);
7
- const arr = str.match(script);
8
- let content = Array.isArray(arr) && arr.length ? arr[0] : "";
9
-
10
- const attrsObj = {};
11
- if (content !== "") {
12
- const dom = parseDOM(content);
13
- const scriptElm = dom.querySelector("script");
14
- const attrs = scriptElm.getAttributeNames();
15
- if (attrs.length)
16
- attrs.forEach((key) => (attrsObj[key] = scriptElm.getAttribute(key)));
17
- }
18
-
19
- content = content.replace(/(<script.*>)/, "");
20
- content = content.replace(/(<\/script>)$/, "");
1
+ function jsParser(sfc) {
2
+ let { js: content, jsAttrs } = sfc;
21
3
  content = content.replace(/onMount\(/, "var mounted = onMount(");
22
4
 
23
5
  content = content.replace(/const state/g, "var state");
24
- return { js: content, jsAttrs: attrsObj };
6
+ return { js: content, jsAttrs };
25
7
  }
26
8
 
27
9
  module.exports = jsParser;
package/lib/parser.js CHANGED
@@ -1,4 +1,6 @@
1
1
  const isDev = true;
2
+
3
+ const splitSFC = require("./sfc");
2
4
  const htmlParser = require("./htmlParser");
3
5
  const cssParser = require("./cssParser");
4
6
  const jsParser = require("./jsParser");
@@ -16,14 +18,15 @@ const {
16
18
  } = require("./helpers");
17
19
  const createSourceMap = require("./sourcemap");
18
20
  const liveProps = require("./liveProps");
21
+ const usage = require("./usage");
19
22
 
20
23
  const parser = (str, counter, filePath) => {
21
- let startIndex =
22
- str.split("\n").findIndex((item) => /<script[\s\S]*?>/gi.test(item)) || 0;
24
+ const sfc = splitSFC(str);
25
+
23
26
  let breaks = "";
24
- for (let i = 0; i < startIndex; i++) breaks += "//\n";
27
+ for (let i = 0; i < sfc.scriptStartLine; i++) breaks += "//\n";
25
28
 
26
- let { js, jsAttrs } = jsParser(str, counter, filePath);
29
+ let { js, jsAttrs } = jsParser(sfc);
27
30
 
28
31
  let parentMethods = [];
29
32
  try {
@@ -36,7 +39,7 @@ const parser = (str, counter, filePath) => {
36
39
  } catch (e) {}
37
40
 
38
41
  let { html, comps, anonHandlers } = htmlParser(
39
- str,
42
+ sfc.template,
40
43
  counter,
41
44
  filePath,
42
45
  parentMethods,
@@ -70,7 +73,7 @@ const parser = (str, counter, filePath) => {
70
73
  let compName = path.basename(filePath).replace(/.html/gi, "");
71
74
  compName = toCamelCase(compName);
72
75
  const currentID = id().slice(1);
73
- const css = cssParser(str, currentID, compName);
76
+ const css = cssParser(sfc.css, currentID, compName);
74
77
 
75
78
  let globalProps = [];
76
79
  let globalMethods = [];
@@ -107,6 +110,27 @@ const parser = (str, counter, filePath) => {
107
110
  const scopedProps = handleScope(globalProps, "props");
108
111
  const scopedMethods = handleScope(globalMethods, "methods");
109
112
 
113
+ if (process.env.NODE_ENV === "development") {
114
+ try {
115
+ const children = [];
116
+ (comps || []).forEach((name) => {
117
+ const hit = (imports || []).find((item) =>
118
+ new RegExp("\\b" + name + "\\b").test(item.statement),
119
+ );
120
+ const spec =
121
+ hit && (hit.statement.match(/from\s+["'](.+?)["']/) || [])[1];
122
+ if (!spec || !spec.startsWith(".")) return;
123
+ const child = usage.relative(
124
+ path
125
+ .resolve(path.dirname(filePath), spec)
126
+ .replace(/\.(js|html)$/, "") + ".html",
127
+ );
128
+ if (!children.includes(child)) children.push(child);
129
+ });
130
+ usage.record(filePath, children);
131
+ } catch (e) {}
132
+ }
133
+
110
134
  if (imports) imports = imports.map((item) => toJs(item.statement));
111
135
 
112
136
  function mkComponentsList(comps) {
@@ -148,6 +172,7 @@ const parser = (str, counter, filePath) => {
148
172
  methods: ${scopedMethods},
149
173
  props: ${scopedProps},
150
174
  compName: "${compName}",
175
+ ${process.env.NODE_ENV === "development" ? `file: ${JSON.stringify(usage.relative(filePath))},` : ""}
151
176
  deps: ${templateDeps ? JSON.stringify(templateDeps) : "null"},
152
177
  components: {${mkComponentsList(comps)}},
153
178
  get getElm() {
@@ -176,6 +201,14 @@ const parser = (str, counter, filePath) => {
176
201
  el: el_${currentID},
177
202
  methodsRef: methods_${currentID},
178
203
  ${isDev ? `stateProps: ${hasState ? "state" : "null"},` : ""}
204
+ ${
205
+ isDev
206
+ ? `localsRef: {${globalProps
207
+ .filter((name) => name !== "state")
208
+ .map((name) => `get ${name}(){return ${name}}`)
209
+ .join(",")}},`
210
+ : ""
211
+ }
179
212
  hooks: {
180
213
  mounted: typeof mounted !== "undefined" ? mounted : null,
181
214
  unMounted: null,
package/lib/regex.js CHANGED
@@ -1,13 +1,8 @@
1
1
  module.exports = {
2
- script: /<script[\s\S]*?>[\s\S]*?<\/script>/gi,
3
- style: /<style[\s\S]*?>[\s\S]*?<\/style>/gi,
4
2
  forOf: /(.*)( of )(.*)/g,
5
3
  forIn: /(.*)( in )(.*)/g,
6
- htmlComment: /\<\!\-\-(?:.|\n|\r)*?-->/gi,
7
- multiLineComment: /(\/\*)([\s\S]*?)(\*\/)/g,
8
4
 
9
5
  selfClosingTag: /<([A-Z](?:"[^"]*"|'[^']*'|[^"'>])*?)\/>/g,
10
6
  normalTag: /<([A-Z](?:"[^"]*"|'[^']*'|[^"'>])*?)>([\s\S]*?)<\/[A-Z][^>]*>/g,
11
- exportDefault: /(export default)(\s+)?(\{)/,
12
7
  compExt: /\.html$/i,
13
8
  };
package/lib/sfc.js ADDED
@@ -0,0 +1,69 @@
1
+ const parse5 = require("parse5");
2
+
3
+ function splitSFC(source) {
4
+ source = String(source);
5
+ const doc = parse5.parse(source, {
6
+ sourceCodeLocationInfo: true,
7
+ scriptingEnabled: false,
8
+ });
9
+
10
+ const scripts = [],
11
+ styles = [],
12
+ comments = [];
13
+ (function walk(node) {
14
+ for (const child of node.childNodes || []) {
15
+ if (child.nodeName === "#comment") {
16
+ comments.push(child);
17
+ continue;
18
+ }
19
+ if (child.tagName === "script") scripts.push(child);
20
+ else if (child.tagName === "style") styles.push(child);
21
+ walk(child);
22
+ if (child.content) walk(child.content);
23
+ }
24
+ })(doc);
25
+
26
+ const inner = (node) => {
27
+ const loc = node.sourceCodeLocation;
28
+ if (!loc) return "";
29
+ const start = loc.startTag ? loc.startTag.endOffset : loc.startOffset;
30
+ const end = loc.endTag ? loc.endTag.startOffset : loc.endOffset;
31
+ return source.slice(start, end);
32
+ };
33
+
34
+ const script = scripts[0] || null;
35
+ const style = styles[0] || null;
36
+
37
+ const jsAttrs = {};
38
+ if (script) script.attrs.forEach((a) => (jsAttrs[a.name] = a.value));
39
+
40
+ const ranges = scripts
41
+ .concat(styles, comments)
42
+ .map((n) => n.sourceCodeLocation)
43
+ .filter(Boolean)
44
+ .map((loc) => [loc.startOffset, loc.endOffset])
45
+ .sort((a, b) => a[0] - b[0]);
46
+ let template = "";
47
+ let pos = 0;
48
+ ranges.forEach(([start, end]) => {
49
+ if (start >= pos) {
50
+ template += source.slice(pos, start);
51
+ pos = end;
52
+ }
53
+ });
54
+ template += source.slice(pos);
55
+
56
+ return {
57
+ js: script ? inner(script) : "",
58
+ jsAttrs,
59
+
60
+ scriptStartLine:
61
+ script && script.sourceCodeLocation
62
+ ? script.sourceCodeLocation.startLine - 1
63
+ : 0,
64
+ css: style ? inner(style) : "",
65
+ template: template.trim(),
66
+ };
67
+ }
68
+
69
+ module.exports = splitSFC;
package/lib/usage.js ADDED
@@ -0,0 +1,39 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ const srcDest = path.resolve(__dirname, "../src");
5
+ const mapFile = path.join(srcDest, "usage.json");
6
+
7
+ const relative = (file) =>
8
+ "src/" + path.relative(srcDest, file).split(path.sep).join("/");
9
+
10
+ const read = () => {
11
+ try {
12
+ return JSON.parse(fs.readFileSync(mapFile, "utf8"));
13
+ } catch (e) {
14
+ return {};
15
+ }
16
+ };
17
+
18
+ const write = (map) => {
19
+ try {
20
+ fs.writeFileSync(mapFile, JSON.stringify(map, null, 2));
21
+ } catch (e) {}
22
+ };
23
+
24
+ module.exports = {
25
+ relative,
26
+ record(file, children) {
27
+ const map = read();
28
+ map[relative(file)] = children;
29
+ write(map);
30
+ },
31
+
32
+ drop(file) {
33
+ const map = read();
34
+ const key = relative(file);
35
+ if (!(key in map)) return;
36
+ delete map[key];
37
+ write(map);
38
+ },
39
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
package/lib/clean.js DELETED
@@ -1,4 +0,0 @@
1
- const { htmlComment } = require("./regex");
2
- module.exports = function clean(str) {
3
- return str.replace(htmlComment, "").trim();
4
- };