olum-compiler 1.2.0 → 1.6.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.
Files changed (49) hide show
  1. package/.claude/settings.local.json +3 -1
  2. package/bin/build.js +14 -8
  3. package/bin/bundle.js +108 -0
  4. package/bin/compiler.js +25 -7
  5. package/bin/copySrc.js +73 -25
  6. package/bin/dev.js +54 -34
  7. package/bin/index.js +6 -4
  8. package/bin/server.js +58 -34
  9. package/bin/watcher.js +15 -11
  10. package/bin/ws.js +16 -11
  11. package/lib/attr.js +1 -25
  12. package/lib/boolAttr.js +32 -15
  13. package/lib/changes.txt +0 -0
  14. package/lib/chokidar.js +52 -101
  15. package/lib/colors.js +1 -7
  16. package/lib/compPlaceholder.js +5 -3
  17. package/lib/compiler.js +11 -8
  18. package/lib/coreLibs.js +2 -7
  19. package/lib/cross-spawn.js +45 -59
  20. package/lib/cssParser.js +61 -37
  21. package/lib/domEvents.js +6 -2
  22. package/lib/events.js +75 -77
  23. package/lib/for.js +56 -28
  24. package/lib/getImports.js +35 -17
  25. package/lib/getTempPath.js +8 -4
  26. package/lib/helpers.js +289 -184
  27. package/lib/html.js +3 -10
  28. package/lib/htmlParser.js +45 -45
  29. package/lib/if.js +40 -20
  30. package/lib/importMap.js +49 -24
  31. package/lib/jsParser.js +8 -13
  32. package/lib/lineCounter.js +18 -5
  33. package/lib/liveProps.js +266 -0
  34. package/lib/log.js +30 -0
  35. package/lib/magic-string.js +45 -52
  36. package/lib/models.js +8 -7
  37. package/lib/parser.js +82 -43
  38. package/lib/placeholder.js +73 -58
  39. package/lib/regex.js +4 -3
  40. package/lib/show.js +16 -8
  41. package/lib/sourcemap.js +23 -24
  42. package/lib/styles.js +7 -13
  43. package/lib/textarea.js +3 -6
  44. package/lib/toJs.js +1 -1
  45. package/lib/tokens.js +10 -22
  46. package/lib/transition.js +86 -0
  47. package/lib/websocket.js +68 -62
  48. package/package.json +1 -1
  49. package/tests/compiler.test.js +450 -172
package/lib/parser.js CHANGED
@@ -1,54 +1,70 @@
1
- const isDev = true; // todo: handle this later to be global var accessable every where in compiler files
1
+ const isDev = true;
2
2
  const htmlParser = require("./htmlParser");
3
3
  const cssParser = require("./cssParser");
4
4
  const jsParser = require("./jsParser");
5
5
  const getImports = require("./getImports");
6
6
  const toJs = require("./toJs");
7
7
  const path = require("path");
8
- const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, getPropsAliases } = require("./helpers");
8
+ const {
9
+ isFullArr,
10
+ id,
11
+ createScopeHandler,
12
+ getGlobalMethods,
13
+ getGlobalProps,
14
+ getPropsAliases,
15
+ computeTemplateDeps,
16
+ } = require("./helpers");
9
17
  const createSourceMap = require("./sourcemap");
18
+ const liveProps = require("./liveProps");
10
19
 
