@argos-js/i18n
v0.1.2
Published
Transparent, high-performance request-scoped internationalization (i18n) for Argos-JS
Readme
@argos-js/i18n
Transparent, high-performance, and request-scoped internationalization (i18n) for Argos-JS.
⚡ Overview
@argos-js/i18n provides seamless multi-language support built for asynchronous, high-throughput Node.js microservices and REST APIs:
- Isolated Request Context (
AsyncLocalStorage): Concurrent requests in different languages run concurrently without race conditions or cross-request pollution. - Fast Token Interpolation: Fast template engine substituting
{param}tokens. - Developer Ergonomics: Canonical
translate()along with concise aliasestrans()andt(), available both onctxand as standalone functions anywhere in your service layers. - Automatic Validation Localization: Intercepts
ctx.validate()failures and transforms schemaverrors into localized 422 JSON payloads based on the requester's language. - Smart Locale Detection: Resolves language preference from
Accept-Languageheaders (withqweight parsing), URL query parameters (?lang=es-ES), or cookies. - Built-in Community Locales: Ships with complete base translations for
pt-BR,en-US, andes-ES. - Regional Formatting: Built-in
formatCurrency()andformatDate()utilities utilizing nativeIntl.
📦 Installation
pnpm add @argos-js/i18n🚀 Quick Start
1. Register the Plugin
import { ArgosApp } from '@argos-js/core';
import { i18nPlugin, ptBR, enUS, esES } from '@argos-js/i18n';
const app = new ArgosApp();
await app.register(
i18nPlugin({
defaultLocale: 'pt-BR',
supportedLocales: ['pt-BR', 'en-US', 'es-ES'],
locales: {
'pt-BR': ptBR,
'en-US': enUS,
'es-ES': esES,
},
detection: {
header: 'accept-language',
query: 'lang', // e.g. ?lang=en-US
},
autoLocalizeValidation: true,
})
);2. Using in Controllers
Use ctx.translate, ctx.trans, or ctx.t directly:
app.get('/dashboard', (ctx) => {
const userName = 'Alice';
return ctx.json({
locale: ctx.locale, // e.g. 'pt-BR'
greeting: ctx.trans('common.welcome', { name: userName }),
balance: ctx.formatCurrency(1450.9, 'BRL'),
lastLogin: ctx.formatDate(new Date(), { dateStyle: 'medium' }),
});
});3. Standalone Usage in Services
Because @argos-js/i18n leverages AsyncLocalStorage, you can call translate or its aliases anywhere inside your business logic without passing ctx:
import { trans, t, translate } from '@argos-js/i18n';
export class OrderService {
async notifyCustomer(orderId: number) {
// Automatically uses the active request's language
const msg = trans('orders.paid_success', { id: orderId });
await emailClient.send(msg);
}
}🛡️ Automatic Validation Localization (422)
When validating schemas with ctx.validate(schema), @argos-js/i18n automatically translates the validation errors into the requester's language:
import { v } from '@argos-js/core';
app.post('/users', async (ctx) => {
const payload = await ctx.validate({
email: v.string().email(),
name: v.string().min(3),
});
return ctx.json({ success: true, data: payload });
});Response for Portuguese Requester (Accept-Language: pt-BR):
{
"success": false,
"error": "Falha na validação",
"fields": {
"email": "O campo deve ser um endereço de e-mail válido",
"name": "O campo deve conter no mínimo 3 caracteres"
}
}Response for Spanish Requester (Accept-Language: es-ES):
{
"success": false,
"error": "Validación fallida",
"fields": {
"email": "El campo debe ser una dirección de correo válida",
"name": "El campo debe contener al menos 3 caracteres"
}
}Response for English Requester (Accept-Language: en-US):
{
"success": false,
"error": "Validation failed",
"fields": {
"email": "The field must be a valid email address",
"name": "The field must contain at least 3 characters"
}
}🌐 Community Translations & Adding New Locales
Adding a new language is straightforward. Create a dictionary object matching the required keys and pass it to locales:
// src/locales/fr-FR.ts
export const frFR = {
validation: {
required: 'Le champ est obligatoire',
string: 'Le champ doit être une chaîne',
number: 'Le champ doit être un nombre',
email: 'Le champ doit être une adresse e-mail valide',
min_length: 'Le champ doit contenir au moins {min} caractères',
failed: 'Échec de la validation',
},
common: {
welcome: 'Bienvenue, {name} !',
},
};Register it in your app:
import { frFR } from './locales/fr-FR';
await app.register(
i18nPlugin({
defaultLocale: 'pt-BR',
locales: {
'fr-FR': frFR,
},
})
);🧰 Regional Formatting
import { formatCurrency, formatDate } from '@argos-js/i18n';
// Automatically uses the active request locale, or pass explicitly:
formatCurrency(1234.56, 'USD', 'en-US'); // "$1,234.56"
formatCurrency(1234.56, 'BRL', 'pt-BR'); // "R$ 1.234,56"
formatCurrency(1234.56, 'EUR', 'es-ES'); // "1.234,56 €"
formatDate(new Date(), { dateStyle: 'short' }); // "02/10/2026"📚 API Reference
Functions & Aliases
translate(key, params?, options?): Canonical translation function.trans(key, params?, options?): Shorter alias fortranslate.t(key, params?, options?): Ultra-short alias fortranslate.formatCurrency(value, currency, locale?): Localized currency formatter.formatDate(date, options?, locale?): Localized date and time formatter.getActiveLocale(): Retrieves the current request's locale tag.
Plugin
i18nPlugin(options: I18nOptions): Plugin factory for ArgosApp.
Base Locales
ptBR: Brazilian Portuguese dictionary.enUS: English dictionary.esES: Spanish dictionary.
📄 License
MIT © Argos-JS
