i18n-ai-translate
Version:
Use LLMs to translate your i18n JSON to any language.
197 lines • 7.45 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.delay = delay;
exports.printError = printError;
exports.printWarn = printWarn;
exports.printInfo = printInfo;
exports.retryJob = retryJob;
exports.getLanguageCodeFromFilename = getLanguageCodeFromFilename;
exports.getAllLanguageCodes = getAllLanguageCodes;
exports.isValidLanguageCode = isValidLanguageCode;
exports.getAllFilesInPath = getAllFilesInPath;
exports.getTranslationDirectoryKey = getTranslationDirectoryKey;
exports.isNAK = isNAK;
exports.isACK = isACK;
exports.getMissingVariables = getMissingVariables;
exports.getTemplatedStringRegex = getTemplatedStringRegex;
exports.printExecutionTime = printExecutionTime;
exports.printProgress = printProgress;
exports.getOutputPathFromInputPath = getOutputPathFromInputPath;
const iso_639_1_1 = __importDefault(require("iso-639-1"));
const ansi_colors_1 = __importDefault(require("ansi-colors"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
* @param delayDuration - time (in ms) to delay
* @returns a promise that resolves after delayDuration
*/
function delay(delayDuration) {
// eslint-disable-next-line no-promise-executor-return
return new Promise((resolve) => setTimeout(resolve, delayDuration));
}
/**
* @param error - the error message
*/
function printError(error) {
console.error(ansi_colors_1.default.redBright(error));
}
/**
* @param warn - the warning message
*/
function printWarn(warn) {
console.warn(ansi_colors_1.default.yellowBright(warn));
}
/**
* @param info - the message
*/
function printInfo(info) {
console.log(ansi_colors_1.default.cyanBright(info));
}
/**
* @param job - the function to retry
* @param jobArgs - arguments to pass to job
* @param maxRetries - retries of job before throwing
* @param firstTry - whether this is the first try
* @param delayDuration - time (in ms) before attempting job retry
* @param sendError - whether to send a warning or error
* @returns the result of job
*/
async function retryJob(job, jobArgs, maxRetries, firstTry, delayDuration, sendError = true) {
if (!firstTry && delayDuration) {
await delay(delayDuration);
}
return job(...jobArgs).catch((err) => {
if (sendError) {
printError(`err = ${err}`);
}
else {
printWarn(`err = ${err}`);
}
if (maxRetries <= 0) {
throw err;
}
return retryJob(job, jobArgs, maxRetries - 1, false, delayDuration);
});
}
/**
* @param filename - the filename to get the language from
* @returns the language code from the filename
*/
function getLanguageCodeFromFilename(filename) {
const splitFilename = filename.split("/");
const lastPart = splitFilename[splitFilename.length - 1];
const splitLastPart = lastPart.split(".");
return splitLastPart[0];
}
/**
* @returns all language codes
*/
function getAllLanguageCodes() {
return iso_639_1_1.default.getAllCodes();
}
/**
* @param languageCode - the language code to validate
* @returns whether the language code is valid
*/
function isValidLanguageCode(languageCode) {
return iso_639_1_1.default.validate(languageCode);
}
/**
* @param directory - the directory to list all files for
* @returns all files with their absolute path that exist within the directory, recursively
*/
function getAllFilesInPath(directory) {
const files = [];
for (const fileOrDir of fs_1.default.readdirSync(directory)) {
const fullPath = path_1.default.join(directory, fileOrDir);
if (fs_1.default.lstatSync(fullPath).isDirectory()) {
files.push(...getAllFilesInPath(fullPath));
}
else {
files.push(fullPath);
}
}
return files;
}
/**
* @param sourceFilePath - the source file's path
* @param key - the key associated with the translation
* @param inputLanguageCode - the language code of the source language
* @param outputLanguageCode - the language code of the output language
* @returns a key to use when translating a key from a directory;
* swaps the input language code with the output language code
*/
function getTranslationDirectoryKey(sourceFilePath, key, inputLanguageCode, outputLanguageCode) {
const outputPath = sourceFilePath.replace(`/${inputLanguageCode}/`, `/${outputLanguageCode ?? inputLanguageCode}/`);
return `${outputPath}:${key}`;
}
/**
* @param response - the message from the LLM
* @returns whether the response includes NAK
*/
function isNAK(response) {
return response.includes("NAK") && !response.includes("ACK");
}
/**
* @param response - the message from the LLM
* @returns whether the response only contains ACK and not NAK
*/
function isACK(response) {
return response.includes("ACK") && !response.includes("NAK");
}
/**
* @param originalTemplateStrings - the template strings in the original text
* @param translatedTemplateStrings - the template strings in the translated text
* @returns the missing template string from the original
*/
function getMissingVariables(originalTemplateStrings, translatedTemplateStrings) {
if (originalTemplateStrings.length === 0)
return [];
const translatedTemplateStringsSet = new Set(translatedTemplateStrings);
const missingTemplateStrings = originalTemplateStrings.filter((originalTemplateString) => !translatedTemplateStringsSet.has(originalTemplateString));
return missingTemplateStrings;
}
/**
* @param templatedStringPrefix - templated String Prefix
* @param templatedStringSuffix - templated String Suffix
* @returns the regex needed to get the templated Strings
*/
function getTemplatedStringRegex(templatedStringPrefix, templatedStringSuffix) {
return new RegExp(`${templatedStringPrefix}[^{}]+${templatedStringSuffix}`, "g");
}
/**
* @param startTime - the startTime
* @param prefix - the prefix of the Execution Time
*/
function printExecutionTime(startTime, prefix) {
const endTime = Date.now();
const roundedSeconds = Math.round((endTime - startTime) / 1000);
printInfo(`${prefix}${roundedSeconds} seconds\n`);
}
/**
* @param title - the title
* @param startTime - the startTime
* @param totalItems - the totalItems
* @param processedItems - the processedItems
*/
function printProgress(title, startTime, totalItems, processedItems) {
const roundedEstimatedTimeLeftSeconds = Math.round((((Date.now() - startTime) / (processedItems + 1)) *
(totalItems - processedItems)) /
1000);
const percentage = ((processedItems / totalItems) * 100).toFixed(0);
process.stdout.write(`\r${ansi_colors_1.default.blueBright(title)} | ${ansi_colors_1.default.greenBright(`Completed ${percentage}%`)} | ${ansi_colors_1.default.yellowBright(`ETA: ${roundedEstimatedTimeLeftSeconds}s`)}`);
}
/**
* @param inputPath - the input path
* @param outputLanguageCode - the output language code
* @returns the output path based on the input path and output language code
*/
function getOutputPathFromInputPath(inputPath, outputLanguageCode) {
const dir = path_1.default.dirname(inputPath);
const filename = `${outputLanguageCode}${path_1.default.extname(inputPath)}`;
return path_1.default.join(dir, filename);
}
//# sourceMappingURL=utils.js.map