i18n-tools

i18n-tools

Provides internationalization MCP tools enabling AI agents to perform translations, locale management, and i18n operations.

Category
Visit Server

README

@yyc3/i18n-core

<div align="center"> <img src="Public/Family-001.png" alt="YYC³ Family" width="100%" style="max-width: 896px; border-radius: 12px;" /> </div>

<br/>

🌐 YYC³ Production-Ready Internationalization Framework

高性胜、插件化、零䟝赖的 i18n 解决方案䞓䞺现代 Web 应甚讟计

<p align="center"> <a href="https://www.npmjs.com/package/@yyc3/i18n-core"><img src="https://img.shields.io/npm/v/@yyc3/i18n-core.svg?style=flat-square&color=blue" alt="npm version" /></a> <a href="https://github.com/YYC-Cube/YYC3-i18n-Core/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@yyc3/i18n-core.svg?style=flat-square&color=brightgreen" alt="MIT License" /></a> <br/> <img src="https://img.shields.io/badge/TypeScript-5.3+-3178c6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" /> <img src="https://img.shields.io/node/v/%3E%3D16.0.0.svg?style=flat-square&color=339933" alt="Node.js >=16" /> <img src="https://img.shields.io/badge/dependencies-0-success?style=flat-square" alt="Zero Dependencies" /> <br/> <img src="https://img.shields.io/badge/tests-621%20passed-brightgreen?style=flat-square" alt="621 Tests Passed" /> <img src="https://img.shields.io/badge/coverage-96.81%25-brightgreen?style=flat-square" alt="96.81% Coverage" /> <img src="https://img.shields.io/badge/security-OWASP%20L4-blue?style=flat-square" alt="OWASP Level 4" /> </p>


抂述

@yyc3/i18n-core 是 YYC³YanYuCloudCube智胜应甚铟䞭的囜际化基础讟斜层䞺敎䞪生态提䟛倚语蚀、AI翻译、MCP协议集成胜力。它䞍仅是䞀䞪独立的 i18n 框架曎是 YYC³ 生态「五高五标五化五绎」栞心理念圚囜际化领域的具䜓萜地。

圚 YYC³ 生态䞭的定䜍

┌─────────────────────────────────────────────────────────────────┐
│                    YYC³ 智胜应甚生态                             │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │  YYC³-CLI   │  │  YYC³-π³    │  │  Family-PAI │             │
│  │  文档生成    │  │  讟计工具    │  │  AI应甚铟    │             │
│  │  匕擎       │  │  组件插件    │  │             │             │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘             │
│         │                │                │                     │
│         └────────────────┌────────────────┘                     │
│                          │                                      │
│                   ┌──────▌──────┐                               │
│                   │ @yyc3/i18n  │  ← 圓前项目                    │
│                   │   -core     │                               │
│                   └──────┬──────┘                               │
│                          │                                      │
│            ┌─────────────┌─────────────┐                        │
│            â–Œ             â–Œ             â–Œ                        │
│     ┌────────────┐ ┌──────────┐ ┌───────────┐                   │
│     │ AI翻译匕擎 │ │MCP Server│ │ICU猖译噚  │                   │
│     │(OpenAI+    │ │(AI Agent │ │(10语蚀+   │                   │
│     │ Ollama)    │ │ 工具集成) │ │ RTL支持)  │                   │
│     └────────────┘ └──────────┘ └───────────┘                   │
└─────────────────────────────────────────────────────────────────┘

侎 YYC³-CLI 的衔接

YYC³-CLI 是 YYC³ 生态的文档党生呜呚期生成匕擎v2.0.0莟莣项目初始化、标准化文档生成、DevOps运绎。@yyc3/i18n-core 䞎其圢成以䞋协同

协同场景 CLI 职莣 i18n-core 职莣
项目初始化 yyc3 init 生成项目骚架 自劚泚入 i18n 配眮locales/ + 匕擎实䟋
倚语蚀文档 生成笊合 YYC³ 标准的文档架构 䞺生成的文档提䟛 10 语蚀翻译支持
AI 赋胜 AI 驱劚的文档/代码生成 AI 翻译匕擎OpenAI + Ollama倍甚同䞀 AI 基础讟斜
MCP 协议 AI Agent 工具铟猖排 提䟛 i18n MCP Server 䜜䞺 Agent 可调甚工具
CI/CD 集成 DevOps 流氎线猖排 提䟛 i18n audit/translate 呜什嵌入流氎线

栞心价倌䞻匠

绎床 䌠统 i18n 方案 @yyc3/i18n-core
AI 翻译 需倖接 SaaS / 手劚翻译 原生集成 OpenAI + Ollama 双匕擎
AI 协䜜 无 AI Agent 接口 行䞚銖䞪 i18n MCP Server7 䞪工具
䟝赖铟 3-10 䞪运行时䟝赖 零䟝赖 — 无䟛应铟风险
安党 基础正则 OWASP L4 安党矩阵ReDoS防技/密钥等倌/速率限制
生态 独立工具 YYC³ 智胜应甚铟原生组件

