UNPKG

proto-gen-dts

Version:
237 lines (178 loc) 7.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatTS = formatTS; exports.getFieldIsRequired = getFieldIsRequired; exports.getNamespaceRoot = getNamespaceRoot; exports.getParentLookup = getParentLookup; exports.getReflectionParentName = getReflectionParentName; exports.isNamespace = isNamespace; exports.optionsToComment = optionsToComment; exports.protoTypeToTSType = protoTypeToTSType; exports.replaceSamePath = replaceSamePath; exports.reportIssues = reportIssues; exports.writeBanner = writeBanner; var _path = _interopRequireDefault(require("path")); var _stanUtils = require("stan-utils"); var _protobufjs = require("protobufjs"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var _require = require('../package.json'), name = _require.name, bugs = _require.bugs; /** * check is protobufjs Namespace * @param nested */ function isNamespace(nested) { var _nested$__proto__, _nested$__proto__$con; // @ts-ignore return (nested === null || nested === void 0 ? void 0 : (_nested$__proto__ = nested.__proto__) === null || _nested$__proto__ === void 0 ? void 0 : (_nested$__proto__$con = _nested$__proto__.constructor) === null || _nested$__proto__$con === void 0 ? void 0 : _nested$__proto__$con.name) === 'Namespace'; } /** * get namespace root * @param nested */ function getNamespaceRoot(nested) { var parent = nested; while (!!parent.parent) { parent = parent.parent; } return parent; } /** * prettier format ts content * @param content * @param opts * @returns parsed content */ function formatTS(content, opts) { var prettierFormatOpts = _objectSpread(_objectSpread({}, opts), {}, { parser: 'typescript' }); // read project prettier config var prettierrc = _stanUtils.prettier.resolveConfigFile.sync(); if (prettierrc) { Object.assign(prettierrc, _stanUtils.prettier.resolveConfig.sync(prettierrc)); } return _stanUtils.prettier.format(content, prettierFormatOpts); } // https://developers.google.com/protocol-buffers/docs/proto3#json var Types = { number: ['int32', 'uint32', 'sint32', 'sfixed32', 'float', 'double', 'fixed32'], string: ['int64', 'uint64', 'sint64', 'sfixed64', 'string', 'bytes', 'fixed64'], boolean: ['bool'] }; /** * process proto type convert ts type * @param input proto type * @returns ts type */ function protoTypeToTSType(input) { var type; for (type in Types) { if (Types[type].includes(input)) { return type; } } } var requiredCommentKeyword = ['@v: required']; function getFieldIsRequired(field) { if (!field.comment) { return field.required; } return requiredCommentKeyword.some(function (v) { return field.comment.includes(v); }) || field.required; } /** * use parent lookup * @param field * @param root * @param type */ function getParentLookup(_ref) { var field = _ref.field, root = _ref.root, type = _ref.type; var parent = field.parent; while (parent) { var res = parent.lookup(type); // when field name same as type if (res && res instanceof _protobufjs.Namespace) return res; parent = parent.parent; } return root.lookup(type); } function getReflectionParentName(field) { var _parent; var parent = field.parent; var namePath = [(_parent = parent) === null || _parent === void 0 ? void 0 : _parent.name]; while ((_parent2 = parent) !== null && _parent2 !== void 0 && _parent2.parent && (_parent3 = parent) !== null && _parent3 !== void 0 && _parent3.name) { var _parent2, _parent3, _parent4; parent = (_parent4 = parent) === null || _parent4 === void 0 ? void 0 : _parent4.parent; namePath.unshift(parent.name); } return namePath.filter(Boolean).join('_'); } /** * replace same real path * @param base * @param file */ function replaceSamePath(base, file) { if (file.startsWith(base)) { return file.replace(base, ''); } base = _path.default.resolve(base); file = _path.default.resolve(file); var a = base.split(_path.default.sep); var b = file.split(_path.default.sep); var index = a.findIndex(function (v, i) { return b[i] !== v; }); if (~index) { return _path.default.join.apply(_path.default, _toConsumableArray(b.slice(index))); } return file; } /** * document banner * @param content file text content */ function writeBanner(content) { var banner = "/** code generate by ".concat(name, " don't edit */"); if (content.includes(banner)) { return content; } return "".concat(banner, "\n\n").concat(content); } /** * output issues uri * @param opt */ function reportIssues(opt) { var _opt$labels = opt.labels, labels = _opt$labels === void 0 ? 'bug' : _opt$labels, _opt$title = opt.title, title = _opt$title === void 0 ? '' : _opt$title, _opt$template = opt.template, template = _opt$template === void 0 ? 'bug_report.md' : _opt$template; var uri = "".concat(bugs.url, "/new?assignees=&labels=").concat(labels, "&template=").concat(template, "&title=").concat(encodeURIComponent(title)); return "".concat(title, "\nPlease report issues ").concat(uri); } function optionsToComment(options) { var str = ''; for (var k in options || {}) { if (options !== null && options !== void 0 && options[k]) { str += "".concat(k, "=").concat(options[k], "\n"); } } return str; }