@infly/libs 2.2.16 → 2.4.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 适配器仅服务脱离
@@ -284,6 +292,8 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
284
292
 
285
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` 仅作为目标化发布兼容别名保留,不再用于新脚本。
286
294
 
295
+ 目标化发布按“冻结所有来源 → 构建并校验所有组件 → 推送所有组件”执行。此前逐组件获取分支、构建并立即推送;现在同源组件共享一次冻结提交,任一组件构建或校验失败时整组不会开始推送。单组件的提交标签与可选 latest 顺序、旧 Compose 入口的版本语义保持不变。多个 Registry push 没有事务性:推送途中失败可能已经留下部分镜像,命令会失败且不显示成功汇总;部署端仍须在更新容器前确认整组镜像齐备。可选 `tagPrefix` 只改变提交标签形式,详见下文字段说明。
296
+
287
297
  当 Docker 配置较大时,推荐在 `package.json` 只保留配置入口和真正需要被 Jenkins 直接读取的部署差异:
288
298
 
289
299
  ```json
@@ -403,15 +413,16 @@ targets:
403
413
  - `compose`:组件构建配置来源,必须指定 `file` 和 `service`。工具从 Compose 服务读取镜像仓库、上下文、Dockerfile、stage 与构建参数;组件显式字段仍可覆盖解析结果。
404
414
  - `target` / `buildArgs`:分别映射到 `docker buildx build --target` 和 `--build-arg`;使用 `compose` 时通常无需重复填写。
405
415
  - `platform`:可选 Docker 构建平台,例如 `linux/amd64`;映射到 `docker buildx build --platform`。这里的组件字段不同于 CLI 的 `--platform` target 兼容别名。
406
- - `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`;工具不会自动执行质量门禁或晋升。
407
418
  - `requiredFiles`:构建前必须存在的源码仓相对路径,例如前端产物的 `index.html`;缺失时停止构建。
408
419
  - `pushBranch` / `pushRef`:target 级可选推送门禁,必须成对配置,例如 `develop` 与 `origin/develop`。仅 `--push` 时要求当前分支匹配、主动 fetch 对应 remote/branch,并要求本地 HEAD 与远端提交相同;`--no-push` 仍允许在其他分支本地验证镜像。
409
420
  - `requirements`:target 级可选本机工具最低版本,目前只支持 `node`、`pnpm` 和 `>=x.y.z` 格式。
410
421
  - `preBuild`:target 级可选准备命令列表。原有命令参数数组继续表示始终执行,例如 `["pnpm", "run", "build:test"]`;需要兼容根 monorepo 与独立子仓时,可使用 `{ "when": "standalone", "command": ["pnpm", "install", "--frozen-lockfile"] }`,其中 `when` 支持 `always`、`monorepo`、`standalone`。它与 `buildStrategy` 共用同一个模式探测器,避免宿主机准备步骤和 Docker context 判断漂移。命令在干净工作树和推送门禁之后、Docker 检查与 `requiredFiles` 校验之前执行;配置具有代码执行权限,必须与源码一样评审。
