olum-compiler 1.5.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 (48) hide show
  1. package/.claude/settings.local.json +2 -1
  2. package/bin/build.js +1 -1
  3. package/bin/bundle.js +32 -30
  4. package/bin/compiler.js +20 -10
  5. package/bin/copySrc.js +45 -41
  6. package/bin/dev.js +46 -39
  7. package/bin/index.js +6 -4
  8. package/bin/server.js +58 -33
  9. package/bin/watcher.js +11 -14
  10. package/bin/ws.js +16 -11
  11. package/lib/attr.js +1 -25
  12. package/lib/boolAttr.js +32 -15
  13. package/lib/chokidar.js +52 -101
  14. package/lib/colors.js +1 -7
  15. package/lib/compPlaceholder.js +5 -3
  16. package/lib/compiler.js +3 -6
  17. package/lib/coreLibs.js +1 -10
  18. package/lib/cross-spawn.js +45 -59
  19. package/lib/cssParser.js +61 -37
  20. package/lib/domEvents.js +6 -2
  21. package/lib/events.js +75 -77
  22. package/lib/for.js +56 -28
  23. package/lib/getImports.js +35 -17
  24. package/lib/getTempPath.js +8 -4
  25. package/lib/helpers.js +289 -184
  26. package/lib/html.js +3 -10
  27. package/lib/htmlParser.js +45 -45
  28. package/lib/if.js +40 -20
  29. package/lib/importMap.js +49 -24
  30. package/lib/jsParser.js +8 -13
  31. package/lib/lineCounter.js +18 -5
  32. package/lib/liveProps.js +124 -78
  33. package/lib/log.js +30 -0
  34. package/lib/magic-string.js +45 -52
  35. package/lib/models.js +8 -7
  36. package/lib/parser.js +76 -44
  37. package/lib/placeholder.js +73 -58
  38. package/lib/regex.js +4 -3
  39. package/lib/show.js +16 -8
  40. package/lib/sourcemap.js +23 -24
  41. package/lib/styles.js +7 -13
  42. package/lib/textarea.js +3 -6
  43. package/lib/toJs.js +1 -1
  44. package/lib/tokens.js +10 -22
  45. package/lib/transition.js +86 -0
  46. package/lib/websocket.js +68 -62
  47. package/package.json +1 -1
  48. package/tests/compiler.test.js +423 -188
package/lib/helpers.js CHANGED
@@ -4,37 +4,37 @@ const path = require("path");
4
4
  const fs = require("fs");
5
5
  const process = require("process");
6
6
  const id = () => "_" + Math.random().toString(36).slice(2);
7
- const isObj = obj => !!(obj !== null && typeof obj === "object");
8
- const isFullArr = arr => !!(isObj(arr) && Array.isArray(arr) && arr.length);
9
- const isDef = val => !!(val !== undefined && val !== null);
10
- const flatten = lists => lists.reduce((a, b) => a.concat(b), []);
11
- const isHTML = str => compExt.test(str);
12
- const isFile = item => !fs.statSync(item).isDirectory();
13
- const isDir = item => fs.statSync(item).isDirectory();
7
+ const isObj = (obj) => !!(obj !== null && typeof obj === "object");
8
+ const isFullArr = (arr) => !!(isObj(arr) && Array.isArray(arr) && arr.length);
9
+ const isDef = (val) => !!(val !== undefined && val !== null);
10
+ const flatten = (lists) => lists.reduce((a, b) => a.concat(b), []);
11
+ const isHTML = (str) => compExt.test(str);
12
+ const isFile = (item) => !fs.statSync(item).isDirectory();
13
+ const isDir = (item) => fs.statSync(item).isDirectory();
14
14
  const isWin = () => !["linux", "darwin"].includes(process.platform);
15
15
  const hasForwardSlash = (paths) => paths.find((item) => /\//g.test(item));
16
- const hasSlash = (paths) => paths.find((item) => /\//g.test(item) || /\\/g.test(item));
17
- const stringToBase64 = (str) => Buffer.from(str).toString('base64');
18
- const base64ToString = (base64) => Buffer.from(base64, 'base64').toString('ascii');
16
+ const hasSlash = (paths) =>
17
+ paths.find((item) => /\//g.test(item) || /\\/g.test(item));
18
+ const stringToBase64 = (str) => Buffer.from(str).toString("base64");
19
+ const base64ToString = (base64) =>
20
+ Buffer.from(base64, "base64").toString("ascii");
19
21
  const acorn = require("acorn");
20
22
 
21
- const cleanParentheses = (filePath, type="name") => {
23
+ const cleanParentheses = (filePath, type = "name") => {
22
24
  if (type == "name") {
23
- return filePath.replace(/\([^)]*\)/g, "")
24
- } else if (type == "url"){ // clean slash after it also e.g. (main)/
25
- return filePath.replace(/\([^)]*\)\//g, "")
25
+ return filePath.replace(/\([^)]*\)/g, "");
26
+ } else if (type == "url") {
27
+ return filePath.replace(/\([^)]*\)\//g, "");
26
28
  }
27
29
  return filePath;
28
- }
30
+ };
29
31
 
30
32
  const cleanNumbersPrefix = (name, type = "name") => {
31
33
  if (type === "url") {
32
- // only the NN- ordering prefix at a segment start — a blanket digit strip would
33
- // corrupt legit digit segments ("/404" -> "/", "/7guis" -> "/guis")
34
34
  return name.replace(/(^|\/)\d+-/g, "$1");
35
35
  }
36
36
  return name.replace(/\d+-?/g, "");
37
- }
37
+ };
38
38
 
