@infly/libs 2.4.1 → 2.5.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/bin/cli.js CHANGED
@@ -152,14 +152,17 @@ function resolveReleaseDockerMode(argv, packageObject = {}) {
152
152
  return hasTargetConfig ? "target" : "quality";
153
153
  }
154
154
 
155
- async function runTargetReleaseCommand(args) {
155
+ async function runTargetReleaseCommand(args, rootSynchronization) {
156
156
  const { parseReleaseArgs, runTargetRelease } = require("../build/docker/target-release");
157
- const result = await runTargetRelease(parseReleaseArgs(args));
157
+ const result = await runTargetRelease(parseReleaseArgs(args), { rootSynchronization });
158
158
  if (result.missingSources?.length) process.exitCode = 2;
159
159
  return result;
160
160
  }
161
161
 
162
162
  async function main(argv = process.argv.slice(2)) {
163
+ // 构建入口在解析配置/加载实现前更新主仓;dry-run 和独立克隆不更新根仓。
164
+ const bootstrap = require("../build/before-build").bootstrapRelease({ argv, entryFile: __filename });
165
+ if (bootstrap.relaunched) { process.exitCode = bootstrap.status; return; }
163
166
  const command = argv[0];
164
167
  const commandMap = {
165
168
  "release:notification": () => {
@@ -190,7 +193,7 @@ async function main(argv = process.argv.slice(2)) {
190
193
  return result;
191
194
  },
192
195
  // 兼容旧脚本;新项目和生成配置统一使用 release:docker。
193
- "docker:release": () => runTargetReleaseCommand(argv.slice(1)),
196
+ "docker:release": () => runTargetReleaseCommand(argv.slice(1), bootstrap.synchronization),
194
197
  afterBuild: () => loadBuildDist().init(),
195
198
  initZip: () => loadBuildDist().init(),
196
199
  preview: () => loadPreview().init(),
@@ -210,7 +213,7 @@ async function main(argv = process.argv.slice(2)) {
210
213
  "release:docker": () => {
211
214
  const args = argv.slice(1);
212
215
  const mode = resolveReleaseDockerMode(args, loadReleasePackage(args));
213
- if (mode === "target") return runTargetReleaseCommand(args);
216
+ if (mode === "target") return runTargetReleaseCommand(args, bootstrap.synchronization);
214
217
  return require("../build/docker/release-docker").releaseDocker(parseArgs(args));
215
218
  },
216
219
  "docker:compose": () => {
@@ -0,0 +1,50 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const { execFileSync, spawnSync } = require("node:child_process");
4
+ const { findOuterWorkspaceRoot, resolveGitWorktreeRoot } = require("../script/git-automation/git-utils");
5
+ const { updateRootRepository } = require("../script/git-automation/root-update");
6
+
7
+ const BUILD_COMMANDS = new Set(["release:docker", "docker:release", "build:docker", "docker:compose"]);
8
+
9
+ /** 在加载构建实现前同步根仓;更新自身代码后重启,防止进程混用新旧模块。 */
10
+ function bootstrapRelease({
11
+ argv = [],
12
+ entryFile,
13
+ cwd = process.cwd(),
14
+ env = process.env,
15
+ run = execFileSync,
16
+ spawn = spawnSync,
17
+ discoverRoot,
18
+ log = console.log
19
+ } = {}) {
20
+ if (!BUILD_COMMANDS.has(argv[0]) || argv.includes("--dry-run")) return {};
21
+ const index = argv.indexOf("--project-dir");
22
+ const equals = argv.find((arg) => arg.startsWith("--project-dir="));
23
+ if ((index >= 0 && (!argv[index + 1] || argv[index + 1].startsWith("--"))) || equals === "--project-dir=") {
24
+ throw new Error("--project-dir 缺少参数值");
25
+ }
26
+ const projectDir = path.resolve(cwd, equals ? equals.slice(14) : index >= 0 ? argv[index + 1] || "." : ".");
27
+ const workspaceRoot = discoverRoot
28
+ ? discoverRoot(projectDir)
29
+ : findOuterWorkspaceRoot(resolveGitWorktreeRoot(projectDir));
30
+ if (!workspaceRoot) return {};
31
+ const synchronization = updateRootRepository(workspaceRoot, "master", { run, requireRemoteHead: true, log });
32
+ const { before, revision } = synchronization;
33
+ const rootEntry = path.join(workspaceRoot, "packages", "infly-libs", "bin", "cli.js");
34
+ if (before !== revision || path.resolve(entryFile) !== rootEntry) {
35
+ if (env.INFLY_BOOTSTRAP_RESTARTS) throw new Error("重启期间根仓再次更新,请重新执行构建命令");
36
+ if (!fs.existsSync(rootEntry)) throw new Error("更新后的根仓缺少公共 CLI,不能回退旧工具");
37
+ log("主仓已同步,使用更新后的公共工具重新启动构建。");
38
+ const child = spawn(process.execPath, [rootEntry, ...argv], {
39
+ cwd,
40
+ stdio: "inherit",
41
+ env: { ...env, INFLY_BOOTSTRAP_RESTARTS: "1" }
42
+ });
43
+ if (child.error || child.signal || child.status == null)
44
+ throw new Error("更新后的构建工具启动失败", { cause: child.error });
45
+ return { relaunched: true, status: child.status };
46
+ }
47
+ return { synchronization };
48
+ }
49
+
50
+ module.exports = { bootstrapRelease };
@@ -56,7 +56,7 @@ function formatCicdLink(value, deployParams) {
56
56
 
57
57
  // 单组件推送成功后预填“平台/镜像版本”参数,新平台首次部署无需从历史选项里挑选;仅对 /build 构建入口追加。
58
58
  if (deployParams !== undefined) {
59
- const { platform, platformLabel, tag, date } = deployParams;
59
+ const { platform, platformLabel, tag, date, releaseVersion } = deployParams;
60
60
  if (typeof platform !== "string" || !/^[a-z0-9]+$/.test(platform)
61
61
  || typeof tag !== "string" || !/^[0-9a-f]{40}$/.test(tag)
62
62
  || typeof date !== "string" || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(date)) {
@@ -66,11 +66,16 @@ function formatCicdLink(value, deployParams) {
66
66
  || /[\u0000-\u001f\u007f]/.test(platformLabel))) {
67
67
  throw new Error("发布系统深链平台名称必须是非空且不含控制字符的字符串");
68
68
  }
69
+ if (releaseVersion !== undefined && !/^[0-9a-f]{40}-r[0-9a-f]{12}$/.test(releaseVersion)) {
70
+ throw new Error("发布系统深链发布版本无效");
71
+ }
69
72
  if (parsedUrl.pathname.endsWith("/build")) {
70
73
  // Jenkins 原生 choice 的显示文本就是提交值;传入标签时须与“中文名称 / 编码”选项完全一致。
71
74
  const platformChoice = platformLabel === undefined ? platform : `${platformLabel.trim()} / ${platform}`;
72
75
  const suffix = `&${encodeURIComponent("平台")}=${encodeURIComponent(platformChoice)}`
73
- + `&${encodeURIComponent("镜像版本")}=${encodeURIComponent(`${platform} / ${tag} / ${date}`)}`;
76
+ + (releaseVersion
77
+ ? `&${encodeURIComponent("发布版本")}=${encodeURIComponent(releaseVersion)}`
78
+ : `&${encodeURIComponent("镜像版本")}=${encodeURIComponent(`${platform} / ${tag} / ${date}`)}`);
74
79
  parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}${suffix}` : `?${suffix.slice(1)}`;
75
80
  }
76
81
  }
@@ -424,7 +429,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
424
429
  projectDir: cwd,
425
430
  });
426
431
  effectiveBuildContext = preparedContext.contextRoot;
427
- console.log(`最小上下文: ${projectDirArg} + packages + 根锁文件`);
432
+ console.log(`最小上下文: ${projectDirArg} + packages + 根安装文件`);
428
433
  }
429
434
  const buildArgs = ["build", "-f", dockerfileArg];
430
435
  tags.forEach((tag) => buildArgs.push("-t", tag));
@@ -29,6 +29,24 @@ function shouldCopy(source) {
29
29
  return !source.split(path.sep).some((segment) => EXCLUDED_DIRECTORIES.has(segment));
30
30
  }
31
31
 
32
+ function normalizeMonorepoContextFiles(files = []) {
33
+ if (!Array.isArray(files)) throw new Error("monorepoContextFiles 必须是文件路径数组");
34
+ const seen = new Set();
35
+ return files.map((file) => {
36
+ if (typeof file !== "string" || !file || file.includes("\0")
37
+ || path.isAbsolute(file) || path.win32.isAbsolute(file) || /^[a-z]:/i.test(file)
38
+ || /[*?{}\[\]]/.test(file)) throw new Error("monorepoContextFiles 只支持根目录内的明确相对文件路径,不支持通配符");
39
+ const normalized = file.replace(/\\/g, "/");
40
+ const segments = normalized.split("/");
41
+ if (segments.some((segment) => !segment || segment === "." || segment === ".."
42
+ || EXCLUDED_DIRECTORIES.has(segment.toLowerCase())) || seen.has(normalized)) {
43
+ throw new Error("monorepoContextFiles 不允许越界、排除目录或重复路径");
44
+ }
45
+ seen.add(normalized);
46
+ return normalized;
47
+ });
48
+ }
49
+
32
50
  function copyEntry(io, workspaceRoot, contextRoot, relative) {
33
51
  const source = path.join(workspaceRoot, relative);
34
52
  if (!io.existsSync(source)) return false;
@@ -44,12 +62,13 @@ function copyEntry(io, workspaceRoot, contextRoot, relative) {
44
62
 
45
63
  /**
46
64
  * 为 monorepo 源码镜像准备保持原目录布局的最小上下文。
47
- * 只带根安装契约、公共 packages 和当前应用,避免把其他产品线发送给 Docker。
65
+ * 只带根安装契约及钩子、公共 packages 和当前应用,避免把其他产品线发送给 Docker。
48
66
  */
49
67
  function prepareMinimalMonorepoContext({
50
68
  workspaceRoot,
51
69
  projectDir,
52
70
  sourceDir,
71
+ additionalFiles = [],
53
72
  io = fs,
54
73
  temporaryRoot = os.tmpdir(),
55
74
  } = {}) {
@@ -58,10 +77,21 @@ function prepareMinimalMonorepoContext({
58
77
  if (!isInside(resolvedWorkspace, resolvedProject)) {
59
78
  throw new Error(`项目目录不在 monorepo 根目录内: ${resolvedProject}`);
60
79
  }
80
+ const explicitFiles = normalizeMonorepoContextFiles(additionalFiles);
81
+ for (const file of explicitFiles) {
82
+ const source = path.join(resolvedWorkspace, file);
83
+ if (!io.existsSync(source)) throw new Error(`缺少 monorepo 构建文件: ${file}`);
84
+ // 只允许普通文件;父目录链接也不能把读取范围带出工作区。
85
+ if (!io.lstatSync(source).isFile()
86
+ || !isInside(io.realpathSync(resolvedWorkspace), io.realpathSync(source))) {
87
+ throw new Error(`monorepoContextFiles 只允许工作区内的普通文件: ${file}`);
88
+ }
89
+ }
61
90
  const projectRelativeDir = path.relative(resolvedWorkspace, resolvedProject);
62
91
  const contextRoot = io.mkdtempSync(path.join(temporaryRoot, "infly-docker-context-"));
63
92
  try {
64
93
  for (const entry of ROOT_ENTRIES) copyEntry(io, resolvedWorkspace, contextRoot, entry);
94
+ for (const file of explicitFiles) copyEntry(io, resolvedWorkspace, contextRoot, file);
65
95
  if (!projectRelativeDir.startsWith(`packages${path.sep}`)) {
66
96
  if (sourceDir) {
67
97
  // 部署仓冻结业务源码后,以该快照替换业务目录,公共包仍来自已核验的根工作区。
@@ -82,6 +112,7 @@ function prepareMinimalMonorepoContext({
82
112
  module.exports = {
83
113
  EXCLUDED_DIRECTORIES,
84
114
  ROOT_ENTRIES,
115
+ normalizeMonorepoContextFiles,
85
116
  prepareMinimalMonorepoContext,
86
117
  shouldCopy,
87
118
  };
@@ -0,0 +1,163 @@
1
+ const fs = require("node:fs");
2
+ const os = require("node:os");
3
+ const path = require("node:path");
4
+ const yaml = require("yaml");
5
+ const { DEPENDENCY_SECTIONS, discoverWorkspacePackages } = require("../../workspace/packages");
6
+ const { shouldCopy } = require("./minimal-context");
7
+
8
+ const LOCAL_PACKAGES = ".infly-local-packages";
9
+
10
+ function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
11
+
12
+ function copyTree(source, destination) {
13
+ fs.cpSync(source, destination, { recursive: true, filter: (file) => {
14
+ if (!shouldCopy(file)) return false;
15
+ if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`构建源码不允许符号链接: ${file}`);
16
+ return true;
17
+ } });
18
+ }
19
+
20
+ function manifestsIn(directory) {
21
+ const result = [];
22
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
23
+ const file = path.join(directory, entry.name);
24
+ if (!shouldCopy(file) || entry.isSymbolicLink()) continue;
25
+ if (entry.isDirectory()) result.push(...manifestsIn(file));
26
+ else if (entry.name === "package.json") result.push({ manifest: readJson(file) });
27
+ }
28
+ return result;
29
+ }
30
+
31
+ /** 项目安装配置 + 按依赖闭包选取的公共源码;不读取父仓安装配置或锁文件。 */
32
+ function prepareProjectInstallContext({ workspaceRoot, sourceDir,
33
+ temporaryRoot = os.tmpdir() }) {
34
+ const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, "infly-project-install-"));
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} 是构建保留目录`);
38
+ }
39
+ copyTree(sourceDir, contextRoot);
40
+ const configFile = path.join(contextRoot, "pnpm-workspace.yaml");
41
+ const document = yaml.parseDocument(fs.readFileSync(configFile, "utf8"));
42
+ if (document.errors.length) throw document.errors[0];
43
+ const config = document.toJS() || {};
44
+ if (config.pnpmfile || fs.existsSync(path.join(contextRoot, ".pnpmfile.cjs"))) {
45
+ throw new Error("projectInstall 要求项目自身不使用 pnpmfile");
46
+ }
47
+ const available = discoverWorkspacePackages(workspaceRoot);
48
+ const byName = new Map();
49
+ for (const pkg of available) {
50
+ if (typeof pkg.name !== "string" || !pkg.name || byName.has(pkg.name)) throw new Error("公共源码包名称缺失或重复");
51
+ byName.set(pkg.name, pkg);
52
+ }
53
+ const localDependencies = (manifest) => {
54
+ const names = new Set(DEPENDENCY_SECTIONS.flatMap((section) => Object.keys(manifest[section] || {})));
55
+ for (const name of names) {
56
+ if (name.startsWith("@infly/") && !byName.has(name)) throw new Error(`缺少公共包源码: ${name}(消费方 ${manifest.name || "未知项目"});禁止回退 npm`);
57
+ }
58
+ return [...names].filter((name) => byName.has(name));
59
+ };
60
+ const selected = new Set(manifestsIn(contextRoot).flatMap((pkg) => localDependencies(pkg.manifest)));
61
+ for (const name of selected) {
62
+ const pkg = byName.get(name);
63
+ // 公共包只参与源码消费,不安装其发布、测试等开发工具。
64
+ const manifest = { ...pkg.manifest };
65
+ delete manifest.devDependencies;
66
+ for (const dependency of localDependencies(manifest)) selected.add(dependency);
67
+ }
68
+ const packages = available.filter((pkg) => selected.has(pkg.name));
69
+ fs.mkdirSync(path.join(contextRoot, ".infly-local-manifests"), { recursive: true });
70
+ for (const pkg of packages) {
71
+ const destination = path.join(contextRoot, LOCAL_PACKAGES, pkg.dir);
72
+ copyTree(pkg.directoryPath, destination);
73
+ const manifest = readJson(path.join(destination, "package.json"));
74
+ 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);
77
+ fs.mkdirSync(manifestDirectory, { recursive: true });
78
+ fs.copyFileSync(path.join(destination, "package.json"), path.join(manifestDirectory, "package.json"));
79
+ }
80
+ config.packages = [...(config.packages || []), `${LOCAL_PACKAGES}/*`];
81
+ config.overrides = { ...(config.overrides || {}), ...Object.fromEntries(packages.map((pkg) => [pkg.name, "workspace:*"])) };
82
+ // 保留业务配置已有的注释和引号风格,只补充本地 workspace 映射。
83
+ document.set("packages", config.packages);
84
+ document.set("overrides", config.overrides);
85
+ 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
+ }
91
+ }
92
+
93
+ /** 独立构建仅更新内部 npm 包;工作树清单与原锁均保持不变。 */
94
+ 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");
104
+ const lockFile = path.join(contextRoot, "pnpm-lock.yaml");
105
+ const lock = yaml.parse(fs.readFileSync(lockFile, "utf8"));
106
+ const queue = new Map();
107
+ const addRequirement = (name, range) => {
108
+ if (!queue.has(name)) queue.set(name, new Set());
109
+ queue.get(name).add(String(range));
110
+ };
111
+ for (const { manifest } of manifestsIn(contextRoot)) {
112
+ for (const section of DEPENDENCY_SECTIONS) {
113
+ for (const [name, range] of Object.entries(manifest[section] || {})) {
114
+ if (name.startsWith("@infly/")) addRequirement(name, range);
115
+ }
116
+ }
117
+ }
118
+ for (const importer of Object.values(lock.importers || {})) {
119
+ for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
120
+ for (const [name, entry] of Object.entries(importer[section] || {})) {
121
+ if (name.startsWith("@infly/")) addRequirement(name, entry.version);
122
+ }
123
+ }
124
+ }
125
+ const packages = [];
126
+ const versions = new Map();
127
+ const verifyMajor = (name, baseline, version) => {
128
+ const current = String(baseline).match(/^[~^<>=\s]*(\d+)(?:\.|$)/);
129
+ if (!current || Number(current[1]) !== Number(version.split(".")[0])) {
130
+ throw new Error(`需要 major 升级二次确认: ${name} ${baseline} → ${version};未修改工作树或安装依赖`);
131
+ }
132
+ };
133
+ for (const [name, requirements] of queue) {
134
+ const metadata = registryManifest(name);
135
+ const version = metadata.version;
136
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version || "")) throw new Error(`${name} Registry latest 版本无效`);
137
+ for (const baseline of requirements) verifyMajor(name, baseline, version);
138
+ versions.set(name, version);
139
+ packages.push({ name, version });
140
+ for (const section of ["dependencies", "optionalDependencies", "peerDependencies"]) {
141
+ for (const [dependency, requirement] of Object.entries(metadata[section] || {})) {
142
+ if (dependency.startsWith("@infly/")) {
143
+ addRequirement(dependency, requirement);
144
+ // 后发现的 peer/传递约束同样检查,不能因包已解析而漏掉主版本冲突。
145
+ if (versions.has(dependency)) verifyMajor(dependency, requirement, versions.get(dependency));
146
+ }
147
+ }
148
+ }
149
+ }
150
+ config.overrides = { ...(config.overrides || {}), ...Object.fromEntries(packages.map(({ name, version }) => [name, version])) };
151
+ document.set("overrides", config.overrides);
152
+ fs.writeFileSync(file, document.toString());
153
+ // 只补充本次内部包约束元数据;实际锁图仍由容器内 pnpm 生成并 frozen 复验。
154
+ lock.overrides = config.overrides;
155
+ 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
+ }
161
+ }
162
+
163
+ module.exports = { LOCAL_PACKAGES, prepareProjectInstallContext, prepareStandaloneInstallContext };
@@ -0,0 +1,22 @@
1
+ const { createHash, randomBytes } = require("node:crypto");
2
+
3
+ function createReleaseId(commit, token = randomBytes(6).toString("hex")) {
4
+ if (!/^[0-9a-f]{40}$/.test(commit) || !/^[0-9a-f]{12}$/.test(token)) throw new Error("发布标识必须包含完整业务提交及 12 位随机标识");
5
+ return `${commit}-r${token}`;
6
+ }
7
+
8
+ function createBuildProvenance({ releaseId, component, businessRevision, workspaceRevision = null,
9
+ configurationRevision = null, workspaceRemote = null, platform, mode, target, buildArgs = {} }) {
10
+ return { schemaVersion: 1, releaseId, component, businessRevision, workspaceRevision,
11
+ configurationRevision, workspaceRemote, platform, mode, target,
12
+ // 不把构建参数值写入来源记录,避免将使用方的私有配置带入日志或发布清单。
13
+ buildArgsSha256: createHash("sha256").update(JSON.stringify(Object.entries(buildArgs).sort(([a], [b]) => a.localeCompare(b)))).digest("hex") };
14
+ }
15
+
16
+ function readRegistryDigest(capture, image) {
17
+ const manifest = JSON.parse(capture("docker", ["buildx", "imagetools", "inspect", "--format", "{{json .Manifest}}", image]));
18
+ if (!/^sha256:[0-9a-f]{64}$/.test(manifest.digest || "")) throw new Error("Registry 没有返回合法的镜像 digest");
19
+ return manifest.digest;
20
+ }
21
+
22
+ module.exports = { createReleaseId, createBuildProvenance, readRegistryDigest };
@@ -0,0 +1,44 @@
1
+ const fs = require("node:fs");
2
+ const os = require("node:os");
3
+ const path = require("node:path");
4
+ const { execFileSync } = require("node:child_process");
5
+
6
+ /** 只导出指定提交跟踪的公共源码,忽略工作目录及其 ignored/untracked 内容。 */
7
+ function prepareWorkspaceSnapshot({ workspaceRoot, revision, run = execFileSync, temporaryRoot = os.tmpdir() }) {
8
+ if (!/^[0-9a-f]{40}$/.test(revision)) throw new Error("公共源码快照必须使用完整提交号");
9
+ const options = { cwd: workspaceRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
10
+ const entries = String(run("git", ["-C", workspaceRoot, "ls-tree", "-r", "-z", revision, "--", "packages"], options)).split("\0").filter(Boolean);
11
+ if (!entries.length) throw new Error("指定提交没有公共 packages 源码");
12
+ for (const entry of entries) {
13
+ const match = entry.match(/^(100644|100755) blob [0-9a-f]{40}\t(packages\/[\s\S]+)$/);
14
+ if (!match || match[2].split("/").some((part) => !part || part === "." || part === ".." || /[\\:\0]/.test(part))) {
15
+ throw new Error("公共源码快照拒绝符号链接、子模块或不安全路径");
16
+ }
17
+ }
18
+ const contextRoot = fs.mkdtempSync(path.join(temporaryRoot, "infly-workspace-source-"));
19
+ try {
20
+ const archive = path.join(contextRoot, "source.tar");
21
+ run("git", ["-C", workspaceRoot, "archive", "--format=tar", `--output=${archive}`, revision, "--", "packages"], options);
22
+ run("tar", ["-xf", archive, "-C", contextRoot], options);
23
+ fs.unlinkSync(archive);
24
+ if (!fs.existsSync(path.join(contextRoot, "packages"))) throw new Error("公共源码快照为空,请检查 Git export 属性");
25
+ return { contextRoot, revision };
26
+ } catch (error) {
27
+ fs.rmSync(contextRoot, { recursive: true, force: true });
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ function verifyWorkspaceRemote({ workspaceRoot, revision, expectedRef, capture }) {
33
+ const match = String(expectedRef || "").match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._/-]*)$/);
34
+ if (!match || expectedRef.includes("..")) throw new Error("workspaceRef 必须是 remote/branch");
35
+ const remoteRef = `refs/heads/${match[2]}`;
36
+ const output = capture("git", ["-C", workspaceRoot, "ls-remote", "--exit-code", match[1], remoteRef]);
37
+ const lines = output.split(/\r?\n/).filter(Boolean);
38
+ if (lines.length !== 1 || lines[0] !== `${revision}\t${remoteRef}`) {
39
+ throw new Error(`主仓 HEAD 与 ${expectedRef} 不一致;请先手动更新/推送主仓,再重新启动发布命令`);
40
+ }
41
+ return { expectedRef, revision, verified: true };
42
+ }
43
+
44
+ module.exports = { prepareWorkspaceSnapshot, verifyWorkspaceRemote };