UNPKG

wuchale

Version:

Protobuf-like i18n from plain code

42 lines (41 loc) 1.34 kB
import toRuntime, {} from '../runtime.js'; import { AsyncLocalStorage } from 'node:async_hooks'; // by locale const runtimes = {}; const runtimeCtx = new AsyncLocalStorage(); const emptyRuntime = toRuntime(); let warningShown = {}; export function currentRuntime(key, loadID) { const runtime = runtimeCtx.getStore()?.[key]?.[loadID]; if (runtime != null) { return runtime; } const warnKey = `${key}.${loadID}`; if (warningShown[warnKey]) { return emptyRuntime; } console.warn(`Catalog for '${warnKey}' not found.\n Either 'runWithLocale' was not called or the environment has a problem.`); warningShown[warnKey] = true; return emptyRuntime; } export async function loadLocales(key, loadIDs, load, locales) { if (loadIDs == null) { loadIDs = [key]; } for (const locale of locales) { if (!(locale in runtimes)) { runtimes[locale] = {}; } const loaded = runtimes[locale]; if (!(key in loaded)) { loaded[key] = {}; } for (const id of loadIDs) { loaded[key][id] = toRuntime(await load(id, locale), locale); } } return (loadID) => currentRuntime(key, loadID); } export async function runWithLocale(locale, func) { return await runtimeCtx.run(runtimes[locale], func); }