- Implemented astro-i18next for multi-language support, including English, Dutch, and Italian. - Configured default locale and language fallback settings. - Defined routes for localized content in the configuration. - Updated package.json and package-lock.json to include new dependencies for i18next and related plugins.
10 lines
7.6 KiB
JavaScript
10 lines
7.6 KiB
JavaScript
|
|
import module2 from 'module';
|
|
import path2 from 'path';
|
|
import * as url2 from 'url';
|
|
const require = module2.createRequire(import.meta.url);
|
|
const __filename = url2.fileURLToPath(import.meta.url);
|
|
const __dirname = path2.dirname(__filename);
|
|
|
|
var g={config:{defaultLocale:"cimode",locales:[],namespaces:"translation",defaultNamespace:"translation",load:["server"],routes:{},flatRoutes:{},showDefaultLocale:!1,trailingSlash:"ignore",resourcesBasePath:"/locales"}},A=e=>{let r={};for(let n in e)n==="routes"&&(r=y(e[n])),g.config[n]=e[n];g.config.flatRoutes=r},$=e=>({...g.config,...e}),y=(e,r=[],n=[],s=null)=>{let o=s||{};for(let t in e)if(typeof e[t]=="object"&&e[t]!==null)y(e[t],[...r,t],[...n,Object.prototype.hasOwnProperty.call(e[t],"index")?e[t].index:t],o);else{let l="/"+r.join("/"),i="/"+n.join("/");t==="index"?(o[l]=i,l+="/"+t,i+="/"+t,o[l]=i):(l+="/"+t,i+="/"+e[t],o[l]=i)}return o};import p,{t as k}from"i18next";import{fileURLToPath as S}from"url";import b from"@proload/core";import w from"@proload/plugin-tsm";var L=async(e,r)=>{let n=S(e),s;if(r){let o=/^\.*\//.test(r)?r:`./${r}`;s=S(new URL(o,e))}return b.use([w]),await b("astro-i18next",{mustExist:!1,cwd:n,filePath:s})},C=(e,r)=>{let n=e.indexOf(r);e.splice(n,1),e.unshift(r)},N=(e,r,n=null)=>{let s=k(e,{ns:n});if(s===e)return console.warn(`WARNING(astro-i18next): missing translation key ${e}.`),r;let o=/<([\w\d]+)([^>]*)>/gi,t=r.match(o);if(!t)return console.warn("WARNING(astro-i18next): default slot does not include any HTML tag to interpolate! You should use the `t` function directly."),s;let l=[];t.forEach(a=>{let[,c,u]=o.exec(a);l.push({name:c,attributes:u}),o.exec("")});let i=s;for(let a=0;a<l.length;a++){let c=l[a];i=i.replaceAll(`<${a}>`,`<${c.name}${c.attributes}>`),i=i.replaceAll(`</${a}>`,`</${c.name}>`)}return i},O=e=>{let r=["strong","br","em","i","b"],n=[];p.options&&(n=["keySeparator","nsSeparator","pluralSeparator","contextSeparator"].map(i=>({key:i,str:p.options[i]})).filter(function(i){return typeof i<"u"}));let s=/<([\w\d]+)([^>]*)>/gi,o=e.match(s);if(!o)return console.warn("WARNING(astro-i18next): default slot does not include any HTML tag to interpolate! You should use the `t` function directly."),e;let t=[];o.forEach(i=>{let[,a,c]=s.exec(i);t.push({name:a,attributes:c}),s.exec("")});let l=e.replace(/\s+/g," ").trim();for(let i=0;i<t.length;i++){let a=t[i];r.includes(a.name)&&a.attributes.trim().length===0||(l=l.replaceAll(new RegExp(`<${a.name}[^>]*?\\s*\\/>`,"gi"),`<${i}/>`),l=l.replaceAll(`<${a.name}${a.attributes}>`,`<${i}>`),l=l.replaceAll(`</${a.name}>`,`</${i}>`))}for(let i=0;i<n.length;i++){let{key:a,str:c}=n[i];l.includes(c)&&console.warn(`WARNING(astro-i18next): "${c}" was found in a <Trans> translation key, but it is also used as ${a}. Either explicitly set an i18nKey or change the value of ${a}.`)}return l},m=(e,r)=>{if(e==="/")return e;switch(r){case"always":return e.endsWith("/")?e:e+"/";case"never":return e.replace(/\/$/,"");default:return e}},P=(e="/",r=null,n=import.meta.env.BASE_URL)=>{r||(r=p.language);let s=e.split("/").filter(f=>f!==""),o=n.split("/").filter(f=>f!=="");JSON.stringify(s).startsWith(JSON.stringify(o).replace(/]+$/,""))&&s.splice(0,o.length),e=s.length===0?"":s.join("/"),n=o.length===0?"/":"/"+o.join("/")+"/";let{flatRoutes:t,showDefaultLocale:l,defaultLocale:i,locales:a,trailingSlash:c}=g.config;if(!a.includes(r))return console.warn(`WARNING(astro-i18next): "${r}" locale is not supported, add it to the locales in your astro config.`),m(`${n}${e}`,c);if(s.length===0)return m(l?`${n}${r}`:r===i?n:`${n}${r}`,c);if(r===i){let f=Object.keys(t).find(d=>t[d]==="/"+e);typeof f<"u"&&(s=f.split("/").filter(d=>d!==""))}for(let f of a)if(s[0]===f){s.shift();break}(l||r!==i)&&(s=[r,...s]);let u=n+s.join("/");return Object.prototype.hasOwnProperty.call(t,u.replace(/\/$/,""))?m(t[u.replace(/\/$/,"")],c):m(u,c)},T=(e,r=null,n=import.meta.env.BASE_URL)=>{let[s,,o,...t]=e.split("/");return s+"//"+o+P(t.join("/"),r,n)},E=e=>{e=e.replace(/^\/+/g,"");let{defaultLocale:r,locales:n}=g.config,s=e.split("/");if(JSON.stringify(s)===JSON.stringify([""])||JSON.stringify(s)===JSON.stringify(["",""]))return r;let o=[...n];o=o.filter(t=>t!==r);for(let t of o)if(s[0]===t)return t;return r},x=e=>{let r=Array.isArray(e),n=r?"[":"{";for(let s in e){if(e[s]===null||e[s]===void 0)continue;let o=null;switch(typeof e[s]){case"string":{o=`"${e[s]}"`;break}case"number":case"boolean":{o=e[s];break}case"object":{o=x(e[s]);break}case"function":{o=e[s].toString().replace(/\s+/g," ");break}case"symbol":{o=`Symbol("${e[s].description}")`;break}default:break}n+=r?`${o},`:`"${s}": ${o},`}return`${n}${r?"]":"}"}`};function j(e=""){return!e||!e.includes("\\")?e:e.replace(/\\/g,"/")}var z=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;function _(){return typeof process<"u"?process.cwd().replace(/\\/g,"/"):"/"}var I=function(...e){e=e.map(s=>j(s));let r="",n=!1;for(let s=e.length-1;s>=-1&&!n;s--){let o=s>=0?e[s]:_();!o||o.length===0||(r=`${o}/${r}`,n=h(o))}return r=v(r,!n),n&&!h(r)?`/${r}`:r.length>0?r:"."};function v(e,r){let n="",s=0,o=-1,t=0,l=null;for(let i=0;i<=e.length;++i){if(i<e.length)l=e[i];else{if(l==="/")break;l="/"}if(l==="/"){if(!(o===i-1||t===1))if(t===2){if(n.length<2||s!==2||n[n.length-1]!=="."||n[n.length-2]!=="."){if(n.length>2){let a=n.lastIndexOf("/");a===-1?(n="",s=0):(n=n.slice(0,a),s=n.length-1-n.lastIndexOf("/")),o=i,t=0;continue}else if(n.length>0){n="",s=0,o=i,t=0;continue}}r&&(n+=n.length>0?"/..":"..",s=2)}else n.length>0?n+=`/${e.slice(o+1,i)}`:n=e.slice(o+1,i),s=i-o-1;o=i,t=0}else l==="."&&t!==-1?++t:t=-1}return n}var h=function(e){return z.test(e)};var ce=e=>{let r=e==null?void 0:e.configPath;return{name:"astro-i18next",hooks:{"astro:config:setup":async({config:n,injectScript:s})=>{var l;let o=await L(n.root,r);if(r&&!(o!=null&&o.value))throw new Error(`[astro-i18next]: Could not find a config file at ${JSON.stringify(r)}. Does the file exist?`);let t=$(o==null?void 0:o.value);if(!t.defaultLocale||t.defaultLocale==="")throw new Error("[astro-i18next]: you must set a `defaultLocale` in your astro-i18next config!");if(t.locales||(t.locales=[t.defaultLocale]),t.locales.includes(t.defaultLocale)||t.locales.unshift(t.defaultLocale),t.locales[0]!==t.defaultLocale&&C(t.locales,t.defaultLocale),t.trailingSlash=n.trailingSlash,t.load.includes("server")){let i={supportedLngs:t.locales,fallbackLng:t.locales,ns:t.namespaces,defaultNS:t.defaultNamespace,initImmediate:!1,backend:{loadPath:I(`${n.publicDir.pathname}/${t.resourcesBasePath}/{{lng}}/{{ns}}.json`)},...t.i18nextServer},c={...{fsBackend:"i18next-fs-backend"},...t.i18nextServerPlugins},{imports:u,i18nextInit:f}=R(i,c);u+='import {initAstroI18next} from "astro-i18next";';let d=`initAstroI18next(${x(t)});`;s("page-ssr",u+f+d)}if((l=t.load)!=null&&l.includes("client")){let i={supportedLngs:t.locales,fallbackLng:t.locales,ns:t.namespaces,defaultNS:t.defaultNamespace,detection:{order:["htmlTag"],caches:[]},backend:{loadPath:`${t.resourcesBasePath}/{{lng}}/{{ns}}.json`},...t.i18nextClient},c={...{httpBackend:"i18next-http-backend",LanguageDetector:"i18next-browser-languagedetector"},...t.i18nextClientPlugins},{imports:u,i18nextInit:f}=R(i,c);s("before-hydration",u+f)}}}}},R=(e,r)=>{let n='import i18next from "i18next";',s="i18next";if(Object.keys(r).length>0)for(let o of Object.keys(r))r[o]!==null&&(n+=`import ${o} from "${r[o]}";`,s+=`.use(${o.replace(/[{}]/g,"")})`);return s+=`.init(${x(e)});`,{imports:n,i18nextInit:s}};function fe(e){A(e)}export{g as AstroI18next,O as createReferenceStringFromHTML,ce as default,E as detectLocaleFromPath,fe as initAstroI18next,N as interpolate,P as localizePath,T as localizeUrl};
|