UNPKG

crowdfree

Version:

A crowdin compatible tool for translation and localisation of websites and applications

75 lines (71 loc) 3.19 kB
const translatte = require('translatte'); const cache = require("./cache") async function getTranslation(string, code, sourceCode) { let result = await translatte(string, { to: code, from: sourceCode, agents: require("./useragents") }) return result.text } async function translate(translations, locales) { for (let i = 0; i < translations.length; i++) { let translation = translations[i] let languageCodes = locales.map(e => e.locale) // Find missing values for (let code of languageCodes) { if (!translation.value[code]?.value) { // Find source language let sourceLanguageCodes = Object.keys(translation.value).filter(x => translation.value[x].value.length) for (let sourceLanguageCode of sourceLanguageCodes) { if (sourceLanguageCode) { try { // Translate let translatedText = await cache(getTranslation, translation.value[sourceLanguageCode].value, code, sourceLanguageCode) if (translatedText) { // Add suggestion to object if (!translation.value[code]) translation.value[code] = { value: false } if (!translation.value[code].suggestions) translation.value[code].suggestions = [] // Remove previous suggestions for the same language pair translation.value[code].suggestions = translation.value[code].suggestions.filter(x => !(x.type === "google_translate" && x.lang === code && x.source === sourceLanguageCode)) translation.value[code].suggestions.push({ type: "google_translate", lang: code, source: sourceLanguageCode, value: translatedText, }) } } catch (e) { // console.error(e) // Could not get token from google } } else { // Didn't find source language, skip } } } } } return translations } // Code for testing // (async () => { // let result = await translate([{ // file: "locale.json", // key: "headertext", // value: { // en: { // value: "English header text", // }, // no: { // value: "Norwegian header text", // }, // es: { // value: false, // This one isn't translated yet, but is expected due to finding the locale folder // } // } // }], [{ locale: "en" }, { locale: "no" }, { locale: "es" },]) // console.log(JSON.stringify(result, null, 2)) // })() module.exports = { translate, }