UNPKG

@awesome-fe/translate

Version:
53 lines 2.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractTranslator = void 0; const fs_1 = require("fs"); const common_1 = require("../dom/common"); const translation_engine_type_1 = require("../translation-engine/translation-engine-type"); class AbstractTranslator { engine; constructor(engine) { this.engine = engine; } async setup() { } async tearDown() { } async translateFile(filename, options = {}) { const content = (0, fs_1.readFileSync)(filename, 'utf8'); const result = await this.translateContentAndFlushStandalone(content, { ...options, filename }); // 提取时不应该更新原始文件 if (![translation_engine_type_1.TranslationEngineType.extractor, translation_engine_type_1.TranslationEngineType.vectorizer].includes(options.engine)) { (0, fs_1.writeFileSync)(filename, result.trim() + '\n', 'utf8'); } } async translateContentAndFlushStandalone(content, options) { await this.engine.setup(options.filename); try { return await this.translateContentAndFlush(content, options); } finally { await this.engine.tearDown(); } } async translateContentAndFlush(content, options) { const result = this.translateContent(content, options); await this.flush(); return this.serialize(result, options); } translateContent(content, options) { const doc = this.parse(content, options); return this.translateDoc(doc, options); } // 前面所有的工作都是在安排异步任务,调 flush 才真正开始执行 async flush() { return this.engine.flush(); } async translateSentence(sentence, translation, format) { return this.engine.translate(sentence, translation, format) // 翻译结果不包含中文时,说明没有进行实质性翻译,返回原文,以便调用者忽略它 .then((translation) => (0, common_1.containsChinese)(translation) ? translation : sentence); } } exports.AbstractTranslator = AbstractTranslator; //# sourceMappingURL=abstract-translator.js.map