release.mjs
26.8 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { writeBuildInfo } from './build-info.mjs';
import { mergeRemoteManifest } from './remote-manifest.mjs';
/**
* 单模块发版 —— 「只改了 system,就只发 system」的可执行入口。
*
* node scripts/release/release.mjs --app system --version 1.2.0
*
* 做四件事,每一步都对应 docs/DEPLOY.md 的一节:
* 1. 定向构建(SUBAPP_BASE 注入 /mfe/<app>/<version>/,让资源路径对齐不可变目录)
* 2. 产物落到 <out>/mfe/<app>/<version>/(已存在的版本拒绝覆盖)
* 3. 校验 index.html 里的资源路径确实带上了该 base(防止「清单生效但白屏」)
* 4. 增量更新 <out>/mfe/manifest.json,只改目标子应用那一条
*
* 不自动上传:脚本只产出「待上传目录」,通过 --upload-cmd 交给实际制品库/CDN。
* 这样不把任何基础设施假设写进仓库。
*
* ── 产物语义(v2:产物树 = 部署树的剪影)────────────────────────────
* <out>(默认 dist)里的**每一次发布都重建**,只装本次要覆盖的文件:
* 改了 system → <out>/ 只有 mfe/system/<ver>/ 与 mfe/manifest.json
* 改了主壳 → <out>/ 根有 index.html(指针)+ mfe/host/<ver>/(主壳实体,不进 mfe/<app>/)
* 运维把 <out>/ 整棵树覆盖进部署根即可,未出现在产物里的模块保持线上老版本。
*
* 代价:本地不再残留历史版本目录,所以「同名版本不可覆盖」这条不变量没法靠
* 检查目录存在来判断,改为记在 state 文件的 published 里(见下)。
*
* ── 状态与产物分离 ───────────────────────────────────────────────────
* manifest 是**增量状态**(只改目标应用那一条,其余原样保留),它不能住在会被
* 重建的产物目录里,因此外移到 <state>(默认 .release-state,MFE_STATE_DIR 可覆盖):
* <state>/manifest.json = { version, updatedAt, subapps, published: { app: [版本...] } }
* <out>/mfe/manifest.json = 只含 { version, updatedAt, subapps }(运行时真正拉的那份)
* published 记录「已对外发布过的版本」,用来在产物重建后仍能拦住同名覆盖。
*
* 回滚 / 灰度不重建:--switch-only 1.2.0 只改清单,把 URL 指回旧版本目录。
*/
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const MICRO_ROOT = path.join(ROOT, 'apps', 'web', 'subapps');
function parseArgs(argv) {
const flags = new Set([
'dry-run',
'skip-build',
'switch-only',
'force',
'help',
'no-clean',
'no-bump',
'quiet',
]);
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === '--') continue; // 容忍 pnpm 把 -- 分隔符透传给脚本
if (!token.startsWith('--')) {
throw new Error(`无法识别的参数:${token}`);
}
const eq = token.indexOf('=');
const key = (eq > 0 ? token.slice(2, eq) : token.slice(2)).replace(/^--/, '');
if (flags.has(key)) {
out[key] = true;
continue;
}
const value = eq > 0 ? token.slice(eq + 1) : argv[++i];
if (value === undefined || value.startsWith('--')) {
throw new Error(`参数 --${key} 缺少取值`);
}
out[key] = value;
}
return out;
}
function die(message) {
console.error(`\n[release] ✗ ${message}\n`);
process.exit(1);
}
function info(message) {
console.log(`[release] ${message}`);
}
function printHelp() {
console.log(`
用法:
node scripts/release/release.mjs --app <子应用目录名> --version <ver> [选项]
选项:
--app <name> 子应用目录名(必填,除 --help 外)
--version <ver> 版本号(可选)。省略时自动从真源解析:线上清单(MFE_REMOTE_MANIFEST) >
本地 .release-state > git tag > 兜底 1.1.0;默认 +minor,可用 --bump 改。
--bump <level> 自动版本号递增级别:minor(默认)/patch/major。如线上 1.2.0 → --bump patch 得 1.2.1
--no-bump 直接用真源当前版本(重发同版本场景,需配合 --force)
--public-base <url> 产物对外根地址,默认同源 ''。
例如 https://cdn.example.com 会生成该域名下的 /mfe/... URL
--out <dir> 产物目录,默认 dist。它镜像部署根、**每次发布重建**,
只装本次要覆盖的文件;运维把整棵树覆盖进部署目录即可。
--state <dir> manifest 累积状态目录,默认 .release-state(或 MFE_STATE_DIR)。
含已发布版本记账,产物重建后仍能拦住同名覆盖。
--skip-build 复用已有 dist,不重新构建(CI 里 build job 已构建时用)
--switch-only 只改清单,不构建不复制;用于回滚 / 灰度
--upload-cmd <cmd> 上传钩子,模板变量见下。推荐两阶段(清单最后落地,见 DEPLOY 文档):
"rsync -a --exclude='manifest.json' {dir}/ /srv/www/ && rsync -a {file} /srv/www/mfe/manifest.json"
也可用环境变量 MFE_UPLOAD_CMD 提供。
{dir} 产物根(= 部署根镜像,主壳在根、子应用在 mfe/ 下)
{host} {dir} 的别名,仅为兼容旧钩子保留
{target} 本次单个版本目录
{remote} 远端相对路径 mfe/<app>/<version>/
{file} manifest.json 本地路径
⚠ 钩子必须覆盖 manifest.json,否则清单不更新、发布不生效。
推荐把清单放在 && 的最后一步:它一旦落地就等于「资源已全部就位」,
中途失败则线上仍是旧清单,下次打包会自动重发同一版本。
--remote-manifest <url>
线上清单地址(也可用 MFE_REMOTE_MANIFEST)。配了就发布前先拉一次
线上清单做合并基线:本次没发的 app 以线上为准,避免并发发版时
后上传的那份把先发的条目覆盖掉。拉取失败只告警不阻断。
--force 允许覆盖已发布过的同名版本(默认禁止,回滚依赖旧目录内容不变)
--no-clean 内部用:不清空产物目录(由外层 release:spec/affected 统一清一次)
--keep-local <a,b> 内部用:批量发版时整批要发的应用名。合并线上清单时不覆盖这些条目,
避免后发的子应用把前面已发的新版本回滚成线上旧值。
--dry-run 只打印计划,不构建、不写文件、不上传
--help 显示本帮助
示例:
# 本地演练
node scripts/release/release.mjs --app system --version 1.2.0 --dry-run
# 正式发 system 一个版本(host 不重建)
pnpm release -- --app system --version 1.2.0
# 回滚到旧版本
pnpm release -- --app system --version 1.1.9 --switch-only
`);
}
/** 只读拉取线上清单的 subapps(用于版本号真源),失败返回 null。 */
async function fetchRemoteSubapps(url, timeoutMs = 8000) {
try {
const res = await fetch(url, {
signal: AbortSignal.timeout(timeoutMs),
headers: { 'cache-control': 'no-cache', pragma: 'no-cache' },
});
if (!res.ok) return null;
const remote = await res.json();
if (!remote || typeof remote.subapps !== 'object' || remote.subapps === null) return null;
return remote.subapps;
} catch {
return null;
}
}
/** 版本号 +1:minor 默认(1.2.0→1.3.0),patch(1.2.0→1.2.1),major(1.2.0→2.0.0)。非 semver 返回 null。 */
function bumpVersion(ver, level = 'minor') {
const m = /^(\d+)\.(\d+)\.(\d+)/.exec(ver);
if (!m) return null;
let [major, minor, patch] = [Number(m[1]), Number(m[2]), Number(m[3])];
if (level === 'major') {
major += 1;
minor = 0;
patch = 0;
} else if (level === 'patch') {
patch += 1;
} else {
minor += 1;
patch = 0;
}
return `${major}.${minor}.${patch}`;
}
/**
* 自动解析版本号(真源优先,OPS/开发者都不必手填)。
* 真源优先级:线上清单(MFE_REMOTE_MANIFEST) > 本地 .release-state > git tag > 兜底。
* noBump 时直接返回真源当前版本(重发同版本,需配合 --force)。
*/
async function resolveReleaseVersion({ app, remoteManifestUrl, stateFile, bumpLevel, noBump, ROOT }) {
let source = null;
if (remoteManifestUrl) {
const remote = await fetchRemoteSubapps(remoteManifestUrl);
const v = remote?.[app]?.version;
if (v) source = v;
}
if (!source) {
try {
const st = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
const v = st?.subapps?.[app]?.version;
if (v) source = v;
} catch {
/* 无状态文件按无真源处理 */
}
}
if (!source) {
const r = spawnSync('git', ['describe', '--tags', '--abbrev=0'], { cwd: ROOT });
if (r.status === 0 && r.stdout?.trim()) source = r.stdout.trim().replace(/^v/i, '');
}
if (source) return noBump ? source : bumpVersion(source, bumpLevel) ?? source;
if (noBump) return '1.0.0';
return bumpLevel === 'major' ? '2.0.0' : bumpLevel === 'patch' ? '1.0.1' : '1.1.0';
}
const args = parseArgs(process.argv.slice(2));
if (args.help) {
printHelp();
process.exit(0);
}
const { app } = args;
if (!app) die('缺少 --app。用 --help 查看用法。');
if (!/^[\w-]+$/.test(app)) die(`子应用名 "${app}" 非法`);
// ---- 版本号自动解析(真源优先,不必手填)----
// 优先级:--version > 线上清单(MFE_REMOTE_MANIFEST) > 本地 .release-state > git tag > 兜底
const bumpLevel =
args.bump === 'major' || args.bump === 'minor' || args.bump === 'patch' ? args.bump : 'minor';
const noBump = Boolean(args['no-bump']);
const rmuForResolve = args['remote-manifest'] ?? process.env.MFE_REMOTE_MANIFEST;
const stateFileForResolve = path.join(
path.resolve(ROOT, args.state ?? process.env.MFE_STATE_DIR ?? '.release-state'),
'manifest.json',
);
let version = args.version;
if (!version) {
version = await resolveReleaseVersion({
app,
remoteManifestUrl: rmuForResolve,
stateFile: stateFileForResolve,
bumpLevel,
noBump,
ROOT,
});
console.log(
`[release] 自动版本:${version}` +
(noBump ? '(直接用真源当前版本)' : `(真源版本 +${bumpLevel},可用 --version 覆盖)`),
);
}
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(version) || version.includes('..')) {
die(`版本号 "${version}" 非法:只允许字母数字 . _ -,且不得含 ".."(防目录穿越)`);
}
if (!/^\d+\.\d+\.\d+/.test(version)) {
info(`提示:版本 "${version}" 不是 semver 形态。CI 用 commit sha 可以,人工发版建议 1.2.0。`);
}
const appDir = path.join(MICRO_ROOT, app);
const pkgFile = path.join(appDir, 'package.json');
if (!fs.existsSync(pkgFile)) die(`子应用不存在:${path.relative(ROOT, appDir)}`);
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
const expectedName = `@uj/web-${app}`;
if (pkg.name !== expectedName) {
die(`${app}/package.json 的 name=${pkg.name},期望 ${expectedName};--filter 会构建到别的包`);
}
// ---- 计算 URL 与目录:两者必须严格对齐 ----
// CI 里同名环境变量即可驱动,不必拼一长串 CLI 参数。
const publicBase = String(args['public-base'] ?? process.env.MFE_PUBLIC_BASE ?? '').replace(
/\/+$/,
'',
);
const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD;
/**
* 线上清单地址。配了就先拉一次做合并基线,把「并发发版互相覆盖」的窗口从
* 整个过程压缩到上传的几秒。不配则行为不变(纯本地状态)。
*/
const remoteManifestUrl = args['remote-manifest'] ?? process.env.MFE_REMOTE_MANIFEST;
const remotePath = `mfe/${app}/${version}/`;
const remoteDir = `${publicBase}/${remotePath}`; // '/mfe/system/1.2.0/' 或 'https://cdn/.../mfe/system/1.2.0/'
const subappBase = remoteDir; // 直接作为 Vite base,产物资源路径与最终 URL 同源同前缀
const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? 'dist');
const stateDir = path.resolve(ROOT, args.state ?? process.env.MFE_STATE_DIR ?? '.release-state');
const targetDir = path.join(outRoot, 'mfe', app, version);
const manifestFile = path.join(outRoot, 'mfe', 'manifest.json'); // 产物里的快照(运行时拉这份)
const stateFile = path.join(stateDir, 'manifest.json'); // 累积状态(含已发布版本),不进产物
const distDir = path.join(appDir, 'dist');
const switchOnly = Boolean(args['switch-only']);
const dryRun = Boolean(args['dry-run']);
const skipBuild = Boolean(args['skip-build']) || switchOnly;
/**
* --quiet:被 release:spec / release:all 批量调用时用。
* 批量入口自己会打印清单级的总览,子进程再各打一份「发版计划 + 三步提醒」就是纯噪音
* (3 个应用 ≈ 50 行,真正有用的端口/产物信息被淹没)。失败路径不受影响。
*/
const quiet = Boolean(args.quiet);
/** quiet 下的静默 info:只丢掉过程性提示,失败仍走 die。 */
const say = quiet ? () => {} : info;
/** 读累积状态;首次升级时从既有产物清单迁移种子,避免丢掉其它应用的条目。 */
function readState() {
const empty = { version: '', updatedAt: '', subapps: {}, published: {} };
if (fs.existsSync(stateFile)) {
let st;
try {
st = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
} catch (err) {
die(`状态文件解析失败 ${path.relative(ROOT, stateFile)}: ${err.message}`);
}
if (!st.subapps || typeof st.subapps !== 'object') {
die(`${path.relative(ROOT, stateFile)} 缺少 subapps 字段,已拒绝覆盖,请人工确认该文件`);
}
if (!st.published || typeof st.published !== 'object') st.published = {};
return st;
}
if (fs.existsSync(manifestFile)) {
try {
const old = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
if (old && typeof old.subapps === 'object') {
info(`首次启用状态目录:从既有 ${path.relative(ROOT, manifestFile)} 迁移清单条目`);
return { ...empty, ...old, published: {} };
}
} catch {
/* 旧清单坏了就当没有,后续会按空状态重建 */
}
}
return empty;
}
if (!quiet) {
console.log('\n[release] ==== 发版计划 ====');
console.log(` 子应用 : ${pkg.name} (${app})`);
console.log(` 版本 : ${version}`);
console.log(` SUBAPP_BASE : ${subappBase}`);
console.log(` 产物目录 : ${path.relative(ROOT, targetDir)}`);
console.log(` 清单 : ${path.relative(ROOT, manifestFile)}`);
console.log(` 状态文件 : ${path.relative(ROOT, stateFile)}`);
console.log(
` 模式 : ${switchOnly ? '仅切换清单(回滚/灰度)' : dryRun ? '演练(不落盘)' : '完整发布'}`,
);
if (!switchOnly && !dryRun)
console.log(` 产物范围 : 本次重建(${path.relative(ROOT, outRoot)}/ 只装本次产物)`);
console.log('');
}
if (dryRun) {
info('--dry-run:以下动作不会执行。');
console.log(
` 1. ${switchOnly ? '(跳过)' : `SUBAPP_BASE=${subappBase} pnpm --filter ${pkg.name} build`}`,
);
console.log(` 2. ${switchOnly ? '(跳过)' : `dist/ -> ${path.relative(ROOT, targetDir)}`}`);
console.log(` 3. ${switchOnly ? '(跳过)' : '校验 index.html 资源路径带 base 前缀'}`);
console.log(
` 4. 写 manifest:subapps.${app} = { url: "${remoteDir}", version: "${version}"${pkg.uj?.route && pkg.uj.route !== app ? `, route: "${pkg.uj.route}"` : ''} }`,
);
if (uploadCmd) console.log(` 5. 上传钩子:${uploadCmd}`);
console.log('');
process.exit(0);
}
// ---- 0:读状态 + 不可变校验 + 重建产物目录 ----
// 产物目录每次重建(它只代表「本次要覆盖什么」),线下的历史版本目录不受影响。
// 「同名版本已发布过」的判定真源是【线上清单】(配置了 remoteManifest 且拉取成功时);
// 本地 state.published 只是拉不到线上时的兜底 —— 它是本机记录,同事的机器上没有。
let state = readState();
/** 线上条目(remoteManifest 拉取成功时为对象,否则 null)。 */
let remoteSubapps = null;
// ---- 0.5:拉线上清单做合并基线 ----
// 必须在不可变校验之前:合并只动 subapps,不动 published,校验依据不受影响;
// 但反过来先校验再合并,就会在 state 已被改写后才判冲突,语义更绕。
if (remoteManifestUrl && !switchOnly) {
// 批量发版(release:spec / affected / diff)会把「整批要发的应用」通过 --keep-local 传进来。
// 每个子进程都必须把同批的其它应用也视作本次发布:否则第 2 个子应用重新合并线上清单时,
// 会用线上旧值覆盖掉第 1 个刚写入的新版本 —— 最终产物清单里前面的发布凭空消失,
// 版本目录传上去了、清单却仍指向旧版本,发布等于没生效。
// 单独调用本脚本时缺省为 [app],行为不变。
const keepLocal = args['keep-local']
? String(args['keep-local'])
.split(',')
.map((s) => s.trim())
.filter(Boolean)
: [app];
const merged = await mergeRemoteManifest({
stateFile,
url: remoteManifestUrl,
keepLocal,
info,
});
if (merged.ok) {
remoteSubapps = merged.remoteSubapps ?? {};
state = readState(); // 合并结果已写回状态文件,重新读一份再继续
} else {
info(
`⚠ 远端清单拉取失败(${merged.error}):本次以本地状态为基线。\n` +
' 若此刻有其它人并发发版,后上传的那份会整份覆盖先前的条目。',
);
}
}
if (!switchOnly) {
const localSeen = Array.isArray(state.published?.[app]) ? state.published[app] : [];
const localHit = localSeen.includes(version);
const remoteEntry = remoteSubapps ? remoteSubapps[app] : undefined;
// url 相同即同一目录,version 字段只是人读的备注 —— 两者任一命中都视为「已在线上」
const remoteHit = Boolean(
remoteEntry && (remoteEntry.url === remoteDir || remoteEntry.version === version),
);
// 线上拉取成功 → 只信线上;拉不到/没配 → 退回本机记录,并如实告知它的局限
const hit = remoteSubapps ? remoteHit : localHit;
if (hit && !args.force) {
if (remoteSubapps) {
die(
`线上清单显示 ${app}@${version} 正在服务(subapps.${app} = ${JSON.stringify(remoteEntry)})。\n` +
'同名重建会把线上版本目录的内容换掉,回滚过去就不再是当初那个版本。\n' +
' 换版本号重发,或确认要就地覆盖时加 --force。',
);
}
die(
`版本 ${app}@${version} 已发布过(本机记录:${path.relative(ROOT, stateFile)})。\n` +
'同名覆盖会把线上旧目录的内容换掉,回滚过去就不再是当初那个版本。\n' +
' 换版本号重发,或确认要就地覆盖时加 --force。\n' +
' 注意:这条记录只在本机有效,其他同事的机器上不会有 —— 跨机器协作请配置\n' +
' MFE_REMOTE_MANIFEST 指向线上清单,让「已发布」判定以线上为准。',
);
}
}
if (!dryRun) fs.mkdirSync(stateDir, { recursive: true });
// ---- 1 / 2:定向构建 + 产物复制 ----
// 注意:清空产物目录放在构建与校验**之后**(见下方 cpSync 前)——
// 版本冲突、构建失败都发生在清空之前,这样失败时上一次的产物还在,不会被清成空目录。
if (!switchOnly) {
if (!skipBuild) {
const isWin = process.platform === 'win32';
const pnpm = isWin ? 'pnpm.cmd' : 'pnpm';
say(`定向构建 ${pkg.name}(其余应用不参与)...`);
const result = spawnSync(pnpm, ['--filter', pkg.name, 'build'], {
cwd: ROOT,
stdio: 'inherit',
shell: isWin,
env: { ...process.env, SUBAPP_BASE: subappBase },
});
if (result.error) {
die(
`启动 pnpm 失败:${result.error.message}\n` +
'若 CI 的 build job 已产出 dist,可加 --skip-build 复用产物。',
);
}
if (result.status !== 0) die(`构建失败(exit ${result.status}),未写 manifest。`);
}
if (!fs.existsSync(path.join(distDir, 'index.html'))) {
die(`找不到 ${path.relative(ROOT, distDir)}/index.html;先构建或去掉 --skip-build。`);
}
// ---- 3:产物 base 校验(这条能自动抓到「清单生效但白屏」)----
const html = fs.readFileSync(path.join(distDir, 'index.html'), 'utf8');
const refs = [...html.matchAll(/\b(?:src|href)="([^"]+)"/g)]
.map((m) => m[1])
.filter((u) => !/^(?:data:|blob:|#)/.test(u));
const basePrefix = publicBase ? subappBase : `/${remotePath}`;
const bad = refs.filter((u) => {
if (/^https?:\/\//.test(u)) return !u.startsWith(subappBase);
if (u.startsWith('/')) return !u.startsWith(basePrefix);
return false; // 相对路径交由 wujie 基于子应用 URL 补全
});
if (bad.length) {
die(
`产物 index.html 有 ${bad.length} 个资源路径未对齐 SUBAPP_BASE=${subappBase}:\n` +
bad
.slice(0, 5)
.map((u) => ` ${u}`)
.join('\n') +
'\n 部署到版本目录后会 404。确认 vite.config 用了 createWebAppConfig 且构建时带了 SUBAPP_BASE。',
);
}
say(`资源路径校验通过(${refs.length} 个引用均带 ${basePrefix} 前缀)`);
// 走到这里说明构建与资源校验都过了,才清空产物目录写本次内容。
// --no-clean 由外层 release:spec/affected 传给第二及以后的子应用(它们共用同一份产物树)。
if (!args['no-clean']) {
fs.rmSync(outRoot, { recursive: true, force: true });
say(`产物目录已重建:${path.relative(ROOT, outRoot)}/(只装本次产物)`);
}
fs.mkdirSync(targetDir, { recursive: true });
fs.cpSync(distDir, targetDir, { recursive: true });
say(`产物已落到 ${path.relative(ROOT, targetDir)}`);
} else {
// switch-only:产物里只留清单,版本目录不在本地(线上旧目录不动)。
if (!args['no-clean'] && fs.existsSync(outRoot)) {
fs.rmSync(outRoot, { recursive: true, force: true });
}
say('仅切换清单:本次产物只有 mfe/manifest.json,不含版本目录(线上旧目录不动)');
}
// ---- 4:增量更新状态(其余子应用条目原样保留),再导出本次产物里的清单快照 ----
state.version = `${new Date().toISOString().replace(/[:.]/g, '-')}-${app}-${version}`;
state.updatedAt = new Date().toISOString();
// route 供 host 运行时动态注册用:host 不重建时读不到新子应用的 package.json,
// 只能靠清单把 URL 首段反查回 shortName。缺省即 shortName,与构建期 subapps.ts 同语义。
const entry = { url: remoteDir, version };
if (typeof pkg.uj?.route === 'string' && pkg.uj.route && pkg.uj.route !== app) {
entry.route = pkg.uj.route;
}
state.subapps[app] = entry;
// 记账:本次真正落过盘的版本才算发布过;switch-only 只改指向,不算新发布。
if (!switchOnly) {
const seen = Array.isArray(state.published[app]) ? state.published[app] : [];
if (!seen.includes(version)) seen.push(version);
state.published[app] = seen;
}
fs.mkdirSync(stateDir, { recursive: true });
fs.writeFileSync(stateFile, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
say(`状态已更新:${path.relative(ROOT, stateFile)}`);
// 产物里那份只给运行时用:published 是本地记账,不该进部署目录。
const snapshot = {
version: state.version,
updatedAt: state.updatedAt,
subapps: state.subapps,
};
fs.mkdirSync(path.dirname(manifestFile), { recursive: true });
fs.writeFileSync(manifestFile, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
say(`清单已写入产物:${path.relative(ROOT, manifestFile)}`);
if (!quiet) console.log(JSON.stringify(snapshot, null, 2));
// 单应用发版也留指纹:产物只有 mfe/<app>/<ver>/ + 清单,但溯源需求一样。
// 批量入口(release:spec / affected / all)会在最后用全量信息覆盖这一份。
const bi = writeBuildInfo({
root: ROOT,
outRoot,
releaseVersion: version,
apps: [app],
hostRel: null,
manifestVersion: snapshot.version,
source: 'release',
});
say(
`构建指纹:BUILD_INFO.json` +
(bi.git
? `(${bi.git.shortSha}${bi.git.dirty ? '+dirty' : ''} @ ${bi.git.branch})`
: '(无 git 信息)'),
);
// ---- 5:上传钩子(可选,不执行时只给提示)----
// 钩子放在清单写完之后、且 switch-only 也执行:回滚只改清单,同样必须把新清单传上去。
if (uploadCmd) {
const template = String(uploadCmd);
if (!/\{dir\}/.test(template)) {
info('⚠ 上传钩子未包含 {dir}:产物是镜像部署根的一棵树,一个 {dir} 覆盖过去即可。');
}
const cmd = template
.replaceAll('{dir}', outRoot)
.replaceAll('{host}', outRoot) // 兼容旧钩子:主壳已落在产物根,不再是独立暂存目录
.replaceAll('{target}', targetDir)
.replaceAll('{remote}', remotePath)
.replaceAll('{file}', manifestFile);
info(`执行上传钩子:${cmd}`);
const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true });
if (res.status !== 0)
die(
`上传失败(exit ${res.status})。清单已在本地更新,远端尚未生效。\n` +
' 线上基线仍是失败前的版本,直接重跑本命令会自动重发;不需要改 package.json 版本号。',
);
}
if (!quiet)
console.log(`
[release] ==== 完成,但发布还没生效,还差三步 ====
1. 把 ${path.relative(ROOT, outRoot)}/ 整棵树覆盖进部署根(或配置 --upload-cmd 自动做)。
它只含本次产物:没出现在里面的模块,线上保持老版本,不用管。
清单 manifest.json 必须响应 Cache-Control: no-cache,否则浏览器缓存会把发布卡住。
2. 主壳启动时才拉清单,且子应用 alive 保活 —— 已打开的页面必须【整页刷新】才拿到新 URL,
SPA 内点菜单切换不会生效。
3. 用构建产物起静态服务逐路由冒烟(dev 走 Vite dev server、prod 走产物 URL,两条链路不同)。
至少验 /system/role、/system/user 首屏与 props.request 不报 10011。
回滚:pnpm release -- --app ${app} --version <旧版本> --switch-only
(只改清单指回旧目录,不重建、不重启 host)
`);
if (quiet) {
// 批量入口(release:spec / release:all)只要一行结果,总览由它自己打印
const target = switchOnly ? '仅清单' : remotePath;
console.log(`[release] ✓ ${app}@${version} → ${target}`);
}