UNPKG

next-intl-scanner

Version:

A tool to extract and manage translations from Next.js projects using next-intl

54 lines (53 loc) 2.29 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.translateBatch = void 0; const translate_1 = require("@google-cloud/translate"); const logger_1 = __importDefault(require("./logger.js")); const translate = new translate_1.v2.Translate({ key: process.env.GOOGLE_TRANSLATE_API_KEY, }); // Maximum number of strings to translate in a single request const BATCH_SIZE = 100; async function batchTranslateStrings(content, sourceLocale, targetLocale) { try { if (!process.env.GOOGLE_TRANSLATE_API_KEY) { logger_1.default.error("GOOGLE_TRANSLATE_API_KEY is not set"); process.exit(1); } // Skip if source and target locales are the same if (sourceLocale === targetLocale) { return content; } logger_1.default.info(`Translating ${Object.keys(content).length} strings from ${sourceLocale} to ${targetLocale}`); const keys = Object.keys(content); const values = Object.values(content); const translatedContent = {}; // Process translations in chunks for (let i = 0; i < values.length; i += BATCH_SIZE) { const chunk = values.slice(i, i + BATCH_SIZE); logger_1.default.info(`Processing batch ${Math.floor(i / BATCH_SIZE) + 1} of ${Math.ceil(values.length / BATCH_SIZE)}`); const [translations] = await translate.translate(chunk, { from: sourceLocale, to: targetLocale, }); // Map translations back to their keys for (let j = 0; j < chunk.length; j++) { translatedContent[keys[i + j]] = translations[j]; } } return translatedContent; } catch (error) { logger_1.default.error(`Translation failed: ${error}`); return content; } } async function translateBatch(content, sourceLocale, targetLocale) { const translated = await batchTranslateStrings(content, sourceLocale, targetLocale); //now for each key in the content, we need to translate the value return translated; } exports.translateBatch = translateBatch;