|
| 1 | +import type { |
| 2 | + TranslateOptions, |
| 3 | + TranslationOption, |
| 4 | +} from '@kabeep/node-translate'; |
| 5 | +import googleTranslate from '@kabeep/node-translate'; |
| 6 | +import { translate as microsoftTranslate } from 'microsoft-translate-api'; |
| 7 | +import { OS_LOCALE_ENV } from '../constants'; |
| 8 | +import type { ArgumentVector, MicrosoftTranslateOption } from '../shared'; |
| 9 | + |
| 10 | +export interface TranslatorOptions |
| 11 | + extends Omit<TranslateOptions, 'raw'>, |
| 12 | + Pick<ArgumentVector, 'engine'> {} |
| 13 | + |
| 14 | +const LOCALE_ALIASES: Record<string, string> = { |
| 15 | + mandarin: 'zh-cn', |
| 16 | + cantonese: 'zh-tw', |
| 17 | + 'zh-hk': 'zh-tw', |
| 18 | +}; |
| 19 | + |
| 20 | +const MICROSOFT_LANG_CODE_DICT: Record<string, string> = { |
| 21 | + zh: 'zh-hans', |
| 22 | + 'zh-cn': 'zh-hans', |
| 23 | + 'zh-tw': 'zh-hant', |
| 24 | +}; |
| 25 | + |
| 26 | +function microsoftLangCodeAdapter(code?: string, adaptive = false) { |
| 27 | + const isAdaptive = !code || code === 'auto'; |
| 28 | + if (!adaptive && isAdaptive) return null; |
| 29 | + |
| 30 | + const source = isAdaptive ? OS_LOCALE_ENV : code; |
| 31 | + const langCode = LOCALE_ALIASES[source] ?? source; |
| 32 | + return MICROSOFT_LANG_CODE_DICT[langCode] ?? langCode; |
| 33 | +} |
| 34 | + |
| 35 | +async function translator( |
| 36 | + text: string, |
| 37 | + options: TranslatorOptions, |
| 38 | +): Promise<TranslationOption | MicrosoftTranslateOption[] | undefined> { |
| 39 | + const { engine = 'google', ...restOptions } = options; |
| 40 | + switch (engine) { |
| 41 | + case 'microsoft': { |
| 42 | + const { from, to } = options; |
| 43 | + const sourceLang = microsoftLangCodeAdapter(from); |
| 44 | + const targetLang = microsoftLangCodeAdapter(to, true); |
| 45 | + return microsoftTranslate( |
| 46 | + text, |
| 47 | + sourceLang, |
| 48 | + targetLang as string, |
| 49 | + ) as unknown as MicrosoftTranslateOption[] | undefined; |
| 50 | + } |
| 51 | + |
| 52 | + case 'google': { |
| 53 | + return googleTranslate(text, restOptions); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +export default translator; |
0 commit comments