UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

493 lines (490 loc) 16.7 kB
import { b as __awaiter, _ as __assign, c as __generator, a as __spreadArray } from '../tslib.es6-096fffdd.js'; import * as fs from 'fs'; import * as path from 'path'; import { formatBite } from '../bite/format-bite.mjs'; import { addTextForImg } from '../canvas/img-text.mjs'; import { getGitCommitInfo } from '../git/git.mjs'; import { saveBase64ImgToFile } from '../node-img/img.mjs'; import { uploadCOSFile } from '../tencent-cloud/cos/cos.mjs'; import { getCosUrlLink } from '../tencent-cloud/cos/link.mjs'; import { timeStampFormat } from '../time/time.mjs'; import { sendWxRobotMarkdown } from '../wecom-robot/base.mjs'; import { DEFAULT_BUILD_SETTING, MAX_TRY_TIMES_MAP, PREVIEW_IMG_MAX_WORD_LENGTH } from './config.mjs'; import { getBundleBuildDesc, getBundleVersion, parseUploadResult, flattenSubPackages } from './helper.mjs'; import '../canvas/get-canvas.mjs'; import '../node/node-command.mjs'; import '@babel/runtime/helpers/typeof'; import '../tencent-cloud/cos/helper.mjs'; import '../wecom-robot/helper.mjs'; import 'axios'; import '../wecom-robot/message.mjs'; function getFullPackageSize(result) { var obj = flattenSubPackages(result); return formatBite(obj.__FULL__.size); } function getMainPackageSize(result) { var obj = flattenSubPackages(result); return formatBite(obj.__APP__.size); } var MpCI = /** @class */function () { /** * 小程序自动化构建工具 * @param {object} options 选项 * * @example * * const { MpCI, fetchRainbowConfig } = require('t-comm'); * * const env = "${env}" * const branch = "${branch}" * * const root = "${WORKSPACE}"; * * async function getCIConfig() { * let res = {}; * const str = await fetchRainbowConfig('mp_ci', { * appId: '', * envName: 'x', * groupName: 'x', * }); * try { * res = JSON.parse(str); * } catch (err) {} * return res; * } * * function getRobot(config = {}) { * return config?.robotMap?.[branch]?.[env] || 1; * } * * async function main() { * const config = await getCIConfig(); * console.log('config: \n', config, typeof config); * const { * appName, * appId, * webhookUrl, * chatId, * cosInfo, * } = config; * * const ci = new MpCI({ * appName, * appId, * root, * env, * robotNumber: getRobot(config), * * webhookUrl, * chatId, * * cosInfo, * }); * * await ci.upload(); * await ci.preview(); * await ci.sendRobotMsg(); * } * * main(); */ function MpCI(options) { this.webhookUrl = ''; this.chatId = ''; this.projectPath = ''; this.privateKeyPath = ''; this.buildDesc = ''; this.version = ''; this.errorLink = ''; this.pagePath = ''; this.searchQuery = ''; this.tryTimesMap = { UPLOAD: 1, PREVIEW: 1 }; var ci = options.ci; if (!ci) { try { ci = require('miniprogram-ci'); } catch (err) { console.log('[MpCI] err', err); } } this.ciLib = ci; this.options = options; this.projectCI = null; this.previewResult = { subPackageInfo: [] }; this.savePreviewPath = path.resolve(process.cwd(), 'mp_ci_preview_destination.png'); var appId = options.appId, appName = options.appName, projectPath = options.projectPath, privateKeyPath = options.privateKeyPath, ignores = options.ignores, type = options.type, root = options.root, env = options.env, robotNumber = options.robotNumber, buildSetting = options.buildSetting, webhookUrl = options.webhookUrl, chatId = options.chatId, cosInfo = options.cosInfo, errorLink = options.errorLink, pagePath = options.pagePath, searchQuery = options.searchQuery; this.appId = appId; this.appName = appName || ''; this.type = type || 'miniProgram'; this.pagePath = pagePath || ''; this.searchQuery = searchQuery || ''; this.root = root || process.cwd(); this.ignores = ignores || ['node_modules/**/*']; this.pkgFile = path.resolve(this.root, './package.json'); this.env = env || 'test'; this.robotNumber = robotNumber || 30; this.webhookUrl = webhookUrl; this.chatId = chatId; this.buildSetting = __assign(__assign({}, DEFAULT_BUILD_SETTING), buildSetting || {}); this.projectPath = projectPath || ''; this.privateKeyPath = privateKeyPath || ''; this.cosInfo = cosInfo || {}; this.errorLink = errorLink || ''; this.validateOptions(); if (this.ciLib) { this.init(); } this.initBaseInfo(); } MpCI.prototype.validateOptions = function () { if (!this.projectPath) { this.projectPath = path.resolve(this.root, 'dist/build/mp-weixin'); } if (!this.privateKeyPath) { this.privateKeyPath = path.resolve(this.root, 'private.key'); } if (this.ciLib && !fs.existsSync(this.privateKeyPath)) { throw new Error('ERROR: privateKeyPath 位置不存在'); } if (!fs.existsSync(this.projectPath)) { throw new Error('ERROR: projectPath 位置不存在'); } // if (!fs.existsSync(this.pkgFile)) { // throw new Error('ERROR: package.json 不存在'); // } }; MpCI.prototype.initBaseInfo = function () { this.getBuildTime(); if (!this.options.commitInfo) { this.commitInfo = getGitCommitInfo(this.root, false, false, false); } else { this.commitInfo = this.options.commitInfo; } if (!this.options.buildDesc) { this.buildDesc = getBundleBuildDesc({ root: this.root, env: this.env }) || ''; } else { this.buildDesc = this.options.buildDesc; } if (!this.options.version) { this.version = getBundleVersion(this.root); } else { this.version = this.options.version; } }; MpCI.prototype.init = function () { var _a = this, appId = _a.appId, projectPath = _a.projectPath, privateKeyPath = _a.privateKeyPath, ignores = _a.ignores, type = _a.type; this.projectCI = new this.ciLib.Project({ appid: appId, type: type, projectPath: projectPath, privateKeyPath: privateKeyPath, ignores: ignores }); }; MpCI.prototype.getBuildTime = function () { this.buildTime = timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss'); }; /** * 上传 */ MpCI.prototype.upload = function () { return __awaiter(this, void 0, void 0, function () { var err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2,, 6]); return [4 /*yield*/, this.tryUpload()]; case 1: _a.sent(); return [3 /*break*/, 6]; case 2: err_1 = _a.sent(); if (!(this.tryTimesMap.UPLOAD < MAX_TRY_TIMES_MAP.UPLOAD)) return [3 /*break*/, 4]; this.tryTimesMap.UPLOAD += 1; return [4 /*yield*/, this.tryUpload()]; case 3: _a.sent(); return [3 /*break*/, 5]; case 4: throw new Error(err_1); case 5: return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }; MpCI.prototype.tryUpload = function () { return __awaiter(this, void 0, void 0, function () { var _a, robotNumber, version, buildDesc, uploadResult; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this, robotNumber = _a.robotNumber, version = _a.version, buildDesc = _a.buildDesc; return [4 /*yield*/, this.ciLib.upload({ project: this.projectCI, version: version, desc: buildDesc, robot: robotNumber, setting: this.buildSetting })]; case 1: uploadResult = _b.sent(); this.getBuildTime(); return [4 /*yield*/, this.ciLib.getDevSourceMap({ project: this.projectCI, robot: robotNumber, sourceMapSavePath: './sm.zip' })]; case 2: _b.sent(); console.log('[MpCI] UploadResult:\n', uploadResult); return [2 /*return*/]; } }); }); }; MpCI.prototype.preview = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2,, 5]); return [4 /*yield*/, this.tryPreview()]; case 1: _a.sent(); return [3 /*break*/, 5]; case 2: _a.sent(); if (!(this.tryTimesMap.UPLOAD < MAX_TRY_TIMES_MAP.UPLOAD)) return [3 /*break*/, 4]; this.tryTimesMap.UPLOAD += 1; return [4 /*yield*/, this.tryPreview()]; case 3: _a.sent(); _a.label = 4; case 4: return [3 /*break*/, 5]; case 5: return [2 /*return*/]; } }); }); }; /** * 预览 */ MpCI.prototype.tryPreview = function () { return __awaiter(this, void 0, void 0, function () { var previewParam, previewResult; return __generator(this, function (_a) { switch (_a.label) { case 0: previewParam = { project: this.projectCI, desc: this.buildDesc, setting: this.buildSetting, qrcodeFormat: 'image', qrcodeOutputDest: this.savePreviewPath, robot: this.robotNumber, pagePath: this.pagePath || undefined, searchQuery: this.searchQuery || undefined // pagePath: 'pages/index/index', // 预览页面 // searchQuery: 'a=1&b=2', // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`&` }; return [4 /*yield*/, this.ciLib.preview(previewParam)]; case 1: previewResult = _a.sent(); console.log('[MpCI] PreviewResult:\n', previewResult); this.previewResult = previewResult; return [4 /*yield*/, this.uploadPreviewImg(previewResult)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** * 上传预览图片到COS */ MpCI.prototype.uploadPreviewImg = function (previewResult) { return __awaiter(this, void 0, void 0, function () { var _a, robotNumber, env, buildTime, commitInfo, version, textList, newPreviewImg; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this, robotNumber = _a.robotNumber, env = _a.env, buildTime = _a.buildTime, commitInfo = _a.commitInfo, version = _a.version; textList = __spreadArray(['[CI RESULT]', "VERSION: ".concat(version), "UPLOADER: CI ROBOT ".concat(robotNumber), "ENV: ".concat(env), "BRANCH: ".concat(commitInfo.branch), "BUILD TIME: ".concat(buildTime), "LAST COMMIT: ".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash)], parseUploadResult(previewResult), true).map(function (item) { if (item.length > PREVIEW_IMG_MAX_WORD_LENGTH) return "".concat(item.slice(0, PREVIEW_IMG_MAX_WORD_LENGTH), "..."); return item; }); return [4 /*yield*/, addTextForImg({ width: 300, height: 300, imgPath: this.savePreviewPath, textList: textList })]; case 1: newPreviewImg = _b.sent(); return [4 /*yield*/, saveBase64ImgToFile({ imgUrl: newPreviewImg, savePath: this.savePreviewPath })]; case 2: _b.sent(); this.uploadFiles([{ key: this.getCosKey(), path: this.savePreviewPath }]); return [2 /*return*/]; } }); }); }; MpCI.prototype.getCosKey = function () { var _a = this, cosInfo = _a.cosInfo, env = _a.env, commitInfo = _a.commitInfo; return "".concat(cosInfo.dir, "/").concat(commitInfo.branch.replace(/\//g, '-'), "_").concat(env, ".png"); }; MpCI.prototype.getCOSFilePath = function () { var _a = this.cosInfo, bucket = _a.bucket, region = _a.region; var cosKey = this.getCosKey(); return getCosUrlLink({ bucket: bucket, region: region, dir: '', fileName: cosKey }); }; /** * 发送机器人消息 */ MpCI.prototype.sendRobotMsg = function (hasImg) { if (hasImg === void 0) { hasImg = true; } return __awaiter(this, void 0, void 0, function () { var _a, robotNumber, webhookUrl, env, commitInfo, version, previewResult, appName, chatId, descList, buildUrl, template; return __generator(this, function (_b) { _a = this, robotNumber = _a.robotNumber, webhookUrl = _a.webhookUrl, env = _a.env, commitInfo = _a.commitInfo, version = _a.version, previewResult = _a.previewResult, appName = _a.appName; chatId = this.chatId; if (!webhookUrl) { return [2 /*return*/]; } if (!chatId) { chatId = undefined; } descList = ["\u5206\u652F\uFF1A".concat(commitInfo.branch), "\u73AF\u5883\uFF1A".concat(env), "\u7248\u672C\uFF1A".concat(version || ''), "\u673A\u5668\u4EBA\uFF1A".concat(robotNumber), "\u6700\u540E\u63D0\u4EA4: ".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash), "\u603B\u5305\uFF1A".concat(getFullPackageSize(previewResult)), "\u4E3B\u5305\uFF1A".concat(getMainPackageSize(previewResult)) // `${buildTime || ''}`, ]; if (hasImg) { descList.push("[\u9884\u89C8\u56FE\u7247](".concat(this.getCOSFilePath(), ")")); } buildUrl = process.env.BK_CI_BUILD_URL; if (buildUrl) { descList.push("[\u6784\u5EFA\u5730\u5740](".concat(buildUrl, ")")); } template = "> \u2705\u3010".concat(appName || '', " WX MP\u3011").concat(descList.join(',')); sendWxRobotMarkdown({ webhookUrl: webhookUrl, content: template, chatId: chatId }); return [2 /*return*/]; }); }); }; MpCI.prototype.uploadAndPreview = function () { return __awaiter(this, void 0, void 0, function () { var err_3, _a, webhookUrl, errorLink, commitInfo, env, appName, chatId, descList, errorContent; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2,, 3]); return [4 /*yield*/, Promise.all([this.upload(), this.preview()])]; case 1: _b.sent(); return [3 /*break*/, 3]; case 2: err_3 = _b.sent(); console.log('[MpCI] err', err_3); _a = this, webhookUrl = _a.webhookUrl, errorLink = _a.errorLink, commitInfo = _a.commitInfo, env = _a.env, appName = _a.appName; chatId = this.chatId; if (!webhookUrl) { return [2 /*return*/]; } if (!chatId) { chatId = undefined; } descList = ["\u5206\u652F\uFF1A".concat(commitInfo.branch), "\u73AF\u5883\uFF1A".concat(env), err_3.toString()]; errorContent = "".concat(errorLink ? "[".concat(appName || '', "\u6784\u5EFA\u5931\u8D25](").concat(errorLink, ")") : '').concat(descList.join(',')); sendWxRobotMarkdown({ webhookUrl: webhookUrl, content: errorContent, chatId: chatId }); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; MpCI.prototype.uploadFiles = function (files) { return __awaiter(this, void 0, void 0, function () { var _a, secretId, secretKey, bucket, region; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this.cosInfo || {}, secretId = _a.secretId, secretKey = _a.secretKey, bucket = _a.bucket, region = _a.region; return [4 /*yield*/, uploadCOSFile({ files: files, secretId: secretId, secretKey: secretKey, bucket: bucket, region: region })]; case 1: _b.sent(); return [2 /*return*/]; } }); }); }; return MpCI; }(); export { MpCI };