next-intl-scanner
Version:
A tool to extract and manage translations from Next.js projects using next-intl
75 lines (74 loc) • 3.21 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.restoreNamespaces = exports.flattenObject = exports.checkForDots = void 0;
const logger_1 = __importDefault(require("./logger.js"));
const checkForDots = (string) => {
if (string.includes(".")) {
logger_1.default.error(`Found a dot in the string "${string}", this will break next-intl translations as keys will be interpreted as namespaces`);
logger_1.default.error("Please rename the key to remove the dot or refer to the readme file for using custom elements that support dot notation");
process.exit(1);
}
};
exports.checkForDots = checkForDots;
const flattenObject = async (obj) => {
const flattened = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if (value && typeof value === "object" && !Array.isArray(value)) {
// This is a nested object (namespace), don't check the key for dots
const nested = await (0, exports.flattenObject)(value);
for (const nestedKey in nested) {
// Allow dots in message keys, but replace them with underscores in values
// checkForDots(nestedKey); // Removed this check to allow dots in keys
// lets temporarily replace the dot with a special charatcer combo to avoid conflicts
flattened[`${key}.${nestedKey}`] = nested[nestedKey].replace(".", "::");
}
}
else {
// This is a direct key-value pair, allow dots in keys
// checkForDots(key); // Removed this check to allow dots in keys
if (typeof value === "string" && value.includes(".")) {
const escapedKey = key.replace(".", "::");
flattened[escapedKey] = value.replace(".", "::");
}
else {
flattened[key] = value;
}
}
}
}
return flattened;
};
exports.flattenObject = flattenObject;
const restoreNamespaces = async (obj) => {
if (!obj || typeof obj !== "object") {
console.error("Invalid input object:", obj);
return {};
}
const restored = {};
for (const key in obj) {
if (key.includes(".")) {
const [namespace, translationKey] = key.split(".");
if (!restored[namespace]) {
restored[namespace] = {};
}
//lets replace back the special character combo
restored[namespace][translationKey] = obj[key].replace("::", ".");
}
else {
if (typeof obj[key] === "string" && obj[key].includes("::")) {
const escapedKey = key.replace("::", ".");
restored[escapedKey] = obj[key].replace("::", ".");
}
else {
restored[key] = obj[key];
}
}
}
return restored;
};
exports.restoreNamespaces = restoreNamespaces;