411
- - `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。
412
423
  - `targetPresets` 与 `targets.*.extends`:可选的具名公共目标配置。preset 可以继续 `extends` 另一个 preset;目标只继承显式指定的 preset,未声明 `extends` 的历史目标不受影响。同名普通对象递归合并;数组、字符串、数字、布尔值和 `null` 由下层整项替换,不按数组下标混合。未知 preset 或循环继承直接失败。本地构建、Compose 发布和部署包生成共用同一解析规则。
413
424
  - `releaseScripts`:可选的组件重跑脚本覆盖。默认从项目 scripts 自动识别严格匹配 `release:<组件>:docker` 的脚本,例如 `release:backend:docker`;源码仓缺失时提示 `pnpm run <脚本> -- --platform ...`。只有脚本名称不遵循约定时才需要显式配置;无匹配时提示通用 `pnpm exec infly-libs release:docker` 命令。
414
- - 无 `source` 时构建当前项目,要求干净工作树;通常配置组件 `expectedRef` 并要求 HEAD 与其相同。target 已配置 `pushBranch` / `pushRef` 时可以省略组件 `expectedRef`,推送同步由 target 门禁负责。有 `source` 时校验临时工作树对应的 origin 分支。
425
+ - 无 `source` 时构建当前项目,要求干净工作树;通常配置组件 `expectedRef` 并要求 HEAD 与其相同。target 已配置 `pushBranch` / `pushRef` 时可以省略组件 `expectedRef`,推送同步由 target 门禁负责。有 `source` 时校验临时工作树与已冻结的远端分支提交一致。当前项目与 monorepo 上下文也会记录初始提交,在构建前及推送前检查工作树与提交未变化;它们仍使用本地上下文,不另外创建整个 monorepo 的 worktree。
415
426
  - `check`:可选镜像内校验,使用 `entrypoint`、`args` 数组及 `addHosts` 数组;失败不推送。配置命令具有代码执行权限,应与源码一样评审,不能来自不可信输入。
416
427
  - `deployment`:仅用于部署包生成;`ready=false` 会阻止生成。可设置 `lockName`,默认 `.infly-release.lock`。服务归属和 imageEnv 必须唯一。
417
428
  - `runtimeEnv`:可选的服务器运行时环境文件白名单。`sourceFile` 必须是部署目录内已存在的总环境文件,公共脚本不会创建它,并在校验通过后收紧为 600 权限;`targetFile` 是自动生成的应用专用文件。`variables` 默认必需且按 `name` 输出,可用 `sources` 声明按顺序读取的候选源变量,用 `optional=true` 声明可选项。源文件不存在、不是普通文件、必需变量缺失/为空/重复时,在拉取或重建容器前失败;生成使用临时文件原子替换并设置 600 权限。失败时恢复已有专用文件;若这是首次生成且容器已经开始重建,则保留新文件,保证旧镜像可继续通过同一挂载路径回滚。脚本不执行 `source`,也不输出变量值。
@@ -436,3 +447,13 @@ infly-libs docker:bundle --target demo --dry-run
436
447
  `release:docker` 不是强制构建入口。独立源码仓可以直接使用 Dockerfile 或 Compose 构建,但若镜像要进入这里生成的部署流程,必须自行保证仓库名、不可变完整 40 位提交标签以及 `org.opencontainers.image.revision`、`org.opencontainers.image.version`、`com.infly.platform` 标签与目标配置一致;公共发布入口只是自动化这些校验和映射。部署侧仅为既有镜像保留旧 12 位标签兼容,新构建不再生成 12 位标签。
437
448
 
438
449
  远端发布持锁后读取全部组件镜像基线,保存 .release-history;配置 `runtimeEnv` 时先从服务器总环境文件按白名单原子生成应用专用文件,再仅更新传入组件的服务(up -d --no-deps)。首次接入可由发布入口显式传入 `--initialize-baseline`:仅在 `deploy.env` 不存在时,从配置声明的运行中服务读取唯一且仓库匹配的 RepoDigest,保存权限受限的 `.onboarding-backup` 接入证据并原子创建基线;已有基线时拒绝覆盖,未显式初始化时仍要求基线预先存在。失败恢复镜像环境文件、应用专用环境文件及选中服务;回滚验证失败明确报错。不创建总环境文件,不创建/修改数据库,不更新未配置的基础设施。服务器不需要 npm/Node,仍需 Bash、Docker Compose 和 curl。
450
+
451
+ ### 部署仓拥有镜像打包规则
452
+
453
+ 外部源码组件可声明 `buildStrategy: source`、`dockerfileFromConfig: Dockerfile.web` 和 `contextFiles: [{from: nginx.conf, to: nginx.conf}]`。Dockerfile 和 from 相对部署仓根目录,to 相对业务源码根目录;不能同时声明 dockerfile,不能越界、写 Git 元数据或跟随越界链接。公共工具将部署文件注入临时上下文,不改写业务工作树或冻结 worktree。
454
+
455
+ 源码仍按 source.directory/source.branch 冻结。monorepo 保留根公共包/锁文件,并用冻结快照替换业务目录;独立仓直接使用冻结源码。OCI revision 取业务提交,`com.infly.deployment.revision` 取部署仓提交,monorepo 额外包含 workspace revision。配置和源码在推送前再次验证。
456
+
457
+ `source.standalone: true` 可显式使用独立源码上下文,即使业务仓位于 monorepo 中也不带根公共包;适用于已有独立安装契约的紧急构建。target 的 `recordConfigurationRevision: true` 则让未注入文件的外部源码组件也记录并复核部署仓提交。两者均为可选布尔值,默认保持原有行为。
458
+
459
+ 组件可声明 `health: {timeoutSeconds: 60, addHost: api:127.0.0.1}`,复用运行镜像的 HEALTHCHECK,失败不推送本组任何镜像。普通 check 仍用于语法或文件检查;不要对后端启动真实业务进程作本地镜像探针。
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));
@@ -22,6 +22,7 @@ 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");
27
28
  const { applyBuildConfigDefaults } = require("./config.js");
@@ -280,7 +281,7 @@ async function init() {
280
281
  exec(`explorer ${outputDir}`);
281
282
  }
282
283
 
283
- if (webhookUrl) {
284
+ if (resolveWebhookUrl({ webhookUrl })) {
284
285
  const webhookParams = {
285
286
  projectName,
286
287
  newFileName,
@@ -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
  };
@@ -49,6 +49,7 @@ function copyEntry(io, workspaceRoot, contextRoot, relative) {
49
49
  function prepareMinimalMonorepoContext({
50
50
  workspaceRoot,
51
51
  projectDir,
52
+ sourceDir,
52
53
  io = fs,
53
54
  temporaryRoot = os.tmpdir(),
54
55
  } = {}) {
@@ -62,7 +63,14 @@ function prepareMinimalMonorepoContext({
62
63
  try {
63
64
  for (const entry of ROOT_ENTRIES) copyEntry(io, resolvedWorkspace, contextRoot, entry);
64
65
  if (!projectRelativeDir.startsWith(`packages${path.sep}`)) {
65
- copyEntry(io, resolvedWorkspace, contextRoot, projectRelativeDir);
66
+ if (sourceDir) {
67
+ // 部署仓冻结业务源码后,以该快照替换业务目录,公共包仍来自已核验的根工作区。
68
+ const destination = path.join(contextRoot, projectRelativeDir);
69
+ io.mkdirSync(path.dirname(destination), { recursive: true });
70
+ io.cpSync(sourceDir, destination, { recursive: true, dereference: false, filter: shouldCopy });
71
+ } else {
72
+ copyEntry(io, resolvedWorkspace, contextRoot, projectRelativeDir);
73
+ }
66
74
  }
67
75
  return { contextRoot, projectRelativeDir: projectRelativeDir.split(path.sep).join("/") };
68
76
  } catch (error) {
@@ -4,7 +4,7 @@ const path = require("node:path");
4
4
  const { execFileSync } = require("node:child_process");
5
5
  const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../../cli/select-option");
6
6
  const { composeRelease } = require("./compose-release");
7
- const { formatCicdLink } = require("./docker-build-push");
7
+ const { formatCicdLink, healthCheckImage } = require("./docker-build-push");
8
8
  const { loadDockerConfig } = require("./config-loader");
9
9
  const { detectReleaseContext, detectReleaseMode } = require("./release-mode");
10
10
  const { prepareMinimalMonorepoContext } = require("./minimal-context");
@@ -89,6 +89,24 @@ function inside(root, relative) {
89
89
  return result;
90
90
  }
91
91
 
92
+ function confinedPath(root, relative, io = fs) {
93
+ const candidate = inside(root, relative);
94
+ let existing = candidate;
95
+ while (existing !== root && !io.existsSync(existing)) {
96
+ if (io.lstatSync) {
97
+ try {
98
+ if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
99
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
100
+ }
101
+ existing = path.dirname(existing);
102
+ }
103
+ if (io.realpathSync && io.existsSync(existing)) {
104
+ const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
105
+ if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
106
+ }
107
+ return candidate;
108
+ }
109
+
92
110
  function normalizeSourceDirectories(value, name) {
93
111
  const directories = Array.isArray(value) ? value : [value];
94
112
  if (!directories.length || directories.some((item) => typeof item !== "string" || !item.trim())) {
@@ -113,7 +131,7 @@ const SAFE_GIT_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
113
131
  const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
114
132
  const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
115
133
  const WINDOWS_PACKAGE_MANAGERS = new Set(["npm", "npx", "pnpm", "yarn"]);
116
- const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!\"]/;
134
+ const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!"]/;
117
135
  const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
118
136
  const BUILD_STRATEGIES = new Set(["artifact", "source"]);
119
137
 
@@ -129,6 +147,9 @@ function normalizePreBuildCommand(value, target) {
129
147
  }
130
148
 
131
149
  function validateReleaseProfile(profile, target) {
150
+ if (profile.recordConfigurationRevision != null && typeof profile.recordConfigurationRevision !== "boolean") {
151
+ throw new Error(`${target} recordConfigurationRevision 必须是布尔值`);
152
+ }
132
153
  if (profile.pushBranch != null && (typeof profile.pushBranch !== "string"
133
154
  || !SAFE_GIT_NAME.test(profile.pushBranch) || profile.pushBranch.startsWith("-")
134
155
  || profile.pushBranch.includes(".."))) {
@@ -262,11 +283,35 @@ function validateComponent(component, name, guardedByProfile = false) {
262
283
  }
263
284
  if (component.source) {
264
285
  normalizeSourceDirectories(component.source.directory, name);
286
+ if (component.source.standalone != null && typeof component.source.standalone !== "boolean") {
287
+ throw new Error(`${name} source.standalone 必须是布尔值`);
288
+ }
265
289
  if (!component.source.branch || component.source.branch.startsWith("-")) {
266
290
  throw new Error(`${name} source 必须配置合法 branch`);
267
291
  }
268
292
  }
269
293
  inside("/config", component.dockerfile || "Dockerfile");
294
+ if (component.dockerfileFromConfig != null) {
295
+ inside("/config", component.dockerfileFromConfig);
296
+ if (!component.source || component.buildStrategy !== "source" || component.dockerfile != null) {
297
+ throw new Error(`${name} dockerfileFromConfig 只支持外部源码构建,不能同时配置 dockerfile`);
298
+ }
299
+ }
300
+ if (component.contextFiles != null) {
301
+ if (!component.source || component.buildStrategy !== "source" || !Array.isArray(component.contextFiles)
302
+ || !component.contextFiles.length) throw new Error(`${name} contextFiles 只支持外部源码构建的非空列表`);
303
+ const destinations = new Set();
304
+ for (const entry of component.contextFiles) {
305
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
306
+ || Object.keys(entry).some((key) => !["from", "to"].includes(key))) throw new Error(`${name} contextFiles 仅支持 from/to`);
307
+ inside("/config", entry.from); inside("/config", entry.to);
308
+ const destination = path.normalize(entry.to);
309
+ if (destination === "." || destination.split(path.sep).includes(".git") || destinations.has(destination)) {
310
+ throw new Error(`${name} contextFiles 目标不能为根、Git 元数据或重复路径`);
311
+ }
312
+ destinations.add(destination);
313
+ }
314
+ }
270
315
  inside("/config", component.context || ".");
271
316
  if (component.target != null && (typeof component.target !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(component.target))) {
272
317
  throw new Error(`${name} target 必须是合法 Docker stage`);
@@ -278,6 +323,10 @@ function validateComponent(component, name, guardedByProfile = false) {
278
323
  if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
279
324
  throw new Error(`${name} mutableTags 必须是布尔值`);
280
325
  }
326
+ if (component.tagPrefix != null && (typeof component.tagPrefix !== "string"
327
+ || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,87}$/.test(component.tagPrefix))) {
328
+ throw new Error(`${name} tagPrefix 必须是 1 到 88 位合法 Docker 标签前缀`);
329
+ }
281
330
  if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
282
331
  throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
283
332
  }
@@ -305,6 +354,16 @@ function validateComponent(component, name, guardedByProfile = false) {
305
354
  throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 数组`);
