@awesome-fe/translate
Version:
Translation utils
217 lines • 11.6 kB
JavaScript
;
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsdocTranslator = void 0;
var abstract_translator_1 = require("./abstract-translator");
var ts_morph_1 = require("ts-morph");
var util_1 = require("util");
var markdown_translator_1 = require("./markdown-translator");
var lodash_1 = require("lodash");
var delay_1 = require("../dom/delay");
function getTagsWithAncestors(node) {
if (!node) {
return [];
}
// 如果不是,就跳过这一层,直接返回父级的结果
if (!ts_morph_1.Node.isJSDocableNode(node)) {
return getTagsWithAncestors(node.getParent());
}
// 取当前节点的所有标记
var tags = node.getJsDocs().map(function (it) { return it.getTags(); }).flat();
// 合并当前节点的标记和父级节点的标记
return __spreadArray(__spreadArray([], tags, true), getTagsWithAncestors(node.getParent()), true);
}
function shouldTranslate(node, options) {
if (!ts_morph_1.Node.isJSDocableNode(node)) {
return false;
}
if (ts_morph_1.Node.isModifierableNode(node)) {
if (node.hasModifier(ts_morph_1.SyntaxKind.PrivateKeyword)) {
return false;
}
}
var tags = getTagsWithAncestors(node).map(function (it) { return it.getTagName(); });
return (!options.mustIncludesTags || (0, lodash_1.intersection)(tags, options.mustIncludesTags).length > 0) &&
(!options.mustExcludesTags || (0, lodash_1.intersection)(tags, options.mustExcludesTags).length === 0);
}
function preprocess(text) {
return text.replace(/(```\w*\n)(.*?)(```\n)/gs, function (_, leading, body, tailing) {
return "".concat(leading).concat(body.replace(/@/g, '@')).concat(tailing);
});
}
function postprocess(text) {
return text.replace(/@/g, '@');
}
function joinChineseLines(text) {
return text;
}
var JsdocTranslator = /** @class */ (function (_super) {
__extends(JsdocTranslator, _super);
function JsdocTranslator() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.markdownTranslator = new markdown_translator_1.MarkdownTranslator(_this.engine);
return _this;
}
JsdocTranslator.prototype.parse = function (text) {
var project = new ts_morph_1.Project({ manipulationSettings: { indentationText: ts_morph_1.IndentationText.TwoSpaces } });
return project.createSourceFile('placeholder.ts', preprocess(text));
};
JsdocTranslator.prototype.serialize = function (doc) {
return postprocess(doc.getFullText());
};
JsdocTranslator.prototype.flush = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.markdownTranslator.flush()];
case 1:
_a.sent();
return [2 /*return*/, _super.prototype.flush.call(this)];
}
});
});
};
JsdocTranslator.prototype.translateSentence = function (sentence) {
return this.markdownTranslator.translateContent(sentence).then(function (result) { return result; });
};
JsdocTranslator.prototype.translateDoc = function (doc, options) {
this.translateNode(doc, options).then(function (it) { return it; });
return doc;
};
JsdocTranslator.prototype.translateNode = function (node, options) {
return __awaiter(this, void 0, void 0, function () {
var docs, _loop_1, this_1, _i, docs_1, doc, children;
var _this = this;
return __generator(this, function (_a) {
if (ts_morph_1.Node.isJSDocableNode(node) && shouldTranslate(node, options)) {
docs = node.getJsDocs();
_loop_1 = function (doc) {
var structure = doc.getStructure();
var tagTasks = structure.tags.map(function (tag) { return _this.translateTag(tag); });
var origin = joinChineseLines(structure.description.trim());
var descriptionTask = this_1.translateSentence(origin).then(function (translation) {
if (translation.trim() !== origin.trim()) {
structure.description = removeExtraBlankLines(translation);
}
});
Promise.all(__spreadArray(__spreadArray([], tagTasks, true), [descriptionTask], false).filter(function (it) { return !!it; })).then(function () {
if (!(0, util_1.isDeepStrictEqual)(structure, doc.getStructure())) {
doc.set(structure);
}
});
};
this_1 = this;
for (_i = 0, docs_1 = docs; _i < docs_1.length; _i++) {
doc = docs_1[_i];
_loop_1(doc);
}
}
children = Array.from(node.getChildren());
children.forEach(function (subNode) {
_this.translateNode(subNode, options);
});
return [2 /*return*/, (0, delay_1.delay)(1000).then(function () { return node; })];
});
});
};
JsdocTranslator.prototype.translateTag = function (tag) {
var _a;
var text = tag.text;
if (isBinaryTag(tag)) {
var _b = (_a = (text !== null && text !== void 0 ? text : '').match(/^((?:{.*?}\s*)?(?:[\w.\[\]]+|\[.*?])\s+)([\s\S]*)$/)) !== null && _a !== void 0 ? _a : [], name_1 = _b[1], description_1 = _b[2];
if (description_1 === null || description_1 === void 0 ? void 0 : description_1.trim()) {
return this.translateSentence(description_1).then(function (translation) {
if (translation.trim() !== description_1.trim()) {
tag.text = (name_1 !== null && name_1 !== void 0 ? name_1 : '') + removeExtraBlankLines(translation);
}
});
}
}
else if (isUnaryTag(tag)) {
var _c = (text !== null && text !== void 0 ? text : '').match(/^({.*?}\s*)?([\s\S]*)$/), prefix_1 = _c[1], description_2 = _c[2];
if (description_2 === null || description_2 === void 0 ? void 0 : description_2.trim()) {
return this.translateSentence(description_2).then(function (translation) {
if (translation.trim() !== description_2.trim()) {
var leadingLines = ['publicApi', 'returns', 'codeGenApi', 'ngModule'].includes(tag.tagName) ? '\n\n' : '';
var tailingLines = ['usageNotes', 'description', 'deprecated'].includes(tag.tagName) ? '\n\n' : '';
tag.text = leadingLines + (prefix_1 !== null && prefix_1 !== void 0 ? prefix_1 : '') + tailingLines + removeExtraBlankLines(translation);
}
});
}
}
};
return JsdocTranslator;
}(abstract_translator_1.AbstractTranslator));
exports.JsdocTranslator = JsdocTranslator;
// 有两个参数且需要翻译的标记,如 @param a Some value
function isBinaryTag(tag) {
return ['param', 'arg', 'argument', 'property', 'prop', 'yields', 'yield', 'template', 'breaking-change'].includes(tag.tagName);
}
// 有一个参数且需要翻译的标记,如 @returns Some value
function isUnaryTag(tag) {
return ['returns', 'return', 'classdesc', 'description', 'desc', 'summary', 'throws',
'deprecated', 'usageNotes', 'see'].includes(tag.tagName);
}
function removeExtraBlankLines(translation) {
return translation.replace(/\n$/s, '') + '\n';
}
//# sourceMappingURL=jsdoc-translator.js.map