valaxy 1.3.3 → 1.3.4

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,4 +1,4 @@
1
- import path, { resolve, basename, dirname, relative as relative$1, join, isAbsolute as isAbsolute$1, parse } from 'node:path';
1
+ import path, { resolve, basename, dirname, join, relative as relative$1, sep as sep$1, isAbsolute as isAbsolute$1, parse } from 'node:path';
2
2
  import process from 'node:process';
3
3
  import yargs from 'yargs';
4
4
  import { hideBin } from 'yargs/helpers';
@@ -12,7 +12,7 @@ import * as yaml from 'js-yaml';
12
12
  import { dump, load, CORE_SCHEMA } from 'js-yaml';
13
13
  import { isFunction, ensurePrefix, slash as slash$1, uniq as uniq$1, ensureSuffix, isObject } from '@antfu/utils';
14
14
  import _debug from 'debug';
15
- import path$1, { resolve as resolve$1, relative, isAbsolute, normalize, join as join$1, basename as basename$1, dirname as dirname$1 } from 'pathe';
15
+ import path$1, { resolve as resolve$1, relative, isAbsolute, sep, normalize, join as join$1, basename as basename$1, dirname as dirname$1 } from 'pathe';
16
16
  import defu, { createDefu } from 'defu';
17
17
  import { mergeConfig, loadConfigFromFile as loadConfigFromFile$1, normalizePath, searchForWorkspaceRoot, build as build$3, createServer as createServer$1 } from 'vite';
18
18
  import { webcrypto, createHash } from 'node:crypto';
@@ -23,13 +23,16 @@ import spawn$1, { spawn } from 'cross-spawn';
23
23
  import { resolvePath } from 'mlly';
24
24
  import { resolveGlobal } from 'resolve-global';
25
25
  import { normalizeRepositoryUrl } from '@valaxyjs/utils';
26
- import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
26
+ import { realpathSync, existsSync, readFileSync, statSync } from 'node:fs';
27
+ import pMap from 'p-map';
27
28
  import picomatch from 'picomatch';
28
29
  import { readFile, mkdir, writeFile, realpath, copyFile, access, constants, rm, stat } from 'node:fs/promises';
29
30
  import dayjs from 'dayjs';
30
31
  import { Feed } from 'feed';
31
32
  import { createMarkdownExit } from 'markdown-exit';
32
33
  import { table, getBorderCharacters } from 'table';
34
+ import { Parser } from 'htmlparser2';
35
+ import MagicString from 'magic-string';
33
36
  import { createHooks } from 'hookable';
34
37
  import { Unhead } from '@unhead/bundler/vite';
35
38
  import { groupIconMdPlugin, groupIconVitePlugin } from 'vitepress-plugin-group-icons';
@@ -38,8 +41,6 @@ import chokidar from 'chokidar';
38
41
  import { createUnplugin, createVitePlugin } from 'unplugin';
39
42
  import { createFilter } from 'unplugin-utils';
40
43
  import { createDebug } from 'obug';
41
- import MagicString from 'magic-string';
42
- import pMap from 'p-map';
43
44
  import pascalCase$1 from 'pascalcase';
44
45
  import VueI18n from '@intlify/unplugin-vue-i18n/vite';
45
46
  import MiniSearch from 'minisearch';
@@ -53,7 +54,6 @@ import { full } from 'markdown-it-emoji';
53
54
  import footnotePlugin from 'markdown-it-footnote';
54
55
  import imageFigures from 'markdown-it-image-figures';
55
56
  import TaskLists from 'markdown-it-task-lists';
56
- import { URL as URL$1, pathToFileURL } from 'node:url';
57
57
  import container from 'markdown-it-container';
58
58
  import katex from 'katex';
59
59
  import 'katex/contrib/mhchem';
@@ -62,9 +62,9 @@ import { createJiti } from 'jiti';
62
62
  import { transformerDirectives, transformerVariantGroup, presetWind4, presetAttributify, presetIcons, presetTypography } from 'unocss';
63
63
  import { convert } from 'html-to-text';
64
64
  import VueRouter from 'vue-router/vite';
65
+ import { pathToFileURL } from 'node:url';
65
66
  import { renderSSRHead } from '@unhead/vue/server';
66
- import { Parser } from 'htmlparser2';
67
- import escapeHtml from 'escape-html';
67
+ import escapeHtml$1 from 'escape-html';
68
68
  import { createRoutesContext, resolveOptions as resolveOptions$3 } from 'vue-router/unplugin';
69
69
  import { execSync, exec } from 'node:child_process';
70
70
  import { intro, confirm, isCancel, cancel, select, outro } from '@clack/prompts';
@@ -73,7 +73,7 @@ import * as readline from 'node:readline';
73
73
  import qrcode from 'qrcode';
74
74
  import ejs from 'ejs';
75
75
 
76
- const version = "1.3.3";
76
+ const version = "1.3.4";
77
77
 
78
78
  const GLOBAL_STATE = {
79
79
  valaxyApp: void 0,
@@ -346,6 +346,110 @@ function extractMarkdownImage(code) {
346
346
  });
347
347
  }
348
348
 
