valaxy 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import path, { resolve, basename, dirname, relative as relative$1, join, isAbsolute as isAbsolute$1, parse, posix } from 'node:path';
2
- import process$1 from 'node:process';
1
+ import path, { resolve, basename, dirname, relative as relative$1, join, isAbsolute as isAbsolute$1, parse } from 'node:path';
2
+ import process from 'node:process';
3
3
  import yargs from 'yargs';
4
4
  import { hideBin } from 'yargs/helpers';
5
5
  import os from 'node:os';
@@ -10,20 +10,21 @@ import matter from 'gray-matter';
10
10
  import { glob, globSync } from 'tinyglobby';
11
11
  import * as yaml from 'js-yaml';
12
12
  import { dump, load, CORE_SCHEMA } from 'js-yaml';
13
- import { isFunction, ensurePrefix, slash as slash$2, uniq, ensureSuffix, isObject } from '@antfu/utils';
14
- import createDebug from 'debug';
15
- import path$1, { resolve as resolve$1, relative, isAbsolute, normalize, join as join$1, basename as basename$1, parse as parse$1, dirname as dirname$1 } from 'pathe';
13
+ import { isFunction, ensurePrefix, slash as slash$1, uniq, ensureSuffix, isObject } from '@antfu/utils';
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';
16
16
  import defu, { createDefu } from 'defu';
17
17
  import { mergeConfig, loadConfigFromFile as loadConfigFromFile$1, searchForWorkspaceRoot, build as build$3, createServer as createServer$1 } from 'vite';
18
18
  import { webcrypto, createHash } from 'node:crypto';
19
19
  import { options } from 'floating-vue';
20
20
  import { loadConfig } from 'define-config-ts';
21
21
  import ora from 'ora';
22
+ import { Buffer as Buffer$1 } from 'node:buffer';
22
23
  import spawn$1, { spawn } from 'cross-spawn';
23
24
  import { resolvePath } from 'mlly';
24
25
  import { resolveGlobal } from 'resolve-global';
25
26
  import { normalizeRepositoryUrl } from '@valaxyjs/utils';
26
- import { existsSync, readFileSync, promises, realpathSync, statSync } from 'node:fs';
27
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
27
28
  import { readFile, mkdir, writeFile, realpath, rm, stat } from 'node:fs/promises';
28
29
  import dayjs from 'dayjs';
29
30
  import { Feed } from 'feed';
@@ -37,19 +38,11 @@ import picomatch from 'picomatch';
37
38
  import chokidar from 'chokidar';
38
39
  import { createUnplugin } from 'unplugin';
39
40
  import { createFilter } from 'unplugin-utils';
40
- import { createDebug as createDebug$1 } from 'obug';
41
+ import { createDebug } from 'obug';
41
42
  import MagicString from 'magic-string';
42
- import { Buffer as Buffer$1 } from 'node:buffer';
43
43
  import pMap from 'p-map';
44
44
  import pascalCase$1 from 'pascalcase';
45
- import { isArray, isString, isBoolean, assign, isEmptyObject, isNumber, generateCodeFrame } from '@intlify/shared';
46
- import { generateJSON, generateYAML, generateJavaScript, generateTypescript } from '@intlify/bundle-utils';
47
- import { createFilter as createFilter$1 } from '@rollup/pluginutils';
48
- import { parse as parse$2, babelParse } from 'vue/compiler-sfc';
49
- import pc from 'picocolors';
50
- import eslintUitls from '@eslint-community/eslint-utils';
51
- import { transformVTDirective } from '@intlify/vue-i18n-extensions';
52
- import { analyze } from '@typescript-eslint/scope-manager';
45
+ import VueI18n from '@intlify/unplugin-vue-i18n/vite';
53
46
  import MiniSearch from 'minisearch';
54
47
  import { transformerNotationDiff, transformerNotationFocus, transformerNotationHighlight, transformerNotationErrorLevel, transformerCompactLineOptions } from '@shikijs/transformers';
55
48
  import { LRUCache } from 'lru-cache';
@@ -72,7 +65,7 @@ import { convert } from 'html-to-text';
72
65
  import VueRouter from 'vue-router/vite';
73
66
  import generateSitemap from 'vite-ssg-sitemap';
74
67
  import { renderSSRHead } from '@unhead/vue/server';
75
- import { createRoutesContext, resolveOptions as resolveOptions$4 } from 'vue-router/unplugin';
68
+ import { createRoutesContext, resolveOptions as resolveOptions$2 } from 'vue-router/unplugin';
76
69
  import { execSync, exec } from 'node:child_process';
77
70
  import { intro, confirm, isCancel, cancel, select, outro } from '@clack/prompts';
78
71
  import net from 'node:net';
@@ -80,7 +73,7 @@ import * as readline from 'node:readline';
80
73
  import qrcode from 'qrcode';
81
74
  import ejs from 'ejs';
82
75
 
83
- const version = "1.1.0";
76
+ const version = "1.2.0";
84
77
 
85
78
  const GLOBAL_STATE = {
86
79
  valaxyApp: void 0,
@@ -294,7 +287,7 @@ const replaceArrMerge = createDefu((obj, key, value) => {
294
287
  async function loadConfigFromFile(name, options = {}) {
295
288
  const { config, configFile } = await loadConfig({
296
289
  name,
297
- cwd: options.cwd || process$1.cwd(),
290
+ cwd: options.cwd || process.cwd(),
298
291
  throwOnNotFound: false
299
292
  });
300
293
  let userConfig = config;
@@ -544,7 +537,7 @@ const mergeValaxyConfig = createDefu((obj, key, value) => {
544
537
  }
545
538
  });
546
539
  async function resolveValaxyConfig(options) {
547
- const configRoot = options.userRoot || process$1.cwd();
540
+ const configRoot = options.userRoot || process.cwd();
548
541
  const endCount = countPerformanceTime();
549
542
  const { config: userValaxyConfig, configFile } = await resolveValaxyConfigFromRoot(configRoot);
550
543
  const duration = endCount();
@@ -655,13 +648,6 @@ function getCryptoDeriveKey(keyMaterial, salt) {
655
648
  ["encrypt", "decrypt"]
656
649
  );
657
650
  }
658
- function bytesToBinaryString(bytes) {
659
- const CHUNK_SIZE = 32768;
660
- const chunks = [];
661
- for (let i = 0; i < bytes.length; i += CHUNK_SIZE)
662
- chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK_SIZE)));
663
- return chunks.join("");
664
- }
665
651
  async function encryptContent(content, options) {
666
652
  const { password, iv, salt } = options;
667
653
  const keyMaterial = await getKeyMaterial(password);
@@ -675,7 +661,7 @@ async function encryptContent(content, options) {
675
661
  key,
676
662
  enc.encode(content)
677
663
  );
678
- return bytesToBinaryString(new Uint8Array(ciphertextData));
664
+ return Buffer$1.from(ciphertextData).toString("base64");
679
665
  }
680
666
 
