UNPKG

@vyxos/astro-i18next

Version:

I18next integration for Astro with dynamic namespace loading.

52 lines (47 loc) 1.56 kB
import i18next from 'i18next'; import { createRequire } from 'module'; // src/middleware.ts // src/constants.ts var INTEGRATION_NAME = "@vyxos/astro-i18next"; // src/utils/helpers.ts function getConfig() { if (!i18next.options.integrationOptions) { throw new Error(`[${INTEGRATION_NAME}] Configuration object empty.`); } return JSON.parse( JSON.stringify(i18next.options.integrationOptions) ); } var isBrowser = typeof window !== "undefined"; isBrowser ? null : createRequire(import.meta.url); // src/middleware.ts var ASTRO_RESERVED_ROUTES = ["/_astro", "/_actions", "/_server-islands"]; async function onRequest(context, next) { const { supportedLngs: lngs, lng } = getConfig(); if ([...ASTRO_RESERVED_ROUTES].some( (route) => context.url.pathname === route || context.url.pathname.startsWith(route + "/") )) { return next(); } const localeFromPathname = context.url.pathname.split("/")[1]; const potentialLocales = [localeFromPathname]; if (lng) { potentialLocales.push(lng); } if (lng === "cimode") { await i18next.changeLanguage("cimode"); return next(); } const nextLocale = potentialLocales.find((locale) => { const containsLocale = Array.isArray(lngs) && lngs.includes(locale); const supportsAnyLanguage = lngs === false; return locale && (containsLocale || supportsAnyLanguage); }); if (nextLocale) { await i18next.changeLanguage(nextLocale); } return next(); } export { onRequest }; //# sourceMappingURL=middleware.js.map //# sourceMappingURL=middleware.js.map