349
+ const HTML_ESCAPE_MAP = {
350
+ "&": "&",
351
+ "<": "&lt;",
352
+ ">": "&gt;",
353
+ '"': "&quot;",
354
+ "'": "&#39;"
355
+ };
356
+ const SAFE_URL_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tel:"]);
357
+ const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif|x-icon|vnd\.microsoft\.icon|svg\+xml)[;,]/i;
358
+ function stripControlsAndSpaces(value) {
359
+ let out = "";
360
+ for (let i = 0; i < value.length; i++) {
361
+ const code = value.charCodeAt(i);
362
+ if (code > 32 && code !== 127)
363
+ out += value[i];
364
+ }
365
+ return out;
366
+ }
367
+ function hasControlChars(value) {
368
+ for (let i = 0; i < value.length; i++) {
369
+ const code = value.charCodeAt(i);
370
+ if (code <= 31 || code === 127)
371
+ return true;
372
+ }
373
+ return false;
374
+ }
375
+ function escapeHtml(str = "") {
376
+ return str.replace(/[&<>"']/g, (ch) => HTML_ESCAPE_MAP[ch]);
377
+ }
378
+ function serializeInlineJsString(value) {
379
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/'/g, "\\u0027").replace(/\//g, "\\u002f").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
380
+ }
381
+ function sanitizeUrl(url, fallback = "#", options = {}) {
382
+ if (!url)
383
+ return fallback;
384
+ const trimmed = url.trim();
385
+ if (!trimmed || hasControlChars(trimmed))
386
+ return fallback;
387
+ const normalized = stripControlsAndSpaces(trimmed);
388
+ if (!normalized)
389
+ return fallback;
390
+ if (options.allowDataImage && SAFE_DATA_IMAGE_RE.test(normalized))
391
+ return trimmed;
392
+ const schemeMatch = normalized.match(/^([a-z][a-z\d+.-]*):/i);
393
+ if (schemeMatch && !SAFE_URL_PROTOCOLS.has(`${schemeMatch[1].toLowerCase()}:`))
394
+ return fallback;
395
+ return trimmed;
396
+ }
397
+
398
+ const PROTOCOL_PREFIX_RE = /^(?:[a-z][a-z\d+.-]*:)?\/\//i;
399
+ function safeDecodeURI(uri) {
400
+ try {
401
+ return decodeURI(uri);
402
+ } catch {
403
+ return uri;
404
+ }
405
+ }
406
+ function safeDecodeURIComponent(uri) {
407
+ try {
408
+ return decodeURIComponent(uri);
409
+ } catch {
410
+ return uri;
411
+ }
412
+ }
413
+ function safeParseUrl(url, base) {
414
+ try {
415
+ return new URL(url, base);
416
+ } catch {
417
+ return null;
418
+ }
419
+ }
420
+ function joinBaseUrl(base = "/", routePath = "") {
421
+ const normalizedBase = (base || "/").replace(/\\/g, "/");
422
+ const normalizedRoute = routePath.replace(/\\/g, "/").replace(/^\/+/, "");
423
+ const protocolMatch = normalizedBase.match(PROTOCOL_PREFIX_RE);
424
+ if (protocolMatch) {
425
+ const prefix = protocolMatch[0];
426
+ const afterProtocol = normalizedBase.slice(prefix.length);
427
+ const slashIdx = afterProtocol.indexOf("/");
428
+ const authority = slashIdx === -1 ? afterProtocol : afterProtocol.slice(0, slashIdx);
429
+ const basePath = slashIdx === -1 ? "" : afterProtocol.slice(slashIdx).replace(/\/+$/, "");
430
+ const joinedPath = normalizedRoute ? `${basePath}/${normalizedRoute}` : `${basePath || ""}/`;
431
+ return `${prefix}${authority}${joinedPath.startsWith("/") ? joinedPath : `/${joinedPath}`}`;
432
+ }
433
+ if (normalizedBase.startsWith("./") || normalizedBase === ".") {
434
+ const cleanBase = normalizedBase.replace(/\/+$/, "");
435
+ const prefix = cleanBase === "." ? "./" : `${cleanBase}/`;
436
+ return `${prefix}${normalizedRoute}`;
437
+ }
438
+ const cleanBasePath = `/${normalizedBase.replace(/^\/+|\/+$/g, "")}`;
439
+ if (!normalizedRoute)
440
+ return cleanBasePath === "/" ? "/" : `${cleanBasePath}/`;
441
+ return cleanBasePath === "/" ? `/${normalizedRoute}` : `${cleanBasePath}/${normalizedRoute}`;
442
+ }
443
+ const INDEX_ONLY_SEGMENTS_RE = /^index(?:\/index)*$/;
444
+ function urlPathToMarkdownPath(urlPath) {
445
+ const normalized = urlPath.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
446
+ const relativeFile = !normalized ? "index.md" : INDEX_ONLY_SEGMENTS_RE.test(normalized) ? `${normalized}/index.md` : `${normalized}.md`;
447
+ return {
448
+ href: `/${relativeFile}`,
449
+ relativeFile
450
+ };
451
+ }
452
+
349
453
  function commonOptions(args) {
350
454
  return args.positional("root", {
351
455
  default: ".",
@@ -854,9 +958,35 @@ async function encryptContent(content, options) {
854
958
  return Buffer$1.from(ciphertextData).toString("base64");
855
959
  }
856
960
 
857
- function getGitTimestamp(file, type = "updated") {
961
+ const pipelineCaches = /* @__PURE__ */ new WeakMap();
962
+ function getGitTimestampCache(scope) {
963
+ let cache = pipelineCaches.get(scope);
964
+ if (!cache) {
965
+ cache = /* @__PURE__ */ new Map();
966
+ pipelineCaches.set(scope, cache);
967
+ }
968
+ return cache;
969
+ }
970
+ function clearGitTimestampCache(cache, file) {
971
+ if (!file) {
972
+ cache.clear();
973
+ return;
974
+ }
858
975
  const filePath = resolve(file);
859
- return new Promise((resolve) => {
976
+ const prefixCreated = `created:${filePath}:`;
977
+ const prefixUpdated = `updated:${filePath}:`;
978
+ for (const key of cache.keys()) {
979
+ if (key.startsWith(prefixCreated) || key.startsWith(prefixUpdated))
980
+ cache.delete(key);
981
+ }
982
+ }
983
+ function getGitTimestamp(file, type = "updated", cache) {
984
+ const filePath = resolve(file);
985
+ const cacheKey = `${type}:${filePath}:${process.env.PATH ?? ""}`;
986
+ const cached = cache?.get(cacheKey);
987
+ if (cached)
988
+ return cached;
989
+ const pending = new Promise((resolve) => {
860
990
  const params = ["--literal-pathspecs", "log", "--follow", "--no-show-signature", "--format=%ct"];
861
991
  if (type === "updated")
862
992
  params.push("-1");
@@ -878,6 +1008,8 @@ function getGitTimestamp(file, type = "updated") {
878
1008
  resolve(0);
879
1009
  });
880
1010
  });
1011
+ cache?.set(cacheKey, pending);
1012
+ return pending;
881
1013
  }
882
1014
 
883
1015
  function isExternal(str) {
@@ -1022,17 +1154,20 @@ function collectRedirects(redirectRules) {
1022
1154
  return redirects;
1023
1155
  }
1024
1156
  async function writeRedirectFiles(route, filePath) {
1157
+ const safeRoute = sanitizeUrl(route, "/");
1158
+ const escapedRoute = escapeHtml(safeRoute);
1159
+ const jsRoute = serializeInlineJsString(safeRoute);
1025
1160
  await fs.ensureFile(filePath);
1026
1161
  await fs.writeFile(filePath, `
1027
1162
  <!DOCTYPE html>
1028
1163
  <html lang="en">
1029
1164
  <head>
1030
1165
  <meta charset="UTF-8">
1031
- <meta http-equiv="refresh" content="0; url=${route}">
1032
- <link rel="canonical" href="${route}">
1166
+ <meta http-equiv="refresh" content="0; url=${escapedRoute}">
1167
+ <link rel="canonical" href="${escapedRoute}">
1033
1168
  </head>
1034
1169
  <script>
1035
- window.location.href = '${route}' + window.location.search + window.location.hash
1170
+ window.location.href = ${jsRoute} + window.location.search + window.location.hash
1036
1171
  <\/script>
1037
1172
  </html>
1038
1173
  `);
@@ -1203,6 +1338,236 @@ const matterOptions = {
1203
1338
  }
1204
1339
  };
1205
1340
 
1341
+ function foucGuardHtml(maxDuration) {
1342
+ return [
1343
+ `<style id="valaxy-fouc">body{margin:0;opacity:0!important}</style>`,
1344
+ `<noscript><style>body{opacity:1!important}</style></noscript>`,
1345
+ `<script>(${foucGuardScript.toString()})(${maxDuration})<\/script>`
1346
+ ].join("");
1347
+ }
1348
+ function foucGuardScript(maxDuration) {
1349
+ var done = 0;
1350
+ var observer = new MutationObserver(check);
1351
+ var timer = maxDuration ? setTimeout(reveal, maxDuration) : void 0;
1352
+ function reveal() {
1353
+ if (done) return;
1354
+ done = 1;
1355
+ observer.disconnect();
1356
+ clearTimeout(timer);
1357
+ document.removeEventListener("load", check, true);
1358
+ removeEventListener("load", reveal);
1359
+ var s = document.getElementById("valaxy-fouc");
1360
+ if (s) s.remove();
1361
+ }
1362
+ function check() {
1363
+ if (!document.body) return;
1364
+ var links = document.head.querySelectorAll('link[rel~="stylesheet"]');
1365
+ for (var i = 0; i < links.length; i++) {
1366
+ var link = links[i];
1367
+ if (!link.disabled && !link.sheet) return;
1368
+ }
1369
+ reveal();
1370
+ }
1371
+ observer.observe(document.documentElement, { childList: true });
1372
+ observer.observe(document.head, {
1373
+ childList: true,
1374
+ subtree: true,
1375
+ attributes: true,
1376
+ attributeFilter: ["media", "rel", "disabled"]
1377
+ });
1378
+ document.addEventListener("load", check, true);
1379
+ addEventListener("load", reveal);
1380
+ }
1381
+
1382
+ function normalizeConfigPath(file) {
1383
+ const abs = resolve(file);
1384
+ try {
1385
+ return realpathSync(abs);
1386
+ } catch {
1387
+ return abs;
1388
+ }
1389
+ }
1390
+ const VITE_DEFAULT_CONFIG_FILES = [
1391
+ "vite.config.js",
1392
+ "vite.config.mjs",
1393
+ "vite.config.ts",
1394
+ "vite.config.cjs",
1395
+ "vite.config.mts",
1396
+ "vite.config.cts"
1397
+ ];
1398
+ async function findRootViteConfig(root) {
1399
+ for (const filename of VITE_DEFAULT_CONFIG_FILES) {
1400
+ const candidate = join(root, filename);
1401
+ if (await fs.exists(candidate))
1402
+ return candidate;
1403
+ }
1404
+ }
1405
+ async function mergeViteConfigs({ userRoot, themeRoot }, command, mode = command === "build" ? "production" : "development", extraFiles = [], isSsrBuild, configLoader, logLevel, customLogger) {
1406
+ const configEnv = {
1407
+ mode,
1408
+ command,
1409
+ ...isSsrBuild !== void 0 ? { isSsrBuild } : {}
1410
+ };
1411
+ let resolvedConfig = {};
1412
+ const discoveredFiles = (await Promise.all(
1413
+ uniq$1([themeRoot, userRoot]).map((root) => findRootViteConfig(root))
1414
+ )).filter((file) => Boolean(file));
1415
+ const seen = /* @__PURE__ */ new Set();
1416
+ const files = [...discoveredFiles, ...extraFiles].filter((file) => {
1417
+ const key = normalizeConfigPath(file);
1418
+ if (seen.has(key))
1419
+ return false;
1420
+ seen.add(key);
1421
+ return true;
1422
+ });
1423
+ const viteConfigs = await Promise.all(
1424
+ files.map((file) => loadConfigFromFile$1(configEnv, file, void 0, logLevel, customLogger, configLoader))
1425
+ );
1426
+ for (const viteConfig of viteConfigs) {
1427
+ if (!viteConfig?.config)
1428
+ continue;
1429
+ resolvedConfig = mergeConfig(resolvedConfig, viteConfig.config);
1430
+ }
1431
+ return resolvedConfig;
1432
+ }
1433
+ async function getIndexHtml({ clientRoot, themeRoot, userRoot, config }, rawHtml) {
1434
+ let main = rawHtml;
1435
+ let head = "";
1436
+ let body = "";
1437
+ if (config.siteConfig.favicon) {
1438
+ const safeFavicon = sanitizeUrl(config.siteConfig.favicon, "", { allowDataImage: true });
1439
+ if (safeFavicon)
1440
+ head += `<link rel="icon" href="${escapeHtml(safeFavicon)}">`;
1441
+ }
1442
+ const roots = [userRoot, themeRoot];
1443
+ if (config.siteConfig.mode === "auto") {
1444
+ head += `
1445
+ <script>
1446
+ ;(function () {
1447
+ const prefersDark =
1448
+ window.matchMedia &&
1449
+ window.matchMedia('(prefers-color-scheme: dark)').matches
1450
+ const setting = localStorage.getItem('vueuse-color-scheme') || 'auto'
1451
+ if (setting === 'dark' || (prefersDark && setting !== 'light'))
1452
+ document.documentElement.classList.toggle('dark', true)
1453
+ })()
1454
+ <\/script>
1455
+ `;
1456
+ head += `<style type="text/css">
1457
+ :root { color-scheme: light dark; --va-c-bg: #fff; }
1458
+ html.dark { --va-c-bg: #000; }
1459
+ html { background-color: var(--va-c-bg); }
1460
+ </style>`;
1461
+ }
1462
+ const foucGuard = config.build?.foucGuard ?? {};
1463
+ const foucEnabled = foucGuard.enabled ?? true;
1464
+ const foucMaxDuration = foucGuard.maxDuration ?? 5e3;
1465
+ if (foucEnabled)
1466
+ head += foucGuardHtml(foucMaxDuration);
1467
+ if (config.siteConfig.lang) {
1468
+ head += `
1469
+ <script>
1470
+ const locale = localStorage.getItem('valaxy-locale') || ${serializeInlineJsString(config.siteConfig.lang)};
1471
+ document.documentElement.setAttribute('lang', locale);
1472
+ <\/script>
1473
+ `;
1474
+ }
1475
+ for (const root of roots) {
1476
+ const path = join(root, "index.html");
1477
+ if (!fs.existsSync(path))
1478
+ continue;
1479
+ const indexHtml = await fs.readFile(path, "utf-8");
1480
+ head += `
1481
+ ${(indexHtml.match(/<head>([\s\S]*?)<\/head>/i)?.[1] || "").trim()}`;
1482
+ body += `
1483
+ ${(indexHtml.match(/<body>([\s\S]*?)<\/body>/i)?.[1] || "").trim()}`;
1484
+ }
1485
+ main = main.replace("__ENTRY__", () => toAtFS(join(clientRoot, "main.ts"))).replace("<!-- head -->", () => head).replace("<!-- body -->", () => body);
1486
+ return main;
1487
+ }
1488
+
1489
+ const resolvedClientInputsWeakMap = /* @__PURE__ */ new WeakMap();
1490
+ function resolvePublicDir(userRoot, publicDir) {
1491
+ if (publicDir === false)
1492
+ return false;
1493
+ return resolve(userRoot, publicDir || "public");
1494
+ }
1495
+ function resolveBuildPaths(options, viteConfig, explicitOutDir) {
1496
+ const rawOutDir = explicitOutDir ?? viteConfig?.build?.outDir ?? options.outDir ?? options.config?.vite?.build?.outDir ?? "dist";
1497
+ const outDir = resolve(options.userRoot, rawOutDir);
1498
+ const rawPublicDir = viteConfig?.publicDir !== void 0 ? viteConfig.publicDir : options.publicDir !== void 0 ? options.publicDir : options.config?.vite?.publicDir;
1499
+ const publicDir = resolvePublicDir(options.userRoot, rawPublicDir);
1500
+ const base = viteConfig?.base ?? options.base ?? options.config?.vite?.base ?? "/";
1501
+ return { outDir, publicDir, base };
1502
+ }
1503
+ async function resolveEffectiveViteConfig(options, command, callerViteConfig = {}, explicitOutDir, isSsrBuild, persistPaths = isSsrBuild !== true) {
1504
+ const preloadedInput = resolvedClientInputsWeakMap.get(callerViteConfig);
1505
+ if (preloadedInput) {
1506
+ if (isSsrBuild !== true) {
1507
+ const paths2 = resolveBuildPaths(options, callerViteConfig, explicitOutDir ?? preloadedInput.explicitOutDir);
1508
+ if (persistPaths) {
1509
+ options.outDir = paths2.outDir;
1510
+ options.publicDir = paths2.publicDir;
1511
+ options.base = paths2.base;
1512
+ }
1513
+ return {
1514
+ viteConfig: callerViteConfig,
1515
+ ...paths2
1516
+ };
1517
+ }
1518
+ callerViteConfig = preloadedInput.callerViteConfig;
1519
+ explicitOutDir = explicitOutDir ?? preloadedInput.explicitOutDir;
1520
+ }
1521
+ const mode = callerViteConfig.mode ?? options.config.vite?.mode ?? ("production" );
1522
+ if (!process.env.NODE_ENV)
1523
+ process.env.NODE_ENV = "production" ;
1524
+ const explicitConfigFile = callerViteConfig.configFile !== void 0 ? callerViteConfig.configFile : options.config.vite?.configFile;
1525
+ const configLoader = callerViteConfig.configLoader ?? options.config.vite?.configLoader;
1526
+ const logLevel = callerViteConfig.logLevel ?? options.config.vite?.logLevel;
1527
+ const customLogger = callerViteConfig.customLogger ?? options.config.vite?.customLogger;
1528
+ const resolvedExplicitConfigFile = typeof explicitConfigFile === "string" ? resolve(explicitConfigFile) : void 0;
1529
+ const baseViteConfig = explicitConfigFile === false ? {} : await mergeViteConfigs(
1530
+ options,
1531
+ command,
1532
+ mode,
1533
+ resolvedExplicitConfigFile ? [resolvedExplicitConfigFile] : [],
1534
+ isSsrBuild,
1535
+ configLoader,
1536
+ logLevel,
1537
+ customLogger
1538
+ );
1539
+ const merged = mergeConfig(
1540
+ mergeConfig(baseViteConfig, options.config.vite || {}),
1541
+ callerViteConfig
1542
+ );
1543
+ const paths = resolveBuildPaths(options, merged, explicitOutDir);
1544
+ if (persistPaths) {
1545
+ options.outDir = paths.outDir;
1546
+ options.publicDir = paths.publicDir;
1547
+ options.base = paths.base;
1548
+ }
1549
+ const viteConfig = mergeConfig(merged, {
1550
+ // Config files were already evaluated for this pass, so disable Vite's own loading
1551
+ // to prevent duplicate plugin registration and precedence inversion.
1552
+ configFile: false,
1553
+ base: paths.base,
1554
+ publicDir: paths.publicDir,
1555
+ build: {
1556
+ outDir: paths.outDir
1557
+ }
1558
+ });
1559
+ if (isSsrBuild !== true) {
1560
+ resolvedClientInputsWeakMap.set(viteConfig, {
1561
+ callerViteConfig,
1562
+ explicitOutDir
1563
+ });
1564
+ }
1565
+ return {
1566
+ viteConfig,
1567
+ ...paths
1568
+ };
1569
+ }
1570
+
1206
1571
  function isProd() {
1207
1572
  return process.env.NODE_ENV === "production";
1208
1573
  }
@@ -1254,8 +1619,12 @@ async function discoverPageFiles(userRoot, include = ["**/*.md"]) {
1254
1619
  for (const root of getPageRoots(userRoot)) {
1255
1620
  const files = await glob(include, { cwd: root, ignore: ["**/node_modules/**"], onlyFiles: true });
1256
1621
  for (const page of files.sort()) {
1622
+ const resolved = resolve$1(root, page);
1623
+ const rel = relative(root, resolved);
1624
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || !getPagePath(resolved, userRoot))
1625
+ continue;
1257
1626
  if (!pages.has(page))
1258
- pages.set(page, resolve$1(root, page));
1627
+ pages.set(page, resolved);
1259
1628
  }
1260
1629
  }
1261
1630
  return pages;
@@ -1281,8 +1650,8 @@ async function generateFuseList(options) {
1281
1650
  loadLocalesYml(path.resolve(options.userRoot, "locales"));
1282
1651
  const globalAuthor = nodeT(options.config.siteConfig.author.name, options.config.siteConfig.lang || "en");
1283
1652
  const posts = [];
1284
- for await (const i of files) {
1285
- const raw = fs.readFileSync(i, "utf-8");
1653
+ for (const i of files) {
1654
+ const raw = await fs.readFile(i, "utf-8");
1286
1655
  const { data, content: rawContent } = matter(raw, matterOptions);
1287
1656
  const fmData = { ...options.config.siteConfig.frontmatter, ...data };
1288
1657
  const content = stripEncryptedContent(rawContent);
@@ -1300,8 +1669,10 @@ async function generateFuseList(options) {
1300
1669
  if (fmData.password || fmData.encrypt === true)
1301
1670
  continue;
1302
1671
  const extendKeys = options.config.fuse?.extendKeys || [];
1303
- const relativeLink = path.join(options.config.vite?.base || "/", getPagePath(i, options.userRoot) || path.relative(path.resolve(options.userRoot, "pages"), i)).replace(/\\/g, "/");
1304
- const link = i.endsWith("index.md") ? relativeLink.replace(/\/index\.md$/, "") : relativeLink.replace(/\.md$/, "");
1672
+ const { base } = resolveBuildPaths(options);
1673
+ const pagePath = (getPagePath(i, options.userRoot) || path.relative(path.resolve(options.userRoot, "pages"), i)).replace(/\\/g, "/");
1674
+ const cleanRoute = pagePath.replace(/(?:^|\/)index\.md$/, "").replace(/\.md$/, "");
1675
+ const link = joinBaseUrl(base, cleanRoute);
1305
1676
  const fuseListItem = {
1306
1677
  title: fmData.title || "",
1307
1678
  tags: (typeof fmData.tags === "string" ? [fmData.tags] : fmData.tags) || [],
@@ -1324,34 +1695,38 @@ async function generateFuseList(options) {
1324
1695
  }
1325
1696
  return posts;
1326
1697
  }
1327
- async function execFuse(options) {
1328
- consola.info("Start generate fuse list...");
1329
- const fuseList = await generateFuseList(options);
1330
- await fs.ensureDir("./dist");
1331
- const publicFolder = path.resolve(options.userRoot, "public");
1332
- const publicFuseFile = path.resolve(publicFolder, options.config.siteConfig.fuse.dataPath);
1333
- const publicRelativeFile = path.join("public", options.config.siteConfig.fuse.dataPath);
1334
- await fs.ensureFile(publicFuseFile);
1335
- fs.writeJSONSync(publicFuseFile, fuseList);
1336
- consola.success(`Generate fuse list in ${colors.dim(publicFolder)}`);
1337
- const distFolder = path.resolve(options.userRoot, "dist");
1338
- const distFuseFile = path.resolve(distFolder, options.config.siteConfig.fuse.dataPath);
1339
- await fs.ensureDir(distFolder);
1340
- fs.writeJSONSync(distFuseFile, fuseList);
1341
- consola.success(`Generate fuse list in ${colors.dim(distFolder)}`);
1342
- try {
1343
- const gitignorePath = path.resolve(options.userRoot, ".gitignore");
1344
- const gitignore = await fs.readFile(gitignorePath, "utf-8");
1345
- const ignorePath = publicRelativeFile.replace(/\\/g, "/");
1346
- if (!gitignore.includes(ignorePath)) {
1347
- await fs.appendFile(gitignorePath, `
1698
+ async function execFuse(options, target = "both", precomputedList) {
1699
+ const fuseList = precomputedList ?? await (async () => {
1700
+ consola.info("Start generate fuse list...");
1701
+ return await generateFuseList(options);
1702
+ })();
1703
+ const { outDir, publicDir } = resolveBuildPaths(options);
1704
+ if ((target === "both" || target === "public") && publicDir !== false) {
1705
+ const publicFuseFile = path.resolve(publicDir, options.config.siteConfig.fuse.dataPath);
1706
+ await fs.ensureFile(publicFuseFile);
1707
+ await fs.writeJson(publicFuseFile, fuseList);
1708
+ consola.success(`Generate fuse list in ${colors.dim(publicDir)}`);
1709
+ try {
1710
+ const gitignorePath = path.resolve(options.userRoot, ".gitignore");
1711
+ const gitignore = await fs.readFile(gitignorePath, "utf-8");
1712
+ const ignorePath = path.relative(options.userRoot, publicFuseFile).replace(/\\/g, "/");
1713
+ if (ignorePath && !ignorePath.startsWith("..") && !path.isAbsolute(ignorePath) && !gitignore.includes(ignorePath)) {
1714
+ await fs.appendFile(gitignorePath, `
1348
1715
  # valaxy fuse
1349
1716
  ${ignorePath}
1350
1717
  `);
1351
- consola.success(`Add ${colors.dim(ignorePath)} to ${colors.dim(".gitignore")}`);
1718
+ consola.success(`Add ${colors.dim(ignorePath)} to ${colors.dim(".gitignore")}`);
1719
+ }
1720
+ } catch {
1352
1721
  }
1353
- } catch {
1354
1722
  }
1723
+ if (target === "both" || target === "dist") {
1724
+ const distFuseFile = path.resolve(outDir, options.config.siteConfig.fuse.dataPath);
1725
+ await fs.ensureFile(distFuseFile);
1726
+ await fs.writeJson(distFuseFile, fuseList);
1727
+ consola.success(`Generate fuse list in ${colors.dim(outDir)}`);
1728
+ }
1729
+ return fuseList;
1355
1730
  }
1356
1731
  function registerFuseCommand(cli) {
1357
1732
  cli.command(
@@ -1361,6 +1736,7 @@ function registerFuseCommand(cli) {
1361
1736
  async ({ root }) => {
1362
1737
  setEnvProd();
1363
1738
  const options = await resolveOptions$2({ userRoot: root }, "build");
1739
+ await resolveEffectiveViteConfig(options, "build");
1364
1740
  await execFuse(options);
1365
1741
  }
1366
1742
  );
@@ -1370,8 +1746,13 @@ const fuseModule = defineValaxyModule({
1370
1746
  registerFuseCommand(cli);
1371
1747
  },
1372
1748
  setup(node) {
1749
+ let cachedFuseList;
1373
1750
  node.hook("build:before", async () => {
1374
- await execFuse(node.options);
1751
+ cachedFuseList = await execFuse(node.options, "public");
1752
+ });
1753
+ node.hook("build:after", async () => {
1754
+ await execFuse(node.options, "dist", cachedFuseList);
1755
+ cachedFuseList = void 0;
1375
1756
  });
1376
1757
  }
1377
1758
  });
@@ -1380,11 +1761,11 @@ async function scanPageFiles(userRoot, include) {
1380
1761
  return [...(await discoverPageFiles(userRoot, include)).values()];
1381
1762
  }
1382
1763
  async function readPostFiles(files, defaults = {}) {
1383
- return Promise.all(files.map(async (filePath) => {
1764
+ return pMap(files, async (filePath) => {
1384
1765
  const raw = await readFile(filePath, "utf-8");
1385
1766
  const { data, content, excerpt } = matter(raw, matterOptions);
1386
1767
  return { data: { ...defaults, ...data }, content, excerpt, filePath };
1387
- }));
1768
+ }, { concurrency: 32 });
1388
1769
  }
1389
1770
  function filterPublicPosts(posts, publishing, userRoot) {
1390
1771
  return posts.filter(({ data, filePath }) => {
@@ -1456,7 +1837,7 @@ async function build$2(options) {
1456
1837
  const posts = await loadLlmsPosts(options);
1457
1838
  const selection = llmsSelection(llmsConfig);
1458
1839
  warnUnmatchedCollapse(posts, selection);
1459
- const distPath = path.resolve(options.userRoot, "dist");
1840
+ const { outDir: distPath } = resolveBuildPaths(options);
1460
1841
  await fs.ensureDir(distPath);
1461
1842
  const title = resolveText(siteConfig.title, lang) || "Valaxy Blog";
1462
1843
  const description = resolveText(siteConfig.description, lang);
@@ -1485,15 +1866,19 @@ async function build$2(options) {
1485
1866
  consola.debug(`[llms] Generated ${colors.dim("dist/llms-full.txt")}`);
1486
1867
  }
1487
1868
  if (llmsConfig.files) {
1488
- await Promise.all(posts.map(async (post) => {
1489
- const mdPath = path.resolve(distPath, `${post.urlPath.slice(1)}.md`);
1869
+ await pMap(posts, async (post) => {
1870
+ const { relativeFile } = urlPathToMarkdownPath(post.urlPath);
1871
+ const mdPath = path.resolve(distPath, relativeFile);
1872
+ const relToDist = path.relative(distPath, mdPath);
1873
+ if (relToDist === ".." || relToDist.startsWith(`..${path.sep}`) || path.isAbsolute(relToDist))
1874
+ return;
1490
1875
  await fs.ensureDir(path.dirname(mdPath));
1491
1876
  const header = formatMetadataHeader(post);
1492
1877
  const body = post.content.trim();
1493
1878
  const fileContent = body ? `${header}${body}
1494
1879
  ` : `${header}`;
1495
1880
  await fs.writeFile(mdPath, fileContent, "utf-8");
1496
- }));
1881
+ }, { concurrency: 32 });
1497
1882
  consola.debug(`[llms] Copied ${colors.dim(posts.length.toString())} raw .md files to dist/`);
1498
1883
  }
1499
1884
  consola.success(`llms.txt generated. (${posts.length} pages)`);
@@ -1600,7 +1985,7 @@ function hrefToUrl(siteUrl, href) {
1600
1985
  return trimmed;
1601
1986
  const directory = trimmed.endsWith("/");
1602
1987
  const urlPath = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
1603
- const target = directory || urlPath.endsWith(".md") ? urlPath : `${normalizeLlmsPath(urlPath)}.md`;
1988
+ const target = directory || urlPath.endsWith(".md") ? urlPath : urlPathToMarkdownPath(urlPath).href;
1604
1989
  return siteUrl ? `${siteUrl}${target}` : target;
1605
1990
  }
1606
1991
  function planLlmsPages(posts, config = {}) {
@@ -1676,7 +2061,7 @@ function groupLlmsEntries(params) {
1676
2061
  sections.set(featuredTitle, featuredPosts.map((post) => ({
1677
2062
  title: post.title,
1678
2063
  description: post.description,
1679
- href: `${post.urlPath}.md`
2064
+ href: urlPathToMarkdownPath(post.urlPath).href
1680
2065
  })));
1681
2066
  }
1682
2067
  for (const post of rest) {
@@ -1685,7 +2070,7 @@ function groupLlmsEntries(params) {
1685
2070
  const entry = {
1686
2071
  title: post.title,
1687
2072
  description: post.description,
1688
- href: `${post.urlPath}.md`
2073
+ href: urlPathToMarkdownPath(post.urlPath).href
1689
2074
  };
1690
2075
  if (entries)
1691
2076
  entries.push(entry);
@@ -1848,6 +2233,7 @@ const llmsModule = defineValaxyModule({
1848
2233
  async ({ root }) => {
1849
2234
  setEnvProd();
1850
2235
  const options = await resolveOptions$2({ userRoot: root }, "build");
2236
+ await resolveEffectiveViteConfig(options, "build");
1851
2237
  await build$2(options);
1852
2238
  }
1853
2239
  );
@@ -1870,46 +2256,122 @@ async function statIfExists(file) {
1870
2256
  throw e;
1871
2257
  }
1872
2258
  }
1873
- async function getCreatedTime(file) {
1874
- return await getGitTimestamp(file, "created") || (await statIfExists(file))?.ctime || Date.now();
2259
+ async function getCreatedTime(file, cache) {
2260
+ return await getGitTimestamp(file, "created", cache) || (await statIfExists(file))?.ctime || Date.now();
1875
2261
  }
1876
- async function getUpdatedTime(file) {
1877
- return await getGitTimestamp(file, "updated") || (await statIfExists(file))?.mtime || Date.now();
2262
+ async function getUpdatedTime(file, cache) {
2263
+ return await getGitTimestamp(file, "updated", cache) || (await statIfExists(file))?.mtime || Date.now();
1878
2264
  }
1879
2265
 
1880
- const markdown = createMarkdownExit({
1881
- html: true,
1882
- breaks: true,
1883
- linkify: true
1884
- });
1885
- async function extractImagePathsFromHTML(htmlPath, DOMAIN) {
1886
- const imageMap = /* @__PURE__ */ new Map();
2266
+ function assetManifestPath(options) {
2267
+ return join(options.tempDir || join(options.userRoot, ".valaxy"), "rss-assets.json");
2268
+ }
2269
+ function sourceKey(file, root) {
2270
+ const path = relative$1(root, file);
2271
+ if (path && path !== ".." && !path.startsWith(`..${sep$1}`) && !isAbsolute$1(path))
2272
+ return path.split(sep$1).join("/");
2273
+ }
2274
+ function createRssAssetsPlugin(options) {
2275
+ return {
2276
+ name: "valaxy:rss-assets",
2277
+ apply: "build",
2278
+ async writeBundle(output, bundle) {
2279
+ const { config } = this.environment;
2280
+ if (config.build.ssr || !output.dir)
2281
+ return;
2282
+ const files = /* @__PURE__ */ new Map();
2283
+ for (const asset of Object.values(bundle)) {
2284
+ if (asset.type !== "asset")
2285
+ continue;
2286
+ for (const original of asset.originalFileNames) {
2287
+ const key = sourceKey(resolve(config.root, original), options.userRoot);
2288
+ if (key)
2289
+ files.set(key, asset.fileName);
2290
+ }
2291
+ }
2292
+ const manifest = {
2293
+ outDir: resolve(config.root, output.dir),
2294
+ base: config.base,
2295
+ files: [...files]
2296
+ };
2297
+ await fs.outputJson(assetManifestPath(options), manifest);
2298
+ }
2299
+ };
2300
+ }
2301
+ async function readBuiltAssetUrls(options, outDir, siteUrl) {
2302
+ try {
2303
+ const manifest = await fs.readJson(assetManifestPath(options));
2304
+ if (manifest.outDir !== outDir)
2305
+ return;
2306
+ const base = new URL(manifest.base || "./", siteUrl);
2307
+ return new Map(manifest.files.map(([source, emitted]) => [
2308
+ source,
2309
+ new URL(emitted.split("/").map(encodeURIComponent).join("/"), base).href
2310
+ ]));
2311
+ } catch {
2312
+ }
2313
+ }
2314
+ function findBuiltAsset(url, markdownFile, root, assets) {
2315
+ let pathname = url;
2316
+ try {
2317
+ pathname = decodeURIComponent(pathname);
2318
+ } catch {
2319
+ }
2320
+ if (isAbsolute$1(pathname))
2321
+ return;
2322
+ const key = sourceKey(resolve(dirname(markdownFile), pathname), root);
2323
+ if (key)
2324
+ return assets.get(key);
2325
+ }
2326
+ async function readLegacyImageUrls(htmlPath, siteUrl) {
2327
+ const images = /* @__PURE__ */ new Map();
1887
2328
  try {
1888
- if (!await fs.exists(htmlPath))
1889
- return imageMap;
2329
+ if (!await fs.pathExists(htmlPath))
2330
+ return images;
1890
2331
  const html = await fs.readFile(htmlPath, "utf-8");
1891
- const imgRegex = /<img[^>]+src="([^"]+)"[^>]*>/g;
1892
- let match;
1893
- while ((match = imgRegex.exec(html)) !== null) {
1894
- const src = match[1];
1895
- const assetMatch = src.match(/\/assets\/(.+)\.([a-zA-Z0-9]+)\.([a-z0-9]+)$/);
1896
- if (assetMatch) {
1897
- const [, basename, , ext] = assetMatch;
1898
- const originalName = `${basename}.${ext}`;
1899
- imageMap.set(originalName, `${DOMAIN}${src}`);
1900
- imageMap.set(`./${originalName}`, `${DOMAIN}${src}`);
1901
- consola.debug(`[RSS] Mapped image: ${originalName} -> ${DOMAIN}${src}`);
2332
+ new Parser({
2333
+ onopentag(name, { src }) {
2334
+ if (name !== "img" || !src)
2335
+ return;
2336
+ const pathname = src.split(/[?#]/, 1)[0];
2337
+ const match = pathname.match(/\/assets\/([^/]+)\.[a-z0-9]+\.([a-z0-9]+)$/i);
2338
+ if (!match)
2339
+ return;
2340
+ const original = `${match[1]}.${match[2]}`;
2341
+ const url = new URL(pathname, siteUrl).href;
2342
+ const existing = images.get(original);
2343
+ images.set(original, existing !== void 0 && existing !== url ? null : url);
1902
2344
  }
1903
- }
1904
- if (imageMap.size > 0) {
1905
- const uniqueImageCount = imageMap.size / 2;
1906
- consola.info(`[RSS] Extracted ${uniqueImageCount} image(s) from ${htmlPath}`);
1907
- }
2345
+ }).end(html);
1908
2346
  } catch (error) {
1909
2347
  consola.debug(`Failed to extract image paths from ${htmlPath}:`, error);
1910
2348
  }
1911
- return imageMap;
2349
+ return images;
1912
2350
  }
2351
+ function rewriteSourceAttributes(html, resolveUrl) {
2352
+ const output = new MagicString(html);
2353
+ let isImage = false;
2354
+ const parser = new Parser({
2355
+ onopentagname(name) {
2356
+ isImage = name === "img";
2357
+ },
2358
+ onattribute(name, src) {
2359
+ if (name !== "src")
2360
+ return;
2361
+ const url = resolveUrl(src, isImage);
2362
+ if (url !== void 0)
2363
+ output.overwrite(parser.startIndex, parser.endIndex, `src="${url.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;")}"`);
2364
+ }
2365
+ });
2366
+ parser.end(html);
2367
+ return output.toString();
2368
+ }
2369
+
2370
+ const markdown = createMarkdownExit({
2371
+ html: true,
2372
+ breaks: true,
2373
+ linkify: true
2374
+ });
1913
2375
  async function build$1(options) {
1914
2376
  consola.start("RSS Generating ...");
1915
2377
  const { config } = options;
@@ -1942,7 +2404,7 @@ async function build$1(options) {
1942
2404
  feedLinks
1943
2405
  };
1944
2406
  const DOMAIN = siteConfig.url.slice(0, -1);
1945
- const files = await glob("pages/posts/**/*.md", { cwd: options.userRoot, absolute: true });
2407
+ const files = options.config.loaders?.length ? [...(await discoverPageFiles(options.userRoot, ["posts/**/*.md"])).values()] : await glob("pages/posts/**/*.md", { cwd: options.userRoot, absolute: true, onlyFiles: true });
1946
2408
  const posts = await getPosts({
1947
2409
  author,
1948
2410
  files,
@@ -1962,13 +2424,12 @@ async function getPosts(params, options) {
1962
2424
  const siteConfig = config.siteConfig;
1963
2425
  const lang = siteConfig.lang || "en";
1964
2426
  const { files, author, DOMAIN } = params;
1965
- const readFilePromises = files.map(async (i) => {
2427
+ const rawPosts = await pMap(files, async (i) => {
1966
2428
  const raw = await readFile(i, "utf-8");
1967
2429
  const { data, content, excerpt } = matter(raw, matterOptions);
1968
2430
  const frontmatter = { ...siteConfig.frontmatter, ...data };
1969
2431
  return { data: frontmatter, content, excerpt, path: i };
1970
- });
1971
- const rawPosts = await Promise.all(readFilePromises);
2432
+ }, { concurrency: 20 });
1972
2433
  const draftPosts = [];
1973
2434
  const filteredPosts = rawPosts.filter((p) => {
1974
2435
  const { data } = p;
@@ -1989,7 +2450,12 @@ async function getPosts(params, options) {
1989
2450
  consola.warn(`[rss] Skipped ${colors.yellow(String(draftPosts.length))} draft post(s):
1990
2451
  ${draftPosts.map((p) => ` ${colors.dim("-")} ${colors.dim(p)}`).join("\n")}`);
1991
2452
  }
2453
+ const gitTimestampCache = getGitTimestampCache(options);
1992
2454
  const posts = [];
2455
+ const siteUrl = `${DOMAIN}/`;
2456
+ const { outDir } = resolveBuildPaths(options);
2457
+ const extractImages = options.config.modules.rss.extractImagePathsFromHTML;
2458
+ const builtAssets = extractImages ? await readBuiltAssetUrls(options, outDir, siteUrl) : void 0;
1993
2459
  for (const rawPost of filteredPosts) {
1994
2460
  const { data, path } = rawPost;
1995
2461
  const content = stripEncryptedContent(rawPost.content);
@@ -1998,43 +2464,38 @@ ${draftPosts.map((p) => ` ${colors.dim("-")} ${colors.dim(p)}`).join("\n")}`);
1998
2464
  const manualExcerpt = tObject(data.excerpt, lang);
1999
2465
  const summaryLength = siteConfig.excerpt?.length || 200;
2000
2466
  if (!data.date)
2001
- data.date = await getCreatedTime(path);
2467
+ data.date = await getCreatedTime(path, gitTimestampCache);
2002
2468
  if (siteConfig.lastUpdated) {
2003
2469
  if (!data.updated)
2004
- data.updated = await getUpdatedTime(path);
2470
+ data.updated = await getUpdatedTime(path, gitTimestampCache);
2005
2471
  }
2006
2472
  const fullText = options.config.modules.rss.fullText;
2007
2473
  const rssContent = fullText ? content : excerpt || content.slice(0, 100);
2008
- const relativePath = relative$1(join(options.userRoot, "pages"), path);
2009
- const urlPath = relativePath.replace(/\\/g, "/").replace(/\.md$/, "");
2474
+ const relativePath = getPagePath(path, options.userRoot) || relative$1(join(options.userRoot, "pages"), path).replace(/\\/g, "/");
2475
+ const urlPath = pagePathToRoute(relativePath);
2010
2476
  const link = `${DOMAIN}/${urlPath}`;
2011
- const extractImages = options.config.modules.rss.extractImagePathsFromHTML;
2012
- let imageMap = /* @__PURE__ */ new Map();
2013
- if (extractImages) {
2014
- let htmlPath = resolve(options.userRoot, "dist", `${urlPath}.html`);
2015
- if (urlPath.endsWith("/index")) {
2016
- const withoutIndex = urlPath.slice(0, -6);
2017
- const alternativePath = resolve(options.userRoot, "dist", `${withoutIndex}.html`);
2018
- if (await fs.exists(alternativePath)) {
2019
- htmlPath = alternativePath;
2020
- }
2021
- }
2022
- imageMap = await extractImagePathsFromHTML(htmlPath, DOMAIN);
2023
- }
2024
- let html = markdown.render(rssContent);
2025
- html = html.replace(/src="([^"]+)"/g, (_fullMatch, src) => {
2026
- if (imageMap.has(src)) {
2027
- return `src="${imageMap.get(src)}"`;
2028
- }
2029
- if (src.startsWith("http://") || src.startsWith("https://")) {
2030
- return _fullMatch;
2031
- }
2032
- if (src.startsWith("/")) {
2033
- return `src="${DOMAIN}${src}"`;
2477
+ let legacyImages;
2478
+ if (extractImages && !builtAssets) {
2479
+ let htmlPath = resolve(outDir, `${urlPath}.html`);
2480
+ if (!await fs.pathExists(htmlPath) && relativePath.endsWith("/index.md"))
2481
+ htmlPath = resolve(outDir, urlPath, "index.html");
2482
+ legacyImages = await readLegacyImageUrls(htmlPath, siteUrl);
2483
+ }
2484
+ const html = rewriteSourceAttributes(markdown.render(rssContent), (src, isImage) => {
2485
+ if (!src || /^(?:\/\/|#|[a-z][\w+.-]*:)/i.test(src))
2486
+ return;
2487
+ if (src.startsWith("/"))
2488
+ return `${DOMAIN}${src}`;
2489
+ if (isImage) {
2490
+ const pathname = src.split(/[?#]/, 1)[0];
2491
+ const mapped = builtAssets ? findBuiltAsset(pathname, path, options.userRoot, builtAssets) : legacyImages?.get(pathname.replace(/^\.\//, ""));
2492
+ if (mapped)
2493
+ return mapped + src.slice(pathname.length);
2034
2494
  }
2035
- const postDirUrl = `${DOMAIN}/${urlPath.split("/").slice(0, -1).join("/")}`;
2495
+ const postDir = relativePath.split("/").slice(0, -1).join("/");
2496
+ const postDirUrl = postDir ? `${DOMAIN}/${postDir}` : DOMAIN;
2036
2497
  const cleanSrc = src.startsWith("./") ? src.slice(2) : src;
2037
- return `src="${postDirUrl}/${cleanSrc}"`;
2498
+ return `${postDirUrl}/${cleanSrc}`;
2038
2499
  });
2039
2500
  if (data.image?.startsWith("/"))
2040
2501
  data.image = DOMAIN + data.image;
@@ -2070,9 +2531,11 @@ ${draftPosts.map((p) => ` ${colors.dim("-")} ${colors.dim(p)}`).join("\n")}`);
2070
2531
  async function writeFeed(feedOptions, posts, options, feedNameMap) {
2071
2532
  const feed = new Feed(feedOptions);
2072
2533
  posts.forEach((item) => feed.addItem(item));
2073
- await fs.ensureDir(dirname(`./dist/${feedNameMap.atom}`));
2074
- const path = resolve(options.userRoot, "./dist");
2075
- const publicFolder = resolve(options.userRoot, "public");
2534
+ const { outDir: distDir, publicDir: publicFolder } = resolveBuildPaths(options);
2535
+ await fs.ensureDir(distDir);
2536
+ if (publicFolder !== false)
2537
+ await fs.ensureDir(publicFolder);
2538
+ const outLabel = basename(distDir) || "dist";
2076
2539
  const { config } = options;
2077
2540
  const siteConfig = config.siteConfig;
2078
2541
  const now = dayjs().format("YYYY-MM-DD HH:mm:ss zzz");
@@ -2084,33 +2547,38 @@ async function writeFeed(feedOptions, posts, options, feedNameMap) {
2084
2547
  const types = ["rss", "atom", "json"];
2085
2548
  for (const type of types) {
2086
2549
  let data = "";
2087
- const distFeedPath = `${path}/${feedNameMap[type]}`;
2550
+ const distFeedPath = `${distDir}/${feedNameMap[type]}`;
2088
2551
  if (type === "rss")
2089
2552
  data = feed.rss2();
2090
2553
  else if (type === "atom")
2091
2554
  data = feed.atom1();
2092
2555
  else if (type === "json")
2093
2556
  data = feed.json1();
2557
+ await fs.ensureDir(dirname(distFeedPath));
2094
2558
  await fs.writeFile(distFeedPath, data, "utf-8");
2095
2559
  consola.debug(`[${colors.cyan(type)}] dist: ${colors.dim(distFeedPath)}`);
2096
- tableData.push([colors.cyan(type), colors.yellow("dist"), colors.dim(distFeedPath)]);
2097
- const publicFeedPath = resolve(publicFolder, feedNameMap[type]);
2098
- const publicRelativeFile = join("public", feedNameMap[type]);
2099
- await fs.writeFile(publicFeedPath, data, "utf-8");
2100
- consola.debug(`[${colors.cyan(type)}] public: ${colors.dim(publicFeedPath)}`);
2101
- tableData.push(["", colors.green("public"), colors.dim(publicFeedPath)]);
2102
- try {
2103
- const gitignorePath = resolve(options.userRoot, ".gitignore");
2104
- const gitignore = await fs.readFile(gitignorePath, "utf-8");
2105
- const ignorePath = publicRelativeFile.replace(/\\/g, "/");
2106
- if (!gitignore.includes(ignorePath)) {
2107
- await fs.appendFile(gitignorePath, `
2560
+ tableData.push([colors.cyan(type), colors.yellow(outLabel), colors.dim(distFeedPath)]);
2561
+ if (publicFolder !== false) {
2562
+ const publicFeedPath = resolve(publicFolder, feedNameMap[type]);
2563
+ const publicRelativeFile = relative$1(options.userRoot, publicFeedPath).replace(/\\/g, "/");
2564
+ await fs.ensureDir(dirname(publicFeedPath));
2565
+ await fs.writeFile(publicFeedPath, data, "utf-8");
2566
+ consola.debug(`[${colors.cyan(type)}] public: ${colors.dim(publicFeedPath)}`);
2567
+ tableData.push(["", colors.green("public"), colors.dim(publicFeedPath)]);
2568
+ if (publicRelativeFile && !publicRelativeFile.startsWith("..")) {
2569
+ try {
2570
+ const gitignorePath = resolve(options.userRoot, ".gitignore");
2571
+ const gitignore = await fs.readFile(gitignorePath, "utf-8");
2572
+ if (!gitignore.includes(publicRelativeFile)) {
2573
+ await fs.appendFile(gitignorePath, `
2108
2574
  # valaxy rss
2109
- ${ignorePath}
2575
+ ${publicRelativeFile}
2110
2576
  `);
2111
- consola.success(`Add ${colors.dim(ignorePath)} to ${colors.dim(".gitignore")}`);
2577
+ consola.success(`Add ${colors.dim(publicRelativeFile)} to ${colors.dim(".gitignore")}`);
2578
+ }
2579
+ } catch {
2580
+ }
2112
2581
  }
2113
- } catch {
2114
2582
  }
2115
2583
  }
2116
2584
  console.log(table(tableData, {
@@ -2143,6 +2611,7 @@ const rssModule = defineValaxyModule({
2143
2611
  async ({ root }) => {
2144
2612
  setEnvProd();
2145
2613
  const options = await resolveOptions$2({ userRoot: root }, "build");
2614
+ await resolveEffectiveViteConfig(options, "build");
2146
2615
  await build$1(options);
2147
2616
  }
2148
2617
  );
@@ -3627,118 +4096,111 @@ export default new Map([${entries.join(",\n")}])`;
3627
4096
  };
3628
4097
  }
3629
4098
 
3630
- function foucGuardHtml(maxDuration) {
3631
- return [
3632
- `<style id="valaxy-fouc">body{margin:0;opacity:0!important}</style>`,
3633
- `<noscript><style>body{opacity:1!important}</style></noscript>`,
3634
- `<script>(${foucGuardScript.toString()})(${maxDuration})<\/script>`
3635
- ].join("");
3636
- }
3637
- function foucGuardScript(maxDuration) {
3638
- var done = 0;
3639
- var observer = new MutationObserver(check);
3640
- var timer = maxDuration ? setTimeout(reveal, maxDuration) : void 0;
3641
- function reveal() {
3642
- if (done) return;
3643
- done = 1;
3644
- observer.disconnect();
3645
- clearTimeout(timer);
3646
- document.removeEventListener("load", check, true);
3647
- removeEventListener("load", reveal);
3648
- var s = document.getElementById("valaxy-fouc");
3649
- if (s) s.remove();
4099
+ function resolveImage(src, source) {
4100
+ if (!src || /^(?:\/|#|[a-z][\w+.-]*:)/i.test(src))
4101
+ return;
4102
+ const [pathname] = src.split(/[?#]/);
4103
+ let filename = pathname;
4104
+ try {
4105
+ filename = decodeURIComponent(pathname);
4106
+ } catch {
3650
4107
  }
3651
- function check() {
3652
- if (!document.body) return;
3653
- var links = document.head.querySelectorAll('link[rel~="stylesheet"]');
3654
- for (var i = 0; i < links.length; i++) {
3655
- var link = links[i];
3656
- if (!link.disabled && !link.sheet) return;
3657
- }
3658
- reveal();
4108
+ if (isAbsolute(filename))
4109
+ return;
4110
+ const file = resolve$1(dirname$1(source), filename);
4111
+ if (/[?#]/.test(file))
4112
+ return;
4113
+ try {
4114
+ if (statSync(file, { throwIfNoEntry: false })?.isFile())
4115
+ return { file, suffix: src.slice(pathname.length) };
4116
+ } catch {
3659
4117
  }
3660
- observer.observe(document.documentElement, { childList: true });
3661
- observer.observe(document.head, {
3662
- childList: true,
3663
- subtree: true,
3664
- attributes: true,
3665
- attributeFilter: ["media", "rel", "disabled"]
3666
- });
3667
- document.addEventListener("load", check, true);
3668
- addEventListener("load", reveal);
3669
4118
  }
3670
-
3671
- async function mergeViteConfigs({ userRoot, themeRoot }, command) {
3672
- const configEnv = {
3673
- mode: "development",
3674
- command
3675
- };
3676
- let resolvedConfig = {};
3677
- const files = uniq$1([themeRoot, userRoot]).map((i) => join(i, "vite.config.ts"));
3678
- const loadViteConfigPromiseArr = files.map(async (file) => {
3679
- if (!await fs.exists(file))
3680
- return;
3681
- return loadConfigFromFile$1(configEnv, file);
4119
+ function collectImageEdits(html, source, importImage) {
4120
+ const edits = [];
4121
+ let tag = "";
4122
+ const parser = new Parser({
4123
+ onopentagname(name) {
4124
+ tag = name;
4125
+ },
4126
+ onattribute(name, src) {
4127
+ if (tag !== "img" || name !== "src")
4128
+ return;
4129
+ const image = resolveImage(src, source);
4130
+ if (!image)
4131
+ return;
4132
+ const { startIndex, endIndex } = parser;
4133
+ const asset = importImage(image.file, !!image.suffix);
4134
+ edits.push(`[${startIndex}, ${endIndex}, ${JSON.stringify(html.slice(startIndex, endIndex))}, ${asset}, ${JSON.stringify(image.suffix)}]`);
4135
+ }
3682
4136
  });
3683
- const viteConfigs = await Promise.all(loadViteConfigPromiseArr);
3684
- for (const viteConfig of viteConfigs) {
3685
- if (!viteConfig?.config)
3686
- continue;
3687
- resolvedConfig = mergeConfig(resolvedConfig, viteConfig.config);
4137
+ parser.end(html);
4138
+ return edits;
4139
+ }
4140
+ function createExcerptAssets() {
4141
+ let tree;
4142
+ const plugin = {
4143
+ name: "valaxy:excerpt-assets",
4144
+ transform(code, id) {
4145
+ if (id !== "\0vue-router/auto-routes" || !tree)
4146
+ return;
4147
+ const imports = /* @__PURE__ */ new Map();
4148
+ function importImage(file, forceFile) {
4149
+ const request = `${toAtFS(file)}?url${forceFile ? "&no-inline" : ""}`;
4150
+ const existing = imports.get(request);
4151
+ if (existing)
4152
+ return existing;
4153
+ const name = `__valaxy_excerpt_asset_${imports.size}`;
4154
+ imports.set(request, name);
4155
+ return name;
4156
+ }
4157
+ const entries = [];
4158
+ for (const route of tree) {
4159
+ const source = route.components.get("default");
4160
+ const { excerpt } = route.meta;
4161
+ if (typeof route.name !== "string" || !source?.endsWith(".md") || typeof excerpt !== "string")
4162
+ continue;
4163
+ const edits = collectImageEdits(excerpt, source, importImage);
4164
+ if (edits.length)
4165
+ entries.push(`[${JSON.stringify(route.name)}, [${edits.reverse().join(", ")}]]`);
4166
+ }
4167
+ if (!entries.length)
4168
+ return;
4169
+ const output = new MagicString(code);
4170
+ output.prepend(`${Array.from(imports, ([request, name]) => `import ${name} from ${JSON.stringify(request)}`).join("\n")}
4171
+ `);
4172
+ output.append(`
4173
+ {
4174
+ const editsByName = new Map([${entries.join(",\n")}])
4175
+ function updateExcerpts(records) {
4176
+ for (const route of records) {
4177
+ const edits = editsByName.get(route.name)
4178
+ let html = route.meta?.excerpt
4179
+ if (edits && typeof html === 'string') {
4180
+ for (const [start, end, original, url, suffix] of edits) {
4181
+ // A definePage() export can override the metadata supplied by the route tree.
4182
+ if (html.slice(start, end) !== original) continue
4183
+ const src = (suffix ? url.replace(/\\?no-inline$/, '') + suffix : url)
4184
+ .replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;')
4185
+ html = html.slice(0, start) + 'src="' + src + '"' + html.slice(end)
4186
+ }
4187
+ route.meta.excerpt = html
4188
+ }
4189
+ if (route.children) updateExcerpts(route.children)
4190
+ }
3688
4191
  }
3689
- return resolvedConfig;
4192
+ updateExcerpts(routes)
3690
4193
  }
3691
- async function getIndexHtml({ clientRoot, themeRoot, userRoot, config }, rawHtml) {
3692
- let main = rawHtml;
3693
- let head = "";
3694
- let body = "";
3695
- if (config.siteConfig.favicon)
3696
- head += `<link rel="icon" href="${config.siteConfig.favicon}">`;
3697
- const roots = [userRoot, themeRoot];
3698
- if (config.siteConfig.mode === "auto") {
3699
- head += `
3700
- <script>
3701
- ;(function () {
3702
- const prefersDark =
3703
- window.matchMedia &&
3704
- window.matchMedia('(prefers-color-scheme: dark)').matches
3705
- const setting = localStorage.getItem('vueuse-color-scheme') || 'auto'
3706
- if (setting === 'dark' || (prefersDark && setting !== 'light'))
3707
- document.documentElement.classList.toggle('dark', true)
3708
- })()
3709
- <\/script>
3710
- `;
3711
- head += `<style type="text/css">
3712
- :root { color-scheme: light dark; --va-c-bg: #fff; }
3713
- html.dark { --va-c-bg: #000; }
3714
- html { background-color: var(--va-c-bg); }
3715
- </style>`;
3716
- }
3717
- const foucGuard = config.build?.foucGuard ?? {};
3718
- const foucEnabled = foucGuard.enabled ?? true;
3719
- const foucMaxDuration = foucGuard.maxDuration ?? 5e3;
3720
- if (foucEnabled)
3721
- head += foucGuardHtml(foucMaxDuration);
3722
- if (config.siteConfig.lang) {
3723
- head += `
3724
- <script>
3725
- const locale = localStorage.getItem('valaxy-locale') || '${config.siteConfig.lang}';
3726
- document.documentElement.setAttribute('lang', locale);
3727
- <\/script>
3728
- `;
3729
- }
3730
- for (const root of roots) {
3731
- const path = join(root, "index.html");
3732
- if (!fs.existsSync(path))
3733
- continue;
3734
- const indexHtml = await fs.readFile(path, "utf-8");
3735
- head += `
3736
- ${(indexHtml.match(/<head>([\s\S]*?)<\/head>/i)?.[1] || "").trim()}`;
3737
- body += `
3738
- ${(indexHtml.match(/<body>([\s\S]*?)<\/body>/i)?.[1] || "").trim()}`;
3739
- }
3740
- main = main.replace("__ENTRY__", toAtFS(join(clientRoot, "main.ts"))).replace("<!-- head -->", head).replace("<!-- body -->", body);
3741
- return main;
4194
+ `);
4195
+ return { code: output.toString(), map: output.generateMap({ hires: true }) };
4196
+ }
4197
+ };
4198
+ return {
4199
+ setRoutes(root) {
4200
+ tree = root;
4201
+ },
4202
+ plugin
4203
+ };
3742
4204
  }
3743
4205
 
3744
4206
  const DEVTOOLS_SEARCH_SHORTCUT_GUARD = `window.addEventListener('keydown', function (event) {
@@ -3833,13 +4295,17 @@ function createConfigPlugin(options) {
3833
4295
  const valaxyDefine = getDefine();
3834
4296
  const userDefine = config.define || {};
3835
4297
  const mergedDefine = { ...valaxyDefine, ...userDefine };
4298
+ const resolvedPublicDir = resolvePublicDir(
4299
+ options.userRoot,
4300
+ config.publicDir !== void 0 ? config.publicDir : options.publicDir !== void 0 ? options.publicDir : options.config.vite?.publicDir
4301
+ );
3836
4302
  const injection = {
3837
4303
  // root: options.userRoot,
3838
4304
  // can not transform valaxy/client/*.ts when use userRoot
3839
4305
  root: options.clientRoot,
3840
4306
  // cacheDir: join(options.userRoot, 'node_modules/.vite'),
3841
4307
  cacheDir: join(options.userRoot, "node_modules/.valaxy/cache"),
3842
- publicDir: join(options.userRoot, "public"),
4308
+ publicDir: resolvedPublicDir,
3843
4309
  define: mergedDefine,
3844
4310
  resolve: {
3845
4311
  alias: await getAlias(options),
@@ -4484,7 +4950,7 @@ The language '${lang}' is not loaded, falling back to '${defaultLang}' for synta
4484
4950
  };
4485
4951
  const restoreMustache = (s) => {
4486
4952
  mustaches.forEach((marker, match) => {
4487
- s = s.replaceAll(marker, match);
4953
+ s = s.replaceAll(marker, () => match);
4488
4954
  });
4489
4955
  return s;
4490
4956
  };
@@ -4878,7 +5344,7 @@ function imagePlugin(md) {
4878
5344
  if (url && !EXTERNAL_URL_RE.test(url)) {
4879
5345
  if (!/^\.?\//.test(url))
4880
5346
  url = `./${url}`;
4881
- token.attrSet("src", decodeURIComponent(url));
5347
+ token.attrSet("src", safeDecodeURIComponent(url));
4882
5348
  }
4883
5349
  return imageRule(tokens, idx, options, env, self);
4884
5350
  };
@@ -4928,13 +5394,13 @@ function linkPlugin(md, externalAttrs, resolveBase) {
4928
5394
  if (env.cleanUrls === "disabled" && !cleanUrl.endsWith(".html") && !cleanUrl.endsWith("/")) {
4929
5395
  cleanUrl += ".html";
4930
5396
  }
4931
- const parsed = new URL$1(url, "http://a.com");
4932
- url = cleanUrl + parsed.search + parsed.hash;
5397
+ const parsed = safeParseUrl(url, "http://a.com");
5398
+ url = cleanUrl + (parsed ? parsed.search + parsed.hash : "");
4933
5399
  }
4934
5400
  if (!url.startsWith("/") && !/^\.\//.test(url))
4935
5401
  url = `./${url}`;
4936
5402
  pushLink(url.replace(/\.html$/, ""), env);
4937
- return decodeURI(url);
5403
+ return safeDecodeURI(url);
4938
5404
  }
4939
5405
  function pushLink(link, env) {
4940
5406
  const links = env.links || (env.links = []);
@@ -5047,6 +5513,42 @@ function containerPlugin(md, containerOptions = {}) {
5047
5513
  });
5048
5514
  md.use(...createCodeGroup(md));
5049
5515
  }
5516
+ const NAMED_HTML_ENTITIES = /* @__PURE__ */ new Map([
5517
+ ["amp", "&"],
5518
+ ["AMP", "&"],
5519
+ ["lt", "<"],
5520
+ ["LT", "<"],
5521
+ ["gt", ">"],
5522
+ ["GT", ">"],
5523
+ ["quot", '"'],
5524
+ ["QUOT", '"'],
5525
+ ["apos", "'"],
5526
+ ["nbsp", "\xA0"],
5527
+ ["copy", "\xA9"],
5528
+ ["COPY", "\xA9"],
5529
+ ["reg", "\xAE"],
5530
+ ["REG", "\xAE"],
5531
+ ["trade", "\u2122"],
5532
+ ["mdash", "\u2014"],
5533
+ ["ndash", "\u2013"],
5534
+ ["hellip", "\u2026"]
5535
+ ]);
5536
+ function decodeHtmlEntities(input) {
5537
+ return input.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z][a-z0-9]+));/gi, (match, dec, hex, named) => {
5538
+ if (dec !== void 0 || hex !== void 0) {
5539
+ const code = Number.parseInt(dec ?? hex, dec !== void 0 ? 10 : 16);
5540
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
5541
+ return "\uFFFD";
5542
+ return String.fromCodePoint(code);
5543
+ }
5544
+ if (named) {
5545
+ const resolved = NAMED_HTML_ENTITIES.get(named);
5546
+ if (resolved !== void 0)
5547
+ return resolved;
5548
+ }
5549
+ return match;
5550
+ });
5551
+ }
5050
5552
  function createCodeGroup(md) {
5051
5553
  return [
5052
5554
  containerCompat,
@@ -5064,8 +5566,10 @@ function createCodeGroup(md) {
5064
5566
  isHtml
5065
5567
  );
5066
5568
  if (title) {
5569
+ const rawTitle = isHtml ? decodeHtmlEntities(title) : title;
5570
+ const escapedTitle = md.utils.escapeHtml(rawTitle);
5067
5571
  tabs += `<input type="radio" name="group-${idx}" id="tab-${i}" ${checked}/>`;
5068
- tabs += `<label data-title="${md.utils.escapeHtml(title)}" for="tab-${i}">${title}</label>`;
5572
+ tabs += `<label v-pre data-title="${escapedTitle}" for="tab-${i}">${escapedTitle}</label>`;
5069
5573
  if (checked && !isHtml)
5070
5574
  tokens[i].info += " active";
5071
5575
  checked = "";
@@ -5331,6 +5835,19 @@ function lineNumberPlugin(md, enable = false) {
5331
5835
  });
5332
5836
  }
5333
5837
 
5838
+ function statSnippetFile(src) {
5839
+ try {
5840
+ const stat = fs.statSync(src, { throwIfNoEntry: false });
5841
+ if (!stat)
5842
+ return "missing";
5843
+ return stat.isFile() ? "file" : "invalid";
5844
+ } catch (error) {
5845
+ const code = error.code;
5846
+ if (code === "ENOENT" || code === "ENOTDIR")
5847
+ return "missing";
5848
+ throw error;
5849
+ }
5850
+ }
5334
5851
  const rawPathRegexp = /^(.+?(?:\.([a-z0-9]+))?)(#[\w-]+)?(?: ?\{(\d+(?:[,-]\d+)*)? ?(\S+)?\})? ?(?:\[(.+)\])?$/;
5335
5852
  function rawPathToToken(rawPath) {
5336
5853
  const [
@@ -5433,13 +5950,24 @@ function snippetPlugin(md, srcDir = "") {
5433
5950
  return fence(...args);
5434
5951
  if (includes)
5435
5952
  includes.push(src);
5436
- const isAFile = fs.statSync(src).isFile();
5437
- if (!fs.existsSync(src) || !isAFile) {
5438
- token.content = isAFile ? `Code snippet path not found: ${src}` : `Invalid code snippet option`;
5953
+ const snippetStatus = statSnippetFile(src);
5954
+ if (snippetStatus !== "file") {
5955
+ token.content = snippetStatus === "missing" ? `Code snippet path not found: ${src}` : `Invalid code snippet option`;
5439
5956
  token.info = "";
5440
5957
  return fence(...args);
5441
5958
  }
5442
- let content = fs.readFileSync(src, "utf8");
5959
+ let content;
5960
+ try {
5961
+ content = fs.readFileSync(src, "utf8");
5962
+ } catch (error) {
5963
+ const code = error.code;
5964
+ if (code === "ENOENT" || code === "ENOTDIR") {
5965
+ token.content = `Code snippet path not found: ${src}`;
5966
+ token.info = "";
5967
+ return fence(...args);
5968
+ }
5969
+ throw error;
5970
+ }
5443
5971
  if (regionName) {
5444
5972
  const lines = content.split(/\r?\n/);
5445
5973
  const region = findRegion(lines, regionName);
@@ -6876,10 +7404,17 @@ function createTransformCodeBlock(options) {
6876
7404
  };
6877
7405
  }
6878
7406
 
7407
+ function isInsideDir(baseDir, targetPath) {
7408
+ const rel = path$1.relative(baseDir, targetPath);
7409
+ return rel !== ".." && !rel.startsWith("../") && !path$1.isAbsolute(rel);
7410
+ }
6879
7411
  function createScanDeadLinks(options) {
6880
7412
  const srcDir = path$1.resolve(options.userRoot, "pages");
6881
7413
  const { ignoreDeadLinks } = options.config.build;
6882
- const publicDir = options.config.vite?.publicDir || "public";
7414
+ const publicDir = resolvePublicDir(
7415
+ options.userRoot,
7416
+ options.publicDir !== void 0 ? options.publicDir : options.config.vite?.publicDir
7417
+ );
6883
7418
  return (code, context) => {
6884
7419
  const { id, fileInfo } = context;
6885
7420
  const { links = [] } = fileInfo || {};
@@ -6909,21 +7444,21 @@ function createScanDeadLinks(options) {
6909
7444
  });
6910
7445
  }
6911
7446
  if (links) {
6912
- const dir = path$1.dirname(file);
6913
7447
  for (let url of links) {
6914
- const { pathname } = new URL(url, "http://a.com");
6915
- if (!treatAsHtml(pathname))
7448
+ const parsed = safeParseUrl(url, "http://a.com");
7449
+ if (!parsed || !treatAsHtml(parsed.pathname))
6916
7450
  continue;
6917
7451
  url = url.replace(/[?#].*$/, "").replace(/\.(html|md)$/, "");
6918
7452
  if (url.endsWith("/"))
6919
7453
  url += `index`;
6920
- const resolved = decodeURIComponent(
7454
+ const resolved = safeDecodeURIComponent(
6921
7455
  slash$1(
6922
7456
  url.startsWith("/") ? url.slice(1) : path$1.normalize(path$1.join(path$1.dirname(logicalFile), url))
6923
7457
  )
6924
7458
  // /index => /
6925
7459
  ).replace(/(^|\/)index$/, "");
6926
- if (!routes.has(resolved) && !resolvePageFile(`${resolved}.vue`, options.userRoot) && !resolvePageFile(path$1.join(resolved, "index.vue"), options.userRoot) && !fs.existsSync(path$1.resolve(dir, publicDir, `${resolved}.html`)) && !shouldIgnoreDeadLink(url)) {
7460
+ const publicCandidate = publicDir ? path$1.resolve(publicDir, `${resolved}.html`) : null;
7461
+ if (!routes.has(resolved) && !resolvePageFile(`${resolved}.vue`, options.userRoot) && !resolvePageFile(path$1.join(resolved, "index.vue"), options.userRoot) && !(publicDir && publicCandidate && isInsideDir(publicDir, publicCandidate) && fs.existsSync(publicCandidate)) && !shouldIgnoreDeadLink(url)) {
6927
7462
  recordDeadLink(url);
6928
7463
  }
6929
7464
  }
@@ -6941,7 +7476,7 @@ function createTransformEncrypt(options) {
6941
7476
  let getValaxyDecryptTemplate = function(options2) {
6942
7477
  return [
6943
7478
  "<ClientOnly>",
6944
- `<ValaxyDecrypt :encrypted-content="${options2.encryptedContent}" hint="${options2.hint || ""}" />`,
7479
+ `<ValaxyDecrypt :encrypted-content="${options2.encryptedContent}" hint="${escapeHtml(options2.hint || "")}" />`,
6945
7480
  "</ClientOnly>"
6946
7481
  ].join("");
6947
7482
  };
@@ -6982,26 +7517,47 @@ function createTransformEncrypt(options) {
6982
7517
  }
6983
7518
  }
6984
7519
  if (password) {
6985
- const templateStart = code.indexOf("<template>");
6986
- const templateEnd = code.lastIndexOf("</template>");
6987
- const content = code.slice(templateStart + 10, templateEnd);
6988
- const encryptedContent = await encryptContent(content, {
6989
- password,
6990
- iv: encrypt.iv,
6991
- salt: encrypt.salt
6992
- });
6993
- frontmatter.encryptedContent = encryptedContent;
6994
- frontmatter.encrypt = true;
6995
- delete frontmatter.password;
6996
- const encryptedContentStr = "$encryptedContent";
6997
- code = code.replace(content, getValaxyDecryptTemplate({
6998
- encryptedContent: encryptedContentStr,
6999
- hint: frontmatter.password_hint
7000
- }));
7001
- const scriptSetupStart = code.lastIndexOf("<script setup>");
7002
- const scriptSetupEnd = code.lastIndexOf("<\/script>");
7003
- const scriptSetupContent = code.slice(scriptSetupStart + 14, scriptSetupEnd);
7004
- code = code.replace(scriptSetupContent, "");
7520
+ const { parse: parseSfc, parseCache } = await import('vue/compiler-sfc');
7521
+ const parsed = parseSfc(code, { filename: id, sourceMap: false });
7522
+ const templateLoc = parsed.descriptor.template ? { start: parsed.descriptor.template.loc.start.offset, end: parsed.descriptor.template.loc.end.offset } : null;
7523
+ const scriptSetupLoc = parsed.descriptor.scriptSetup ? { start: parsed.descriptor.scriptSetup.loc.start.offset, end: parsed.descriptor.scriptSetup.loc.end.offset } : null;
7524
+ for (const [key, entry] of parseCache) {
7525
+ if (entry === parsed) {
7526
+ parseCache.delete(key);
7527
+ break;
7528
+ }
7529
+ }
7530
+ const patches = [];
7531
+ if (templateLoc) {
7532
+ const content = code.slice(templateLoc.start, templateLoc.end);
7533
+ const encryptedContent = await encryptContent(content, {
7534
+ password,
7535
+ iv: encrypt.iv,
7536
+ salt: encrypt.salt
7537
+ });
7538
+ frontmatter.encryptedContent = encryptedContent;
7539
+ frontmatter.encrypt = true;
7540
+ delete frontmatter.password;
7541
+ patches.push({
7542
+ start: templateLoc.start,
7543
+ end: templateLoc.end,
7544
+ text: getValaxyDecryptTemplate({
7545
+ encryptedContent: "$encryptedContent",
7546
+ hint: frontmatter.password_hint
7547
+ })
7548
+ });
7549
+ } else {
7550
+ delete frontmatter.password;
7551
+ }
7552
+ if (scriptSetupLoc) {
7553
+ patches.push({
7554
+ start: scriptSetupLoc.start,
7555
+ end: scriptSetupLoc.end,
7556
+ text: ""
7557
+ });
7558
+ }
7559
+ for (const patch of patches.sort((a, b) => b.start - a.start))
7560
+ code = `${code.slice(0, patch.start)}${patch.text}${code.slice(patch.end)}`;
7005
7561
  }
7006
7562
  if (frontmatter.gallery_password) {
7007
7563
  const encryptedPhotos = await encryptContent(JSON.stringify(frontmatter.photos), {
@@ -7580,14 +8136,15 @@ const templateLocales = {
7580
8136
  })
7581
8137
  `
7582
8138
  ];
7583
- const languages = config.siteConfig.languages || ["zh-CN", "en"];
8139
+ const languages = [...new Set(config.siteConfig.languages || ["zh-CN", "en"])];
7584
8140
  roots.forEach((root, i) => {
7585
- languages.forEach((lang) => {
8141
+ languages.forEach((lang, langIndex) => {
7586
8142
  const langYml = `${root}/locales/${lang}.yml`;
7587
8143
  if (fs.existsSync(langYml) && fs.readFileSync(langYml, "utf-8")) {
7588
- const varName = lang.replace("-", "") + i;
8144
+ const varName = `locale_${i}_${langIndex}`;
8145
+ const langKey = JSON.stringify(lang);
7589
8146
  imports.unshift(`import ${varName} from "${toAtFS(langYml)}"`);
7590
- imports.push(`messages['${lang}'] = replaceArrMerge(${varName}, messages['${lang}'])`);
8147
+ imports.push(`messages[${langKey}] = replaceArrMerge(${varName}, messages[${langKey}])`);
7591
8148
  }
7592
8149
  });
7593
8150
  });
@@ -7754,6 +8311,7 @@ async function createValaxyPlugin(options, serverOptions = {}, state = Valaxy.st
7754
8311
  return reloadConfigAndEntries(valaxyConfig);
7755
8312
  }
7756
8313
  if (file.endsWith(".md")) {
8314
+ clearGitTimestampCache(getGitTimestampCache(options), file);
7757
8315
  const endCount = countPerformanceTime();
7758
8316
  const content = await read();
7759
8317
  const { code, pageData } = await markdownToVue(content, file);
@@ -7863,7 +8421,7 @@ function generateAutoExcerptMd(content, length) {
7863
8421
  return "";
7864
8422
  return cleaned.length > length ? `${cleaned.slice(0, length)}...` : cleaned;
7865
8423
  }
7866
- async function createRouterPlugin(valaxyApp, base, editorRoutes) {
8424
+ async function createRouterPlugin(valaxyApp, base, editorRoutes, excerptAssets) {
7867
8425
  const options = await createRouterOptions(valaxyApp, base);
7868
8426
  return VueRouter({
7869
8427
  ...options,
@@ -7878,12 +8436,14 @@ async function createRouterPlugin(valaxyApp, base, editorRoutes) {
7878
8436
  async beforeWriteFiles(root) {
7879
8437
  await options.beforeWriteFiles?.(root);
7880
8438
  await editorRoutes?.update(root);
8439
+ excerptAssets?.setRoutes(root);
7881
8440
  }
7882
8441
  });
7883
8442
  }
7884
8443
  async function createRouterOptions(valaxyApp, base, parseMatter = (source) => matter(source, matterOptions), onDispose) {
7885
8444
  const { options } = valaxyApp;
7886
8445
  const { roots, config: valaxyConfig } = options;
8446
+ clearGitTimestampCache(getGitTimestampCache(options));
7887
8447
  const mdIt = await createMarkdownRenderer(options, base, onDispose);
7888
8448
  let _lastFrontmatterRef = valaxyConfig.siteConfig.frontmatter;
7889
8449
  let _cachedFrontmatter = structuredClone(valaxyConfig.siteConfig.frontmatter);
@@ -7969,11 +8529,12 @@ async function createRouterOptions(valaxyApp, base, parseMatter = (source) => ma
7969
8529
  delete mdFm.gallery_password;
7970
8530
  delete mdFm.photos;
7971
8531
  }
8532
+ const gitTimestampCache = options.mode === "build" ? getGitTimestampCache(options) : void 0;
7972
8533
  if (!mdFm.date)
7973
- mdFm.date = new Date(await getCreatedTime(path));
8534
+ mdFm.date = new Date(await getCreatedTime(path, gitTimestampCache));
7974
8535
  if (lastUpdated) {
7975
8536
  if (!mdFm.updated)
7976
- mdFm.updated = new Date(await getUpdatedTime(path));
8537
+ mdFm.updated = new Date(await getUpdatedTime(path, gitTimestampCache));
7977
8538
  }
7978
8539
  if (mdFm.from) {
7979
8540
  if (Array.isArray(mdFm.from)) {
@@ -8150,6 +8711,7 @@ function createMemoryReleasePlugin(state, releaseThreshold = 1) {
8150
8711
  async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {}, expectedBuilds = 1) {
8151
8712
  const { options } = valaxyApp;
8152
8713
  const state = new StateManager();
8714
+ const excerptAssets = createExcerptAssets();
8153
8715
  const editorRoutes = options.mode === "dev" ? new EditorRoutes() : void 0;
8154
8716
  const { roots, config: valaxyConfig } = options;
8155
8717
  const markdownBase = createMarkdownBaseContext(viteConfig.base || valaxyConfig.vite?.base || "/");
@@ -8229,7 +8791,7 @@ async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {},
8229
8791
  vLogger.debug(` \u251C\u2500 plugin-vue: ${timers.vue()}`);
8230
8792
  return r;
8231
8793
  }),
8232
- createRouterPlugin(valaxyApp, markdownBase, editorRoutes).then((r) => {
8794
+ createRouterPlugin(valaxyApp, markdownBase, editorRoutes, excerptAssets).then((r) => {
8233
8795
  vLogger.debug(` \u251C\u2500 createRouterPlugin: ${timers.router()}`);
8234
8796
  return r;
8235
8797
  }),
@@ -8252,6 +8814,7 @@ async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {},
8252
8814
  ...editorRoutes ? [editorPlugin(options, editorRoutes)] : [],
8253
8815
  createCdnPlugin(options),
8254
8816
  createLlmsPlugin(options),
8817
+ valaxyConfig.modules?.rss?.extractImagePathsFromHTML && createRssAssetsPlugin(options),
8255
8818
  MarkdownPlugin,
8256
8819
  ValaxyPlugin,
8257
8820
  vuePlugin,
@@ -8261,6 +8824,7 @@ async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {},
8261
8824
  Unhead(),
8262
8825
  // https://router.vuejs.org/file-based-routing/
8263
8826
  RouterPlugin,
8827
+ excerptAssets.plugin,
8264
8828
  createLayoutsPlugin(options),
8265
8829
  // https://github.com/antfu/unplugin-vue-components
8266
8830
  Components({
@@ -8362,13 +8926,13 @@ async function renderPage(opts) {
8362
8926
  const stateScript = serializeState(result.initialState);
8363
8927
  let html = template;
8364
8928
  if (headPayload.htmlAttrs)
8365
- html = html.replace(/<html[^>]*>/, `<html ${headPayload.htmlAttrs}>`);
8929
+ html = html.replace(/<html[^>]*>/, () => `<html ${headPayload.htmlAttrs}>`);
8366
8930
  if (headPayload.bodyAttrs)
8367
- html = html.replace(/<body[^>]*>/, `<body ${headPayload.bodyAttrs}>`);
8931
+ html = html.replace(/<body[^>]*>/, () => `<body ${headPayload.bodyAttrs}>`);
8368
8932
  html = html.replace("</head>", () => `${preloadLinks}${headPayload.headTags}
8369
8933
  </head>`).replace(
8370
8934
  '<div id="app"></div>',
8371
- `${headPayload.bodyTagsOpen || ""}<div id="app">${result.html}</div>${stateScript}${headPayload.bodyTags || ""}`
8935
+ () => `${headPayload.bodyTagsOpen || ""}<div id="app">${result.html}</div>${stateScript}${headPayload.bodyTags || ""}`
8372
8936
  );
8373
8937
  if (result.teleports) {
8374
8938
  for (const [target, content] of Object.entries(result.teleports)) {
@@ -8378,12 +8942,12 @@ async function renderPage(opts) {
8378
8942
  throw new Error("Missing #valaxy-teleports container in the HTML template");
8379
8943
  html = html.replace(container, () => `<div id="valaxy-teleports">${content}</div>`);
8380
8944
  } else if (target === "head") {
8381
- html = html.replace("</head>", `${content}
8945
+ html = html.replace("</head>", () => `${content}
8382
8946
  </head>`);
8383
8947
  } else if (target === "body") {
8384
8948
  html = html.replace(/<body\b[^>]*>/, (match) => `${match}${content}`);
8385
8949
  } else {
8386
- html = html.replace("</body>", `${content}
8950
+ html = html.replace("</body>", () => `${content}
8387
8951
  </body>`);
8388
8952
  }
8389
8953
  }
@@ -8463,7 +9027,7 @@ function renderPreloadLinks(modules, manifest) {
8463
9027
  function serializeState(state) {
8464
9028
  if (!state || Object.keys(state).length === 0)
8465
9029
  return "";
8466
- const serialised = JSON.stringify(state).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/'/g, "\\u0027").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
9030
+ const serialised = JSON.stringify(state).replace(/\\/g, "\\\\").replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/'/g, "\\u0027").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
8467
9031
  return `<script>window.__INITIAL_STATE__='${serialised}'<\/script>`;
8468
9032
  }
8469
9033
  function decodePathSegment(segment) {
@@ -8499,7 +9063,7 @@ async function fileExists(file) {
8499
9063
  }
8500
9064
  async function writeTrailingSlashAliases(outDir, routes) {
8501
9065
  const outputs = new Set(routes.map(routeToFileName));
8502
- await Promise.all(routes.map(async (route) => {
9066
+ await pMap(routes, async (route) => {
8503
9067
  const alias = trailingSlashAlias(route);
8504
9068
  if (!alias || outputs.has(alias))
8505
9069
  return;
@@ -8509,7 +9073,7 @@ async function writeTrailingSlashAliases(outDir, routes) {
8509
9073
  return;
8510
9074
  await mkdir(dirname(to), { recursive: true });
8511
9075
  await copyFile(from, to);
8512
- }));
9076
+ }, { concurrency: 32 });
8513
9077
  }
8514
9078
 
8515
9079
  async function writeSitemap(outDir, siteUrl, pages) {
@@ -8544,7 +9108,7 @@ async function writeSitemap(outDir, siteUrl, pages) {
8544
9108
  const sitemap = [
8545
9109
  '<?xml version="1.0" encoding="UTF-8"?>',
8546
9110
  '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
8547
- ...[...urls].sort().map((url) => ` <url><loc>${escapeHtml(url)}</loc></url>`),
9111
+ ...[...urls].sort().map((url) => ` <url><loc>${escapeHtml$1(url)}</loc></url>`),
8548
9112
  "</urlset>",
8549
9113
  ""
8550
9114
  ].join("\n");
@@ -8592,14 +9156,20 @@ function getSsgSsrConfig() {
8592
9156
  }
8593
9157
  async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
8594
9158
  const { options } = valaxyApp;
8595
- const configOutDir = viteConfig.build?.outDir || "dist";
8596
- const outDir = isAbsolute$1(configOutDir) ? configOutDir : resolve(options.userRoot, configOutDir);
9159
+ const { viteConfig: effectiveClientViteConfig, outDir } = await resolveEffectiveViteConfig(
9160
+ options,
9161
+ "build",
9162
+ viteConfig,
9163
+ void 0,
9164
+ false
9165
+ );
9166
+ delete effectiveClientViteConfig.ssgOptions;
8597
9167
  const ssgTemp = resolve(outDir, ".vite-ssg-temp");
8598
9168
  let routePaths = [];
8599
9169
  let renderedPages;
8600
9170
  const defaultConfig = {
8601
9171
  ...defaultViteConfig,
8602
- plugins: await profileBuildPhase("plugins", () => ViteValaxyPlugins(valaxyApp, {}, viteConfig, 2)),
9172
+ plugins: await profileBuildPhase("plugins", () => ViteValaxyPlugins(valaxyApp, {}, effectiveClientViteConfig, 2)),
8603
9173
  // `ssr.noExternal` only affects the server build (step 2) — the client build
8604
9174
  // ignores it. See `getSsgSsrConfig` for why everything is bundled.
8605
9175
  ssr: getSsgSsrConfig(),
@@ -8610,17 +9180,26 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
8610
9180
  watch: null
8611
9181
  }
8612
9182
  };
8613
- const inlineConfig = mergeConfig(defaultConfig, viteConfig);
9183
+ const clientInlineConfig = mergeConfig(defaultConfig, effectiveClientViteConfig);
8614
9184
  try {
8615
9185
  consola.info("Building client bundle...");
8616
- await profileBuildPhase("client-bundle", () => build$3(mergeConfig(inlineConfig, {
9186
+ await profileBuildPhase("client-bundle", () => build$3(mergeConfig(clientInlineConfig, {
8617
9187
  build: {
8618
9188
  ssrManifest: true,
8619
9189
  outDir
8620
9190
  }
8621
9191
  })));
9192
+ const { viteConfig: effectiveServerViteConfig } = await resolveEffectiveViteConfig(
9193
+ options,
9194
+ "build",
9195
+ viteConfig,
9196
+ void 0,
9197
+ true
9198
+ );
9199
+ delete effectiveServerViteConfig.ssgOptions;
9200
+ const serverInlineConfig = mergeConfig(defaultConfig, effectiveServerViteConfig);
8622
9201
  consola.info("Building server bundle...");
8623
- await profileBuildPhase("server-bundle", () => build$3(mergeConfig(inlineConfig, {
9202
+ await profileBuildPhase("server-bundle", () => build$3(mergeConfig(serverInlineConfig, {
8624
9203
  build: {
8625
9204
  ssr: resolve(options.clientRoot, "entry-ssr.ts"),
8626
9205
  outDir: ssgTemp,
@@ -8686,10 +9265,17 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
8686
9265
  }
8687
9266
 
8688
9267
  async function build(valaxyApp, viteConfig = defaultViteConfig) {
8689
- const inlineConfig = mergeConfig(viteConfig, {
8690
- ...defaultViteConfig,
8691
- plugins: await ViteValaxyPlugins(valaxyApp, {}, viteConfig)
8692
- });
9268
+ const { viteConfig: resolvedViteConfig } = await resolveEffectiveViteConfig(
9269
+ valaxyApp.options,
9270
+ "build",
9271
+ viteConfig,
9272
+ void 0,
9273
+ false
9274
+ );
9275
+ const inlineConfig = mergeConfig(
9276
+ mergeConfig(defaultViteConfig, resolvedViteConfig),
9277
+ { plugins: await ViteValaxyPlugins(valaxyApp, {}, resolvedViteConfig) }
9278
+ );
8693
9279
  await build$3(inlineConfig);
8694
9280
  }
8695
9281
  async function postProcessForSSG(options) {
@@ -8698,7 +9284,7 @@ async function postProcessForSSG(options) {
8698
9284
  }
8699
9285
  async function generateClientRedirects(options) {
8700
9286
  consola.info("generate client redirects...");
8701
- const outputPath = resolve(options.userRoot, "dist");
9287
+ const { outDir: outputPath } = resolveBuildPaths(options);
8702
9288
  const redirectRules = collectRedirects(options.redirects);
8703
9289
  const task = redirectRules.map(async (rule) => {
8704
9290
  const fromPath = join(outputPath, `${rule.from}.html`);
@@ -9205,21 +9791,22 @@ async function execBuild({ ssg, root, output, log, siteUrl }) {
9205
9791
  valaxyApp,
9206
9792
  modules
9207
9793
  );
9208
- const valaxyViteConfig = mergeConfig(await mergeViteConfigs(options, "build"), options.config.vite || {});
9209
- const viteConfig = mergeConfig(
9210
- valaxyViteConfig,
9211
- {
9212
- // avoid load userRoot/vite.config.ts repeatedly
9213
- configFile: path.resolve(options.clientRoot, "vite.config.ts"),
9214
- build: {
9215
- // make out dir empty, https://vitejs.dev/config/#build-emptyoutdir
9216
- emptyOutDir: true,
9217
- outDir: path.resolve(options.userRoot, output)
9218
- },
9219
- logLevel: log
9220
- }
9221
- );
9222
9794
  await callHookWithLog("config:init", valaxyApp);
9795
+ const rawViteConfig = {
9796
+ build: {
9797
+ // make out dir empty, https://vitejs.dev/config/#build-emptyoutdir
9798
+ emptyOutDir: true,
9799
+ ...output !== void 0 ? { outDir: path.resolve(options.userRoot, output) } : {}
9800
+ },
9801
+ logLevel: log
9802
+ };
9803
+ const { viteConfig } = await resolveEffectiveViteConfig(
9804
+ options,
9805
+ "build",
9806
+ rawViteConfig,
9807
+ output,
9808
+ false
9809
+ );
9223
9810
  await profileBuildPhase("build-before", () => callHookWithLog("build:before", valaxyApp));
9224
9811
  await validateTaxonomyI18n(options);
9225
9812
  consola.box("\u{1F320} Start building...");
@@ -9250,7 +9837,6 @@ function registerBuildCommand(cli) {
9250
9837
  }).option("output", {
9251
9838
  alias: "o",
9252
9839
  type: "string",
9253
- default: "dist",
9254
9840
  describe: "output dir"
9255
9841
  }).option("log", {
9256
9842
  default: "warn",
@@ -9381,6 +9967,7 @@ function createContentService(app, settings = {}) {
9381
9967
  const options = await routerOptions;
9382
9968
  const routes = [];
9383
9969
  routerApp.options.redirects.length = 0;
9970
+ clearGitTimestampCache(getGitTimestampCache(routerApp.options));
9384
9971
  const context = createRoutesContext(resolveOptions$3({
9385
9972
  ...options,
9386
9973
  root: userRoot,
@@ -9508,6 +10095,16 @@ function createContentService(app, settings = {}) {
9508
10095
  add("route-collision", "error", `The route or alias ${key} is used by multiple pages.`, "Choose a unique route path or alias in your route hooks.");
9509
10096
  }
9510
10097
  }
10098
+ const isPost = page.routes.some((route) => route.path.startsWith("/posts/") || route.layout === "post");
10099
+ if (isPost && !page.draft && (data.description === void 0 || typeof data.description === "string" && !data.description.trim())) {
10100
+ add(
10101
+ "missing-description",
10102
+ "warning",
10103
+ "Post is missing a frontmatter description.",
10104
+ "Add a concise description in frontmatter for SEO, RSS, and social sharing.",
10105
+ data.description !== void 0 ? fieldLine("description") : 1
10106
+ );
10107
+ }
9511
10108
  try {
9512
10109
  const layoutNames = await resolveContentLayouts(app.options);
9513
10110
  for (const layout of new Set(page.routes.map((route) => route.layout))) {
@@ -10177,4 +10774,4 @@ async function run(argv = hideBin(process.argv), options = {}) {
10177
10774
  await cli.parseAsync();
10178
10775
  }
10179
10776
 
10180
- export { resolveValaxyConfig as $, ALL_ROUTE as A, isInstalledGlobally as B, isKatexEnabled as C, isKatexPluginNeeded as D, EXCERPT_SEPARATOR as E, isMathJaxEnabled as F, GLOBAL_STATE as G, isPath as H, loadAllContent as I, loadConfigFromFile as J, mergeValaxyConfig as K, mergeViteConfigs as L, postProcessForSSG as M, processValaxyOptions as N, registerDevCommand as O, PATHNAME_PROTOCOL_RE as P, resolveAddonsConfig as Q, resolveImportPath as R, StateManager as S, resolveImportUrl as T, resolveOptions$2 as U, ViteValaxyPlugins as V, resolveSiteConfig as W, resolveSiteConfigFromRoot as X, resolveThemeConfigFromRoot as Y, resolveThemeValaxyConfig as Z, resolveUserThemeConfig as _, createContentService as a, resolveValaxyConfigFromRoot as a0, run as a1, ssgBuild as a2, startValaxyDev as a3, toAtFS as a4, transformObject as a5, version as a6, build as b, createCli as c, createMemoryReleasePlugin as d, createServer as e, createValaxyNode as f, createValaxyPlugin as g, customElements as h, defaultSiteConfig as i, defaultValaxyConfig as j, defaultViteConfig as k, defineAddon as l, defineConfig as m, defineSiteConfig as n, defineTheme as o, defineValaxyAddon as p, defineValaxyConfig as q, defineValaxyTheme as r, desktopRuntimeVersion as s, encryptContent as t, execBuild as u, generateClientRedirects as v, getGitTimestamp as w, getIndexHtml as x, getServerInfoText as y, isExternal as z };
10777
+ export { resolveThemeValaxyConfig as $, ALL_ROUTE as A, getServerInfoText as B, isExternal as C, isInstalledGlobally as D, EXCERPT_SEPARATOR as E, isKatexEnabled as F, GLOBAL_STATE as G, isKatexPluginNeeded as H, isMathJaxEnabled as I, isPath as J, loadAllContent as K, loadConfigFromFile as L, mergeValaxyConfig as M, mergeViteConfigs as N, postProcessForSSG as O, PATHNAME_PROTOCOL_RE as P, processValaxyOptions as Q, registerDevCommand as R, StateManager as S, resolveAddonsConfig as T, resolveImportPath as U, ViteValaxyPlugins as V, resolveImportUrl as W, resolveOptions$2 as X, resolveSiteConfig as Y, resolveSiteConfigFromRoot as Z, resolveThemeConfigFromRoot as _, createCli as a, resolveUserThemeConfig as a0, resolveValaxyConfig as a1, resolveValaxyConfigFromRoot as a2, run as a3, ssgBuild as a4, startValaxyDev as a5, toAtFS as a6, transformObject as a7, version as a8, build as b, clearGitTimestampCache as c, createContentService as d, createMemoryReleasePlugin as e, createServer as f, createValaxyNode as g, createValaxyPlugin as h, customElements as i, defaultSiteConfig as j, defaultValaxyConfig as k, defaultViteConfig as l, defineAddon as m, defineConfig as n, defineSiteConfig as o, defineTheme as p, defineValaxyAddon as q, defineValaxyConfig as r, defineValaxyTheme as s, desktopRuntimeVersion as t, encryptContent as u, execBuild as v, generateClientRedirects as w, getGitTimestamp as x, getGitTimestampCache as y, getIndexHtml as z };