@infly/libs 2.5.0 → 2.7.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.
Files changed (41) hide show
  1. package/README.md +502 -469
  2. package/adapters/vue2/project-preview.js +9 -16
  3. package/adapters/webpack/auto-export.js +53 -52
  4. package/bin/cli.js +3 -2
  5. package/build/build-dist/index.js +34 -44
  6. package/build/build-utils/command.js +58 -57
  7. package/build/build-utils/deps.js +28 -28
  8. package/build/build-utils/git.js +246 -254
  9. package/build/build-utils/preview.js +79 -78
  10. package/build/build-utils/webhook.js +135 -135
  11. package/build/docker/compose-release.js +7 -9
  12. package/build/docker/deployment/health-check.sh +5 -1
  13. package/build/docker/deployment/promote-image.sh +75 -5
  14. package/build/docker/deployment/release.sh +5 -1
  15. package/build/docker/docker-build-push.js +23 -23
  16. package/build/docker/project-install.js +42 -35
  17. package/build/docker/release-docker.js +7 -25
  18. package/build/docker/release-mode.js +7 -25
  19. package/build/docker/release-paths.js +30 -0
  20. package/build/docker/release-validation.js +248 -0
  21. package/build/docker/source-snapshot.js +2 -1
  22. package/build/docker/target-image.js +227 -0
  23. package/build/docker/target-release.js +540 -860
  24. package/build/project-files.js +47 -47
  25. package/cli/progress.js +4 -11
  26. package/cli/terminal-style.js +40 -0
  27. package/core/async/concurrency.js +29 -29
  28. package/jenkins/README.md +94 -0
  29. package/jenkins/src/com/infly/jenkins/BuildProvenance.groovy +16 -0
  30. package/jenkins/src/com/infly/jenkins/PipelineJson.groovy +28 -0
  31. package/jenkins/src/com/infly/jenkins/ReleaseNotification.groovy +86 -0
  32. package/jenkins/vars/inflyNotify.groovy +83 -0
  33. package/package.json +4 -1
  34. package/script/git-automation/check-packages.js +5 -12
  35. package/script/git-automation/git-clone.js +6 -5
  36. package/script/git-automation/git-configure.js +3 -3
  37. package/script/git-automation/git-submodule.js +3 -2
  38. package/script/git-automation/git-utils.js +59 -59
  39. package/script/git-automation/index.js +813 -828
  40. package/script/git-automation/submodule-utils.js +16 -16
  41. package/workspace/config.js +144 -144
@@ -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 };
@@ -1,3 +1,4 @@
1
+ const { logTerminal } = require("../../cli/terminal-style");
1
2
  const fs = require("node:fs");
2
3
  const path = require("node:path");
3
4
  const { execFileSync, spawn, spawnSync } = require("node:child_process");