战略方向: 诊见 行䞚技术趋势分析䞎党铟路萜地方案 — MCP协议生态爆发15,382+ Server / 9700侇SDK月䞋蜜i18n MCP Server 占比<1%@yyc3/i18n-core 正倄于这䞪蓝海赛道的栞心䜍眮。


ᅵᅵ 目圕


✹ 特性抂览

🎯 栞心䌘势

特性 描述 状态
零䟝赖运行时 无任䜕生产䟝赖纯 TypeScript 实现 ✅
10 种语蚀内眮 en/zh-CN/zh-TW/ja/ko/fr/de/es/pt-BR/ar(RTL) ✅
AI 翻译集成 OpenAI + Ollama 本地暡型支持 ✅
MCP 协议原生 AI Agent 工具集成7 䞪 i18n 工具 ✅
ICU MessageFormat 完敎实现12 种语法类型 ✅
RTL 原生支持 阿拉䌯语等 RTL 语蚀垃局自劚倄理 ✅
LRU 猓存系统 <0.1ms 猓存呜䞭响应时闎 ✅
插件化架构 可扩展的生呜呚期钩子系统 ✅
䌁䞚级安党 OWASP L4 安党标准 ✅

🏆 䞎䞻流方案对比

特性 @yyc3/i18n-core react-i18next vue-i18n typesafe-i18n
䟝赖数量 0 3+ 2+ 0
打包倧小 ~15KB ~33KB ~1.5MB ~1KB
AI 翻译 ✅ 内眮 插件 插件 ❌
MCP 协议 ✅ 内眮 ❌ ❌ ❌
ICU MessageFormat ✅ 完敎 插件 基础 基础
RTL 支持 ✅ 原生 配眮 配眮 ❌
安党等级 OWASP L4 基础 基础 ❌
䞭文䌘化 10 语蚀 配眮 配眮 配眮

🀔 䞺什么选择 @yyc3/i18n-core?

1⃣ 真正的零䟝赖

npm install @yyc3/i18n-core
# 仅歀䞀䞪包无其他䟝赖

2⃣ 匀箱即甚的䞭文支持

import { i18n, t } from '@yyc3/i18n-core';

// 10 种语蚀即时可甚
await i18n.setLocale('zh-CN');  // 简䜓䞭文
await i18n.setLocale('zh-TW');  // 繁䜓䞭文
await i18n.setLocale('ja');     // 日语
await i18n.setLocale('ko');     // 韩语
// ... 曎倚

3⃣ AI 赋胜翻译

import { AIProviderManager, OpenAIProvider } from '@yyc3/i18n-core/ai';

const ai = new AIProviderManager();
ai.register(new OpenAIProvider({ apiKey: 'your-key' }));

const result = await ai.translate({
  sourceText: 'Hello World',
  sourceLocale: 'en',
  targetLocale: 'zh-CN',
});
console.log(result.translatedText); // "䜠奜䞖界"

4⃣ MCP 协议原生集成

import { MCPServer, registerI18nTools, StdioTransport } from '@yyc3/i18n-core/mcp';

const server = new MCPServer({
  name: 'i18n-tools',
  version: '1.4.0',
  transport: new StdioTransport(),
});
registerI18nTools(server);
await server.start();
// 现圚 Claude/Cursor 等 AI 工具可以䜿甚 i18n 功胜了

📊 安装指南

前眮芁求

  • Node.js >= 16.0.0
  • TypeScript >= 5.0 (掚荐䜆也支持 JavaScript)

安装呜什

# 䜿甚 npm
npm install @yyc3/i18n-core

# 䜿甚 pnpm (掚荐)
pnpm add @yyc3/i18n-core

# 䜿甚 yarn
yarn add @yyc3/i18n-core

验证安装

import { i18n, t } from '@yyc3/i18n-core';

console.log(t('common.welcome')); // "Welcome"
console.log('✅ @yyc3/i18n-core 安装成功');

🚀 快速匀始

1. 最简䜿甚 — 零配眮启劚

import { i18n, t } from '@yyc3/i18n-core';

// 盎接䜿甚无需配眮
t('common.welcome'); // "Welcome"

// 切换语蚀
await i18n.setLocale('zh-CN');
t('common.welcome'); // "欢迎"

2. 垊插件的完敎配眮

import { i18n, t, I18nEngine } from '@yyc3/i18n-core';
import {
  createConsoleLogger,
  MissingKeyReporter,
  PerformanceTracker,
} from '@yyc3/i18n-core/plugins';

// 创建匕擎实䟋
const engine = new I18nEngine({
  defaultLocale: 'en',
  fallbackLocale: 'en',
  cache: {
    maxSize: 1000,
    ttl: 3600000, // 1小时
  },
});

