@infly/libs 2.2.15 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,14 @@
6
6
 
7
7
  Vue 2 专属的 Permission、Vuex store、实例 mixin、Vue CLI 预览和 webpack 配置集中在 `adapters/vue2/`,避免核心入口依赖 Vue 项目约定。
8
8
 
9
+ ## 发布结果通知
10
+
11
+ `@infly/libs/build/release-result.js` 的 `formatReleaseResult` / `createReleasePayload` 统一投影项目、环境、组件、状态、源码版本、镜像版本、构建号、触发人、发布说明和日志链接。输入字段分别为 `project/environment/components/status/sourceVersion/imageVersion/buildNumber/actor/note/logUrl`;不接受环境变量全集,日志 URL 去除认证及查询参数。
12
+
13
+ `infly-libs release:notification --input result.json --output payload.json` 只生成 JSON,不发送通知。Jenkins 无需为了通知在部署服务器安装 Node,可保留同字段的薄 Groovy payload 生成,发送凭据仍由各自 Credentials 注入。源码版本与镜像版本不能相互冒充:产物仓镜像应注明产物提交,knowledge 与 Go 应分别记录提交。
14
+
15
+ 历史 `build/build-utils/webhook-single.js` 仅转发 `webhook.js` 的 `postVersionFileAndMsg`,单条和批量汇总共用正文格式、发送、超时、响应检查和凭据解析;两种调用路径继续兼容。可在 `extraParams.releaseResult` 传入上述结果对象采用统一正文,未传时保留原构建文案。`RELEASE_WEBHOOK_URL` / `WECOM_WEBHOOK_URL` 进程注入优先于原 `webhookUrl` 本机配置;所有跳过通知参数和环境开关共用。错误日志仅输出受限错误码,避免 Axios error/config 带出 URL 凭据。
16
+
9
17
  ## 注意事项
10
18
 
11
19
  新代码应显式导入 Vue 2 适配路径。Webpack 适配器仅服务脱离
@@ -135,7 +143,9 @@ infly-libs release:docker --local --health-check --health-timeout=60
135
143
 
136
144
  `checks` 中的名称必须对应应用已有的 pnpm script;任一检查、覆盖率文件验证、Sonar Quality Gate 或镜像健康门禁失败,命令都会退出且不会推送镜像。`sonar` 默认为 `true`;设为 `false` 时由 CI 单独负责扫描和 Quality Gate。本地启用 Sonar 时必须通过当前进程环境或应用根目录下被 Git 忽略的 `.env.production.local` 提供 `SONAR_TOKEN`,并确保 `sonar-scanner` CLI 可执行;当前进程环境变量的优先级更高。`release:docker` 会拒绝含未提交文件的应用工作树,固定使用完整 40 位应用 commit 作为镜像标签及 OCI revision/version;普通 `build:docker` 未显式传版本时同样使用完整 commit。应用差异保留在应用配置,通用编排由 `infly-libs` 维护。
137
145
 
138
- `infly-libs beforeBuild` 要求应用通过 `infly.buildConfigs.gitAutoPushReposBranchMap` 声明可构建分支;当前应用、可选产物仓、历史独立 packages 仓以及 monorepo 根仓更新均只允许 fast-forward,分支发生分叉时立即停止,不自动创建 merge commit。只需要更新应用和根仓源码的项目应显式设置 `gitAuto: false` 与 `gitAutoPushRepos: false`,避免进入产物自动提交或产物仓分支处理。兄弟应用依赖会从 `vue.config.js`、`vite.config.js/mjs/ts` 和 `next.config.js/mjs/ts` 的相对路径 alias 中静态识别,不执行配置文件;识别到的兄弟仓同样要求工作树干净并以 fast-forward-only 更新。
146
+ `infly-libs beforeBuild` 在应用未配置 `infly.buildConfigs.gitAutoPushReposBranchMap` 时,默认使用 `{ "master": "master", "develop": "develop" }`;应用显式配置的映射(包括空对象)会整体覆盖默认值,不合并分支。默认映射不会隐式启用产物仓推送;显式映射仍沿用原有启用行为,`gitAutoPushRepos: false` 始终优先。当前应用、可选产物仓、历史独立 packages 仓以及 monorepo 根仓更新均只允许 fast-forward,分支发生分叉时立即停止,不自动创建 merge commit。只需要更新应用和根仓源码的项目应显式设置 `gitAuto: false` 与 `gitAutoPushRepos: false`,避免进入产物自动提交或产物仓分支处理。兄弟应用依赖会从 `vue.config.js`、`vite.config.js/mjs/ts` 和 `next.config.js/mjs/ts` 的相对路径 alias 中静态识别,不执行配置文件;识别到的兄弟仓同样要求工作树干净并以 fast-forward-only 更新。
147
+
148
+ `beforeBuild` 优先使用当前调用的显式 `--mode`:测试发布推荐 `infly-libs beforeBuild --mode staging`,正式发布推荐 `infly-libs beforeBuild --mode production`。未传参数时,按构建/发布脚本名的冒号分段识别 `test/stage/staging` 或 `pro/prod/production`,兼容现有 `build:stage`、`build:prod` 和 `release:*:test:docker`、`release:prod:docker`;不再从整条脚本的其他命令中推测环境。测试模式沿用现有映射选择测试分支,正式模式选择 `master`;环境未知或命令名同时包含两种环境字段时保留原有校验提示,Docker 发布不统一绕过确认。显式未知模式不会回退到命令名识别。
139
149
 
