@lingo.dev/compiler 0.4.9 → 0.4.11

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.
package/README.md CHANGED
@@ -117,6 +117,7 @@ See `demo/new-compiler-next16` for the working example
117
117
  | `useDirective` | `boolean` | `false` | Whether to require `'use i18n'` directive |
118
118
  | `models` | `string \| Record<string, string>` | `"lingo.dev"` | Model configuration (see below) |
119
119
  | `prompt` | `string` | `undefined` | Custom translation prompt |
120
+ | `aiTimeout` | `number` | `120000` | Milliseconds to wait for a single AI translation request. Raise it for slow networks or large chunks |
120
121
  | `buildMode` | `"translate" \| "cache-only"` | `"translate"` | Build mode (see below) |
121
122
 
122
123
  ### Development Configuration
@@ -1,5 +1,17 @@
1
1
 
2
2
  //#region src/translators/api.ts
3
+ /**
4
+ * Thrown when a translation run fails partway through, carrying the entries
5
+ * that already came back. They have been paid for, so discarding them makes the
6
+ * next build request and pay for identical source text again.
7
+ */
8
+ var PartialTranslationError = class extends Error {
9
+ constructor(message, partialTranslations, cause) {
10
+ super(message, { cause });
11
+ this.partialTranslations = partialTranslations;
12
+ this.name = "PartialTranslationError";
13
+ }
14
+ };
3
15
  function dictionaryFrom(locale, entries) {
4
16
  return {
5
17
  version: .1,
@@ -9,4 +21,5 @@ function dictionaryFrom(locale, entries) {
9
21
  }
10
22
 
11
23
  //#endregion
24
+ exports.PartialTranslationError = PartialTranslationError;
12
25
  exports.dictionaryFrom = dictionaryFrom;
@@ -1,4 +1,16 @@
1
1
  //#region src/translators/api.ts
2
+ /**
3
+ * Thrown when a translation run fails partway through, carrying the entries
4
+ * that already came back. They have been paid for, so discarding them makes the
5
+ * next build request and pay for identical source text again.
6
+ */
7
+ var PartialTranslationError = class extends Error {
8
+ constructor(message, partialTranslations, cause) {
9
+ super(message, { cause });
10
+ this.partialTranslations = partialTranslations;
11
+ this.name = "PartialTranslationError";
12
+ }
13
+ };
2
14
  function dictionaryFrom(locale, entries) {
3
15
  return {
4
16
  version: .1,
@@ -8,5 +20,5 @@ function dictionaryFrom(locale, entries) {
8
20
  }
9
21
 
10
22
  //#endregion
11
- export { dictionaryFrom };
23
+ export { PartialTranslationError, dictionaryFrom };
12
24
  //# sourceMappingURL=api.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.mjs","names":[],"sources":["../../src/translators/api.ts"],"sourcesContent":["import type { LocaleCode } from \"lingo.dev/spec\";\n\nexport type TranslatableEntry = { text: string; context: Record<string, any> };\n\nexport interface Translator<Config> {\n config: Config;\n\n translate: (\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ) => Promise<Record<string, string>>;\n}\n\n/**\n * Dictionary schema for translation\n * Simple flat structure with direct access to translations\n */\nexport interface DictionarySchema {\n version: number;\n locale: LocaleCode;\n entries: Record<string, string>;\n}\n\nexport function dictionaryFrom(\n locale: LocaleCode,\n entries: DictionarySchema[\"entries\"],\n) {\n return {\n // TODO (AleksandrSl 14/12/2025): We do not use version anywhere.\n // We should either get rid of it, or start cheking it, e.g. if we updated the hash function we should nuke the caches. However, in this case we can tie version to the hash somewhat automatically by using hash function name\n version: 0.1,\n locale,\n entries,\n };\n}\n"],"mappings":";AAuBA,SAAgB,eACd,QACA,SACA;AACA,QAAO;EAGL,SAAS;EACT;EACA;EACD"}
1
+ {"version":3,"file":"api.mjs","names":["partialTranslations: Record<string, string>"],"sources":["../../src/translators/api.ts"],"sourcesContent":["import type { LocaleCode } from \"lingo.dev/spec\";\n\nexport type TranslatableEntry = { text: string; context: Record<string, any> };\n\nexport interface Translator<Config> {\n config: Config;\n\n translate: (\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ) => Promise<Record<string, string>>;\n}\n\n/**\n * Thrown when a translation run fails partway through, carrying the entries\n * that already came back. They have been paid for, so discarding them makes the\n * next build request and pay for identical source text again.\n */\nexport class PartialTranslationError extends Error {\n constructor(\n message: string,\n public readonly partialTranslations: Record<string, string>,\n cause: unknown,\n ) {\n super(message, { cause });\n this.name = \"PartialTranslationError\";\n }\n}\n\n/**\n * Dictionary schema for translation\n * Simple flat structure with direct access to translations\n */\nexport interface DictionarySchema {\n version: number;\n locale: LocaleCode;\n entries: Record<string, string>;\n}\n\nexport function dictionaryFrom(\n locale: LocaleCode,\n entries: DictionarySchema[\"entries\"],\n) {\n return {\n // TODO (AleksandrSl 14/12/2025): We do not use version anywhere.\n // We should either get rid of it, or start cheking it, e.g. if we updated the hash function we should nuke the caches. However, in this case we can tie version to the hash somewhat automatically by using hash function name\n version: 0.1,\n locale,\n entries,\n };\n}\n"],"mappings":";;;;;;AAkBA,IAAa,0BAAb,cAA6C,MAAM;CACjD,YACE,SACA,AAAgBA,qBAChB,OACA;AACA,QAAM,SAAS,EAAE,OAAO,CAAC;EAHT;AAIhB,OAAK,OAAO;;;AAchB,SAAgB,eACd,QACA,SACA;AACA,QAAO;EAGL,SAAS;EACT;EACA;EACD"}
@@ -37,14 +37,18 @@ var LingoTranslator = class {
37
37
  const chunks = this.chunkDictionary(sourceDictionary);
38
38
  this.logger.debug(`Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`);
39
39
  const translatedChunks = [];
40
- for (let i = 0; i < chunks.length; i++) {
41
- const chunk = chunks[i];
42
- this.logger.debug(`Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`);
43
- const chunkStartTime = performance.now();
44
- const translatedChunk = await this.translateChunk(chunk, targetLocale);
45
- const chunkEndTime = performance.now();
46
- this.logger.debug(`Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`);
47
- translatedChunks.push(translatedChunk);
40
+ try {
41
+ for (let i = 0; i < chunks.length; i++) {
42
+ const chunk = chunks[i];
43
+ this.logger.debug(`Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`);
44
+ const chunkStartTime = performance.now();
45
+ const translatedChunk = await this.translateChunk(chunk, targetLocale);
46
+ const chunkEndTime = performance.now();
47
+ this.logger.debug(`Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`);
48
+ translatedChunks.push(translatedChunk);
49
+ }
50
+ } catch (error) {
51
+ throw new require_api.PartialTranslationError(error instanceof Error ? error.message : String(error), this.mergeDictionaries(translatedChunks).entries, error);
48
52
  }
49
53
  const result = this.mergeDictionaries(translatedChunks);
50
54
  this.logger.debug(`Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`);
@@ -59,7 +63,7 @@ var LingoTranslator = class {
59
63
  }
60
64
  /**
61
65
  * Translate using Lingo.dev Engine
62
- * Times out after 60 seconds to prevent indefinite hangs
66
+ * Times out after `aiTimeout` to prevent indefinite hangs
63
67
  */
64
68
  async translateWithLingoDotDev(sourceDictionary, targetLocale) {
65
69
  const apiKey = this.validatedKeys["lingo.dev"];
@@ -70,7 +74,7 @@ var LingoTranslator = class {
70
74
  return await require_timeout.withTimeout(engine.localizeObject(sourceDictionary, {
71
75
  sourceLocale: this.config.sourceLocale,
72
76
  targetLocale
73
- }), require_timeout.DEFAULT_TIMEOUTS.AI_API, `Lingo.dev API translation to ${targetLocale}`);
77
+ }), this.config.aiTimeout ?? require_timeout.DEFAULT_TIMEOUTS.AI_API, `Lingo.dev API translation to ${targetLocale}`);
74
78
  } catch (error) {
75
79
  this.logger.error(`translateWithLingoDotDev() failed:`, error);
76
80
  throw new Error(`Lingo.dev translation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
@@ -78,7 +82,7 @@ var LingoTranslator = class {
78
82
  }
79
83
  /**
80
84
  * Translate using generic LLM
81
- * Times out after 60 seconds to prevent indefinite hangs
85
+ * Times out after `aiTimeout` to prevent indefinite hangs
82
86
  */
83
87
  async translateWithLLM(sourceDictionary, targetLocale) {
84
88
  const localeModel = require_model_factory.getLocaleModel(this.config.models, this.config.sourceLocale, targetLocale);
@@ -109,7 +113,7 @@ var LingoTranslator = class {
109
113
  content: require_parse_xml.obj2xml(sourceDictionary)
110
114
  }
111
115
  ]
112
- }), require_timeout.DEFAULT_TIMEOUTS.AI_API, `${localeModel.provider} LLM translation to ${targetLocale}`)).text);
116
+ }), this.config.aiTimeout ?? require_timeout.DEFAULT_TIMEOUTS.AI_API, `${localeModel.provider} LLM translation to ${targetLocale}`)).text);
113
117
  } catch (error) {
114
118
  throw new Error(`LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : "Unknown error"}`);
115
119
  }
@@ -1,4 +1,4 @@
1
- import { dictionaryFrom } from "../api.mjs";
1
+ import { PartialTranslationError, dictionaryFrom } from "../api.mjs";
2
2
  import { getSystemPrompt } from "./prompt.mjs";
3
3
  import { obj2xml, parseXmlFromResponseText } from "../parse-xml.mjs";
4
4
  import { shots } from "./shots.mjs";
@@ -36,14 +36,18 @@ var LingoTranslator = class {
36
36
  const chunks = this.chunkDictionary(sourceDictionary);
37
37
  this.logger.debug(`Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`);
38
38
  const translatedChunks = [];
39
- for (let i = 0; i < chunks.length; i++) {
40
- const chunk = chunks[i];
41
- this.logger.debug(`Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`);
42
- const chunkStartTime = performance.now();
43
- const translatedChunk = await this.translateChunk(chunk, targetLocale);
44
- const chunkEndTime = performance.now();
45
- this.logger.debug(`Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`);
46
- translatedChunks.push(translatedChunk);
39
+ try {
40
+ for (let i = 0; i < chunks.length; i++) {
41
+ const chunk = chunks[i];
42
+ this.logger.debug(`Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`);
43
+ const chunkStartTime = performance.now();
44
+ const translatedChunk = await this.translateChunk(chunk, targetLocale);
45
+ const chunkEndTime = performance.now();
46
+ this.logger.debug(`Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`);
47
+ translatedChunks.push(translatedChunk);
48
+ }
49
+ } catch (error) {
50
+ throw new PartialTranslationError(error instanceof Error ? error.message : String(error), this.mergeDictionaries(translatedChunks).entries, error);
47
51
  }
48
52
  const result = this.mergeDictionaries(translatedChunks);
49
53
  this.logger.debug(`Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`);
@@ -58,7 +62,7 @@ var LingoTranslator = class {
58
62
  }
59
63
  /**
60
64
  * Translate using Lingo.dev Engine
61
- * Times out after 60 seconds to prevent indefinite hangs
65
+ * Times out after `aiTimeout` to prevent indefinite hangs
62
66
  */
63
67
  async translateWithLingoDotDev(sourceDictionary, targetLocale) {
64
68
  const apiKey = this.validatedKeys["lingo.dev"];
@@ -69,7 +73,7 @@ var LingoTranslator = class {
69
73
  return await withTimeout(engine.localizeObject(sourceDictionary, {
70
74
  sourceLocale: this.config.sourceLocale,
71
75
  targetLocale
72
- }), DEFAULT_TIMEOUTS.AI_API, `Lingo.dev API translation to ${targetLocale}`);
76
+ }), this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API, `Lingo.dev API translation to ${targetLocale}`);
73
77
  } catch (error) {
74
78
  this.logger.error(`translateWithLingoDotDev() failed:`, error);
75
79
  throw new Error(`Lingo.dev translation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
@@ -77,7 +81,7 @@ var LingoTranslator = class {
77
81
  }
78
82
  /**
79
83
  * Translate using generic LLM
80
- * Times out after 60 seconds to prevent indefinite hangs
84
+ * Times out after `aiTimeout` to prevent indefinite hangs
81
85
  */
82
86
  async translateWithLLM(sourceDictionary, targetLocale) {
83
87
  const localeModel = getLocaleModel(this.config.models, this.config.sourceLocale, targetLocale);
@@ -108,7 +112,7 @@ var LingoTranslator = class {
108
112
  content: obj2xml(sourceDictionary)
109
113
  }
110
114
  ]
111
- }), DEFAULT_TIMEOUTS.AI_API, `${localeModel.provider} LLM translation to ${targetLocale}`)).text);
115
+ }), this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API, `${localeModel.provider} LLM translation to ${targetLocale}`)).text);
112
116
  } catch (error) {
113
117
  throw new Error(`LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : "Unknown error"}`);
114
118
  }
