Skip to content

Commit 196b8f8

Browse files
committed
fix: cleanup logs and unused functions
1 parent fb8ca8c commit 196b8f8

File tree

6 files changed

+31
-159
lines changed

6 files changed

+31
-159
lines changed

packages/new-compiler/src/plugin/build-translator.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,6 @@ export async function processBuildTranslations(
6464

6565
logger.info(`🌍 Build mode: ${buildMode}`);
6666

67-
if (metadataFilePath) {
68-
logger.info(`📋 Using build metadata file: ${metadataFilePath}`);
69-
}
70-
7167
const metadata = await loadMetadata(metadataFilePath);
7268

7369
if (!metadata || Object.keys(metadata.entries).length === 0) {
@@ -172,7 +168,10 @@ export async function processBuildTranslations(
172168
stats,
173169
};
174170
} catch (error) {
175-
logger.error("❌ Translation generation failed:", error);
171+
logger.error(
172+
"❌ Translation generation failed:\n",
173+
error instanceof Error ? error.message : error,
174+
);
176175
process.exit(1);
177176
} finally {
178177
if (translationServer) {

packages/new-compiler/src/plugin/next.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,6 @@ export async function withLingo(
297297
}
298298

299299
logger.info("Running post-build translation generation...");
300-
logger.info(`Build mode: Using metadata file: ${metadataFilePath}`);
301300

302301
try {
303302
await processBuildTranslations({
@@ -306,7 +305,10 @@ export async function withLingo(
306305
metadataFilePath,
307306
});
308307
} catch (error) {
309-
logger.error("Translation generation failed:", error);
308+
logger.error(
309+
"Translation generation failed:",
310+
error instanceof Error ? error.message : error,
311+
);
310312
throw error;
311313
}
312314
};

packages/new-compiler/src/translators/lingo/model-factory.ts

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { createMistral } from "@ai-sdk/mistral";
1010
import type { LanguageModel } from "ai";
1111
import * as dotenv from "dotenv";
1212
import * as path from "path";
13+
import { formatNoApiKeysError } from "./provider-details";
1314

1415
export type LocaleModel = {
1516
provider: string;
@@ -169,7 +170,7 @@ export function validateAndGetApiKeys(
169170
config: "lingo.dev" | Record<string, string>,
170171
): ValidatedApiKeys {
171172
const keys: ValidatedApiKeys = {};
172-
const missingKeys: Array<{ provider: string; envVar: string }> = [];
173+
const missingProviders: string[] = [];
173174

174175
// Determine which providers are configured
175176
let providersToValidate: string[];
@@ -195,7 +196,7 @@ export function validateAndGetApiKeys(
195196

196197
if (!providerConfig) {
197198
throw new Error(
198-
`⚠️ Unknown provider "${provider}". Supported providers: ${Object.keys(providerDetails).join(", ")}`,
199+
`⚠️ Unknown provider "${provider}". Supported providers: ${Object.keys(providerDetails).join(", ")}`,
199200
);
200201
}
201202

@@ -208,21 +209,13 @@ export function validateAndGetApiKeys(
208209
if (key) {
209210
keys[provider] = key;
210211
} else {
211-
missingKeys.push({
212-
provider: providerConfig.name,
213-
envVar: providerConfig.apiKeyEnvVar,
214-
});
212+
missingProviders.push(provider);
215213
}
216214
}
217215

218216
// If any keys are missing, throw with detailed error
219-
if (missingKeys.length > 0) {
220-
const errorLines = missingKeys.map(
221-
({ provider, envVar }) => ` - ${provider}: ${envVar}`,
222-
);
223-
throw new Error(
224-
`⚠️ Missing API keys for configured providers:\n${errorLines.join("\n")}\n\nPlease set the required environment variables.`,
225-
);
217+
if (missingProviders.length > 0) {
218+
throw new Error(formatNoApiKeysError(missingProviders));
226219
}
227220

228221
return keys;
@@ -253,6 +246,7 @@ export function createAiModel(
253246
? validatedKeys[model.provider]
254247
: undefined;
255248

249+
// TODO (AleksandrSl 25/12/2025): Do we really need to make a second check? Maybe creation should be combined with validation.
256250
// Verify key is present for providers that require it
257251
if (providerConfig.apiKeyEnvVar && !apiKey) {
258252
throw new Error(

packages/new-compiler/src/translators/lingo/provider-details.ts

Lines changed: 2 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -55,111 +55,6 @@ export const providerDetails: Record<string, ProviderDetails> = {
5555
},
5656
};
5757

58-
/**
59-
* Get provider details by ID
60-
*/
61-
export function getProviderDetails(providerId: string): ProviderDetails | null {
62-
return providerDetails[providerId] || null;
63-
}
64-
65-
/**
66-
* Get all providers that require API keys
67-
*/
68-
export function getProvidersRequiringKeys(): string[] {
69-
return Object.keys(providerDetails).filter(
70-
(id) => providerDetails[id].apiKeyEnvVar !== undefined,
71-
);
72-
}
73-
74-
/**
75-
* Format a helpful error message when API key is missing
76-
*/
77-
export function formatMissingApiKeyError(providerId: string): string {
78-
const details = providerDetails[providerId];
79-
80-
if (!details) {
81-
return `Unknown provider: ${providerId}`;
82-
}
83-
84-
if (!details.apiKeyEnvVar) {
85-
// Provider doesn't need API key (like Ollama)
86-
return `Provider ${details.name} doesn't require an API key. Check connection at ${details.getKeyLink}`;
87-
}
88-
89-
return [
90-
`⚠️ ${details.name} API key not found.`,
91-
``,
92-
`To use ${details.name} for translations, you need to set ${details.apiKeyEnvVar}.`,
93-
``,
94-
`👉 Set the API key:`,
95-
` 1. Add to .env file: ${details.apiKeyEnvVar}=<your-api-key>`,
96-
` 2. Or export in terminal: export ${details.apiKeyEnvVar}=<your-api-key>`,
97-
``,
98-
`⭐️ Get your API key:`,
99-
` ${details.getKeyLink}`,
100-
``,
101-
`📚 Documentation:`,
102-
` ${details.docsLink}`,
103-
].join("\n");
104-
}
105-
106-
/**
107-
* Format a helpful error message when API call fails
108-
*/
109-
export function formatApiCallError(
110-
providerId: string,
111-
targetLocale: string,
112-
errorMessage: string,
113-
): string {
114-
const details = providerDetails[providerId];
115-
116-
if (!details) {
117-
return `Translation failed with unknown provider "${providerId}": ${errorMessage}`;
118-
}
119-
120-
// Check for common error patterns
121-
const isInvalidApiKey =
122-
errorMessage.toLowerCase().includes("invalid api key") ||
123-
errorMessage.toLowerCase().includes("unauthorized") ||
124-
errorMessage.toLowerCase().includes("authentication failed");
125-
126-
if (isInvalidApiKey) {
127-
return [
128-
`⚠️ ${details.name} API key is invalid.`,
129-
``,
130-
`Error details: ${errorMessage}`,
131-
``,
132-
`👉 Please check your API key:`,
133-
details.apiKeyEnvVar
134-
? ` Environment variable: ${details.apiKeyEnvVar}`
135-
: "",
136-
``,
137-
`⭐️ Get a new API key:`,
138-
` ${details.getKeyLink}`,
139-
``,
140-
`📚 Troubleshooting:`,
141-
` ${details.docsLink}`,
142-
]
143-
.filter(Boolean)
144-
.join("\n");
145-
}
146-
147-
// Generic API error
148-
return [
149-
`⚠️ Translation to "${targetLocale}" failed via ${details.name}.`,
150-
``,
151-
`Error details: ${errorMessage}`,
152-
``,
153-
`📚 Check ${details.name} documentation for more details:`,
154-
` ${details.docsLink}`,
155-
``,
156-
`💡 Tips:`,
157-
` - Check your API quota/credits`,
158-
` - Verify the model is available for your account`,
159-
` - Check ${details.name} status page for outages`,
160-
].join("\n");
161-
}
162-
16358
/**
16459
* Format error message when API keys are missing for configured providers
16560
* @param missingProviders List of providers that are missing API keys
@@ -179,14 +74,12 @@ export function formatNoApiKeysError(
17974
// Header
18075
if (allProviders && allProviders.length > missingProviders.length) {
18176
lines.push(
182-
`⚠️ Missing API keys for ${missingProviders.length} of ${allProviders.length} configured providers.`,
77+
`Missing API keys for ${missingProviders.length} of ${allProviders.length} configured providers.`,
18378
);
18479
} else {
185-
lines.push(`⚠️ Missing API keys for configured translation providers.`);
80+
lines.push(`Missing API keys for configured translation providers.`);
18681
}
18782

188-
lines.push(``);
189-
19083
// List missing providers with their environment variables and links
19184
lines.push(`Missing API keys for:`);
19285
for (const providerId of missingProviders) {
@@ -210,8 +103,6 @@ export function formatNoApiKeysError(
210103
` 1. Add to .env file (recommended)`,
211104
` 2. Or export in terminal: export API_KEY_NAME=<your-key>`,
212105
``,
213-
`💡 In development mode, the app will auto-fallback to pseudotranslator.`,
214-
` In production, all configured providers must have valid API keys.`,
215106
);
216107

217108
return lines.join("\n");

packages/new-compiler/src/translators/lingo/translator.ts

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,10 @@
11
import { generateText } from "ai";
22
import { LingoDotDevEngine } from "lingo.dev/sdk";
3-
import {
4-
dictionaryFrom,
5-
type DictionarySchema,
6-
type TranslatableEntry,
7-
type Translator,
8-
} from "../api";
3+
import { dictionaryFrom, type DictionarySchema, type TranslatableEntry, type Translator, } from "../api";
94
import { getSystemPrompt } from "./prompt";
105
import { obj2xml, parseXmlFromResponseText } from "../parse-xml";
116
import { shots } from "./shots";
12-
import {
13-
createAiModel,
14-
getLocaleModel,
15-
validateAndGetApiKeys,
16-
type ValidatedApiKeys,
17-
} from "./model-factory";
7+
import { createAiModel, getLocaleModel, validateAndGetApiKeys, type ValidatedApiKeys, } from "./model-factory";
188
import { Logger } from "../../utils/logger";
199
import { DEFAULT_TIMEOUTS, withTimeout } from "../../utils/timeout";
2010
import type { LocaleCode } from "lingo.dev/spec";
@@ -51,7 +41,7 @@ export class LingoTranslator implements Translator<LingoTranslatorConfig> {
5141
entriesMap: Record<string, TranslatableEntry>,
5242
): Promise<Record<string, string>> {
5343
this.logger.debug(
54-
`[TRACE-LINGO] translate() called for ${locale} with ${Object.keys(entriesMap).length} entries`,
44+
`translate() called for ${locale} with ${Object.keys(entriesMap).length} entries`,
5545
);
5646

5747
const sourceDictionary: DictionarySchema = dictionaryFrom(
@@ -62,7 +52,7 @@ export class LingoTranslator implements Translator<LingoTranslatorConfig> {
6252
);
6353

6454
this.logger.debug(
65-
`[TRACE-LINGO] Created source dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,
55+
`Created source dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,
6656
);
6757
const translated = await this.translateDictionary(sourceDictionary, locale);
6858

@@ -76,35 +66,33 @@ export class LingoTranslator implements Translator<LingoTranslatorConfig> {
7666
sourceDictionary: DictionarySchema,
7767
targetLocale: string,
7868
): Promise<DictionarySchema> {
69+
const chunks = this.chunkDictionary(sourceDictionary);
7970
this.logger.debug(
80-
`[TRACE-LINGO] Chunking dictionary with ${Object.keys(sourceDictionary.entries).length} entries`,
71+
`Split dictionary with ${Object.keys(sourceDictionary.entries).length} into ${chunks.length} chunks`,
8172
);
82-
const chunks = this.chunkDictionary(sourceDictionary);
83-
this.logger.debug(`[TRACE-LINGO] Split into ${chunks.length} chunks`);
8473

8574
const translatedChunks: DictionarySchema[] = [];
8675

8776
for (let i = 0; i < chunks.length; i++) {
8877
const chunk = chunks[i];
8978
this.logger.debug(
90-
`[TRACE-LINGO] Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`,
79+
`Translating chunk ${i + 1}/${chunks.length} with ${Object.keys(chunk.entries).length} entries`,
9180
);
9281
const chunkStartTime = performance.now();
9382

9483
const translatedChunk = await this.translateChunk(chunk, targetLocale);
9584

9685
const chunkEndTime = performance.now();
9786
this.logger.debug(
98-
`[TRACE-LINGO] Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`,
87+
`Chunk ${i + 1}/${chunks.length} completed in ${(chunkEndTime - chunkStartTime).toFixed(2)}ms`,
9988
);
10089

10190
translatedChunks.push(translatedChunk);
10291
}
10392

104-
this.logger.debug(`[TRACE-LINGO] All chunks translated, merging results`);
10593
const result = this.mergeDictionaries(translatedChunks);
10694
this.logger.debug(
107-
`[TRACE-LINGO] Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`,
95+
`Merge completed, final dictionary has ${Object.keys(result.entries).length} entries`,
10896
);
10997

11098
return result;
@@ -139,7 +127,7 @@ export class LingoTranslator implements Translator<LingoTranslatorConfig> {
139127
);
140128
}
141129

142-
this.logger.info(
130+
this.logger.debug(
143131
`Using Lingo.dev Engine to localize from "${this.config.sourceLocale}" to "${targetLocale}"`,
144132
);
145133

@@ -184,7 +172,7 @@ export class LingoTranslator implements Translator<LingoTranslatorConfig> {
184172
);
185173
}
186174

187-
this.logger.info(
175+
this.logger.debug(
188176
`Using LLM ("${localeModel.provider}":"${localeModel.name}") to translate from "${this.config.sourceLocale}" to "${targetLocale}"`,
189177
);
190178

packages/new-compiler/src/translators/translation-service.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,9 @@ export class TranslationService {
117117
// Use console.error to ensure visibility in all contexts (loader, server, etc.)
118118
const errorMsg =
119119
error instanceof Error ? error.message : String(error);
120-
this.logger.warn(`\n⚠️ Translation setup error: ${errorMsg}\n`);
121-
this.logger.warn(
122-
`⚠️ Auto-fallback to pseudotranslator in development mode.\n` +
123-
` Set the required API keys for real translations.\n`,
124-
);
120+
this.logger.warn(`⚠️ Translation setup error: \n${errorMsg}\n
121+
⚠️ Auto-fallback to pseudotranslator in development mode.
122+
Set the required API keys for real translations.`);
125123

126124
this.translator = new PseudoTranslator(
127125
{ delayMedian: 100 },

0 commit comments

Comments
 (0)