39
39
  function isUpper(char) {
40
40
  const upperChar = char.toUpperCase();
@@ -42,7 +42,10 @@ function isUpper(char) {
42
42
  return regex.test(char);
43
43
  }
44
44
  function isNum(str) {
45
- if (["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].includes(str.trim()[0])) return true;
45
+ if (
46
+ ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].includes(str.trim()[0])
47
+ )
48
+ return true;
46
49
  return false;
47
50
  }
48
51
  function toLower(str) {
@@ -52,8 +55,6 @@ function toUpper(str) {
52
55
  return str.toUpperCase();
53
56
  }
54
57
 
55
- // takes absolute path
56
- // e.g. ls(src, { absolute: false })
57
58
  function ls(src, opt) {
58
59
  let paths = [];
59
60
 
@@ -83,10 +84,9 @@ function ls(src, opt) {
83
84
  });
84
85
  }
85
86
 
86
- // handle options
87
- if (opt && opt.hasOwnProperty("absolute") && opt.absolute === false) paths = paths.map((item) => item.replace(src + "/", ""));
87
+ if (opt && opt.hasOwnProperty("absolute") && opt.absolute === false)
88
+ paths = paths.map((item) => item.replace(src + "/", ""));
88
89
 
89
- // handle slashes
90
90
  if (hasSlash(paths)) {
91
91
  const hasForward = hasForwardSlash(paths);
92
92
  const win = isWin();
@@ -100,8 +100,6 @@ function ls(src, opt) {
100
100
  return paths;
101
101
  }
102
102
 
103
- // todo make other tests
104
- // e.g. copy("path/to/src", "path/to/dest");
105
103
  function copy(src, dest, cb) {
106
104
  const files = ls(src);
107
105
  let srcDir = path.basename(src);
@@ -115,21 +113,25 @@ function copy(src, dest, cb) {
115
113
  if (!dirs.includes(dir)) dirs.push(dir);
116
114
  });
117
115
 
118
- dirs.forEach((dir) => dir.replace(new RegExp(`${srcDir}.*`), (str) => cleanDirs.push(destDirChunck + str.replace(new RegExp(`${srcDir}`), destDir))));
119
- files.forEach((dir) => dir.replace(new RegExp(`${srcDir}.*`), (str) => cleanFiles.push(destDirChunck + str.replace(new RegExp(`${srcDir}`), destDir))));
120
-
121
- // console.log({ dirs });
122
- // console.log({ cleanDirs });
123
- // console.log({ cleanFiles });
124
- // console.log({ srcDir });
125
- // console.log({ destDir });
126
- // console.log({ files });
127
- // console.log({ destDirChunck });
128
- // make dirs
116
+ dirs.forEach((dir) =>
117
+ dir.replace(new RegExp(`${srcDir}.*`), (str) =>
118
+ cleanDirs.push(
119
+ destDirChunck + str.replace(new RegExp(`${srcDir}`), destDir),
120
+ ),
121
+ ),
122
+ );
123
+ files.forEach((dir) =>
124
+ dir.replace(new RegExp(`${srcDir}.*`), (str) =>
125
+ cleanFiles.push(
126
+ destDirChunck + str.replace(new RegExp(`${srcDir}`), destDir),
127
+ ),
128
+ ),
129
+ );
130
+
129
131
  cleanDirs.forEach((dir) => {
130
132
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
131
133
  });
132
- // copy files to pre-made dirs above
134
+
133
135
  files.forEach((file, index) => {
134
136
  if (fs.lstatSync(file).isFile()) {
135
137
  const fileDest = cleanFiles[index];
@@ -139,59 +141,40 @@ function copy(src, dest, cb) {
139
141
  if (cb) cb();
140
142
  }
141
143
 
142
- // e.g. remove("path/to/dir");
143
144
  function remove(src, cb) {
144
145
  const files = ls(src);
145
- // console.log({ files });
146
-
147
- const upDir = path.resolve(files[0] , "..");
146
+
147
+ const upDir = path.resolve(files[0], "..");
148
148
  files.unshift(upDir);
149
- // console.log(upDir);
150
- // console.log({ files });
151
149
 
152
150
  files.forEach((dir) => {
153
151
  if (fs.existsSync(dir) && fs.lstatSync(dir).isFile()) fs.unlinkSync(dir);
154
152
  });
155
153
 
156
154
  files.reverse().forEach((dir) => {
157
- if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory()) fs.rmdirSync(dir);
155
+ if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory())
156
+ fs.rmdirSync(dir);
158
157
  });
159
158
  if (cb) cb();
160
159
  }
161
160
 
162
- function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs: attributes }) {
163
- /*
164
-
165
- // must type the attribute as kebab-case if it was camel-case in the logic. e.g.: you have method/prop called getAge, then it will be: exclude-get-age
166
- private
167
- private-props
168
- private-methods
169
- ----------
170
- public
171
- public-props
172
- public-methods
173
- ----------
174
- exclude-prop-name
175
- exclude-method-name
176
-
177
- convert above attributes to below query syntax:
178
-
179
- all=private&except=['age','name']
180
-
181
- ----------
182
-
183
- Order matters:
184
-
185
- ['public-props', 'exclude-age', 'exclude-name', 'private-methods', 'exclude-get-age']
186
- ↓ ↓ ↓ ↓ ↓
187
- open props → age → name close props → getAge
188
- open methods close methods (end)
189
-
190
- */
191
-
161
+ function createScopeHandler({
162
+ stateProps,
163
+ hasState,
164
+ propsTobeExcluded,
165
+ jsAttrs: attributes,
166
+ }) {
192
167
  function scopePolyfill(attrs) {
193
- const SCOPES = ["public", "public-props", "public-methods", "private", "private-props", "private-methods"];
194
- const toCamel = str => str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
168
+ const SCOPES = [
169
+ "public",
170
+ "public-props",
171
+ "public-methods",
172
+ "private",
173
+ "private-props",
174
+ "private-methods",
175
+ ];
176
+ const toCamel = (str) =>
177
+ str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
195
178
  const results = {};
196
179
 
197
180
  let current = null;
@@ -223,7 +206,7 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
223
206
  return results;
224
207
  }
225
208
 
226
- const jsAttrs = scopePolyfill(Object.keys(attributes))
209
+ const jsAttrs = scopePolyfill(Object.keys(attributes));
227
210
  const scope = {
228
211
  methods: { all: null, except: null },
229
212
  props: { all: null, except: null },
@@ -246,8 +229,10 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
246
229
  if (stateProps.includes(propsInState)) propsInExcept.push(propsInState);
247
230
  }
248
231
  });
249
- if (type === "public") arr = stateProps.filter((prop) => !propsInExcept.includes(prop));
250
- else if (type === "private") arr = stateProps.filter((prop) => propsInExcept.includes(prop));
232
+ if (type === "public")
233
+ arr = stateProps.filter((prop) => !propsInExcept.includes(prop));
234
+ else if (type === "private")
235
+ arr = stateProps.filter((prop) => propsInExcept.includes(prop));
251
236
  return arr;
252
237
  }
253
238
 
@@ -256,11 +241,18 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
256
241
  let arr = [];
257
242
  exceptArr.forEach((name) => {
258
243
  if (globalNamesArr.includes(name)) {
259
- if (name !== "state" && !name.startsWith("state.")) namesInExcept.push(name);
244
+ if (name !== "state" && !name.startsWith("state."))
245
+ namesInExcept.push(name);
260
246
  }
261
247
  });
262
- if (type === "public") arr = globalNamesArr.filter((prop) => !namesInExcept.includes(prop) && prop !== "state");
263
- if (type === "private") arr = globalNamesArr.filter((prop) => namesInExcept.includes(prop) && prop !== "state");
248
+ if (type === "public")
249
+ arr = globalNamesArr.filter(
250
+ (prop) => !namesInExcept.includes(prop) && prop !== "state",
251
+ );
252
+ if (type === "private")
253
+ arr = globalNamesArr.filter(
254
+ (prop) => namesInExcept.includes(prop) && prop !== "state",
255
+ );
264
256
  return arr;
265
257
  }