140
150
  受控紧急构建可使用 `--emergency` 跳过 `checks`、覆盖率文件校验和 Sonar,但必须提供 8~200 个字符且无控制字符的 `--emergency-reason`,并同时启用 `--standalone --commit-only --health-check`。紧急模式仍执行工作树干净检查、commit/revision 解析、镜像构建、健康检查和推送;缺少任一保护参数会在调用 Docker 前失败。
141
151
 
@@ -282,6 +292,8 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
282
292
 
283
293
  `infly-libs release:docker` 是统一发布入口:项目配置 `infly.docker` 或传入 target/component 参数时进入目标化发布,项目只配置 `infly.dockerRelease` 时保持原有单镜像质量发布。目标化发布先单选 target,再多选该 target 的 components;默认不推送,`--push` 构建、验证后先推送不可变 `<完整40位提交版本>`,再更新 `latest`,组件显式设置 `mutableTags: false` 时只生成、推送不可变提交标签。`--dry-run` 只解析配置,不联网、不运行 Git/Docker、不创建目录。旧命令 `docker:release` 仅作为目标化发布兼容别名保留,不再用于新脚本。
284
294
 
295
+ 目标化发布按“冻结所有来源 → 构建并校验所有组件 → 推送所有组件”执行。此前逐组件获取分支、构建并立即推送;现在同源组件共享一次冻结提交,任一组件构建或校验失败时整组不会开始推送。单组件的提交标签与可选 latest 顺序、旧 Compose 入口的版本语义保持不变。多个 Registry push 没有事务性:推送途中失败可能已经留下部分镜像,命令会失败且不显示成功汇总;部署端仍须在更新容器前确认整组镜像齐备。可选 `tagPrefix` 只改变提交标签形式,详见下文字段说明。
296
+
285
297
  当 Docker 配置较大时,推荐在 `package.json` 只保留配置入口和真正需要被 Jenkins 直接读取的部署差异:
286
298
 
