Files

66 lines
2.3 KiB
TypeScript

import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Resource, ResourceLanguage } from "i18next";
import { catalogReadyLocales, i18nNamespaces } from "@hivegrid/i18n";
type ResolveServerLocalePathOptions = {
moduleUrl?: string;
cwd?: string;
exists?: (candidate: string) => boolean;
};
export function resolveServerLocalePath({
moduleUrl = import.meta.url,
cwd = process.cwd(),
exists = existsSync,
}: ResolveServerLocalePathOptions = {}) {
const parsedModuleUrl = new URL(moduleUrl);
const usesPosixFixturePath = process.platform === "win32" && parsedModuleUrl.protocol === "file:" && !/^\/[a-zA-Z]:\//.test(parsedModuleUrl.pathname);
const pathApi = usesPosixFixturePath ? path.posix : path;
const modulePath = usesPosixFixturePath ? decodeURIComponent(parsedModuleUrl.pathname) : fileURLToPath(parsedModuleUrl);
const moduleDir = pathApi.dirname(modulePath);
const candidates = [
pathApi.resolve(moduleDir, "../../public/locales"),
pathApi.resolve(cwd, "apps/web/public/locales"),
pathApi.resolve(cwd, "public/locales"),
];
return candidates.find((candidate) => exists(candidate)) ?? candidates[0];
}
export const serverLocalePath = resolveServerLocalePath();
const serverLanguages = [...catalogReadyLocales, ...catalogReadyLocales.map((locale) => `${locale}-formal`)];
let resourcesSnapshot: Resource | null = null;
let resourceLoadCount = 0;
export function getServerI18nResourcesSnapshot(): Resource {
if (resourcesSnapshot !== null) return resourcesSnapshot;
const resources: Resource = {};
for (const locale of serverLanguages) {
const bundle: ResourceLanguage = {};
for (const namespace of i18nNamespaces) {
try {
const file = path.join(serverLocalePath, locale, `${namespace}.json`);
bundle[namespace] = JSON.parse(readFileSync(file, "utf8")) as ResourceLanguage[string];
} catch {
bundle[namespace] = {};
}
}
resources[locale] = bundle;
}
resourcesSnapshot = resources;
resourceLoadCount += 1;
return resourcesSnapshot;
}
/** Test-only diagnostic proving locale files are parsed once per process. */
export function __getServerI18nResourceLoadCountForTests(): number {
return resourceLoadCount;
}