@lingo.dev/compiler 0.4.10 → 0.4.12
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 +1 -0
- package/build/plugin/transform/process-file.cjs +14 -1
- package/build/plugin/transform/process-file.mjs +14 -1
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/react/server/ServerLingoProvider.d.cts +2 -2
- package/build/react/shared/LingoProvider.d.cts +2 -2
- package/build/translators/api.cjs +13 -0
- package/build/translators/api.mjs +13 -1
- package/build/translators/api.mjs.map +1 -1
- package/build/translators/lingo/translator.cjs +16 -12
- package/build/translators/lingo/translator.mjs +17 -13
- package/build/translators/lingo/translator.mjs.map +1 -1
- package/build/translators/pluralization/service.cjs +3 -1
- package/build/translators/pluralization/service.mjs +3 -1
- package/build/translators/pluralization/service.mjs.map +1 -1
- package/build/translators/pluralization/types.d.cts +5 -0
- package/build/translators/pluralization/types.d.mts +5 -0
- package/build/translators/translation-service.cjs +23 -30
- package/build/translators/translation-service.mjs +23 -30
- package/build/translators/translation-service.mjs.map +1 -1
- package/build/types.d.cts +11 -0
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +11 -0
- package/build/types.d.mts.map +1 -1
- package/build/utils/config-factory.cjs +1 -0
- package/build/utils/config-factory.mjs +1 -0
- package/build/utils/config-factory.mjs.map +1 -1
- package/build/utils/timeout.cjs +1 -1
- package/build/utils/timeout.mjs +1 -1
- package/build/utils/timeout.mjs.map +1 -1
- package/package.json +3 -3
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
|
|
@@ -242,9 +242,21 @@ function processJSXElement(path, state) {
|
|
|
242
242
|
const entry = require_utils.createTranslationEntry("content", scope.text, { componentName: component.name }, state.filePath, path.node.loc?.start.line, path.node.loc?.start.column, overrides);
|
|
243
243
|
registerEntry(entry, state, component.name);
|
|
244
244
|
rewriteChildren(path, state, scope, entry.hash);
|
|
245
|
+
if (path.node.type === "JSXElement") path.get("openingElement").traverse(componentVisitors, { visitorState: state });
|
|
245
246
|
path.skip();
|
|
246
247
|
}
|
|
247
248
|
/**
|
|
249
|
+
* Is this node part of the value handed to a JSX attribute?
|
|
250
|
+
*
|
|
251
|
+
* Two visitors need the answer, and neither can get it from the node alone. A
|
|
252
|
+
* function sitting in a prop is a callback, not a component — `inferComponentName`
|
|
253
|
+
* only looks for a name and would happily accept `actions={function renderIt() { … }}`
|
|
254
|
+
* — and an `<html>` sitting in a prop is not the document root.
|
|
255
|
+
*/
|
|
256
|
+
function isInsidePropValue(path) {
|
|
257
|
+
return path.findParent((parent) => parent.isJSXAttribute()) !== null;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
248
260
|
* Inject dynamic locale attribute into <html> elements
|
|
249
261
|
* Transforms: <html> → <html lang={locale}>
|
|
250
262
|
*
|
|
@@ -294,6 +306,7 @@ function addTranslationImports(programPath, state) {
|
|
|
294
306
|
* Handle component function detection and state update
|
|
295
307
|
*/
|
|
296
308
|
function processComponentFunction(path, state) {
|
|
309
|
+
if (isInsidePropValue(path)) return;
|
|
297
310
|
if (!require_utils.isReactComponent(path)) {
|
|
298
311
|
path.skip();
|
|
299
312
|
require_logger.logger.debug(`Skipping non-React component: ${path.node.type}`);
|
|
@@ -332,7 +345,7 @@ const componentVisitors = {
|
|
|
332
345
|
},
|
|
333
346
|
JSXElement(path) {
|
|
334
347
|
translateAttributes(path.node, this.visitorState);
|
|
335
|
-
injectHtmlLangAttribute(path.node, this.visitorState);
|
|
348
|
+
if (!isInsidePropValue(path)) injectHtmlLangAttribute(path.node, this.visitorState);
|
|
336
349
|
if (shouldSkipTranslationForElement(path.node)) {
|
|
337
350
|
path.skip();
|
|
338
351
|
return;
|
|
@@ -240,9 +240,21 @@ function processJSXElement(path, state) {
|
|
|
240
240
|
const entry = createTranslationEntry("content", scope.text, { componentName: component.name }, state.filePath, path.node.loc?.start.line, path.node.loc?.start.column, overrides);
|
|
241
241
|
registerEntry(entry, state, component.name);
|
|
242
242
|
rewriteChildren(path, state, scope, entry.hash);
|
|
243
|
+
if (path.node.type === "JSXElement") path.get("openingElement").traverse(componentVisitors, { visitorState: state });
|
|
243
244
|
path.skip();
|
|
244
245
|
}
|
|
245
246
|
/**
|
|
247
|
+
* Is this node part of the value handed to a JSX attribute?
|
|
248
|
+
*
|
|
249
|
+
* Two visitors need the answer, and neither can get it from the node alone. A
|
|
250
|
+
* function sitting in a prop is a callback, not a component — `inferComponentName`
|
|
251
|
+
* only looks for a name and would happily accept `actions={function renderIt() { … }}`
|
|
252
|
+
* — and an `<html>` sitting in a prop is not the document root.
|
|
253
|
+
*/
|
|
254
|
+
function isInsidePropValue(path) {
|
|
255
|
+
return path.findParent((parent) => parent.isJSXAttribute()) !== null;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
246
258
|
* Inject dynamic locale attribute into <html> elements
|
|
247
259
|
* Transforms: <html> → <html lang={locale}>
|
|
248
260
|
*
|
|
@@ -292,6 +304,7 @@ function addTranslationImports(programPath, state) {
|
|
|
292
304
|
* Handle component function detection and state update
|
|
293
305
|
*/
|
|
294
306
|
function processComponentFunction(path, state) {
|
|
307
|
+
if (isInsidePropValue(path)) return;
|
|
295
308
|
if (!isReactComponent(path)) {
|
|
296
309
|
path.skip();
|
|
297
310
|
logger.debug(`Skipping non-React component: ${path.node.type}`);
|
|
@@ -330,7 +343,7 @@ const componentVisitors = {
|
|
|
330
343
|
},
|
|
331
344
|
JSXElement(path) {
|
|
332
345
|
translateAttributes(path.node, this.visitorState);
|
|
333
|
-
injectHtmlLangAttribute(path.node, this.visitorState);
|
|
346
|
+
if (!isInsidePropValue(path)) injectHtmlLangAttribute(path.node, this.visitorState);
|
|
334
347
|
if (shouldSkipTranslationForElement(path.node)) {
|
|
335
348
|
path.skip();
|
|
336
349
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process-file.mjs","names":["variables: string[]","text","componentEntry: ComponentEntry","state: VisitorsInternalState"],"sources":["../../../src/plugin/transform/process-file.ts"],"sourcesContent":["/**\n * Keep mutations to the current node and children. Do not mutate program inserting imports when processing the component.\n * This should be done in the end.\n * The overall idea is that state is used for side effect tracking. When we exit relevant points, we check if we need to make extra changes at this level.\n * e.g. when we transform elements to insert translations, we record their hashes and add the translation hook call when leaving the component.\n */\nimport * as t from \"@babel/types\";\nimport type { NodePath, TraverseOptions } from \"@babel/traverse\";\nimport type { TranslationEntry } from \"../../types\";\nimport { logger } from \"../../utils/logger\";\nimport {\n comstructUnifiedImport,\n constructServerImport,\n constructTranslationCall,\n createTranslationEntry,\n escapeTextForICU,\n hasUseI18nDirective,\n inferComponentName,\n injectServerHook,\n injectUnifiedHook,\n isReactComponent,\n isVoidElement,\n normalizeWhitespace,\n} from \"./utils\";\nimport {\n type MetadataOutputState,\n processNextDynamicMetadata,\n processNextStaticMetadata,\n} from \"./metadata\";\nimport { traverse } from \"./babel-compat\";\nimport { processOverrideAttributes } from \"./parse-override\";\n\ntype ComponentEntry = {\n name: string;\n isAsync: boolean;\n};\n\n/**\n * State shared between all the visitors.\n */\nexport interface VisitorsInternalState {\n needsDirective: boolean;\n filePath: string;\n newEntries: TranslationEntry[];\n /** Stores component encountered up the tree at the current point, to avoid lookups. */\n componentsStack: ComponentEntry[];\n /** Map component names to their translation hashes */\n componentHashes: Map<string, string[]>;\n /** Track metadata functions that need translation */\n /** Track if we need the unified hook import */\n needsUnifiedImport: boolean;\n /** Track if we need the async API import */\n needsAsyncImport: boolean;\n /** Track which components need locale from hook (for <html> lang attribute) */\n componentsNeedingLocale: Set<string>;\n}\n\nfunction updateWithMetadataState(\n state: VisitorsInternalState,\n newState: MetadataOutputState,\n): VisitorsInternalState {\n state.newEntries = [...state.newEntries, ...newState.newEntries];\n state.needsAsyncImport = state.needsAsyncImport || newState.needsAsyncImport;\n return state;\n}\n\nconst SKIP_ATTRIBUTE = \"data-lingo-skip\";\n\n/**\n * Elements whose content should not be translated by default.\n * These are typically code-related or technical elements where translation\n * would break functionality or meaning.\n */\nconst NON_TRANSLATABLE_ELEMENTS = new Set([\n \"code\",\n \"pre\",\n \"script\",\n \"style\",\n \"kbd\",\n \"samp\",\n \"var\",\n]);\n\nconst TRANSLATABLE_ATTRIBUTES = new Set([\n \"title\",\n \"aria-label\",\n \"aria-description\",\n \"alt\",\n \"label\",\n \"description\",\n \"placeholder\",\n \"content\",\n \"subtitle\",\n]);\n\n/**\n * Check if a JSX element should skip translation based on:\n * 1. Element type (code, pre, script, style, etc.)\n * 2. translate=\"no\" attribute (HTML standard)\n * 3. data-lingo-skip attribute\n */\nfunction shouldSkipTranslationForElement(\n element: t.JSXElement | t.JSXFragment,\n): boolean {\n // We always translate fragments\n if (element.type === \"JSXFragment\") {\n return false;\n }\n const openingElement = element.openingElement;\n\n // Check element type\n if (openingElement.name.type === \"JSXIdentifier\") {\n if (NON_TRANSLATABLE_ELEMENTS.has(openingElement.name.name)) {\n return true;\n }\n }\n\n for (const attr of openingElement.attributes) {\n if (attr.type === \"JSXAttribute\" && attr.name.type === \"JSXIdentifier\") {\n // Check for translate=\"no\" (HTML standard)\n if (attr.name.name === \"translate\") {\n if (attr.value?.type === \"StringLiteral\" && attr.value.value === \"no\") {\n return true;\n }\n }\n\n if (attr.name.name === SKIP_ATTRIBUTE) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n// Called even on the element which are not translatable.\nfunction translateAttributes(\n node: t.JSXElement,\n state: VisitorsInternalState,\n): void {\n const openingElement = node.openingElement;\n\n const component = state.componentsStack.at(-1);\n if (!component) return;\n\n for (const attr of openingElement.attributes) {\n if (\n attr.type === \"JSXAttribute\" &&\n attr.name.type === \"JSXIdentifier\" &&\n TRANSLATABLE_ATTRIBUTES.has(attr.name.name) &&\n attr.value?.type === \"StringLiteral\"\n ) {\n const text = normalizeWhitespace(attr.value.value);\n if (text.length == 0) continue;\n\n const entry = createTranslationEntry(\n \"attribute\",\n text,\n {\n attributeName: attr.name.name,\n componentName: component.name,\n },\n state.filePath,\n node.loc?.start.line,\n node.loc?.start.column,\n );\n registerEntry(entry, state, component.name);\n\n attr.value = constructTranslationCall(entry.hash, text);\n }\n }\n}\n\n/**\n * Check if a JSX element has mixed content that needs rich text translation\n * Mixed content = text nodes + expressions + nested JSX elements (excluding void elements)\n */\nfunction hasMixedContent(element: t.JSXElement | t.JSXFragment): boolean {\n const children = element.children;\n if (children.length === 0) return false;\n // 001\n // 221\n // 101\n // States:\n // 0 - no text or translatable nodes\n // 1 - text node\n // 2 - expression or translatable element\n // 3 - interrupted text node\n // 4 - mixed\n //\n let state = 0;\n\n for (const child of children) {\n if (child.type === \"JSXText\") {\n if (child.value.trim().length > 0) {\n switch (state) {\n case 0:\n state = 1;\n break;\n case 1:\n break;\n case 2:\n return true;\n case 3:\n return true;\n }\n }\n // Expressions require a substitution of the placeholder and are usually a part of the text so should be translated in one context\n } else if (child.type === \"JSXExpressionContainer\") {\n switch (state) {\n case 0:\n state = 2;\n break;\n case 1:\n return true;\n case 2:\n break;\n case 3:\n return true;\n }\n } else if (child.type === \"JSXElement\") {\n if (!isVoidElement(child)) {\n switch (state) {\n case 0:\n state = 2;\n break;\n case 1:\n return true;\n case 2:\n break;\n case 3:\n return true;\n }\n } else {\n switch (state) {\n case 0:\n break;\n case 1:\n state = 3;\n break;\n case 2:\n break;\n case 3:\n break;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Result of serializing JSX children to a translation string\n */\ninterface SerializedJSX {\n /** The serialized string with placeholders, e.g. \"Hello {name}, you have <strong0>{count}</strong0> messages\" */\n text: string;\n /** Variable identifiers extracted from expressions, e.g. [\"name\", \"count\"] */\n variables: string[];\n expressions: Map<string, t.Expression>;\n /** Component mappings for nested elements, e.g. { strong0: <strong>...</strong> } */\n components: Map<string, t.JSXElement>;\n}\n\n/**\n * Serialize JSX children to a translation string with placeholders\n */\nfunction serializeJSXChildren(\n children: Array<\n | t.JSXText\n | t.JSXExpressionContainer\n | t.JSXElement\n | t.JSXSpreadChild\n | t.JSXFragment\n >,\n state: VisitorsInternalState,\n): SerializedJSX {\n let text = \"\";\n const variables: string[] = [];\n const expressions = new Map<string, t.Expression>();\n const components = new Map<string, t.JSXElement>();\n const elementCounts = new Map<string, number>();\n\n for (const child of children) {\n if (child.type === \"JSXText\") {\n // Normalize whitespace within this text node\n let normalized = normalizeWhitespace(child.value);\n\n // If we have accumulated text and this node starts with whitespace,\n // ensure there's a space separator\n if (\n text.length > 0 &&\n child.value.match(/^\\s/) &&\n normalized.length > 0\n ) {\n if (!text.endsWith(\" \")) {\n normalized = ` ${normalized}`;\n }\n }\n\n // If this node ends with whitespace and has content, add trailing space\n if (normalized.length > 0 && child.value.match(/\\s$/)) {\n if (!text.endsWith(\" \")) {\n normalized = `${normalized} `;\n }\n }\n\n text += escapeTextForICU(normalized);\n } else if (child.type === \"JSXExpressionContainer\") {\n // Extract variable name from expression\n const expr = child.expression;\n if (expr.type === \"Identifier\") {\n text += `{${expr.name}}`;\n if (!variables.includes(expr.name)) {\n variables.push(expr.name);\n }\n } else if (expr.type === \"StringLiteral\") {\n // String literal (like {\" \"}) - include the literal text directly\n text += escapeTextForICU(expr.value);\n } else if (expr.type !== \"JSXEmptyExpression\") {\n const name = `expression${expressions.size}`;\n text += `{${name}}`;\n expressions.set(name, expr);\n }\n } else if (child.type === \"JSXElement\") {\n let shouldTranslate = true;\n // Skip void elements (they cannot have children and shouldn't be in rich text)\n if (isVoidElement(child)) {\n // Void elements are ignored in the translation string\n // They will remain in their original position in the JSX tree\n shouldTranslate = false;\n }\n\n // Skip elements that should not be translated (code, pre, etc.)\n // These elements remain in the JSX tree but are not included in translation\n if (shouldSkipTranslationForElement(child)) {\n shouldTranslate = false;\n }\n\n // Get element name\n const openingElement = child.openingElement;\n let elementName = \"\";\n if (openingElement.name.type === \"JSXIdentifier\") {\n elementName = openingElement.name.name;\n } else {\n // TODO (AleksandrSl 02/12/2025): What is this corner case?\n // I thought it may be a fragment, but it seems that fragment is a separate JSXFragment node.\n elementName = \"element\";\n }\n\n // Generate unique tag name with index\n const count = elementCounts.get(elementName) || 0;\n elementCounts.set(elementName, count + 1);\n const tagName = `${elementName}${count}`;\n\n translateAttributes(child, state);\n\n if (shouldTranslate) {\n // Recursively serialize nested content\n const nested = serializeJSXChildren(child.children, state);\n text += `<${tagName}>${nested.text}</${tagName}>`;\n\n // Merge nested variables\n for (const v of nested.variables) {\n if (!variables.includes(v)) {\n variables.push(v);\n }\n }\n\n // Merge nested component mappings with prefixes to avoid conflicts\n for (const [nestedTag, nestedElement] of nested.components) {\n components.set(`${tagName}_${nestedTag}`, nestedElement);\n }\n } else {\n // There is no support for self-closing tags in format js, so we should generate empty ones.\n text += `<${tagName}></${tagName}>`;\n child.extra = {\n ...child.extra,\n shouldTranslate: false,\n };\n }\n\n // Store component mapping\n components.set(tagName, child);\n }\n }\n\n return { text, variables, expressions, components };\n}\n\nfunction transformVoidElement(\n node: t.JSXElement,\n state: VisitorsInternalState,\n) {\n translateAttributes(node, state);\n}\n\ntype TranslationScope =\n | { kind: \"mixed\"; text: string; args: any }\n | { kind: \"text\"; text: string; textNodeIndex: number };\n\nfunction getTranslationScope(\n node: t.JSXElement | t.JSXFragment,\n state: VisitorsInternalState,\n): TranslationScope | null {\n if (hasMixedContent(node)) {\n const serialized = serializeJSXChildren(node.children, state);\n const text = serialized.text.trim();\n if (text.length === 0) return null;\n\n return {\n kind: \"mixed\",\n text,\n args: {\n variables: serialized.variables,\n expressions: serialized.expressions,\n components: serialized.components,\n },\n };\n }\n\n // Non-mixed: allow exactly one meaningful JSXText + optional void elements + whitespace\n const textNodeIndex = node.children.findIndex(\n (child) => child.type === \"JSXText\" && child.value.trim().length > 0,\n );\n if (textNodeIndex === -1) return null;\n\n const allowed = node.children.every(\n (child) =>\n child.type === \"JSXText\" ||\n (child.type === \"JSXElement\" && isVoidElement(child)),\n );\n if (!allowed) return null;\n\n const textNode = node.children[textNodeIndex] as t.JSXText;\n const text = normalizeWhitespace(textNode.value);\n if (text.length === 0) return null;\n\n return { kind: \"text\", text, textNodeIndex };\n}\n\nfunction registerEntry(\n entry: ReturnType<typeof createTranslationEntry>,\n state: VisitorsInternalState,\n componentName: string,\n) {\n state.newEntries.push(entry);\n\n const hashes = state.componentHashes.get(componentName) ?? [];\n hashes.push(entry.hash);\n state.componentHashes.set(componentName, hashes);\n}\n\nfunction rewriteChildren(\n path: NodePath<t.JSXElement | t.JSXFragment>,\n state: VisitorsInternalState,\n translationScope: TranslationScope,\n entryHash: string,\n) {\n if (translationScope.kind === \"mixed\") {\n path.node.children = [\n constructTranslationCall(\n entryHash,\n translationScope.text,\n translationScope.args,\n ),\n ];\n return;\n }\n\n const { textNodeIndex, text } = translationScope;\n\n path.node.children = path.node.children.map((child, index) => {\n if (index === textNodeIndex) {\n return constructTranslationCall(entryHash, text);\n }\n if (child.type === \"JSXElement\") {\n transformVoidElement(child, state);\n }\n return child;\n });\n}\n\nfunction processJSXElement(\n path: NodePath<t.JSXElement | t.JSXFragment>,\n state: VisitorsInternalState,\n): void {\n const component = state.componentsStack.at(-1);\n if (!component) return;\n\n const scope = getTranslationScope(path.node, state);\n if (!scope) return;\n\n const overrides = processOverrideAttributes(path);\n\n const entry = createTranslationEntry(\n \"content\",\n scope.text,\n { componentName: component.name },\n state.filePath,\n path.node.loc?.start.line,\n path.node.loc?.start.column,\n overrides,\n );\n\n registerEntry(entry, state, component.name);\n rewriteChildren(path, state, scope, entry.hash);\n\n path.skip();\n}\n\n/**\n * Inject dynamic locale attribute into <html> elements\n * Transforms: <html> → <html lang={locale}>\n *\n * Only injects if:\n * 1. Element is <html>\n * 2. No existing lang/language attribute\n * 3. We're inside a React component (has locale context)\n */\nfunction injectHtmlLangAttribute(\n node: t.JSXElement,\n state: VisitorsInternalState,\n): void {\n const openingElement = node.openingElement;\n\n if (\n openingElement.name.type !== \"JSXIdentifier\" ||\n openingElement.name.name !== \"html\"\n ) {\n return;\n }\n\n // Check if lang attribute already exists\n const hasLangAttr = openingElement.attributes.some((attr) => {\n return (\n attr.type === \"JSXAttribute\" &&\n attr.name.type === \"JSXIdentifier\" &&\n (attr.name.name === \"lang\" || attr.name.name === \"language\")\n );\n });\n\n if (hasLangAttr) {\n // Already has lang attribute, don't inject\n return;\n }\n\n // Check if we're inside a component (has access to locale context)\n const component = state.componentsStack.at(-1);\n if (!component) {\n // Not inside a component, can't inject locale\n return;\n }\n\n // Inject lang={locale} attribute\n // This creates: <html lang={locale}>\n const langAttr = t.jsxAttribute(\n t.jsxIdentifier(\"lang\"),\n t.jsxExpressionContainer(t.identifier(\"locale\")),\n );\n\n openingElement.attributes.push(langAttr);\n\n logger.debug(\n `Injected locale attribute into <html> element in component: ${component.name}`,\n );\n\n // Mark that this component needs locale destructured from the hook\n state.componentsNeedingLocale.add(component.name);\n}\n\n/**\n * Inject translation hook into a component when it's done processing\n * Called when popping component from stack\n */\nexport function injectTranslationHook(\n path: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n component: ComponentEntry,\n state: VisitorsInternalState,\n): void {\n const needsLocale = state.componentsNeedingLocale.has(component.name);\n const hashes = state.componentHashes.get(component.name);\n if ((!hashes || hashes.length === 0) && !needsLocale) {\n return; // No translations needed\n }\n\n if (component.isAsync) {\n // Async component uses getServerTranslations\n injectServerHook(path, hashes ?? [], needsLocale);\n state.needsAsyncImport = true;\n } else {\n // Non-async component uses unified hook (useTranslation)\n injectUnifiedHook(path, hashes ?? [], needsLocale);\n state.needsUnifiedImport = true;\n }\n}\n\n/**\n * Add translation imports at the top of the file\n * Called on Program exit after all components have been processed\n */\nfunction addTranslationImports(\n programPath: NodePath<t.Program>,\n state: VisitorsInternalState,\n): void {\n // A file can have both async and non-async components!\n if (state.needsAsyncImport) {\n programPath.node.body.unshift(constructServerImport());\n }\n if (state.needsUnifiedImport) {\n programPath.node.body.unshift(comstructUnifiedImport());\n }\n}\n\n/**\n * Handle component function detection and state update\n */\nfunction processComponentFunction(\n path: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n state: VisitorsInternalState,\n): void {\n if (!isReactComponent(path)) {\n path.skip();\n logger.debug(`Skipping non-React component: ${path.node.type}`);\n return;\n }\n\n const componentName = inferComponentName(path);\n if (!componentName) {\n path.skip();\n return;\n }\n\n // Store component info for later hook injection\n if (!state.componentHashes.has(componentName)) {\n state.componentHashes.set(componentName, []);\n }\n\n // Push component to stack with async info and path reference\n const componentEntry: ComponentEntry = {\n name: componentName,\n isAsync: path.node.async,\n };\n state.componentsStack.push(componentEntry);\n logger.debug(`Component ${JSON.stringify(componentEntry)} entered`);\n\n path.setData(\"componentName\", componentName);\n path.traverse(componentVisitors, { visitorState: state });\n const component = state.componentsStack.pop();\n if (component) {\n injectTranslationHook(path, component, state);\n }\n // We have already traversed the path's children so the main traverse can skip it.\n path.skip();\n}\n\nconst componentVisitors = {\n // 1. Handle nested components. FunctionDeclaration|FunctionExpression|ArrowFunctionExpression unfortunately doesn't give the correct type signature for the path.\n FunctionDeclaration(path: NodePath<t.FunctionDeclaration>) {\n processComponentFunction(path, this.visitorState);\n },\n ArrowFunctionExpression(path: NodePath<t.ArrowFunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n FunctionExpression(path: NodePath<t.FunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n // 2. Fragments are separate from other JSX elements. Both <> and <Fragment> are the same AST node type.\n JSXFragment(path: NodePath<t.JSXFragment>) {\n // No attributes to translate on the fragment, so we only check if it has mixed content. If it doesn't, go ahead and its children will be checked.\n // We also do not check for translation skip, because fragments are mostly used to make the bare text translatable.\n // But if we want to support <Fragment data-lingo-skip>Text</Fragment> we should do it here.\n processJSXElement(path, this.visitorState);\n },\n\n // Transform JSX elements with mixed content (text + expressions or nested elements)\n JSXElement(path: NodePath<t.JSXElement>) {\n translateAttributes(path.node, this.visitorState);\n\n // Inject locale attribute into <html> elements for Next.js\n injectHtmlLangAttribute(path.node, this.visitorState);\n\n if (shouldSkipTranslationForElement(path.node)) {\n path.skip();\n return;\n }\n processJSXElement(path, this.visitorState);\n },\n} satisfies TraverseOptions<{ visitorState: VisitorsInternalState }>;\n\nconst fileVisitors = {\n // Handle static metadata exports: export const metadata = { ... }\n ExportNamedDeclaration(path: NodePath<t.ExportNamedDeclaration>) {\n // Check if the export is a metadata export and converts it to a function\n const metadataState = processNextStaticMetadata(path, {\n filePath: this.visitorState.filePath,\n });\n\n if (metadataState) {\n updateWithMetadataState(this.visitorState, metadataState);\n }\n },\n\n // All component function types share the same handler\n FunctionDeclaration(path: NodePath<t.FunctionDeclaration>) {\n const metadataState = processNextDynamicMetadata(path, {\n filePath: this.visitorState.filePath,\n });\n if (metadataState) {\n updateWithMetadataState(this.visitorState, metadataState);\n }\n\n // Otherwise, handle as component\n processComponentFunction(path, this.visitorState);\n },\n\n // export const MyComponent = () => {}\n ArrowFunctionExpression(path: NodePath<t.ArrowFunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n\n // All these are considered function expressions\n // const myFunction = function() {\n // return 'hello';\n // };\n //\n // const myFunction2 = function namedFunc() {\n // return 'hello';\n // };\n //\n // setTimeout(function() {\n // console.log('hello');\n // }, 1000);\n // While\n // export default function() {}\n // is not\n FunctionExpression(path: NodePath<t.FunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n} satisfies TraverseOptions<{ visitorState: VisitorsInternalState }>;\n\n/**\n * Create Babel visitors for auto-translation (single-pass transformation)\n */\nconst programVisitor = {\n Program: {\n enter(path: NodePath<t.Program>) {\n // We do the check on the loader level, but since they could be false positive, accepting the files we don't need to process, we do the check here as well.\n if (this.visitorState.needsDirective && !hasUseI18nDirective(path)) {\n path.skip();\n return;\n }\n\n path.traverse(fileVisitors, {\n visitorState: this.visitorState,\n });\n },\n\n exit(path: NodePath<t.Program>) {\n if (\n this.visitorState.needsUnifiedImport ||\n this.visitorState.needsAsyncImport\n ) {\n addTranslationImports(path, this.visitorState);\n }\n },\n },\n} satisfies TraverseOptions<{ visitorState: VisitorsInternalState }>;\n\nexport function processFile(\n ast: t.Node,\n options: { relativeFilePath: string; needsDirective: boolean },\n) {\n const state: VisitorsInternalState = {\n needsDirective: options.needsDirective,\n filePath: options.relativeFilePath,\n newEntries: [],\n componentsStack: [],\n componentHashes: new Map<string, string[]>(),\n needsUnifiedImport: false,\n needsAsyncImport: false,\n componentsNeedingLocale: new Set<string>(),\n };\n\n traverse(ast, programVisitor, undefined, { visitorState: state });\n\n return state.newEntries;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyDA,SAAS,wBACP,OACA,UACuB;AACvB,OAAM,aAAa,CAAC,GAAG,MAAM,YAAY,GAAG,SAAS,WAAW;AAChE,OAAM,mBAAmB,MAAM,oBAAoB,SAAS;AAC5D,QAAO;;AAGT,MAAM,iBAAiB;;;;;;AAOvB,MAAM,4BAA4B,IAAI,IAAI;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,0BAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;AAQF,SAAS,gCACP,SACS;AAET,KAAI,QAAQ,SAAS,cACnB,QAAO;CAET,MAAM,iBAAiB,QAAQ;AAG/B,KAAI,eAAe,KAAK,SAAS,iBAC/B;MAAI,0BAA0B,IAAI,eAAe,KAAK,KAAK,CACzD,QAAO;;AAIX,MAAK,MAAM,QAAQ,eAAe,WAChC,KAAI,KAAK,SAAS,kBAAkB,KAAK,KAAK,SAAS,iBAAiB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,CAAC;AACF,MAAI,cACF,yBAAwB,KAAK,cAAc,cAAc;AAI3D,2BAAyB,MAAM,KAAK,aAAa;;CAInD,wBAAwB,MAA2C;AACjE,2BAAyB,MAAM,KAAK,aAAa;;CAkBnD,mBAAmB,MAAsC;AACvD,2BAAyB,MAAM,KAAK,aAAa;;CAEpD;;;;AAKD,MAAM,iBAAiB,EACrB,SAAS;CACP,MAAM,MAA2B;AAE/B,MAAI,KAAK,aAAa,kBAAkB,CAAC,oBAAoB,KAAK,EAAE;AAClE,QAAK,MAAM;AACX;;AAGF,OAAK,SAAS,cAAc,EAC1B,cAAc,KAAK,cACpB,CAAC;;CAGJ,KAAK,MAA2B;AAC9B,MACE,KAAK,aAAa,sBAClB,KAAK,aAAa,iBAElB,uBAAsB,MAAM,KAAK,aAAa;;CAGnD,EACF;AAED,SAAgB,YACd,KACA,SACA;CACA,MAAMC,QAA+B;EACnC,gBAAgB,QAAQ;EACxB,UAAU,QAAQ;EAClB,YAAY,EAAE;EACd,iBAAiB,EAAE;EACnB,iCAAiB,IAAI,KAAuB;EAC5C,oBAAoB;EACpB,kBAAkB;EAClB,yCAAyB,IAAI,KAAa;EAC3C;AAED,UAAS,KAAK,gBAAgB,QAAW,EAAE,cAAc,OAAO,CAAC;AAEjE,QAAO,MAAM"}
|
|
1
|
+
{"version":3,"file":"process-file.mjs","names":["variables: string[]","text","componentEntry: ComponentEntry","state: VisitorsInternalState"],"sources":["../../../src/plugin/transform/process-file.ts"],"sourcesContent":["/**\n * Keep mutations to the current node and children. Do not mutate program inserting imports when processing the component.\n * This should be done in the end.\n * The overall idea is that state is used for side effect tracking. When we exit relevant points, we check if we need to make extra changes at this level.\n * e.g. when we transform elements to insert translations, we record their hashes and add the translation hook call when leaving the component.\n */\nimport * as t from \"@babel/types\";\nimport type { NodePath, TraverseOptions } from \"@babel/traverse\";\nimport type { TranslationEntry } from \"../../types\";\nimport { logger } from \"../../utils/logger\";\nimport {\n comstructUnifiedImport,\n constructServerImport,\n constructTranslationCall,\n createTranslationEntry,\n escapeTextForICU,\n hasUseI18nDirective,\n inferComponentName,\n injectServerHook,\n injectUnifiedHook,\n isReactComponent,\n isVoidElement,\n normalizeWhitespace,\n} from \"./utils\";\nimport {\n type MetadataOutputState,\n processNextDynamicMetadata,\n processNextStaticMetadata,\n} from \"./metadata\";\nimport { traverse } from \"./babel-compat\";\nimport { processOverrideAttributes } from \"./parse-override\";\n\ntype ComponentEntry = {\n name: string;\n isAsync: boolean;\n};\n\n/**\n * State shared between all the visitors.\n */\nexport interface VisitorsInternalState {\n needsDirective: boolean;\n filePath: string;\n newEntries: TranslationEntry[];\n /** Stores component encountered up the tree at the current point, to avoid lookups. */\n componentsStack: ComponentEntry[];\n /** Map component names to their translation hashes */\n componentHashes: Map<string, string[]>;\n /** Track metadata functions that need translation */\n /** Track if we need the unified hook import */\n needsUnifiedImport: boolean;\n /** Track if we need the async API import */\n needsAsyncImport: boolean;\n /** Track which components need locale from hook (for <html> lang attribute) */\n componentsNeedingLocale: Set<string>;\n}\n\nfunction updateWithMetadataState(\n state: VisitorsInternalState,\n newState: MetadataOutputState,\n): VisitorsInternalState {\n state.newEntries = [...state.newEntries, ...newState.newEntries];\n state.needsAsyncImport = state.needsAsyncImport || newState.needsAsyncImport;\n return state;\n}\n\nconst SKIP_ATTRIBUTE = \"data-lingo-skip\";\n\n/**\n * Elements whose content should not be translated by default.\n * These are typically code-related or technical elements where translation\n * would break functionality or meaning.\n */\nconst NON_TRANSLATABLE_ELEMENTS = new Set([\n \"code\",\n \"pre\",\n \"script\",\n \"style\",\n \"kbd\",\n \"samp\",\n \"var\",\n]);\n\nconst TRANSLATABLE_ATTRIBUTES = new Set([\n \"title\",\n \"aria-label\",\n \"aria-description\",\n \"alt\",\n \"label\",\n \"description\",\n \"placeholder\",\n \"content\",\n \"subtitle\",\n]);\n\n/**\n * Check if a JSX element should skip translation based on:\n * 1. Element type (code, pre, script, style, etc.)\n * 2. translate=\"no\" attribute (HTML standard)\n * 3. data-lingo-skip attribute\n */\nfunction shouldSkipTranslationForElement(\n element: t.JSXElement | t.JSXFragment,\n): boolean {\n // We always translate fragments\n if (element.type === \"JSXFragment\") {\n return false;\n }\n const openingElement = element.openingElement;\n\n // Check element type\n if (openingElement.name.type === \"JSXIdentifier\") {\n if (NON_TRANSLATABLE_ELEMENTS.has(openingElement.name.name)) {\n return true;\n }\n }\n\n for (const attr of openingElement.attributes) {\n if (attr.type === \"JSXAttribute\" && attr.name.type === \"JSXIdentifier\") {\n // Check for translate=\"no\" (HTML standard)\n if (attr.name.name === \"translate\") {\n if (attr.value?.type === \"StringLiteral\" && attr.value.value === \"no\") {\n return true;\n }\n }\n\n if (attr.name.name === SKIP_ATTRIBUTE) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n// Called even on the element which are not translatable.\nfunction translateAttributes(\n node: t.JSXElement,\n state: VisitorsInternalState,\n): void {\n const openingElement = node.openingElement;\n\n const component = state.componentsStack.at(-1);\n if (!component) return;\n\n for (const attr of openingElement.attributes) {\n if (\n attr.type === \"JSXAttribute\" &&\n attr.name.type === \"JSXIdentifier\" &&\n TRANSLATABLE_ATTRIBUTES.has(attr.name.name) &&\n attr.value?.type === \"StringLiteral\"\n ) {\n const text = normalizeWhitespace(attr.value.value);\n if (text.length == 0) continue;\n\n const entry = createTranslationEntry(\n \"attribute\",\n text,\n {\n attributeName: attr.name.name,\n componentName: component.name,\n },\n state.filePath,\n node.loc?.start.line,\n node.loc?.start.column,\n );\n registerEntry(entry, state, component.name);\n\n attr.value = constructTranslationCall(entry.hash, text);\n }\n }\n}\n\n/**\n * Check if a JSX element has mixed content that needs rich text translation\n * Mixed content = text nodes + expressions + nested JSX elements (excluding void elements)\n */\nfunction hasMixedContent(element: t.JSXElement | t.JSXFragment): boolean {\n const children = element.children;\n if (children.length === 0) return false;\n // 001\n // 221\n // 101\n // States:\n // 0 - no text or translatable nodes\n // 1 - text node\n // 2 - expression or translatable element\n // 3 - interrupted text node\n // 4 - mixed\n //\n let state = 0;\n\n for (const child of children) {\n if (child.type === \"JSXText\") {\n if (child.value.trim().length > 0) {\n switch (state) {\n case 0:\n state = 1;\n break;\n case 1:\n break;\n case 2:\n return true;\n case 3:\n return true;\n }\n }\n // Expressions require a substitution of the placeholder and are usually a part of the text so should be translated in one context\n } else if (child.type === \"JSXExpressionContainer\") {\n switch (state) {\n case 0:\n state = 2;\n break;\n case 1:\n return true;\n case 2:\n break;\n case 3:\n return true;\n }\n } else if (child.type === \"JSXElement\") {\n if (!isVoidElement(child)) {\n switch (state) {\n case 0:\n state = 2;\n break;\n case 1:\n return true;\n case 2:\n break;\n case 3:\n return true;\n }\n } else {\n switch (state) {\n case 0:\n break;\n case 1:\n state = 3;\n break;\n case 2:\n break;\n case 3:\n break;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Result of serializing JSX children to a translation string\n */\ninterface SerializedJSX {\n /** The serialized string with placeholders, e.g. \"Hello {name}, you have <strong0>{count}</strong0> messages\" */\n text: string;\n /** Variable identifiers extracted from expressions, e.g. [\"name\", \"count\"] */\n variables: string[];\n expressions: Map<string, t.Expression>;\n /** Component mappings for nested elements, e.g. { strong0: <strong>...</strong> } */\n components: Map<string, t.JSXElement>;\n}\n\n/**\n * Serialize JSX children to a translation string with placeholders\n */\nfunction serializeJSXChildren(\n children: Array<\n | t.JSXText\n | t.JSXExpressionContainer\n | t.JSXElement\n | t.JSXSpreadChild\n | t.JSXFragment\n >,\n state: VisitorsInternalState,\n): SerializedJSX {\n let text = \"\";\n const variables: string[] = [];\n const expressions = new Map<string, t.Expression>();\n const components = new Map<string, t.JSXElement>();\n const elementCounts = new Map<string, number>();\n\n for (const child of children) {\n if (child.type === \"JSXText\") {\n // Normalize whitespace within this text node\n let normalized = normalizeWhitespace(child.value);\n\n // If we have accumulated text and this node starts with whitespace,\n // ensure there's a space separator\n if (\n text.length > 0 &&\n child.value.match(/^\\s/) &&\n normalized.length > 0\n ) {\n if (!text.endsWith(\" \")) {\n normalized = ` ${normalized}`;\n }\n }\n\n // If this node ends with whitespace and has content, add trailing space\n if (normalized.length > 0 && child.value.match(/\\s$/)) {\n if (!text.endsWith(\" \")) {\n normalized = `${normalized} `;\n }\n }\n\n text += escapeTextForICU(normalized);\n } else if (child.type === \"JSXExpressionContainer\") {\n // Extract variable name from expression\n const expr = child.expression;\n if (expr.type === \"Identifier\") {\n text += `{${expr.name}}`;\n if (!variables.includes(expr.name)) {\n variables.push(expr.name);\n }\n } else if (expr.type === \"StringLiteral\") {\n // String literal (like {\" \"}) - include the literal text directly\n text += escapeTextForICU(expr.value);\n } else if (expr.type !== \"JSXEmptyExpression\") {\n const name = `expression${expressions.size}`;\n text += `{${name}}`;\n expressions.set(name, expr);\n }\n } else if (child.type === \"JSXElement\") {\n let shouldTranslate = true;\n // Skip void elements (they cannot have children and shouldn't be in rich text)\n if (isVoidElement(child)) {\n // Void elements are ignored in the translation string\n // They will remain in their original position in the JSX tree\n shouldTranslate = false;\n }\n\n // Skip elements that should not be translated (code, pre, etc.)\n // These elements remain in the JSX tree but are not included in translation\n if (shouldSkipTranslationForElement(child)) {\n shouldTranslate = false;\n }\n\n // Get element name\n const openingElement = child.openingElement;\n let elementName = \"\";\n if (openingElement.name.type === \"JSXIdentifier\") {\n elementName = openingElement.name.name;\n } else {\n // TODO (AleksandrSl 02/12/2025): What is this corner case?\n // I thought it may be a fragment, but it seems that fragment is a separate JSXFragment node.\n elementName = \"element\";\n }\n\n // Generate unique tag name with index\n const count = elementCounts.get(elementName) || 0;\n elementCounts.set(elementName, count + 1);\n const tagName = `${elementName}${count}`;\n\n translateAttributes(child, state);\n\n if (shouldTranslate) {\n // Recursively serialize nested content\n const nested = serializeJSXChildren(child.children, state);\n text += `<${tagName}>${nested.text}</${tagName}>`;\n\n // Merge nested variables\n for (const v of nested.variables) {\n if (!variables.includes(v)) {\n variables.push(v);\n }\n }\n\n // Merge nested component mappings with prefixes to avoid conflicts\n for (const [nestedTag, nestedElement] of nested.components) {\n components.set(`${tagName}_${nestedTag}`, nestedElement);\n }\n } else {\n // There is no support for self-closing tags in format js, so we should generate empty ones.\n text += `<${tagName}></${tagName}>`;\n child.extra = {\n ...child.extra,\n shouldTranslate: false,\n };\n }\n\n // Store component mapping\n components.set(tagName, child);\n }\n }\n\n return { text, variables, expressions, components };\n}\n\nfunction transformVoidElement(\n node: t.JSXElement,\n state: VisitorsInternalState,\n) {\n translateAttributes(node, state);\n}\n\ntype TranslationScope =\n | { kind: \"mixed\"; text: string; args: any }\n | { kind: \"text\"; text: string; textNodeIndex: number };\n\nfunction getTranslationScope(\n node: t.JSXElement | t.JSXFragment,\n state: VisitorsInternalState,\n): TranslationScope | null {\n if (hasMixedContent(node)) {\n const serialized = serializeJSXChildren(node.children, state);\n const text = serialized.text.trim();\n if (text.length === 0) return null;\n\n return {\n kind: \"mixed\",\n text,\n args: {\n variables: serialized.variables,\n expressions: serialized.expressions,\n components: serialized.components,\n },\n };\n }\n\n // Non-mixed: allow exactly one meaningful JSXText + optional void elements + whitespace\n const textNodeIndex = node.children.findIndex(\n (child) => child.type === \"JSXText\" && child.value.trim().length > 0,\n );\n if (textNodeIndex === -1) return null;\n\n const allowed = node.children.every(\n (child) =>\n child.type === \"JSXText\" ||\n (child.type === \"JSXElement\" && isVoidElement(child)),\n );\n if (!allowed) return null;\n\n const textNode = node.children[textNodeIndex] as t.JSXText;\n const text = normalizeWhitespace(textNode.value);\n if (text.length === 0) return null;\n\n return { kind: \"text\", text, textNodeIndex };\n}\n\nfunction registerEntry(\n entry: ReturnType<typeof createTranslationEntry>,\n state: VisitorsInternalState,\n componentName: string,\n) {\n state.newEntries.push(entry);\n\n const hashes = state.componentHashes.get(componentName) ?? [];\n hashes.push(entry.hash);\n state.componentHashes.set(componentName, hashes);\n}\n\nfunction rewriteChildren(\n path: NodePath<t.JSXElement | t.JSXFragment>,\n state: VisitorsInternalState,\n translationScope: TranslationScope,\n entryHash: string,\n) {\n if (translationScope.kind === \"mixed\") {\n path.node.children = [\n constructTranslationCall(\n entryHash,\n translationScope.text,\n translationScope.args,\n ),\n ];\n return;\n }\n\n const { textNodeIndex, text } = translationScope;\n\n path.node.children = path.node.children.map((child, index) => {\n if (index === textNodeIndex) {\n return constructTranslationCall(entryHash, text);\n }\n if (child.type === \"JSXElement\") {\n transformVoidElement(child, state);\n }\n return child;\n });\n}\n\nfunction processJSXElement(\n path: NodePath<t.JSXElement | t.JSXFragment>,\n state: VisitorsInternalState,\n): void {\n const component = state.componentsStack.at(-1);\n if (!component) return;\n\n const scope = getTranslationScope(path.node, state);\n if (!scope) return;\n\n const overrides = processOverrideAttributes(path);\n\n const entry = createTranslationEntry(\n \"content\",\n scope.text,\n { componentName: component.name },\n state.filePath,\n path.node.loc?.start.line,\n path.node.loc?.start.column,\n overrides,\n );\n\n registerEntry(entry, state, component.name);\n rewriteChildren(path, state, scope, entry.hash);\n\n // `path.skip()` below prunes the whole subtree, `openingElement` included, so JSX\n // handed to this element through an attribute (`actions={<span>Text</span>}`) would\n // never be visited. Traverse the opening element first. Fragments have no attributes.\n if (path.node.type === \"JSXElement\") {\n path.get(\"openingElement\").traverse(componentVisitors, { visitorState: state });\n }\n\n path.skip();\n}\n\n/**\n * Is this node part of the value handed to a JSX attribute?\n *\n * Two visitors need the answer, and neither can get it from the node alone. A\n * function sitting in a prop is a callback, not a component — `inferComponentName`\n * only looks for a name and would happily accept `actions={function renderIt() { … }}`\n * — and an `<html>` sitting in a prop is not the document root.\n */\nfunction isInsidePropValue(path: NodePath): boolean {\n return path.findParent((parent) => parent.isJSXAttribute()) !== null;\n}\n\n/**\n * Inject dynamic locale attribute into <html> elements\n * Transforms: <html> → <html lang={locale}>\n *\n * Only injects if:\n * 1. Element is <html>\n * 2. No existing lang/language attribute\n * 3. We're inside a React component (has locale context)\n */\nfunction injectHtmlLangAttribute(\n node: t.JSXElement,\n state: VisitorsInternalState,\n): void {\n const openingElement = node.openingElement;\n\n if (\n openingElement.name.type !== \"JSXIdentifier\" ||\n openingElement.name.name !== \"html\"\n ) {\n return;\n }\n\n // Check if lang attribute already exists\n const hasLangAttr = openingElement.attributes.some((attr) => {\n return (\n attr.type === \"JSXAttribute\" &&\n attr.name.type === \"JSXIdentifier\" &&\n (attr.name.name === \"lang\" || attr.name.name === \"language\")\n );\n });\n\n if (hasLangAttr) {\n // Already has lang attribute, don't inject\n return;\n }\n\n // Check if we're inside a component (has access to locale context)\n const component = state.componentsStack.at(-1);\n if (!component) {\n // Not inside a component, can't inject locale\n return;\n }\n\n // Inject lang={locale} attribute\n // This creates: <html lang={locale}>\n const langAttr = t.jsxAttribute(\n t.jsxIdentifier(\"lang\"),\n t.jsxExpressionContainer(t.identifier(\"locale\")),\n );\n\n openingElement.attributes.push(langAttr);\n\n logger.debug(\n `Injected locale attribute into <html> element in component: ${component.name}`,\n );\n\n // Mark that this component needs locale destructured from the hook\n state.componentsNeedingLocale.add(component.name);\n}\n\n/**\n * Inject translation hook into a component when it's done processing\n * Called when popping component from stack\n */\nexport function injectTranslationHook(\n path: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n component: ComponentEntry,\n state: VisitorsInternalState,\n): void {\n const needsLocale = state.componentsNeedingLocale.has(component.name);\n const hashes = state.componentHashes.get(component.name);\n if ((!hashes || hashes.length === 0) && !needsLocale) {\n return; // No translations needed\n }\n\n if (component.isAsync) {\n // Async component uses getServerTranslations\n injectServerHook(path, hashes ?? [], needsLocale);\n state.needsAsyncImport = true;\n } else {\n // Non-async component uses unified hook (useTranslation)\n injectUnifiedHook(path, hashes ?? [], needsLocale);\n state.needsUnifiedImport = true;\n }\n}\n\n/**\n * Add translation imports at the top of the file\n * Called on Program exit after all components have been processed\n */\nfunction addTranslationImports(\n programPath: NodePath<t.Program>,\n state: VisitorsInternalState,\n): void {\n // A file can have both async and non-async components!\n if (state.needsAsyncImport) {\n programPath.node.body.unshift(constructServerImport());\n }\n if (state.needsUnifiedImport) {\n programPath.node.body.unshift(comstructUnifiedImport());\n }\n}\n\n/**\n * Handle component function detection and state update\n */\nfunction processComponentFunction(\n path: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n state: VisitorsInternalState,\n): void {\n // A function handed to a prop is a callback, however React-shaped it looks. Return\n // without skipping so its JSX is still reached by the ambient traversal and gets\n // registered against the enclosing component, whose `t` it closes over. Skipping\n // here instead would drop those strings, which is what used to happen to arrow\n // render props.\n if (isInsidePropValue(path)) return;\n\n if (!isReactComponent(path)) {\n path.skip();\n logger.debug(`Skipping non-React component: ${path.node.type}`);\n return;\n }\n\n const componentName = inferComponentName(path);\n if (!componentName) {\n path.skip();\n return;\n }\n\n // Store component info for later hook injection\n if (!state.componentHashes.has(componentName)) {\n state.componentHashes.set(componentName, []);\n }\n\n // Push component to stack with async info and path reference\n const componentEntry: ComponentEntry = {\n name: componentName,\n isAsync: path.node.async,\n };\n state.componentsStack.push(componentEntry);\n logger.debug(`Component ${JSON.stringify(componentEntry)} entered`);\n\n path.setData(\"componentName\", componentName);\n path.traverse(componentVisitors, { visitorState: state });\n const component = state.componentsStack.pop();\n if (component) {\n injectTranslationHook(path, component, state);\n }\n // We have already traversed the path's children so the main traverse can skip it.\n path.skip();\n}\n\nconst componentVisitors = {\n // 1. Handle nested components. FunctionDeclaration|FunctionExpression|ArrowFunctionExpression unfortunately doesn't give the correct type signature for the path.\n FunctionDeclaration(path: NodePath<t.FunctionDeclaration>) {\n processComponentFunction(path, this.visitorState);\n },\n ArrowFunctionExpression(path: NodePath<t.ArrowFunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n FunctionExpression(path: NodePath<t.FunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n // 2. Fragments are separate from other JSX elements. Both <> and <Fragment> are the same AST node type.\n JSXFragment(path: NodePath<t.JSXFragment>) {\n // No attributes to translate on the fragment, so we only check if it has mixed content. If it doesn't, go ahead and its children will be checked.\n // We also do not check for translation skip, because fragments are mostly used to make the bare text translatable.\n // But if we want to support <Fragment data-lingo-skip>Text</Fragment> we should do it here.\n processJSXElement(path, this.visitorState);\n },\n\n // Transform JSX elements with mixed content (text + expressions or nested elements)\n JSXElement(path: NodePath<t.JSXElement>) {\n translateAttributes(path.node, this.visitorState);\n\n // Inject locale attribute into <html> elements for Next.js\n // Only the document root gets the locale. An `<html>` handed to a prop is\n // somebody's example markup, not the page.\n if (!isInsidePropValue(path)) {\n injectHtmlLangAttribute(path.node, this.visitorState);\n }\n\n if (shouldSkipTranslationForElement(path.node)) {\n path.skip();\n return;\n }\n processJSXElement(path, this.visitorState);\n },\n} satisfies TraverseOptions<{ visitorState: VisitorsInternalState }>;\n\nconst fileVisitors = {\n // Handle static metadata exports: export const metadata = { ... }\n ExportNamedDeclaration(path: NodePath<t.ExportNamedDeclaration>) {\n // Check if the export is a metadata export and converts it to a function\n const metadataState = processNextStaticMetadata(path, {\n filePath: this.visitorState.filePath,\n });\n\n if (metadataState) {\n updateWithMetadataState(this.visitorState, metadataState);\n }\n },\n\n // All component function types share the same handler\n FunctionDeclaration(path: NodePath<t.FunctionDeclaration>) {\n const metadataState = processNextDynamicMetadata(path, {\n filePath: this.visitorState.filePath,\n });\n if (metadataState) {\n updateWithMetadataState(this.visitorState, metadataState);\n }\n\n // Otherwise, handle as component\n processComponentFunction(path, this.visitorState);\n },\n\n // export const MyComponent = () => {}\n ArrowFunctionExpression(path: NodePath<t.ArrowFunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n\n // All these are considered function expressions\n // const myFunction = function() {\n // return 'hello';\n // };\n //\n // const myFunction2 = function namedFunc() {\n // return 'hello';\n // };\n //\n // setTimeout(function() {\n // console.log('hello');\n // }, 1000);\n // While\n // export default function() {}\n // is not\n FunctionExpression(path: NodePath<t.FunctionExpression>) {\n processComponentFunction(path, this.visitorState);\n },\n} satisfies TraverseOptions<{ visitorState: VisitorsInternalState }>;\n\n/**\n * Create Babel visitors for auto-translation (single-pass transformation)\n */\nconst programVisitor = {\n Program: {\n enter(path: NodePath<t.Program>) {\n // We do the check on the loader level, but since they could be false positive, accepting the files we don't need to process, we do the check here as well.\n if (this.visitorState.needsDirective && !hasUseI18nDirective(path)) {\n path.skip();\n return;\n }\n\n path.traverse(fileVisitors, {\n visitorState: this.visitorState,\n });\n },\n\n exit(path: NodePath<t.Program>) {\n if (\n this.visitorState.needsUnifiedImport ||\n this.visitorState.needsAsyncImport\n ) {\n addTranslationImports(path, this.visitorState);\n }\n },\n },\n} satisfies TraverseOptions<{ visitorState: VisitorsInternalState }>;\n\nexport function processFile(\n ast: t.Node,\n options: { relativeFilePath: string; needsDirective: boolean },\n) {\n const state: VisitorsInternalState = {\n needsDirective: options.needsDirective,\n filePath: options.relativeFilePath,\n newEntries: [],\n componentsStack: [],\n componentHashes: new Map<string, string[]>(),\n needsUnifiedImport: false,\n needsAsyncImport: false,\n componentsNeedingLocale: new Set<string>(),\n };\n\n traverse(ast, programVisitor, undefined, { visitorState: state });\n\n return state.newEntries;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyDA,SAAS,wBACP,OACA,UACuB;AACvB,OAAM,aAAa,CAAC,GAAG,MAAM,YAAY,GAAG,SAAS,WAAW;AAChE,OAAM,mBAAmB,MAAM,oBAAoB,SAAS;AAC5D,QAAO;;AAGT,MAAM,iBAAiB;;;;;;AAOvB,MAAM,4BAA4B,IAAI,IAAI;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,0BAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;AAQF,SAAS,gCACP,SACS;AAET,KAAI,QAAQ,SAAS,cACnB,QAAO;CAET,MAAM,iBAAiB,QAAQ;AAG/B,KAAI,eAAe,KAAK,SAAS,iBAC/B;MAAI,0BAA0B,IAAI,eAAe,KAAK,KAAK,CACzD,QAAO;;AAIX,MAAK,MAAM,QAAQ,eAAe,WAChC,KAAI,KAAK,SAAS,kBAAkB,KAAK,KAAK,SAAS,iBAAiB;AAEtE,MAAI,KAAK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7C;AAED,MAAM,eAAe;CAEnB,uBAAuB,MAA0C;EAE/D,MAAM,gBAAgB,0BAA0B,MAAM,EACpD,UAAU,KAAK,aAAa,UAC7B,CAAC;AAEF,MAAI,cACF,yBAAwB,KAAK,cAAc,cAAc;;CAK7D,oBAAoB,MAAuC;EACzD,MAAM,gBAAgB,2BAA2B,MAAM,EACrD,UAAU,KAAK,aAAa,UAC7B,CAAC;AACF,MAAI,cACF,yBAAwB,KAAK,cAAc,cAAc;AAI3D,2BAAyB,MAAM,KAAK,aAAa;;CAInD,wBAAwB,MAA2C;AACjE,2BAAyB,MAAM,KAAK,aAAa;;CAkBnD,mBAAmB,MAAsC;AACvD,2BAAyB,MAAM,KAAK,aAAa;;CAEpD;;;;AAKD,MAAM,iBAAiB,EACrB,SAAS;CACP,MAAM,MAA2B;AAE/B,MAAI,KAAK,aAAa,kBAAkB,CAAC,oBAAoB,KAAK,EAAE;AAClE,QAAK,MAAM;AACX;;AAGF,OAAK,SAAS,cAAc,EAC1B,cAAc,KAAK,cACpB,CAAC;;CAGJ,KAAK,MAA2B;AAC9B,MACE,KAAK,aAAa,sBAClB,KAAK,aAAa,iBAElB,uBAAsB,MAAM,KAAK,aAAa;;CAGnD,EACF;AAED,SAAgB,YACd,KACA,SACA;CACA,MAAMC,QAA+B;EACnC,gBAAgB,QAAQ;EACxB,UAAU,QAAQ;EAClB,YAAY,EAAE;EACd,iBAAiB,EAAE;EACnB,iCAAiB,IAAI,KAAuB;EAC5C,oBAAoB;EACpB,kBAAkB;EAClB,yCAAyB,IAAI,KAAa;EAC3C;AAED,UAAS,KAAK,gBAAgB,QAAW,EAAE,cAAc,OAAO,CAAC;AAEjE,QAAO,MAAM"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { LingoProviderProps } from "../shared/LingoProvider.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime1 from "react/jsx-runtime";
|
|
3
3
|
|
|
4
4
|
//#region src/react/server/ServerLingoProvider.d.ts
|
|
5
5
|
declare function LingoProvider({
|
|
6
6
|
initialLocale,
|
|
7
7
|
initialTranslations,
|
|
8
8
|
...rest
|
|
9
|
-
}: LingoProviderProps): Promise<
|
|
9
|
+
}: LingoProviderProps): Promise<react_jsx_runtime1.JSX.Element>;
|
|
10
10
|
//#endregion
|
|
11
11
|
export { LingoProvider };
|
|
12
12
|
//# sourceMappingURL=ServerLingoProvider.d.cts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LocaleCode } from "lingo.dev/spec";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime3 from "react/jsx-runtime";
|
|
3
3
|
import { PropsWithChildren } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/react/shared/LingoProvider.d.ts
|
|
@@ -70,7 +70,7 @@ declare function LingoProvider__Dev({
|
|
|
70
70
|
router,
|
|
71
71
|
devWidget,
|
|
72
72
|
children
|
|
73
|
-
}: LingoProviderProps):
|
|
73
|
+
}: LingoProviderProps): react_jsx_runtime3.JSX.Element;
|
|
74
74
|
//#endregion
|
|
75
75
|
export { LingoProvider, LingoProviderProps };
|
|
76
76
|
//# sourceMappingURL=LingoProvider.d.cts.map
|
|
@@ -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":";
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
|
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
|
|
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,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,OAAK,IAAI,IAAI,GAAG,IAAI,OA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,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,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AED,GAAG,MAAM,SAAS,eAAe,CAC/B;MACE,MAAM;MACN,SAAS,QAAQ,WAAW,GAAG;MAChC,EACD;MACE,MAAM;MACN,SAAS,QAAQ,WAAW,GAAG;MAChC,CACF,CAAC;KACF;MACE,MAAM;MACN,SAAS,QAAQ,iBAAiB;MACnC;KACF;IACF,CAAC,EACF,KAAK,OAAO,aAAa,iBAAiB,QAC1C,GAAG,YAAY,SAAS,sBAAsB,eAC/C,EAE0D,KAAK;WACzD,OAAO;AACd,SAAM,IAAI,MACR,+BAA+B,YAAY,SAAS,IAAI,iBAAiB,QAAQ,MAAM,UAAU,kBAClG;;;;;;CAOL,AAAQ,gBAAgB,YAAkD;EACxE,MAAM,wBAAwB;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"}
|
|
@@ -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,OAAK,eAAe,OAAO;AAC3B,OAAK,SAAS,g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,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,AAAiB;CACjB,AAAiB;CAEjB,YACE,QACA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,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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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:
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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:
|
|
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,SAAK,QAAQ,IAAI,wBAAwB;SAGzC,OAAM;;;;;;;;;;;CAcd,MAAM,UACJ,QACA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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,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACxD,SAAK,OAAO,KAAK,iCAAi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AoB;AAE3D,UAAO,KAAK;IACV,MAAM;IACN,YAAY;IACZ,OAAO;IACR,CAAC;;AAKN,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,eAAe,QACpB,SAAS,iBAAiB,SAAS,CAAC,gBAAgB,MACtD,CAAC;IACH;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"}
|
package/build/types.d.cts
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
|
package/build/types.d.cts.map
CHANGED
|
@@ -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;
|
|
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
|
package/build/types.d.mts.map
CHANGED
|
@@ -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,KAjBU,uBAAA,GAiBV;EAAO,IAAA,EAAA,QAAA;EAUG,MAAA,EA3BoD,YA2BpC;AAK5B,CAAA;;;;AAsEwB,KAjGZ,yBAAA,GAiGY,cAAA,GAAA,eAAA;
|
|
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,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"}
|
|
@@ -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,K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pB,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;CACD,QAAQ;CACR,WAAW;CACX,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"}
|
package/build/utils/timeout.cjs
CHANGED
package/build/utils/timeout.mjs
CHANGED
|
@@ -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:
|
|
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.
|
|
3
|
+
"version": "0.4.12",
|
|
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.
|
|
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.
|
|
164
|
+
"lingo.dev": "^0.138.6"
|
|
165
165
|
},
|
|
166
166
|
"peerDependencies": {
|
|
167
167
|
"next": "^15.0.0 || ^16.0.4",
|