@djangocfg/llm 2.1.164

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.
Files changed (45) hide show
  1. package/README.md +181 -0
  2. package/dist/index.cjs +1164 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +164 -0
  5. package/dist/index.d.ts +164 -0
  6. package/dist/index.mjs +1128 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/providers/index.cjs +317 -0
  9. package/dist/providers/index.cjs.map +1 -0
  10. package/dist/providers/index.d.cts +30 -0
  11. package/dist/providers/index.d.ts +30 -0
  12. package/dist/providers/index.mjs +304 -0
  13. package/dist/providers/index.mjs.map +1 -0
  14. package/dist/sdkrouter-D8GMBmTi.d.ts +171 -0
  15. package/dist/sdkrouter-hlQlVd0v.d.cts +171 -0
  16. package/dist/text-utils-DoYqMIr6.d.ts +289 -0
  17. package/dist/text-utils-VXWN-8Oq.d.cts +289 -0
  18. package/dist/translator/index.cjs +794 -0
  19. package/dist/translator/index.cjs.map +1 -0
  20. package/dist/translator/index.d.cts +24 -0
  21. package/dist/translator/index.d.ts +24 -0
  22. package/dist/translator/index.mjs +769 -0
  23. package/dist/translator/index.mjs.map +1 -0
  24. package/dist/types-D6lazgm1.d.cts +59 -0
  25. package/dist/types-D6lazgm1.d.ts +59 -0
  26. package/package.json +82 -0
  27. package/src/client.ts +119 -0
  28. package/src/index.ts +70 -0
  29. package/src/providers/anthropic.ts +98 -0
  30. package/src/providers/base.ts +90 -0
  31. package/src/providers/index.ts +15 -0
  32. package/src/providers/openai.ts +73 -0
  33. package/src/providers/sdkrouter.ts +279 -0
  34. package/src/translator/cache.ts +237 -0
  35. package/src/translator/index.ts +55 -0
  36. package/src/translator/json-translator.ts +408 -0
  37. package/src/translator/prompts.ts +90 -0
  38. package/src/translator/text-utils.ts +148 -0
  39. package/src/translator/types.ts +112 -0
  40. package/src/translator/validator.ts +181 -0
  41. package/src/types.ts +85 -0
  42. package/src/utils/env.ts +67 -0
  43. package/src/utils/index.ts +2 -0
  44. package/src/utils/json.ts +44 -0
  45. package/src/utils/schema.ts +153 -0
