@vuepress/plugin-redirect 2.0.0-rc.11 → 2.0.0-rc.111

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 (71) 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 -4
  8. package/lib/client/config.js +2 -11
  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-BBJERz7T.js +2 -0
  14. package/lib/client/setupRedirect-BBJERz7T.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 -10
  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 -2
  22. package/lib/node/index.js +90 -1
  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 -2
  36. package/lib/node/ensureRootHomePage.js +0 -15
  37. package/lib/node/generate/generateAutoLocaleRedirectFiles.d.ts +0 -3
  38. package/lib/node/generate/generateAutoLocaleRedirectFiles.js +0 -28
  39. package/lib/node/generate/generateRedirectFiles.d.ts +0 -2
  40. package/lib/node/generate/generateRedirectFiles.js +0 -21
  41. package/lib/node/generate/getLocaleRedirectHTML.d.ts +0 -2
  42. package/lib/node/generate/getLocaleRedirectHTML.js +0 -77
  43. package/lib/node/generate/getRedirectHTML.d.ts +0 -1
  44. package/lib/node/generate/getRedirectHTML.js +0 -18
  45. package/lib/node/generate/index.d.ts +0 -2
  46. package/lib/node/generate/index.js +0 -2
  47. package/lib/node/getRedirectLocaleConfig.d.ts +0 -4
  48. package/lib/node/getRedirectLocaleConfig.js +0 -35
  49. package/lib/node/getRedirectMap.d.ts +0 -3
  50. package/lib/node/getRedirectMap.js +0 -25
  51. package/lib/node/handleRedirectTo.d.ts +0 -2
  52. package/lib/node/handleRedirectTo.js +0 -19
  53. package/lib/node/locales.d.ts +0 -3
  54. package/lib/node/locales.js +0 -129
  55. package/lib/node/logger.d.ts +0 -3
  56. package/lib/node/logger.js +0 -3
  57. package/lib/node/redirectPlugin.d.ts +0 -3
  58. package/lib/node/redirectPlugin.js +0 -53
  59. package/lib/node/types/frontmatter.d.ts +0 -4
  60. package/lib/node/types/frontmatter.js +0 -1
  61. package/lib/node/types/index.d.ts +0 -2
  62. package/lib/node/types/index.js +0 -1
  63. package/lib/node/types/options.d.ts +0 -22
  64. package/lib/node/types/options.js +0 -1
  65. package/lib/shared/index.d.ts +0 -3
  66. package/lib/shared/index.js +0 -3
  67. package/lib/shared/localeConfig.js +0 -1
  68. package/lib/shared/locales.d.ts +0 -24
  69. package/lib/shared/locales.js +0 -1
  70. package/lib/shared/normalizePath.d.ts +0 -1
  71. package/lib/shared/normalizePath.js +0 -4