266
258
 
@@ -270,8 +262,10 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
270
262
  exceptArr.forEach((name) => {
271
263
  if (globalNamesArr.includes(name)) namesInExcept.push(name);
272
264
  });
273
- if (type === "public") arr = globalNamesArr.filter((method) => !namesInExcept.includes(method));
274
- if (type === "private") arr = globalNamesArr.filter((method) => namesInExcept.includes(method));
265
+ if (type === "public")
266
+ arr = globalNamesArr.filter((method) => !namesInExcept.includes(method));
267
+ if (type === "private")
268
+ arr = globalNamesArr.filter((method) => namesInExcept.includes(method));
275
269
  return arr;
276
270
  }
277
271
 
@@ -294,11 +288,15 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
294
288
  const currentScope = parseScope(jsAttrs[type + "-scope"]);
295
289
  if (currentScope) {
296
290
  if (currentScope.all && currentScope.all.trim() !== "") {
297
- if (["public", "private"].includes(toLower(currentScope.all))) scope[type].all = toLower(currentScope.all).trim();
291
+ if (["public", "private"].includes(toLower(currentScope.all)))
292
+ scope[type].all = toLower(currentScope.all).trim();
298
293
  }
299
294
  if (currentScope.except && isFullArr(currentScope.except)) {
300
- currentScope.except = currentScope.except.filter((item) => item && item.trim() !== "").map((item) => item.trim());
301
- if (isFullArr(currentScope.except)) scope[type].except = currentScope.except;
295
+ currentScope.except = currentScope.except
296
+ .filter((item) => item && item.trim() !== "")
297
+ .map((item) => item.trim());
298
+ if (isFullArr(currentScope.except))
299
+ scope[type].except = currentScope.except;
302
300
  }
303
301
  }