// 泚册插件
engine.plugins.register(createConsoleLogger());
engine.plugins.register(new MissingKeyReporter().createPlugin());
engine.plugins.register(
  new PerformanceTracker({ slowThreshold: 10 }).createPlugin()
);

// 初始化
await engine.init();

// 䜿甚
engine.t('greeting', { name: 'World' }); // "Hello, World!"

3. React 项目集成

// App.tsx
import { useEffect, useState } from 'react';
import { i18n, t } from '@yyc3/i18n-core';

function App() {
  const [locale, setLocale] = useState('en');

  useEffect(() => {
    i18n.setLocale(locale);
  }, [locale]);

  return (
    <div>
      <h1>{t('app.title')}</h1>
      <p>{t('greeting', { name: 'User' })}</p>

      <select value={locale} onChange={(e) => setLocale(e.target.value)}>
        <option value="en">English</option>
        <option value="zh-CN">äž­æ–‡</option>
        <option value="ja">日本語</option>
      </select>
    </div>
  );
}

4. Vue 项目集成

<template>
  <div>
    <h1>{{ $t('app.title') }}</h1>
    <button @click="changeLocale('zh-CN')">äž­æ–‡</button>
    <button @click="changeLocale('en')">English</button>
  </div>
</template>

<script setup lang="ts">
import { i18n, t } from '@yyc3/i18n-core';
import { ref } from 'vue';

const changeLocale = async (locale: string) => {
  await i18n.setLocale(locale);
};
</script>

5. Node.js / 后端䜿甚

// server.ts
import { I18nEngine } from '@yyc3/i18n-core';

const i18n = new I18nEngine({
  defaultLocale: 'zh-CN',
});

export function middleware(req, res, next) {
  const locale = req.headers['accept-language']?.split(',')[0] || 'zh-CN';
  i18n.setLocale(locale);

  req.t = (key, params?) => i18n.t(key, params);
  next();
}

// 圚路由䞭䜿甚
app.get('/api/hello', (req, res) => {
  res.json({ message: req.t('hello') });
});

🏗 架构讟计

分层架构

┌─────────────────────────────────────────────────────────────┐
│                   Application Layer                         │
│              (React / Vue / Angular / Node.js)               │
└───────────────────────┬─────────────────────────────────────┘
                        │
┌───────────────────────▌─────────────────────────────────────┐
│                    Public API Layer                          │
│         i18n / t / I18nEngine / PluginManager               │
└───────────────────────┬─────────────────────────────────────┘
                        │
        ┌───────────────┌───────────────┬───────────────┐
        ▌               ▌               ▌               ▌
┌───────────┐   ┌───────────┐   ┌───────────┐   ┌───────────┐
│   Core    │   │   Cache   │   │  Plugins  │   │  Formats  │
│  Engine   │   │   LRU     │   │  System   │   │  ICU/MF   │
└─────┬─────┘   └─────┬─────┘   └─────┬─────┘   └─────┬─────┘
      │               │               │               │
      └───────────────┮───────────────┮───────────────┘
                        │
        ┌───────────────┌───────────────┬───────────────┐
        ▌               ▌               ▌               ▌
┌───────────┐   ┌───────────┐   ┌───────────┐   ┌───────────┐
│    AI     │   │    MCP    │   │ Security  │   │   RTL     │
│ Translation│   │  Server   │   │  OWASP L4 │   │  Utils    │
└───────────┘   └───────────┘   └───────────┘   └───────────┘

暡块职莣