@@ -1 +1 @@
1
- {"version":3,"file":"translator.mjs","names":["config: LingoTranslatorConfig","logger: Logger","sourceDictionary: DictionarySchema","translatedChunks: DictionarySchema[]","chunks: DictionarySchema[]","mergedEntries: Record<string, string>"],"sources":["../../../src/translators/lingo/translator.ts"],"sourcesContent":["import { generateText } from \"ai\";\nimport { LingoDotDevEngine } from \"lingo.dev/sdk\";\nimport { dictionaryFrom, type DictionarySchema, type TranslatableEntry, type Translator, } from \"../api\";\nimport { getSystemPrompt } from \"./prompt\";\nimport { obj2xml, parseXmlFromResponseText } from \"../parse-xml\";\nimport { shots } from \"./shots\";\nimport { createAiModel, getLocaleModel, validateAndGetApiKeys, type ValidatedApiKeys, } from \"./model-factory\";\nimport { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\n/**\n * Lingo Translator configuration\n */\nexport interface LingoTranslatorConfig {\n models: \"lingo.dev\" | Record<string, string>;\n sourceLocale: LocaleCode;\n prompt?: string;\n}\n\n/**\n * Lingo translator using AI models\n */\nexport class LingoTranslator implements Translator<LingoTranslatorConfig> {\n private readonly validatedKeys: ValidatedApiKeys;\n\n constructor(\n readonly config: LingoTranslatorConfig,\n private logger: Logger,\n ) {\n this.logger.info(\"Validating API keys for translation...\");\n this.validatedKeys = validateAndGetApiKeys(config.models);\n this.logger.info(\"✅ API keys validated successfully\");\n }\n\n /**\n * Translate multiple entries\n */\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n this.logger.debug(\n `translate() called for ${locale} with ${Object.keys(entriesMap).length} entries`,\n );\n\n const sourceDictionary: DictionarySchema = dictionaryFrom(\n this.config.sourceLocale,\n Object.fromEntries(\n Object.entries(entriesMap).map(([hash, entry]) => [hash, entry.text]),\n ),\n );\n\n this.logger.debug(\n `Created source dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,\n );\n const translated = await this.translateDictionary(sourceDictionary, locale);\n\n return translated.entries || {};\n }\n\n /**\n * Translate a complete dictionary\n */\n private async translateDictionary(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const chunks = this.chunkDictionary(sourceDictionary);\n this.logger.debug(\n `Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`,\n );\n\n const translatedChunks: DictionarySchema[] = [];\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n this.logger.debug(\n `Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`,\n );\n const chunkStartTime = performance.now();\n\n const translatedChunk = await this.translateChunk(chunk, targetLocale);\n\n const chunkEndTime = performance.now();\n this.logger.debug(\n `Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`,\n );\n\n translatedChunks.push(translatedChunk);\n }\n\n const result = this.mergeDictionaries(translatedChunks);\n this.logger.debug(\n `Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`,\n );\n\n return result;\n }\n\n /**\n * Translate a single chunk\n */\n private async translateChunk(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n if (this.config.models === \"lingo.dev\") {\n return this.translateWithLingoDotDev(sourceDictionary, targetLocale);\n } else {\n return this.translateWithLLM(sourceDictionary, targetLocale);\n }\n }\n\n /**\n * Translate using Lingo.dev Engine\n * Times out after 60 seconds to prevent indefinite hangs\n */\n private async translateWithLingoDotDev(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const apiKey = this.validatedKeys[\"lingo.dev\"];\n if (!apiKey) {\n throw new Error(\n \"Internal error: Lingo.dev API key not found after validation. Please restart the service.\",\n );\n }\n\n this.logger.debug(\n `Using Lingo.dev Engine to localize from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const engine = new LingoDotDevEngine({ apiKey });\n\n try {\n const result = await withTimeout(\n engine.localizeObject(sourceDictionary, {\n sourceLocale: this.config.sourceLocale,\n targetLocale: targetLocale,\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Lingo.dev API translation to ${targetLocale}`,\n );\n\n return result as DictionarySchema;\n } catch (error) {\n this.logger.error(`translateWithLingoDotDev() failed:`, error);\n throw new Error(\n `Lingo.dev translation failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Translate using generic LLM\n * Times out after 60 seconds to prevent indefinite hangs\n */\n private async translateWithLLM(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const localeModel = getLocaleModel(\n this.config.models as Record<string, string>,\n this.config.sourceLocale,\n targetLocale,\n );\n\n if (!localeModel) {\n throw new Error(\n `No model configured for translation from ${this.config.sourceLocale} to ${targetLocale}`,\n );\n }\n\n this.logger.debug(\n `Using LLM (\"${localeModel.provider}\":\"${localeModel.name}\") to translate from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const aiModel = createAiModel(localeModel, this.validatedKeys);\n\n try {\n const response = await withTimeout(\n generateText({\n model: aiModel,\n messages: [\n {\n role: \"system\",\n content: getSystemPrompt({\n sourceLocale: this.config.sourceLocale,\n targetLocale,\n prompt: this.config.prompt,\n }),\n },\n // Add few-shot examples\n ...shots.flatMap((shotsTuple) => [\n {\n role: \"user\" as const,\n content: obj2xml(shotsTuple[0]),\n },\n {\n role: \"assistant\" as const,\n content: obj2xml(shotsTuple[1]),\n },\n ]),\n {\n role: \"user\",\n content: obj2xml(sourceDictionary),\n },\n ],\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `${localeModel.provider} LLM translation to ${targetLocale}`,\n );\n\n return parseXmlFromResponseText<DictionarySchema>(response.text);\n } catch (error) {\n throw new Error(\n `LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Split dictionary into chunks for processing\n */\n private chunkDictionary(dictionary: DictionarySchema): DictionarySchema[] {\n const MAX_ENTRIES_PER_CHUNK = 100;\n const { entries, ...rest } = dictionary;\n const chunks: DictionarySchema[] = [];\n\n const entryPairs = Object.entries(entries);\n\n // Split entries into chunks of MAX_ENTRIES_PER_CHUNK\n for (let i = 0; i < entryPairs.length; i += MAX_ENTRIES_PER_CHUNK) {\n const chunkEntries = entryPairs.slice(i, i + MAX_ENTRIES_PER_CHUNK);\n chunks.push({\n ...rest,\n entries: Object.fromEntries(chunkEntries),\n });\n }\n\n return chunks;\n }\n\n /**\n * Merge multiple dictionaries into one\n */\n private mergeDictionaries(\n dictionaries: DictionarySchema[],\n ): DictionarySchema {\n if (dictionaries.length === 0) {\n return dictionaryFrom(this.config.sourceLocale, {});\n }\n\n // Merge all entries from all dictionaries\n const mergedEntries: Record<string, string> = {};\n for (const dict of dictionaries) {\n Object.assign(mergedEntries, dict.entries);\n }\n\n return {\n version: dictionaries[0].version,\n locale: dictionaries[0].locale,\n entries: mergedEntries,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,IAAa,kBAAb,MAA0E;CACxE,AAAiB;CAEjB,YACE,AAASA,QACT,AAAQC,QACR;EAFS;EACD;AAER,OAAK,OAAO,KAAK,yCAAyC;AAC1D,OAAK,gBAAgB,sBAAsB,OAAO,OAAO;AACzD,OAAK,OAAO,KAAK,oCAAoC;;;;;CAMvD,MAAM,UACJ,QACA,YACiC;AACjC,OAAK,OAAO,MACV,0BAA0B,OAAO,QAAQ,OAAO,KAAK,WAAW,CAAC,OAAO,UACzE;EAED,MAAMC,mBAAqC,eACzC,KAAK,OAAO,cACZ,OAAO,YACL,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,MAAM,KAAK,CAAC,CACtE,CACF;AAED,OAAK,OAAO,MACV,k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BAAwB;EAC9B,MAAM,EAAE,SAAS,GAAG,SAAS;EAC7B,MAAMC,SAA6B,EAAE;EAErC,MAAM,aAAa,OAAO,QAAQ,QAAQ;AAG1C,OAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK,uBAAuB;GACjE,MAAM,eAAe,WAAW,MAAM,GAAG,IAAI,sBAAsB;AACnE,UAAO,KAAK;IACV,GAAG;IACH,SAAS,OAAO,YAAY,aAAa;IAC1C,CAAC;;AAGJ,SAAO;;;;;CAMT,AAAQ,kBACN,cACkB;AAClB,MAAI,aAAa,WAAW,EAC1B,QAAO,eAAe,KAAK,OAAO,cAAc,EAAE,CAAC;EAIrD,MAAMC,gBAAwC,EAAE;AAChD,OAAK,MAAM,QAAQ,aACjB,QAAO,OAAO,eAAe,KAAK,QAAQ;AAG5C,SAAO;GACL,SAAS,aAAa,GAAG;GACzB,QAAQ,aAAa,GAAG;GACxB,SAAS;GACV"}
1
+ {"version":3,"file":"translator.mjs","names":["config: LingoTranslatorConfig","logger: Logger","sourceDictionary: DictionarySchema","translatedChunks: DictionarySchema[]","chunks: DictionarySchema[]","mergedEntries: Record<string, string>"],"sources":["../../../src/translators/lingo/translator.ts"],"sourcesContent":["import { generateText } from \"ai\";\nimport { LingoDotDevEngine } from \"lingo.dev/sdk\";\nimport { dictionaryFrom, PartialTranslationError, type DictionarySchema, type TranslatableEntry, type Translator, } from \"../api\";\nimport { getSystemPrompt } from \"./prompt\";\nimport { obj2xml, parseXmlFromResponseText } from \"../parse-xml\";\nimport { shots } from \"./shots\";\nimport { createAiModel, getLocaleModel, validateAndGetApiKeys, type ValidatedApiKeys, } from \"./model-factory\";\nimport { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\n/**\n * Lingo Translator configuration\n */\nexport interface LingoTranslatorConfig {\n models: \"lingo.dev\" | Record<string, string>;\n sourceLocale: LocaleCode;\n prompt?: string;\n aiTimeout?: number;\n}\n\n/**\n * Lingo translator using AI models\n */\nexport class LingoTranslator implements Translator<LingoTranslatorConfig> {\n private readonly validatedKeys: ValidatedApiKeys;\n\n constructor(\n readonly config: LingoTranslatorConfig,\n private logger: Logger,\n ) {\n this.logger.info(\"Validating API keys for translation...\");\n this.validatedKeys = validateAndGetApiKeys(config.models);\n this.logger.info(\"✅ API keys validated successfully\");\n }\n\n /**\n * Translate multiple entries\n */\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n this.logger.debug(\n `translate() called for ${locale} with ${Object.keys(entriesMap).length} entries`,\n );\n\n const sourceDictionary: DictionarySchema = dictionaryFrom(\n this.config.sourceLocale,\n Object.fromEntries(\n Object.entries(entriesMap).map(([hash, entry]) => [hash, entry.text]),\n ),\n );\n\n this.logger.debug(\n `Created source dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,\n );\n const translated = await this.translateDictionary(sourceDictionary, locale);\n\n return translated.entries || {};\n }\n\n /**\n * Translate a complete dictionary\n */\n private async translateDictionary(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const chunks = this.chunkDictionary(sourceDictionary);\n this.logger.debug(\n `Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`,\n );\n\n const translatedChunks: DictionarySchema[] = [];\n\n try {\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n this.logger.debug(\n `Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`,\n );\n const chunkStartTime = performance.now();\n\n const translatedChunk = await this.translateChunk(chunk, targetLocale);\n\n const chunkEndTime = performance.now();\n this.logger.debug(\n `Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`,\n );\n\n translatedChunks.push(translatedChunk);\n }\n } catch (error) {\n throw new PartialTranslationError(\n error instanceof Error ? error.message : String(error),\n this.mergeDictionaries(translatedChunks).entries,\n error,\n );\n }\n\n const result = this.mergeDictionaries(translatedChunks);\n this.logger.debug(\n `Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`,\n );\n\n return result;\n }\n\n /**\n * Translate a single chunk\n */\n private async translateChunk(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n if (this.config.models === \"lingo.dev\") {\n return this.translateWithLingoDotDev(sourceDictionary, targetLocale);\n } else {\n return this.translateWithLLM(sourceDictionary, targetLocale);\n }\n }\n\n /**\n * Translate using Lingo.dev Engine\n * Times out after `aiTimeout` to prevent indefinite hangs\n */\n private async translateWithLingoDotDev(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const apiKey = this.validatedKeys[\"lingo.dev\"];\n if (!apiKey) {\n throw new Error(\n \"Internal error: Lingo.dev API key not found after validation. Please restart the service.\",\n );\n }\n\n this.logger.debug(\n `Using Lingo.dev Engine to localize from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const engine = new LingoDotDevEngine({ apiKey });\n\n try {\n const result = await withTimeout(\n engine.localizeObject(sourceDictionary, {\n sourceLocale: this.config.sourceLocale,\n targetLocale: targetLocale,\n }),\n this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API,\n `Lingo.dev API translation to ${targetLocale}`,\n );\n\n return result as DictionarySchema;\n } catch (error) {\n this.logger.error(`translateWithLingoDotDev() failed:`, error);\n throw new Error(\n `Lingo.dev translation failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Translate using generic LLM\n * Times out after `aiTimeout` to prevent indefinite hangs\n */\n private async translateWithLLM(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const localeModel = getLocaleModel(\n this.config.models as Record<string, string>,\n this.config.sourceLocale,\n targetLocale,\n );\n\n if (!localeModel) {\n throw new Error(\n `No model configured for translation from ${this.config.sourceLocale} to ${targetLocale}`,\n );\n }\n\n this.logger.debug(\n `Using LLM (\"${localeModel.provider}\":\"${localeModel.name}\") to translate from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const aiModel = createAiModel(localeModel, this.validatedKeys);\n\n try {\n const response = await withTimeout(\n generateText({\n model: aiModel,\n messages: [\n {\n role: \"system\",\n content: getSystemPrompt({\n sourceLocale: this.config.sourceLocale,\n targetLocale,\n prompt: this.config.prompt,\n }),\n },\n // Add few-shot examples\n ...shots.flatMap((shotsTuple) => [\n {\n role: \"user\" as const,\n content: obj2xml(shotsTuple[0]),\n },\n {\n role: \"assistant\" as const,\n content: obj2xml(shotsTuple[1]),\n },\n ]),\n {\n role: \"user\",\n content: obj2xml(sourceDictionary),\n },\n ],\n }),\n this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API,\n `${localeModel.provider} LLM translation to ${targetLocale}`,\n );\n\n return parseXmlFromResponseText<DictionarySchema>(response.text);\n } catch (error) {\n throw new Error(\n `LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Split dictionary into chunks for processing\n */\n private chunkDictionary(dictionary: DictionarySchema): DictionarySchema[] {\n const MAX_ENTRIES_PER_CHUNK = 100;\n const { entries, ...rest } = dictionary;\n const chunks: DictionarySchema[] = [];\n\n const entryPairs = Object.entries(entries);\n\n // Split entries into chunks of MAX_ENTRIES_PER_CHUNK\n for (let i = 0; i < entryPairs.length; i += MAX_ENTRIES_PER_CHUNK) {\n const chunkEntries = entryPairs.slice(i, i + MAX_ENTRIES_PER_CHUNK);\n chunks.push({\n ...rest,\n entries: Object.fromEntries(chunkEntries),\n });\n }\n\n return chunks;\n }\n\n /**\n * Merge multiple dictionaries into one\n */\n private mergeDictionaries(\n dictionaries: DictionarySchema[],\n ): DictionarySchema {\n if (dictionaries.length === 0) {\n return dictionaryFrom(this.config.sourceLocale, {});\n }\n\n // Merge all entries from all dictionaries\n const mergedEntries: Record<string, string> = {};\n for (const dict of dictionaries) {\n Object.assign(mergedEntries, dict.entries);\n }\n\n return {\n version: dictionaries[0].version,\n locale: dictionaries[0].locale,\n entries: mergedEntries,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,IAAa,kBAAb,MAA0E;CACxE,AAAiB;CAEjB,YACE,AAASA,QACT,AAAQC,QACR;EAFS;EACD;AAER,OAAK,OAAO,KAAK,yCAAyC;AAC1D,OAAK,gBAAgB,sBAAsB,OAAO,OAAO;AACzD,OAAK,OAAO,KAAK,oCAAoC;;;;;CAMvD,MAAM,UACJ,QACA,YACiC;AACjC,OAAK,OAAO,MACV,0BAA0B,OAAO,QAAQ,OAAO,KAAK,WAAW,CAAC,OAAO,UACzE;EAED,MAAMC,mBAAqC,eACzC,KAAK,OAAO,cACZ,OAAO,YACL,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,MAAM,KAAK,CAAC,CACtE,CACF;AAED,OAAK,OAAO,MACV,kCAAkC,OAAO,KAAK,iBAAiB,QAAQ,CAAC,OAAO,UAChF;AAGD,UAFmB,MAAM,KAAK,oBAAoB,kBAAkB,OAAO,EAEzD,WAAW,EAAE;;;;;CAMjC,MAAc,oBACZ,kBACA,cAC2B;EAC3B,MAAM,SAAS,KAAK,gBAAgB,iBAAiB;AACrD,OAAK,OAAO,MACV,yBAAyB,OAAO,KAAK,iBAAiB,QAAQ,CAAC,OAAO,QAAQ,OAAO,OAAO,SAC7F;EAED,MAAMC,mBAAuC,EAAE;AAE/C,MAAI;AACF,QAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;IACtC,MAAM,QAAQ,OAAO;AACrB,SAAK,OAAO,MACV,qBAAqB,IAAI,EAAE,GAAG,OAAO,OAAO,QAAQ,OAAO,KAAK,MAAM,QAAQ,CAAC,OAAO,UACvF;IACD,MAAM,iBAAiB,YAAY,KAAK;IAExC,MAAM,kBAAkB,MAAM,KAAK,eAAe,OAAO,aAA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EAAE;AAChD,OAAK,MAAM,QAAQ,aACjB,QAAO,OAAO,eAAe,KAAK,QAAQ;AAG5C,SAAO;GACL,SAAS,aAAa,GAAG;GACzB,QAAQ,aAAa,GAAG;GACxB,SAAS;GACV"}
@@ -17,12 +17,14 @@ var PluralizationService = class {
17
17
  cache = /* @__PURE__ */ new Map();
18
18
  prompt;
19
19
  sourceLocale;
20
+ aiTimeout;
20
21
  constructor(config, logger) {
21
22
  this.logger = logger;
22
23
  const localeModel = require_model_factory.parseModelString(config.model);
23
24
  if (!localeModel) throw new Error(`Invalid model format in pluralization service: "${config.model}"`);
24
25
  this.languageModel = require_model_factory.createAiModel(localeModel, require_model_factory.validateAndGetApiKeys({ "*:*": config.model }));
25
26
  this.sourceLocale = config.sourceLocale;
27
+ this.aiTimeout = config.aiTimeout;
26
28
  this.prompt = require_prompt.getSystemPrompt({ sourceLocale: config.sourceLocale });
27
29
  this.logger.debug(`Initialized pluralization service with ${localeModel.provider}:${localeModel.name}`);
28
30
  }
@@ -89,7 +91,7 @@ var PluralizationService = class {
89
91
  content: require_parse_xml.obj2xml(batchRequest)
90
92
  }
91
93
  ]
92
- }), require_timeout.DEFAULT_TIMEOUTS.AI_API * 2, `Pluralization with ${this.languageModel}`)).text.trim();
94
+ }), (this.aiTimeout ?? require_timeout.DEFAULT_TIMEOUTS.AI_API) * 2, `Pluralization with ${this.languageModel}`)).text.trim();
93
95
  this.logger.debug(`LLM XML response: ${responseText.substring(0, 200)}...`);
