@infly/libs 2.5.0 → 2.6.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.
@@ -62,7 +62,9 @@ function composeRelease(options = {}, dependencies = {}) {
62
62
  const resolved = resolveComposePath(projectDir, file);
63
63
  const original = fs.readFileSync(resolved.composePath, "utf8");
64
64
  const updated = bumpComposeImageVersion(original, bump);
65
- const baseArgs = ["compose", "-f", resolved.composePath];
65
+ const commands = ["config", "build", ...(push ? ["push"] : [])]
66
+ .map((command) => ["compose", "-f", resolved.composePath, command]);
67
+ const result = { ...updated, ...resolved };
66
68
 
67
69
  if (bump === "none") {
68
70
  console.log(`Version fixed: ${updated.from}`);
@@ -71,24 +73,20 @@ function composeRelease(options = {}, dependencies = {}) {
71
73
  }
72
74
 
73
75
  if (dryRun) {
74
- console.log(`[dry-run] docker ${[...baseArgs, "config"].join(" ")}`);
75
- console.log(`[dry-run] docker ${[...baseArgs, "build"].join(" ")}`);
76
- if (push) console.log(`[dry-run] docker ${[...baseArgs, "push"].join(" ")}`);
77
- return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
76
+ for (const args of commands) console.log(`[dry-run] docker ${args.join(" ")}`);
77
+ return result;
78
78
  }
79
79
 
80
80
  const versionChanged = updated.content !== original;
81
81
  if (versionChanged) fs.writeFileSync(resolved.composePath, updated.content, "utf8");
82
82
  try {
83
- runDocker([...baseArgs, "config"], { cwd: resolved.projectDir });
84
- runDocker([...baseArgs, "build"], { cwd: resolved.projectDir });
85
- if (push) runDocker([...baseArgs, "push"], { cwd: resolved.projectDir });
83
+ for (const args of commands) runDocker(args, { cwd: resolved.projectDir });
86
84
  } catch (error) {
87
85
  if (versionChanged) fs.writeFileSync(resolved.composePath, original, "utf8");
88
86
  throw error;
89
87
  }
90
88
 
91
- return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
89
+ return result;
92
90
  }
93
91
 
94
92
  module.exports = {
@@ -23,9 +23,44 @@ cleanup() {
23
23
  }
24
24
  trap cleanup EXIT
25
25
 
26
+ push_release_image() {
27
+ local help api_versions client_api server_api api platform_supported=true
28
+ help=$(docker push --help) || return 1
29
+ if [[ "$help" == *--platform* ]]; then
30
+ api_versions=$(docker version --format '{{.Client.APIVersion}} {{.Server.APIVersion}}') || return 1
31
+ read -r client_api server_api <<< "$api_versions"
32
+ for api in "$client_api" "$server_api" "${DOCKER_API_VERSION:-1.46}"; do
33
+ [[ "$api" =~ ^([0-9]+)\.([0-9]+)$ ]] || {
34
+ echo "$component 无法确定 Docker push API 兼容性" >&2
35
+ return 1
36
+ }
37
+ if ((10#${BASH_REMATCH[1]} < 1 || (10#${BASH_REMATCH[1]} == 1 && 10#${BASH_REMATCH[2]} < 46))); then
38
+ platform_supported=false
39
+ fi
40
+ done
41
+ else
42
+ platform_supported=false
43
+ fi
44
+ if [[ "$platform_supported" == true ]]; then
45
+ # containerd 拉取的镜像可能保留未完整下载的索引;正式标签只推送已核验镜像的平台清单。
46
+ # 平台来自镜像 ID,不能假定 Jenkins 主机或业务镜像使用 amd64。
47
+ echo "$component 按已核验平台晋升镜像: $source_platform"
48
+ docker push --platform "$source_platform" "$final_image"
49
+ else
50
+ # 旧 CLI/API 保留原有单镜像推送;真实推送失败立即停止,不再降级重试。
51
+ echo "$component Docker CLI/API 不支持指定平台推送,使用兼容的单镜像推送"
52
+ docker push "$final_image"
53
+ fi
54
+ }
55
+
26
56
  docker manifest inspect "$source_image" >/dev/null
27
57
  docker pull "$source_image"
28
- actual_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$source_image")
58
+ source_id=$(docker image inspect --format '{{.Id}}' "$source_image")
59
+ [[ "$source_id" =~ ^sha256:[0-9a-f]{64}$ ]] || {
60
+ echo "$component qc 镜像 ID 无效" >&2
61
+ exit 1
62
+ }
63
+ actual_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$source_id")
29
64
  if [[ "$actual_revision" != "$expected_revision" ]]; then
30
65
  echo "$component qc 镜像完整 revision 校验失败: image=$source_image" >&2
31
66
  exit 1
@@ -48,10 +83,45 @@ if ! grep -Eqi 'manifest unknown|no such manifest|manifest[^[:cntrl:]]*not found
48
83
  exit 1
49
84
  fi
50
85
 
51
- # 本地构建只推送当前构建节点平台的 qc 镜像;Jenkins 门禁通过后才允许创建不可变正式标签。
52
- # 单平台镜像已完整拉取到本地,可直接重新标记并推送,无需在 Jenkins 节点安装 Buildx。
53
- docker tag "$source_image" "$final_image"
54
- docker push "$final_image"
86
+ if docker buildx version >/dev/null 2>&1; then
87
+ if [[ "$source_image" == *@* ]]; then
88
+ source_digest=${source_image##*@}
89
+ source_repository=${source_image%@*}
90
+ [[ -n "$source_repository" && "$source_repository" != *@* ]] || exit 1
91
+ else
92
+ # printf 前缀兼容 Buildx v0.10.5,避免其把以 {{.Manifest 开头的格式当成固定展示模式。
93
+ source_digest=$(docker buildx imagetools inspect "$source_image" --format '{{printf "%s" .Manifest.Digest}}')
94
+ source_repository=$source_image
95
+ # 只移除最后一个路径段的标签,保留 registry:port 与未显式指定标签的仓库名。
96
+ if [[ "${source_repository##*/}" == *:* ]]; then source_repository=${source_repository%:*}; fi
97
+ fi
98
+ [[ "$source_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || {
99
+ echo "$component 无法冻结 qc 镜像 Registry digest" >&2
100
+ exit 1
101
+ }
102
+ frozen_source="$source_repository@$source_digest"
103
+ # 在冻结后重新拉取并校验;若 QC 标签在第一次校验后漂移,禁止复制另一个镜像。
104
+ docker pull "$frozen_source"
105
+ frozen_id=$(docker image inspect --format '{{.Id}}' "$frozen_source")
106
+ frozen_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$frozen_id")
107
+ if [[ "$frozen_id" != "$source_id" || "$frozen_revision" != "$expected_revision" ]]; then
108
+ echo "$component 冻结后的 qc 镜像与已核验镜像不一致,禁止晋升" >&2
109
+ exit 1
110
+ fi
111
+ echo "$component 从已冻结 Registry digest 晋升镜像: $frozen_source"
112
+ # 仓库端复制保留完整索引及附加证明,不依赖 Docker Engine 的 push --platform 能力。
113
+ # inspect/create 的真实错误立即停止,不切换到本地推送路径。
114
+ docker buildx imagetools create --tag "$final_image" "$frozen_source"
115
+ else
116
+ source_platform=$(docker image inspect --format '{{.Os}}/{{.Architecture}}{{if .Variant}}/{{.Variant}}{{end}}' "$source_id")
117
+ [[ "$source_platform" =~ ^[a-z0-9][a-z0-9_.-]*/[a-z0-9][a-z0-9_.-]*(/[a-z0-9][a-z0-9_.-]*)?$ ]] || {
118
+ echo "$component qc 镜像平台无效" >&2
119
+ exit 1
120
+ }
121
+ # 没有 Buildx 时以已核验的 ID 重标记,保留新旧 Docker CLI/API 兼容路径。
122
+ docker tag "$source_id" "$final_image"
123
+ push_release_image
124
+ fi
55
125
  docker pull "$final_image"
56
126
  final_revision=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$final_image")
57
127
  if [[ "$final_revision" != "$expected_revision" ]]; then
@@ -351,6 +351,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
351
351
  // 1. 检测运行模式并定位关键路径
352
352
  const cwd = path.resolve(process.cwd());
353
353
  const { isStandalone, contextRoot } = detectMode({ standalone });
354
+ const mode = isStandalone ? "standalone" : "monorepo";
354
355
 
355
356
  const appPkgPath = path.join(cwd, "package.json");
356
357
  if (!fs.existsSync(appPkgPath)) {
@@ -435,7 +436,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
435
436
  tags.forEach((tag) => buildArgs.push("-t", tag));
436
437
  buildArgs.push(
437
438
  "--build-arg", `GIT_COMMIT=${fullCommit}`,
438
- "--build-arg", `BUILD_MODE=${isStandalone ? "standalone" : "monorepo"}`,
439
+ "--build-arg", `BUILD_MODE=${mode}`,
439
440
  "--build-arg", `PROJECT_DIR=${projectDirArg}`,
440
441
  "--label", `org.opencontainers.image.revision=${fullCommit}`,
441
442
  "--label", `org.opencontainers.image.version=${commitHash}`
@@ -493,7 +494,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
493
494
  }
494
495
  console.log("");
495
496
 
496
- return { mode: isStandalone ? "standalone" : "monorepo", buildContext, imageName, commitHash, tags };
497
+ return { mode, buildContext, imageName, commitHash, tags };
497
498
  }
498
499
 
499
500
  module.exports = {
@@ -6,6 +6,8 @@ const { DEPENDENCY_SECTIONS, discoverWorkspacePackages } = require("../../worksp
6
6
  const { shouldCopy } = require("./minimal-context");
7
7
 
8
8
  const LOCAL_PACKAGES = ".infly-local-packages";
9
+ const LOCAL_MANIFESTS = ".infly-local-manifests";
10
+ const RELEASE_RECORD = ".infly-release.json";
9
11
 
10
12
  function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
11
13
 
@@ -23,18 +25,16 @@ function manifestsIn(directory) {
23
25
  const file = path.join(directory, entry.name);
24
26
  if (!shouldCopy(file) || entry.isSymbolicLink()) continue;
25
27
  if (entry.isDirectory()) result.push(...manifestsIn(file));
26
- else if (entry.name === "package.json") result.push({ manifest: readJson(file) });
28
+ else if (entry.name === "package.json") result.push(readJson(file));
27
29
  }
28
30
  return result;
29
31
  }
30
32
 
31
- /** 项目安装配置 + 按依赖闭包选取的公共源码;不读取父仓安装配置或锁文件。 */
32
- function prepareProjectInstallContext({ workspaceRoot, sourceDir,
33
- temporaryRoot = os.tmpdir() }) {
34
- const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, "infly-project-install-"));
33
+ function prepareInstallContext({ sourceDir, temporaryRoot, prefix, reserved, pnpmfileError }, prepare) {
34
+ const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, prefix));
35
35
  try {
36
- for (const reserved of [LOCAL_PACKAGES, ".infly-local-manifests", ".infly-release.json"]) {
37
- if (fs.existsSync(path.join(sourceDir, reserved))) throw new Error(`${reserved} 是构建保留目录`);
36
+ for (const [file, error] of reserved) {
37
+ if (fs.existsSync(path.join(sourceDir, file))) throw new Error(error);
38
38
  }
39
39
  copyTree(sourceDir, contextRoot);
40
40
  const configFile = path.join(contextRoot, "pnpm-workspace.yaml");
@@ -42,8 +42,23 @@ function prepareProjectInstallContext({ workspaceRoot, sourceDir,
42
42
  if (document.errors.length) throw document.errors[0];
43
43
  const config = document.toJS() || {};
44
44
  if (config.pnpmfile || fs.existsSync(path.join(contextRoot, ".pnpmfile.cjs"))) {
45
- throw new Error("projectInstall 要求项目自身不使用 pnpmfile");
45
+ throw new Error(pnpmfileError);
46
46
  }
47
+ const packages = prepare({ contextRoot, configFile, document, config });
48
+ return { contextRoot, projectRelativeDir: ".", packages };
49
+ } catch (error) {
50
+ fs.rmSync(contextRoot, { recursive: true, force: true });
51
+ throw error;
52
+ }
53
+ }
54
+
55
+ /** 项目安装配置 + 按依赖闭包选取的公共源码;不读取父仓安装配置或锁文件。 */
56
+ function prepareProjectInstallContext({ workspaceRoot, sourceDir, temporaryRoot = os.tmpdir() }) {
57
+ return prepareInstallContext({
58
+ sourceDir, temporaryRoot, prefix: "infly-project-install-",
59
+ reserved: [LOCAL_PACKAGES, LOCAL_MANIFESTS, RELEASE_RECORD].map((file) => [file, `${file} 是构建保留目录`]),
60
+ pnpmfileError: "projectInstall 要求项目自身不使用 pnpmfile",
61
+ }, ({ contextRoot, configFile, document, config }) => {
47
62
  const available = discoverWorkspacePackages(workspaceRoot);
48
63
  const byName = new Map();
49
64
  for (const pkg of available) {
@@ -57,7 +72,7 @@ function prepareProjectInstallContext({ workspaceRoot, sourceDir,
57
72
  }
58
73
  return [...names].filter((name) => byName.has(name));
59
74
  };
60
- const selected = new Set(manifestsIn(contextRoot).flatMap((pkg) => localDependencies(pkg.manifest)));
75
+ const selected = new Set(manifestsIn(contextRoot).flatMap(localDependencies));
61
76
  for (const name of selected) {
62
77
  const pkg = byName.get(name);
63
78
  // 公共包只参与源码消费,不安装其发布、测试等开发工具。
@@ -66,16 +81,18 @@ function prepareProjectInstallContext({ workspaceRoot, sourceDir,
66
81
  for (const dependency of localDependencies(manifest)) selected.add(dependency);
67
82
  }
68
83
  const packages = available.filter((pkg) => selected.has(pkg.name));
69
- fs.mkdirSync(path.join(contextRoot, ".infly-local-manifests"), { recursive: true });
84
+ const manifestRoot = path.join(contextRoot, LOCAL_MANIFESTS);
85
+ fs.mkdirSync(manifestRoot, { recursive: true });
70
86
  for (const pkg of packages) {
71
87
  const destination = path.join(contextRoot, LOCAL_PACKAGES, pkg.dir);
72
88
  copyTree(pkg.directoryPath, destination);
73
- const manifest = readJson(path.join(destination, "package.json"));
89
+ const manifestFile = path.join(destination, "package.json");
90
+ const manifest = readJson(manifestFile);
74
91
  delete manifest.devDependencies;
75
- fs.writeFileSync(path.join(destination, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
76
- const manifestDirectory = path.join(contextRoot, ".infly-local-manifests", pkg.dir);
92
+ fs.writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`);
93
+ const manifestDirectory = path.join(manifestRoot, pkg.dir);
77
94
  fs.mkdirSync(manifestDirectory, { recursive: true });
78
- fs.copyFileSync(path.join(destination, "package.json"), path.join(manifestDirectory, "package.json"));
95
+ fs.copyFileSync(manifestFile, path.join(manifestDirectory, "package.json"));
79
96
  }
80
97
  config.packages = [...(config.packages || []), `${LOCAL_PACKAGES}/*`];
81
98
  config.overrides = { ...(config.overrides || {}), ...Object.fromEntries(packages.map((pkg) => [pkg.name, "workspace:*"])) };
@@ -83,24 +100,17 @@ function prepareProjectInstallContext({ workspaceRoot, sourceDir,
83
100
  document.set("packages", config.packages);
84
101
  document.set("overrides", config.overrides);
85
102
  fs.writeFileSync(configFile, document.toString());
86
- return { contextRoot, projectRelativeDir: ".", packages: packages.map((pkg) => pkg.name) };
87
- } catch (error) {
88
- fs.rmSync(contextRoot, { recursive: true, force: true });
89
- throw error;
90
- }
103
+ return packages.map((pkg) => pkg.name);
104
+ });
91
105
  }
92
106
 
93
107
  /** 独立构建仅更新内部 npm 包;工作树清单与原锁均保持不变。 */
94
108
  function prepareStandaloneInstallContext({ sourceDir, registryManifest, temporaryRoot = os.tmpdir() }) {
95
- const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, "infly-standalone-install-"));
96
- try {
97
- if (fs.existsSync(path.join(sourceDir, ".infly-release.json"))) throw new Error(".infly-release.json 是构建保留文件");
98
- copyTree(sourceDir, contextRoot);
99
- const file = path.join(contextRoot, "pnpm-workspace.yaml");
100
- const document = yaml.parseDocument(fs.readFileSync(file, "utf8"));
101
- if (document.errors.length) throw document.errors[0];
102
- const config = document.toJS() || {};
103
- if (config.pnpmfile || fs.existsSync(path.join(contextRoot, ".pnpmfile.cjs"))) throw new Error("独立源码构建不加载 pnpmfile");
109
+ return prepareInstallContext({
110
+ sourceDir, temporaryRoot, prefix: "infly-standalone-install-",
111
+ reserved: [[RELEASE_RECORD, `${RELEASE_RECORD} 是构建保留文件`]],
112
+ pnpmfileError: "独立源码构建不加载 pnpmfile",
113
+ }, ({ contextRoot, configFile, document, config }) => {
104
114
  const lockFile = path.join(contextRoot, "pnpm-lock.yaml");
105
115
  const lock = yaml.parse(fs.readFileSync(lockFile, "utf8"));
106
116
  const queue = new Map();
@@ -108,7 +118,7 @@ function prepareStandaloneInstallContext({ sourceDir, registryManifest, temporar
108
118
  if (!queue.has(name)) queue.set(name, new Set());
109
119
  queue.get(name).add(String(range));
110
120
  };
111
- for (const { manifest } of manifestsIn(contextRoot)) {
121
+ for (const manifest of manifestsIn(contextRoot)) {
112
122
  for (const section of DEPENDENCY_SECTIONS) {
113
123
  for (const [name, range] of Object.entries(manifest[section] || {})) {
114
124
  if (name.startsWith("@infly/")) addRequirement(name, range);
@@ -149,15 +159,12 @@ function prepareStandaloneInstallContext({ sourceDir, registryManifest, temporar
149
159
  }
150
160
  config.overrides = { ...(config.overrides || {}), ...Object.fromEntries(packages.map(({ name, version }) => [name, version])) };
151
161
  document.set("overrides", config.overrides);
152
- fs.writeFileSync(file, document.toString());
162
+ fs.writeFileSync(configFile, document.toString());
153
163
  // 只补充本次内部包约束元数据;实际锁图仍由容器内 pnpm 生成并 frozen 复验。
154
164
  lock.overrides = config.overrides;
155
165
  fs.writeFileSync(lockFile, yaml.stringify(lock));
156
- return { contextRoot, projectRelativeDir: ".", packages };
157
- } catch (error) {
158
- fs.rmSync(contextRoot, { recursive: true, force: true });
159
- throw error;
160
- }
166
+ return packages;
167
+ });
161
168
  }
162
169
 
163
170
  module.exports = { LOCAL_PACKAGES, prepareProjectInstallContext, prepareStandaloneInstallContext };
@@ -71,18 +71,6 @@ function runShellCommand(command, label, cwd) {
71
71
  run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", command], label, cwd);
72
72
  }
73
73
 
74
- function runShellCommandAsync(command, label, cwd) {
75
- if (/[\r\n&|<>^]/.test(command)) {
76
- throw new Error(`${label}包含不安全的 Windows shell 字符`);
77
- }
78
- return runAsync(
79
- process.env.ComSpec || "cmd.exe",
80
- ["/d", "/s", "/c", command],
81
- label,
82
- cwd
83
- );
84
- }
85
-
86
74
  function buildPnpmScriptSpawn(scriptName) {
87
75
  if (!SAFE_SCRIPT_NAME.test(scriptName)) {
88
76
  throw new Error(`dockerRelease.checks 包含非法脚本名: ${scriptName}`);
@@ -102,11 +90,6 @@ function buildPnpmScriptSpawn(scriptName) {
102
90
  return { command: "pnpm", args: ["run", scriptName], label };
103
91
  }
104
92
 
105
- function runPnpmScript(scriptName, cwd) {
106
- const { command, args, label } = buildPnpmScriptSpawn(scriptName);
107
- run(command, args, label, cwd);
108
- }
109
-
110
93
  async function runPnpmScriptAsync(scriptName, cwd) {
111
94
  const { command, args, label } = buildPnpmScriptSpawn(scriptName);
112
95
  return runAsync(command, args, label, cwd);
@@ -116,11 +99,9 @@ async function runProjectChecks(scriptNames, cwd) {
116
99
  const results = await Promise.allSettled(
117
100
  scriptNames.map((scriptName) => runPnpmScriptAsync(scriptName, cwd))
118
101
  );
119
- const failures = results
120
- .map((result, index) => ({ result, scriptName: scriptNames[index] }))
121
- .filter(({ result }) => result.status === "rejected");
102
+ const failures = results.filter((result) => result.status === "rejected");
122
103
  if (failures.length === 0) return;
123
- const lines = failures.map(({ result }) => ` - ${result.reason.message}`);
104
+ const lines = failures.map(({ reason }) => ` - ${reason.message}`);
124
105
  throw new Error(
125
106
  `项目检查未全部通过(失败 ${failures.length}/${scriptNames.length}):\n${lines.join("\n")}`
126
107
  );
@@ -11,39 +11,21 @@ function detectReleaseContext({
11
11
  const resolvedProjectDir = path.resolve(projectDir);
12
12
  const projectGitRoot = resolveGitWorktreeRoot(resolvedProjectDir);
13
13
 
14
- if (standalone) {
15
- if (resolvedProjectDir !== projectGitRoot) {
16
- throw new Error("--standalone 必须在当前 Git 仓库根目录执行");
17
- }
18
- return {
19
- mode: "standalone",
20
- isStandalone: true,
21
- contextRoot: resolvedProjectDir,
22
- projectDir: resolvedProjectDir,
23
- projectRelativeDir: ".",
24
- };
14
+ if (standalone && resolvedProjectDir !== projectGitRoot) {
15
+ throw new Error("--standalone 必须在当前 Git 仓库根目录执行");
25
16
  }
26
17
 
27
- const outerWorkspaceRoot = findOuterWorkspaceRoot(projectGitRoot);
28
- if (outerWorkspaceRoot) {
29
- return {
30
- mode: "monorepo",
31
- isStandalone: false,
32
- contextRoot: outerWorkspaceRoot,
33
- projectDir: resolvedProjectDir,
34
- projectRelativeDir: path.relative(outerWorkspaceRoot, resolvedProjectDir).split(path.sep).join("/"),
35
- };
36
- }
37
-
38
- const isStandalone = resolvedProjectDir === projectGitRoot;
18
+ const workspaceRoot = standalone ? null : findOuterWorkspaceRoot(projectGitRoot);
19
+ const contextRoot = workspaceRoot || projectGitRoot;
20
+ const isStandalone = !workspaceRoot && resolvedProjectDir === projectGitRoot;
39
21
  return {
40
22
  mode: isStandalone ? "standalone" : "monorepo",
41
23
  isStandalone,
42
- contextRoot: isStandalone ? resolvedProjectDir : projectGitRoot,
24
+ contextRoot,
43
25
  projectDir: resolvedProjectDir,
44
26
  projectRelativeDir: isStandalone
45
27
  ? "."
46
- : path.relative(projectGitRoot, resolvedProjectDir).split(path.sep).join("/"),
28
+ : path.relative(contextRoot, resolvedProjectDir).split(path.sep).join("/"),
47
29
  };
48
30
  }
49
31
 
@@ -0,0 +1,30 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ function inside(root, relative) {
5
+ if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
6
+ const result = path.resolve(root, relative);
7
+ const offset = path.relative(root, result);
8
+ if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
9
+ return result;
10
+ }
11
+
12
+ function confinedPath(root, relative, io = fs) {
13
+ const candidate = inside(root, relative);
14
+ let existing = candidate;
15
+ while (existing !== root && !io.existsSync(existing)) {
16
+ if (io.lstatSync) {
17
+ try {
18
+ if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
19
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
20
+ }
21
+ existing = path.dirname(existing);
22
+ }
23
+ if (io.realpathSync && io.existsSync(existing)) {
24
+ const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
25
+ if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
26
+ }
27
+ return candidate;
28
+ }
29
+
30
+ module.exports = { inside, confinedPath };
@@ -0,0 +1,204 @@
1
+ const path = require("node:path");
2
+ const { inside } = require("./release-paths");
3
+ const { normalizeMonorepoContextFiles } = require("./minimal-context");
4
+
5
+ function normalizeSourceDirectories(value, name) {
6
+ const directories = Array.isArray(value) ? value : [value];
7
+ if (!directories.length || directories.some((item) => typeof item !== "string" || !item.trim())) {
8
+ throw new Error(`${name} source.directory 必须是非空路径字符串或非空路径数组`);
9
+ }
10
+ return [...new Set(directories.map((item) => item.trim()))];
11
+ }
12
+
13
+ function resolveSourceDirectories(projectDir, value, name) {
14
+ return normalizeSourceDirectories(value, name).map((directory) => path.resolve(projectDir, directory));
15
+ }
16
+
17
+ const SAFE_GIT_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
18
+ const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
19
+ const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
20
+ const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
21
+ const BUILD_STRATEGIES = new Set(["artifact", "source"]);
22
+
23
+ function normalizePreBuildCommand(value, target) {
24
+ const entry = Array.isArray(value) ? { command: value, when: "always" } : value;
25
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
26
+ || !Array.isArray(entry.command) || entry.command.length === 0
27
+ || entry.command.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg))
28
+ || (entry.when != null && !PRE_BUILD_MODES.has(entry.when))) {
29
+ throw new Error(`${target} preBuild 必须是命令参数数组,或包含 command 与合法 when 的对象`);
30
+ }
31
+ return { command: entry.command, when: entry.when || "always" };
32
+ }
33
+
34
+ function compareVersions(actual, required) {
35
+ const actualMatch = String(actual).trim().replace(/^v/, "").match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
36
+ const requiredMatch = String(required).match(SAFE_VERSION_REQUIREMENT);
37
+ if (!actualMatch || !requiredMatch) return false;
38
+ for (let index = 1; index <= 3; index++) {
39
+ const left = Number(actualMatch[index] || 0);
40
+ const right = Number(requiredMatch[index] || 0);
41
+ if (left !== right) return left > right;
42
+ }
43
+ return true;
44
+ }
45
+
46
+ function validateReleaseProfile(profile, target) {
47
+ const instructions = profile.deployment?.instructions;
48
+ if (instructions != null && (!Array.isArray(instructions)
49
+ || instructions.some((line) => typeof line !== "string" || !line.trim()))) {
50
+ throw new Error(`${target} deployment.instructions 必须是非空文本组成的列表`);
51
+ }
52
+ if (profile.recordConfigurationRevision != null && typeof profile.recordConfigurationRevision !== "boolean") {
53
+ throw new Error(`${target} recordConfigurationRevision 必须是布尔值`);
54
+ }
55
+ if (profile.pushBranch != null && (typeof profile.pushBranch !== "string"
56
+ || !SAFE_GIT_NAME.test(profile.pushBranch) || profile.pushBranch.startsWith("-")
57
+ || profile.pushBranch.includes(".."))) {
58
+ throw new Error(`${target} pushBranch 必须是合法 Git 分支名`);
59
+ }
60
+ if (profile.pushRef != null && (typeof profile.pushRef !== "string"
61
+ || !SAFE_GIT_NAME.test(profile.pushRef) || profile.pushRef.startsWith("-")
62
+ || profile.pushRef.includes("..") || !profile.pushRef.includes("/"))) {
63
+ throw new Error(`${target} pushRef 必须使用 remote/branch 格式`);
64
+ }
65
+ if ((profile.pushBranch == null) !== (profile.pushRef == null)) {
66
+ throw new Error(`${target} pushBranch 和 pushRef 必须同时配置`);
67
+ }
68
+ if (profile.requirements != null) {
69
+ if (!profile.requirements || typeof profile.requirements !== "object"
70
+ || Array.isArray(profile.requirements)) throw new Error(`${target} requirements 必须是对象`);
71
+ for (const [tool, requirement] of Object.entries(profile.requirements)) {
72
+ if (!["node", "pnpm"].includes(tool) || typeof requirement !== "string"
73
+ || !SAFE_VERSION_REQUIREMENT.test(requirement)) {
74
+ throw new Error(`${target} requirements 只支持 node/pnpm 的 >=x.y.z 版本约束`);
75
+ }
76
+ }
77
+ }
78
+ if (profile.preBuild != null && (!Array.isArray(profile.preBuild) || profile.preBuild.length === 0)) {
79
+ throw new Error(`${target} preBuild 必须是非空列表`);
80
+ }
81
+ for (const command of profile.preBuild || []) normalizePreBuildCommand(command, target);
82
+ }
83
+
84
+ function validateComponent(component, name, guardedByProfile = false) {
85
+ if (!component || !/^[a-z0-9][a-z0-9._:/-]*$/.test(component.repository || "") || component.repository.includes("@")) {
86
+ throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
87
+ }
88
+ if (component.repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
89
+ if (!component.expectedRef && !component.source?.branch && !guardedByProfile) {
90
+ throw new Error(`${name} 必须配置 expectedRef、source.branch 或 target pushRef`);
91
+ }
92
+ if (component.source) {
93
+ normalizeSourceDirectories(component.source.directory, name);
94
+ if (component.source.standalone != null && typeof component.source.standalone !== "boolean") {
95
+ throw new Error(`${name} source.standalone 必须是布尔值`);
96
+ }
97
+ if (!component.source.branch || component.source.branch.startsWith("-")) {
98
+ throw new Error(`${name} source 必须配置合法 branch`);
99
+ }
100
+ }
101
+ inside("/config", component.dockerfile || "Dockerfile");
102
+ if (component.dockerfileFromConfig != null) {
103
+ inside("/config", component.dockerfileFromConfig);
104
+ if (!component.source || component.buildStrategy !== "source" || component.dockerfile != null) {
105
+ throw new Error(`${name} dockerfileFromConfig 只支持外部源码构建,不能同时配置 dockerfile`);
106
+ }
107
+ }
108
+ if (component.contextFiles != null) {
109
+ if (!component.source || component.buildStrategy !== "source" || !Array.isArray(component.contextFiles)
110
+ || !component.contextFiles.length) throw new Error(`${name} contextFiles 只支持外部源码构建的非空列表`);
111
+ const destinations = new Set();
112
+ for (const entry of component.contextFiles) {
113
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
114
+ || Object.keys(entry).some((key) => !["from", "to"].includes(key))) throw new Error(`${name} contextFiles 仅支持 from/to`);
115
+ inside("/config", entry.from); inside("/config", entry.to);
116
+ const destination = path.normalize(entry.to);
117
+ if (destination === "." || destination.split(path.sep).includes(".git") || destinations.has(destination)) {
118
+ throw new Error(`${name} contextFiles 目标不能为根、Git 元数据或重复路径`);
119
+ }
120
+ destinations.add(destination);
121
+ }
122
+ }
123
+ inside("/config", component.context || ".");
124
+ if (component.sourceCheck != null && (!Array.isArray(component.sourceCheck)
125
+ || component.sourceCheck.length === 0
126
+ || component.sourceCheck.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg)))) {
127
+ throw new Error(`${name} sourceCheck 必须是非空命令参数数组`);
128
+ }
129
+ if (component.target != null && (typeof component.target !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(component.target))) {
130
+ throw new Error(`${name} target 必须是合法 Docker stage`);
131
+ }
132
+ if (component.platform != null && (typeof component.platform !== "string"
133
+ || !SAFE_DOCKER_PLATFORM.test(component.platform))) {
134
+ throw new Error(`${name} platform 必须是 linux/amd64 等合法 Docker 平台`);
135
+ }
136
+ if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
137
+ throw new Error(`${name} mutableTags 必须是布尔值`);
138
+ }
139
+ if (component.tagPrefix != null && (typeof component.tagPrefix !== "string"
140
+ || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,87}$/.test(component.tagPrefix))) {
141
+ throw new Error(`${name} tagPrefix 必须是 1 到 88 位合法 Docker 标签前缀`);
142
+ }
143
+ if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
144
+ throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
145
+ }
146
+ if (component.buildStrategy === "source" && component.files != null) {
147
+ throw new Error(`${name} source 构建不能同时配置 files 产物上下文`);
148
+ }
149
+ if (component.monorepoContextFiles != null) {
150
+ if (component.buildStrategy !== "source") throw new Error(`${name} monorepoContextFiles 仅用于 source 构建`);
151
+ normalizeMonorepoContextFiles(component.monorepoContextFiles);
152
+ }
153
+ if (component.projectInstall != null) {
154
+ if (typeof component.projectInstall !== "boolean" || !component.source || component.buildStrategy !== "source" || component.monorepoContextFiles != null) {
155
+ throw new Error(`${name} projectInstall 必须是布尔值,只用于外部源码构建,不能与 monorepoContextFiles 同时配置`);
156
+ }
157
+ }
158
+ if (component.releaseIdentity != null && (typeof component.releaseIdentity !== "boolean"
159
+ || component.buildStrategy !== "source" || !component.source)) {
160
+ throw new Error(`${name} releaseIdentity 仅支持外部 source 构建的布尔值`);
161
+ }
162
+ if (component.workspaceRef != null && (typeof component.workspaceRef !== "string"
163
+ || !SAFE_GIT_NAME.test(component.workspaceRef) || !component.workspaceRef.includes("/") || component.workspaceRef.includes(".."))) {
164
+ throw new Error(`${name} workspaceRef 必须使用 remote/branch`);
165
+ }
166
+ if (component.releaseIdentity && (component.tagPrefix || "").length > 74) throw new Error(`${name} 唯一发布标签的前缀过长`);
167
+ if (component.releaseIdentity && !component.platform) throw new Error(`${name} 唯一发布必须明确声明 platform`);
168
+ if (component.releaseChannel != null && (typeof component.releaseChannel !== "boolean" || !component.releaseIdentity)) {
169
+ throw new Error(`${name} releaseChannel 仅支持启用 releaseIdentity 的布尔值`);
170
+ }
171
+ if (component.buildArgs != null && (!component.buildArgs || typeof component.buildArgs !== "object"
172
+ || Array.isArray(component.buildArgs) || Object.entries(component.buildArgs).some(([key, value]) =>
173
+ !/^[A-Z_][A-Z0-9_]*$/.test(key) || !["string", "number", "boolean"].includes(typeof value)))) {
174
+ throw new Error(`${name} buildArgs 必须是合法构建参数对象`);
175
+ }
176
+ if (component.requiredFiles) {
177
+ if (!Array.isArray(component.requiredFiles)) throw new Error(`${name} requiredFiles 必须是数组`);
178
+ for (const file of component.requiredFiles) inside("/config", file);
179
+ }
180
+ if (component.files) {
181
+ if (!Array.isArray(component.files) || component.files.length === 0) throw new Error(`${name} files 必须是非空数组`);
182
+ for (const file of component.files) { inside("/config", file.from); inside("/config", file.to); }
183
+ }
184
+ if (component.check) {
185
+ const { entrypoint, args, addHosts = [] } = component.check;
186
+ if (typeof entrypoint !== "string" || !entrypoint || !Array.isArray(args)
187
+ || !args.every((arg) => typeof arg === "string") || !Array.isArray(addHosts)
188
+ || !addHosts.every((host) => typeof host === "string" && host.includes(":"))) {
189
+ throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 数组`);
190
+ }
191
+ }
192
+ if (component.health != null) {
193
+ const health = component.health;
194
+ if (!health || typeof health !== "object" || Array.isArray(health)
195
+ || Object.keys(health).some((key) => !["timeoutSeconds", "addHost"].includes(key))
196
+ || !Number.isInteger(health.timeoutSeconds) || health.timeoutSeconds < 1 || health.timeoutSeconds > 600
197
+ || (health.addHost != null && (typeof health.addHost !== "string"
198
+ || !/^[A-Za-z0-9][A-Za-z0-9._-]*:(?:[A-Fa-f0-9:.]+|host-gateway)$/.test(health.addHost)))) {
199
+ throw new Error(`${name} health 必须声明 1 到 600 秒的 timeoutSeconds 及可选 addHost`);
200
+ }
201
+ }
202
+ }
203
+
204
+ module.exports = { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent, validateReleaseProfile };
@@ -19,7 +19,8 @@ function prepareWorkspaceSnapshot({ workspaceRoot, revision, run = execFileSync,
19
19
  try {
20
20
  const archive = path.join(contextRoot, "source.tar");
21
21
  run("git", ["-C", workspaceRoot, "archive", "--format=tar", `--output=${archive}`, revision, "--", "packages"], options);
22
- run("tar", ["-xf", archive, "-C", contextRoot], options);
22
+ // GNU tar 会把 Windows 盘符中的冒号识别成远程地址;在临时目录内用相对文件名解压。
23
+ run("tar", ["-xf", path.basename(archive)], { ...options, cwd: contextRoot });
23
24
  fs.unlinkSync(archive);
24
25
  if (!fs.existsSync(path.join(contextRoot, "packages"))) throw new Error("公共源码快照为空,请检查 Git export 属性");
25
26
  return { contextRoot, revision };