@@ -71,18 +72,6 @@ function runShellCommand(command, label, cwd) {
71
72
  run(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", command], label, cwd);
72
73
  }
73
74
 
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
75
  function buildPnpmScriptSpawn(scriptName) {
87
76
  if (!SAFE_SCRIPT_NAME.test(scriptName)) {
88
77
  throw new Error(`dockerRelease.checks 包含非法脚本名: ${scriptName}`);
@@ -102,11 +91,6 @@ function buildPnpmScriptSpawn(scriptName) {
102
91
  return { command: "pnpm", args: ["run", scriptName], label };
103
92
  }
104
93
 
105
- function runPnpmScript(scriptName, cwd) {
106
- const { command, args, label } = buildPnpmScriptSpawn(scriptName);
107
- run(command, args, label, cwd);
108
- }
109
-
110
94
  async function runPnpmScriptAsync(scriptName, cwd) {
111
95
  const { command, args, label } = buildPnpmScriptSpawn(scriptName);
112
96
  return runAsync(command, args, label, cwd);
@@ -116,11 +100,9 @@ async function runProjectChecks(scriptNames, cwd) {
116
100
  const results = await Promise.allSettled(
117
101
  scriptNames.map((scriptName) => runPnpmScriptAsync(scriptName, cwd))
118
102
  );
119
- const failures = results
120
- .map((result, index) => ({ result, scriptName: scriptNames[index] }))
121
- .filter(({ result }) => result.status === "rejected");
103
+ const failures = results.filter((result) => result.status === "rejected");
122
104
  if (failures.length === 0) return;
123
- const lines = failures.map(({ result }) => ` - ${result.reason.message}`);
105
+ const lines = failures.map(({ reason }) => ` - ${reason.message}`);
124
106
  throw new Error(
125
107
  `项目检查未全部通过(失败 ${failures.length}/${scriptNames.length}):\n${lines.join("\n")}`
126
108
  );
@@ -223,9 +205,9 @@ async function releaseDocker(options = {}) {
223
205
  }
224
206
 
225
207
  if (emergency.emergency) {
226
- console.warn("\n⚠️ 紧急构建模式:已跳过项目检查和 SonarQube");
227
- console.warn(`紧急原因: ${emergency.emergencyReason}`);
228
- console.warn(`目标 commit: ${projectVersion.fullCommit}`);
208
+ logTerminal("warning", "\n紧急构建模式:已跳过项目检查和 SonarQube");
209
+ logTerminal("warning", `紧急原因: ${emergency.emergencyReason}`);
210
+ logTerminal("warning", `目标 commit: ${projectVersion.fullCommit}`);
229
211
  } else {
230
212
  await runProjectChecks(config.checks, projectRoot);
231
213
  }
@@ -234,7 +216,7 @@ async function releaseDocker(options = {}) {
234
216
  if (!fs.existsSync(config.coverageReport) || fs.statSync(config.coverageReport).size === 0) {
235
217
  throw new Error(`覆盖率报告不存在或为空: ${config.coverageReport}`);
236
218
  }
237
- console.log(`✓ 覆盖率报告已生成: ${config.coverageReport}`);
219
+ logTerminal("success", `覆盖率报告已生成: ${config.coverageReport}`);
238
220
  }
239
221
 
240
222
  if (!emergency.emergency && config.sonar) {
@@ -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,248 @@
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
+ const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;
23
+ const DOCKER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
24
+
25
+ function validateRepository(repository, name) {
26
+ if (typeof repository !== "string" || !/^[a-z0-9][a-z0-9._:/-]*$/.test(repository)) {
27
+ throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
28
+ }
29
+ if (repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
30
+ }
31
+
32
+ function validateBuildInputs(component, name) {
33
+ const { buildSecrets, noCacheFilter, buildTimestampArg, buildArgs } = component;
34
+ if (buildSecrets != null) {
35
+ if (!Array.isArray(buildSecrets) || !buildSecrets.length || buildSecrets.some((secret) =>
36
+ !secret || typeof secret !== "object" || Object.keys(secret).some((key) => !["id", "fileEnv", "defaultFile"].includes(key))
37
+ || typeof secret.id !== "string" || !DOCKER_NAME.test(secret.id)
38
+ || typeof secret.fileEnv !== "string" || !ENV_NAME.test(secret.fileEnv)
39
+ ) || new Set(buildSecrets.map(({ id }) => id)).size !== buildSecrets.length) {
40
+ throw new Error(`${name} buildSecrets 需声明唯一 id 及保存文件路径的 fileEnv`);
41
+ }
42
+ for (const { defaultFile } of buildSecrets) {
43
+ if (defaultFile == null) continue;
44
+ if (typeof defaultFile !== "string" || !defaultFile.trim() || /[,\r\n\0"]/.test(defaultFile)) {
45
+ throw new Error(`${name} buildSecrets.defaultFile 必须是部署仓内的相对文件路径`);
46
+ }
47
+ inside("/config", defaultFile);
48
+ }
49
+ }
50
+ if (noCacheFilter != null && (!Array.isArray(noCacheFilter) || !noCacheFilter.length
51
+ || noCacheFilter.some((stage) => typeof stage !== "string" || !DOCKER_NAME.test(stage)))) {
52
+ throw new Error(`${name} noCacheFilter 必须是合法 Docker stage 列表`);
53
+ }
54
+ if (buildTimestampArg != null && (typeof buildTimestampArg !== "string"
55
+ || !ENV_NAME.test(buildTimestampArg) || Object.hasOwn(buildArgs || {}, buildTimestampArg)
56
+ || ["BUILD_MODE", "PROJECT_DIR", "REFRESH_INTERNAL"].includes(buildTimestampArg))) {
57
+ throw new Error(`${name} buildTimestampArg 必须是未被占用的构建参数名`);
58
+ }
59
+ }
60
+
61
+ function normalizePreBuildCommand(value, target) {
62
+ const entry = Array.isArray(value) ? { command: value, when: "always" } : value;
63
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
64
+ || !Array.isArray(entry.command) || entry.command.length === 0
65
+ || entry.command.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg))
66
+ || (entry.when != null && !PRE_BUILD_MODES.has(entry.when))) {
67
+ throw new Error(`${target} preBuild 必须是命令参数数组,或包含 command 与合法 when 的对象`);
68
+ }
69
+ return { command: entry.command, when: entry.when || "always" };
70
+ }
71
+
72
+ function compareVersions(actual, required) {
73
+ const actualMatch = String(actual).trim().replace(/^v/, "").match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
74
+ const requiredMatch = String(required).match(SAFE_VERSION_REQUIREMENT);
75
+ if (!actualMatch || !requiredMatch) return false;
76
+ for (let index = 1; index <= 3; index++) {
77
+ const left = Number(actualMatch[index] || 0);
78
+ const right = Number(requiredMatch[index] || 0);
79
+ if (left !== right) return left > right;
80
+ }
81
+ return true;
82
+ }
83
+
84
+ function validateReleaseProfile(profile, target) {
85
+ const instructions = profile.deployment?.instructions;
86
+ if (instructions != null && (!Array.isArray(instructions)
87
+ || instructions.some((line) => typeof line !== "string" || !line.trim()))) {
88
+ throw new Error(`${target} deployment.instructions 必须是非空文本组成的列表`);
89
+ }
90
+ if (profile.recordConfigurationRevision != null && typeof profile.recordConfigurationRevision !== "boolean") {
91
+ throw new Error(`${target} recordConfigurationRevision 必须是布尔值`);
92
+ }
93
+ if (profile.pushBranch != null && (typeof profile.pushBranch !== "string"
94
+ || !SAFE_GIT_NAME.test(profile.pushBranch) || profile.pushBranch.startsWith("-")
95
+ || profile.pushBranch.includes(".."))) {
96
+ throw new Error(`${target} pushBranch 必须是合法 Git 分支名`);
97
+ }
98
+ if (profile.pushRef != null && (typeof profile.pushRef !== "string"
99
+ || !SAFE_GIT_NAME.test(profile.pushRef) || profile.pushRef.startsWith("-")
100
+ || profile.pushRef.includes("..") || !profile.pushRef.includes("/"))) {
101
+ throw new Error(`${target} pushRef 必须使用 remote/branch 格式`);
102
+ }
103
+ if ((profile.pushBranch == null) !== (profile.pushRef == null)) {
104
+ throw new Error(`${target} pushBranch 和 pushRef 必须同时配置`);
105
+ }
106
+ if (profile.requirements != null) {
107
+ if (!profile.requirements || typeof profile.requirements !== "object"
108
+ || Array.isArray(profile.requirements)) throw new Error(`${target} requirements 必须是对象`);
109
+ for (const [tool, requirement] of Object.entries(profile.requirements)) {
110
+ if (!["node", "pnpm"].includes(tool) || typeof requirement !== "string"
111
+ || !SAFE_VERSION_REQUIREMENT.test(requirement)) {
112
+ throw new Error(`${target} requirements 只支持 node/pnpm 的 >=x.y.z 版本约束`);
113
+ }
114
+ }
115
+ }
116
+ if (profile.preBuild != null && (!Array.isArray(profile.preBuild) || profile.preBuild.length === 0)) {
117
+ throw new Error(`${target} preBuild 必须是非空列表`);
118
+ }
119
+ for (const command of profile.preBuild || []) normalizePreBuildCommand(command, target);
120
+ }
121
+
122
+ function validateComponent(component, name, guardedByProfile = false) {
123
+ if (component?.repositoryEnv != null) {
124
+ if (typeof component.repositoryEnv !== "string" || !ENV_NAME.test(component.repositoryEnv) || component.repository != null) {
125
+ throw new Error(`${name} repositoryEnv 必须是环境变量名,且不能同时配置 repository`);
126
+ }
127
+ } else {
128
+ validateRepository(component?.repository, name);
129
+ }
130
+ validateBuildInputs(component, name);
131
+ if (!component.expectedRef && !component.source?.branch && !guardedByProfile) {
132
+ throw new Error(`${name} 必须配置 expectedRef、source.branch 或 target pushRef`);
133
+ }
134
+ if (component.source) {
135
+ normalizeSourceDirectories(component.source.directory, name);
136
+ if (component.source.standalone != null && typeof component.source.standalone !== "boolean") {
137
+ throw new Error(`${name} source.standalone 必须是布尔值`);
138
+ }
139
+ if (!component.source.branch || component.source.branch.startsWith("-")) {
140
+ throw new Error(`${name} source 必须配置合法 branch`);
141
+ }
142
+ }
143
+ inside("/config", component.dockerfile || "Dockerfile");
144
+ if (component.dockerfileFromConfig != null) {
145
+ inside("/config", component.dockerfileFromConfig);
146
+ if (!component.source || component.buildStrategy !== "source" || component.dockerfile != null) {
147
+ throw new Error(`${name} dockerfileFromConfig 只支持外部源码构建,不能同时配置 dockerfile`);
148
+ }
149
+ }
150
+ if (component.contextFiles != null) {
151
+ if (!component.source || component.buildStrategy !== "source" || !Array.isArray(component.contextFiles)
152
+ || !component.contextFiles.length) throw new Error(`${name} contextFiles 只支持外部源码构建的非空列表`);
153
+ const destinations = new Set();
154
+ for (const entry of component.contextFiles) {
155
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)
156
+ || Object.keys(entry).some((key) => !["from", "to"].includes(key))) throw new Error(`${name} contextFiles 仅支持 from/to`);
157
+ inside("/config", entry.from); inside("/config", entry.to);
158
+ const destination = path.normalize(entry.to);
159
+ if (destination === "." || destination.split(path.sep).includes(".git") || destinations.has(destination)) {
160
+ throw new Error(`${name} contextFiles 目标不能为根、Git 元数据或重复路径`);
161
+ }
162
+ destinations.add(destination);
163
+ }
164
+ }
165
+ inside("/config", component.context || ".");
166
+ if (component.sourceCheck != null && (!Array.isArray(component.sourceCheck)
167
+ || component.sourceCheck.length === 0
168
+ || component.sourceCheck.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg)))) {
169
+ throw new Error(`${name} sourceCheck 必须是非空命令参数数组`);
170
+ }
171
+ if (component.target != null && (typeof component.target !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(component.target))) {
172
+ throw new Error(`${name} target 必须是合法 Docker stage`);
173
+ }
174
+ if (component.platform != null && (typeof component.platform !== "string"
175
+ || !SAFE_DOCKER_PLATFORM.test(component.platform))) {
176
+ throw new Error(`${name} platform 必须是 linux/amd64 等合法 Docker 平台`);
177
+ }
178
+ if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
179
+ throw new Error(`${name} mutableTags 必须是布尔值`);
180
+ }
181
+ if (component.tagPrefix != null && (typeof component.tagPrefix !== "string"
182
+ || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,87}$/.test(component.tagPrefix))) {
183
+ throw new Error(`${name} tagPrefix 必须是 1 到 88 位合法 Docker 标签前缀`);
184
+ }
185
+ if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
186
+ throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
187
+ }
188
+ if (component.buildStrategy === "source" && component.files != null) {
189
+ throw new Error(`${name} source 构建不能同时配置 files 产物上下文`);
190
+ }
191
+ if (component.monorepoContextFiles != null) {
192
+ if (component.buildStrategy !== "source") throw new Error(`${name} monorepoContextFiles 仅用于 source 构建`);
193
+ normalizeMonorepoContextFiles(component.monorepoContextFiles);
194
+ }
195
+ if (component.projectInstall != null) {
196
+ if (typeof component.projectInstall !== "boolean" || !component.source || component.buildStrategy !== "source" || component.monorepoContextFiles != null) {
197
+ throw new Error(`${name} projectInstall 必须是布尔值,只用于外部源码构建,不能与 monorepoContextFiles 同时配置`);
198
+ }
199
+ }
200
+ if (component.releaseIdentity != null && (typeof component.releaseIdentity !== "boolean"
201
+ || component.buildStrategy !== "source" || !component.source)) {
202
+ throw new Error(`${name} releaseIdentity 仅支持外部 source 构建的布尔值`);
203
+ }
204
+ if (component.workspaceRef != null && (typeof component.workspaceRef !== "string"
205
+ || !SAFE_GIT_NAME.test(component.workspaceRef) || !component.workspaceRef.includes("/") || component.workspaceRef.includes(".."))) {
206
+ throw new Error(`${name} workspaceRef 必须使用 remote/branch`);
207
+ }
208
+ if (component.releaseIdentity && (component.tagPrefix || "").length > 74) throw new Error(`${name} 唯一发布标签的前缀过长`);
209
+ if (component.releaseIdentity && !component.platform) throw new Error(`${name} 唯一发布必须明确声明 platform`);
210
+ if (component.releaseChannel != null && (typeof component.releaseChannel !== "boolean" || !component.releaseIdentity)) {
211
+ throw new Error(`${name} releaseChannel 仅支持启用 releaseIdentity 的布尔值`);
212
+ }
213
+ if (component.buildArgs != null && (!component.buildArgs || typeof component.buildArgs !== "object"
214
+ || Array.isArray(component.buildArgs) || Object.entries(component.buildArgs).some(([key, value]) =>
215
+ !/^[A-Z_][A-Z0-9_]*$/.test(key) || !["string", "number", "boolean"].includes(typeof value)))) {
216
+ throw new Error(`${name} buildArgs 必须是合法构建参数对象`);
217
+ }
218
+ if (component.requiredFiles) {
219
+ if (!Array.isArray(component.requiredFiles)) throw new Error(`${name} requiredFiles 必须是数组`);
220
+ for (const file of component.requiredFiles) inside("/config", file);
221
+ }
222
+ if (component.files) {
223
+ if (!Array.isArray(component.files) || component.files.length === 0) throw new Error(`${name} files 必须是非空数组`);
224
+ for (const file of component.files) { inside("/config", file.from); inside("/config", file.to); }
225
+ }
226
+ if (component.check) {
227
+ const { entrypoint, args, addHosts = [], network } = component.check;
228
+ if (typeof entrypoint !== "string" || !entrypoint || !Array.isArray(args)
229
+ || !args.every((arg) => typeof arg === "string") || !Array.isArray(addHosts)
230
+ || !addHosts.every((host) => typeof host === "string" && host.includes(":"))
231
+ || (network != null && network !== "none")) {
232
+ throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 或 network: none`);
233
+ }
234
+ }
235
+ if (component.health != null) {
236
+ const health = component.health;
237
+ if (!health || typeof health !== "object" || Array.isArray(health)
238
+ || Object.keys(health).some((key) => !["timeoutSeconds", "addHost"].includes(key))
239
+ || !Number.isInteger(health.timeoutSeconds) || health.timeoutSeconds < 1 || health.timeoutSeconds > 600
240
+ || (health.addHost != null && (typeof health.addHost !== "string"
241
+ || !/^[A-Za-z0-9][A-Za-z0-9._-]*:(?:[A-Fa-f0-9:.]+|host-gateway)$/.test(health.addHost)))) {
242
+ throw new Error(`${name} health 必须声明 1 到 600 秒的 timeoutSeconds 及可选 addHost`);
243
+ }
244
+ }
245
+ }
246
+
247
+ module.exports = { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent,
248
+ validateReleaseProfile, validateRepository };
@@ -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 };