306
355
  }
307
356
  }
357
+ if (component.health != null) {
358
+ const health = component.health;
359
+ if (!health || typeof health !== "object" || Array.isArray(health)
360
+ || Object.keys(health).some((key) => !["timeoutSeconds", "addHost"].includes(key))
361
+ || !Number.isInteger(health.timeoutSeconds) || health.timeoutSeconds < 1 || health.timeoutSeconds > 600
362
+ || (health.addHost != null && (typeof health.addHost !== "string"
363
+ || !/^[A-Za-z0-9][A-Za-z0-9._-]*:(?:[A-Fa-f0-9:.]+|host-gateway)$/.test(health.addHost)))) {
364
+ throw new Error(`${name} health 必须声明 1 到 600 秒的 timeoutSeconds 及可选 addHost`);
365
+ }
366
+ }
308
367
  }
309
368
 
310
369
  function execute(command, args, options = {}) {
@@ -421,64 +480,139 @@ async function runTargetRelease(options = {}, dependencies = {}) {
421
480
  }
422
481
  await checkDocker(run, projectDir, true, dependencies);
423
482
  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;
483
+ const sources = new Map();
484
+ const workspaces = new Map();
485
+ const resources = [];
486
+ const verifyFrozen = ({ sourceDir, commit }, name) => {
487
+ const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
488
+ if (git("status", "--porcelain", "--untracked-files=all")
489
+ || git("rev-parse", "HEAD").toLowerCase() !== commit) {
490
+ throw new Error(`${name} 源码在冻结后发生变化,已停止本组构建及推送`);
491
+ }
492
+ };
493
+ let releaseError;
494
+ try {
495
+ let configuration;
496
+ if (profile.recordConfigurationRevision || plan.some((item) => item.dockerfileFromConfig || item.contextFiles)) {
497
+ const commit = capture("git", ["-C", projectDir, "rev-parse", "HEAD"]).toLowerCase();
498
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error("无法冻结部署配置版本");
499
+ configuration = { sourceDir: projectDir, commit };
500
+ verifyFrozen(configuration, "部署配置");
501
+ workspaces.set(projectDir, configuration);
502
+ }
503
+ // 所有来源先冻结,再开始任何镜像构建。相同仓库和分支只 fetch 一次,
504
+ // worktree 使用完整 SHA,后续远端分支前移不会把同一组镜像拆成不同版本。
505
+ for (const item of plan) {
506
+ const directory = item.source?.directory || projectDir;
507
+ const sourceKey = JSON.stringify([directory, item.source?.branch || null]);
508
+ let frozen = sources.get(sourceKey);
509
+ if (!frozen) {
510
+ let sourceDir = projectDir;
511
+ let commit;
512
+ if (item.source) {
513
+ run("git", ["-C", directory, "fetch", "origin"], { cwd: projectDir });
514
+ commit = capture("git", ["-C", directory, "rev-parse", `origin/${item.source.branch}^{commit}`]).toLowerCase();
515
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
516
+ const tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
517
+ sourceDir = path.join(tempRoot, "source");
518
+ // add 失败时也保留清理记录;不能安全移除 worktree 时留下目录供人工恢复。
519
+ resources.push({ tempRoot, worktree: sourceDir, repository: directory });
520
+ run("git", ["-C", directory, "worktree", "add", "--detach", sourceDir, commit], { cwd: projectDir });
521
+ } else {
522
+ commit = capture("git", ["-C", sourceDir, "rev-parse", "HEAD"]).toLowerCase();
523
+ }
524
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
525
+ frozen = { sourceDir, commit };
526
+ sources.set(sourceKey, frozen);
436
527
  }
437
- const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
528
+ const git = (...args) => capture("git", ["-C", frozen.sourceDir, ...args]);
438
529
  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 对应仓库`);
530
+ const expectedRef = item.source ? null : item.expectedRef;
531
+ if (git("rev-parse", "HEAD").toLowerCase() !== frozen.commit || (expectedRef
532
+ && frozen.commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase())) {
533
+ throw new Error(`${item.name} HEAD 与 ${expectedRef || "冻结提交"} 不一致,请先核对并 fetch 对应仓库`);
444
534
  }
535
+ item.frozen = frozen;
536
+ item.releaseContext = item.source
537
+ ? ((!item.source.standalone && (item.dockerfileFromConfig || item.contextFiles))
538
+ ? (dependencies.detectReleaseContext || detectReleaseContext)({ projectDir: item.source.directory })
539
+ : { mode: "standalone", contextRoot: frozen.sourceDir, projectRelativeDir: "." })
540
+ : releaseContext;
541
+ if (item.source && item.releaseContext.mode === "standalone") {
542
+ item.releaseContext = { ...item.releaseContext, contextRoot: frozen.sourceDir, projectRelativeDir: "." };
543
+ }
544
+ if (item.buildStrategy === "source" && item.releaseContext.mode === "monorepo") {
545
+ const contextRoot = item.releaseContext.contextRoot;
546
+ let workspace = workspaces.get(contextRoot);
547
+ if (!workspace) {
548
+ const revision = capture("git", ["-C", contextRoot, "rev-parse", "HEAD"]).toLowerCase();
549
+ if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
550
+ workspace = { sourceDir: contextRoot, commit: revision };
551
+ verifyFrozen(workspace, `${item.name} 的 monorepo 构建上下文`);
552
+ workspaces.set(contextRoot, workspace);
553
+ }
554
+ item.workspace = workspace;
555
+ }
556
+ }
557
+ for (const item of plan) {
558
+ const { sourceDir, commit } = item.frozen;
559
+ let tempRoot;
560
+ verifyFrozen(item.frozen, item.name);
445
561
  if (item.source) {
446
562
  const sourceLabel = item.name === "backend" ? "后端" : (item.label || item.name);
447
563
  log(`\x1b[0;32m✓ ${sourceLabel}构建分支:${item.source.branch}\x1b[0m`);
448
564
  }
449
565
  const buildStrategy = item.buildStrategy || "artifact";
450
- const componentReleaseContext = item.source
451
- ? { mode: "standalone", contextRoot: sourceDir, projectRelativeDir: "." }
452
- : releaseContext;
566
+ const componentReleaseContext = item.releaseContext;
453
567
  let context = buildStrategy === "source"
454
568
  ? componentReleaseContext.contextRoot
455
569
  : inside(sourceDir, item.context || ".");
456
570
  let dockerfile = inside(sourceDir, item.dockerfile || "Dockerfile");
457
571
  let workspaceRevision;
458
572
  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
- }
573
+ verifyFrozen(item.workspace, `${item.name} 的 monorepo 构建上下文`);
574
+ workspaceRevision = item.workspace.commit;
467
575
  const prepared = (dependencies.prepareMinimalMonorepoContext || prepareMinimalMonorepoContext)({
468
576
  workspaceRoot: componentReleaseContext.contextRoot,
469
- projectDir: sourceDir,
577
+ projectDir: item.source ? item.source.directory : sourceDir,
578
+ ...(item.source ? { sourceDir } : {}),
470
579
  io,
471
580
  });
472
581
  tempRoot = prepared.contextRoot;
582
+ resources.push({ tempRoot });
473
583
  context = prepared.contextRoot;
474
584
  dockerfile = inside(context, `${prepared.projectRelativeDir}/${item.dockerfile || "Dockerfile"}`);
475
585
  log(`最小上下文: ${prepared.projectRelativeDir} + packages + 根锁文件`);
476
586
  }
587
+ // 部署仓提供 Dockerfile/运行配置;独立模式也先复制上下文,绝不改写冻结源码。
588
+ if (item.contextFiles) {
589
+ if (!tempRoot) {
590
+ tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-context-"));
591
+ resources.push({ tempRoot });
592
+ context = path.join(tempRoot, "context");
593
+ io.cpSync(sourceDir, context, { recursive: true, dereference: false,
594
+ filter: (file) => !path.relative(sourceDir, file).split(path.sep).includes(".git") });
595
+ }
596
+ const destinationRoot = componentReleaseContext.mode === "monorepo"
597
+ ? inside(context, componentReleaseContext.projectRelativeDir) : context;
598
+ for (const entry of item.contextFiles) {
599
+ const from = confinedPath(projectDir, entry.from, io);
600
+ const to = confinedPath(destinationRoot, entry.to, io);
601
+ if (!io.existsSync(from)) throw new Error(`缺少部署构建文件: ${entry.from}`);
602
+ io.mkdirSync(path.dirname(to), { recursive: true });
603
+ io.cpSync(from, to, { recursive: true, dereference: true,
604
+ filter: (file) => { confinedPath(projectDir, path.relative(projectDir, file), io); return true; } });
605
+ }
606
+ }
607
+ if (item.dockerfileFromConfig) dockerfile = confinedPath(projectDir, item.dockerfileFromConfig, io);
477
608
  for (const file of item.requiredFiles || []) {
478
609
  if (!io.existsSync(inside(sourceDir, file))) throw new Error(`缺少必需构建产物: ${file}`);
479
610
  }
480
611
  if (item.files) {
481
- tempRoot ||= io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
612
+ if (!tempRoot) {
613
+ tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
614
+ resources.push({ tempRoot });
615
+ }
482
616
  context = path.join(tempRoot, "context");
483
617
  io.mkdirSync(context, { recursive: true });
484
618
  for (const file of item.files) {
@@ -491,7 +625,7 @@ async function runTargetRelease(options = {}, dependencies = {}) {
491
625
  dockerfile = inside(context, item.dockerfile || "Dockerfile");
492
626
  }
493
627
  if (!io.existsSync(dockerfile)) throw new Error(`缺少 Dockerfile: ${dockerfile}`);
494
- const image = `${item.repository}:${commit}`;
628
+ const image = `${item.repository}:${item.tagPrefix || ""}${commit}`;
495
629
  const latestImage = item.mutableTags === false ? null : `${item.repository}:latest`;
496
630
  // --load 只把当前构建节点平台的镜像载入本地镜像存储;发布流程直接使用单平台镜像。
497
631
  const buildOptions = ["buildx", "build", "--load", "--file", dockerfile];
@@ -510,6 +644,7 @@ async function runTargetRelease(options = {}, dependencies = {}) {
510
644
  run("docker", [...buildOptions,
511
645
  "--label", `org.opencontainers.image.revision=${commit}`, "--label", `org.opencontainers.image.version=${commit}`,
512
646
  ...(workspaceRevision ? ["--label", `com.infly.workspace.revision=${workspaceRevision}`] : []),
647
+ ...(configuration ? ["--label", `com.infly.deployment.revision=${configuration.commit}`] : []),
513
648
  "--label", `com.infly.platform=${target}`, "--tag", image,
514
649
  ...(latestImage ? ["--tag", latestImage] : []), context], { cwd: projectDir });
515
650
  if (capture("docker", ["image", "inspect", "--format", '{{ index .Config.Labels "org.opencontainers.image.revision" }}', image]) !== commit) {
@@ -519,20 +654,47 @@ async function runTargetRelease(options = {}, dependencies = {}) {
519
654
  const hosts = (item.check.addHosts || []).flatMap((host) => ["--add-host", host]);
520
655
  run("docker", ["run", "--rm", ...hosts, "--entrypoint", item.check.entrypoint, image, ...item.check.args], { cwd: projectDir });
521
656
  }
522
- if (options.push) {
523
- run("docker", ["push", image], { cwd: projectDir });
524
- if (latestImage) run("docker", ["push", latestImage], { cwd: projectDir });
657
+ if (item.health) {
658
+ await (dependencies.healthCheckImage || healthCheckImage)(image, {
659
+ cwd: projectDir, healthTimeout: String(item.health.timeoutSeconds), healthAddHost: item.health.addHost,
660
+ });
525
661
  }
526
662
  log(`${item.name}_commit=${commit}`);
527
663
  log(`${item.name}=${image}`);
528
664
  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 });
665
+ results.push({ component: item.name, commit, image, latestImage, pushed: false });
666
+ }
667
+ for (const frozen of sources.values()) verifyFrozen(frozen, frozen.sourceDir);
668
+ for (const frozen of workspaces.values()) verifyFrozen(frozen, "monorepo 构建上下文");
669
+ // 整组构建及校验通过后才推送。Registry 的多次 push 不具备事务性,
670
+ // 网络失败可能留下部分镜像;不打印成功汇总,部署端仍需校验整组镜像齐备。
671
+ if (options.push) {
672
+ for (const result of results) {
673
+ run("docker", ["push", result.image], { cwd: projectDir });
674
+ if (result.latestImage) run("docker", ["push", result.latestImage], { cwd: projectDir });
675
+ result.pushed = true;
676
+ }
534
677
  }
678
+ } catch (error) {
679
+ releaseError = error;
680
+ } finally {
681
+ const cleanupErrors = [];
682
+ for (const resource of resources.reverse()) {
683
+ try {
684
+ // 只移除本次创建的隔离 worktree;移除失败时不删除其父目录。
685
+ if (resource.worktree) run("git", ["-C", resource.repository, "worktree", "remove", "--force", resource.worktree], { cwd: projectDir });
686
+ io.rmSync(resource.tempRoot, { recursive: true, force: true });
687
+ } catch (error) {
688
+ log(`临时构建目录清理失败,已保留恢复路径:${resource.tempRoot}`);
689
+ cleanupErrors.push(new Error(`清理失败,保留恢复路径:${resource.tempRoot}`, { cause: error }));
690
+ }
691
+ }
692
+ if (cleanupErrors.length) releaseError = new globalThis.AggregateError(
693
+ [...(releaseError ? [releaseError] : []), ...cleanupErrors],
694
+ [releaseError?.message, ...cleanupErrors.map((error) => error.message)].filter(Boolean).join(";"),
695
+ );
535
696
  }
697
+ if (releaseError) throw releaseError;
536
698
 
537
699
  // 构建结果汇总(排版与 build:docker 保持一致:✅ 完成 + 可用标签 + 可选发布系统链接)。
538
700
  // 构建时已逐组件打印 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.16",
3
+ "version": "2.4.0",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",