681
667
  function getGitTimestamp(file, type = "updated") {
@@ -719,7 +705,7 @@ async function resolveImportUrl(id) {
719
705
  return toAtFS(await resolveImportPath(id, true));
720
706
  }
721
707
  function toAtFS(path) {
722
- return `/@fs${ensurePrefix("/", slash$2(path))}`;
708
+ return `/@fs${ensurePrefix("/", slash$1(path))}`;
723
709
  }
724
710
  async function resolveImportPath(importName, ensure = false) {
725
711
  try {
@@ -756,7 +742,7 @@ async function getModuleRoot(name, entry) {
756
742
  }
757
743
  }
758
744
 
759
- async function parseAddons(addons, userRoot = process$1.cwd()) {
745
+ async function parseAddons(addons, userRoot = process.cwd()) {
760
746
  const spinner = ora(`Resolve ${colors.cyan("addons")} from ${colors.dim(userRoot)}`).start();
761
747
  const resolvers = {};
762
748
  const mergeResolver = (resolver) => {
@@ -794,7 +780,7 @@ async function parseAddons(addons, userRoot = process$1.cwd()) {
794
780
  return resolvedAddons;
795
781
  }
796
782
  async function readAddonModule(name, options = {}) {
797
- const root = await getAddonRoot(name, options.cwd || process$1.cwd());
783
+ const root = await getAddonRoot(name, options.cwd || process.cwd());
798
784
  const packageJSONPath = resolve$1(root, "./package.json");
799
785
  if (!await fs.exists(packageJSONPath)) {
800
786
  logger.error(`No addon named ${name} found`);
@@ -867,7 +853,7 @@ async function getThemeRoot(name, entry) {
867
853
  return await getModuleRoot(themeModule, entry);
868
854
  }
869
855
 
870
- const debug$8 = createDebug("valaxy:options");
856
+ const debug$6 = _debug("valaxy:options");
871
857
  async function processSiteConfig(options) {
872
858
  const { config, themeRoot, theme } = options;
873
859
  const siteConfig = config.siteConfig;
@@ -940,10 +926,10 @@ async function processValaxyOptions(valaxyOptions, valaxyConfig) {
940
926
  consola.debug(` \u2514\u2500 processSiteConfig: ${siteConfigTimer()}`);
941
927
  return valaxyOptions;
942
928
  }
943
- async function resolveOptions$3(options = { userRoot: process$1.cwd() }, mode = "dev") {
929
+ async function resolveOptions$1(options = { userRoot: process.cwd() }, mode = "dev") {
944
930
  const pkgRoot = dirname(await resolveImportPath("valaxy/package.json", true));
945
931
  const clientRoot = resolve$1(pkgRoot, "client");
946
- const userRoot = resolve$1(options.userRoot || process$1.cwd());
932
+ const userRoot = resolve$1(options.userRoot || process.cwd());
947
933
  consola.start(`Resolve ${colors.magenta("valaxy")} config ...`);
948
934
  const configTimer = countPerformanceTime();
949
935
  const [resolvedValaxy, resolvedSite, resolvedTheme, pages] = await Promise.all([
@@ -999,7 +985,7 @@ async function resolveOptions$3(options = { userRoot: process$1.cwd() }, mode =
999
985
  links: []
1000
986
  }
1001
987
  };
1002
- debug$8(valaxyOptions);
988
+ debug$6(valaxyOptions);
1003
989
  const themeValaxyConfig = await resolveThemeValaxyConfig(valaxyOptions);
1004
990
  const valaxyConfig = mergeValaxyConfig(userValaxyConfig, themeValaxyConfig);
1005
991
  const processTimer = countPerformanceTime();
@@ -1067,10 +1053,10 @@ const matterOptions = {
1067
1053
  };
1068
1054
 
1069
1055
  function isProd() {
1070
- return process$1.env.NODE_ENV === "production";
1056
+ return process.env.NODE_ENV === "production";
1071
1057
  }
1072
1058
  function setEnv(env = "development") {
1073
- process$1.env.NODE_ENV = env;
1059
+ process.env.NODE_ENV = env;
1074
1060
  consola.level = isProd() ? 2 : 3;
1075
1061
  logger.level = consola.level;
1076
1062
  }
@@ -1078,7 +1064,7 @@ function setEnvProd() {
1078
1064
  return setEnv("production");
1079
1065
  }
1080
1066
  function setTimezone(timezone) {
1081
- process$1.env.TZ = timezone;
1067
+ process.env.TZ = timezone;
1082
1068
  }
1083
1069
  async function isPagesDirExist(root) {
1084
1070
  const exist = await fs.exists(path.resolve(root, "pages"));
@@ -1214,7 +1200,7 @@ function registerFuseCommand(cli) {
1214
1200
  (args) => commonOptions(args).strict().help(),
1215
1201
  async ({ root }) => {
1216
1202
  setEnvProd();
1217
- const options = await resolveOptions$3({ userRoot: root }, "build");
1203
+ const options = await resolveOptions$1({ userRoot: root }, "build");
1218
1204
  await execFuse(options);
1219
1205
  }
1220
1206
  );
@@ -1462,7 +1448,7 @@ const llmsModule = defineValaxyModule({
1462
1448
  (args) => commonOptions(args).strict().help(),
1463
1449
  async ({ root }) => {
1464
1450
  setEnvProd();
1465
- const options = await resolveOptions$3({ userRoot: root }, "build");
1451
+ const options = await resolveOptions$1({ userRoot: root }, "build");
1466
1452
  await build$2(options);
1467
1453
  }
1468
1454
  );
@@ -1475,11 +1461,21 @@ const llmsModule = defineValaxyModule({
1475
1461
  }
1476
1462
  });
1477
1463
 
1464
+ async function statIfExists(file) {
1465
+ try {
1466
+ return await fs.stat(file);
1467
+ } catch (e) {
1468
+ const code = e.code;
1469
+ if (code === "ENOENT" || code === "ENOTDIR")
1470
+ return void 0;
1471
+ throw e;
1472
+ }
1473
+ }
1478
1474
  async function getCreatedTime(file) {
1479
- return await getGitTimestamp(file, "created") || (await fs.stat(file)).ctime;
1475
+ return await getGitTimestamp(file, "created") || (await statIfExists(file))?.ctime || Date.now();
1480
1476
  }
1481
1477
  async function getUpdatedTime(file) {
1482
- return await getGitTimestamp(file, "updated") || (await fs.stat(file)).mtime;
1478
+ return await getGitTimestamp(file, "updated") || (await statIfExists(file))?.mtime || Date.now();
1483
1479
  }
1484
1480
 
1485
1481
  const markdown = createMarkdownExit({
@@ -1742,7 +1738,7 @@ const rssModule = defineValaxyModule({
1742
1738
  (args) => commonOptions(args).strict().help(),
1743
1739
  async ({ root }) => {
1744
1740
  setEnvProd();
1745
- const options = await resolveOptions$3({ userRoot: root }, "build");
1741
+ const options = await resolveOptions$1({ userRoot: root }, "build");
1746
1742
  await build$1(options);
1747
1743
  }
1748
1744
  );
@@ -2047,7 +2043,7 @@ function toArray(array) {
2047
2043
  function notNullish(v) {
2048
2044
  return v != null;
2049
2045
  }
2050
- function slash$1(str) {
2046
+ function slash(str) {
2051
2047
  return str.replace(/\\/g, "/");
2052
2048
  }
2053
2049
  function throttle$1(delay, callback, options) {
@@ -2090,7 +2086,7 @@ function throttle(...args) {
2090
2086
  return throttle$1(...args);
2091
2087
  }
2092
2088
  const DISABLE_COMMENT = "/* unplugin-vue-components disabled */";
2093
- Boolean(process$1.env.SSR || process$1.env.SSG || process$1.env.VITE_SSR || process$1.env.VITE_SSG);
2089
+ Boolean(process.env.SSR || process.env.SSG || process.env.VITE_SSR || process.env.VITE_SSG);
2094
2090
  function pascalCase(str) {
2095
2091
  return capitalize(camelCase(str));
2096
2092
  }
@@ -2121,7 +2117,7 @@ function isEmpty(value) {
2121
2117
  function matchGlobs(filepath, globs) {
2122
2118
  for (const glob of globs) {
2123
2119
  const isNegated = glob[0] === "!";
2124
- if (picomatch(isNegated ? glob.slice(1) : glob)(slash$1(filepath))) return !isNegated;
2120
+ if (picomatch(isNegated ? glob.slice(1) : glob)(slash(filepath))) return !isNegated;
2125
2121
  }
2126
2122
  return false;
2127
2123
  }
@@ -2159,7 +2155,7 @@ function stringifyComponentImport({ as: name, from: path, name: importName, side
2159
2155
  }
2160
2156
  function getNameFromFilePath(filePath, options) {
2161
2157
  const { resolvedDirs, directoryAsNamespace, globalNamespaces, collapseSamePrefixes, root } = options;
2162
- const parsedFilePath = parse(slash$1(filePath));
2158
+ const parsedFilePath = parse(slash(filePath));
2163
2159
  let strippedPath = "";
2164
2160
  for (const dir of resolvedDirs) if (parsedFilePath.dir.startsWith(dir)) {
2165
2161
  strippedPath = parsedFilePath.dir.slice(dir.length);
@@ -2264,7 +2260,7 @@ function parseDeclaration(code) {
2264
2260
  function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
2265
2261
  if (!name) return void 0;
2266
2262
  path = getTransformedPath(path, importPathTransform);
2267
- return [name, `typeof import('${slash$1(isAbsolute$1(path) ? `./${relative$1(dirname(filepath), path)}` : path)}')['${importName || "default"}']`];
2263
+ return [name, `typeof import('${slash(isAbsolute$1(path) ? `./${relative$1(dirname(filepath), path)}` : path)}')['${importName || "default"}']`];
2268
2264
  }
2269
2265
  function stringifyComponentsInfo(filepath, components, importPathTransform) {
2270
2266
  return Object.fromEntries(components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(notNullish));
@@ -2353,9 +2349,9 @@ async function writeComponentsJson(ctx, _removeUnused = false) {
2353
2349
  })), ...resolveTypeImports(ctx.options.types)];
2354
2350
  await writeFile$1(ctx.dumpComponentsInfoPath, JSON.stringify(components, null, 2));
2355
2351
  }
2356
- const debug$4$1 = createDebug$1("unplugin-vue-components:glob");
2352
+ const debug$4 = createDebug("unplugin-vue-components:glob");
2357
2353
  function searchComponents(ctx) {
2358
- debug$4$1(`started with: [${ctx.options.globs.join(", ")}]`);
2354
+ debug$4(`started with: [${ctx.options.globs.join(", ")}]`);
2359
2355
  const root = ctx.root;
2360
2356
  const files = globSync(ctx.options.globs, {
2361
2357
  ignore: ctx.options.globsExclude,
@@ -2365,7 +2361,7 @@ function searchComponents(ctx) {
2365
2361
  expandDirectories: false
2366
2362
  });
2367
2363
  if (!files.length && !ctx.options.resolvers?.length) console.warn("[unplugin-vue-components] no components found");
2368
- debug$4$1(`${files.length} components found.`);
2364
+ debug$4(`${files.length} components found.`);
2369
2365
  ctx.addComponents(files);
2370
2366
  }
2371
2367
  const defaultOptions = {
@@ -2394,9 +2390,9 @@ function normalizeResolvers(resolvers) {
2394
2390
  }
2395
2391
  function resolveGlobsExclude(root, glob2) {
2396
2392
  const excludeReg = /^!/;
2397
- return slash$1(`${excludeReg.test(glob2) ? "!" : ""}${resolve(root, glob2.replace(excludeReg, ""))}`);
2393
+ return slash(`${excludeReg.test(glob2) ? "!" : ""}${resolve(root, glob2.replace(excludeReg, ""))}`);
2398
2394
  }
2399
- function resolveOptions$2(options, root) {
2395
+ function resolveOptions(options, root) {
2400
2396
  const resolved = Object.assign({}, defaultOptions, options);
2401
2397
  resolved.resolvers = normalizeResolvers(resolved.resolvers);
2402
2398
  resolved.extensions = toArray(resolved.extensions);
@@ -2414,7 +2410,7 @@ function resolveOptions$2(options, root) {
2414
2410
  prefix = "!";
2415
2411
  i = i.slice(1);
2416
2412
  }
2417
- return resolved.deep ? prefix + escapeSpecialChars(slash$1(join(i, `**/*.${extsGlob}`))) : prefix + escapeSpecialChars(slash$1(join(i, `*.${extsGlob}`)));
2413
+ return resolved.deep ? prefix + escapeSpecialChars(slash(join(i, `**/*.${extsGlob}`))) : prefix + escapeSpecialChars(slash(join(i, `*.${extsGlob}`)));
2418
2414
  });
2419
2415
  if (!resolved.extensions.length) throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
2420
2416
  }
@@ -2431,7 +2427,7 @@ function resolveOptions$2(options, root) {
2431
2427
  resolved.directives ??= resolved.resolvers.some((i) => i.type === "directive");
2432
2428
  return resolved;
2433
2429
  }
2434
- const debug$3$1 = createDebug$1("unplugin-vue-components:transform:component");
2430
+ const debug$3 = createDebug("unplugin-vue-components:transform:component");
2435
2431
  function resolveVue3$1(code, s, transformerUserResolveFunctions) {
2436
2432
  const results = [];
2437
2433
  for (const match of code.matchAll(/_?resolveComponent\d*\("(.+?)"\)/g)) {
@@ -2452,7 +2448,7 @@ async function transformComponent(code, s, ctx, sfcPath) {
2452
2448
  let no = 0;
2453
2449
  const results = resolveVue3$1(code, s, ctx.options.transformerUserResolveFunctions);
2454
2450
  for (const { rawName, replace } of results) {
2455
- debug$3$1(`| ${rawName}`);
2451
+ debug$3(`| ${rawName}`);
2456
2452
  const name = pascalCase(rawName);
2457
2453
  ctx.updateUsageMap(sfcPath, [name]);
2458
2454
  const component = await ctx.findComponent(name, "component", [sfcPath]);
@@ -2467,9 +2463,9 @@ async function transformComponent(code, s, ctx, sfcPath) {
2467
2463
  replace(varName);
2468
2464
  }
2469
2465
  }
2470
- debug$3$1(`^ (${no})`);
2466
+ debug$3(`^ (${no})`);
2471
2467
  }
2472
- const debug$2$1 = createDebug$1("unplugin-vue-components:transform:directive");
2468
+ const debug$2$1 = createDebug("unplugin-vue-components:transform:directive");
2473
2469
  async function transformDirective(code, s, ctx, sfcPath) {
2474
2470
  let no = 0;
2475
2471
  const results = resolveVue3(code, s, ctx.options.transformerUserResolveFunctions);
@@ -2506,12 +2502,12 @@ function resolveVue3(code, s, transformerUserResolveFunctions) {
2506
2502
  }
2507
2503
  return results;
2508
2504
  }
2509
- const debug$1$2 = createDebug$1("unplugin-vue-components:transformer");
2505
+ const debug$1$1 = createDebug("unplugin-vue-components:transformer");
2510
2506
  function transformer(ctx) {
2511
2507
  return async (code, id, path) => {
2512
2508
  ctx.searchGlob();
2513
2509
  const sfcPath = ctx.normalizePath(path);
2514
- debug$1$2(sfcPath);
2510
+ debug$1$1(sfcPath);
2515
2511
  const s = new MagicString(code);
2516
2512
  await transformComponent(code, s, ctx, sfcPath);
2517
2513
  if (ctx.options.directives) await transformDirective(code, s, ctx, sfcPath);
@@ -2525,12 +2521,12 @@ function transformer(ctx) {
2525
2521
  return result;
2526
2522
  };
2527
2523
  }
2528
- const debug$7 = {
2529
- components: createDebug$1("unplugin-vue-components:context:components"),
2530
- search: createDebug$1("unplugin-vue-components:context:search"),
2531
- hmr: createDebug$1("unplugin-vue-components:context:hmr"),
2532
- declaration: createDebug$1("unplugin-vue-components:declaration"),
2533
- env: createDebug$1("unplugin-vue-components:env")
2524
+ const debug$5 = {
2525
+ components: createDebug("unplugin-vue-components:context:components"),
2526
+ search: createDebug("unplugin-vue-components:context:search"),
2527
+ hmr: createDebug("unplugin-vue-components:context:hmr"),
2528
+ declaration: createDebug("unplugin-vue-components:declaration"),
2529
+ env: createDebug("unplugin-vue-components:env")
2534
2530
  };
2535
2531
  var Context = class {
2536
2532
  rawOptions;
@@ -2543,13 +2539,13 @@ var Context = class {
2543
2539
  _directiveCustomMap = {};
2544
2540
  _removeUnused = false;
2545
2541
  _server;
2546
- root = process$1.cwd();
2542
+ root = process.cwd();
2547
2543
  sourcemap = true;
2548
2544
  alias = {};
2549
2545
  dumpComponentsInfoPath;
2550
2546
  constructor(rawOptions) {
2551
2547
  this.rawOptions = rawOptions;
2552
- this.options = resolveOptions$2(rawOptions, this.root);
2548
+ this.options = resolveOptions(rawOptions, this.root);
2553
2549
  this.sourcemap = rawOptions.sourcemap ?? true;
2554
2550
  this.generateDeclaration = throttle(500, this._generateDeclaration.bind(this), { noLeading: false });
2555
2551
  this._removeUnused = this.options.syncMode !== "append";
@@ -2562,9 +2558,9 @@ var Context = class {
2562
2558
  }
2563
2559
  setRoot(root) {
2564
2560
  if (this.root === root) return;
2565
- debug$7.env("root", root);
2561
+ debug$5.env("root", root);
2566
2562
  this.root = root;
2567
- this.options = resolveOptions$2(this.rawOptions, this.root);
2563
+ this.options = resolveOptions(this.rawOptions, this.root);
2568
2564
  }
2569
2565
  transform(code, id) {
2570
2566
  const { path, query } = parseId(id);
@@ -2581,13 +2577,13 @@ var Context = class {
2581
2577
  this._removeUnused = this.options.syncMode === "overwrite";
2582
2578
  watcher.on("unlink", (path) => {
2583
2579
  if (!matchGlobs(path, globs)) return;
2584
- path = slash$1(path);
2580
+ path = slash(path);
2585
2581
  this.removeComponents(path);
2586
2582
  this.onUpdate(path);
2587
2583
  });
2588
2584
  watcher.on("add", (path) => {
2589
2585
  if (!matchGlobs(path, globs)) return;
2590
- path = slash$1(path);
2586
+ path = slash(path);
2591
2587
  this.addComponents(path);
2592
2588
  this.onUpdate(path);
2593
2589
  });
@@ -2600,13 +2596,13 @@ var Context = class {
2600
2596
  this._removeUnused = this.options.syncMode === "overwrite";
2601
2597
  watcher.on("unlink", (path) => {
2602
2598
  if (!matchGlobs(path, globs)) return;
2603
- path = slash$1(path);
2599
+ path = slash(path);
2604
2600
  this.removeComponents(path);
2605
2601
  emitUpdate(path, "unlink");
2606
2602
  });
2607
2603
  watcher.on("add", (path) => {
2608
2604
  if (!matchGlobs(path, globs)) return;
2609
- path = slash$1(path);
2605
+ path = slash(path);
2610
2606
  this.addComponents(path);
2611
2607
  emitUpdate(path, "add");
2612
2608
  });
@@ -2623,7 +2619,7 @@ var Context = class {
2623
2619
  });
2624
2620
  }
2625
2621
  addComponents(paths) {
2626
- debug$7.components("add", paths);
2622
+ debug$5.components("add", paths);
2627
2623
  const size = this._componentPaths.size;
2628
2624
  toArray(paths).forEach((p) => this._componentPaths.add(p));
2629
2625
  if (this._componentPaths.size !== size) {
@@ -2639,7 +2635,7 @@ var Context = class {
2639
2635
  if (info.as) this._directiveCustomMap[info.as] = info;
2640
2636
  }
2641
2637
  removeComponents(paths) {
2642
- debug$7.components("remove", paths);
2638
+ debug$5.components("remove", paths);
2643
2639
  const size = this._componentPaths.size;
2644
2640
  toArray(paths).forEach((p) => this._componentPaths.delete(p));
2645
2641
  if (this._componentPaths.size !== size) {
@@ -2660,7 +2656,7 @@ var Context = class {
2660
2656
  const name = pascalCase(getNameFromFilePath(path, this.options));
2661
2657
  Object.entries(this._componentUsageMap).forEach(([key, values]) => {
2662
2658
  if (values.has(name)) {
2663
- const r = `/${slash$1(relative$1(this.root, key))}`;
2659
+ const r = `/${slash(relative$1(this.root, key))}`;
2664
2660
  payload.updates.push({
2665
2661
  acceptedPath: r,
2666
2662
  path: r,
@@ -2679,7 +2675,7 @@ var Context = class {
2679
2675
  const fileName = getNameFromFilePath(path, this.options);
2680
2676
  const name = this.options.prefix ? `${pascalCase(this.options.prefix)}${pascalCase(fileName)}` : pascalCase(fileName);
2681
2677
  if (isExclude(name, this.options.excludeNames)) {
2682
- debug$7.components("exclude", name);
2678
+ debug$5.components("exclude", name);
2683
2679
  return;
2684
2680
  }
2685
2681
  if (this._componentNameMap[name] && !this.options.allowOverrides) {
@@ -2716,8 +2712,8 @@ var Context = class {
2716
2712
  return resolveAlias(path, this.viteConfig?.resolve?.alias || this.viteConfig?.alias || []);
2717
2713
  }
2718
2714
  relative(path) {
2719
- if (path.startsWith("/") && !path.startsWith(this.root)) return slash$1(path.slice(1));
2720
- return slash$1(relative$1(this.root, path));
2715
+ if (path.startsWith("/") && !path.startsWith(this.root)) return slash(path.slice(1));
2716
+ return slash(relative$1(this.root, path));
2721
2717
  }
2722
2718
  _searched = false;
2723
2719
  /**
@@ -2728,12 +2724,12 @@ var Context = class {
2728
2724
  searchGlob() {
2729
2725
  if (this._searched) return;
2730
2726
  searchComponents(this);
2731
- debug$7.search(this._componentNameMap);
2727
+ debug$5.search(this._componentNameMap);
2732
2728
  this._searched = true;
2733
2729
  }
2734
2730
  _generateDeclaration(removeUnused = this._removeUnused) {
2735
2731
  if (!this.options.dts) return;
2736
- debug$7.declaration("generating dts");
2732
+ debug$5.declaration("generating dts");
2737
2733
  return writeDeclaration(this, this.options.dts, removeUnused);
2738
2734
  }
2739
2735
  generateDeclaration(removeUnused = this._removeUnused) {
@@ -2741,7 +2737,7 @@ var Context = class {
2741
2737
  }
2742
2738
  _generateComponentsJson(removeUnused = this._removeUnused) {
2743
2739
  if (!Object.keys(this._componentNameMap).length) return;
2744
- debug$7.components("generating components-info");
2740
+ debug$5.components("generating components-info");
2745
2741
  return writeComponentsJson(this, removeUnused);
2746
2742
  }
2747
2743
  generateComponentsJson(removeUnused = this._removeUnused) {
@@ -2823,7 +2819,7 @@ var unplugin_default = createUnplugin((options = {}) => {
2823
2819
  path,
2824
2820
  type
2825
2821
  });
2826
- process$1.nextTick(() => {
2822
+ process.nextTick(() => {
2827
2823
  watcher.invalidate();
2828
2824
  });
2829
2825
  });
@@ -2844,300 +2840,6 @@ var unplugin_default = createUnplugin((options = {}) => {
2844
2840
 
2845
2841
  const Components = unplugin_default.vite;
2846
2842
 
2847
- const REGEX_BACKSLASH$1 = /\\/g;
2848
- const REGEX_SEPARATORS = /[-_/.\s]+/g;
2849
- const REGEX_NON_ALPHANUMERIC = /[^a-z0-9-]+/gi;
2850
- const REGEX_REPEATED_DASH = /-+/g;
2851
- const REGEX_EDGE_DASH = /^-|-$/g;
2852
- const REGEX_NUMBER = /\d/;
2853
- function isUppercase(char = "") {
2854
- if (REGEX_NUMBER.test(char)) return void 0;
2855
- return char !== char.toLowerCase();
2856
- }
2857
- function caseBoundary(previousUpper, isUpper, buffer) {
2858
- if (previousUpper === false && isUpper === true) return "before";
2859
- if (previousUpper === true && isUpper === false && buffer.length > 1) return "after";
2860
- }
2861
- function splitByCase(value) {
2862
- const parts = [];
2863
- let buffer = "";
2864
- let previousUpper;
2865
- let previousSplitter;
2866
- const flush = () => {
2867
- if (buffer) parts.push(buffer);
2868
- };
2869
- for (const char of value) {
2870
- const isSplitter = REGEX_SEPARATORS.test(char);
2871
- REGEX_SEPARATORS.lastIndex = 0;
2872
- if (isSplitter) {
2873
- flush();
2874
- buffer = "";
2875
- previousUpper = void 0;
2876
- previousSplitter = true;
2877
- continue;
2878
- }
2879
- const isUpper = isUppercase(char);
2880
- const boundary = previousSplitter === false ? caseBoundary(previousUpper, isUpper, buffer) : void 0;
2881
- if (boundary === "before") {
2882
- flush();
2883
- buffer = char;
2884
- } else if (boundary === "after") {
2885
- parts.push(buffer.slice(0, -1));
2886
- buffer = buffer.at(-1) + char;
2887
- } else buffer += char;
2888
- previousUpper = isUpper;
2889
- previousSplitter = false;
2890
- }
2891
- flush();
2892
- return parts;
2893
- }
2894
- function kebabCaseSegments(segments) {
2895
- return segments.map((segment) => segment.toLowerCase()).join("-").replace(REGEX_NON_ALPHANUMERIC, "-").replace(REGEX_REPEATED_DASH, "-").replace(REGEX_EDGE_DASH, "");
2896
- }
2897
- function resolveLayoutNameSegments(fileName, prefixParts) {
2898
- const fileNameParts = splitByCase(fileName);
2899
- const fileNamePartsContent = fileNameParts.join("/").toLowerCase();
2900
- const layoutNameParts = prefixParts.flatMap((part) => splitByCase(part));
2901
- const matchedSuffix = [];
2902
- let index = prefixParts.length - 1;
2903
- while (index >= 0) {
2904
- const prefixPart = prefixParts[index];
2905
- matchedSuffix.unshift(...splitByCase(prefixPart).map((part) => part.toLowerCase()));
2906
- const matchedSuffixContent = matchedSuffix.join("/");
2907
- if (fileNamePartsContent === matchedSuffixContent || fileNamePartsContent.startsWith(`${matchedSuffixContent}/`) || prefixPart.toLowerCase() === fileNamePartsContent && prefixParts[index + 1] && prefixParts[index] === prefixParts[index + 1]) layoutNameParts.length = index;
2908
- index -= 1;
2909
- }
2910
- return [...layoutNameParts, ...fileNameParts];
2911
- }
2912
- function normalizeLayoutName(file) {
2913
- const normalizedFile = file.replace(REGEX_BACKSLASH$1, "/");
2914
- const slashIndex = normalizedFile.lastIndexOf("/");
2915
- const dir = slashIndex === -1 ? "" : normalizedFile.slice(0, slashIndex);
2916
- const basename = slashIndex === -1 ? normalizedFile : normalizedFile.slice(slashIndex + 1);
2917
- const dotIndex = basename.lastIndexOf(".");
2918
- const name = dotIndex <= 0 ? basename : basename.slice(0, dotIndex);
2919
- const prefixParts = splitByCase(dir);
2920
- return kebabCaseSegments(resolveLayoutNameSegments(dir && name.toLowerCase() === "index" ? "" : name, prefixParts).filter(Boolean));
2921
- }
2922
-
2923
- const RUNTIME_ID = "valaxy/vendor/layouts/runtime.mjs";
2924
- function getClientCode(importCode, options) {
2925
- const inheritDefaultLayout = options.inheritDefaultLayout ?? true;
2926
- const fallbackArg = options.fallbackLayout ? `, '${options.fallbackLayout}'` : "";
2927
- return `
2928
- import { createGetRoutes, createLayoutWrapper, createSetupLayouts, lazyLayout, setPageLayout, useLayout } from '${RUNTIME_ID}'
2929
- export { createGetRoutes, setPageLayout, useLayout }
2930
- ${importCode}
2931
- const LayoutWrapper = createLayoutWrapper(layouts, '${options.defaultLayout}'${fallbackArg})
2932
- export const setupLayouts = createSetupLayouts(LayoutWrapper, { inheritDefaultLayout: ${inheritDefaultLayout} })
2933
- `;
2934
- }
2935
- function normalizePath$1(path) {
2936
- path = path.startsWith("/") ? path : `/${path}`;
2937
- return posix.normalize(path);
2938
- }
2939
- async function createVirtualModuleCode(options) {
2940
- const { layoutDir, defaultLayout, fallbackLayout, importMode, inheritDefaultLayout = true } = options;
2941
- const normalizedTarget = normalizePath$1(layoutDir);
2942
- const isSync = importMode === "sync";
2943
- const fallbackArg = fallbackLayout ? `, '${fallbackLayout}'` : "";
2944
- return `
2945
- import { createGetRoutes, createLayoutWrapper, createSetupLayouts, lazyLayout, normalizeLayoutName, setPageLayout, useLayout } from '${RUNTIME_ID}'
2946
- export { createGetRoutes, setPageLayout, useLayout }
2947
-
2948
- const modules = import.meta.glob("${normalizedTarget}/**/*.vue", { eager: ${isSync} })
2949
-
2950
- export const layouts = {}
2951
- Object.entries(modules).forEach(([name, module]) => {
2952
- const key = normalizeLayoutName(name.replace("${normalizedTarget}/", ''))
2953
- layouts[key] = ${isSync ? "module.default" : "lazyLayout(module)"}
2954
- })
2955
-
2956
- const LayoutWrapper = createLayoutWrapper(layouts, '${defaultLayout}'${fallbackArg})
2957
- export const setupLayouts = createSetupLayouts(LayoutWrapper, { inheritDefaultLayout: ${inheritDefaultLayout} })
2958
- `;
2959
- }
2960
- const REGEX_BACKSLASH = /\\/g;
2961
- function extensionsToGlob(extensions) {
2962
- return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
2963
- }
2964
- function normalizePath$2(str) {
2965
- return str.replace(REGEX_BACKSLASH, "/");
2966
- }
2967
- const debug$6 = createDebug("vite-plugin-layouts-next");
2968
- function resolveDirs(dirs, root) {
2969
- if (dirs === null) return [];
2970
- const dirsArray = Array.isArray(dirs) ? dirs : [dirs];
2971
- const dirsResolved = [];
2972
- for (const dir of dirsArray) if (dir.includes("**")) {
2973
- const matches = globSync(dir, { cwd: root, onlyDirectories: true });
2974
- for (const match of matches) dirsResolved.push(normalizePath$2(resolve(root, match)));
2975
- } else dirsResolved.push(normalizePath$2(resolve(root, dir)));
2976
- return dirsResolved;
2977
- }
2978
- async function getFilesFromPath(path, options) {
2979
- const { exclude, extensions } = options;
2980
- const ext = extensionsToGlob(extensions);
2981
- debug$6(extensions);
2982
- return await glob(`**/*.${ext}`, {
2983
- ignore: [
2984
- "node_modules",
2985
- ".git",
2986
- "**/__*__/*",
2987
- ...exclude
2988
- ],
2989
- onlyFiles: true,
2990
- cwd: path
2991
- });
2992
- }
2993
- function getImportCode(files, options) {
2994
- const imports = [];
2995
- const head = [];
2996
- let id = 0;
2997
- for (const __ of files) for (const file of __.files) {
2998
- const path = __.path.startsWith("/") ? `${__.path}/${file}` : `/${__.path}/${file}`;
2999
- const name = normalizeLayoutName(file);
3000
- if (options.importMode(name) === "sync") {
3001
- const variable = `__layout_${id}`;
3002
- head.push(`import ${variable} from '${path}'`);
3003
- imports.push(`'${name}': ${variable},`);
3004
- id += 1;
3005
- } else imports.push(`'${name}': lazyLayout(() => import('${path}')),`);
3006
- }
3007
- return `
3008
- ${head.join("\n")}
3009
- export const layouts = {
3010
- ${imports.join("\n")}
3011
- }`;
3012
- }
3013
- const MODULE_ID = "virtual:generated-layouts";
3014
- const MODULE_ID_VIRTUAL = "/@vite-plugin-vue-layouts-next/generated-layouts";
3015
- function defaultImportMode(name) {
3016
- if (process$1.env.VITE_SSG) return "sync";
3017
- return name === "default" ? "sync" : "async";
3018
- }
3019
- function resolveOptions$1(userOptions) {
3020
- return {
3021
- defaultLayout: "default",
3022
- layoutsDirs: "src/layouts",
3023
- extensions: ["vue"],
3024
- exclude: [],
3025
- importMode: defaultImportMode,
3026
- inheritDefaultLayout: true,
3027
- ...userOptions
3028
- };
3029
- }
3030
- function Layout(userOptions = {}) {
3031
- if (canEnableClientLayout(userOptions)) return ClientSideLayout({
3032
- defaultLayout: userOptions.defaultLayout,
3033
- fallbackLayout: userOptions.fallbackLayout,
3034
- layoutsDirs: userOptions.layoutsDirs,
3035
- inheritDefaultLayout: userOptions.inheritDefaultLayout
3036
- });
3037
- let config;
3038
- const options = resolveOptions$1(userOptions);
3039
- let layoutsDirs;
3040
- return {
3041
- name: "vite-plugin-vue-layouts-next",
3042
- enforce: "pre",
3043
- config() {
3044
- return { optimizeDeps: { include: [RUNTIME_ID] } };
3045
- },
3046
- configResolved(_config) {
3047
- config = _config;
3048
- layoutsDirs = resolveDirs(options.layoutsDirs, config.root);
3049
- },
3050
- configureServer({ moduleGraph, watcher, ws }) {
3051
- watcher.add(options.layoutsDirs);
3052
- const reloadModule = (module, path = "*") => {
3053
- if (module) {
3054
- moduleGraph.invalidateModule(module);
3055
- if (ws) ws.send({
3056
- path,
3057
- type: "full-reload"
3058
- });
3059
- }
3060
- };
3061
- const updateVirtualModule = (path) => {
3062
- path = normalizePath$2(path);
3063
- if (layoutsDirs.some((dir) => path.startsWith(dir))) {
3064
- debug$6("reload", path);
3065
- const module = moduleGraph.getModuleById(MODULE_ID_VIRTUAL);
3066
- reloadModule(module);
3067
- }
3068
- };
3069
- watcher.on("add", (path) => {
3070
- updateVirtualModule(path);
3071
- });
3072
- watcher.on("unlink", (path) => {
3073
- updateVirtualModule(path);
3074
- });
3075
- watcher.on("change", async (path) => {
3076
- updateVirtualModule(path);
3077
- });
3078
- },
3079
- resolveId(id) {
3080
- return id === MODULE_ID || id.startsWith(MODULE_ID) ? MODULE_ID_VIRTUAL : null;
3081
- },
3082
- async load(id) {
3083
- if (id === MODULE_ID_VIRTUAL) {
3084
- const container = [];
3085
- for (const dir of layoutsDirs) {
3086
- const layoutsDirPath = dir.startsWith("/") ? normalizePath$2(dir) : normalizePath$2(resolve(config.root, dir));
3087
- debug$6("Loading Layout Dir: %O", layoutsDirPath);
3088
- const _f = await getFilesFromPath(layoutsDirPath, options);
3089
- container.push({
3090
- path: layoutsDirPath,
3091
- files: _f
3092
- });
3093
- }
3094
- const clientCode = getClientCode(getImportCode(container, options), options);
3095
- debug$6("Client code: %O", clientCode);
3096
- return {
3097
- code: clientCode,
3098
- moduleType: "js"
3099
- };
3100
- }
3101
- }
3102
- };
3103
- }
3104
- function ClientSideLayout(options) {
3105
- const { layoutsDirs, layoutDir: legacyLayoutDir, defaultLayout = "default", fallbackLayout, importMode = process$1.env.VITE_SSG ? "sync" : "async", inheritDefaultLayout = true } = options || {};
3106
- const layoutDir = layoutsDirs ?? legacyLayoutDir ?? "src/layouts";
3107
- return {
3108
- name: "vite-plugin-vue-layouts-next",
3109
- config() {
3110
- return { optimizeDeps: { include: [RUNTIME_ID] } };
3111
- },
3112
- resolveId(id) {
3113
- if (id === MODULE_ID) return `\0${MODULE_ID}`;
3114
- },
3115
- async load(id) {
3116
- if (id === `\0${MODULE_ID}`) return {
3117
- code: await createVirtualModuleCode({
3118
- layoutDir,
3119
- importMode,
3120
- defaultLayout,
3121
- fallbackLayout,
3122
- inheritDefaultLayout
3123
- }),
3124
- moduleType: "js"
3125
- };
3126
- }
3127
- };
3128
- }
3129
- function canEnableClientLayout(options) {
3130
- const keys = Object.keys(options);
3131
- if (keys.length > 4 || keys.some((key) => ![
3132
- "layoutsDirs",
3133
- "defaultLayout",
3134
- "fallbackLayout",
3135
- "inheritDefaultLayout"
3136
- ].includes(key))) return false;
3137
- if (options.layoutsDirs && (Array.isArray(options.layoutsDirs) || options.layoutsDirs.includes("*"))) return false;
3138
- return true;
3139
- }
3140
-
3141
2843
  function isLoopback(address = "") {
3142
2844
  return address === "::1" || /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(address);
3143
2845
  }
@@ -3301,7 +3003,7 @@ class EditorRoutes {
3301
3003
  }
3302
3004
  }
3303
3005
 
3304
- const debug$5 = createDebug("valaxy:group-icons");
3006
+ const debug$2 = _debug("valaxy:group-icons");
3305
3007
  const codeBlockTitleRE = /^[ \t]{0,3}`{3}[^\n[]*\[((?:[^[\]]|\[[^[\]]*\])*)\]/gm;
3306
3008
  async function scanCodeBlockTitles(options) {
3307
3009
  const titles = /* @__PURE__ */ new Set();
@@ -3315,7 +3017,7 @@ async function scanCodeBlockTitles(options) {
3315
3017
  const content = await readFile(file, "utf-8");
3316
3018
  extractCodeBlockTitles(content, titles);
3317
3019
  } catch (error) {
3318
- debug$5("Failed to read %s: %O", page, error);
3020
+ debug$2("Failed to read %s: %O", page, error);
3319
3021
  }
3320
3022
  },
3321
3023
  { concurrency: 64 }
@@ -3820,1368 +3522,215 @@ async function getAlias(options) {
3820
3522
  return alias;
3821
3523
  }
3822
3524
 
3823
- function normalizeGlobOption(val) {
3824
- if (!val) return void 0;
3825
- return isString(val) ? [normalize(val)] : val.map(normalize);
3826
- }
3827
- function resolveOptions(options) {
3828
- const moduleType = options.module || "vue-i18n";
3829
- let onlyLocales = [];
3830
- if (options.onlyLocales) {
3831
- onlyLocales = isArray(options.onlyLocales) ? options.onlyLocales : [options.onlyLocales];
3832
- }
3833
- const forceStringify = !!options.forceStringify;
3834
- const defaultSFCLang = isString(options.defaultSFCLang) ? options.defaultSFCLang : "json";
3835
- const globalSFCScope = !!options.globalSFCScope;
3836
- const runtimeOnly = isBoolean(options.runtimeOnly) ? options.runtimeOnly : true;
3837
- const dropMessageCompiler = !!options.dropMessageCompiler;
3838
- const compositionOnly = moduleType === "vue-i18n" ? isBoolean(options.compositionOnly) ? options.compositionOnly : true : true;
3839
- const fullInstall = moduleType === "vue-i18n" ? isBoolean(options.fullInstall) ? options.fullInstall : true : false;
3840
- const ssrBuild = !!options.ssr;
3841
- const allowDynamic = !!options.allowDynamic;
3842
- const strictMessage = isBoolean(options.strictMessage) ? options.strictMessage : true;
3843
- const escapeHtml = !!options.escapeHtml;
3844
- const optimizeTranslationDirective = isString(options.optimizeTranslationDirective) || isArray(options.optimizeTranslationDirective) ? options.optimizeTranslationDirective : !!options.optimizeTranslationDirective;
3845
- const translationIdentifiers = /* @__PURE__ */ new Map();
3846
- const transformI18nBlock = typeof options.transformI18nBlock === "function" ? options.transformI18nBlock : null;
3847
- const treeShaking = options.treeShaking ? typeof options.treeShaking === "object" ? {
3848
- safelist: options.treeShaking.safelist || [],
3849
- dynamicKeyStrategy: options.treeShaking.dynamicKeyStrategy || "keep-all",
3850
- scanPatterns: options.treeShaking.scanPatterns
3851
- } : { safelist: [], dynamicKeyStrategy: "keep-all" } : null;
3852
- return {
3853
- include: normalizeGlobOption(options.include || []),
3854
- exclude: normalizeGlobOption(options.exclude),
3855
- module: moduleType,
3856
- onlyLocales,
3857
- forceStringify,
3858
- defaultSFCLang,
3859
- globalSFCScope,
3860
- runtimeOnly,
3861
- dropMessageCompiler,
3862
- compositionOnly,
3863
- fullInstall,
3864
- ssrBuild,
3865
- allowDynamic,
3866
- strictMessage,
3867
- escapeHtml,
3868
- optimizeTranslationDirective,
3869
- translationIdentifiers,
3870
- transformI18nBlock,
3871
- treeShaking
3872
- };
3873
- }
3874
- const PKG_NAME = "unplugin-vue-i18n";
3875
- function warn(...args) {
3876
- console.warn(pc.yellow(pc.bold(`[${PKG_NAME}] `)), ...args);
3877
- }
3878
- function error(...args) {
3879
- console.error(pc.red(pc.bold(`[${PKG_NAME}] `)), ...args);
3880
- }
3881
- function raiseError(message) {
3882
- throw new Error(`[${PKG_NAME}] ${message}`);
3883
- }
3884
- function resolveNamespace(name) {
3885
- return `${PKG_NAME}:${name}`;
3886
- }
3887
- function getVitePlugin(config, name) {
3888
- return config.plugins.find((p) => p.name === name);
3889
- }
3890
- function checkVuePlugin(vuePlugin) {
3891
- if (vuePlugin == null || !vuePlugin.api) {
3892
- error(
3893
- "`@vitejs/plugin-vue` plugin is not found or invalid version. Please install `@vitejs/plugin-vue` v4.3.4 or later version."
3894
- );
3895
- return false;
3896
- }
3897
- return true;
3898
- }
3899
- const isWindows = typeof process !== "undefined" && process.platform === "win32";
3900
- const windowsSlashRE = /\\/g;
3901
- function slash(p) {
3902
- return p.replace(windowsSlashRE, "/");
3903
- }
3904
- function normalizePath(id) {
3905
- return path.posix.normalize(isWindows ? slash(id) : id);
3906
- }
3907
- function parseVueRequest(id) {
3908
- const [filename, rawQuery] = id.split(`?`, 2);
3909
- const params = new URLSearchParams(rawQuery);
3910
- const ret = {};
3911
- const langPart = Object.keys(Object.fromEntries(params)).find((key) => /lang\./i.test(key));
3912
- ret.vue = params.has("vue");
3913
- ret.global = params.has("global");
3914
- ret.src = params.has("src");
3915
- ret.raw = params.has("raw");
3916
- if (params.has("type")) {
3917
- ret.type = params.get("type");
3918
- }
3919
- if (params.has("blockType")) {
3920
- ret.blockType = params.get("blockType");
3921
- }
3922
- if (params.has("index")) {
3923
- ret.index = Number(params.get("index"));
3924
- }
3925
- if (params.has("locale")) {
3926
- ret.locale = params.get("locale");
3927
- }
3928
- if (langPart) {
3929
- const [, lang] = langPart.split(".");
3930
- ret.lang = lang;
3931
- } else if (params.has("lang")) {
3932
- ret.lang = params.get("lang");
3933
- }
3934
- if (params.has("issuerPath")) {
3935
- ret.issuerPath = params.get("issuerPath");
3936
- }
3937
- return {
3938
- filename,
3939
- query: ret
3940
- };
3941
- }
3942
- function getVueCompiler(vuePlugin) {
3943
- return vuePlugin?.api?.options.compiler;
3944
- }
3945
- function getVuePluginOptions(vuePlugin) {
3946
- return {
3947
- isProduction: vuePlugin?.api?.options.isProduction,
3948
- root: vuePlugin?.api?.options.root,
3949
- template: vuePlugin?.api?.options.template,
3950
- compiler: vuePlugin?.api?.options.compiler
3951
- };
3952
- }
3953
- function createDescriptor(filename, source, { template, compiler }) {
3954
- const { descriptor, errors } = compiler.parse(source, {
3955
- filename,
3956
- templateParseOptions: template?.compilerOptions
3957
- });
3958
- return { descriptor, errors };
3959
- }
3960
- function getDescriptor(filename, code, options) {
3961
- const { descriptor, errors } = createDescriptor(filename, code, options);
3962
- if (errors.length) {
3963
- throw errors[0];
3964
- }
3965
- return descriptor;
3966
- }
3967
- const INTLIFY_BUNDLE_IMPORT_ID = "@intlify/unplugin-vue-i18n/messages";
3968
- const VIRTUAL_PREFIX = "virtual:";
3969
- const RE_RESOURCE_FORMAT = /\.(json5?|ya?ml|[c|m]?[j|t]s)$/;
3970
- const RE_SFC_I18N_CUSTOM_BLOCK = /\?vue&type=i18n/;
3971
- const RE_SFC_I18N_WEBPACK_CUSTOM_BLOCK = /blockType=i18n/;
3972
- const VITE_VIRTUAL_PREFIX = "virtual:intlify-i18n-";
3973
- const debug$3 = createDebug(resolveNamespace("resource"));
3974
- function resourcePlugin({
3975
- onlyLocales,
3976
- include,
3977
- exclude,
3978
- module,
3979
- forceStringify,
3980
- defaultSFCLang,
3981
- globalSFCScope,
3982
- runtimeOnly,
3983
- dropMessageCompiler,
3984
- compositionOnly,
3985
- fullInstall,
3986
- ssrBuild,
3987
- strictMessage,
3988
- allowDynamic,
3989
- escapeHtml,
3990
- transformI18nBlock
3991
- }, meta, collector) {
3992
- function resolveIncludeExclude() {
3993
- const customBlockInclude = meta.framework === "vite" ? RE_SFC_I18N_CUSTOM_BLOCK : RE_SFC_I18N_WEBPACK_CUSTOM_BLOCK;
3994
- return include ? [[...include, customBlockInclude], exclude] : [[RE_RESOURCE_FORMAT, customBlockInclude], exclude];
3995
- }
3996
- function resolveIncludeExcludeForLegacy() {
3997
- const customBlockInclude = meta.framework === "vite" ? RE_SFC_I18N_CUSTOM_BLOCK : RE_SFC_I18N_WEBPACK_CUSTOM_BLOCK;
3998
- return include ? [[...include, customBlockInclude], void 0] : [void 0, ["**/**"]];
3999
- }
4000
- let _filter = null;
4001
- async function getFilter() {
4002
- if (_filter != null) {
4003
- return _filter;
4004
- }
4005
- if (meta.framework == "webpack") {
4006
- debug$3("Using filter for webpack");
4007
- _filter = createFilter$1(...resolveIncludeExclude());
4008
- } else if (hasViteJsonPlugin) {
4009
- debug$3("Using filter for rollup-vite");
4010
- _filter = createFilter$1(...resolveIncludeExcludeForLegacy());
4011
- } else {
4012
- debug$3("Using filter for rolldown-vite");
4013
- _filter = createFilter$1(...resolveIncludeExclude());
4014
- }
4015
- return _filter;
4016
- }
4017
- const getVueI18nAliasPath = ({ ssr = false, runtimeOnly: runtimeOnly2 = false }) => {
4018
- return `${module}/dist/${module}${runtimeOnly2 ? ".runtime" : ""}.${!ssr ? "esm-bundler.js" : "node.mjs"}`;
4019
- };
4020
- let isProduction = false;
4021
- let sourceMap = false;
4022
- let hasViteJsonPlugin = false;
4023
- const vueI18nAliasName = module;
4024
- debug$3(`vue-i18n alias name: ${vueI18nAliasName}`);
4025
- let vuePlugin = null;
4026
- const getSfcParser = () => {
4027
- return vuePlugin ? getVueCompiler(vuePlugin).parse : parse$2;
4028
- };
4029
- const virtualIdToRealPath = /* @__PURE__ */ new Map();
4030
- const realPathToVirtualId = /* @__PURE__ */ new Map();
4031
- let virtualCounter = 0;
4032
- function intlifyVirtualize(realPath) {
4033
- const normalized = normalize(realPath);
4034
- let virtualId = realPathToVirtualId.get(normalized);
4035
- if (!virtualId) {
4036
- virtualId = `${VITE_VIRTUAL_PREFIX}${virtualCounter++}`;
4037
- virtualIdToRealPath.set(virtualId, normalized);
4038
- realPathToVirtualId.set(normalized, virtualId);
4039
- }
4040
- return virtualId;
4041
- }
4042
- function isIntlifyVirtualId(id) {
4043
- return virtualIdToRealPath.has(id);
4044
- }
4045
- return {
4046
- name: resolveNamespace("resource"),
4047
- /**
4048
- * NOTE:
4049
- *
4050
- * For vite, If we have json (including SFC's custom block),
4051
- * transform it first because it will be transformed into javascript code by `vite:json` plugin.
4052
- *
4053
- * For webpack, This plugin will handle with 'post', because vue-loader generate the request query.
4054
- */
4055
- enforce: meta.framework === "vite" ? "pre" : "post",
4056
- vite: {
4057
- config() {
4058
- const defineConfig = {
4059
- define: {
4060
- __VUE_I18N_LEGACY_API__: !compositionOnly,
4061
- __VUE_I18N_FULL_INSTALL__: fullInstall,
4062
- __INTLIFY_DROP_MESSAGE_COMPILER__: dropMessageCompiler,
4063
- __VUE_I18N_PROD_DEVTOOLS__: false
4064
- }
4065
- };
4066
- debug$3("define Config:", defineConfig);
4067
- const aliasConfig = {
4068
- resolve: {
4069
- alias: {
4070
- [vueI18nAliasName]: getVueI18nAliasPath({
4071
- ssr: ssrBuild,
4072
- runtimeOnly
4073
- })
4074
- }
4075
- }
4076
- };
4077
- debug$3("alias Config:", aliasConfig);
4078
- return assign(defineConfig, aliasConfig);
4079
- },
4080
- async configResolved(config) {
4081
- vuePlugin = getVitePlugin(config, "vite:vue");
4082
- if (!checkVuePlugin(vuePlugin)) {
4083
- return;
4084
- }
4085
- isProduction = config.isProduction;
4086
- sourceMap = config.command === "build" ? !!config.build.sourcemap : false;
4087
- debug$3(`configResolved: isProduction = ${isProduction}, sourceMap = ${sourceMap}`);
4088
- const jsonPlugin = getVitePlugin(config, "vite:json");
4089
- hasViteJsonPlugin = !!jsonPlugin;
4090
- if (jsonPlugin && jsonPlugin.transform) {
4091
- const transform = jsonPlugin.transform;
4092
- const isObjectHook = typeof transform !== "function" && "handler" in transform;
4093
- const orgTransform = isObjectHook ? transform.handler : transform;
4094
- async function overrideJson(code, id) {
4095
- const filter = await getFilter();
4096
- if (!/\.json$/.test(id) || filter(id)) {
4097
- return;
4098
- }
4099
- const { query } = parseVueRequest(id);
4100
- if (query.vue) {
4101
- return;
4102
- }
4103
- debug$3("org json plugin");
4104
- return orgTransform.apply(this, [code, id]);
4105
- }
4106
- if (isObjectHook) {
4107
- transform.handler = overrideJson;
4108
- } else {
4109
- jsonPlugin.transform = overrideJson;
4110
- }
4111
- }
4112
- },
4113
- handleHotUpdate({ file, modules, server }) {
4114
- const key = normalize(file);
4115
- const virtualId = realPathToVirtualId.get(key);
4116
- const inBundle = !!(include && createFilter$1(include, exclude)(key));
4117
- if (!virtualId && !inBundle) return;
4118
- const affected = new Set(modules);
4119
- const addById = (id) => {
4120
- const mod = id && server.moduleGraph.getModuleById(id);
4121
- if (mod) affected.add(mod);
4122
- };
4123
- addById(virtualId);
4124
- if (inBundle) {
4125
- addById(asVirtualId(INTLIFY_BUNDLE_IMPORT_ID, meta.framework));
4126
- }
4127
- if (affected.size === modules.length) return;
4128
- return [...affected];
4129
- }
4130
- },
4131
- webpack(compiler) {
4132
- isProduction = compiler.options.mode !== "development";
4133
- sourceMap = !!compiler.options.devtool;
4134
- debug$3(`webpack: isProduction = ${isProduction}, sourceMap = ${sourceMap}`);
4135
- compiler.options.resolve = normalizeConfigResolveAlias(
4136
- compiler.options.resolve,
4137
- meta.framework
4138
- );
4139
- compiler.options.resolve.alias[vueI18nAliasName] = getVueI18nAliasPath({
4140
- ssr: ssrBuild,
4141
- runtimeOnly
4142
- });
4143
- debug$3(
4144
- `set ${vueI18nAliasName}: ${getVueI18nAliasPath({
4145
- ssr: ssrBuild,
4146
- runtimeOnly
4147
- })}`
4148
- );
4149
- compiler.options.plugins.push(
4150
- new compiler.webpack.DefinePlugin({
4151
- __VUE_I18N_LEGACY_API__: JSON.stringify(compositionOnly),
4152
- __VUE_I18N_FULL_INSTALL__: JSON.stringify(fullInstall),
4153
- __INTLIFY_PROD_DEVTOOLS__: "false"
4154
- })
4155
- );
4156
- debug$3(`set __VUE_I18N_LEGACY_API__ is '${compositionOnly}'`);
4157
- debug$3(`set __VUE_I18N_FULL_INSTALL__ is '${fullInstall}'`);
4158
- const filter = createFilter$1(...resolveIncludeExclude());
4159
- if (compiler.options.module) {
4160
- compiler.options.module.rules.push({
4161
- test: RE_RESOURCE_FORMAT,
4162
- type: "javascript/auto",
4163
- include(resource) {
4164
- debug$3("webpack resource include", resource);
4165
- return filter(resource);
4166
- }
4167
- });
4168
- }
4169
- },
4170
- resolveId: {
4171
- async handler(id, importer) {
4172
- if (id === INTLIFY_BUNDLE_IMPORT_ID) {
4173
- return asVirtualId(id, meta.framework);
4174
- }
4175
- if (meta.framework === "vite" && !hasViteJsonPlugin) {
4176
- if (id.includes("?vue&type=i18n") && /[?&]lang\.(?:json|json5)(?:$|&)/.test(id)) {
4177
- const { filename, query } = parseVueRequest(id);
4178
- let virtualKey = id;
4179
- if (query.src && importer) {
4180
- const importerPath = (isIntlifyVirtualId(importer) ? virtualIdToRealPath.get(importer) : importer).split("?")[0];
4181
- if (importerPath.endsWith(".vue")) {
4182
- const resolvedSidecar = resolve$1(dirname$1(importerPath), filename);
4183
- virtualKey = id.replace(filename, resolvedSidecar);
4184
- }
4185
- }
4186
- return intlifyVirtualize(virtualKey);
4187
- }
4188
- const idPath = id.split("?")[0];
4189
- if (!RE_RESOURCE_FORMAT.test(idPath)) return;
4190
- let resolvedPath;
4191
- if (idPath.startsWith(".")) {
4192
- const realImporter = importer && isIntlifyVirtualId(importer) ? virtualIdToRealPath.get(importer) : importer;
4193
- if (!realImporter) return;
4194
- resolvedPath = resolve$1(dirname$1(realImporter), idPath);
4195
- } else if (idPath.startsWith("/") || /^[a-z]:[/\\]/i.test(idPath)) {
4196
- resolvedPath = idPath;
4197
- } else {
4198
- return;
4199
- }
4200
- const filter = await getFilter();
4201
- if (!filter(resolvedPath)) return;
4202
- return intlifyVirtualize(resolvedPath);
4203
- }
4204
- }
4205
- },
4206
- load: {
4207
- async handler(id) {
4208
- debug$3("load", id);
4209
- if (INTLIFY_BUNDLE_IMPORT_ID === getVirtualId(id, meta.framework) && include) {
4210
- let resourcePaths = [];
4211
- for (const inc of include) {
4212
- resourcePaths = [...resourcePaths, ...await glob(inc, { absolute: true })];
4213
- }
4214
- resourcePaths = resourcePaths.filter((el, pos) => resourcePaths.indexOf(el) === pos);
4215
- const code = await generateBundleResources(resourcePaths, isProduction, {
4216
- forceStringify,
4217
- strictMessage,
4218
- escapeHtml,
4219
- usedKeyFilter: collector ? (keyPath) => collector.shouldKeepKey(keyPath) : void 0
4220
- });
4221
- return {
4222
- moduleType: "js",
4223
- code,
4224
- map: { mappings: "" }
4225
- };
4226
- }
4227
- if (isIntlifyVirtualId(id)) {
4228
- const realId = virtualIdToRealPath.get(id);
4229
- if (realId.includes("?vue&type=i18n")) {
4230
- const { filename, query } = parseVueRequest(realId);
4231
- let source;
4232
- if (query.src) {
4233
- this.addWatchFile(filename);
4234
- source = await promises.readFile(filename, "utf-8");
4235
- } else {
4236
- this.addWatchFile(filename);
4237
- const sfcSource = await promises.readFile(filename, "utf-8");
4238
- const { descriptor } = getSfcParser()(sfcSource, {
4239
- sourceMap,
4240
- filename
4241
- });
4242
- const block = descriptor.customBlocks[query.index];
4243
- if (!block) return;
4244
- source = block.content;
4245
- }
4246
- if (typeof transformI18nBlock === "function") {
4247
- const modifiedSource = transformI18nBlock(source);
4248
- if (modifiedSource && typeof modifiedSource === "string") {
4249
- source = modifiedSource;
4250
- } else {
4251
- warn("transformI18nBlock should return a string");
4252
- }
4253
- }
4254
- let langInfo2 = defaultSFCLang;
4255
- if (isString(query.lang)) {
4256
- langInfo2 = query.src ? query.lang === "i18n" ? defaultSFCLang : query.lang : query.lang;
4257
- }
4258
- if (/\.?[cm]?[jt]s$/.test(langInfo2)) {
4259
- source = `export default ${source.replace(/^[\s;]+/, "")}`;
4260
- }
4261
- const generate2 = getGenerator(langInfo2, generateYAML);
4262
- const isGlobalBlock = globalSFCScope || !!query.global;
4263
- const parseOptions2 = getOptions(
4264
- filename,
4265
- isProduction,
4266
- query,
4267
- sourceMap,
4268
- {
4269
- isGlobal: globalSFCScope,
4270
- allowDynamic,
4271
- jit: true,
4272
- strictMessage,
4273
- escapeHtml,
4274
- onlyLocales,
4275
- forceStringify,
4276
- usedKeyFilter: collector && isGlobalBlock ? (keyPath) => collector.shouldKeepKey(keyPath) : void 0
4277
- }
4278
- );
4279
- const { code: generatedCode2 } = await generate2(source, parseOptions2);
4280
- return {
4281
- moduleType: "js",
4282
- code: generatedCode2,
4283
- map: { mappings: "" }
4284
- };
4285
- }
4286
- this.addWatchFile(realId);
4287
- const code = await promises.readFile(realId, "utf-8");
4288
- const langInfo = parse$1(realId).ext;
4289
- const generate = getGenerator(langInfo);
4290
- const parseOptions = getOptions(
4291
- realId,
4292
- isProduction,
4293
- {},
4294
- sourceMap,
4295
- {
4296
- isGlobal: globalSFCScope,
4297
- allowDynamic,
4298
- strictMessage,
4299
- escapeHtml,
4300
- jit: true,
4301
- onlyLocales,
4302
- forceStringify,
4303
- usedKeyFilter: collector ? (keyPath) => collector.shouldKeepKey(keyPath) : void 0
4304
- }
4305
- );
4306
- const { code: generatedCode } = await generate(code, parseOptions);
4307
- return {
4308
- moduleType: "js",
4309
- code: generatedCode,
4310
- map: { mappings: "" }
4311
- };
4312
- }
4313
- }
4314
- },
4315
- transform: {
4316
- async handler(code, id) {
4317
- if (isIntlifyVirtualId(id)) return;
4318
- const filter = await getFilter();
4319
- if (!filter(id)) {
4320
- return;
4321
- }
4322
- const { filename, query } = parseVueRequest(id);
4323
- debug$3("transform", id, JSON.stringify(query), filename);
4324
- let langInfo = defaultSFCLang;
4325
- let inSourceMap;
4326
- if (!query.vue) {
4327
- langInfo = parse$1(filename).ext;
4328
- const generate = getGenerator(langInfo);
4329
- const parseOptions = getOptions(
4330
- filename,
4331
- isProduction,
4332
- query,
4333
- sourceMap,
4334
- {
4335
- inSourceMap,
4336
- isGlobal: globalSFCScope,
4337
- allowDynamic,
4338
- strictMessage,
4339
- escapeHtml,
4340
- jit: true,
4341
- onlyLocales,
4342
- forceStringify,
4343
- usedKeyFilter: collector ? (keyPath) => collector.shouldKeepKey(keyPath) : void 0
4344
- }
4345
- );
4346
- debug$3("parseOptions", parseOptions);
4347
- const { code: generatedCode, map } = await generate(code, parseOptions);
4348
- debug$3("generated code", generatedCode);
4349
- debug$3("sourcemap", map, sourceMap);
4350
- if (code === generatedCode) return;
4351
- return {
4352
- moduleType: "js",
4353
- code: generatedCode,
4354
- // prettier-ignore
4355
- map: { mappings: "" }
4356
- };
4357
- } else {
4358
- if (isCustomBlock(query)) {
4359
- if (isString(query.lang)) {
4360
- langInfo = query.src ? query.lang === "i18n" ? defaultSFCLang : query.lang : query.lang;
4361
- } else if (defaultSFCLang) {
4362
- langInfo = defaultSFCLang;
4363
- }
4364
- debug$3("langInfo", langInfo);
4365
- const generate = getGenerator(langInfo, generateYAML);
4366
- const isGlobalBlock = globalSFCScope || !!query.global;
4367
- const parseOptions = getOptions(
4368
- filename,
4369
- isProduction,
4370
- query,
4371
- sourceMap,
4372
- {
4373
- inSourceMap,
4374
- isGlobal: globalSFCScope,
4375
- allowDynamic,
4376
- jit: true,
4377
- strictMessage,
4378
- escapeHtml,
4379
- onlyLocales,
4380
- forceStringify,
4381
- usedKeyFilter: collector && isGlobalBlock ? (keyPath) => collector.shouldKeepKey(keyPath) : void 0
4382
- }
4383
- );
4384
- debug$3("parseOptions", parseOptions);
4385
- let source = await getCode(
4386
- code,
4387
- filename,
4388
- sourceMap,
4389
- query,
4390
- getSfcParser(),
4391
- meta.framework
4392
- );
4393
- if (typeof transformI18nBlock === "function") {
4394
- const modifiedSource = transformI18nBlock(source);
4395
- if (modifiedSource && typeof modifiedSource === "string") {
4396
- source = modifiedSource;
4397
- } else {
4398
- warn("transformI18nBlock should return a string");
4399
- }
4400
- }
4401
- if (/\.?[cm]?[jt]s$/.test(langInfo)) {
4402
- source = `export default ${source.replace(/^[\s;]+/, "")}`;
4403
- }
4404
- const { code: generatedCode, map } = await generate(source, parseOptions);
4405
- debug$3("generated code", generatedCode);
4406
- debug$3("sourcemap", map, sourceMap);
4407
- if (code === generatedCode) return;
4408
- return {
4409
- moduleType: "js",
4410
- code: generatedCode,
4411
- // prettier-ignore
4412
- map: { mappings: "" }
4413
- };
4414
- }
4415
- }
4416
- }
4417
- }
4418
- };
4419
- }
4420
- function getGenerator(ext, fallback = generateJSON) {
4421
- if (/\.?json5?$/.test(ext)) {
4422
- return generateJSON;
4423
- }
4424
- if (/\.?ya?ml$/.test(ext)) {
4425
- return generateYAML;
4426
- }
4427
- if (/\.?[cm]?js$/.test(ext)) {
4428
- return generateJavaScript;
4429
- }
4430
- if (/\.?[cm]?ts$/.test(ext)) {
4431
- return generateTypescript;
4432
- }
4433
- return fallback;
4434
- }
4435
- function normalizeConfigResolveAlias(resolve2, framework) {
4436
- if (resolve2 && resolve2.alias) {
4437
- return resolve2;
4438
- }
4439
- if (!resolve2) {
4440
- if (framework === "vite") {
4441
- return { alias: [] };
4442
- } else if (framework === "webpack") {
4443
- return { alias: {} };
4444
- }
4445
- } else if (!resolve2.alias) {
4446
- if (framework === "vite") {
4447
- resolve2.alias = [];
4448
- return resolve2;
4449
- } else if (framework === "webpack") {
4450
- resolve2.alias = {};
4451
- return resolve2;
4452
- }
4453
- }
4454
- }
4455
- async function generateBundleResources(resources, isProduction, {
4456
- forceStringify = false,
4457
- isGlobal = false,
4458
- onlyLocales = [],
4459
- strictMessage = true,
4460
- escapeHtml = false,
4461
- jit = true,
4462
- transformI18nBlock = void 0,
4463
- usedKeyFilter = void 0
4464
- }) {
4465
- const codes = [];
4466
- for (const res of resources) {
4467
- debug$3(`${res} bundle loading ...`);
4468
- if (/\.(json5?|ya?ml)$/.test(res)) {
4469
- const { ext, name } = parse$1(res);
4470
- const source = await getRaw(res);
4471
- const generate = /json5?/.test(ext) ? generateJSON : generateYAML;
4472
- const parseOptions = getOptions(res, isProduction, {}, false, {
4473
- isGlobal,
4474
- jit,
4475
- onlyLocales,
4476
- strictMessage,
4477
- escapeHtml,
4478
- forceStringify,
4479
- transformI18nBlock,
4480
- usedKeyFilter
4481
- });
4482
- parseOptions.type = "bare";
4483
- const { code } = generate(source, parseOptions);
4484
- debug$3("generated code", code);
4485
- codes.push(`${JSON.stringify(name)}: ${code}`);
4486
- }
4487
- }
4488
- return `const isObject = (item) => item && typeof item === 'object' && !Array.isArray(item);
4489
-
4490
- const mergeDeep = (target, ...sources) => {
4491
- if (!sources.length) return target;
4492
- const source = sources.shift();
4493
-
4494
- if (isObject(target) && isObject(source)) {
4495
- for (const key in source) {
4496
- if (isObject(source[key])) {
4497
- if (!target[key]) Object.assign(target, { [key]: {} });
4498
- mergeDeep(target[key], source[key]);
4499
- } else {
4500
- Object.assign(target, { [key]: source[key] });
4501
- }
4502
- }
4503
- }
4504
-
4505
- return mergeDeep(target, ...sources);
4506
- }
4507
-
4508
- export default mergeDeep({},
4509
- ${codes.map((code) => `{${code}}`).join(",\n")}
4510
- );`;
4511
- }
4512
- async function getCode(source, filename, sourceMap, query, parser, framework = "vite") {
4513
- const { index, issuerPath } = query;
4514
- if (!isNumber(index)) {
4515
- raiseError(`unexpected index: ${index}`);
4516
- }
4517
- if (framework === "webpack") {
4518
- if (issuerPath) {
4519
- debug$3(`getCode (webpack) ${index} via issuerPath`, issuerPath);
4520
- return await getRaw(filename);
4521
- } else {
4522
- const result = parser(await getRaw(filename), {
4523
- sourceMap,
4524
- filename
4525
- });
4526
- const block = result.descriptor.customBlocks[index];
4527
- if (block) {
4528
- const code = block.src ? await getRaw(resolveBlockSrc(block.src, filename)) : block.content;
4529
- debug$3(`getCode (webpack) ${index} from SFC`, code);
4530
- return code;
4531
- } else {
4532
- return source;
4533
- }
4534
- }
4535
- } else {
4536
- return source;
4537
- }
4538
- }
4539
- function isCustomBlock(query) {
4540
- return !isEmptyObject(query) && "vue" in query && (query["type"] === "custom" || // for webpack (vue-loader)
4541
- query["type"] === "i18n" || // for vite (@vite/plugin-vue)
4542
- query["blockType"] === "i18n");
4543
- }
4544
- function getOptions(filename, isProduction, query, sourceMap, {
4545
- inSourceMap = void 0,
4546
- forceStringify = false,
4547
- isGlobal = false,
4548
- onlyLocales = [],
4549
- allowDynamic = false,
4550
- strictMessage = true,
4551
- escapeHtml = false,
4552
- jit = true,
4553
- transformI18nBlock = null,
4554
- usedKeyFilter = void 0
4555
- }) {
4556
- const mode = isProduction ? "production" : "development";
4557
- const baseOptions = {
4558
- filename,
4559
- sourceMap,
4560
- inSourceMap,
4561
- forceStringify,
4562
- allowDynamic,
4563
- strictMessage,
4564
- escapeHtml,
4565
- jit,
4566
- onlyLocales,
4567
- usedKeyFilter,
4568
- env: mode,
4569
- transformI18nBlock,
4570
- onWarn: (msg) => {
4571
- warn(`${filename} ${msg}`);
4572
- },
4573
- onError: (msg, extra) => {
4574
- const codeFrame = generateCodeFrame(
4575
- extra?.source || extra?.location?.source || "",
4576
- extra?.location?.start.column,
4577
- extra?.location?.end.column
4578
- );
4579
- const errMssage = `${msg} (error code: ${extra?.code}) in ${filename}
4580
- target message: ${extra?.source}
4581
- target message path: ${extra?.path}
4582
-
4583
- ${codeFrame}
4584
- `;
4585
- error(errMssage);
4586
- throw new Error(errMssage);
4587
- }
4588
- };
4589
- if (isCustomBlock(query)) {
4590
- return assign(baseOptions, {
4591
- type: "sfc",
4592
- locale: isString(query.locale) ? query.locale : "",
4593
- isGlobal: isGlobal || !!query.global
4594
- });
4595
- } else {
4596
- return assign(baseOptions, {
4597
- type: "plain",
4598
- isGlobal: false
4599
- });
4600
- }
4601
- }
4602
- function resolveBlockSrc(src, sfcFilename) {
4603
- if (src.startsWith(".") || !src.startsWith("/") && !/^[a-z]:[/\\]/i.test(src)) {
4604
- return resolve$1(dirname$1(sfcFilename), src);
4605
- }
4606
- return src;
4607
- }
4608
- function getVirtualId(id, framework = "vite") {
4609
- return framework === "vite" ? id.startsWith(VIRTUAL_PREFIX) ? id.slice(VIRTUAL_PREFIX.length) : "" : id;
3525
+ const LAYOUTS_MODULE_ID = "virtual:generated-layouts";
3526
+ const RESOLVED_LAYOUTS_MODULE_ID = `\0${LAYOUTS_MODULE_ID}`;
3527
+ function defaultImportMode(name) {
3528
+ if (process.env.VITE_SSG)
3529
+ return "sync";
3530
+ return name === "default" ? "sync" : "async";
4610
3531
  }
4611
- function asVirtualId(id, framework = "vite") {
4612
- return framework === "vite" ? VIRTUAL_PREFIX + id : id;
3532
+ const REGEX_BACKSLASH = /\\/g;
3533
+ const REGEX_SEPARATORS = /[-_/.\s]/;
3534
+ const REGEX_NON_ALPHANUMERIC = /[^a-z0-9-]+/gi;
3535
+ const REGEX_REPEATED_DASH = /-+/g;
3536
+ const REGEX_EDGE_DASH = /^-|-$/g;
3537
+ const REGEX_NUMBER = /\d/;
3538
+ function isUppercase(char = "") {
3539
+ if (REGEX_NUMBER.test(char))
3540
+ return void 0;
3541
+ return char !== char.toLowerCase();
4613
3542
  }
4614
- async function getRaw(path2) {
4615
- return promises.readFile(path2, { encoding: "utf-8" });
3543
+ function caseBoundary(previousUpper, isUpper, buffer) {
3544
+ if (previousUpper === false && isUpper === true)
3545
+ return "before";
3546
+ if (previousUpper === true && isUpper === false && buffer.length > 1)
3547
+ return "after";
4616
3548
  }
4617
- const debug$2 = createDebug(resolveNamespace("directive"));
4618
- const tsEstree = {
4619
- parse: void 0,
4620
- simpleTraverse: void 0,
4621
- AST_NODE_TYPES: void 0
4622
- };
4623
- function directivePlugin({
4624
- optimizeTranslationDirective,
4625
- translationIdentifiers
4626
- }) {
4627
- let vuePlugin = null;
4628
- let vuePluginOptions = null;
4629
- const excludeLangs = ["pug", "jsx", "tsx"];
4630
- return {
4631
- name: resolveNamespace("directive"),
4632
- enforce: "pre",
4633
- vite: {
4634
- async config(config) {
4635
- await import('@typescript-eslint/typescript-estree').then((r) => {
4636
- tsEstree.parse = r.parse;
4637
- tsEstree.simpleTraverse = r.simpleTraverse;
4638
- tsEstree.AST_NODE_TYPES = r.AST_NODE_TYPES;
4639
- return;
4640
- });
4641
- vuePlugin = getVitePlugin(config, "vite:vue");
4642
- if (!checkVuePlugin(vuePlugin)) {
4643
- return;
4644
- }
4645
- if (optimizeTranslationDirective) {
4646
- vuePlugin.api.options = resolveVueOptions(
4647
- vuePlugin,
4648
- optimizeTranslationDirective,
4649
- translationIdentifiers
4650
- );
4651
- debug$2(`vite:vue options['template']:`, vuePlugin.api.options);
4652
- }
4653
- },
4654
- configResolved(config) {
4655
- vuePlugin = getVitePlugin(config, "vite:vue");
4656
- if (!checkVuePlugin(vuePlugin)) {
4657
- return;
4658
- }
4659
- }
4660
- },
4661
- async transform(code, id) {
4662
- if (id.endsWith(".vue")) {
4663
- const { filename, query } = parseVueRequest(id);
4664
- if (!excludeLangs.includes(query.lang ?? "")) {
4665
- if (vuePluginOptions == null) {
4666
- vuePluginOptions = getVuePluginOptions(vuePlugin);
4667
- }
4668
- if (vuePluginOptions?.compiler) {
4669
- analyzeIdentifiers(
4670
- getDescriptor(filename, code, vuePluginOptions),
4671
- vuePluginOptions,
4672
- translationIdentifiers
4673
- );
4674
- return {
4675
- code,
4676
- map: { version: 3, mappings: "", sources: [] }
4677
- };
4678
- }
4679
- }
4680
- }
4681
- }
3549
+ function splitByCase(value) {
3550
+ const parts = [];
3551
+ let buffer = "";
3552
+ let previousUpper;
3553
+ let previousSplitter;
3554
+ const flush = () => {
3555
+ if (buffer)
3556
+ parts.push(buffer);
4682
3557
  };
4683
- }
4684
- function resolveVueOptions(vuePlugin, optimizeTranslationDirective, translationIdentifiers) {
4685
- const vueOptions = vuePlugin.api.options;
4686
- vueOptions.template ||= {};
4687
- vueOptions.template.compilerOptions ||= {};
4688
- vueOptions.template.compilerOptions.directiveTransforms ||= {};
4689
- const translationSignatureResolver = (context, baseResolver) => {
4690
- const { filename } = context;
4691
- const vuePluginOptions = getVuePluginOptions(vuePlugin);
4692
- const normalizedFilename = normalizePath(path.relative(vuePluginOptions.root, filename));
4693
- const resolveIdentifier2 = translationIdentifiers.get(normalizedFilename);
4694
- debug$2("resolved vue-i18n Identifier", resolveIdentifier2);
4695
- if (resolveIdentifier2 == null) {
4696
- return void 0;
3558
+ for (const char of value) {
3559
+ if (REGEX_SEPARATORS.test(char)) {
3560
+ flush();
3561
+ buffer = "";
3562
+ previousUpper = void 0;
3563
+ previousSplitter = true;
3564
+ continue;
4697
3565
  }
4698
- if (resolveIdentifier2.type === "identifier") {
4699
- return baseResolver(context, resolveIdentifier2.key);
3566
+ const isUpper = isUppercase(char);
3567
+ const boundary = previousSplitter === false ? caseBoundary(previousUpper, isUpper, buffer) : void 0;
3568
+ if (boundary === "before") {
3569
+ flush();
3570
+ buffer = char;
3571
+ } else if (boundary === "after") {
3572
+ parts.push(buffer.slice(0, -1));
3573
+ buffer = buffer.at(-1) + char;
4700
3574
  } else {
4701
- const resolvedSignature = baseResolver(context, resolveIdentifier2.key);
4702
- return resolveIdentifier2?.style === "script-setup" ? `${resolvedSignature}.t` : resolvedSignature;
4703
- }
4704
- };
4705
- vueOptions.template.compilerOptions.directiveTransforms.t = transformVTDirective({
4706
- translationSignatures: isBoolean(optimizeTranslationDirective) ? translationSignatureResolver : optimizeTranslationDirective
4707
- });
4708
- return vueOptions;
4709
- }
4710
- function analyzeIdentifiers(descriptor, { root }, translationIdentifiers) {
4711
- const source = descriptor.scriptSetup?.content || descriptor.script?.content;
4712
- debug$2("getDescriptor content", source);
4713
- if (!source) {
4714
- return;
4715
- }
4716
- const ast = tsEstree.parse(source, { range: true });
4717
- tsEstree.simpleTraverse(ast, {
4718
- enter(node, parent) {
4719
- if (parent) {
4720
- node.parent = parent;
4721
- }
4722
- }
4723
- });
4724
- const scopeManager = analyze(ast, { sourceType: "module" });
4725
- const scope = getScope(scopeManager, ast);
4726
- const importLocalName = getImportLocalName(scope, "vue-i18n", "useI18n");
4727
- if (importLocalName == null) {
4728
- return;
4729
- }
4730
- debug$2("importLocalName", importLocalName);
4731
- const resolvedIdentifier = getVueI18nIdentifier(scope, importLocalName);
4732
- if (resolvedIdentifier) {
4733
- const normalizedFilename = normalizePath(path.relative(root, descriptor.filename));
4734
- debug$2("set vue-i18n resolved identifier: ", resolvedIdentifier);
4735
- translationIdentifiers.set(normalizedFilename, resolvedIdentifier);
4736
- }
4737
- }
4738
- function getScope(manager, node) {
4739
- const scope = manager.acquire(node, true);
4740
- if (scope) {
4741
- if (scope.type === "function-expression-name") {
4742
- return scope.childScopes[0];
3575
+ buffer += char;
4743
3576
  }
4744
- return scope;
3577
+ previousUpper = isUpper;
3578
+ previousSplitter = false;
4745
3579
  }
4746
- return manager.scopes[0];
3580
+ flush();
3581
+ return parts;
4747
3582
  }
4748
- function getImportLocalName(scope, source, imported) {
4749
- const importDecl = getImportDeclaration(scope, source);
4750
- if (importDecl) {
4751
- const specifierNode = importDecl.specifiers.find(
4752
- (specifierNode2) => isImportedIdentifierInImportClause(specifierNode2) && specifierNode2.imported.name === imported
4753
- );
4754
- return specifierNode ? specifierNode.local.name : null;
4755
- }
4756
- return null;
3583
+ function kebabCaseSegments(segments) {
3584
+ return segments.map((segment) => segment.toLowerCase()).join("-").replace(REGEX_NON_ALPHANUMERIC, "-").replace(REGEX_REPEATED_DASH, "-").replace(REGEX_EDGE_DASH, "");
4757
3585
  }
4758
- function getImportDeclaration(scope, source) {
4759
- const tracker = new eslintUitls.ReferenceTracker(scope);
4760
- const traceMap = {
4761
- [source]: {
4762
- [eslintUitls.ReferenceTracker.ESM]: true,
4763
- [eslintUitls.ReferenceTracker.READ]: true
3586
+ function resolveLayoutNameSegments(fileName, prefixParts) {
3587
+ const fileNameParts = splitByCase(fileName);
3588
+ const fileNamePartsContent = fileNameParts.join("/").toLowerCase();
3589
+ const layoutNameParts = prefixParts.flatMap((part) => splitByCase(part));
3590
+ const matchedSuffix = [];
3591
+ let index = prefixParts.length - 1;
3592
+ while (index >= 0) {
3593
+ const prefixPart = prefixParts[index];
3594
+ matchedSuffix.unshift(...splitByCase(prefixPart).map((part) => part.toLowerCase()));
3595
+ const matchedSuffixContent = matchedSuffix.join("/");
3596
+ if (fileNamePartsContent === matchedSuffixContent || fileNamePartsContent.startsWith(`${matchedSuffixContent}/`) || prefixPart.toLowerCase() === fileNamePartsContent && prefixParts[index + 1] && prefixParts[index] === prefixParts[index + 1]) {
3597
+ layoutNameParts.length = index;
4764
3598
  }
4765
- };
4766
- const refs = Array.from(tracker.iterateEsmReferences(traceMap));
4767
- return refs.length ? refs[0].node : null;
4768
- }
4769
- function isImportedIdentifierInImportClause(node) {
4770
- return "imported" in node;
4771
- }
4772
- function getVueI18nIdentifier(scope, local) {
4773
- const { callExpression, returnStatement } = getCallExpressionAndReturnStatement(scope, local);
4774
- if (callExpression == null) {
4775
- return null;
4776
- }
4777
- const id = getVariableDeclarationIdFrom(callExpression);
4778
- if (id == null) {
4779
- return null;
4780
- }
4781
- const variableIdPairs = parseVariableId(id);
4782
- debug$2("variableIdPairs:", variableIdPairs);
4783
- const returnVariableIdPairs = parseReturnStatement(returnStatement);
4784
- debug$2("returnVariableIdPairs:", returnVariableIdPairs);
4785
- return resolveIdentifier(variableIdPairs, returnVariableIdPairs);
4786
- }
4787
- const EMPTY_NODE_RETURN = {
4788
- callExpression: null,
4789
- returnStatement: null
4790
- };
4791
- function getCallExpressionAndReturnStatement(scope, local) {
4792
- const variable = eslintUitls.findVariable(scope, local);
4793
- if (variable == null) {
4794
- return EMPTY_NODE_RETURN;
4795
- }
4796
- const callExpressionRef = variable.references.find((ref) => {
4797
- return ref.identifier.parent?.type === tsEstree.AST_NODE_TYPES.CallExpression;
4798
- });
4799
- if (callExpressionRef == null) {
4800
- return EMPTY_NODE_RETURN;
4801
- }
4802
- let returnStatement = null;
4803
- if (callExpressionRef.from.type === "function" && callExpressionRef.from.block.type === tsEstree.AST_NODE_TYPES.FunctionExpression && // @ts-expect-error -- FIXME: type error
4804
- callExpressionRef.from.block.parent.type === tsEstree.AST_NODE_TYPES.Property && // @ts-expect-error -- FIXME: type error
4805
- callExpressionRef.from.block.parent.key.type === tsEstree.AST_NODE_TYPES.Identifier && // @ts-expect-error -- FIXME: type error
4806
- callExpressionRef.from.block.parent.key.name === "setup") {
4807
- returnStatement = callExpressionRef.from.block.body.body.find((statement) => {
4808
- return statement.type === tsEstree.AST_NODE_TYPES.ReturnStatement;
4809
- });
3599
+ index -= 1;
4810
3600
  }
4811
- return {
4812
- // @ts-expect-error -- FIXME: type error
4813
- callExpression: callExpressionRef.identifier.parent,
4814
- returnStatement
4815
- };
3601
+ return [...layoutNameParts, ...fileNameParts];
4816
3602
  }
4817
- function getVariableDeclarationIdFrom(node) {
4818
- if (node.parent?.type !== tsEstree.AST_NODE_TYPES.VariableDeclarator) {
4819
- return null;
4820
- }
4821
- return node.parent.id;
3603
+ function normalizeLayoutName(file) {
3604
+ const normalizedFile = file.replace(REGEX_BACKSLASH, "/");
3605
+ const slashIndex = normalizedFile.lastIndexOf("/");
3606
+ const dir = slashIndex === -1 ? "" : normalizedFile.slice(0, slashIndex);
3607
+ const basename = slashIndex === -1 ? normalizedFile : normalizedFile.slice(slashIndex + 1);
3608
+ const dotIndex = basename.lastIndexOf(".");
3609
+ const name = dotIndex <= 0 ? basename : basename.slice(0, dotIndex);
3610
+ const prefixParts = splitByCase(dir);
3611
+ return kebabCaseSegments(
3612
+ resolveLayoutNameSegments(dir && name.toLowerCase() === "index" ? "" : name, prefixParts).filter(Boolean)
3613
+ );
4822
3614
  }
4823
- function parseVariableId(node) {
4824
- if (node.type === tsEstree.AST_NODE_TYPES.Identifier) {
4825
- return [{ key: node.name, value: null }];
4826
- } else {
4827
- const props = node.properties.filter(
4828
- // ignore RestElement
4829
- (prop) => prop.type === tsEstree.AST_NODE_TYPES.Property
4830
- );
4831
- const pairs = [];
4832
- for (const prop of props) {
4833
- if (prop?.key.type === tsEstree.AST_NODE_TYPES.Identifier && prop?.value.type === tsEstree.AST_NODE_TYPES.Identifier) {
4834
- pairs.push({ key: prop.key.name, value: prop.value.name });
4835
- }
3615
+ function resolveLayoutsDirs(layoutsDirs, root) {
3616
+ const dirs = [];
3617
+ for (const dir of Array.isArray(layoutsDirs) ? layoutsDirs : [layoutsDirs]) {
3618
+ if (dir.includes("**")) {
3619
+ const matches = globSync(dir, { cwd: root, onlyDirectories: true, absolute: true, expandDirectories: false });
3620
+ dirs.push(...matches.sort().map((match) => normalize(match).replace(/\/$/, "")));
3621
+ } else {
3622
+ dirs.push(normalize(resolve$1(root, dir)));
4836
3623
  }
4837
- return pairs;
4838
3624
  }
3625
+ return dirs;
4839
3626
  }
4840
- function parseReturnStatement(node) {
4841
- const pairs = [];
4842
- if (node == null || node.argument == null) {
4843
- return pairs;
4844
- }
4845
- if (node.argument.type === tsEstree.AST_NODE_TYPES.ObjectExpression) {
4846
- for (const prop of node.argument.properties) {
4847
- if (prop.type === tsEstree.AST_NODE_TYPES.Property) {
4848
- if (prop.key.type === tsEstree.AST_NODE_TYPES.Identifier && prop.value.type === tsEstree.AST_NODE_TYPES.Identifier) {
4849
- pairs.push({ key: prop.key.name, value: prop.value.name });
4850
- } else if (prop.key.type === tsEstree.AST_NODE_TYPES.Identifier && prop.value.type === tsEstree.AST_NODE_TYPES.MemberExpression && prop.value.object.type === tsEstree.AST_NODE_TYPES.Identifier && prop.value.property.type === tsEstree.AST_NODE_TYPES.Identifier) {
4851
- pairs.push({
4852
- key: prop.key.name,
4853
- value: `${prop.value.object.name}.${prop.value.property.name}`
4854
- });
4855
- }
4856
- }
3627
+ function resolveLayoutsOptions(options, userOptions = {}) {
3628
+ const resolved = {
3629
+ layoutsDirs: options.roots.map((root) => `${root}/layouts`),
3630
+ extensions: ["vue"],
3631
+ exclude: [],
3632
+ defaultLayout: "default",
3633
+ // In SSG builds, layout components must be imported synchronously so that
3634
+ // the client-side hydration tree matches the server-rendered HTML. Lazy
3635
+ // non-default layouts (post, home, etc.) would not have resolved when
3636
+ // hydration starts, causing a mismatch.
3637
+ importMode: options.mode === "build" ? () => "sync" : defaultImportMode,
3638
+ inheritDefaultLayout: true
3639
+ };
3640
+ for (const [key, value] of Object.entries(userOptions)) {
3641
+ if (value !== void 0)
3642
+ resolved[key] = value;
3643
+ }
3644
+ return { ...resolved, dirs: resolveLayoutsDirs(resolved.layoutsDirs, options.userRoot) };
3645
+ }
3646
+ async function scanLayouts(options) {
3647
+ const pattern = options.extensions.length > 1 ? `**/*.{${options.extensions.join(",")}}` : `**/*.${options.extensions[0] || ""}`;
3648
+ const layouts = /* @__PURE__ */ new Map();
3649
+ const dirFiles = await Promise.all(options.dirs.map((dir) => glob(pattern, {
3650
+ cwd: dir,
3651
+ ignore: ["**/node_modules/**", "**/.git/**", "**/__*__/*", ...options.exclude],
3652
+ onlyFiles: true,
3653
+ expandDirectories: false
3654
+ })));
3655
+ options.dirs.forEach((dir, index) => {
3656
+ for (const file of dirFiles[index].sort()) {
3657
+ const name = normalizeLayoutName(file);
3658
+ layouts.delete(name);
3659
+ layouts.set(name, normalize(resolve$1(dir, file)));
4857
3660
  }
4858
- return pairs;
4859
- } else if (node.argument.type === tsEstree.AST_NODE_TYPES.Identifier) {
4860
- return pairs;
4861
- } else {
4862
- return pairs;
4863
- }
3661
+ });
3662
+ return layouts;
4864
3663
  }
4865
- function resolveIdentifier(localVariables, returnVariable) {
4866
- if (returnVariable.length === 0) {
4867
- const variable = localVariables.find((pair) => pair.key === "t");
4868
- if (variable && variable.value) {
4869
- return { type: "identifier", key: variable.value };
4870
- }
4871
- const identifierOnly = localVariables.find((pair) => pair.value === null);
4872
- if (identifierOnly && identifierOnly.key) {
4873
- return { type: "object", key: identifierOnly.key, style: "script-setup" };
4874
- }
4875
- return null;
4876
- } else {
4877
- const variable = localVariables.find((pair) => pair.key === "t");
4878
- if (variable && variable.value) {
4879
- const returnVar = returnVariable.find((pair) => pair.value === variable.value);
4880
- if (returnVar && returnVar.key) {
4881
- return { type: "identifier", key: returnVar.key };
4882
- }
4883
- }
4884
- const identifierOnly = localVariables.find((pair) => pair.value === null);
4885
- if (identifierOnly && identifierOnly.key) {
4886
- const targetKey = identifierOnly.key;
4887
- const returnVar = returnVariable.find((pair) => pair.value?.startsWith(targetKey));
4888
- if (returnVar && returnVar.key) {
4889
- return { type: "object", key: returnVar.key, style: "setup-hook" };
4890
- }
3664
+ function generateLayoutsCode(layouts, options, runtime) {
3665
+ const head = [];
3666
+ const entries = [];
3667
+ for (const [name, file] of layouts) {
3668
+ const id = JSON.stringify(toAtFS(file));
3669
+ if (options.importMode(name) === "sync") {
3670
+ const variable = `__layout_${head.length}`;
3671
+ head.push(`import ${variable} from ${id}`);
3672
+ entries.push(` ${JSON.stringify(name)}: ${variable},`);
3673
+ } else {
3674
+ entries.push(` ${JSON.stringify(name)}: lazyLayout(() => import(${id})),`);
4891
3675
  }
4892
- return null;
4893
3676
  }
3677
+ const fallbackArg = options.fallbackLayout ? `, ${JSON.stringify(options.fallbackLayout)}` : "";
3678
+ return `import { createGetRoutes, createLayoutWrapper, createSetupLayouts, lazyLayout, setPageLayout, useLayout } from ${JSON.stringify(toAtFS(runtime))}
3679
+ ${head.join("\n")}
3680
+ export { createGetRoutes, setPageLayout, useLayout }
3681
+ export const layouts = {
3682
+ ${entries.join("\n")}
4894
3683
  }
4895
- function matchSafelistPattern(keyPath, pattern) {
4896
- const regexStr = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^.]*").replace(/\{\{GLOBSTAR\}\}/g, ".*");
4897
- return new RegExp(`^${regexStr}$`).test(keyPath);
3684
+ const LayoutWrapper = createLayoutWrapper(layouts, ${JSON.stringify(options.defaultLayout)}${fallbackArg})
3685
+ export const setupLayouts = createSetupLayouts(LayoutWrapper, { inheritDefaultLayout: ${options.inheritDefaultLayout} })
3686
+ `;
4898
3687
  }
4899
- function createUsedKeysCollector(options) {
4900
- const usedKeys = /* @__PURE__ */ new Set();
4901
- const safelistPatterns = options.safelist || [];
4902
- const dynamicKeyStrategy = options.dynamicKeyStrategy || "keep-all";
4903
- const removedKeys = /* @__PURE__ */ new Map();
4904
- let dynamicKeysDetected = false;
3688
+ function createLayoutsPlugin(options) {
3689
+ const runtime = resolve$1(options.clientRoot, "utils/layouts.ts");
3690
+ const resolveOptions = () => resolveLayoutsOptions(options, options.config.layouts);
3691
+ const isLayoutFile = (file, layoutsOptions) => {
3692
+ const path = normalize(file);
3693
+ return layoutsOptions.extensions.some((ext) => path.endsWith(`.${ext}`)) && layoutsOptions.dirs.some((dir) => {
3694
+ const rel = relative(dir, path);
3695
+ return !!rel && !rel.startsWith("..") && !isAbsolute(rel);
3696
+ });
3697
+ };
4905
3698
  return {
4906
- get usedKeys() {
4907
- return usedKeys;
4908
- },
4909
- get dynamicKeysDetected() {
4910
- return dynamicKeysDetected;
4911
- },
4912
- set dynamicKeysDetected(val) {
4913
- dynamicKeysDetected = val;
4914
- },
4915
- safelistPatterns,
4916
- removedKeys,
4917
- addKey(key) {
4918
- usedKeys.add(key);
4919
- },
4920
- markDynamic() {
4921
- dynamicKeysDetected = true;
4922
- },
4923
- shouldKeepKey(keyPath) {
4924
- if (dynamicKeysDetected && dynamicKeyStrategy === "keep-all") {
4925
- return true;
4926
- }
4927
- if (safelistPatterns.some((pattern) => matchSafelistPattern(keyPath, pattern))) {
4928
- return true;
4929
- }
4930
- if (usedKeys.has(keyPath)) {
4931
- return true;
4932
- }
4933
- for (const key of usedKeys) {
4934
- if (key.startsWith(keyPath + ".")) {
4935
- return true;
4936
- }
4937
- }
4938
- return false;
3699
+ name: "valaxy:layouts",
3700
+ resolveId(id) {
3701
+ if (id === LAYOUTS_MODULE_ID)
3702
+ return RESOLVED_LAYOUTS_MODULE_ID;
4939
3703
  },
4940
- reportRemoved(filename, keyPath) {
4941
- const existing = removedKeys.get(filename);
4942
- if (existing) {
4943
- existing.push(keyPath);
4944
- } else {
4945
- removedKeys.set(filename, [keyPath]);
4946
- }
3704
+ async load(id) {
3705
+ if (id !== RESOLVED_LAYOUTS_MODULE_ID)
3706
+ return;
3707
+ const layoutsOptions = resolveOptions();
3708
+ return {
3709
+ code: generateLayoutsCode(await scanLayouts(layoutsOptions), layoutsOptions, runtime),
3710
+ moduleType: "js"
3711
+ };
4947
3712
  },
4948
- getDiagnostics() {
4949
- let totalRemoved = 0;
4950
- for (const keys of removedKeys.values()) {
4951
- totalRemoved += keys.length;
4952
- }
4953
- return { totalRemoved, byFile: removedKeys };
4954
- }
4955
- };
4956
- }
4957
- const I18N_FUNCTIONS = /* @__PURE__ */ new Set(["t", "$t", "tc", "$tc", "te", "$te", "d", "$d", "n", "$n"]);
4958
- const TEMPLATE_T_REGEX = /\$?t\s*\(\s*['"]([^'"]+)['"]/g;
4959
- const VT_DIRECTIVE_STRING_REGEX = /v-t\s*=\s*"'([^']+)'"/g;
4960
- const VT_DIRECTIVE_PATH_REGEX = /v-t\s*=\s*"\{[^}]*path\s*:\s*'([^']+)'/g;
4961
- const TEMPLATE_DYNAMIC_T_REGEX = /\$?t\s*\(\s*[a-zA-Z_$]/g;
4962
- async function extractKeysFromScript(source) {
4963
- const keys = [];
4964
- let hasDynamic = false;
4965
- let tsEstree2;
4966
- try {
4967
- tsEstree2 = await import('@typescript-eslint/typescript-estree');
4968
- } catch {
4969
- return extractKeysFromScriptRegex(source);
4970
- }
4971
- try {
4972
- const ast = tsEstree2.parse(source, {
4973
- range: true,
4974
- jsx: true,
4975
- allowInvalidAST: true,
4976
- suppressDeprecatedPropertyWarnings: true
4977
- });
4978
- tsEstree2.simpleTraverse(ast, {
4979
- enter(node) {
4980
- if (node.type !== tsEstree2.AST_NODE_TYPES.CallExpression) {
4981
- return;
4982
- }
4983
- const calleeName = getCalleeName(node, tsEstree2.AST_NODE_TYPES);
4984
- if (!calleeName || !I18N_FUNCTIONS.has(calleeName)) {
4985
- return;
4986
- }
4987
- const firstArg = node.arguments[0];
4988
- if (!firstArg) {
3713
+ configureServer(server) {
3714
+ server.watcher.add(resolveOptions().dirs);
3715
+ const invalidate = (file) => {
3716
+ if (!isLayoutFile(file, resolveOptions()))
4989
3717
  return;
3718
+ for (const environment of Object.values(server.environments)) {
3719
+ const module = environment.moduleGraph.getModuleById(RESOLVED_LAYOUTS_MODULE_ID);
3720
+ if (module)
3721
+ environment.moduleGraph.invalidateModule(module);
4990
3722
  }
4991
- if (firstArg.type === tsEstree2.AST_NODE_TYPES.Literal && typeof firstArg.value === "string") {
4992
- keys.push(firstArg.value);
4993
- } else if (firstArg.type === tsEstree2.AST_NODE_TYPES.TemplateLiteral && firstArg.expressions.length === 0 && firstArg.quasis.length === 1) {
4994
- const value = firstArg.quasis[0].value.cooked;
4995
- if (value) {
4996
- keys.push(value);
4997
- }
4998
- } else {
4999
- hasDynamic = true;
5000
- }
5001
- }
5002
- });
5003
- } catch {
5004
- return extractKeysFromScriptRegex(source);
5005
- }
5006
- return { keys, hasDynamic };
5007
- }
5008
- function getCalleeName(node, AST_NODE_TYPES) {
5009
- const callee = node.callee;
5010
- if (callee.type === AST_NODE_TYPES.Identifier) {
5011
- return callee.name;
5012
- }
5013
- if (callee.type === AST_NODE_TYPES.MemberExpression && callee.property.type === AST_NODE_TYPES.Identifier) {
5014
- return callee.property.name;
5015
- }
5016
- return null;
5017
- }
5018
- function extractKeysFromScriptRegex(source) {
5019
- const keys = [];
5020
- let match;
5021
- const regex = /\b(?:\$?t|tc|\$tc|te|\$te|d|\$d|n|\$n)\s*\(\s*['"]([^'"]+)['"]/g;
5022
- while ((match = regex.exec(source)) !== null) {
5023
- keys.push(match[1]);
5024
- }
5025
- return { keys, hasDynamic: false };
5026
- }
5027
- function extractKeysFromTemplate(templateContent) {
5028
- const keys = [];
5029
- let hasDynamic = false;
5030
- let match;
5031
- TEMPLATE_T_REGEX.lastIndex = 0;
5032
- VT_DIRECTIVE_STRING_REGEX.lastIndex = 0;
5033
- VT_DIRECTIVE_PATH_REGEX.lastIndex = 0;
5034
- TEMPLATE_DYNAMIC_T_REGEX.lastIndex = 0;
5035
- while ((match = TEMPLATE_T_REGEX.exec(templateContent)) !== null) {
5036
- keys.push(match[1]);
5037
- }
5038
- while ((match = VT_DIRECTIVE_STRING_REGEX.exec(templateContent)) !== null) {
5039
- keys.push(match[1]);
5040
- }
5041
- while ((match = VT_DIRECTIVE_PATH_REGEX.exec(templateContent)) !== null) {
5042
- keys.push(match[1]);
5043
- }
5044
- if (TEMPLATE_DYNAMIC_T_REGEX.test(templateContent)) {
5045
- hasDynamic = true;
5046
- }
5047
- return { keys, hasDynamic };
5048
- }
5049
- async function analyzeVueSFC(content) {
5050
- const keys = [];
5051
- let hasDynamic = false;
5052
- let parse2;
5053
- try {
5054
- const compilerSfc = await import('vue/compiler-sfc');
5055
- parse2 = compilerSfc.parse;
5056
- } catch {
5057
- const templateResult = extractKeysFromTemplate(content);
5058
- const scriptResult = await extractKeysFromScript(content);
5059
- return {
5060
- keys: [...templateResult.keys, ...scriptResult.keys],
5061
- hasDynamic: templateResult.hasDynamic || scriptResult.hasDynamic
5062
- };
5063
- }
5064
- const { descriptor } = parse2(content);
5065
- if (descriptor.template?.content) {
5066
- const templateResult = extractKeysFromTemplate(descriptor.template.content);
5067
- keys.push(...templateResult.keys);
5068
- if (templateResult.hasDynamic) {
5069
- hasDynamic = true;
5070
- }
5071
- }
5072
- const scriptContent = descriptor.scriptSetup?.content || descriptor.script?.content;
5073
- if (scriptContent) {
5074
- const scriptResult = await extractKeysFromScript(scriptContent);
5075
- keys.push(...scriptResult.keys);
5076
- if (scriptResult.hasDynamic) {
5077
- hasDynamic = true;
5078
- }
5079
- }
5080
- return { keys, hasDynamic };
5081
- }
5082
- async function analyzeFile(content, filePath, collector) {
5083
- let result;
5084
- if (filePath.endsWith(".vue")) {
5085
- result = await analyzeVueSFC(content);
5086
- } else {
5087
- result = await extractKeysFromScript(content);
5088
- }
5089
- for (const key of result.keys) {
5090
- collector.addKey(key);
5091
- }
5092
- if (result.hasDynamic) {
5093
- collector.markDynamic();
5094
- }
5095
- }
5096
- const debug$1$1 = createDebug(resolveNamespace("tree-shaking"));
5097
- function treeShakingPlugin(resolvedOptions, collector) {
5098
- let projectRoot = "";
5099
- return {
5100
- name: resolveNamespace("tree-shaking"),
5101
- enforce: "pre",
5102
- vite: {
5103
- configResolved(config) {
5104
- projectRoot = config.root;
5105
- }
5106
- },
5107
- webpack(compiler) {
5108
- projectRoot = compiler.options.context || process.cwd();
5109
- },
5110
- async buildStart() {
5111
- const treeShaking = resolvedOptions.treeShaking;
5112
- const patterns = treeShaking?.scanPatterns || [`${projectRoot}/src/**/*.{vue,ts,js,tsx,jsx}`];
5113
- debug$1$1("scanning patterns:", patterns);
5114
- const files = await glob(patterns, {
5115
- ignore: ["**/node_modules/**"],
5116
- absolute: true
3723
+ server.ws.send({ type: "full-reload" });
3724
+ };
3725
+ server.watcher.on("add", invalidate);
3726
+ server.watcher.on("unlink", invalidate);
3727
+ server.httpServer?.once("close", () => {
3728
+ server.watcher.off("add", invalidate);
3729
+ server.watcher.off("unlink", invalidate);
5117
3730
  });
5118
- debug$1$1(`found ${files.length} source files to scan`);
5119
- for (const file of files) {
5120
- try {
5121
- const content = await promises.readFile(file, "utf-8");
5122
- await analyzeFile(content, file, collector);
5123
- } catch (err) {
5124
- debug$1$1(`failed to analyze file: ${file}`, err);
5125
- }
5126
- }
5127
- debug$1$1(
5128
- `scan complete: ${collector.usedKeys.size} used keys found, dynamic: ${collector.dynamicKeysDetected}`
5129
- );
5130
- if (collector.dynamicKeysDetected) {
5131
- const strategy = treeShaking?.dynamicKeyStrategy || "keep-all";
5132
- if (strategy === "keep-all") {
5133
- warn(
5134
- "Tree-shaking: dynamic key usage detected. All keys will be preserved (dynamicKeyStrategy: keep-all)."
5135
- );
5136
- } else {
5137
- warn(
5138
- "Tree-shaking: dynamic key usage detected. Unused keys will still be removed (dynamicKeyStrategy: ignore)."
5139
- );
5140
- }
5141
- }
5142
- },
5143
- buildEnd() {
5144
- const diagnostics = collector.getDiagnostics();
5145
- if (diagnostics.totalRemoved > 0) {
5146
- debug$1$1(`tree-shaking: removed ${diagnostics.totalRemoved} unused message keys`);
5147
- for (const [file, keys] of diagnostics.byFile) {
5148
- debug$1$1(` ${file}: removed ${keys.length} keys (${keys.join(", ")})`);
5149
- }
5150
- } else {
5151
- debug$1$1("tree-shaking: no keys removed");
5152
- }
5153
3731
  }
5154
3732
  };
5155
3733
  }
5156
- const debug$4 = createDebug(resolveNamespace("root"));
5157
- const unpluginFactory = (options = {}, meta) => {
5158
- debug$4("meta framework", meta.framework);
5159
- if (!["vite", "webpack"].includes(meta.framework)) {
5160
- raiseError(`This plugin is supported 'vite' and 'webpack' only`);
5161
- }
5162
- debug$4("plugin options (resolving):", options);
5163
- const resolvedOptions = resolveOptions(options);
5164
- debug$4("plugin options (resolved):", resolvedOptions);
5165
- const collector = resolvedOptions.treeShaking ? createUsedKeysCollector(resolvedOptions.treeShaking) : null;
5166
- const plugins = [];
5167
- if (resolvedOptions.treeShaking && collector) {
5168
- plugins.push(treeShakingPlugin(resolvedOptions, collector));
5169
- }
5170
- plugins.push(resourcePlugin(resolvedOptions, meta, collector));
5171
- if (resolvedOptions.optimizeTranslationDirective) {
5172
- if (meta.framework === "webpack") {
5173
- raiseError(
5174
- `The 'optimizeTranslationDirective' option still is not supported for webpack.
5175
- We are waiting for your Pull Request \u{1F642}.`
5176
- );
5177
- }
5178
- plugins.push(directivePlugin(resolvedOptions));
5179
- }
5180
- return plugins;
5181
- };
5182
- const unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
5183
-
5184
- const VueI18n = unplugin.vite;
5185
3734
 
5186
3735
  function createLlmsPlugin(options) {
5187
3736
  const llmsConfig = options.config.siteConfig.llms;
@@ -6720,7 +5269,7 @@ function cacheMarkdownRender(md, state, base, fileInfoFor) {
6720
5269
  maxSize: 32 * 1024 * 1024,
6721
5270
  sizeCalculation: (item) => item.bytes
6722
5271
  });
6723
- const log = createDebug("valaxy:md");
5272
+ const log = _debug("valaxy:md");
6724
5273
  const getBase = createMarkdownBaseResolver(base);
6725
5274
  const render = md.renderAsync.bind(md);
6726
5275
  let active = true;
@@ -6755,7 +5304,7 @@ function cacheMarkdownRender(md, state, base, fileInfoFor) {
6755
5304
  const KNOWN_EXTENSIONS = /* @__PURE__ */ new Set();
6756
5305
  function treatAsHtml(filename) {
6757
5306
  if (KNOWN_EXTENSIONS.size === 0) {
6758
- const extraExts = typeof process$1 === "object" && process$1.env.VITE_EXTRA_EXTENSIONS || process$1.env?.VITE_EXTRA_EXTENSIONS || "";
5307
+ const extraExts = typeof process === "object" && process.env.VITE_EXTRA_EXTENSIONS || process.env?.VITE_EXTRA_EXTENSIONS || "";
6759
5308
  `3g2,3gp,aac,ai,apng,au,avif,bin,bmp,cer,class,conf,crl,css,csv,dll,doc,eps,epub,exe,gif,gz,ics,ief,jar,jpe,jpeg,jpg,js,json,jsonld,m4a,man,mid,midi,mjs,mov,mp2,mp3,mp4,mpe,mpeg,mpg,mpp,oga,ogg,ogv,ogx,opus,otf,p10,p7c,p7m,p7s,pdf,png,ps,qt,roff,rtf,rtx,ser,svg,t,tif,tiff,tr,ts,tsv,ttf,txt,vtt,wav,weba,webm,webp,woff,woff2,xhtml,xml,yaml,yml,zip${extraExts && typeof extraExts === "string" ? `,${extraExts}` : ""}`.split(",").forEach((ext2) => KNOWN_EXTENSIONS.add(ext2));
6760
5309
  }
6761
5310
  const ext = filename.split(".").pop();
@@ -6805,7 +5354,7 @@ function resolveTransformIncludes(code, id, options) {
6805
5354
  code = code.replace(includedRE, (m, m1) => {
6806
5355
  const atPresent = m1.startsWith("@");
6807
5356
  const includePath = atPresent ? path$1.resolve(options.userRoot, m1.slice(m1[1] === "/" ? 2 : 1)) : path$1.join(dir, m1);
6808
- includes.push(slash$2(includePath));
5357
+ includes.push(slash$1(includePath));
6809
5358
  return "";
6810
5359
  });
6811
5360
  return {
@@ -6956,7 +5505,7 @@ async function createLightMarkdownRenderer(options, base) {
6956
5505
  return md;
6957
5506
  }
6958
5507
 
6959
- const debug$1 = createDebug("valaxy:local-search");
5508
+ const debug$1 = _debug("valaxy:local-search");
6960
5509
  const LOCAL_SEARCH_INDEX_ID = "@localSearchIndex";
6961
5510
  const LOCAL_SEARCH_INDEX_REQUEST_PATH = `/${LOCAL_SEARCH_INDEX_ID}`;
6962
5511
  async function localSearchPlugin(options, base) {
@@ -6981,7 +5530,7 @@ async function localSearchPlugin(options, base) {
6981
5530
  async function render(file) {
6982
5531
  if (!fs.existsSync(file))
6983
5532
  return { html: "", shared: false };
6984
- const relativePath = getPagePath(file, options.userRoot) || slash$2(path.relative(srcDir, file));
5533
+ const relativePath = getPagePath(file, options.userRoot) || slash$1(path.relative(srcDir, file));
6985
5534
  const env = { path: file, relativePath };
6986
5535
  const mdRaw = await fs.promises.readFile(file, "utf-8");
6987
5536
  const { data: fm, content } = matter(mdRaw, matterOptions);
@@ -7025,8 +5574,8 @@ async function localSearchPlugin(options, base) {
7025
5574
  }
7026
5575
  }
7027
5576
  function getDocId(file) {
7028
- const relFile = getPagePath(file, options.userRoot) || slash$2(path.relative(srcDir, file));
7029
- let id = slash$2(path.join("/", relFile));
5577
+ const relFile = getPagePath(file, options.userRoot) || slash$1(path.relative(srcDir, file));
5578
+ let id = slash$1(path.join("/", relFile));
7030
5579
  id = id.replace(/(^|\/)index\.md$/, "$1");
7031
5580
  id = id.replace(/\.md$/, "");
7032
5581
  return id;
@@ -7152,7 +5701,7 @@ async function localSearchPlugin(options, base) {
7152
5701
  },
7153
5702
  async load(id) {
7154
5703
  if (id === LOCAL_SEARCH_INDEX_REQUEST_PATH) {
7155
- if (process$1.env.NODE_ENV === "production") {
5704
+ if (process.env.NODE_ENV === "production") {
7156
5705
  await scanForBuild();
7157
5706
  }
7158
5707
  const records = [];
@@ -7174,7 +5723,7 @@ async function localSearchPlugin(options, base) {
7174
5723
  },
7175
5724
  async handleHotUpdate({ file }) {
7176
5725
  if (file.endsWith(".md")) {
7177
- const relPath = getPagePath(file, options.userRoot) || slash$2(path.relative(srcDir, file));
5726
+ const relPath = getPagePath(file, options.userRoot) || slash$1(path.relative(srcDir, file));
7178
5727
  if (!relPath.startsWith("..")) {
7179
5728
  changedPages.add(relPath);
7180
5729
  await flushUpdates();
@@ -7283,7 +5832,7 @@ function createScanDeadLinks(options) {
7283
5832
  if (url.endsWith("/"))
7284
5833
  url += `index`;
7285
5834
  const resolved = decodeURIComponent(
7286
- slash$2(
5835
+ slash$1(
7287
5836
  url.startsWith("/") ? url.slice(1) : path$1.normalize(path$1.join(path$1.dirname(logicalFile), url))
7288
5837
  )
7289
5838
  // /index => /
@@ -7310,7 +5859,7 @@ function createTransformEncrypt(options) {
7310
5859
  "</ClientOnly>"
7311
5860
  ].join("");
7312
5861
  };
7313
- const globalPassword = process$1.env.VALAXY_ENCRYPT_PASSWORD;
5862
+ const globalPassword = process.env.VALAXY_ENCRYPT_PASSWORD;
7314
5863
  const password = frontmatter.password || frontmatter.encrypt === true && globalPassword || void 0;
7315
5864
  if (password && !frontmatter.password && globalPassword) {
7316
5865
  if (!globalPasswordLoggedOnce) {
@@ -7520,7 +6069,7 @@ async function generatePageData(code, context, options) {
7520
6069
  return pageData;
7521
6070
  }
7522
6071
 
7523
- const debug = createDebug("valaxy:md");
6072
+ const debug = _debug("valaxy:md");
7524
6073
  const caches = /* @__PURE__ */ new WeakMap();
7525
6074
  function getMarkdownCache(state) {
7526
6075
  let cache = caches.get(state);
@@ -7629,7 +6178,7 @@ function createClientSetupPlugin(options) {
7629
6178
  if (legacySetup)
7630
6179
  warnMermaidMigration(options, legacySetup);
7631
6180
  }
7632
- const setupEntry = slash$2(resolve(clientRoot, "setup"));
6181
+ const setupEntry = slash$1(resolve(clientRoot, "setup"));
7633
6182
  return {
7634
6183
  name: "valaxy:setup",
7635
6184
  enforce: "pre",
@@ -8052,7 +6601,7 @@ async function createValaxyPlugin(options, serverOptions = {}, state = Valaxy.st
8052
6601
  };
8053
6602
  const configFiles = [options.configFile, options.siteConfigFile, resolve$1(options.themeRoot, "valaxy.config.ts")];
8054
6603
  if (configFiles.includes(file)) {
8055
- const { config } = await resolveOptions$3({ userRoot: options.userRoot });
6604
+ const { config } = await resolveOptions$1({ userRoot: options.userRoot });
8056
6605
  return reloadConfigAndEntries(config);
8057
6606
  }
8058
6607
  if (file === options.themeConfigFile) {
@@ -8200,8 +6749,12 @@ async function createRouterOptions(valaxyApp, base, parseMatter = (source) => ma
8200
6749
  }
8201
6750
  }
8202
6751
  const path = route.components.get("default") || "";
8203
- if (path.endsWith(".md")) {
8204
- const md = await fs.readFile(path, "utf-8");
6752
+ const md = path.endsWith(".md") ? await fs.readFile(path, "utf-8").catch((e) => {
6753
+ if (e.code === "ENOENT" || e.code === "ENOTDIR")
6754
+ return void 0;
6755
+ throw e;
6756
+ }) : void 0;
6757
+ if (md !== void 0) {
8205
6758
  const { data, excerpt, content } = parseMatter(md);
8206
6759
  const mdFm = data;
8207
6760
  const lastUpdated = valaxyConfig.siteConfig.lastUpdated;
@@ -8479,17 +7032,7 @@ async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {},
8479
7032
  Unhead(),
8480
7033
  // https://router.vuejs.org/file-based-routing/
8481
7034
  RouterPlugin,
8482
- // https://github.com/loicduong/vite-plugin-vue-layouts-next
8483
- Layout({
8484
- layoutsDirs: roots.map((root) => `${root}/layouts`),
8485
- // In SSG builds, layout components must be imported synchronously so that
8486
- // the client-side hydration tree matches the server-rendered HTML. Without
8487
- // this, non-default layouts (post, home, etc.) are lazy-loaded and haven't
8488
- // resolved when hydration starts, causing a mismatch. The built-in SSG
8489
- // engine needs an explicit importMode override to force synchronous imports.
8490
- ...options.mode === "build" ? { importMode: () => "sync" } : {},
8491
- ...valaxyConfig.layouts
8492
- }),
7035
+ createLayoutsPlugin(options),
8493
7036
  // https://github.com/antfu/unplugin-vue-components
8494
7037
  Components({
8495
7038
  extensions: ["vue", "md"],
@@ -8568,13 +7111,13 @@ async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {},
8568
7111
  }
8569
7112
 
8570
7113
  async function profileBuildPhase(phase, run) {
8571
- if (!process$1.env.VALAXY_BUILD_PROFILE)
7114
+ if (!process.env.VALAXY_BUILD_PROFILE)
8572
7115
  return run();
8573
7116
  const started = performance.now();
8574
7117
  try {
8575
7118
  return await run();
8576
7119
  } finally {
8577
- process$1.stdout.write(`[valaxy:build] ${JSON.stringify({ phase, durationMs: performance.now() - started, rssMiB: process$1.memoryUsage().rss / 1024 / 1024 })}
7120
+ process.stdout.write(`[valaxy:build] ${JSON.stringify({ phase, durationMs: performance.now() - started, rssMiB: process.memoryUsage().rss / 1024 / 1024 })}
8578
7121
  `);
8579
7122
  }
8580
7123
  }
@@ -8657,7 +7200,15 @@ function serializeState(state) {
8657
7200
  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");
8658
7201
  return `<script>window.__INITIAL_STATE__='${serialised}'<\/script>`;
8659
7202
  }
7203
+ function decodePathSegment(segment) {
7204
+ try {
7205
+ return decodeURIComponent(segment);
7206
+ } catch {
7207
+ return segment;
7208
+ }
7209
+ }
8660
7210
  function routeToFileName(route) {
7211
+ route = route.split("/").map(decodePathSegment).join("/");
8661
7212
  if (route.endsWith("/"))
8662
7213
  return `${route}index.html`.slice(1);
8663
7214
  if (route.endsWith(".html"))
@@ -9146,7 +7697,7 @@ function getServerInfoText(msg) {
9146
7697
  return `${valaxyPrefix} ${colors.gray(msg)}`;
9147
7698
  }
9148
7699
  async function createServer(valaxyApp, viteConfig = {}, serverOptions = {}) {
9149
- process$1.env.EDITOR = process$1.env.EDITOR || "code";
7700
+ process.env.EDITOR = process.env.EDITOR || "code";
9150
7701
  const { options } = valaxyApp;
9151
7702
  const pluginsTimer = countPerformanceTime();
9152
7703
  const plugins = await ViteValaxyPlugins(valaxyApp, serverOptions, viteConfig);
@@ -9280,7 +7831,7 @@ async function initServer(valaxyApp, viteConfig) {
9280
7831
  } catch (e) {
9281
7832
  consola.error("failed to start server. error:\n");
9282
7833
  console.error(e);
9283
- process$1.exit(1);
7834
+ process.exit(1);
9284
7835
  }
9285
7836
  }
9286
7837
 
@@ -9289,7 +7840,7 @@ async function execBuild({ ssg, root, output, log, siteUrl }) {
9289
7840
  if (!await isPagesDirExist(root))
9290
7841
  throw new Error(`Pages directory not found: ${root}`);
9291
7842
  const userRoot = path.resolve(root);
9292
- const options = await profileBuildPhase("resolve-options", () => resolveOptions$3({ userRoot }, "build"));
7843
+ const options = await profileBuildPhase("resolve-options", () => resolveOptions$1({ userRoot }, "build"));
9293
7844
  if (siteUrl)
9294
7845
  options.config.siteConfig.url = siteUrl;
9295
7846
  setTimezone(options.config.siteConfig.timezone);
@@ -9369,8 +7920,8 @@ function registerBuildCommand(cli) {
9369
7920
  }
9370
7921
 
9371
7922
  async function cleanDist() {
9372
- const distDir = path.join(process$1.cwd(), "dist");
9373
- const cacheDir = path.join(process$1.cwd(), ".valaxy");
7923
+ const distDir = path.join(process.cwd(), "dist");
7924
+ const cacheDir = path.join(process.cwd(), ".valaxy");
9374
7925
  consola.box("\u{1F9F9} Starting clean...");
9375
7926
  if (await fs.exists(distDir)) {
9376
7927
  consola.info("dist directory exists, removing...");
@@ -9410,28 +7961,8 @@ function registerCleanCommand(cli) {
9410
7961
  }
9411
7962
 
9412
7963
  async function resolveContentLayouts(options) {
9413
- const configured = options.config.layouts;
9414
- const dirs = configured?.layoutsDirs ?? options.roots.map((root) => join$1(root, "layouts"));
9415
- const plugin = Layout({
9416
- ...configured,
9417
- // Array form selects the server-side registry generator, including for one directory.
9418
- layoutsDirs: Array.isArray(dirs) ? dirs : [dirs]
9419
- });
9420
- const configure = plugin.configResolved;
9421
- const load = plugin.load;
9422
- configure({ root: options.userRoot });
9423
- const source = await load("/@vite-plugin-vue-layouts-next/generated-layouts");
9424
- const ast = babelParse(source.code, { sourceType: "module" });
9425
- for (const statement of ast.program.body) {
9426
- if (statement.type !== "ExportNamedDeclaration" || statement.declaration?.type !== "VariableDeclaration")
9427
- continue;
9428
- for (const declaration of statement.declaration.declarations) {
9429
- if (declaration.id.type !== "Identifier" || declaration.id.name !== "layouts" || declaration.init?.type !== "ObjectExpression")
9430
- continue;
9431
- return new Set(declaration.init.properties.flatMap((property) => property.type === "ObjectProperty" && property.key.type === "StringLiteral" ? [property.key.value] : []));
9432
- }
9433
- }
9434
- throw new Error("Layout registry was not generated");
7964
+ const layouts = await scanLayouts(resolveLayoutsOptions(options, options.config.layouts));
7965
+ return new Set(layouts.keys());
9435
7966
  }
9436
7967
 
9437
7968
  const safeMatterOptions = {
@@ -9501,7 +8032,7 @@ function createContentService(app, settings = {}) {
9501
8032
  const options = await routerOptions;
9502
8033
  const routes = [];
9503
8034
  routerApp.options.redirects.length = 0;
9504
- const context = createRoutesContext(resolveOptions$4({
8035
+ const context = createRoutesContext(resolveOptions$2({
9505
8036
  ...options,
9506
8037
  root: userRoot,
9507
8038
  dts: false,
@@ -9726,7 +8257,7 @@ function registerContentCommands(cli) {
9726
8257
  setEnv();
9727
8258
  if (json)
9728
8259
  setLogLevel(-999);
9729
- const options = await resolveOptions$3({ userRoot: resolve$1(root) });
8260
+ const options = await resolveOptions$1({ userRoot: resolve$1(root) });
9730
8261
  setTimezone(options.config.siteConfig.timezone);
9731
8262
  const app = createValaxyNode(options);
9732
8263
  if (options.config.loaders?.length) {
@@ -9742,7 +8273,7 @@ function registerContentCommands(cli) {
9742
8273
  });
9743
8274
  const result = command === "inspect" ? await service.inspectPage(file) : await service.checkPage(file);
9744
8275
  if ("ok" in result && !result.ok)
9745
- process$1.exitCode = 1;
8276
+ process.exitCode = 1;
9746
8277
  if (json || !("diagnostics" in result)) {
9747
8278
  console.log(JSON.stringify(result, null, 2));
9748
8279
  } else {
@@ -9752,7 +8283,7 @@ function registerContentCommands(cli) {
9752
8283
  ${diagnostic.hint}`);
9753
8284
  }
9754
8285
  } catch (error) {
9755
- process$1.exitCode = 1;
8286
+ process.exitCode = 1;
9756
8287
  const message = error instanceof Error ? error.message : "Content inspection failed";
9757
8288
  if (json)
9758
8289
  console.log(JSON.stringify({ path: file, ok: false, error: message }));
@@ -9779,12 +8310,12 @@ async function collectDebugInfo() {
9779
8310
  const info = {
9780
8311
  os: os.platform(),
9781
8312
  arch: os.arch(),
9782
- node: process$1.version,
8313
+ node: process.version,
9783
8314
  pnpm: getPnpmVersion(),
9784
8315
  valaxy: version
9785
8316
  };
9786
8317
  try {
9787
- const options = await resolveOptions$3({ userRoot: process$1.cwd() });
8318
+ const options = await resolveOptions$1({ userRoot: process.cwd() });
9788
8319
  info.userRoot = options.userRoot;
9789
8320
  info.theme = options.theme;
9790
8321
  info.themeVersion = options.config.themeConfig?.pkg?.version;
@@ -9892,12 +8423,12 @@ function registerDeployCommand(cli) {
9892
8423
  });
9893
8424
  if (isCancel(shouldBuild)) {
9894
8425
  cancel("Operation cancelled.");
9895
- process$1.exit(0);
8426
+ process.exit(0);
9896
8427
  }
9897
8428
  if (shouldBuild) {
9898
8429
  await execBuild({ ssg: true, root, output, log: "info" });
9899
8430
  }
9900
- const options = await resolveOptions$3({ userRoot: root }, "build");
8431
+ const options = await resolveOptions$1({ userRoot: root }, "build");
9901
8432
  const configDeployType = type ?? options.config.deploy?.type;
9902
8433
  const deployType = configDeployType ?? await select({
9903
8434
  message: "Where do you want to deploy?",
@@ -9908,7 +8439,7 @@ function registerDeployCommand(cli) {
9908
8439
  });
9909
8440
  if (isCancel(deployType)) {
9910
8441
  cancel("Operation cancelled.");
9911
- process$1.exit(0);
8442
+ process.exit(0);
9912
8443
  }
9913
8444
  if (deployType === "gh-pages") {
9914
8445
  let isGhPagesInstalled = false;
@@ -9921,7 +8452,7 @@ function registerDeployCommand(cli) {
9921
8452
  });
9922
8453
  if (isCancel(installGhPages)) {
9923
8454
  cancel("Operation cancelled.");
9924
- process$1.exit(0);
8455
+ process.exit(0);
9925
8456
  }
9926
8457
  if (installGhPages) {
9927
8458
  try {
@@ -10008,7 +8539,7 @@ const SHORTCUTS = [
10008
8539
  key: "e",
10009
8540
  description: "edit",
10010
8541
  action() {
10011
- exec(`code "${process$1.cwd()}"`, (err) => {
8542
+ exec(`code "${process.cwd()}"`, (err) => {
10012
8543
  if (err)
10013
8544
  console.error("Failed to open editor", err);
10014
8545
  });
@@ -10016,15 +8547,15 @@ const SHORTCUTS = [
10016
8547
  }
10017
8548
  ];
10018
8549
  function bindShortcuts(server, createDevServer) {
10019
- if (!server.httpServer || !process$1.stdin.isTTY || process$1.env.CI)
8550
+ if (!server.httpServer || !process.stdin.isTTY || process.env.CI)
10020
8551
  return;
10021
- process$1.stdin.resume();
10022
- process$1.stdin.setEncoding("utf8");
10023
- readline.emitKeypressEvents(process$1.stdin);
10024
- process$1.stdin.setRawMode(true);
8552
+ process.stdin.resume();
8553
+ process.stdin.setEncoding("utf8");
8554
+ readline.emitKeypressEvents(process.stdin);
8555
+ process.stdin.setRawMode(true);
10025
8556
  async function onKeyPress(str, key) {
10026
8557
  if (key.ctrl && key.name === "c") {
10027
- process$1.exit();
8558
+ process.exit();
10028
8559
  } else {
10029
8560
  const shortcut = SHORTCUTS.find((shortcut2) => shortcut2.key === str);
10030
8561
  if (!shortcut)
@@ -10036,14 +8567,14 @@ function bindShortcuts(server, createDevServer) {
10036
8567
  }
10037
8568
  }
10038
8569
  }
10039
- process$1.stdin.on("keypress", onKeyPress);
8570
+ process.stdin.on("keypress", onKeyPress);
10040
8571
  server.httpServer.on("close", () => {
10041
- process$1.stdin.off("keypress", onKeyPress);
8572
+ process.stdin.off("keypress", onKeyPress);
10042
8573
  });
10043
8574
  }
10044
8575
 
10045
8576
  async function startValaxyDev({
10046
- root = process$1.cwd(),
8577
+ root = process.cwd(),
10047
8578
  port,
10048
8579
  remote,
10049
8580
  log,
@@ -10055,10 +8586,10 @@ async function startValaxyDev({
10055
8586
  if (log === "debug")
10056
8587
  setLogLevel(4);
10057
8588
  if (!await isPagesDirExist(root))
10058
- process$1.exit(0);
8589
+ process.exit(0);
10059
8590
  port = port || await findFreePort(4859);
10060
8591
  const resolveTimer = countPerformanceTime();
10061
- const resolvedOptions = await resolveOptions$3({ userRoot: root });
8592
+ const resolvedOptions = await resolveOptions$1({ userRoot: root });
10062
8593
  vLogger.debug(`resolveOptions: ${resolveTimer()}`);
10063
8594
  setTimezone(resolvedOptions.config.siteConfig.timezone);
10064
8595
  const createNodeTimer = countPerformanceTime();
@@ -10168,7 +8699,7 @@ function registerDevCommand(cli) {
10168
8699
  );
10169
8700
  }
10170
8701
 
10171
- const userRoot = process$1.cwd();
8702
+ const userRoot = process.cwd();
10172
8703
  const defaultPostTemplate = `---
10173
8704
  layout: <%=layout%>
10174
8705
  title: <%=title%>
@@ -10177,7 +8708,7 @@ date: <%=date%>
10177
8708
  `;
10178
8709
 
10179
8710
  async function getTemplate(layout) {
10180
- const { clientRoot, themeRoot } = await resolveOptions$3({ userRoot });
8711
+ const { clientRoot, themeRoot } = await resolveOptions$1({ userRoot });
10181
8712
  const roots = [userRoot, themeRoot, clientRoot];
10182
8713
  for (const root of roots) {
10183
8714
  const scaffoldPath = path.resolve(root, "scaffolds", `${layout}.md`);
@@ -10218,7 +8749,7 @@ async function genLayoutTemplate({
10218
8749
  let template = await getTemplate(layout);
10219
8750
  if (!template)
10220
8751
  template = defaultPostTemplate;
10221
- const dateFormat = "YYYY-MM-DD HH:mm:ss";
8752
+ const dateFormat = "YYYY-MM-DDTHH:mm:ssZ";
10222
8753
  return ejs.render(template, { title, layout, date: date ? dayjs().format(dateFormat) : "" });
10223
8754
  }
10224
8755
 
@@ -10283,18 +8814,18 @@ function createCoreCli(argv) {
10283
8814
  });
10284
8815
  return cli.help();
10285
8816
  }
10286
- async function createCli(argv = hideBin(process$1.argv), options = {}) {
8817
+ async function createCli(argv = hideBin(process.argv), options = {}) {
10287
8818
  const cli = createCoreCli(argv);
10288
8819
  if (!shouldResolveAddonCli(argv))
10289
8820
  return cli;
10290
- const userRoot = resolve(options.userRoot || process$1.cwd());
8821
+ const userRoot = resolve(options.userRoot || process.cwd());
10291
8822
  const extensions = await resolveAddonCliExtensions(userRoot);
10292
8823
  registerAddonCliExtensions(cli, extensions, userRoot);
10293
8824
  return cli;
10294
8825
  }
10295
- async function run(argv = hideBin(process$1.argv), options = {}) {
8826
+ async function run(argv = hideBin(process.argv), options = {}) {
10296
8827
  const cli = await createCli(argv, options);
10297
8828
  await cli.parseAsync();
10298
8829
  }
10299
8830
 
10300
- export { resolveUserThemeConfig 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, resolveFootnoteConfig as R, StateManager as S, resolveImportPath as T, resolveImportUrl as U, ViteValaxyPlugins as V, resolveOptions$3 as W, resolveSiteConfig as X, resolveSiteConfigFromRoot as Y, resolveThemeConfigFromRoot as Z, resolveThemeValaxyConfig as _, createContentService as a, resolveValaxyConfig as a0, resolveValaxyConfigFromRoot as a1, run as a2, ssgBuild as a3, startValaxyDev as a4, toAtFS as a5, transformObject as a6, version as a7, 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 };
8831
+ export { resolveUserThemeConfig 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, resolveFootnoteConfig as R, StateManager as S, resolveImportPath as T, resolveImportUrl as U, ViteValaxyPlugins as V, resolveOptions$1 as W, resolveSiteConfig as X, resolveSiteConfigFromRoot as Y, resolveThemeConfigFromRoot as Z, resolveThemeValaxyConfig as _, createContentService as a, resolveValaxyConfig as a0, resolveValaxyConfigFromRoot as a1, run as a2, ssgBuild as a3, startValaxyDev as a4, toAtFS as a5, transformObject as a6, version as a7, 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 };