UNPKG

@intlayer/core

Version:

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

78 lines (76 loc) 2.81 kB
import { deepTransformNode } from "../interpreter/getContent/deepTransform.mjs"; import { NodeType } from "@intlayer/types"; import configuration from "@intlayer/config/built"; //#region src/deepTransformPlugins/getMissingLocalesContent.ts const getDeepKeyPaths = (obj, prefix = []) => { if (typeof obj !== "object" || obj === null) return []; if (Array.isArray(obj)) return []; return Object.keys(obj).flatMap((key) => { const newPath = [...prefix, key]; return [newPath, ...getDeepKeyPaths(obj[key], newPath)]; }); }; const hasDeepKeyPath = (obj, keyPath) => { let current = obj; for (const key of keyPath) { if (current === void 0 || current === null || typeof current !== "object") return false; if (!(key in current)) return false; current = current[key]; } return true; }; /** Translation plugin. Replaces node with a locale string if nodeType = Translation. */ const checkMissingLocalesPlugin = (locales, onMissingLocale) => ({ id: "check-missing-locales-plugin", canHandle: (node) => typeof node === "object" && node?.nodeType === NodeType.Translation, transform: (node, props, deepTransformNode$1) => { const translations = node[NodeType.Translation]; const allKeys = /* @__PURE__ */ new Set(); for (const locale of locales) if (translations[locale]) getDeepKeyPaths(translations[locale]).forEach((path) => { allKeys.add(JSON.stringify(path)); }); for (const locale of locales) { if (!translations[locale]) { onMissingLocale(locale); continue; } for (const pathStr of allKeys) { const path = JSON.parse(pathStr); if (!hasDeepKeyPath(translations[locale], path)) { onMissingLocale(locale); break; } } } for (const key in translations) { const child = translations[key]; deepTransformNode$1(child, { ...props, children: child }); } return node; } }); /** * Return the content of a node with only the translation plugin. * * @param node The node to transform. * @param locales The locales to check for missing translations. */ const getMissingLocalesContent = (node, locales = configuration?.internationalization?.locales, nodeProps) => { const missingLocales = /* @__PURE__ */ new Set(); const plugins = [checkMissingLocalesPlugin(locales, (locale) => missingLocales.add(locale)), ...nodeProps.plugins ?? []]; deepTransformNode(node, { ...nodeProps, plugins }); return Array.from(missingLocales); }; const getMissingLocalesContentFromDictionary = (dictionary, locales = configuration?.internationalization?.locales) => getMissingLocalesContent(dictionary.content, locales, { dictionaryKey: dictionary.key, keyPath: [] }); //#endregion export { checkMissingLocalesPlugin, getMissingLocalesContent, getMissingLocalesContentFromDictionary }; //# sourceMappingURL=getMissingLocalesContent.mjs.map