package/lib/node/index.js CHANGED
@@ -1 +1,90 @@
1
- export * from './redirectPlugin.js';
1
+ import{Logger as y,removeEndingSlash as s,entries as h,removeLeadingSlash as u,isLinkHttp as k,isLinkAbsolute as f,deepAssign as P,fromEntries as g,isPlainObject as $,isArray as w,keys as R,isFunction as z,getFullLocaleConfig as S,getModulePath as D,addViteSsrNoExternal as E}from"@vuepress/helper";import{fs as r,path as p,colors as C,getDirname as _}from"vuepress/utils";import{createPage as F}from"vuepress/core";const j=async a=>{a.pages.every(({path:e})=>e!=="/")&&a.pages.push(await F(a,{path:"/",frontmatter:{title:"Home"},content:`Redirecting to the correct locale...
2
+ `}))},b="@vuepress/plugin-redirect",m=new y(b),A=({config:a,defaultBehavior:e,defaultLocale:c,localeFallback:n},i,t)=>`<!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.slice(${t.length});
11
+ const { languages } = window.navigator;
12
+ const anchor = hash.slice(1);
13
+
14
+ const config = ${JSON.stringify(a)};
15
+ const availableLocales = ${JSON.stringify(i)};
16
+ const defaultLocale = ${i.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}${s(t)}\${defaultLocale}\${routePath}\${anchor? \`#\${anchor}\`: ""}\`: null;
34
+
35
+ // a locale matches
36
+ if (matchedLocalePath) {
37
+ const localeLink = \`\${origin}${s(t)}\${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}${s(t)}\${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}${s(t)}/404.html\`;
64
+ }
65
+ <\/script>
66
+ </head>
67
+ <body>
68
+ <p>Redirecting...</p>
69
+ </body>
70
+ </html>
71
+ `,M=async(a,e)=>{const c=a.pages.filter(({pathLocale:t})=>t==="/").map(({path:t})=>t),n={};a.pages.filter(({pathLocale:t})=>t!=="/").forEach(({path:t,pathLocale:o})=>{const l=t.replace(o,"/").replace(/\/$/,"/index.html");c.includes(l)||(n[l]??=[]).push(o)});const{succeed:i}=m.load("Generating locale redirect files");await Promise.all(h(n).map(async([t,o])=>{const l=a.dir.dest(u(t));r.existsSync(l)||(await r.ensureDir(p.dirname(l)),await r.writeFile(l,A(e,o,a.siteData.base)))})),i()},T=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.slice(1);
81
+ window.location.replace(\`${a}\${anchor? \`#\${anchor}\`: ""}\`);
82
+ <\/script>
83
+ </head>
84
+ <body>
85
+ <p>Redirecting...</p>
86
+ </body>
87
+ </html>
88
+ `,B=async(a,e,c="")=>{const n=c?s(k(c)?c:`https://${c}`):"",{succeed:i}=m.load("Generating redirect files");await Promise.all(h(e).map(async([t,o])=>{const l=a.dir.dest(u(t));if(!r.existsSync(l)){const v=f(o)?`${n}${a.siteData.base}${u(o)}`:o;await r.ensureDir(p.dirname(l)),await r.writeFile(l,T(v))}})),i()},I=["defaultLocale","homepage","404"],N=(a,e)=>{const{locales:c}=a.siteData,n=P(g(h(c).filter(([i,{lang:t}])=>t?!0:(m.error(`Missing ${C.magenta("lang")} option for locale "${i}", this locale will be ignored!`),!1)).map(([i,{lang:t}])=>[i,[t]])),$(e.localeConfig)?g(h(e.localeConfig).map(([i,t])=>[i,w(t)?t:[t]])):{});return{config:n,autoLocale:e.autoLocale??!1,defaultLocale:e.defaultLocale||R(n).pop(),localeFallback:e.localeFallback??!0,defaultBehavior:e.defaultBehavior&&I.includes(e.defaultBehavior)?e.defaultBehavior:"defaultLocale"}},O=/#.*$/u,d=(a,e=!1)=>(e?a.replace(O,""):a).replace(/\/(?:README\.md)?$/i,"/index.html").replace(/(?:\.(?:md|html))?$/,".html"),x=(a,e)=>{const c=z(e.config)?e.config(a):$(e.config)?e.config:{};return{...g(a.pages.map(({frontmatter:n,path:i})=>w(n.redirectFrom)?n.redirectFrom.map(t=>[d(t,!0),i]):n.redirectFrom?[[d(n.redirectFrom,!0),i]]:[]).flat()),...g(h(c).map(([n,i])=>[d(n,!0),d(i)]))}},H=({frontmatter:a},e)=>{const{base:c}=e.siteData,{redirectTo:n}=a;if(n){const i=d(f(n)?`${c}${u(n)}`:n);(a.head??=[]).unshift(["script",{},`{const anchor = window.location.hash.slice(1);window.location.replace(\`${i}\${anchor? \`#\${anchor}\`: ""}\`);}`])}},U=[[["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:V}=import.meta,L=_(V),J=(a={})=>e=>{e.env.isDebug&&m.info("Options:",a);const c=N(e,a);let n=null;return{name:b,alias:{"@vuepress/plugin-redirect/modal":a.switchLocale==="modal"?p.resolve(L,"../client/components/RedirectModal.js"):D("@vuepress/helper/noopComponent",import.meta)},define:{__REDIRECT_CONFIG__:c,__REDIRECT_DIRECT__:a.switchLocale==="direct",__REDIRECT_MODAL__:a.switchLocale==="modal",__REDIRECT_LOCALES__:S({app:e,name:"redirect",config:a.locales,default:U})},extendsBundlerOptions:i=>{E(i,e,"@vuepress/helper")},extendsPage:i=>{H(i,e)},onInitialized:async()=>{n=x(e,a),e.env.isDebug&&m.info("Redirect Map:",n),a.autoLocale&&e.env.isDebug&&await j(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 B(e,n),a.autoLocale&&await M(e,c)},clientConfigFile:p.join(L,"../client/config.js")}};export{J as redirectPlugin};
90
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/node/ensureRootHomePage.ts","../../src/node/logger.ts","../../src/node/generate/getLocaleRedirectHTML.ts","../../src/node/generate/generateAutoLocaleRedirectFiles.ts","../../src/node/generate/getRedirectHTML.ts","../../src/node/generate/generateRedirectFiles.ts","../../src/node/getRedirectLocaleConfig.ts","../../src/shared/normalizePath.ts","../../src/node/getRedirectMap.ts","../../src/node/handleRedirectTo.ts","../../src/node/locales.ts","../../src/node/redirectPlugin.ts"],"sourcesContent":["import type { App } from 'vuepress/core'\nimport { createPage } from 'vuepress/core'\n\nexport const ensureRootHomePage = async (app: App): Promise<void> => {\n if (\n // root homepage not exists\n app.pages.every(({ path }) => path !== '/')\n ) {\n app.pages.push(\n await createPage(app, {\n path: '/',\n frontmatter: { title: 'Home' },\n // set markdown content\n content: `\\\nRedirecting to the correct locale...\n`,\n }),\n )\n }\n}\n","import { Logger } from '@vuepress/helper'\n\nexport const PLUGIN_NAME = '@vuepress/plugin-redirect'\n\nexport const logger = new Logger(PLUGIN_NAME)\n","import { removeEndingSlash } from '@vuepress/helper'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\n\nexport const getLocaleRedirectHTML = (\n {\n config,\n defaultBehavior,\n defaultLocale,\n localeFallback,\n }: RedirectBehaviorConfig,\n availableLocales: string[],\n base: string,\n): string => `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"robots\" content=\"noindex\">\n <title>Redirecting...</title>\n <script>\n const { hash, origin, pathname } = window.location;\n const routePath = pathname.slice(${base.length});\n const { languages } = window.navigator;\n const anchor = hash.slice(1);\n\n const config = ${JSON.stringify(config)};\n const availableLocales = ${JSON.stringify(availableLocales)};\n const defaultLocale = ${\n availableLocales.includes(defaultLocale)\n ? JSON.stringify(defaultLocale)\n : 'availableLocales.pop()'\n };\n const defaultBehavior = ${JSON.stringify(defaultBehavior)}\n\n let matchedLocalePath = null;\n\n // get matched locale\n findLanguage:\n for (const lang of languages)\n for (const [localePath, langs] of Object.entries(config))\n if (langs.includes(lang)) {\n${\n localeFallback\n ? `\\\n if (!availableLocales.includes(localePath))\n continue;\n`\n : ``\n}\\\n matchedLocalePath = localePath;\n break findLanguage;\n }\n\n // default link\n const defaultLink = defaultLocale? \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${defaultLocale}\\${routePath}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`: null;\n\n // a locale matches\n if (matchedLocalePath) {\n const localeLink = \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${matchedLocalePath}\\${routePath}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`;\n\n if (availableLocales.includes(matchedLocalePath)) {\n location.href = localeLink;\n }\n // the page does not exist\n else {\n // locale homepage\n if (defaultBehavior === \"homepage\") {\n location.href = \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${matchedLocalePath}\\`;\n }\n // default locale page\n else if (defaultBehavior === \"defaultLocale\" && defaultLink) {\n location.href = defaultLink;\n }\n // as is to get a 404 page of that locale\n else {\n location.href = localeLink;\n }\n }\n }\n // we have a default page\n else if (defaultLink) {\n location.href = defaultLink;\n }\n else {\n location.href = \\`\\${origin}${removeEndingSlash(base)}/404.html\\`;\n }\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n","import { entries, removeLeadingSlash } from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { fs, path } from 'vuepress/utils'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { logger } from '../logger.js'\nimport { getLocaleRedirectHTML } from './getLocaleRedirectHTML.js'\n\nexport const generateAutoLocaleRedirectFiles = async (\n app: App,\n localeOptions: RedirectBehaviorConfig,\n): Promise<void> => {\n const rootPaths = app.pages\n .filter(({ pathLocale }) => pathLocale === '/')\n .map(({ path: pagePath }) => pagePath)\n const localeRedirectMap: Record<string, string[]> = {}\n\n app.pages\n .filter(({ pathLocale }) => pathLocale !== '/')\n .forEach(({ path: pagePath, pathLocale }) => {\n const rootPath = pagePath\n .replace(pathLocale, '/')\n .replace(/\\/$/, '/index.html')\n\n if (!rootPaths.includes(rootPath))\n (localeRedirectMap[rootPath] ??= []).push(pathLocale)\n })\n\n const { succeed } = logger.load('Generating locale redirect files')\n\n await Promise.all(\n entries(localeRedirectMap).map(async ([rootPath, availableLocales]) => {\n const filePath = app.dir.dest(removeLeadingSlash(rootPath))\n\n if (!fs.existsSync(filePath)) {\n await fs.ensureDir(path.dirname(filePath))\n await fs.writeFile(\n filePath,\n getLocaleRedirectHTML(\n localeOptions,\n availableLocales,\n app.siteData.base,\n ),\n )\n }\n }),\n )\n\n succeed()\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.slice(1);\n window.location.replace(\\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`);\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n","import {\n entries,\n isLinkAbsolute,\n isLinkHttp,\n removeEndingSlash,\n removeLeadingSlash,\n} from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { fs, path } from 'vuepress/utils'\nimport { logger } from '../logger.js'\nimport { getRedirectHTML } from './getRedirectHTML.js'\n\nexport const generateRedirectFiles = async (\n app: App,\n config: Record<string, string>,\n hostname = '',\n): Promise<void> => {\n const resolvedHostname = hostname\n ? removeEndingSlash(isLinkHttp(hostname) ? hostname : `https://${hostname}`)\n : ''\n\n const { succeed } = logger.load('Generating redirect files')\n\n await Promise.all(\n entries(config).map(async ([from, to]) => {\n const filePath = app.dir.dest(removeLeadingSlash(from))\n\n if (!fs.existsSync(filePath)) {\n const redirectUrl = isLinkAbsolute(to)\n ? `${resolvedHostname}${app.siteData.base}${removeLeadingSlash(to)}`\n : to\n\n await fs.ensureDir(path.dirname(filePath))\n await fs.writeFile(filePath, getRedirectHTML(redirectUrl))\n }\n }),\n )\n\n succeed()\n}\n","import {\n deepAssign,\n entries,\n fromEntries,\n isArray,\n isPlainObject,\n keys,\n} from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { colors } from 'vuepress/utils'\nimport type { RedirectBehaviorConfig } from '../shared/index.js'\nimport { logger } from './logger.js'\nimport type { RedirectPluginOptions } from './types/index.js'\n\nconst AVAILABLE_FALLBACK = ['defaultLocale', 'homepage', '404'] as const\n\nexport const getRedirectBehaviorConfig = (\n app: App,\n options: RedirectPluginOptions,\n): RedirectBehaviorConfig => {\n const { locales } = app.siteData\n\n const config = deepAssign(\n fromEntries(\n entries(locales)\n .filter(([key, { lang }]) => {\n if (!lang) {\n logger.error(\n `Missing ${colors.magenta(\n 'lang',\n )} option for locale \"${key}\", this locale will be ignored!`,\n )\n\n return false\n }\n\n return true\n })\n .map(([key, { lang }]) => [key, [lang!]]),\n ),\n isPlainObject(options.localeConfig)\n ? fromEntries(\n entries(options.localeConfig).map(([routePath, lang]) => [\n routePath,\n isArray(lang) ? lang : [lang],\n ]),\n )\n : {},\n )\n\n return {\n config,\n autoLocale: options.autoLocale ?? false,\n defaultLocale: options.defaultLocale || keys(config).pop()!,\n localeFallback: options.localeFallback ?? true,\n defaultBehavior:\n options.defaultBehavior &&\n AVAILABLE_FALLBACK.includes(options.defaultBehavior)\n ? options.defaultBehavior\n : 'defaultLocale',\n }\n}\n","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 {\n entries,\n fromEntries,\n isArray,\n isFunction,\n isPlainObject,\n} from '@vuepress/helper'\nimport type { App, Page } from 'vuepress/core'\nimport { normalizePath } from '../shared/normalizePath.js'\nimport type {\n RedirectPluginFrontmatter,\n RedirectPluginOptions,\n} from './types/index.js'\n\nexport const getRedirectMap = (\n app: App,\n options: RedirectPluginOptions,\n): Record<string, string> => {\n const config = isFunction(options.config)\n ? options.config(app)\n : isPlainObject(options.config)\n ? options.config\n : {}\n\n return {\n ...fromEntries(\n (app.pages as Page<Record<string, never>, RedirectPluginFrontmatter>[])\n .map<\n [string, string][]\n >(({ frontmatter, path }) => (isArray(frontmatter.redirectFrom) ? frontmatter.redirectFrom.map((from) => [normalizePath(from, true), path]) : frontmatter.redirectFrom ? [[normalizePath(frontmatter.redirectFrom, true), path]] : []))\n .flat(),\n ),\n ...fromEntries(\n entries(config).map(([from, to]) => [\n normalizePath(from, true),\n normalizePath(to),\n ]),\n ),\n }\n}\n","import { isLinkAbsolute, removeLeadingSlash } from '@vuepress/helper'\nimport type { App, Page } from 'vuepress/core'\nimport { normalizePath } from '../shared/normalizePath.js'\nimport type { RedirectPluginFrontmatter } from './types/index.js'\n\nexport const handleRedirectTo = ({ frontmatter }: Page, app: App): void => {\n const { base } = app.siteData\n const { redirectTo } = frontmatter as RedirectPluginFrontmatter\n\n if (redirectTo) {\n const redirectUrl = normalizePath(\n isLinkAbsolute(redirectTo)\n ? `${base}${removeLeadingSlash(redirectTo)}`\n : redirectTo,\n )\n\n ;(frontmatter.head ??= []).unshift([\n 'script',\n {},\n `{\\\nconst anchor = window.location.hash.slice(1);\\\nwindow.location.replace(\\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`);\\\n}`,\n ])\n }\n}\n","import type { DefaultLocaleInfo } from '@vuepress/helper'\nimport type { RedirectPluginLocaleData } from '../shared/index.js'\n\n/**\n * Default locale info for `@vuepress/plugin-redirect`\n */\nexport const redirectLocaleInfo: DefaultLocaleInfo<RedirectPluginLocaleData> = [\n [\n ['en', 'en-US'],\n {\n name: 'English',\n hint: 'Your primary language is $1, do you want to switch to it?',\n switch: 'Switch to $1',\n cancel: 'Cancel',\n remember: 'Remember my choice',\n },\n ],\n [\n ['zh', 'zh-CN', 'zh-Hans'],\n {\n name: '简体中文',\n hint: '你的首选语言是 $1,是否切换到该语言?',\n switch: '切换到 $1',\n cancel: '取消',\n remember: '记住我的选择',\n },\n ],\n [\n ['zh-TW', 'zh-Hant'],\n {\n name: '繁體中文',\n hint: '你的首選語言是 $1,是否切換到該語言?',\n switch: '切換到 $1',\n cancel: '取消',\n remember: '記住我的選擇',\n },\n ],\n [\n ['de', 'de-DE'],\n {\n name: 'Deutsch',\n hint: 'Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?',\n switch: 'Zu $1 wechseln',\n cancel: 'Abbrechen',\n remember: 'Meine Wahl merken',\n },\n ],\n [\n ['de-AT'],\n {\n name: 'Deutsch (Österreich)',\n hint: 'Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?',\n switch: 'Zu $1 wechseln',\n cancel: 'Abbrechen',\n remember: 'Meine Wahl merken',\n },\n ],\n [\n ['vi', 'vi-VN'],\n {\n name: 'Tiếng Việt',\n hint: 'Ngôn ngữ chính của bạn là $1, bạn có muốn chuyển sang nó?',\n switch: 'Chuyển sang $1',\n cancel: 'Hủy',\n remember: 'Nhớ lựa chọn của tôi',\n },\n ],\n [\n ['uk'],\n {\n name: 'Українська',\n hint: 'Вашою основною мовою є $1, чи бажаєте ви переключитися на неї?',\n switch: 'Переключитися на $1',\n cancel: 'Скасувати',\n remember: 'Запам’ятати мій вибір',\n },\n ],\n [\n ['ru', 'ru-RU'],\n {\n name: 'Русский',\n hint: 'Ваш основной язык - $1, вы хотите переключиться на него?',\n switch: 'Переключиться на $1',\n cancel: 'Отмена',\n remember: 'Запомнить мой выбор',\n },\n ],\n [\n ['br'],\n {\n name: 'Português (Brasil)',\n hint: 'A língua principal é $1, deseja mudar para ela?',\n switch: 'Mudar para $1',\n cancel: 'Cancelar',\n remember: 'Lembrar minha escolha',\n },\n ],\n [\n ['pl', 'pl-PL'],\n {\n name: 'Polski',\n hint: 'Twoim głównym językiem jest $1, czy chcesz przełączyć się na niego?',\n switch: 'Przełącz na $1',\n cancel: 'Anuluj',\n remember: 'Zapamiętaj moje wybory',\n },\n ],\n [\n ['sk', 'sk-SK'],\n {\n name: 'Slovenčina',\n hint: 'Vašou hlavnou jazykom je $1, chcete prepnúť naň?',\n switch: 'Prepnúť na $1',\n cancel: 'Zrušiť',\n remember: 'Zapamätať si moju voľbu',\n },\n ],\n [\n ['fr', 'fr-FR'],\n {\n name: 'Français',\n hint: 'Votre langue principale est $1, voulez-vous la changer ?',\n switch: 'Changer pour $1',\n cancel: 'Annuler',\n remember: 'Se souvenir de mon choix',\n },\n ],\n [\n ['tr', 'tr-TR'],\n {\n name: 'Türkçe',\n hint: 'Ana diliniz $1, ona geçmek ister misiniz?',\n switch: \"$1'e geç\",\n cancel: 'İptal',\n remember: 'Seçimimi hatırla',\n },\n ],\n [\n ['fi', 'fi-FI'],\n {\n name: 'Suomi',\n hint: 'Pääkielenäsi on $1, haluatko vaihtaa siihen?',\n switch: 'Vaihda $1:een',\n cancel: 'Peruuta',\n remember: 'Muista valintani',\n },\n ],\n [\n ['hu', 'hu-HU'],\n {\n name: 'Magyar',\n hint: 'A fő nyelvét $1, szeretné váltani?',\n switch: 'Váltás $1',\n cancel: 'Mégse',\n remember: 'Emlékezzen a választásomra',\n },\n ],\n [\n ['id', 'id-ID'],\n {\n name: 'Bahasa Indonesia',\n hint: 'Bahasa utama Anda adalah $1, apakah Anda ingin beralih ke sana?',\n switch: 'Beralih ke $1',\n cancel: 'Batal',\n remember: 'Ingat pilihan saya',\n },\n ],\n [\n ['nl', 'nl-NL'],\n {\n name: 'Nederlands',\n hint: 'Uw primaire taal is $1, wilt u overschakelen?',\n switch: 'Overschakelen naar $1',\n cancel: 'Annuleren',\n remember: 'Onthoud mijn keuze',\n },\n ],\n [\n ['ja', 'ja-JP'],\n {\n name: '日本語',\n hint: 'あなたの主要な言語は $1 です。それに切り替えますか?',\n switch: '$1 に切り替える',\n cancel: 'キャンセル',\n remember: '選択を記憶する',\n },\n ],\n [\n ['ko', 'ko-KO'],\n {\n name: '한국어',\n hint: '당신의 기본 언어는 $1입니다. 그것으로 전환 하시겠습니까?',\n switch: '$1로 전환',\n cancel: '취소',\n remember: '내 선택 기억하기',\n },\n ],\n [\n ['es', 'es-ES'],\n {\n name: 'Español',\n hint: 'Su idioma principal es $1, ¿desea cambiarlo?',\n switch: 'Cambiar a $1',\n cancel: 'Cancelar',\n remember: 'Recordar mi elección',\n },\n ],\n [\n ['/pt'],\n {\n name: 'Português',\n hint: 'Sua língua principal é $1, deseja mudar para ela?',\n switch: 'Mudar para $1',\n cancel: 'Cancelar',\n remember: 'Lembrar minha escolha',\n },\n ],\n]\n","import {\n addViteSsrNoExternal,\n getFullLocaleConfig,\n getModulePath,\n} from '@vuepress/helper'\nimport type { PluginFunction } from 'vuepress/core'\nimport { getDirname, path } from 'vuepress/utils'\nimport { ensureRootHomePage } from './ensureRootHomePage.js'\nimport {\n generateAutoLocaleRedirectFiles,\n generateRedirectFiles,\n} from './generate/index.js'\nimport { getRedirectBehaviorConfig } from './getRedirectLocaleConfig.js'\nimport { getRedirectMap } from './getRedirectMap.js'\nimport { handleRedirectTo } from './handleRedirectTo.js'\nimport { redirectLocaleInfo } from './locales.js'\nimport { PLUGIN_NAME, logger } from './logger.js'\nimport type { RedirectPluginOptions } from './types/index.js'\n\nconst { url } = import.meta\nconst __dirname = getDirname(url)\n\nexport const redirectPlugin =\n (options: RedirectPluginOptions = {}): PluginFunction =>\n (app) => {\n if (app.env.isDebug) logger.info('Options:', options)\n\n const behaviorConfig = getRedirectBehaviorConfig(app, options)\n let redirectMap: Record<string, string> | null = null\n\n return {\n name: PLUGIN_NAME,\n\n alias: {\n '@vuepress/plugin-redirect/modal':\n options.switchLocale === 'modal'\n ? path.resolve(__dirname, '../client/components/RedirectModal.js')\n : getModulePath('@vuepress/helper/noopComponent', import.meta),\n },\n\n define: {\n __REDIRECT_CONFIG__: behaviorConfig,\n __REDIRECT_DIRECT__: options.switchLocale === 'direct',\n __REDIRECT_MODAL__: options.switchLocale === 'modal',\n __REDIRECT_LOCALES__: getFullLocaleConfig({\n app,\n name: 'redirect',\n config: options.locales,\n default: redirectLocaleInfo,\n }),\n },\n\n extendsBundlerOptions: (bundlerOptions: unknown): void => {\n addViteSsrNoExternal(bundlerOptions, app, '@vuepress/helper')\n },\n\n extendsPage: (page) => {\n handleRedirectTo(page, app)\n },\n\n onInitialized: async (): Promise<void> => {\n redirectMap = getRedirectMap(app, options)\n\n if (app.env.isDebug) logger.info('Redirect Map:', redirectMap)\n\n if (options.autoLocale && app.env.isDebug) await ensureRootHomePage(app)\n },\n\n onPrepared: async (): Promise<void> => {\n await app.writeTemp(\n 'redirect/map.js',\n `\\\nexport const redirectMap = ${\n app.env.isDev ? JSON.stringify(redirectMap, null, 2) : '{}'\n };\n`,\n )\n // clean redirectMap reference in dev server\n if (app.env.isDev) redirectMap = null\n },\n\n onGenerated: async (): Promise<void> => {\n await generateRedirectFiles(app, redirectMap!)\n if (options.autoLocale)\n await generateAutoLocaleRedirectFiles(app, behaviorConfig)\n },\n\n clientConfigFile: path.join(__dirname, '../client/config.js'),\n }\n }\n"],"names":["ensureRootHomePage","app","path","createPage","PLUGIN_NAME","logger","Logger","getLocaleRedirectHTML","config","defaultBehavior","defaultLocale","localeFallback","availableLocales","base","removeEndingSlash","generateAutoLocaleRedirectFiles","localeOptions","rootPaths","pathLocale","pagePath","localeRedirectMap","rootPath","succeed","entries","filePath","removeLeadingSlash","fs","getRedirectHTML","redirectUrl","generateRedirectFiles","hostname","resolvedHostname","isLinkHttp","from","to","isLinkAbsolute","AVAILABLE_FALLBACK","getRedirectBehaviorConfig","options","locales","deepAssign","fromEntries","key","lang","colors","isPlainObject","routePath","isArray","keys","HASH_REGEXP","normalizePath","removeHash","getRedirectMap","isFunction","frontmatter","handleRedirectTo","redirectTo","redirectLocaleInfo","url","__dirname","getDirname","redirectPlugin","behaviorConfig","redirectMap","getModulePath","getFullLocaleConfig","bundlerOptions","addViteSsrNoExternal","page"],"mappings":"gaAGO,MAAMA,EAAqB,MAAOC,GAA4B,CAGjEA,EAAI,MAAM,MAAM,CAAC,CAAE,KAAAC,CAAK,IAAMA,IAAS,GAAG,GAE1CD,EAAI,MAAM,KACR,MAAME,EAAWF,EAAK,CACpB,KAAM,IACN,YAAa,CAAE,MAAO,MAAO,EAE7B,QAAS;AAAA,CAGX,CAAC,CACH,CAEJ,ECjBaG,EAAc,4BAEdC,EAAS,IAAIC,EAAOF,CAAW,ECD/BG,EAAwB,CACnC,CACE,OAAAC,EACA,gBAAAC,EACA,cAAAC,EACA,eAAAC,CACF,EACAC,EACAC,IACW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uCAQ0BA,EAAK,MAAM;AAAA;AAAA;AAAA;AAAA,qBAI7B,KAAK,UAAUL,CAAM,CAAC;AAAA,+BACZ,KAAK,UAAUI,CAAgB,CAAC;AAAA,4BAEzDA,EAAiB,SAASF,CAAa,EACnC,KAAK,UAAUA,CAAa,EAC5B,wBACN;AAAA,8BAC0B,KAAK,UAAUD,CAAe,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU3DE,EACI;AAAA;AAAA,EAIA,EACN;AAAA;AAAA;AAAA;AAAA;AAAA,qDAMqDG,EAC/CD,CACF,CAAC;AAAA;AAAA;AAAA;AAAA,uCAIkCC,EAC/BD,CACF,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wCASiCC,EAC5BD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2.0.0-rc.111",
4
4
  "description": "VuePress plugin - redirect",
5
5
  "keywords": [
6
6
  "vuepress-plugin",
@@ -8,14 +8,14 @@
8
8
  "plugin",
9
9
  "redirect"
10
10
  ],
11
- "homepage": "https://ecosystem.vuejs.press/plugins/redirect.html",
11
+ "homepage": "https://ecosystem.vuejs.press/plugins/tools/redirect.html",
12
12
  "bugs": {
13
13
  "url": "https://github.com/vuepress/ecosystem/issues"
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
17
  "url": "git+https://github.com/vuepress/ecosystem.git",
18
- "directory": "plugins/plugin-redirect"
18
+ "directory": "plugins/tools/plugin-redirect"
19
19
  },
20
20
  "license": "MIT",
21
21
  "author": {
@@ -26,6 +26,7 @@
26
26
  "type": "module",
27
27
  "exports": {
28
28
  ".": "./lib/node/index.js",
29
+ "./client": "./lib/client/index.js",
29
30
  "./package.json": "./package.json"
30
31
  },
31
32
  "main": "./lib/node/index.js",
@@ -36,23 +37,17 @@
36
37
  "files": [
37
38
  "lib"
38
39
  ],
39
- "scripts": {
40
- "build": "tsc -b tsconfig.build.json",
41
- "clean": "rimraf --glob ./lib ./*.tsbuildinfo",
42
- "style": "sass src:lib --no-source-map"
43
- },
44
40
  "dependencies": {
45
- "@vuepress/helper": "~2.0.0-rc.11",
46
- "@vueuse/core": "^10.7.2",
47
- "cac": "^6.7.14",
48
- "vue": "^3.4.15",
49
- "vue-router": "^4.2.5"
41
+ "@vuepress/helper": "2.0.0-rc.111",
42
+ "@vueuse/core": "^13.5.0",
43
+ "commander": "^14.0.0",
44
+ "vue": "^3.5.17"
50
45
  },
51
46
  "peerDependencies": {
52
- "vuepress": "2.0.0-rc.6"
47
+ "vuepress": "2.0.0-rc.24"
53
48
  },
54
49
  "publishConfig": {
55
50
  "access": "public"
56
51
  },
57
- "gitHead": "7ba11252716b7f900ecb4215b8a523c51d751738"
52
+ "gitHead": "d5246d2b40807aa5227e5320a3759c44a877d8cd"
58
53
  }
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
@@ -1,4 +0,0 @@
1
- import type { VNode } from 'vue';
2
- import '../styles/language-switch.css';
3
- declare const _default: import("vue").DefineComponent<{}, () => VNode | null, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{}>>, {}, {}>;
4
- export default _default;
@@ -1,99 +0,0 @@
1
- import { usePreferredLanguages, useScrollLock, useSessionStorage, } from '@vueuse/core';
2
- import { computed, defineComponent, h, onMounted, onUnmounted, ref, TransitionGroup, watch, } from 'vue';
3
- import { useRoute, useRouter } from 'vue-router';
4
- import { useRouteLocale } from 'vuepress/client';
5
- import { redirectLocaleConfig, redirectLocaleEntries } from '../define.js';
6
- import '../styles/language-switch.css';
7
- const redirectLocales = __REDIRECT_LOCALES__;
8
- const { switchLocale } = redirectLocaleConfig;
9
- const REDIRECT_LOCALE_STORAGE = useSessionStorage('VUEPRESS_REDIRECT_LOCALES', {});
10
- export default defineComponent({
11
- name: 'LanguageSwitch',
12
- setup() {
13
- const languages = usePreferredLanguages();
14
- const route = useRoute();
15
- const router = useRouter();
16
- const routeLocale = useRouteLocale();
17
- const showModal = ref(false);
18
- const info = computed(() => {
19
- if (redirectLocaleEntries.some(([key]) => routeLocale.value === key))
20
- for (const language of languages.value)
21
- for (const [localePath, langs] of redirectLocaleEntries)
22
- if (langs.includes(language)) {
23
- if (localePath === routeLocale.value)
24
- return null;
25
- return {
26
- lang: language,
27
- localePath,
28
- };
29
- }
30
- return null;
31
- });
32
- const locale = computed(() => {
33
- if (info.value) {
34
- const { lang, localePath } = info.value;
35
- const locales = [
36
- redirectLocales[routeLocale.value],
37
- redirectLocales[localePath],
38
- ];
39
- return {
40
- hint: locales.map(({ hint }) => hint.replace('$1', lang)),
41
- switch: locales
42
- .map(({ switch: switchText }) => switchText.replace('$1', lang))
43
- .join(' / '),
44
- cancel: locales.map(({ cancel }) => cancel).join(' / '),
45
- };
46
- }
47
- return null;
48
- });
49
- const targetRoute = computed(() => info.value
50
- ? route.path.replace(routeLocale.value, info.value.localePath)
51
- : null);
52
- const updateStatus = () => {
53
- REDIRECT_LOCALE_STORAGE.value[routeLocale.value] = true;
54
- showModal.value = false;
55
- };
56
- onMounted(() => {
57
- const isLocked = useScrollLock(document.body);
58
- if (!REDIRECT_LOCALE_STORAGE.value[routeLocale.value])
59
- if (info.value)
60
- if (switchLocale === 'direct')
61
- router.replace(targetRoute.value);
62
- else if (switchLocale === 'modal')
63
- showModal.value = true;
64
- else
65
- showModal.value = false;
66
- else
67
- showModal.value = false;
68
- watch(showModal, (value) => {
69
- isLocked.value = value;
70
- }, { immediate: true });
71
- onUnmounted(() => {
72
- isLocked.value = false;
73
- });
74
- });
75
- return () => showModal.value
76
- ? h(TransitionGroup, { name: 'lang-modal-fade' }, () => showModal.value
77
- ? h('div', { key: 'mask', class: 'lang-modal-mask' }, h('div', {
78
- key: 'popup',
79
- class: 'lang-modal-wrapper',
80
- }, [
81
- h('div', { class: 'lang-modal-content' }, locale.value?.hint.map((text) => h('p', text))),
82
- h('button', {
83
- type: 'button',
84
- class: 'lang-modal-action primary',
85
- onClick: () => {
86
- updateStatus();
87
- router.replace(targetRoute.value);
88
- },
89
- }, locale.value?.switch),
90
- h('button', {
91
- type: 'button',
92
- class: 'lang-modal-action',
93
- onClick: () => updateStatus(),
94
- }, locale.value?.cancel),
95
- ]))
96
- : null)
97
- : null;
98
- },
99
- });
@@ -1 +0,0 @@
1
- export * from './setupDevServerRedirect.js';
@@ -1 +0,0 @@
1
- export * from './setupDevServerRedirect.js';
@@ -1 +0,0 @@
1
- export declare const setupDevServerRedirect: () => void;
@@ -1,80 +0,0 @@
1
- import { redirectMap } from '@temp/redirect/map.js';
2
- import { entries, isLinkHttp } from '@vuepress/helper/client';
3
- import { usePreferredLanguages } from '@vueuse/core';
4
- import { computed, watch } from 'vue';
5
- import { useRoute, useRouter } from 'vue-router';
6
- import { useRouteLocale } from 'vuepress/client';
7
- import { normalizePath } from '../../shared/index.js';
8
- import { redirectLocaleConfig, redirectLocaleEntries } from '../define.js';
9
- const { autoLocale, defaultBehavior, defaultLocale: defaultLocalePath, localeFallback, } = redirectLocaleConfig;
10
- export const setupDevServerRedirect = () => {
11
- const languages = usePreferredLanguages();
12
- const route = useRoute();
13
- const router = useRouter();
14
- const routeLocale = useRouteLocale();
15
- const isRootLocale = computed(() => routeLocale.value === '/');
16
- const handleLocaleRedirect = () => {
17
- const routes = router.getRoutes();
18
- const defaultLocale = defaultLocalePath &&
19
- routes.some(({ path }) => path === route.path.replace('/', defaultLocalePath))
20
- ? defaultLocalePath
21
- : routes.find(({ path }) => route.path.split('/').length >= 3 &&
22
- path === route.path.replace(/^\/[^/]+\//, '/'))?.path;
23
- let matchedLocalePath = null;
24
- // get matched locale
25
- // eslint-disable-next-line no-labels
26
- findLanguage: for (const lang of languages.value)
27
- for (const [localePath, langs] of redirectLocaleEntries)
28
- if (langs.includes(lang)) {
29
- if (localeFallback &&
30
- routes.every(({ path }) => path !== route.path.replace('/', path)))
31
- continue;
32
- matchedLocalePath = localePath;
33
- // eslint-disable-next-line no-labels
34
- break findLanguage;
35
- }
36
- // default link
37
- const defaultRoute = defaultLocale
38
- ? route.fullPath.replace('/', defaultLocale)
39
- : null;
40
- // a locale matches
41
- if (matchedLocalePath) {
42
- const hasLocalePage = routes.some(({ path }) => route.path.replace('/', matchedLocalePath) === path);
43
- const localeRoute = route.fullPath.replace('/', matchedLocalePath);
44
- const routePath =
45
- // the locale page exists
46
- hasLocalePage
47
- ? localeRoute
48
- : // the page does not exist
49
- defaultBehavior === 'homepage'
50
- ? // locale homepage
51
- matchedLocalePath
52
- : defaultBehavior === 'defaultLocale' && defaultRoute
53
- ? // default locale page
54
- defaultRoute
55
- : // as is to get a 404 page of that locale
56
- localeRoute;
57
- router.replace(routePath);
58
- }
59
- // we have a default page
60
- else if (defaultRoute) {
61
- router.replace(defaultRoute);
62
- }
63
- else if (route.path !== '/404.html') {
64
- router.replace('/404.html');
65
- }
66
- };
67
- watch(() => route.path, (path) => {
68
- // handle redirects
69
- for (const [from, to] of entries(redirectMap))
70
- if (normalizePath(path.toLowerCase()) === from.toLowerCase()) {
71
- if (isLinkHttp(to))
72
- window.open(to);
73
- else
74
- router.replace(to);
75
- return;
76
- }
77
- if (autoLocale && isRootLocale.value)
78
- handleLocaleRedirect();
79
- }, { immediate: true });
80
- };
@@ -1,3 +0,0 @@
1
- import type { RedirectLocaleConfig } from '../shared/index.js';
2
- export declare const redirectLocaleConfig: RedirectLocaleConfig;
3
- export declare const redirectLocaleEntries: [string, string[]][];
@@ -1,3 +0,0 @@
1
- import { entries } from '@vuepress/helper/client';
2
- export const redirectLocaleConfig = __REDIRECT_LOCALE_CONFIG__;
3
- export const redirectLocaleEntries = entries(redirectLocaleConfig.localeConfig);
@@ -1,57 +0,0 @@
1
- .lang-modal-fade-enter-active,
2
- .lang-modal-fade-leave-active {
3
- transition: opacity 0.5s;
4
- }
5
-
6
- .lang-modal-fade-enter,
7
- .lang-modal-fade-leave-to {
8
- opacity: 0;
9
- }
10
-
11
- .lang-modal-mask {
12
- position: fixed;
13
- inset: 0;
14
- z-index: var(--redirect-z-index);
15
- display: flex;
16
- align-items: center;
17
- justify-content: center;
18
- backdrop-filter: blur(10px);
19
- }
20
- @media print {
21
- .lang-modal-mask {
22
- display: none;
23
- }
24
- }
25
-
26
- .lang-modal-wrapper {
27
- position: relative;
28
- z-index: 1500;
29
- overflow: hidden;
30
- max-width: 80vw;
31
- padding: 1rem 2rem;
32
- border-radius: 8px;
33
- background: var(--redirect-bg-color);
34
- box-shadow: 0 2px 6px 0 var(--card-shadow);
35
- }
36
-
37
- .lang-modal-action {
38
- display: block;
39
- width: 100%;
40
- margin: 1rem 0;
41
- padding: 0.5rem 0.75rem;
42
- border: none;
43
- border-radius: 8px;
44
- background-color: var(--redirect-bg-color-lighter);
45
- color: inherit;
46
- cursor: pointer;
47
- }
48
- .lang-modal-action:hover {
49
- background-color: var(--redirect-bg-color-light);
50
- }
51
- .lang-modal-action.primary {
52
- background-color: var(--redirect-primary-color);
53
- color: var(--redirect-primary-text-color);
54
- }
55
- .lang-modal-action.primary:hover {
56
- background-color: var(--redirect-primary-hover-color);
57
- }
@@ -1,2 +0,0 @@
1
- import type { App } from 'vuepress/core';
2
- export declare const ensureRootHomePage: (app: App) => Promise<void>;
@@ -1,15 +0,0 @@
1
- import { createPage } from 'vuepress/core';
2
- export const ensureRootHomePage = async (app) => {
3
- if (
4
- // root homepage not exists
5
- app.pages.every(({ path }) => path !== '/')) {
6
- app.pages.push(await createPage(app, {
7
- path: '/',
8
- frontmatter: { title: 'Home' },
9
- // set markdown content
10
- content: `\
11
- Redirecting to the correct locale...
12
- `,
13
- }));
14
- }
15
- };
@@ -1,3 +0,0 @@
1
- import type { App } from 'vuepress/core';
2
- import type { RedirectLocaleConfig } from '../../shared/index.js';
3
- export declare const generateAutoLocaleRedirectFiles: ({ dir, options, pages }: App, localeOptions: RedirectLocaleConfig) => Promise<void>;
@@ -1,28 +0,0 @@
1
- import { entries, removeLeadingSlash } from '@vuepress/helper';
2
- import { fs, path } from 'vuepress/utils';
3
- import { logger } from '../logger.js';
4
- import { getLocaleRedirectHTML } from './getLocaleRedirectHTML.js';
5
- export const generateAutoLocaleRedirectFiles = async ({ dir, options, pages }, localeOptions) => {
6
- const rootPaths = pages
7
- .filter(({ pathLocale }) => pathLocale === '/')
8
- .map(({ path }) => path);
9
- const localeRedirectMap = {};
10
- pages
11
- .filter(({ pathLocale }) => pathLocale !== '/')
12
- .forEach(({ path, pathLocale }) => {
13
- const rootPath = path
14
- .replace(pathLocale, '/')
15
- .replace(/\/$/, '/index.html');
16
- if (!rootPaths.includes(rootPath))
17
- (localeRedirectMap[rootPath] ??= []).push(pathLocale);
18
- });
19
- const { succeed } = logger.load('Generating locale redirect files');
20
- await Promise.all(entries(localeRedirectMap).map(async ([rootPath, availableLocales]) => {
21
- const filePath = dir.dest(removeLeadingSlash(rootPath));
22
- if (!fs.existsSync(filePath)) {
23
- await fs.ensureDir(path.dirname(filePath));
24
- await fs.writeFile(filePath, getLocaleRedirectHTML(localeOptions, availableLocales, options.base));
25
- }
26
- }));
27
- succeed();
28
- };
@@ -1,2 +0,0 @@
1
- import type { App } from 'vuepress/core';
2
- export declare const generateRedirectFiles: ({ dir, options }: App, config: Record<string, string>, hostname?: string) => Promise<void>;
@@ -1,21 +0,0 @@
1
- import { entries, isLinkAbsolute, isLinkHttp, removeEndingSlash, removeLeadingSlash, } from '@vuepress/helper';
2
- import { fs, path } from 'vuepress/utils';
3
- import { logger } from '../logger.js';
4
- import { getRedirectHTML } from './getRedirectHTML.js';
5
- export const generateRedirectFiles = async ({ dir, options }, config, hostname = '') => {
6
- const resolvedHostname = hostname
7
- ? removeEndingSlash(isLinkHttp(hostname) ? hostname : `https://${hostname}`)
8
- : '';
9
- const { succeed } = logger.load('Generating redirect files');
10
- await Promise.all(entries(config).map(async ([from, to]) => {
11
- const filePath = dir.dest(removeLeadingSlash(from));
12
- if (!fs.existsSync(filePath)) {
13
- const redirectUrl = isLinkAbsolute(to)
14
- ? `${resolvedHostname}${options.base}${removeLeadingSlash(to)}`
15
- : to;
16
- await fs.ensureDir(path.dirname(filePath));
17
- await fs.writeFile(filePath, getRedirectHTML(redirectUrl));
18
- }
19
- }));
20
- succeed();
21
- };
@@ -1,2 +0,0 @@
1
- import type { RedirectLocaleConfig } from '../../shared/index.js';
2
- export declare const getLocaleRedirectHTML: ({ localeConfig, defaultBehavior, defaultLocale, localeFallback, }: RedirectLocaleConfig, availableLocales: string[], base: string) => string;