chocola 2.0.0-next.2 → 2.0.0-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,6 @@
1
1
  import path from "path";
2
- import chalk from "chalk";
3
2
  import { getChocolaConfig } from "../utils.js";
4
3
 
5
- /**
6
- * Loads and merges Chocola configuration with defaults
7
- * @param {import("fs").PathLike} rootDir
8
- * @returns {Promise<{
9
- * srcDir: string,
10
- * outDir: string,
11
- * libDir: string,
12
- * emptyOutDir: boolean
13
- * }>}
14
- */
15
4
  export async function loadConfig(rootDir) {
16
5
  const config = await getChocolaConfig(rootDir);
17
6
  const bundleConfig = config.bundle || {};
@@ -20,52 +9,10 @@ export async function loadConfig(rootDir) {
20
9
  const outDir = bundleConfig.outDir || "dist";
21
10
  const libDir = bundleConfig.libDir || "lib";
22
11
  const emptyOutDir = bundleConfig.emptyOutDir !== false;
23
- const assetImport = bundleConfig.assetImport || "legacy";
24
12
 
25
- logConfigWarnings(bundleConfig, emptyOutDir, assetImport);
26
-
27
- return { srcDir, outDir, libDir, emptyOutDir, assetImport };
28
- }
29
-
30
- function logConfigWarnings(bundleConfig, emptyOutDir, assetImport) {
31
- if (!bundleConfig.srcDir) {
32
- console.warn(
33
- chalk.bold.yellow("WARNING!"),
34
- 'srcDir not defined in chocola.config.json file: using default "src" directory.'
35
- );
36
- }
37
-
38
- if (!bundleConfig.outDir) {
39
- console.warn(
40
- chalk.bold.yellow("WARNING!"),
41
- 'outDir not defined in chocola.config.json file: using default "dist" directory.'
42
- );
43
- }
44
-
45
- if (!bundleConfig.libDir) {
46
- console.warn(
47
- chalk.bold.yellow("WARNING!"),
48
- 'libDir not defined in chocola.config.json file: using default "lib" directory.'
49
- );
50
- }
51
-
52
- console.log(`> using emptyOutDir = ${emptyOutDir}`);
53
-
54
- if (assetImport !== "static") {
55
- console.warn(
56
- chalk.bold.yellow("DEPRECATION WARNING!"),
57
- 'The legacy asset import system ("bundle.assetImport") will be removed in Chocola 2. ' +
58
- 'Set "bundle.assetImport": "static" in chocola.config.json and migrate your assets to src/static/.'
59
- );
60
- }
13
+ return { srcDir, outDir, libDir, emptyOutDir };
61
14
  }
62
15
 
63
- /**
64
- * Resolves all path directories based on configuration
65
- * @param {import("fs").PathLike} rootDir
66
- * @param {object} config
67
- * @returns {object}
68
- */
69
16
  export function resolvePaths(rootDir, config) {
70
17
  return {
71
18
  outDir: path.join(rootDir, config.outDir),
@@ -4,20 +4,10 @@ import path from "path";
4
4
  import { throwError, protectCurlyBraces, restoreCurlyBraces, compileExpression } from "./utils.js";
5
5
  import { readMyFile } from "./fs.js";
6
6
 
7
- /**
8
- * Creates a JSDOM instance from source index file
9
- * @param {string} srcIndexContent
10
- * @returns {JSDOM}
11
- */
12
7
  export function createDOM(srcIndexContent) {
13
8
  return new JSDOM(protectCurlyBraces(srcIndexContent));
14
9
  }
15
10
 
16
- /**
17
- * Validates that the index file has an <app> root element
18
- * @param {Document} doc
19
- * @throws {Error} if <app> element not found
20
- */
21
11
  export function validateAppContainer(doc) {
22
12
  const appContainer = doc.querySelector("app");
23
13
  if (!appContainer) {
@@ -26,20 +16,10 @@ export function validateAppContainer(doc) {
26
16
  return appContainer;
27
17
  }
28
18
 
29
- /**
30
- * Extracts all child elements from app container
31
- * @param {Element} appContainer
32
- * @returns {Element[]}
33
- */
34
19
  export function getAppElements(appContainer) {
35
20
  return Array.from(appContainer.querySelectorAll("*"));
36
21
  }
37
22
 
38
- /**
39
- * Extracts context attributes from element (ctx.* attributes)
40
- * @param {Element} element
41
- * @returns {object}
42
- */
43
23
  export function extractContextFromElement(element) {
44
24
  const ctx = {};
45
25
  for (const attr of element.attributes) {
@@ -58,31 +38,14 @@ export function extractContextFromElement(element) {
58
38
  return ctx;
59
39
  }
60
40
 
61
- /**
62
- * Serializes and formats DOM to pretty HTML
63
- * @param {JSDOM} dom
64
- * @returns {string}
65
- */
66
41
  export async function serializeDOM(dom) {
67
- const beautify = (await import("js-beautify")).default;
68
- const finalHtml = restoreCurlyBraces(dom.serialize());
69
- return beautify.html(finalHtml, { indent_size: 2 });
42
+ return restoreCurlyBraces(dom.serialize());
70
43
  }
71
44
 
72
- /**
73
- * Writes the final HTML to output directory
74
- * @param {string} html
75
- * @param {import("fs").PathLike} outDirPath
76
- */
77
45
  export async function writeHTMLOutput(html, outDirPath) {
78
46
  await fs.writeFile(path.join(outDirPath, "index.html"), html);
79
47
  }
80
48
 
81
- /**
82
- * Gets all stylesheet and icon links from document
83
- * @param {Document} doc
84
- * @returns {{stylesheets: HTMLLinkElement[], icons: HTMLLinkElement[]}}
85
- */
86
49
  export function getAssetLinks(doc) {
87
50
  const docLinks = Array.from(doc.querySelectorAll("link"));
88
51
  const stylesheets = docLinks.filter(link => link.rel === "stylesheet");
@@ -90,21 +53,10 @@ export function getAssetLinks(doc) {
90
53
  return { stylesheets, icons };
91
54
  }
92
55
 
93
- /**
94
- * Writes CSS to output directory
95
- * @param {string} css
96
- * @param {import("fs").PathLike} outDirPath
97
- * @param {string} filename
98
- */
99
56
  export async function writeCSSOutput(css, outDirPath, filename = "scopes.css") {
100
57
  await fs.writeFile(path.join(outDirPath, filename), css);
101
58
  }
102
59
 
103
- /**
104
- * Appends a stylesheet link element to document head
105
- * @param {Document} doc
106
- * @param {string} filename
107
- */
108
60
  export function appendStylesheetLink(doc, filename) {
109
61
  const linkEl = doc.createElement("link");
110
62
  linkEl.rel = "stylesheet";
@@ -112,11 +64,10 @@ export function appendStylesheetLink(doc, filename) {
112
64
  doc.head.appendChild(linkEl);
113
65
  }
114
66
 
115
- /**
116
- * Appends a script element to document body
117
- * @param {Document} doc
118
- * @param {string} filename
119
- */
67
+ export function getScriptElements(doc) {
68
+ return Array.from(doc.querySelectorAll("script[src]"));
69
+ }
70
+
120
71
  export function appendRuntimeScript(doc, filename) {
121
72
  const runtimeScriptEl = doc.createElement("script");
122
73
  runtimeScriptEl.type = "module";
package/compiler/fs.js CHANGED
@@ -1,12 +1,6 @@
1
1
  import { promises as fs } from "fs";
2
2
  import { throwError } from "./utils.js";
3
3
 
4
- /**
5
- * Reads a file and returns its contents as a UTF-8 string
6
- * @param {import("fs").PathLike} filePath - Path to the file
7
- * @returns {Promise<string>} - File contents
8
- * @throws {Error} - If file cannot be read
9
- */
10
4
  export async function readMyFile(filePath) {
11
5
  try {
12
6
  const data = await fs.readFile(filePath, "utf-8");
@@ -16,11 +10,6 @@ export async function readMyFile(filePath) {
16
10
  }
17
11
  }
18
12
 
19
- /**
20
- * Checks if a file exists
21
- * @param {import("fs").PathLike} filePath - Path to check
22
- * @returns {Promise<boolean>} - True if file exists, false otherwise
23
- */
24
13
  export async function checkFile(filePath) {
25
14
  try {
26
15
  await fs.access(filePath);
package/compiler/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { promises as fs } from "fs";
2
- import chalk from "chalk";
2
+ import chalk from "./chalk.js";
3
3
  import { loadConfig, resolvePaths } from "./config.js";
4
4
  import {
5
5
  createDOM,
6
6
  validateAppContainer,
7
7
  getAppElements,
8
8
  getAssetLinks,
9
+ getScriptElements,
9
10
  appendRuntimeScript,
10
11
  appendStylesheetLink,
11
12
  serializeDOM,
@@ -14,13 +15,13 @@ import {
14
15
  } from "./dom-processor.js";
15
16
  import { processAllComponents } from "./component-processor.js";
16
17
  import { generateRuntimeScript } from "./runtime-generator.js";
17
- import { genRandomId, throwError, compileExpression } from "./utils.js";
18
+ import { genRandomId, throwError, compileExpression, hasDelIfAttr, getDelIfAttr, removeDelIfAttr } from "./utils.js";
18
19
  import {
19
- copyResources,
20
20
  copyStaticDir,
21
21
  getComponents,
22
22
  getSrcIndex,
23
23
  processIcons,
24
+ processScript,
24
25
  processStylesheet,
25
26
  } from "./pipeline.js";
26
27
 
@@ -76,15 +77,15 @@ async function setupOutputDirectory(outDirPath, emptyOutDir) {
76
77
 
77
78
  async function loadAndDisplayComponents(srcComponentsPath) {
78
79
  const foundComponents = await getComponents(srcComponentsPath);
79
- const { loadedComponents, notDefComps, componentsLib } = foundComponents;
80
+ const { loadedComponents, notDefComps: emptyComps, componentsLib } = foundComponents;
80
81
 
81
82
  console.log(` LOADING COMPONENTS`);
82
83
  console.log(chalk.bold.green(">"), "Components found in", chalk.green.underline(srcComponentsPath) + ":");
83
84
  console.log(" ", componentsLib, "\n");
84
85
 
85
- if (notDefComps.length > 0) {
86
- console.warn(chalk.bold.yellow("WARNING!"), "The following components don't include a default export:");
87
- console.log(" ", notDefComps);
86
+ if (emptyComps?.length > 0) {
87
+ console.warn(chalk.bold.yellow("WARNING!"), "The following component files are empty:");
88
+ console.log(" ", emptyComps);
88
89
  }
89
90
 
90
91
  return loadedComponents;
@@ -92,6 +93,7 @@ async function loadAndDisplayComponents(srcComponentsPath) {
92
93
 
93
94
  async function processAssets(doc, rootDir, srcDir, outDirPath) {
94
95
  const { stylesheets, icons } = getAssetLinks(doc);
96
+ const scripts = getScriptElements(doc);
95
97
  const fileIds = [];
96
98
  let cssContents = [];
97
99
 
@@ -103,18 +105,82 @@ async function processAssets(doc, rootDir, srcDir, outDirPath) {
103
105
  for (const link of icons) {
104
106
  await processIcons(link, rootDir, srcDir, outDirPath);
105
107
  }
108
+
109
+ for (const script of scripts) {
110
+ await processScript(doc, script, rootDir, srcDir, outDirPath, fileIds);
111
+ }
106
112
  return cssContents
107
113
  }
108
114
 
109
- /**
110
- * Compiles a static build of your Chocola project from the directory provided.
111
- * @param {import("fs").PathLike} rootDir
112
- * @param {Object<{
113
- * isHotReload?: boolean
114
- * }
115
- * >} config
116
- */
117
- export default async function runtime(rootDir, buildConfig) {
115
+ function processPageConditionals(parent) {
116
+ const children = [...parent.children];
117
+ let chainActive = false;
118
+ let chainRendered = false;
119
+
120
+ for (const child of children) {
121
+ const hasIf = child.hasAttribute("if");
122
+ const hasDelIf = hasDelIfAttr(child);
123
+ const hasElif = child.hasAttribute("elif");
124
+ const hasElse = child.hasAttribute("else");
125
+
126
+ if (hasElif || hasElse) {
127
+ if (!chainActive) continue;
128
+ if (chainRendered) { child.remove(); continue; }
129
+ }
130
+
131
+ if (hasIf) {
132
+ const raw = child.getAttribute("if");
133
+ const expr = raw.startsWith("{") ? raw.slice(1, -1) : raw;
134
+ const fn = compileExpression(expr, false);
135
+ const result = fn();
136
+ chainActive = true;
137
+ if (result) {
138
+ chainRendered = true;
139
+ } else {
140
+ child.remove();
141
+ chainRendered = false;
142
+ }
143
+ child.removeAttribute("if");
144
+ } else if (hasDelIf) {
145
+ const raw = getDelIfAttr(child);
146
+ const expr = raw.startsWith("{") ? raw.slice(1, -1) : raw;
147
+ const fn = compileExpression(expr, false);
148
+ const result = fn();
149
+ chainActive = true;
150
+ if (result) {
151
+ chainRendered = true;
152
+ } else {
153
+ child.remove();
154
+ chainRendered = false;
155
+ }
156
+ removeDelIfAttr(child);
157
+ } else if (hasElif) {
158
+ const raw = child.getAttribute("elif");
159
+ const expr = raw.startsWith("{") ? raw.slice(1, -1) : raw;
160
+ const fn = compileExpression(expr, false);
161
+ const result = fn();
162
+ if (result) {
163
+ chainRendered = true;
164
+ } else {
165
+ child.remove();
166
+ }
167
+ child.removeAttribute("elif");
168
+ } else if (hasElse) {
169
+ chainRendered = true;
170
+ chainActive = false;
171
+ child.removeAttribute("else");
172
+ } else {
173
+ chainActive = false;
174
+ chainRendered = false;
175
+ }
176
+
177
+ if (child.parentNode) {
178
+ processPageConditionals(child);
179
+ }
180
+ }
181
+ }
182
+
183
+ export default async function compile(rootDir, buildConfig) {
118
184
  const isHotReload = buildConfig?.isHotReload || null;
119
185
  !isHotReload && logBanner();
120
186
 
@@ -138,96 +204,12 @@ export default async function runtime(rootDir, buildConfig) {
138
204
  const doc = dom.window.document;
139
205
  const appContainer = validateAppContainer(doc);
140
206
 
141
- const warnedDeprecated = new Set();
142
- function hasDelIfAttr(el, sourceLoc) {
143
- if (el.hasAttribute("del-if") && !el.hasAttribute("del:if") && !warnedDeprecated.has(sourceLoc)) {
144
- warnedDeprecated.add(sourceLoc);
145
- const name = sourceLoc ? sourceLoc.split(/[\\/]/).pop() : "unknown";
146
- console.warn(chalk.yellow(`[deprecation] "del-if" is deprecated in ${chalk.cyan(name)} and will be removed in Chocola 2. Use "del:if" instead.`));
147
- }
148
- return el.hasAttribute("del-if") || el.hasAttribute("del:if");
149
- }
150
- function getDelIfAttr(el) {
151
- return el.getAttribute("del:if") ?? el.getAttribute("del-if");
152
- }
153
- function removeDelIfAttr(el) {
154
- el.removeAttribute("del-if");
155
- el.removeAttribute("del:if");
156
- }
157
-
158
- function processPageConditionals(parent) {
159
- const children = [...parent.children];
160
- let chainActive = false;
161
- let chainRendered = false;
162
-
163
- for (const child of children) {
164
- const hasIf = child.hasAttribute("if");
165
- const hasDelIf = hasDelIfAttr(child, pageSourcePath);
166
- const hasElif = child.hasAttribute("elif");
167
- const hasElse = child.hasAttribute("else");
168
-
169
- if (hasElif || hasElse) {
170
- if (!chainActive) continue;
171
- if (chainRendered) { child.remove(); continue; }
172
- }
173
-
174
- if (hasIf) {
175
- const raw = child.getAttribute("if");
176
- const expr = raw.startsWith("{") ? raw.slice(1, -1) : raw;
177
- const fn = compileExpression(expr, false);
178
- const result = fn();
179
- chainActive = true;
180
- if (result) {
181
- chainRendered = true;
182
- } else {
183
- child.remove();
184
- chainRendered = false;
185
- }
186
- child.removeAttribute("if");
187
- } else if (hasDelIf) {
188
- const raw = getDelIfAttr(child);
189
- const expr = raw.startsWith("{") ? raw.slice(1, -1) : raw;
190
- const fn = compileExpression(expr, false);
191
- const result = fn();
192
- chainActive = true;
193
- if (result) {
194
- chainRendered = true;
195
- } else {
196
- child.remove();
197
- chainRendered = false;
198
- }
199
- removeDelIfAttr(child);
200
- } else if (hasElif) {
201
- const raw = child.getAttribute("elif");
202
- const expr = raw.startsWith("{") ? raw.slice(1, -1) : raw;
203
- const fn = compileExpression(expr, false);
204
- const result = fn();
205
- if (result) {
206
- chainRendered = true;
207
- } else {
208
- child.remove();
209
- }
210
- child.removeAttribute("elif");
211
- } else if (hasElse) {
212
- chainRendered = true;
213
- chainActive = false;
214
- child.removeAttribute("else");
215
- } else {
216
- chainActive = false;
217
- chainRendered = false;
218
- }
219
-
220
- if (child.parentNode) {
221
- processPageConditionals(child);
222
- }
223
- }
224
- }
225
207
  processPageConditionals(appContainer);
226
208
 
227
209
  const appElements = getAppElements(appContainer);
228
210
  const { runtimeScript, scopesCss } = processAllComponents(appElements, loadedComponents, pageSourcePath, srcIndexContent);
229
211
  const runtimeFilename = await generateRuntimeScript(runtimeScript, paths.outDir);
230
- const globalCss = (await processAssets(doc, rootDir, config.srcDir, paths.outDir)).join("\n");
212
+ await processAssets(doc, rootDir, config.srcDir, paths.outDir);
231
213
 
232
214
  if (scopesCss) {
233
215
  const fileName = "sc-" + genRandomId(null, 6) + ".css";
@@ -240,11 +222,7 @@ export default async function runtime(rootDir, buildConfig) {
240
222
  await writeHTMLOutput(html, paths.outDir);
241
223
 
242
224
  try {
243
- if (config.assetImport === "static") {
244
- await copyStaticDir(paths.src, paths.outDir);
245
- } else {
246
- await copyResources(rootDir, scopesCss, globalCss, config.srcDir, paths.outDir);
247
- }
225
+ await copyStaticDir(paths.src, paths.outDir);
248
226
  } catch (err) {
249
227
  throwError(err.message || err);
250
228
  }
@@ -273,5 +251,5 @@ export const app = {
273
251
  * @example
274
252
  * @param {PathLike} __rootdir the directory where your Chocola App is
275
253
  */
276
- async build(__rootdir) { return runtime(__rootdir) }
254
+ async build(__rootdir) { return compile(__rootdir) }
277
255
  };