94
96
  const parsed = require_parse_xml.parseXmlFromResponseText(responseText);
95
97
  const resultArray = Array.isArray(parsed.results.result) ? parsed.results.result : [parsed.results.result];
@@ -16,12 +16,14 @@ var PluralizationService = class {
16
16
  cache = /* @__PURE__ */ new Map();
17
17
  prompt;
18
18
  sourceLocale;
19
+ aiTimeout;
19
20
  constructor(config, logger) {
20
21
  this.logger = logger;
21
22
  const localeModel = parseModelString(config.model);
22
23
  if (!localeModel) throw new Error(`Invalid model format in pluralization service: "${config.model}"`);
23
24
  this.languageModel = createAiModel(localeModel, validateAndGetApiKeys({ "*:*": config.model }));
24
25
  this.sourceLocale = config.sourceLocale;
26
+ this.aiTimeout = config.aiTimeout;
25
27
  this.prompt = getSystemPrompt({ sourceLocale: config.sourceLocale });
26
28
  this.logger.debug(`Initialized pluralization service with ${localeModel.provider}:${localeModel.name}`);
27
29
  }
@@ -88,7 +90,7 @@ var PluralizationService = class {
88
90
  content: obj2xml(batchRequest)
89
91
  }
90
92
  ]
91
- }), DEFAULT_TIMEOUTS.AI_API * 2, `Pluralization with ${this.languageModel}`)).text.trim();
93
+ }), (this.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API) * 2, `Pluralization with ${this.languageModel}`)).text.trim();
92
94
  this.logger.debug(`LLM XML response: ${responseText.substring(0, 200)}...`);
93
95
  const parsed = parseXmlFromResponseText(responseText);
94
96
  const resultArray = Array.isArray(parsed.results.result) ? parsed.results.result : [parsed.results.result];
