Skip to main content

@happyvertical/translator

Standardized translation interface supporting Google Translate, DeepL, and LibreTranslate. Uses a factory/adapter pattern with a unified Translator interface across all providers. Google and DeepL providers include automatic in-memory caching via @happyvertical/cache.

Installation​

pnpm add @happyvertical/translator
# Requires GitHub Packages registry for @happyvertical scope

Quick Start​

Environment Variables​

export HAVE_TRANSLATOR_PROVIDER=deepl
export DEEPL_API_KEY=your_key
import { getTranslator } from '@happyvertical/translator';

const translator = await getTranslator();
const result = await translator.translate('Hello, world!', 'es');
console.log(result.translatedText); // "Β‘Hola, mundo!"

Explicit Options​

// Google Translate
const translator = await getTranslator({
provider: 'google',
apiKey: process.env.GOOGLE_TRANSLATE_API_KEY!,
});

// DeepL
const translator = await getTranslator({
provider: 'deepl',
apiKey: process.env.DEEPL_API_KEY!,
freeApi: true,
});

// LibreTranslate (no API key required for public instances)
const translator = await getTranslator({
provider: 'libretranslate',
apiUrl: 'https://libretranslate.com',
});

Template Function​

Create pre-configured translation functions for repeated use:

const t = translator.templateFunction('en', 'es');

const greeting = await t('Hello, world!'); // "Β‘Hola, mundo!"
const farewell = await t('Goodbye!'); // "Β‘AdiΓ³s!"

API​

getTranslator(options?): Promise<Translator>​

Factory function. Reads HAVE_TRANSLATOR_* environment variables, merged with explicit options (explicit wins).

Translator Interface​

interface Translator {
translate(text: string, targetLang: string, sourceLang?: string): Promise<TranslationResult>;
detectLanguage(text: string): Promise<LanguageDetectionResult>;
getSupportedLanguages(): Promise<SupportedLanguage[]>;
translateBatch(texts: string[], targetLang: string, sourceLang?: string): Promise<TranslationResult[]>;
templateFunction(sourceLang?: string, targetLang?: string): (text: string) => Promise<string>;
}

TranslationResult​

interface TranslationResult {
translatedText: string;
sourceText: string;
sourceLanguage: string;
targetLanguage: string;
confidence?: number;
alternatives?: string[];
detectedSourceLanguage: boolean;
raw: any;
}

LanguageDetectionResult​

interface LanguageDetectionResult {
language: string;
confidence: number;
alternatives?: Array<{ language: string; confidence: number }>;
raw: any;
}

Error Classes​

All extend TranslationError:

  • TranslationError β€” base error with code and provider fields
  • UnsupportedLanguageError β€” invalid language code
  • QuotaExceededError β€” provider quota limit hit
  • AuthenticationError β€” bad or missing API key
  • InvalidTextError β€” empty or invalid input text

Environment Variables​

VariableDescription
HAVE_TRANSLATOR_PROVIDERgoogle, deepl, or libretranslate
HAVE_TRANSLATOR_TIMEOUTRequest timeout in ms
HAVE_TRANSLATOR_MAX_RETRIESMax retry attempts
HAVE_TRANSLATOR_API_URLLibreTranslate instance URL
HAVE_TRANSLATOR_FREE_APIDeepL free tier (true/false)
HAVE_TRANSLATOR_PROJECT_IDGoogle Cloud project ID
GOOGLE_TRANSLATE_API_KEYGoogle Translate API key
DEEPL_API_KEYDeepL API key

Utility Exports​

  • LANGUAGE_NAMES β€” map of ISO 639-1 codes to English names
  • isValidLanguageCode(code) β€” validates 2-letter language codes
  • getLanguageName(code) β€” looks up language name from code
  • normalizeConfidence(score) β€” normalizes scores to 0–1 range
  • isValidText(text) β€” checks text is non-empty
  • truncateText(text, maxLength) β€” truncates with ellipsis

License​

ISC