304
302
  }
@@ -307,49 +305,74 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
307
305
  let arr = [];
308
306
  arr = globalNamesArr
309
307
  .map((name) => {
310
- if (!["state", ...propsTobeExcluded].includes(name)) return `get ${name}(){return ${name}},set ${name}(val){return ${name} = val}`;
308
+ if (!["state", ...propsTobeExcluded].includes(name))
309
+ return `get ${name}(){return ${name}},set ${name}(val){return ${name} = val}`;
311
310
  })
312
311
  .filter((item) => item);
313
312
  if (hasState && isFullArr(stateProps)) {
314
313
  let fragments = stateProps.map((prop) => prop + ": state." + prop);
315
- arr.push(`get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`);
314
+ arr.push(
315
+ `get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`,
316
+ );
316
317
  }
317
318
  return arr;
318
319
  }
319
320
 
320
- // all methods/props are private by default
321
321
  function handleScope(globalNamesArr, type) {
322
322
  if (globalNamesArr && isFullArr(globalNamesArr) && type) {
323
323
  if (!scope[type]) return toObj();
324
324
  if (!scope[type].all) return toObj();
325
325
  if (scope[type].all === "public") {
326
- if (!scope[type].except) return type === "methods" ? toObj(globalNamesArr) : toObj(shareAllProps(globalNamesArr));
326
+ if (!scope[type].except)
327
+ return type === "methods"
328
+ ? toObj(globalNamesArr)
329
+ : toObj(shareAllProps(globalNamesArr));
327
330
  if (scope[type].except && isFullArr(scope[type].except)) {
328
331
  if (type === "methods") {
329
332
  let arr = [];
330
- let newArr = getMethods(scope[type].except, globalNamesArr, "public");
333
+ let newArr = getMethods(
334
+ scope[type].except,
335
+ globalNamesArr,
336
+ "public",
337
+ );
331
338
  if (newArr.length) arr = newArr;
332
339
  else return toObj();
333
340
  return arr.length ? toObj(arr) : toObj(globalNamesArr);
334
341
  } else if (type === "props") {
335
- const hasStateKeywordInExcecpt = scope[type].except.find((name) => name === "state");
342
+ const hasStateKeywordInExcecpt = scope[type].except.find(
343
+ (name) => name === "state",
344
+ );
336
345
  let arr = [];
337
346
  let newArr = getProps(scope[type].except, globalNamesArr, "public");
338
347
  if (newArr.length) arr = newArr;
339
- arr = arr.map((item) => `get ${item}(){return ${item}},set ${item}(val){return ${item} = val}`);
348
+ arr = arr.map(
349
+ (item) =>
350
+ `get ${item}(){return ${item}},set ${item}(val){return ${item} = val}`,
351
+ );
340
352
  if (hasState && isFullArr(stateProps)) {
341
353
  let publicPropsInState = [];
342
354
  if (!hasStateKeywordInExcecpt) {
343
- if (!hasStateDot(scope[type].except)) publicPropsInState = stateProps;
344
- else publicPropsInState = getStateProps(scope[type].except, "public");
355
+ if (!hasStateDot(scope[type].except))
356
+ publicPropsInState = stateProps;
357
+ else
358
+ publicPropsInState = getStateProps(
359
+ scope[type].except,
360
+ "public",
361
+ );
345
362
  }
346
363
  if (isFullArr(publicPropsInState)) {
347
- let fragments = publicPropsInState.map((prop) => prop + ": state." + prop);
348
- arr.push(`get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`);
364
+ let fragments = publicPropsInState.map(
365
+ (prop) => prop + ": state." + prop,
366
+ );
367
+ arr.push(
368
+ `get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`,
369
+ );
349
370
  }
350
371
  }
351
372
  if (!newArr.length && !arr.length) return toObj();
352
- return arr.length ? toObj(arr) : toObj(shareAllProps(globalNamesArr));
373
+ return arr.length
374
+ ? toObj(arr)
375
+ : toObj(shareAllProps(globalNamesArr));
353
376
  }
354
377
  }
355
378
  } else if (scope[type].all === "private") {
@@ -360,19 +383,32 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
360
383
  arr = getMethods(scope[type].except, globalNamesArr, "private");
361
384
  return arr.length ? toObj(arr) : toObj();
362
385
  } else if (type === "props") {
363
- const hasStateKeywordInExcecpt = scope[type].except.find((name) => name === "state");
386
+ const hasStateKeywordInExcecpt = scope[type].except.find(
387
+ (name) => name === "state",
388
+ );
364
389
  let arr = [];
365
390
  arr = getProps(scope[type].except, globalNamesArr, "private");
366
- arr = arr.map((item) => `get ${item}(){return ${item}},set ${item}(val){return ${item} = val}`);
391
+ arr = arr.map(
392
+ (item) =>
393
+ `get ${item}(){return ${item}},set ${item}(val){return ${item} = val}`,
394
+ );
367
395
  if (hasState && isFullArr(stateProps)) {
368
396
  let publicPropsInState = [];
369
397
  if (hasStateKeywordInExcecpt) publicPropsInState = stateProps;
370
398
  else {
371
- if (hasStateDot(scope[type].except)) publicPropsInState = getStateProps(scope[type].except, "private");
399
+ if (hasStateDot(scope[type].except))
400
+ publicPropsInState = getStateProps(
401
+ scope[type].except,
402
+ "private",
403
+ );
372
404
  }
373
405
  if (isFullArr(publicPropsInState)) {
374
- let fragments = publicPropsInState.map((prop) => prop + ": state." + prop);
375
- arr.push(`get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`);
406
+ let fragments = publicPropsInState.map(
407
+ (prop) => prop + ": state." + prop,
408
+ );
409
+ arr.push(
410
+ `get state(){return window.olum.proxyHandlerForScope(${"{" + fragments.join(",") + "}"}, state);}`,
411
+ );
376
412
  }
377
413
  }
378
414
  return arr.length ? toObj(arr) : toObj();
@@ -388,7 +424,6 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
388
424
  return handleScope;
389
425
  }
390
426
 
391
- // get methods names
392
427
  function getGlobalMethods(str) {
393
428
  return acorn
394
429
  .parse(str, { ecmaVersion: "latest", sourceType: "module" })
@@ -403,7 +438,8 @@ function getGlobalMethods(str) {
403
438
  obj.declarations[0].id.name &&
404
439
  obj.declarations[0].init &&
405
440
  obj.declarations[0].init.type &&
406
- (obj.declarations[0].init.type === "FunctionExpression" || obj.declarations[0].init.type === "ArrowFunctionExpression")
441
+ (obj.declarations[0].init.type === "FunctionExpression" ||
442
+ obj.declarations[0].init.type === "ArrowFunctionExpression")
407
443
  ) {
408
444
  return obj.declarations[0].id.name;
409
445
  }
@@ -411,34 +447,42 @@ function getGlobalMethods(str) {
411
447
  .filter((item) => item);
412
448
  }
413
449
 
414
- // top-level bindings destructured from props(): const { onMessage, onSave: save } = props()
415
- // returns a localName -> propKey map so placeholder.js can flag bare-identifier prop forwards
416
- // (onMessage="{onMessage}") as kind "props" src entries — functions can't cross the JSON channel
417
450
  function getPropsAliases(str) {
418
451
  const aliases = {};
419
- acorn.parse(str, { ecmaVersion: "latest", sourceType: "module" }).body.forEach((obj) => {
420
- if (obj.type !== "VariableDeclaration" || !Array.isArray(obj.declarations)) return;
421
- obj.declarations.forEach((decl) => {
452
+ acorn
453
+ .parse(str, { ecmaVersion: "latest", sourceType: "module" })
454
+ .body.forEach((obj) => {
422
455
  if (
423
- decl.id &&
424
- decl.id.type === "ObjectPattern" &&
425
- decl.init &&
426
- decl.init.type === "CallExpression" &&
427
- decl.init.callee &&
428
- decl.init.callee.name === "props"
429
- ) {
430
- decl.id.properties.forEach((prop) => {
431
- if (prop.type === "Property" && prop.key && prop.key.name && prop.value && prop.value.type === "Identifier") {
432
- aliases[prop.value.name] = prop.key.name; // localName -> original prop key (handles renames)
433
- }
434
- });
435
- }
456
+ obj.type !== "VariableDeclaration" ||
457
+ !Array.isArray(obj.declarations)
458
+ )
459
+ return;
460
+ obj.declarations.forEach((decl) => {
461
+ if (
462
+ decl.id &&
463
+ decl.id.type === "ObjectPattern" &&
464
+ decl.init &&
465
+ decl.init.type === "CallExpression" &&
466
+ decl.init.callee &&
467
+ decl.init.callee.name === "props"
468
+ ) {
469
+ decl.id.properties.forEach((prop) => {
470
+ if (
471
+ prop.type === "Property" &&
472
+ prop.key &&
473
+ prop.key.name &&
474
+ prop.value &&
475
+ prop.value.type === "Identifier"
476
+ ) {
477
+ aliases[prop.value.name] = prop.key.name;
478
+ }
479
+ });
480
+ }
481
+ });
436
482
  });
437
- });
438
483
  return aliases;
439
484
  }
440
485
 
441
- // get props names
442
486
  function getGlobalProps(str) {
443
487
  return acorn
444
488
  .parse(str, { ecmaVersion: "latest", sourceType: "module" })
@@ -459,10 +503,15 @@ function getGlobalProps(str) {
459
503
  obj.declarations[0].init.type === "Identifier")
460
504
  ) {
461
505
  const name = obj.declarations[0].id.name;
462
- // get all props names inside state object
506
+
463
507
  if (obj.declarations[0].id.name === "state") {
464
508
  if (Array.isArray(obj.declarations) && obj.declarations.length) {
465
- if (obj.declarations[0].init && obj.declarations[0].init.properties && Array.isArray(obj.declarations[0].init.properties) && obj.declarations[0].init.properties.length) {
509
+ if (
510
+ obj.declarations[0].init &&
511
+ obj.declarations[0].init.properties &&
512
+ Array.isArray(obj.declarations[0].init.properties) &&
513
+ obj.declarations[0].init.properties.length
514
+ ) {
466
515
  const arr = obj.declarations[0].init.properties;
467
516
  stateProps = arr.map((item) => item && item.key && item.key.name);
468
517
  }
@@ -474,71 +523,130 @@ function getGlobalProps(str) {
474
523
  .filter((item) => item);
475
524
  }
476
525
 
477
- // minify js as string into one line without changing the js content
526
+ function computeTemplateDeps(html, methodNames, propNames, hasState, js) {
527
+ if (!hasState) return null;
528
+ if (/\bscope\s*\(/.test(html)) return null;
529
+ if (/\bstate\b(?!\s*\.)/.test(html)) return null;
530
+
531
+ const nameStart = "(?<![A-Za-z0-9_$])";
532
+ const escapeName = (name) => name.replace(/\$/g, "\\$");
533
+ for (const name of methodNames) {
534
+ if (name && new RegExp(nameStart + escapeName(name) + "\\s*\\(").test(html))
535
+ return null;
536
+ }
537
+
538
+ for (const prop of propNames || []) {
539
+ if (!prop || prop === "state") continue;
540
+ if (
541
+ new RegExp(
542
+ nameStart +
543
+ escapeName(prop) +
544
+ "\\s*\\.\\s*[A-Za-z_$][A-Za-z0-9_$]*\\s*\\(",
545
+ ).test(html)
546
+ )
547
+ return null;
548
+ }
549
+ const deps = [];
550
+ const addDep = (key) => {
551
+ if (key && !deps.includes(key)) deps.push(key);
552
+ };
553
+ html.replace(/\bstate\s*\.\s*([A-Za-z_$][A-Za-z0-9_$]*)/g, (match, key) => {
554
+ addDep(key);
555
+ return match;
556
+ });
557
+
558
+ if (js) {
559
+ const usesAlias = (alias) =>
560
+ alias &&
561
+ new RegExp(nameStart + escapeName(alias) + "(?![A-Za-z0-9_$])").test(
562
+ html,
563
+ );
564
+
565
+ js.replace(
566
+ /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*state\s*\.\s*([A-Za-z_$][\w$]*)/g,
567
+ (m, alias, key) => {
568
+ if (usesAlias(alias)) addDep(key);
569
+ return m;
570
+ },
571
+ );
572
+
573
+ js.replace(/(?:const|let|var)\s*\{([^}]*)\}\s*=\s*state\b/g, (m, inner) => {
574
+ inner.split(",").forEach((part) => {
575
+ const bits = part
576
+ .split(":")
577
+ .map((s) => s.replace(/=[\s\S]*/, "").trim());
578
+ const key = bits[0];
579
+ const alias = bits[1] || bits[0];
580
+ if (usesAlias(alias)) addDep(key);
581
+ });
582
+ return m;
583
+ });
584
+ }
585
+ return deps;
586
+ }
587
+
478
588
  function minifyJS(src) {
479
- let out = '';
589
+ let out = "";
480
590
  let i = 0;
481
591
  const n = src.length;
482
592
 
483
593
  while (i < n) {
484
- // Line comment — strip until end of line
485
- if (src[i] === '/' && src[i+1] === '/') {
486
- while (i < n && src[i] !== '\n') i++;
487
- out += ' ';
594
+ if (src[i] === "/" && src[i + 1] === "/") {
595
+ while (i < n && src[i] !== "\n") i++;
596
+ out += " ";
488
597
  continue;
489
598
  }
490
599
 
491
- // Block comment — strip entirely
492
- if (src[i] === '/' && src[i+1] === '*') {
600
+ if (src[i] === "/" && src[i + 1] === "*") {
493
601
  i += 2;
494
- while (i < n && !(src[i] === '*' && src[i+1] === '/')) i++;
602
+ while (i < n && !(src[i] === "*" && src[i + 1] === "/")) i++;
495
603
  i += 2;
496
- out += ' ';
604
+ out += " ";
497
605
  continue;
498
606
  }
499
607
 
500
- // Quoted string — copy verbatim (respect escapes)
501
608
  if (src[i] === '"' || src[i] === "'") {
502
609
  const q = src[i++];
503
610
  out += q;
504
611
  while (i < n) {
505
612
  const c = src[i++];
506
613
  out += c;
507
- if (c === '\\' && i < n) { out += src[i++]; continue; }
614
+ if (c === "\\" && i < n) {
615
+ out += src[i++];
616
+ continue;
617
+ }
508
618
  if (c === q) break;
509
619
  }
510
620
  continue;
511
621
  }
512
622
 
513
- // Whitespace — collapse to single space
514
623
  if (/\s/.test(src[i])) {
515
624
  while (i < n && /\s/.test(src[i])) i++;
516
- out += ' ';
625
+ out += " ";
517
626
  continue;
518
627
  }
519
628
 
520
- // Everything else — copy as-is
521
629
  out += src[i++];
522
630
  }
523
631
 
524
- // Remove spaces around punctuation, restore keyword spacing, collapse multi-spaces
525
632
  out = out
526
- .replace(/ *([=+\-*/%&|^~<>!?,;:{}()[\]]) */g, '$1')
527
- .replace(/\b(const|let|var|return|if|else|for|while|do|switch|case|new|delete|typeof|instanceof|in|of|void|throw|catch|finally|function|class|import|export|from|async|await)\b/g, '$1 ')
528
- .replace(/ {2,}/g, ' ')
633
+ .replace(/ *([=+\-*/%&|^~<>!?,;:{}()[\]]) */g, "$1")
634
+ .replace(
635
+ /\b(const|let|var|return|if|else|for|while|do|switch|case|new|delete|typeof|instanceof|in|of|void|throw|catch|finally|function|class|import|export|from|async|await)\b/g,
636
+ "$1 ",
637
+ )
638
+ .replace(/ {2,}/g, " ")
529
639
  .trim();
530
640
 
531
641
  return out;
532
642
  }
533
643
 
534
- // handle routing based on files
535
644
  function generateRouteManifest(paths, rootDir) {
536
645
  const routes = {};
537
646
 
538
647
  for (const absolutePath of paths) {
539
648
  const relative = path.relative(rootDir, absolutePath).replace(/\\/g, "/");
540
649
 
541
- // Global not-found
542
650
  if (relative === "not-found.html") {
543
651
  routes["not-found"] = {
544
652
  page: "not-found.html",
@@ -546,35 +654,33 @@ function generateRouteManifest(paths, rootDir) {
546
654
  continue;
547
655
  }
548
656
 
549
- // Only page files create routes
550
657
  if (!relative.endsWith("/page.html") && relative !== "page.html") {
551
658
  continue;
552
659
  }
553
660
 
554
- // Remove "/page.html" or "page.html"
555
661
  let routePath = relative
556
662
  .replace(/\/page\.html$/, "")
557
663
  .replace(/^page\.html$/, "");
558
- routePath = cleanParentheses(routePath, "url")
664
+ routePath = cleanParentheses(routePath, "url");
559
665
 
560
- const segments = routePath
561
- .split("/")
562
- .filter(Boolean);
666
+ const segments = routePath.split("/").filter(Boolean);
563
667
 
564
668
  const params = [];
565
669
 
566
- const route = "/" + segments
567
- .map(segment => {
568
- const match = segment.match(/^\[(.+)\]$/);
670
+ const route =
671
+ "/" +
672
+ segments
673
+ .map((segment) => {
674
+ const match = segment.match(/^\[(.+)\]$/);
569
675
 
570
- if (match) {
571
- params.push(match[1]);
572
- return `:${match[1]}`;
573
- }
676
+ if (match) {
677
+ params.push(match[1]);
678
+ return `:${match[1]}`;
679
+ }
574
680
 
575
- return segment;
576
- })
577
- .join("/");
681
+ return segment;
682
+ })
683
+ .join("/");
578
684
 
579
685
  routes[route === "/" ? "/" : route] = {
580
686
  page: relative,
@@ -593,15 +699,14 @@ function toComponentName(file) {
593
699
  return file
594
700
  .replace(/\/page\.html$/, "")
595
701
  .split("/")
596
- .map(segment => {
597
- // [slug] -> Slug
702
+ .map((segment) => {
598
703
  if (/^\[.+\]$/.test(segment)) {
599
704
  segment = segment.slice(1, -1);
600
705
  }
601
706
 
602
707
  return segment
603
708
  .split("-")
604
- .map(word => word.charAt(0).toUpperCase() + word.slice(1))
709
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
605
710
  .join("");
606
711
  })
607
712
  .join("");
@@ -619,7 +724,6 @@ function generateImports(manifest) {
619
724
  function generateRoutes(manifest) {
620
725
  const routes = [];
621
726
 
622
- // Root first
623
727
  if (manifest["/"]) {
624
728
  routes.push({
625
729
  path: "/",
@@ -627,7 +731,6 @@ function generateRoutes(manifest) {
627
731
  });
628
732
  }
629
733
 
630
- // Other routes
631
734
  for (const [route, config] of Object.entries(manifest)) {
632
735
  if (route === "/" || route === "not-found") continue;
633
736
 
@@ -637,7 +740,6 @@ function generateRoutes(manifest) {
637
740
  });
638
741
  }
639
742
 
640
- // 404 last
641
743
  if (manifest["not-found"]) {
642
744
  routes.push({
643
745
  path: "/404",
@@ -647,7 +749,10 @@ function generateRoutes(manifest) {
647
749
 
648
750
  return `export const routes = [
649
751
  ${routes
650
- .map(({ path, comp }) => ` { path: "${cleanNumbersPrefix(path, "url")}", comp: ${cleanNumbersPrefix(comp)} }`)
752
+ .map(
753
+ ({ path, comp }) =>
754
+ ` { path: "${cleanNumbersPrefix(path, "url")}", comp: ${cleanNumbersPrefix(comp)} }`,
755
+ )
651
756
  .join(",\n")}
652
757
  ];`;
653
758
  }
@@ -659,23 +764,22 @@ const compileRoutes = (entryPoint) => {
659
764
  const isDir = fs.lstatSync(item).isDirectory();
660
765
  const isHtml = fs.lstatSync(item).isFile() && extension == ".html";
661
766
  const segments = path.relative(entryPoint, item).split(path.sep);
662
- const inExcludedDir = segments.some((seg) => ["components", "utils"].includes(seg) || seg.startsWith("_"));
767
+ const inExcludedDir = segments.some(
768
+ (seg) => ["components", "utils"].includes(seg) || seg.startsWith("_"),
769
+ );
663
770
  if (isDir || (isHtml && !inExcludedDir)) return item;
664
771
  });
665
- // generate routes manifest
772
+
666
773
  const manifest = generateRouteManifest(routes, entryPoint);
667
774
  let has404Page = false;
668
- if (manifest['not-found']) has404Page = true;
775
+ if (manifest["not-found"]) has404Page = true;
669
776
  const libImports = `import Olum from "olum";\nimport Router from "olum-router";`;
670
- const imports = generateImports(manifest)
671
- const config = `const config = { mode: "history", root: "/", ${has404Page? `err: "/404",` : "" } routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
777
+ const imports = generateImports(manifest);
778
+ const config = `const config = { mode: "history", root: "/", ${has404Page ? `err: "/404",` : ""} routes: routes };\nconst router = new Router(config);\nnew Olum().$("#app").use(router);`;
672
779
  routes = generateRoutes(manifest);
673
- // console.log(libImports);
674
- // console.log(imports);
675
- // console.log(routes);
676
- // console.log(config);
780
+
677
781
  return `${libImports}\n${imports}\n${routes}\n${config}`;
678
- }
782
+ };
679
783
 
680
784
  module.exports.isNum = isNum;
681
785
  module.exports.id = id;
@@ -698,6 +802,7 @@ module.exports.createScopeHandler = createScopeHandler;
698
802
  module.exports.getGlobalMethods = getGlobalMethods;
699
803
  module.exports.getPropsAliases = getPropsAliases;
700
804
  module.exports.getGlobalProps = getGlobalProps;
805
+ module.exports.computeTemplateDeps = computeTemplateDeps;
701
806
  module.exports.minifyJS = minifyJS;
702
807
  module.exports.generateRouteManifest = generateRouteManifest;
703
808
  module.exports.generateImports = generateImports;