release-runner.mjs
10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
* 批量发版引擎 —— 全量、增量、单应用共用的唯一实现。
*
* 发版流程只在这里写一遍,任何入口(release-all / release-diff / release)都调它。
* 历史上 uj 把流程写了三份,清空时机、--no-clean 传递、上传模板变量各有一处漏改,
* 结果三条路径行为分叉。这里用 spec 描述"发什么",runner 负责"怎么发"。
*/
import fs from 'node:fs';
import path from 'node:path';
import {
ROOT, pathsOf, readState, writeState, writeSnapshot, mergeRemoteManifest,
assertBase, buildApp, cleanDir, runUpload, writeBuildInfo,
remoteDirOf, versionPath, assertVersion, cmpVersion,
} from './release-core.mjs';
const noop = () => {};
const die = (msg) => { throw new Error(msg); };
/**
* 增量基线检查:本次没发的 app 条目从哪来?
* - 配了线上清单 → 以线上为真源(跨机器一致)
* - 本机有累积状态 → 用它(仅本机有效,告警)
* - 都没有 → 拦截:否则清单只含本次 app,线上其它 app 被整份抹掉 → 白屏
*/
export function assertBaseline({ apps, allApps, remoteManifest, stateFile }, { info = noop } = {}) {
const isPartial = apps.length < allApps.length;
if (!isPartial || remoteManifest) return;
let hasLocal = false;
if (fs.existsSync(stateFile)) {
try {
const st = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
hasLocal = Boolean(st.subapps && Object.keys(st.subapps).length > 0);
} catch { /* 坏文件按无基线 */ }
}
if (hasLocal) {
info(`⚠ 增量基线来自本机 ${path.relative(ROOT, stateFile)}(仅本机有效)。` +
'跨机器协作请配置 deploy/environments.json 的 base 或注入 MFE_REMOTE_MANIFEST。');
return;
}
die(
`增量发版(只发 ${apps.join(', ')})缺少清单基线。\n` +
` 本次没发的条目必须来自基线,否则 mfe/manifest.json 只含本次 app,` +
`线上其它 app(${allApps.filter((a) => !apps.includes(a)).join(', ') || '其它'})会被抹掉而白屏。\n` +
` 出路:① 配 MFE_REMOTE_MANIFEST=<线上清单 URL> 后重跑(推荐);` +
`② 先跑一次 release:all 生成本地基线。`,
);
}
/**
* 执行发版。
* @param {object} spec { version, apps: [{name,shortName,version}], host: {name,version}|null, note }
* @param {object} args parseArgs 结果(out/state/public-base/upload-cmd/skip-build/force/quiet/no-clean 等)
* @param {object} ctx { remoteManifest, workspace, config }
*/
export function runRelease(spec, args, ctx = {}) {
const quiet = Boolean(args.quiet);
const info = quiet ? noop : (m) => console.log(m);
const { workspace, config = {}, remoteManifest = '' } = ctx;
const paths = pathsOf(args, config);
const { outRoot, stateFile, manifestFile, publicBase, uploadCmd } = paths;
const skipBuild = Boolean(args['skip-build']);
const force = Boolean(args.force);
const switchOnly = Boolean(args['switch-only']);
const isWin = process.platform === 'win32';
const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm';
if (!spec.apps.length && !spec.host) die('发版规格为空:没有要发布的 app 或主壳');
const state = readState(stateFile, manifestFile, { info });
// 不可变保护:同名版本已发布过就拒绝,只有 --force 能放行。
// 两种情况例外:switch-only 是回滚(切回旧版本正是它的职责);补发由增量判定阶段
// 探测到目录缺失后主动设置 args.force,走正常放行路径。
// ⚠ skip-build 不能作为绕过口子——CI 里 build/deploy 分离,它是常规路径。
if (!switchOnly && !force) {
for (const a of spec.apps) {
const seen = state.published[a.shortName] ?? [];
if (seen.includes(a.version)) {
die(`${a.shortName}@${a.version} 已发布过。版本目录不可变;确需覆盖请加 --force。`);
}
}
}
if (!quiet) {
console.log('\n[release] ==== 发版计划 ====');
console.log(` 版本 : ${spec.version}${spec.note ? `(${spec.note})` : ''}`);
console.log(` 子应用 : ${spec.apps.map((a) => `${a.shortName}@${a.version}`).join(', ') || '(无)'}`);
console.log(` 主壳 : ${spec.host ? `${spec.host.version}` : '(无)'}`);
console.log(` 产物根 : ${path.relative(ROOT, outRoot)}/`);
console.log(` 线上基线 : ${remoteManifest || '(无,仅首次全量可用)'}`);
console.log(` 模式 : ${switchOnly ? '仅切换清单(回滚/灰度)' : skipBuild ? '复用已有 dist' : '完整发布'}`);
console.log('');
}
// 线上基线合并:本次发的用本地,其余沿用线上(防并发发布互相覆盖)
if (remoteManifest && spec.apps.length) {
// 合并是异步的,由调用方在进 runRelease 前完成并写回 state;这里只提示
info('线上基线已在判定阶段合并,本次未发的 app 沿用线上条目。');
}
// 产物树重建:只装本次内容;--no-clean 由批量入口传第二及以后的 app。
// ⚠ switch-only(回滚/灰度)绝不重建产物根:它改的只是清单指向,线上旧版本目录
// 必须原样留着才回滚得回去;本地这份 dist 也是"部署根剪影",清了就等于假装旧版本没了。
if (!switchOnly && !args['no-clean'] && fs.existsSync(outRoot)) {
cleanDir(outRoot);
info(`产物根已重建:${path.relative(ROOT, outRoot)}/`);
}
if (switchOnly) info('仅切换清单:不构建、不动版本目录');
let hostRel = null;
let fileCount = 0;
if (switchOnly) {
// 仅切换清单:不构建、不落版本目录、不记 published,但要真正改掉清单指向。
// 回滚的全部意义就在这里——把 subapps.<app>.url/version 指回旧版本目录。
for (const a of spec.apps) {
const meta = workspace.apps.find((w) => w.shortName === a.shortName);
const entry = { url: remoteDirOf(a.shortName, a.version, publicBase), version: a.version };
if (meta?.route && meta.route !== a.shortName) entry.route = meta.route;
state.subapps[a.shortName] = entry;
info(`${a.shortName} 清单已切到 ${a.version}(版本目录未动)`);
}
if (spec.host) {
state.host = { url: remoteDirOf('host', spec.host.version, publicBase), version: spec.host.version };
info(`主壳清单已切到 ${spec.host.version}(版本目录未动)`);
}
} else {
// ---- 子应用:构建 → base 校验 → 落版本目录 → 记清单 ----
for (const a of spec.apps) {
const meta = workspace.apps.find((w) => w.shortName === a.shortName);
if (!meta) die(`workspace 里找不到子应用 ${a.shortName}`);
const remoteDir = remoteDirOf(a.shortName, a.version, publicBase);
const basePrefix = publicBase ? remoteDir : `/${versionPath(a.shortName, a.version)}`;
if (!skipBuild) {
buildApp(meta.name, { SUBAPP_BASE: remoteDir }, { die, info });
}
const appDist = path.join(meta.dir, 'dist');
fileCount += assertBase(appDist, basePrefix, { info, die });
const target = path.join(outRoot, 'mfe', a.shortName, a.version);
fs.mkdirSync(path.dirname(target), { recursive: true });
if (fs.existsSync(target)) cleanDir(target);
fs.cpSync(appDist, target, { recursive: true });
info(`${a.shortName}@${a.version} 产物已落到 ${path.relative(ROOT, target)}`);
const entry = { url: remoteDir, version: a.version };
if (meta.route && meta.route !== a.shortName) entry.route = meta.route;
state.subapps[a.shortName] = entry;
const seen = Array.isArray(state.published[a.shortName]) ? state.published[a.shortName] : [];
if (!seen.includes(a.version)) seen.push(a.version);
state.published[a.shortName] = seen;
}
// ---- 主壳:构建 → base 校验 → 版本目录 + 根 index.html 指针 ----
if (spec.host) {
const shell = workspace.shell;
if (!shell) die('未找到主壳包,无法部署 host');
const remoteDir = remoteDirOf('host', spec.host.version, publicBase);
const basePrefix = publicBase ? remoteDir : `/${versionPath('host', spec.host.version)}`;
const shellDist = path.join(shell.dir, 'dist');
if (!skipBuild) {
buildApp(shell.name, { SHELL_BASE: remoteDir }, { die, info });
}
fileCount += assertBase(shellDist, basePrefix, { info, die });
hostRel = `mfe/host/${spec.host.version}`;
const hostTarget = path.join(outRoot, 'mfe', 'host', spec.host.version);
fs.mkdirSync(path.dirname(hostTarget), { recursive: true });
if (fs.existsSync(hostTarget)) cleanDir(hostTarget);
fs.cpSync(shellDist, hostTarget, { recursive: true });
// 站点根 index.html 是唯一被原地覆盖的文件,内容指向版本化主壳
fs.copyFileSync(path.join(shellDist, 'index.html'), path.join(outRoot, 'index.html'));
info(`主壳已落到 ${hostRel}/,站点根 index.html 已指向它`);
state.host = { url: remoteDir, version: spec.host.version };
}
}
// ---- 写状态 + 运行时快照 ----
state.version = `${new Date().toISOString().replace(/[:.]/g, '-')}-${spec.version}`;
state.updatedAt = new Date().toISOString();
writeState(stateFile, state);
const snapshot = writeSnapshot(manifestFile, state);
info(`清单已写入 ${path.relative(ROOT, manifestFile)}`);
const bi = writeBuildInfo({
root: ROOT, outRoot, version: spec.version,
apps: spec.apps.map((a) => a.shortName), hostRel,
manifestVersion: snapshot.version, source: 'release',
});
info(`构建指纹 BUILD_INFO.json(${bi.git?.shortSha ?? '无 git'})`);
if (!quiet) console.log(JSON.stringify(snapshot, null, 2));
// ---- 上传:先资源(排除清单),全部成功后最后单独传清单(提交点)----
// 两段式是铁律:清单先落地而资源没传完 = 线上"清单指向 404"。
if (uploadCmd && !dryRun(args)) {
info('上传阶段 ①/②:资源(排除 manifest.json)');
runUpload(uploadCmd, { dir: outRoot, file: '' }, { die, info });
info('上传阶段 ②/②:清单 manifest.json(提交点)');
runUpload(uploadCmd, { dir: outRoot, file: path.join(outRoot, 'mfe', 'manifest.json') }, { die, info });
} else if (!quiet) {
console.log('\n 上传未配置:产物已生成在 dist/,请按「先资源、后清单」两步上传。');
console.log(' 切勿用 rsync --delete(会删掉线上旧版本目录,回滚就没了)。');
console.log(' 切勿把 manifest.json 和资源放一次上传(顺序不可控,清单可能先落地)。');
}
return { ok: true, snapshot, hostRel, fileCount };
}
function dryRun(args) { return Boolean(args['dry-run']); }