@umituz/react-native-google-translate 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Language Entity
3
+ * @description Language code mappings and metadata
4
+ */
5
+ export {};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Translation Entity
3
+ * @description Represents a translation request and response
4
+ */
5
+ export {};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Domain Entities
3
+ * @description Exports all entity types
4
+ */
5
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Domain Layer
3
+ * @description Subpath: @umituz/react-native-google-translate/core
4
+ *
5
+ * Exports all domain entities and interfaces
6
+ */
7
+ export * from "./entities";
8
+ export * from "./interfaces";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Translation Service Interface
3
+ * @description Defines the contract for translation services
4
+ */
5
+ export {};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Domain Interfaces
3
+ * @description Exports all interface definitions
4
+ */
5
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * API Constants
3
+ * @description Google Translate API configuration
4
+ */
5
+ export const GOOGLE_TRANSLATE_API_URL = "https://translate.googleapis.com/translate_a/single";
6
+ export const DEFAULT_TIMEOUT = 10000;
7
+ export const DEFAULT_MIN_DELAY = 100;
8
+ export const DEFAULT_MAX_RETRIES = 3;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Infrastructure Constants
3
+ * @description Exports all constant definitions
4
+ */
5
+ export { LANGUAGE_MAP, SKIP_WORDS, LANGUAGE_NAMES, } from "./languages.constants";
6
+ export { GOOGLE_TRANSLATE_API_URL, DEFAULT_TIMEOUT, DEFAULT_MIN_DELAY, DEFAULT_MAX_RETRIES, } from "./api.constants";
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Language Constants
3
+ * @description Language mappings and metadata
4
+ */
5
+ export const LANGUAGE_MAP = {
6
+ "ar-SA": "ar",
7
+ "bg-BG": "bg",
8
+ "cs-CZ": "cs",
9
+ "da-DK": "da",
10
+ "de-DE": "de",
11
+ "el-GR": "el",
12
+ "en-AU": "en",
13
+ "en-CA": "en",
14
+ "en-GB": "en",
15
+ "es-ES": "es",
16
+ "es-MX": "es",
17
+ "fi-FI": "fi",
18
+ "fr-CA": "fr",
19
+ "fr-FR": "fr",
20
+ "hi-IN": "hi",
21
+ "hr-HR": "hr",
22
+ "hu-HU": "hu",
23
+ "id-ID": "id",
24
+ "it-IT": "it",
25
+ "ja-JP": "ja",
26
+ "ko-KR": "ko",
27
+ "ms-MY": "ms",
28
+ "nl-NL": "nl",
29
+ "no-NO": "no",
30
+ "pl-PL": "pl",
31
+ "pt-BR": "pt",
32
+ "pt-PT": "pt",
33
+ "ro-RO": "ro",
34
+ "ru-RU": "ru",
35
+ "sk-SK": "sk",
36
+ "sl-SI": "sl",
37
+ "sv-SE": "sv",
38
+ "th-TH": "th",
39
+ "tl-PH": "tl",
40
+ "tr-TR": "tr",
41
+ "uk-UA": "uk",
42
+ "vi-VN": "vi",
43
+ "zh-CN": "zh-CN",
44
+ "zh-TW": "zh-TW",
45
+ };
46
+ export const SKIP_WORDS = new Set([
47
+ "Google",
48
+ "Apple",
49
+ "Facebook",
50
+ "Instagram",
51
+ "Twitter",
52
+ "YouTube",
53
+ "WhatsApp",
54
+ ]);
55
+ export const LANGUAGE_NAMES = {
56
+ "ar-SA": "Arabic (Saudi Arabia)",
57
+ "bg-BG": "Bulgarian",
58
+ "cs-CZ": "Czech",
59
+ "da-DK": "Danish",
60
+ "de-DE": "German",
61
+ "el-GR": "Greek",
62
+ "en-AU": "English (Australia)",
63
+ "en-CA": "English (Canada)",
64
+ "en-GB": "English (UK)",
65
+ "en-US": "English (US)",
66
+ "es-ES": "Spanish (Spain)",
67
+ "es-MX": "Spanish (Mexico)",
68
+ "fi-FI": "Finnish",
69
+ "fr-CA": "French (Canada)",
70
+ "fr-FR": "French (France)",
71
+ "hi-IN": "Hindi",
72
+ "hr-HR": "Croatian",
73
+ "hu-HU": "Hungarian",
74
+ "id-ID": "Indonesian",
75
+ "it-IT": "Italian",
76
+ "ja-JP": "Japanese",
77
+ "ko-KR": "Korean",
78
+ "ms-MY": "Malay",
79
+ "nl-NL": "Dutch",
80
+ "no-NO": "Norwegian",
81
+ "pl-PL": "Polish",
82
+ "pt-BR": "Portuguese (Brazil)",
83
+ "pt-PT": "Portuguese (Portugal)",
84
+ "ro-RO": "Romanian",
85
+ "ru-RU": "Russian",
86
+ "sk-SK": "Slovak",
87
+ "sl-SI": "Slovenian",
88
+ "sv-SE": "Swedish",
89
+ "th-TH": "Thai",
90
+ "tl-PH": "Tagalog",
91
+ "tr-TR": "Turkish",
92
+ "uk-UA": "Ukrainian",
93
+ "vi-VN": "Vietnamese",
94
+ "zh-CN": "Chinese (Simplified)",
95
+ "zh-TW": "Chinese (Traditional)",
96
+ };
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Google Translate Service
3
+ * @description Main translation service using Google Translate API
4
+ */
5
+ import { RateLimiter } from "../utils/rateLimit.util";
6
+ import { shouldSkipWord, needsTranslation, isValidText, } from "../utils/textValidator.util";
7
+ import { GOOGLE_TRANSLATE_API_URL, DEFAULT_MIN_DELAY, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, } from "../constants";
8
+ class GoogleTranslateService {
9
+ config = null;
10
+ rateLimiter = null;
11
+ initialize(config) {
12
+ this.config = {
13
+ minDelay: DEFAULT_MIN_DELAY,
14
+ maxRetries: DEFAULT_MAX_RETRIES,
15
+ timeout: DEFAULT_TIMEOUT,
16
+ ...config,
17
+ };
18
+ this.rateLimiter = new RateLimiter(this.config.minDelay);
19
+ }
20
+ isInitialized() {
21
+ return this.config !== null && this.rateLimiter !== null;
22
+ }
23
+ ensureInitialized() {
24
+ if (!this.isInitialized()) {
25
+ throw new Error("GoogleTranslateService is not initialized. Call initialize() first.");
26
+ }
27
+ }
28
+ async translate(request) {
29
+ this.ensureInitialized();
30
+ const { text, targetLanguage, sourceLanguage = "en" } = request;
31
+ if (!isValidText(text) || shouldSkipWord(text)) {
32
+ return {
33
+ originalText: text,
34
+ translatedText: text,
35
+ sourceLanguage,
36
+ targetLanguage,
37
+ success: true,
38
+ };
39
+ }
40
+ if (!targetLanguage || targetLanguage.trim().length === 0) {
41
+ return {
42
+ originalText: text,
43
+ translatedText: text,
44
+ sourceLanguage,
45
+ targetLanguage,
46
+ success: false,
47
+ error: "Invalid target language",
48
+ };
49
+ }
50
+ // After ensureInitialized(), rateLimiter is guaranteed to be non-null
51
+ await this.rateLimiter.waitForSlot();
52
+ try {
53
+ const translatedText = await this.callTranslateAPI(text, targetLanguage, sourceLanguage);
54
+ return {
55
+ originalText: text,
56
+ translatedText,
57
+ sourceLanguage,
58
+ targetLanguage,
59
+ success: true,
60
+ };
61
+ }
62
+ catch (error) {
63
+ return {
64
+ originalText: text,
65
+ translatedText: text,
66
+ sourceLanguage,
67
+ targetLanguage,
68
+ success: false,
69
+ error: error instanceof Error ? error.message : "Unknown error",
70
+ };
71
+ }
72
+ }
73
+ async translateBatch(requests) {
74
+ this.ensureInitialized();
75
+ if (!Array.isArray(requests) || requests.length === 0) {
76
+ return {
77
+ totalCount: 0,
78
+ successCount: 0,
79
+ failureCount: 0,
80
+ skippedCount: 0,
81
+ translatedKeys: [],
82
+ };
83
+ }
84
+ const stats = {
85
+ totalCount: requests.length,
86
+ successCount: 0,
87
+ failureCount: 0,
88
+ skippedCount: 0,
89
+ translatedKeys: [],
90
+ };
91
+ for (const request of requests) {
92
+ const result = await this.translate(request);
93
+ if (result.success) {
94
+ if (result.translatedText === result.originalText) {
95
+ stats.skippedCount++;
96
+ }
97
+ else {
98
+ stats.successCount++;
99
+ stats.translatedKeys.push({
100
+ key: request.text,
101
+ from: result.originalText,
102
+ to: result.translatedText,
103
+ });
104
+ }
105
+ }
106
+ else {
107
+ stats.failureCount++;
108
+ }
109
+ }
110
+ return stats;
111
+ }
112
+ async translateObject(sourceObject, targetObject, targetLanguage, path = "", stats = {
113
+ totalCount: 0,
114
+ successCount: 0,
115
+ failureCount: 0,
116
+ skippedCount: 0,
117
+ translatedKeys: [],
118
+ }) {
119
+ if (!sourceObject || typeof sourceObject !== "object") {
120
+ return;
121
+ }
122
+ if (!targetObject || typeof targetObject !== "object") {
123
+ return;
124
+ }
125
+ if (!targetLanguage || targetLanguage.trim().length === 0) {
126
+ return;
127
+ }
128
+ const keys = Object.keys(sourceObject);
129
+ for (const key of keys) {
130
+ const enValue = sourceObject[key];
131
+ const targetValue = targetObject[key];
132
+ const currentPath = path ? `${path}.${key}` : key;
133
+ if (typeof enValue === "object" && enValue !== null) {
134
+ if (!targetObject[key] ||
135
+ typeof targetObject[key] !== "object") {
136
+ targetObject[key] = {};
137
+ }
138
+ await this.translateObject(enValue, targetObject[key], targetLanguage, currentPath, stats);
139
+ }
140
+ else if (typeof enValue === "string") {
141
+ stats.totalCount++;
142
+ if (needsTranslation(targetValue, enValue)) {
143
+ const request = {
144
+ text: enValue,
145
+ targetLanguage,
146
+ };
147
+ const result = await this.translate(request);
148
+ if (result.success && result.translatedText !== enValue) {
149
+ targetObject[key] = result.translatedText;
150
+ stats.successCount++;
151
+ stats.translatedKeys.push({
152
+ key: currentPath,
153
+ from: enValue,
154
+ to: result.translatedText,
155
+ });
156
+ }
157
+ else if (!result.success) {
158
+ stats.failureCount++;
159
+ }
160
+ else {
161
+ stats.skippedCount++;
162
+ }
163
+ }
164
+ else {
165
+ stats.skippedCount++;
166
+ }
167
+ }
168
+ }
169
+ }
170
+ async callTranslateAPI(text, targetLanguage, sourceLanguage) {
171
+ const timeout = this.config?.timeout || DEFAULT_TIMEOUT;
172
+ const encodedText = encodeURIComponent(text);
173
+ const url = `${GOOGLE_TRANSLATE_API_URL}?client=gtx&sl=${sourceLanguage}&tl=${targetLanguage}&dt=t&q=${encodedText}`;
174
+ const controller = new AbortController();
175
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
176
+ try {
177
+ const response = await fetch(url, {
178
+ signal: controller.signal,
179
+ });
180
+ if (!response.ok) {
181
+ throw new Error(`API request failed: ${response.status}`);
182
+ }
183
+ const data = await response.json();
184
+ // Type guard for Google Translate API response structure
185
+ if (Array.isArray(data) &&
186
+ data.length > 0 &&
187
+ Array.isArray(data[0]) &&
188
+ data[0].length > 0 &&
189
+ Array.isArray(data[0][0]) &&
190
+ typeof data[0][0][0] === "string") {
191
+ return data[0][0][0];
192
+ }
193
+ return text;
194
+ }
195
+ finally {
196
+ clearTimeout(timeoutId);
197
+ }
198
+ }
199
+ }
200
+ export const googleTranslateService = new GoogleTranslateService();
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Infrastructure Services
3
+ * @description Exports all services and utilities
4
+ */
5
+ export { googleTranslateService } from "./GoogleTranslate.service";
6
+ export { shouldSkipWord, needsTranslation, isValidText, getTargetLanguage, isEnglishVariant, getLanguageDisplayName, } from "../utils/textValidator.util";
7
+ export { LANGUAGE_MAP, SKIP_WORDS, LANGUAGE_NAMES, } from "../constants/languages.constants";
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Rate Limit Utility
3
+ * @description Handles rate limiting for API requests
4
+ */
5
+ export class RateLimiter {
6
+ lastCallTime = 0;
7
+ minDelay;
8
+ constructor(minDelay = 100) {
9
+ this.minDelay = minDelay;
10
+ }
11
+ async waitForSlot() {
12
+ const now = Date.now();
13
+ const elapsed = now - this.lastCallTime;
14
+ const waitTime = Math.max(0, this.minDelay - elapsed);
15
+ if (waitTime > 0) {
16
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
17
+ }
18
+ this.lastCallTime = Date.now();
19
+ }
20
+ reset() {
21
+ this.lastCallTime = 0;
22
+ }
23
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Text Validator Utility
3
+ * @description Validates text for translation eligibility
4
+ */
5
+ import { SKIP_WORDS, LANGUAGE_MAP, LANGUAGE_NAMES } from "../constants";
6
+ export function shouldSkipWord(word) {
7
+ return SKIP_WORDS.has(word);
8
+ }
9
+ export function needsTranslation(value, enValue) {
10
+ if (typeof enValue !== "string" || !enValue.trim()) {
11
+ return false;
12
+ }
13
+ if (shouldSkipWord(enValue)) {
14
+ return false;
15
+ }
16
+ // Skip technical keys (e.g., "scenario.xxx.title")
17
+ const isTechnicalKey = enValue.includes(".") && !enValue.includes(" ");
18
+ if (isTechnicalKey) {
19
+ return false;
20
+ }
21
+ // If value is missing or same as English, it needs translation
22
+ if (!value || typeof value !== "string") {
23
+ return true;
24
+ }
25
+ if (value === enValue) {
26
+ const isSingleWord = !enValue.includes(" ") && enValue.length < 20;
27
+ return !isSingleWord;
28
+ }
29
+ // Detect outdated template patterns (e.g., {{appName}}, {{variable}})
30
+ if (typeof value === "string") {
31
+ const hasTemplatePattern = value.includes("{{") && value.includes("}}");
32
+ if (hasTemplatePattern && !enValue.includes("{{")) {
33
+ return true;
34
+ }
35
+ }
36
+ return false;
37
+ }
38
+ export function isValidText(text) {
39
+ return typeof text === "string" && text.length > 0;
40
+ }
41
+ export function getTargetLanguage(langCode) {
42
+ return LANGUAGE_MAP[langCode];
43
+ }
44
+ export function isEnglishVariant(langCode) {
45
+ const targetLang = getTargetLanguage(langCode);
46
+ return targetLang === "en";
47
+ }
48
+ export function getLanguageDisplayName(code) {
49
+ return LANGUAGE_NAMES[code] || code;
50
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Translation Scripts
3
+ * Scripts for translating and synchronizing localization files
4
+ */
5
+ export * from './translate';
6
+ export * from './sync';
7
+ export * from './setup';
8
+ export * from './utils';
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Setup Languages Script
4
+ * Creates stub files for all supported languages (if not exist),
5
+ * then generates index.ts from all available translation files.
6
+ * Usage: node setup.ts [locales-dir]
7
+ */
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import { LANGUAGE_MAP, getLanguageDisplayName } from '../infrastructure/services';
11
+ export function setupLanguages(options) {
12
+ const { targetDir } = options;
13
+ const localesDir = path.resolve(process.cwd(), targetDir);
14
+ if (!fs.existsSync(localesDir)) {
15
+ console.error(`❌ Locales directory not found: ${localesDir}`);
16
+ return false;
17
+ }
18
+ // Create stub files for all supported languages that don't exist yet
19
+ let created = 0;
20
+ for (const langCode of Object.keys(LANGUAGE_MAP)) {
21
+ // Skip English variants — en-US is the base, others (en-AU, en-GB) are redundant
22
+ if (langCode.startsWith('en-') && langCode !== 'en-US')
23
+ continue;
24
+ const filePath = path.join(localesDir, `${langCode}.ts`);
25
+ if (!fs.existsSync(filePath)) {
26
+ const langName = getLanguageDisplayName(langCode);
27
+ fs.writeFileSync(filePath, `/**\n * ${langName} Translations\n * Auto-synced from en-US.ts\n */\n\nexport default {};\n`);
28
+ console.log(` ✅ Created ${langCode}.ts (${langName})`);
29
+ created++;
30
+ }
31
+ }
32
+ if (created > 0) {
33
+ console.log(`\n📦 Created ${created} new language stubs.\n`);
34
+ }
35
+ // Generate index.ts from all language files
36
+ const files = fs.readdirSync(localesDir)
37
+ .filter(f => f.match(/^[a-z]{2}-[A-Z]{2}\.ts$/))
38
+ .sort();
39
+ const imports = [];
40
+ const exports = [];
41
+ files.forEach(file => {
42
+ const code = file.replace('.ts', '');
43
+ const varName = code.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase()).replace('-', '');
44
+ imports.push(`import ${varName} from "./${code}";`);
45
+ exports.push(` "${code}": ${varName},`);
46
+ });
47
+ const content = `/**
48
+ * Localization Index
49
+ * Exports all available translation files
50
+ * Auto-generated by scripts/setup.ts
51
+ */
52
+
53
+ ${imports.join('\n')}
54
+
55
+ export const translations = {
56
+ ${exports.join('\n')}
57
+ };
58
+
59
+ export type TranslationKey = keyof typeof translations;
60
+
61
+ export default translations;
62
+ `;
63
+ fs.writeFileSync(path.join(localesDir, 'index.ts'), content);
64
+ console.log(`✅ Generated index.ts with ${files.length} languages`);
65
+ return true;
66
+ }
67
+ // CLI interface
68
+ export function runSetupLanguages() {
69
+ const targetDir = process.argv[2] || 'src/infrastructure/locales';
70
+ console.log('🚀 Setting up language files...\n');
71
+ setupLanguages({ targetDir });
72
+ }
73
+ if (import.meta.url === `file://${process.argv[1]}`) {
74
+ runSetupLanguages();
75
+ }
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Sync Translations Script
4
+ * Synchronizes translation keys from en-US.ts to all other language files
5
+ */
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { parseTypeScriptFile, generateTypeScriptContent, } from './utils/file-parser';
9
+ import { addMissingKeys, removeExtraKeys, } from './utils/sync-helper';
10
+ import { detectNewKeys } from './utils/key-detector';
11
+ import { extractUsedKeys } from './utils/key-extractor';
12
+ import { setDeep, countKeys } from './utils/object-helper';
13
+ export function syncLanguageFile(enUSPath, targetPath, langCode) {
14
+ const enUS = parseTypeScriptFile(enUSPath);
15
+ let target;
16
+ try {
17
+ target = parseTypeScriptFile(targetPath);
18
+ }
19
+ catch {
20
+ target = {};
21
+ }
22
+ const detectedNewKeys = detectNewKeys(enUS, target);
23
+ const addStats = { added: 0, newKeys: [] };
24
+ const removeStats = { removed: 0, removedKeys: [] };
25
+ addMissingKeys(enUS, target, addStats);
26
+ removeExtraKeys(enUS, target, removeStats);
27
+ const changed = (addStats.added || 0) > 0 || (removeStats.removed || 0) > 0;
28
+ if (changed) {
29
+ const content = generateTypeScriptContent(target, langCode);
30
+ fs.writeFileSync(targetPath, content);
31
+ }
32
+ return {
33
+ added: addStats.added,
34
+ newKeys: addStats.newKeys,
35
+ removed: removeStats.removed,
36
+ removedKeys: removeStats.removedKeys,
37
+ changed,
38
+ detectedNewKeys,
39
+ };
40
+ }
41
+ function processExtraction(srcDir, enUSPath) {
42
+ if (!srcDir)
43
+ return;
44
+ console.log(`🔍 Scanning source code and dependencies: ${srcDir}...`);
45
+ const usedKeyMap = extractUsedKeys(srcDir);
46
+ console.log(` Found ${usedKeyMap.size} unique keys.`);
47
+ const oldEnUS = parseTypeScriptFile(enUSPath);
48
+ const newEnUS = {};
49
+ let addedCount = 0;
50
+ for (const [key, defaultValue] of usedKeyMap) {
51
+ // Try to keep existing translation if it exists
52
+ const existingValue = key.split('.').reduce((obj, k) => {
53
+ if (obj && typeof obj === 'object' && k in obj) {
54
+ return obj[k];
55
+ }
56
+ return undefined;
57
+ }, oldEnUS);
58
+ // We treat it as "not translated" if the value is exactly the key string
59
+ const isActuallyTranslated = typeof existingValue === 'string' && existingValue !== key;
60
+ const valueToSet = isActuallyTranslated ? existingValue : defaultValue;
61
+ if (setDeep(newEnUS, key, valueToSet)) {
62
+ if (!isActuallyTranslated)
63
+ addedCount++;
64
+ }
65
+ }
66
+ const oldTotal = countKeys(oldEnUS);
67
+ const newTotal = countKeys(newEnUS);
68
+ const removedCount = Math.max(0, oldTotal - (newTotal - addedCount));
69
+ console.log(` ✨ Optimized en-US.ts: ${addedCount} keys populated/updated, pruned ${removedCount} unused.`);
70
+ const content = generateTypeScriptContent(newEnUS, 'en-US');
71
+ fs.writeFileSync(enUSPath, content);
72
+ }
73
+ export function syncTranslations(options) {
74
+ const { targetDir, srcDir } = options;
75
+ const localesDir = path.resolve(process.cwd(), targetDir);
76
+ const enUSPath = path.join(localesDir, 'en-US.ts');
77
+ if (!fs.existsSync(localesDir) || !fs.existsSync(enUSPath)) {
78
+ console.error(`❌ Localization files not found in: ${localesDir}`);
79
+ return false;
80
+ }
81
+ processExtraction(srcDir, enUSPath);
82
+ const files = fs.readdirSync(localesDir)
83
+ .filter(f => f.match(/^[a-z]{2}-[A-Z]{2}\.ts$/) && f !== 'en-US.ts')
84
+ .sort();
85
+ console.log(`📊 Languages to sync: ${files.length}\n`);
86
+ files.forEach(file => {
87
+ const langCode = file.replace('.ts', '');
88
+ const targetPath = path.join(localesDir, file);
89
+ const result = syncLanguageFile(enUSPath, targetPath, langCode);
90
+ if (result.changed) {
91
+ console.log(` 🌍 ${langCode}: ✏️ +${result.added || 0} keys, -${result.removed || 0} keys`);
92
+ }
93
+ });
94
+ console.log(`\n✅ Synchronization completed!`);
95
+ return true;
96
+ }
97
+ // CLI interface
98
+ export function runSyncTranslations() {
99
+ const targetDir = process.argv[2] || 'src/infrastructure/locales';
100
+ const srcDir = process.argv[3];
101
+ console.log('🚀 Starting translation synchronization...\n');
102
+ syncTranslations({ targetDir, srcDir });
103
+ }
104
+ if (import.meta.url === `file://${process.argv[1]}`) {
105
+ runSyncTranslations();
106
+ }
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Translate Missing Script
4
+ * Automatically translates missing strings using Google Translate
5
+ */
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { parseTypeScriptFile, generateTypeScriptContent, } from './utils/file-parser';
9
+ import { googleTranslateService, getTargetLanguage, getLanguageDisplayName } from '../infrastructure/services';
10
+ // Width of terminal line to clear for progress updates
11
+ const PROGRESS_LINE_WIDTH = 80;
12
+ export async function translateMissing(options) {
13
+ const { targetDir, srcDir, skipSync = false } = options;
14
+ // Initialize the translation service
15
+ googleTranslateService.initialize({
16
+ minDelay: 100,
17
+ maxRetries: 3,
18
+ timeout: 10000,
19
+ });
20
+ const localesDir = path.resolve(process.cwd(), targetDir);
21
+ const enUSPath = path.join(localesDir, 'en-US.ts');
22
+ if (!fs.existsSync(localesDir) || !fs.existsSync(enUSPath)) {
23
+ console.error(`❌ Localization files not found in: ${localesDir}`);
24
+ return;
25
+ }
26
+ const files = fs.readdirSync(localesDir)
27
+ .filter(f => f.match(/^[a-z]{2}-[A-Z]{2}\.ts$/) && f !== 'en-US.ts')
28
+ .sort();
29
+ console.log(`\n📊 Languages to translate: ${files.length}\n`);
30
+ const enUS = parseTypeScriptFile(enUSPath);
31
+ for (const file of files) {
32
+ const langCode = file.replace('.ts', '');
33
+ // Skip English variants
34
+ const targetLang = getTargetLanguage(langCode);
35
+ if (!targetLang || targetLang === 'en') {
36
+ console.log(`⏭️ Skipping ${langCode} (English variant)`);
37
+ continue;
38
+ }
39
+ const langName = getLanguageDisplayName(langCode);
40
+ console.log(`🌍 Translating ${langCode} (${langName})...`);
41
+ const targetPath = path.join(localesDir, file);
42
+ const target = parseTypeScriptFile(targetPath);
43
+ const stats = {
44
+ totalCount: 0,
45
+ successCount: 0,
46
+ failureCount: 0,
47
+ skippedCount: 0,
48
+ translatedKeys: [],
49
+ };
50
+ await googleTranslateService.translateObject(enUS, target, targetLang, '', stats);
51
+ // Clear progress line
52
+ process.stdout.write('\r' + ' '.repeat(PROGRESS_LINE_WIDTH) + '\r');
53
+ if (stats.successCount > 0) {
54
+ const content = generateTypeScriptContent(target, langCode);
55
+ fs.writeFileSync(targetPath, content);
56
+ console.log(` ✅ Successfully translated ${stats.successCount} keys:`);
57
+ // Detailed logging of translated keys
58
+ const displayCount = Math.min(stats.translatedKeys.length, 15);
59
+ stats.translatedKeys.slice(0, displayCount).forEach(item => {
60
+ console.log(` • ${item.key}: "${item.from}" → "${item.to}"`);
61
+ });
62
+ if (stats.translatedKeys.length > displayCount) {
63
+ console.log(` ... and ${stats.translatedKeys.length - displayCount} more.`);
64
+ }
65
+ }
66
+ else {
67
+ console.log(` ✨ Already up to date.`);
68
+ }
69
+ }
70
+ console.log('\n✅ All translations completed!');
71
+ }
72
+ // CLI interface
73
+ export function runTranslateMissing() {
74
+ const args = process.argv.slice(2).filter(arg => !arg.startsWith('--'));
75
+ const targetDir = args[0] || 'src/infrastructure/locales';
76
+ const srcDir = args[1];
77
+ const skipSync = process.argv.includes('--no-sync');
78
+ console.log('🚀 Starting integrated translation workflow...');
79
+ translateMissing({ targetDir, srcDir, skipSync }).catch(err => {
80
+ console.error('\n❌ Translation workflow failed:', err.message);
81
+ process.exit(1);
82
+ });
83
+ }
84
+ if (import.meta.url === `file://${process.argv[1]}`) {
85
+ runTranslateMissing();
86
+ }
@@ -0,0 +1,90 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { getLanguageDisplayName } from '../../infrastructure/utils/textValidator.util';
4
+ /**
5
+ * File Parser
6
+ * Parse and generate TypeScript translation files
7
+ */
8
+ export function parseTypeScriptFile(filePath) {
9
+ const content = fs.readFileSync(filePath, 'utf8');
10
+ // Match: export default { ... } OR export const NAME = { ... }
11
+ const match = content.match(/export\s+(?:default|const\s+\w+\s*=)\s*(\{[\s\S]*\});?\s*$/);
12
+ if (!match) {
13
+ throw new Error(`Could not parse TypeScript file: ${filePath}`);
14
+ }
15
+ const objectStr = match[1].replace(/;$/, '');
16
+ try {
17
+ // Basic evaluation for simple objects (safe for generated translation files)
18
+ // Only contains string literals, numbers, booleans, and nested objects
19
+ // eslint-disable-next-line no-eval
20
+ return eval(`(${objectStr})`);
21
+ }
22
+ catch (error) {
23
+ // File might be a barrel file with named imports
24
+ const dir = path.dirname(filePath);
25
+ const importMatches = [...content.matchAll(/import\s*\{\s*(\w+)\s*\}\s*from\s*["']\.\/(\w+)["']/g)];
26
+ if (importMatches.length > 0) {
27
+ const result = {};
28
+ for (const [, varName, moduleName] of importMatches) {
29
+ const subFilePath = path.join(dir, `${moduleName}.ts`);
30
+ if (fs.existsSync(subFilePath)) {
31
+ try {
32
+ result[varName] = parseTypeScriptFile(subFilePath);
33
+ }
34
+ catch (subError) {
35
+ // Log sub-file parse errors but continue with other files
36
+ console.warn(`Warning: Could not parse sub-file ${subFilePath}: ${subError instanceof Error ? subError.message : 'Unknown error'}`);
37
+ }
38
+ }
39
+ }
40
+ if (Object.keys(result).length > 0) {
41
+ return result;
42
+ }
43
+ }
44
+ }
45
+ return {};
46
+ }
47
+ export function stringifyValue(value, indent = 2) {
48
+ if (typeof value === 'string') {
49
+ const escaped = value
50
+ .replace(/\\/g, '\\\\')
51
+ .replace(/"/g, '\\"')
52
+ .replace(/\n/g, '\\n');
53
+ return `"${escaped}"`;
54
+ }
55
+ if (Array.isArray(value)) {
56
+ if (value.length === 0)
57
+ return '[]';
58
+ const items = value.map(v => stringifyValue(v, indent + 2));
59
+ return `[${items.join(', ')}]`;
60
+ }
61
+ if (typeof value === 'object' && value !== null) {
62
+ const entries = Object.entries(value);
63
+ if (entries.length === 0) {
64
+ return '{}';
65
+ }
66
+ const spaces = ' '.repeat(indent);
67
+ const innerSpaces = ' '.repeat(indent + 2);
68
+ const entriesStr = entries
69
+ .sort((a, b) => a[0].localeCompare(b[0]))
70
+ .map(([k, v]) => {
71
+ const key = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(k) ? k : `"${k}"`;
72
+ return `${innerSpaces}${key}: ${stringifyValue(v, indent + 2)}`;
73
+ })
74
+ .join(',\n');
75
+ return `{\n${entriesStr},\n${spaces}}`;
76
+ }
77
+ return String(value);
78
+ }
79
+ export function generateTypeScriptContent(obj, langCode) {
80
+ const langName = getLanguageDisplayName(langCode);
81
+ const isBase = langCode === 'en-US';
82
+ const objString = stringifyValue(obj, 0);
83
+ return `/**
84
+ * ${langName} Translations
85
+ * ${isBase ? 'Base translations file' : 'Auto-synced from en-US.ts'}
86
+ */
87
+
88
+ export default ${objString};
89
+ `;
90
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Scripts Utils
3
+ * Utility functions for translation scripts
4
+ */
5
+ export * from './file-parser';
6
+ export * from './key-detector';
7
+ export * from './key-extractor';
8
+ export * from './object-helper';
9
+ export * from './sync-helper';
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Key Detector
3
+ * Detects new, missing, and removed keys between source and target objects
4
+ */
5
+ export function detectNewKeys(sourceObj, targetObj, path = '', newKeys = []) {
6
+ for (const key in sourceObj) {
7
+ const currentPath = path ? `${path}.${key}` : key;
8
+ const sourceValue = sourceObj[key];
9
+ const targetValue = targetObj[key];
10
+ if (!Object.prototype.hasOwnProperty.call(targetObj, key)) {
11
+ newKeys.push({ path: currentPath, value: sourceValue });
12
+ }
13
+ else if (typeof sourceValue === 'object' &&
14
+ sourceValue !== null &&
15
+ !Array.isArray(sourceValue)) {
16
+ if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue)) {
17
+ detectNewKeys(sourceValue, targetValue, currentPath, newKeys);
18
+ }
19
+ }
20
+ }
21
+ return newKeys;
22
+ }
23
+ export function detectMissingKeys(sourceObj, targetObj, path = '', missingKeys = []) {
24
+ for (const key in targetObj) {
25
+ const currentPath = path ? `${path}.${key}` : key;
26
+ if (!Object.prototype.hasOwnProperty.call(sourceObj, key)) {
27
+ missingKeys.push(currentPath);
28
+ }
29
+ else if (typeof sourceObj[key] === 'object' &&
30
+ sourceObj[key] !== null &&
31
+ !Array.isArray(sourceObj[key]) &&
32
+ typeof targetObj[key] === 'object' &&
33
+ targetObj[key] !== null &&
34
+ !Array.isArray(targetObj[key])) {
35
+ detectMissingKeys(sourceObj[key], targetObj[key], currentPath, missingKeys);
36
+ }
37
+ }
38
+ return missingKeys;
39
+ }
@@ -0,0 +1,95 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ /**
4
+ * Generic Key Extractor
5
+ * Scans source code for i18n translation keys
6
+ */
7
+ const IGNORED_DOMAINS = ['.com', '.org', '.net', '.io', '.co', '.app', '.ai', '.gov', '.edu'];
8
+ const IGNORED_EXTENSIONS = [
9
+ '.ts', '.tsx', '.js', '.jsx', '.json', '.yaml', '.yml',
10
+ '.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.pdf',
11
+ '.mp4', '.mov', '.avi', '.mp3', '.wav', '.css', '.scss', '.md'
12
+ ];
13
+ const IGNORED_LAYOUT_VALS = new Set([
14
+ 'center', 'row', 'column', 'flex', 'absolute', 'relative', 'hidden', 'visible',
15
+ 'transparent', 'bold', 'normal', 'italic', 'contain', 'cover', 'stretch',
16
+ 'top', 'bottom', 'left', 'right', 'middle', 'auto', 'none', 'underline',
17
+ 'capitalize', 'uppercase', 'lowercase', 'solid', 'dotted', 'dashed', 'wrap',
18
+ 'nowrap', 'space-between', 'space-around', 'flex-start', 'flex-end', 'baseline',
19
+ 'react', 'index', 'default', 'string', 'number', 'boolean', 'key', 'id'
20
+ ]);
21
+ function extractFromFile(content, keyMap) {
22
+ // Pattern 1: t('key') or t("key")
23
+ const tRegex = /(?:^|\W)t\(['"`]([^'"`]+)['"`]\)/g;
24
+ let match;
25
+ while ((match = tRegex.exec(content)) !== null) {
26
+ const key = match[1];
27
+ if (!key.includes('${') && !keyMap.has(key)) {
28
+ keyMap.set(key, key);
29
+ }
30
+ }
31
+ // Pattern 2: Dot-notation strings (potential i18n keys)
32
+ const dotRegex = /['"`]([a-z][a-z0-9_]*\.(?:[a-z0-9_]+\.)+[a-z0-9_]+)['"`]/gi;
33
+ while ((match = dotRegex.exec(content)) !== null) {
34
+ const key = match[1];
35
+ const isIgnoredDomain = IGNORED_DOMAINS.some(ext => key.toLowerCase().endsWith(ext));
36
+ const isIgnoredExt = IGNORED_EXTENSIONS.some(ext => key.toLowerCase().endsWith(ext));
37
+ if (!isIgnoredDomain && !isIgnoredExt && !key.includes(' ') && !keyMap.has(key)) {
38
+ keyMap.set(key, key);
39
+ }
40
+ }
41
+ // Pattern 3: Template literals t(`prefix.${var}`)
42
+ const templateRegex = /t\(\`([a-z0-9_.]+)\.\$\{/g;
43
+ while ((match = templateRegex.exec(content)) !== null) {
44
+ const prefix = match[1];
45
+ const arrayMatches = content.matchAll(/\[([\s\S]*?)\]/g);
46
+ for (const arrayMatch of arrayMatches) {
47
+ const inner = arrayMatch[1];
48
+ const idMatches = inner.matchAll(/['"`]([a-z0-9_]{2,40})['"`]/g);
49
+ for (const idMatch of idMatches) {
50
+ const id = idMatch[1];
51
+ if (IGNORED_LAYOUT_VALS.has(id.toLowerCase()))
52
+ continue;
53
+ if (/^[0-9]+$/.test(id))
54
+ continue;
55
+ const dynamicKey = `${prefix}.${id}`;
56
+ if (!keyMap.has(dynamicKey)) {
57
+ keyMap.set(dynamicKey, dynamicKey);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
63
+ function walkDirectory(dir, keyMap, skipDirs = ['node_modules', '.expo', '.git', 'build', 'ios', 'android', 'assets', 'locales', '__tests__']) {
64
+ if (!fs.existsSync(dir))
65
+ return;
66
+ const files = fs.readdirSync(dir);
67
+ for (const file of files) {
68
+ const fullPath = path.join(dir, file);
69
+ const stat = fs.statSync(fullPath);
70
+ if (stat.isDirectory()) {
71
+ if (!skipDirs.includes(file)) {
72
+ walkDirectory(fullPath, keyMap, skipDirs);
73
+ }
74
+ }
75
+ else if (/\.(ts|tsx|js|jsx)$/.test(file)) {
76
+ const content = fs.readFileSync(fullPath, 'utf8');
77
+ extractFromFile(content, keyMap);
78
+ }
79
+ }
80
+ }
81
+ export function extractUsedKeys(srcDir) {
82
+ const keyMap = new Map();
83
+ if (!srcDir)
84
+ return keyMap;
85
+ const projectRoot = process.cwd();
86
+ const absoluteSrcDir = path.resolve(projectRoot, srcDir);
87
+ // Scan project source
88
+ walkDirectory(absoluteSrcDir, keyMap);
89
+ // Scan @umituz packages for shared keys
90
+ const packagesDir = path.resolve(projectRoot, 'node_modules/@umituz');
91
+ if (fs.existsSync(packagesDir)) {
92
+ walkDirectory(packagesDir, keyMap);
93
+ }
94
+ return keyMap;
95
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Object Helper
3
+ * Utilities for deep object manipulation
4
+ */
5
+ /**
6
+ * Set a value in a nested object, creating intermediate objects if necessary
7
+ * Returns true if the key was newly added, false if it already existed
8
+ */
9
+ export function setDeep(obj, path, value) {
10
+ const keys = path.split('.');
11
+ let current = obj;
12
+ for (let i = 0; i < keys.length - 1; i++) {
13
+ const key = keys[i];
14
+ if (!current[key] || typeof current[key] !== 'object' || Array.isArray(current[key])) {
15
+ current[key] = {};
16
+ }
17
+ current = current[key];
18
+ }
19
+ const lastKey = keys[keys.length - 1];
20
+ if (current[lastKey] === undefined) {
21
+ current[lastKey] = value;
22
+ return true;
23
+ }
24
+ return false;
25
+ }
26
+ /**
27
+ * Count all leaf keys in a nested object
28
+ */
29
+ export function countKeys(obj) {
30
+ let count = 0;
31
+ const walk = (o) => {
32
+ for (const k in o) {
33
+ if (typeof o[k] === 'object' && o[k] !== null) {
34
+ walk(o[k]);
35
+ }
36
+ else {
37
+ count++;
38
+ }
39
+ }
40
+ };
41
+ walk(obj);
42
+ return count;
43
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Sync Helper
3
+ * Helper functions for synchronizing translation keys
4
+ */
5
+ export function addMissingKeys(sourceObj, targetObj, stats = {}) {
6
+ stats.added = stats.added || 0;
7
+ stats.newKeys = stats.newKeys || [];
8
+ for (const key in sourceObj) {
9
+ const sourceValue = sourceObj[key];
10
+ const isNewKey = !Object.prototype.hasOwnProperty.call(targetObj, key);
11
+ if (isNewKey) {
12
+ targetObj[key] = sourceValue;
13
+ stats.added++;
14
+ stats.newKeys.push(key);
15
+ }
16
+ else if (typeof sourceValue === 'object' &&
17
+ sourceValue !== null &&
18
+ !Array.isArray(sourceValue)) {
19
+ if (!targetObj[key] || typeof targetObj[key] !== 'object') {
20
+ targetObj[key] = {};
21
+ }
22
+ addMissingKeys(sourceValue, targetObj[key], stats);
23
+ }
24
+ }
25
+ return stats;
26
+ }
27
+ export function removeExtraKeys(sourceObj, targetObj, stats = {}) {
28
+ stats.removed = stats.removed || 0;
29
+ stats.removedKeys = stats.removedKeys || [];
30
+ for (const key in targetObj) {
31
+ const isExtraKey = !Object.prototype.hasOwnProperty.call(sourceObj, key);
32
+ if (isExtraKey) {
33
+ delete targetObj[key];
34
+ stats.removed++;
35
+ stats.removedKeys.push(key);
36
+ }
37
+ else if (typeof sourceObj[key] === 'object' &&
38
+ sourceObj[key] !== null &&
39
+ !Array.isArray(sourceObj[key]) &&
40
+ typeof targetObj[key] === 'object' &&
41
+ targetObj[key] !== null &&
42
+ !Array.isArray(targetObj[key])) {
43
+ removeExtraKeys(sourceObj[key], targetObj[key], stats);
44
+ }
45
+ }
46
+ return stats;
47
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/react-native-google-translate",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Google Translate integration for React Native apps with rate limiting, batch translation, and TypeScript support",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
@@ -16,10 +16,12 @@
16
16
  "./*": "./src/*/index.ts"
17
17
  },
18
18
  "scripts": {
19
- "setup": "node src/scripts/setup.ts",
20
- "translate": "node src/scripts/translate.ts",
21
- "sync": "node src/scripts/sync.ts",
22
- "i18n:setup": "node src/scripts/setup.ts",
19
+ "build:scripts": "tsc -p tsconfig.scripts.json",
20
+ "setup": "node dist/scripts/setup.js",
21
+ "translate": "node dist/scripts/translate.js",
22
+ "sync": "node dist/scripts/sync.js",
23
+ "i18n:setup": "node dist/scripts/setup.js",
24
+ "prepublishOnly": "npm run build:scripts",
23
25
  "typecheck": "tsc --noEmit",
24
26
  "lint": "echo 'Lint passed'",
25
27
  "version:patch": "npm version patch -m 'chore: release v%s'",
@@ -56,6 +58,7 @@
56
58
  },
57
59
  "files": [
58
60
  "src",
61
+ "dist",
59
62
  "README.md",
60
63
  "LICENSE"
61
64
  ]
@@ -51,8 +51,8 @@ export function setupLanguages(options: SetupLanguagesOptions): boolean {
51
51
  .filter(f => f.match(/^[a-z]{2}-[A-Z]{2}\.ts$/))
52
52
  .sort();
53
53
 
54
- const imports = [];
55
- const exports = [];
54
+ const imports: string[] = [];
55
+ const exports: string[] = [];
56
56
 
57
57
  files.forEach(file => {
58
58
  const code = file.replace('.ts', '');