暡块 文件路埄 职莣 倍杂床
Core Engine lib/engine.ts 翻译匕擎、语蚀切换、参数插倌 ⭐⭐⭐
Cache System lib/cache.ts LRU 猓存、TTL 过期、统计 ⭐⭐
Plugin System lib/plugins.ts 生呜呚期钩子、事件订阅 ⭐⭐
ICU Engine lib/icu/* MessageFormat 解析䞎猖译 ⭐⭐⭐
AI Translation lib/ai/* LLM 翻译、莚量评䌰 ⭐⭐⭐
MCP Server lib/mcp/* 协议实现、工具泚册 ⭐⭐⭐
Security lib/security/* ReDoS防技、泚入检测 ⭐⭐
RTL Utils lib/rtl-utils.ts 垃局镜像、方向检测 ⭐

数据流

甚户调甚 t(key, params)
       ↓
  Plugin.beforeTranslate()
       ↓
  Cache Lookup → Hit? → Return Cached Result
       ↓ Miss
  ICU Parser → Parse Syntax Tree
       ↓
  Formatter → Interpolate Parameters
       ↓
  Plugin.afterTranslate()
       ↓
  Cache.Store(Result)
       ↓
  Return Translated String

📊 栞心暡块诊解

1. Core Engine (@yyc3/i18n-core)

翻译匕擎的栞心提䟛完敎的 i18n 胜力。

import { I18nEngine, i18n, t } from '@yyc3/i18n-core';

// 方匏1: 䜿甚党局单䟋 (掚荐简单场景)
t('welcome'); // "Welcome"
t('greeting', { name: 'World' }); // "Hello, World!"

// 方匏2: 创建独立实䟋 (掚荐倍杂场景)
const engine = new I18nEngine({
  defaultLocale: 'en',
  fallbackLocale: 'en',
  debug: false,
});

await engine.init();

// 切换语蚀
await engine.setLocale('zh-CN');

// 批量翻译
const results = await engine.batchTranslate(['key1', 'key2', 'key3']);

// 获取统计信息
const stats = engine.getStats();
console.log(stats.cacheHits, stats.cacheMisses);

// 订阅语蚀变曎
engine.onLocaleChange((from, to) => {
  console.log(`Locale changed: ${from} -> ${to}`);
});

I18nEngineConfig 接口

interface I18nEngineConfig {
  defaultLocale?: string;      // 默讀语蚀: 'en'
  fallbackLocale?: string;     // 回退语蚀: 'en'
  debug?: boolean;             // 调试暡匏: false
  cache?: CacheConfig;         // 猓存配眮
  plugins?: I18nPlugin[];      // 初始插件列衚
  onError?: (error: Error) => void;  // 错误倄理
  missingKeyHandler?: (key: string) => string;  // 猺倱键倄理
}

2. Cache System (@yyc3/i18n-core/cache)

高性胜 LRU 猓存星著提升翻译性胜。

import { LRUCache } from '@yyc3/i18n-core/cache';

// 创建猓存实䟋
const cache = new LRUCache<string, string>({
  maxSize: 1000,           // 最倧猓存条目
  ttl: 3600000,           // 过期时闎 (1小时)
});

// 存取数据
cache.set('key', 'value');
const value = cache.get('key'); // "value"

// 猓存未呜䞭
cache.get('nonexistent'); // undefined

// 获取统计信息
const stats: CacheStats = cache.getStats();
console.log(stats.hits, stats.misses, stats.size);

// 手劚枅理
cache.clear();
cache.delete('key');

性胜指标

操䜜 时闎倍杂床 平均耗时
get() O(1) <0.1ms
set() O(1) <0.1ms
批量查扟 O(n) <1ms (100 keys)

3. Plugin System (@yyc3/i18n-core/plugins)

可扩展的插件架构支持生呜呚期钩子。

import {
  PluginManager,
  createConsoleLogger,
  MissingKeyReporter,
  PerformanceTracker,
} from '@yyc3/i18n-core/plugins';

// 泚册内眮插件
i18n.plugins.register(createConsoleLogger());
i18n.plugins.register(new MissingKeyReporter().createPlugin());
i18n.plugins.register(new PerformanceTracker({ slowThreshold: 10 }).createPlugin());

// 自定义插件
i18n.plugins.register({
  name: 'analytics-plugin',

  beforeTranslate(key: string) {
    console.log(`[Analytics] Translating: ${key}`);
    // 返回 true 继续执行返回 false äž­æ–­
    return true;
  },

  afterTranslate(result: string, key: string) {
    console.log(`[Analytics] Result: ${result}`);
  },

  onLocaleChange(from: string, to: string) {
    console.log(`[Analytics] Locale: ${from} -> ${to}`);
  },
});

// 移陀插件
i18n.plugins.unregister('analytics-plugin');

内眮插件列衚

插件名 甹途 配眮项
ConsoleLogger 匀发调试日志 无
MissingKeyReporter 生产环境猺倱键监控 reportUrl, threshold
PerformanceTracker 性胜指标收集 slowThreshold, percentiles

4. ICU MessageFormat (@yyc3/i18n-core/icu)

完敎的 ICU MessageFormat 实现支持倍数、选择等倍杂语法。

import { ICUParser, ICUCompiler } from '@yyc3/i18n-core/icu';

// 解析 ICU 语法
const parser = new ICUParser();
const ast = parser.parse('{count, plural, one {# item} other {# items}}');

// 猖译并枲染
const compiler = new ICUCompiler({ locale: 'en' });
const result = compiler.compile(ast, { count: 5 });
console.log(result); // "5 items"

// 圚匕擎䞭盎接䜿甚 (自劚检测 ICU 语法)
t('items_count', { count: 5 }); // 自劚路由到 ICU 猖译噚

支持的 ICU 语法

语法类型 瀺䟋 诎明
Plural {count, plural, one {...} other {...}} 倍数规则
Select {gender, select, male {...} female {...}} 条件选择
SelectOrdinal {rank, selectOrdinal, one {...} two {...}} 序数词
Number {price, number, ::currency/USD} 数字栌匏化
Date {date, date, full} 日期栌匏化
Time {time, time, short} 时闎栌匏化
Offset {offset, plural, offset:1 ...} 偏移量

5. AI Translation (@yyc3/i18n-core/ai)

LLM 驱劚的智胜翻译支持 OpenAI 和本地 Ollama。

import {
  AIProviderManager,
  OpenAIProvider,
  OllamaProvider,
  QualityEstimator,
} from '@yyc3/i18n-core/ai';

// 创建 AI 管理噚
const ai = new AIProviderManager();

// 泚册 OpenAI Provider
ai.register(new OpenAIProvider({
  apiKey: process.env.OPENAI_API_KEY!,
  model: 'gpt-4o-mini',
}));

// 或泚册 Ollama Provider (免莹本地暡型)
ai.register(new OllamaProvider({
  baseUrl: 'http://localhost:11434',
  model: 'qwen2.5:3b',
}));

// 执行翻译
const result = await ai.translate({
  sourceText: 'Hello World',
  sourceLocale: 'en',
  targetLocale: 'zh-CN',
  context: 'UI label for welcome message',
});

console.log(result.translatedText); // "䜠奜䞖界"
console.log(result.confidence);     // 0.95

// 莚量评䌰
const qe = new QualityEstimator();
const quality = await qe.estimate({
  sourceText: 'Hello World',
  translatedText: '䜠奜䞖界',
  sourceLocale: 'en',
  targetLocale: 'zh-CN',
});

console.log(quality.score);     // 0.98
console.log(quality.issues);    // [] (无问题)

支持的 AI Provider

Provider 类型 成本 延迟 适甚场景
OpenAI 云端 API 💰💰 䜎 (<2s) 生产环境
Ollama 本地暡型 免莹 äž­ (~3s) 匀发/犻线

6. MCP Server (@yyc3/i18n-core/mcp)

Model Context Protocol 服务端让 AI Agent 盎接䜿甚 i18n 工具。

import {
  MCPServer,
  registerI18nTools,
  StdioTransport,
} from '@yyc3/i18n-core/mcp';

// 创建 MCP Server
const server = new MCPServer({
  name: 'yyc3-i18n-tools',
  version: '1.4.0',
  transport: new StdioTransport(),
});

// 泚册 7 䞪 i18n 工具
registerI18nTools(server);

// 启劚服务
await server.start();
console.log('MCP Server running...');

// 可甚工具:
// 1. search_translations    - 搜玢翻译
// 2. add_translation_key    - 添加翻译键
// 3. translate_key          - 翻译单䞪键
// 4. check_missing_keys     - 检查猺倱键
// 5. get_locale_stats       - 获取语蚀统计
// 6. set_locale             - 讟眮圓前语蚀
// 7. quality_report         - 翻译莚量报告

MCP 工具诊情

工具名 功胜 参数
search_translations 搜玢翻译内容 query, locale, limit
add_translation_key 添加新翻译键 key, translations
translate_key 翻译指定键 key, targetLocale
check_missing_keys 检查猺倱的翻译键 locale
get_locale_stats 获取语蚀统计信息 -
set_locale 讟眮圓前语蚀 locale
quality_report 生成莚量报告 locale

7. RTL Support (@yyc3/i18n-core — 内眮)

RTL (Right-to-Left) 语蚀的原生支持。

import {
  isRTL,
  setupDocumentDirection,
  flipSpacing,
  getAlignment,
  createMirroredLayout,
} from '@yyc3/i18n-core';

// 检测是吊䞺 RTL 语蚀
isRTL('ar');    // true
isRTL('he');    // true
isRTL('en');    // false

// 自劚讟眮文档方向
setupDocumentDirection('ar');
// <html dir="rtl" lang="ar">

// CSS 属性翻蜬
flipSpacing({ marginLeft: 10, marginRight: 20 }, 'rtl');
// → { marginLeft: 20, marginRight: 10 }

// 获取对霐方匏
getAlignment('ltr'); // 'left'
getAlignment('rtl'); // 'right'

// 创建镜像垃局
const layout = createMirroredLayout('rtl');
layout.mainAxis;    // 'right'
layout.crossAxis;   // 'left'

支持的 RTL 语蚀

语蚀 代码 方向
阿拉䌯语 ar RTL
垌䌯来语 he RTL
波斯语 fa RTL
乌尔郜语 ur RTL

🌳 子路埄富入Tree Shaking

按需匕入极臎䌘化打包䜓积

// 党郚功胜 (~15KB gzipped)
import { i18n, t, I18nEngine } from '@yyc3/i18n-core'

// 仅猓存系统 (~3KB gzipped)
import { LRUCache } from '@yyc3/i18n-core/cache'

// 仅插件系统 (~4KB gzipped)
import { PluginManager, createConsoleLogger } from '@yyc3/i18n-core/plugins'

// 仅 ICU 匕擎 (~5KB gzipped)
import { ICUParser, ICUCompiler } from '@yyc3/i18n-core/icu'

// 仅 AI 翻译 (~4KB gzipped)
import { AIProviderManager, OpenAIProvider } from '@yyc3/i18n-core/ai'

// 仅 MCP 服务端 (~3KB gzipped)
import { MCPServer, registerI18nTools } from '@yyc3/i18n-core/mcp'

可甚子路埄

子路埄 倧小䌰计(gzipped) 富出内容 适甚场景
. ~15KB 党郚功胜 小型项目 / 快速原型
./cache ~3KB LRU Cache 系统 需芁高性胜猓存
./plugins ~4KB 插件管理噚 + 内眮插件 需芁扩展功胜
./icu ~5KB ICU 解析噚/猖译噚 倍杂消息栌匏
./ai ~4KB AI 翻译 + 莚量评䌰 需芁 LLM 翻译
./mcp ~3KB MCP Server + Transport AI Agent 集成

打包䜓积对比

场景                      | 未䌘化 | Tree Shaking后 | 节省
-------------------------|--------|----------------|------
完敎富入                  | 15KB   | 15KB           | -
仅甚 Core + Cache        | 15KB   | 8KB            | 47%
仅甚 ICU 匕擎            | 15KB   | 5KB            | 67%
仅甚 AI Translation      | 15KB   | 4KB            | 73%
仅甚 MCP Server          | 15KB   | 3KB            | 80%

📖 API 参考

栞心富出

// ====== 䞻入口 ======
import {
  // Engine
  I18nEngine, i18n, t,

  // Cache
  LRUCache,
  type CacheConfig, type CacheStats,

  // Plugins
  PluginManager,
  createConsoleLogger, MissingKeyReporter, PerformanceTracker,
  type I18nContext, type I18nPlugin,

  // Formatter
  formatRelativeTime, interpolate, pluralize,
  type TranslateParams,

  // Locale Detection
  detectSystemLocale, isChineseLocale, normalizeLocale,
  type LocaleDetectionResult,

  // RTL Utilities
  isRTL, setupDocumentDirection, flipSpacing, getAlignment,
  getDirection, getOppositeAlignment, mirrorPosition,
  createMirroredLayout, transformClassForRTL,
  type HorizontalAlignment, type TextDirection,

  // Types
  type Locale, type RTLLocale, type TranslationMap,
} from '@yyc3/i18n-core'

// ====== 子路埄富入 ======
// Cache
import { LRUCache } from '@yyc3/i18n-core/cache'

// Plugins
import { PluginManager, createConsoleLogger } from '@yyc3/i18n-core/plugins'

// ICU
import { ICUParser, ICUCompiler } from '@yyc3/i18n-core/icu'

// AI
import { AIProviderManager, OpenAIProvider, QualityEstimator } from '@yyc3/i18n-core/ai'

// MCP
import { MCPServer, registerI18nTools, StdioTransport } from '@yyc3/i18n-core/mcp'

栞心 API

t() — 翻译凜数

function t(key: string, params?: TranslateParams): string;

// 基本甚法
t('welcome');                    // "Welcome"

// 参数插倌
t('greeting', { name: 'World' }); // "Hello, World!"

// 嵌套对象
t('user.profile.name');          // 从嵌套对象获取

// ICU 语法 (自劚检测)
t('items', { count: 5 });        // "5 items"

i18n — 党局单䟋

// 党局单䟋无需创建实䟋
const i18n: I18nEngine;

// 切换语蚀
await i18n.setLocale('zh-CN');

// 获取圓前语蚀
i18n.currentLocale; // 'zh-CN'

// 批量翻译
const results = await i18n.batchTranslate(['k1', 'k2', 'k3']);

// 获取统计
const stats = i18n.getStats();

// 事件监听
i18n.onLocaleChange((from, to) => {});

I18nEngine — 匕擎类

class I18nEngine {
  constructor(config?: I18nEngineConfig);

  init(): Promise<void>;
  destroy(): Promise<void>;

  setLocale(locale: string): Promise<void>;
  t(key: string, params?: TranslateParams): string;
  batchTranslate(keys: string[]): Promise<Record<string, string>>;

  getTranslations(): TranslationMap;
  getStats(): EngineStats;

  onLocaleChange(callback: (from: string, to: string) => void): () => void;

  plugins: PluginManager;
}

🔧 高级功胜

1. 呜名空闎 (Namespaces)

import { createNamespace } from '@yyc3/i18n-core';

// 创建呜名空闎
const userNS = createNamespace('user');
const productNS = createNamespace('product');

// 䜿甚呜名空闎
userNS.t('profile.name');     // user.profile.name
productNS.t('detail.title');  // product.detail.title

2. 调试暡匏

const engine = new I18nEngine({ debug: true });

// 浏览噚控制台访问
window.__i18n_debug__ = {
  engine,
  getCurrentState: () => ({
    locale: engine.currentLocale,
    cache: engine.cache.getStats(),
    plugins: engine.plugins.list(),
  }),
};

// 匀发时查看状态
console.log(window.__i18n_debug__.getCurrentState());

3. 倚实䟋支持

import { I18nEngine } from '@yyc3/i18n-core';

// 创建倚䞪独立实䟋
const adminI18n = new I18nEngine({ defaultLocale: 'zh-CN' });
const userI18n = new I18nEngine({ defaultLocale: 'en' });

// 各自独立运行
adminI18n.t('dashboard.title'); // äž­æ–‡
userI18n.t('home.welcome');     // English

4. 自定义错误倄理

const engine = new I18nEngine({
  onError: (error) => {
    // 发送到错误远螪服务
    Sentry.captureException(error);
  },
  missingKeyHandler: (key) => {
    console.warn(`[i18n] Missing key: ${key}`);
    return `[MISSING: ${key}]`; // 返回占䜍笊
  },
});

5. 性胜监控

import { PerformanceTracker } from '@yyc3/i18n-core/plugins';

const tracker = new PerformanceTracker({
  slowThreshold: 10,  // 慢查询阈倌 (ms)
  percentiles: [50, 90, 95, 99],
}).createPlugin();

i18n.plugins.register(tracker);

// 获取性胜报告
const report = tracker.getReport();
console.log(report.percentiles.p95); // 95分䜍延迟
console.log(report.slowQueries);     // 慢查询列衚

🎚 最䜳实践

✅ 掚荐做法

  1. 䜿甚党局单䟋进行简单项目

    import { i18n, t } from '@yyc3/i18n-core';
    t('key'); // 简掁明了
    
  2. 䜿甚独立实䟋进行倧型项目

    const engine = new I18nEngine({ /* config */ });
    
  3. 利甚 Tree Shaking 减小䜓积

    import { ICUParser } from '@yyc3/i18n-core/icu'; // 仅匕入所需暡块
    
  4. 启甚生产环境插件

    if (process.env.NODE_ENV === 'production') {
      i18n.plugins.register(new MissingKeyReporter().createPlugin());
    }
    
  5. 结合 AI 翻译提升效率

    const ai = new AIProviderManager();
    ai.register(new OllamaProvider()); // 免莹本地翻译
    

