@mixxtor/translader
v1.0.3
Published
Modern TypeScript translation service with type inference and multiple providers. Framework agnostic with clean architecture.
Downloads
408
Maintainers
Readme
TransladerJS
A powerful, type-safe translation library for JavaScript and TypeScript
Features
✨ Multiple Translation Providers - Support for Google Translate (Free & Paid), with easy extensibility for DeepL, OpenAI, and more
🔒 Type-Safe - Full TypeScript support with intelligent type inference
🎯 Provider Switching - Dynamically switch between translation providers at runtime
📦 Zero Config - Works out of the box with sensible defaults
🚀 Modern - Built with ESM, works in Node.js 18+
🧪 Well Tested - Comprehensive test coverage
🔌 Framework Agnostic - Use with any JavaScript framework or vanilla JS
Installation
npm install @mixxtor/transladeryarn add @mixxtor/transladerpnpm add @mixxtor/transladerQuick Start
Basic Usage
import { createTranslator, providers } from '@mixxtor/translader'
const translator = createTranslator({
default: 'google-free',
providers: {
'google-free': providers.googleFree(),
},
})
// Translate text
const result = await translator.translateText('Hello, world!', 'en', 'es')
console.log(result.translation) // ¡Hola Mundo!Using Google Cloud Translation API
import { createTranslator, providers } from '@mixxtor/translader'
const translator = createTranslator({
default: 'google-paid',
providers: {
'google-paid': providers.googlePaid({
apiKey: process.env.GOOGLE_TRANSLATE_API_KEY,
}),
},
})
const result = await translator.translateText('Hello', 'en', 'ja')
console.log(result.translation) // こんにちはNeed help getting an API key? See our Google Cloud Setup Guide for detailed instructions.
Multiple Providers with Switching
const translator = createTranslator({
default: 'google-free',
providers: {
'google-free': providers.googleFree(),
'google-cloud': providers.googlePaid({ apiKey: 'YOUR_API_KEY' }),
},
})
// Use free provider
let result = await translator.translateText('Hello', 'en', 'es')
// Switch to paid provider
translator.use('google-cloud')
result = await translator.translateText('Hello', 'en', 'fr')Core Concepts
Providers
Providers are the backbone of Translader. Each provider implements translation functionality for a specific service:
- Google Translate Free - No API key required, good for development
- Google Cloud Translation - Official Google Cloud API, requires API key
Configuration
Use the defineConfig helper for type-safe configuration:
import { defineConfig, providers } from '@mixxtor/translader'
const config = defineConfig({
default: 'google-free',
providers: {
'google-free': providers.googleFree({
timeout: 5000,
}),
},
})
const translator = createTranslator(config)Type Safety
Translader provides full type inference based on your configuration:
const translator = createTranslator({
default: 'primary',
providers: {
'primary': providers.googleFree(),
'backup': providers.googlePaid({ apiKey: 'key' }),
},
})
// TypeScript knows about 'primary' and 'backup'
translator.use('primary') // ✅ Valid
translator.use('backup') // ✅ Valid
translator.use('invalid') // ❌ TypeScript errorAPI Reference
createTranslator(config)
Creates a new translator instance.
const translator = createTranslator({
default: 'provider-name',
providers: {
'provider-name': providers.googleFree(),
},
})Translation Methods
translateText(text, from, to)
Simple text translation.
const result = await translator.translateText('Hello', 'en', 'es')
// Returns: TranslationResulttranslate(params)
Full translation with all options.
const result = await translator.translate({
text: 'Hello, world!',
from: 'en',
to: 'es',
})
// Returns: TranslationResulttranslateBatch(params)
Translate multiple texts at once.
const result = await translator.translateBatch({
texts: ['Hello', 'Goodbye'],
from: 'en',
to: 'es',
})
// Returns: BatchTranslationResultdetect(text)
Detect the language of text.
const result = await translator.detect('Bonjour')
// Returns: DetectionResult with language 'fr'Provider Management
use(providerName)
Switch to a different provider.
translator.use('google-cloud')getCurrentProvider()
Get the name of the current provider.
const current = translator.getCurrentProvider()
// Returns: stringgetAvailableProviders()
Get a list of all configured providers.
const providers = translator.getAvailableProviders()
// Returns: string[]getSupportedLanguages()
Get supported languages for the current provider.
const result = await translator.getSupportedLanguages()
// Returns: SupportedLanguagesResultgetSupportedLanguagesFor(providerName)
Get supported languages for a specific provider.
const result = await translator.getSupportedLanguagesFor('google-free')
// Returns: SupportedLanguagesResultProvider Configuration
Google Translate Free
providers.googleFree({
timeout: 5000, // Request timeout in ms (optional)
retries: 3, // Number of retries (optional)
})Google Cloud Translation
providers.googlePaid({
apiKey: 'YOUR_API_KEY', // Required
timeout: 10000, // Request timeout in ms (optional)
retries: 3, // Number of retries (optional)
})Language Codes
Translader uses ISO 639-1 language codes:
type LanguageCode =
| 'en' // English
| 'es' // Spanish
| 'fr' // French
| 'de' // German
| 'it' // Italian
| 'ja' // Japanese
| 'ko' // Korean
| 'zh' // Chinese
// ... and many moreResponse Types
TranslationResult
interface TranslationResult {
success: boolean
translation?: string
query: {
text: string
from: LanguageCode
to: LanguageCode
}
provider?: string // Name of the provider that performed the translation
info?: {
detectedSourceLanguage?: LanguageCode
metadata?: Record<string, unknown>
}
error?: {
code?: number
info: string
type?: string
}
}BatchTranslationResult
interface BatchTranslationResult {
success: boolean
translations?: string[]
query: {
from: LanguageCode
to: LanguageCode
count: number
}
provider?: string // Name of the provider that performed the translation
info?: {
detectedSourceLanguage?: LanguageCode
metadata?: Record<string, unknown>
}
error?: {
code?: number
info: string
type?: string
}
}DetectionResult
interface DetectionResult {
success: boolean
language?: LanguageCode
confidence?: number
provider?: string // Name of the provider that performed the detection
alternatives?: Array<{
language: LanguageCode
confidence: number
}>
error?: {
code?: number
info: string
type?: string
}
}Error Handling
All methods return results with a success flag:
const result = await translator.translateText('Hello', 'en', 'es')
if (result.success) {
console.log(result.translation)
} else {
console.error(result.error)
}Advanced Usage
Environment-Based Configuration
const translator = createTranslator({
default: process.env.NODE_ENV === 'production' ? 'google-cloud' : 'google-free',
providers: {
'google-free': providers.googleFree(),
'google-cloud': providers.googlePaid({
apiKey: process.env.GOOGLE_TRANSLATE_API_KEY!,
}),
},
})Fallback Strategy
async function translateWithFallback(text: string, from: string, to: string) {
translator.use('primary')
let result = await translator.translateText(text, from, to)
if (!result.success) {
translator.use('backup')
result = await translator.translateText(text, from, to)
}
return result
}Framework Integration
Express
import express from 'express'
import { createTranslator, providers } from '@mixxtor/translader'
const app = express()
const translator = createTranslator({
default: 'google-free',
providers: {
'google-free': providers.googleFree(),
},
})
app.get('/translate', async (req, res) => {
const { text, from, to } = req.query
const result = await translator.translateText(text, from, to)
res.json(result)
})Next.js API Routes
import { createTranslator, providers } from '@mixxtor/translader'
const translator = createTranslator({
default: 'google-free',
providers: {
'google-free': providers.googleFree(),
},
})
export default async function handler(req, res) {
const { text, from, to } = req.query
const result = await translator.translateText(text, from, to)
res.json(result)
}Examples
See the examples directory for more usage examples:
- basic-usage.ts - Basic translation examples
- multiple-providers.ts - Provider switching and management
Documentation
- Quick Start Guide - Get started quickly
- Complete Overview - Comprehensive guide
- Google Cloud Setup - How to set up Google Cloud Translation API
- Contributing - How to contribute
License
MIT License - see LICENSE for details
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
