@vuepress/plugin-redirect 2.0.0-rc.9 → 2.0.0-rc.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/lib/cli/index.js +19 -73
  2. package/lib/cli/index.js.map +1 -0
  3. package/lib/{shared/localeConfig.d.ts → client/behavior-BgEQhx7R.d.ts} +15 -19
  4. package/lib/client/components/RedirectModal.d.ts +61 -0
  5. package/lib/client/components/RedirectModal.js +2 -0
  6. package/lib/client/components/RedirectModal.js.map +1 -0
  7. package/lib/client/config.d.ts +7 -3
  8. package/lib/client/config.js +2 -10
  9. package/lib/client/config.js.map +1 -0
  10. package/lib/client/index.d.ts +21 -0
  11. package/lib/client/index.js +2 -0
  12. package/lib/client/index.js.map +1 -0
  13. package/lib/client/setupRedirect-DVhycPIJ.js +2 -0
  14. package/lib/client/setupRedirect-DVhycPIJ.js.map +1 -0
  15. package/lib/client/styles/redirect-modal.css +1 -0
  16. package/lib/client/styles/redirect-modal.css.map +1 -0
  17. package/lib/client/styles/vars.css +1 -0
  18. package/lib/client/styles/vars.css.map +1 -0
  19. package/lib/client/useRedirectInfo-BzhIENgm.js +2 -0
  20. package/lib/client/useRedirectInfo-BzhIENgm.js.map +1 -0
  21. package/lib/node/index.d.ts +113 -3
  22. package/lib/node/index.js +90 -3
  23. package/lib/node/index.js.map +1 -0
  24. package/package.json +10 -15
  25. package/lib/cli/index.d.ts +0 -2
  26. package/lib/client/components/LanguageSwitch.d.ts +0 -4
  27. package/lib/client/components/LanguageSwitch.js +0 -99
  28. package/lib/client/composables/index.d.ts +0 -1
  29. package/lib/client/composables/index.js +0 -1
  30. package/lib/client/composables/setupDevServerRedirect.d.ts +0 -1
  31. package/lib/client/composables/setupDevServerRedirect.js +0 -80
  32. package/lib/client/define.d.ts +0 -3
  33. package/lib/client/define.js +0 -3
  34. package/lib/client/styles/language-switch.css +0 -57
  35. package/lib/node/ensureRootHomePage.d.ts +0 -3
  36. package/lib/node/ensureRootHomePage.js +0 -68
  37. package/lib/node/frontmatter.d.ts +0 -4
  38. package/lib/node/frontmatter.js +0 -1
  39. package/lib/node/generate/generateAutoLocaleRedirectFiles.d.ts +0 -3
  40. package/lib/node/generate/generateAutoLocaleRedirectFiles.js +0 -28
  41. package/lib/node/generate/generateRedirectFiles.d.ts +0 -2
  42. package/lib/node/generate/generateRedirectFiles.js +0 -21
  43. package/lib/node/generate/getLocaleRedirectHTML.d.ts +0 -2
  44. package/lib/node/generate/getLocaleRedirectHTML.js +0 -77
  45. package/lib/node/generate/getRedirectHTML.d.ts +0 -1
  46. package/lib/node/generate/getRedirectHTML.js +0 -18
  47. package/lib/node/generate/index.d.ts +0 -2
  48. package/lib/node/generate/index.js +0 -2
  49. package/lib/node/getRedirectLocaleConfig.d.ts +0 -4
  50. package/lib/node/getRedirectLocaleConfig.js +0 -35
  51. package/lib/node/getRedirectMap.d.ts +0 -3
  52. package/lib/node/getRedirectMap.js +0 -25
  53. package/lib/node/handleRedirectTo.d.ts +0 -2
  54. package/lib/node/handleRedirectTo.js +0 -19
  55. package/lib/node/locales.d.ts +0 -3
  56. package/lib/node/locales.js +0 -129
  57. package/lib/node/logger.d.ts +0 -3
  58. package/lib/node/logger.js +0 -3
  59. package/lib/node/options.d.ts +0 -22
  60. package/lib/node/options.js +0 -1
  61. package/lib/node/redirectPlugin.d.ts +0 -3
  62. package/lib/node/redirectPlugin.js +0 -53
  63. package/lib/shared/index.d.ts +0 -3
  64. package/lib/shared/index.js +0 -3
  65. package/lib/shared/localeConfig.js +0 -1
  66. package/lib/shared/locales.d.ts +0 -24
  67. package/lib/shared/locales.js +0 -1
  68. package/lib/shared/normalizePath.d.ts +0 -1
  69. package/lib/shared/normalizePath.js +0 -4