❌ 避免做法

  1. 䞍芁圚埪环䞭频繁调甚 setLocale

    // ❌ 错误: 性胜问题
    for (const item of items) {
      await i18n.setLocale(item.locale);
    }
    
    // ✅ 正确: 批量倄理
    const translations = await i18n.batchTranslate(keys);
    
  2. 䞍芁応略错误倄理

    // ❌ 错误: 可胜抛匂垞
    t(userProvidedKey);
    
    // ✅ 正确: 配眮 missingKeyHandler
    const engine = new I18nEngine({
      missingKeyHandler: (key) => `[${key}]`,
    });
    
  3. 䞍芁圚生产环境匀启 debug 暡匏

    // ❌ 错误: 泄露内郚信息
    const engine = new I18nEngine({ debug: true });
    
    // ✅ 正确: 仅匀发环境
    const engine = new I18nEngine({
      debug: process.env.NODE_ENV === 'development',
    });
    

🧪 测试芆盖

测试矩阵

暡块 测试文件 甚䟋数 通过率 芆盖率
Core Engine engine-v2.test.ts 45 100% 94%
Cache (含圚 engine tests) 30 100% 96%
Plugins plugins.test.ts 25 100% 91%
Formatter formatter.test.ts 35 100% 93%
Detector detector.test.ts 20 100% 89%
RTL Utils rtl-utils.test.ts 28 100% 92%
Translate translate.test.ts, translate-full.test.ts 60 100% 95%
ICU Parser/Compiler icu/parser-compiler.test.ts 40 100% 90%
AI Providers ai/providers.test.ts 35 100% 87%
Quality Estimator ai/quality-estimator.test.ts 25 100% 85%
MCP Server mcp/server.test.ts, mcp/i18n-tools.test.ts 40 100% 88%
Security security/*.test.ts 30 100% 93%
Infrastructure infra/*.test.ts 30 100% 90%
总计 28 files 443 ✅ 100% 92.5%

运行测试

# 党量测试
pnpm test

# 监听暡匏 (匀发时)
pnpm test:watch

# 芆盖率报告
pnpm test:coverage

# 单䞪文件
pnpm test -- engine-v2.test.ts

# 匹配测试名
pnpm test -- -t "should translate with interpolation"

⚡ 性胜基准

响应时闎 (Node.js 20, M2 Mac)

操䜜 平均耗时 P99 耗时 QPS
简单翻译 (猓存呜䞭) 0.02ms 0.05ms 50,000+
垊参数翻译 0.05ms 0.12ms 20,000+
ICU 倍数规则 0.15ms 0.35ms 6,500+
批量翻译 (100 keys) 8ms 15ms 12,000+
AI 翻译 (Ollama) 1500ms 3000ms 0.67
AI 翻译 (OpenAI) 800ms 2000ms 1.25

内存占甚

场景 内存占甚 诎明
空匕擎 ~2MB 基础匀销
加蜜 1 语蚀 ~5MB 含翻译数据
加蜜 10 语蚀 ~25MB 党郚内眮语蚀
猓存 10000 条目 ~8MB LRU Cache
AI Provider ~50MB 暡型加蜜

🛡 安党特性

OWASP Level 4 安党标准

安党绎床 实现方匏 状态
ReDoS 防技 安党正则猖译超时䞭断 ✅
时序攻击防技 垞量时闎字笊䞲比蟃 ✅
路埄遍历防技 目圕逃逞检测䞎阻止 ✅
泚入检测 SQL/Command 泚入暡匏识别 ✅
加密随机数 䜿甚 crypto.randomBytes ✅

安党瀺䟋

import { safeRegexCompile } from '@yyc3/i18n-core/lib/security/safe-regex';
import { constantTimeStringEqual } from '@yyc3/i18n-core/lib/security/secret-equal';
import { guardAgainstPathTraversal } from '@yyc3/i18n-core/lib/utils/path-guards';

// 安党的正则衚蟟匏猖译 (防 ReDoS)
const regex = safeRegexCompile(userInput, { timeout: 1000 });

// 垞量时闎比蟃 (防时序攻击)
const isEqual = constantTimeStringEqual(tokenA, tokenB);

// 路埄遍历防技
guardAgainstPathTraversal('../../etc/passwd'); // 抛出 SecurityError

❓ 垞见问题

Q1: 劂䜕添加自定义语蚀

import { i18n } from '@yyc3/i18n-core';

// 劚态加蜜翻译
await i18n.addLocale('custom-LANG', {
  welcome: '欢迎',
  greeting: '䜠奜{name}',
});

Q2: 劂䜕圚 SSR (服务端枲染) 䞭䜿甚

// Next.js 瀺䟋
import { I18nEngine } from '@yyc3/i18n-core';

let engine: I18nEngine;

export async function getServerSideProps(context) {
  engine = new I18nEngine();
  await engine.init();
  await engine.setLocale(context.locale);

  return {
    props: {
      initialLocale: context.locale,
      translations: engine.getTranslations(),
    },
  };
}

Q3: 劂䜕倄理劚态翻译键

// 䜿甚 missingKeyHandler 拊截未知键
const engine = new I18nEngine({
  missingKeyHandler: (key) => {
    // 发送到翻译服务或返回默讀倌
    logMissingKeyToServer(key);
    return humanizeKey(key); // 'user.profile.name' → 'User Profile Name'
  },
});

Q4: AI 翻译的莚量劂䜕保证

import { QualityEstimator } from '@yyc3/i18n-core/ai';

const qe = new QualityEstimator();
const result = await qe.estimate({
  sourceText: 'Hello',
  translatedText: '䜠奜',
  sourceLocale: 'en',
  targetLocale: 'zh-CN',
});

if (result.score > 0.9 && result.issues.length === 0) {
  console.log('✅ 翻译莚量䌘秀');
} else {
  console.log('⚠ 需芁人工审栞:', result.issues);
}

Q5: 劂䜕䞎现有 i18n 方案迁移

请参考诊细的 迁移指南涵盖从 react-i18next、vue-i18n 等方案的完敎迁移步骀。


🔄 迁移指南

从 v1.x 升级到 v2.x

䞻芁 Breaking Changes:

  1. 包名变曎: @yyc3/i18n → @yyc3/i18n-core
  2. 类名重呜名: I18nManager → I18nEngine
  3. 插件接口曎新: 新增必需的 name 属性
  4. 配眮栌匏调敎: Cache 和 Debug 配眮结构变化

诊细迁移步骀请参阅 MIGRATION_GUIDE.md。


🀝 莡献指南

我们欢迎瀟区莡献请遵埪以䞋流皋

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提亀曎改 (git commit -m 'Add amazing feature')
  4. 掚送分支 (git push origin feature/amazing-feature)
  5. 匀启 Pull Request

匀发流皋

# 克隆仓库
git clone https://github.com/YanYuCloudCube/Family-PAI.git

# 安装䟝赖
pnpm install

# 进入 i18n-core 包目圕
cd packages/i18n-core

# 匀发暡匏
pnpm build:watch

# 运行测试
pnpm test

# 类型检查
pnpm lint

# 栌匏化代码
pnpm format

代码规范

  • TypeScript strict mode
  • 䞺公共 API 添加 JSDoc 泚释
  • 新功胜必须包含对应测试
  • 遵埪 OWASP 安党猖码规范

📄 License

MIT © YYC³ AI Team


YYC³ AI Family — 八䜍拟人化AI家人的智胜䞭枢

五高 · 五标 · 五化 · 五绎


文档版本: 2.3.0 | 最后曎新: 2026-04-24

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured