olum-compiler 1.9.7 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/build.js CHANGED
@@ -1,13 +1,18 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
1
3
  const bundle = require("./bundle");
2
4
  const compile = require("./compiler");
3
5
  const copySrc = require("./copySrc");
6
+ const ssg = require("./ssg");
4
7
 
5
8
  (async function () {
6
9
  const bootAt = Date.now();
10
+ const sitemap = path.resolve(__dirname, "../src/sitemap.js");
7
11
  try {
8
12
  await copySrc();
9
13
  await compile();
10
14
  await bundle(bootAt);
15
+ if (fs.existsSync(sitemap)) await ssg();
11
16
  } catch (error) {
12
17
  console.error(error);
13
18
  process.exitCode = 1;
package/bin/bundle.js CHANGED
@@ -134,3 +134,4 @@ async function bundle(bootAt) {
134
134
  }
135
135
 
136
136
  module.exports = bundle;
137
+ module.exports.ensureVite = ensureVite;
package/bin/server.js CHANGED
@@ -5,6 +5,7 @@ const http = require("http");
5
5
  const { parseDOM } = require("../lib/dom");
6
6
  const colors = require("../lib/colors");
7
7
  const mimes = require("./mimes.json");
8
+ const sitemapPath = path.resolve(__dirname, "../src/sitemap.js");
8
9
  let wsPort = 8090;
9
10
 
10
11
  function handleWsFile() {
@@ -44,12 +45,22 @@ function serve(entry, port, mode = "development") {
44
45
  return new Promise((resolve, reject) => {
45
46
  const PORT = Number(port || process.env.PORT || 3000);
46
47
 
48
+ const ssgHosting = fs.existsSync(sitemapPath);
49
+ const entryDir = path.resolve(entry);
50
+
51
+ function ssgIndex(urlPath) {
52
+ if (!ssgHosting || urlPath === "/") return null;
53
+ const nested = path.resolve(entryDir, "." + urlPath, "index.html");
54
+ if (!nested.startsWith(entryDir + path.sep)) return null;
55
+ return fs.existsSync(nested) ? nested : null;
56
+ }
57
+
47
58
  const server = http.createServer(handler);
48
59
  function handler(req, res) {
49
60
  const urlPath = req.url.split("?")[0];
50
61
 
51
62
  function serveIndex() {
52
- let indexPath = entry + "/index.html";
63
+ let indexPath = ssgIndex(urlPath) || entry + "/index.html";
53
64
  if (!fs.existsSync(indexPath)) indexPath = entry + "/index.htm";
54
65
 
55
66
  fs.readFile(indexPath, (err, content) => {
package/bin/ssg.js ADDED
@@ -0,0 +1,380 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const colors = require("../lib/colors");
4
+ const spawn = require("../lib/cross-spawn");
5
+ const { ensureVite } = require("./bundle");
6
+ const serve = require("./server");
7
+
8
+ const cwd = process.cwd();
9
+ const root = cwd.replace(/\/module$/, "");
10
+ const sitemapPath = path.resolve(__dirname, "../src/sitemap.js");
11
+ const routesPath = path.resolve(__dirname, "../routes.json");
12
+ const distDir = path.resolve(root, "dist");
13
+ const shellPath = path.join(distDir, "index.html");
14
+ const tmpDir = path.resolve(__dirname, "../.olum-ssg");
15
+ const tmpEntry = path.join(tmpDir, "sitemap.mjs");
16
+
17
+ const info = (msg) => console.log(colors("white", msg));
18
+ const fail = (msg) => console.error(colors("red", "SSG: " + msg));
19
+ const reason = (err) => (err && err.message) || String(err);
20
+
21
+ function ensurePuppeteer() {
22
+ if (fs.existsSync(path.join(root, "node_modules/puppeteer/package.json")))
23
+ return;
24
+ info(
25
+ "puppeteer not found — installing it into the project root (one-time, downloads Chrome)...",
26
+ );
27
+
28
+ const result = spawn.sync(
29
+ "npm",
30
+ ["install", "--save-dev", "--include=dev", "puppeteer"],
31
+ { cwd: root, stdio: "inherit" },
32
+ );
33
+ if (result.status !== 0)
34
+ throw new Error(
35
+ "Failed to install puppeteer — run `npm i -D puppeteer` in " +
36
+ root +
37
+ " then re-run the build.",
38
+ );
39
+ }
40
+
41
+ function routerRoutes() {
42
+ if (!fs.existsSync(routesPath)) return [];
43
+ try {
44
+ const parsed = JSON.parse(fs.readFileSync(routesPath, "utf8"));
45
+ return Array.isArray(parsed) ? parsed : [];
46
+ } catch (err) {
47
+ fail("routes.json is unreadable — " + reason(err));
48
+ return [];
49
+ }
50
+ }
51
+
52
+ async function sitemapRoutes() {
53
+ let paths;
54
+ try {
55
+ ensureVite();
56
+ const { build } = await import("vite");
57
+ await build({
58
+ root,
59
+ configFile: false,
60
+ logLevel: "silent",
61
+ build: {
62
+ ssr: true,
63
+ outDir: tmpDir,
64
+ emptyOutDir: true,
65
+ minify: false,
66
+ rollupOptions: {
67
+ input: sitemapPath,
68
+ output: { format: "esm", entryFileNames: path.basename(tmpEntry) },
69
+ },
70
+ },
71
+ });
72
+
73
+ const { default: fn } = await import(`file://${tmpEntry}?t=${Date.now()}`);
74
+ if (typeof fn !== "function") {
75
+ fail("src/sitemap.js must default-export a function.");
76
+ return [];
77
+ }
78
+ paths = await fn();
79
+ } catch (err) {
80
+ fail("sitemap.js failed — " + reason(err));
81
+ return [];
82
+ } finally {
83
+ fs.rmSync(tmpDir, { recursive: true, force: true });
84
+ }
85
+
86
+ if (!Array.isArray(paths)) {
87
+ fail("sitemap.js must return an array of routes.");
88
+ return [];
89
+ }
90
+ return paths.filter((item) => typeof item === "string" && item.trim() !== "");
91
+ }
92
+
93
+ function routeMatches(pattern, pathname) {
94
+ const patternSegs = pattern.split("/").filter(Boolean);
95
+ const pathSegs = pathname.split("/").filter(Boolean);
96
+ if (patternSegs.length !== pathSegs.length) return false;
97
+ return patternSegs.every(
98
+ (seg, i) => seg.charAt(0) === ":" || seg === pathSegs[i],
99
+ );
100
+ }
101
+
102
+ function writeShells(finalRoutes, patterns) {
103
+ if (!fs.existsSync(shellPath)) {
104
+ fail("dist/index.html is missing — the bundle step must run first.");
105
+ return 0;
106
+ }
107
+
108
+ const shell = fs.readFileSync(shellPath);
109
+ const dirs = new Set();
110
+ for (const route of finalRoutes) {
111
+ let current = "";
112
+ for (const segment of route.split("/")) {
113
+ if (!segment || segment === "." || segment === "..") continue;
114
+ current += "/" + segment;
115
+
116
+ if (patterns.some((pattern) => routeMatches(pattern, current)))
117
+ dirs.add(current);
118
+ }
119
+ }
120
+
121
+ for (const dir of dirs) {
122
+ const target = path.join(distDir, dir);
123
+ fs.mkdirSync(target, { recursive: true });
124
+ fs.writeFileSync(path.join(target, "index.html"), shell);
125
+ }
126
+ return dirs.size;
127
+ }
128
+
129
+ async function serveDist() {
130
+ const { server } = await serve(distDir, undefined, "production");
131
+ await new Promise((resolve, reject) => {
132
+ server.on("error", reject);
133
+
134
+ server.listen(0, resolve);
135
+ });
136
+ return { server, origin: "http://localhost:" + server.address().port };
137
+ }
138
+
139
+ function writeRendered(route, html) {
140
+ const target = path.join(distDir, route, "index.html");
141
+ if (!target.startsWith(distDir + path.sep)) return false;
142
+ if (!fs.existsSync(target)) return false;
143
+ fs.writeFileSync(target, html);
144
+ return true;
145
+ }
146
+
147
+ function siteUrl() {
148
+ const clean = (str) => str.trim().replace(/\/+$/, "");
149
+ try {
150
+ const pkg = JSON.parse(
151
+ fs.readFileSync(path.join(root, "package.json"), "utf8"),
152
+ );
153
+ const url = pkg.olum && pkg.olum.SITE_URL;
154
+ if (typeof url === "string" && url.trim()) return clean(url);
155
+ } catch (err) {}
156
+ return "";
157
+ }
158
+
159
+ function readDelay(raw, source) {
160
+ if (raw === undefined || raw === null || raw === "") return 0;
161
+
162
+ const ms =
163
+ typeof raw === "number" || typeof raw === "string" ? Number(raw) : NaN;
164
+ if (!Number.isFinite(ms) || ms < 0) {
165
+ const shown = typeof raw === "string" ? JSON.stringify(raw) : String(raw);
166
+ fail(
167
+ `ignoring ${source} — expected a number of milliseconds, got ${shown}`,
168
+ );
169
+ return 0;
170
+ }
171
+ return Math.round(ms);
172
+ }
173
+
174
+ function ssgDelay() {
175
+ try {
176
+ const pkg = JSON.parse(
177
+ fs.readFileSync(path.join(root, "package.json"), "utf8"),
178
+ );
179
+ return readDelay(
180
+ pkg.olum && pkg.olum.SSG_DELAY,
181
+ 'package.json "olum.SSG_DELAY"',
182
+ );
183
+ } catch (err) {
184
+ return 0;
185
+ }
186
+ }
187
+
188
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
189
+
190
+ const xmlEscape = (str) =>
191
+ str
192
+ .replace(/&/g, "&amp;")
193
+ .replace(/</g, "&lt;")
194
+ .replace(/>/g, "&gt;")
195
+ .replace(/"/g, "&quot;")
196
+ .replace(/'/g, "&apos;");
197
+
198
+ function writeSitemapXml(finalRoutes) {
199
+ const base = siteUrl();
200
+ if (!base)
201
+ fail(
202
+ 'no package.json "olum.SITE_URL" — sitemap.xml falls back to relative paths, which crawlers ignore',
203
+ );
204
+
205
+ const urls = finalRoutes.filter((route) =>
206
+ fs.existsSync(path.join(distDir, route, "index.html")),
207
+ );
208
+ const lastmod = new Date().toISOString().slice(0, 10);
209
+ const body = urls
210
+ .map(
211
+ (route) =>
212
+ ` <url>\n <loc>${xmlEscape(base + route)}</loc>\n <lastmod>${lastmod}</lastmod>\n </url>`,
213
+ )
214
+ .join("\n");
215
+
216
+ fs.writeFileSync(
217
+ path.join(distDir, "sitemap.xml"),
218
+ `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${body}\n</urlset>\n`,
219
+ );
220
+ return urls.length;
221
+ }
222
+
223
+ async function prerender(finalRoutes) {
224
+ if (!finalRoutes.length) return 0;
225
+ const delay = ssgDelay();
226
+ if (delay) {
227
+ const total = (delay * finalRoutes.length) / 1000;
228
+ info(
229
+ `SSG: waiting ${delay}ms after each route (+${total < 60 ? total.toFixed(1) + "s" : (total / 60).toFixed(1) + "min"} to this build)`,
230
+ );
231
+ }
232
+ ensurePuppeteer();
233
+ const mod = await import("puppeteer");
234
+ const puppeteer = mod.default || mod;
235
+
236
+ const { server, origin } = await serveDist();
237
+
238
+ const browser = await puppeteer.launch({
239
+ args: ["--no-sandbox", "--disable-setuid-sandbox"],
240
+ });
241
+
242
+ const isShell = (route) =>
243
+ path.join(distDir, route, "index.html") === shellPath ? 1 : 0;
244
+ const ordered = [...finalRoutes].sort((a, b) => isShell(a) - isShell(b));
245
+
246
+ let written = 0;
247
+
248
+ const width = String(ordered.length).length;
249
+ const counter = (index) =>
250
+ colors("white", String(index + 1).padStart(width) + "/" + ordered.length);
251
+
252
+ try {
253
+ const page = await browser.newPage();
254
+ for (const [index, route] of ordered.entries()) {
255
+ try {
256
+ await page.goto(origin + route, { waitUntil: "networkidle0" });
257
+
258
+ await page.waitForFunction(
259
+ () => document.querySelector("#olum-app")?.childElementCount > 0,
260
+ { timeout: 15000 },
261
+ );
262
+
263
+ if (delay) await sleep(delay);
264
+ const html =
265
+ "<!doctype html>\n" +
266
+ (await page.evaluate(() => document.documentElement.outerHTML));
267
+ if (writeRendered(route, html)) written++;
268
+ console.log(
269
+ colors("green", " ✓ ") +
270
+ counter(index) +
271
+ " " +
272
+ colors("cyan", route),
273
+ );
274
+ } catch (err) {
275
+ console.error(
276
+ colors("red", " ✗ ") +
277
+ counter(index) +
278
+ " " +
279
+ colors("cyan", route) +
280
+ colors("red", " failed to render — " + reason(err)),
281
+ );
282
+ }
283
+ }
284
+ } finally {
285
+ await browser.close();
286
+ server.close();
287
+ }
288
+
289
+ return written;
290
+ }
291
+
292
+ const formatSize = (bytes) =>
293
+ bytes < 1024
294
+ ? bytes + " B"
295
+ : (bytes / 1024 < 10
296
+ ? (bytes / 1024).toFixed(1)
297
+ : Math.round(bytes / 1024)) + " kB";
298
+
299
+ function printRoutesTree(finalRoutes) {
300
+ const root = { name: "/", children: new Map() };
301
+ let built = 0;
302
+ for (const route of finalRoutes) {
303
+ const file = path.join(distDir, route, "index.html");
304
+ if (!fs.existsSync(file)) continue;
305
+ built++;
306
+ let node = root;
307
+ for (const segment of route.split("/").filter(Boolean)) {
308
+ if (!node.children.has(segment))
309
+ node.children.set(segment, { name: segment, children: new Map() });
310
+ node = node.children.get(segment);
311
+ }
312
+ node.size = formatSize(fs.statSync(file).size);
313
+ }
314
+ if (!built) return;
315
+
316
+ const rows = [{ label: root.name, size: root.size }];
317
+ const walk = (node, prefix) => {
318
+ const kids = [...node.children.values()].sort((a, b) =>
319
+ a.name.localeCompare(b.name),
320
+ );
321
+ kids.forEach((kid, index) => {
322
+ const last = index === kids.length - 1;
323
+ rows.push({
324
+ prefix: prefix + (last ? "└── " : "├── "),
325
+ label: kid.name,
326
+ size: kid.size,
327
+ });
328
+ walk(kid, prefix + (last ? " " : "│ "));
329
+ });
330
+ };
331
+ walk(root, "");
332
+
333
+ const width = Math.max(
334
+ ...rows.map((row) => (row.prefix || "").length + row.label.length),
335
+ );
336
+ const sizeWidth = Math.max(...rows.map((row) => (row.size || "").length));
337
+ console.log("");
338
+ for (const row of rows) {
339
+ const branch =
340
+ colors("white", row.prefix || "") + colors("cyan", row.label);
341
+ if (!row.size) {
342
+ console.log(branch);
343
+ continue;
344
+ }
345
+ const gap = " ".repeat(
346
+ width - (row.prefix || "").length - row.label.length + 3,
347
+ );
348
+ console.log(branch + gap + colors("white", row.size.padStart(sizeWidth)));
349
+ }
350
+ console.log("");
351
+ }
352
+
353
+ async function ssg() {
354
+ console.log("");
355
+ const patterns = routerRoutes();
356
+ const routes = [...patterns];
357
+ if (fs.existsSync(sitemapPath)) routes.push(...(await sitemapRoutes()));
358
+
359
+ const finalRoutes = [...new Set(routes)].filter(
360
+ (route) => !route.includes("/:"),
361
+ );
362
+ info(`SSG: ${finalRoutes.length} route(s) to prerender`);
363
+
364
+ const count = writeShells(finalRoutes, patterns);
365
+ info(`SSG: created ${count + 1} index.html file(s) into dist`);
366
+
367
+ const prerendered = await prerender(finalRoutes);
368
+ info(`SSG: prerendered ${prerendered} page(s)`);
369
+
370
+ const listed = writeSitemapXml(finalRoutes);
371
+ info(`SSG: sitemap.xml lists ${listed} URL(s)`);
372
+
373
+ printRoutesTree(finalRoutes);
374
+ }
375
+
376
+ module.exports = ssg;
377
+ module.exports.ensurePuppeteer = ensurePuppeteer;
378
+ module.exports.siteUrl = siteUrl;
379
+ module.exports.ssgDelay = ssgDelay;
380
+ module.exports.readDelay = readDelay;
package/lib/changes.txt CHANGED
@@ -1,8 +0,0 @@
1
- change /tmp/olum-dev-test-E0g6QU/src/page.html
2
- change /tmp/olum-dev-test-E0g6QU/public/main.css
3
- addDir /tmp/olum-dev-test-E0g6QU/src/blog
4
- add /tmp/olum-dev-test-E0g6QU/src/blog/page.html
5
- unlink /tmp/olum-dev-test-E0g6QU/src/blog/page.html
6
- unlinkDir /tmp/olum-dev-test-E0g6QU/src/blog
7
- change /tmp/olum-dev-test-E0g6QU/src/util.js
8
- change /tmp/olum-dev-test-E0g6QU/src/page.html
@@ -0,0 +1,67 @@
1
+ const path = require("path");
2
+ const colors = require("./colors");
3
+
4
+ const LD_JSON =
5
+ /(<script\b[^>]*\btype\s*=\s*["']application\/ld\+json["'][^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
6
+ const JSON_STRING = /"(?:[^"\\]|\\.)*"/g;
7
+ const EXPR = /\{([^{}]+)\}/g;
8
+
9
+ const MARK = "OLUM_HEAD_EXPR";
10
+
11
+ const escapeLiteral = (str) =>
12
+ str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
13
+
14
+ const PAGE_FILES = ["page.html", "not-found.html"];
15
+
16
+ function headParser(content, filePath) {
17
+ content = (content || "").trim();
18
+ if (!content) return "";
19
+
20
+ if (
21
+ filePath &&
22
+ PAGE_FILES.indexOf(path.basename(filePath).toLowerCase()) === -1
23
+ ) {
24
+ console.warn(
25
+ colors("yellow.bold", "\n<<Olum Warning>>\n") +
26
+ colors(
27
+ "yellow",
28
+ " File: " +
29
+ filePath +
30
+ "\n <head> was ignored: only a page component (page.html / not-found.html) owns the document head.\n Move these tags into the page.html that renders this component.\n",
31
+ ),
32
+ );
33
+ return "";
34
+ }
35
+
36
+ const exprs = [];
37
+ const lift = (expr, raw) =>
38
+ MARK + (exprs.push({ expr: expr.trim(), raw }) - 1) + MARK;
39
+
40
+ let out = "";
41
+ let cursor = 0;
42
+ content.replace(LD_JSON, (block, open, body, close, at) => {
43
+ out += content
44
+ .slice(cursor, at)
45
+ .replace(EXPR, (_m, expr) => lift(expr, false));
46
+ out +=
47
+ open +
48
+ body.replace(JSON_STRING, (str) =>
49
+ str.replace(EXPR, (_m, expr) => lift(expr, true)),
50
+ ) +
51
+ close;
52
+ cursor = at + block.length;
53
+ return block;
54
+ });
55
+ out += content.slice(cursor).replace(EXPR, (_m, expr) => lift(expr, false));
56
+
57
+ out = escapeLiteral(out);
58
+
59
+ out = out.replace(new RegExp(MARK + "(\\d+)" + MARK, "g"), (_m, index) => {
60
+ const { expr, raw } = exprs[index];
61
+ return raw ? "${" + expr + "}" : "${olum.esc(" + expr + ")}";
62
+ });
63
+
64
+ return "__head__() { return `" + out + "`;},\n";
65
+ }
66
+
67
+ module.exports = headParser;
package/lib/helpers.js CHANGED
@@ -20,6 +20,9 @@ const base64ToString = (base64) =>
20
20
  Buffer.from(base64, "base64").toString("ascii");
21
21
  const acorn = require("acorn");
22
22
 
23
+ // keep in sync with bin/ssg.js, which reads this same file
24
+ const routesPath = path.resolve(__dirname, "../routes.json");
25
+
23
26
  const cleanParentheses = (filePath, type = "name") => {
24
27
  if (type == "name") {
25
28
  return filePath.replace(/\([^)]*\)/g, "");
@@ -723,6 +726,7 @@ function generateImports(manifest) {
723
726
 
724
727
  function generateRoutes(manifest) {
725
728
  const routes = [];
729
+ const paths = [];
726
730
 
727
731
  if (manifest["/"]) {
728
732
  routes.push({
@@ -747,14 +751,17 @@ function generateRoutes(manifest) {
747
751
  });
748
752
  }
749
753
 
750
- return `export const routes = [
754
+ const result = `export const routes = [
751
755
  ${routes
752
- .map(
753
- ({ path, comp }) =>
754
- ` { path: "${cleanNumbersPrefix(path, "url")}", comp: ${cleanNumbersPrefix(comp)} }`,
755
- )
756
+ .map(({ path, comp }) => {
757
+ paths.push(`${cleanNumbersPrefix(path, "url")}`);
758
+ return ` { path: "${cleanNumbersPrefix(path, "url")}", comp: ${cleanNumbersPrefix(comp)} }`;
759
+ })
756
760
  .join(",\n")}
757
761
  ];`;
762
+
763
+ fs.writeFileSync(routesPath, `${JSON.stringify(paths, null, 2)}`);
764
+ return result;
758
765
  }
759
766
 
760
767
  const compileRoutes = (entryPoint) => {
package/lib/parser.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const splitSFC = require("./sfc");
2
2
  const htmlParser = require("./htmlParser");
3
3
  const cssParser = require("./cssParser");
4
+ const headParser = require("./headParser");
4
5
  const jsParser = require("./jsParser");
5
6
  const getImports = require("./getImports");
6
7
  const toJs = require("./toJs");
@@ -76,6 +77,8 @@ const parser = (str, counter, filePath) => {
76
77
  const currentID = id().slice(1);
77
78
  const css = cssParser(sfc.css, currentID, compName);
78
79
 
80
+ const head = headParser(sfc.head, filePath);
81
+
79
82
  let globalProps = [];
80
83
  let globalMethods = [];
81
84
  let stateProps = [];
@@ -158,7 +161,7 @@ const parser = (str, counter, filePath) => {
158
161
  html = html.replace(/props\(\s*\)/g, "props(_storeKey)");
159
162
 
160
163
  const templateDeps = computeTemplateDeps(
161
- html,
164
+ html + head,
162
165
  globalMethods,
163
166
  globalProps,
164
167
  hasState,
@@ -170,7 +173,7 @@ const parser = (str, counter, filePath) => {
170
173
  var host = el_${currentID};
171
174
  var methods_${currentID} = {${globalMethods}};
172
175
  var olum_${currentID} = {
173
- ${css}
176
+ ${css}${head}
174
177
  methods: ${scopedMethods},
175
178
  props: ${scopedProps},
176
179
  compName: "${compName}",
package/lib/sfc.js CHANGED
@@ -76,6 +76,61 @@ function neutralizeStrayRawText(source) {
76
76
  return out + source.slice(cursor);
77
77
  }
78
78
 
79
+ function extractHead(source, filePath) {
80
+ const rawRanges = scanRawTextBlocks(source, ["script", "style"]).map(
81
+ (block) => [block.start, block.end],
82
+ );
83
+ const inRawText = (at) =>
84
+ rawRanges.some(([start, end]) => at >= start && at < end);
85
+ const lineAt = (at) => source.slice(0, at).split("\n").length;
86
+
87
+ const open = /<head(?=[\s/>])/gi;
88
+ const blocks = [];
89
+ let match;
90
+ while ((match = open.exec(source)) !== null) {
91
+ if (inRawText(match.index)) continue;
92
+ const tagEnd = findTagEnd(source, match.index);
93
+ if (tagEnd === -1) break;
94
+ const close = source.slice(tagEnd + 1).match(/<\/head\s*>/i);
95
+ if (!close) {
96
+ warn(
97
+ filePath,
98
+ lineAt(match.index),
99
+ "<head> is never closed, so it was ignored. Add a </head>.",
100
+ );
101
+ break;
102
+ }
103
+ const innerEnd = tagEnd + 1 + close.index;
104
+ blocks.push({
105
+ inner: source.slice(tagEnd + 1, innerEnd),
106
+ start: match.index,
107
+ end: innerEnd + close[0].length,
108
+ });
109
+ open.lastIndex = innerEnd + close[0].length;
110
+ }
111
+ if (!blocks.length) return { head: "", source };
112
+
113
+ if (blocks.length > 1) {
114
+ warn(
115
+ filePath,
116
+ lineAt(blocks[1].start),
117
+ "A component compiles only its FIRST <head> — this one was dropped. Merge the tags into the first block.",
118
+ );
119
+ }
120
+
121
+ let out = "";
122
+ let cursor = 0;
123
+ blocks.forEach((block) => {
124
+ out +=
125
+ source.slice(cursor, block.start) +
126
+ source.slice(block.start, block.end).replace(/[^\n]/g, "");
127
+ cursor = block.end;
128
+ });
129
+ out += source.slice(cursor);
130
+
131
+ return { head: blocks[0].inner, source: out };
132
+ }
133
+
79
134
  function warn(filePath, line, msg) {
80
135
  console.warn(
81
136
  colors("yellow.bold", "\n<<Olum Warning>>\n") +
@@ -94,6 +149,8 @@ function warn(filePath, line, msg) {
94
149
 
95
150
  function splitSFC(source, filePath) {
96
151
  source = neutralizeStrayRawText(expandSelfClosingRawText(String(source)));
152
+ const headBlock = extractHead(source, filePath);
153
+ source = headBlock.source;
97
154
  const doc = parse5.parse(source, {
98
155
  sourceCodeLocationInfo: true,
99
156
  scriptingEnabled: false,
@@ -123,7 +180,14 @@ function splitSFC(source, filePath) {
123
180
  return source.slice(start, end);
124
181
  };
125
182
 
126
- const script = scripts[0] || null;
183
+ const isDataScript = (node) =>
184
+ node.attrs.some(
185
+ (a) =>
186
+ a.name.toLowerCase() === "type" &&
187
+ a.value.trim().toLowerCase() === "application/ld+json",
188
+ );
189
+
190
+ const script = scripts.find((node) => !isDataScript(node)) || null;
127
191
  const style = styles[0] || null;
128
192
 
129
193
  const jsAttrs = {};
@@ -187,6 +251,7 @@ function splitSFC(source, filePath) {
187
251
 
188
252
  scriptStartLine,
189
253
  css,
254
+ head: headBlock.head,
190
255
  template: template.trim(),
191
256
  };
192
257
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "1.9.7",
3
+ "version": "2.0.1",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -891,7 +891,7 @@ checkFn(
891
891
  /err: "\/404",/.test(out) &&
892
892
  !/Widget|_drafts|Drafts/.test(out) &&
893
893
  /new Router\(config\)/.test(out) &&
894
- /new Olum\(\)\.\$\("olum-app"\)\.use\(router\)/.test(out)
894
+ /new Olum\(\)\.\$\("#olum-app"\)\.use\(router\)/.test(out)
895
895
  );
896
896
  },
897
897
  );
@@ -1367,6 +1367,167 @@ check(
1367
1367
 
1368
1368
  console.warn = realWarn;
1369
1369
 
1370
+ section("§27 <head> page metadata");
1371
+
1372
+ function compilePage(template, file) {
1373
+ return parser(template, _idSeq++, file || "/app/src/match/[slug]/page.html");
1374
+ }
1375
+ function headOf(out) {
1376
+ const m = out.match(/__head__\(\) \{ return `([\s\S]*?)`;\},/);
1377
+ return m ? m[1] : "";
1378
+ }
1379
+ function checkHead(name, template, assertion, file) {
1380
+ let out;
1381
+ try {
1382
+ out = compilePage(template, file);
1383
+ } catch (e) {
1384
+ recordFail(name);
1385
+ console.log(
1386
+ " " + FAIL_ICON + " " + name + dim(" (threw: " + e.message + ")"),
1387
+ );
1388
+ console.log(" " + dim("↳ in " + currentSection));
1389
+ return;
1390
+ }
1391
+ let ok = false;
1392
+ try {
1393
+ ok = assertion(out);
1394
+ } catch (e) {}
1395
+ if (ok) {
1396
+ passed++;
1397
+ console.log(" " + PASS_ICON + " " + name);
1398
+ } else {
1399
+ recordFail(name);
1400
+ console.log(
1401
+ " " +
1402
+ FAIL_ICON +
1403
+ " " +
1404
+ red(name) +
1405
+ "\n " +
1406
+ dim("head: " + headOf(out).replace(/\s+/g, " ").slice(0, 140)),
1407
+ );
1408
+ console.log(" " + dim("↳ in " + currentSection));
1409
+ }
1410
+ }
1411
+
1412
+ const PAGE_HEAD = `<head>\n <title>Hi</title>\n <meta name="description" content="d" />\n</head>`;
1413
+
1414
+ checkHead(
1415
+ "moves the head out of the markup and into __head__",
1416
+ PAGE_HEAD + `\n<script>${STATE}</script>\n<main>{state.name}</main>`,
1417
+ (out) =>
1418
+ !/<meta|<title/i.test(tmpl(out)) &&
1419
+ /<title>Hi<\/title>/.test(headOf(out)) &&
1420
+ parses(out),
1421
+ );
1422
+
1423
+ checkHead(
1424
+ "a head written BELOW the script is still extracted",
1425
+ `<script>${STATE}</script>\n` + PAGE_HEAD + `\n<main>x</main>`,
1426
+ (out) =>
1427
+ !/<meta|<title/i.test(tmpl(out)) &&
1428
+ /content="d"/.test(headOf(out)) &&
1429
+ parses(out),
1430
+ );
1431
+
1432
+ checkHead(
1433
+ "compiles {expr} in the head against the script scope",
1434
+ `<head>\n <title>{state.name}</title>\n</head>\n<script>${STATE}</script>\n<main>x</main>`,
1435
+ (out) =>
1436
+ /<title>\$\{olum\.esc\(state\.name\)\}<\/title>/.test(headOf(out)) &&
1437
+ parses(out),
1438
+ );
1439
+
1440
+ checkHead(
1441
+ "leaves JSON-LD braces alone",
1442
+ `<head>\n <script type="application/ld+json">\n { "@type": "WebSite", "name": "Site" }\n </script>\n</head>\n<script>${STATE}</script>\n<main>x</main>`,
1443
+ (out) =>
1444
+ /\{ "@type": "WebSite", "name": "Site" \}/.test(headOf(out)) &&
1445
+ !/olum\.esc/.test(headOf(out)) &&
1446
+ parses(out),
1447
+ );
1448
+
1449
+ checkHead(
1450
+ "interpolates JSON-LD only inside a quoted string, and raw (no esc)",
1451
+ `<head>\n <script type="application/ld+json">\n { "@type": "Thing", "name": "{state.name}" }\n </script>\n</head>\n<script>${STATE}</script>\n<main>x</main>`,
1452
+ (out) =>
1453
+ /"name": "\$\{state\.name\}"/.test(headOf(out)) &&
1454
+ /\{ "@type": "Thing"/.test(headOf(out)) &&
1455
+ parses(out),
1456
+ );
1457
+
1458
+ checkHead(
1459
+ "escapes a backtick and a backslash typed in the head",
1460
+ '<head>\n <meta name="a" content="`x` C:\\path" />\n</head>\n<script>' +
1461
+ STATE +
1462
+ "</script>\n<main>x</main>",
1463
+ (out) => /\\`x\\` C:\\\\path/.test(headOf(out)) && parses(out),
1464
+ );
1465
+
1466
+ checkHead(
1467
+ "a ${expr} in the head interpolates like it does in the markup",
1468
+ "<head>\n <title>${state.name}</title>\n</head>\n<script>" +
1469
+ STATE +
1470
+ "</script>\n<main>${state.name}</main>",
1471
+ (out) =>
1472
+ /<title>\$\$\{olum\.esc\(state\.name\)\}<\/title>/.test(headOf(out)) &&
1473
+ /\$\$\{olum\.esc\(state\.name\)\}/.test(tmpl(out)) &&
1474
+ parses(out),
1475
+ );
1476
+
1477
+ checkHead(
1478
+ "keeps the script's original line number under a multi-line head",
1479
+ `<head>\n <title>Hi</title>\n</head>\n\n<script>${STATE}</script>\n<main>x</main>`,
1480
+ (out) =>
1481
+ out
1482
+ .split("\n")
1483
+ .slice(0, 4)
1484
+ .every((line) => line === "//") && !/^\/\//.test(out.split("\n")[4]),
1485
+ );
1486
+
1487
+ checkHead(
1488
+ "a component with no head emits no __head__",
1489
+ `<script>${STATE}</script>\n<main>x</main>`,
1490
+ (out) => !/__head__/.test(out) && parses(out),
1491
+ );
1492
+
1493
+ console.warn = () => {};
1494
+
1495
+ checkHead(
1496
+ "ignores a <head> in a component that is not a page",
1497
+ PAGE_HEAD + `\n<script>${STATE}</script>\n<main>x</main>`,
1498
+ (out) =>
1499
+ !/__head__/.test(out) && !/<meta|<title/i.test(tmpl(out)) && parses(out),
1500
+ "/app/src/components/Card.html",
1501
+ );
1502
+
1503
+ checkHead(
1504
+ "ignores an unclosed <head> instead of swallowing the file",
1505
+ `<head>\n <title>Hi</title>\n<script>${STATE}</script>\n<main id="home">x</main>`,
1506
+ (out) => !/__head__/.test(out) && /id="home"/.test(tmpl(out)) && parses(out),
1507
+ );
1508
+
1509
+ checkHead(
1510
+ "compiles only the FIRST head and drops the second",
1511
+ PAGE_HEAD +
1512
+ `\n<head>\n <meta name="robots" content="noindex" />\n</head>\n<script>${STATE}</script>\n<main>x</main>`,
1513
+ (out) =>
1514
+ /<title>Hi<\/title>/.test(headOf(out)) &&
1515
+ !/robots/.test(headOf(out)) &&
1516
+ !/robots/.test(tmpl(out)) &&
1517
+ parses(out),
1518
+ );
1519
+
1520
+ checkHead(
1521
+ "a <head> inside a JS string stays in the script",
1522
+ `<script>${STATE}\nconst t = "<head><title>no</title></head>";</script>\n<main>x</main>`,
1523
+ (out) =>
1524
+ !/__head__/.test(out) &&
1525
+ /<head><title>no<\/title><\/head>/.test(out) &&
1526
+ parses(out),
1527
+ );
1528
+
1529
+ console.warn = realWarn;
1530
+
1370
1531
  console.log("\n========================");
1371
1532
  const summary = `${passed} passed, ${failed} failed`;
1372
1533
  console.log((failed ? red(bold(summary)) : green(bold(summary))) + "\n");
@@ -1384,7 +1545,7 @@ if (failed) {
1384
1545
  console.log("");
1385
1546
  }
1386
1547
 
1387
- const EXPECTED_CHECKS = 118;
1548
+ const EXPECTED_CHECKS = 131;
1388
1549
  const total = passed + failed;
1389
1550
  if (total !== EXPECTED_CHECKS) {
1390
1551
  console.log(