package/lib/cli/index.js CHANGED
@@ -1,74 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from 'node:module';
3
- import { removeEndingSlash, removeLeadingSlash } from '@vuepress/helper';
4
- import { cac } from 'cac';
5
- import { loadUserConfig, resolveAppConfig, resolveCliAppConfig, resolveUserConfigConventionalPath, transformUserConfigToPlugin, } from 'vuepress/cli';
6
- import { createBuildApp } from 'vuepress/core';
7
- import { fs, logger, path } from 'vuepress/utils';
8
- import { getRedirectHTML } from '../node/generate/getRedirectHTML.js';
9
- const require = createRequire(import.meta.url);
10
- const cli = cac('vp-redirect');
11
- const { version } = require('@vuepress/plugin-redirect/package.json');
12
- cli
13
- .command('generate [source-dir]', 'Generate redirect site using VuePress project under source folder')
14
- .option('--hostname <hostname>', 'Hostname to redirect to (E.g.: https://new.example.com/)', { default: '/' })
15
- .option('-c, --config <config>', 'Set path to config file')
16
- .option('-o, --output <output>', 'Set the output directory (default: .vuepress/redirect)')
17
- .option('--cache <cache>', 'Set the directory of the cache files')
18
- .option('-t, --temp <temp>', 'Set the directory of the temporary files')
19
- .option('--clean-cache', 'Clean the cache files before generation')
20
- .option('--clean-temp', 'Clean the temporary files before generation')
21
- .action(async (sourceDir, commandOptions) => {
22
- if (!sourceDir)
23
- return cli.outputHelp();
24
- // ensure NODE_ENV is set
25
- process.env.NODE_ENV ??= 'production';
26
- // resolve app config from cli options
27
- const cliAppConfig = resolveCliAppConfig(sourceDir, {});
28
- // resolve user config file
29
- const userConfigPath = resolveUserConfigConventionalPath(cliAppConfig.source);
30
- const { userConfig } = await loadUserConfig(userConfigPath);
31
- // resolve the final app config to use
32
- const appConfig = resolveAppConfig({
33
- defaultAppConfig: {},
34
- cliAppConfig,
35
- userConfig,
36
- });
37
- if (appConfig === null)
38
- return;
39
- // create vuepress app
40
- const app = createBuildApp(appConfig);
41
- // use user-config plugin
42
- app.use(transformUserConfigToPlugin(userConfig, cliAppConfig.source));
43
- // clean temp and cache
44
- if (commandOptions.cleanTemp === true) {
45
- logger.info('Cleaning temp...');
46
- await fs.remove(app.dir.temp());
47
- }
48
- if (commandOptions.cleanCache === true) {
49
- logger.info('Cleaning cache...');
50
- await fs.remove(app.dir.cache());
51
- }
52
- const outputFolder = commandOptions.output
53
- ? path.join(process.cwd(), commandOptions.output)
54
- : path.join(app.dir.source(), '.vuepress', 'redirect');
55
- // empty output directory
56
- await fs.emptyDir(outputFolder);
57
- // initialize vuepress app to get pages
58
- logger.info('Initializing VuePress and preparing data...');
59
- await app.init();
60
- // redirect all pages
61
- // initialize vuepress app to get pages
62
- logger.info('Generating redirect pages...');
63
- await Promise.all(app.pages.map((page) => {
64
- const redirectUrl = `${removeEndingSlash(commandOptions.hostname)}${app.options.base}${removeLeadingSlash(page.path)}`;
65
- const destLocation = path.join(outputFolder, removeLeadingSlash(page.path.replace(/\/$/, '/index.html')));
66
- return fs
67
- .ensureDir(path.dirname(destLocation))
68
- .then(() => fs.writeFile(destLocation, getRedirectHTML(redirectUrl)));
69
- }));
70
- });
71
- cli.command('').action(() => cli.outputHelp());
72
- cli.help();
73
- cli.version(version);
74
- cli.parse();
2
+ import{removeEndingSlash as v,removeLeadingSlash as h}from"@vuepress/helper";import{createCommand as C}from"commander";import{resolveCliAppConfig as y,resolveUserConfigPath as w,resolveUserConfigConventionalPath as $,loadUserConfig as b,resolveAppConfig as S,transformUserConfigToPlugin as A}from"vuepress/cli";import{createBuildApp as P}from"vuepress/core";import{fs as o,logger as n,path as a}from"vuepress/utils";var j="2.0.0-rc.91",x={version:j};const E=e=>`<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="UTF-8">
6
+ <meta name="robots" content="noindex">
7
+ <meta http-equiv="refresh" content="0; url=${e}">
8
+ <link rel="canonical" href="${e}">
9
+ <title>Redirecting...</title>
10
+ <script>
11
+ const anchor = window.location.hash.substring(1);
12
+ location.href = \`${e}\${anchor? \`#\${anchor}\`: ""}\`;
13
+ <\/script>
14
+ </head>
15
+ <body>
16
+ <p>Redirecting...</p>
17
+ </body>
18
+ </html>
19
+ `,i=C("vp-redirect");i.summary("Generate redirect site").description("Generate redirect site for current VuePress project").option("--hostname <hostname>","Hostname to redirect to (E.g.: https://new.example.com/)","/").option("-c, --config [config]","Set path to config file").option("--cache [cache]","Set the directory of the cache files").option("--temp [temp]","Set the directory of the temporary files").option("--clean-cache","Clean the cache files before generation").option("--clean-temp","Clean the temporary files before generation").argument("<source>","Source directory of VuePress project").argument("[output]","Output folder (default: .vuepress/redirect relative to source folder)").action(async(e,s,t)=>{process.env.NODE_ENV??="production",o.existsSync(e)||i.error(`Source directory ${e} does not exist!`);const c=y(e,{}),u=t.config?w(t.config):$(c.source),{userConfig:p}=await b(u),l=S({defaultAppConfig:{},cliAppConfig:c,userConfig:p});if(l===null)return;const r=P(l);r.use(A(p,c.source)),t.cleanTemp===!0&&(n.info("Cleaning temp..."),await o.remove(r.dir.temp())),t.cleanCache===!0&&(n.info("Cleaning cache..."),await o.remove(r.dir.cache()));const f=s?a.join(process.cwd(),s):a.join(r.dir.source(),".vuepress","redirect");await o.emptyDir(f),n.info("Initializing VuePress and preparing data..."),await r.init(),n.info("Generating redirect pages..."),await Promise.all(r.pages.map(m=>{const g=`${v(t.hostname)}${r.siteData.base}${h(m.path)}`,d=a.join(f,h(m.path.replace(/\/$/,"/index.html")));return o.ensureDir(a.dirname(d)).then(()=>o.writeFile(d,E(g)))}))}),i.version(x.version),i.showHelpAfterError("add --help for additional information"),await i.parseAsync();
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../package.json","../../src/node/generate/getRedirectHTML.ts","../../src/cli/index.ts"],"sourcesContent":["{\n \"name\": \"@vuepress/plugin-redirect\",\n \"version\": \"2.0.0-rc.91\",\n \"description\": \"VuePress plugin - redirect\",\n \"keywords\": [\n \"vuepress-plugin\",\n \"vuepress\",\n \"plugin\",\n \"redirect\"\n ],\n \"homepage\": \"https://ecosystem.vuejs.press/plugins/tools/redirect.html\",\n \"bugs\": {\n \"url\": \"https://github.com/vuepress/ecosystem/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/vuepress/ecosystem.git\",\n \"directory\": \"plugins/tools/plugin-redirect\"\n },\n \"license\": \"MIT\",\n \"author\": {\n \"name\": \"Mr.Hope\",\n \"email\": \"mister-hope@outlook.com\",\n \"url\": \"https://mister-hope.com\"\n },\n \"type\": \"module\",\n \"exports\": {\n \".\": \"./lib/node/index.js\",\n \"./client\": \"./lib/client/index.js\",\n \"./package.json\": \"./package.json\"\n },\n \"main\": \"./lib/node/index.js\",\n \"types\": \"./lib/node/index.d.ts\",\n \"bin\": {\n \"vp-redirect\": \"./lib/cli/index.js\"\n },\n \"files\": [\n \"lib\"\n ],\n \"scripts\": {\n \"build\": \"tsc -b tsconfig.build.json\",\n \"bundle\": \"rollup -c rollup.config.ts --configPlugin esbuild\",\n \"clean\": \"rimraf --glob ./lib ./*.tsbuildinfo\",\n \"style\": \"sass src:lib --embed-sources --style=compressed --pkg-importer=node\"\n },\n \"dependencies\": {\n \"@vuepress/helper\": \"workspace:*\",\n \"@vueuse/core\": \"catalog:\",\n \"commander\": \"^13.1.0\",\n \"vue\": \"catalog:\"\n },\n \"peerDependencies\": {\n \"vuepress\": \"catalog:\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","export const getRedirectHTML = (redirectUrl: string): string => `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"robots\" content=\"noindex\">\n <meta http-equiv=\"refresh\" content=\"0; url=${redirectUrl}\">\n <link rel=\"canonical\" href=\"${redirectUrl}\">\n <title>Redirecting...</title>\n <script>\n const anchor = window.location.hash.substring(1);\n location.href = \\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`;\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n","#!/usr/bin/env node\nimport { removeEndingSlash, removeLeadingSlash } from '@vuepress/helper'\nimport { createCommand } from 'commander'\nimport {\n loadUserConfig,\n resolveAppConfig,\n resolveCliAppConfig,\n resolveUserConfigConventionalPath,\n resolveUserConfigPath,\n transformUserConfigToPlugin,\n} from 'vuepress/cli'\nimport { createBuildApp } from 'vuepress/core'\nimport { fs, logger, path } from 'vuepress/utils'\nimport pkg from '../../package.json' with { type: 'json' }\nimport { getRedirectHTML } from '../node/generate/getRedirectHTML.js'\n\ninterface RedirectCommandOptions {\n hostname: string\n config?: string\n cache?: string\n temp?: string\n cleanCache?: boolean\n cleanTemp?: boolean\n}\n\nconst program = createCommand('vp-redirect')\n\nprogram\n .summary('Generate redirect site')\n .description('Generate redirect site for current VuePress project')\n .option(\n '--hostname <hostname>',\n 'Hostname to redirect to (E.g.: https://new.example.com/)',\n '/',\n )\n .option('-c, --config [config]', 'Set path to config file')\n .option('--cache [cache]', 'Set the directory of the cache files')\n .option('--temp [temp]', 'Set the directory of the temporary files')\n .option('--clean-cache', 'Clean the cache files before generation')\n .option('--clean-temp', 'Clean the temporary files before generation')\n .argument('<source>', 'Source directory of VuePress project')\n .argument(\n '[output]',\n 'Output folder (default: .vuepress/redirect relative to source folder)',\n )\n .action(\n async (\n sourceDir: string,\n output: string | undefined,\n commandOptions: RedirectCommandOptions,\n ) => {\n // ensure NODE_ENV is set\n process.env.NODE_ENV ??= 'production'\n\n if (!fs.existsSync(sourceDir)) {\n program.error(`Source directory ${sourceDir} does not exist!`)\n }\n\n // resolve app config from cli options\n const cliAppConfig = resolveCliAppConfig(sourceDir, {})\n\n // resolve user config file\n const userConfigPath = commandOptions.config\n ? resolveUserConfigPath(commandOptions.config)\n : resolveUserConfigConventionalPath(cliAppConfig.source)\n\n const { userConfig } = await loadUserConfig(userConfigPath)\n\n // resolve the final app config to use\n const appConfig = resolveAppConfig({\n defaultAppConfig: {},\n cliAppConfig,\n userConfig,\n })\n\n if (appConfig === null) return\n\n // create vuepress app\n const app = createBuildApp(appConfig)\n\n // use user-config plugin\n app.use(transformUserConfigToPlugin(userConfig, cliAppConfig.source))\n\n // clean temp and cache\n if (commandOptions.cleanTemp === true) {\n logger.info('Cleaning temp...')\n await fs.remove(app.dir.temp())\n }\n if (commandOptions.cleanCache === true) {\n logger.info('Cleaning cache...')\n await fs.remove(app.dir.cache())\n }\n\n const outputFolder = output\n ? path.join(process.cwd(), output)\n : path.join(app.dir.source(), '.vuepress', 'redirect')\n\n // empty output directory\n await fs.emptyDir(outputFolder)\n\n // initialize vuepress app to get pages\n logger.info('Initializing VuePress and preparing data...')\n\n // initialize vuepress app to get pages\n await app.init()\n\n logger.info('Generating redirect pages...')\n\n // redirect all pages\n await Promise.all(\n app.pages.map((page) => {\n const redirectUrl = `${removeEndingSlash(commandOptions.hostname)}${\n app.siteData.base\n }${removeLeadingSlash(page.path)}`\n const destLocation = path.join(\n outputFolder,\n removeLeadingSlash(page.path.replace(/\\/$/, '/index.html')),\n )\n\n return fs\n .ensureDir(path.dirname(destLocation))\n .then(() =>\n fs.writeFile(destLocation, getRedirectHTML(redirectUrl)),\n )\n }),\n )\n },\n )\n\nprogram.version(pkg.version)\nprogram.showHelpAfterError('add --help for additional information')\n\nawait program.parseAsync()\n"],"names":["version","package_default","getRedirectHTML","redirectUrl","program","createCommand","sourceDir","output","commandOptions","fs","cliAppConfig","resolveCliAppConfig","userConfigPath","resolveUserConfigPath","resolveUserConfigConventionalPath","userConfig","loadUserConfig","appConfig","resolveAppConfig","app","createBuildApp","transformUserConfigToPlugin","logger","outputFolder","path","page","removeEndingSlash","removeLeadingSlash","destLocation","pkg"],"mappings":";gaACE,IACAA,EAAW,cAFbC,EAAA,CAEE,QAAAD,CAuDF,ECzDO,MAAME,EAAmBC,GAAgC;AAAA;AAAA;AAAA;AAAA;AAAA,+CAKjBA,CAAW;AAAA,gCAC1BA,CAAW;AAAA;AAAA;AAAA;AAAA,wBAInBA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECe7BC,EAAUC,EAAc,aAAa,EAE3CD,EACG,QAAQ,wBAAwB,EAChC,YAAY,qDAAqD,EACjE,OACC,wBACA,2DACA,GACF,EACC,OAAO,wBAAyB,yBAAyB,EACzD,OAAO,kBAAmB,sCAAsC,EAChE,OAAO,gBAAiB,0CAA0C,EAClE,OAAO,gBAAiB,yCAAyC,EACjE,OAAO,eAAgB,6CAA6C,EACpE,SAAS,WAAY,sCAAsC,EAC3D,SACC,WACA,uEACF,EACC,OACC,MACEE,EACAC,EACAC,IACG,CAEH,QAAQ,IAAI,WAAa,aAEpBC,EAAG,WAAWH,CAAS,GAC1BF,EAAQ,MAAM,oBAAoBE,CAAS,kBAAkB,EAI/D,MAAMI,EAAeC,EAAoBL,EAAW,CAAE,CAAA,EAGhDM,EAAiBJ,EAAe,OAClCK,EAAsBL,EAAe,MAAM,EAC3CM,EAAkCJ,EAAa,MAAM,EAEnD,CAAE,WAAAK,CAAW,EAAI,MAAMC,EAAeJ,CAAc,EAGpDK,EAAYC,EAAiB,CACjC,iBAAkB,CAClB,EAAA,aAAAR,EACA,WAAAK,CACF,CAAC,EAED,GAAIE,IAAc,KAAM,OAGxB,MAAME,EAAMC,EAAeH,CAAS,EAGpCE,EAAI,IAAIE,EAA4BN,EAAYL,EAAa,MAAM,CAAC,EAGhEF,EAAe,YAAc,KAC/Bc,EAAO,KAAK,kBAAkB,EAC9B,MAAMb,EAAG,OAAOU,EAAI,IAAI,KAAA,CAAM,GAE5BX,EAAe,aAAe,KAChCc,EAAO,KAAK,mBAAmB,EAC/B,MAAMb,EAAG,OAAOU,EAAI,IAAI,MAAO,CAAA,GAGjC,MAAMI,EAAehB,EACjBiB,EAAK,KAAK,QAAQ,MAAOjB,CAAM,EAC/BiB,EAAK,KAAKL,EAAI,IAAI,OAAU,EAAA,YAAa,UAAU,EAGvD,MAAMV,EAAG,SAASc,CAAY,EAG9BD,EAAO,KAAK,6CAA6C,EAGzD,MAAMH,EAAI,OAEVG,EAAO,KAAK,8BAA8B,EAG1C,MAAM,QAAQ,IACZH,EAAI,MAAM,IAAKM,GAAS,CACtB,MAAMtB,EAAc,GAAGuB,EAAkBlB,EAAe,QAAQ,CAAC,GAC/DW,EAAI,SAAS,IACf,GAAGQ,EAAmBF,EAAK,IAAI,CAAC,GAC1BG,EAAeJ,EAAK,KACxBD,EACAI,EAAmBF,EAAK,KAAK,QAAQ,MAAO,aAAa,CAAC,CAC5D,EAEA,OAAOhB,EACJ,UAAUe,EAAK,QAAQI,CAAY,CAAC,EACpC,KAAK,IACJnB,EAAG,UAAUmB,EAAc1B,EAAgBC,CAAW,CAAC,CACzD,CACJ,CAAC,CACH,CACF,CACF,EAEFC,EAAQ,QAAQyB,EAAI,OAAO,EAC3BzB,EAAQ,mBAAmB,uCAAuC,EAElE,MAAMA,EAAQ,WAAW"}
@@ -1,4 +1,4 @@
1
- export interface RedirectLocaleConfig {
1
+ interface RedirectBehaviorOptions {
2
2
  /**
3
3
  * Whether enable locales redirection
4
4
  *
@@ -6,21 +6,7 @@ export interface RedirectLocaleConfig {
6
6
  *
7
7
  * @default false
8
8
  */
9
- autoLocale: boolean;
10
- /**
11
- * Whether switch locales
12
- *
13
- * 是否启用重定向语言
14
- *
15
- * @default false
16
- */
17
- switchLocale: 'direct' | 'modal' | false;
18
- /**
19
- * Locale language config
20
- *
21
- * 多语言语言配置
22
- */
23
- localeConfig: Record<string, string[]>;
9
+ autoLocale?: boolean;
24
10
  /**
25
11
  * Whether fallback to other locales user defined
26
12
  *
@@ -28,7 +14,7 @@ export interface RedirectLocaleConfig {
28
14
  *
29
15
  * @default true
30
16
  */
31
- localeFallback: boolean;
17
+ localeFallback?: boolean;
32
18
  /**
33
19
  * Behavior when a locale version is not available for current link
34
20
  *
@@ -40,7 +26,7 @@ export interface RedirectLocaleConfig {
40
26
  *
41
27
  * @default "defaultLocale"
42
28
  */
43
- defaultBehavior: 'defaultLocale' | 'homepage' | '404';
29
+ defaultBehavior?: '404' | 'defaultLocale' | 'homepage';
44
30
  /**
45
31
  * Default locale path
46
32
  *
@@ -50,5 +36,15 @@ export interface RedirectLocaleConfig {
50
36
  *
51
37
  * @description 如果缺失,则使用第一个语言
52
38
  */
53
- defaultLocale: string;
39
+ defaultLocale?: string;
40
+ }
41
+ interface RedirectBehaviorConfig extends Required<RedirectBehaviorOptions> {
42
+ /**
43
+ * Locale language config
44
+ *
45
+ * 多语言语言配置
46
+ */
47
+ config: Record<string, string[]>;
54
48
  }
49
+
50
+ export type { RedirectBehaviorConfig as R };
@@ -0,0 +1,61 @@
1
+ import * as vue from 'vue';
2
+ import { PropType, VNode } from 'vue';
3
+ import { R as RedirectBehaviorConfig } from '../behavior-BgEQhx7R.js';
4
+ import { ExactLocaleConfig } from '@vuepress/helper/client';
5
+
6
+ interface RedirectPluginLocaleData {
7
+ /**
8
+ * Language name
9
+ *
10
+ * 语言名称
11
+ */
12
+ name: string;
13
+ /**
14
+ * Switch hint
15
+ *
16
+ * 切换提示
17
+ */
18
+ hint: string;
19
+ /**
20
+ * Switch button text
21
+ *
22
+ * 切换按钮文字
23
+ */
24
+ switch: string;
25
+ /**
26
+ * Cancel button text
27
+ *
28
+ * 取消按钮文字
29
+ */
30
+ cancel: string;
31
+ /**
32
+ * remember hint text
33
+ *
34
+ * 记住提示文本
35
+ */
36
+ remember: string;
37
+ }
38
+
39
+ type RedirectPluginLocaleConfig = ExactLocaleConfig<RedirectPluginLocaleData>;
40
+
41
+ declare const _default: vue.DefineComponent<vue.ExtractPropTypes<{
42
+ config: {
43
+ type: PropType<RedirectBehaviorConfig>;
44
+ required: true;
45
+ };
46
+ locales: {
47
+ type: PropType<RedirectPluginLocaleConfig>;
48
+ required: true;
49
+ };
50
+ }>, () => VNode | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
51
+ config: {
52
+ type: PropType<RedirectBehaviorConfig>;
53
+ required: true;
54
+ };
55
+ locales: {
56
+ type: PropType<RedirectPluginLocaleConfig>;
57
+ required: true;
58
+ };
59
+ }>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
60
+
61
+ export { _default as default };
@@ -0,0 +1,2 @@
1
+ import{useScrollLock as y}from"@vueuse/core";import{defineComponent as k,ref as v,computed as g,h as e,watch as w,onMounted as R,nextTick as j,onBeforeUnmount as C,TransitionGroup as S}from"vue";import{useRouter as x,useRoutePath as L,useRouteLocale as M}from"vuepress/client";import"@vuepress/helper/transition/fade-in-scale-up.css";import"../styles/redirect-modal.css";import{u as P,s as d,a as f}from"../useRedirectInfo-BzhIENgm.js";import"@vuepress/helper/client";var $=k({name:"RedirectModal",props:{config:{type:Object,required:!0},locales:{type:Object,required:!0}},setup(n){const h=x(),s=L(),l=M(),r=P(n.config),m=v(),t=y(m),o=v(!1),u=g(()=>{if(!r.value)return null;const{lang:c,localePath:b}=r.value,i=[n.locales[b],n.locales[l.value]];return{hint:i.map(({hint:a})=>a.replace("$1",c)),switch:i.map(({switch:a})=>a.replace("$1",c)).join(" / "),cancel:i.map(({cancel:a})=>a).join(" / "),remember:i.map(({remember:a})=>a).join(" / ")}}),p=()=>{d.value[l.value]=!0,o.value&&(f.value[l.value]=!0),t.value=!1};return w(s,()=>{t.value=!1}),R(async()=>{m.value=document.body,await j(),r.value&&!d.value[l.value]&&!f.value[l.value]&&(t.value=!0)}),C(()=>{t.value=!1}),()=>e(S,{name:"fade-in-scale-up"},()=>t.value?e("div",{key:"mask",class:"redirect-modal-mask"},e("div",{key:"popup",class:"redirect-modal-wrapper"},[e("div",{class:"redirect-modal-content"},u.value?.hint.map(c=>e("p",c))),e("div",{class:"redirect-modal-hint"},[e("input",{id:"remember-redirect",type:"checkbox",value:o.value,onChange:()=>{o.value=!o.value}}),e("label",{for:"remember-redirect"},u.value?.remember)]),e("button",{type:"button",class:"redirect-modal-action primary",onClick:()=>{p(),h.replace(s.value.replace(l.value,r.value.localePath))}},u.value?.switch),e("button",{type:"button",class:"redirect-modal-action",onClick:()=>{p()}},u.value?.cancel)])):null)}});export{$ as default};
2
+ //# sourceMappingURL=RedirectModal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RedirectModal.js","sources":["../../../src/client/components/RedirectModal.ts"],"sourcesContent":["import { useScrollLock } from '@vueuse/core'\nimport type { PropType, VNode } from 'vue'\nimport {\n TransitionGroup,\n computed,\n defineComponent,\n h,\n nextTick,\n onBeforeUnmount,\n onMounted,\n ref,\n watch,\n} from 'vue'\nimport { useRouteLocale, useRoutePath, useRouter } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { useRedirectInfo } from '../composables/index.js'\nimport type { RedirectPluginLocaleConfig } from '../types.js'\nimport { statusLocalStorage, statusSessionStorage } from '../utils/index.js'\n\nimport '@vuepress/helper/transition/fade-in-scale-up.css'\nimport '../styles/redirect-modal.css'\n\nexport default defineComponent({\n name: 'RedirectModal',\n\n props: {\n config: {\n type: Object as PropType<RedirectBehaviorConfig>,\n required: true,\n },\n\n locales: {\n type: Object as PropType<RedirectPluginLocaleConfig>,\n required: true,\n },\n },\n\n setup(props) {\n const router = useRouter()\n const routePath = useRoutePath()\n const routeLocale = useRouteLocale()\n const redirectInfo = useRedirectInfo(props.config)\n\n const body = ref<HTMLElement>()\n // lock body scroll when modal is displayed\n const showModal = useScrollLock(body)\n const shouldRemember = ref(false)\n\n const locale = computed(() => {\n if (!redirectInfo.value) return null\n\n const { lang, localePath } = redirectInfo.value\n const locales = [\n props.locales[localePath],\n props.locales[routeLocale.value],\n ]\n\n return {\n hint: locales.map(({ hint }) => hint.replace('$1', lang)),\n switch: locales\n .map(({ switch: switchText }) => switchText.replace('$1', lang))\n .join(' / '),\n cancel: locales.map(({ cancel }) => cancel).join(' / '),\n remember: locales.map(({ remember }) => remember).join(' / '),\n }\n })\n\n const updateState = (): void => {\n statusSessionStorage.value[routeLocale.value] = true\n if (shouldRemember.value) {\n statusLocalStorage.value[routeLocale.value] = true\n }\n showModal.value = false\n }\n\n watch(routePath, () => {\n showModal.value = false\n })\n\n onMounted(async () => {\n body.value = document.body\n\n await nextTick()\n\n if (\n redirectInfo.value &&\n !statusSessionStorage.value[routeLocale.value] &&\n !statusLocalStorage.value[routeLocale.value]\n ) {\n showModal.value = true\n }\n })\n\n onBeforeUnmount(() => {\n showModal.value = false\n })\n\n return (): VNode | null =>\n h(TransitionGroup, { name: 'fade-in-scale-up' }, () =>\n showModal.value\n ? h(\n 'div',\n { key: 'mask', class: 'redirect-modal-mask' },\n h(\n 'div',\n {\n key: 'popup',\n class: 'redirect-modal-wrapper',\n },\n [\n h(\n 'div',\n { class: 'redirect-modal-content' },\n locale.value?.hint.map((text) => h('p', text)),\n ),\n h('div', { class: 'redirect-modal-hint' }, [\n h('input', {\n id: 'remember-redirect',\n type: 'checkbox',\n value: shouldRemember.value,\n onChange: () => {\n shouldRemember.value = !shouldRemember.value\n },\n }),\n h(\n 'label',\n { for: 'remember-redirect' },\n locale.value?.remember,\n ),\n ]),\n h(\n 'button',\n {\n type: 'button',\n class: 'redirect-modal-action primary',\n onClick: () => {\n updateState()\n router.replace(\n routePath.value.replace(\n routeLocale.value,\n redirectInfo.value!.localePath,\n ),\n )\n },\n },\n locale.value?.switch,\n ),\n h(\n 'button',\n {\n type: 'button',\n class: 'redirect-modal-action',\n onClick: () => {\n updateState()\n },\n },\n locale.value?.cancel,\n ),\n ],\n ),\n )\n : null,\n )\n },\n})\n"],"names":["RedirectModal","defineComponent","props","router","useRouter","routePath","useRoutePath","routeLocale","useRouteLocale","redirectInfo","useRedirectInfo","body","ref","showModal","useScrollLock","shouldRemember","locale","computed","lang","localePath","locales","hint","switchText","cancel","remember","updateState","statusSessionStorage","statusLocalStorage","watch","onMounted","nextTick","onBeforeUnmount","h","TransitionGroup","text"],"mappings":"odAsBA,IAAAA,EAAeC,EAAgB,CAC7B,KAAM,gBAEN,MAAO,CACL,OAAQ,CACN,KAAM,OACN,SAAU,EACZ,EAEA,QAAS,CACP,KAAM,OACN,SAAU,EACZ,CACF,EAEA,MAAMC,EAAO,CACX,MAAMC,EAASC,IACTC,EAAYC,IACZC,EAAcC,EACdC,EAAAA,EAAeC,EAAgBR,EAAM,MAAM,EAE3CS,EAAOC,IAEPC,EAAYC,EAAcH,CAAI,EAC9BI,EAAiBH,EAAI,EAAK,EAE1BI,EAASC,EAAS,IAAM,CAC5B,GAAI,CAACR,EAAa,MAAO,OAAO,KAEhC,KAAM,CAAE,KAAAS,EAAM,WAAAC,CAAW,EAAIV,EAAa,MACpCW,EAAU,CACdlB,EAAM,QAAQiB,CAAU,EACxBjB,EAAM,QAAQK,EAAY,KAAK,CACjC,EAEA,MAAO,CACL,KAAMa,EAAQ,IAAI,CAAC,CAAE,KAAAC,CAAK,IAAMA,EAAK,QAAQ,KAAMH,CAAI,CAAC,EACxD,OAAQE,EACL,IAAI,CAAC,CAAE,OAAQE,CAAW,IAAMA,EAAW,QAAQ,KAAMJ,CAAI,CAAC,EAC9D,KAAK,KAAK,EACb,OAAQE,EAAQ,IAAI,CAAC,CAAE,OAAAG,CAAO,IAAMA,CAAM,EAAE,KAAK,KAAK,EACtD,SAAUH,EAAQ,IAAI,CAAC,CAAE,SAAAI,CAAS,IAAMA,CAAQ,EAAE,KAAK,KAAK,CAC9D,CACF,CAAC,EAEKC,EAAc,IAAY,CAC9BC,EAAqB,MAAMnB,EAAY,KAAK,EAAI,GAC5CQ,EAAe,QACjBY,EAAmB,MAAMpB,EAAY,KAAK,EAAI,IAEhDM,EAAU,MAAQ,EACpB,EAEA,OAAAe,EAAMvB,EAAW,IAAM,CACrBQ,EAAU,MAAQ,EACpB,CAAC,EAEDgB,EAAU,SAAY,CACpBlB,EAAK,MAAQ,SAAS,KAEtB,MAAMmB,EAGJrB,EAAAA,EAAa,OACb,CAACiB,EAAqB,MAAMnB,EAAY,KAAK,GAC7C,CAACoB,EAAmB,MAAMpB,EAAY,KAAK,IAE3CM,EAAU,MAAQ,GAEtB,CAAC,EAEDkB,EAAgB,IAAM,CACpBlB,EAAU,MAAQ,EACpB,CAAC,EAEM,IACLmB,EAAEC,EAAiB,CAAE,KAAM,kBAAmB,EAAG,IAC/CpB,EAAU,MACNmB,EACE,MACA,CAAE,IAAK,OAAQ,MAAO,qBAAsB,EAC5CA,EACE,MACA,CACE,IAAK,QACL,MAAO,wBACT,EACA,CACEA,EACE,MACA,CAAE,MAAO,wBAAyB,EAClChB,EAAO,OAAO,KAAK,IAAKkB,GAASF,EAAE,IAAKE,CAAI,CAAC,CAC/C,EACAF,EAAE,MAAO,CAAE,MAAO,qBAAsB,EAAG,CACzCA,EAAE,QAAS,CACT,GAAI,oBACJ,KAAM,WACN,MAAOjB,EAAe,MACtB,SAAU,IAAM,CACdA,EAAe,MAAQ,CAACA,EAAe,KACzC,CACF,CAAC,EACDiB,EACE,QACA,CAAE,IAAK,mBAAoB,EAC3BhB,EAAO,OAAO,QAChB,CACF,CAAC,EACDgB,EACE,SACA,CACE,KAAM,SACN,MAAO,gCACP,QAAS,IAAM,CACbP,EAAY,EACZtB,EAAO,QACLE,EAAU,MAAM,QACdE,EAAY,MACZE,EAAa,MAAO,UACtB,CACF,CACF,CACF,EACAO,EAAO,OAAO,MAChB,EACAgB,EACE,SACA,CACE,KAAM,SACN,MAAO,wBACP,QAAS,IAAM,CACbP,EACF,CAAA,CACF,EACAT,EAAO,OAAO,MAChB,CACF,CACF,CACF,EACA,IACN,CACJ,CACF,CAAC"}
@@ -1,3 +1,7 @@
1
- import type { ClientConfig } from 'vuepress/client';
2
- declare const _default: ClientConfig;
3
- export default _default;
1
+ import * as vuepress_client from 'vuepress/client';
2
+ import { R as RedirectBehaviorConfig } from './behavior-BgEQhx7R.js';
3
+
4
+ declare const config: RedirectBehaviorConfig;
5
+ declare const _default: vuepress_client.ClientConfig;
6
+
7
+ export { config, _default as default };
@@ -1,10 +1,2 @@
1
- import { defineClientConfig } from 'vuepress/client';
2
- import LanguageSwitch from './components/LanguageSwitch.js';
3
- import { setupDevServerRedirect } from './composables/setupDevServerRedirect.js';
4
- export default defineClientConfig({
5
- setup() {
6
- if (__VUEPRESS_DEV__)
7
- setupDevServerRedirect();
8
- },
9
- rootComponents: __REDIRECT_LOCALE_SWITCH__ ? [LanguageSwitch] : [],
10
- });
1
+ import o from"@vuepress/plugin-redirect/modal";import{h as r}from"vue";import{defineClientConfig as t}from"vuepress/client";import"./styles/vars.css";import{a as e,s as i}from"./setupRedirect-DVhycPIJ.js";import"@temp/redirect/map.js";import"@vuepress/helper/client";import"@vueuse/core";import"./useRedirectInfo-BzhIENgm.js";const _=__REDIRECT_CONFIG__;var m=t({setup(){__REDIRECT_DIRECT__&&e(_),__VUEPRESS_DEV__&&i(_)},...__REDIRECT_MODAL__?{rootComponents:[()=>r(o,{config:_,locales:__REDIRECT_LOCALES__})]}:{}});export{_ as config,m as default};
2
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sources":["../../src/client/config.ts"],"sourcesContent":["import RedirectModal from '@vuepress/plugin-redirect/modal'\nimport { h } from 'vue'\nimport { defineClientConfig } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../shared/index.js'\nimport { setupDevServerRedirect, setupRedirect } from './composables/index.js'\nimport type { RedirectPluginLocaleConfig } from './types.js'\n\nimport './styles/vars.css'\n\ndeclare const __REDIRECT_CONFIG__: RedirectBehaviorConfig\ndeclare const __REDIRECT_LOCALES__: RedirectPluginLocaleConfig\ndeclare const __REDIRECT_DIRECT__: boolean\ndeclare const __REDIRECT_MODAL__: boolean\n\nexport const config = __REDIRECT_CONFIG__\n\nexport default defineClientConfig({\n setup() {\n if (__REDIRECT_DIRECT__) setupRedirect(config)\n if (__VUEPRESS_DEV__) setupDevServerRedirect(config)\n },\n ...(__REDIRECT_MODAL__\n ? {\n rootComponents: [\n () =>\n h(RedirectModal, {\n config,\n locales: __REDIRECT_LOCALES__,\n }),\n ],\n }\n : {}),\n})\n"],"names":["config","config$1","defineClientConfig","setupRedirect","setupDevServerRedirect","h","RedirectModal"],"mappings":"sUAcO,MAAMA,EAAS,oBAEtB,IAAAC,EAAeC,EAAmB,CAChC,OAAQ,CACF,qBAAqBC,EAAcH,CAAM,EACzC,kBAAkBI,EAAuBJ,CAAM,CACrD,EACA,GAAI,mBACA,CACE,eAAgB,CACd,IACEK,EAAEC,EAAe,CACf,OAAAN,EACA,QAAS,oBACX,CAAC,CACL,CACF,EACA,CACN,CAAA,CAAC"}
@@ -0,0 +1,21 @@
1
+ export { default as RedirectModal } from './components/RedirectModal.js';
2
+ import { R as RedirectBehaviorConfig } from './behavior-BgEQhx7R.js';
3
+ import { ComputedRef } from 'vue';
4
+ import '@vuepress/helper/client';
5
+
6
+ declare const setupDevServerRedirect: ({ autoLocale, config, defaultBehavior, defaultLocale: defaultLocalePath, localeFallback, }: RedirectBehaviorConfig) => void;
7
+
8
+ interface LocaleInfo {
9
+ lang: string;
10
+ localePath: string;
11
+ }
12
+ declare const setupRedirect: (behaviorConfig: RedirectBehaviorConfig) => void;
13
+
14
+ interface RedirectInfo {
15
+ lang: string;
16
+ localePath: string;
17
+ }
18
+ declare const useRedirectInfo: (behaviorConfig: RedirectBehaviorConfig) => ComputedRef<RedirectInfo | null>;
19
+
20
+ export { setupDevServerRedirect, setupRedirect, useRedirectInfo };
21
+ export type { LocaleInfo, RedirectInfo };
@@ -0,0 +1,2 @@
1
+ import{default as d}from"./components/RedirectModal.js";import{s as u,a as c}from"./setupRedirect-DVhycPIJ.js";import{u as x}from"./useRedirectInfo-BzhIENgm.js";import"@vueuse/core";import"vue";import"vuepress/client";import"@vuepress/helper/transition/fade-in-scale-up.css";import"./styles/redirect-modal.css";import"@temp/redirect/map.js";import"@vuepress/helper/client";export{d as RedirectModal,u as setupDevServerRedirect,c as setupRedirect,x as useRedirectInfo};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ import{redirectMap as $}from"@temp/redirect/map.js";import{entries as x,isLinkHttp as C}from"@vuepress/helper/client";import{usePreferredLanguages as D,watchImmediate as E}from"@vueuse/core";import{computed as I,onMounted as j}from"vue";import{useRoute as y,useRouter as R,useRouteLocale as L,useRoutePath as g}from"vuepress/client";import{u as z,s as P}from"./useRedirectInfo-BzhIENgm.js";const A=/#.*$/u,B=(a,o=!1)=>(o?a.replace(A,""):a).replace(/\/(?:README\.md)?$/i,"/index.html").replace(/(?:\.(?:md|html))?$/,".html"),F=({autoLocale:a,config:o,defaultBehavior:l,defaultLocale:c,localeFallback:m})=>{const w=Object.entries(o),b=D(),d=y(),s=R(),k=L(),h=g(),M=I(()=>k.value==="/"),S=()=>{const e=h.value,r=s.getRoutes(),u=c&&r.some(({path:t})=>t===e.replace("/",c))?c:r.find(({path:t})=>e.split("/").length>=3&&t===e.replace(/^\/[^/]+\//,"/"))?.path;let p=null;e:for(const t of b.value)for(const[f,v]of w)if(v.includes(t)){if(m&&r.every(({path:i})=>i!==e.replace("/",i)))continue;p=f;break e}const n=u?d.fullPath.replace("/",u):null;if(p){const t=r.some(({path:i})=>e.replace("/",p)===i),f=d.fullPath.replace("/",p),v=t?f:l==="homepage"?p:l==="defaultLocale"&&n?n:f;s.replace(v)}else n?s.replace(n):h.value!=="/404.html"&&s.replace("/404.html")};E(h,e=>{for(const[r,u]of x($))if(B(e.toLowerCase())===r.toLowerCase()){C(u)?window.open(u):s.replace(u);return}a&&M.value&&S()})},H=a=>{const o=z(a),l=L(),c=g(),m=R();j(()=>{o.value&&!P.value[l.value]&&(m.replace(c.value.replace(l.value,o.value.localePath)),P.value[l.value]=!0)})};export{H as a,F as s};
2
+ //# sourceMappingURL=setupRedirect-DVhycPIJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setupRedirect-DVhycPIJ.js","sources":["../../src/shared/normalizePath.ts","../../src/client/composables/setupDevServerRedirect.ts","../../src/client/composables/setupRedirect.ts"],"sourcesContent":["const HASH_REGEXP = /#.*$/u\n\nexport const normalizePath = (path: string, removeHash = false): string =>\n (removeHash ? path.replace(HASH_REGEXP, '') : path)\n .replace(/\\/(?:README\\.md)?$/i, '/index.html')\n .replace(/(?:\\.(?:md|html))?$/, '.html')\n","import { redirectMap } from '@temp/redirect/map.js'\nimport { entries, isLinkHttp } from '@vuepress/helper/client'\nimport { usePreferredLanguages, watchImmediate } from '@vueuse/core'\nimport { computed } from 'vue'\nimport {\n useRoute,\n useRouteLocale,\n useRoutePath,\n useRouter,\n} from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { normalizePath } from '../../shared/index.js'\n\nexport const setupDevServerRedirect = ({\n autoLocale,\n config,\n defaultBehavior,\n defaultLocale: defaultLocalePath,\n localeFallback,\n}: RedirectBehaviorConfig): void => {\n const localeEntries = Object.entries(config)\n const languages = usePreferredLanguages()\n const route = useRoute()\n const router = useRouter()\n const routeLocale = useRouteLocale()\n const routePath = useRoutePath()\n\n const isRootLocale = computed(() => routeLocale.value === '/')\n\n const handleLocaleRedirect = (): void => {\n const routePathValue = routePath.value\n const routes = router.getRoutes()\n const defaultLocale =\n defaultLocalePath &&\n routes.some(\n ({ path }) => path === routePathValue.replace('/', defaultLocalePath),\n )\n ? defaultLocalePath\n : routes.find(\n ({ path }) =>\n routePathValue.split('/').length >= 3 &&\n path === routePathValue.replace(/^\\/[^/]+\\//, '/'),\n )?.path\n\n let matchedLocalePath: string | null = null\n\n // get matched locale\n // eslint-disable-next-line no-restricted-syntax\n findLanguage: for (const lang of languages.value)\n for (const [localePath, langs] of localeEntries)\n if (langs.includes(lang)) {\n if (\n localeFallback &&\n routes.every(\n ({ path }) => path !== routePathValue.replace('/', path),\n )\n )\n continue\n\n matchedLocalePath = localePath\n break findLanguage\n }\n\n // default link\n const defaultRoute = defaultLocale\n ? route.fullPath.replace('/', defaultLocale)\n : null\n\n // a locale matches\n if (matchedLocalePath) {\n const hasLocalePage = routes.some(\n ({ path }) => routePathValue.replace('/', matchedLocalePath) === path,\n )\n const localeRoute = route.fullPath.replace('/', matchedLocalePath)\n\n const redirectPath =\n // the locale page exists\n hasLocalePage\n ? localeRoute\n : // the page does not exist\n defaultBehavior === 'homepage'\n ? // locale homepage\n matchedLocalePath\n : defaultBehavior === 'defaultLocale' && defaultRoute\n ? // default locale page\n defaultRoute\n : // as is to get a 404 page of that locale\n localeRoute\n\n router.replace(redirectPath)\n }\n // we have a default page\n else if (defaultRoute) {\n router.replace(defaultRoute)\n } else if (routePath.value !== '/404.html') {\n router.replace('/404.html')\n }\n }\n\n watchImmediate(routePath, (path) => {\n // handle redirects\n for (const [from, to] of entries(redirectMap))\n if (normalizePath(path.toLowerCase()) === from.toLowerCase()) {\n if (isLinkHttp(to)) window.open(to)\n else router.replace(to)\n\n return\n }\n\n if (autoLocale && isRootLocale.value) handleLocaleRedirect()\n })\n}\n","import { onMounted } from 'vue'\nimport { useRouteLocale, useRoutePath, useRouter } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { statusSessionStorage } from '../utils/index.js'\nimport { useRedirectInfo } from './useRedirectInfo.js'\n\nexport interface LocaleInfo {\n lang: string\n localePath: string\n}\n\nexport const setupRedirect = (behaviorConfig: RedirectBehaviorConfig): void => {\n const redirectInfo = useRedirectInfo(behaviorConfig)\n const routeLocale = useRouteLocale()\n const routePath = useRoutePath()\n const router = useRouter()\n\n onMounted(() => {\n if (redirectInfo.value && !statusSessionStorage.value[routeLocale.value]) {\n router.replace(\n routePath.value.replace(\n routeLocale.value,\n redirectInfo.value.localePath,\n ),\n )\n statusSessionStorage.value[routeLocale.value] = true\n }\n })\n}\n"],"names":["HASH_REGEXP","normalizePath","path","removeHash","setupDevServerRedirect","autoLocale","config","defaultBehavior","defaultLocalePath","localeFallback","localeEntries","languages","usePreferredLanguages","route","useRoute","router","useRouter","routeLocale","useRouteLocale","routePath","useRoutePath","isRootLocale","computed","handleLocaleRedirect","routePathValue","routes","defaultLocale","matchedLocalePath","findLanguage","lang","localePath","langs","defaultRoute","hasLocalePage","localeRoute","redirectPath","watchImmediate","from","to","entries","redirectMap","isLinkHttp","setupRedirect","behaviorConfig","redirectInfo","useRedirectInfo","onMounted","statusSessionStorage"],"mappings":"sYAAA,MAAMA,EAAc,QAEPC,EAAgB,CAACC,EAAcC,EAAa,MACtDA,EAAaD,EAAK,QAAQF,EAAa,EAAE,EAAIE,GAC3C,QAAQ,sBAAuB,aAAa,EAC5C,QAAQ,sBAAuB,OAAO,ECQ9BE,EAAyB,CAAC,CACrC,WAAAC,EACA,OAAAC,EACA,gBAAAC,EACA,cAAeC,EACf,eAAAC,CACF,IAAoC,CAClC,MAAMC,EAAgB,OAAO,QAAQJ,CAAM,EACrCK,EAAYC,EAAsB,EAClCC,EAAQC,EACRC,EAAAA,EAASC,EAAU,EACnBC,EAAcC,IACdC,EAAYC,EAAAA,EAEZC,EAAeC,EAAS,IAAML,EAAY,QAAU,GAAG,EAEvDM,EAAuB,IAAY,CACvC,MAAMC,EAAiBL,EAAU,MAC3BM,EAASV,EAAO,YAChBW,EACJlB,GACAiB,EAAO,KACL,CAAC,CAAE,KAAAvB,CAAK,IAAMA,IAASsB,EAAe,QAAQ,IAAKhB,CAAiB,CACtE,EACIA,EACAiB,EAAO,KACL,CAAC,CAAE,KAAAvB,CAAK,IACNsB,EAAe,MAAM,GAAG,EAAE,QAAU,GACpCtB,IAASsB,EAAe,QAAQ,aAAc,GAAG,CACrD,GAAG,KAET,IAAIG,EAAmC,KAIvCC,EAAc,UAAWC,KAAQlB,EAAU,MACzC,SAAW,CAACmB,EAAYC,CAAK,IAAKrB,EAChC,GAAIqB,EAAM,SAASF,CAAI,EAAG,CACxB,GACEpB,GACAgB,EAAO,MACL,CAAC,CAAE,KAAAvB,CAAK,IAAMA,IAASsB,EAAe,QAAQ,IAAKtB,CAAI,CACzD,EAEA,SAEFyB,EAAoBG,EACpB,MAAMF,CACR,CAGJ,MAAMI,EAAeN,EACjBb,EAAM,SAAS,QAAQ,IAAKa,CAAa,EACzC,KAGJ,GAAIC,EAAmB,CACrB,MAAMM,EAAgBR,EAAO,KAC3B,CAAC,CAAE,KAAAvB,CAAK,IAAMsB,EAAe,QAAQ,IAAKG,CAAiB,IAAMzB,CACnE,EACMgC,EAAcrB,EAAM,SAAS,QAAQ,IAAKc,CAAiB,EAE3DQ,EAEJF,EACIC,EAEA3B,IAAoB,WAElBoB,EACApB,IAAoB,iBAAmByB,EAErCA,EAEAE,EAEVnB,EAAO,QAAQoB,CAAY,CAC7B,MAESH,EACPjB,EAAO,QAAQiB,CAAY,EAClBb,EAAU,QAAU,aAC7BJ,EAAO,QAAQ,WAAW,CAE9B,EAEAqB,EAAejB,EAAYjB,GAAS,CAElC,SAAW,CAACmC,EAAMC,CAAE,IAAKC,EAAQC,CAAW,EAC1C,GAAIvC,EAAcC,EAAK,YAAa,CAAA,IAAMmC,EAAK,YAAe,EAAA,CACxDI,EAAWH,CAAE,EAAG,OAAO,KAAKA,CAAE,EAC7BvB,EAAO,QAAQuB,CAAE,EAEtB,MACF,CAEEjC,GAAcgB,EAAa,OAAOE,EACxC,CAAA,CAAC,CACH,ECpGamB,EAAiBC,GAAiD,CAC7E,MAAMC,EAAeC,EAAgBF,CAAc,EAC7C1B,EAAcC,IACdC,EAAYC,IACZL,EAASC,IAEf8B,EAAU,IAAM,CACVF,EAAa,OAAS,CAACG,EAAqB,MAAM9B,EAAY,KAAK,IACrEF,EAAO,QACLI,EAAU,MAAM,QACdF,EAAY,MACZ2B,EAAa,MAAM,UACrB,CACF,EACAG,EAAqB,MAAM9B,EAAY,KAAK,EAAI,GAEpD,CAAC,CACH"}
@@ -0,0 +1 @@
1
+ .redirect-modal-mask{position:fixed;inset:0;z-index:var(--redirect-z-index);display:flex;align-items:center;justify-content:center;backdrop-filter:blur(10px)}@media print{.redirect-modal-mask{display:none}}.redirect-modal-wrapper{position:relative;z-index:1500;overflow:hidden;max-width:80vw;padding:1rem 2rem;border-radius:.5rem;background:var(--redirect-c-bg);box-shadow:0 2px 6px 0 var(--redirect-c-shadow)}.redirect-modal-hint{margin-top:.5rem;color:var(--vp-c-text-mute);font-size:.875rem;text-align:start}.redirect-modal-hint input[type=checkbox]{position:relative;vertical-align:text-bottom;height:1em;margin-inline-end:18px;font-size:inherit;cursor:pointer;appearance:none}.redirect-modal-hint input[type=checkbox]::after{content:" ";position:absolute;top:0;display:inline-block;box-sizing:border-box;width:14px;height:14px;padding-inline-start:0;border:1px solid var(--vp-c-border);border-radius:50%;background:var(--vp-c-control);text-align:center;visibility:visible}.redirect-modal-hint input[type=checkbox]:checked::after{content:"";border-color:var(--vp-c-accent-bg);background:var(--vp-c-accent-bg)}.redirect-modal-hint input[type=checkbox]:checked::before{content:"";position:absolute;inset-inline-start:5px;top:2px;z-index:1;width:2px;height:6px;border:solid var(--vp-c-white);border-width:0 2px 2px 0;transform:rotate(45deg)}.redirect-modal-hint label{display:inline-block}.redirect-modal-action{display:block;width:100%;margin:1rem 0;padding:.5rem .75rem;border:none;border-radius:.5rem;background-color:var(--redirect-c-control);color:inherit;cursor:pointer}.redirect-modal-action:hover{background-color:var(--redirect-c-control-hover)}.redirect-modal-action.primary{background-color:var(--redirect-c-accent-bg);color:var(--redirect-c-accent-text)}.redirect-modal-action.primary:hover{background-color:var(--redirect-c-accent-hover)}/*# sourceMappingURL=redirect-modal.css.map */
@@ -0,0 +1 @@
1
+ {"version":3,"sourceRoot":"","sources":["../../../src/client/styles/redirect-modal.scss"],"names":[],"mappings":"AAAA,qBACE,eACA,QACA,gCAEA,aACA,mBACA,uBAEA,2BAEA,aAXF,qBAYI,cAIJ,wBACE,kBACA,aAEA,gBAEA,eACA,kBACA,oBAEA,gCACA,gDAGF,qBACE,iBACA,4BACA,kBACA,iBAEA,0CACE,kBAEA,2BAEA,WACA,uBAEA,kBAEA,eAEA,gBAEA,iDACE,YAEA,kBACA,MAEA,qBAEA,sBACA,WACA,YACA,uBACA,oCACA,kBAEA,+BAEA,kBAEA,mBAIA,yDACE,WACA,mCACA,iCAGF,0DACE,WAEA,kBACA,uBACA,QACA,UAEA,UACA,WACA,+BACA,yBAEA,wBAKN,2BACE,qBAIJ,uBACE,cAEA,WACA,cACA,qBACA,YACA,oBAEA,2CACA,cAEA,eAEA,6BACE,iDAGF,+BACE,6CACA,oCAEA,qCACE","file":"redirect-modal.css","sourcesContent":[".redirect-modal-mask {\n position: fixed;\n inset: 0;\n z-index: var(--redirect-z-index);\n\n display: flex;\n align-items: center;\n justify-content: center;\n\n backdrop-filter: blur(10px);\n\n @media print {\n display: none;\n }\n}\n\n.redirect-modal-wrapper {\n position: relative;\n z-index: 1500;\n\n overflow: hidden;\n\n max-width: 80vw;\n padding: 1rem 2rem;\n border-radius: 0.5rem;\n\n background: var(--redirect-c-bg);\n box-shadow: 0 2px 6px 0 var(--redirect-c-shadow);\n}\n\n.redirect-modal-hint {\n margin-top: 0.5rem;\n color: var(--vp-c-text-mute);\n font-size: 0.875rem;\n text-align: start;\n\n input[type='checkbox'] {\n position: relative;\n\n vertical-align: text-bottom;\n\n height: 1em;\n margin-inline-end: 18px;\n\n font-size: inherit;\n\n cursor: pointer;\n\n appearance: none;\n\n &::after {\n content: ' ';\n\n position: absolute;\n top: 0;\n\n display: inline-block;\n\n box-sizing: border-box;\n width: 14px;\n height: 14px;\n padding-inline-start: 0;\n border: 1px solid var(--vp-c-border);\n border-radius: 50%;\n\n background: var(--vp-c-control);\n\n text-align: center;\n\n visibility: visible;\n }\n\n &:checked {\n &::after {\n content: '';\n border-color: var(--vp-c-accent-bg);\n background: var(--vp-c-accent-bg);\n }\n\n &::before {\n content: '';\n\n position: absolute;\n inset-inline-start: 5px;\n top: 2px;\n z-index: 1;\n\n width: 2px;\n height: 6px;\n border: solid var(--vp-c-white);\n border-width: 0 2px 2px 0;\n\n transform: rotate(45deg);\n }\n }\n }\n\n label {\n display: inline-block;\n }\n}\n\n.redirect-modal-action {\n display: block;\n\n width: 100%;\n margin: 1rem 0;\n padding: 0.5rem 0.75rem;\n border: none;\n border-radius: 0.5rem;\n\n background-color: var(--redirect-c-control);\n color: inherit;\n\n cursor: pointer;\n\n &:hover {\n background-color: var(--redirect-c-control-hover);\n }\n\n &.primary {\n background-color: var(--redirect-c-accent-bg);\n color: var(--redirect-c-accent-text);\n\n &:hover {\n background-color: var(--redirect-c-accent-hover);\n }\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ :root{--redirect-z-index: 1499;--redirect-c-bg: var(--vp-c-bg-elv);--redirect-c-text: var(--vp-c-text);--redirect-c-accent-bg: var(--vp-c-accent-bg);--redirect-c-accent-hover: var(--vp-c-accent-hover);--redirect-c-accent-text: var(--vp-c-accent-text);--redirect-c-control: var(--vp-c-control);--redirect-c-control-hover: var(--vp-c-control-hover);--redirect-c-shadow: var(--vp-c-shadow)}/*# sourceMappingURL=vars.css.map */
@@ -0,0 +1 @@
1
+ {"version":3,"sourceRoot":"","sources":["../../../src/client/styles/vars.css"],"names":[],"mappings":"AAAA,MACE,yBACA,oCACA,oCACA,8CACA,oDACA,kDACA,0CACA,sDACA","file":"vars.css","sourcesContent":[":root {\n --redirect-z-index: 1499;\n --redirect-c-bg: var(--vp-c-bg-elv);\n --redirect-c-text: var(--vp-c-text);\n --redirect-c-accent-bg: var(--vp-c-accent-bg);\n --redirect-c-accent-hover: var(--vp-c-accent-hover);\n --redirect-c-accent-text: var(--vp-c-accent-text);\n --redirect-c-control: var(--vp-c-control);\n --redirect-c-control-hover: var(--vp-c-control-hover);\n --redirect-c-shadow: var(--vp-c-shadow);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import{useSessionStorage as c,useLocalStorage as l,usePreferredLanguages as f}from"@vueuse/core";import{entries as i}from"@vuepress/helper/client";import{computed as m}from"vue";import{useRouteLocale as S}from"vuepress/client";const s="VUEPRESS_REDIRECT_STATUS",g=l(s,{}),p=c(s,{}),R=a=>{const u=f(),e=S(),t=i(a.config);return m(()=>{if(t.some(([o])=>e.value===o)){for(const o of u.value)for(const[r,n]of t)if(n.includes(o))return r===e.value?null:{lang:o,localePath:r}}return null})};export{g as a,p as s,R as u};
2
+ //# sourceMappingURL=useRedirectInfo-BzhIENgm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRedirectInfo-BzhIENgm.js","sources":["../../src/client/utils/storage.ts","../../src/client/composables/useRedirectInfo.ts"],"sourcesContent":["import { useLocalStorage, useSessionStorage } from '@vueuse/core'\n\nconst REDIRECT_STORAGE_KEY = 'VUEPRESS_REDIRECT_STATUS'\n\nexport const statusLocalStorage = useLocalStorage<Record<string, boolean>>(\n REDIRECT_STORAGE_KEY,\n {},\n)\n\nexport const statusSessionStorage = useSessionStorage<Record<string, boolean>>(\n REDIRECT_STORAGE_KEY,\n {},\n)\n","import { entries } from '@vuepress/helper/client'\nimport { usePreferredLanguages } from '@vueuse/core'\nimport type { ComputedRef } from 'vue'\nimport { computed } from 'vue'\nimport { useRouteLocale } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\n\nexport interface RedirectInfo {\n lang: string\n localePath: string\n}\n\nexport const useRedirectInfo = (\n behaviorConfig: RedirectBehaviorConfig,\n): ComputedRef<RedirectInfo | null> => {\n const languages = usePreferredLanguages()\n const routeLocale = useRouteLocale()\n\n const localeEntries = entries(behaviorConfig.config)\n\n return computed(() => {\n if (localeEntries.some(([key]) => routeLocale.value === key))\n for (const language of languages.value)\n for (const [localePath, langs] of localeEntries)\n if (langs.includes(language)) {\n if (localePath === routeLocale.value) return null\n\n return {\n lang: language,\n localePath,\n }\n }\n\n return null\n })\n}\n"],"names":["REDIRECT_STORAGE_KEY","statusLocalStorage","useLocalStorage","statusSessionStorage","useSessionStorage","useRedirectInfo","behaviorConfig","languages","usePreferredLanguages","routeLocale","useRouteLocale","localeEntries","entries","computed","key","language","localePath","langs"],"mappings":"mOAEA,MAAMA,EAAuB,2BAEhBC,EAAqBC,EAChCF,EACA,CACF,CAAA,EAEaG,EAAuBC,EAClCJ,EACA,CACF,CAAA,ECAaK,EACXC,GACqC,CACrC,MAAMC,EAAYC,EAAAA,EACZC,EAAcC,EAEdC,EAAAA,EAAgBC,EAAQN,EAAe,MAAM,EAEnD,OAAOO,EAAS,IAAM,CACpB,GAAIF,EAAc,KAAK,CAAC,CAACG,CAAG,IAAML,EAAY,QAAUK,CAAG,GACzD,UAAWC,KAAYR,EAAU,MAC/B,SAAW,CAACS,EAAYC,CAAK,IAAKN,EAChC,GAAIM,EAAM,SAASF,CAAQ,EACzB,OAAIC,IAAeP,EAAY,MAAc,KAEtC,CACL,KAAMM,EACN,WAAAC,CACF,EAGR,OAAO,IACT,CAAC,CACH"}
@@ -1,3 +1,113 @@
1
- export * from './frontmatter.js';
2
- export * from './options.js';
3
- export * from './redirectPlugin.js';
1
+ import { App, LocaleConfig, PluginFunction } from 'vuepress/core';
2
+ import { PageFrontmatter } from 'vuepress';
3
+
4
+ interface RedirectPluginFrontmatter extends PageFrontmatter {
5
+ redirectFrom?: string[] | string;
6
+ redirectTo?: string;
7
+ }
8
+
9
+ interface RedirectBehaviorOptions {
10
+ /**
11
+ * Whether enable locales redirection
12
+ *
13
+ * 是否启用语言重定向
14
+ *
15
+ * @default false
16
+ */
17
+ autoLocale?: boolean;
18
+ /**
19
+ * Whether fallback to other locales user defined
20
+ *
21
+ * 是否回退到用户定义的其他语言
22
+ *
23
+ * @default true
24
+ */
25
+ localeFallback?: boolean;
26
+ /**
27
+ * Behavior when a locale version is not available for current link
28
+ *
29
+ * @description `"homepage"` and `"404"` is only available when a locale is assigned to current language
30
+ *
31
+ * 当前链接没有可用的语言版本时的行为
32
+ *
33
+ * @description 只有当语言分配给当前语言时,`"homepage"` 和 `"404"` 才可用
34
+ *
35
+ * @default "defaultLocale"
36
+ */
37
+ defaultBehavior?: '404' | 'defaultLocale' | 'homepage';
38
+ /**
39
+ * Default locale path
40
+ *
41
+ * @description the first locale will be used if absent
42
+ *
43
+ * 默认语言路径
44
+ *
45
+ * @description 如果缺失,则使用第一个语言
46
+ */
47
+ defaultLocale?: string;
48
+ }
49
+
50
+ interface RedirectPluginLocaleData {
51
+ /**
52
+ * Language name
53
+ *
54
+ * 语言名称
55
+ */
56
+ name: string;
57
+ /**
58
+ * Switch hint
59
+ *
60
+ * 切换提示
61
+ */
62
+ hint: string;
63
+ /**
64
+ * Switch button text
65
+ *
66
+ * 切换按钮文字
67
+ */
68
+ switch: string;
69
+ /**
70
+ * Cancel button text
71
+ *
72
+ * 取消按钮文字
73
+ */
74
+ cancel: string;
75
+ /**
76
+ * remember hint text
77
+ *
78
+ * 记住提示文本
79
+ */
80
+ remember: string;
81
+ }
82
+
83
+ interface RedirectPluginOptions extends RedirectBehaviorOptions {
84
+ /**
85
+ * Redirect mapping
86
+ *
87
+ * 重定向映射
88
+ */
89
+ config?: Record<string, string> | ((app: App) => Record<string, string>);
90
+ /**
91
+ * Whether switch locales
92
+ *
93
+ * 是否启用重定向语言
94
+ */
95
+ switchLocale?: 'direct' | 'modal' | false;
96
+ /**
97
+ * Locale language config
98
+ *
99
+ * 多语言语言配置
100
+ */
101
+ localeConfig?: Record<string, string[] | string>;
102
+ /**
103
+ * Locales config
104
+ *
105
+ * 多语言选项
106
+ */
107
+ locales?: LocaleConfig<RedirectPluginLocaleData>;
108
+ }
109
+
110
+ declare const redirectPlugin: (options?: RedirectPluginOptions) => PluginFunction;
111
+
112
+ export { redirectPlugin };
113
+ export type { RedirectPluginFrontmatter, RedirectPluginOptions };
package/lib/node/index.js CHANGED
@@ -1,3 +1,90 @@
1
- export * from './frontmatter.js';
2
- export * from './options.js';
3
- export * from './redirectPlugin.js';
1
+ import{Logger as k,removeEndingSlash as h,entries as m,removeLeadingSlash as g,isLinkHttp as P,isLinkAbsolute as b,deepAssign as R,fromEntries as p,isPlainObject as w,isArray as L,keys as z,isFunction as S,getFullLocaleConfig as D,getModulePath as E,addViteSsrNoExternal as C}from"@vuepress/helper";import{fs as s,path as f,colors as _,getDirname as F}from"vuepress/utils";import{createPage as j}from"vuepress/core";const A=async a=>{a.pages.every(({path:e})=>e!=="/")&&a.pages.push(await j(a,{path:"/",frontmatter:{title:"Home"},content:`Redirecting to the correct locale...
2
+ `}))},v="@vuepress/plugin-redirect",d=new k(v),M=({config:a,defaultBehavior:e,defaultLocale:c,localeFallback:n},t,i)=>`<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="UTF-8">
6
+ <meta name="robots" content="noindex">
7
+ <title>Redirecting...</title>
8
+ <script>
9
+ const { hash, origin, pathname } = window.location;
10
+ const routePath = pathname.substring(${i.length});
11
+ const { languages } = window.navigator;
12
+ const anchor = hash.substring(1);
13
+
14
+ const config = ${JSON.stringify(a)};
15
+ const availableLocales = ${JSON.stringify(t)};
16
+ const defaultLocale = ${t.includes(c)?JSON.stringify(c):"availableLocales.pop()"};
17
+ const defaultBehavior = ${JSON.stringify(e)}
18
+
19
+ let matchedLocalePath = null;
20
+
21
+ // get matched locale
22
+ findLanguage:
23
+ for (const lang of languages)
24
+ for (const [localePath, langs] of Object.entries(config))
25
+ if (langs.includes(lang)) {
26
+ ${n?` if (!availableLocales.includes(localePath))
27
+ continue;
28
+ `:""} matchedLocalePath = localePath;
29
+ break findLanguage;
30
+ }
31
+
32
+ // default link
33
+ const defaultLink = defaultLocale? \`\${origin}${h(i)}\${defaultLocale}\${routePath}\${anchor? \`#\${anchor}\`: ""}\`: null;
34
+
35
+ // a locale matches
36
+ if (matchedLocalePath) {
37
+ const localeLink = \`\${origin}${h(i)}\${matchedLocalePath}\${routePath}\${anchor? \`#\${anchor}\`: ""}\`;
38
+
39
+ if (availableLocales.includes(matchedLocalePath)) {
40
+ location.href = localeLink;
41
+ }
42
+ // the page does not exist
43
+ else {
44
+ // locale homepage
45
+ if (defaultBehavior === "homepage") {
46
+ location.href = \`\${origin}${h(i)}\${matchedLocalePath}\`;
47
+ }
48
+ // default locale page
49
+ else if (defaultBehavior === "defaultLocale" && defaultLink) {
50
+ location.href = defaultLink;
51
+ }
52
+ // as is to get a 404 page of that locale
53
+ else {
54
+ location.href = localeLink;
55
+ }
56
+ }
57
+ }
58
+ // we have a default page
59
+ else if (defaultLink) {
60
+ location.href = defaultLink;
61
+ }
62
+ else {
63
+ location.href = \`\${origin}${h(i)}/404.html\`;
64
+ }
65
+ <\/script>
66
+ </head>
67
+ <body>
68
+ <p>Redirecting...</p>
69
+ </body>
70
+ </html>
71
+ `,T=async({dir:a,options:e,pages:c},n)=>{const t=c.filter(({pathLocale:l})=>l==="/").map(({path:l})=>l),i={};c.filter(({pathLocale:l})=>l!=="/").forEach(({path:l,pathLocale:o})=>{const r=l.replace(o,"/").replace(/\/$/,"/index.html");t.includes(r)||(i[r]??=[]).push(o)});const{succeed:$}=d.load("Generating locale redirect files");await Promise.all(m(i).map(async([l,o])=>{const r=a.dest(g(l));s.existsSync(r)||(await s.ensureDir(f.dirname(r)),await s.writeFile(r,M(n,o,e.base)))})),$()},B=a=>`<!doctype html>
72
+ <html lang="en">
73
+ <head>
74
+ <meta charset="UTF-8">
75
+ <meta name="robots" content="noindex">
76
+ <meta http-equiv="refresh" content="0; url=${a}">
77
+ <link rel="canonical" href="${a}">
78
+ <title>Redirecting...</title>
79
+ <script>
80
+ const anchor = window.location.hash.substring(1);
81
+ location.href = \`${a}\${anchor? \`#\${anchor}\`: ""}\`;
82
+ <\/script>
83
+ </head>
84
+ <body>
85
+ <p>Redirecting...</p>
86
+ </body>
87
+ </html>
88
+ `,I=async({dir:a,options:e},c,n="")=>{const t=n?h(P(n)?n:`https://${n}`):"",{succeed:i}=d.load("Generating redirect files");await Promise.all(m(c).map(async([$,l])=>{const o=a.dest(g($));if(!s.existsSync(o)){const r=b(l)?`${t}${e.base}${g(l)}`:l;await s.ensureDir(f.dirname(o)),await s.writeFile(o,B(r))}})),i()},N=["defaultLocale","homepage","404"],O=(a,e)=>{const{locales:c}=a.siteData,n=R(p(m(c).filter(([t,{lang:i}])=>i?!0:(d.error(`Missing ${_.magenta("lang")} option for locale "${t}", this locale will be ignored!`),!1)).map(([t,{lang:i}])=>[t,[i]])),w(e.localeConfig)?p(m(e.localeConfig).map(([t,i])=>[t,L(i)?i:[i]])):{});return{config:n,autoLocale:e.autoLocale??!1,defaultLocale:e.defaultLocale||z(n).pop(),localeFallback:e.localeFallback??!0,defaultBehavior:e.defaultBehavior&&N.includes(e.defaultBehavior)?e.defaultBehavior:"defaultLocale"}},x=/#.*$/u,u=(a,e=!1)=>(e?a.replace(x,""):a).replace(/\/(?:README\.md)?$/i,"/index.html").replace(/(?:\.(?:md|html))?$/,".html"),H=(a,e)=>{const c=S(e.config)?e.config(a):w(e.config)?e.config:{};return{...p(a.pages.map(({frontmatter:n,path:t})=>L(n.redirectFrom)?n.redirectFrom.map(i=>[u(i,!0),t]):n.redirectFrom?[[u(n.redirectFrom,!0),t]]:[]).flat()),...p(m(c).map(([n,t])=>[u(n,!0),u(t)]))}},U=({frontmatter:a},e)=>{const{base:c}=e.siteData,{redirectTo:n}=a;if(n){const t=u(b(n)?`${c}${g(n)}`:n);(a.head??=[]).unshift(["script",{},`{const anchor = window.location.hash.substring(1);location.href=\`${t}\${anchor? \`#\${anchor}\`: ""}\`;}`])}},V=[[["en","en-US"],{name:"English",hint:"Your primary language is $1, do you want to switch to it?",switch:"Switch to $1",cancel:"Cancel",remember:"Remember my choice"}],[["zh","zh-CN","zh-Hans"],{name:"简体中文",hint:"您的首选语言是 $1,是否切换到该语言?",switch:"切换到 $1",cancel:"取消",remember:"记住我的选择"}],[["zh-TW","zh-Hant"],{name:"繁體中文",hint:"您的首選語言是 $1,是否切換到該語言?",switch:"切換到 $1",cancel:"取消",remember:"記住我的選擇"}],[["de","de-DE"],{name:"Deutsch",hint:"Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?",switch:"Zu $1 wechseln",cancel:"Abbrechen",remember:"Meine Wahl merken"}],[["de-AT"],{name:"Deutsch (Österreich)",hint:"Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?",switch:"Zu $1 wechseln",cancel:"Abbrechen",remember:"Meine Wahl merken"}],[["vi","vi-VN"],{name:"Tiếng Việt",hint:"Ngôn ngữ chính của bạn là $1, bạn có muốn chuyển sang nó?",switch:"Chuyển sang $1",cancel:"Hủy",remember:"Nhớ lựa chọn của tôi"}],[["uk"],{name:"Українська",hint:"Вашою основною мовою є $1, чи бажаєте ви переключитися на неї?",switch:"Переключитися на $1",cancel:"Скасувати",remember:"Запам’ятати мій вибір"}],[["ru","ru-RU"],{name:"Русский",hint:"Ваш основной язык - $1, вы хотите переключиться на него?",switch:"Переключиться на $1",cancel:"Отмена",remember:"Запомнить мой выбор"}],[["br"],{name:"Português (Brasil)",hint:"A língua principal é $1, deseja mudar para ela?",switch:"Mudar para $1",cancel:"Cancelar",remember:"Lembrar minha escolha"}],[["pl","pl-PL"],{name:"Polski",hint:"Twoim głównym językiem jest $1, czy chcesz przełączyć się na niego?",switch:"Przełącz na $1",cancel:"Anuluj",remember:"Zapamiętaj moje wybory"}],[["sk","sk-SK"],{name:"Slovenčina",hint:"Vašou hlavnou jazykom je $1, chcete prepnúť naň?",switch:"Prepnúť na $1",cancel:"Zrušiť",remember:"Zapamätať si moju voľbu"}],[["fr","fr-FR"],{name:"Français",hint:"Votre langue principale est $1, voulez-vous la changer ?",switch:"Changer pour $1",cancel:"Annuler",remember:"Se souvenir de mon choix"}],[["tr","tr-TR"],{name:"Türkçe",hint:"Ana diliniz $1, ona geçmek ister misiniz?",switch:"$1'e geç",cancel:"İptal",remember:"Seçimimi hatırla"}],[["fi","fi-FI"],{name:"Suomi",hint:"Pääkielenäsi on $1, haluatko vaihtaa siihen?",switch:"Vaihda $1:een",cancel:"Peruuta",remember:"Muista valintani"}],[["hu","hu-HU"],{name:"Magyar",hint:"A fő nyelvét $1, szeretné váltani?",switch:"Váltás $1",cancel:"Mégse",remember:"Emlékezzen a választásomra"}],[["id","id-ID"],{name:"Bahasa Indonesia",hint:"Bahasa utama Anda adalah $1, apakah Anda ingin beralih ke sana?",switch:"Beralih ke $1",cancel:"Batal",remember:"Ingat pilihan saya"}],[["nl","nl-NL"],{name:"Nederlands",hint:"Uw primaire taal is $1, wilt u overschakelen?",switch:"Overschakelen naar $1",cancel:"Annuleren",remember:"Onthoud mijn keuze"}],[["ja","ja-JP"],{name:"日本語",hint:"あなたの主要な言語は $1 です。それに切り替えますか?",switch:"$1 に切り替える",cancel:"キャンセル",remember:"選択を記憶する"}],[["ko","ko-KO"],{name:"한국어",hint:"당신의 기본 언어는 $1입니다. 그것으로 전환 하시겠습니까?",switch:"$1로 전환",cancel:"취소",remember:"내 선택 기억하기"}],[["es","es-ES"],{name:"Español",hint:"Su idioma principal es $1, ¿desea cambiarlo?",switch:"Cambiar a $1",cancel:"Cancelar",remember:"Recordar mi elección"}],[["/pt"],{name:"Português",hint:"Sua língua principal é $1, deseja mudar para ela?",switch:"Mudar para $1",cancel:"Cancelar",remember:"Lembrar minha escolha"}]],{url:J}=import.meta,y=F(J),G=(a={})=>e=>{e.env.isDebug&&d.info("Options:",a);const c=O(e,a);let n=null;return{name:v,alias:{"@vuepress/plugin-redirect/modal":a.switchLocale==="modal"?f.resolve(y,"../client/components/RedirectModal.js"):E("@vuepress/helper/noopComponent",import.meta)},define:{__REDIRECT_CONFIG__:c,__REDIRECT_DIRECT__:a.switchLocale==="direct",__REDIRECT_MODAL__:a.switchLocale==="modal",__REDIRECT_LOCALES__:D({app:e,name:"redirect",config:a.locales,default:V})},extendsBundlerOptions:t=>{C(t,e,"@vuepress/helper")},extendsPage:t=>{U(t,e)},onInitialized:async()=>{n=H(e,a),e.env.isDebug&&d.info("Redirect Map:",n),a.autoLocale&&e.env.isDebug&&await A(e)},onPrepared:async()=>{await e.writeTemp("redirect/map.js",`export const redirectMap = ${e.env.isDev?JSON.stringify(n,null,2):"{}"};
89
+ `),e.env.isDev&&(n=null)},onGenerated:async()=>{await I(e,n),a.autoLocale&&await T(e,c)},clientConfigFile:f.join(y,"../client/config.js")}};export{G as redirectPlugin};
90
+ //# sourceMappingURL=index.js.map