@@ -1 +1 @@
1
- {"version":3,"file":"service.mjs","names":["logger: Logger","batchRequest: PluralizationBatch"],"sources":["../../../src/translators/pluralization/service.ts"],"sourcesContent":["/**\n * Pluralization service with batching and caching\n */\n\nimport type { LanguageModel } from \"ai\";\nimport { generateText } from \"ai\";\nimport type {\n ICUGenerationResult,\n PluralCandidate,\n PluralizationBatch,\n PluralizationConfig,\n PluralizationResponse,\n PluralizationStats,\n} from \"./types\";\nimport {\n createAiModel,\n parseModelString,\n validateAndGetApiKeys,\n} from \"../lingo/model-factory\";\nimport { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { getSystemPrompt } from \"./prompt\";\nimport { obj2xml, parseXmlFromResponseText } from \"../parse-xml\";\nimport { shots } from \"./shots\";\nimport type { MetadataSchema } from \"../../types\";\nimport { detectPluralCandidates } from \"./pattern-detector\";\nimport { validateICU } from \"./icu-validator\";\n\n/**\n * Pluralization service with batching and model reuse\n */\nexport class PluralizationService {\n private readonly languageModel: LanguageModel;\n private cache = new Map<string, ICUGenerationResult>();\n private readonly prompt: string;\n private readonly sourceLocale: string;\n\n constructor(\n config: PluralizationConfig,\n private logger: Logger,\n ) {\n const localeModel = parseModelString(config.model);\n if (!localeModel) {\n throw new Error(\n `Invalid model format in pluralization service: \"${config.model}\"`,\n );\n }\n\n // Validate and fetch API keys for the pluralization provider\n // We need to create a models config that validateAndFetchApiKeys can use\n const modelsConfig: Record<string, string> = {\n \"*:*\": config.model,\n };\n\n const validatedKeys = validateAndGetApiKeys(modelsConfig);\n\n this.languageModel = createAiModel(localeModel, validatedKeys);\n this.sourceLocale = config.sourceLocale;\n this.prompt = getSystemPrompt({ sourceLocale: config.sourceLocale });\n\n this.logger.debug(\n `Initialized pluralization service with ${localeModel.provider}:${localeModel.name}`,\n );\n }\n\n /**\n * Generate ICU formats for multiple candidates in a single batch\n *\n * @param candidates Array of plural candidates\n * @param batchSize Maximum candidates per batch (default: 10)\n * @returns Map of hash -> ICU generation result\n */\n async generateBatch(\n candidates: PluralCandidate[],\n batchSize: number = 10,\n ): Promise<Map<string, ICUGenerationResult>> {\n const { uncachedCandidates, results } = candidates.reduce(\n (acc, c) => {\n const cached = this.cache.get(c.hash);\n if (cached) {\n acc.results.set(c.hash, cached);\n } else {\n acc.uncachedCandidates.push(c);\n }\n return acc;\n },\n {\n uncachedCandidates: [] as PluralCandidate[],\n results: new Map<string, ICUGenerationResult>(),\n },\n );\n\n if (uncachedCandidates.length === 0) {\n return results;\n }\n\n this.logger.debug(\n `Processing ${uncachedCandidates.length} candidates (${candidates.length - uncachedCandidates.length} cached)`,\n );\n\n // Process in batches\n for (let i = 0; i < uncachedCandidates.length; i += batchSize) {\n const batch = uncachedCandidates.slice(i, i + batchSize);\n\n this.logger.debug(\n `Processing batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(uncachedCandidates.length / batchSize)} (${batch.length} candidates)`,\n );\n\n const batchResults = await this.processBatch(batch);\n\n // Store results and cache them\n for (const [hash, result] of batchResults) {\n results.set(hash, result);\n this.cache.set(hash, result);\n }\n }\n\n return results;\n }\n\n /**\n * Process a single batch of candidates\n */\n private async processBatch(\n candidates: PluralCandidate[],\n ): Promise<Map<string, ICUGenerationResult>> {\n const results = new Map<string, ICUGenerationResult>();\n\n try {\n // Prepare batch request in XML format\n const batchRequest: PluralizationBatch = {\n version: 0.1,\n sourceLocale: this.sourceLocale,\n candidates: {\n candidate: candidates.map((c) => ({\n hash: c.hash,\n text: c.sourceText,\n })),\n },\n };\n\n // Call LLM with XML format and few-shot examples\n const response = await withTimeout(\n generateText({\n model: this.languageModel,\n messages: [\n {\n role: \"system\",\n content: this.prompt,\n },\n // Add few-shot examples\n ...shots.flatMap((shotsTuple) => [\n {\n role: \"user\" as const,\n content: obj2xml(shotsTuple[0]),\n },\n {\n role: \"assistant\" as const,\n content: obj2xml(shotsTuple[1]),\n },\n ]),\n {\n role: \"user\",\n content: obj2xml(batchRequest),\n },\n ],\n }),\n DEFAULT_TIMEOUTS.AI_API * 2, // Double timeout for batch\n `Pluralization with ${this.languageModel}`,\n );\n\n const responseText = response.text.trim();\n this.logger.debug(\n `LLM XML response: ${responseText.substring(0, 200)}...`,\n );\n // Parse XML response\n const parsed =\n parseXmlFromResponseText<PluralizationResponse>(responseText);\n\n // Process results\n const resultArray = Array.isArray(parsed.results.result)\n ? parsed.results.result\n : [parsed.results.result];\n\n for (const result of resultArray) {\n const candidate = candidates.find((c) => c.hash === result.hash);\n if (!candidate) {\n this.logger.warn(`No candidate found for hash: ${result.hash}`);\n continue;\n }\n\n if (result.shouldPluralize && result.icuText) {\n this.logger.debug(\n `✓ ICU format generated for \"${candidate.sourceText}\": \"${result.icuText}\"`,\n );\n results.set(result.hash, {\n success: true,\n icuText: result.icuText,\n reasoning: result.reasoning,\n });\n } else {\n this.logger.debug(\n `✗ Pluralization not appropriate for \"${candidate.sourceText}\": ${result.reasoning}`,\n );\n results.set(result.hash, {\n success: false,\n reasoning: result.reasoning,\n });\n }\n }\n\n // Handle missing results (LLM didn't return result for some candidates)\n for (const candidate of candidates) {\n if (!results.has(candidate.hash)) {\n this.logger.warn(\n `No result returned for a candidate: ${candidate.sourceText}`,\n );\n results.set(candidate.hash, {\n success: false,\n error: \"No result returned by LLM\",\n });\n }\n }\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : \"Unknown error\";\n this.logger.error(`Failed to process batch: ${errorMsg}`);\n\n // Mark all candidates as failed\n for (const candidate of candidates) {\n results.set(candidate.hash, {\n success: false,\n error: errorMsg,\n });\n }\n }\n\n return results;\n }\n\n /**\n * Process metadata entries for pluralization\n *\n * This is the main entry point that:\n * 1. Detects plural candidates using pattern matching\n * 2. Generates ICU format using LLM (batched)\n * 3. Validates the ICU format\n * 4. Updates metadata entries in-place (modifies sourceText)\n * 5. Returns statistics\n * @param metadata Metadata schema with translation entries\n\n * @returns Statistics about the pluralization process\n */\n async process(metadata: MetadataSchema): Promise<PluralizationStats> {\n const startTime = performance.now();\n const totalEntries = Object.keys(metadata).length;\n\n if (totalEntries === 0) {\n return {\n total: 0,\n candidates: 0,\n pluralized: 0,\n rejected: 0,\n failed: 0,\n durationMs: 0,\n };\n }\n\n this.logger.debug(\n `Starting pluralization processing for ${totalEntries} entries`,\n );\n\n // Step 1: Detect plural candidates using pattern matching\n const entriesMap: Record<string, string> = Object.fromEntries(\n Object.entries(metadata).map(([hash, entry]) => [hash, entry.sourceText]),\n );\n\n const candidates = detectPluralCandidates(entriesMap, this.logger);\n\n this.logger.debug(\n `Found ${candidates.length} plural candidates (${((candidates.length / totalEntries) * 100).toFixed(1)}%)`,\n );\n\n if (candidates.length === 0) {\n const endTime = performance.now();\n return {\n total: totalEntries,\n candidates: 0,\n pluralized: 0,\n rejected: 0,\n failed: 0,\n durationMs: endTime - startTime,\n };\n }\n\n // Step 2: Generate ICU formats with batching\n this.logger.debug(\"Generating ICU formats with batching...\");\n const icuResults = await this.generateBatch(candidates, 10);\n\n // Step 3: Validate and update metadata entries\n this.logger.debug(\"Validating and updating entries...\");\n let pluralized = 0;\n let rejected = 0;\n let failed = 0;\n\n for (const candidate of candidates) {\n const result = icuResults.get(candidate.hash);\n const entry = metadata[candidate.hash];\n this.logger.debug(`Processing candidate: ${candidate.sourceText}`);\n if (!entry) {\n this.logger.warn(`Entry not found for hash: ${candidate.hash}`);\n failed++;\n continue;\n }\n\n if (!result) {\n this.logger.warn(`No result for hash: ${candidate.hash}`);\n failed++;\n continue;\n }\n\n if (result.error) {\n this.logger.warn(\n `Error generating ICU for \"${candidate.sourceText}\": ${result.error}`,\n );\n failed++;\n continue;\n }\n\n if (!result.success || !result.icuText) {\n this.logger.debug(\n `Rejected pluralization for \"${candidate.sourceText}\": ${result.reasoning}`,\n );\n rejected++;\n continue;\n }\n\n const isValid = validateICU(\n result.icuText,\n candidate.sourceText,\n this.logger,\n );\n\n if (!isValid) {\n this.logger.warn(\n `Invalid ICU format generated for \"${candidate.sourceText}\", falling back to original`,\n );\n failed++;\n continue;\n }\n\n this.logger.debug(\n `Pluralizing: \"${entry.sourceText}\" -> \"${result.icuText}\"`,\n );\n entry.sourceText = result.icuText;\n pluralized++;\n }\n\n const endTime = performance.now();\n const duration = endTime - startTime;\n\n this.logger.debug(\n `Pluralization completed: ${pluralized} pluralized, ${rejected} rejected, ${failed} failed in ${duration.toFixed(0)}ms`,\n );\n\n return {\n total: totalEntries,\n candidates: candidates.length,\n pluralized,\n rejected,\n failed,\n durationMs: duration,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,IAAa,uBAAb,MAAkC;CAChC,AAAiB;CACjB,AAAQ,wBAAQ,IAAI,KAAkC;CACtD,AAAiB;CACjB,AAAiB;CAEjB,YACE,QACA,AAAQA,QACR;EADQ;EAER,MAAM,cAAc,iBAAiB,OAAO,MAAM;AAClD,MAAI,CAAC,YACH,OAAM,IAAI,MACR,mDAAmD,OAAO,MAAM,GACjE;AAWH,OAAK,gBAAgB,cAAc,aAFb,sBAJuB,EAC3C,OAAO,OAAO,OACf,CAEwD,CAEK;AAC9D,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B,UAAU,OAAO;AAC/D;AACA;;AAGF,OAAI,CAAC,QAAQ;AACX,SAAK,OAAO,KAAK,uBAAuB,UAAU,OAAO;AACzD;AACA;;AAGF,OAAI,OAAO,OAAO;AAChB,SAAK,OAAO,KACV,6BAA6B,UAAU,WAAW,KAAK,OAAO,QAC/D;AACD;AACA;;AAGF,OAAI,CAAC,OAAO,WAAW,CAAC,OAAO,SAAS;AACtC,SAAK,OAAO,MACV,+BAA+B,UAAU,WAAW,KAAK,OAAO,YACjE;AACD;AACA;;AASF,OAAI,CANY,YACd,OAAO,SACP,UAAU,YACV,KAAK,OACN,EAEa;AACZ,SAAK,OAAO,KACV,qCAAqC,UAAU,WAAW,6BAC3D;AACD;AACA;;AAGF,QAAK,OAAO,MACV,iBAAiB,MAAM,WAAW,QAAQ,OAAO,QAAQ,GAC1D;AACD,SAAM,aAAa,OAAO;AAC1B;;EAIF,MAAM,WADU,YAAY,KAAK,GACN;AAE3B,OAAK,OAAO,MACV,4BAA4B,WAAW,eAAe,SAAS,aAAa,OAAO,aAAa,SAAS,QAAQ,EAAE,CAAC,IACrH;AAED,SAAO;GACL,OAAO;GACP,YAAY,WAAW;GACvB;GACA;GACA;GACA,YAAY;GACb"}
1
+ {"version":3,"file":"service.mjs","names":["logger: Logger","batchRequest: PluralizationBatch"],"sources":["../../../src/translators/pluralization/service.ts"],"sourcesContent":["/**\n * Pluralization service with batching and caching\n */\n\nimport type { LanguageModel } from \"ai\";\nimport { generateText } from \"ai\";\nimport type {\n ICUGenerationResult,\n PluralCandidate,\n PluralizationBatch,\n PluralizationConfig,\n PluralizationResponse,\n PluralizationStats,\n} from \"./types\";\nimport {\n createAiModel,\n parseModelString,\n validateAndGetApiKeys,\n} from \"../lingo/model-factory\";\nimport { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { getSystemPrompt } from \"./prompt\";\nimport { obj2xml, parseXmlFromResponseText } from \"../parse-xml\";\nimport { shots } from \"./shots\";\nimport type { MetadataSchema } from \"../../types\";\nimport { detectPluralCandidates } from \"./pattern-detector\";\nimport { validateICU } from \"./icu-validator\";\n\n/**\n * Pluralization service with batching and model reuse\n */\nexport class PluralizationService {\n private readonly languageModel: LanguageModel;\n private cache = new Map<string, ICUGenerationResult>();\n private readonly prompt: string;\n private readonly sourceLocale: string;\n private readonly aiTimeout: number | undefined;\n\n constructor(\n config: PluralizationConfig,\n private logger: Logger,\n ) {\n const localeModel = parseModelString(config.model);\n if (!localeModel) {\n throw new Error(\n `Invalid model format in pluralization service: \"${config.model}\"`,\n );\n }\n\n // Validate and fetch API keys for the pluralization provider\n // We need to create a models config that validateAndFetchApiKeys can use\n const modelsConfig: Record<string, string> = {\n \"*:*\": config.model,\n };\n\n const validatedKeys = validateAndGetApiKeys(modelsConfig);\n\n this.languageModel = createAiModel(localeModel, validatedKeys);\n this.sourceLocale = config.sourceLocale;\n this.aiTimeout = config.aiTimeout;\n this.prompt = getSystemPrompt({ sourceLocale: config.sourceLocale });\n\n this.logger.debug(\n `Initialized pluralization service with ${localeModel.provider}:${localeModel.name}`,\n );\n }\n\n /**\n * Generate ICU formats for multiple candidates in a single batch\n *\n * @param candidates Array of plural candidates\n * @param batchSize Maximum candidates per batch (default: 10)\n * @returns Map of hash -> ICU generation result\n */\n async generateBatch(\n candidates: PluralCandidate[],\n batchSize: number = 10,\n ): Promise<Map<string, ICUGenerationResult>> {\n const { uncachedCandidates, results } = candidates.reduce(\n (acc, c) => {\n const cached = this.cache.get(c.hash);\n if (cached) {\n acc.results.set(c.hash, cached);\n } else {\n acc.uncachedCandidates.push(c);\n }\n return acc;\n },\n {\n uncachedCandidates: [] as PluralCandidate[],\n results: new Map<string, ICUGenerationResult>(),\n },\n );\n\n if (uncachedCandidates.length === 0) {\n return results;\n }\n\n this.logger.debug(\n `Processing ${uncachedCandidates.length} candidates (${candidates.length - uncachedCandidates.length} cached)`,\n );\n\n // Process in batches\n for (let i = 0; i < uncachedCandidates.length; i += batchSize) {\n const batch = uncachedCandidates.slice(i, i + batchSize);\n\n this.logger.debug(\n `Processing batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(uncachedCandidates.length / batchSize)} (${batch.length} candidates)`,\n );\n\n const batchResults = await this.processBatch(batch);\n\n // Store results and cache them\n for (const [hash, result] of batchResults) {\n results.set(hash, result);\n this.cache.set(hash, result);\n }\n }\n\n return results;\n }\n\n /**\n * Process a single batch of candidates\n */\n private async processBatch(\n candidates: PluralCandidate[],\n ): Promise<Map<string, ICUGenerationResult>> {\n const results = new Map<string, ICUGenerationResult>();\n\n try {\n // Prepare batch request in XML format\n const batchRequest: PluralizationBatch = {\n version: 0.1,\n sourceLocale: this.sourceLocale,\n candidates: {\n candidate: candidates.map((c) => ({\n hash: c.hash,\n text: c.sourceText,\n })),\n },\n };\n\n // Call LLM with XML format and few-shot examples\n const response = await withTimeout(\n generateText({\n model: this.languageModel,\n messages: [\n {\n role: \"system\",\n content: this.prompt,\n },\n // Add few-shot examples\n ...shots.flatMap((shotsTuple) => [\n {\n role: \"user\" as const,\n content: obj2xml(shotsTuple[0]),\n },\n {\n role: \"assistant\" as const,\n content: obj2xml(shotsTuple[1]),\n },\n ]),\n {\n role: \"user\",\n content: obj2xml(batchRequest),\n },\n ],\n }),\n (this.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API) * 2, // Double timeout for batch\n `Pluralization with ${this.languageModel}`,\n );\n\n const responseText = response.text.trim();\n this.logger.debug(\n `LLM XML response: ${responseText.substring(0, 200)}...`,\n );\n // Parse XML response\n const parsed =\n parseXmlFromResponseText<PluralizationResponse>(responseText);\n\n // Process results\n const resultArray = Array.isArray(parsed.results.result)\n ? parsed.results.result\n : [parsed.results.result];\n\n for (const result of resultArray) {\n const candidate = candidates.find((c) => c.hash === result.hash);\n if (!candidate) {\n this.logger.warn(`No candidate found for hash: ${result.hash}`);\n continue;\n }\n\n if (result.shouldPluralize && result.icuText) {\n this.logger.debug(\n `✓ ICU format generated for \"${candidate.sourceText}\": \"${result.icuText}\"`,\n );\n results.set(result.hash, {\n success: true,\n icuText: result.icuText,\n reasoning: result.reasoning,\n });\n } else {\n this.logger.debug(\n `✗ Pluralization not appropriate for \"${candidate.sourceText}\": ${result.reasoning}`,\n );\n results.set(result.hash, {\n success: false,\n reasoning: result.reasoning,\n });\n }\n }\n\n // Handle missing results (LLM didn't return result for some candidates)\n for (const candidate of candidates) {\n if (!results.has(candidate.hash)) {\n this.logger.warn(\n `No result returned for a candidate: ${candidate.sourceText}`,\n );\n results.set(candidate.hash, {\n success: false,\n error: \"No result returned by LLM\",\n });\n }\n }\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : \"Unknown error\";\n this.logger.error(`Failed to process batch: ${errorMsg}`);\n\n // Mark all candidates as failed\n for (const candidate of candidates) {\n results.set(candidate.hash, {\n success: false,\n error: errorMsg,\n });\n }\n }\n\n return results;\n }\n\n /**\n * Process metadata entries for pluralization\n *\n * This is the main entry point that:\n * 1. Detects plural candidates using pattern matching\n * 2. Generates ICU format using LLM (batched)\n * 3. Validates the ICU format\n * 4. Updates metadata entries in-place (modifies sourceText)\n * 5. Returns statistics\n * @param metadata Metadata schema with translation entries\n\n * @returns Statistics about the pluralization process\n */\n async process(metadata: MetadataSchema): Promise<PluralizationStats> {\n const startTime = performance.now();\n const totalEntries = Object.keys(metadata).length;\n\n if (totalEntries === 0) {\n return {\n total: 0,\n candidates: 0,\n pluralized: 0,\n rejected: 0,\n failed: 0,\n durationMs: 0,\n };\n }\n\n this.logger.debug(\n `Starting pluralization processing for ${totalEntries} entries`,\n );\n\n // Step 1: Detect plural candidates using pattern matching\n const entriesMap: Record<string, string> = Object.fromEntries(\n Object.entries(metadata).map(([hash, entry]) => [hash, entry.sourceText]),\n );\n\n const candidates = detectPluralCandidates(entriesMap, this.logger);\n\n this.logger.debug(\n `Found ${candidates.length} plural candidates (${((candidates.length / totalEntries) * 100).toFixed(1)}%)`,\n );\n\n if (candidates.length === 0) {\n const endTime = performance.now();\n return {\n total: totalEntries,\n candidates: 0,\n pluralized: 0,\n rejected: 0,\n failed: 0,\n durationMs: endTime - startTime,\n };\n }\n\n // Step 2: Generate ICU formats with batching\n this.logger.debug(\"Generating ICU formats with batching...\");\n const icuResults = await this.generateBatch(candidates, 10);\n\n // Step 3: Validate and update metadata entries\n this.logger.debug(\"Validating and updating entries...\");\n let pluralized = 0;\n let rejected = 0;\n let failed = 0;\n\n for (const candidate of candidates) {\n const result = icuResults.get(candidate.hash);\n const entry = metadata[candidate.hash];\n this.logger.debug(`Processing candidate: ${candidate.sourceText}`);\n if (!entry) {\n this.logger.warn(`Entry not found for hash: ${candidate.hash}`);\n failed++;\n continue;\n }\n\n if (!result) {\n this.logger.warn(`No result for hash: ${candidate.hash}`);\n failed++;\n continue;\n }\n\n if (result.error) {\n this.logger.warn(\n `Error generating ICU for \"${candidate.sourceText}\": ${result.error}`,\n );\n failed++;\n continue;\n }\n\n if (!result.success || !result.icuText) {\n this.logger.debug(\n `Rejected pluralization for \"${candidate.sourceText}\": ${result.reasoning}`,\n );\n rejected++;\n continue;\n }\n\n const isValid = validateICU(\n result.icuText,\n candidate.sourceText,\n this.logger,\n );\n\n if (!isValid) {\n this.logger.warn(\n `Invalid ICU format generated for \"${candidate.sourceText}\", falling back to original`,\n );\n failed++;\n continue;\n }\n\n this.logger.debug(\n `Pluralizing: \"${entry.sourceText}\" -> \"${result.icuText}\"`,\n );\n entry.sourceText = result.icuText;\n pluralized++;\n }\n\n const endTime = performance.now();\n const duration = endTime - startTime;\n\n this.logger.debug(\n `Pluralization completed: ${pluralized} pluralized, ${rejected} rejected, ${failed} failed in ${duration.toFixed(0)}ms`,\n );\n\n return {\n total: totalEntries,\n candidates: candidates.length,\n pluralized,\n rejected,\n failed,\n durationMs: duration,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,IAAa,uBAAb,MAAkC;CAChC,AAAiB;CACjB,AAAQ,wBAAQ,IAAI,KAAkC;CACtD,AAAiB;CACjB,AAAi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OAAO,MAAM,qCAAqC;EACvD,IAAI,aAAa;EACjB,IAAI,WAAW;EACf,IAAI,SAAS;AAEb,OAAK,MAAM,aAAa,YAAY;GAClC,MAAM,SAAS,WAAW,IAAI,UAAU,KAAK;GAC7C,MAAM,QAAQ,SAAS,UAAU;AACjC,QAAK,OAAO,MAAM,yBAAyB,UAAU,aAAa;AAClE,OAAI,CAAC,OAAO;AACV,SAAK,OAAO,KAAK,6BAA6B,UAAU,OAAO;AAC/D;AACA;;AAGF,OAAI,CAAC,QAAQ;AACX,SAAK,OAAO,KAAK,uBAAuB,UAAU,OAAO;AACzD;AACA;;AAGF,OAAI,OAAO,OAAO;AAChB,SAAK,OAAO,KACV,6BAA6B,UAAU,WAAW,KAAK,OAAO,QAC/D;AACD;AACA;;AAGF,OAAI,CAAC,OAAO,WAAW,CAAC,OAAO,SAAS;AACtC,SAAK,OAAO,MACV,+BAA+B,UAAU,WAAW,KAAK,OAAO,YACjE;AACD;AACA;;AASF,OAAI,CANY,YACd,OAAO,SACP,UAAU,YACV,KAAK,OACN,EAEa;AACZ,SAAK,OAAO,KACV,qCAAqC,UAAU,WAAW,6BAC3D;AACD;AACA;;AAGF,QAAK,OAAO,MACV,iBAAiB,MAAM,WAAW,QAAQ,OAAO,QAAQ,GAC1D;AACD,SAAM,aAAa,OAAO;AAC1B;;EAIF,MAAM,WADU,YAAY,KAAK,GACN;AAE3B,OAAK,OAAO,MACV,4BAA4B,WAAW,eAAe,SAAS,aAAa,OAAO,aAAa,SAAS,QAAQ,EAAE,CAAC,IACrH;AAED,SAAO;GACL,OAAO;GACP,YAAY,WAAW;GACvB;GACA;GACA;GACA,YAAY;GACb"}
@@ -5,6 +5,11 @@ import { LocaleCode } from "lingo.dev/spec";
5
5
  type PluralizationConfig = {
6
6
  sourceLocale: LocaleCode;
7
7
  enabled: boolean;
8
+ /**
9
+ * Milliseconds to wait for a pluralization batch. Defaults to twice the
10
+ * translation timeout, since a batch asks the model for more at once.
11
+ */
12
+ aiTimeout?: number;
8
13
  /**
9
14
  * LLM provider for pluralization detection
10
15
  * Format: "provider:model" (e.g., "groq:llama3-8b-8192")
@@ -5,6 +5,11 @@ import { LocaleCode } from "lingo.dev/spec";
5
5
  type PluralizationConfig = {
6
6
  sourceLocale: LocaleCode;
7
7
  enabled: boolean;
8
+ /**
9
+ * Milliseconds to wait for a pluralization batch. Defaults to twice the
10
+ * translation timeout, since a batch asks the model for more at once.
11
+ */
12
+ aiTimeout?: number;
8
13
  /**
9
14
  * LLM provider for pluralization detection
10
15
  * Format: "provider:model" (e.g., "groq:llama3-8b-8192")
@@ -1,4 +1,5 @@
1
1
  const require_index = require('./pseudotranslator/index.cjs');
2
+ const require_api = require('./api.cjs');
2
3
  const require_translator = require('./lingo/translator.cjs');
3
4
  const require_service = require('./pluralization/service.cjs');
4
5
  const require_cache_factory = require('./cache-factory.cjs');
@@ -24,11 +25,13 @@ var TranslationService = class {
24
25
  this.translator = new require_translator.LingoTranslator({
25
26
  models,
26
27
  sourceLocale: config.sourceLocale,
27
- prompt: config.prompt
28
+ prompt: config.prompt,
29
+ aiTimeout: config.aiTimeout
28
30
  }, this.logger);
29
31
  if (this.config.pluralization?.enabled) this.pluralizationService = new require_service.PluralizationService({
30
32
  ...this.config.pluralization,
31
- sourceLocale: this.config.sourceLocale
33
+ sourceLocale: this.config.sourceLocale,
34
+ aiTimeout: this.config.pluralization.aiTimeout ?? config.aiTimeout
32
35
  }, this.logger);
33
36
  } catch (error) {
34
37
  if (isDev) {
@@ -91,33 +94,13 @@ Set the required API keys for real translations.`);
91
94
  if (locale === this.config.sourceLocale) {
92
95
  this.logger.debug(`Source locale detected, returning sourceText for ${hashesNeedingTranslation.length} entries`);
93
96
  for (const [hash, entry] of Object.entries(entriesToTranslate)) newTranslations[hash] = entry.text;
94
- } else if (Object.keys(entriesToTranslate).length > 0) {
95
- try {
96
- this.logger.debug(`Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`);
97
- const translatedTexts = await this.translator.translate(locale, entriesToTranslate);
98
- newTranslations = {
99
- ...overriddenTranslations,
100
- ...translatedTexts
101
- };
102
- } catch (error) {
103
- const errorMessage = error instanceof Error ? error.message : String(error);
104
- this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
105
- if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
106
- return {
107
- translations: this.pickTranslations(cachedTranslations, workingHashes),
108
- errors: [{
109
- hash: "all",
110
- sourceText: "all",
111
- error: errorMessage
112
- }],
113
- stats: {
114
- total: workingHashes.length,
115
- cached: cachedCount,
116
- translated: 0,
117
- failed: uncachedHashes.length
118
- }
119
- };
120
- }
97
+ } else if (Object.keys(entriesToTranslate).length > 0) try {
98
+ this.logger.debug(`Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`);
99
+ const translatedTexts = await this.translator.translate(locale, entriesToTranslate);
100
+ newTranslations = {
101
+ ...overriddenTranslations,
102
+ ...translatedTexts
103
+ };
121
104
  for (const hash of uncachedHashes) if (!newTranslations[hash]) {
122
105
  const entry = filteredMetadata[hash];
123
106
  errors.push({
@@ -126,6 +109,16 @@ Set the required API keys for real translations.`);
126
109
  error: "Translator doesn't return translation"
127
110
  });
128
111
  }
112
+ } catch (error) {
113
+ const errorMessage = error instanceof Error ? error.message : String(error);
114
+ this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
115
+ if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
116
+ if (error instanceof require_api.PartialTranslationError) Object.assign(newTranslations, error.partialTranslations);
117
+ errors.push({
118
+ hash: "all",
119
+ sourceText: "all",
120
+ error: errorMessage
121
+ });
129
122
  }
130
123
  if (Object.keys(newTranslations).length > 0) try {
131
124
  await this.cache.update(locale, newTranslations);
@@ -146,7 +139,7 @@ Set the required API keys for real translations.`);
146
139
  total: workingHashes.length,
147
140
  cached: cachedCount,
148
141
  translated: Object.keys(newTranslations).length,
149
- failed: errors.length
142
+ failed: uncachedHashes.filter((hash) => filteredMetadata[hash] && !newTranslations[hash]).length
150
143
  }
151
144
  };
152
145
  }
@@ -1,4 +1,5 @@
1
1
  import { PseudoTranslator } from "./pseudotranslator/index.mjs";
2
+ import { PartialTranslationError } from "./api.mjs";
2
3
  import { LingoTranslator } from "./lingo/translator.mjs";
3
4
  import { PluralizationService } from "./pluralization/service.mjs";
4
5
  import { createCache } from "./cache-factory.mjs";
@@ -24,11 +25,13 @@ var TranslationService = class {
24
25
  this.translator = new LingoTranslator({
25
26
  models,
26
27
  sourceLocale: config.sourceLocale,
27
- prompt: config.prompt
28
+ prompt: config.prompt,
29
+ aiTimeout: config.aiTimeout
28
30
  }, this.logger);
29
31
  if (this.config.pluralization?.enabled) this.pluralizationService = new PluralizationService({
30
32
  ...this.config.pluralization,
31
- sourceLocale: this.config.sourceLocale
33
+ sourceLocale: this.config.sourceLocale,
34
+ aiTimeout: this.config.pluralization.aiTimeout ?? config.aiTimeout
32
35
  }, this.logger);
33
36
  } catch (error) {
34
37
  if (isDev) {
@@ -91,33 +94,13 @@ Set the required API keys for real translations.`);
91
94
  if (locale === this.config.sourceLocale) {
92
95
  this.logger.debug(`Source locale detected, returning sourceText for ${hashesNeedingTranslation.length} entries`);
93
96
  for (const [hash, entry] of Object.entries(entriesToTranslate)) newTranslations[hash] = entry.text;
94
- } else if (Object.keys(entriesToTranslate).length > 0) {
95
- try {
96
- this.logger.debug(`Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`);
97
- const translatedTexts = await this.translator.translate(locale, entriesToTranslate);
98
- newTranslations = {
99
- ...overriddenTranslations,
100
- ...translatedTexts
101
- };
102
- } catch (error) {
103
- const errorMessage = error instanceof Error ? error.message : String(error);
104
- this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
105
- if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
106
- return {
107
- translations: this.pickTranslations(cachedTranslations, workingHashes),
108
- errors: [{
109
- hash: "all",
110
- sourceText: "all",
111
- error: errorMessage
112
- }],
113
- stats: {
114
- total: workingHashes.length,
115
- cached: cachedCount,
116
- translated: 0,
117
- failed: uncachedHashes.length
118
- }
119
- };
120
- }
97
+ } else if (Object.keys(entriesToTranslate).length > 0) try {
98
+ this.logger.debug(`Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`);
99
+ const translatedTexts = await this.translator.translate(locale, entriesToTranslate);
100
+ newTranslations = {
101
+ ...overriddenTranslations,
102
+ ...translatedTexts
103
+ };
121
104
  for (const hash of uncachedHashes) if (!newTranslations[hash]) {
122
105
  const entry = filteredMetadata[hash];
123
106
  errors.push({
@@ -126,6 +109,16 @@ Set the required API keys for real translations.`);
126
109
  error: "Translator doesn't return translation"
127
110
  });
128
111
  }
112
+ } catch (error) {
113
+ const errorMessage = error instanceof Error ? error.message : String(error);
114
+ this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
115
+ if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
116
+ if (error instanceof PartialTranslationError) Object.assign(newTranslations, error.partialTranslations);
117
+ errors.push({
118
+ hash: "all",
119
+ sourceText: "all",
120
+ error: errorMessage
121
+ });
129
122
  }
130
123
  if (Object.keys(newTranslations).length > 0) try {
131
124
  await this.cache.update(locale, newTranslations);
@@ -146,7 +139,7 @@ Set the required API keys for real translations.`);
146
139
  total: workingHashes.length,
147
140
  cached: cachedCount,
148
141
  translated: Object.keys(newTranslations).length,
149
- failed: errors.length
142
+ failed: uncachedHashes.filter((hash) => filteredMetadata[hash] && !newTranslations[hash]).length
150
143
  }
151
144
  };
152
145
  }
@@ -1 +1 @@
1
- {"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","overriddenTranslations: Record<string, string>","hashesNeedingTranslation: string[]","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { LingoEnvironment, MetadataSchema } from \"../types\";\nimport {\n type PluralizationConfig,\n PluralizationService,\n} from \"./pluralization\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\nimport { PseudoTranslator } from \"./pseudotranslator\";\nimport { LingoTranslator } from \"./lingo\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\nimport { MemoryTranslationCache } from \"./memory-cache\";\n\nexport type TranslationServiceConfig = {\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /**\n * Pluralization configuration\n * If provided, enables automatic pluralization of source messages\n */\n pluralization: Omit<PluralizationConfig, \"sourceLocale\">;\n models: \"lingo.dev\" | Record<string, string>;\n prompt?: string;\n environment: LingoEnvironment;\n dev?: {\n usePseudotranslator?: boolean;\n };\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private pluralizationService?: PluralizationService;\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n const isDev = config.environment === \"development\";\n\n // 1. Explicit dev override takes precedence\n if (isDev && config.dev?.usePseudotranslator) {\n this.logger.info(\n \"📝 Using pseudotranslator (dev.usePseudotranslator enabled)\",\n );\n this.translator = new PseudoTranslator({ delayMedian: 100 }, logger);\n this.cache = new MemoryTranslationCache();\n } else {\n // 2. Try to create real translator\n // LingoTranslator constructor will validate and fetch API keys\n // If validation fails, it will throw an error with helpful message\n try {\n const models = config.models;\n\n this.logger.debug(\n `Creating Lingo translator with models: ${JSON.stringify(models)}`,\n );\n\n this.cache = createCache(config);\n this.translator = new LingoTranslator(\n {\n models,\n sourceLocale: config.sourceLocale,\n prompt: config.prompt,\n },\n this.logger,\n );\n\n if (this.config.pluralization?.enabled) {\n this.pluralizationService = new PluralizationService(\n {\n ...this.config.pluralization,\n sourceLocale: this.config.sourceLocale,\n },\n this.logger,\n );\n }\n } catch (error) {\n // 3. Auto-fallback in dev mode if creation fails\n if (isDev) {\n // Use console.error to ensure visibility in all contexts (loader, server, etc.)\n const errorMsg =\n error instanceof Error ? error.message : String(error);\n this.logger.warn(`⚠️ Translation setup error: \\n${errorMsg}\\n\n⚠️ Auto-fallback to pseudotranslator in development mode.\nSet the required API keys for real translations.`);\n\n this.translator = new PseudoTranslator(\n { delayMedian: 100 },\n this.logger,\n );\n this.cache = new MemoryTranslationCache();\n } else {\n // 4. Fail in production\n throw error;\n }\n }\n }\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation/pluralization\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Process pluralization for filtered entries\n if (this.pluralizationService) {\n this.logger.debug(\n `Processing pluralization for ${Object.keys(filteredMetadata).length} entries...`,\n );\n const pluralStats =\n await this.pluralizationService.process(filteredMetadata);\n this.logger.debug(\n `Pluralization stats: ${pluralStats.pluralized} pluralized, ${pluralStats.rejected} rejected, ${pluralStats.failed} failed`,\n );\n }\n\n // Step 6: Separate overridden entries from entries that need translation\n const overriddenTranslations: Record<string, string> = {};\n const hashesNeedingTranslation: string[] = [];\n\n this.logger.debug(\n `Checking for overrides in ${uncachedHashes.length} entries`,\n );\n\n for (const hash of uncachedHashes) {\n const entry = filteredMetadata[hash];\n if (!entry) continue;\n\n // Check if this entry has an override for the current locale\n if (entry.overrides && entry.overrides[locale]) {\n overriddenTranslations[hash] = entry.overrides[locale];\n this.logger.debug(\n `Using override for ${hash} in locale ${locale}: \"${entry.overrides[locale]}\"`,\n );\n } else {\n hashesNeedingTranslation.push(hash);\n }\n }\n\n // Step 7: Prepare entries for translation (excluding overridden ones)\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n hashesNeedingTranslation,\n );\n\n // Step 8: Translate or return source text\n let newTranslations: Record<string, string> = { ...overriddenTranslations };\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the (possibly pluralized) sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${hashesNeedingTranslation.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate only entries without overrides\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n // Merge translated texts with overridden translations\n newTranslations = { ...overriddenTranslations, ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"Translator doesn't return translation\",\n });\n }\n }\n }\n\n // Step 5: Update cache with successful translations (skip for pseudo)\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 6: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;;;AAiEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;EAER,MAAM,QAAQ,OAAO,gBAAgB;AAGrC,MAAI,SAAS,OAAO,KAAK,qBAAqB;AAC5C,QAAK,OAAO,KACV,8DACD;AACD,QAAK,aAAa,IAAI,iBAAiB,EAAE,aAAa,KAAK,EAAE,OAAO;AACpE,QAAK,QAAQ,IAAI,wBAAwB;QAKzC,KAAI;GACF,MAAM,SAAS,OAAO;AAEtB,QAAK,OAAO,MACV,0CAA0C,KAAK,UAAU,OAAO,GACjE;AAED,QAAK,QAAQ,YAAY,OAAO;AAChC,QAAK,aAAa,IAAI,gBACpB;IACE;IACA,cAAc,OAAO;IACrB,QAAQ,OAAO;IAChB,EACD,KAAK,OACN;AAED,OAAI,KAAK,OAAO,eAAe,QAC7B,MAAK,uBAAuB,IAAI,qBAC9B;IACE,GAAG,KAAK,OAAO;IACf,cAAc,KAAK,OAAO;IAC3B,EACD,KAAK,OACN;WAEI,OAAO;AAEd,OAAI,OAAO;IAET,MAAM,WACJ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACxD,SAAK,OAAO,KAAK,iCAAiC,SAAS;;kDAEnB;AAExC,SAAK,aAAa,IAAI,iBACpB,EAAE,aAAa,KAAK,EACpB,KAAK,OACN;AACD,SAA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ACA,YAAY,OAAO,cAAc;KACjC,OAAO;KACR,CAAC;;;AAMR,MAAI,OAAO,KAAK,gBAAgB,CAAC,SAAS,EACxC,KAAI;AACF,SAAM,KAAK,MAAM,OAAO,QAAQ,gBAAgB;WACzC,OAAO;AACd,QAAK,OAAO,MAAM,2BAA2B,MAAM;;EAMvD,MAAM,kBAAkB;GAAE,GAAG;GAAoB,GAAG;GAAiB;EACrE,MAAM,SAAS,KAAK,iBAAiB,iBAAiB,cAAc;EAEpE,MAAM,UAAU,YAAY,KAAK;AACjC,OAAK,OAAO,MACV,6BAA6B,OAAO,IAAI,OAAO,KAAK,gBAAgB,CAAC,OAAO,QAAQ,YAAY,WAAW,OAAO,OAAO,cAAc,UAAU,WAAW,QAAQ,EAAE,CAAC,IACxK;AAED,SAAO;GACL,cAAc;GACd;GACA,OAAO;IACL,OAAO,cAAc;IACrB,QAAQ;IACR,YAAY,OAAO,KAAK,gBAAgB,CAAC;IACzC,QAAQ,OAAO;IAChB;GACF;;;;;CAMH,AAAQ,eACN,UACA,QACmC;EACnC,MAAMC,UAA6C,EAAE;AAErD,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,QAAQ,SAAS;AACvB,OAAI,MACF,SAAQ,QAAQ;IACd,MAAM,MAAM;IACZ,SAAS,MAAM,WAAW,EAAE;IAC7B;;AAIL,SAAO;;;;;CAOT,AAAQ,iBACN,iBACA,iBACwB;EACxB,MAAMC,SAAiC,EAAE;AAEzC,OAAK,MAAM,QAAQ,gBACjB,KAAI,gBAAgB,MAClB,QAAO,QAAQ,gBAAgB;AAInC,SAAO"}
1
+ {"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","overriddenTranslations: Record<string, string>","hashesNeedingTranslation: string[]","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport {\n PartialTranslationError,\n type TranslatableEntry,\n type Translator,\n} from \"./api\";\nimport type { LingoEnvironment, MetadataSchema } from \"../types\";\nimport {\n type PluralizationConfig,\n PluralizationService,\n} from \"./pluralization\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\nimport { PseudoTranslator } from \"./pseudotranslator\";\nimport { LingoTranslator } from \"./lingo\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\nimport { MemoryTranslationCache } from \"./memory-cache\";\n\nexport type TranslationServiceConfig = {\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /**\n * Pluralization configuration\n * If provided, enables automatic pluralization of source messages\n */\n pluralization: Omit<PluralizationConfig, \"sourceLocale\">;\n models: \"lingo.dev\" | Record<string, string>;\n prompt?: string;\n aiTimeout?: number;\n environment: LingoEnvironment;\n dev?: {\n usePseudotranslator?: boolean;\n };\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private pluralizationService?: PluralizationService;\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n const isDev = config.environment === \"development\";\n\n // 1. Explicit dev override takes precedence\n if (isDev && config.dev?.usePseudotranslator) {\n this.logger.info(\n \"📝 Using pseudotranslator (dev.usePseudotranslator enabled)\",\n );\n this.translator = new PseudoTranslator({ delayMedian: 100 }, logger);\n this.cache = new MemoryTranslationCache();\n } else {\n // 2. Try to create real translator\n // LingoTranslator constructor will validate and fetch API keys\n // If validation fails, it will throw an error with helpful message\n try {\n const models = config.models;\n\n this.logger.debug(\n `Creating Lingo translator with models: ${JSON.stringify(models)}`,\n );\n\n this.cache = createCache(config);\n this.translator = new LingoTranslator(\n {\n models,\n sourceLocale: config.sourceLocale,\n prompt: config.prompt,\n aiTimeout: config.aiTimeout,\n },\n this.logger,\n );\n\n if (this.config.pluralization?.enabled) {\n this.pluralizationService = new PluralizationService(\n {\n ...this.config.pluralization,\n sourceLocale: this.config.sourceLocale,\n aiTimeout:\n this.config.pluralization.aiTimeout ?? config.aiTimeout,\n },\n this.logger,\n );\n }\n } catch (error) {\n // 3. Auto-fallback in dev mode if creation fails\n if (isDev) {\n // Use console.error to ensure visibility in all contexts (loader, server, etc.)\n const errorMsg =\n error instanceof Error ? error.message : String(error);\n this.logger.warn(`⚠️ Translation setup error: \\n${errorMsg}\\n\n⚠️ Auto-fallback to pseudotranslator in development mode.\nSet the required API keys for real translations.`);\n\n this.translator = new PseudoTranslator(\n { delayMedian: 100 },\n this.logger,\n );\n this.cache = new MemoryTranslationCache();\n } else {\n // 4. Fail in production\n throw error;\n }\n }\n }\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation/pluralization\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Process pluralization for filtered entries\n if (this.pluralizationService) {\n this.logger.debug(\n `Processing pluralization for ${Object.keys(filteredMetadata).length} entries...`,\n );\n const pluralStats =\n await this.pluralizationService.process(filteredMetadata);\n this.logger.debug(\n `Pluralization stats: ${pluralStats.pluralized} pluralized, ${pluralStats.rejected} rejected, ${pluralStats.failed} failed`,\n );\n }\n\n // Step 6: Separate overridden entries from entries that need translation\n const overriddenTranslations: Record<string, string> = {};\n const hashesNeedingTranslation: string[] = [];\n\n this.logger.debug(\n `Checking for overrides in ${uncachedHashes.length} entries`,\n );\n\n for (const hash of uncachedHashes) {\n const entry = filteredMetadata[hash];\n if (!entry) continue;\n\n // Check if this entry has an override for the current locale\n if (entry.overrides && entry.overrides[locale]) {\n overriddenTranslations[hash] = entry.overrides[locale];\n this.logger.debug(\n `Using override for ${hash} in locale ${locale}: \"${entry.overrides[locale]}\"`,\n );\n } else {\n hashesNeedingTranslation.push(hash);\n }\n }\n\n // Step 7: Prepare entries for translation (excluding overridden ones)\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n hashesNeedingTranslation,\n );\n\n // Step 8: Translate or return source text\n let newTranslations: Record<string, string> = { ...overriddenTranslations };\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the (possibly pluralized) sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${hashesNeedingTranslation.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate only entries without overrides\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n // Merge translated texts with overridden translations\n newTranslations = { ...overriddenTranslations, ...translatedTexts };\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"Translator doesn't return translation\",\n });\n }\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n if (error instanceof PartialTranslationError) {\n Object.assign(newTranslations, error.partialTranslations);\n }\n errors.push({\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n });\n }\n }\n\n // Step 5: Update cache with successful translations (skip for pseudo)\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 6: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: uncachedHashes.filter(\n (hash) => filteredMetadata[hash] && !newTranslations[hash],\n ).length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;;;;AAsEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;EAER,MAAM,QAAQ,OAAO,gBAAgB;AAGrC,MAAI,SAAS,OAAO,KAAK,qBAAqB;AAC5C,QAAK,OAAO,KACV,8DACD;AACD,QAAK,aAAa,IAAI,iBAAiB,EAAE,aAAa,KAAK,EAAE,OAAO;AACpE,QAAK,QAAQ,IAAI,wBAAwB;QAKzC,KAAI;GACF,MAAM,SAAS,OAAO;AAEtB,QAAK,OAAO,MACV,0CAA0C,KAAK,UAAU,OAAO,GACjE;AAED,QAAK,QAAQ,YAAY,OAAO;AAChC,QAAK,aAAa,IAAI,gBACpB;IACE;IACA,cAAc,OAAO;IACrB,QAAQ,OAAO;IACf,WAAW,OAAO;IACnB,EACD,KAAK,OACN;AAED,OAAI,KAAK,OAAO,eAAe,QAC7B,MAAK,uBAAuB,IAAI,qBAC9B;IACE,GAAG,KAAK,OAAO;IACf,cAAc,KAAK,OAAO;IAC1B,WACE,KAAK,OAAO,cAAc,aAAa,OAAO;IACjD,EACD,KAAK,OACN;WAEI,OAAO;AAEd,OAAI,OAAO;IAET,MAAM,WACJ,iBAAi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
114
  prompt?: string;
115
+ /**
116
+ * Milliseconds to wait for a single AI translation request before giving up.
117
+ *
118
+ * Raise it when builds run somewhere with slow network to the model, such as
119
+ * CI, or when a chunk carries enough text that the model needs longer. The
120
+ * request that times out is not cancelled and is still billed, so a value
121
+ * that is too low costs money as well as build time.
122
+ *
123
+ * @default 120000
124
+ */
125
+ aiTimeout: number;
115
126
  /**
116
127
  * Pluralization configuration
117
128
  * Automatically detects and converts messages to ICU MessageFormat
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;AA4BA;AAKA;AAEA;AAEY,UA3BK,YAAA,CA2BL;EACL;;;;EAMK,IAAA,EAAA,MAAA;EAA0B;;;;EAIhC,MAAA,EAAA,MAAA;;;;;;AAHJ,KAjBU,uBAAA,GAiBV;EAAO,IAAA,EAAA,QAAA;EAUG,MAAA,EA3BoD,YA2BpC;AAK5B,CAAA;;;;AAsEwB,KAjGZ,yBAAA,GAiGY,cAAA,GAAA,eAAA;AAYF,KA3GV,mBAAA,GA2GU,aAAA,GAAA,WAAA;AAAL,KAzGL,0BAAA,GAA6B,OAyGxB,CAxGf,IAwGe,CAxGV,mBAwGU,EAAA,cAAA,CAAA,CAAA;;;;KAlGL,kBAAA,GAAqB,KAAK,aAAa,6BACjD,QACE,KACE,aACA,oCAAoC;OAE/B,QAAQ;iBACE;;KAIT,gBAAA;;;;KAKA,WAAA;;;;;;;;;;;;;;;;eAkBG;;;;;;;;;;;;;;;;;;;;gBAsBC;;;;;;;;;;;iBAYC;;;;;;;;;;;;;;;;wBAkBO;;;;;;;;;;iBAYP,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqCD"}
1
+ {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;AA4BA;AAKA;AAEA;AAEY,UA3BK,YAAA,CA2BL;EACL;;;;EAMK,IAAA,EAAA,MAAA;EAA0B;;;;EAIhC,MAAA,EAAA,MAAA;;;;;;AAHJ,KAjBU,uBAAA,GAiBV;EAAO,IAAA,EAAA,QAAA;EAUG,MAAA,EA3BoD,YA2BpC;AAK5B,CAAA;;;;AAsEwB,KAjGZ,yBAAA,GAiGY,cAAA,GAAA,eAAA;AAwBF,KAvHV,mBAAA,GAuHU,aAAA,GAAA,WAAA;AAAL,KArHL,0BAAA,GAA6B,OAqHxB,CApHf,IAoHe,CApHV,mBAoHU,EAAA,cAAA,CAAA,CAAA;;;;KA9GL,kBAAA,GAAqB,KAAK,aAAa,6BACjD,QACE,KACE,aACA,oCAAoC;OAE/B,QAAQ;iBACE;;KAIT,gBAAA;;;;KAKA,WAAA;;;;;;;;;;;;;;;;eAkBG;;;;;;;;;;;;;;;;;;;;gBAsBC;;;;;;;;;;;iBAYC;;;;;;;;;;;;;;;;wBAkBO;;;;;;;;;;;;;;;;;;;;;iBAwBP,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqCD"}
package/build/types.d.mts CHANGED
@@ -112,6 +112,17 @@ type LingoConfig = {
112
112
  * Use {SOURCE_LOCALE} and {TARGET_LOCALE} placeholders
113
113
  */
114
114
  prompt?: string;
115
+ /**
116
+ * Milliseconds to wait for a single AI translation request before giving up.
117
+ *
118
+ * Raise it when builds run somewhere with slow network to the model, such as
119
+ * CI, or when a chunk carries enough text that the model needs longer. The
120
+ * request that times out is not cancelled and is still billed, so a value
121
+ * that is too low costs money as well as build time.
122
+ *
123
+ * @default 120000
124
+ */
125
+ aiTimeout: number;
115
126
  /**
116
127
  * Pluralization configuration
117
128
  * Automatically detects and converts messages to ICU MessageFormat
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;AA4BA;AAKA;AAEA;AAEY,UA3BK,YAAA,CA2BL;EACL;;;;EAMK,IAAA,EAAA,MAAA;EAA0B;;;;EAIhC,MAAA,EAAA,MAAA;;;;;;AAHJ,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AYC;;;;;;;;;;;;;;;;wBAkBO;;;;;;;;;;;;;;;;;;;;;iBAwBP,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqCD"}
@@ -16,6 +16,7 @@ const DEFAULT_CONFIG = {
16
16
  }
17
17
  },
18
18
  models: "lingo.dev",
19
+ aiTimeout: 12e4,
19
20
  pluralization: {
20
21
  enabled: false,
21
22
  model: "groq:llama-3.1-8b-instant"
@@ -15,6 +15,7 @@ const DEFAULT_CONFIG = {
15
15
  }
16
16
  },
17
17
  models: "lingo.dev",
18
+ aiTimeout: 12e4,
18
19
  pluralization: {
19
20
  enabled: false,
20
21
  model: "groq:llama-3.1-8b-instant"
@@ -1 +1 @@
1
- {"version":3,"file":"config-factory.mjs","names":["config: LingoConfig"],"sources":["../../src/utils/config-factory.ts"],"sourcesContent":["/**\n * Config factory for creating LoaderConfig instances\n */\nimport type {\n LingoConfig,\n LingoConfigRequiredFields,\n LingoInternalFields,\n PartialLingoConfig,\n} from \"../types\";\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG = {\n sourceRoot: \"src\",\n lingoDir: \"lingo\",\n useDirective: false,\n dev: {\n translationServerStartPort: 60000,\n },\n localePersistence: {\n type: \"cookie\" as const,\n config: {\n name: \"locale\",\n maxAge: 31536000,\n },\n },\n models: \"lingo.dev\",\n pluralization: {\n enabled: false,\n model: \"groq:llama-3.1-8b-instant\",\n },\n buildMode: \"translate\",\n} satisfies Omit<\n LingoConfig,\n // Looks like we can use LingoInternalFields, but it's only a coincidence that the types match, we may want to provide default for internal fields\n LingoConfigRequiredFields | \"environment\" | \"cacheType\"\n>;\n\nfunction getModelStringForLocales(\n models: Record<string, string>,\n sourceLocale: string,\n targetLocale: string | undefined,\n): string | undefined {\n const localeKeys = targetLocale\n ? [\n `${sourceLocale}:${targetLocale}`,\n `*:${targetLocale}`,\n `${sourceLocale}:*`,\n \"*:*\",\n ]\n : [`${sourceLocale}:*`, \"*:*\"];\n\n const modelKey = localeKeys.find((key) => key in models);\n if (modelKey) {\n return models[modelKey];\n }\n\n const sortedKeys = Object.keys(models).sort();\n if (sortedKeys.length === 0) {\n return undefined;\n }\n\n return models[sortedKeys[0]];\n}\n\nfunction inferPluralizationModel(\n models: \"lingo.dev\" | Record<string, string>,\n sourceLocale: string,\n targetLocales: string[],\n): string | undefined {\n if (models === \"lingo.dev\") {\n return undefined;\n }\n\n return getModelStringForLocales(\n models,\n sourceLocale,\n targetLocales[0],\n );\n}\n\n/**\n * Create a LoaderConfig with defaults applied\n *\n * @param options - Partial config to override defaults\n * @returns Complete LoaderConfig with all defaults applied\n *\n */\nexport function createLingoConfig(\n options: PartialLingoConfig & Partial<Pick<LingoConfig, LingoInternalFields>>,\n): LingoConfig {\n const cleanOptions = { ...options };\n\n const cleanObject = (obj: any) => {\n if (!obj || typeof obj !== \"object\") return;\n Object.keys(obj).forEach((key) => {\n if (obj[key] === undefined) {\n delete obj[key];\n } else if (\n obj[key] &&\n typeof obj[key] === \"object\" &&\n !Array.isArray(obj[key])\n ) {\n cleanObject(obj[key]);\n }\n });\n };\n\n cleanObject(cleanOptions);\n\n const config: LingoConfig = {\n ...DEFAULT_CONFIG,\n ...cleanOptions,\n environment:\n cleanOptions.environment ??\n (process.env.NODE_ENV === \"development\" ? \"development\" : \"production\"),\n cacheType: cleanOptions.cacheType ?? \"local\",\n dev: {\n ...DEFAULT_CONFIG.dev,\n ...cleanOptions.dev,\n },\n pluralization: {\n ...DEFAULT_CONFIG.pluralization,\n ...cleanOptions.pluralization,\n },\n localePersistence: {\n ...DEFAULT_CONFIG.localePersistence,\n ...cleanOptions.localePersistence,\n config: {\n ...DEFAULT_CONFIG.localePersistence.config,\n ...cleanOptions.localePersistence?.config,\n },\n },\n };\n\n const explicitEnabled = cleanOptions.pluralization?.enabled;\n const explicitModel = cleanOptions.pluralization?.model;\n const hasExplicitModel =\n typeof explicitModel === \"string\" && explicitModel.trim().length > 0;\n const hasExplicitEnabled = typeof explicitEnabled === \"boolean\";\n\n const pluralizationEnabled = hasExplicitEnabled\n ? explicitEnabled\n : hasExplicitModel;\n\n let pluralizationModel = hasExplicitModel\n ? explicitModel!.trim()\n : config.pluralization.model;\n\n if (pluralizationEnabled && !hasExplicitModel) {\n const inferredModel = inferPluralizationModel(\n config.models,\n config.sourceLocale,\n config.targetLocales,\n );\n\n if (!inferredModel) {\n throw new Error(\n 'Pluralization is enabled but no \"pluralization.model\" is configured. Please set \"pluralization.model\" explicitly or use direct LLM models (not \"lingo.dev\") so the model can be inferred.',\n );\n }\n\n pluralizationModel = inferredModel;\n }\n\n config.pluralization = {\n ...config.pluralization,\n enabled: pluralizationEnabled,\n model: pluralizationModel,\n };\n\n return config;\n}\n"],"mappings":";;;;AAaA,MAAa,iBAAiB;CAC5B,YAAY;CACZ,UAAU;CACV,cAAc;CACd,KAAK,EACH,4BAA4B,KAC7B;CACD,mBAAmB;EACjB,MAAM;EACN,QAAQ;GACN,MAAM;GACN,QAAQ;GACT;EACF;CACD,QAAQ;CACR,eAAe;EACb,SAAS;EACT,OAAO;EACR;CACD,WAAW;CACZ;AAMD,SAAS,yBACP,QACA,cACA,cACoB;CAUpB,MAAM,YATa,eACf;EACE,GAAG,aAAa,GAAG;EACnB,KAAK;EACL,GAAG,aAAa;EAChB;EACD,GACD,CAAC,GAAG,aAAa,KAAK,MAAM,EAEJ,MAAM,QAAQ,OAAO,OAAO;AACxD,KAAI,SACF,QAAO,OAAO;CAGhB,MAAM,aAAa,OAAO,KAAK,OAAO,CAAC,MAAM;AAC7C,KAAI,WAAW,WAAW,EACxB;AAGF,QAAO,OAAO,WAAW;;AAG3B,SAAS,wBACP,QACA,cACA,eACoB;AACpB,KAAI,WAAW,YACb;AAGF,QAAO,yBACL,QACA,cACA,cAAc,GACf;;;;;;;;;AAUH,SAAgB,kBACd,SACa;CACb,MAAM,eAAe,EAAE,GAAG,SAAS;CAEnC,MAAM,eAAe,QAAa;AAChC,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU;AACrC,SAAO,KAAK,IAAI,CAAC,SAAS,QAAQ;AAChC,OAAI,IAAI,SAAS,OACf,QAAO,IAAI;YAEX,IAAI,QACJ,OAAO,IAAI,SAAS,YACpB,CAAC,MAAM,QAAQ,IAAI,KAAK,CAExB,aAAY,IAAI,KAAK;IAEvB;;AAGJ,aAAY,aAAa;CAEzB,MAAMA,SAAsB;EAC1B,GAAG;EACH,GAAG;EACH,aACE,aAAa,gBACZ,QAAQ,IAAI,aAAa,gBAAgB,gBAAgB;EAC5D,WAAW,aAAa,aAAa;EACrC,KAAK;GACH,GAAG,eAAe;GAClB,GAAG,aAAa;GACjB;EACD,eAAe;GACb,GAAG,eAAe;GAClB,GAAG,aAAa;GACjB;EACD,mBAAmB;GACjB,GAAG,eAAe;GAClB,GAAG,aAAa;GAChB,QAAQ;IACN,GAAG,eAAe,kBAAkB;IACpC,GAAG,aAAa,mBAAmB;IACpC;GACF;EACF;CAED,MAAM,kBAAkB,aAAa,eAAe;CACpD,MAAM,gBAAgB,aAAa,eAAe;CAClD,MAAM,mBACJ,OAAO,kBAAkB,YAAY,cAAc,MAAM,CAAC,SAAS;CAGrE,MAAM,uBAFqB,OAAO,oBAAoB,YAGlD,kBACA;CAEJ,IAAI,qBAAqB,mBACrB,cAAe,MAAM,GACrB,OAAO,cAAc;AAEzB,KAAI,wBAAwB,CAAC,kBAAkB;EAC7C,MAAM,gBAAgB,wBACpB,OAAO,QACP,OAAO,cACP,OAAO,cACR;AAED,MAAI,CAAC,cACH,OAAM,IAAI,MACR,kMACD;AAGH,uBAAqB;;AAGvB,QAAO,gBAAgB;EACrB,GAAG,OAAO;EACV,SAAS;EACT,OAAO;EACR;AAED,QAAO"}
1
+ {"version":3,"file":"config-factory.mjs","names":["config: LingoConfig"],"sources":["../../src/utils/config-factory.ts"],"sourcesContent":["/**\n * Config factory for creating LoaderConfig instances\n */\nimport type {\n LingoConfig,\n LingoConfigRequiredFields,\n LingoInternalFields,\n PartialLingoConfig,\n} from \"../types\";\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG = {\n sourceRoot: \"src\",\n lingoDir: \"lingo\",\n useDirective: false,\n dev: {\n translationServerStartPort: 60000,\n },\n localePersistence: {\n type: \"cookie\" as const,\n config: {\n name: \"locale\",\n maxAge: 31536000,\n },\n },\n models: \"lingo.dev\",\n aiTimeout: 120_000,\n pluralization: {\n enabled: false,\n model: \"groq:llama-3.1-8b-instant\",\n },\n buildMode: \"translate\",\n} satisfies Omit<\n LingoConfig,\n // Looks like we can use LingoInternalFields, but it's only a coincidence that the types match, we may want to provide default for internal fields\n LingoConfigRequiredFields | \"environment\" | \"cacheType\"\n>;\n\nfunction getModelStringForLocales(\n models: Record<string, string>,\n sourceLocale: string,\n targetLocale: string | undefined,\n): string | undefined {\n const localeKeys = targetLocale\n ? [\n `${sourceLocale}:${targetLocale}`,\n `*:${targetLocale}`,\n `${sourceLocale}:*`,\n \"*:*\",\n ]\n : [`${sourceLocale}:*`, \"*:*\"];\n\n const modelKey = localeKeys.find((key) => key in models);\n if (modelKey) {\n return models[modelKey];\n }\n\n const sortedKeys = Object.keys(models).sort();\n if (sortedKeys.length === 0) {\n return undefined;\n }\n\n return models[sortedKeys[0]];\n}\n\nfunction inferPluralizationModel(\n models: \"lingo.dev\" | Record<string, string>,\n sourceLocale: string,\n targetLocales: string[],\n): string | undefined {\n if (models === \"lingo.dev\") {\n return undefined;\n }\n\n return getModelStringForLocales(\n models,\n sourceLocale,\n targetLocales[0],\n );\n}\n\n/**\n * Create a LoaderConfig with defaults applied\n *\n * @param options - Partial config to override defaults\n * @returns Complete LoaderConfig with all defaults applied\n *\n */\nexport function createLingoConfig(\n options: PartialLingoConfig & Partial<Pick<LingoConfig, LingoInternalFields>>,\n): LingoConfig {\n const cleanOptions = { ...options };\n\n const cleanObject = (obj: any) => {\n if (!obj || typeof obj !== \"object\") return;\n Object.keys(obj).forEach((key) => {\n if (obj[key] === undefined) {\n delete obj[key];\n } else if (\n obj[key] &&\n typeof obj[key] === \"object\" &&\n !Array.isArray(obj[key])\n ) {\n cleanObject(obj[key]);\n }\n });\n };\n\n cleanObject(cleanOptions);\n\n const config: LingoConfig = {\n ...DEFAULT_CONFIG,\n ...cleanOptions,\n environment:\n cleanOptions.environment ??\n (process.env.NODE_ENV === \"development\" ? \"development\" : \"production\"),\n cacheType: cleanOptions.cacheType ?? \"local\",\n dev: {\n ...DEFAULT_CONFIG.dev,\n ...cleanOptions.dev,\n },\n pluralization: {\n ...DEFAULT_CONFIG.pluralization,\n ...cleanOptions.pluralization,\n },\n localePersistence: {\n ...DEFAULT_CONFIG.localePersistence,\n ...cleanOptions.localePersistence,\n config: {\n ...DEFAULT_CONFIG.localePersistence.config,\n ...cleanOptions.localePersistence?.config,\n },\n },\n };\n\n const explicitEnabled = cleanOptions.pluralization?.enabled;\n const explicitModel = cleanOptions.pluralization?.model;\n const hasExplicitModel =\n typeof explicitModel === \"string\" && explicitModel.trim().length > 0;\n const hasExplicitEnabled = typeof explicitEnabled === \"boolean\";\n\n const pluralizationEnabled = hasExplicitEnabled\n ? explicitEnabled\n : hasExplicitModel;\n\n let pluralizationModel = hasExplicitModel\n ? explicitModel!.trim()\n : config.pluralization.model;\n\n if (pluralizationEnabled && !hasExplicitModel) {\n const inferredModel = inferPluralizationModel(\n config.models,\n config.sourceLocale,\n config.targetLocales,\n );\n\n if (!inferredModel) {\n throw new Error(\n 'Pluralization is enabled but no \"pluralization.model\" is configured. Please set \"pluralization.model\" explicitly or use direct LLM models (not \"lingo.dev\") so the model can be inferred.',\n );\n }\n\n pluralizationModel = inferredModel;\n }\n\n config.pluralization = {\n ...config.pluralization,\n enabled: pluralizationEnabled,\n model: pluralizationModel,\n };\n\n return config;\n}\n"],"mappings":";;;;AAaA,MAAa,iBAAiB;CAC5B,YAAY;CACZ,UAAU;CACV,cAAc;CACd,KAAK,EACH,4BAA4B,KAC7B;CACD,mBAAmB;EACjB,MAAM;EACN,QAAQ;GACN,MAAM;GACN,QAAQ;GACT;EACF;CAC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e;CACpD,MAAM,gBAAgB,aAAa,eAAe;CAClD,MAAM,mBACJ,OAAO,kBAAkB,YAAY,cAAc,MAAM,CAAC,SAAS;CAGrE,MAAM,uBAFqB,OAAO,oBAAoB,YAGlD,kBACA;CAEJ,IAAI,qBAAqB,mBACrB,cAAe,MAAM,GACrB,OAAO,cAAc;AAEzB,KAAI,wBAAwB,CAAC,kBAAkB;EAC7C,MAAM,gBAAgB,wBACpB,OAAO,QACP,OAAO,cACP,OAAO,cACR;AAED,MAAI,CAAC,cACH,OAAM,IAAI,MACR,kMACD;AAGH,uBAAqB;;AAGvB,QAAO,gBAAgB;EACrB,GAAG,OAAO;EACV,SAAS;EACT,OAAO;EACR;AAED,QAAO"}
@@ -31,7 +31,7 @@ var TimeoutError = class extends Error {
31
31
  const DEFAULT_TIMEOUTS = {
32
32
  FILE_IO: 1e4,
33
33
  METADATA: 15e3,
34
- AI_API: 6e4,
34
+ AI_API: 12e4,
35
35
  HTTP_REQUEST: 3e4,
36
36
  SERVER_START: 3e4,
37
37
  TRANSLATION: 12e4
@@ -30,7 +30,7 @@ var TimeoutError = class extends Error {
30
30
  const DEFAULT_TIMEOUTS = {
31
31
  FILE_IO: 1e4,
32
32
  METADATA: 15e3,
33
- AI_API: 6e4,
33
+ AI_API: 12e4,
34
34
  HTTP_REQUEST: 3e4,
35
35
  SERVER_START: 3e4,
36
36
  TRANSLATION: 12e4
@@ -1 +1 @@
1
- {"version":3,"file":"timeout.mjs","names":["timeoutMs: number"],"sources":["../../src/utils/timeout.ts"],"sourcesContent":["/**\n * Timeout utilities for preventing operations from hanging indefinitely\n */\n\n/**\n * Wrap a promise with a timeout\n * If the promise doesn't resolve/reject within the timeout, it will reject with a TimeoutError\n *\n * @param promise - The promise to wrap\n * @param timeoutMs - Timeout in milliseconds\n * @param operationName - Name of the operation for error messages\n * @returns Promise that resolves/rejects with timeout protection\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n operationName: string = \"Operation\",\n): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(\n () =>\n reject(\n new TimeoutError(\n `${operationName} timed out after ${timeoutMs}ms`,\n timeoutMs,\n ),\n ),\n timeoutMs,\n ),\n ),\n ]);\n}\n\n/**\n * Custom error for timeout operations\n */\nexport class TimeoutError extends Error {\n constructor(\n message: string,\n public readonly timeoutMs: number,\n ) {\n super(message);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Default timeout values (in milliseconds)\n */\nexport const DEFAULT_TIMEOUTS = {\n /** File I/O operations (read/write) */\n FILE_IO: 10_000, // 10 seconds\n\n /** Metadata operations (loading/saving) */\n METADATA: 15_000, // 15 seconds\n\n /** AI API calls for translation */\n AI_API: 60_000, // 60 seconds\n\n /** HTTP requests to translation server */\n HTTP_REQUEST: 30_000, // 30 seconds\n\n /** Server initialization */\n SERVER_START: 30_000, // 30 seconds\n\n /** Translation service full operation */\n TRANSLATION: 120_000, // 2 minutes\n} as const;\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,YACd,SACA,WACA,gBAAwB,aACZ;AACZ,QAAO,QAAQ,KAAK,CAClB,SACA,IAAI,SAAY,GAAG,WACjB,iBAEI,OACE,IAAI,aACF,GAAG,cAAc,mBAAmB,UAAU,KAC9C,UACD,CACF,EACH,UACD,CACF,CACF,CAAC;;;;;AAMJ,IAAa,eAAb,cAAkC,MAAM;CACtC,YACE,SACA,AAAgBA,WAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;;;;AAOhB,MAAa,mBAAmB;CAE9B,SAAS;CAGT,UAAU;CAGV,QAAQ;CAGR,cAAc;CAGd,cAAc;CAGd,aAAa;CACd"}
1
+ {"version":3,"file":"timeout.mjs","names":["timeoutMs: number"],"sources":["../../src/utils/timeout.ts"],"sourcesContent":["/**\n * Timeout utilities for preventing operations from hanging indefinitely\n */\n\n/**\n * Wrap a promise with a timeout\n * If the promise doesn't resolve/reject within the timeout, it will reject with a TimeoutError\n *\n * @param promise - The promise to wrap\n * @param timeoutMs - Timeout in milliseconds\n * @param operationName - Name of the operation for error messages\n * @returns Promise that resolves/rejects with timeout protection\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n operationName: string = \"Operation\",\n): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(\n () =>\n reject(\n new TimeoutError(\n `${operationName} timed out after ${timeoutMs}ms`,\n timeoutMs,\n ),\n ),\n timeoutMs,\n ),\n ),\n ]);\n}\n\n/**\n * Custom error for timeout operations\n */\nexport class TimeoutError extends Error {\n constructor(\n message: string,\n public readonly timeoutMs: number,\n ) {\n super(message);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Default timeout values (in milliseconds)\n */\nexport const DEFAULT_TIMEOUTS = {\n /** File I/O operations (read/write) */\n FILE_IO: 10_000, // 10 seconds\n\n /** Metadata operations (loading/saving) */\n METADATA: 15_000, // 15 seconds\n\n /** AI API calls for translation */\n AI_API: 120_000, // 2 minutes\n\n /** HTTP requests to translation server */\n HTTP_REQUEST: 30_000, // 30 seconds\n\n /** Server initialization */\n SERVER_START: 30_000, // 30 seconds\n\n /** Translation service full operation */\n TRANSLATION: 120_000, // 2 minutes\n} as const;\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,YACd,SACA,WACA,gBAAwB,aACZ;AACZ,QAAO,QAAQ,KAAK,CAClB,SACA,IAAI,SAAY,GAAG,WACjB,iBAEI,OACE,IAAI,aACF,GAAG,cAAc,mBAAmB,UAAU,KAC9C,UACD,CACF,EACH,UACD,CACF,CACF,CAAC;;;;;AAMJ,IAAa,eAAb,cAAkC,MAAM;CACtC,YACE,SACA,AAAgBA,WAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;;;;AAOhB,MAAa,mBAAmB;CAE9B,SAAS;CAGT,UAAU;CAGV,QAAQ;CAGR,cAAc;CAGd,cAAc;CAGd,aAAa;CACd"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingo.dev/compiler",
3
- "version": "0.4.9",
3
+ "version": "0.4.11",
4
4
  "description": "Lingo.dev Compiler",
5
5
  "private": false,
6
6
  "repository": {
@@ -129,7 +129,7 @@
129
129
  "@types/react": "19.2.7",
130
130
  "@types/react-dom": "19.2.3",
131
131
  "@types/ws": "8.18.1",
132
- "next": "16.2.9",
132
+ "next": "16.2.11",
133
133
  "tsdown": "0.18.2",
134
134
  "tsx": "4.21.0",
135
135
  "typescript": "5.9.3",
@@ -161,7 +161,7 @@
161
161
  "posthog-node": "5.14.0",
162
162
  "lmdb": "3.2.6",
163
163
  "ws": "8.21.0",
164
- "lingo.dev": "^0.138.0"
164
+ "lingo.dev": "^0.138.4"
165
165
  },
166
166
  "peerDependencies": {
167
167
  "next": "^15.0.0 || ^16.0.4",