UNPKG

intl-watcher

Version:

Automated translation key extraction and dictionary management plugin for Next.js

82 lines (81 loc) 1.95 kB
import fs from "node:fs"; import lodash from "lodash"; import { log } from "./logger.js"; function runOnce(fn) { if (process.env.__INTL_WATCHER_INITIALIZED === "true") { return; } process.env.__INTL_WATCHER_INITIALIZED = "true"; fn(); } function readDictionaryFile(filepath) { try { const content = fs.readFileSync(filepath).toString(); return JSON.parse(content); } catch (e) { log.warn(`Error reading dictionary file at \`${filepath}\`: ${e}`); return {}; } } function writeDictionaryFile(filepath, messages) { const newContent = `${JSON.stringify(messages, void 0, " ")} `; let currentContent = null; try { currentContent = fs.readFileSync(filepath, "utf8"); } catch (_error) { } if (currentContent !== newContent) { fs.writeFileSync(filepath, newContent, { flag: "w" }); } } function formatDuration(ms) { if (ms < 1e3) { return `${ms.toFixed(0).toLocaleString()}ms`; } return `${(ms / 1e3).toPrecision(2).toLocaleString()}s`; } function flattenDictionary(dictionary, prefix = "") { return lodash.reduce( dictionary, (acc, value, key) => { const prefixedKey = prefix ? `${prefix}.${key}` : key; if (lodash.isPlainObject(value)) { lodash.assign(acc, flattenDictionary(value, prefixedKey)); } else { acc[prefixedKey] = value; } return acc; }, {} ); } function unflattenDictionary(dictionary) { return lodash.reduce( dictionary, (acc, value, key) => { lodash.set(acc, key, value); return acc; }, {} ); } function getCommonPrefix(words) { if (!words[0] || words.length === 1) { return words[0] ?? ""; } let i = 0; while (words[0][i] && words.every((w) => w[i] === words[0][i])) { i++; } return words[0].slice(0, i); } export { flattenDictionary, formatDuration, getCommonPrefix, readDictionaryFile, runOnce, unflattenDictionary, writeDictionaryFile };