11
20
  const parser = (str, counter, filePath) => {
12
- // start: calc lines above script tag (from line 1 to script tag)
13
- let startIndex = str.split("\n").findIndex(item => /<script[\s\S]*?>/gi.test(item)) || 0;
21
+ let startIndex =
22
+ str.split("\n").findIndex((item) => /<script[\s\S]*?>/gi.test(item)) || 0;
14
23
  let breaks = "";
15
24
  for (let i = 0; i < startIndex; i++) breaks += "//\n";
16
- // end
17
25
 
18
- let { js, jsAttrs } = jsParser(str, counter, filePath); // js content and attributes in script opening tag
26
+ let { js, jsAttrs } = jsParser(str, counter, filePath);
19
27
 
20
- // top-level function names of THIS component, computed before htmlParser so placeholder.js can
21
- // flag bare-identifier props referencing them (toggle="{toggle}") as function props — functions
22
- // can't cross the JSON data-o-props channel, so they travel via data-o-props-src kind "method"
23
28
  let parentMethods = [];
24
- try { parentMethods = getGlobalMethods(js); } catch (e) {}
25
- // names destructured from props() — forwarding them (onMessage="{onMessage}") must travel via
26
- // data-o-props-src kind "props" so function props survive intermediate components at any depth
29
+ try {
30
+ parentMethods = getGlobalMethods(js);
31
+ } catch (e) {}
32
+
27
33
  let propsAliases = {};
28
- try { propsAliases = getPropsAliases(js); } catch (e) {}
34
+ try {
35
+ propsAliases = getPropsAliases(js);
36
+ } catch (e) {}
37
+
38
+ let { html, comps, anonHandlers } = htmlParser(
39
+ str,
40
+ counter,
41
+ filePath,
42
+ parentMethods,
43
+ propsAliases,
44
+ );
29
45
 
30
- let {html, comps, anonHandlers} = htmlParser(str, counter, filePath, parentMethods, propsAliases); // html content and all components tags <olum></olum>
31
- html = html.replace(/\"\-\[\[\-/g, "'").replace(/\-\]\]\-\"/g, "'"); // fix json in attribute issue
46
+ html = html.replace(/\-\]\]\-\-\[\[\-/g, "OLUM_EVT_SEP");
47
+ html = html.replace(/\"\-\[\[\-/g, "'").replace(/\-\]\]\-\"/g, "'");
32
48
 
33
- // Inject anonymous handler declarations so getGlobalMethods picks them up as regular methods
34
- if (anonHandlers && anonHandlers.length) js = js + "\n" + anonHandlers.join("\n");
49
+ if (anonHandlers && anonHandlers.length)
50
+ js = js + "\n" + anonHandlers.join("\n");
35
51
 
36
- // clean import statements
37
52
  let imports = getImports(js);
38
53
  if (imports) {
39
54
  const importRegex = /(import)(\s+)?(?!from)/g;
40
55
  imports.forEach((item) => {
41
- if (item.type && item.type == "noFrom") js = js.replace(new RegExp(item.regex, "gm"), "");
56
+ if (item.type && item.type == "noFrom")
57
+ js = js.replace(new RegExp(item.regex, "gm"), "");
42
58
  if (!item.type) js = js.replace(new RegExp(item.regex, "g"), "*/");
43
59
  });
44
60
  js = js.replace(importRegex, "/* olum:toBeRemoved");
45
- // clean multiple line comments of imports and delete lines
61
+
46
62
  js = js.replace(/(\/\* olum\:toBeRemoved)([\s\S]*?)(\*\/).*\n?/gm, "");
47
63
  }
48
64
 
49
65
  function toCamelCase(name) {
50
66
  return name;
51
- return name.slice(0, 1).toLowerCase() + name.slice(1); // todo decide what to do with component name, leave it as it is or make it pascal case or camelcase of cababcase
67
+ return name.slice(0, 1).toLowerCase() + name.slice(1);
52
68
  }
53
69
 
54
70
  let compName = path.basename(filePath).replace(/.html/gi, "");
@@ -61,7 +77,7 @@ const parser = (str, counter, filePath) => {
61
77
  let stateProps = [];
62
78
  let hasState = false;
63
79
  let hasWatcher = false;
64
- // let hasComputed = false;
80
+
65
81
  let hasMounted = false;
66
82
  let hasUnMounted = false;
67
83
 
@@ -71,32 +87,34 @@ const parser = (str, counter, filePath) => {
71
87
  globalProps = getGlobalProps(js);
72
88
  globalMethods = getGlobalMethods(js);
73
89
 
74
- // check existance before runtime
75
- // methods
76
90
  hasMounted = globalMethods.includes("mounted") ? true : false;
77
91
  hasUnMounted = globalMethods.includes("unMounted") ? true : false;
78
- // props
92
+
79
93
  hasState = globalProps.includes("state") ? true : false;
80
94
  hasWatcher = globalProps.includes("watcher") ? true : false;
81
- // hasComputed = globalProps.includes("computed") ? true : false;
82
95
 
83
- // exclude props/methods
84
- globalMethods = globalMethods.filter((name) => !methodsTobeExcluded.includes(name));
96
+ globalMethods = globalMethods.filter(
97
+ (name) => !methodsTobeExcluded.includes(name),
98
+ );
85
99
  globalProps = globalProps.filter((name) => !propsTobeExcluded.includes(name));
86
100
 
87
- const handleScope = createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs });
101
+ const handleScope = createScopeHandler({
102
+ stateProps,
103
+ hasState,
104
+ propsTobeExcluded,
105
+ jsAttrs,
106
+ });
88
107
  const scopedProps = handleScope(globalProps, "props");
89
108
  const scopedMethods = handleScope(globalMethods, "methods");
90
109
 
91
- // convert .html to .js and add .js if it doesn't exist
92
110
  if (imports) imports = imports.map((item) => toJs(item.statement));
93
111
 
94
112
  function mkComponentsList(comps) {
95
113
  if (!imports || !isFullArr(imports)) return "";
96
- // emit a deduped name->factory map; word-boundary match so "Todos" doesn't also match "FilterTodos"
114
+
97
115
  const seen = {};
98
116
  const entries = [];
99
- imports.forEach(importStatement => {
117
+ imports.forEach((importStatement) => {
100
118
  comps.forEach((name) => {
101
119
  if (seen[name]) return;
102
120
  if (new RegExp("\\b" + name + "\\b").test(importStatement)) {
@@ -108,12 +126,20 @@ const parser = (str, counter, filePath) => {
108
126
  return entries.join(",");
109
127
  }
110
128
 
111
- js = js.replace(/params\(/, `params("${filePath}",location.pathname`); // handle params of router
112
- // bind the imported props() accessor to this instance's runtime store key: props() -> props(_storeKey)
129
+ js = js.replace(/params\(/, `params("${filePath}",location.pathname`);
130
+
113
131
  js = js.replace(/props\(\s*\)/g, "props(_storeKey)");
114
132
  html = html.replace(/props\(\s*\)/g, "props(_storeKey)");
115
133
 
116
- return `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const _storeKey=_instanceKey||"${compName}"; ${js}
134
+ const templateDeps = computeTemplateDeps(
135
+ html,
136
+ globalMethods,
137
+ globalProps,
138
+ hasState,
139
+ js,
140
+ );
141
+
142
+ let out = `${breaks}${imports ? imports.join("\n") + "\n" : ""}export default (_instanceKey) => {const _storeKey=_instanceKey||"${compName}"; ${js}
117
143
  var el_${currentID} = olum.mkElm("div", "${compName}", "${currentID}");
118
144
  var host = el_${currentID};
119
145
  var methods_${currentID} = {${globalMethods}};
@@ -122,27 +148,32 @@ const parser = (str, counter, filePath) => {
122
148
  methods: ${scopedMethods},
123
149
  props: ${scopedProps},
124
150
  compName: "${compName}",
151
+ deps: ${templateDeps ? JSON.stringify(templateDeps) : "null"},
125
152
  components: {${mkComponentsList(comps)}},
126
153
  get getElm() {
127
- el_${currentID}.innerHTML = \`
154
+ var target_${currentID} = el_${currentID}.isConnected ? olum.vdom.mkStaging(el_${currentID}) : el_${currentID};
155
+ target_${currentID}.innerHTML = \`
128
156
  ${html}\`;
129
157
  olum.injectStyle("${compName}", olum_${currentID}.__style__());
130
- return olum.handleMarkup("${compName}", "${currentID}", el_${currentID}, methods_${currentID});
158
+ return olum.handleMarkup("${compName}", "${currentID}", target_${currentID}, methods_${currentID});
131
159
  },
132
160
  };
133
161
 
134
162
  // todo: check if state.__olum__ needed since it's wiped out here
135
- ${ hasState ? `
163
+ ${
164
+ hasState
165
+ ? `
136
166
  state.__olum__ = { compName: _storeKey, compId: "${currentID}" };
137
167
  state = olum.proxyHandler(state, ${hasWatcher ? "watcher" : "null"}, el_${currentID});
138
- ` : "" }
168
+ `
169
+ : ""
170
+ }
139
171
 
140
172
  return {
141
173
  methods: olum_${currentID}.methods,
142
174
  props: olum_${currentID}.props,
143
175
  __OLUM__: olum_${currentID},
144
176
  el: el_${currentID},
145
- incomingPropsProxy: olum.props(_storeKey),
146
177
  methodsRef: methods_${currentID},
147
178
  ${isDev ? `stateProps: ${hasState ? "state" : "null"},` : ""}
148
179
  hooks: {
@@ -152,8 +183,16 @@ const parser = (str, counter, filePath) => {
152
183
  isUnMounted: false,
153
184
  }
154
185
  };
155
- };
156
- //# sourceMappingURL=data:application/json;charset=utf-8;base64,${createSourceMap(str, filePath)}`;
186
+ };`;
187
+
188
+ try {
189
+ out = liveProps(out);
190
+ } catch (e) {}
191
+ return (
192
+ out +
193
+ `
194
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,${createSourceMap(str, filePath)}`
195
+ );
157
196
  };
158
197
 
159
- module.exports = parser;
198
+ module.exports = parser;
@@ -1,16 +1,10 @@
1
1
  const { isFullArr, isUpper } = require("./helpers");
2
2
 
3
- // { must be double-encoded so it survives jsdom + htmlParser transformations
4
3
  const ESC = "&amp;lt;-olum-&amp;gt;";
5
4
 
6
- // A string-valued prop is literal by default, with {expr} interpolation inside (like a regular
7
- // attribute): title="Hello {state.name}". If it contains {expr}, compile it to a TEMPLATE LITERAL
8
- // so the literal text + interpolated parts concatenate into a string. The { of each ${...} is
9
- // ESC-encoded so htmlParser's {expr} escape pass leaves it alone (restored to { at the end).
10
- // A plain value (no braces) stays a quoted string literal.
11
5
  function literalExpr(raw) {
12
6
  if (/\{[^{}]+\}/.test(raw)) {
13
- const body = raw.replace(/`/g, "\\`").replace(/\{([^{}]+)\}/g, "${$1}"); // {x} -> ${x}
7
+ const body = raw.replace(/`/g, "\\`").replace(/\{([^{}]+)\}/g, "${$1}");
14
8
  return ("`" + body + "`").replace(/\{/g, ESC);
15
9
  }
16
10
  return "'" + raw.replace(/'/g, "\\'") + "'";
@@ -18,88 +12,102 @@ function literalExpr(raw) {
18
12
 
19
13
  function parseProps(attrsStr, parentMethods, propsAliases) {
20
14
  const entries = [];
21
- const srcEntries = []; // prop-name:state-key pairs for setter write-back
22
- // six alternatives in priority order (groups kept intact for easy toggling):
23
- // 1. {key} 2. key="{expr}" 3. key='{expr}' 4. key={expr} 5. key="value" 6. key='value'
24
- // NOTE: the naked-brace forms 1 ({key} shorthand) and 4 (key={expr}) are DISABLED — values must
25
- // live inside quotes, consistent with every other attribute. Uncomment their branches to re-enable.
26
- const attrRegex = /\{(\w+)\}|(\w+)="\{([^}]+)\}"|(\w+)='\{([^}]+)\}'|(\w+)=\{([^}]+)\}|(\w+)="([^"]*)"|(\w+)='([^']*)'/g;
15
+ const srcEntries = [];
16
+
17
+ const attrRegex =
18
+ /\{(\w+)\}|(\w+)="\{([^}]+)\}"|(\w+)='\{([^}]+)\}'|(\w+)=\{([^}]+)\}|(\w+)="([^"]*)"|(\w+)='([^']*)'/g;
27
19
  let match;
28
20
  while ((match = attrRegex.exec(attrsStr)) !== null) {
29
- let propName, expr, isExpr = false;
30
- // DISABLED — {key} shorthand. Uncomment to re-enable.
31
- // if (match[1] !== undefined) {
32
- // propName = match[1]; expr = match[1]; isExpr = true; // {key} shorthand
33
- // } else
21
+ let propName,
22
+ expr,
23
+ isExpr = false;
24
+
34
25
  if (match[2] && match[3] !== undefined) {
35
- propName = match[2]; expr = match[3]; isExpr = true; // key="{expr}"
26
+ propName = match[2];
27
+ expr = match[3];
28
+ isExpr = true;
36
29
  } else if (match[4] && match[5] !== undefined) {
37
- propName = match[4]; expr = match[5]; isExpr = true; // key='{expr}'
38
- // DISABLED — key={expr} unquoted. Uncomment to re-enable.
39
- // } else if (match[6] && match[7] !== undefined) {
40
- // propName = match[6]; expr = match[7]; isExpr = true; // key={expr}
30
+ propName = match[4];
31
+ expr = match[5];
32
+ isExpr = true;
41
33
  } else if (match[8] && match[9] !== undefined) {
42
- // key="value" — literal string, or template literal if it contains {expr} interpolation
43
34
  let v = match[9];
44
- if (!/\{[^{}]+\}/.test(v) && v.startsWith("'") && v.endsWith("'") && v.length >= 2) v = v.slice(1, -1);
45
- propName = match[8]; expr = literalExpr(v); isExpr = false;
35
+ if (
36
+ !/\{[^{}]+\}/.test(v) &&
37
+ v.startsWith("'") &&
38
+ v.endsWith("'") &&
39
+ v.length >= 2
40
+ )
41
+ v = v.slice(1, -1);
42
+ propName = match[8];
43
+ expr = literalExpr(v);
44
+ isExpr = false;
46
45
  } else if (match[10] && match[11] !== undefined) {
47
- propName = match[10]; expr = literalExpr(match[11]); isExpr = false;
46
+ propName = match[10];
47
+ expr = literalExpr(match[11]);
48
+ isExpr = false;
48
49
  }
49
50
  if (!propName) continue;
50
51
  if (isExpr) {
51
- // FUNCTION PROP: a bare identifier naming a top-level function of THIS (parent) component,
52
- // e.g. toggle="{toggle}". Functions can't cross the JSON data-o-props channel, so skip the
53
- // JSON entry and record it in data-o-props-src as kind "method" — buildTree resolves it
54
- // live from the parent instance's methodsRef on every render pass.
55
52
  const bare = expr.trim();
56
- if (parentMethods && parentMethods.includes(bare) && /^[A-Za-z_$][\w$]*$/.test(bare)) {
57
- srcEntries.push(propName + ':method:' + bare);
53
+ if (
54
+ parentMethods &&
55
+ parentMethods.includes(bare) &&
56
+ /^[A-Za-z_$][\w$]*$/.test(bare)
57
+ ) {
58
+ srcEntries.push(propName + ":method:" + bare);
58
59
  continue;
59
60
  }
60
- // PROP FORWARD: a bare identifier destructured from props() in THIS (parent) component,
61
- // e.g. `const { onMessage } = props()` + onMessage="{onMessage}". Emit both the JSON entry
62
- // (carries serializable values) and a kind "props" src entry keyed by the ORIGINAL prop name
63
- // — buildTree falls back to the parent's own incomingProps when JSON dropped the value
64
- // (it was a function), so function props survive any nesting depth.
65
- if (propsAliases && Object.prototype.hasOwnProperty.call(propsAliases, bare) && /^[A-Za-z_$][\w$]*$/.test(bare)) {
66
- entries.push(propName + ': ' + bare);
67
- srcEntries.push(propName + ':props:' + propsAliases[bare]);
61
+
62
+ if (
63
+ propsAliases &&
64
+ Object.prototype.hasOwnProperty.call(propsAliases, bare) &&
65
+ /^[A-Za-z_$][\w$]*$/.test(bare)
66
+ ) {
67
+ entries.push(propName + ": " + bare);
68
+ srcEntries.push(propName + ":props:" + propsAliases[bare]);
68
69
  continue;
69
70
  }
70
- // object literal: restore {} wrappers, escaping { so htmlParser won't turn it into ${
71
- const entryExpr = /^\s*\w+\s*:/.test(expr) ? ESC + expr + '}' : expr;
72
- entries.push(propName + ': ' + entryExpr);
73
- // record write-back source: state.X writes to the parent's state; props.X chains up to the
74
- // parent's own prop (the setter recurses until it reaches whoever holds it in state).
75
- // format: propName:kind:srcKey (kind = state | props)
71
+
72
+ const entryExpr = /^\s*\w+\s*:/.test(expr) ? ESC + expr + "}" : expr;
73
+ entries.push(propName + ": " + entryExpr);
74
+
76
75
  const stateMatch = expr.trim().match(/^state\.(\w+)$/);
77
- // props source is the wrapper call `props().X` (old proxy access `props.X` also accepted)
76
+
78
77
  const propsMatch = expr.trim().match(/^props(?:\(\s*\))?\.(\w+)$/);
79
- if (stateMatch) srcEntries.push(propName + ':state:' + stateMatch[1]);
80
- else if (propsMatch) srcEntries.push(propName + ':props:' + propsMatch[1]);
78
+ if (stateMatch) srcEntries.push(propName + ":state:" + stateMatch[1]);
79
+ else if (propsMatch)
80
+ srcEntries.push(propName + ":props:" + propsMatch[1]);
81
81
  } else {
82
- entries.push(propName + ': ' + expr);
82
+ entries.push(propName + ": " + expr);
83
83
  }
84
84
  }
85
85
  return { entries, srcEntries };
86
86
  }
87
87
 
88
88
  function buildPropsAttr(attrsStr, parentMethods, propsAliases) {
89
- const { entries, srcEntries } = parseProps(attrsStr, parentMethods, propsAliases);
89
+ const { entries, srcEntries } = parseProps(
90
+ attrsStr,
91
+ parentMethods,
92
+ propsAliases,
93
+ );
90
94
 
91
- // emit the two attributes independently: a component may receive only function props
92
- // (src entries, no JSON payload) or only data props (JSON payload, no src entries)
93
95
  let attr = "";
94
96
  if (entries.length) {
95
- const expr = "$" + ESC + "encodeURIComponent(JSON.stringify(" + ESC + entries.join(", ") + "}))}";
97
+ const expr =
98
+ "$" +
99
+ ESC +
100
+ "encodeURIComponent(JSON.stringify(" +
101
+ ESC +
102
+ entries.join(", ") +
103
+ "})).replace(/'/g,'%27')}";
96
104
  attr += ' data-o-props="-[[-' + expr + '-]]-"';
97
105
  }
98
- if (srcEntries.length) attr += ' data-o-props-src="' + srcEntries.join("|") + '"';
106
+ if (srcEntries.length)
107
+ attr += ' data-o-props-src="' + srcEntries.join("|") + '"';
99
108
  return attr;
100
109
  }
101
110
 
102
- // handle components placeholders with olum tag <olum></olum>
103
111
  function placeholder(content, regex, type, parentMethods, propsAliases) {
104
112
  return content.replace(regex, (str, $1, $2) => {
105
113
  let data = $1.split(" ");
@@ -107,7 +115,14 @@ function placeholder(content, regex, type, parentMethods, propsAliases) {
107
115
  let name = data[0].trim();
108
116
  if (isUpper(name[0])) {
109
117
  name = "name='" + name + "'";
110
- const propsAttr = data.length > 1 ? buildPropsAttr(data.slice(1).join(" "), parentMethods, propsAliases) : "";
118
+ const propsAttr =
119
+ data.length > 1
120
+ ? buildPropsAttr(
121
+ data.slice(1).join(" "),
122
+ parentMethods,
123
+ propsAliases,
124
+ )
125
+ : "";
111
126
  const slot = type === "normal" ? $2 : "";
112
127
  return "<olum " + name + propsAttr + ">" + slot + "</olum>";
113
128
  }
package/lib/regex.js CHANGED
@@ -5,8 +5,9 @@ module.exports = {
5
5
  forIn: /(.*)( in )(.*)/g,
6
6
  htmlComment: /\<\!\-\-(?:.|\n|\r)*?-->/gi,
7
7
  multiLineComment: /(\/\*)([\s\S]*?)(\*\/)/g,
8
- selfClosingTag: /<([A-Z][^\/>]+)\/>/g,
9
- normalTag: /<([A-Z][^\/>]+)>([\s\S]*?)<\/[A-Z][^\/>]+>/g,
8
+
9
+ selfClosingTag: /<([A-Z](?:"[^"]*"|'[^']*'|[^"'>])*?)\/>/g,
10
+ normalTag: /<([A-Z](?:"[^"]*"|'[^']*'|[^"'>])*?)>([\s\S]*?)<\/[A-Z][^>]*>/g,
10
11
  exportDefault: /(export default)(\s+)?(\{)/,
11
- compExt: /\.html$/i
12
+ compExt: /\.html$/i,
12
13
  };
package/lib/show.js CHANGED
@@ -2,17 +2,25 @@ const { getLineInfo } = require("./lineCounter");
2
2
  const { RAW_OPEN, RAW_CLOSE, shieldOps } = require("./tokens");
3
3
 
4
4
  function handleShowStatement(body, counter, filePath) {
5
- const showElms = new Array().slice.call(body.querySelectorAll("show")).reverse(); // we must reverse to start with the very deep if tag which doesn't have nested if tags inside it
6
- showElms.forEach(item => {
7
- // console.log(item.outerHTML + "\n----------");
5
+ const showElms = new Array().slice
6
+ .call(body.querySelectorAll("show"))
7
+ .reverse();
8
+ showElms.forEach((item) => {
8
9
  if (item.hasAttribute("when")) {
9
- // `when` is a plain JS expression (no braces): <show when="state.visible">
10
- // shieldOps: protect <,> from the jsdom text round-trip (restored in htmlParser)
11
10
  const condition = shieldOps(item.getAttribute("when").trim());
12
11
  const innerContent = item.innerHTML;
13
- // RAW_OPEN/RAW_CLOSE: structural interpolation (both branches return HTML); see tokens.js / #2.
14
- const ternaryOperator = RAW_OPEN+condition +"?`"+ innerContent + "`:`"+ "<div style=\"display:none;\">"+innerContent+"</div>`"+RAW_CLOSE;
15
- item.insertAdjacentHTML("beforebegin", ternaryOperator);
12
+
13
+ const wrapper =
14
+ '<div data-o-show style="display:' +
15
+ RAW_OPEN +
16
+ "(" +
17
+ condition +
18
+ ")?'contents':'none'" +
19
+ RAW_CLOSE +
20
+ ';">' +
21
+ innerContent +
22
+ "</div>";
23
+ item.insertAdjacentHTML("beforebegin", wrapper);
16
24
  item.remove();
17
25
  } else {
18
26
  const msg = "Missing 'when' attribute:";
package/lib/sourcemap.js CHANGED
@@ -1,34 +1,33 @@
1
- // todo support mapping for html (stuff above script tag)
2
- const MagicString = require('./magic-string');
1
+ const MagicString = require("./magic-string");
3
2
  const { stringToBase64 } = require("./helpers");
4
3
  const path = require("path");
5
4
 
6
5
  function mkMapping(str, filePath) {
7
- const s = new MagicString(str);
8
- const map = s.generateMap({
9
- source: filePath,
10
- file: filePath + '.map',
11
- includeContent: true
12
- });
13
- return JSON.parse(map.toString()).mappings;
6
+ const s = new MagicString(str);
7
+ const map = s.generateMap({
8
+ source: filePath,
9
+ file: filePath + ".map",
10
+ includeContent: true,
11
+ });
12
+ return JSON.parse(map.toString()).mappings;
14
13
  }
15
14
 
16
15
  function createSourceMap(str, filePath) {
17
- try {
18
- filePath = filePath.replaceAll(filePath.split("src")[0], "./");
19
- } catch (err) {
20
- filePath = "./src/" + path.basename(filePath);
21
- }
16
+ try {
17
+ filePath = filePath.replaceAll(filePath.split("src")[0], "./");
18
+ } catch (err) {
19
+ filePath = "./src/" + path.basename(filePath);
20
+ }
22
21
 
23
- const map = {
24
- version: 3,
25
- file: filePath,
26
- mappings: mkMapping(str, filePath),
27
- sources: ["olum://appName/" + filePath], // todo replace appName
28
- sourcesContent: [str],
29
- names: ["olum"]
30
- };
22
+ const map = {
23
+ version: 3,
24
+ file: filePath,
25
+ mappings: mkMapping(str, filePath),
26
+ sources: ["olum://appName/" + filePath],
27
+ sourcesContent: [str],
28
+ names: ["olum"],
29
+ };
31
30
 
32
- return stringToBase64(JSON.stringify(map));
31
+ return stringToBase64(JSON.stringify(map));
33
32
  }
34
- module.exports = createSourceMap;
33
+ module.exports = createSourceMap;
package/lib/styles.js CHANGED
@@ -3,27 +3,21 @@ const path = require("path");
3
3
 
4
4
  function handleStyles(body, counter, filePath) {
5
5
  let name = path.basename(filePath).replace(/\.html/i, "");
6
- name = name.slice(0, 1).toLowerCase() + name.slice(1); // make compName camel case
6
+ name = name.slice(0, 1).toLowerCase() + name.slice(1);
7
7
 
8
8
  const elms = new Array().slice.call(body.querySelectorAll("*"));
9
- elms.forEach(item => {
9
+ elms.forEach((item) => {
10
10
  if (item.hasAttribute(":style")) {
11
11
  let attrValue = item.getAttribute(":style");
12
12
  if (attrValue) {
13
13
  attrValue = attrValue.trim();
14
- // if (attrValue.startsWith("{") && attrValue.endsWith("}")) {
15
- // attrValue = attrValue.slice(1,-1);
16
- // console.log(attrValue);
17
14
 
18
- // added special delimiters for json in attribute to overcome double quotes issue -[[- , -]]-
19
- let chain = "-[[-${JSON.stringify(" + attrValue + ")}-]]-";
15
+ let chain = "-[[-${JSON.stringify(" + attrValue + ")}-]]-";
20
16
 
21
- chain = chain.replace(/{/g, "&lt;-olum-&gt;"); // using <-olum-> (&lt;-olum-&gt;) as placeholder for "{"
22
- // console.log({chain});
23
- item.setAttribute("data-o-style", chain);
24
- item.removeAttribute(":style");
25
- // console.log(item.outerHTML + "\n----------");
26
- // }
17
+ chain = chain.replace(/{/g, "&lt;-olum-&gt;");
18
+
19
+ item.setAttribute("data-o-style", chain);
20
+ item.removeAttribute(":style");
27
21
  }
28
22
  }
29
23
  });
package/lib/textarea.js CHANGED
@@ -1,10 +1,7 @@
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
1
  function handleTextarea(body) {
7
- const elms = Array.prototype.slice.call(body.querySelectorAll("textarea[value]"));
2
+ const elms = Array.prototype.slice.call(
3
+ body.querySelectorAll("textarea[value]"),
4
+ );
8
5
  elms.forEach((item) => {
9
6
  item.textContent = item.getAttribute("value");
10
7
  item.removeAttribute("value");
package/lib/toJs.js CHANGED
@@ -3,7 +3,7 @@ const path = require("path");
3
3
  function toJs(statement) {
4
4
  return statement.replace(/(from)(\s+)?.*/g, (str) => {
5
5
  let _path = str.replace(/from|'|"/g, "").trim();
6
- // bare specifiers (npm pkgs, olum) resolve via the import map in index.html — don't touch them
6
+
7
7
  if (!/^\.{0,2}\//.test(_path)) return 'from "' + _path + '";';
8
8
  const extname = path.extname(_path);
9
9
  const newPath = extname ? _path.replace(extname, "") : _path;
package/lib/tokens.js CHANGED
@@ -1,35 +1,23 @@
1
- // Sentinels for compiler-generated ("structural") template interpolations.
2
- //
3
- // #2 (escape-by-default): the htmlParser wraps every remaining `{expr}` it finds in `olum.esc(...)`.
4
- // But control-flow handlers (<if>/<for>/<show>) ALSO produce `{...}` interpolations whose result is
5
- // raw HTML (a ternary returning a template string, a `.map().join('')`, etc.) and must NOT be escaped.
6
- // To tell the two apart, those handlers emit these sentinels instead of literal braces; htmlParser
7
- // converts the sentinels straight to `${...}` (unescaped) AFTER it has escaped the user braces.
8
- //
9
- // Plain ASCII so they survive a jsdom parse/serialize round-trip unchanged, and regex-safe so they
10
- // can be swapped with a simple global replace.
11
- // LT/GT shield: a directive expression (when="a > b", each="x of f(a < b)") is spliced into the
12
- // markup as TEXT, so jsdom serializes its < and > to &lt;/&gt; and produces broken JS. We replace
13
- // them with these sentinels in the CONDITION string only (never in branch/display text), then
14
- // restore them in htmlParser after the round-trip — so escaped <,> in user-visible text are untouched.
15
1
  const LT = "OLUM_LT";
16
2
  const GT = "OLUM_GT";
3
+ const QUOT = "OLUM_QUOT";
17
4
 
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";
5
+ const restrictedTags =
6
+ "select|table|caption|colgroup|col|thead|tbody|tfoot|tr|td|th";
24
7
  const shieldRe = new RegExp("<(\\/?)(" + restrictedTags + ")(?=[\\s/>])", "gi");
25
- const unshieldRe = new RegExp("<(\\/?)olum-(" + restrictedTags + ")(?=[\\s/>])", "gi");
8
+ const unshieldRe = new RegExp(
9
+ "<(\\/?)olum-(" + restrictedTags + ")(?=[\\s/>])",
10
+ "gi",
11
+ );
26
12
 
27
13
  module.exports = {
28
14
  RAW_OPEN: "OLUM_RAW_OPEN",
29
15
  RAW_CLOSE: "OLUM_RAW_CLOSE",
30
16
  LT,
31
17
  GT,
32
- shieldOps: (s) => String(s).split("<").join(LT).split(">").join(GT),
18
+ QUOT,
19
+ shieldOps: (s) =>
20
+ String(s).split("<").join(LT).split(">").join(GT).split('"').join(QUOT),
33
21
  shieldTags: (s) => s.replace(shieldRe, "<$1olum-$2"),
34
22
  unshieldTags: (s) => s.replace(unshieldRe, "<$1$2"),
35
23
  };