UNPKG

@intlayer/core

Version:

Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.

41 lines (39 loc) 1.77 kB
import { getDictionary } from "./getDictionary.mjs"; import { log } from "@intlayer/config/built"; import { colorizeKey, getAppLogger } from "@intlayer/config/logger"; import { getDictionaries } from "@intlayer/dictionaries-entry"; //#region src/interpreter/getIntlayer.ts /** * Creates a Recursive Proxy that returns the path of the accessed key * stringified. This prevents the app from crashing on undefined access. */ const createSafeFallback = (path = "") => { return new Proxy({}, { get: (_target, prop) => { if (prop === "toJSON" || prop === Symbol.toPrimitive || prop === "toString" || prop === "valueOf") return () => path; if (prop === "then") return; if (prop === Symbol.iterator) return function* () { yield path; }; return createSafeFallback(path ? `${path}.${String(prop)}` : String(prop)); } }); }; const dictionaryCache = /* @__PURE__ */ new Map(); const warnedMissingDictionaries = /* @__PURE__ */ new Set(); const getIntlayer = (key, locale, plugins) => { const dictionary = getDictionaries()[key]; if (!dictionary && true) { if (!warnedMissingDictionaries.has(key)) { getAppLogger({ log })(typeof window === "undefined" ? `Dictionary ${colorizeKey(key)} was not found. Using fallback proxy.` : `Dictionary ${key} was not found. Using fallback proxy.`, { level: "warn" }); warnedMissingDictionaries.add(key); } return createSafeFallback(key); } const cacheKey = `${key}_${locale ?? "default"}_${plugins ? "custom_plugins" : "default_plugins"}`; if (dictionaryCache.has(cacheKey)) return dictionaryCache.get(cacheKey); const result = getDictionary(dictionary, locale, plugins); dictionaryCache.set(cacheKey, result); return result; }; //#endregion export { getIntlayer }; //# sourceMappingURL=getIntlayer.mjs.map