@@ -0,0 +1,769 @@
1
+ import crypto from 'crypto';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
7
+ // src/translator/text-utils.ts
8
+ function isTechnicalContent(text) {
9
+ const trimmed = text.trim();
10
+ if (!trimmed) return true;
11
+ if (/^(https?:\/\/|\/\/|www\.)/i.test(trimmed)) return true;
12
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) return true;
13
+ if (/^\/[a-zA-Z]/.test(trimmed)) return true;
14
+ if (/\.(js|ts|tsx|jsx|json|css|scss|html|md|py|go|rs)$/i.test(trimmed)) return true;
15
+ if (/^[\d.,]+%?$/.test(trimmed)) return true;
16
+ if (/^[A-Z][A-Z0-9_]*$/.test(trimmed)) return true;
17
+ if (/^(\{[^}]+\}|\{\{[^}]+\}\}|%[sd]|\$\d+)$/.test(trimmed)) return true;
18
+ if (/^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/.test(trimmed)) return true;
19
+ return false;
20
+ }
21
+ function containsCJK(text) {
22
+ return /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(text);
23
+ }
24
+ function containsCyrillic(text) {
25
+ return /[\u0400-\u04ff]/.test(text);
26
+ }
27
+ function containsArabic(text) {
28
+ return /[\u0600-\u06ff]/.test(text);
29
+ }
30
+ function detectScript(text) {
31
+ if (containsCJK(text)) return "cjk";
32
+ if (containsCyrillic(text)) return "cyrillic";
33
+ if (containsArabic(text)) return "arabic";
34
+ if (/[a-zA-Z]/.test(text)) return "latin";
35
+ return "unknown";
36
+ }
37
+ function extractPlaceholders(text) {
38
+ const patterns = [
39
+ /\{[^}]+\}/g,
40
+ // {name}
41
+ /\{\{[^}]+\}\}/g,
42
+ // {{name}}
43
+ /%[sd]/g,
44
+ // %s, %d
45
+ /\$\d+/g
46
+ // $1, $2
47
+ ];
48
+ const placeholders = [];
49
+ for (const pattern of patterns) {
50
+ const matches = text.match(pattern);
51
+ if (matches) {
52
+ placeholders.push(...matches);
53
+ }
54
+ }
55
+ return [...new Set(placeholders)];
56
+ }
57
+ function validatePlaceholders(original, translated) {
58
+ const originalPlaceholders = extractPlaceholders(original);
59
+ const translatedPlaceholders = extractPlaceholders(translated);
60
+ const missing = originalPlaceholders.filter(
61
+ (p) => !translatedPlaceholders.includes(p)
62
+ );
63
+ const extra = translatedPlaceholders.filter(
64
+ (p) => !originalPlaceholders.includes(p)
65
+ );
66
+ return {
67
+ valid: missing.length === 0 && extra.length === 0,
68
+ missing,
69
+ extra
70
+ };
71
+ }
72
+ function extractTranslatableValues(obj, path = "") {
73
+ const values = [];
74
+ if (typeof obj === "string") {
75
+ if (!isTechnicalContent(obj)) {
76
+ values.push({ path, value: obj });
77
+ }
78
+ } else if (Array.isArray(obj)) {
79
+ obj.forEach((item, index) => {
80
+ values.push(
81
+ ...extractTranslatableValues(item, path ? `${path}[${index}]` : `[${index}]`)
82
+ );
83
+ });
84
+ } else if (obj !== null && typeof obj === "object") {
85
+ for (const [key, value] of Object.entries(obj)) {
86
+ values.push(
87
+ ...extractTranslatableValues(value, path ? `${path}.${key}` : key)
88
+ );
89
+ }
90
+ }
91
+ return values;
92
+ }
93
+
94
+ // src/translator/validator.ts
95
+ function validateJsonKeys(original, translated, path = "") {
96
+ const errors = [];
97
+ if (typeof original !== typeof translated) {
98
+ errors.push(`Type mismatch at ${path || "root"}: expected ${typeof original}, got ${typeof translated}`);
99
+ return { valid: false, errors };
100
+ }
101
+ if (original === null || translated === null) {
102
+ if (original !== translated) {
103
+ errors.push(`Null mismatch at ${path || "root"}`);
104
+ }
105
+ return { valid: errors.length === 0, errors };
106
+ }
107
+ if (Array.isArray(original)) {
108
+ if (!Array.isArray(translated)) {
109
+ errors.push(`Expected array at ${path || "root"}`);
110
+ return { valid: false, errors };
111
+ }
112
+ if (original.length !== translated.length) {
113
+ errors.push(
114
+ `Array length mismatch at ${path || "root"}: expected ${original.length}, got ${translated.length}`
115
+ );
116
+ }
117
+ const minLen = Math.min(original.length, translated.length);
118
+ for (let i = 0; i < minLen; i++) {
119
+ const result = validateJsonKeys(
120
+ original[i],
121
+ translated[i],
122
+ `${path}[${i}]`
123
+ );
124
+ errors.push(...result.errors);
125
+ }
126
+ return { valid: errors.length === 0, errors };
127
+ }
128
+ if (typeof original === "object") {
129
+ if (typeof translated !== "object" || Array.isArray(translated)) {
130
+ errors.push(`Expected object at ${path || "root"}`);
131
+ return { valid: false, errors };
132
+ }
133
+ const origKeys = Object.keys(original);
134
+ const transKeys = Object.keys(translated);
135
+ for (const key of origKeys) {
136
+ if (!transKeys.includes(key)) {
137
+ errors.push(`Missing key: ${path ? `${path}.${key}` : key}`);
138
+ }
139
+ }
140
+ for (const key of transKeys) {
141
+ if (!origKeys.includes(key)) {
142
+ errors.push(
143
+ `Unexpected key: ${path ? `${path}.${key}` : key} (key was translated?)`
144
+ );
145
+ }
146
+ }
147
+ for (const key of origKeys) {
148
+ if (transKeys.includes(key)) {
149
+ const result = validateJsonKeys(
150
+ original[key],
151
+ translated[key],
152
+ path ? `${path}.${key}` : key
153
+ );
154
+ errors.push(...result.errors);
155
+ }
156
+ }
157
+ return { valid: errors.length === 0, errors };
158
+ }
159
+ return { valid: true, errors: [] };
160
+ }
161
+ function validatePlaceholders2(original, translated, path = "") {
162
+ const errors = [];
163
+ if (typeof original === "string" && typeof translated === "string") {
164
+ const origPlaceholders = extractPlaceholders(original);
165
+ const transPlaceholders = extractPlaceholders(translated);
166
+ for (const placeholder of origPlaceholders) {
167
+ if (!transPlaceholders.includes(placeholder)) {
168
+ errors.push(
169
+ `Missing placeholder "${placeholder}" at ${path || "root"}`
170
+ );
171
+ }
172
+ }
173
+ for (const placeholder of transPlaceholders) {
174
+ if (!origPlaceholders.includes(placeholder)) {
175
+ errors.push(
176
+ `Extra placeholder "${placeholder}" at ${path || "root"}`
177
+ );
178
+ }
179
+ }
180
+ } else if (Array.isArray(original) && Array.isArray(translated)) {
181
+ const minLen = Math.min(original.length, translated.length);
182
+ for (let i = 0; i < minLen; i++) {
183
+ const result = validatePlaceholders2(
184
+ original[i],
185
+ translated[i],
186
+ `${path}[${i}]`
187
+ );
188
+ errors.push(...result.errors);
189
+ }
190
+ } else if (typeof original === "object" && original !== null && typeof translated === "object" && translated !== null) {
191
+ for (const key of Object.keys(original)) {
192
+ if (key in translated) {
193
+ const result = validatePlaceholders2(
194
+ original[key],
195
+ translated[key],
196
+ path ? `${path}.${key}` : key
197
+ );
198
+ errors.push(...result.errors);
199
+ }
200
+ }
201
+ }
202
+ return { valid: errors.length === 0, errors };
203
+ }
204
+ function validateTranslation(original, translated) {
205
+ const keyResult = validateJsonKeys(original, translated);
206
+ const placeholderResult = validatePlaceholders2(original, translated);
207
+ return {
208
+ valid: keyResult.valid && placeholderResult.valid,
209
+ errors: [...keyResult.errors, ...placeholderResult.errors]
210
+ };
211
+ }
212
+
213
+ // src/utils/json.ts
214
+ function extractJson(text) {
215
+ let jsonStr = text.trim();
216
+ if (jsonStr.startsWith("```json")) {
217
+ jsonStr = jsonStr.slice(7);
218
+ } else if (jsonStr.startsWith("```")) {
219
+ jsonStr = jsonStr.slice(3);
220
+ }
221
+ if (jsonStr.endsWith("```")) {
222
+ jsonStr = jsonStr.slice(0, -3);
223
+ }
224
+ jsonStr = jsonStr.trim();
225
+ const jsonStart = jsonStr.search(/[\[{]/);
226
+ const jsonEndBracket = jsonStr.lastIndexOf("]");
227
+ const jsonEndBrace = jsonStr.lastIndexOf("}");
228
+ const jsonEnd = Math.max(jsonEndBracket, jsonEndBrace);
229
+ if (jsonStart !== -1 && jsonEnd !== -1) {
230
+ jsonStr = jsonStr.slice(jsonStart, jsonEnd + 1);
231
+ }
232
+ try {
233
+ return JSON.parse(jsonStr);
234
+ } catch (error) {
235
+ throw new Error(
236
+ `Failed to parse JSON from LLM response: ${error instanceof Error ? error.message : "Unknown error"}
237
+
238
+ Response:
239
+ ${text}`
240
+ );
241
+ }
242
+ }
243
+
244
+ // src/translator/types.ts
245
+ var LANGUAGE_NAMES = {
246
+ en: "English",
247
+ ru: "Russian",
248
+ ko: "Korean",
249
+ ja: "Japanese",
250
+ zh: "Chinese",
251
+ de: "German",
252
+ fr: "French",
253
+ es: "Spanish",
254
+ it: "Italian",
255
+ pt: "Portuguese",
256
+ "pt-BR": "Brazilian Portuguese",
257
+ ar: "Arabic",
258
+ nl: "Dutch",
259
+ tr: "Turkish",
260
+ pl: "Polish",
261
+ sv: "Swedish",
262
+ no: "Norwegian",
263
+ da: "Danish",
264
+ uk: "Ukrainian",
265
+ hi: "Hindi"
266
+ };
267
+
268
+ // src/translator/prompts.ts
269
+ function getLanguageName(code) {
270
+ return LANGUAGE_NAMES[code] ?? code;
271
+ }
272
+ function buildJsonTranslationPrompt(json, sourceLanguage, targetLanguage) {
273
+ const sourceName = getLanguageName(sourceLanguage);
274
+ const targetName = getLanguageName(targetLanguage);
275
+ return `Translate all string VALUES in this JSON from ${sourceName} to ${targetName}.
276
+
277
+ Rules:
278
+ - Translate ALL string values to ${targetName}
279
+ - Keep JSON keys unchanged (English)
280
+ - Skip: URLs, emails, numbers, "SKIP"
281
+ - Keep placeholders: {name}, {{var}}, %s
282
+
283
+ ${json}
284
+
285
+ Return ONLY the JSON with all values translated to ${targetName}:`;
286
+ }
287
+ function buildTextTranslationPrompt(text, sourceLanguage, targetLanguage) {
288
+ const sourceName = getLanguageName(sourceLanguage);
289
+ const targetName = getLanguageName(targetLanguage);
290
+ return `Translate from ${sourceName} to ${targetName}.
291
+
292
+ RULES:
293
+ 1. Translate ONLY the text provided
294
+ 2. Preserve formatting, numbers, URLs
295
+ 3. Keep placeholders like {name}, {{var}} unchanged
296
+ 4. Return ONLY the translation, no explanations
297
+
298
+ Text: ${text}
299
+
300
+ Translation:`;
301
+ }
302
+ function buildRetryPrompt(originalJson, wrongJson, errors, targetLanguage) {
303
+ const targetName = getLanguageName(targetLanguage);
304
+ return `Your previous translation had errors. Fix them.
305
+
306
+ ERRORS FOUND:
307
+ ${errors.map((e) => `- ${e}`).join("\n")}
308
+
309
+ ORIGINAL JSON:
310
+ ${originalJson}
311
+
312
+ YOUR WRONG TRANSLATION:
313
+ ${wrongJson}
314
+
315
+ FIX THE ERRORS. Remember:
316
+ - JSON keys must stay in English
317
+ - Only translate string values
318
+ - Preserve all placeholders
319
+
320
+ Return ONLY the corrected JSON translated to ${targetName}:`;
321
+ }
322
+ var TranslationCache = class {
323
+ constructor(maxMemorySize = 1e3, storage) {
324
+ this.maxMemorySize = maxMemorySize;
325
+ this.storage = storage;
326
+ __publicField(this, "memoryCache", /* @__PURE__ */ new Map());
327
+ __publicField(this, "cacheOrder", []);
328
+ __publicField(this, "hits", 0);
329
+ __publicField(this, "misses", 0);
330
+ }
331
+ /**
332
+ * Generate hash for text
333
+ */
334
+ getTextHash(text) {
335
+ return crypto.createHash("md5").update(text).digest("hex");
336
+ }
337
+ /**
338
+ * Get storage key for language pair
339
+ */
340
+ getStorageKey(sourceLang, targetLang) {
341
+ return `translator:${sourceLang}-${targetLang}`;
342
+ }
343
+ /**
344
+ * Load from persistent storage
345
+ */
346
+ loadFromStorage(sourceLang, targetLang) {
347
+ if (!this.storage) return {};
348
+ try {
349
+ const key = this.getStorageKey(sourceLang, targetLang);
350
+ const data = this.storage.getItem(key);
351
+ return data ? JSON.parse(data) : {};
352
+ } catch {
353
+ return {};
354
+ }
355
+ }
356
+ /**
357
+ * Save to persistent storage
358
+ */
359
+ saveToStorage(sourceLang, targetLang, cache) {
360
+ if (!this.storage) return;
361
+ try {
362
+ const key = this.getStorageKey(sourceLang, targetLang);
363
+ this.storage.setItem(key, JSON.stringify(cache));
364
+ } catch {
365
+ }
366
+ }
367
+ /**
368
+ * Evict oldest entries if memory is full
369
+ */
370
+ evictIfNeeded() {
371
+ while (this.memoryCache.size >= this.maxMemorySize && this.cacheOrder.length > 0) {
372
+ const oldestKey = this.cacheOrder.shift();
373
+ this.memoryCache.delete(oldestKey);
374
+ }
375
+ }
376
+ /**
377
+ * Get translation from cache
378
+ */
379
+ get(text, sourceLang, targetLang) {
380
+ const textHash = this.getTextHash(text);
381
+ const cacheKey = `${sourceLang}-${targetLang}:${textHash}`;
382
+ if (this.memoryCache.has(cacheKey)) {
383
+ this.hits++;
384
+ return this.memoryCache.get(cacheKey);
385
+ }
386
+ const fileCache = this.loadFromStorage(sourceLang, targetLang);
387
+ if (textHash in fileCache) {
388
+ const translation = fileCache[textHash];
389
+ this.evictIfNeeded();
390
+ this.memoryCache.set(cacheKey, translation);
391
+ this.cacheOrder.push(cacheKey);
392
+ this.hits++;
393
+ return translation;
394
+ }
395
+ this.misses++;
396
+ return void 0;
397
+ }
398
+ /**
399
+ * Store translation in cache
400
+ */
401
+ set(text, sourceLang, targetLang, translation) {
402
+ const textHash = this.getTextHash(text);
403
+ const cacheKey = `${sourceLang}-${targetLang}:${textHash}`;
404
+ this.evictIfNeeded();
405
+ this.memoryCache.set(cacheKey, translation);
406
+ if (!this.cacheOrder.includes(cacheKey)) {
407
+ this.cacheOrder.push(cacheKey);
408
+ }
409
+ const fileCache = this.loadFromStorage(sourceLang, targetLang);
410
+ fileCache[textHash] = translation;
411
+ this.saveToStorage(sourceLang, targetLang, fileCache);
412
+ }
413
+ /**
414
+ * Get multiple translations at once
415
+ */
416
+ getMany(texts, sourceLang, targetLang) {
417
+ const cached = /* @__PURE__ */ new Map();
418
+ const uncached = [];
419
+ for (const text of texts) {
420
+ const translation = this.get(text, sourceLang, targetLang);
421
+ if (translation !== void 0) {
422
+ cached.set(text, translation);
423
+ } else {
424
+ uncached.push(text);
425
+ }
426
+ }
427
+ return { cached, uncached };
428
+ }
429
+ /**
430
+ * Store multiple translations at once
431
+ */
432
+ setMany(translations, sourceLang, targetLang) {
433
+ for (const [text, translation] of translations) {
434
+ this.set(text, sourceLang, targetLang, translation);
435
+ }
436
+ }
437
+ /**
438
+ * Clear cache
439
+ */
440
+ clear(sourceLang, targetLang) {
441
+ if (sourceLang && targetLang) {
442
+ const prefix = `${sourceLang}-${targetLang}:`;
443
+ for (const key of [...this.memoryCache.keys()]) {
444
+ if (key.startsWith(prefix)) {
445
+ this.memoryCache.delete(key);
446
+ const idx = this.cacheOrder.indexOf(key);
447
+ if (idx !== -1) this.cacheOrder.splice(idx, 1);
448
+ }
449
+ }
450
+ if (this.storage) {
451
+ this.storage.removeItem(this.getStorageKey(sourceLang, targetLang));
452
+ }
453
+ } else {
454
+ this.memoryCache.clear();
455
+ this.cacheOrder = [];
456
+ this.hits = 0;
457
+ this.misses = 0;
458
+ }
459
+ }
460
+ /**
461
+ * Get cache statistics
462
+ */
463
+ getStats() {
464
+ const languagePairs = [];
465
+ const pairCounts = /* @__PURE__ */ new Map();
466
+ for (const key of this.memoryCache.keys()) {
467
+ const pair = key.split(":")[0];
468
+ pairCounts.set(pair, (pairCounts.get(pair) || 0) + 1);
469
+ }
470
+ for (const [pair, count] of pairCounts) {
471
+ languagePairs.push({ pair, translations: count });
472
+ }
473
+ return {
474
+ memorySize: this.memoryCache.size,
475
+ hits: this.hits,
476
+ misses: this.misses,
477
+ languagePairs
478
+ };
479
+ }
480
+ };
481
+ function createCache(maxMemorySize, storage) {
482
+ return new TranslationCache(maxMemorySize, storage);
483
+ }
484
+
485
+ // src/translator/json-translator.ts
486
+ var DEFAULT_TRANSLATION_MODEL = "openai/gpt-4o-mini";
487
+ var JsonTranslator = class {
488
+ constructor(client, cache, defaultModel) {
489
+ this.client = client;
490
+ __publicField(this, "cache");
491
+ __publicField(this, "defaultModel");
492
+ this.cache = cache ?? createCache();
493
+ this.defaultModel = defaultModel ?? DEFAULT_TRANSLATION_MODEL;
494
+ }
495
+ /**
496
+ * Detect language from text
497
+ */
498
+ detectLanguage(text) {
499
+ const script = detectScript(text);
500
+ switch (script) {
501
+ case "cjk":
502
+ return "zh";
503
+ case "cyrillic":
504
+ return "ru";
505
+ case "arabic":
506
+ return "ar";
507
+ default:
508
+ return "en";
509
+ }
510
+ }
511
+ /**
512
+ * Check if text needs translation
513
+ */
514
+ needsTranslation(text, sourceLang, targetLang) {
515
+ if (!text || !text.trim()) return false;
516
+ if (isTechnicalContent(text)) return false;
517
+ if (sourceLang === targetLang) return false;
518
+ return true;
519
+ }
520
+ /**
521
+ * Translate single text
522
+ */
523
+ async translateText(text, targetLanguage, options) {
524
+ if (!text || !text.trim()) return text;
525
+ const sourceLang = options?.sourceLanguage ?? "auto";
526
+ const actualSource = sourceLang === "auto" ? this.detectLanguage(text) : sourceLang;
527
+ if (!this.needsTranslation(text, actualSource, targetLanguage)) {
528
+ return text;
529
+ }
530
+ const cached = this.cache.get(text, actualSource, targetLanguage);
531
+ if (cached) return cached;
532
+ const response = await this.client.chat(
533
+ `Translate this text to ${targetLanguage}. Return ONLY the translation:
534
+
535
+ ${text}`,
536
+ {
537
+ ...options,
538
+ model: options?.model ?? this.defaultModel,
539
+ temperature: 0
540
+ }
541
+ );
542
+ const translated = response.content.trim();
543
+ this.cache.set(text, actualSource, targetLanguage, translated);
544
+ return translated;
545
+ }
546
+ /**
547
+ * Translate JSON object with smart text-level caching
548
+ *
549
+ * @example
550
+ * ```ts
551
+ * const translator = new JsonTranslator(llm)
552
+ * const result = await translator.translate(
553
+ * { title: 'Hello', items: ['World', 'Earth'] },
554
+ * 'ru'
555
+ * )
556
+ * // { data: { title: 'Привет', items: ['Мир', 'Земля'] }, valid: true, ... }
557
+ * ```
558
+ */
559
+ async translate(data, targetLanguage, options) {
560
+ const sourceLang = options?.sourceLanguage ?? "auto";
561
+ const translatableTexts = this.extractTranslatableTexts(data, sourceLang, targetLanguage);
562
+ if (translatableTexts.size === 0) {
563
+ return {
564
+ data,
565
+ valid: true,
566
+ errors: [],
567
+ retries: 0,
568
+ sourceLanguage: sourceLang,
569
+ targetLanguage
570
+ };
571
+ }
572
+ let actualSource = sourceLang;
573
+ if (sourceLang === "auto") {
574
+ const firstText = [...translatableTexts][0];
575
+ actualSource = this.detectLanguage(firstText);
576
+ }
577
+ const { cached, uncached } = this.cache.getMany(
578
+ [...translatableTexts],
579
+ actualSource,
580
+ targetLanguage
581
+ );
582
+ if (uncached.length === 0) {
583
+ return {
584
+ data: this.applyTranslations(data, cached),
585
+ valid: true,
586
+ errors: [],
587
+ retries: 0,
588
+ sourceLanguage: actualSource,
589
+ targetLanguage
590
+ };
591
+ }
592
+ const partialJson = this.createPartialJson(data, new Set(uncached));
593
+ const jsonStr = JSON.stringify(partialJson, null, 2);
594
+ try {
595
+ const prompt = buildJsonTranslationPrompt(jsonStr, actualSource, targetLanguage);
596
+ const response = await this.client.chat(prompt, {
597
+ ...options,
598
+ model: options?.model ?? this.defaultModel,
599
+ temperature: 0
600
+ });
601
+ const translatedPartial = extractJson(response.content);
602
+ const newTranslations = this.extractTranslationsByComparison(
603
+ partialJson,
604
+ translatedPartial,
605
+ uncached
606
+ );
607
+ this.cache.setMany(newTranslations, actualSource, targetLanguage);
608
+ const allTranslations = new Map([...cached, ...newTranslations]);
609
+ return {
610
+ data: this.applyTranslations(data, allTranslations),
611
+ valid: true,
612
+ errors: [],
613
+ retries: 0,
614
+ sourceLanguage: actualSource,
615
+ targetLanguage
616
+ };
617
+ } catch (error) {
618
+ const errorMsg = error instanceof Error ? error.message : String(error);
619
+ console.error("Translation failed:", errorMsg);
620
+ return {
621
+ data: cached.size > 0 ? this.applyTranslations(data, cached) : data,
622
+ valid: false,
623
+ errors: [errorMsg],
624
+ retries: 0,
625
+ sourceLanguage: actualSource,
626
+ targetLanguage
627
+ };
628
+ }
629
+ }
630
+ /**
631
+ * Translate to multiple languages in parallel
632
+ */
633
+ async translateToMany(data, targetLanguages, options) {
634
+ const results = /* @__PURE__ */ new Map();
635
+ const promises = targetLanguages.map(async (lang) => {
636
+ const result = await this.translate(data, lang, options);
637
+ return { lang, result };
638
+ });
639
+ const settled = await Promise.all(promises);
640
+ for (const { lang, result } of settled) {
641
+ results.set(lang, result);
642
+ }
643
+ return results;
644
+ }
645
+ /**
646
+ * Extract all translatable texts from object
647
+ */
648
+ extractTranslatableTexts(obj, sourceLang, targetLang) {
649
+ const texts = /* @__PURE__ */ new Set();
650
+ const extract = (item) => {
651
+ if (typeof item === "string") {
652
+ if (this.needsTranslation(item, sourceLang, targetLang)) {
653
+ texts.add(item);
654
+ }
655
+ } else if (Array.isArray(item)) {
656
+ for (const i of item) extract(i);
657
+ } else if (item !== null && typeof item === "object") {
658
+ for (const v of Object.values(item)) extract(v);
659
+ }
660
+ };
661
+ extract(obj);
662
+ return texts;
663
+ }
664
+ /**
665
+ * Apply translations to object
666
+ */
667
+ applyTranslations(obj, translations) {
668
+ const apply = (item) => {
669
+ if (typeof item === "string") {
670
+ return translations.get(item) ?? item;
671
+ } else if (Array.isArray(item)) {
672
+ return item.map(apply);
673
+ } else if (item !== null && typeof item === "object") {
674
+ const result = {};
675
+ for (const [k, v] of Object.entries(item)) {
676
+ result[k] = apply(v);
677
+ }
678
+ return result;
679
+ }
680
+ return item;
681
+ };
682
+ return apply(obj);
683
+ }
684
+ /**
685
+ * Create partial JSON with only texts that need translation
686
+ */
687
+ createPartialJson(data, textsToInclude) {
688
+ const filter = (obj) => {
689
+ if (typeof obj === "string") {
690
+ return textsToInclude.has(obj) ? obj : "SKIP";
691
+ } else if (Array.isArray(obj)) {
692
+ return obj.map(filter).filter((i) => this.hasTranslatable(i, textsToInclude));
693
+ } else if (obj !== null && typeof obj === "object") {
694
+ const result = {};
695
+ for (const [k, v] of Object.entries(obj)) {
696
+ const filtered = filter(v);
697
+ if (this.hasTranslatable(filtered, textsToInclude)) {
698
+ result[k] = filtered;
699
+ }
700
+ }
701
+ return result;
702
+ }
703
+ return obj;
704
+ };
705
+ return filter(data);
706
+ }
707
+ /**
708
+ * Check if object contains translatable text
709
+ */
710
+ hasTranslatable(obj, textsSet) {
711
+ if (typeof obj === "string") return textsSet.has(obj);
712
+ if (Array.isArray(obj)) return obj.some((i) => this.hasTranslatable(i, textsSet));
713
+ if (obj !== null && typeof obj === "object") {
714
+ return Object.values(obj).some((v) => this.hasTranslatable(v, textsSet));
715
+ }
716
+ return false;
717
+ }
718
+ /**
719
+ * Extract translations by comparing original and translated JSON
720
+ */
721
+ extractTranslationsByComparison(original, translated, uncachedTexts) {
722
+ const translations = /* @__PURE__ */ new Map();
723
+ const uncachedSet = new Set(uncachedTexts);
724
+ const compare = (orig, trans) => {
725
+ if (typeof orig === "string" && typeof trans === "string") {
726
+ if (uncachedSet.has(orig) && trans !== "SKIP" && trans.trim()) {
727
+ translations.set(orig, trans);
728
+ }
729
+ } else if (Array.isArray(orig) && Array.isArray(trans)) {
730
+ for (let i = 0; i < Math.min(orig.length, trans.length); i++) {
731
+ compare(orig[i], trans[i]);
732
+ }
733
+ } else if (orig !== null && typeof orig === "object" && trans !== null && typeof trans === "object") {
734
+ for (const key of Object.keys(orig)) {
735
+ if (key in trans) {
736
+ compare(
737
+ orig[key],
738
+ trans[key]
739
+ );
740
+ }
741
+ }
742
+ }
743
+ };
744
+ compare(original, translated);
745
+ return translations;
746
+ }
747
+ /**
748
+ * Get translation statistics
749
+ */
750
+ getStats() {
751
+ return this.cache.getStats();
752
+ }
753
+ /**
754
+ * Clear translation cache
755
+ */
756
+ clearCache(sourceLang, targetLang) {
757
+ this.cache.clear(sourceLang, targetLang);
758
+ }
759
+ };
760
+ function createTranslator(client, configOrCache) {
761
+ if (configOrCache instanceof TranslationCache) {
762
+ return new JsonTranslator(client, configOrCache);
763
+ }
764
+ return new JsonTranslator(client, configOrCache?.cache, configOrCache?.model);
765
+ }
766
+
767
+ export { JsonTranslator, LANGUAGE_NAMES, TranslationCache, buildJsonTranslationPrompt, buildRetryPrompt, buildTextTranslationPrompt, containsArabic, containsCJK, containsCyrillic, createCache, createTranslator, detectScript, extractPlaceholders, extractTranslatableValues, getLanguageName, isTechnicalContent, validateJsonKeys, validatePlaceholders2 as validatePlaceholders, validatePlaceholders as validateTextPlaceholders, validateTranslation };
768
+ //# sourceMappingURL=index.mjs.map
769
+ //# sourceMappingURL=index.mjs.map