npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@yyc3/i18n-core

v2.4.0

Published

🌐 YYC³ Production-Ready Internationalization (i18n) Framework - High-performance, plugin-based, zero-dependency i18n solution for TypeScript/JavaScript applications

Readme

@yyc3/i18n-core

🌐 YYC³ Production-Ready Internationalization Framework

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


📋 目圕


✹ 特性抂览

🎯 栞心䌘势

| 特性 | 描述 | 状态 | |------|------|------| | 零䟝赖运行时 | 无任䜕生产䟝赖纯 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