import { AsyncLocalStorage } from "node:async_hooks"; import i18next, { type Resource, type TFunction } from "i18next"; import { catalogReadyLocales, defaultLocale, i18nConfig } from "./i18n"; import { __getServerI18nResourceLoadCountForTests, getServerI18nResourcesSnapshot } from "./i18next-resources.server"; import { REQUEST_TRANSLATOR_RESOLVER, type RequestTranslatorResolver } from "./request-scoped-t"; // The process-level resource store must resolve fixed translators for the // formal variants ("de-formal", "en-formal") as well as the base locales. // Their bundles are loaded best-effort (missing files are non-fatal) and fall // back to the base locale for un-overridden keys. const globalLngs = [...catalogReadyLocales, ...catalogReadyLocales.map((locale) => `${locale}-formal`)]; /** * Server-side bootstrap for the process-level i18next resource store. Every * locale is loaded once, but the singleton language is never changed per * request: overlapping loaders and streaming renders would otherwise be able to * observe another request's locale. Request-aware call sites resolve a fixed * translator through the AsyncLocalStorage bridge below. */ function registerAllBundles(resources: Resource): void { // Register every locale/namespace bundle. `init({ resources })` only // guarantees the active language's bundle is added; registering them all // up-front lets `getFixedT` resolve any supported locale synchronously. // This also backfills bundles when another module (e.g. test setup) already // initialised the global instance with a narrower resource set. for (const locale of Object.keys(resources)) { for (const namespace of Object.keys(resources[locale]!)) { if (!i18next.hasResourceBundle(locale, namespace)) { i18next.addResourceBundle(locale, namespace, resources[locale]![namespace], true, true); } } } } let initPromise: Promise | null = null; const fixedTranslators = new Map(); type RequestI18nStore = { language: string; translator: TFunction; }; const REQUEST_I18N_STORAGE = Symbol.for("hivegrid.i18n.request-storage"); type GlobalWithRequestI18n = typeof globalThis & { [REQUEST_I18N_STORAGE]?: AsyncLocalStorage; [REQUEST_TRANSLATOR_RESOLVER]?: RequestTranslatorResolver; }; const requestI18nGlobal = globalThis as GlobalWithRequestI18n; const requestI18nStorage = requestI18nGlobal[REQUEST_I18N_STORAGE] ?? (requestI18nGlobal[REQUEST_I18N_STORAGE] = new AsyncLocalStorage()); // Reinstall on module evaluation so development reloads cannot leave a resolver // pointing at an obsolete module-local storage instance. requestI18nGlobal[REQUEST_TRANSLATOR_RESOLVER] = () => requestI18nStorage.getStore()?.translator; export async function ensureServerGlobalI18n(): Promise { if (!initPromise) { const resources = getServerI18nResourcesSnapshot(); if (i18next.isInitialized) { registerAllBundles(resources); initPromise = Promise.resolve(i18next); } else { initPromise = i18next .init({ ...i18nConfig, // Accept the formal variants so fixed translators retain the // requested variant instead of dropping back to detection fallback. supportedLngs: globalLngs, lng: defaultLocale, preload: [...globalLngs], resources, // Resources are bundled in memory, so no backend/async loading is needed. initImmediate: false, }) .then(() => { registerAllBundles(resources); return i18next; }); } } return initPromise; } export async function runWithServerI18nLanguage(language: string, callback: () => T | Promise): Promise { const instance = await ensureServerGlobalI18n(); const activeStore = requestI18nStorage.getStore(); if (activeStore?.language === language) { return callback(); } return requestI18nStorage.run( { language, translator: getFixedTranslator(instance, language), }, callback ); } function getFixedTranslator(instance: typeof i18next, language: string): TFunction { const cached = fixedTranslators.get(language); if (cached) { return cached; } const translator = instance.getFixedT(language); fixedTranslators.set(language, translator); return translator; } export function getServerRequestI18nLanguage(): string | undefined { return requestI18nStorage.getStore()?.language; } /** Test-only diagnostic proving locale files are loaded at most once per process. */ export function __getServerGlobalI18nResourceLoadCountForTests(): number { return __getServerI18nResourceLoadCountForTests(); } export { getServerI18nResourcesSnapshot } from "./i18next-resources.server";