@lingo.dev/compiler 0.4.11 → 0.4.13
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/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/lingo/translator.cjs +15 -21
- package/build/translators/lingo/translator.mjs +15 -21
- package/build/translators/lingo/translator.mjs.map +1 -1
- package/build/translators/pluralization/service.cjs +11 -17
- package/build/translators/pluralization/service.mjs +11 -17
- package/build/translators/pluralization/service.mjs.map +1 -1
- package/package.json +7 -7
|
@@ -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,C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","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,0B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d,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
|
|
@@ -92,27 +92,21 @@ var LingoTranslator = class {
|
|
|
92
92
|
try {
|
|
93
93
|
return require_parse_xml.parseXmlFromResponseText((await require_timeout.withTimeout((0, ai.generateText)({
|
|
94
94
|
model: aiModel,
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}]),
|
|
111
|
-
{
|
|
112
|
-
role: "user",
|
|
113
|
-
content: require_parse_xml.obj2xml(sourceDictionary)
|
|
114
|
-
}
|
|
115
|
-
]
|
|
95
|
+
system: require_prompt.getSystemPrompt({
|
|
96
|
+
sourceLocale: this.config.sourceLocale,
|
|
97
|
+
targetLocale,
|
|
98
|
+
prompt: this.config.prompt
|
|
99
|
+
}),
|
|
100
|
+
messages: [...require_shots.shots.flatMap((shotsTuple) => [{
|
|
101
|
+
role: "user",
|
|
102
|
+
content: require_parse_xml.obj2xml(shotsTuple[0])
|
|
103
|
+
}, {
|
|
104
|
+
role: "assistant",
|
|
105
|
+
content: require_parse_xml.obj2xml(shotsTuple[1])
|
|
106
|
+
}]), {
|
|
107
|
+
role: "user",
|
|
108
|
+
content: require_parse_xml.obj2xml(sourceDictionary)
|
|
109
|
+
}]
|
|
116
110
|
}), this.config.aiTimeout ?? require_timeout.DEFAULT_TIMEOUTS.AI_API, `${localeModel.provider} LLM translation to ${targetLocale}`)).text);
|
|
117
111
|
} catch (error) {
|
|
118
112
|
throw new Error(`LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
@@ -91,27 +91,21 @@ var LingoTranslator = class {
|
|
|
91
91
|
try {
|
|
92
92
|
return parseXmlFromResponseText((await withTimeout(generateText({
|
|
93
93
|
model: aiModel,
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}]),
|
|
110
|
-
{
|
|
111
|
-
role: "user",
|
|
112
|
-
content: obj2xml(sourceDictionary)
|
|
113
|
-
}
|
|
114
|
-
]
|
|
94
|
+
system: getSystemPrompt({
|
|
95
|
+
sourceLocale: this.config.sourceLocale,
|
|
96
|
+
targetLocale,
|
|
97
|
+
prompt: this.config.prompt
|
|
98
|
+
}),
|
|
99
|
+
messages: [...shots.flatMap((shotsTuple) => [{
|
|
100
|
+
role: "user",
|
|
101
|
+
content: obj2xml(shotsTuple[0])
|
|
102
|
+
}, {
|
|
103
|
+
role: "assistant",
|
|
104
|
+
content: obj2xml(shotsTuple[1])
|
|
105
|
+
}]), {
|
|
106
|
+
role: "user",
|
|
107
|
+
content: obj2xml(sourceDictionary)
|
|
108
|
+
}]
|
|
115
109
|
}), this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API, `${localeModel.provider} LLM translation to ${targetLocale}`)).text);
|
|
116
110
|
} catch (error) {
|
|
117
111
|
throw new Error(`LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
@@ -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, PartialTranslationError, type DictionarySchema, type TranslatableEntry, type Translator, } from \"../api\";\nimport { getSystemPrompt } from \"./prompt\";\nimport { obj2xml, parseXmlFromResponseText } from \"../parse-xml\";\nimport { shots } from \"./shots\";\nimport { createAiModel, getLocaleModel, validateAndGetApiKeys, type ValidatedApiKeys, } from \"./model-factory\";\nimport { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\n/**\n * Lingo Translator configuration\n */\nexport interface LingoTranslatorConfig {\n models: \"lingo.dev\" | Record<string, string>;\n sourceLocale: LocaleCode;\n prompt?: string;\n aiTimeout?: number;\n}\n\n/**\n * Lingo translator using AI models\n */\nexport class LingoTranslator implements Translator<LingoTranslatorConfig> {\n private readonly validatedKeys: ValidatedApiKeys;\n\n constructor(\n readonly config: LingoTranslatorConfig,\n private logger: Logger,\n ) {\n this.logger.info(\"Validating API keys for translation...\");\n this.validatedKeys = validateAndGetApiKeys(config.models);\n this.logger.info(\"✅ API keys validated successfully\");\n }\n\n /**\n * Translate multiple entries\n */\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n this.logger.debug(\n `translate() called for ${locale} with ${Object.keys(entriesMap).length} entries`,\n );\n\n const sourceDictionary: DictionarySchema = dictionaryFrom(\n this.config.sourceLocale,\n Object.fromEntries(\n Object.entries(entriesMap).map(([hash, entry]) => [hash, entry.text]),\n ),\n );\n\n this.logger.debug(\n `Created source dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,\n );\n const translated = await this.translateDictionary(sourceDictionary, locale);\n\n return translated.entries || {};\n }\n\n /**\n * Translate a complete dictionary\n */\n private async translateDictionary(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const chunks = this.chunkDictionary(sourceDictionary);\n this.logger.debug(\n `Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`,\n );\n\n const translatedChunks: DictionarySchema[] = [];\n\n try {\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n this.logger.debug(\n `Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`,\n );\n const chunkStartTime = performance.now();\n\n const translatedChunk = await this.translateChunk(chunk, targetLocale);\n\n const chunkEndTime = performance.now();\n this.logger.debug(\n `Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`,\n );\n\n translatedChunks.push(translatedChunk);\n }\n } catch (error) {\n throw new PartialTranslationError(\n error instanceof Error ? error.message : String(error),\n this.mergeDictionaries(translatedChunks).entries,\n error,\n );\n }\n\n const result = this.mergeDictionaries(translatedChunks);\n this.logger.debug(\n `Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`,\n );\n\n return result;\n }\n\n /**\n * Translate a single chunk\n */\n private async translateChunk(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n if (this.config.models === \"lingo.dev\") {\n return this.translateWithLingoDotDev(sourceDictionary, targetLocale);\n } else {\n return this.translateWithLLM(sourceDictionary, targetLocale);\n }\n }\n\n /**\n * Translate using Lingo.dev Engine\n * Times out after `aiTimeout` to prevent indefinite hangs\n */\n private async translateWithLingoDotDev(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const apiKey = this.validatedKeys[\"lingo.dev\"];\n if (!apiKey) {\n throw new Error(\n \"Internal error: Lingo.dev API key not found after validation. Please restart the service.\",\n );\n }\n\n this.logger.debug(\n `Using Lingo.dev Engine to localize from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const engine = new LingoDotDevEngine({ apiKey });\n\n try {\n const result = await withTimeout(\n engine.localizeObject(sourceDictionary, {\n sourceLocale: this.config.sourceLocale,\n targetLocale: targetLocale,\n }),\n this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API,\n `Lingo.dev API translation to ${targetLocale}`,\n );\n\n return result as DictionarySchema;\n } catch (error) {\n this.logger.error(`translateWithLingoDotDev() failed:`, error);\n throw new Error(\n `Lingo.dev translation failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Translate using generic LLM\n * Times out after `aiTimeout` to prevent indefinite hangs\n */\n private async translateWithLLM(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const localeModel = getLocaleModel(\n this.config.models as Record<string, string>,\n this.config.sourceLocale,\n targetLocale,\n );\n\n if (!localeModel) {\n throw new Error(\n `No model configured for translation from ${this.config.sourceLocale} to ${targetLocale}`,\n );\n }\n\n this.logger.debug(\n `Using LLM (\"${localeModel.provider}\":\"${localeModel.name}\") to translate from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const aiModel = createAiModel(localeModel, this.validatedKeys);\n\n try {\n const response = await withTimeout(\n generateText({\n model: aiModel,\n messages: [\n {\n role: \"system\",\n content: getSystemPrompt({\n sourceLocale: this.config.sourceLocale,\n targetLocale,\n prompt: this.config.prompt,\n }),\n },\n // Add few-shot examples\n ...shots.flatMap((shotsTuple) => [\n {\n role: \"user\" as const,\n content: obj2xml(shotsTuple[0]),\n },\n {\n role: \"assistant\" as const,\n content: obj2xml(shotsTuple[1]),\n },\n ]),\n {\n role: \"user\",\n content: obj2xml(sourceDictionary),\n },\n ],\n }),\n this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API,\n `${localeModel.provider} LLM translation to ${targetLocale}`,\n );\n\n return parseXmlFromResponseText<DictionarySchema>(response.text);\n } catch (error) {\n throw new Error(\n `LLM translation failed with ${localeModel.provider}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Split dictionary into chunks for processing\n */\n private chunkDictionary(dictionary: DictionarySchema): DictionarySchema[] {\n const MAX_ENTRIES_PER_CHUNK = 100;\n const { entries, ...rest } = dictionary;\n const chunks: DictionarySchema[] = [];\n\n const entryPairs = Object.entries(entries);\n\n // Split entries into chunks of MAX_ENTRIES_PER_CHUNK\n for (let i = 0; i < entryPairs.length; i += MAX_ENTRIES_PER_CHUNK) {\n const chunkEntries = entryPairs.slice(i, i + MAX_ENTRIES_PER_CHUNK);\n chunks.push({\n ...rest,\n entries: Object.fromEntries(chunkEntries),\n });\n }\n\n return chunks;\n }\n\n /**\n * Merge multiple dictionaries into one\n */\n private mergeDictionaries(\n dictionaries: DictionarySchema[],\n ): DictionarySchema {\n if (dictionaries.length === 0) {\n return dictionaryFrom(this.config.sourceLocale, {});\n }\n\n // Merge all entries from all dictionaries\n const mergedEntries: Record<string, string> = {};\n for (const dict of dictionaries) {\n Object.assign(mergedEntries, dict.entries);\n }\n\n return {\n version: dictionaries[0].version,\n locale: dictionaries[0].locale,\n entries: mergedEntries,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,IAAa,kBAAb,MAA0E;CACxE,AAAiB;CAEjB,YACE,AAASA,QACT,AAAQC,QACR;EAFS;EACD;AAER,OAAK,OAAO,KAAK,yCAAyC;AAC1D,OAAK,gBAAgB,sBAAsB,OAAO,OAAO;AACzD,OAAK,OAAO,KAAK,oCAAoC;;;;;CAMvD,MAAM,UACJ,QACA,YACiC;AACjC,OAAK,OAAO,MACV,0BAA0B,OAAO,QAAQ,OAAO,KAAK,WAAW,CAAC,OAAO,UACzE;EAED,MAAMC,mBAAqC,eACzC,KAAK,OAAO,cACZ,OAAO,YACL,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,MAAM,KAAK,CAAC,CACtE,CACF;AAED,OAAK,OAAO,MACV,kCAAkC,OAAO,KAAK,iBAAiB,QAAQ,CAAC,OAAO,UAChF;AAGD,UAFmB,MAAM,KAAK,oBAAoB,kBAAkB,OAAO,EAEzD,WAAW,EAAE;;;;;CAMjC,MAAc,oBACZ,kBACA,cAC2B;EAC3B,MAAM,SAAS,KAAK,gBAAgB,iBAAiB;AACrD,OAAK,OAAO,MACV,yBAAyB,OAAO,KAAK,iBAAiB,QAAQ,CAAC,OAAO,QAAQ,OAAO,OAAO,SAC7F;EAED,MAAMC,mBAAuC,EAAE;AAE/C,MAAI;AACF,QAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;IACtC,MAAM,QAAQ,OAAO;AACrB,SAAK,OAAO,MACV,qBAAqB,IAAI,EAAE,GAAG,OAAO,OAAO,QAAQ,OAAO,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,AAAQ,kBACN,cACkB;AAClB,MAAI,aAAa,WAAW,EAC1B,QAAO,eAAe,KAAK,OAAO,cAAc,EAAE,CAAC;EAIrD,MAAMC,gBAAwC,EAAE;AAChD,OAAK,MAAM,QAAQ,aACjB,QAAO,OAAO,eAAe,KAAK,QAAQ;AAG5C,SAAO;GACL,SAAS,aAAa,GAAG;GACzB,QAAQ,aAAa,GAAG;GACxB,SAAS;GACV"}
|
|
1
|
+
{"version":3,"file":"translator.mjs","names":["config: LingoTranslatorConfig","logger: Logger","sourceDictionary: DictionarySchema","translatedChunks: DictionarySchema[]","chunks: DictionarySchema[]","mergedEntries: Record<string, string>"],"sources":["../../../src/translators/lingo/translator.ts"],"sourcesContent":["import { generateText } from \"ai\";\nimport { LingoDotDevEngine } from \"lingo.dev/sdk\";\nimport { dictionaryFrom, PartialTranslationError, type DictionarySchema, type TranslatableEntry, type Translator, } from \"../api\";\nimport { getSystemPrompt } from \"./prompt\";\nimport { obj2xml, parseXmlFromResponseText } from \"../parse-xml\";\nimport { shots } from \"./shots\";\nimport { createAiModel, getLocaleModel, validateAndGetApiKeys, type ValidatedApiKeys, } from \"./model-factory\";\nimport { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport type { LocaleCode } from \"lingo.dev/spec\";\n\n/**\n * Lingo Translator configuration\n */\nexport interface LingoTranslatorConfig {\n models: \"lingo.dev\" | Record<string, string>;\n sourceLocale: LocaleCode;\n prompt?: string;\n aiTimeout?: number;\n}\n\n/**\n * Lingo translator using AI models\n */\nexport class LingoTranslator implements Translator<LingoTranslatorConfig> {\n private readonly validatedKeys: ValidatedApiKeys;\n\n constructor(\n readonly config: LingoTranslatorConfig,\n private logger: Logger,\n ) {\n this.logger.info(\"Validating API keys for translation...\");\n this.validatedKeys = validateAndGetApiKeys(config.models);\n this.logger.info(\"✅ API keys validated successfully\");\n }\n\n /**\n * Translate multiple entries\n */\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n this.logger.debug(\n `translate() called for ${locale} with ${Object.keys(entriesMap).length} entries`,\n );\n\n const sourceDictionary: DictionarySchema = dictionaryFrom(\n this.config.sourceLocale,\n Object.fromEntries(\n Object.entries(entriesMap).map(([hash, entry]) => [hash, entry.text]),\n ),\n );\n\n this.logger.debug(\n `Created source dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,\n );\n const translated = await this.translateDictionary(sourceDictionary, locale);\n\n return translated.entries || {};\n }\n\n /**\n * Translate a complete dictionary\n */\n private async translateDictionary(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const chunks = this.chunkDictionary(sourceDictionary);\n this.logger.debug(\n `Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`,\n );\n\n const translatedChunks: DictionarySchema[] = [];\n\n try {\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n this.logger.debug(\n `Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`,\n );\n const chunkStartTime = performance.now();\n\n const translatedChunk = await this.translateChunk(chunk, targetLocale);\n\n const chunkEndTime = performance.now();\n this.logger.debug(\n `Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`,\n );\n\n translatedChunks.push(translatedChunk);\n }\n } catch (error) {\n throw new PartialTranslationError(\n error instanceof Error ? error.message : String(error),\n this.mergeDictionaries(translatedChunks).entries,\n error,\n );\n }\n\n const result = this.mergeDictionaries(translatedChunks);\n this.logger.debug(\n `Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`,\n );\n\n return result;\n }\n\n /**\n * Translate a single chunk\n */\n private async translateChunk(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n if (this.config.models === \"lingo.dev\") {\n return this.translateWithLingoDotDev(sourceDictionary, targetLocale);\n } else {\n return this.translateWithLLM(sourceDictionary, targetLocale);\n }\n }\n\n /**\n * Translate using Lingo.dev Engine\n * Times out after `aiTimeout` to prevent indefinite hangs\n */\n private async translateWithLingoDotDev(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const apiKey = this.validatedKeys[\"lingo.dev\"];\n if (!apiKey) {\n throw new Error(\n \"Internal error: Lingo.dev API key not found after validation. Please restart the service.\",\n );\n }\n\n this.logger.debug(\n `Using Lingo.dev Engine to localize from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const engine = new LingoDotDevEngine({ apiKey });\n\n try {\n const result = await withTimeout(\n engine.localizeObject(sourceDictionary, {\n sourceLocale: this.config.sourceLocale,\n targetLocale: targetLocale,\n }),\n this.config.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API,\n `Lingo.dev API translation to ${targetLocale}`,\n );\n\n return result as DictionarySchema;\n } catch (error) {\n this.logger.error(`translateWithLingoDotDev() failed:`, error);\n throw new Error(\n `Lingo.dev translation failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Translate using generic LLM\n * Times out after `aiTimeout` to prevent indefinite hangs\n */\n private async translateWithLLM(\n sourceDictionary: DictionarySchema,\n targetLocale: string,\n ): Promise<DictionarySchema> {\n const localeModel = getLocaleModel(\n this.config.models as Record<string, string>,\n this.config.sourceLocale,\n targetLocale,\n );\n\n if (!localeModel) {\n throw new Error(\n `No model configured for translation from ${this.config.sourceLocale} to ${targetLocale}`,\n );\n }\n\n this.logger.debug(\n `Using LLM (\"${localeModel.provider}\":\"${localeModel.name}\") to translate from \"${this.config.sourceLocale}\" to \"${targetLocale}\"`,\n );\n\n const aiModel = createAiModel(localeModel, this.validatedKeys);\n\n try {\n const response = await withTimeout(\n generateText({\n model: aiModel,\n system: getSystemPrompt({\n sourceLocale: this.config.sourceLocale,\n targetLocale,\n prompt: this.config.prompt,\n }),\n messages: [\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,o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AAU,CAER,GAAG,MAAM,SAAS,eAAe,CAC/B;KACE,MAAM;KACN,SAAS,QAAQ,WAAW,GAAG;KAChC,EACD;KACE,MAAM;KACN,SAAS,QAAQ,WAAW,GAAG;KAChC,CACF,CAAC,EACF;KACE,MAAM;KACN,SAAS,QAAQ,iBAAiB;KACnC,CACF;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"}
|
|
@@ -74,23 +74,17 @@ var PluralizationService = class {
|
|
|
74
74
|
};
|
|
75
75
|
const responseText = (await require_timeout.withTimeout((0, ai.generateText)({
|
|
76
76
|
model: this.languageModel,
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
}]),
|
|
89
|
-
{
|
|
90
|
-
role: "user",
|
|
91
|
-
content: require_parse_xml.obj2xml(batchRequest)
|
|
92
|
-
}
|
|
93
|
-
]
|
|
77
|
+
system: this.prompt,
|
|
78
|
+
messages: [...require_shots.shots.flatMap((shotsTuple) => [{
|
|
79
|
+
role: "user",
|
|
80
|
+
content: require_parse_xml.obj2xml(shotsTuple[0])
|
|
81
|
+
}, {
|
|
82
|
+
role: "assistant",
|
|
83
|
+
content: require_parse_xml.obj2xml(shotsTuple[1])
|
|
84
|
+
}]), {
|
|
85
|
+
role: "user",
|
|
86
|
+
content: require_parse_xml.obj2xml(batchRequest)
|
|
87
|
+
}]
|
|
94
88
|
}), (this.aiTimeout ?? require_timeout.DEFAULT_TIMEOUTS.AI_API) * 2, `Pluralization with ${this.languageModel}`)).text.trim();
|
|
95
89
|
this.logger.debug(`LLM XML response: ${responseText.substring(0, 200)}...`);
|
|
96
90
|
const parsed = require_parse_xml.parseXmlFromResponseText(responseText);
|
|
@@ -73,23 +73,17 @@ var PluralizationService = class {
|
|
|
73
73
|
};
|
|
74
74
|
const responseText = (await withTimeout(generateText({
|
|
75
75
|
model: this.languageModel,
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}]),
|
|
88
|
-
{
|
|
89
|
-
role: "user",
|
|
90
|
-
content: obj2xml(batchRequest)
|
|
91
|
-
}
|
|
92
|
-
]
|
|
76
|
+
system: this.prompt,
|
|
77
|
+
messages: [...shots.flatMap((shotsTuple) => [{
|
|
78
|
+
role: "user",
|
|
79
|
+
content: obj2xml(shotsTuple[0])
|
|
80
|
+
}, {
|
|
81
|
+
role: "assistant",
|
|
82
|
+
content: obj2xml(shotsTuple[1])
|
|
83
|
+
}]), {
|
|
84
|
+
role: "user",
|
|
85
|
+
content: obj2xml(batchRequest)
|
|
86
|
+
}]
|
|
93
87
|
}), (this.aiTimeout ?? DEFAULT_TIMEOUTS.AI_API) * 2, `Pluralization with ${this.languageModel}`)).text.trim();
|
|
94
88
|
this.logger.debug(`LLM XML response: ${responseText.substring(0, 200)}...`);
|
|
95
89
|
const parsed = parseXmlFromResponseText(responseText);
|
|
@@ -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 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,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,YAAY,OAAO;AACxB,OAAK,SAAS,gBAAgB,EAAE,cAAc,OAAO,cAAc,CAAC;AAEpE,OAAK,OAAO,MACV,0CAA0C,YAAY,SAAS,GAAG,YAAY,OAC/E;;;;;;;;;CAUH,MAAM,cACJ,YACA,YAAoB,IACuB;EAC3C,MAAM,EAAE,oB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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 system: this.prompt,\n messages: [\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,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,OAA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ClE,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lingo.dev/compiler",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.13",
|
|
4
4
|
"description": "Lingo.dev Compiler",
|
|
5
5
|
"private": false,
|
|
6
6
|
"repository": {
|
|
@@ -137,10 +137,10 @@
|
|
|
137
137
|
"vitest": "4.1.0"
|
|
138
138
|
},
|
|
139
139
|
"dependencies": {
|
|
140
|
-
"@ai-sdk/google": "3.0.
|
|
141
|
-
"@ai-sdk/groq": "3.0.
|
|
142
|
-
"@ai-sdk/mistral": "3.0.
|
|
143
|
-
"@ai-sdk/openai": "3.0.
|
|
140
|
+
"@ai-sdk/google": "3.0.122",
|
|
141
|
+
"@ai-sdk/groq": "3.0.65",
|
|
142
|
+
"@ai-sdk/mistral": "3.0.64",
|
|
143
|
+
"@ai-sdk/openai": "3.0.112",
|
|
144
144
|
"@babel/core": "7.29.6",
|
|
145
145
|
"@babel/generator": "7.28.5",
|
|
146
146
|
"@babel/parser": "7.28.5",
|
|
@@ -150,7 +150,7 @@
|
|
|
150
150
|
"@babel/types": "7.28.5",
|
|
151
151
|
"@formatjs/icu-messageformat-parser": "3.1.1",
|
|
152
152
|
"@openrouter/ai-sdk-provider": "1.5.4",
|
|
153
|
-
"ai": "6.0.
|
|
153
|
+
"ai": "6.0.280",
|
|
154
154
|
"ai-sdk-ollama": "3.8.8",
|
|
155
155
|
"dotenv": "17.2.3",
|
|
156
156
|
"fast-xml-parser": "5.7.0",
|
|
@@ -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.8"
|
|
165
165
|
},
|
|
166
166
|
"peerDependencies": {
|
|
167
167
|
"next": "^15.0.0 || ^16.0.4",
|