(origin: string, context: string = document.title, options: TranslateOptions = {})
| 23 | * @returns 翻译结果的Promise |
| 24 | */ |
| 25 | export async function translateText(origin: string, context: string = document.title, options: TranslateOptions = {}): Promise<string> { |
| 26 | const { |
| 27 | maxRetries = 3, |
| 28 | retryDelay = 1000, |
| 29 | timeout = 45000, |
| 30 | useCache = config.useCache, |
| 31 | } = options; |
| 32 | |
| 33 | // 如果目标语言与当前文本语言相同,直接返回原文 |
| 34 | if (detectlang(origin.replace(/[\s\u3000]/g, '')) === config.to) { |
| 35 | return origin; |
| 36 | } |
| 37 | |
| 38 | // 检查缓存 |
| 39 | if (useCache) { |
| 40 | const cachedResult = cache.localGet(origin); |
| 41 | if (cachedResult) { |
| 42 | if (isDev) { |
| 43 | console.log('[翻译API] 命中缓存,直接返回缓存结果'); |
| 44 | } |
| 45 | return cachedResult; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // 增加翻译计数 |
| 50 | config.count++; |
| 51 | // 保存配置以确保计数持久化 |
| 52 | storage.setItem('local:config', JSON.stringify(config)); |
| 53 | |
| 54 | // 使用队列处理翻译请求 |
| 55 | return enqueueTranslation(async () => { |
| 56 | // 创建翻译任务 |
| 57 | const translationTask = async (retryCount: number = 0): Promise<string> => { |
| 58 | try { |
| 59 | // 发送翻译请求给background脚本处理 |
| 60 | const result = await Promise.race([ |
| 61 | browser.runtime.sendMessage({ context, origin }), |
| 62 | new Promise<never>((_, reject) => |
| 63 | setTimeout(() => reject(new Error('翻译请求超时')), timeout) |
| 64 | ) |
| 65 | ]) as string; |
| 66 | |
| 67 | // 如果翻译结果为空或与原文完全相同,直接返回原文 |
| 68 | if (!result || result === origin) { |
| 69 | return origin; |
| 70 | } |
| 71 | |
| 72 | // 缓存翻译结果 |
| 73 | if (useCache) { |
| 74 | cache.localSet(origin, result); |
| 75 | } |
| 76 | |
| 77 | return result; |
| 78 | } catch (error) { |
| 79 | // 处理错误,根据重试策略决定是否重试 |
| 80 | if (retryCount < maxRetries) { |
| 81 | if (isDev) { |
| 82 | console.log(`[翻译API] 翻译失败,${retryCount + 1}/${maxRetries} 次重试,原因:`, error); |
no test coverage detected