287
299
  ```json
@@ -401,15 +413,16 @@ targets:
401
413
  - `compose`:组件构建配置来源,必须指定 `file` 和 `service`。工具从 Compose 服务读取镜像仓库、上下文、Dockerfile、stage 与构建参数;组件显式字段仍可覆盖解析结果。
402
414
  - `target` / `buildArgs`:分别映射到 `docker buildx build --target` 和 `--build-arg`;使用 `compose` 时通常无需重复填写。
403
415
  - `platform`:可选 Docker 构建平台,例如 `linux/amd64`;映射到 `docker buildx build --platform`。这里的组件字段不同于 CLI 的 `--platform` target 兼容别名。
404
- - `mutableTags`:默认 `true`,保持 commit + latest 双标签;设为 `false` 时只构建和推送完整 40 位 commit 标签。
416
+ - `mutableTags`:默认 `true`,保持提交版本 + latest 双标签;设为 `false` 时不生成或推送 latest。
417
+ - `tagPrefix`:可选的提交版本标签前缀,例如 `qc-` 生成 `qc-<完整40位commit>`,供独立质量门禁通过后晋升。默认不加前缀,保持既有标签语义;只改变镜像标签,OCI revision/version、输出和返回值中的 commit 仍为裸 40 位提交号。前缀须为 1 到 88 位 Docker 标签合法字符,不能以 `.` 或 `-` 开头。隔离镜像建议同时设置 `mutableTags: false`;工具不会自动执行质量门禁或晋升。
405
418
  - `requiredFiles`:构建前必须存在的源码仓相对路径,例如前端产物的 `index.html`;缺失时停止构建。
406
419
  - `pushBranch` / `pushRef`:target 级可选推送门禁,必须成对配置,例如 `develop` 与 `origin/develop`。仅 `--push` 时要求当前分支匹配、主动 fetch 对应 remote/branch,并要求本地 HEAD 与远端提交相同;`--no-push` 仍允许在其他分支本地验证镜像。
407
420
  - `requirements`:target 级可选本机工具最低版本,目前只支持 `node`、`pnpm` 和 `>=x.y.z` 格式。
408
421
  - `preBuild`:target 级可选准备命令列表。原有命令参数数组继续表示始终执行,例如 `["pnpm", "run", "build:test"]`;需要兼容根 monorepo 与独立子仓时,可使用 `{ "when": "standalone", "command": ["pnpm", "install", "--frozen-lockfile"] }`,其中 `when` 支持 `always`、`monorepo`、`standalone`。它与 `buildStrategy` 共用同一个模式探测器,避免宿主机准备步骤和 Docker context 判断漂移。命令在干净工作树和推送门禁之后、Docker 检查与 `requiredFiles` 校验之前执行;配置具有代码执行权限,必须与源码一样评审。
409
- - `source`:可选独立源码仓;`directory` 支持单个路径或按优先级排列的候选路径数组,路径均从项目目录解析,采用第一个包含 `.git` 的目录。fetch 后使用指定分支的临时 detached worktree,不切换当前开发分支。交互终端找不到候选仓库时会列出已检查路径、展示路径示例并等待手动输入;取消或非交互环境仍明确说明未执行构建或推送,打印编号化的 clone、fetch 和重跑步骤,全部构建停止,CLI 返回 2。
422
+ - `source`:可选独立源码仓;`directory` 支持单个路径或按优先级排列的候选路径数组,路径均从项目目录解析,采用第一个包含 `.git` 的目录。同一次调用中,解析后目录与 branch 相同的组件只 fetch 一次、解析一次完整提交号并共用一个 detached worktree;worktree 直接使用冻结 SHA,不随 origin 分支后续变化,也不切换当前开发分支。所有来源在首个镜像构建之前冻结;临时目录仅在本次调用结束后清理,worktree 清理失败会保留父目录并报告恢复路径。交互终端找不到候选仓库时会列出已检查路径、展示路径示例并等待手动输入;取消或非交互环境仍明确说明未执行构建或推送,打印编号化的 clone、fetch 和重跑步骤,全部构建停止,CLI 返回 2。
410
423
  - `targetPresets` 与 `targets.*.extends`:可选的具名公共目标配置。preset 可以继续 `extends` 另一个 preset;目标只继承显式指定的 preset,未声明 `extends` 的历史目标不受影响。同名普通对象递归合并;数组、字符串、数字、布尔值和 `null` 由下层整项替换,不按数组下标混合。未知 preset 或循环继承直接失败。本地构建、Compose 发布和部署包生成共用同一解析规则。
411
424
  - `releaseScripts`:可选的组件重跑脚本覆盖。默认从项目 scripts 自动识别严格匹配 `release:<组件>:docker` 的脚本,例如 `release:backend:docker`;源码仓缺失时提示 `pnpm run <脚本> -- --platform ...`。只有脚本名称不遵循约定时才需要显式配置;无匹配时提示通用 `pnpm exec infly-libs release:docker` 命令。
412
- - 无 `source` 时构建当前项目,要求干净工作树;通常配置组件 `expectedRef` 并要求 HEAD 与其相同。target 已配置 `pushBranch` / `pushRef` 时可以省略组件 `expectedRef`,推送同步由 target 门禁负责。有 `source` 时校验临时工作树对应的 origin 分支。
425
+ - 无 `source` 时构建当前项目,要求干净工作树;通常配置组件 `expectedRef` 并要求 HEAD 与其相同。target 已配置 `pushBranch` / `pushRef` 时可以省略组件 `expectedRef`,推送同步由 target 门禁负责。有 `source` 时校验临时工作树与已冻结的远端分支提交一致。当前项目与 monorepo 上下文也会记录初始提交,在构建前及推送前检查工作树与提交未变化;它们仍使用本地上下文,不另外创建整个 monorepo 的 worktree。
413
426
  - `check`:可选镜像内校验,使用 `entrypoint`、`args` 数组及 `addHosts` 数组;失败不推送。配置命令具有代码执行权限,应与源码一样评审,不能来自不可信输入。
414
427
  - `deployment`:仅用于部署包生成;`ready=false` 会阻止生成。可设置 `lockName`,默认 `.infly-release.lock`。服务归属和 imageEnv 必须唯一。
415
428
  - `runtimeEnv`:可选的服务器运行时环境文件白名单。`sourceFile` 必须是部署目录内已存在的总环境文件,公共脚本不会创建它,并在校验通过后收紧为 600 权限;`targetFile` 是自动生成的应用专用文件。`variables` 默认必需且按 `name` 输出,可用 `sources` 声明按顺序读取的候选源变量,用 `optional=true` 声明可选项。源文件不存在、不是普通文件、必需变量缺失/为空/重复时,在拉取或重建容器前失败;生成使用临时文件原子替换并设置 600 权限。失败时恢复已有专用文件;若这是首次生成且容器已经开始重建,则保留新文件,保证旧镜像可继续通过同一挂载路径回滚。脚本不执行 `source`,也不输出变量值。
package/bin/cli.js CHANGED
@@ -162,6 +162,16 @@ async function runTargetReleaseCommand(args) {
162
162
  async function main(argv = process.argv.slice(2)) {
163
163
  const command = argv[0];
164
164
  const commandMap = {
165
+ "release:notification": () => {
166
+ const args = argv.slice(1);
167
+ const input = optionValue(args, "--input");
168
+ const output = optionValue(args, "--output");
169
+ if (!input || !output) throw new Error("release:notification 必须提供 --input 与 --output;只生成 JSON,不发送通知");
170
+ const { createReleasePayload } = require("../build/release-result");
171
+ const payload = createReleasePayload(JSON.parse(fs.readFileSync(input, "utf8")));
172
+ fs.writeFileSync(output, JSON.stringify(payload), { encoding: "utf8", mode: 0o600 });
173
+ return payload;
174
+ },
165
175
  "docker:config": () => {
166
176
  const { parseReleaseArgs } = require("../build/docker/target-release");
167
177
  const options = parseReleaseArgs(argv.slice(1));
@@ -0,0 +1,26 @@
1
+ const modes = new Map([
2
+ ["test", "stage"],
3
+ ["stage", "stage"],
4
+ ["staging", "stage"],
5
+ ["pro", "prod"],
6
+ ["prod", "prod"],
7
+ ["production", "prod"],
8
+ ]);
9
+
10
+ function resolveBuildMode(modeArg, lifecycleEvent = "") {
11
+ // 显式环境优先,未知参数不再通过命令名猜测环境。
12
+ if (modeArg) {
13
+ return modes.get(modeArg) || "";
14
+ }
15
+
16
+ const fields = lifecycleEvent.split(":");
17
+ if (!fields.includes("build") && !fields.includes("release")) {
18
+ return "";
19
+ }
20
+
21
+ const inferredModes = new Set(fields.map((field) => modes.get(field)).filter(Boolean));
22
+ // 命令名同时包含测试和正式环境字段时,交给原有校验提示处理。
23
+ return inferredModes.size === 1 ? [...inferredModes][0] : "";
24
+ }
25
+
26
+ module.exports = { resolveBuildMode };
@@ -0,0 +1,18 @@
1
+ function applyBuildConfigDefaults(config) {
2
+ const buildConfigs = config.buildConfigs || {};
3
+
4
+ return {
5
+ ...config,
6
+ buildConfigs: {
7
+ gitAutoPushReposBranchMap: { master: "master", develop: "develop" },
8
+ ...buildConfigs,
9
+ // 默认映射只声明可构建分支;不能因此隐式启用产物仓推送。
10
+ gitAutoPushRepos:
11
+ buildConfigs.gitAutoPushRepos === undefined
12
+ ? buildConfigs.gitAutoPushReposBranchMap || false
13
+ : buildConfigs.gitAutoPushRepos,
14
+ },
15
+ };
16
+ }
17
+
18
+ module.exports = { applyBuildConfigDefaults };
@@ -22,8 +22,11 @@ const { zipSync } = require("./zip.js");
22
22
  const { buildList } = require("../../script");
23
23
  const { init: previewInit } = require("../../adapters/vue2/project-preview.js");
24
24
  const { postVersionFileAndMsg } = require("../build-utils/webhook-single.js");
25
+ const { resolveWebhookUrl } = require("../release-result");
25
26
  const { scriptWrite, targetProjectFileResolve, currentProjectFileResolve } = require("../project-files.js");
26
27
  const { shouldManageBuildScripts } = require("./script-management.js");
28
+ const { applyBuildConfigDefaults } = require("./config.js");
29
+ const { resolveBuildMode } = require("./build-mode.js");
27
30
  const {
28
31
  autoBranchProcess,
29
32
  autoGitProcess,
@@ -162,25 +165,7 @@ function getNextStandaloneServerPath(distPath) {
162
165
  }
163
166
 
164
167
  function getBuildMode() {
165
- const modeArg = getArgValue("--mode");
166
- const lifecycleText = [process.env.npm_lifecycle_event, process.env.npm_lifecycle_script, ...process.argv]
167
- .filter(Boolean)
168
- .join(" ");
169
-
170
- if (modeArg === "staging" || lifecycleText.includes("build:stage") || lifecycleText.includes("--mode staging")) {
171
- return "stage";
172
- }
173
-
174
- if (
175
- modeArg === "production" ||
176
- modeArg === "prod" ||
177
- lifecycleText.includes("build:prod") ||
178
- lifecycleText.includes("build:pro")
179
- ) {
180
- return "prod";
181
- }
182
-
183
- return "";
168
+ return resolveBuildMode(getArgValue("--mode"), process.env.npm_lifecycle_event);
184
169
  }
185
170
 
186
171
  function getStageBranch(branchMap = {}, branch = currentBranch) {
@@ -296,7 +281,7 @@ async function init() {
296
281
  exec(`explorer ${outputDir}`);
297
282
  }
298
283
 
299
- if (webhookUrl) {
284
+ if (resolveWebhookUrl({ webhookUrl })) {
300
285
  const webhookParams = {
301
286
  projectName,
302
287
  newFileName,
@@ -336,6 +321,8 @@ function normalizeBuildConfig(config, packageKey, branch, title) {
336
321
  normalizedConfig = normalizedConfig[packageKey];
337
322
  }
338
323
 
324
+ normalizedConfig = applyBuildConfigDefaults(normalizedConfig);
325
+
339
326
  // 自动启用 gitAutoPushRepos
340
327
  if (!normalizedConfig.gitAutoPushRepos && normalizedConfig.gitAutoPushReposBranchMap) {
341
328
  normalizedConfig.gitAutoPushRepos = true;
@@ -416,9 +403,8 @@ async function validateConfig(buildConfig, targetBranch = currentBranch) {
416
403
  }
417
404
 
418
405
  const buildMode = getBuildMode();
419
- const lifecycleEvent = process.env.npm_lifecycle_event || "";
420
- const isProdBuild = buildMode === "prod" || lifecycleEvent.includes("prod");
421
- const isStageBuild = buildMode === "stage" || lifecycleEvent.includes("stage");
406
+ const isProdBuild = buildMode === "prod";
407
+ const isStageBuild = buildMode === "stage";
422
408
 
423
409
  if (targetBranch === "master" && !isProdBuild) {
424
410
  console.error(global.logColor.error, `❌ 目标分支为 master 分支,请使用正式环境构建命令进行构建`);
@@ -1,136 +1,4 @@
1
- function shouldSkipWebhook() {
2
- const args = process.argv || [];
3
- const hasNoWebhookArg = args.some((arg = "") =>
4
- ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg)
5
- );
6
-
7
- const env = process.env || {};
8
- const envValues = [
9
- env.npm_config_nowebhook,
10
- env.npm_config_noWebhook,
11
- env.NO_WEBHOOK,
12
- env.DISABLE_WEBHOOK
13
- ];
14
- const hasNoWebhookEnv = envValues.some((value) => {
15
- const normalized = String(value || "").toLowerCase();
16
- return ["1", "true", "yes", "on"].includes(normalized);
17
- });
18
-
19
- return hasNoWebhookArg || hasNoWebhookEnv;
20
- }
21
-
22
- function getWebhookMessage() {
23
- const args = process.argv || [];
24
- const env = process.env || {};
25
- const messageEnv =
26
- env.npm_config_m ||
27
- env.npm_config_message ||
28
- env.WEBHOOK_MESSAGE ||
29
- env.BUILD_MESSAGE ||
30
- "";
31
-
32
- if (messageEnv) {
33
- return String(messageEnv).trim();
34
- }
35
-
36
- for (let index = 0; index < args.length; index += 1) {
37
- const arg = args[index] || "";
38
-
39
- if (arg === "-m" || arg === "--message") {
40
- return String(args[index + 1] || "").trim();
41
- }
42
-
43
- if (arg.startsWith("-m=")) {
44
- return arg.slice(3).trim();
45
- }
46
-
47
- if (arg.startsWith("--message=")) {
48
- return arg.slice(10).trim();
49
- }
50
- }
51
-
52
- return "";
53
- }
54
-
55
- function postVersionFileAndMsg(publishText, extraParams = {}) {
56
- const {
57
- projectName,
58
- newFileName,
59
- gitInfo,
60
- webhookUrl = "", // 启用企业微信推送
61
- webhookAtUser = [],
62
- webhookExtraText = "",
63
- gitAutoPushRepos,
64
- gitAutoPushReposBranchMap,
65
- repos,
66
- deployUrl = ""
67
- } = extraParams || {};
68
- const { branch, commitMsg, author } = gitInfo || {};
69
- const webhookMessage = getWebhookMessage();
70
- const GITPATH = `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`;
71
- const UPLOADURL = `https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=&type=file`;
72
- /* const data = {
73
- msgtype: "markdown",
74
- markdown: {
75
- content: `${publishText}\n构建文件:[点击下载](${GITPATH})`,
76
- },
77
- };
78
- if (Array.isArray(webhookAtUser) && webhookAtUser.length > 0) {
79
- webhookAtUser.forEach((item, index) => {
80
- data.markdown.content = `${data.markdown.content}\n<@${item}>`;
81
- });
82
- } */
83
- let content = publishText;
84
- if (gitAutoPushReposBranchMap) {
85
- content = [
86
- publishText,
87
- `构建文件:已推送对应仓库【${repos}】- 分支【${gitAutoPushReposBranchMap[branch]}】`,
88
- `构建人:${author}`,
89
- deployUrl ? `部署系统:${deployUrl}` : ""
90
- ].filter(Boolean).join("\n");
91
- } else {
92
- content = `${publishText}\n构建文件下载地址:${GITPATH}\n${webhookExtraText}\n`;
93
- }
94
-
95
- if (webhookMessage) {
96
- content = `${content}\n${webhookMessage}`;
97
- }
98
-
99
- // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
100
- content = (content || "").replace(/%s/g, "");
101
-
102
- const data = {
103
- msgtype: "text",
104
- text: {
105
- content,
106
- mentioned_mobile_list: Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[branch] // 支持按分支配置不同的提醒人
107
- }
108
- };
109
-
110
- if (shouldSkipWebhook()) {
111
- console.log(global.logColor?.info || "%s", "🔕 已跳过企业微信机器人推送(nowebhook)");
112
- return;
113
- }
114
-
115
- try {
116
- const axios = require("axios");
117
-
118
- if (axios) {
119
- axios
120
- .post(webhookUrl, data, {
121
- headers: {
122
- "Content-Type": "application/json"
123
- }
124
- })
125
- .catch((e) => {
126
- console.error("请求出错:", e);
127
- });
128
- }
129
- } catch (error) {
130
- console.error("axios is not available, please install it.");
131
- }
132
- }
133
-
134
- module.exports = {
135
- postVersionFileAndMsg
136
- };
1
+ // 兼容历史调用路径;正文组织、凭据注入与发送逻辑统一由 webhook 维护。
2
+ const { postVersionFileAndMsg } = require("./webhook");
3
+
4
+ module.exports = { postVersionFileAndMsg };
@@ -1,24 +1,49 @@
1
1
  const fs = require("fs");
2
+ const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
2
3
 
3
- function shouldSkipWebhook(args) {
4
- return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg));
4
+ function shouldSkipWebhook(args = process.argv, env = process.env) {
5
+ return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
+ || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
+ .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
5
8
  }
6
9
 
7
- function getVersionFromRecord(record) {
8
- const fileName = record.extraParams?.newFileName || "";
9
- const match = fileName.match(/-v([^-.]+(?:\.[^-.]+)*)-/);
10
- return match ? match[1] : "";
10
+ function getWebhookMessage(args = process.argv, env = process.env) {
11
+ const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
+ if (configured) return String(configured).trim();
13
+ for (let index = 0; index < args.length; index++) {
14
+ const arg = args[index] || "";
15
+ if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
+ if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
+ if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
+ }
19
+ return "";
11
20
  }
12
21
 
13
- function getProjectLine(record) {
14
- const { projectName, gitInfo = {}, repos } = record.extraParams || {};
15
- const version = getVersionFromRecord(record);
16
- const branch = gitInfo.branch || "";
17
- const repoText = repos ? `,构建仓库:${repos}` : "";
18
- return `- ${projectName || "unknown"}${version ? ` v${version}` : ""}${branch ? ` ${branch}` : ""}${repoText}`;
22
+ async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
+ const env = dependencies.env || process.env;
24
+ const logger = dependencies.logger || console;
25
+ const webhookUrl = resolveWebhookUrl(options, env);
26
+ if (!webhookUrl) return false;
27
+ const { webhookAtUser = [], gitInfo = {} } = options;
28
+ const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
+ try {
30
+ const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
+ msgtype: "text", text: {
32
+ content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
+ },
34
+ }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
+ if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
+ return true;
37
+ } catch (error) {
38
+ // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
+ const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
+ logger.error("企业微信推送失败", code);
41
+ return false;
42
+ }
19
43
  }
20
44
 
21
45
  function getRecordContent(record, deployUrl) {
46
+ if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
22
47
  const { publishText = "", extraParams = {} } = record || {};
23
48
  const {
24
49
  gitInfo = {},
@@ -56,8 +81,8 @@ function getRecordContent(record, deployUrl) {
56
81
  .join("\n");
57
82
  }
58
83
 
59
- async function postBatchWebhook(batchWebhookFile, extraArgs, mode) {
60
- if (shouldSkipWebhook(extraArgs)) {
84
+ async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
+ if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
61
86
  console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
62
87
  return;
63
88
  }
@@ -77,43 +102,34 @@ async function postBatchWebhook(batchWebhookFile, extraArgs, mode) {
77
102
  }
78
103
 
79
104
  const [firstRecord] = records;
80
- const { webhookUrl, webhookAtUser = [], gitInfo = {}, deployUrl = "" } =
105
+ const { deployUrl = "" } =
81
106
  firstRecord.extraParams || {};
82
107
 
83
- if (!webhookUrl) {
84
- return;
85
- }
86
-
87
108
  let content = [
88
109
  records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
89
110
  ].join("\n");
90
111
  // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
91
112
  content = (content || "").replace(/%s/g, "");
92
- const mentionedMobileList = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
93
-
94
- try {
95
- await require("axios").post(
96
- webhookUrl,
97
- {
98
- msgtype: "text",
99
- text: {
100
- content,
101
- mentioned_mobile_list: mentionedMobileList
102
- }
103
- },
104
- {
105
- headers: {
106
- "Content-Type": "application/json"
107
- }
108
- }
109
- );
113
+ if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
110
114
  console.log("\n已发送批量构建企业微信汇总推送");
111
- } catch (error) {
112
- console.error("企业微信汇总推送失败", error.message);
113
115
  }
114
116
  }
115
117
 
118
+ function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
+ const env = dependencies.env || process.env;
120
+ const args = dependencies.args || process.argv;
121
+ if (shouldSkipWebhook(args, env)) return;
122
+ let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
+ const message = getWebhookMessage(args, env);
124
+ if (message && !extraParams.releaseResult) content += `\n${message}`;
125
+ return sendWebhookContent(content, extraParams, dependencies);
126
+ }
127
+
116
128
  module.exports = {
117
129
  getRecordContent,
130
+ getWebhookMessage,
131
+ shouldSkipWebhook,
132
+ sendWebhookContent,
133
+ postVersionFileAndMsg,
118
134
  postBatchWebhook
119
135
  };
@@ -113,7 +113,7 @@ const SAFE_GIT_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
113
113
  const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
114
114
  const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
115
115
  const WINDOWS_PACKAGE_MANAGERS = new Set(["npm", "npx", "pnpm", "yarn"]);
116
- const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!\"]/;
116
+ const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!"]/;
117
117
  const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
118
118
  const BUILD_STRATEGIES = new Set(["artifact", "source"]);
119
119
 
@@ -278,6 +278,10 @@ function validateComponent(component, name, guardedByProfile = false) {
278
278
  if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
279
279
  throw new Error(`${name} mutableTags 必须是布尔值`);
280
280
  }
281
+ if (component.tagPrefix != null && (typeof component.tagPrefix !== "string"
282
+ || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,87}$/.test(component.tagPrefix))) {
283
+ throw new Error(`${name} tagPrefix 必须是 1 到 88 位合法 Docker 标签前缀`);
284
+ }
281
285
  if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
282
286
  throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
283
287
  }
@@ -421,27 +425,68 @@ async function runTargetRelease(options = {}, dependencies = {}) {
421
425
  }
422
426
  await checkDocker(run, projectDir, true, dependencies);
423
427
  const results = [];
424
- for (const item of plan) {
425
- let tempRoot;
426
- let worktree;
427
- let sourceDir = projectDir;
428
- try {
429
- if (item.source) {
430
- run("git", ["-C", item.source.directory, "fetch", "origin"], { cwd: projectDir });
431
- tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
432
- const candidate = path.join(tempRoot, "source");
433
- run("git", ["-C", item.source.directory, "worktree", "add", "--detach", candidate, `origin/${item.source.branch}`], { cwd: projectDir });
434
- worktree = candidate;
435
- sourceDir = worktree;
428
+ const sources = new Map();
429
+ const workspaces = new Map();
430
+ const resources = [];
431
+ const verifyFrozen = ({ sourceDir, commit }, name) => {
432
+ const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
433
+ if (git("status", "--porcelain", "--untracked-files=all")
434
+ || git("rev-parse", "HEAD").toLowerCase() !== commit) {
435
+ throw new Error(`${name} 源码在冻结后发生变化,已停止本组构建及推送`);
436
+ }
437
+ };
438
+ let releaseError;
439
+ try {
440
+ // 所有来源先冻结,再开始任何镜像构建。相同仓库和分支只 fetch 一次,
441
+ // worktree 使用完整 SHA,后续远端分支前移不会把同一组镜像拆成不同版本。
442
+ for (const item of plan) {
443
+ const directory = item.source?.directory || projectDir;
444
+ const sourceKey = JSON.stringify([directory, item.source?.branch || null]);
445
+ let frozen = sources.get(sourceKey);
446
+ if (!frozen) {
447
+ let sourceDir = projectDir;
448
+ let commit;
449
+ if (item.source) {
450
+ run("git", ["-C", directory, "fetch", "origin"], { cwd: projectDir });
451
+ commit = capture("git", ["-C", directory, "rev-parse", `origin/${item.source.branch}^{commit}`]).toLowerCase();
452
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
453
+ const tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
454
+ sourceDir = path.join(tempRoot, "source");
455
+ // add 失败时也保留清理记录;不能安全移除 worktree 时留下目录供人工恢复。
456
+ resources.push({ tempRoot, worktree: sourceDir, repository: directory });
457
+ run("git", ["-C", directory, "worktree", "add", "--detach", sourceDir, commit], { cwd: projectDir });
458
+ } else {
459
+ commit = capture("git", ["-C", sourceDir, "rev-parse", "HEAD"]).toLowerCase();
460
+ }
461
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
462
+ frozen = { sourceDir, commit };
463
+ sources.set(sourceKey, frozen);
436
464
  }
437
- const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
465
+ const git = (...args) => capture("git", ["-C", frozen.sourceDir, ...args]);
438
466
  if (git("status", "--porcelain", "--untracked-files=all")) throw new Error(`${item.name} 仓库存在未提交改动`);
439
- const commit = git("rev-parse", "HEAD").toLowerCase();
440
- const expectedRef = item.source ? `origin/${item.source.branch}` : item.expectedRef;
441
- if (!/^[a-f0-9]{40}$/.test(commit) || (expectedRef
442
- && commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase())) {
443
- throw new Error(`${item.name} HEAD 与 ${expectedRef} 不一致,请先核对并 fetch 对应仓库`);
467
+ const expectedRef = item.source ? null : item.expectedRef;
468
+ if (git("rev-parse", "HEAD").toLowerCase() !== frozen.commit || (expectedRef
469
+ && frozen.commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase())) {
470
+ throw new Error(`${item.name} HEAD 与 ${expectedRef || "冻结提交"} 不一致,请先核对并 fetch 对应仓库`);
471
+ }
472
+ item.frozen = frozen;
473
+ if (!item.source && item.buildStrategy === "source" && releaseContext.mode === "monorepo") {
474
+ const contextRoot = releaseContext.contextRoot;
475
+ let workspace = workspaces.get(contextRoot);
476
+ if (!workspace) {
477
+ const revision = capture("git", ["-C", contextRoot, "rev-parse", "HEAD"]).toLowerCase();
478
+ if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
479
+ workspace = { sourceDir: contextRoot, commit: revision };
480
+ verifyFrozen(workspace, `${item.name} 的 monorepo 构建上下文`);
481
+ workspaces.set(contextRoot, workspace);
482
+ }
483
+ item.workspace = workspace;
444
484
  }
485
+ }
486
+ for (const item of plan) {
487
+ const { sourceDir, commit } = item.frozen;
488
+ let tempRoot;
489
+ verifyFrozen(item.frozen, item.name);
445
490
  if (item.source) {
446
491
  const sourceLabel = item.name === "backend" ? "后端" : (item.label || item.name);
447
492
  log(`\x1b[0;32m✓ ${sourceLabel}构建分支:${item.source.branch}\x1b[0m`);
@@ -456,20 +501,15 @@ async function runTargetRelease(options = {}, dependencies = {}) {
456
501
  let dockerfile = inside(sourceDir, item.dockerfile || "Dockerfile");
457
502
  let workspaceRevision;
458
503
  if (buildStrategy === "source" && componentReleaseContext.mode === "monorepo") {
459
- const workspaceChanges = capture("git", ["-C", context, "status", "--porcelain", "--untracked-files=all"]);
460
- if (workspaceChanges) {
461
- throw new Error(`${item.name} 的 monorepo 构建上下文存在未提交改动`);
462
- }
463
- workspaceRevision = capture("git", ["-C", context, "rev-parse", "HEAD"]).toLowerCase();
464
- if (!/^[a-f0-9]{40}$/.test(workspaceRevision)) {
465
- throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
466
- }
504
+ verifyFrozen(item.workspace, `${item.name} 的 monorepo 构建上下文`);
505
+ workspaceRevision = item.workspace.commit;
467
506
  const prepared = (dependencies.prepareMinimalMonorepoContext || prepareMinimalMonorepoContext)({
468
507
  workspaceRoot: componentReleaseContext.contextRoot,
469
508
  projectDir: sourceDir,
470
509
  io,
471
510
  });
472
511
  tempRoot = prepared.contextRoot;
512
+ resources.push({ tempRoot });
473
513
  context = prepared.contextRoot;
474
514
  dockerfile = inside(context, `${prepared.projectRelativeDir}/${item.dockerfile || "Dockerfile"}`);
475
515
  log(`最小上下文: ${prepared.projectRelativeDir} + packages + 根锁文件`);
@@ -478,7 +518,10 @@ async function runTargetRelease(options = {}, dependencies = {}) {
478
518
  if (!io.existsSync(inside(sourceDir, file))) throw new Error(`缺少必需构建产物: ${file}`);
479
519
  }
480
520
  if (item.files) {
481
- tempRoot ||= io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
521
+ if (!tempRoot) {
522
+ tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
523
+ resources.push({ tempRoot });
524
+ }
482
525
  context = path.join(tempRoot, "context");
483
526
  io.mkdirSync(context, { recursive: true });
484
527
  for (const file of item.files) {
@@ -491,7 +534,7 @@ async function runTargetRelease(options = {}, dependencies = {}) {
491
534
  dockerfile = inside(context, item.dockerfile || "Dockerfile");
492
535
  }
493
536
  if (!io.existsSync(dockerfile)) throw new Error(`缺少 Dockerfile: ${dockerfile}`);
494
- const image = `${item.repository}:${commit}`;
537
+ const image = `${item.repository}:${item.tagPrefix || ""}${commit}`;
495
538
  const latestImage = item.mutableTags === false ? null : `${item.repository}:latest`;
496
539
  // --load 只把当前构建节点平台的镜像载入本地镜像存储;发布流程直接使用单平台镜像。
497
540
  const buildOptions = ["buildx", "build", "--load", "--file", dockerfile];
@@ -519,20 +562,42 @@ async function runTargetRelease(options = {}, dependencies = {}) {
519
562
  const hosts = (item.check.addHosts || []).flatMap((host) => ["--add-host", host]);
520
563
  run("docker", ["run", "--rm", ...hosts, "--entrypoint", item.check.entrypoint, image, ...item.check.args], { cwd: projectDir });
521
564
  }
522
- if (options.push) {
523
- run("docker", ["push", image], { cwd: projectDir });
524
- if (latestImage) run("docker", ["push", latestImage], { cwd: projectDir });
525
- }
526
565
  log(`${item.name}_commit=${commit}`);
527
566
  log(`${item.name}=${image}`);
528
567
  if (latestImage) log(`${item.name}_latest=${latestImage}`);
529
- results.push({ component: item.name, commit, image, latestImage, pushed: Boolean(options.push) });
530
- } finally {
531
- // 只移除本次创建的隔离 worktree;清理失败保留目录供人工恢复,绝不清空开发工作区。
532
- if (worktree) run("git", ["-C", item.source.directory, "worktree", "remove", "--force", worktree], { cwd: projectDir });
533
- if (tempRoot) io.rmSync(tempRoot, { recursive: true, force: true });
568
+ results.push({ component: item.name, commit, image, latestImage, pushed: false });
569
+ }
570
+ for (const frozen of sources.values()) verifyFrozen(frozen, frozen.sourceDir);
571
+ for (const frozen of workspaces.values()) verifyFrozen(frozen, "monorepo 构建上下文");
572
+ // 整组构建及校验通过后才推送。Registry 的多次 push 不具备事务性,
573
+ // 网络失败可能留下部分镜像;不打印成功汇总,部署端仍需校验整组镜像齐备。
574
+ if (options.push) {
575
+ for (const result of results) {
576
+ run("docker", ["push", result.image], { cwd: projectDir });
577
+ if (result.latestImage) run("docker", ["push", result.latestImage], { cwd: projectDir });
578
+ result.pushed = true;
579
+ }
534
580
  }
581
+ } catch (error) {
582
+ releaseError = error;
583
+ } finally {
584
+ const cleanupErrors = [];
585
+ for (const resource of resources.reverse()) {
586
+ try {
587
+ // 只移除本次创建的隔离 worktree;移除失败时不删除其父目录。
588
+ if (resource.worktree) run("git", ["-C", resource.repository, "worktree", "remove", "--force", resource.worktree], { cwd: projectDir });
589
+ io.rmSync(resource.tempRoot, { recursive: true, force: true });
590
+ } catch (error) {
591
+ log(`临时构建目录清理失败,已保留恢复路径:${resource.tempRoot}`);
592
+ cleanupErrors.push(new Error(`清理失败,保留恢复路径:${resource.tempRoot}`, { cause: error }));
593
+ }
594
+ }
595
+ if (cleanupErrors.length) releaseError = new globalThis.AggregateError(
596
+ [...(releaseError ? [releaseError] : []), ...cleanupErrors],
597
+ [releaseError?.message, ...cleanupErrors.map((error) => error.message)].filter(Boolean).join(";"),
598
+ );
535
599
  }
600
+ if (releaseError) throw releaseError;
536
601
 
537
602
  // 构建结果汇总(排版与 build:docker 保持一致:✅ 完成 + 可用标签 + 可选发布系统链接)。
538
603
  // 构建时已逐组件打印 frontend_commit= 等机器行,供失败前人工留档;这里汇总为可直接复制到
@@ -0,0 +1,37 @@
1
+ // 通知只投影已确认的结果字段;凭据与环境变量全集不得进入结果正文。
2
+ const RESULT_FIELDS = [
3
+ ['project', '项目'], ['environment', '环境'], ['components', '组件'],
4
+ ['status', '状态'], ['sourceVersion', '源码版本'], ['imageVersion', '镜像版本'],
5
+ ['buildNumber', '构建号'], ['actor', '触发人'], ['note', '发布说明'], ['logUrl', '日志链接'],
6
+ ];
7
+
8
+ function display(value) {
9
+ if (Array.isArray(value)) return value.map(display).join(', ');
10
+ if (value == null || value === '') return '未解析';
11
+ if (!['string', 'number', 'boolean'].includes(typeof value)) throw new Error('通知字段必须是文本、数字或文本数组');
12
+ return String(value).replace(/[\r\n\u0000-\u001f\u007f]+/g, ' ').trim() || '未解析';
13
+ }
14
+
15
+ function safeLogUrl(value) {
16
+ if (!value) return '未解析';
17
+ let url;
18
+ try { url = new URL(value); } catch { throw new Error('通知日志链接必须是有效 HTTP(S) URL'); }
19
+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error('通知日志链接必须是 HTTP(S) URL');
20
+ url.username = ''; url.password = ''; url.search = ''; url.hash = '';
21
+ return url.toString();
22
+ }
23
+
24
+ function formatReleaseResult(result) {
25
+ if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error('通知结果必须为对象');
26
+ return RESULT_FIELDS.map(([name, label]) => `${label}:${name === 'logUrl' ? safeLogUrl(result[name]) : display(result[name])}`).join('\n');
27
+ }
28
+
29
+ function createReleasePayload(result) {
30
+ return { msgtype: 'text', text: { content: formatReleaseResult(result) } };
31
+ }
32
+
33
+ function resolveWebhookUrl(options = {}, env = process.env) {
34
+ return env.RELEASE_WEBHOOK_URL || env.WECOM_WEBHOOK_URL || options.webhookUrl || '';
35
+ }
36
+
37
+ module.exports = { createReleasePayload, formatReleaseResult, resolveWebhookUrl };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infly/libs",
3
- "version": "2.2.15",
3
+ "version": "2.3.0",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",