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
@@ -0,0 +1,266 @@
1
+ const acorn = require("acorn");
2
+ const walk = require("acorn-walk");
3
+
4
+ function patternNames(node, set) {
5
+ if (!node) return;
6
+ switch (node.type) {
7
+ case "Identifier":
8
+ set.add(node.name);
9
+ break;
10
+ case "ObjectPattern":
11
+ node.properties.forEach((p) =>
12
+ patternNames(p.type === "Property" ? p.value : p.argument, set),
13
+ );
14
+ break;
15
+ case "ArrayPattern":
16
+ node.elements.forEach((el) => patternNames(el, set));
17
+ break;
18
+ case "AssignmentPattern":
19
+ patternNames(node.left, set);
20
+ break;
21
+ case "RestElement":
22
+ patternNames(node.argument, set);
23
+ break;
24
+ }
25
+ }
26
+
27
+ function hoistedNames(node, set) {
28
+ (function rec(n) {
29
+ if (!n || typeof n !== "object") return;
30
+ if (Array.isArray(n)) return n.forEach(rec);
31
+ if (typeof n.type !== "string") return;
32
+ if (n.type === "FunctionDeclaration") {
33
+ if (n.id) set.add(n.id.name);
34
+ return;
35
+ }
36
+ if (n.type === "FunctionExpression" || n.type === "ArrowFunctionExpression")
37
+ return;
38
+ if (n.type === "VariableDeclaration" && n.kind === "var")
39
+ n.declarations.forEach((d) => patternNames(d.id, set));
40
+ for (const k in n) {
41
+ if (k === "type" || k === "start" || k === "end") continue;
42
+ rec(n[k]);
43
+ }
44
+ })(node);
45
+ }
46
+
47
+ function lexicalNames(node, set) {
48
+ const fromStatements = (stmts) =>
49
+ stmts.forEach((st) => {
50
+ if (
51
+ st.type === "VariableDeclaration" &&
52
+ (st.kind === "let" || st.kind === "const")
53
+ )
54
+ st.declarations.forEach((d) => patternNames(d.id, set));
55
+ else if (
56
+ st.type === "FunctionDeclaration" ||
57
+ st.type === "ClassDeclaration"
58
+ )
59
+ st.id && set.add(st.id.name);
60
+ });
61
+ switch (node.type) {
62
+ case "BlockStatement":
63
+ case "StaticBlock":
64
+ fromStatements(node.body);
65
+ break;
66
+ case "ForStatement":
67
+ if (node.init && node.init.type === "VariableDeclaration")
68
+ node.init.declarations.forEach((d) => patternNames(d.id, set));
69
+ break;
70
+ case "ForInStatement":
71
+ case "ForOfStatement":
72
+ if (node.left.type === "VariableDeclaration")
73
+ node.left.declarations.forEach((d) => patternNames(d.id, set));
74
+ break;
75
+ case "CatchClause":
76
+ patternNames(node.param, set);
77
+ break;
78
+ case "SwitchStatement":
79
+ node.cases.forEach((c) => fromStatements(c.consequent));
80
+ break;
81
+ }
82
+ }
83
+
84
+ const isFn = (t) =>
85
+ t === "FunctionDeclaration" ||
86
+ t === "FunctionExpression" ||
87
+ t === "ArrowFunctionExpression";
88
+ const within = (node, container) =>
89
+ container && node.start >= container.start && node.end <= container.end;
90
+
91
+ function transform(code) {
92
+ if (!/\}\s*=\s*props\(_storeKey\)/.test(code)) return code;
93
+
94
+ let ast;
95
+ try {
96
+ ast = acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" });
97
+ } catch (e) {
98
+ return code;
99
+ }
100
+
101
+ let factory = null;
102
+ ast.body.forEach((st) => {
103
+ if (st.type === "ExportDefaultDeclaration" && isFn(st.declaration.type))
104
+ factory = st.declaration;
105
+ });
106
+ if (!factory || factory.body.type !== "BlockStatement") return code;
107
+ const factoryBody = factory.body;
108
+
109
+ const bindings = {};
110
+ const declPatterns = [];
111
+ factoryBody.body.forEach((st) => {
112
+ if (st.type !== "VariableDeclaration") return;
113
+ st.declarations.forEach((decl) => {
114
+ if (!decl.id || decl.id.type !== "ObjectPattern") return;
115
+ if (
116
+ !decl.init ||
117
+ decl.init.type !== "CallExpression" ||
118
+ !decl.init.callee ||
119
+ decl.init.callee.name !== "props"
120
+ )
121
+ return;
122
+ declPatterns.push(decl.id);
123
+ decl.id.properties.forEach((p) => {
124
+ if (p.type !== "Property" || p.computed || !p.key || !p.key.name)
125
+ return;
126
+ if (p.value.type === "Identifier")
127
+ bindings[p.value.name] = { key: p.key.name, dflt: null };
128
+ else if (
129
+ p.value.type === "AssignmentPattern" &&
130
+ p.value.left.type === "Identifier"
131
+ )
132
+ bindings[p.value.left.name] = {
133
+ key: p.key.name,
134
+ dflt: code.slice(p.value.right.start, p.value.right.end),
135
+ };
136
+ });
137
+ });
138
+ });
139
+ if (!Object.keys(bindings).length) return code;
140
+
141
+ let propsRef = "__props";
142
+ while (code.indexOf(propsRef) !== -1) propsRef += "$";
143
+
144
+ const repl = (name) => {
145
+ const b = bindings[name];
146
+ const read = propsRef + "." + b.key;
147
+ return b.dflt === null
148
+ ? read
149
+ : "(" + read + " === undefined ? (" + b.dflt + ") : " + read + ")";
150
+ };
151
+
152
+ const edits = [];
153
+ walk.fullAncestor(ast, (node, state, ancestors) => {
154
+ if (node.type !== "Identifier" || !bindings[node.name]) return;
155
+ const parent = ancestors[ancestors.length - 2];
156
+ if (!parent) return;
157
+
158
+ if (declPatterns.some((dp) => within(node, dp))) return;
159
+
160
+ if (
161
+ parent.type === "Property" &&
162
+ parent.key === node &&
163
+ !parent.computed &&
164
+ !parent.shorthand
165
+ )
166
+ return;
167
+ if (
168
+ parent.type === "MemberExpression" &&
169
+ parent.property === node &&
170
+ !parent.computed
171
+ )
172
+ return;
173
+ if (
174
+ (parent.type === "MethodDefinition" ||
175
+ parent.type === "PropertyDefinition") &&
176
+ parent.key === node &&
177
+ !parent.computed
178
+ )
179
+ return;
180
+ if (
181
+ parent.type.indexOf("Import") === 0 ||
182
+ parent.type === "ExportSpecifier"
183
+ )
184
+ return;
185
+ if (
186
+ (parent.type === "LabeledStatement" ||
187
+ parent.type === "BreakStatement" ||
188
+ parent.type === "ContinueStatement") &&
189
+ parent.label === node
190
+ )
191
+ return;
192
+ if (isFn(parent.type) && parent.id === node) return;
193
+ if (
194
+ parent.type === "ClassDeclaration" ||
195
+ parent.type === "ClassExpression"
196
+ ) {
197
+ if (parent.id === node) return;
198
+ }
199
+
200
+ let inFactory = false;
201
+ for (let i = ancestors.length - 2; i >= 0; i--) {
202
+ const a = ancestors[i];
203
+ if (a === factoryBody) {
204
+ inFactory = true;
205
+ break;
206
+ }
207
+
208
+ if (a.type === "VariableDeclarator" && within(node, a.id)) return;
209
+ if (
210
+ isFn(a.type) &&
211
+ a.params.length &&
212
+ node.start >= a.params[0].start &&
213
+ node.end <= a.params[a.params.length - 1].end
214
+ )
215
+ return;
216
+ if (a.type === "CatchClause" && a.param && within(node, a.param)) return;
217
+
218
+ const declared = new Set();
219
+ if (isFn(a.type)) {
220
+ a.params.forEach((p) => patternNames(p, declared));
221
+ hoistedNames(a.body, declared);
222
+ } else {
223
+ lexicalNames(a, declared);
224
+ }
225
+ if (declared.has(node.name)) return;
226
+ }
227
+ if (!inFactory) return;
228
+
229
+ const grand = ancestors[ancestors.length - 3];
230
+ if (
231
+ parent.type === "Property" &&
232
+ parent.shorthand &&
233
+ parent.value === node &&
234
+ grand &&
235
+ grand.type === "ObjectExpression"
236
+ ) {
237
+ edits.push({
238
+ start: node.start,
239
+ end: node.end,
240
+ text: node.name + ": " + repl(node.name),
241
+ });
242
+ return;
243
+ }
244
+ if (parent.type === "Property" && parent.shorthand && parent.value === node)
245
+ return;
246
+
247
+ edits.push({ start: node.start, end: node.end, text: repl(node.name) });
248
+ });
249
+
250
+ if (!edits.length) return code;
251
+
252
+ const anchor = factoryBody.body[0];
253
+ edits.push({
254
+ start: anchor.end,
255
+ end: anchor.end,
256
+ text: " const " + propsRef + " = props(_storeKey);",
257
+ });
258
+ edits.sort((a, b) => b.start - a.start);
259
+ let out = code;
260
+ edits.forEach(
261
+ (e) => (out = out.slice(0, e.start) + e.text + out.slice(e.end)),
262
+ );
263
+ return out;
264
+ }
265
+
266
+ module.exports = transform;
package/lib/log.js ADDED
@@ -0,0 +1,30 @@
1
+ const { getLineInfo } = require("./lineCounter");
2
+ const { RAW_OPEN, RAW_CLOSE, shieldOps } = require("./tokens");
3
+
4
+ function handleLog(body, counter, filePath) {
5
+ const elms = new Array().slice.call(body.querySelectorAll("log"));
6
+ elms.forEach((item) => {
7
+ const raw = (item.textContent || "").trim();
8
+ const match = raw.match(/^\{([\s\S]*)\}$/);
9
+ if (!match || !match[1].trim()) {
10
+ getLineInfo(
11
+ counter,
12
+ item,
13
+ filePath,
14
+ "Empty or malformed <log> — expected <log>{expr}</log>:",
15
+ );
16
+ item.remove();
17
+ return;
18
+ }
19
+ const expr = shieldOps(match[1].trim());
20
+ const encoded = expr.replace(/{/g, "&lt;-olum-&gt;");
21
+
22
+ item.insertAdjacentHTML(
23
+ "beforebegin",
24
+ RAW_OPEN + "(console.log(" + encoded + "), '')" + RAW_CLOSE,
25
+ );
26
+ item.remove();
27
+ });
28
+ }
29
+
30
+ module.exports = handleLog;
@@ -1,32 +1,7 @@
1
- /**
2
- * magic-string.js — standalone single-file source map generator
3
- * Minimal replacement for the `magic-string` package (v0.30.21), using only
4
- * node built-ins. This project (lib/sourcemap.js) only ever builds an
5
- * IDENTITY map — `new MagicString(str)` with zero edits, then
6
- * `generateMap({ source, file, includeContent })` — so that surface is ported
7
- * faithfully (byte-identical output, including the VLQ `mappings`, JSON key
8
- * order and `toString()`/`toUrl()`):
9
- *
10
- * const MagicString = require("./magic-string");
11
- * const map = new MagicString(code).generateMap({ source, file, includeContent, hires });
12
- * map.mappings / map.toString() / map.toUrl()
13
- *
14
- * Supported: generateMap / generateDecodedMap with options
15
- * `source`, `file`, `includeContent`, `hires` (true | "boundary" | falsy).
16
- *
17
- * KNOWN LIMITATIONS vs the real magic-string (future maintenance):
18
- * The string EDITING api (overwrite, update, appendLeft/Right, prepend,
19
- * append, remove, move, indent, trim, slice, clone, addSourcemapLocation,
20
- * Bundle, ...) is NOT implemented — those methods throw with a clear message
21
- * instead of failing silently. If the compiler ever needs to transform code
22
- * while tracking mappings (e.g. the sourcemap.js TODO about mapping html
23
- * above the script tag), either extend this file's char-walk in
24
- * generateDecodedMap to consume an edit list, or reinstall the real package.
25
- */
26
1
  "use strict";
27
2
 
28
- // ------------------------------------------------ base64 VLQ (sourcemap-codec)
29
- const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3
+ const BASE64 =
4
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
30
5
 
31
6
  function encodeVlq(num) {
32
7
  num = num < 0 ? (-num << 1) | 1 : num << 1;
@@ -34,15 +9,12 @@ function encodeVlq(num) {
34
9
  do {
35
10
  let digit = num & 31;
36
11
  num >>>= 5;
37
- if (num > 0) digit |= 32; // continuation bit
12
+ if (num > 0) digit |= 32;
38
13
  out += BASE64[digit];
39
14
  } while (num > 0);
40
15
  return out;
41
16
  }
42
17
 
43
- // encode decoded mappings ([[ [genCol, srcIdx, srcLine, srcCol, name?], ...], ...])
44
- // into the standard delta-encoded VLQ string: fields are relative to the
45
- // previous segment; generated column resets per line, the rest carry over
46
18
  function encodeMappings(decoded) {
47
19
  let sourceIndex = 0;
48
20
  let sourceLine = 0;
@@ -50,14 +22,17 @@ function encodeMappings(decoded) {
50
22
  let nameIndex = 0;
51
23
 
52
24
  return decoded
53
- .map(line => {
25
+ .map((line) => {
54
26
  let genColumn = 0;
55
27
  return line
56
- .map(segment => {
28
+ .map((segment) => {
57
29
  let out = encodeVlq(segment[0] - genColumn);
58
30
  genColumn = segment[0];
59
31
  if (segment.length > 1) {
60
- out += encodeVlq(segment[1] - sourceIndex) + encodeVlq(segment[2] - sourceLine) + encodeVlq(segment[3] - sourceColumn);
32
+ out +=
33
+ encodeVlq(segment[1] - sourceIndex) +
34
+ encodeVlq(segment[2] - sourceLine) +
35
+ encodeVlq(segment[3] - sourceColumn);
61
36
  sourceIndex = segment[1];
62
37
  sourceLine = segment[2];
63
38
  sourceColumn = segment[3];
@@ -73,12 +48,11 @@ function encodeMappings(decoded) {
73
48
  .join(";");
74
49
  }
75
50
 
76
- // path of `to` relative to `from`'s directory (magic-string's own helper)
77
51
  function getRelativePath(from, to) {
78
52
  const fromParts = from.split(/[/\\]/);
79
53
  const toParts = to.split(/[/\\]/);
80
54
 
81
- fromParts.pop(); // get dirname
55
+ fromParts.pop();
82
56
 
83
57
  while (fromParts[0] === toParts[0]) {
84
58
  fromParts.shift();
@@ -93,7 +67,6 @@ function getRelativePath(from, to) {
93
67
  return fromParts.concat(toParts).join("/");
94
68
  }
95
69
 
96
- // --------------------------------------------------------------- SourceMap
97
70
  class SourceMap {
98
71
  constructor(properties) {
99
72
  this.version = 3;
@@ -105,15 +78,17 @@ class SourceMap {
105
78
  }
106
79
 
107
80
  toString() {
108
- return JSON.stringify(this); // undefined keys (file, sourcesContent) drop out
81
+ return JSON.stringify(this);
109
82
  }
110
83
 
111
84
  toUrl() {
112
- return "data:application/json;charset=utf-8;base64," + Buffer.from(this.toString(), "utf-8").toString("base64");
85
+ return (
86
+ "data:application/json;charset=utf-8;base64," +
87
+ Buffer.from(this.toString(), "utf-8").toString("base64")
88
+ );
113
89
  }
114
90
  }
115
91
 
116
- // -------------------------------------------------------------- MagicString
117
92
  const wordRegex = /\w/;
118
93
 
119
94
  class MagicString {
@@ -130,10 +105,6 @@ class MagicString {
130
105
  return this.original.length;
131
106
  }
132
107
 
133
- // identity mapping: walk the original char by char, mirroring magic-string's
134
- // Mappings.addUneditedChunk — a segment at the first char of every line
135
- // (every char for hires: true, word boundaries for hires: "boundary");
136
- // lines with no characters get no segment
137
108
  generateDecodedMap(options = {}) {
138
109
  const hires = options.hires;
139
110
  const mappings = [];
@@ -157,7 +128,6 @@ class MagicString {
157
128
  if (hires || first) {
158
129
  const segment = [genColumn, 0, sourceLine, sourceColumn];
159
130
  if (hires === "boundary") {
160
- // one segment per word, plus one for every non-word char
161
131
  if (wordRegex.test(this.original[i])) {
162
132
  if (!inBoundary) {
163
133
  line.push(segment);
@@ -180,7 +150,11 @@ class MagicString {
180
150
 
181
151
  return {
182
152
  file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
183
- sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
153
+ sources: [
154
+ options.source
155
+ ? getRelativePath(options.file || "", options.source)
156
+ : options.file || "",
157
+ ],
184
158
  sourcesContent: options.includeContent ? [this.original] : undefined,
185
159
  names: [],
186
160
  mappings,
@@ -192,18 +166,37 @@ class MagicString {
192
166
  }
193
167
  }
194
168
 
195
- // editing api is intentionally absent — fail loudly, not silently
196
169
  for (const method of [
197
- "addSourcemapLocation", "append", "appendLeft", "appendRight", "clone", "indent",
198
- "insertLeft", "insertRight", "move", "overwrite", "prepend", "prependLeft",
199
- "prependRight", "remove", "replace", "replaceAll", "reset", "slice", "snip",
200
- "trim", "trimEnd", "trimStart", "trimLines", "update",
170
+ "addSourcemapLocation",
171
+ "append",
172
+ "appendLeft",
173
+ "appendRight",
174
+ "clone",
175
+ "indent",
176
+ "insertLeft",
177
+ "insertRight",
178
+ "move",
179
+ "overwrite",
180
+ "prepend",
181
+ "prependLeft",
182
+ "prependRight",
183
+ "remove",
184
+ "replace",
185
+ "replaceAll",
186
+ "reset",
187
+ "slice",
188
+ "snip",
189
+ "trim",
190
+ "trimEnd",
191
+ "trimStart",
192
+ "trimLines",
193
+ "update",
201
194
  ]) {
202
195
  MagicString.prototype[method] = function () {
203
196
  throw new Error(
204
197
  `MagicString#${method}() is not implemented in the standalone lib/magic-string.js — ` +
205
198
  "only identity source map generation (generateMap) is supported. " +
206
- "See the header comment for how to extend it, or reinstall the real magic-string package."
199
+ "See the header comment for how to extend it, or reinstall the real magic-string package.",
207
200
  );
208
201
  };
209
202
  }
package/lib/models.js CHANGED
@@ -4,7 +4,7 @@ const path = require("path");
4
4
  function handleModels(body, counter, filePath) {
5
5
  const elms = new Array().slice.call(body.querySelectorAll("[model]"));
6
6
  const name = path.basename(filePath).replace(/\.html/i, "");
7
- elms.forEach(item => {
7
+ elms.forEach((item) => {
8
8
  const value = item.getAttribute("model").trim();
9
9
  if (value) {
10
10
  const data = value.split(".");
@@ -16,17 +16,18 @@ function handleModels(body, counter, filePath) {
16
16
  item.setAttribute("data-o-model", prop + "," + name);
17
17
  item.removeAttribute("model");
18
18
  if (mode.length) item.setAttribute("data-o-model-mode", mode.join(","));
19
- // console.log({ index, data, prop, mode });
20
- // console.log(item.outerHTML + "\n----------");
21
19
  } else if (index === false) {
22
20
  const prop = data.join(".");
23
21
  item.setAttribute("data-o-e", "true");
24
22
  item.setAttribute("data-o-model", prop + "," + name);
25
23
  item.removeAttribute("model");
26
- // console.log({ index, data, prop });
27
- // console.log(item.outerHTML + "\n----------");
28
24
  } else if (index === 0) {
29
- getLineInfo(counter, item, filePath, "Can't start model attribute with a modifier!");
25
+ getLineInfo(
26
+ counter,
27
+ item,
28
+ filePath,
29
+ "Can't start model attribute with a modifier!",
30
+ );
30
31
  }
31
32
  }
32
33
  });
@@ -42,7 +43,7 @@ function hasMode(data) {
42
43
  mode3 = mode3 === -1 ? max : mode3;
43
44
  const indexArr = [mode1, mode2, mode3];
44
45
  const min = Math.min(...indexArr);
45
- // console.log({ min, mode1, mode2, mode3 });
46
+
46
47
  if (min === max) return false;
47
48
  else if (min === 0) return 0;
48
49
  return min;