同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
tmp/
|
||||
inputs/
|
||||
outputs/
|
||||
__pycache__/
|
||||
dist/
|
||||
.env
|
||||
*.log
|
||||
.continuerules
|
||||
.continue/
|
||||
@@ -0,0 +1,320 @@
|
||||
#!/usr/bin/env node
|
||||
import { execSync } from 'child_process';
|
||||
import { copyFileSync, mkdirSync, existsSync, readFileSync, writeFileSync, rmSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = join(__dirname, '..');
|
||||
|
||||
// 辅助函数:执行命令
|
||||
function exec(command, options = {}) {
|
||||
console.log(`\n📦 执行: ${command}`);
|
||||
try {
|
||||
execSync(command, { stdio: 'inherit', cwd: rootDir, ...options });
|
||||
} catch (error) {
|
||||
console.error(`❌ 命令失败: ${command}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数:确保目录存在
|
||||
function ensureDir(dir) {
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数:读取和写入 JSON
|
||||
function readJSON(path) {
|
||||
return JSON.parse(readFileSync(path, 'utf-8'));
|
||||
}
|
||||
|
||||
function writeJSON(path, data) {
|
||||
writeFileSync(path, JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
// 获取命令行参数
|
||||
const args = process.argv.slice(2);
|
||||
const command = args[0];
|
||||
|
||||
// 构建任务
|
||||
const tasks = {
|
||||
// 清理所有构建产物
|
||||
clean() {
|
||||
console.log('🧹 清理构建产物...');
|
||||
const dirs = [
|
||||
'packages/web/build',
|
||||
'packages/web/dist',
|
||||
'packages/core/dist',
|
||||
'packages/core/web-build',
|
||||
'packages/electron/dist',
|
||||
'packages/electron/web-build'
|
||||
];
|
||||
|
||||
dirs.forEach(dir => {
|
||||
const path = join(rootDir, dir);
|
||||
if (existsSync(path)) {
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
console.log(` ✅ 已删除: ${dir}`);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// 构建 Web 前端
|
||||
async buildWeb() {
|
||||
console.log('\n🌐 构建 Web 前端...');
|
||||
exec('npm run build', { cwd: join(rootDir, 'packages/web') });
|
||||
},
|
||||
|
||||
// 构建 Shared 包
|
||||
async buildShared() {
|
||||
console.log('\n📦 构建 Shared 包...');
|
||||
exec('npm run build', { cwd: join(rootDir, 'packages/shared') });
|
||||
},
|
||||
|
||||
// 构建 Shared 包 (用于发布)
|
||||
async buildSharedForPublish() {
|
||||
console.log('\n📦 构建 Shared 包 (发布版)...');
|
||||
const sharedDir = join(rootDir, 'packages/shared');
|
||||
|
||||
// 先构建
|
||||
await tasks.buildShared();
|
||||
|
||||
// 处理 package.json(用于发布)
|
||||
const pkgPath = join(sharedDir, 'package.json');
|
||||
let pkg = readJSON(pkgPath);
|
||||
|
||||
// 更新版本号
|
||||
const rootPkg = readJSON(join(rootDir, 'package.json'));
|
||||
pkg.version = rootPkg.version;
|
||||
|
||||
writeJSON(pkgPath, pkg);
|
||||
console.log(' ✅ 已处理 Shared 包发布配置');
|
||||
},
|
||||
|
||||
// 构建 Core(Node.js 核心)
|
||||
async buildCore() {
|
||||
console.log('\n🎯 构建 Core 包...');
|
||||
const coreDir = join(rootDir, 'packages/core');
|
||||
const distDir = join(coreDir, 'dist');
|
||||
|
||||
// 创建输出目录
|
||||
ensureDir(distDir);
|
||||
|
||||
// 先确保 Web 已构建
|
||||
if (!existsSync(join(rootDir, 'packages/web/build'))) {
|
||||
await tasks.buildWeb();
|
||||
}
|
||||
|
||||
// 使用完整构建流程(包含web构建)
|
||||
exec('npm run build:full', { cwd: coreDir });
|
||||
|
||||
// 复制必要文件
|
||||
const filesToCopy = ['README.md'];
|
||||
filesToCopy.forEach(file => {
|
||||
const src = join(rootDir, file);
|
||||
const dest = join(distDir, file);
|
||||
if (existsSync(src)) {
|
||||
copyFileSync(src, dest);
|
||||
console.log(` ✅ 复制: ${file}`);
|
||||
}
|
||||
});
|
||||
|
||||
// 处理 package.json(用于发布)
|
||||
if (args.includes('--publish')) {
|
||||
const corePkgPath = join(coreDir, 'package.json');
|
||||
let pkg = readJSON(corePkgPath);
|
||||
|
||||
// 更新版本号
|
||||
const rootPkg = readJSON(join(rootDir, 'package.json'));
|
||||
pkg.version = rootPkg.version;
|
||||
|
||||
// 替换 file: 依赖为实际的包版本
|
||||
if (pkg.dependencies && pkg.dependencies['@dadigua/hyperchat-shared']) {
|
||||
pkg.dependencies['@dadigua/hyperchat-shared'] = `^${rootPkg.version}`;
|
||||
console.log(` ✅ 更新 @dadigua/hyperchat-shared 依赖版本: ^${rootPkg.version}`);
|
||||
}
|
||||
|
||||
writeJSON(corePkgPath, pkg);
|
||||
console.log(' ✅ 已处理 Core 包发布配置');
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
|
||||
// 构建 Electron
|
||||
async buildElectron() {
|
||||
console.log('\n💻 构建 Electron 应用...');
|
||||
const electronDir = join(rootDir, 'packages/electron');
|
||||
|
||||
// 先确保 Web 已构建
|
||||
if (!existsSync(join(rootDir, 'packages/web/build'))) {
|
||||
await tasks.buildWeb();
|
||||
}
|
||||
|
||||
// 使用 Electron 包的完整构建流程
|
||||
exec('npm run build:electron', { cwd: electronDir });
|
||||
},
|
||||
|
||||
// 构建所有
|
||||
async buildAll() {
|
||||
console.log('🚀 开始完整构建...\n');
|
||||
|
||||
// 清理
|
||||
tasks.clean();
|
||||
|
||||
// 构建各包 (不再需要shared,使用路径别名替换)
|
||||
await tasks.buildCore(); // Core 构建现在包含web构建
|
||||
await tasks.buildElectron();
|
||||
|
||||
console.log('\n✨ 所有构建已完成!');
|
||||
},
|
||||
|
||||
// 发布准备:构建并配置发布用的包
|
||||
async buildForPublish() {
|
||||
console.log('📦 准备发布构建...\n');
|
||||
|
||||
// 清理
|
||||
tasks.clean();
|
||||
|
||||
// 构建 core 包 (发布版)
|
||||
args.push('--publish'); // 确保传递 --publish 参数
|
||||
await tasks.buildCore();
|
||||
|
||||
console.log('\n✨ 发布构建已完成!');
|
||||
console.log('\n📝 下一步:');
|
||||
console.log('1. 运行: npm run publish:core');
|
||||
},
|
||||
|
||||
|
||||
// 发布 core 包
|
||||
async publishCore() {
|
||||
console.log('📤 发布 Core 包...');
|
||||
const coreDir = join(rootDir, 'packages/core');
|
||||
|
||||
// 检查是否已经构建
|
||||
if (!existsSync(join(coreDir, 'dist'))) {
|
||||
console.log('⚠️ 检测到 Core 包未构建,先进行构建...');
|
||||
if (!args.includes('--publish')) {
|
||||
args.push('--publish'); // 确保传递 --publish 参数
|
||||
}
|
||||
await tasks.buildCore();
|
||||
}
|
||||
|
||||
const publishTag = process.env.NPM_PUBLISH_TAG || 'latest';
|
||||
const tagFlag = publishTag === 'latest' ? '' : ` --tag ${publishTag}`;
|
||||
console.log(`📦 发布标签: ${publishTag}`);
|
||||
exec(`npm publish --access public${tagFlag}`, { cwd: coreDir });
|
||||
console.log('✅ Core 包发布完成!');
|
||||
},
|
||||
|
||||
// 完整发布流程
|
||||
async publishAll() {
|
||||
console.log('🚀 开始完整发布流程...\n');
|
||||
|
||||
// 1. 构建发布版本
|
||||
await tasks.buildForPublish();
|
||||
|
||||
// 2. 发布 core 包
|
||||
await tasks.publishCore();
|
||||
|
||||
console.log('\n🎉 Core 包发布完成!');
|
||||
},
|
||||
|
||||
// 开发模式
|
||||
dev() {
|
||||
const target = args[1] || 'web';
|
||||
console.log(`🔧 启动开发模式: ${target}`);
|
||||
|
||||
switch (target) {
|
||||
case 'shared':
|
||||
exec('npm run dev', { cwd: join(rootDir, 'packages/shared') });
|
||||
break;
|
||||
case 'web':
|
||||
exec('npm run start', { cwd: join(rootDir, 'packages/web') });
|
||||
break;
|
||||
case 'core':
|
||||
exec('npm run start', { cwd: join(rootDir, 'packages/core') });
|
||||
break;
|
||||
case 'cli':
|
||||
exec('npm run start', { cwd: join(rootDir, 'packages/cli') });
|
||||
break;
|
||||
case 'electron':
|
||||
exec('npm run start', { cwd: join(rootDir, 'packages/electron') });
|
||||
break;
|
||||
case 'all':
|
||||
// 使用 concurrently 同时运行多个开发服务器
|
||||
exec('npx concurrently "npm run start --prefix packages/web" "npm run start --prefix packages/core"');
|
||||
break;
|
||||
default:
|
||||
console.error(`❌ 未知的开发目标: ${target}`);
|
||||
console.log('可用选项: shared, web, core, cli, electron, all');
|
||||
process.exit(1);
|
||||
}
|
||||
},
|
||||
|
||||
// 帮助信息
|
||||
help() {
|
||||
console.log(`
|
||||
HyperChat 构建脚本
|
||||
|
||||
使用方法:
|
||||
node scripts/build.mjs <command> [options]
|
||||
|
||||
构建命令:
|
||||
clean 清理所有构建产物
|
||||
buildWeb 构建 Web 前端
|
||||
buildCore 构建 Core 包 (包含Web前端)
|
||||
buildElectron 构建 Electron 应用
|
||||
buildAll 构建所有包
|
||||
buildForPublish 构建Core包 (发布版)
|
||||
|
||||
发布命令:
|
||||
publishCore 发布 Core 包到 npm
|
||||
publishAll 完整发布流程 (推荐)
|
||||
|
||||
开发命令:
|
||||
dev [target] 启动开发模式 (shared/web/core/cli/electron/all)
|
||||
help 显示此帮助信息
|
||||
|
||||
选项:
|
||||
--publish 为发布准备 Core 包(处理 package.json)
|
||||
|
||||
示例:
|
||||
node scripts/build.mjs buildAll
|
||||
node scripts/build.mjs dev web
|
||||
node scripts/build.mjs buildForPublish
|
||||
node scripts/build.mjs publishCore
|
||||
|
||||
发布流程:
|
||||
1. node scripts/build.mjs publishAll # 推荐:一键发布
|
||||
或者分步执行:
|
||||
2a. node scripts/build.mjs buildForPublish
|
||||
2b. node scripts/build.mjs publishCore
|
||||
`);
|
||||
}
|
||||
};
|
||||
|
||||
// 执行命令
|
||||
const taskName = command || 'help';
|
||||
const task = tasks[taskName];
|
||||
|
||||
if (task) {
|
||||
try {
|
||||
const result = task();
|
||||
if (result && typeof result.catch === 'function') {
|
||||
result.catch(error => {
|
||||
console.error('❌ 构建失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 构建失败:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
console.error(`❌ 未知命令: ${taskName}`);
|
||||
tasks.help();
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 清理构建产物脚本
|
||||
*
|
||||
* 清理源码目录中错误生成的编译产物
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import { readdirSync, statSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const projectRoot = process.cwd();
|
||||
|
||||
// 需要清理的文件类型
|
||||
const cleanPatterns = [
|
||||
'*.js.map',
|
||||
'*.mjs.map',
|
||||
'*.d.ts.map'
|
||||
];
|
||||
|
||||
// 需要清理的目录(相对于项目根目录)
|
||||
const cleanDirs = [
|
||||
'packages/core/src',
|
||||
'packages/web/src',
|
||||
'packages/electron/src',
|
||||
'packages/cli/src'
|
||||
];
|
||||
|
||||
console.log('🧹 开始清理构建产物...');
|
||||
|
||||
let totalCleaned = 0;
|
||||
|
||||
for (const dir of cleanDirs) {
|
||||
const fullPath = join(projectRoot, dir);
|
||||
|
||||
try {
|
||||
// 检查目录是否存在
|
||||
if (statSync(fullPath).isDirectory()) {
|
||||
console.log(`📁 清理目录: ${dir}`);
|
||||
|
||||
for (const pattern of cleanPatterns) {
|
||||
try {
|
||||
const command = `find "${fullPath}" -name "${pattern}" -type f`;
|
||||
const files = execSync(command, { encoding: 'utf8' }).trim();
|
||||
|
||||
if (files) {
|
||||
const fileList = files.split('\n').filter(f => f.trim());
|
||||
console.log(` 🗑️ 删除 ${fileList.length} 个 ${pattern} 文件`);
|
||||
|
||||
// 删除文件
|
||||
execSync(`find "${fullPath}" -name "${pattern}" -type f -delete`);
|
||||
totalCleaned += fileList.length;
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略查找错误(通常是因为没有匹配的文件)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`⚠️ 目录不存在: ${dir}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 清理完成!共清理 ${totalCleaned} 个文件`);
|
||||
|
||||
// 如果有参数 --verbose,显示当前构建输出目录的状态
|
||||
if (process.argv.includes('--verbose')) {
|
||||
console.log('\\n📊 当前构建输出目录状态:');
|
||||
|
||||
const outputDirs = [
|
||||
'packages/core/js',
|
||||
'packages/core/dist',
|
||||
'packages/web/dist',
|
||||
'packages/electron/dist',
|
||||
'packages/cli/dist'
|
||||
];
|
||||
|
||||
for (const dir of outputDirs) {
|
||||
const fullPath = join(projectRoot, dir);
|
||||
try {
|
||||
const stats = statSync(fullPath);
|
||||
if (stats.isDirectory()) {
|
||||
const files = readdirSync(fullPath);
|
||||
console.log(` 📁 ${dir}: ${files.length} 个文件`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(` 📁 ${dir}: 不存在`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { fs, path } from "zx";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const rootDir = path.resolve(__dirname, "../");
|
||||
const i18nPath = path.resolve(rootDir, "./packages/shared/src/i18n/i18n.json");
|
||||
|
||||
async function main() {
|
||||
console.log("🧹 开始清理 i18n.json 中包含变量的键...");
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(i18nPath)) {
|
||||
console.error(`❌ 错误: i18n.json 文件不存在: ${i18nPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
// 读取并解析 JSON 文件
|
||||
const jsonContent = fs.readFileSync(i18nPath, 'utf8');
|
||||
const i18nData = JSON.parse(jsonContent);
|
||||
|
||||
// 统计信息
|
||||
const totalKeys = Object.keys(i18nData).length;
|
||||
let removedCount = 0;
|
||||
const removedKeys = [];
|
||||
|
||||
console.log(`📊 总共找到 ${totalKeys} 个翻译键`);
|
||||
|
||||
// 查找包含变量的键 (${xxx} 模式)
|
||||
const variableRegex = /\$\{[^}]+\}/;
|
||||
const keysWithTranslations = [];
|
||||
const keysWithoutTranslations = [];
|
||||
|
||||
Object.keys(i18nData).forEach(key => {
|
||||
if (variableRegex.test(key)) {
|
||||
// 强制删除所有包含变量的键(因为代码已经修复,这些翻译不再使用)
|
||||
removedKeys.push(key);
|
||||
delete i18nData[key];
|
||||
removedCount++;
|
||||
}
|
||||
});
|
||||
|
||||
if (removedCount === 0) {
|
||||
console.log("✅ 没有找到包含变量的键,无需清理");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n🗑️ 找到 ${removedCount} 个包含变量的键(已删除):`);
|
||||
removedKeys.forEach((key, index) => {
|
||||
console.log(`${index + 1}. "${key}"`);
|
||||
});
|
||||
|
||||
// 备份原文件
|
||||
const backupPath = i18nPath + '.backup-' + Date.now();
|
||||
fs.copyFileSync(i18nPath, backupPath);
|
||||
console.log(`\n💾 已备份原文件到: ${backupPath}`);
|
||||
|
||||
// 写入清理后的文件
|
||||
const cleanedContent = JSON.stringify(i18nData, null, 2);
|
||||
fs.writeFileSync(i18nPath, cleanedContent);
|
||||
|
||||
const remainingKeys = Object.keys(i18nData).length;
|
||||
console.log(`\n✅ 清理完成!`);
|
||||
console.log(`📊 统计信息:`);
|
||||
console.log(` - 原有键数: ${totalKeys}`);
|
||||
console.log(` - 删除键数: ${removedCount}`);
|
||||
console.log(` - 剩余键数: ${remainingKeys}`);
|
||||
|
||||
// 重新构建 shared 包以更新 dist 目录
|
||||
console.log('\n🔧 重新构建 shared 包...');
|
||||
try {
|
||||
const { $ } = await import('zx');
|
||||
await $`npm run build --workspace=@dadigua/hyperchat-shared`;
|
||||
console.log('✅ shared 包构建完成,i18n.json 已同步到 dist 目录');
|
||||
} catch (error) {
|
||||
console.warn('⚠️ shared 包构建失败,可能需要手动运行: npm run build --workspace=@dadigua/hyperchat-shared');
|
||||
console.warn('错误:', error.message);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ 脚本执行失败:", error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 运行主函数
|
||||
await main();
|
||||
@@ -0,0 +1,335 @@
|
||||
#!/usr/bin/env node
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, join } from 'path';
|
||||
import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from 'fs';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = join(__dirname, '..');
|
||||
|
||||
// 需要扫描的目录
|
||||
const SCAN_DIRS = [
|
||||
'packages/web/src',
|
||||
'packages/core/src',
|
||||
'packages/shared/src'
|
||||
];
|
||||
|
||||
// 需要扫描的文件扩展名
|
||||
const FILE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.js', '.jsx'];
|
||||
|
||||
// 提取 t`...` 的正则表达式
|
||||
const T_REGEX = /\bt`([^`]*)`/g;
|
||||
|
||||
// 检测 t`...` 中包含 ${} 的正则表达式
|
||||
const TEMPLATE_LITERAL_IN_T_REGEX = /\bt`([^`]*\$\{[^}]*\}[^`]*)`/g;
|
||||
|
||||
// 存储所有找到的文本
|
||||
const foundTexts = new Set();
|
||||
|
||||
// 存储发现的问题
|
||||
const i18nIssues = [];
|
||||
|
||||
/**
|
||||
* 递归扫描目录获取所有文件
|
||||
*/
|
||||
function getAllFiles(dir, fileList = []) {
|
||||
const fullPath = join(rootDir, dir);
|
||||
|
||||
if (!existsSync(fullPath)) {
|
||||
console.warn(`⚠️ 目录不存在: ${fullPath}`);
|
||||
return fileList;
|
||||
}
|
||||
|
||||
const files = readdirSync(fullPath);
|
||||
|
||||
files.forEach(file => {
|
||||
const filePath = join(fullPath, file);
|
||||
const stat = statSync(filePath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// 跳过 node_modules, dist, build 等目录
|
||||
if (!['node_modules', 'dist', 'build', '.git'].includes(file)) {
|
||||
getAllFiles(join(dir, file), fileList);
|
||||
}
|
||||
} else {
|
||||
// 只处理指定扩展名的文件
|
||||
if (FILE_EXTENSIONS.some(ext => file.endsWith(ext))) {
|
||||
fileList.push(join(dir, file));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return fileList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测 t`...` 中的国际化问题
|
||||
*/
|
||||
function detectI18nIssues(content, filePath) {
|
||||
const issues = [];
|
||||
const lines = content.split('\n');
|
||||
|
||||
lines.forEach((line, lineNumber) => {
|
||||
// 跳过注释行
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('//') || trimmedLine.startsWith('/*') || trimmedLine.startsWith('*')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检测 t`...` 中包含 ${} 的情况
|
||||
let match;
|
||||
const regex = new RegExp(TEMPLATE_LITERAL_IN_T_REGEX.source, TEMPLATE_LITERAL_IN_T_REGEX.flags);
|
||||
|
||||
while ((match = regex.exec(line)) !== null) {
|
||||
const text = match[1];
|
||||
const fullMatch = match[0];
|
||||
|
||||
issues.push({
|
||||
type: 'template-literal-in-t',
|
||||
message: 'Found template literal inside t`...`. Use template literal outside instead.',
|
||||
suggestion: 'Move variables outside: `${t`Text`}: ${variable}`',
|
||||
text: text,
|
||||
fullMatch: fullMatch,
|
||||
file: filePath,
|
||||
line: lineNumber + 1,
|
||||
lineContent: line.trim()
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return issues;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件内容中提取 t`...` 文本
|
||||
*/
|
||||
function extractTextsFromContent(content, filePath) {
|
||||
const matches = [];
|
||||
const lines = content.split('\n');
|
||||
|
||||
lines.forEach((line, lineNumber) => {
|
||||
// 跳过注释行
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('//') || trimmedLine.startsWith('/*') || trimmedLine.startsWith('*')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 查找该行中的 t`...` 模式
|
||||
let match;
|
||||
const regex = new RegExp(T_REGEX.source, T_REGEX.flags);
|
||||
|
||||
while ((match = regex.exec(line)) !== null) {
|
||||
const text = match[1];
|
||||
|
||||
// 过滤掉明显错误的提取
|
||||
if (text.length > 0 && text.length < 100 && // 限制长度
|
||||
!text.includes('\n') && !text.includes('\r') && // 不包含换行符
|
||||
!text.includes('\\n') && !text.includes('\\r') && // 不包含转义换行符
|
||||
!/^\s*$/.test(text) && // 不是纯空白
|
||||
!text.includes('function') && // 不包含代码关键字
|
||||
!text.includes('console') &&
|
||||
!text.includes('return') &&
|
||||
text.split(' ').length < 20) { // 单词数量限制
|
||||
matches.push({
|
||||
text,
|
||||
file: filePath,
|
||||
line: lineNumber + 1
|
||||
});
|
||||
foundTexts.add(text);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个文件
|
||||
*/
|
||||
function processFile(filePath) {
|
||||
try {
|
||||
const fullPath = join(rootDir, filePath);
|
||||
const content = readFileSync(fullPath, 'utf-8');
|
||||
|
||||
// 提取正常的 i18n 文本
|
||||
const matches = extractTextsFromContent(content, filePath);
|
||||
|
||||
// 检测 i18n 问题
|
||||
const issues = detectI18nIssues(content, filePath);
|
||||
|
||||
if (matches.length > 0) {
|
||||
console.log(`📄 ${filePath}: 找到 ${matches.length} 个文本`);
|
||||
matches.forEach(match => {
|
||||
console.log(` 第${match.line}行: "${match.text}"`);
|
||||
});
|
||||
}
|
||||
|
||||
// 添加发现的问题到全局列表
|
||||
i18nIssues.push(...issues);
|
||||
|
||||
return { matches, issues };
|
||||
} catch (error) {
|
||||
console.error(`❌ 处理文件失败 ${filePath}:`, error.message);
|
||||
return { matches: [], issues: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 i18n.json 文件
|
||||
*/
|
||||
function updateI18nFile() {
|
||||
const i18nPath = join(rootDir, 'packages/shared/src/i18n/i18n.json');
|
||||
let existingTranslations = {};
|
||||
|
||||
// 读取现有翻译
|
||||
if (existsSync(i18nPath)) {
|
||||
try {
|
||||
const content = readFileSync(i18nPath, 'utf-8');
|
||||
existingTranslations = JSON.parse(content);
|
||||
console.log(`📖 已读取现有翻译文件: ${Object.keys(existingTranslations).length} 条`);
|
||||
} catch (error) {
|
||||
console.warn(`⚠️ 读取现有翻译文件失败:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 生成新的翻译映射
|
||||
const newTranslations = { ...existingTranslations };
|
||||
let newCount = 0;
|
||||
let updatedCount = 0;
|
||||
|
||||
Array.from(foundTexts).sort().forEach(text => {
|
||||
if (!newTranslations[text]) {
|
||||
// 使用新格式:{ "text": {} } - 只提取key,不提供翻译
|
||||
newTranslations[text] = {};
|
||||
newCount++;
|
||||
} else {
|
||||
updatedCount++;
|
||||
}
|
||||
});
|
||||
|
||||
// 写入文件
|
||||
try {
|
||||
writeFileSync(i18nPath, JSON.stringify(newTranslations, null, 2), 'utf-8');
|
||||
console.log(`\n✅ i18n.json 已更新:`);
|
||||
console.log(` 📝 新增条目: ${newCount} 条`);
|
||||
console.log(` 🔄 保持现有: ${updatedCount} 条`);
|
||||
console.log(` 📊 总计: ${Object.keys(newTranslations).length} 条`);
|
||||
console.log(` 📁 文件位置: ${i18nPath}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ 写入翻译文件失败:`, error.message);
|
||||
}
|
||||
|
||||
return newTranslations;
|
||||
}
|
||||
|
||||
/**
|
||||
* 报告发现的 i18n 问题
|
||||
*/
|
||||
function reportI18nIssues() {
|
||||
if (i18nIssues.length === 0) {
|
||||
console.log(`\n✅ 未发现 i18n 问题`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n⚠️ 发现 ${i18nIssues.length} 个 i18n 问题:`);
|
||||
console.log(`=`.repeat(60));
|
||||
|
||||
// 按文件分组显示问题
|
||||
const issuesByFile = {};
|
||||
i18nIssues.forEach(issue => {
|
||||
if (!issuesByFile[issue.file]) {
|
||||
issuesByFile[issue.file] = [];
|
||||
}
|
||||
issuesByFile[issue.file].push(issue);
|
||||
});
|
||||
|
||||
Object.entries(issuesByFile).forEach(([file, issues]) => {
|
||||
console.log(`\n📁 ${file}:`);
|
||||
issues.forEach(issue => {
|
||||
console.log(` 🚫 第${issue.line}行: ${issue.fullMatch}`);
|
||||
console.log(` ✨ ${issue.suggestion}`);
|
||||
console.log(` 📝 ${issue.message}`);
|
||||
console.log(` 📄 ${issue.lineContent}`);
|
||||
console.log('');
|
||||
});
|
||||
});
|
||||
|
||||
console.log(`\n💡 修复建议:`);
|
||||
console.log(` - 模板字符串应该在 t\`...\` 外面使用`);
|
||||
console.log(` - 错误写法: t\`Hello \${name}\``);
|
||||
console.log(` - 正确写法: \`\${t\`Hello\`} \${name}\``);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成提取报告
|
||||
*/
|
||||
function generateReport(allMatches) {
|
||||
console.log(`\n📊 提取报告:`);
|
||||
console.log(`=`.repeat(50));
|
||||
|
||||
// 按文件统计
|
||||
const fileStats = {};
|
||||
allMatches.forEach(match => {
|
||||
if (!fileStats[match.file]) {
|
||||
fileStats[match.file] = 0;
|
||||
}
|
||||
fileStats[match.file]++;
|
||||
});
|
||||
|
||||
console.log(`\n📁 按文件统计:`);
|
||||
Object.entries(fileStats)
|
||||
.sort(([,a], [,b]) => b - a)
|
||||
.slice(0, 10)
|
||||
.forEach(([file, count]) => {
|
||||
console.log(` ${file}: ${count} 个`);
|
||||
});
|
||||
|
||||
console.log(`\n✨ 提取完成! 总共找到 ${foundTexts.size} 个唯一文本`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 主函数
|
||||
*/
|
||||
function main() {
|
||||
console.log(`🚀 开始提取 i18n 文本...`);
|
||||
console.log(`📂 扫描目录: ${SCAN_DIRS.join(', ')}`);
|
||||
console.log(`📄 文件类型: ${FILE_EXTENSIONS.join(', ')}`);
|
||||
console.log('');
|
||||
|
||||
// 获取所有需要处理的文件
|
||||
let allFiles = [];
|
||||
SCAN_DIRS.forEach(dir => {
|
||||
const files = getAllFiles(dir);
|
||||
allFiles = allFiles.concat(files);
|
||||
});
|
||||
|
||||
console.log(`📋 找到 ${allFiles.length} 个文件\n`);
|
||||
|
||||
// 处理所有文件
|
||||
const allMatches = [];
|
||||
allFiles.forEach(file => {
|
||||
const result = processFile(file);
|
||||
allMatches.push(...result.matches);
|
||||
});
|
||||
|
||||
console.log(`\n🔍 扫描完成! 找到 ${allMatches.length} 个 t\`...\` 用法`);
|
||||
console.log(`📝 唯一文本: ${foundTexts.size} 个`);
|
||||
|
||||
// 报告发现的 i18n 问题
|
||||
reportI18nIssues();
|
||||
|
||||
// 更新翻译文件
|
||||
updateI18nFile();
|
||||
|
||||
// 生成报告
|
||||
generateReport(allMatches);
|
||||
|
||||
// 提供下一步建议
|
||||
console.log(`\n📋 下一步建议:`);
|
||||
console.log(` 1. 检查生成的 packages/shared/src/i18n/i18n.json 文件`);
|
||||
console.log(` 2. 手动添加需要的翻译到每个条目中`);
|
||||
console.log(` 3. 格式: { "English Text": { "zh": "中文翻译" } }`);
|
||||
console.log(` 4. 测试前端界面的国际化效果`);
|
||||
}
|
||||
|
||||
// 运行脚本
|
||||
main();
|
||||
Generated
+6528
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@dadigua/hyper-chat",
|
||||
"scripts": {
|
||||
"dev": "tsx task.mts --dev",
|
||||
"prod": "tsx task.mts --prod",
|
||||
"build": "tsx task.mts --build",
|
||||
"pre_commit": "tsx task.mts --pre_commit",
|
||||
"prod_node": "tsx task.mts --prod_node",
|
||||
"updateVersion": "tsx task.mts --updateVersion",
|
||||
"docs:dev": "vuepress dev docs",
|
||||
"docs:build": "vuepress build docs"
|
||||
},
|
||||
"pre-commit": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"description": "",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.10.2",
|
||||
"cross-spawn": "^7.0.6",
|
||||
"dotenv": "16.4.7",
|
||||
"lodash": "^4.17.21",
|
||||
"openai": "^4.94.0",
|
||||
"tsx": "^4.9.3",
|
||||
"uuid": "^11.1.0",
|
||||
"zx": "8.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vuepress/bundler-vite": "^2.0.0-rc.22",
|
||||
"@vuepress/theme-default": "^2.0.0-rc.98",
|
||||
"pre-commit": "^1.2.2",
|
||||
"sass-embedded": "^1.87.0",
|
||||
"vue": "^3.5.13",
|
||||
"vuepress": "^2.0.0-rc.22"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
console.log('🚀 开始发布新版本...');
|
||||
|
||||
try {
|
||||
|
||||
// 获取当前版本
|
||||
const packageJson = JSON.parse(readFileSync('./package.json', 'utf8'));
|
||||
const currentVersion = packageJson.version;
|
||||
console.log(`📦 当前版本: ${currentVersion}`);
|
||||
|
||||
// 升级版本
|
||||
console.log('🔢 升级 alpha 版本...');
|
||||
execSync('npm version prerelease --preid=alpha --no-git-tag-version', { stdio: 'inherit' });
|
||||
|
||||
// 同步版本到所有包
|
||||
console.log('🔄 同步版本到所有包...');
|
||||
execSync('npm run version:sync', { stdio: 'inherit' });
|
||||
|
||||
// 同步 electron 依赖
|
||||
console.log('🔄 同步 electron 依赖...');
|
||||
execSync('npm run --prefix packages/electron sync-core-dependencies', { stdio: 'inherit' });
|
||||
|
||||
// 获取新版本
|
||||
const newPackageJson = JSON.parse(readFileSync('./package.json', 'utf8'));
|
||||
const newVersion = newPackageJson.version;
|
||||
console.log(`✅ 版本已升级: ${currentVersion} → ${newVersion}`);
|
||||
|
||||
|
||||
// 询问是否推送
|
||||
console.log('\n🎯 版本发布准备完成!');
|
||||
console.log(`📦 新版本: ${newVersion}`);
|
||||
console.log('\n选择下一步操作:');
|
||||
console.log('1️⃣ git push origin dev2 # 推送并触发 npm 发布');
|
||||
console.log('2️⃣ git reset HEAD~1 # 撤销版本提交');
|
||||
console.log('');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 发布失败:', error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFileSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname } from 'path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const rootDir = join(__dirname, '..');
|
||||
|
||||
// 读取根目录的版本号
|
||||
function getRootVersion() {
|
||||
const rootPackagePath = join(rootDir, 'package.json');
|
||||
const rootPackage = JSON.parse(readFileSync(rootPackagePath, 'utf8'));
|
||||
return rootPackage.version;
|
||||
}
|
||||
|
||||
// 更新子包的版本号
|
||||
function updatePackageVersion(packagePath, version) {
|
||||
try {
|
||||
const packageJsonPath = join(packagePath, 'package.json');
|
||||
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
|
||||
|
||||
const oldVersion = packageJson.version;
|
||||
packageJson.version = version;
|
||||
|
||||
writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n');
|
||||
|
||||
console.log(`✅ ${packagePath.split('/').pop()}: ${oldVersion} → ${version}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`❌ 更新 ${packagePath} 失败:`, error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 主函数
|
||||
function syncVersions() {
|
||||
const rootVersion = getRootVersion();
|
||||
console.log(`🔄 同步版本号: ${rootVersion}`);
|
||||
console.log('');
|
||||
|
||||
// 定义所有需要同步的包
|
||||
const packages = [
|
||||
'packages/shared',
|
||||
'packages/core',
|
||||
'packages/web',
|
||||
'packages/electron'
|
||||
];
|
||||
|
||||
let success = true;
|
||||
|
||||
for (const pkg of packages) {
|
||||
const packagePath = join(rootDir, pkg);
|
||||
if (!updatePackageVersion(packagePath, rootVersion)) {
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('');
|
||||
if (success) {
|
||||
console.log('🎉 所有包版本号同步完成!');
|
||||
} else {
|
||||
console.log('⚠️ 部分包同步失败,请检查错误信息');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 执行同步
|
||||
syncVersions();
|
||||
@@ -0,0 +1,266 @@
|
||||
import { $, argv, fs, os, path, usePowerShell, within } from "zx";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
import spawn from "cross-spawn";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const rootDir = path.resolve(__dirname, "../");
|
||||
if (argv.updateVersion) {
|
||||
let pack = await fs.readJSON(path.resolve(rootDir, "./package.json"));
|
||||
let webpackage = await fs.readJSON(
|
||||
path.resolve(rootDir, "./web/package.json")
|
||||
);
|
||||
if (webpackage.version != pack.version) {
|
||||
webpackage.version = pack.version;
|
||||
await fs.writeFile(
|
||||
path.resolve(rootDir, "./web/package.json"),
|
||||
JSON.stringify(webpackage, null, 2)
|
||||
);
|
||||
}
|
||||
let electronpackage = await fs.readJSON(
|
||||
path.resolve(rootDir, "./electron/package.json")
|
||||
);
|
||||
if (electronpackage.version != pack.version) {
|
||||
electronpackage.version = pack.version;
|
||||
await fs.writeFile(
|
||||
path.resolve(rootDir, "./electron/package.json"),
|
||||
JSON.stringify(electronpackage, null, 2)
|
||||
);
|
||||
}
|
||||
}
|
||||
$.verbose = true;
|
||||
|
||||
if (os.platform() === "win32") {
|
||||
usePowerShell();
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
"./electron/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js",
|
||||
fs
|
||||
.readFileSync(
|
||||
"./electron/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"
|
||||
)
|
||||
.toString()
|
||||
.replace(
|
||||
`import { spawn } from "node:child_process";`,
|
||||
`import spawn from "cross-spawn";`
|
||||
)
|
||||
);
|
||||
|
||||
fs.writeFileSync(
|
||||
"./electron/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js",
|
||||
fs
|
||||
.readFileSync(
|
||||
"./electron/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js"
|
||||
)
|
||||
.toString()
|
||||
.replace(
|
||||
`const node_child_process_1 = require("node:child_process");`,
|
||||
`const spawn = require("cross-spawn");`
|
||||
)
|
||||
.replace(
|
||||
`node_child_process_1.spawn`,
|
||||
`spawn`
|
||||
)
|
||||
);
|
||||
|
||||
// if (
|
||||
// !fs
|
||||
// .readFileSync(
|
||||
// "./electron/node_modules/@modelcontextprotocol/sdk/dist/client/sse.js"
|
||||
// )
|
||||
// .toString()
|
||||
// .includes(`'eventsource'`)
|
||||
// ) {
|
||||
// fs.writeFileSync(
|
||||
// "./electron/node_modules/@modelcontextprotocol/sdk/dist/client/sse.js",
|
||||
// fs
|
||||
// .readFileSync(
|
||||
// "./electron/node_modules/@modelcontextprotocol/sdk/dist/client/sse.js"
|
||||
// )
|
||||
// .toString()
|
||||
// .replace(
|
||||
// `import { JSONRPCMessageSchema } from "../types.js";`,
|
||||
// `import { JSONRPCMessageSchema } from "../types.js";
|
||||
// import {EventSource} from 'eventsource'`
|
||||
// )
|
||||
// );
|
||||
// }
|
||||
|
||||
const spawnWithOutput = (command: string, args: string[], options) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn(command, args, options);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
proc.stdout.pipe(process.stdout);
|
||||
proc.stderr.pipe(process.stderr);
|
||||
|
||||
proc.stdout.on("data", (data) => {
|
||||
stdout += data.toString();
|
||||
// console.log(data.toString()); // 实时输出
|
||||
});
|
||||
|
||||
proc.stderr.on("data", (data) => {
|
||||
stderr += data.toString();
|
||||
// console.error(data.toString()); // 实时输出错误
|
||||
});
|
||||
|
||||
proc.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Command failed with code ${code}\n${stderr}`));
|
||||
} else {
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
code,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
proc.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (argv.dev) {
|
||||
spawnWithOutput(
|
||||
"npx",
|
||||
["cross-env", "NODE_ENV=development", "myEnv=dev", "webpack", "serve"],
|
||||
{
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
}
|
||||
);
|
||||
spawnWithOutput(
|
||||
"npx",
|
||||
[
|
||||
"cross-env",
|
||||
"NODE_ENV=development",
|
||||
"myEnv=dev",
|
||||
"webpack",
|
||||
"-w",
|
||||
"-c",
|
||||
"webpack.eval.js",
|
||||
],
|
||||
{
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
}
|
||||
);
|
||||
|
||||
spawnWithOutput("npm", ["run", "dev"], {
|
||||
cwd: path.resolve(rootDir, "./electron/"),
|
||||
});
|
||||
|
||||
// $({
|
||||
// cwd: path.resolve(__dirname, "./web/"),
|
||||
// spawn: spawn as any,
|
||||
// })`npx cross-env NODE_ENV=development webpack serve -c webpack.config.js`;
|
||||
|
||||
// $({
|
||||
// cwd: path.resolve(__dirname, "./electron/"),
|
||||
// spawn: spawn as any,
|
||||
// })`npm run dev`;
|
||||
}
|
||||
|
||||
if (argv.prod) {
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=production myEnv=prod webpack -c webpack.config.js`;
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=development myEnv=dev webpack -c webpack.eval.js`;
|
||||
|
||||
await fs.copy(
|
||||
`./web/public/logo.png`,
|
||||
`./electron/web-build/assets/favicon.png`,
|
||||
{
|
||||
overwrite: true,
|
||||
}
|
||||
);
|
||||
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./electron/"),
|
||||
})`npm run prod`;
|
||||
|
||||
// let p = path.resolve(__dirname, `./dist`);
|
||||
// fs.ensureDirSync(p);
|
||||
// let pack = await fs.readJSON(
|
||||
// path.resolve(__dirname, "./electron/package.json")
|
||||
// );
|
||||
|
||||
// let arr = [
|
||||
// `HyperChat-${pack.version}-win-x64.exe`,
|
||||
// `HyperChat-${pack.version}-mac-x64.exe`,
|
||||
// `HyperChat-${pack.version}-mac-arm64.exe`,
|
||||
// ];
|
||||
// for (let name of arr) {
|
||||
// if (fs.existsSync(`./electron/dist/HyperChat-${pack.version}-x64.exe`)) {
|
||||
// await fs.copy(`./electron/dist/` + name, p + `/` + name, {
|
||||
// overwrite: true,
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
if (argv.prod_node) {
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=production myEnv=prod webpack -c webpack.config.js`;
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=development myEnv=dev webpack -c webpack.eval.js`;
|
||||
|
||||
await fs.copy(
|
||||
`./web/public/logo.png`,
|
||||
`./electron/web-build/assets/favicon.png`,
|
||||
{
|
||||
overwrite: true,
|
||||
}
|
||||
);
|
||||
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./electron/"),
|
||||
})`npm run build:node`;
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (argv.build) {
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=production myEnv=prod webpack -c webpack.config.js`;
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=development myEnv=dev webpack -c webpack.eval.js`;
|
||||
|
||||
await fs.copy(
|
||||
`./web/public/logo.png`,
|
||||
`./electron/web-build/assets/favicon.png`,
|
||||
{
|
||||
overwrite: true,
|
||||
}
|
||||
);
|
||||
|
||||
await $({
|
||||
cwd: path.resolve(rootDir, "./electron/"),
|
||||
})`npm run build`;
|
||||
}
|
||||
|
||||
if (argv.test) {
|
||||
await within(() => {
|
||||
return Promise.all([
|
||||
$({
|
||||
cwd: path.resolve(rootDir, "./web/"),
|
||||
})`npx cross-env NODE_ENV=development myEnv=test webpack -c webpack.config.js`,
|
||||
$({
|
||||
cwd: path.resolve(rootDir, "./electron/"),
|
||||
})`npm run testprod`,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
if (argv.pre_commit) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 测试 Git 钩子是否正确配置
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const projectRoot = join(__dirname, '..');
|
||||
|
||||
console.log('🧪 测试 Git 钩子配置...\n');
|
||||
|
||||
// 检查 Husky 文件是否存在
|
||||
const huskyFiles = [
|
||||
'.husky/_/husky.sh',
|
||||
'.husky/pre-commit',
|
||||
'.husky/pre-push'
|
||||
];
|
||||
|
||||
let allFilesExist = true;
|
||||
|
||||
for (const file of huskyFiles) {
|
||||
const filePath = join(projectRoot, file);
|
||||
if (existsSync(filePath)) {
|
||||
console.log(`✅ ${file} 存在`);
|
||||
} else {
|
||||
console.log(`❌ ${file} 不存在`);
|
||||
allFilesExist = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!allFilesExist) {
|
||||
console.log('\n❌ 部分 Husky 文件缺失!');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 检查 package.json 中的 scripts
|
||||
try {
|
||||
const packageJson = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
|
||||
|
||||
console.log('\n📦 检查 package.json scripts:');
|
||||
|
||||
const requiredScripts = ['prepare', 'pre-commit', 'pre-push', 'typecheck'];
|
||||
for (const script of requiredScripts) {
|
||||
if (packageJson.scripts[script]) {
|
||||
console.log(`✅ script "${script}": ${packageJson.scripts[script]}`);
|
||||
} else {
|
||||
console.log(`❌ script "${script}" 缺失`);
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 devDependencies 中是否有 husky
|
||||
if (packageJson.devDependencies.husky) {
|
||||
console.log(`✅ Husky 依赖版本: ${packageJson.devDependencies.husky}`);
|
||||
} else {
|
||||
console.log('❌ Husky 依赖缺失');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.log(`❌ 读取 package.json 失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 测试类型检查命令
|
||||
console.log('\n🔍 测试类型检查命令:');
|
||||
try {
|
||||
execSync('npm run typecheck', { stdio: 'pipe' });
|
||||
console.log('✅ typecheck 命令可用');
|
||||
} catch (error) {
|
||||
console.log('⚠️ typecheck 命令执行失败(这可能是正常的,取决于代码状态)');
|
||||
}
|
||||
|
||||
console.log('\n🎉 Git 钩子配置检查完成!');
|
||||
console.log('\n📝 使用说明:');
|
||||
console.log('1. 当你运行 git commit 时,会自动执行类型检查和 lint');
|
||||
console.log('2. 当你运行 git push 时,会自动执行构建检查和依赖同步');
|
||||
console.log('3. 如果检查失败,提交或推送会被阻止');
|
||||
console.log('4. 团队成员在 npm install 后会自动启用钩子');
|
||||
@@ -0,0 +1,737 @@
|
||||
import {
|
||||
fs,
|
||||
argv,
|
||||
path,
|
||||
$,
|
||||
usePowerShell,
|
||||
os,
|
||||
} from "zx";
|
||||
import { fileURLToPath } from "url";
|
||||
import "dotenv/config";
|
||||
import { z } from "zod";
|
||||
import { generateObject, streamObject } from 'ai';
|
||||
import { createOpenAI } from '@ai-sdk/openai';
|
||||
import { createAnthropic } from '@ai-sdk/anthropic';
|
||||
import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
||||
|
||||
if (os.platform() === "win32") {
|
||||
usePowerShell();
|
||||
}
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const rootDir = path.resolve(__dirname, "../");
|
||||
const i18nPath = path.resolve(rootDir, "./packages/shared/src/i18n/i18n.json");
|
||||
|
||||
// 🎯 HyperChat 多语言专业术语词典
|
||||
const TERMINOLOGY_DICT = {
|
||||
zh: {
|
||||
"Agent": "代理",
|
||||
"Agents": "代理",
|
||||
"MCP": "MCP",
|
||||
"MCP Server": "MCP 服务器",
|
||||
"MCP Client": "MCP 客户端",
|
||||
"Workspace": "工作区",
|
||||
"Workspaces": "工作区",
|
||||
"Chat": "聊天",
|
||||
"Model": "模型",
|
||||
"Provider": "提供商",
|
||||
"API Key": "API 密钥",
|
||||
"Task": "任务",
|
||||
"Tasks": "任务",
|
||||
"Schedule": "调度",
|
||||
"Scheduler": "调度器",
|
||||
"CLI": "命令行工具",
|
||||
"Command": "命令",
|
||||
"Template": "模板",
|
||||
"Gateway": "网关",
|
||||
"Token": "令牌",
|
||||
"Prompt": "提示词",
|
||||
"Temperature": "温度",
|
||||
"Tool": "工具",
|
||||
"Tools": "工具",
|
||||
"Resource": "资源",
|
||||
"System Prompt": "系统提示词",
|
||||
"Chat Log": "聊天记录",
|
||||
"History": "历史记录",
|
||||
"Session": "会话",
|
||||
"Configuration": "配置",
|
||||
"Settings": "设置"
|
||||
},
|
||||
ja: {
|
||||
"Agent": "エージェント",
|
||||
"Agents": "エージェント",
|
||||
"MCP": "MCP",
|
||||
"MCP Server": "MCPサーバー",
|
||||
"MCP Client": "MCPクライアント",
|
||||
"Workspace": "ワークスペース",
|
||||
"Workspaces": "ワークスペース",
|
||||
"Chat": "チャット",
|
||||
"Model": "モデル",
|
||||
"Provider": "プロバイダー",
|
||||
"API Key": "APIキー",
|
||||
"Task": "タスク",
|
||||
"Tasks": "タスク",
|
||||
"Schedule": "スケジュール",
|
||||
"Scheduler": "スケジューラー",
|
||||
"CLI": "コマンドラインツール",
|
||||
"Command": "コマンド",
|
||||
"Template": "テンプレート",
|
||||
"Gateway": "ゲートウェイ",
|
||||
"Token": "トークン",
|
||||
"Prompt": "プロンプト",
|
||||
"Temperature": "温度",
|
||||
"Tool": "ツール",
|
||||
"Tools": "ツール",
|
||||
"Resource": "リソース",
|
||||
"System Prompt": "システムプロンプト",
|
||||
"Chat Log": "チャット履歴",
|
||||
"History": "履歴",
|
||||
"Session": "セッション",
|
||||
"Configuration": "設定",
|
||||
"Settings": "設定"
|
||||
},
|
||||
ko: {
|
||||
"Agent": "에이전트",
|
||||
"Agents": "에이전트",
|
||||
"MCP": "MCP",
|
||||
"MCP Server": "MCP 서버",
|
||||
"MCP Client": "MCP 클라이언트",
|
||||
"Workspace": "워크스페이스",
|
||||
"Workspaces": "워크스페이스",
|
||||
"Chat": "채팅",
|
||||
"Model": "모델",
|
||||
"Provider": "프로바이더",
|
||||
"API Key": "API 키",
|
||||
"Task": "작업",
|
||||
"Tasks": "작업",
|
||||
"Schedule": "스케줄",
|
||||
"Scheduler": "스케줄러",
|
||||
"CLI": "명령줄 도구",
|
||||
"Command": "명령",
|
||||
"Template": "템플릿",
|
||||
"Gateway": "게이트웨이",
|
||||
"Token": "토큰",
|
||||
"Prompt": "프롬프트",
|
||||
"Temperature": "온도",
|
||||
"Tool": "도구",
|
||||
"Tools": "도구",
|
||||
"Resource": "리소스",
|
||||
"System Prompt": "시스템 프롬프트",
|
||||
"Chat Log": "채팅 기록",
|
||||
"History": "히스토리",
|
||||
"Session": "세션",
|
||||
"Configuration": "구성",
|
||||
"Settings": "설정"
|
||||
},
|
||||
fr: {
|
||||
"Agent": "Agent",
|
||||
"Agents": "Agents",
|
||||
"MCP": "MCP",
|
||||
"MCP Server": "Serveur MCP",
|
||||
"MCP Client": "Client MCP",
|
||||
"Workspace": "Espace de travail",
|
||||
"Workspaces": "Espaces de travail",
|
||||
"Chat": "Chat",
|
||||
"Model": "Modèle",
|
||||
"Provider": "Fournisseur",
|
||||
"API Key": "Clé API",
|
||||
"Task": "Tâche",
|
||||
"Tasks": "Tâches",
|
||||
"Schedule": "Planification",
|
||||
"Scheduler": "Planificateur",
|
||||
"CLI": "Outil en ligne de commande",
|
||||
"Command": "Commande",
|
||||
"Template": "Modèle",
|
||||
"Gateway": "Passerelle",
|
||||
"Token": "Jeton",
|
||||
"Prompt": "Invite",
|
||||
"Temperature": "Température",
|
||||
"Tool": "Outil",
|
||||
"Tools": "Outils",
|
||||
"Resource": "Ressource",
|
||||
"System Prompt": "Invite système",
|
||||
"Chat Log": "Journal de chat",
|
||||
"History": "Historique",
|
||||
"Session": "Session",
|
||||
"Configuration": "Configuration",
|
||||
"Settings": "Paramètres"
|
||||
},
|
||||
de: {
|
||||
"Agent": "Agent",
|
||||
"Agents": "Agenten",
|
||||
"MCP": "MCP",
|
||||
"MCP Server": "MCP-Server",
|
||||
"MCP Client": "MCP-Client",
|
||||
"Workspace": "Arbeitsbereich",
|
||||
"Workspaces": "Arbeitsbereiche",
|
||||
"Chat": "Chat",
|
||||
"Model": "Modell",
|
||||
"Provider": "Anbieter",
|
||||
"API Key": "API-Schlüssel",
|
||||
"Task": "Aufgabe",
|
||||
"Tasks": "Aufgaben",
|
||||
"Schedule": "Zeitplan",
|
||||
"Scheduler": "Planer",
|
||||
"CLI": "Kommandozeilen-Tool",
|
||||
"Command": "Befehl",
|
||||
"Template": "Vorlage",
|
||||
"Gateway": "Gateway",
|
||||
"Token": "Token",
|
||||
"Prompt": "Eingabeaufforderung",
|
||||
"Temperature": "Temperatur",
|
||||
"Tool": "Werkzeug",
|
||||
"Tools": "Werkzeuge",
|
||||
"Resource": "Ressource",
|
||||
"System Prompt": "System-Eingabeaufforderung",
|
||||
"Chat Log": "Chat-Protokoll",
|
||||
"History": "Verlauf",
|
||||
"Session": "Sitzung",
|
||||
"Configuration": "Konfiguration",
|
||||
"Settings": "Einstellungen"
|
||||
}
|
||||
};
|
||||
|
||||
// 🎯 语言配置映射
|
||||
const LANGUAGE_CONFIG = {
|
||||
zh: { name: '中文(简体)', nativeName: '中文', region: '中国大陆' },
|
||||
ja: { name: '日语', nativeName: '日本語', region: '日本' },
|
||||
ko: { name: '韩语', nativeName: '한국어', region: '韩国' },
|
||||
fr: { name: '法语', nativeName: 'Français', region: '法国' },
|
||||
de: { name: '德语', nativeName: 'Deutsch', region: '德国' }
|
||||
};
|
||||
|
||||
// 🎯 软件背景信息和翻译上下文
|
||||
const HYPERCHAT_CONTEXT = `
|
||||
HyperChat 是一个多平台的 AI 聊天应用,具有以下特点:
|
||||
- 支持多种 AI 模型(OpenAI、Claude、Gemini、Qwen、Deepseek 等)
|
||||
- 完整的 MCP(模型上下文协议)支持
|
||||
- 工作区概念:每个项目可以有独立的配置和代理
|
||||
- AI 代理系统:可创建专门用途的 AI 助手
|
||||
- 任务调度系统:支持定时任务执行
|
||||
- 多平台支持:Web、桌面(Electron)、命令行(CLI)
|
||||
- 支持多语言界面(中文/英文)
|
||||
|
||||
UI 组件包括:表单、按钮、菜单、设置面板、聊天界面、文件管理等。
|
||||
用户群体:开发者、AI 研究人员、需要 AI 辅助工作的专业人士。
|
||||
`;
|
||||
|
||||
// 🎯 翻译结果 Schema - 批量翻译
|
||||
const BatchTranslationSchema = z.object({
|
||||
translations: z.array(z.object({
|
||||
index: z.number(),
|
||||
original: z.string(),
|
||||
translation: z.string(),
|
||||
confidence: z.number().min(0).max(1).optional().describe("翻译置信度,0-1之间")
|
||||
})).describe("按原始顺序排列的翻译结果数组")
|
||||
});
|
||||
|
||||
// 🎯 翻译结果 Schema - 单个翻译
|
||||
const SingleTranslationSchema = z.object({
|
||||
translation: z.string().describe("翻译后的中文文本"),
|
||||
confidence: z.number().min(0).max(1).optional().describe("翻译置信度,0-1之间"),
|
||||
reasoning: z.string().optional().describe("翻译推理过程")
|
||||
});
|
||||
|
||||
// 🎯 AI 提供商配置
|
||||
interface AIConfig {
|
||||
provider: 'openai' | 'anthropic' | 'google';
|
||||
model: string;
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
}
|
||||
|
||||
// 🎯 获取 AI 模型
|
||||
function getAIModel(config: AIConfig) {
|
||||
// 如果使用 OpenRouter,统一使用 OpenAI 兼容接口
|
||||
if (config.baseURL && config.baseURL.includes('openrouter.ai')) {
|
||||
const openai = createOpenAI({
|
||||
apiKey: config.apiKey,
|
||||
baseURL: config.baseURL
|
||||
});
|
||||
return openai(config.model);
|
||||
}
|
||||
|
||||
switch (config.provider) {
|
||||
case 'openai':
|
||||
const openai = createOpenAI({
|
||||
apiKey: config.apiKey,
|
||||
baseURL: config.baseURL
|
||||
});
|
||||
return openai(config.model);
|
||||
|
||||
case 'anthropic':
|
||||
const anthropic = createAnthropic({
|
||||
apiKey: config.apiKey,
|
||||
baseURL: config.baseURL
|
||||
});
|
||||
return anthropic(config.model);
|
||||
|
||||
case 'google':
|
||||
const google = createGoogleGenerativeAI({
|
||||
apiKey: config.apiKey,
|
||||
baseURL: config.baseURL
|
||||
});
|
||||
return google(config.model);
|
||||
|
||||
default:
|
||||
throw new Error(`不支持的 AI 提供商: ${config.provider}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 🎯 创建翻译提示词 - 批量
|
||||
function createBatchTranslationPrompt(items: string[], targetLang: string): string {
|
||||
const langConfig = LANGUAGE_CONFIG[targetLang];
|
||||
const terminologyDict = TERMINOLOGY_DICT[targetLang] || {};
|
||||
const terminologyList = Object.entries(terminologyDict)
|
||||
.map(([en, translated]) => `- ${en} → ${translated}`)
|
||||
.join('\n');
|
||||
|
||||
const itemsList = items.map((text, index) => `${index + 1}. "${text}"`).join('\n');
|
||||
|
||||
return `作为专业的软件本地化翻译专家,请将以下 HyperChat 软件界面文本从英文翻译成${langConfig.name}。
|
||||
|
||||
【软件背景】${HYPERCHAT_CONTEXT}
|
||||
|
||||
【专业术语词典】
|
||||
${terminologyList}
|
||||
|
||||
【翻译原则】
|
||||
1. 保持用户界面的简洁性和一致性
|
||||
2. 使用${langConfig.region}用户习惯的表达方式
|
||||
3. 技术术语保持准确性,优先使用词典中的对应翻译
|
||||
4. 保持原文的格式、标点符号和特殊字符
|
||||
5. 错误信息要清晰易懂,帮助用户快速定位问题
|
||||
6. 按钮和菜单项要简洁有力
|
||||
7. 如果原文是空字符串,返回空字符串
|
||||
8. 确保翻译质量高且专业,符合软件界面标准
|
||||
|
||||
【待翻译文本列表】
|
||||
${itemsList}
|
||||
|
||||
请按照相同的顺序和索引返回结构化的翻译结果。每个翻译都应该准确、自然且符合${langConfig.nativeName}表达习惯。`;
|
||||
}
|
||||
|
||||
// 🎯 创建翻译提示词 - 单个
|
||||
function createSingleTranslationPrompt(text: string, targetLang: string): string {
|
||||
const langConfig = LANGUAGE_CONFIG[targetLang];
|
||||
const terminologyDict = TERMINOLOGY_DICT[targetLang] || {};
|
||||
const terminologyList = Object.entries(terminologyDict)
|
||||
.map(([en, translated]) => `- ${en} → ${translated}`)
|
||||
.join('\n');
|
||||
|
||||
return `作为专业的软件本地化翻译专家,请将以下 HyperChat 软件界面文本从英文翻译成${langConfig.name}。
|
||||
|
||||
【软件背景】${HYPERCHAT_CONTEXT}
|
||||
|
||||
【专业术语词典】
|
||||
${terminologyList}
|
||||
|
||||
【翻译原则】
|
||||
1. 保持用户界面的简洁性和一致性
|
||||
2. 使用中国大陆用户习惯的表达方式
|
||||
3. 技术术语保持准确性,优先使用词典中的对应翻译
|
||||
4. 保持原文的格式、标点符号和特殊字符
|
||||
5. 错误信息要清晰易懂,帮助用户快速定位问题
|
||||
6. 按钮和菜单项要简洁有力
|
||||
7. 如果原文是空字符串,返回空字符串
|
||||
|
||||
【待翻译文本】"${text}"
|
||||
|
||||
请提供高质量的${langConfig.nativeName}翻译,确保准确性和专业性。`;
|
||||
}
|
||||
|
||||
// 🎯 批量翻译函数
|
||||
export async function translateBatch(items: string[], config: AIConfig, targetLang: string = 'zh'): Promise<string[]> {
|
||||
if (items.length === 0) return [];
|
||||
|
||||
try {
|
||||
const model = getAIModel(config);
|
||||
const prompt = createBatchTranslationPrompt(items, targetLang);
|
||||
|
||||
console.log(`🤖 使用 ${config.provider}/${config.model} 进行批量翻译...`);
|
||||
|
||||
const result = await generateObject({
|
||||
model,
|
||||
schema: BatchTranslationSchema,
|
||||
prompt,
|
||||
temperature: 0.1, // 低温度确保一致性
|
||||
} as any) as any;
|
||||
|
||||
// 按索引排序并提取翻译结果
|
||||
const sortedTranslations = result.object.translations
|
||||
.sort((a, b) => a.index - b.index)
|
||||
.map(t => t.translation);
|
||||
|
||||
if (sortedTranslations.length !== items.length) {
|
||||
console.warn(`⚠️ 翻译数量不匹配,期望 ${items.length},实际 ${sortedTranslations.length}`);
|
||||
return await translateFallback(items, config, targetLang);
|
||||
}
|
||||
|
||||
// 质量检查
|
||||
let lowConfidenceCount = 0;
|
||||
result.object.translations.forEach(t => {
|
||||
if (t.confidence && t.confidence < 0.8) {
|
||||
lowConfidenceCount++;
|
||||
console.warn(`⚠️ 低置信度翻译: "${t.original}" -> "${t.translation}" (${t.confidence})`);
|
||||
}
|
||||
});
|
||||
|
||||
if (lowConfidenceCount > 0) {
|
||||
console.warn(`⚠️ 发现 ${lowConfidenceCount} 个低置信度翻译`);
|
||||
}
|
||||
|
||||
return sortedTranslations;
|
||||
} catch (error) {
|
||||
console.warn('批量翻译失败,回退到单个翻译模式:', error);
|
||||
return await translateFallback(items, config, targetLang);
|
||||
}
|
||||
}
|
||||
|
||||
// 🎯 单个翻译函数
|
||||
export async function translateSingle(text: string, config: AIConfig, targetLang: string = 'zh'): Promise<string> {
|
||||
try {
|
||||
const model = getAIModel(config);
|
||||
const prompt = createSingleTranslationPrompt(text, targetLang);
|
||||
|
||||
const result = await generateObject({
|
||||
model,
|
||||
schema: SingleTranslationSchema,
|
||||
prompt,
|
||||
temperature: 0.1,
|
||||
} as any) as any;
|
||||
|
||||
// 质量检查
|
||||
if (result.object.confidence && result.object.confidence < 0.8) {
|
||||
console.warn(`⚠️ 低置信度翻译: "${text}" -> "${result.object.translation}" (${result.object.confidence})`);
|
||||
if (result.object.reasoning) {
|
||||
console.warn(` 推理: ${result.object.reasoning}`);
|
||||
}
|
||||
}
|
||||
|
||||
return result.object.translation;
|
||||
} catch (error) {
|
||||
console.error(`单个翻译失败: ${text}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 🎯 回退翻译方法
|
||||
async function translateFallback(items: string[], config: AIConfig, targetLang: string = 'zh'): Promise<string[]> {
|
||||
console.log('使用单个翻译回退模式...');
|
||||
const results: string[] = [];
|
||||
for (const item of items) {
|
||||
try {
|
||||
const translation = await translateSingle(item, config, targetLang);
|
||||
results.push(translation);
|
||||
await new Promise(resolve => setTimeout(resolve, 200)); // 增加延迟避免限速
|
||||
} catch (error) {
|
||||
console.error(`翻译失败: ${item}`, error);
|
||||
results.push(item); // 翻译失败时保持原文
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// 🎯 翻译质量验证
|
||||
function validateTranslation(original: string, translation: string, targetLang: string = 'zh'): { isValid: boolean; issues: string[] } {
|
||||
const issues: string[] = [];
|
||||
const terminologyDict = TERMINOLOGY_DICT[targetLang] || {};
|
||||
|
||||
// 检查是否为空
|
||||
if (!translation.trim()) {
|
||||
if (original.trim()) {
|
||||
issues.push("翻译结果为空但原文不为空");
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否包含英文(可能翻译不完整)
|
||||
if (/[a-zA-Z]{3,}/.test(translation) && translation !== original) {
|
||||
// 排除专业术语
|
||||
const hasValidTerminology = Object.values(terminologyDict).some(term =>
|
||||
translation.includes(term as string)
|
||||
);
|
||||
if (!hasValidTerminology) {
|
||||
issues.push("翻译中包含较长英文单词");
|
||||
}
|
||||
}
|
||||
|
||||
// 检查长度是否合理
|
||||
if (translation.length > original.length * 4) {
|
||||
issues.push("翻译长度异常过长");
|
||||
}
|
||||
|
||||
// 检查专业术语使用
|
||||
for (const [en, translated] of Object.entries(terminologyDict)) {
|
||||
if (original.includes(en) && !translation.includes(translated as string) && !translation.includes(en)) {
|
||||
issues.push(`专业术语 "${en}" 可能翻译不准确`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: issues.length === 0,
|
||||
issues
|
||||
};
|
||||
}
|
||||
|
||||
// 🎯 处理单个语言的翻译
|
||||
async function processLanguage(json: any, aiConfig: AIConfig, targetLang: string): Promise<boolean> {
|
||||
const langConfig = LANGUAGE_CONFIG[targetLang];
|
||||
let hasChanges = false;
|
||||
|
||||
// 仅验证模式
|
||||
if (argv.validate) {
|
||||
console.log(`🔍 验证 ${langConfig.name} 翻译质量...`);
|
||||
let issues = 0;
|
||||
for (const [key, value] of Object.entries(json)) {
|
||||
const entry = value as { [key: string]: string };
|
||||
if (entry[targetLang]) {
|
||||
const validation = validateTranslation(key, entry[targetLang], targetLang);
|
||||
if (!validation.isValid) {
|
||||
console.warn(`⚠️ [${key}]: ${validation.issues.join(', ')}`);
|
||||
issues++;
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(issues === 0 ? `✅ ${langConfig.name} 所有翻译质量良好` : `⚠️ ${langConfig.name} 发现 ${issues} 个质量问题`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 统计需要翻译的条目
|
||||
const needTranslation = Object.keys(json).filter(key => {
|
||||
if (argv.force) {
|
||||
return true;
|
||||
}
|
||||
const entry = json[key] as { [key: string]: string | null };
|
||||
const translation = entry[targetLang];
|
||||
return translation == null || translation === "";
|
||||
});
|
||||
|
||||
if (needTranslation.length === 0) {
|
||||
console.log(`✅ ${langConfig.name} 所有条目都已翻译,无需处理`);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log(`📊 ${langConfig.name} 找到 ${needTranslation.length} 个需要翻译的条目`);
|
||||
|
||||
// 如果是 dry-run 模式,只显示需要翻译的条目
|
||||
if (argv['dry-run']) {
|
||||
console.log(`\n📋 ${langConfig.name}翻译预览:`);
|
||||
needTranslation.forEach((key, index) => {
|
||||
const entry = json[key] as { [key: string]: string | null };
|
||||
const translation = entry[targetLang];
|
||||
const status = translation ? '(重新翻译)' : '(新翻译)';
|
||||
console.log(`${index + 1}. ${key} ${status}`);
|
||||
});
|
||||
console.log(`\n📈 ${langConfig.name} 总计: ${needTranslation.length} 个条目`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 🚀 批量翻译处理
|
||||
const batchSize = parseInt(argv['batch-size']) || 8;
|
||||
const batches = [];
|
||||
for (let i = 0; i < needTranslation.length; i += batchSize) {
|
||||
batches.push(needTranslation.slice(i, i + batchSize));
|
||||
}
|
||||
|
||||
console.log(`⚡ ${langConfig.name} 使用批量翻译模式,${batches.length} 个批次,每批 ${batchSize} 个条目`);
|
||||
|
||||
for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
|
||||
const batch = batches[batchIndex];
|
||||
console.log(`\n🔄 ${langConfig.name} 处理批次 ${batchIndex + 1}/${batches.length} (${batch.length} 个条目)`);
|
||||
|
||||
try {
|
||||
const translations = await translateBatch(batch, aiConfig, targetLang);
|
||||
|
||||
// 应用翻译结果并验证质量
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const key = batch[i];
|
||||
if (translations[i]) {
|
||||
const entry = json[key] as { [key: string]: string | null };
|
||||
entry[targetLang] = translations[i];
|
||||
hasChanges = true;
|
||||
|
||||
// 翻译质量验证
|
||||
const validation = validateTranslation(key, translations[i], targetLang);
|
||||
if (validation.isValid) {
|
||||
console.log(`✅ ${key}`);
|
||||
} else {
|
||||
console.warn(`⚠️ ${key} (质量警告: ${validation.issues.join(', ')})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 批次间延迟,避免 API 限速
|
||||
if (batchIndex < batches.length - 1) {
|
||||
console.log('⏳ 等待 1 秒避免 API 限速...');
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ ${langConfig.name} 批次 ${batchIndex + 1} 翻译失败:`, error);
|
||||
console.log('继续处理下一批次...');
|
||||
}
|
||||
}
|
||||
|
||||
return hasChanges;
|
||||
}
|
||||
|
||||
// 🎯 解析 AI 配置
|
||||
function parseAIConfig(): { aiConfig: AIConfig; targetLang: string } {
|
||||
const baseURL = process.env.baseURL;
|
||||
|
||||
// 如果使用 OpenRouter,默认使用 OpenAI 兼容模式
|
||||
let provider: AIConfig['provider'];
|
||||
let model: string;
|
||||
|
||||
if (baseURL && baseURL.includes('openrouter.ai')) {
|
||||
provider = 'openai';
|
||||
model = argv.model || "google/gemini-2.5-flash";
|
||||
} else {
|
||||
provider = (argv.provider || 'google') as AIConfig['provider'];
|
||||
model = argv.model || "google/gemini-2.5-flash";
|
||||
}
|
||||
|
||||
const apiKey = process.env.apiKey || process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.GOOGLE_API_KEY;
|
||||
const targetLang = argv.lang || argv.language || 'all';
|
||||
|
||||
if (!apiKey) {
|
||||
console.error("❌ 错误: 缺少 API 密钥");
|
||||
console.error("请设置环境变量: apiKey 或对应的提供商 API 密钥");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (targetLang !== 'all' && !LANGUAGE_CONFIG[targetLang]) {
|
||||
console.error(`❌ 错误: 不支持的语言: ${targetLang}`);
|
||||
console.error(`支持的语言: ${Object.keys(LANGUAGE_CONFIG).join(', ')}, all`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return {
|
||||
aiConfig: {
|
||||
provider,
|
||||
model,
|
||||
apiKey,
|
||||
baseURL
|
||||
},
|
||||
targetLang
|
||||
};
|
||||
}
|
||||
|
||||
// 🎯 主函数
|
||||
async function main() {
|
||||
if (argv.help || argv.h) {
|
||||
console.log(`
|
||||
🌐 HyperChat 智能翻译工具 (基于 AI SDK)
|
||||
|
||||
用法: npx tsx scripts/translate.mts [选项]
|
||||
|
||||
选项:
|
||||
--help, -h 显示帮助信息
|
||||
--dry-run 仅显示需要翻译的条目,不执行翻译
|
||||
--force 强制重新翻译所有条目(包括已有翻译的)
|
||||
--batch-size N 批量翻译大小(默认: 8)
|
||||
--validate 仅验证现有翻译质量
|
||||
--provider NAME AI 提供商 (openai|anthropic|google, 默认: google)
|
||||
--model MODEL 指定模型 (默认: google/gemini-2.0-flash-exp)
|
||||
--lang, --language 目标语言 (zh|ja|ko|fr|de|all, 默认: all)
|
||||
|
||||
环境变量:
|
||||
apiKey API 密钥(通用)
|
||||
OPENAI_API_KEY OpenAI API 密钥
|
||||
ANTHROPIC_API_KEY Anthropic API 密钥
|
||||
GOOGLE_API_KEY Google API 密钥
|
||||
baseURL API 基础 URL(可选)
|
||||
|
||||
特性:
|
||||
✅ 基于独立 AI SDK,轻量高效
|
||||
✅ 支持多个 AI 提供商 (OpenAI/Anthropic/Google)
|
||||
✅ JSON Schema 确保翻译结构化和一致性
|
||||
✅ 针对 HyperChat 软件的专业术语词典
|
||||
✅ 智能批量翻译减少 API 调用
|
||||
✅ 置信度评估和质量验证
|
||||
✅ 智能回退机制
|
||||
|
||||
示例:
|
||||
npx tsx scripts/translate.mts # 翻译所有语言
|
||||
npx tsx scripts/translate.mts --lang zh # 仅翻译中文
|
||||
npx tsx scripts/translate.mts --lang ja # 翻译为日语
|
||||
npx tsx scripts/translate.mts --lang ko # 翻译为韩语
|
||||
npx tsx scripts/translate.mts --lang fr # 翻译为法语
|
||||
npx tsx scripts/translate.mts --lang de # 翻译为德语
|
||||
npx tsx scripts/translate.mts --provider anthropic --lang ja # 使用 Claude 翻译日语
|
||||
npx tsx scripts/translate.mts --dry-run --lang ko # 预览韩语翻译计划
|
||||
npx tsx scripts/translate.mts --validate --lang fr # 验证法语翻译质量
|
||||
npx tsx scripts/translate.mts --dry-run # 预览所有语言翻译计划
|
||||
`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
try {
|
||||
const { aiConfig, targetLang } = parseAIConfig();
|
||||
|
||||
// 检查 i18n.json 文件是否存在
|
||||
if (!fs.existsSync(i18nPath)) {
|
||||
console.error(`❌ 错误: i18n.json 文件不存在: ${i18nPath}`);
|
||||
console.error(`请先运行 'node scripts/extract-i18n.mjs' 生成 i18n.json 文件`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("🌐 开始 HyperChat 智能翻译 (基于 AI SDK)...");
|
||||
console.log(`🤖 使用: ${aiConfig.provider}/${aiConfig.model}`);
|
||||
|
||||
const json = JSON.parse(fs.readFileSync(i18nPath).toString());
|
||||
let hasChanges = false;
|
||||
|
||||
// 如果选择翻译所有语言
|
||||
if (targetLang === 'all') {
|
||||
console.log("🌍 翻译所有支持的语言...");
|
||||
for (const lang of Object.keys(LANGUAGE_CONFIG)) {
|
||||
console.log(`\n📍 开始翻译 ${LANGUAGE_CONFIG[lang].name} (${lang})...`);
|
||||
const result = await processLanguage(json, aiConfig, lang);
|
||||
if (result) hasChanges = true;
|
||||
}
|
||||
} else {
|
||||
const langConfig = LANGUAGE_CONFIG[targetLang];
|
||||
console.log(`📍 翻译目标语言: ${langConfig.name}`);
|
||||
const result = await processLanguage(json, aiConfig, targetLang);
|
||||
if (result) hasChanges = true;
|
||||
}
|
||||
|
||||
// 如果是 dry-run 或 validate 模式,提前返回
|
||||
if (argv['dry-run'] || argv.validate) {
|
||||
if (argv['dry-run'] && targetLang === 'all') {
|
||||
console.log(`⚡ 预计使用批量翻译,减少 API 调用`);
|
||||
console.log(`🤖 使用模型: ${aiConfig.provider}/${aiConfig.model}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
// 备份原文件
|
||||
const backupPath = i18nPath + '.backup-' + Date.now();
|
||||
fs.copyFileSync(i18nPath, backupPath);
|
||||
console.log(`\n💾 已备份原文件到: ${backupPath}`);
|
||||
|
||||
fs.writeFileSync(i18nPath, JSON.stringify(json, null, 2));
|
||||
console.log(`✅ 已更新 i18n.json 文件`);
|
||||
|
||||
// 重新构建 shared 包
|
||||
console.log('\n🔧 重新构建 shared 包...');
|
||||
try {
|
||||
await $`npm run build --workspace=@dadigua/hyperchat-shared`;
|
||||
console.log('✅ shared 包构建完成,i18n.json 已同步到 dist 目录');
|
||||
} catch (error) {
|
||||
console.warn('⚠️ shared 包构建失败,可能需要手动运行: npm run build --workspace=@dadigua/hyperchat-shared');
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n🎉 翻译完成!使用 ${aiConfig.provider}/${aiConfig.model} 完成智能翻译`);
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ 脚本执行失败:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 运行主函数
|
||||
await main();
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": false,
|
||||
"composite": false,
|
||||
"esModuleInterop": true,
|
||||
"jsxFactory": "React.createElement",
|
||||
"jsxFragmentFactory": "React.Fragment",
|
||||
"jsx": "react",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "Node",
|
||||
"experimentalDecorators": true,
|
||||
"removeComments": false,
|
||||
"resolveJsonModule": true,
|
||||
"sourceMap": true,
|
||||
"strict": false,
|
||||
"strictNullChecks": false,
|
||||
"lib": [
|
||||
"ESNext",
|
||||
"DOM"
|
||||
],
|
||||
"target": "ESNext",
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"./types/"
|
||||
],
|
||||
"outDir": "./dist"
|
||||
},
|
||||
"include": [
|
||||
"*.mts",
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user