|
| 1 | +//@ts-expect-error Node |
| 2 | +import fs from 'fs'; |
| 3 | +import { mainLocale, baseUrl } from '../config'; |
| 4 | +import type { SiteConfig } from 'vitepress'; |
| 5 | + |
| 6 | +async function createFile(path: string, content: string) { |
| 7 | + const dir = path.replace(/\/[^/]+$/, ''); |
| 8 | + await fs.promises.writeFile(path, content).catch((err) => { |
| 9 | + if (err.code === 'ENOENT') { |
| 10 | + fs.promises.mkdir(dir, { recursive: true }).then(() => createFile(path, content)); |
| 11 | + } |
| 12 | + }); |
| 13 | +} |
| 14 | + |
| 15 | +export async function genI18nRedirector(siteConfig: SiteConfig) { |
| 16 | + const routes = siteConfig.pages |
| 17 | + .filter((page) => page.startsWith(`${mainLocale}/`)) |
| 18 | + .map((page) => page.replace(new RegExp(`^${mainLocale}\/`), '').replace(/\.md$/, '.html')); |
| 19 | + |
| 20 | + const promises = routes.map((route) => { |
| 21 | + const localeNames = Object.keys(siteConfig.site.locales); |
| 22 | + const routeForRender = route.replace(/index\.html$/, ''); |
| 23 | + const linkAlternate = localeNames.map((name) => `<link rel="alternate" hreflang="${siteConfig.site.locales[name].lang || name}" href="${baseUrl}/${name}/${routeForRender}">`).join('\n '); |
| 24 | + const fallbackLinks = localeNames.map((name) => `<a href="${baseUrl}/${name}/${routeForRender}">${siteConfig.site.locales[name].label}</a>`).join(', '); |
| 25 | + const content = `<!DOCTYPE html> |
| 26 | +<html lang="${siteConfig.site.locales[mainLocale].lang || 'ja-JP'}"> |
| 27 | +<head> |
| 28 | + <meta charset="UTF-8"> |
| 29 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 30 | + <title>Redirecting...</title> |
| 31 | + ${linkAlternate} |
| 32 | + <link rel="alternate" hreflang="x-default" href="${baseUrl}/${mainLocale}/${routeForRender}"> |
| 33 | + <link rel="canonical" href="${baseUrl}/${mainLocale}/${routeForRender}"> |
| 34 | + <script type="text/javascript">const s = ${JSON.stringify(localeNames)}; const d = localStorage.getItem('ais:locale'); if (d) { location.replace('/' + d + location.pathname + location.search); } else if (s.includes(navigator.language.split("-")[0])) { location.replace('/' + navigator.language.split("-")[0] + location.pathname + location.search); } else { location.replace('/ja' + location.pathname + location.search); }</script> |
| 35 | +</head> |
| 36 | +<body> |
| 37 | + <noscript>${fallbackLinks}</noscript> |
| 38 | +</body> |
| 39 | +</html> |
| 40 | +`; |
| 41 | + return createFile(`${siteConfig.outDir}/${route}`, content); |
| 42 | + }); |
| 43 | + |
| 44 | + await Promise.allSettled(promises); |
| 45 | + |
| 46 | + console.log('I18n redirector generated'); |
| 47 | +} |
0 commit comments